Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
release(v4.17.0): honest times, faces that survive, and films you can fix
mrbizarro6cf2da2a51e2
diff --git a/README.md b/README.mdindex 3a5874c..b9ff595 100644--- a/README.md+++ b/README.md@@ -19,7 +19,7 @@</p>-> **Current release: v4.16.3.** **Three fixes from the field.** The Hailuo H3 progress card now reads "12m in · ~18m left" instead of "12m / ~18m", which looked like a total, and its estimate counts the model load of every window still to come. A LoRA whose download was cut short is named and refused before the render ("style.safetensors is incomplete ... download it again") instead of failing with "cannot reshape array". And if the first ffmpeg Phosphene finds cannot encode H.264 (no libx264), it uses the next one that can, instead of failing every export with "Unknown encoder 'libx264'". Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).+> **Current release: v4.17.0.** **Honest times, faces that survive, and films you can fix.** We used every flow on small and big Macs and fixed the 222 places it lied, lost work or made you hunt. Time estimates are for your Mac, not ours. Portrait and phone photos keep the face (right way up, right shape, with a crop you can drag). Stop, Clear queue and Hide have Undo or a confirm, and One Shot keeps its finished parts. Lip-sync is a Video mode with a 3 s draft, a sync verdict and Continue the song. The Editor gains Sync to song, Match colour, slip and roll edits, Replace and take history, and renders are versions you can cancel. Press Update in Pinokio, then restart. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).## Overview@@ -112,7 +112,7 @@ The Train tab also exposes **Style** training (experimental in v3.0) — same en### Audio-to-Video<img width="876" height="557" alt="image" src="https://github.com/user-attachments/assets/e64b2a23-e3e2-4132-8ceb-838b0c089136" />-New workflow tab in 3.0. WAV or MP3 in, MP4 out — the audio drives motion in the generated video, and an optional reference image anchors frame zero. The pipeline runs in two stages: low-resolution with classifier-free guidance, then full-resolution with the distilled LoRA fused on top. The original input audio is muxed onto the final clip so the result is a single self-contained MP4. Requires Q8 + ≥64 GB unified memory.+New workflow tab in 3.0 — Phosphene's lip-sync: a picture (optional) and a stretch of audio become one clip whose mouth follows the track. WAV or MP3 in, MP4 out — the audio drives motion in the generated video, and an optional reference image anchors frame zero. On Q8 (≥64 GB unified memory) it runs the two-stage pipeline: low-resolution with classifier-free guidance, then full-resolution with the distilled LoRA fused on top. Below that it falls back to a faster Q4 distilled lane — smaller Macs still get Audio-to-Video, just not the Q8 pipeline. The original input audio is muxed onto the final clip so the result is a single self-contained MP4.### LoRAsdiff --git a/VERSION b/VERSIONindex 595ad53..43b5827 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.16.3+4.17.0diff --git a/data/fleet_timings.json b/data/fleet_timings.jsonnew file mode 100644index 0000000..c553bdb--- /dev/null+++ b/data/fleet_timings.json@@ -0,0 +1,17532 @@+{+ "built_at": "2026-09-29T18:21:15Z",+ "levels": {+ "cell": {+ "cells": {+ "h3|i2v|draft_10s_dense|243.0|M4 Max|128.0|fast": {+ "n": 9,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s_dense|243.0|M4 Pro|48.0|fast": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_10s_dense|243.0|M5 Pro|48.0|best": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s_dense|243.0|M5 Pro|48.0|fast": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|draft_10s|243.0|M1 Max|64.0|fast": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_10s|243.0|M1 Ultra|64.0|fast": {+ "n": 14,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_10s|243.0|M2 Max|96.0|fast": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|M4 Max|128.0|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|M4 Max|64.0|best": {+ "n": 16,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|M4 Max|64.0|fast": {+ "n": 36,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_10s|243.0|M5 Max|128.0|fast": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_10s|243.0|M5 Pro|48.0|fast": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_10s|243.0|M5 Pro|64.0|best": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|M5 Pro|64.0|fast": {+ "n": 23,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_15s|362.0|M1 Max|64.0|fast": {+ "n": 20,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_15s|362.0|M1 Ultra|64.0|fast": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|i2v|draft_15s|362.0|M4 Max|128.0|best": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1125.0+ },+ "h3|i2v|draft_15s|362.0|M4 Max|128.0|fast": {+ "n": 17,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_15s|362.0|M4 Pro|48.0|best": {+ "n": 4,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|draft_15s|362.0|M4 Pro|48.0|fast": {+ "n": 4,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1350.0+ },+ "h3|i2v|draft_15s|362.0|M5 Max|64.0|best": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_15s|362.0|M5 Max|64.0|fast": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|i2v|draft_15s|362.0|M5 Pro|48.0|fast": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|i2v|draft_15s|362.0|M5 Pro|64.0|fast": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_3s|73.0|M1 Max|64.0|best": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_3s|73.0|M1 Max|64.0|fast": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "h3|i2v|draft_3s|73.0|M3 Max|36.0|best": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 465.0+ },+ "h3|i2v|draft_3s|73.0|M3 Max|36.0|fast": {+ "n": 16,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|i2v|draft_3s|73.0|M3 Ultra|256.0|fast": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 67.5+ },+ "h3|i2v|draft_3s|73.0|M3 Ultra|512.0|best": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 165.0+ },+ "h3|i2v|draft_3s|73.0|M4 Max|128.0|best": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 255.0+ },+ "h3|i2v|draft_3s|73.0|M4 Max|128.0|fast": {+ "n": 17,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|i2v|draft_3s|73.0|M4 Max|64.0|best": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 285.0+ },+ "h3|i2v|draft_3s|73.0|M4 Max|64.0|fast": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_3s|73.0|M4 Pro|48.0|best": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_3s|73.0|M4 Pro|48.0|fast": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|i2v|draft_3s|73.0|M5 Max|128.0|best": {+ "n": 8,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 210.0+ },+ "h3|i2v|draft_3s|73.0|M5 Pro|48.0|best": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_3s|73.0|M5 Pro|64.0|fast": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "h3|i2v|draft_5s|124.0|M1 Max|64.0|best": {+ "n": 25,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_5s|124.0|M1 Max|64.0|fast": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_5s|124.0|M1 Ultra|64.0|fast": {+ "n": 13,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_5s|124.0|M3 Max|36.0|best": {+ "n": 3,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_5s|124.0|M3 Max|36.0|fast": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_5s|124.0|M3 Max|96.0|best": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_5s|124.0|M3 Ultra|256.0|fast": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_5s|124.0|M3 Ultra|512.0|best": {+ "n": 7,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|i2v|draft_5s|124.0|M3 Ultra|512.0|fast": {+ "n": 15,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_5s|124.0|M4 Max|128.0|fast": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_5s|124.0|M4 Max|48.0|fast": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_5s|124.0|M4 Max|64.0|fast": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_5s|124.0|M4 Pro|48.0|fast": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_5s|124.0|M5 Max|128.0|best": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|draft_5s|124.0|M5 Max|128.0|fast": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 75.0,+ "p75_sec": 90.0+ },+ "h3|i2v|draft_5s|124.0|M5 Pro|48.0|fast": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "h3|i2v|draft_5s|124.0|M5 Pro|64.0|best": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_5s|124.0|M5 Pro|64.0|fast": {+ "n": 28,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|i2v|high_10s_dense|243.0|M1 Ultra|64.0|best": {+ "n": 12,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|high_10s_dense|243.0|M4 Max|64.0|fast": {+ "n": 8,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s_dense|243.0|M4 Pro|48.0|fast": {+ "n": 4,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2700.0+ },+ "h3|i2v|high_10s_dense|243.0|M5 Pro|48.0|best": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M1 Max|64.0|fast": {+ "n": 4,+ "p25_sec": 2250.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M1 Ultra|64.0|best": {+ "n": 19,+ "p25_sec": 2400.0,+ "p50_sec": 3600.0,+ "p75_sec": 4500.0+ },+ "h3|i2v|high_10s|243.0|M1 Ultra|64.0|fast": {+ "n": 8,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s|243.0|M2 Max|64.0|fast": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s|243.0|M3 Max|96.0|best": {+ "n": 3,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|high_10s|243.0|M3 Ultra|256.0|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_10s|243.0|M3 Ultra|96.0|best": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|high_10s|243.0|M4 Max|128.0|fast": {+ "n": 8,+ "p25_sec": 1650.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|high_10s|243.0|M4 Max|48.0|best": {+ "n": 7,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M4 Max|64.0|best": {+ "n": 83,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M4 Max|64.0|fast": {+ "n": 99,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s|243.0|M5 Max|128.0|best": {+ "n": 9,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M5 Max|128.0|fast": {+ "n": 26,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 825.0+ },+ "h3|i2v|high_10s|243.0|M5 Pro|48.0|best": {+ "n": 33,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s|243.0|M5 Pro|48.0|fast": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_15s|362.0|M1 Max|64.0|fast": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 3000.0+ },+ "h3|i2v|high_15s|362.0|M1 Ultra|64.0|best": {+ "n": 77,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|high_15s|362.0|M4 Max|128.0|best": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_15s|362.0|M4 Max|128.0|fast": {+ "n": 568,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_15s|362.0|M5 Max|128.0|fast": {+ "n": 11,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_15s|362.0|M5 Max|64.0|best": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2100.0+ },+ "h3|i2v|high_15s|362.0|M5 Max|64.0|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|i2v|high_15s|362.0|M5 Pro|48.0|best": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_15s|362.0|M5 Pro|48.0|fast": {+ "n": 8,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|high_15s|362.0|M5 Pro|64.0|fast": {+ "n": 9,+ "p25_sec": 1800.0,+ "p50_sec": 3600.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|high_3s|73.0|M1 Ultra|64.0|best": {+ "n": 11,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|i2v|high_3s|73.0|M3 Ultra|96.0|best": {+ "n": 12,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|high_3s|73.0|M4 Max|128.0|fast": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|high_3s|73.0|M4 Max|48.0|fast": {+ "n": 6,+ "p25_sec": 255.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_3s|73.0|M4 Max|64.0|best": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_3s|73.0|M4 Max|64.0|fast": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_3s|73.0|M5 Max|128.0|fast": {+ "n": 29,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|high_3s|73.0|M5 Pro|48.0|best": {+ "n": 207,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_3s|73.0|M5 Pro|48.0|fast": {+ "n": 58,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|i2v|high_5s|124.0|M1 Max|64.0|best": {+ "n": 4,+ "p25_sec": 2250.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_5s|124.0|M1 Max|64.0|fast": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|M1 Ultra|128.0|fast": {+ "n": 29,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M1 Ultra|64.0|best": {+ "n": 60,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|high_5s|124.0|M1 Ultra|64.0|fast": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M2 Ultra|128.0|best": {+ "n": 151,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|M2 Ultra|64.0|best": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|high_5s|124.0|M2 Ultra|64.0|fast": {+ "n": 22,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|high_5s|124.0|M3 Max|128.0|best": {+ "n": 19,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_5s|124.0|M3 Max|128.0|fast": {+ "n": 19,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M3 Ultra|256.0|best": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|high_5s|124.0|M3 Ultra|256.0|fast": {+ "n": 56,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_5s|124.0|M3 Ultra|512.0|best": {+ "n": 9,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_5s|124.0|M3 Ultra|96.0|best": {+ "n": 44,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|high_5s|124.0|M3 Ultra|96.0|fast": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|high_5s|124.0|M4 Max|128.0|fast": {+ "n": 45,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|M4 Max|48.0|best": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|M4 Max|48.0|fast": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M4 Max|64.0|best": {+ "n": 4,+ "p25_sec": 1125.0,+ "p50_sec": 1500.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|high_5s|124.0|M4 Max|64.0|fast": {+ "n": 90,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M4 Pro|48.0|fast": {+ "n": 7,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|i2v|high_5s|124.0|M5 Max|128.0|best": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|M5 Max|128.0|fast": {+ "n": 69,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_5s|124.0|M5 Pro|48.0|best": {+ "n": 281,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M5 Pro|48.0|fast": {+ "n": 146,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|native_10s|243.0|M1 Ultra|64.0|best": {+ "n": 13,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_10s|243.0|M4 Max|48.0|best": {+ "n": 3,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_10s|243.0|M4 Max|64.0|fast": {+ "n": 15,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|native_10s|243.0|M5 Max|128.0|fast": {+ "n": 12,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|native_15s|362.0|M1 Ultra|64.0|best": {+ "n": 9,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_15s|362.0|M2 Ultra|64.0|fast": {+ "n": 5,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|native_15s|362.0|M4 Max|128.0|best": {+ "n": 5,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_3s|73.0|M4 Max|128.0|best": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1500.0+ },+ "h3|i2v|native_3s|73.0|M4 Max|128.0|fast": {+ "n": 24,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|native_5s|124.0|M1 Max|64.0|best": {+ "n": 14,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_5s|124.0|M1 Ultra|64.0|best": {+ "n": 3,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|native_5s|124.0|M3 Ultra|512.0|best": {+ "n": 5,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|native_5s|124.0|M4 Max|128.0|best": {+ "n": 3,+ "p25_sec": 3000.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|native_5s|124.0|M4 Max|128.0|fast": {+ "n": 14,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 2250.0+ },+ "h3|i2v|native_5s|124.0|M4 Max|64.0|best": {+ "n": 13,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|native_5s|124.0|M5 Max|128.0|fast": {+ "n": 12,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|i2v|native_5s|124.0|M5 Pro|48.0|best": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|standard_10s_dense|243.0|M1 Ultra|64.0|best": {+ "n": 4,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_10s_dense|243.0|M3 Ultra|96.0|best": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Max|64.0|best": {+ "n": 5,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Max|64.0|fast": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Pro|48.0|fast": {+ "n": 8,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1350.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Pro|64.0|best": {+ "n": 7,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Pro|64.0|fast": {+ "n": 14,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s_dense|243.0|M5 Max|64.0|fast": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_10s|243.0|M1 Max|64.0|best": {+ "n": 9,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_10s|243.0|M1 Max|64.0|fast": {+ "n": 19,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|i2v|standard_10s|243.0|M1 Ultra|64.0|fast": {+ "n": 11,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_10s|243.0|M2 Max|64.0|fast": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 975.0+ },+ "h3|i2v|standard_10s|243.0|M2 Max|96.0|fast": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_10s|243.0|M2 Ultra|128.0|fast": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_10s|243.0|M2 Ultra|64.0|best": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|M3 Ultra|256.0|fast": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_10s|243.0|M3 Ultra|96.0|best": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|M4 Max|128.0|fast": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|i2v|standard_10s|243.0|M4 Max|64.0|best": {+ "n": 49,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|M4 Max|64.0|fast": {+ "n": 138,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_10s|243.0|M4 Pro|48.0|best": {+ "n": 6,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_10s|243.0|M4 Pro|48.0|fast": {+ "n": 11,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|M5 Max|64.0|fast": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|i2v|standard_10s|243.0|M5 Pro|48.0|fast": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_10s|243.0|M5 Pro|64.0|best": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_10s|243.0|M5 Pro|64.0|fast": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_15s|362.0|M1 Max|64.0|best": {+ "n": 11,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|standard_15s|362.0|M1 Max|64.0|fast": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1650.0+ },+ "h3|i2v|standard_15s|362.0|M1 Ultra|64.0|best": {+ "n": 10,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_15s|362.0|M4 Max|64.0|fast": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_15s|362.0|M4 Pro|48.0|fast": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 2400.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|standard_15s|362.0|M4 Pro|64.0|best": {+ "n": 6,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|standard_15s|362.0|M4 Pro|64.0|fast": {+ "n": 7,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|standard_15s|362.0|M5 Max|128.0|best": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_15s|362.0|M5 Max|64.0|best": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_15s|362.0|M5 Max|64.0|fast": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_15s|362.0|M5 Pro|64.0|best": {+ "n": 10,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_15s|362.0|M5 Pro|64.0|fast": {+ "n": 35,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1500.0+ },+ "h3|i2v|standard_3s|73.0|M1 Max|64.0|best": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_3s|73.0|M2 Max|64.0|best": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 465.0+ },+ "h3|i2v|standard_3s|73.0|M3 Max|36.0|fast": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "h3|i2v|standard_3s|73.0|M4 Max|64.0|fast": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|standard_3s|73.0|M5 Max|128.0|best": {+ "n": 18,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|i2v|standard_3s|73.0|M5 Max|64.0|fast": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "h3|i2v|standard_3s|73.0|M5 Pro|48.0|best": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|standard_3s|73.0|M5 Pro|64.0|fast": {+ "n": 13,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|i2v|standard_5s|124.0|M1 Max|64.0|best": {+ "n": 31,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_5s|124.0|M1 Max|64.0|fast": {+ "n": 19,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_5s|124.0|M1 Ultra|128.0|fast": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "h3|i2v|standard_5s|124.0|M2 Ultra|64.0|best": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_5s|124.0|M3 Max|128.0|best": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_5s|124.0|M3 Max|128.0|fast": {+ "n": 25,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_5s|124.0|M3 Max|36.0|fast": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_5s|124.0|M3 Ultra|256.0|best": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_5s|124.0|M3 Ultra|256.0|fast": {+ "n": 8,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|standard_5s|124.0|M3 Ultra|512.0|best": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_5s|124.0|M3 Ultra|512.0|fast": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 465.0+ },+ "h3|i2v|standard_5s|124.0|M3 Ultra|96.0|best": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_5s|124.0|M3 Ultra|96.0|fast": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|i2v|standard_5s|124.0|M4 Max|128.0|best": {+ "n": 6,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1125.0+ },+ "h3|i2v|standard_5s|124.0|M4 Max|128.0|fast": {+ "n": 4,+ "p25_sec": 285.0,+ "p50_sec": 300.0,+ "p75_sec": 375.0+ },+ "h3|i2v|standard_5s|124.0|M4 Max|64.0|fast": {+ "n": 253,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|i2v|standard_5s|124.0|M4 Pro|48.0|fast": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_5s|124.0|M5 Max|128.0|best": {+ "n": 68,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_5s|124.0|M5 Max|48.0|best": {+ "n": 3,+ "p25_sec": 210.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|i2v|standard_5s|124.0|M5 Max|64.0|fast": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|i2v|standard_5s|124.0|M5 Pro|48.0|best": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_5s|124.0|M5 Pro|48.0|fast": {+ "n": 16,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_5s|124.0|M5 Pro|64.0|fast": {+ "n": 7,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "h3|keyframe|high_3s|73.0|M5 Max|128.0|fast": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|keyframe|high_5s|124.0|M5 Max|128.0|fast": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_10s_dense|243.0|M4 Pro|48.0|best": {+ "n": 9,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|draft_10s_dense|243.0|M5 Max|128.0|best": {+ "n": 53,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s_dense|243.0|M5 Pro|48.0|fast": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_10s|243.0|M1 Max|64.0|best": {+ "n": 10,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1650.0+ },+ "h3|t2v|draft_10s|243.0|M1 Max|64.0|fast": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|draft_10s|243.0|M1 Ultra|64.0|fast": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_10s|243.0|M2 Max|64.0|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s|243.0|M2 Max|96.0|fast": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s|243.0|M3 Max|96.0|best": {+ "n": 6,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2250.0+ },+ "h3|t2v|draft_10s|243.0|M3 Ultra|512.0|fast": {+ "n": 10,+ "p25_sec": 240.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s|243.0|M4 Pro|48.0|best": {+ "n": 36,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_10s|243.0|M4 Pro|48.0|fast": {+ "n": 10,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s|243.0|M5 Max|128.0|best": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 330.0+ },+ "h3|t2v|draft_10s|243.0|M5 Max|128.0|fast": {+ "n": 4,+ "p25_sec": 112.5,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_15s|362.0|M1 Max|64.0|fast": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 3300.0+ },+ "h3|t2v|draft_15s|362.0|M1 Ultra|64.0|fast": {+ "n": 11,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_15s|362.0|M4 Max|64.0|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_15s|362.0|M4 Pro|48.0|best": {+ "n": 7,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|draft_15s|362.0|M4 Pro|48.0|fast": {+ "n": 14,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_15s|362.0|M5 Max|128.0|fast": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_15s|362.0|M5 Max|64.0|best": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_15s|362.0|M5 Max|64.0|fast": {+ "n": 4,+ "p25_sec": 225.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_15s|362.0|M5 Pro|48.0|fast": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|t2v|draft_3s|73.0|M1 Max|64.0|best": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "h3|t2v|draft_3s|73.0|M1 Max|64.0|fast": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "h3|t2v|draft_3s|73.0|M2 Ultra|64.0|best": {+ "n": 11,+ "p25_sec": 210.0,+ "p50_sec": 240.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_3s|73.0|M2 Ultra|64.0|fast": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_3s|73.0|M3 Max|128.0|best": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 330.0,+ "p75_sec": 465.0+ },+ "h3|t2v|draft_3s|73.0|M3 Max|128.0|fast": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|t2v|draft_3s|73.0|M3 Max|36.0|fast": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "h3|t2v|draft_3s|73.0|M3 Max|96.0|best": {+ "n": 7,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_3s|73.0|M3 Ultra|512.0|best": {+ "n": 17,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_3s|73.0|M3 Ultra|512.0|fast": {+ "n": 9,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "h3|t2v|draft_3s|73.0|M3 Ultra|96.0|best": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_3s|73.0|M3 Ultra|96.0|fast": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "h3|t2v|draft_3s|73.0|M4 Max|128.0|best": {+ "n": 4,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "h3|t2v|draft_3s|73.0|M4 Max|128.0|fast": {+ "n": 17,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_3s|73.0|M4 Max|48.0|best": {+ "n": 4,+ "p25_sec": 165.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "h3|t2v|draft_3s|73.0|M4 Max|64.0|best": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "h3|t2v|draft_3s|73.0|M4 Max|64.0|fast": {+ "n": 6,+ "p25_sec": 67.5,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|t2v|draft_3s|73.0|M4 Pro|48.0|best": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_3s|73.0|M4 Pro|48.0|fast": {+ "n": 76,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_3s|73.0|M5 Max|128.0|best": {+ "n": 540,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|t2v|draft_3s|73.0|M5 Max|128.0|fast": {+ "n": 16,+ "p25_sec": 30.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "h3|t2v|draft_3s|73.0|M5 Max|48.0|best": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|t2v|draft_3s|73.0|M5 Max|64.0|best": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "h3|t2v|draft_3s|73.0|M5 Max|64.0|fast": {+ "n": 5,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "h3|t2v|draft_3s|73.0|M5 Pro|48.0|best": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_3s|73.0|M5 Pro|64.0|best": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_3s|73.0|M5 Pro|64.0|fast": {+ "n": 20,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "h3|t2v|draft_5s|124.0|M1 Max|64.0|best": {+ "n": 46,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|draft_5s|124.0|M1 Max|64.0|fast": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M1 Ultra|128.0|best": {+ "n": 13,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_5s|124.0|M1 Ultra|128.0|fast": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "h3|t2v|draft_5s|124.0|M1 Ultra|64.0|best": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_5s|124.0|M2 Max|64.0|fast": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_5s|124.0|M2 Ultra|64.0|best": {+ "n": 56,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_5s|124.0|M3 Max|128.0|fast": {+ "n": 20,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M3 Max|96.0|best": {+ "n": 19,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_5s|124.0|M3 Ultra|512.0|best": {+ "n": 7,+ "p25_sec": 390.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|t2v|draft_5s|124.0|M3 Ultra|512.0|fast": {+ "n": 27,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_5s|124.0|M3 Ultra|96.0|best": {+ "n": 14,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M4 Max|128.0|best": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 510.0,+ "p75_sec": 675.0+ },+ "h3|t2v|draft_5s|124.0|M4 Max|128.0|fast": {+ "n": 11,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M4 Max|64.0|best": {+ "n": 15,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M4 Max|64.0|fast": {+ "n": 16,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M4 Pro|48.0|best": {+ "n": 20,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_5s|124.0|M4 Pro|48.0|fast": {+ "n": 33,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_5s|124.0|M5 Max|128.0|best": {+ "n": 126,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|t2v|draft_5s|124.0|M5 Max|128.0|fast": {+ "n": 54,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_5s|124.0|M5 Max|36.0|best": {+ "n": 4,+ "p25_sec": 255.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M5 Max|48.0|best": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_5s|124.0|M5 Max|48.0|fast": {+ "n": 4,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_5s|124.0|M5 Pro|48.0|fast": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "h3|t2v|draft_5s|124.0|M5 Pro|64.0|best": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M5 Pro|64.0|fast": {+ "n": 7,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "h3|t2v|high_10s_dense|243.0|M1 Ultra|64.0|best": {+ "n": 4,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_10s_dense|243.0|M2 Max|64.0|best": {+ "n": 11,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_10s_dense|243.0|M4 Pro|48.0|best": {+ "n": 18,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_10s_dense|243.0|M5 Max|128.0|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_10s_dense|243.0|M5 Pro|48.0|fast": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_10s|243.0|M1 Max|64.0|best": {+ "n": 3,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 4500.0+ },+ "h3|t2v|high_10s|243.0|M1 Ultra|128.0|best": {+ "n": 7,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|high_10s|243.0|M1 Ultra|64.0|best": {+ "n": 8,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|high_10s|243.0|M4 Max|128.0|fast": {+ "n": 4,+ "p25_sec": 1650.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|high_10s|243.0|M4 Max|48.0|fast": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_15s|362.0|M1 Ultra|128.0|best": {+ "n": 14,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_15s|362.0|M1 Ultra|64.0|best": {+ "n": 21,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_15s|362.0|M2 Ultra|64.0|best": {+ "n": 4,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_15s|362.0|M4 Pro|48.0|best": {+ "n": 4,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_15s|362.0|M4 Pro|48.0|fast": {+ "n": 9,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|high_15s|362.0|M5 Max|128.0|fast": {+ "n": 4,+ "p25_sec": 825.0,+ "p50_sec": 1050.0,+ "p75_sec": 1500.0+ },+ "h3|t2v|high_15s|362.0|M5 Pro|64.0|best": {+ "n": 7,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|high_3s|73.0|M1 Ultra|64.0|best": {+ "n": 23,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_3s|73.0|M4 Max|128.0|fast": {+ "n": 6,+ "p25_sec": 465.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_3s|73.0|M4 Pro|48.0|fast": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_3s|73.0|M5 Max|128.0|best": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_3s|73.0|M5 Max|128.0|fast": {+ "n": 66,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|high_5s|124.0|M1 Max|64.0|best": {+ "n": 5,+ "p25_sec": 2400.0,+ "p50_sec": 3600.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_5s|124.0|M1 Max|64.0|fast": {+ "n": 6,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1125.0+ },+ "h3|t2v|high_5s|124.0|M1 Ultra|64.0|best": {+ "n": 7,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_5s|124.0|M2 Max|64.0|fast": {+ "n": 13,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_5s|124.0|M3 Max|128.0|best": {+ "n": 8,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2700.0+ },+ "h3|t2v|high_5s|124.0|M3 Max|128.0|fast": {+ "n": 3,+ "p25_sec": 570.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|t2v|high_5s|124.0|M3 Ultra|512.0|fast": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 1050.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_5s|124.0|M4 Max|128.0|fast": {+ "n": 34,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_5s|124.0|M4 Max|48.0|best": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1125.0+ },+ "h3|t2v|high_5s|124.0|M5 Max|128.0|best": {+ "n": 39,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_5s|124.0|M5 Max|128.0|fast": {+ "n": 15,+ "p25_sec": 270.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|high_5s|124.0|M5 Pro|48.0|best": {+ "n": 10,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_5s|124.0|M5 Pro|48.0|fast": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|high_5s|124.0|M5 Pro|64.0|best": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|t2v|high_5s|124.0|M5 Pro|64.0|fast": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|native_10s_dense|243.0|M4 Max|48.0|best": {+ "n": 10,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_10s|243.0|M1 Ultra|64.0|best": {+ "n": 5,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_10s|243.0|M4 Max|128.0|fast": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|native_15s|362.0|M4 Max|128.0|fast": {+ "n": 3,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|native_15s|362.0|M4 Pro|48.0|best": {+ "n": 3,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_3s|73.0|M1 Ultra|64.0|best": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|native_3s|73.0|M4 Max|128.0|fast": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|native_3s|73.0|M5 Max|128.0|best": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 810.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|native_3s|73.0|M5 Max|128.0|fast": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "h3|t2v|native_5s|124.0|M1 Ultra|64.0|best": {+ "n": 3,+ "p25_sec": 3000.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|native_5s|124.0|M3 Ultra|512.0|fast": {+ "n": 6,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|native_5s|124.0|M4 Max|64.0|best": {+ "n": 9,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|standard_10s_dense|243.0|M4 Max|48.0|fast": {+ "n": 3,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_10s_dense|243.0|M4 Pro|48.0|best": {+ "n": 31,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_10s_dense|243.0|M5 Max|128.0|best": {+ "n": 7,+ "p25_sec": 750.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_10s_dense|243.0|M5 Max|128.0|fast": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 390.0+ },+ "h3|t2v|standard_10s|243.0|M1 Max|64.0|best": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_10s|243.0|M1 Ultra|128.0|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_10s|243.0|M2 Ultra|192.0|best": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|standard_10s|243.0|M3 Max|96.0|best": {+ "n": 6,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_10s|243.0|M3 Ultra|512.0|fast": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_10s|243.0|M3 Ultra|96.0|fast": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "h3|t2v|standard_10s|243.0|M4 Max|48.0|fast": {+ "n": 3,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_10s|243.0|M4 Max|64.0|fast": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|t2v|standard_10s|243.0|M4 Pro|48.0|best": {+ "n": 24,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|standard_10s|243.0|M4 Pro|48.0|fast": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_10s|243.0|M5 Max|128.0|fast": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|t2v|standard_10s|243.0|M5 Max|48.0|best": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 465.0+ },+ "h3|t2v|standard_10s|243.0|M5 Pro|48.0|fast": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_10s|243.0|M5 Pro|64.0|fast": {+ "n": 16,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_15s|362.0|M1 Max|64.0|best": {+ "n": 4,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 4050.0+ },+ "h3|t2v|standard_15s|362.0|M4 Pro|48.0|best": {+ "n": 10,+ "p25_sec": 2400.0,+ "p50_sec": 3000.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_15s|362.0|M4 Pro|48.0|fast": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|standard_15s|362.0|M5 Max|128.0|fast": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|t2v|standard_15s|362.0|M5 Max|64.0|best": {+ "n": 7,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_15s|362.0|M5 Max|64.0|fast": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|standard_15s|362.0|M5 Pro|48.0|fast": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|standard_15s|362.0|M5 Pro|64.0|best": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_15s|362.0|M5 Pro|64.0|fast": {+ "n": 17,+ "p25_sec": 420.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_3s|73.0|M1 Max|64.0|best": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|t2v|standard_3s|73.0|M1 Max|64.0|fast": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "h3|t2v|standard_3s|73.0|M3 Max|96.0|best": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|t2v|standard_3s|73.0|M3 Ultra|512.0|fast": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 75.0+ },+ "h3|t2v|standard_3s|73.0|M4 Max|128.0|best": {+ "n": 3,+ "p25_sec": 450.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_3s|73.0|M4 Max|128.0|fast": {+ "n": 11,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_3s|73.0|M4 Pro|48.0|fast": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_3s|73.0|M5 Max|128.0|best": {+ "n": 9,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "h3|t2v|standard_3s|73.0|M5 Max|128.0|fast": {+ "n": 4,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "h3|t2v|standard_3s|73.0|M5 Max|48.0|best": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 135.0+ },+ "h3|t2v|standard_3s|73.0|M5 Max|64.0|fast": {+ "n": 9,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "h3|t2v|standard_3s|73.0|M5 Pro|64.0|best": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|standard_3s|73.0|M5 Pro|64.0|fast": {+ "n": 52,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "h3|t2v|standard_5s|124.0|M1 Max|64.0|best": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|standard_5s|124.0|M1 Max|64.0|fast": {+ "n": 29,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_5s|124.0|M1 Ultra|64.0|best": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|t2v|standard_5s|124.0|M3 Max|128.0|best": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|t2v|standard_5s|124.0|M3 Max|128.0|fast": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_5s|124.0|M3 Max|96.0|best": {+ "n": 16,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|standard_5s|124.0|M3 Ultra|256.0|best": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_5s|124.0|M3 Ultra|512.0|fast": {+ "n": 18,+ "p25_sec": 150.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_5s|124.0|M3 Ultra|96.0|best": {+ "n": 6,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|standard_5s|124.0|M4 Max|128.0|best": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_5s|124.0|M4 Max|128.0|fast": {+ "n": 30,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|t2v|standard_5s|124.0|M4 Max|64.0|best": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_5s|124.0|M4 Max|64.0|fast": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|standard_5s|124.0|M4 Pro|48.0|best": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_5s|124.0|M4 Pro|48.0|fast": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_5s|124.0|M4 Pro|64.0|best": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|t2v|standard_5s|124.0|M5 Max|128.0|best": {+ "n": 17,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|standard_5s|124.0|M5 Max|128.0|fast": {+ "n": 9,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "h3|t2v|standard_5s|124.0|M5 Max|48.0|best": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 330.0+ },+ "h3|t2v|standard_5s|124.0|M5 Max|64.0|best": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|standard_5s|124.0|M5 Max|64.0|fast": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "h3|t2v|standard_5s|124.0|M5 Pro|48.0|fast": {+ "n": 9,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|standard_5s|124.0|M5 Pro|64.0|best": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_5s|124.0|M5 Pro|64.0|fast": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx23|t2v|high|121.0|M3 Ultra|96.0|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|balanced|105.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|121.0|M4 Max|64.0|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|121.0|M4 Pro|48.0|any": {+ "n": 15,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|121.0|M4|32.0|any": {+ "n": 46,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|121.0|M5 Max|48.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|a2v|balanced|129.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|a2v|balanced|129.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|a2v|balanced|137.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 420.0,+ "p75_sec": 465.0+ },+ "ltx|a2v|balanced|137.0|M5 Max|128.0|any": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|145.0|M4 Pro|48.0|any": {+ "n": 10,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 555.0+ },+ "ltx|a2v|balanced|145.0|M5 Max|128.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|145.0|M5 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|153.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|161.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|169.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|177.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|193.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|209.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|balanced|217.0|M4 Pro|48.0|any": {+ "n": 9,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|241.0|M4 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|balanced|49.0|M4|32.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|57.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|57.0|M4|32.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|65.0|M4|32.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|a2v|balanced|65.0|M5 Max|48.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 52.5+ },+ "ltx|a2v|balanced|73.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 750.0+ },+ "ltx|a2v|balanced|73.0|M4|32.0|any": {+ "n": 42,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|73.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 37.5,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|a2v|balanced|73.0|M5 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 112.5,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|81.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|81.0|M4|32.0|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|89.0|M4|32.0|any": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|89.0|M5 Max|48.0|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 67.5+ },+ "ltx|a2v|balanced|97.0|M4 Pro|48.0|any": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|97.0|M4|32.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|97.0|M5 Max|48.0|any": {+ "n": 4,+ "p25_sec": 82.5,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|high|105.0|M4 Max|64.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|105.0|M5 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|a2v|high|113.0|M5 Max|128.0|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|121.0|M1 Ultra|64.0|any": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 570.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|121.0|M2 Max|32.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|high|121.0|M4 Max|64.0|any": {+ "n": 12,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|121.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|high|121.0|M4 Pro|48.0|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|121.0|M5 Max|128.0|any": {+ "n": 10,+ "p25_sec": 150.0,+ "p50_sec": 240.0,+ "p75_sec": 285.0+ },+ "ltx|a2v|high|121.0|M5 Pro|48.0|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|high|129.0|M5 Max|48.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|high|137.0|M5 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|high|145.0|M1 Ultra|64.0|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|153.0|M5 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|high|169.0|M1 Max|64.0|any": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|169.0|M2 Max|96.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|169.0|M3 Ultra|96.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|169.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 210.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|high|169.0|M4 Pro|24.0|any": {+ "n": 15,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|169.0|M4 Pro|48.0|any": {+ "n": 12,+ "p25_sec": 420.0,+ "p50_sec": 660.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|169.0|M4|16.0|any": {+ "n": 7,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|169.0|M5 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 150.0,+ "p50_sec": 210.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|high|169.0|M5 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|185.0|M5 Max|128.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|193.0|M4 Pro|48.0|any": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|217.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|a2v|high|217.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1350.0+ },+ "ltx|a2v|high|241.0|M1 Ultra|64.0|any": {+ "n": 22,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|241.0|M2 Pro|32.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|241.0|M4 Max|128.0|any": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|241.0|M4 Max|36.0|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 390.0+ },+ "ltx|a2v|high|241.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|241.0|M4 Pro|48.0|any": {+ "n": 14,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|241.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|241.0|M5 Pro|24.0|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|265.0|M1 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|a2v|high|289.0|M5 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|385.0|M4|24.0|any": {+ "n": 38,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|409.0|M4 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|433.0|M2 Pro|32.0|any": {+ "n": 4,+ "p25_sec": 2100.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|433.0|M4 Pro|24.0|any": {+ "n": 70,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|433.0|M5 Max|128.0|any": {+ "n": 29,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|481.0|M1 Ultra|64.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 810.0+ },+ "ltx|a2v|high|481.0|M4 Pro|24.0|any": {+ "n": 13,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|481.0|M5 Max|128.0|any": {+ "n": 20,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|57.0|M5 Pro|24.0|any": {+ "n": 16,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|a2v|high|601.0|M4 Pro|24.0|any": {+ "n": 8,+ "p25_sec": 2250.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|65.0|M5 Pro|24.0|any": {+ "n": 6,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|a2v|high|713.0|M5 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|89.0|M1 Max|64.0|any": {+ "n": 3,+ "p25_sec": 2100.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|97.0|M1 Max|64.0|any": {+ "n": 4,+ "p25_sec": 825.0,+ "p50_sec": 1350.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|quick|241.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|105.0|M4 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|121.0|M5 Max|128.0|any": {+ "n": 4,+ "p25_sec": 165.0,+ "p50_sec": 180.0,+ "p75_sec": 285.0+ },+ "ltx|a2v|standard|129.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|137.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|145.0|M4 Pro|48.0|any": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|standard|153.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|a2v|standard|161.0|M4 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|standard|169.0|M4 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 900.0,+ "p50_sec": 1050.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|standard|177.0|M4 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 975.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|standard|193.0|M4 Pro|48.0|any": {+ "n": 11,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|standard|241.0|M4 Max|48.0|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 975.0+ },+ "ltx|a2v|standard|241.0|M4 Pro|48.0|any": {+ "n": 48,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|73.0|M5 Max|128.0|any": {+ "n": 32,+ "p25_sec": 90.0,+ "p50_sec": 105.0,+ "p75_sec": 180.0+ },+ "ltx|a2v|standard|97.0|M4 Pro|48.0|any": {+ "n": 24,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|97.0|M5 Max|128.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 165.0+ },+ "ltx|extend|balanced|121.0|M1 Max|64.0|any": {+ "n": 4,+ "p25_sec": 1005.0,+ "p50_sec": 1800.0,+ "p75_sec": 3150.0+ },+ "ltx|extend|balanced|121.0|M3 Ultra|256.0|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|extend|balanced|121.0|M3 Ultra|96.0|any": {+ "n": 4,+ "p25_sec": 1050.0,+ "p50_sec": 1800.0,+ "p75_sec": 2700.0+ },+ "ltx|extend|balanced|121.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 2700.0,+ "p75_sec": 4050.0+ },+ "ltx|extend|balanced|121.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "ltx|extend|balanced|121.0|M5 Max|48.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 450.0,+ "p75_sec": 750.0+ },+ "ltx|extend|balanced|241.0|M1 Max|64.0|any": {+ "n": 3,+ "p25_sec": 3000.0,+ "p50_sec": 3600.0,+ "p75_sec": 4500.0+ },+ "ltx|extend|balanced|241.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 4650.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "ltx|extend|high|121.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "ltx|extend|high|241.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 4500.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "ltx|extend|high|241.0|M5 Max|48.0|any": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1500.0+ },+ "ltx|extend|quick|121.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 3600.0+ },+ "ltx|extend|standard|241.0|M1 Max|64.0|any": {+ "n": 4,+ "p25_sec": 3300.0,+ "p50_sec": 4500.0,+ "p75_sec": 5400.0+ },+ "ltx|i2v|balanced|105.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 285.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|113.0|M5 Max|128.0|any": {+ "n": 43,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|121.0|M1 Max|32.0|any": {+ "n": 36,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|i2v|balanced|121.0|M1 Max|64.0|any": {+ "n": 290,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M1 Pro|16.0|any": {+ "n": 24,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M1 Pro|32.0|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M1 Ultra|128.0|any": {+ "n": 12,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 210.0+ },+ "ltx|i2v|balanced|121.0|M1 Ultra|64.0|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 270.0+ },+ "ltx|i2v|balanced|121.0|M1|16.0|any": {+ "n": 17,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|121.0|M1|8.0|any": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|121.0|M2 Max|32.0|any": {+ "n": 135,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|121.0|M2 Max|64.0|any": {+ "n": 99,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|121.0|M2 Max|96.0|any": {+ "n": 55,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|121.0|M2 Pro|16.0|any": {+ "n": 6,+ "p25_sec": 255.0,+ "p50_sec": 300.0,+ "p75_sec": 390.0+ },+ "ltx|i2v|balanced|121.0|M2 Pro|32.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|121.0|M2 Ultra|128.0|any": {+ "n": 26,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M2 Ultra|64.0|any": {+ "n": 17,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M2|16.0|any": {+ "n": 7,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|balanced|121.0|M2|8.0|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|121.0|M3 Max|128.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "ltx|i2v|balanced|121.0|M3 Max|36.0|any": {+ "n": 36,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|121.0|M3 Max|48.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|i2v|balanced|121.0|M3 Max|64.0|any": {+ "n": 162,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M3 Pro|18.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M3 Ultra|256.0|any": {+ "n": 135,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|121.0|M3 Ultra|512.0|any": {+ "n": 52,+ "p25_sec": 165.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M3 Ultra|96.0|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M3|16.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 540.0+ },+ "ltx|i2v|balanced|121.0|M3|24.0|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|i2v|balanced|121.0|M4 Max|128.0|any": {+ "n": 25,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M4 Max|36.0|any": {+ "n": 210,+ "p25_sec": 97.5,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M4 Max|48.0|any": {+ "n": 37,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|121.0|M4 Max|64.0|any": {+ "n": 71,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|121.0|M4 Pro|24.0|any": {+ "n": 132,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|121.0|M4 Pro|48.0|any": {+ "n": 165,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M4 Pro|64.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M4|16.0|any": {+ "n": 67,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|121.0|M4|24.0|any": {+ "n": 75,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M4|32.0|any": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M5 Max|128.0|any": {+ "n": 71,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|121.0|M5 Max|36.0|any": {+ "n": 3,+ "p25_sec": 52.5,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|121.0|M5 Max|48.0|any": {+ "n": 10,+ "p25_sec": 67.5,+ "p50_sec": 90.0,+ "p75_sec": 112.5+ },+ "ltx|i2v|balanced|121.0|M5 Max|64.0|any": {+ "n": 68,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|121.0|M5 Pro|24.0|any": {+ "n": 21,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|121.0|M5 Pro|48.0|any": {+ "n": 215,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M5 Pro|64.0|any": {+ "n": 176,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M5|16.0|any": {+ "n": 27,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M5|24.0|any": {+ "n": 41,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M5|32.0|any": {+ "n": 13,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|145.0|M3 Max|64.0|any": {+ "n": 59,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|145.0|M4 Pro|48.0|any": {+ "n": 92,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|145.0|M5 Pro|48.0|any": {+ "n": 94,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|169.0|M1 Max|32.0|any": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|169.0|M1 Max|64.0|any": {+ "n": 20,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|169.0|M1 Pro|16.0|any": {+ "n": 14,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|169.0|M2 Max|32.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|169.0|M2 Max|64.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 450.0+ },+ "ltx|i2v|balanced|169.0|M2 Pro|32.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|169.0|M2 Ultra|64.0|any": {+ "n": 14,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|169.0|M2|8.0|any": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|169.0|M3 Max|64.0|any": {+ "n": 44,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|169.0|M3 Ultra|256.0|any": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|169.0|M4 Max|36.0|any": {+ "n": 157,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|169.0|M4 Max|48.0|any": {+ "n": 24,+ "p25_sec": 285.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|169.0|M4 Max|64.0|any": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|169.0|M4 Pro|24.0|any": {+ "n": 8,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 285.0+ },+ "ltx|i2v|balanced|169.0|M4 Pro|48.0|any": {+ "n": 45,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|169.0|M4 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|169.0|M4|16.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 975.0+ },+ "ltx|i2v|balanced|169.0|M4|24.0|any": {+ "n": 95,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|169.0|M4|32.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|169.0|M5 Max|128.0|any": {+ "n": 7,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|169.0|M5 Max|64.0|any": {+ "n": 11,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|169.0|M5 Pro|24.0|any": {+ "n": 40,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|169.0|M5 Pro|48.0|any": {+ "n": 36,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|169.0|M5 Pro|64.0|any": {+ "n": 25,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|177.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|185.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|185.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|193.0|M3 Max|64.0|any": {+ "n": 40,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|193.0|M3 Ultra|256.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|193.0|M4 Pro|48.0|any": {+ "n": 117,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|193.0|M5 Max|128.0|any": {+ "n": 24,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|193.0|M5 Max|36.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 105.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|225.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|241.0|M1 Max|32.0|any": {+ "n": 40,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M1 Max|64.0|any": {+ "n": 79,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M1 Pro|16.0|any": {+ "n": 24,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|balanced|241.0|M1 Ultra|128.0|any": {+ "n": 56,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M1 Ultra|64.0|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M1|16.0|any": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|241.0|M2 Max|32.0|any": {+ "n": 61,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M2 Max|64.0|any": {+ "n": 25,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M2 Max|96.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 660.0+ },+ "ltx|i2v|balanced|241.0|M2 Pro|32.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|241.0|M2 Ultra|128.0|any": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|241.0|M2 Ultra|192.0|any": {+ "n": 10,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|241.0|M2 Ultra|64.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M2|16.0|any": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|i2v|balanced|241.0|M3 Max|128.0|any": {+ "n": 33,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M3 Max|36.0|any": {+ "n": 4,+ "p25_sec": 285.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M3 Pro|18.0|any": {+ "n": 12,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M3 Pro|36.0|any": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|241.0|M3 Ultra|256.0|any": {+ "n": 67,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|241.0|M3 Ultra|512.0|any": {+ "n": 6,+ "p25_sec": 375.0,+ "p50_sec": 600.0,+ "p75_sec": 825.0+ },+ "ltx|i2v|balanced|241.0|M3 Ultra|96.0|any": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|241.0|M3|24.0|any": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|241.0|M4 Max|128.0|any": {+ "n": 23,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 510.0+ },+ "ltx|i2v|balanced|241.0|M4 Max|36.0|any": {+ "n": 47,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|241.0|M4 Max|48.0|any": {+ "n": 56,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|241.0|M4 Max|64.0|any": {+ "n": 35,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|241.0|M4 Pro|24.0|any": {+ "n": 308,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|241.0|M4 Pro|48.0|any": {+ "n": 170,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M4 Pro|64.0|any": {+ "n": 15,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M4|16.0|any": {+ "n": 81,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|balanced|241.0|M4|24.0|any": {+ "n": 39,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|241.0|M4|32.0|any": {+ "n": 13,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M5 Max|128.0|any": {+ "n": 599,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|241.0|M5 Max|48.0|any": {+ "n": 15,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|241.0|M5 Max|64.0|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M5 Pro|24.0|any": {+ "n": 47,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|241.0|M5 Pro|48.0|any": {+ "n": 415,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M5 Pro|64.0|any": {+ "n": 43,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|i2v|balanced|241.0|M5|16.0|any": {+ "n": 18,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 825.0+ },+ "ltx|i2v|balanced|241.0|M5|24.0|any": {+ "n": 45,+ "p25_sec": 240.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|balanced|241.0|M5|32.0|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|25.0|M5|24.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|balanced|289.0|M1 Ultra|64.0|any": {+ "n": 22,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|289.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|M1 Max|64.0|any": {+ "n": 6,+ "p25_sec": 1275.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|i2v|balanced|361.0|M1 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|361.0|M2 Ultra|64.0|any": {+ "n": 16,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|M4 Max|128.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|i2v|balanced|361.0|M4 Pro|48.0|any": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|M5 Max|128.0|any": {+ "n": 77,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|361.0|M5 Max|36.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|361.0|M5|24.0|any": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|433.0|M2 Ultra|64.0|any": {+ "n": 18,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|481.0|M4 Max|128.0|any": {+ "n": 16,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|481.0|M5 Pro|48.0|any": {+ "n": 85,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|481.0|M5|16.0|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|481.0|M5|24.0|any": {+ "n": 14,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|49.0|M1 Max|64.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|49.0|M1 Pro|16.0|any": {+ "n": 8,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|49.0|M3 Max|64.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 52.5+ },+ "ltx|i2v|balanced|49.0|M3 Ultra|256.0|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "ltx|i2v|balanced|49.0|M3 Ultra|512.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|balanced|49.0|M4 Max|64.0|any": {+ "n": 43,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|49.0|M4 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|49.0|M5 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 48.8+ },+ "ltx|i2v|balanced|65.0|M1 Max|64.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|721.0|M2 Max|64.0|any": {+ "n": 10,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|i2v|balanced|73.0|M1 Max|32.0|any": {+ "n": 7,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M1 Max|64.0|any": {+ "n": 8,+ "p25_sec": 165.0,+ "p50_sec": 210.0,+ "p75_sec": 255.0+ },+ "ltx|i2v|balanced|73.0|M1 Pro|16.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|73.0|M2 Max|32.0|any": {+ "n": 11,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M2|16.0|any": {+ "n": 3,+ "p25_sec": 105.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M3 Max|36.0|any": {+ "n": 6,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 112.5+ },+ "ltx|i2v|balanced|73.0|M3 Max|64.0|any": {+ "n": 14,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M3 Pro|18.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|73.0|M3 Ultra|256.0|any": {+ "n": 7,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|73.0|M3|8.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|i2v|balanced|73.0|M4 Max|128.0|any": {+ "n": 14,+ "p25_sec": 97.5,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|73.0|M4 Max|36.0|any": {+ "n": 82,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|73.0|M4 Max|48.0|any": {+ "n": 6,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|73.0|M4 Max|64.0|any": {+ "n": 10,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M4 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 112.5,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M4 Pro|48.0|any": {+ "n": 30,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|73.0|M4|16.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 450.0+ },+ "ltx|i2v|balanced|73.0|M4|32.0|any": {+ "n": 4,+ "p25_sec": 225.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|73.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 52.5+ },+ "ltx|i2v|balanced|73.0|M5 Max|64.0|any": {+ "n": 4,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|balanced|73.0|M5 Pro|48.0|any": {+ "n": 23,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|73.0|M5 Pro|64.0|any": {+ "n": 16,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M5|24.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|81.0|M1 Max|64.0|any": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 285.0+ },+ "ltx|i2v|balanced|81.0|M5 Max|48.0|any": {+ "n": 17,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|97.0|M3 Ultra|512.0|any": {+ "n": 19,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|i2v|balanced|97.0|M4 Pro|24.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|97.0|M4 Pro|48.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|97.0|M5 Max|36.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 52.5+ },+ "ltx|i2v|balanced|97.0|M5 Max|48.0|any": {+ "n": 10,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|97.0|M5 Pro|48.0|any": {+ "n": 22,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|draft|121.0|M5 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high_720p|121.0|M3 Ultra|96.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high_720p|121.0|M4 Max|128.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high_720p|121.0|M4 Max|64.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high_720p|241.0|M2 Max|64.0|any": {+ "n": 18,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|113.0|M5 Max|128.0|any": {+ "n": 35,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|high|121.0|M1 Max|64.0|any": {+ "n": 7,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|121.0|M2 Max|64.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|121.0|M2 Ultra|64.0|any": {+ "n": 11,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|121.0|M3 Max|128.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|121.0|M3 Max|64.0|any": {+ "n": 16,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high|121.0|M3 Ultra|256.0|any": {+ "n": 3,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high|121.0|M3 Ultra|96.0|any": {+ "n": 10,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|121.0|M4 Max|128.0|any": {+ "n": 32,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|121.0|M4 Max|48.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|i2v|high|121.0|M4 Max|64.0|any": {+ "n": 41,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high|121.0|M4 Pro|48.0|any": {+ "n": 41,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|121.0|M5 Max|128.0|any": {+ "n": 14,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 285.0+ },+ "ltx|i2v|high|121.0|M5 Max|48.0|any": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|121.0|M5 Pro|48.0|any": {+ "n": 179,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|121.0|M5 Pro|64.0|any": {+ "n": 14,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|145.0|M5 Pro|48.0|any": {+ "n": 76,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high|169.0|M1 Max|64.0|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|high|169.0|M1 Ultra|64.0|any": {+ "n": 12,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|169.0|M4 Max|48.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|169.0|M4 Max|64.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|169.0|M4 Pro|48.0|any": {+ "n": 12,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|169.0|M5 Max|128.0|any": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|241.0|M1 Max|64.0|any": {+ "n": 34,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|241.0|M1 Ultra|128.0|any": {+ "n": 12,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|241.0|M1 Ultra|64.0|any": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|241.0|M2 Max|64.0|any": {+ "n": 13,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|241.0|M2 Ultra|128.0|any": {+ "n": 89,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|241.0|M2 Ultra|192.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|i2v|high|241.0|M3 Max|48.0|any": {+ "n": 4,+ "p25_sec": 525.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|i2v|high|241.0|M3 Ultra|512.0|any": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|241.0|M3 Ultra|96.0|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high|241.0|M4 Max|128.0|any": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1500.0,+ "p75_sec": 1800.0+ },+ "ltx|i2v|high|241.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|high|241.0|M4 Max|48.0|any": {+ "n": 12,+ "p25_sec": 825.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|241.0|M4 Max|64.0|any": {+ "n": 33,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|241.0|M4 Pro|48.0|any": {+ "n": 12,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|241.0|M5 Max|128.0|any": {+ "n": 21,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|241.0|M5 Max|48.0|any": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high|241.0|M5 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|241.0|M5 Pro|64.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 465.0+ },+ "ltx|i2v|high|289.0|M2 Ultra|64.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|33.0|M5 Max|48.0|any": {+ "n": 10,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|high|337.0|M1 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 1050.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|361.0|M5 Max|128.0|any": {+ "n": 20,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|41.0|M5 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|high|49.0|M5 Max|48.0|any": {+ "n": 24,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|high|49.0|M5 Pro|48.0|any": {+ "n": 27,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|65.0|M5 Pro|48.0|any": {+ "n": 18,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|73.0|M2 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|73.0|M4 Max|128.0|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|73.0|M4 Max|64.0|any": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|high|73.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|73.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "ltx|i2v|high|73.0|M5 Pro|48.0|any": {+ "n": 76,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|high|97.0|M5 Max|128.0|any": {+ "n": 4,+ "p25_sec": 105.0,+ "p50_sec": 120.0,+ "p75_sec": 135.0+ },+ "ltx|i2v|high|97.0|M5 Pro|48.0|any": {+ "n": 196,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|113.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|121.0|M1 Max|32.0|any": {+ "n": 26,+ "p25_sec": 195.0,+ "p50_sec": 240.0,+ "p75_sec": 285.0+ },+ "ltx|i2v|quick|121.0|M1 Max|64.0|any": {+ "n": 15,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|121.0|M1 Pro|16.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|121.0|M1 Pro|32.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|121.0|M1 Ultra|128.0|any": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 75.0,+ "p75_sec": 112.5+ },+ "ltx|i2v|quick|121.0|M2 Max|32.0|any": {+ "n": 45,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|121.0|M2 Max|96.0|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|121.0|M2|16.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|121.0|M3 Max|36.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|121.0|M3 Pro|18.0|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|121.0|M3 Ultra|512.0|any": {+ "n": 14,+ "p25_sec": 67.5,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|121.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|121.0|M4 Max|48.0|any": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|121.0|M4 Max|64.0|any": {+ "n": 13,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|121.0|M4 Pro|24.0|any": {+ "n": 19,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|121.0|M4 Pro|48.0|any": {+ "n": 36,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|121.0|M4|16.0|any": {+ "n": 21,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|quick|121.0|M4|24.0|any": {+ "n": 26,+ "p25_sec": 255.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|121.0|M5 Max|36.0|any": {+ "n": 12,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 67.5+ },+ "ltx|i2v|quick|121.0|M5 Max|64.0|any": {+ "n": 9,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|i2v|quick|121.0|M5 Pro|24.0|any": {+ "n": 77,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|121.0|M5 Pro|48.0|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 600.0,+ "p75_sec": 3600.0+ },+ "ltx|i2v|quick|121.0|M5 Pro|64.0|any": {+ "n": 14,+ "p25_sec": 60.0,+ "p50_sec": 105.0,+ "p75_sec": 225.0+ },+ "ltx|i2v|quick|121.0|M5|16.0|any": {+ "n": 13,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|121.0|M5|24.0|any": {+ "n": 12,+ "p25_sec": 375.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|129.0|M2 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|145.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|169.0|M1 Max|64.0|any": {+ "n": 11,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|169.0|M2 Max|32.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|169.0|M4 Max|64.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 105.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|169.0|M4 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 405.0+ },+ "ltx|i2v|quick|169.0|M4 Pro|48.0|any": {+ "n": 11,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|169.0|M4|16.0|any": {+ "n": 3,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|quick|169.0|M5 Max|128.0|any": {+ "n": 12,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|quick|169.0|M5 Pro|24.0|any": {+ "n": 13,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|241.0|M1 Max|32.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|241.0|M1 Max|64.0|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|241.0|M1 Pro|16.0|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|quick|241.0|M1 Ultra|128.0|any": {+ "n": 8,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|241.0|M1|8.0|any": {+ "n": 4,+ "p25_sec": 1650.0,+ "p50_sec": 2700.0,+ "p75_sec": 4050.0+ },+ "ltx|i2v|quick|241.0|M3 Pro|18.0|any": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|241.0|M4 Max|64.0|any": {+ "n": 34,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|241.0|M4 Pro|24.0|any": {+ "n": 59,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|241.0|M4 Pro|48.0|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 1125.0+ },+ "ltx|i2v|quick|241.0|M4|16.0|any": {+ "n": 19,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|quick|241.0|M5 Max|128.0|any": {+ "n": 10,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|241.0|M5 Max|36.0|any": {+ "n": 26,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|241.0|M5 Max|48.0|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|241.0|M5 Pro|48.0|any": {+ "n": 18,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|241.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 270.0+ },+ "ltx|i2v|quick|241.0|M5|24.0|any": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|quick|289.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|313.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|361.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 75.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|i2v|quick|41.0|M1 Max|64.0|any": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|481.0|M1 Max|32.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|481.0|M1 Max|64.0|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|481.0|M1|16.0|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|quick|481.0|M2 Max|32.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|481.0|M2 Ultra|64.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 750.0+ },+ "ltx|i2v|quick|481.0|M4 Max|128.0|any": {+ "n": 41,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|481.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|481.0|M4 Pro|24.0|any": {+ "n": 28,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|481.0|M4 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "ltx|i2v|quick|481.0|M4|16.0|any": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|quick|481.0|M5 Max|128.0|any": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|481.0|M5 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 1485.0+ },+ "ltx|i2v|quick|481.0|M5 Pro|48.0|any": {+ "n": 41,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|481.0|M5 Pro|64.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|481.0|M5|16.0|any": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|481.0|M5|24.0|any": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|49.0|M3 Ultra|512.0|any": {+ "n": 3,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 22.5+ },+ "ltx|i2v|quick|49.0|M4 Max|128.0|any": {+ "n": 3,+ "p25_sec": 105.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|49.0|M4|16.0|any": {+ "n": 14,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|73.0|M1 Max|32.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|73.0|M1 Max|64.0|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "ltx|i2v|quick|73.0|M1 Pro|16.0|any": {+ "n": 3,+ "p25_sec": 450.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|73.0|M2 Max|64.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|73.0|M2 Max|96.0|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|73.0|M2|16.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|73.0|M3 Max|36.0|any": {+ "n": 6,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|73.0|M3 Max|64.0|any": {+ "n": 14,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|73.0|M3 Ultra|96.0|any": {+ "n": 4,+ "p25_sec": 41.2,+ "p50_sec": 67.5,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|73.0|M4 Max|128.0|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 75.0+ },+ "ltx|i2v|quick|73.0|M4 Max|64.0|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|73.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 165.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|73.0|M4 Pro|48.0|any": {+ "n": 7,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|i2v|quick|73.0|M4|16.0|any": {+ "n": 53,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|73.0|M4|24.0|any": {+ "n": 14,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|73.0|M5 Max|128.0|any": {+ "n": 25,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|quick|73.0|M5 Pro|24.0|any": {+ "n": 8,+ "p25_sec": 56.2,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|73.0|M5 Pro|48.0|any": {+ "n": 12,+ "p25_sec": 30.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|quick|73.0|M5 Pro|64.0|any": {+ "n": 7,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 67.5+ },+ "ltx|i2v|quick|73.0|M5|16.0|any": {+ "n": 10,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|73.0|M5|24.0|any": {+ "n": 8,+ "p25_sec": 90.0,+ "p50_sec": 150.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|73.0|M5|32.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|i2v|quick|97.0|M4|16.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|97.0|M5 Pro|48.0|any": {+ "n": 21,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|standard|121.0|M1 Max|32.0|any": {+ "n": 202,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|M1 Max|64.0|any": {+ "n": 11,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|121.0|M1 Pro|16.0|any": {+ "n": 12,+ "p25_sec": 240.0,+ "p50_sec": 360.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|121.0|M1 Ultra|128.0|any": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|121.0|M1|16.0|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 2025.0+ },+ "ltx|i2v|standard|121.0|M2 Max|32.0|any": {+ "n": 18,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|121.0|M2 Max|64.0|any": {+ "n": 33,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|M2 Max|96.0|any": {+ "n": 110,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|M2 Ultra|64.0|any": {+ "n": 42,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|121.0|M3 Max|36.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|121.0|M3 Max|48.0|any": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|121.0|M3 Pro|18.0|any": {+ "n": 3,+ "p25_sec": 810.0,+ "p50_sec": 1200.0,+ "p75_sec": 1500.0+ },+ "ltx|i2v|standard|121.0|M3 Ultra|256.0|any": {+ "n": 8,+ "p25_sec": 165.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|121.0|M3 Ultra|512.0|any": {+ "n": 48,+ "p25_sec": 285.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|121.0|M4 Max|128.0|any": {+ "n": 36,+ "p25_sec": 225.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|121.0|M4 Max|36.0|any": {+ "n": 22,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 112.5+ },+ "ltx|i2v|standard|121.0|M4 Max|48.0|any": {+ "n": 75,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|121.0|M4 Max|64.0|any": {+ "n": 6,+ "p25_sec": 255.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|M4 Pro|24.0|any": {+ "n": 104,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|121.0|M4 Pro|48.0|any": {+ "n": 91,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|M4|16.0|any": {+ "n": 14,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|121.0|M4|24.0|any": {+ "n": 21,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|121.0|M5 Max|128.0|any": {+ "n": 78,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|121.0|M5 Max|36.0|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|standard|121.0|M5 Max|48.0|any": {+ "n": 7,+ "p25_sec": 52.5,+ "p50_sec": 60.0,+ "p75_sec": 105.0+ },+ "ltx|i2v|standard|121.0|M5 Max|64.0|any": {+ "n": 18,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|121.0|M5 Pro|24.0|any": {+ "n": 21,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|standard|121.0|M5 Pro|48.0|any": {+ "n": 63,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|121.0|M5 Pro|64.0|any": {+ "n": 63,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|121.0|M5|16.0|any": {+ "n": 17,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|121.0|M5|24.0|any": {+ "n": 141,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|121.0|M5|32.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|137.0|M4 Max|64.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|145.0|M2 Ultra|64.0|any": {+ "n": 52,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|145.0|M4 Max|36.0|any": {+ "n": 20,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|145.0|M4 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|145.0|M5 Max|128.0|any": {+ "n": 10,+ "p25_sec": 60.0,+ "p50_sec": 180.0,+ "p75_sec": 225.0+ },+ "ltx|i2v|standard|169.0|M1 Max|32.0|any": {+ "n": 110,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M1 Max|64.0|any": {+ "n": 9,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|standard|169.0|M1 Pro|16.0|any": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M2 Max|32.0|any": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|169.0|M2 Max|96.0|any": {+ "n": 40,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|169.0|M2 Ultra|192.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|169.0|M2 Ultra|64.0|any": {+ "n": 99,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|169.0|M3 Pro|18.0|any": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M3|16.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|i2v|standard|169.0|M4 Max|128.0|any": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M4 Max|36.0|any": {+ "n": 78,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|169.0|M4 Max|48.0|any": {+ "n": 35,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|169.0|M4 Max|64.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|169.0|M4 Pro|24.0|any": {+ "n": 58,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|169.0|M4 Pro|48.0|any": {+ "n": 52,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|169.0|M4|16.0|any": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M4|24.0|any": {+ "n": 15,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|169.0|M5 Max|128.0|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|169.0|M5 Max|48.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|i2v|standard|169.0|M5 Max|64.0|any": {+ "n": 132,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|169.0|M5 Pro|24.0|any": {+ "n": 10,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|standard|169.0|M5 Pro|48.0|any": {+ "n": 32,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|169.0|M5 Pro|64.0|any": {+ "n": 22,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|169.0|M5|16.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M5|32.0|any": {+ "n": 3,+ "p25_sec": 450.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|185.0|M3|24.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|i2v|standard|193.0|M2 Ultra|64.0|any": {+ "n": 36,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|193.0|M4 Max|36.0|any": {+ "n": 13,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|193.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|i2v|standard|217.0|M2 Ultra|64.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M1 Max|32.0|any": {+ "n": 180,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M1 Max|64.0|any": {+ "n": 29,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|241.0|M1 Pro|16.0|any": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M1 Ultra|128.0|any": {+ "n": 13,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M1 Ultra|64.0|any": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M1|16.0|any": {+ "n": 13,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|i2v|standard|241.0|M2 Max|32.0|any": {+ "n": 46,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|241.0|M2 Max|64.0|any": {+ "n": 144,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|standard|241.0|M2 Max|96.0|any": {+ "n": 30,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M2 Pro|32.0|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M2 Ultra|128.0|any": {+ "n": 10,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M2 Ultra|192.0|any": {+ "n": 13,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|241.0|M2 Ultra|64.0|any": {+ "n": 84,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M2|16.0|any": {+ "n": 9,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|241.0|M3 Pro|18.0|any": {+ "n": 18,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M3 Ultra|256.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 750.0+ },+ "ltx|i2v|standard|241.0|M3 Ultra|96.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M4 Max|128.0|any": {+ "n": 17,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|241.0|M4 Max|36.0|any": {+ "n": 42,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 225.0+ },+ "ltx|i2v|standard|241.0|M4 Max|48.0|any": {+ "n": 66,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M4 Max|64.0|any": {+ "n": 22,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M4 Pro|24.0|any": {+ "n": 56,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|241.0|M4 Pro|48.0|any": {+ "n": 29,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M4|16.0|any": {+ "n": 76,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|241.0|M4|24.0|any": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M4|32.0|any": {+ "n": 323,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M5 Max|128.0|any": {+ "n": 24,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M5 Max|36.0|any": {+ "n": 17,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|241.0|M5 Max|64.0|any": {+ "n": 39,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|241.0|M5 Pro|24.0|any": {+ "n": 38,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|241.0|M5 Pro|48.0|any": {+ "n": 29,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|241.0|M5 Pro|64.0|any": {+ "n": 23,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M5|16.0|any": {+ "n": 145,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M5|24.0|any": {+ "n": 4,+ "p25_sec": 525.0,+ "p50_sec": 750.0,+ "p75_sec": 975.0+ },+ "ltx|i2v|standard|241.0|M5|32.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|249.0|M4 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|265.0|M5 Max|36.0|any": {+ "n": 3,+ "p25_sec": 52.5,+ "p50_sec": 60.0,+ "p75_sec": 75.0+ },+ "ltx|i2v|standard|289.0|M2 Ultra|64.0|any": {+ "n": 67,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|289.0|M4 Pro|48.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|337.0|M4 Pro|48.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|353.0|M5 Max|128.0|any": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|361.0|M2 Ultra|64.0|any": {+ "n": 8,+ "p25_sec": 825.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|standard|361.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|361.0|M4 Pro|48.0|any": {+ "n": 17,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|393.0|M3 Max|48.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|41.0|M5 Max|48.0|any": {+ "n": 25,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|standard|433.0|M5 Pro|24.0|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|481.0|M2 Ultra|64.0|any": {+ "n": 23,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|481.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|i2v|standard|481.0|M4|32.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|49.0|M4 Pro|48.0|any": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|49.0|M5 Max|128.0|any": {+ "n": 31,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|standard|73.0|M1 Max|32.0|any": {+ "n": 27,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|73.0|M2 Max|32.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|i2v|standard|73.0|M2 Max|64.0|any": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|73.0|M3 Max|36.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|73.0|M3 Pro|36.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|73.0|M4 Max|128.0|any": {+ "n": 3,+ "p25_sec": 210.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|i2v|standard|73.0|M4 Max|36.0|any": {+ "n": 11,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|i2v|standard|73.0|M4 Pro|24.0|any": {+ "n": 12,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|73.0|M4 Pro|48.0|any": {+ "n": 31,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|73.0|M4 Pro|64.0|any": {+ "n": 29,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|73.0|M4|32.0|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|73.0|M5 Max|128.0|any": {+ "n": 158,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|73.0|M5 Max|48.0|any": {+ "n": 5,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|standard|73.0|M5 Pro|48.0|any": {+ "n": 14,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|standard|73.0|M5 Pro|64.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 135.0+ },+ "ltx|i2v|standard|73.0|M5|16.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 1110.0+ },+ "ltx|i2v|standard|81.0|M5 Max|48.0|any": {+ "n": 25,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|standard|89.0|M5 Max|128.0|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|standard|97.0|M2 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|97.0|M3 Ultra|256.0|any": {+ "n": 5,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|i2v|standard|97.0|M4 Pro|48.0|any": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|97.0|M5 Max|128.0|any": {+ "n": 81,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|97.0|M5 Max|48.0|any": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|standard|97.0|M5 Pro|48.0|any": {+ "n": 10,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|standard|97.0|unknown|0.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|balanced|121.0|M1 Max|64.0|any": {+ "n": 11,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|121.0|M2 Max|32.0|any": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|121.0|M2 Max|64.0|any": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|balanced|121.0|M3 Ultra|256.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|balanced|121.0|M4 Max|128.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|121.0|M4 Max|48.0|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|balanced|121.0|M4 Max|64.0|any": {+ "n": 10,+ "p25_sec": 465.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|121.0|M4 Pro|48.0|any": {+ "n": 18,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|121.0|M5 Max|64.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|keyframe|balanced|121.0|M5 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|balanced|121.0|M5 Pro|64.0|any": {+ "n": 10,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|balanced|169.0|M2 Max|32.0|any": {+ "n": 12,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|169.0|M3 Ultra|256.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|balanced|169.0|M4 Pro|48.0|any": {+ "n": 12,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|169.0|M5 Pro|64.0|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|balanced|241.0|M1 Max|64.0|any": {+ "n": 20,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|241.0|M2 Max|32.0|any": {+ "n": 20,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|keyframe|balanced|241.0|M4 Max|48.0|any": {+ "n": 3,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|keyframe|balanced|241.0|M4 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|73.0|M1 Max|64.0|any": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|73.0|M2 Max|32.0|any": {+ "n": 11,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|73.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|balanced|73.0|M5 Max|64.0|any": {+ "n": 13,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|keyframe|balanced|97.0|M4 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|113.0|M5 Max|128.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|121.0|M1 Max|64.0|any": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|keyframe|high|121.0|M3 Max|48.0|any": {+ "n": 11,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|121.0|M3 Ultra|256.0|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|121.0|M5 Max|128.0|any": {+ "n": 34,+ "p25_sec": 255.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|121.0|M5 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|keyframe|high|129.0|M3 Ultra|256.0|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|161.0|M3 Ultra|256.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|193.0|M3 Ultra|256.0|any": {+ "n": 7,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|193.0|M4 Pro|48.0|any": {+ "n": 19,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|241.0|M1 Max|64.0|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|keyframe|high|241.0|M3 Ultra|96.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|241.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|keyframe|high|241.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|361.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|keyframe|high|433.0|M2 Ultra|64.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|73.0|M3 Ultra|256.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|keyframe|high|73.0|M4 Max|64.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|keyframe|high|97.0|M3 Ultra|256.0|any": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|quick|121.0|M4 Max|64.0|any": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|quick|241.0|M4 Max|64.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|standard|121.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|keyframe|standard|121.0|M5 Pro|64.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|keyframe|standard|169.0|M4 Max|128.0|any": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1500.0,+ "p75_sec": 1800.0+ },+ "ltx|keyframe|standard|193.0|M2 Ultra|64.0|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|standard|241.0|M1 Max|64.0|any": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "ltx|keyframe|standard|241.0|M2 Ultra|64.0|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 390.0+ },+ "ltx|keyframe|standard|241.0|M5 Max|48.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|keyframe|standard|289.0|M2 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|standard|481.0|M2 Ultra|64.0|any": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|standard|49.0|M5 Max|128.0|any": {+ "n": 19,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|keyframe|standard|73.0|M5 Max|128.0|any": {+ "n": 43,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|standard|97.0|M5 Max|128.0|any": {+ "n": 17,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|113.0|M5 Max|128.0|any": {+ "n": 6,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|M1 Max|32.0|any": {+ "n": 88,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|121.0|M1 Max|64.0|any": {+ "n": 162,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|121.0|M1 Pro|16.0|any": {+ "n": 76,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|121.0|M1 Pro|32.0|any": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|121.0|M1 Ultra|128.0|any": {+ "n": 34,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M1 Ultra|64.0|any": {+ "n": 23,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M1|16.0|any": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|121.0|M1|8.0|any": {+ "n": 30,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|121.0|M2 Max|32.0|any": {+ "n": 27,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M2 Max|64.0|any": {+ "n": 61,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|121.0|M2 Max|96.0|any": {+ "n": 46,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M2 Pro|16.0|any": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 285.0+ },+ "ltx|t2v|balanced|121.0|M2 Pro|32.0|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M2 Ultra|128.0|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|121.0|M2 Ultra|64.0|any": {+ "n": 23,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|121.0|M2|16.0|any": {+ "n": 3,+ "p25_sec": 660.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|t2v|balanced|121.0|M2|8.0|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|121.0|M3 Max|36.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 360.0+ },+ "ltx|t2v|balanced|121.0|M3 Max|48.0|any": {+ "n": 15,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|121.0|M3 Max|64.0|any": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|t2v|balanced|121.0|M3 Max|96.0|any": {+ "n": 10,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|121.0|M3 Pro|18.0|any": {+ "n": 13,+ "p25_sec": 180.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|121.0|M3 Pro|36.0|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|121.0|M3 Ultra|256.0|any": {+ "n": 20,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|M3 Ultra|512.0|any": {+ "n": 52,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|M3 Ultra|96.0|any": {+ "n": 25,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|121.0|M3|16.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 675.0+ },+ "ltx|t2v|balanced|121.0|M3|24.0|any": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|121.0|M4 Max|128.0|any": {+ "n": 138,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M4 Max|36.0|any": {+ "n": 93,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M4 Max|48.0|any": {+ "n": 14,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M4 Max|64.0|any": {+ "n": 523,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M4 Pro|24.0|any": {+ "n": 194,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|121.0|M4 Pro|48.0|any": {+ "n": 109,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|121.0|M4 Pro|64.0|any": {+ "n": 40,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|121.0|M4|16.0|any": {+ "n": 30,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|121.0|M4|24.0|any": {+ "n": 22,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|121.0|M4|32.0|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "ltx|t2v|balanced|121.0|M5 Max|128.0|any": {+ "n": 80,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|121.0|M5 Max|36.0|any": {+ "n": 3,+ "p25_sec": 52.5,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|121.0|M5 Max|48.0|any": {+ "n": 30,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M5 Max|64.0|any": {+ "n": 50,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|M5 Pro|24.0|any": {+ "n": 19,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|M5 Pro|48.0|any": {+ "n": 83,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|121.0|M5 Pro|64.0|any": {+ "n": 102,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|121.0|M5|16.0|any": {+ "n": 38,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|121.0|M5|24.0|any": {+ "n": 14,+ "p25_sec": 135.0,+ "p50_sec": 210.0,+ "p75_sec": 525.0+ },+ "ltx|t2v|balanced|121.0|M5|32.0|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|145.0|M1 Max|64.0|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|145.0|M4 Max|64.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|145.0|M4 Pro|48.0|any": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|t2v|balanced|145.0|M5 Pro|24.0|any": {+ "n": 45,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|145.0|M5 Pro|48.0|any": {+ "n": 34,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|153.0|M5 Pro|24.0|any": {+ "n": 9,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|169.0|M1 Max|32.0|any": {+ "n": 11,+ "p25_sec": 210.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|t2v|balanced|169.0|M1 Max|64.0|any": {+ "n": 16,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 465.0+ },+ "ltx|t2v|balanced|169.0|M2 Max|96.0|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|169.0|M3 Pro|36.0|any": {+ "n": 10,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|169.0|M3 Ultra|256.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|169.0|M3|24.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 975.0+ },+ "ltx|t2v|balanced|169.0|M4 Max|36.0|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 165.0+ },+ "ltx|t2v|balanced|169.0|M4 Max|64.0|any": {+ "n": 32,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|169.0|M4 Pro|24.0|any": {+ "n": 7,+ "p25_sec": 270.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|169.0|M4 Pro|48.0|any": {+ "n": 19,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|169.0|M4|16.0|any": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|169.0|M5 Max|128.0|any": {+ "n": 11,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|169.0|M5 Pro|24.0|any": {+ "n": 41,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|169.0|M5 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|169.0|M5 Pro|64.0|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|169.0|M5|24.0|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 405.0+ },+ "ltx|t2v|balanced|193.0|M1 Max|64.0|any": {+ "n": 6,+ "p25_sec": 210.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|193.0|M4 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 465.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|217.0|M4 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|M1 Max|32.0|any": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|M1 Max|64.0|any": {+ "n": 35,+ "p25_sec": 180.0,+ "p50_sec": 420.0,+ "p75_sec": 750.0+ },+ "ltx|t2v|balanced|241.0|M1 Pro|16.0|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|241.0|M1 Ultra|128.0|any": {+ "n": 81,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|241.0|M1 Ultra|64.0|any": {+ "n": 36,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|241.0|M1|16.0|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 5400.0+ },+ "ltx|t2v|balanced|241.0|M2 Max|32.0|any": {+ "n": 7,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 450.0+ },+ "ltx|t2v|balanced|241.0|M2 Max|64.0|any": {+ "n": 61,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|M2 Max|96.0|any": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|M2 Pro|32.0|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 810.0+ },+ "ltx|t2v|balanced|241.0|M2|16.0|any": {+ "n": 7,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|balanced|241.0|M3 Max|96.0|any": {+ "n": 12,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|241.0|M3 Pro|36.0|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|M3 Ultra|512.0|any": {+ "n": 33,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|241.0|M3 Ultra|96.0|any": {+ "n": 12,+ "p25_sec": 225.0,+ "p50_sec": 330.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|241.0|M3|24.0|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|241.0|M4 Max|36.0|any": {+ "n": 19,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|241.0|M4 Max|48.0|any": {+ "n": 211,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|241.0|M4 Max|64.0|any": {+ "n": 29,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|241.0|M4 Pro|24.0|any": {+ "n": 77,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|241.0|M4 Pro|48.0|any": {+ "n": 81,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|241.0|M4 Pro|64.0|any": {+ "n": 18,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|241.0|M4|16.0|any": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|241.0|M4|24.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 1500.0,+ "p75_sec": 2700.0+ },+ "ltx|t2v|balanced|241.0|M5 Max|128.0|any": {+ "n": 23,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|241.0|M5 Max|48.0|any": {+ "n": 8,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|241.0|M5 Max|64.0|any": {+ "n": 16,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 195.0+ },+ "ltx|t2v|balanced|241.0|M5 Pro|48.0|any": {+ "n": 18,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|241.0|M5 Pro|64.0|any": {+ "n": 10,+ "p25_sec": 255.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|241.0|M5|16.0|any": {+ "n": 19,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|241.0|M5|24.0|any": {+ "n": 34,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|25.0|M1 Max|64.0|any": {+ "n": 14,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|25.0|M4 Pro|64.0|any": {+ "n": 12,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|33.0|M3 Ultra|256.0|any": {+ "n": 3,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|361.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|361.0|M4 Max|64.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|361.0|M5 Pro|48.0|any": {+ "n": 10,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|409.0|M1 Ultra|64.0|any": {+ "n": 20,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|41.0|M5 Max|48.0|any": {+ "n": 10,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|t2v|balanced|481.0|M2 Max|64.0|any": {+ "n": 9,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|49.0|M3 Ultra|512.0|any": {+ "n": 25,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|49.0|M5 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 56.2,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|65.0|M5 Max|128.0|any": {+ "n": 6,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|balanced|73.0|M1 Max|32.0|any": {+ "n": 40,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M1 Max|64.0|any": {+ "n": 28,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|73.0|M1 Ultra|128.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 135.0+ },+ "ltx|t2v|balanced|73.0|M2 Max|32.0|any": {+ "n": 15,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "ltx|t2v|balanced|73.0|M2 Max|64.0|any": {+ "n": 14,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M2 Max|96.0|any": {+ "n": 16,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M3 Max|64.0|any": {+ "n": 4,+ "p25_sec": 105.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M3 Max|96.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M3 Ultra|256.0|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|73.0|M3 Ultra|512.0|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 67.5+ },+ "ltx|t2v|balanced|73.0|M3 Ultra|96.0|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|73.0|M4 Max|128.0|any": {+ "n": 118,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|73.0|M4 Max|36.0|any": {+ "n": 10,+ "p25_sec": 165.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|73.0|M4 Max|64.0|any": {+ "n": 36,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M4 Pro|48.0|any": {+ "n": 40,+ "p25_sec": 90.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|73.0|M4 Pro|64.0|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|73.0|M5 Max|128.0|any": {+ "n": 24,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 48.8+ },+ "ltx|t2v|balanced|73.0|M5 Pro|48.0|any": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|73.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 75.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|73.0|M5|24.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|73.0|M5|32.0|any": {+ "n": 6,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 112.5+ },+ "ltx|t2v|balanced|89.0|M5 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|balanced|97.0|M1 Max|64.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|97.0|M3 Max|96.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|t2v|balanced|97.0|M3 Ultra|512.0|any": {+ "n": 204,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|97.0|M4 Max|64.0|any": {+ "n": 17,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|97.0|M4 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|draft|121.0|M4 Max|64.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high_720p|121.0|M3 Max|128.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high_720p|121.0|M4 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high_720p|241.0|M1 Ultra|128.0|any": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high_720p|241.0|M4 Max|128.0|any": {+ "n": 13,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high_720p|73.0|M4 Max|128.0|any": {+ "n": 3,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high_720p|73.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high|1.0|M4 Max|128.0|any": {+ "n": 14,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|high|113.0|M5 Max|128.0|any": {+ "n": 120,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|121.0|M1 Max|64.0|any": {+ "n": 58,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|121.0|M1 Ultra|128.0|any": {+ "n": 23,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|121.0|M2 Max|64.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|121.0|M2 Max|96.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|121.0|M2 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|t2v|high|121.0|M3 Ultra|512.0|any": {+ "n": 6,+ "p25_sec": 135.0,+ "p50_sec": 210.0,+ "p75_sec": 510.0+ },+ "ltx|t2v|high|121.0|M4 Max|128.0|any": {+ "n": 57,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|121.0|M4 Max|64.0|any": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|121.0|M4 Pro|48.0|any": {+ "n": 10,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|121.0|M5 Max|128.0|any": {+ "n": 8,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|121.0|M5 Max|48.0|any": {+ "n": 6,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 112.5+ },+ "ltx|t2v|high|121.0|M5 Max|64.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|121.0|M5 Pro|48.0|any": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|121.0|M5 Pro|64.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|t2v|high|145.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|t2v|high|145.0|M5 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|high|169.0|M1 Max|64.0|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|169.0|M1 Ultra|128.0|any": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|169.0|M2 Max|64.0|any": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|169.0|M2 Ultra|64.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|169.0|M4 Pro|48.0|any": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|169.0|M5 Max|128.0|any": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 255.0+ },+ "ltx|t2v|high|241.0|M1 Max|64.0|any": {+ "n": 42,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|241.0|M1 Ultra|128.0|any": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|241.0|M1 Ultra|64.0|any": {+ "n": 15,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|241.0|M2 Max|64.0|any": {+ "n": 4,+ "p25_sec": 825.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|241.0|M3 Max|96.0|any": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1950.0+ },+ "ltx|t2v|high|241.0|M3 Ultra|512.0|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|241.0|M4 Max|128.0|any": {+ "n": 11,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high|241.0|M4 Max|48.0|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high|241.0|M4 Max|64.0|any": {+ "n": 22,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|241.0|M4 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high|241.0|M5 Max|128.0|any": {+ "n": 11,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|241.0|M5 Max|48.0|any": {+ "n": 4,+ "p25_sec": 285.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|289.0|M2 Max|96.0|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|385.0|M1 Max|64.0|any": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high|385.0|M1 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 1125.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high|41.0|M5 Max|48.0|any": {+ "n": 11,+ "p25_sec": 30.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|high|65.0|M3 Ultra|96.0|any": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|65.0|M5 Max|128.0|any": {+ "n": 17,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high|73.0|M1 Max|64.0|any": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|73.0|M1 Ultra|128.0|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|high|73.0|M2 Max|64.0|any": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|73.0|M2 Max|96.0|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|73.0|M2 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high|73.0|M3 Ultra|512.0|any": {+ "n": 23,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|high|73.0|M4 Max|128.0|any": {+ "n": 20,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 330.0+ },+ "ltx|t2v|high|73.0|M4 Max|64.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|73.0|M4 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|97.0|M5 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 135.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M1 Max|32.0|any": {+ "n": 27,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|121.0|M1 Max|64.0|any": {+ "n": 34,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M1 Pro|16.0|any": {+ "n": 13,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|121.0|M1 Ultra|128.0|any": {+ "n": 11,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|121.0|M1 Ultra|64.0|any": {+ "n": 8,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 75.0+ },+ "ltx|t2v|quick|121.0|M2 Max|32.0|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|121.0|M2 Max|64.0|any": {+ "n": 44,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|121.0|M2 Max|96.0|any": {+ "n": 4,+ "p25_sec": 82.5,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|121.0|M2 Ultra|64.0|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M3 Max|36.0|any": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M3 Max|48.0|any": {+ "n": 10,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|121.0|M3 Pro|18.0|any": {+ "n": 3,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|121.0|M3 Ultra|256.0|any": {+ "n": 29,+ "p25_sec": 30.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|121.0|M3 Ultra|512.0|any": {+ "n": 36,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 97.5+ },+ "ltx|t2v|quick|121.0|M3 Ultra|96.0|any": {+ "n": 15,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|121.0|M3|16.0|any": {+ "n": 12,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 975.0+ },+ "ltx|t2v|quick|121.0|M4 Max|128.0|any": {+ "n": 21,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|121.0|M4 Max|36.0|any": {+ "n": 15,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|121.0|M4 Max|64.0|any": {+ "n": 10,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 112.5+ },+ "ltx|t2v|quick|121.0|M4 Pro|24.0|any": {+ "n": 21,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M4 Pro|48.0|any": {+ "n": 83,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M4 Pro|64.0|any": {+ "n": 14,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M4|16.0|any": {+ "n": 7,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|t2v|quick|121.0|M4|24.0|any": {+ "n": 8,+ "p25_sec": 285.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "ltx|t2v|quick|121.0|M5 Max|128.0|any": {+ "n": 88,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|121.0|M5 Max|36.0|any": {+ "n": 38,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|121.0|M5 Max|48.0|any": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|121.0|M5 Max|64.0|any": {+ "n": 19,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 52.5+ },+ "ltx|t2v|quick|121.0|M5 Pro|24.0|any": {+ "n": 8,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|121.0|M5 Pro|48.0|any": {+ "n": 16,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|121.0|M5 Pro|64.0|any": {+ "n": 13,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|121.0|M5|16.0|any": {+ "n": 15,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|121.0|M5|24.0|any": {+ "n": 35,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|145.0|M4 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|t2v|quick|145.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 52.5+ },+ "ltx|t2v|quick|145.0|M5 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|145.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|153.0|M4|24.0|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|169.0|M1 Max|64.0|any": {+ "n": 11,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|169.0|M3 Pro|18.0|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|169.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|169.0|M4 Pro|48.0|any": {+ "n": 8,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|193.0|M4 Pro|48.0|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|193.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|201.0|M4 Max|64.0|any": {+ "n": 15,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|241.0|M1 Max|32.0|any": {+ "n": 4,+ "p25_sec": 525.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|t2v|quick|241.0|M1 Max|64.0|any": {+ "n": 28,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|241.0|M1 Pro|32.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|241.0|M1 Ultra|128.0|any": {+ "n": 13,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|241.0|M2 Max|64.0|any": {+ "n": 30,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|241.0|M3 Ultra|512.0|any": {+ "n": 24,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 135.0+ },+ "ltx|t2v|quick|241.0|M4 Max|128.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|241.0|M4 Max|36.0|any": {+ "n": 8,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|241.0|M4 Pro|24.0|any": {+ "n": 31,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|241.0|M4 Pro|48.0|any": {+ "n": 28,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|241.0|M4|16.0|any": {+ "n": 41,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|241.0|M4|24.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|quick|241.0|M5 Max|128.0|any": {+ "n": 13,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|241.0|M5 Max|36.0|any": {+ "n": 20,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|241.0|M5 Max|64.0|any": {+ "n": 6,+ "p25_sec": 67.5,+ "p50_sec": 90.0,+ "p75_sec": 112.5+ },+ "ltx|t2v|quick|241.0|M5 Pro|48.0|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|241.0|M5 Pro|64.0|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|241.0|M5|16.0|any": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|t2v|quick|241.0|M5|24.0|any": {+ "n": 15,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|25.0|M1 Max|64.0|any": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|25.0|M1 Ultra|128.0|any": {+ "n": 3,+ "p25_sec": 22.5,+ "p50_sec": 30.0,+ "p75_sec": 37.5+ },+ "ltx|t2v|quick|481.0|M1 Max|64.0|any": {+ "n": 4,+ "p25_sec": 525.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|t2v|quick|481.0|M1 Pro|32.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|481.0|M1 Ultra|128.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|t2v|quick|481.0|M1|8.0|any": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2100.0+ },+ "ltx|t2v|quick|481.0|M2 Max|64.0|any": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|481.0|M3 Ultra|96.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|481.0|M4 Pro|24.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|481.0|M4 Pro|48.0|any": {+ "n": 16,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|481.0|M4 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|481.0|M5 Max|128.0|any": {+ "n": 11,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|481.0|M5 Max|64.0|any": {+ "n": 3,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|481.0|M5 Pro|64.0|any": {+ "n": 28,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|49.0|M1 Max|64.0|any": {+ "n": 10,+ "p25_sec": 67.5,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|49.0|M2 Max|64.0|any": {+ "n": 3,+ "p25_sec": 52.5,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|49.0|M3 Max|48.0|any": {+ "n": 3,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 37.5+ },+ "ltx|t2v|quick|49.0|M3 Ultra|512.0|any": {+ "n": 19,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|quick|49.0|M4 Max|48.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|49.0|M4 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|49.0|M5 Pro|64.0|any": {+ "n": 4,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|quick|73.0|M1 Max|32.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "ltx|t2v|quick|73.0|M1 Max|64.0|any": {+ "n": 19,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|73.0|M1 Pro|16.0|any": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|73.0|M1 Ultra|128.0|any": {+ "n": 8,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M1 Ultra|64.0|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M2 Max|64.0|any": {+ "n": 16,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M2 Max|96.0|any": {+ "n": 5,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M2 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 101.2,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|73.0|M3 Max|48.0|any": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M3 Ultra|256.0|any": {+ "n": 6,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 41.2+ },+ "ltx|t2v|quick|73.0|M3 Ultra|512.0|any": {+ "n": 17,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|73.0|M3 Ultra|96.0|any": {+ "n": 15,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|73.0|M4 Max|128.0|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|73.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M4 Max|64.0|any": {+ "n": 11,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 150.0+ },+ "ltx|t2v|quick|73.0|M4 Pro|24.0|any": {+ "n": 15,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|73.0|M4 Pro|48.0|any": {+ "n": 44,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|73.0|M4|16.0|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|73.0|M5 Max|128.0|any": {+ "n": 12,+ "p25_sec": 26.2,+ "p50_sec": 37.5,+ "p75_sec": 56.2+ },+ "ltx|t2v|quick|73.0|M5 Max|64.0|any": {+ "n": 3,+ "p25_sec": 22.5,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|quick|73.0|M5 Pro|64.0|any": {+ "n": 10,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|73.0|M5|16.0|any": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|73.0|M5|24.0|any": {+ "n": 22,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|73.0|M5|32.0|any": {+ "n": 9,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|97.0|M1 Max|64.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|97.0|M3 Max|48.0|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|97.0|M3 Ultra|512.0|any": {+ "n": 4,+ "p25_sec": 101.2,+ "p50_sec": 120.0,+ "p75_sec": 135.0+ },+ "ltx|t2v|quick|97.0|M4 Max|36.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|97.0|M4 Pro|24.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|97.0|M4|16.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|97.0|M5 Pro|48.0|any": {+ "n": 4,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|97.0|M5 Pro|64.0|any": {+ "n": 5,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|97.0|M5|24.0|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|standard|121.0|M1 Max|32.0|any": {+ "n": 22,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|121.0|M1 Max|64.0|any": {+ "n": 63,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|121.0|M1 Pro|16.0|any": {+ "n": 19,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|121.0|M1 Ultra|128.0|any": {+ "n": 3,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 810.0+ },+ "ltx|t2v|standard|121.0|M2 Max|32.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|121.0|M2 Pro|32.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|t2v|standard|121.0|M2 Ultra|64.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|121.0|M3 Max|128.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|t2v|standard|121.0|M3 Max|64.0|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|121.0|M3 Ultra|256.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|121.0|M3 Ultra|512.0|any": {+ "n": 43,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|121.0|M3 Ultra|96.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|121.0|M3|16.0|any": {+ "n": 6,+ "p25_sec": 675.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|standard|121.0|M4 Max|128.0|any": {+ "n": 83,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|121.0|M4 Max|36.0|any": {+ "n": 18,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|121.0|M4 Max|48.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "ltx|t2v|standard|121.0|M4 Max|64.0|any": {+ "n": 8,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|121.0|M4 Pro|24.0|any": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|121.0|M4 Pro|48.0|any": {+ "n": 49,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|121.0|M4|16.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 375.0+ },+ "ltx|t2v|standard|121.0|M4|24.0|any": {+ "n": 3,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|t2v|standard|121.0|M5 Max|128.0|any": {+ "n": 20,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|121.0|M5 Max|36.0|any": {+ "n": 18,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|standard|121.0|M5 Max|48.0|any": {+ "n": 13,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|standard|121.0|M5 Max|64.0|any": {+ "n": 32,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|121.0|M5 Pro|24.0|any": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|standard|121.0|M5 Pro|64.0|any": {+ "n": 15,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|121.0|M5|16.0|any": {+ "n": 33,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|121.0|M5|24.0|any": {+ "n": 144,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|121.0|M5|32.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|145.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|t2v|standard|145.0|M5 Max|128.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|169.0|M2 Ultra|64.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|169.0|M4 Pro|48.0|any": {+ "n": 15,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|169.0|M4|16.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|t2v|standard|169.0|M4|24.0|any": {+ "n": 7,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|169.0|M5 Max|128.0|any": {+ "n": 10,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|169.0|M5 Max|64.0|any": {+ "n": 91,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|169.0|M5 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 172.5+ },+ "ltx|t2v|standard|169.0|M5 Pro|48.0|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|169.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|217.0|M4 Max|48.0|any": {+ "n": 30,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M1 Max|32.0|any": {+ "n": 3,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|t2v|standard|241.0|M1 Max|64.0|any": {+ "n": 56,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|standard|241.0|M1 Pro|16.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 675.0+ },+ "ltx|t2v|standard|241.0|M1 Ultra|128.0|any": {+ "n": 178,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M1|16.0|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 1050.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|standard|241.0|M1|8.0|any": {+ "n": 19,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|standard|241.0|M2 Max|32.0|any": {+ "n": 4,+ "p25_sec": 225.0,+ "p50_sec": 240.0,+ "p75_sec": 255.0+ },+ "ltx|t2v|standard|241.0|M2 Max|64.0|any": {+ "n": 35,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M2 Pro|32.0|any": {+ "n": 6,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|241.0|M2|8.0|any": {+ "n": 4,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|standard|241.0|M3 Ultra|256.0|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M3 Ultra|512.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 750.0+ },+ "ltx|t2v|standard|241.0|M4 Max|128.0|any": {+ "n": 12,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|standard|241.0|M4 Max|36.0|any": {+ "n": 90,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|241.0|M4 Max|48.0|any": {+ "n": 52,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M4 Max|64.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M4 Pro|24.0|any": {+ "n": 55,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M4 Pro|48.0|any": {+ "n": 18,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M4|16.0|any": {+ "n": 22,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|standard|241.0|M4|24.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M5 Max|128.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|241.0|M5 Max|36.0|any": {+ "n": 12,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|standard|241.0|M5 Max|48.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|241.0|M5 Pro|24.0|any": {+ "n": 16,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|241.0|M5 Pro|48.0|any": {+ "n": 10,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|241.0|M5 Pro|64.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|t2v|standard|241.0|M5|16.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M5|24.0|any": {+ "n": 48,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|241.0|M5|32.0|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|25.0|M1 Ultra|128.0|any": {+ "n": 10,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|standard|25.0|M5 Max|48.0|any": {+ "n": 8,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|t2v|standard|313.0|M4|16.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|361.0|M5|24.0|any": {+ "n": 292,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|481.0|M5 Max|48.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|481.0|M5 Pro|24.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|49.0|M4 Max|36.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|standard|73.0|M1 Max|32.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|73.0|M1 Max|64.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 270.0+ },+ "ltx|t2v|standard|73.0|M3 Ultra|256.0|any": {+ "n": 3,+ "p25_sec": 165.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|73.0|M4 Max|128.0|any": {+ "n": 12,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|73.0|M4 Max|48.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|73.0|M4 Pro|24.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|73.0|M4 Pro|64.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|73.0|M4|32.0|any": {+ "n": 21,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|73.0|M5|16.0|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|73.0|M5|32.0|any": {+ "n": 3,+ "p25_sec": 75.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|standard|97.0|M1 Max|32.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "ltx|t2v|standard|97.0|M4 Max|48.0|any": {+ "n": 3,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|97.0|M4 Pro|48.0|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|97.0|M5 Pro|48.0|any": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ }+ },+ "dims": [+ "engine",+ "mode",+ "tier",+ "frames",+ "chip_family",+ "ram_gb",+ "speed"+ ]+ },+ "chip": {+ "cells": {+ "h3|i2v|draft_10s_dense|243.0|M4 Max|fast": {+ "n": 10,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s_dense|243.0|M4 Pro|best": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 3000.0+ },+ "h3|i2v|draft_10s_dense|243.0|M4 Pro|fast": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_10s_dense|243.0|M5 Pro|best": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s_dense|243.0|M5 Pro|fast": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|draft_10s|243.0|M1 Max|fast": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_10s|243.0|M1 Ultra|fast": {+ "n": 14,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_10s|243.0|M2 Max|fast": {+ "n": 9,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|M3 Max|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_10s|243.0|M3 Ultra|fast": {+ "n": 3,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "h3|i2v|draft_10s|243.0|M4 Max|best": {+ "n": 18,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|M4 Max|fast": {+ "n": 40,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_10s|243.0|M5 Max|fast": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_10s|243.0|M5 Pro|best": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|M5 Pro|fast": {+ "n": 26,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_15s|362.0|M1 Max|fast": {+ "n": 20,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_15s|362.0|M1 Ultra|fast": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|i2v|draft_15s|362.0|M4 Max|best": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1125.0+ },+ "h3|i2v|draft_15s|362.0|M4 Max|fast": {+ "n": 17,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_15s|362.0|M4 Pro|best": {+ "n": 4,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|draft_15s|362.0|M4 Pro|fast": {+ "n": 4,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1350.0+ },+ "h3|i2v|draft_15s|362.0|M5 Max|best": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_15s|362.0|M5 Max|fast": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|i2v|draft_15s|362.0|M5 Pro|fast": {+ "n": 16,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_3s|73.0|M1 Max|best": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_3s|73.0|M1 Max|fast": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "h3|i2v|draft_3s|73.0|M3 Max|best": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 465.0+ },+ "h3|i2v|draft_3s|73.0|M3 Max|fast": {+ "n": 16,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|i2v|draft_3s|73.0|M3 Ultra|best": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|i2v|draft_3s|73.0|M3 Ultra|fast": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "h3|i2v|draft_3s|73.0|M4 Max|best": {+ "n": 13,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|i2v|draft_3s|73.0|M4 Max|fast": {+ "n": 24,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "h3|i2v|draft_3s|73.0|M4 Pro|best": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_3s|73.0|M4 Pro|fast": {+ "n": 8,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "h3|i2v|draft_3s|73.0|M5 Max|best": {+ "n": 11,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 150.0+ },+ "h3|i2v|draft_3s|73.0|M5 Pro|best": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_3s|73.0|M5 Pro|fast": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "h3|i2v|draft_5s|124.0|M1 Max|best": {+ "n": 25,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_5s|124.0|M1 Max|fast": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_5s|124.0|M1 Ultra|best": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 660.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_5s|124.0|M1 Ultra|fast": {+ "n": 14,+ "p25_sec": 180.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_5s|124.0|M3 Max|best": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|i2v|draft_5s|124.0|M3 Max|fast": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_5s|124.0|M3 Ultra|best": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_5s|124.0|M3 Ultra|fast": {+ "n": 19,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "h3|i2v|draft_5s|124.0|M4 Max|fast": {+ "n": 19,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_5s|124.0|M4 Pro|fast": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_5s|124.0|M5 Max|best": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|draft_5s|124.0|M5 Max|fast": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "h3|i2v|draft_5s|124.0|M5 Pro|best": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|i2v|draft_5s|124.0|M5 Pro|fast": {+ "n": 35,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|i2v|high_10s_dense|243.0|M1 Ultra|best": {+ "n": 12,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|high_10s_dense|243.0|M4 Max|fast": {+ "n": 8,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s_dense|243.0|M4 Pro|fast": {+ "n": 4,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2700.0+ },+ "h3|i2v|high_10s_dense|243.0|M5 Pro|best": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M1 Max|fast": {+ "n": 4,+ "p25_sec": 2250.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M1 Ultra|best": {+ "n": 19,+ "p25_sec": 2400.0,+ "p50_sec": 3600.0,+ "p75_sec": 4500.0+ },+ "h3|i2v|high_10s|243.0|M1 Ultra|fast": {+ "n": 8,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s|243.0|M2 Max|fast": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s|243.0|M3 Max|best": {+ "n": 3,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|high_10s|243.0|M3 Ultra|best": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|high_10s|243.0|M3 Ultra|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_10s|243.0|M4 Max|best": {+ "n": 90,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M4 Max|fast": {+ "n": 108,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s|243.0|M5 Max|best": {+ "n": 9,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|M5 Max|fast": {+ "n": 28,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|i2v|high_10s|243.0|M5 Pro|best": {+ "n": 34,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_10s|243.0|M5 Pro|fast": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|i2v|high_15s|362.0|M1 Max|fast": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 3000.0+ },+ "h3|i2v|high_15s|362.0|M1 Ultra|best": {+ "n": 77,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|high_15s|362.0|M4 Max|best": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_15s|362.0|M4 Max|fast": {+ "n": 569,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_15s|362.0|M5 Max|best": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_15s|362.0|M5 Max|fast": {+ "n": 16,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_15s|362.0|M5 Pro|best": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_15s|362.0|M5 Pro|fast": {+ "n": 17,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|high_3s|73.0|M1 Ultra|best": {+ "n": 11,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|i2v|high_3s|73.0|M3 Ultra|best": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|high_3s|73.0|M4 Max|best": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_3s|73.0|M4 Max|fast": {+ "n": 16,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|i2v|high_3s|73.0|M5 Max|fast": {+ "n": 29,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|high_3s|73.0|M5 Pro|best": {+ "n": 209,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_3s|73.0|M5 Pro|fast": {+ "n": 58,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|i2v|high_5s|124.0|M1 Max|best": {+ "n": 4,+ "p25_sec": 2250.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_5s|124.0|M1 Max|fast": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|M1 Ultra|best": {+ "n": 62,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|high_5s|124.0|M1 Ultra|fast": {+ "n": 34,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M2 Ultra|best": {+ "n": 154,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|M2 Ultra|fast": {+ "n": 22,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|high_5s|124.0|M3 Max|best": {+ "n": 20,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_5s|124.0|M3 Max|fast": {+ "n": 19,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M3 Ultra|best": {+ "n": 56,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|high_5s|124.0|M3 Ultra|fast": {+ "n": 64,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_5s|124.0|M4 Max|best": {+ "n": 9,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|high_5s|124.0|M4 Max|fast": {+ "n": 141,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|i2v|high_5s|124.0|M4 Pro|fast": {+ "n": 7,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|i2v|high_5s|124.0|M5 Max|best": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|M5 Max|fast": {+ "n": 69,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_5s|124.0|M5 Pro|best": {+ "n": 282,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|high_5s|124.0|M5 Pro|fast": {+ "n": 147,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|native_10s|243.0|M1 Ultra|best": {+ "n": 13,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_10s|243.0|M4 Max|best": {+ "n": 6,+ "p25_sec": 4050.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_10s|243.0|M4 Max|fast": {+ "n": 15,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|native_10s|243.0|M5 Max|fast": {+ "n": 12,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|native_15s|362.0|M1 Ultra|best": {+ "n": 9,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_15s|362.0|M2 Ultra|fast": {+ "n": 5,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|native_15s|362.0|M4 Max|best": {+ "n": 6,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_3s|73.0|M4 Max|best": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1500.0+ },+ "h3|i2v|native_3s|73.0|M4 Max|fast": {+ "n": 24,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|native_5s|124.0|M1 Max|best": {+ "n": 14,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_5s|124.0|M1 Ultra|best": {+ "n": 3,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|native_5s|124.0|M1 Ultra|fast": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|native_5s|124.0|M3 Ultra|best": {+ "n": 5,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|native_5s|124.0|M4 Max|best": {+ "n": 16,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|native_5s|124.0|M4 Max|fast": {+ "n": 16,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1950.0+ },+ "h3|i2v|native_5s|124.0|M5 Max|fast": {+ "n": 13,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|i2v|native_5s|124.0|M5 Pro|best": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|standard_10s_dense|243.0|M1 Ultra|best": {+ "n": 4,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_10s_dense|243.0|M3 Ultra|best": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Max|best": {+ "n": 5,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Max|fast": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Pro|best": {+ "n": 7,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|standard_10s_dense|243.0|M4 Pro|fast": {+ "n": 22,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s_dense|243.0|M5 Max|fast": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_10s|243.0|M1 Max|best": {+ "n": 9,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_10s|243.0|M1 Max|fast": {+ "n": 19,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|i2v|standard_10s|243.0|M1 Ultra|fast": {+ "n": 11,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_10s|243.0|M2 Max|fast": {+ "n": 9,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_10s|243.0|M2 Ultra|best": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|M2 Ultra|fast": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_10s|243.0|M3 Ultra|best": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|M3 Ultra|fast": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_10s|243.0|M4 Max|best": {+ "n": 49,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|M4 Max|fast": {+ "n": 144,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_10s|243.0|M4 Pro|best": {+ "n": 6,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_10s|243.0|M4 Pro|fast": {+ "n": 11,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|M5 Max|best": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 555.0+ },+ "h3|i2v|standard_10s|243.0|M5 Max|fast": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_10s|243.0|M5 Pro|best": {+ "n": 6,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_10s|243.0|M5 Pro|fast": {+ "n": 17,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_15s|362.0|M1 Max|best": {+ "n": 11,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|standard_15s|362.0|M1 Max|fast": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1650.0+ },+ "h3|i2v|standard_15s|362.0|M1 Ultra|best": {+ "n": 10,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|standard_15s|362.0|M4 Max|fast": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_15s|362.0|M4 Pro|best": {+ "n": 8,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|standard_15s|362.0|M4 Pro|fast": {+ "n": 12,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1950.0+ },+ "h3|i2v|standard_15s|362.0|M5 Max|best": {+ "n": 7,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|i2v|standard_15s|362.0|M5 Max|fast": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_15s|362.0|M5 Pro|best": {+ "n": 10,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_15s|362.0|M5 Pro|fast": {+ "n": 37,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_3s|73.0|M1 Max|best": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_3s|73.0|M2 Max|best": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_3s|73.0|M3 Max|fast": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_3s|73.0|M4 Max|fast": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|standard_3s|73.0|M5 Max|best": {+ "n": 20,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|i2v|standard_3s|73.0|M5 Max|fast": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "h3|i2v|standard_3s|73.0|M5 Pro|best": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|standard_3s|73.0|M5 Pro|fast": {+ "n": 13,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|i2v|standard_5s|124.0|M1 Max|best": {+ "n": 31,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_5s|124.0|M1 Max|fast": {+ "n": 19,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_5s|124.0|M1 Ultra|best": {+ "n": 4,+ "p25_sec": 825.0,+ "p50_sec": 900.0,+ "p75_sec": 975.0+ },+ "h3|i2v|standard_5s|124.0|M1 Ultra|fast": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_5s|124.0|M2 Ultra|best": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_5s|124.0|M3 Max|best": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_5s|124.0|M3 Max|fast": {+ "n": 33,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_5s|124.0|M3 Ultra|best": {+ "n": 16,+ "p25_sec": 390.0,+ "p50_sec": 510.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_5s|124.0|M3 Ultra|fast": {+ "n": 26,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_5s|124.0|M4 Max|best": {+ "n": 7,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|i2v|standard_5s|124.0|M4 Max|fast": {+ "n": 257,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|i2v|standard_5s|124.0|M4 Pro|fast": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_5s|124.0|M5 Max|best": {+ "n": 73,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_5s|124.0|M5 Max|fast": {+ "n": 6,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|i2v|standard_5s|124.0|M5 Pro|best": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_5s|124.0|M5 Pro|fast": {+ "n": 23,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 270.0+ },+ "h3|keyframe|high_3s|73.0|M5 Max|fast": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|keyframe|high_5s|124.0|M5 Max|fast": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_10s_dense|243.0|M4 Pro|best": {+ "n": 9,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|draft_10s_dense|243.0|M5 Max|best": {+ "n": 53,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s_dense|243.0|M5 Pro|fast": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_10s|243.0|M1 Max|best": {+ "n": 10,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1650.0+ },+ "h3|t2v|draft_10s|243.0|M1 Max|fast": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|draft_10s|243.0|M1 Ultra|fast": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_10s|243.0|M2 Max|fast": {+ "n": 7,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s|243.0|M3 Max|best": {+ "n": 6,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2250.0+ },+ "h3|t2v|draft_10s|243.0|M3 Ultra|best": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 810.0+ },+ "h3|t2v|draft_10s|243.0|M3 Ultra|fast": {+ "n": 11,+ "p25_sec": 180.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s|243.0|M4 Pro|best": {+ "n": 38,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_10s|243.0|M4 Pro|fast": {+ "n": 10,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s|243.0|M5 Max|best": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_10s|243.0|M5 Max|fast": {+ "n": 4,+ "p25_sec": 112.5,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_10s|243.0|M5 Pro|fast": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_15s|362.0|M1 Max|fast": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 3300.0+ },+ "h3|t2v|draft_15s|362.0|M1 Ultra|fast": {+ "n": 11,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_15s|362.0|M4 Max|fast": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|t2v|draft_15s|362.0|M4 Pro|best": {+ "n": 7,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|draft_15s|362.0|M4 Pro|fast": {+ "n": 14,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_15s|362.0|M5 Max|best": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_15s|362.0|M5 Max|fast": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_15s|362.0|M5 Pro|fast": {+ "n": 11,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_3s|73.0|M1 Max|best": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_3s|73.0|M1 Max|fast": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "h3|t2v|draft_3s|73.0|M1 Ultra|best": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 330.0+ },+ "h3|t2v|draft_3s|73.0|M1 Ultra|fast": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 105.0,+ "p75_sec": 150.0+ },+ "h3|t2v|draft_3s|73.0|M2 Max|best": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_3s|73.0|M2 Max|fast": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "h3|t2v|draft_3s|73.0|M2 Ultra|best": {+ "n": 11,+ "p25_sec": 210.0,+ "p50_sec": 240.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_3s|73.0|M2 Ultra|fast": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_3s|73.0|M3 Max|best": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_3s|73.0|M3 Max|fast": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 165.0+ },+ "h3|t2v|draft_3s|73.0|M3 Ultra|best": {+ "n": 30,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_3s|73.0|M3 Ultra|fast": {+ "n": 17,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "h3|t2v|draft_3s|73.0|M4 Max|best": {+ "n": 15,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_3s|73.0|M4 Max|fast": {+ "n": 23,+ "p25_sec": 90.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_3s|73.0|M4 Pro|best": {+ "n": 7,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_3s|73.0|M4 Pro|fast": {+ "n": 76,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_3s|73.0|M5 Max|best": {+ "n": 550,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|t2v|draft_3s|73.0|M5 Max|fast": {+ "n": 21,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 60.0+ },+ "h3|t2v|draft_3s|73.0|M5 Pro|best": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_3s|73.0|M5 Pro|fast": {+ "n": 21,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "h3|t2v|draft_5s|124.0|M1 Max|best": {+ "n": 46,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|draft_5s|124.0|M1 Max|fast": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M1 Ultra|best": {+ "n": 34,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_5s|124.0|M1 Ultra|fast": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M2 Max|fast": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_5s|124.0|M2 Ultra|best": {+ "n": 57,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_5s|124.0|M3 Max|best": {+ "n": 20,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_5s|124.0|M3 Max|fast": {+ "n": 22,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M3 Ultra|best": {+ "n": 21,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M3 Ultra|fast": {+ "n": 27,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_5s|124.0|M4 Max|best": {+ "n": 27,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_5s|124.0|M4 Max|fast": {+ "n": 27,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M4 Pro|best": {+ "n": 22,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_5s|124.0|M4 Pro|fast": {+ "n": 34,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|t2v|draft_5s|124.0|M5 Max|best": {+ "n": 135,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|t2v|draft_5s|124.0|M5 Max|fast": {+ "n": 58,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|draft_5s|124.0|M5 Pro|best": {+ "n": 10,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_5s|124.0|M5 Pro|fast": {+ "n": 14,+ "p25_sec": 60.0,+ "p50_sec": 75.0,+ "p75_sec": 90.0+ },+ "h3|t2v|high_10s_dense|243.0|M1 Ultra|best": {+ "n": 4,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_10s_dense|243.0|M1 Ultra|fast": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|high_10s_dense|243.0|M2 Max|best": {+ "n": 11,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_10s_dense|243.0|M4 Pro|best": {+ "n": 18,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_10s_dense|243.0|M5 Max|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_10s_dense|243.0|M5 Pro|fast": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_10s|243.0|M1 Max|best": {+ "n": 3,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 4500.0+ },+ "h3|t2v|high_10s|243.0|M1 Ultra|best": {+ "n": 15,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|high_10s|243.0|M2 Ultra|best": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2700.0+ },+ "h3|t2v|high_10s|243.0|M2 Ultra|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "h3|t2v|high_10s|243.0|M3 Ultra|fast": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1500.0+ },+ "h3|t2v|high_10s|243.0|M4 Max|fast": {+ "n": 12,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1350.0+ },+ "h3|t2v|high_15s|362.0|M1 Ultra|best": {+ "n": 35,+ "p25_sec": 3600.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_15s|362.0|M2 Ultra|best": {+ "n": 4,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_15s|362.0|M4 Max|fast": {+ "n": 4,+ "p25_sec": 3150.0,+ "p50_sec": 3600.0,+ "p75_sec": 4050.0+ },+ "h3|t2v|high_15s|362.0|M4 Pro|best": {+ "n": 4,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_15s|362.0|M4 Pro|fast": {+ "n": 9,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|high_15s|362.0|M5 Max|fast": {+ "n": 4,+ "p25_sec": 825.0,+ "p50_sec": 1050.0,+ "p75_sec": 1500.0+ },+ "h3|t2v|high_15s|362.0|M5 Pro|best": {+ "n": 7,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|high_15s|362.0|M5 Pro|fast": {+ "n": 4,+ "p25_sec": 825.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|high_3s|73.0|M1 Ultra|best": {+ "n": 24,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|t2v|high_3s|73.0|M4 Max|fast": {+ "n": 7,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_3s|73.0|M4 Pro|fast": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_3s|73.0|M5 Max|best": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_3s|73.0|M5 Max|fast": {+ "n": 68,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|high_5s|124.0|M1 Max|best": {+ "n": 5,+ "p25_sec": 2400.0,+ "p50_sec": 3600.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_5s|124.0|M1 Max|fast": {+ "n": 6,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1125.0+ },+ "h3|t2v|high_5s|124.0|M1 Ultra|best": {+ "n": 9,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|high_5s|124.0|M2 Max|fast": {+ "n": 13,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_5s|124.0|M3 Max|best": {+ "n": 8,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2700.0+ },+ "h3|t2v|high_5s|124.0|M3 Max|fast": {+ "n": 3,+ "p25_sec": 570.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|t2v|high_5s|124.0|M3 Ultra|fast": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|t2v|high_5s|124.0|M4 Max|best": {+ "n": 8,+ "p25_sec": 900.0,+ "p50_sec": 1500.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|high_5s|124.0|M4 Max|fast": {+ "n": 36,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_5s|124.0|M5 Max|best": {+ "n": 40,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|high_5s|124.0|M5 Max|fast": {+ "n": 15,+ "p25_sec": 270.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|high_5s|124.0|M5 Pro|best": {+ "n": 13,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|high_5s|124.0|M5 Pro|fast": {+ "n": 12,+ "p25_sec": 285.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "h3|t2v|native_10s_dense|243.0|M4 Max|best": {+ "n": 10,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_10s|243.0|M1 Ultra|best": {+ "n": 5,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_10s|243.0|M4 Max|fast": {+ "n": 3,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|native_15s|362.0|M4 Max|fast": {+ "n": 3,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|native_15s|362.0|M4 Pro|best": {+ "n": 3,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_3s|73.0|M1 Ultra|best": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|native_3s|73.0|M4 Max|fast": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|native_3s|73.0|M5 Max|best": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 810.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|native_3s|73.0|M5 Max|fast": {+ "n": 6,+ "p25_sec": 285.0,+ "p50_sec": 420.0,+ "p75_sec": 555.0+ },+ "h3|t2v|native_5s|124.0|M1 Ultra|best": {+ "n": 3,+ "p25_sec": 3000.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|native_5s|124.0|M3 Ultra|fast": {+ "n": 8,+ "p25_sec": 1575.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|native_5s|124.0|M4 Max|best": {+ "n": 9,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|native_5s|124.0|M4 Max|fast": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|standard_10s_dense|243.0|M4 Max|fast": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 825.0+ },+ "h3|t2v|standard_10s_dense|243.0|M4 Pro|best": {+ "n": 31,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_10s_dense|243.0|M5 Max|best": {+ "n": 7,+ "p25_sec": 750.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_10s_dense|243.0|M5 Max|fast": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 390.0+ },+ "h3|t2v|standard_10s|243.0|M1 Max|best": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_10s|243.0|M1 Ultra|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_10s|243.0|M2 Ultra|best": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|standard_10s|243.0|M3 Max|best": {+ "n": 6,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_10s|243.0|M3 Ultra|fast": {+ "n": 8,+ "p25_sec": 285.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_10s|243.0|M4 Max|fast": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_10s|243.0|M4 Pro|best": {+ "n": 24,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|standard_10s|243.0|M4 Pro|fast": {+ "n": 7,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_10s|243.0|M5 Max|best": {+ "n": 10,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_10s|243.0|M5 Max|fast": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|t2v|standard_10s|243.0|M5 Pro|fast": {+ "n": 25,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_15s|362.0|M1 Max|best": {+ "n": 4,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 4050.0+ },+ "h3|t2v|standard_15s|362.0|M4 Max|fast": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_15s|362.0|M4 Pro|best": {+ "n": 11,+ "p25_sec": 2400.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_15s|362.0|M4 Pro|fast": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|standard_15s|362.0|M5 Max|best": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_15s|362.0|M5 Max|fast": {+ "n": 22,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|standard_15s|362.0|M5 Pro|best": {+ "n": 9,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_15s|362.0|M5 Pro|fast": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_3s|73.0|M1 Max|best": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "h3|t2v|standard_3s|73.0|M1 Max|fast": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "h3|t2v|standard_3s|73.0|M2 Max|best": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 465.0+ },+ "h3|t2v|standard_3s|73.0|M3 Max|best": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "h3|t2v|standard_3s|73.0|M3 Ultra|fast": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|t2v|standard_3s|73.0|M4 Max|best": {+ "n": 4,+ "p25_sec": 285.0,+ "p50_sec": 450.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_3s|73.0|M4 Max|fast": {+ "n": 11,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_3s|73.0|M4 Pro|fast": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_3s|73.0|M5 Max|best": {+ "n": 14,+ "p25_sec": 97.5,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "h3|t2v|standard_3s|73.0|M5 Max|fast": {+ "n": 13,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "h3|t2v|standard_3s|73.0|M5 Pro|best": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|t2v|standard_3s|73.0|M5 Pro|fast": {+ "n": 52,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "h3|t2v|standard_5s|124.0|M1 Max|best": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|standard_5s|124.0|M1 Max|fast": {+ "n": 29,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_5s|124.0|M1 Ultra|best": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_5s|124.0|M1 Ultra|fast": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|t2v|standard_5s|124.0|M3 Max|best": {+ "n": 20,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1950.0+ },+ "h3|t2v|standard_5s|124.0|M3 Max|fast": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "h3|t2v|standard_5s|124.0|M3 Ultra|best": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 465.0+ },+ "h3|t2v|standard_5s|124.0|M3 Ultra|fast": {+ "n": 21,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_5s|124.0|M4 Max|best": {+ "n": 10,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_5s|124.0|M4 Max|fast": {+ "n": 38,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|t2v|standard_5s|124.0|M4 Pro|best": {+ "n": 8,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_5s|124.0|M4 Pro|fast": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|standard_5s|124.0|M5 Max|best": {+ "n": 30,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|standard_5s|124.0|M5 Max|fast": {+ "n": 12,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "h3|t2v|standard_5s|124.0|M5 Pro|best": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "h3|t2v|standard_5s|124.0|M5 Pro|fast": {+ "n": 16,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx23|t2v|high|121.0|M3 Ultra|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|balanced|105.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|121.0|M4 Max|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|121.0|M4 Pro|any": {+ "n": 15,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|121.0|M4|any": {+ "n": 46,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|121.0|M5 Max|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|balanced|129.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|a2v|balanced|129.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 105.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|137.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 390.0,+ "p50_sec": 420.0,+ "p75_sec": 465.0+ },+ "ltx|a2v|balanced|137.0|M5 Max|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|145.0|M4 Pro|any": {+ "n": 10,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 555.0+ },+ "ltx|a2v|balanced|145.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|145.0|M5 Pro|any": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|153.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|161.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|169.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|177.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|193.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|209.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|balanced|217.0|M4 Pro|any": {+ "n": 9,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|241.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|balanced|49.0|M4|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|57.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|57.0|M4|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|65.0|M4|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|a2v|balanced|65.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 52.5+ },+ "ltx|a2v|balanced|73.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 750.0+ },+ "ltx|a2v|balanced|73.0|M4|any": {+ "n": 43,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|73.0|M5 Max|any": {+ "n": 5,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "ltx|a2v|balanced|73.0|M5 Pro|any": {+ "n": 8,+ "p25_sec": 112.5,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|81.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|81.0|M4|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|89.0|M4|any": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|89.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 67.5+ },+ "ltx|a2v|balanced|97.0|M4 Pro|any": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|97.0|M4|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|97.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 82.5,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|high|105.0|M4 Max|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 615.0+ },+ "ltx|a2v|high|105.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|a2v|high|113.0|M5 Max|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|121.0|M1 Ultra|any": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 570.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|121.0|M2 Max|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|high|121.0|M4 Max|any": {+ "n": 14,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|121.0|M4 Pro|any": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 450.0,+ "p75_sec": 675.0+ },+ "ltx|a2v|high|121.0|M5 Max|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|a2v|high|121.0|M5 Pro|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 375.0+ },+ "ltx|a2v|high|129.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|high|137.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|high|145.0|M1 Ultra|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|145.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|high|153.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|high|169.0|M1 Max|any": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|169.0|M2 Max|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|169.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|169.0|M4 Max|any": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 570.0,+ "p75_sec": 1125.0+ },+ "ltx|a2v|high|169.0|M4 Pro|any": {+ "n": 27,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 660.0+ },+ "ltx|a2v|high|169.0|M4|any": {+ "n": 9,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|169.0|M5 Max|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 255.0+ },+ "ltx|a2v|high|169.0|M5 Pro|any": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|185.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|193.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 750.0,+ "p50_sec": 1200.0,+ "p75_sec": 1650.0+ },+ "ltx|a2v|high|217.0|M4 Pro|any": {+ "n": 7,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|241.0|M1 Ultra|any": {+ "n": 22,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|241.0|M2 Pro|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|241.0|M4 Max|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 810.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|241.0|M4 Pro|any": {+ "n": 17,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|241.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|241.0|M5 Pro|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|265.0|M1 Ultra|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|a2v|high|289.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|361.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 2010.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "ltx|a2v|high|385.0|M4|any": {+ "n": 38,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|409.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|433.0|M2 Pro|any": {+ "n": 4,+ "p25_sec": 2100.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|433.0|M4 Pro|any": {+ "n": 71,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|433.0|M5 Max|any": {+ "n": 29,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|481.0|M1 Ultra|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 810.0+ },+ "ltx|a2v|high|481.0|M4 Pro|any": {+ "n": 13,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|481.0|M5 Max|any": {+ "n": 20,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|57.0|M5 Pro|any": {+ "n": 16,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|a2v|high|601.0|M4 Pro|any": {+ "n": 8,+ "p25_sec": 2250.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|65.0|M5 Pro|any": {+ "n": 6,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|a2v|high|713.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|73.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 450.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|89.0|M1 Max|any": {+ "n": 3,+ "p25_sec": 2100.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|97.0|M1 Max|any": {+ "n": 4,+ "p25_sec": 825.0,+ "p50_sec": 1350.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|97.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 165.0,+ "p50_sec": 240.0,+ "p75_sec": 330.0+ },+ "ltx|a2v|quick|241.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|105.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|121.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 165.0,+ "p50_sec": 180.0,+ "p75_sec": 285.0+ },+ "ltx|a2v|standard|129.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|137.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|145.0|M4 Pro|any": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|standard|153.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|a2v|standard|161.0|M4 Pro|any": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|standard|169.0|M4 Pro|any": {+ "n": 8,+ "p25_sec": 900.0,+ "p50_sec": 1050.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|standard|177.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 975.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|standard|193.0|M4 Pro|any": {+ "n": 11,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|standard|241.0|M4 Max|any": {+ "n": 6,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|standard|241.0|M4 Pro|any": {+ "n": 48,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|73.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|73.0|M5 Max|any": {+ "n": 32,+ "p25_sec": 90.0,+ "p50_sec": 105.0,+ "p75_sec": 180.0+ },+ "ltx|a2v|standard|97.0|M4 Pro|any": {+ "n": 24,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|97.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 165.0+ },+ "ltx|extend|balanced|121.0|M1 Max|any": {+ "n": 4,+ "p25_sec": 1005.0,+ "p50_sec": 1800.0,+ "p75_sec": 3150.0+ },+ "ltx|extend|balanced|121.0|M2 Max|any": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 2100.0+ },+ "ltx|extend|balanced|121.0|M3 Ultra|any": {+ "n": 8,+ "p25_sec": 900.0,+ "p50_sec": 1050.0,+ "p75_sec": 1500.0+ },+ "ltx|extend|balanced|121.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 2700.0,+ "p75_sec": 4050.0+ },+ "ltx|extend|balanced|121.0|M5 Max|any": {+ "n": 7,+ "p25_sec": 450.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|extend|balanced|121.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|extend|balanced|241.0|M1 Max|any": {+ "n": 3,+ "p25_sec": 3000.0,+ "p50_sec": 3600.0,+ "p75_sec": 4500.0+ },+ "ltx|extend|balanced|241.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 4650.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "ltx|extend|balanced|241.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1500.0+ },+ "ltx|extend|high|121.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "ltx|extend|high|241.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 4500.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "ltx|extend|high|241.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 1050.0,+ "p50_sec": 1200.0,+ "p75_sec": 1500.0+ },+ "ltx|extend|quick|121.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 3600.0+ },+ "ltx|extend|standard|241.0|M1 Max|any": {+ "n": 4,+ "p25_sec": 3300.0,+ "p50_sec": 4500.0,+ "p75_sec": 5400.0+ },+ "ltx|i2v|balanced|105.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 285.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|113.0|M5 Max|any": {+ "n": 44,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|121.0|M1 Max|any": {+ "n": 326,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M1 Pro|any": {+ "n": 36,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M1 Ultra|any": {+ "n": 18,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 270.0+ },+ "ltx|i2v|balanced|121.0|M1|any": {+ "n": 26,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|121.0|M2 Max|any": {+ "n": 289,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|121.0|M2 Pro|any": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M2 Ultra|any": {+ "n": 45,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M2|any": {+ "n": 12,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|balanced|121.0|M3 Max|any": {+ "n": 206,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M3 Pro|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|121.0|M3 Ultra|any": {+ "n": 193,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M3|any": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|121.0|M4 Max|any": {+ "n": 343,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M4 Pro|any": {+ "n": 306,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|121.0|M4|any": {+ "n": 146,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|121.0|M5 Max|any": {+ "n": 152,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|121.0|M5 Pro|any": {+ "n": 412,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|121.0|M5|any": {+ "n": 81,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|137.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|145.0|M1 Max|any": {+ "n": 3,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|145.0|M3 Max|any": {+ "n": 59,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|145.0|M4 Pro|any": {+ "n": 92,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|145.0|M5 Pro|any": {+ "n": 95,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|169.0|M1 Max|any": {+ "n": 29,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|169.0|M1 Pro|any": {+ "n": 15,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|169.0|M2 Max|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "ltx|i2v|balanced|169.0|M2 Pro|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|169.0|M2 Ultra|any": {+ "n": 15,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|169.0|M2|any": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|169.0|M3 Max|any": {+ "n": 47,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|169.0|M3 Ultra|any": {+ "n": 12,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|169.0|M4 Max|any": {+ "n": 190,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|169.0|M4 Pro|any": {+ "n": 56,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|169.0|M4|any": {+ "n": 104,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|169.0|M5 Max|any": {+ "n": 19,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|169.0|M5 Pro|any": {+ "n": 101,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|169.0|M5|any": {+ "n": 4,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "ltx|i2v|balanced|177.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|185.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|185.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|193.0|M3 Max|any": {+ "n": 40,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|193.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|193.0|M4 Pro|any": {+ "n": 117,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|193.0|M5 Max|any": {+ "n": 28,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|225.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|241.0|M1 Max|any": {+ "n": 119,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M1 Pro|any": {+ "n": 26,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|balanced|241.0|M1 Ultra|any": {+ "n": 64,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M1|any": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|241.0|M2 Max|any": {+ "n": 89,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M2 Pro|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|241.0|M2 Ultra|any": {+ "n": 23,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M2|any": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|i2v|balanced|241.0|M3 Max|any": {+ "n": 39,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M3 Pro|any": {+ "n": 16,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M3 Ultra|any": {+ "n": 80,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|241.0|M3|any": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|balanced|241.0|M4 Max|any": {+ "n": 161,+ "p25_sec": 180.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|241.0|M4 Pro|any": {+ "n": 493,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|241.0|M4|any": {+ "n": 133,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|balanced|241.0|M5 Max|any": {+ "n": 625,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|241.0|M5 Pro|any": {+ "n": 505,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|241.0|M5|any": {+ "n": 68,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 675.0+ },+ "ltx|i2v|balanced|25.0|M5|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|balanced|289.0|M1 Ultra|any": {+ "n": 22,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|289.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|M1 Max|any": {+ "n": 6,+ "p25_sec": 1275.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|i2v|balanced|361.0|M1 Ultra|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|361.0|M2 Ultra|any": {+ "n": 16,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|M4 Max|any": {+ "n": 6,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|M4 Pro|any": {+ "n": 12,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|M5 Max|any": {+ "n": 81,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|361.0|M5|any": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|balanced|433.0|M2 Ultra|any": {+ "n": 18,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|481.0|M4 Max|any": {+ "n": 17,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|481.0|M5 Pro|any": {+ "n": 86,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|481.0|M5|any": {+ "n": 17,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|49.0|M1 Max|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|49.0|M1 Pro|any": {+ "n": 8,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|49.0|M3 Max|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 52.5+ },+ "ltx|i2v|balanced|49.0|M3 Ultra|any": {+ "n": 8,+ "p25_sec": 45.0,+ "p50_sec": 480.0,+ "p75_sec": 1950.0+ },+ "ltx|i2v|balanced|49.0|M4 Max|any": {+ "n": 43,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|49.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 142.5+ },+ "ltx|i2v|balanced|49.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 48.8+ },+ "ltx|i2v|balanced|65.0|M1 Max|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|721.0|M2 Max|any": {+ "n": 10,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|i2v|balanced|73.0|M1 Max|any": {+ "n": 15,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 210.0+ },+ "ltx|i2v|balanced|73.0|M1 Pro|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|73.0|M2 Max|any": {+ "n": 15,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M2|any": {+ "n": 3,+ "p25_sec": 105.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M3 Max|any": {+ "n": 22,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M3 Pro|any": {+ "n": 4,+ "p25_sec": 165.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|73.0|M3 Ultra|any": {+ "n": 10,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|73.0|M3|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|i2v|balanced|73.0|M4 Max|any": {+ "n": 112,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|73.0|M4 Pro|any": {+ "n": 35,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|73.0|M4|any": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|73.0|M5 Max|any": {+ "n": 9,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|balanced|73.0|M5 Pro|any": {+ "n": 40,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|73.0|M5|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|balanced|81.0|M1 Max|any": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 285.0+ },+ "ltx|i2v|balanced|81.0|M5 Max|any": {+ "n": 17,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|97.0|M3 Ultra|any": {+ "n": 19,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|i2v|balanced|97.0|M4 Pro|any": {+ "n": 16,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|97.0|M5 Max|any": {+ "n": 13,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|97.0|M5 Pro|any": {+ "n": 24,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|draft|121.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high_720p|121.0|M3 Ultra|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high_720p|121.0|M4 Max|any": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high_720p|121.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high_720p|241.0|M2 Max|any": {+ "n": 18,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|113.0|M5 Max|any": {+ "n": 35,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|high|121.0|M1 Max|any": {+ "n": 7,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|121.0|M2 Max|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|121.0|M2 Ultra|any": {+ "n": 13,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|121.0|M3 Max|any": {+ "n": 20,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|121.0|M3 Ultra|any": {+ "n": 13,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|121.0|M4 Max|any": {+ "n": 77,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|121.0|M4 Pro|any": {+ "n": 41,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|121.0|M5 Max|any": {+ "n": 24,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|121.0|M5 Pro|any": {+ "n": 193,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|145.0|M5 Pro|any": {+ "n": 76,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high|169.0|M1 Max|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|high|169.0|M1 Ultra|any": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|169.0|M4 Max|any": {+ "n": 15,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|169.0|M4 Pro|any": {+ "n": 13,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|169.0|M5 Max|any": {+ "n": 9,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|241.0|M1 Max|any": {+ "n": 34,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|241.0|M1 Ultra|any": {+ "n": 20,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|241.0|M2 Max|any": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|241.0|M2 Ultra|any": {+ "n": 98,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|241.0|M3 Max|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|241.0|M3 Ultra|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|241.0|M4 Max|any": {+ "n": 54,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|241.0|M4 Pro|any": {+ "n": 12,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|241.0|M5 Max|any": {+ "n": 31,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|241.0|M5 Pro|any": {+ "n": 7,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|289.0|M2 Ultra|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|33.0|M5 Max|any": {+ "n": 10,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|high|337.0|M1 Ultra|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 1050.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|361.0|M5 Max|any": {+ "n": 20,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|41.0|M5 Pro|any": {+ "n": 8,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|high|49.0|M5 Max|any": {+ "n": 25,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|high|49.0|M5 Pro|any": {+ "n": 27,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|65.0|M5 Pro|any": {+ "n": 18,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|73.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|73.0|M4 Max|any": {+ "n": 17,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|high|73.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|high|73.0|M5 Max|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|73.0|M5 Pro|any": {+ "n": 78,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|high|97.0|M5 Max|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|97.0|M5 Pro|any": {+ "n": 196,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|113.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|121.0|M1 Max|any": {+ "n": 41,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|121.0|M1 Pro|any": {+ "n": 20,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|121.0|M1 Ultra|any": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 75.0,+ "p75_sec": 112.5+ },+ "ltx|i2v|quick|121.0|M2 Max|any": {+ "n": 52,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|121.0|M2|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|121.0|M3 Max|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|121.0|M3 Pro|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|121.0|M3 Ultra|any": {+ "n": 16,+ "p25_sec": 56.2,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|121.0|M4 Max|any": {+ "n": 25,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|121.0|M4 Pro|any": {+ "n": 57,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|121.0|M4|any": {+ "n": 48,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|121.0|M5 Max|any": {+ "n": 22,+ "p25_sec": 30.0,+ "p50_sec": 52.5,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|121.0|M5 Pro|any": {+ "n": 96,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|121.0|M5|any": {+ "n": 26,+ "p25_sec": 240.0,+ "p50_sec": 360.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|129.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|145.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|169.0|M1 Max|any": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|169.0|M2 Max|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|169.0|M4 Max|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|169.0|M4 Pro|any": {+ "n": 15,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|169.0|M4|any": {+ "n": 3,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|quick|169.0|M5 Max|any": {+ "n": 13,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|quick|169.0|M5 Pro|any": {+ "n": 13,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|169.0|M5|any": {+ "n": 3,+ "p25_sec": 210.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|241.0|M1 Max|any": {+ "n": 17,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|241.0|M1 Pro|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|quick|241.0|M1 Ultra|any": {+ "n": 8,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|241.0|M1|any": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 3600.0+ },+ "ltx|i2v|quick|241.0|M2 Max|any": {+ "n": 4,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|241.0|M3 Pro|any": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|241.0|M4 Max|any": {+ "n": 35,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|241.0|M4 Pro|any": {+ "n": 69,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|241.0|M4|any": {+ "n": 21,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|quick|241.0|M5 Max|any": {+ "n": 42,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|241.0|M5 Pro|any": {+ "n": 22,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|241.0|M5|any": {+ "n": 8,+ "p25_sec": 525.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|quick|289.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|313.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|361.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 75.0,+ "p50_sec": 90.0,+ "p75_sec": 105.0+ },+ "ltx|i2v|quick|41.0|M1 Max|any": {+ "n": 7,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|481.0|M1 Max|any": {+ "n": 10,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|481.0|M1|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|quick|481.0|M2 Max|any": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|481.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 525.0+ },+ "ltx|i2v|quick|481.0|M3 Max|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|481.0|M4 Max|any": {+ "n": 46,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|481.0|M4 Pro|any": {+ "n": 36,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|481.0|M4|any": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|quick|481.0|M5 Max|any": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|481.0|M5 Pro|any": {+ "n": 50,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|481.0|M5|any": {+ "n": 25,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|49.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 22.5+ },+ "ltx|i2v|quick|49.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 105.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|49.0|M4|any": {+ "n": 14,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|73.0|M1 Max|any": {+ "n": 14,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|73.0|M1 Pro|any": {+ "n": 3,+ "p25_sec": 450.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|73.0|M1|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|i2v|quick|73.0|M2 Max|any": {+ "n": 8,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 97.5+ },+ "ltx|i2v|quick|73.0|M2|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|73.0|M3 Max|any": {+ "n": 21,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|73.0|M3 Ultra|any": {+ "n": 6,+ "p25_sec": 33.8,+ "p50_sec": 67.5,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|73.0|M3|any": {+ "n": 3,+ "p25_sec": 660.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|quick|73.0|M4 Max|any": {+ "n": 13,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|quick|73.0|M4 Pro|any": {+ "n": 10,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|quick|73.0|M4|any": {+ "n": 68,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|73.0|M5 Max|any": {+ "n": 27,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|quick|73.0|M5 Pro|any": {+ "n": 27,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|73.0|M5|any": {+ "n": 21,+ "p25_sec": 90.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|quick|97.0|M4|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|97.0|M5 Pro|any": {+ "n": 22,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|standard|121.0|M1 Max|any": {+ "n": 213,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|M1 Pro|any": {+ "n": 13,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|121.0|M1 Ultra|any": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|121.0|M1|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 2025.0+ },+ "ltx|i2v|standard|121.0|M2 Max|any": {+ "n": 161,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|M2 Ultra|any": {+ "n": 43,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|121.0|M2|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|i2v|standard|121.0|M3 Max|any": {+ "n": 20,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|121.0|M3 Pro|any": {+ "n": 3,+ "p25_sec": 810.0,+ "p50_sec": 1200.0,+ "p75_sec": 1500.0+ },+ "ltx|i2v|standard|121.0|M3 Ultra|any": {+ "n": 56,+ "p25_sec": 180.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|121.0|M3|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|121.0|M4 Max|any": {+ "n": 139,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|121.0|M4 Pro|any": {+ "n": 195,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|M4|any": {+ "n": 36,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|121.0|M5 Max|any": {+ "n": 108,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|121.0|M5 Pro|any": {+ "n": 147,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|121.0|M5|any": {+ "n": 163,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|137.0|M4 Max|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|145.0|M2 Ultra|any": {+ "n": 52,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|145.0|M4 Max|any": {+ "n": 20,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|145.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|145.0|M5 Max|any": {+ "n": 11,+ "p25_sec": 60.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|i2v|standard|169.0|M1 Max|any": {+ "n": 119,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M1 Pro|any": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M1 Ultra|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|169.0|M2 Max|any": {+ "n": 47,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|169.0|M2 Ultra|any": {+ "n": 102,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|169.0|M3 Pro|any": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M3|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|i2v|standard|169.0|M4 Max|any": {+ "n": 125,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|169.0|M4 Pro|any": {+ "n": 110,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|169.0|M4|any": {+ "n": 36,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|169.0|M5 Max|any": {+ "n": 139,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|169.0|M5 Pro|any": {+ "n": 64,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|169.0|M5|any": {+ "n": 7,+ "p25_sec": 450.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|185.0|M3|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|i2v|standard|193.0|M2 Ultra|any": {+ "n": 36,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|193.0|M4 Max|any": {+ "n": 13,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|193.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|i2v|standard|217.0|M2 Ultra|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M1 Max|any": {+ "n": 209,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|standard|241.0|M1 Pro|any": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M1 Ultra|any": {+ "n": 21,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M1|any": {+ "n": 13,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|i2v|standard|241.0|M2 Max|any": {+ "n": 220,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|standard|241.0|M2 Pro|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M2 Ultra|any": {+ "n": 107,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M2|any": {+ "n": 9,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|241.0|M3 Max|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M3 Pro|any": {+ "n": 19,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M3 Ultra|any": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M3|any": {+ "n": 3,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|241.0|M4 Max|any": {+ "n": 147,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M4 Pro|any": {+ "n": 86,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M4|any": {+ "n": 406,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|241.0|M5 Max|any": {+ "n": 82,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|241.0|M5 Pro|any": {+ "n": 90,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|241.0|M5|any": {+ "n": 156,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|249.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 150.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|265.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 52.5,+ "p50_sec": 60.0,+ "p75_sec": 75.0+ },+ "ltx|i2v|standard|289.0|M2 Ultra|any": {+ "n": 67,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|289.0|M4 Pro|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|337.0|M4 Pro|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|353.0|M5 Max|any": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|361.0|M2 Ultra|any": {+ "n": 8,+ "p25_sec": 825.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|standard|361.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|361.0|M4 Pro|any": {+ "n": 17,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|393.0|M3 Max|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|41.0|M5 Max|any": {+ "n": 25,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|standard|433.0|M5 Pro|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|481.0|M2 Ultra|any": {+ "n": 23,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|481.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|i2v|standard|481.0|M4|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|49.0|M4 Pro|any": {+ "n": 10,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|49.0|M5 Max|any": {+ "n": 31,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|standard|73.0|M1 Max|any": {+ "n": 28,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|73.0|M2 Max|any": {+ "n": 11,+ "p25_sec": 150.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|73.0|M3 Max|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|73.0|M3 Pro|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|73.0|M4 Max|any": {+ "n": 18,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|73.0|M4 Pro|any": {+ "n": 72,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|73.0|M4|any": {+ "n": 6,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|73.0|M5 Max|any": {+ "n": 163,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|73.0|M5 Pro|any": {+ "n": 18,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 82.5+ },+ "ltx|i2v|standard|73.0|M5|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 1110.0+ },+ "ltx|i2v|standard|81.0|M5 Max|any": {+ "n": 25,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|standard|89.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|standard|97.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|97.0|M3 Ultra|any": {+ "n": 5,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|i2v|standard|97.0|M4 Pro|any": {+ "n": 7,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|standard|97.0|M5 Max|any": {+ "n": 88,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|97.0|M5 Pro|any": {+ "n": 10,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|standard|97.0|unknown|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|balanced|121.0|M1 Max|any": {+ "n": 11,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|121.0|M2 Max|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|121.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|balanced|121.0|M4 Max|any": {+ "n": 17,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|121.0|M4 Pro|any": {+ "n": 18,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|121.0|M5 Max|any": {+ "n": 8,+ "p25_sec": 90.0,+ "p50_sec": 105.0,+ "p75_sec": 195.0+ },+ "ltx|keyframe|balanced|121.0|M5 Pro|any": {+ "n": 13,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|balanced|169.0|M2 Max|any": {+ "n": 13,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|169.0|M3 Ultra|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|balanced|169.0|M4 Pro|any": {+ "n": 12,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|169.0|M5 Pro|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|balanced|241.0|M1 Max|any": {+ "n": 20,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|241.0|M2 Max|any": {+ "n": 21,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|keyframe|balanced|241.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|241.0|M4 Max|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|241.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|241.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|balanced|73.0|M1 Max|any": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|73.0|M2 Max|any": {+ "n": 11,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|balanced|73.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|balanced|73.0|M5 Max|any": {+ "n": 13,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|keyframe|balanced|97.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|113.0|M5 Max|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|121.0|M1 Max|any": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 675.0+ },+ "ltx|keyframe|high|121.0|M3 Max|any": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|121.0|M3 Ultra|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|121.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|keyframe|high|121.0|M5 Max|any": {+ "n": 34,+ "p25_sec": 255.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|121.0|M5 Pro|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|129.0|M3 Ultra|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|161.0|M3 Ultra|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|169.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|high|193.0|M3 Ultra|any": {+ "n": 7,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|193.0|M4 Pro|any": {+ "n": 19,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|241.0|M1 Max|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1050.0+ },+ "ltx|keyframe|high|241.0|M3 Ultra|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|241.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|keyframe|high|241.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|361.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|keyframe|high|433.0|M2 Ultra|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|73.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|keyframe|high|73.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|keyframe|high|97.0|M3 Ultra|any": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|quick|121.0|M4 Max|any": {+ "n": 8,+ "p25_sec": 240.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|quick|241.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|standard|121.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 750.0+ },+ "ltx|keyframe|standard|121.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 157.5,+ "p50_sec": 240.0,+ "p75_sec": 330.0+ },+ "ltx|keyframe|standard|121.0|M5 Pro|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|standard|169.0|M4 Max|any": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1500.0,+ "p75_sec": 1800.0+ },+ "ltx|keyframe|standard|193.0|M2 Ultra|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|standard|241.0|M1 Max|any": {+ "n": 5,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "ltx|keyframe|standard|241.0|M2 Ultra|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 390.0+ },+ "ltx|keyframe|standard|241.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|standard|241.0|M5 Max|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 225.0+ },+ "ltx|keyframe|standard|289.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|standard|481.0|M2 Ultra|any": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|standard|49.0|M5 Max|any": {+ "n": 19,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|keyframe|standard|73.0|M5 Max|any": {+ "n": 43,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|standard|97.0|M5 Max|any": {+ "n": 17,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|113.0|M5 Max|any": {+ "n": 7,+ "p25_sec": 75.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|M1 Max|any": {+ "n": 250,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|121.0|M1 Pro|any": {+ "n": 81,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|121.0|M1 Ultra|any": {+ "n": 57,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M1|any": {+ "n": 39,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|121.0|M2 Max|any": {+ "n": 134,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M2 Pro|any": {+ "n": 17,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|121.0|M2 Ultra|any": {+ "n": 29,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|121.0|M2|any": {+ "n": 9,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|121.0|M3 Max|any": {+ "n": 36,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 255.0+ },+ "ltx|t2v|balanced|121.0|M3 Pro|any": {+ "n": 18,+ "p25_sec": 180.0,+ "p50_sec": 330.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|121.0|M3 Ultra|any": {+ "n": 97,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|M3|any": {+ "n": 11,+ "p25_sec": 510.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|121.0|M4 Max|any": {+ "n": 768,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|121.0|M4 Pro|any": {+ "n": 343,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|121.0|M4|any": {+ "n": 64,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|121.0|M5 Max|any": {+ "n": 163,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|M5 Pro|any": {+ "n": 204,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|121.0|M5|any": {+ "n": 63,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|121.0|M6|any": {+ "n": 4,+ "p25_sec": 112.5,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|145.0|M1 Max|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|145.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|145.0|M4 Pro|any": {+ "n": 7,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|t2v|balanced|145.0|M5 Pro|any": {+ "n": 79,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|153.0|M5 Pro|any": {+ "n": 9,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|169.0|M1 Max|any": {+ "n": 27,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|169.0|M2 Max|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|169.0|M3 Pro|any": {+ "n": 10,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|169.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|169.0|M3|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 825.0+ },+ "ltx|t2v|balanced|169.0|M4 Max|any": {+ "n": 39,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|169.0|M4 Pro|any": {+ "n": 26,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|169.0|M4|any": {+ "n": 9,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|169.0|M5 Max|any": {+ "n": 13,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|169.0|M5 Pro|any": {+ "n": 50,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|169.0|M5|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 405.0+ },+ "ltx|t2v|balanced|193.0|M1 Max|any": {+ "n": 6,+ "p25_sec": 210.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|193.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 465.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|217.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|M1 Max|any": {+ "n": 44,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|241.0|M1 Pro|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|241.0|M1 Ultra|any": {+ "n": 117,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|241.0|M1|any": {+ "n": 6,+ "p25_sec": 975.0,+ "p50_sec": 1800.0,+ "p75_sec": 4650.0+ },+ "ltx|t2v|balanced|241.0|M2 Max|any": {+ "n": 77,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|M2 Pro|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 810.0+ },+ "ltx|t2v|balanced|241.0|M2|any": {+ "n": 7,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|balanced|241.0|M3 Max|any": {+ "n": 16,+ "p25_sec": 420.0,+ "p50_sec": 750.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|241.0|M3 Pro|any": {+ "n": 8,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|M3 Ultra|any": {+ "n": 45,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|241.0|M3|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|241.0|M4 Max|any": {+ "n": 261,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|241.0|M4 Pro|any": {+ "n": 176,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|241.0|M4|any": {+ "n": 19,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|balanced|241.0|M5 Max|any": {+ "n": 49,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|241.0|M5 Pro|any": {+ "n": 29,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|241.0|M5|any": {+ "n": 55,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|241.0|M6|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 570.0+ },+ "ltx|t2v|balanced|25.0|M1 Max|any": {+ "n": 14,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|25.0|M4 Pro|any": {+ "n": 12,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|33.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|361.0|M4 Max|any": {+ "n": 8,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|361.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|t2v|balanced|361.0|M5 Pro|any": {+ "n": 10,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|409.0|M1 Ultra|any": {+ "n": 20,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|41.0|M5 Max|any": {+ "n": 10,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|t2v|balanced|481.0|M2 Max|any": {+ "n": 9,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|49.0|M3 Ultra|any": {+ "n": 25,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|49.0|M4 Pro|any": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|49.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 26.2,+ "p50_sec": 37.5,+ "p75_sec": 45.0+ },+ "ltx|t2v|balanced|49.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 56.2,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|65.0|M5 Max|any": {+ "n": 6,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|balanced|73.0|M1 Max|any": {+ "n": 68,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M1 Ultra|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 135.0+ },+ "ltx|t2v|balanced|73.0|M2 Max|any": {+ "n": 45,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M3 Max|any": {+ "n": 10,+ "p25_sec": 97.5,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|73.0|M3 Ultra|any": {+ "n": 14,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|73.0|M4 Max|any": {+ "n": 165,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|73.0|M4 Pro|any": {+ "n": 47,+ "p25_sec": 90.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|balanced|73.0|M4|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|73.0|M5 Max|any": {+ "n": 25,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|balanced|73.0|M5 Pro|any": {+ "n": 12,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|balanced|73.0|M5|any": {+ "n": 12,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|89.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|balanced|97.0|M1 Max|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|97.0|M3 Max|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|t2v|balanced|97.0|M3 Ultra|any": {+ "n": 204,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|97.0|M4 Max|any": {+ "n": 18,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|97.0|M4 Pro|any": {+ "n": 9,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|draft|121.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high_720p|121.0|M3 Max|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high_720p|121.0|M4 Pro|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high_720p|241.0|M1 Ultra|any": {+ "n": 5,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high_720p|241.0|M4 Max|any": {+ "n": 13,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high_720p|73.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 270.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high_720p|73.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high|1.0|M4 Max|any": {+ "n": 14,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|high|113.0|M5 Max|any": {+ "n": 120,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|121.0|M1 Max|any": {+ "n": 58,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|121.0|M1 Ultra|any": {+ "n": 23,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|121.0|M2 Max|any": {+ "n": 13,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|121.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|t2v|high|121.0|M3 Ultra|any": {+ "n": 8,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 330.0+ },+ "ltx|t2v|high|121.0|M4 Max|any": {+ "n": 71,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|121.0|M4 Pro|any": {+ "n": 10,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|121.0|M5 Max|any": {+ "n": 18,+ "p25_sec": 97.5,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|121.0|M5 Pro|any": {+ "n": 11,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|145.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|t2v|high|145.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|high|169.0|M1 Max|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|169.0|M1 Ultra|any": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|169.0|M2 Max|any": {+ "n": 4,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|169.0|M2 Ultra|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|169.0|M4 Pro|any": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 750.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|169.0|M5 Max|any": {+ "n": 14,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|high|241.0|M1 Max|any": {+ "n": 42,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|241.0|M1 Ultra|any": {+ "n": 22,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|241.0|M2 Max|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|241.0|M3 Max|any": {+ "n": 8,+ "p25_sec": 555.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high|241.0|M3 Ultra|any": {+ "n": 6,+ "p25_sec": 255.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|241.0|M4 Max|any": {+ "n": 38,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high|241.0|M4 Pro|any": {+ "n": 9,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high|241.0|M5 Max|any": {+ "n": 17,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|289.0|M2 Max|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|385.0|M1 Max|any": {+ "n": 4,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high|385.0|M1 Ultra|any": {+ "n": 4,+ "p25_sec": 1125.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high|41.0|M5 Max|any": {+ "n": 11,+ "p25_sec": 30.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|high|65.0|M3 Ultra|any": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|65.0|M5 Max|any": {+ "n": 17,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high|73.0|M1 Max|any": {+ "n": 14,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|73.0|M1 Ultra|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|high|73.0|M2 Max|any": {+ "n": 14,+ "p25_sec": 255.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|73.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high|73.0|M3 Ultra|any": {+ "n": 23,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|high|73.0|M4 Max|any": {+ "n": 25,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|73.0|M4 Pro|any": {+ "n": 8,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|high|97.0|M5 Pro|any": {+ "n": 6,+ "p25_sec": 135.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M1 Max|any": {+ "n": 61,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|121.0|M1 Pro|any": {+ "n": 15,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|121.0|M1 Ultra|any": {+ "n": 19,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|121.0|M2 Max|any": {+ "n": 54,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|121.0|M2 Ultra|any": {+ "n": 11,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M3 Max|any": {+ "n": 19,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|121.0|M3 Pro|any": {+ "n": 3,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|121.0|M3 Ultra|any": {+ "n": 80,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|121.0|M3|any": {+ "n": 12,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 975.0+ },+ "ltx|t2v|quick|121.0|M4 Max|any": {+ "n": 47,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M4 Pro|any": {+ "n": 118,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|M4|any": {+ "n": 17,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|121.0|M5 Max|any": {+ "n": 151,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|121.0|M5 Pro|any": {+ "n": 37,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|121.0|M5|any": {+ "n": 51,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|145.0|M4 Pro|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|145.0|M5 Max|any": {+ "n": 5,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|145.0|M5 Pro|any": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|153.0|M4|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|169.0|M1 Max|any": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|169.0|M3 Pro|any": {+ "n": 3,+ "p25_sec": 360.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|169.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|169.0|M4 Pro|any": {+ "n": 8,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|193.0|M4 Pro|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|193.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|201.0|M4 Max|any": {+ "n": 15,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|241.0|M1 Max|any": {+ "n": 32,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|241.0|M1 Pro|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|241.0|M1 Ultra|any": {+ "n": 14,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|241.0|M2 Max|any": {+ "n": 32,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|241.0|M3 Max|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 195.0+ },+ "ltx|t2v|quick|241.0|M3 Ultra|any": {+ "n": 28,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 195.0+ },+ "ltx|t2v|quick|241.0|M4 Max|any": {+ "n": 12,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 255.0+ },+ "ltx|t2v|quick|241.0|M4 Pro|any": {+ "n": 60,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|241.0|M4|any": {+ "n": 46,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|241.0|M5 Max|any": {+ "n": 40,+ "p25_sec": 60.0,+ "p50_sec": 105.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|241.0|M5 Pro|any": {+ "n": 22,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 255.0+ },+ "ltx|t2v|quick|241.0|M5|any": {+ "n": 24,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 465.0+ },+ "ltx|t2v|quick|25.0|M1 Max|any": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|25.0|M1 Ultra|any": {+ "n": 3,+ "p25_sec": 22.5,+ "p50_sec": 30.0,+ "p75_sec": 37.5+ },+ "ltx|t2v|quick|25.0|M3 Ultra|any": {+ "n": 3,+ "p25_sec": 15.0,+ "p50_sec": 30.0,+ "p75_sec": 37.5+ },+ "ltx|t2v|quick|481.0|M1 Max|any": {+ "n": 4,+ "p25_sec": 525.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|t2v|quick|481.0|M1 Pro|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|481.0|M1 Ultra|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 360.0+ },+ "ltx|t2v|quick|481.0|M1|any": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 2100.0+ },+ "ltx|t2v|quick|481.0|M2 Max|any": {+ "n": 7,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|481.0|M3 Max|any": {+ "n": 3,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|481.0|M3 Ultra|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|481.0|M4 Max|any": {+ "n": 5,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|481.0|M4 Pro|any": {+ "n": 28,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|481.0|M5 Max|any": {+ "n": 14,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 225.0+ },+ "ltx|t2v|quick|481.0|M5 Pro|any": {+ "n": 29,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|49.0|M1 Max|any": {+ "n": 11,+ "p25_sec": 75.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|49.0|M2 Max|any": {+ "n": 3,+ "p25_sec": 52.5,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|49.0|M3 Max|any": {+ "n": 3,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 37.5+ },+ "ltx|t2v|quick|49.0|M3 Ultra|any": {+ "n": 20,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|quick|49.0|M4 Max|any": {+ "n": 4,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 48.8+ },+ "ltx|t2v|quick|49.0|M4 Pro|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|49.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 15.0,+ "p50_sec": 22.5,+ "p75_sec": 30.0+ },+ "ltx|t2v|quick|49.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|quick|73.0|M1 Max|any": {+ "n": 22,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|73.0|M1 Pro|any": {+ "n": 11,+ "p25_sec": 270.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|73.0|M1 Ultra|any": {+ "n": 13,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M2 Max|any": {+ "n": 22,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 101.2,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|73.0|M3 Max|any": {+ "n": 11,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|73.0|M3 Ultra|any": {+ "n": 38,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|73.0|M4 Max|any": {+ "n": 20,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|73.0|M4 Pro|any": {+ "n": 60,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|73.0|M4|any": {+ "n": 13,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|quick|73.0|M5 Max|any": {+ "n": 18,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|73.0|M5 Pro|any": {+ "n": 14,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|73.0|M5|any": {+ "n": 40,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 135.0+ },+ "ltx|t2v|quick|97.0|M1 Max|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|97.0|M3 Max|any": {+ "n": 6,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|quick|97.0|M3 Ultra|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|97.0|M4 Max|any": {+ "n": 6,+ "p25_sec": 97.5,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|97.0|M4 Pro|any": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|97.0|M4|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|97.0|M5 Pro|any": {+ "n": 9,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|quick|97.0|M5|any": {+ "n": 3,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|standard|121.0|M1 Max|any": {+ "n": 85,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|121.0|M1 Pro|any": {+ "n": 19,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|121.0|M1 Ultra|any": {+ "n": 4,+ "p25_sec": 210.0,+ "p50_sec": 330.0,+ "p75_sec": 615.0+ },+ "ltx|t2v|standard|121.0|M2 Max|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|121.0|M2 Pro|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|t2v|standard|121.0|M2 Ultra|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|121.0|M3 Max|any": {+ "n": 12,+ "p25_sec": 285.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|121.0|M3 Ultra|any": {+ "n": 51,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|121.0|M3|any": {+ "n": 7,+ "p25_sec": 750.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|standard|121.0|M4 Max|any": {+ "n": 112,+ "p25_sec": 180.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|121.0|M4 Pro|any": {+ "n": 58,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|121.0|M4|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|121.0|M5 Max|any": {+ "n": 83,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|121.0|M5 Pro|any": {+ "n": 22,+ "p25_sec": 60.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|121.0|M5|any": {+ "n": 180,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|145.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 150.0,+ "p50_sec": 180.0,+ "p75_sec": 210.0+ },+ "ltx|t2v|standard|145.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|169.0|M1 Max|any": {+ "n": 4,+ "p25_sec": 225.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|169.0|M2 Ultra|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|169.0|M4 Pro|any": {+ "n": 17,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|169.0|M4|any": {+ "n": 10,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|169.0|M5 Max|any": {+ "n": 103,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|169.0|M5 Pro|any": {+ "n": 12,+ "p25_sec": 202.5,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|217.0|M4 Max|any": {+ "n": 30,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M1 Max|any": {+ "n": 59,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|standard|241.0|M1 Pro|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 675.0+ },+ "ltx|t2v|standard|241.0|M1 Ultra|any": {+ "n": 180,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M1|any": {+ "n": 23,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|standard|241.0|M2 Max|any": {+ "n": 39,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M2 Pro|any": {+ "n": 6,+ "p25_sec": 330.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|241.0|M2|any": {+ "n": 4,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|standard|241.0|M3 Ultra|any": {+ "n": 10,+ "p25_sec": 330.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M4 Max|any": {+ "n": 159,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|241.0|M4 Pro|any": {+ "n": 74,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|M4|any": {+ "n": 27,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|standard|241.0|M5 Max|any": {+ "n": 26,+ "p25_sec": 67.5,+ "p50_sec": 240.0,+ "p75_sec": 390.0+ },+ "ltx|t2v|standard|241.0|M5 Pro|any": {+ "n": 29,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|241.0|M5|any": {+ "n": 58,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|25.0|M1 Ultra|any": {+ "n": 10,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|standard|25.0|M5 Max|any": {+ "n": 8,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|t2v|standard|313.0|M4|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|361.0|M5|any": {+ "n": 292,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|481.0|M5 Max|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|481.0|M5 Pro|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|49.0|M4 Max|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|standard|73.0|M1 Max|any": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|73.0|M3 Ultra|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|73.0|M4 Max|any": {+ "n": 20,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|73.0|M4 Pro|any": {+ "n": 8,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|73.0|M4|any": {+ "n": 23,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|73.0|M5 Max|any": {+ "n": 4,+ "p25_sec": 60.0,+ "p50_sec": 75.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|standard|73.0|M5|any": {+ "n": 9,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|97.0|M1 Max|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 150.0+ },+ "ltx|t2v|standard|97.0|M4 Max|any": {+ "n": 4,+ "p25_sec": 210.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|97.0|M4 Pro|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|97.0|M5 Pro|any": {+ "n": 3,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ }+ },+ "dims": [+ "engine",+ "mode",+ "tier",+ "frames",+ "chip_family",+ "speed"+ ]+ },+ "model": {+ "cells": {+ "h3|i2v|draft_10s_dense|243.0|best": {+ "n": 12,+ "p25_sec": 675.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|draft_10s_dense|243.0|fast": {+ "n": 24,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|best": {+ "n": 50,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_10s|243.0|fast": {+ "n": 113,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_15s|362.0|best": {+ "n": 16,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|draft_15s|362.0|fast": {+ "n": 69,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "h3|i2v|draft_3s|73.0|best": {+ "n": 106,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "h3|i2v|draft_3s|73.0|fast": {+ "n": 71,+ "p25_sec": 105.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|draft_5s|124.0|best": {+ "n": 86,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|draft_5s|124.0|fast": {+ "n": 118,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "h3|i2v|high_10s_dense|243.0|best": {+ "n": 15,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|high_10s_dense|243.0|fast": {+ "n": 16,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|best": {+ "n": 179,+ "p25_sec": 1800.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|high_10s|243.0|fast": {+ "n": 167,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_15s|362.0|best": {+ "n": 97,+ "p25_sec": 3600.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|high_15s|362.0|fast": {+ "n": 607,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_3s|73.0|best": {+ "n": 269,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "h3|i2v|high_3s|73.0|fast": {+ "n": 108,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "h3|i2v|high_5s|124.0|best": {+ "n": 619,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|high_5s|124.0|fast": {+ "n": 507,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "h3|i2v|native_10s_dense|243.0|fast": {+ "n": 3,+ "p25_sec": 4500.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_10s|243.0|best": {+ "n": 25,+ "p25_sec": 4500.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_10s|243.0|fast": {+ "n": 33,+ "p25_sec": 1800.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|i2v|native_15s|362.0|best": {+ "n": 20,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_15s|362.0|fast": {+ "n": 10,+ "p25_sec": 2700.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|native_3s|73.0|best": {+ "n": 9,+ "p25_sec": 1200.0,+ "p50_sec": 1500.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|native_3s|73.0|fast": {+ "n": 28,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|native_5s|124.0|best": {+ "n": 46,+ "p25_sec": 2400.0,+ "p50_sec": 3600.0,+ "p75_sec": 5400.0+ },+ "h3|i2v|native_5s|124.0|fast": {+ "n": 38,+ "p25_sec": 600.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s_dense|243.0|best": {+ "n": 30,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|standard_10s_dense|243.0|fast": {+ "n": 45,+ "p25_sec": 600.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|best": {+ "n": 149,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|i2v|standard_10s|243.0|fast": {+ "n": 230,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|i2v|standard_15s|362.0|best": {+ "n": 83,+ "p25_sec": 900.0,+ "p50_sec": 2400.0,+ "p75_sec": 3600.0+ },+ "h3|i2v|standard_15s|362.0|fast": {+ "n": 77,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1800.0+ },+ "h3|i2v|standard_3s|73.0|best": {+ "n": 49,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 420.0+ },+ "h3|i2v|standard_3s|73.0|fast": {+ "n": 46,+ "p25_sec": 90.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "h3|i2v|standard_5s|124.0|best": {+ "n": 188,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "h3|i2v|standard_5s|124.0|fast": {+ "n": 382,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|keyframe|high_3s|73.0|fast": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "h3|keyframe|high_5s|124.0|fast": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "h3|t2v|draft_10s_dense|243.0|best": {+ "n": 125,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s_dense|243.0|fast": {+ "n": 12,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_10s|243.0|best": {+ "n": 82,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_10s|243.0|fast": {+ "n": 50,+ "p25_sec": 240.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_15s|362.0|best": {+ "n": 20,+ "p25_sec": 750.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|draft_15s|362.0|fast": {+ "n": 54,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|draft_3s|73.0|best": {+ "n": 745,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "h3|t2v|draft_3s|73.0|fast": {+ "n": 185,+ "p25_sec": 60.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "h3|t2v|draft_5s|124.0|best": {+ "n": 497,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "h3|t2v|draft_5s|124.0|fast": {+ "n": 211,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "h3|t2v|high_10s_dense|243.0|best": {+ "n": 78,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_10s_dense|243.0|fast": {+ "n": 12,+ "p25_sec": 1050.0,+ "p50_sec": 1500.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|high_10s|243.0|best": {+ "n": 29,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|high_10s|243.0|fast": {+ "n": 25,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|high_15s|362.0|best": {+ "n": 57,+ "p25_sec": 3600.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|high_15s|362.0|fast": {+ "n": 25,+ "p25_sec": 1200.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|high_3s|73.0|best": {+ "n": 32,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|t2v|high_3s|73.0|fast": {+ "n": 83,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "h3|t2v|high_5s|124.0|best": {+ "n": 90,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1350.0+ },+ "h3|t2v|high_5s|124.0|fast": {+ "n": 93,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "h3|t2v|native_10s_dense|243.0|best": {+ "n": 13,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_10s|243.0|best": {+ "n": 8,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_10s|243.0|fast": {+ "n": 11,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|native_15s|362.0|best": {+ "n": 10,+ "p25_sec": 5400.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "h3|t2v|native_15s|362.0|fast": {+ "n": 4,+ "p25_sec": 3150.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|native_3s|73.0|best": {+ "n": 12,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|native_3s|73.0|fast": {+ "n": 13,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "h3|t2v|native_5s|124.0|best": {+ "n": 16,+ "p25_sec": 2400.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|native_5s|124.0|fast": {+ "n": 18,+ "p25_sec": 900.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "h3|t2v|standard_10s_dense|243.0|best": {+ "n": 60,+ "p25_sec": 3600.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_10s_dense|243.0|fast": {+ "n": 16,+ "p25_sec": 390.0,+ "p50_sec": 510.0,+ "p75_sec": 675.0+ },+ "h3|t2v|standard_10s|243.0|best": {+ "n": 74,+ "p25_sec": 900.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "h3|t2v|standard_10s|243.0|fast": {+ "n": 60,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 675.0+ },+ "h3|t2v|standard_15s|362.0|best": {+ "n": 40,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 3600.0+ },+ "h3|t2v|standard_15s|362.0|fast": {+ "n": 52,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "h3|t2v|standard_3s|73.0|best": {+ "n": 58,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 555.0+ },+ "h3|t2v|standard_3s|73.0|fast": {+ "n": 97,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 240.0+ },+ "h3|t2v|standard_5s|124.0|best": {+ "n": 144,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "h3|t2v|standard_5s|124.0|fast": {+ "n": 133,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx23|t2v|high|121.0|any": {+ "n": 4,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|a2v|balanced|105.0|any": {+ "n": 8,+ "p25_sec": 247.5,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|113.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 255.0,+ "p75_sec": 765.0+ },+ "ltx|a2v|balanced|121.0|any": {+ "n": 82,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|129.0|any": {+ "n": 8,+ "p25_sec": 112.5,+ "p50_sec": 270.0,+ "p75_sec": 465.0+ },+ "ltx|a2v|balanced|137.0|any": {+ "n": 15,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 210.0+ },+ "ltx|a2v|balanced|145.0|any": {+ "n": 24,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|153.0|any": {+ "n": 3,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|balanced|161.0|any": {+ "n": 6,+ "p25_sec": 195.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|169.0|any": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|177.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|193.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|balanced|209.0|any": {+ "n": 3,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|balanced|217.0|any": {+ "n": 10,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 825.0+ },+ "ltx|a2v|balanced|241.0|any": {+ "n": 7,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|balanced|41.0|any": {+ "n": 4,+ "p25_sec": 97.5,+ "p50_sec": 210.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|49.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|57.0|any": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|65.0|any": {+ "n": 7,+ "p25_sec": 52.5,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|73.0|any": {+ "n": 61,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|balanced|81.0|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 330.0+ },+ "ltx|a2v|balanced|89.0|any": {+ "n": 12,+ "p25_sec": 82.5,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|balanced|97.0|any": {+ "n": 23,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|105.0|any": {+ "n": 10,+ "p25_sec": 60.0,+ "p50_sec": 330.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|113.0|any": {+ "n": 6,+ "p25_sec": 195.0,+ "p50_sec": 270.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|121.0|any": {+ "n": 54,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|129.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|a2v|high|137.0|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|145.0|any": {+ "n": 19,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|a2v|high|153.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|a2v|high|161.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 270.0,+ "p75_sec": 1215.0+ },+ "ltx|a2v|high|169.0|any": {+ "n": 171,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|185.0|any": {+ "n": 5,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|a2v|high|193.0|any": {+ "n": 22,+ "p25_sec": 360.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|217.0|any": {+ "n": 26,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|241.0|any": {+ "n": 81,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|249.0|any": {+ "n": 3,+ "p25_sec": 390.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|high|265.0|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 825.0+ },+ "ltx|a2v|high|289.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 660.0+ },+ "ltx|a2v|high|361.0|any": {+ "n": 10,+ "p25_sec": 810.0,+ "p50_sec": 1200.0,+ "p75_sec": 2700.0+ },+ "ltx|a2v|high|385.0|any": {+ "n": 42,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|409.0|any": {+ "n": 6,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|high|433.0|any": {+ "n": 108,+ "p25_sec": 1200.0,+ "p50_sec": 1500.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|481.0|any": {+ "n": 43,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|high|57.0|any": {+ "n": 17,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|a2v|high|601.0|any": {+ "n": 8,+ "p25_sec": 2250.0,+ "p50_sec": 2400.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|high|65.0|any": {+ "n": 7,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|a2v|high|713.0|any": {+ "n": 4,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|721.0|any": {+ "n": 9,+ "p25_sec": 2400.0,+ "p50_sec": 3900.0,+ "p75_sec": 5400.0+ },+ "ltx|a2v|high|73.0|any": {+ "n": 12,+ "p25_sec": 240.0,+ "p50_sec": 600.0,+ "p75_sec": 1050.0+ },+ "ltx|a2v|high|81.0|any": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|high|89.0|any": {+ "n": 6,+ "p25_sec": 375.0,+ "p50_sec": 1200.0,+ "p75_sec": 2250.0+ },+ "ltx|a2v|high|97.0|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 510.0,+ "p75_sec": 825.0+ },+ "ltx|a2v|quick|241.0|any": {+ "n": 8,+ "p25_sec": 495.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|105.0|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|121.0|any": {+ "n": 6,+ "p25_sec": 135.0,+ "p50_sec": 180.0,+ "p75_sec": 495.0+ },+ "ltx|a2v|standard|129.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|137.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|145.0|any": {+ "n": 16,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|standard|153.0|any": {+ "n": 5,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|a2v|standard|161.0|any": {+ "n": 8,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|a2v|standard|169.0|any": {+ "n": 8,+ "p25_sec": 900.0,+ "p50_sec": 1050.0,+ "p75_sec": 1800.0+ },+ "ltx|a2v|standard|177.0|any": {+ "n": 6,+ "p25_sec": 975.0,+ "p50_sec": 1800.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|standard|193.0|any": {+ "n": 11,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 2400.0+ },+ "ltx|a2v|standard|241.0|any": {+ "n": 55,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|a2v|standard|73.0|any": {+ "n": 36,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 195.0+ },+ "ltx|a2v|standard|97.0|any": {+ "n": 28,+ "p25_sec": 555.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|extend|balanced|121.0|any": {+ "n": 40,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1950.0+ },+ "ltx|extend|balanced|241.0|any": {+ "n": 12,+ "p25_sec": 1800.0,+ "p50_sec": 2400.0,+ "p75_sec": 5400.0+ },+ "ltx|extend|high|121.0|any": {+ "n": 4,+ "p25_sec": 825.0,+ "p50_sec": 1050.0,+ "p75_sec": 1500.0+ },+ "ltx|extend|high|241.0|any": {+ "n": 9,+ "p25_sec": 1800.0,+ "p50_sec": 3600.0,+ "p75_sec": 3600.0+ },+ "ltx|extend|quick|121.0|any": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 3600.0+ },+ "ltx|extend|standard|241.0|any": {+ "n": 5,+ "p25_sec": 3600.0,+ "p50_sec": 5400.0,+ "p75_sec": 5400.0+ },+ "ltx|i2v|balanced|105.0|any": {+ "n": 5,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|113.0|any": {+ "n": 44,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|balanced|121.0|any": {+ "n": 2832,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|137.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|145.0|any": {+ "n": 254,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|161.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|169.0|any": {+ "n": 624,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|177.0|any": {+ "n": 3,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|185.0|any": {+ "n": 7,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|193.0|any": {+ "n": 193,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|225.0|any": {+ "n": 3,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|241.0|any": {+ "n": 2820,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|25.0|any": {+ "n": 6,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 56.2+ },+ "ltx|i2v|balanced|289.0|any": {+ "n": 26,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|361.0|any": {+ "n": 140,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|balanced|433.0|any": {+ "n": 18,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|balanced|481.0|any": {+ "n": 174,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|balanced|49.0|any": {+ "n": 77,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|balanced|65.0|any": {+ "n": 6,+ "p25_sec": 67.5,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|721.0|any": {+ "n": 10,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|i2v|balanced|73.0|any": {+ "n": 307,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|81.0|any": {+ "n": 25,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|balanced|97.0|any": {+ "n": 89,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 285.0+ },+ "ltx|i2v|draft|121.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 135.0+ },+ "ltx|i2v|high_720p|121.0|any": {+ "n": 15,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high_720p|241.0|any": {+ "n": 22,+ "p25_sec": 1200.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|113.0|any": {+ "n": 35,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|high|121.0|any": {+ "n": 436,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 330.0+ },+ "ltx|i2v|high|145.0|any": {+ "n": 77,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|high|169.0|any": {+ "n": 61,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|193.0|any": {+ "n": 6,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|241.0|any": {+ "n": 301,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|i2v|high|289.0|any": {+ "n": 4,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 1800.0+ },+ "ltx|i2v|high|33.0|any": {+ "n": 10,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|high|337.0|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|high|361.0|any": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|high|41.0|any": {+ "n": 10,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|high|49.0|any": {+ "n": 53,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|high|65.0|any": {+ "n": 20,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|high|73.0|any": {+ "n": 119,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|high|97.0|any": {+ "n": 203,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|105.0|any": {+ "n": 3,+ "p25_sec": 270.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|113.0|any": {+ "n": 6,+ "p25_sec": 135.0,+ "p50_sec": 210.0,+ "p75_sec": 285.0+ },+ "ltx|i2v|quick|121.0|any": {+ "n": 490,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|129.0|any": {+ "n": 6,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 195.0+ },+ "ltx|i2v|quick|145.0|any": {+ "n": 4,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|169.0|any": {+ "n": 76,+ "p25_sec": 105.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|i2v|quick|241.0|any": {+ "n": 279,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|25.0|any": {+ "n": 4,+ "p25_sec": 26.2,+ "p50_sec": 30.0,+ "p75_sec": 172.5+ },+ "ltx|i2v|quick|289.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|313.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|361.0|any": {+ "n": 5,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|41.0|any": {+ "n": 8,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|quick|481.0|any": {+ "n": 215,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|quick|49.0|any": {+ "n": 25,+ "p25_sec": 90.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|quick|73.0|any": {+ "n": 271,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|quick|97.0|any": {+ "n": 40,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|121.0|any": {+ "n": 1369,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|137.0|any": {+ "n": 4,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|i2v|standard|145.0|any": {+ "n": 97,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|169.0|any": {+ "n": 788,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|185.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|i2v|standard|193.0|any": {+ "n": 64,+ "p25_sec": 225.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|217.0|any": {+ "n": 5,+ "p25_sec": 345.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|233.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 690.0+ },+ "ltx|i2v|standard|241.0|any": {+ "n": 1682,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|249.0|any": {+ "n": 5,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|265.0|any": {+ "n": 4,+ "p25_sec": 56.2,+ "p50_sec": 75.0,+ "p75_sec": 172.5+ },+ "ltx|i2v|standard|289.0|any": {+ "n": 75,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|i2v|standard|313.0|any": {+ "n": 7,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 510.0+ },+ "ltx|i2v|standard|337.0|any": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|i2v|standard|353.0|any": {+ "n": 5,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|361.0|any": {+ "n": 45,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 675.0+ },+ "ltx|i2v|standard|393.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|i2v|standard|41.0|any": {+ "n": 25,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|i2v|standard|433.0|any": {+ "n": 6,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|481.0|any": {+ "n": 37,+ "p25_sec": 600.0,+ "p50_sec": 1200.0,+ "p75_sec": 1200.0+ },+ "ltx|i2v|standard|49.0|any": {+ "n": 45,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|i2v|standard|73.0|any": {+ "n": 343,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|i2v|standard|81.0|any": {+ "n": 25,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|i2v|standard|89.0|any": {+ "n": 5,+ "p25_sec": 60.0,+ "p50_sec": 60.0,+ "p75_sec": 60.0+ },+ "ltx|i2v|standard|97.0|any": {+ "n": 119,+ "p25_sec": 90.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|keyframe|balanced|121.0|any": {+ "n": 111,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|169.0|any": {+ "n": 35,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|balanced|241.0|any": {+ "n": 79,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|keyframe|balanced|49.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|keyframe|balanced|73.0|any": {+ "n": 36,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|balanced|97.0|any": {+ "n": 7,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|113.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|121.0|any": {+ "n": 71,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|129.0|any": {+ "n": 10,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|high|145.0|any": {+ "n": 3,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|high|161.0|any": {+ "n": 11,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|high|169.0|any": {+ "n": 14,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|193.0|any": {+ "n": 27,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|241.0|any": {+ "n": 21,+ "p25_sec": 420.0,+ "p50_sec": 600.0,+ "p75_sec": 1050.0+ },+ "ltx|keyframe|high|361.0|any": {+ "n": 3,+ "p25_sec": 1500.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|keyframe|high|433.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|high|49.0|any": {+ "n": 10,+ "p25_sec": 180.0,+ "p50_sec": 210.0,+ "p75_sec": 285.0+ },+ "ltx|keyframe|high|73.0|any": {+ "n": 9,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|high|97.0|any": {+ "n": 16,+ "p25_sec": 180.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|quick|121.0|any": {+ "n": 13,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|quick|169.0|any": {+ "n": 6,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 555.0+ },+ "ltx|keyframe|quick|241.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|quick|73.0|any": {+ "n": 4,+ "p25_sec": 450.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|standard|121.0|any": {+ "n": 18,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|standard|169.0|any": {+ "n": 11,+ "p25_sec": 675.0,+ "p50_sec": 1050.0,+ "p75_sec": 1650.0+ },+ "ltx|keyframe|standard|193.0|any": {+ "n": 9,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|keyframe|standard|241.0|any": {+ "n": 22,+ "p25_sec": 300.0,+ "p50_sec": 420.0,+ "p75_sec": 900.0+ },+ "ltx|keyframe|standard|289.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 420.0,+ "p75_sec": 420.0+ },+ "ltx|keyframe|standard|481.0|any": {+ "n": 14,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|keyframe|standard|49.0|any": {+ "n": 19,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|keyframe|standard|73.0|any": {+ "n": 46,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|keyframe|standard|97.0|any": {+ "n": 18,+ "p25_sec": 195.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|113.0|any": {+ "n": 7,+ "p25_sec": 75.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|121.0|any": {+ "n": 2590,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|balanced|145.0|any": {+ "n": 99,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|153.0|any": {+ "n": 9,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|169.0|any": {+ "n": 211,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|193.0|any": {+ "n": 14,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|217.0|any": {+ "n": 6,+ "p25_sec": 300.0,+ "p50_sec": 360.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|balanced|241.0|any": {+ "n": 979,+ "p25_sec": 180.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|25.0|any": {+ "n": 28,+ "p25_sec": 60.0,+ "p50_sec": 75.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|33.0|any": {+ "n": 4,+ "p25_sec": 26.2,+ "p50_sec": 30.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|balanced|361.0|any": {+ "n": 26,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|balanced|409.0|any": {+ "n": 20,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|balanced|41.0|any": {+ "n": 10,+ "p25_sec": 15.0,+ "p50_sec": 15.0,+ "p75_sec": 15.0+ },+ "ltx|t2v|balanced|481.0|any": {+ "n": 24,+ "p25_sec": 300.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|balanced|49.0|any": {+ "n": 44,+ "p25_sec": 45.0,+ "p50_sec": 60.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|balanced|65.0|any": {+ "n": 10,+ "p25_sec": 30.0,+ "p50_sec": 37.5,+ "p75_sec": 78.8+ },+ "ltx|t2v|balanced|73.0|any": {+ "n": 431,+ "p25_sec": 90.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|balanced|89.0|any": {+ "n": 3,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|balanced|97.0|any": {+ "n": 241,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|draft|121.0|any": {+ "n": 6,+ "p25_sec": 120.0,+ "p50_sec": 120.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|high_720p|121.0|any": {+ "n": 14,+ "p25_sec": 510.0,+ "p50_sec": 600.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high_720p|169.0|any": {+ "n": 3,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 750.0+ },+ "ltx|t2v|high_720p|241.0|any": {+ "n": 23,+ "p25_sec": 1200.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high_720p|73.0|any": {+ "n": 7,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|1.0|any": {+ "n": 16,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 30.0+ },+ "ltx|t2v|high|113.0|any": {+ "n": 120,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|121.0|any": {+ "n": 295,+ "p25_sec": 240.0,+ "p50_sec": 420.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|145.0|any": {+ "n": 11,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|high|169.0|any": {+ "n": 52,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|high|241.0|any": {+ "n": 184,+ "p25_sec": 600.0,+ "p50_sec": 900.0,+ "p75_sec": 1200.0+ },+ "ltx|t2v|high|289.0|any": {+ "n": 5,+ "p25_sec": 900.0,+ "p50_sec": 900.0,+ "p75_sec": 900.0+ },+ "ltx|t2v|high|361.0|any": {+ "n": 4,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 450.0+ },+ "ltx|t2v|high|385.0|any": {+ "n": 8,+ "p25_sec": 1200.0,+ "p50_sec": 1500.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high|41.0|any": {+ "n": 11,+ "p25_sec": 30.0,+ "p50_sec": 45.0,+ "p75_sec": 45.0+ },+ "ltx|t2v|high|481.0|any": {+ "n": 3,+ "p25_sec": 1800.0,+ "p50_sec": 1800.0,+ "p75_sec": 1800.0+ },+ "ltx|t2v|high|49.0|any": {+ "n": 7,+ "p25_sec": 30.0,+ "p50_sec": 90.0,+ "p75_sec": 90.0+ },+ "ltx|t2v|high|65.0|any": {+ "n": 27,+ "p25_sec": 105.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|high|73.0|any": {+ "n": 100,+ "p25_sec": 135.0,+ "p50_sec": 240.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|high|97.0|any": {+ "n": 8,+ "p25_sec": 165.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|121.0|any": {+ "n": 884,+ "p25_sec": 60.0,+ "p50_sec": 120.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|145.0|any": {+ "n": 33,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|153.0|any": {+ "n": 12,+ "p25_sec": 300.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|169.0|any": {+ "n": 44,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|quick|193.0|any": {+ "n": 13,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 270.0+ },+ "ltx|t2v|quick|201.0|any": {+ "n": 15,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|quick|241.0|any": {+ "n": 373,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|quick|25.0|any": {+ "n": 19,+ "p25_sec": 15.0,+ "p50_sec": 45.0,+ "p75_sec": 60.0+ },+ "ltx|t2v|quick|289.0|any": {+ "n": 4,+ "p25_sec": 90.0,+ "p50_sec": 105.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|41.0|any": {+ "n": 3,+ "p25_sec": 7.5,+ "p50_sec": 15.0,+ "p75_sec": 22.5+ },+ "ltx|t2v|quick|481.0|any": {+ "n": 122,+ "p25_sec": 240.0,+ "p50_sec": 300.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|quick|49.0|any": {+ "n": 70,+ "p25_sec": 30.0,+ "p50_sec": 30.0,+ "p75_sec": 82.5+ },+ "ltx|t2v|quick|73.0|any": {+ "n": 365,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|quick|97.0|any": {+ "n": 49,+ "p25_sec": 60.0,+ "p50_sec": 90.0,+ "p75_sec": 120.0+ },+ "ltx|t2v|standard|121.0|any": {+ "n": 706,+ "p25_sec": 120.0,+ "p50_sec": 240.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|145.0|any": {+ "n": 8,+ "p25_sec": 210.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|169.0|any": {+ "n": 161,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 300.0+ },+ "ltx|t2v|standard|217.0|any": {+ "n": 31,+ "p25_sec": 600.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|241.0|any": {+ "n": 756,+ "p25_sec": 300.0,+ "p50_sec": 600.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|25.0|any": {+ "n": 18,+ "p25_sec": 15.0,+ "p50_sec": 37.5,+ "p75_sec": 45.0+ },+ "ltx|t2v|standard|289.0|any": {+ "n": 3,+ "p25_sec": 180.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|313.0|any": {+ "n": 4,+ "p25_sec": 420.0,+ "p50_sec": 510.0,+ "p75_sec": 600.0+ },+ "ltx|t2v|standard|361.0|any": {+ "n": 296,+ "p25_sec": 240.0,+ "p50_sec": 240.0,+ "p75_sec": 240.0+ },+ "ltx|t2v|standard|481.0|any": {+ "n": 14,+ "p25_sec": 120.0,+ "p50_sec": 300.0,+ "p75_sec": 420.0+ },+ "ltx|t2v|standard|49.0|any": {+ "n": 6,+ "p25_sec": 45.0,+ "p50_sec": 45.0,+ "p75_sec": 78.8+ },+ "ltx|t2v|standard|73.0|any": {+ "n": 83,+ "p25_sec": 120.0,+ "p50_sec": 180.0,+ "p75_sec": 180.0+ },+ "ltx|t2v|standard|97.0|any": {+ "n": 18,+ "p25_sec": 97.5,+ "p50_sec": 120.0,+ "p75_sec": 165.0+ }+ },+ "dims": [+ "engine",+ "mode",+ "tier",+ "frames",+ "speed"+ ]+ }+ },+ "min_n_to_ship": 3,+ "owner_excluded": true,+ "priced_modes": [+ "t2v",+ "i2v",+ "a2v",+ "extend",+ "keyframe"+ ],+ "schema": "fleet_timings/1",+ "total_events_counted": 97152,+ "wall_sec": "bucket_lower_edge",+ "window_days": 75+}diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.mdindex 9416939..73a8cbc 100644--- a/docs/ANALYTICS.md+++ b/docs/ANALYTICS.md@@ -283,7 +283,7 @@ The surfaces render events cannot see. One event per action, no free text.| prop | type | example | why ||---|---|---|---|-| `feature` | string | `"storyboard_plan"` | **Closed vocabulary**: `storyboard_plan`, `storyboard_export`, `editor_open`, `editor_export`, `civitai_download`, `sample_character`, `train_start`, `enhance_prompt`. Unknown names are dropped locally, never sent |+| `feature` | string | `"storyboard_plan"` | **Closed vocabulary**: `storyboard_plan`, `storyboard_export`, `editor_open`, `editor_export`, `civitai_download`, `sample_character`, `train_start`, `enhance_prompt`, `train_refused`. Unknown names are dropped locally, never sent. `train_start` fires only past `/train/start`'s RAM refusal (SYS-41) — a refused click counts as `train_refused` with `detail: "ram"` instead || `detail` | string | `"nle"` | Optional, lowercase `[a-z0-9_.-]` only, ≤32 chars — a sub-choice within the feature || `version` | string | `"4.9.7"` | As on `app_boot` |@@ -324,6 +324,7 @@ event. This is not a heartbeat and the panel still has none.| `outcome` | string | `"failed"` | **Closed vocabulary**: `started`, `ok`, `failed`, `skipped` || `error_class` | string | `"venv_broken"` | Only on `failed`, and only from the same closed taxonomy `render_failed` uses || `version` | string | `"4.16.0"` | The build that reported it |+| `ram_gb` | int | `16` | SYS-16: lets `first_queue` (this event) be sliced the same way `render_completed`'s `first_render` already is — the reviewer's finding was that activation is LOWEST on the machines that struggle most (36 GB 53%, 8 GB 57%, 16 GB 63%), and answering "first_queue vs first_render, per tier" needed this on both events, not a join against `app_boot` by install_id |**What this event deliberately does not carry**, and why: no path, no filename, no URL, no host, no byte count, and — unlike `render_failed` — **no@@ -571,6 +572,7 @@ Env override: `PHOSPHENE_ANALYTICS_QUERY_KEY`.| `PHOSPHENE_ANALYTICS_API_HOST` | `https://us.posthog.com` | Query API host for the fleet view || `PHOSPHENE_ANALYTICS_PROJECT` | `@current` | PostHog project id used in the query URL || `PHOSPHENE_ANALYTICS_DISABLED` | *(unset)* | `1` disables everything, overriding the setting |+| `PHOSPHENE_TEST_RIG` | *(unset)* | `1` sends events as normal but tags every one with `test_rig: true` (SYS-41). For the owner's own dev machine, a release-gate run, or a clean-room test install — anything that sends REAL telemetry on purpose (unlike an agent review worktree, which sets `PHOSPHENE_ANALYTICS_DISABLED=1` and sends nothing) but is not a real user. A fleet query excludes these with `WHERE NOT properties.test_rig`, instead of a hand-derived "which rows are probably the owner" heuristic. |---diff --git a/docs/API.md b/docs/API.mdindex 8900aff..1ee3e93 100644--- a/docs/API.md+++ b/docs/API.md@@ -114,7 +114,11 @@ Returns `{"ok": true}`.### `POST /queue/clear`-Empty the queue. Returns `{"ok": true, "cleared": <count>}`.+Empty the queue. Returns `{"cleared": <count>, "ids": [...], "undo_token": "<hex>"|null}`.+The token undoes THIS clear once, for 60 s (`POST /queue/restore` with+`{"token": "<hex>"}` puts back exactly the removed jobs, original ids included,+ahead of anything queued since). A later clear supersedes it; an expired or+spent token answers `410`.### `POST /queue/pause`, `POST /queue/resume`@@ -122,7 +126,10 @@ Pause/resume the queue dispatcher (does not affect a job already running).### `POST /stop`-Request the running job to stop. Returns `{"ok": true}`.+Request the running job to stop. Returns `{"ok": true}`. Optional `?id=<job id>`+(what the panel sends): stop only if that job is still the one running —+otherwise `409 {"stale": true}` and nothing is stopped. `/stop/after_part`+takes the same `id`.### `POST /queue/batch`diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.mdindex fd672d6..c3eecca 100644--- a/docs/H3_ENGINE.md+++ b/docs/H3_ENGINE.md@@ -120,7 +120,7 @@ duplicating 75 GB.| `LTX_H3_MODELS` | `<install>/mlx_models/hailuo-h3` | the three weight components || `LTX_H3_PYTHON` | `<H3_ROOT>/.venv/bin/python3.11` → `python` | interpreter override (a checkout without its own venv) || `LTX_H3_FORCE_CAPABLE` | unset | test-only: stop the UI hiding the pill on a small Mac. Does **not** make it render. |-| `LTX_H3_DENSE_10S` | unset | re-adds the pre-chaining dense 10 s tier (36 min) for A/B work |+| `LTX_H3_DENSE_10S` | **dead — not read anywhere in the code (H3-15)** | the dense 10 s tier ("10s single pass") ships `"offered": True` unconditionally; this var does nothing. Kept documented so a future re-gate has somewhere to land, not because it currently works. || `LTX_H3_WIDE_DRAFT` | unset | adds an experimental **512×288 16:9 draft** (~2 min). Off because 0.15 MP is below anything this campaign has measured — see Tiers. |**Set them in `ENVIRONMENT`, not in your shell.** An `export` in a terminal reaches@@ -159,14 +159,36 @@ shape; the campaign checkout uses the first.`H3_TIERS` in `mlx_ltx_panel.py` is the single source of truth — the UI rendersits chips from `/status.h3.tiers`, so a tier change is one Python edit.-| Tier | Geometry | Aspect | Windows | Sigma points | Wall time |-|---|---|---|---|---|---|-| Draft · 3s | 640×384 · 73f | 5:3 | 1 | 9 (8 forwards) | ~3 min |-| HQ · 3s | 768×448 · 73f | 12:7 | 1 | 9 (8 forwards) | ~4-5 min |-| HQ · 5s | 768×448 · 124f | 12:7 | 1 | 9 (8 forwards) | ~8 min |-| **Wide / High · 5s** | **1024×576 · 124f** | **16:9** | 1 | **16 (15 forwards)** since 2026-09-16 | **~34 min** (was ~19 at 8 forwards) |-| Long · 10s | 768×448 · 243f | 12:7 | **2 × 124f chained** | 9 (8 forwards) | ~17 min |-| Long · 15s | 768×448 · 362f | 12:7 | **3 × 124f chained** | 9 (8 forwards) | ~27 min · batch |+The table below uses the CURRENT names — two independent axes, Quality+(canvas) × Length (duration) — the same ones `/status.h3.tiers` and the UI's+chips use. H3-31: this table used to be written entirely in the RETIRED+fixed-tier vocabulary (HQ / Wide / Long), which the UI dropped for the+two-axis picker; `H3_TIER_ALIASES` (mlx_ltx_panel.py) still resolves those old+composite keys for a sidecar written before the split — **HQ → Standard**,+**Wide → High**, **Long → the chained lengths (10s/15s) at any quality** — but+they are not choices in the UI, and this table should not have kept reading+as if they were.++| Quality | Length | Geometry | Aspect | Windows | Sigma points | Wall time |+|---|---|---|---|---|---|---|+| Draft | 3s | 640×384 · 73f | 5:3 | 1 | 9 (8 forwards) | ~3 min |+| Standard | 3s | 768×448 · 73f | 12:7 | 1 | 9 (8 forwards) | ~4-5 min |+| Standard | 5s | 768×448 · 124f | 12:7 | 1 | 9 (8 forwards) | ~8 min |+| **High** | **5s** | **1024×576 · 124f** | **16:9** | 1 | **16 (15 forwards)** since 2026-09-16 | **~34 min** (was ~19 at 8 forwards) |+| Standard | 10s | 768×448 · 243f | 12:7 | **2 × 124f chained** | 9 (8 forwards) | ~17 min |+| Standard | 15s | 768×448 · 362f | 12:7 | **3 × 124f chained** | 9 (8 forwards) | ~27 min · batch |++Legacy composite key → current two-axis key, for reading an old sidecar:++| Legacy key | Current key |+|---|---|+| `hq_3s` | `standard_3s` |+| `hq_5s` | `standard_5s` |+| `wide_5s` | `high_5s` |+| `long_10s` | `standard_10s` |+| `long_15s` | `standard_15s` |+| `long_10s_dense` | `standard_10s_dense` |+| `wide_draft_3s` | `preview_3s` |### Aspect — why one tier is 16:9 and the rest are not (2026-08-06)@@ -342,7 +364,9 @@ and `make_job` falls back to `H3_TIER_FINISH_DEFAULT` (`hq_5s`) rather thanfailing a queued job — named explicitly, because the old "last single-pass rowin the table" scan started meaning the ~19 min `wide_5s` the day a tier wasappended, and a fallback nobody asked for has to be the cheap one.-`LTX_H3_DENSE_10S=1` restores the old dense 10 s tier for A/B work.+The dense 10 s tier ("10s single pass") ships visible by default, always —+`LTX_H3_DENSE_10S` is not read anywhere and restores nothing; see the+constants table above.### Export pass — the same post-process LTX renders get@@ -499,21 +523,24 @@ existing wrapper rather than nesting one — nesting hid the quantized base's`scales` from `plan()` and skipped every module (`tests/test_lora_stack.py`in the engine tree pins this).-**Key layouts.** Three exist in the wild and only two work:+**Key layouts.** Four exist in the wild; three load, one is refused:| Layout | Keys | What happens ||---|---|---|| bare | `blocks.N.attn.qkv_proj.lora_A/B.weight` | loads as-is || ComfyUI repack | the same, namespaced under `diffusion_model.` | **converted in place** at install time — a safetensors *header* rewrite (the offsets are relative to the tensor buffer, so every tensor byte is untouched), recorded in the sidecar as `lora_layout` / `lora_converted_prefix` |+| kohya / sd-scripts | `lora_down`/`lora_up` + `.alpha` | **converted in place** (2026-09-06) — the character LoRAs people actually train for H3 come out of kohya-style trainers in exactly this shape, and the two things the runner can't read (the naming, the `.alpha` scalar) are both mechanical: `_h3_lora_convert_kohya` renames the keys onto the runner's `lora_A`/`lora_B` and folds alpha/rank into `lora_B`, so strength 1.0 means "as trained" — same as every other file. Recorded in the sidecar as `lora_layout: "kohya"`. || diffusers / PEFT | split `to_q`/`to_k`/`to_v`, `ff.net.*` | **refused, by design** |-| kohya | `lora_down`/`lora_up` + `.alpha` | **refused, by design** |-The refusals are not laziness. A diffusers-namespace adapter needs a runtime+The diffusers refusal is not laziness. That adapter needs a runtime`alpha / rank` multiplier that **is not in the file** — LightX2V's is`8 / 128 = 0.0625`, supplied externally by its own inference script — andapplying it at 1.0 renders coloured noise, not a slightly-off clip. See`LIGHTX2V_LORA_FIX.md` and `scripts/convert_lightx2v_lora.py` in the engine-repo for the manual path. The panel says exactly this in the error.+repo for the manual path. The panel says exactly this in the error, and+since a diffusers-layout file trained for LTX is the file people most often+try here by mistake, the import UI also tells them it looks like an LTX+LoRA and won't run on H3.**CivitAI.** The browser's video context has family pills (`ltx` / `h3`),preselected from the active engine, so an LTX user's default view is unchanged.diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.mdindex 5dd785e..84d3a5e 100644--- a/docs/RELEASE_CHECKLIST.md+++ b/docs/RELEASE_CHECKLIST.md@@ -169,6 +169,37 @@ Exit 0 on both. For a DiT pack, finish with a real loader round-trip on thereassembled transformer (`verify_load_ltx_dit` in `scripts/quantize_ltx.py`) —sha256 proves the bytes arrived, only the loader proves they are a model.+## 3c. Fleet timings — rebuild before every release++Owner ruling (2026-09-29): every time estimate in the panel should be built+from what the fleet's own installs actually measured, not just the+chip-factor cost model. `data/fleet_timings.json` (committed) is a+snapshot, not live — it goes stale the moment new render_completed events+land, so it is rebuilt as part of cutting a release, not on some separate+schedule:++```+python3 scripts/fleet_timings_build.py+```++Needs a PostHog personal API key in Settings -> analytics_query_key on the+Mac running it (the maintainer's own dev panel already has one — see+`~/pinokio/api/phosphene-dev.git/state/panel_settings.json`, read-only, the+key is never printed or committed). Queries the last 75 days of+`render_completed` events, excludes the maintainer's own install by+`distinct_id`, and writes three levels of real p25/p50/p75 wall-clock data+(cell / chip family / model-wide) to `data/fleet_timings.json`. Users'+own panels never query PostHog themselves — they only read the committed+table, the same way every other bundled data file ships.++Diff the rebuilt file before committing — a release that ran during an+outage, or against a key that lost access, should not silently ship a+near-empty table. `test_fleet_timings.py`'s+`test_the_real_shipped_table_loads_without_raising` is a structural+sanity check only (schema + the three level names); it cannot catch a+table that is technically valid but thin, because real data changes every+rebuild and a value assertion there would fail on the next honest run.+## 4. Version + compile```diff --git a/docs/STATE.md b/docs/STATE.mdindex 1439150..2b3fd3f 100644--- a/docs/STATE.md+++ b/docs/STATE.md@@ -1,3 +1,7 @@+> **🚀 2026-09-29 — v4.17.0: the flow-review mega ship (222 findings).** Five hands-on reviews drove every flow on a clean panel at four window sizes (video-core, video-advanced, H3, film, system; `review-2026-09-29-ux/` in the PM hub) and ten fix packages landed on `int-4170` off beta `70665d3`, merged in order system → est → size-faces → safety → h3 → lipsync → video-ui → board → editor-a → editor-b. **Headline for users:** estimates are for THEIR Mac (fleet p25–p75 per chip+RAM from `data/fleet_timings.json`, rebuilt at release, self-calibrating on the install's own renders); no silent downgrades (16:9 stays 16:9 under 48 GB, size chips show the delivered size); faces survive (EXIF rotation, HEIC, portrait shape picked from the photo, draggable crop, original photo kept in the sidecar); Stop/Clear/Hide have confirm or Undo and One Shot keeps finished parts; New take everywhere; Lip-sync is a Video mode (3 s draft, verdict chip, Continue the song, Split into clips on Compact, Retake a moment); the Editor gets Sync to song, Match colour + per-clip grade, slip/roll, Replace, take history, versioned cancelable renders. **Merge notes:** conflicts and every resolution are in the PM hub's `INTEGRATION_NOTES.txt` §1–6 (notable: video-ui reparented onto safety's real commits; two Retry-smaller implementations unified; `_ensure_video_poster` defined twice → the editor's renamed `_ensure_proxy_poster`; est's `window.BOOT` read (BOOT is a top-level const) made Keyframe/Extend refuse on every Mac). **Codex:** one round, 7 areas, 80 findings, all fixed or proven duplicate, each with a failing-first test (`test_codex_4170*.py`). **Render checks** (both GPU locks, Pinokio-shaped env): T2V, I2V from a sideways EXIF-6 portrait, lip-sync + Continue the song, H3 Draft, Retake, Windows partial (helper killed mid-chain), Split into clips on a faked-32 GB Compact panel, Editor render with Match colour. They found six more bugs, fixed with tests in `test_render_check_4170.py`: **Save dropped every per-clip grade** (`sbeCleanClip` rebuilt `adjust` as brightness only — Match colour never reached a render), a2v/keyframe live preview never fills (pinned engine drops the monitor → held out of `LTX_LIVE_PREVIEW_MODES`), the Compact cap + Split link hidden behind a 0.1 s silent-tail note, Retake's size cap unstated, the windows-partial sidecar keeping the ASKED frames, and the portrait player header wrapping inside items. **Open, deliberately:** `lipsync_score` reads weak on synthetic TTS voices; Match colour at 100% pulls a night shot orange when the cut mixes night and day (strength slider + Undo); mixed-orientation films render on a max(w)×max(h) canvas; H3 Stop-after-window stays off until the runner keeps windows (`H3_RUNNER_KEEPS_WINDOWS_ON_STOP`).++> **📊 2026-09-29 — beta (mega-est package): time estimates now come from real fleet data, shown as a range.** Owner ruling: "If we have the fleet data, we can provide proper time estimations, or at least a range." Every estimate before this was a MODEL (a per-chip speed factor × a cost function fitted to renders on the maintainer's own Macs) — this adds a REAL-DATA layer on top. `scripts/fleet_timings_build.py` queries PostHog HogQL for `render_completed` events (last 75 days, the maintainer's own install excluded by `distinct_id`) at three levels of granularity — cell (chip + RAM + exact length), chip (any RAM), model (any chip) — and writes `data/fleet_timings.json` (committed; a user's own panel never queries PostHog itself, only reads this table). `fleet_estimate_range()` / `fleet_calibrated_range()` (mlx_ltx_panel.py) walk that table at runtime: exact cell → same chip+RAM at a different length (scaled by the cost model's own ratio between the two lengths) → chip family → model-wide → `None` (caller falls back to the existing cost model). This install's own per-render self-calibration (VC-01) is layered on top of the fleet range, but ONLY once this Mac has finished 2+ renders — one lucky-or-unlucky render must not visibly skew a number built from hundreds of fleet renders. `ltxCellEta`/`h3CellEta` (engines.js) now show "~12-18 min" wherever the fleet has enough data for this exact shape, falling back to the model's single point estimate otherwise; the chip's tooltip says where the number comes from ("based on 523 renders on Macs like yours" / "estimated — few renders on this Mac class yet"). **Release process:** `scripts/fleet_timings_build.py` must run before every release (docs/RELEASE_CHECKLIST.md §3c) — the table is a snapshot, not live. **Tests:** `test_fleet_timings.py` (loader, three-level fallback order including the scaled-length case, range formatting, calibration gating on sample count, and that the runtime key-builder matches the build script's byte-for-byte).+> **🩺 2026-09-28 — v4.16.3: three field fixes (fleet + Pinokio).** Ships beta `5b2003d` (H3 Now card "X in · ~Y left" + later windows' load time, promised to @abandonedmuse, comment-2487) and two fleet bugs, both reproduced. **(1) Truncated LoRA → raw numpy error.** Fleet: `cannot reshape array of size 57408 into shape (32,2048)`, 14 failed renders, 1 install, 4.16.1/4.16.2, always with a style LoRA. Cause: an interrupted download keeps its safetensors header (first bytes) and loses its tail, so `inspect_lora_compatibility` (keys only) passed and `measure_adapter_effect`'s `read()` got a short buffer and reshaped it. Reproduced exactly by cutting (65536−57408)×2 bytes off a rank-32 F16 adapter. **Fix:** `lora_compat._tensor_header_cached` compares the file size with `8 + header + max(data_offsets end)` and raises `LoraCompatibilityError("'<file>' is incomplete: the file is X MB but it should be Y MB … download it again")`; `read()` also refuses a short or self-contradicting tensor by name. The panel's `_ltx_lora_compatibility` already catches that error, so the picker marks the file unavailable with the reason and the enqueue refuses it. **(2) ffmpeg without libx264.** Fleet: H3 `Unknown encoder 'libx264'` ×2 and LTX `ffmpeg encode_single_frame failed: ffmpeg version 8.1.2` ×1, one 4.16.1 install (M4 Max 64 GB) that never finished a render — the first ffmpeg `_resolve_tool` found was a build without libx264 (conda-forge's LGPL variant and some static builds). **Fix:** `_resolve_ffmpeg()` walks the same candidates in the same order (LTX_FFMPEG, PATH, Pinokio's bin dirs, Homebrew, /usr/local, /opt/local), probes `-encoders`, skips any that lists its encoders without libx264 (an unreadable probe counts as usable), and `FFMPEG_NOTE` is printed at boot; the helper and the H3 runner get the chosen one first on PATH as before. Test `test_fleet_4163.py` (11; 9 fail on 4.16.2). Fleet read 09-24→09-28 (PostHog): 173 active installs on 4.16.x; failure rate 4.16.1 5.3%, 4.16.2 7.3% (2.9% without four installs; H3 0.4%); metal_watchdog still the top class (87 events, 10 installs, LTX only, four M1/M2 32–96 GB installs = 74) — not fixed here; the empty-venv install failure fell 4% → 0.9% of installs and every affected install recovered (looks like a first-boot race, not proven); Music Studio 57 songs, 2 failures. Not fixed, noted: H3 `TypeError: RenderIntegrityError.__init__() missing 1 required positional argument` (1 event; the runner's exception has a two-argument `__init__`, so any copy/pickle of it breaks — runner-repo fix), Qwen-Edit-2511 "stuck at 121.6 GB" (1 install, blobs dir holds more than one revision; likely disk).> **⏱ 2026-09-26 — beta, after 4.16.2 (unreleased): the H3 Now card says "left".** @abandonedmuse's screenshot on the 4.15 post showed `27m 23s / ~18m 21s` in window 2/3 at step 7/8 — the H3 run loop's `eta_sec` is the time LEFT, and the Now card prints `eta_sec` as "elapsed / ~X", which reads as a total (the user's "supposed to be 18 min"). The loop now also sends `remaining_sec`, so the card reads "27m 23s in · ~18m 21s left", and the estimate adds `H3_LOAD_SEC` (× the H3 speed factor) for each window still to come. The same screenshot says step 7/8: that render ran Best, not Fast (the Fast adapter is a one-click 180 MB install). Promised in the Pinokio reply (comment-2487); ships with the next release. Test: `test_h3_progress_time_left.py`.diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex b315491..a9102fe 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -33,6 +33,7 @@ import subprocessimport sysimport threadingimport time+import unicodedataimport zipfilefrom email import policyfrom email.message import Message as _EmailMessage@@ -906,6 +907,55 @@ def pack_for_repo_key(repo_key: str | None) -> dict | None:return None+def _all_version_owned_repo_keys() -> set[str]:+ """Every repo key any MODEL_VERSION claims as its own pack, text encoder+ or High add-on — across every registered generation, not just the+ active one."""+ keys: set[str] = set()+ for v in MODEL_VERSIONS:+ keys.update(p.get("repo_key") for p in v.get("packs", ()) if p.get("repo_key"))+ te = (v.get("text_encoder") or {}).get("repo_key")+ if te:+ keys.add(te)+ hq = v.get("hq_addon_repo_key")+ if hq:+ keys.add(hq)+ return keys+++def relevant_repo_keys(version_id: str | None = None) -> set[str]:+ """Repo keys worth counting for THIS install's "models ready" tally.++ VC-32: the header health pill's "models N/M" used ALL twelve+ required_files.json repos as M — including q4/gemma/q8 (2.3's own base+ pack, irrelevant while 2.5 is active) and every IC-LoRA/tae extra a+ user may never touch. A fresh, fully-working 2.5 install with none of+ the IC-LoRA packs read "models 4/12", which looks broken (and was+ reported as a colour confusion downstream of the same root cause —+ "models 10/12" shown green: the REQUIRED set was complete, but the+ number implied otherwise).++ "Relevant" = the ACTIVE generation's own base pack, text encoder and+ High add-on, PLUS every repo that is version-agnostic (not claimed as a+ pack/text-encoder/add-on by ANY registered generation — the IC-LoRA+ adapters and the temporal autoencoder, all usable regardless of which+ generation is active). A generation this install is NOT running (e.g.+ 2.3's q4/gemma/q8 while 2.5 is active) is excluded — LTX_MODEL_VERSION+ switches it back in, which changes what "active" resolves to here too.+ """+ ver = model_version(version_id)+ keys = {p.get("repo_key") for p in ver.get("packs", ()) if p.get("repo_key")}+ te = (ver.get("text_encoder") or {}).get("repo_key")+ if te:+ keys.add(te)+ hq = ver.get("hq_addon_repo_key")+ if hq:+ keys.add(hq)+ owned_elsewhere = _all_version_owned_repo_keys()+ keys.update(r.get("key") for r in _repos() if r.get("key") not in owned_elsewhere)+ return keys++def version_cap_tiers(version_id: str | None = None) -> tuple[str, ...]:return tuple(model_version(version_id).get("cap_tiers", ("q4",)))@@ -1040,6 +1090,10 @@ def _settings_defaults() -> dict:# when the model state regresses (e.g. a download disappears) so# a real new problem still surfaces. UI-only; no security impact."models_card_dismissed": False,+ # SYS-16: the first-run "Make your first clip" card, dismissed+ # manually (× button) independent of whether a render has actually+ # finished yet — same one-shot shape as models_card_dismissed.+ "first_run_card_dismissed": False,# Spicy mode — gates NSFW LoRA visibility. Default OFF (kid-safe).# When OFF: the CivitAI browser hides its "Show NSFW" toggle, the# server forces nsfw=false on CivitAI requests, and any incoming@@ -1342,6 +1396,14 @@ def _validate_settings_patch(patch: dict) -> tuple[dict, str | None]:else:out["models_card_dismissed"] = str(v).strip().lower() in ("1", "true", "yes", "on")+ if "first_run_card_dismissed" in patch:+ # Same urlencoded-bool coercion as models_card_dismissed.+ v = patch["first_run_card_dismissed"]+ if isinstance(v, bool):+ out["first_run_card_dismissed"] = v+ else:+ out["first_run_card_dismissed"] = str(v).strip().lower() in ("1", "true", "yes", "on")+if "spicy_mode" in patch:# Same urlencoded-bool coercion as models_card_dismissed.v = patch["spicy_mode"]@@ -1517,6 +1579,7 @@ def get_settings_public() -> dict:"has_civitai_key": bool(s.get("civitai_api_key", "").strip()),"has_hf_token": bool(s.get("hf_token", "").strip()),"models_card_dismissed": bool(s.get("models_card_dismissed", False)),+ "first_run_card_dismissed": bool(s.get("first_run_card_dismissed", False)),"spicy_mode": bool(s.get("spicy_mode", False)),"live_preview": str(s.get("live_preview", "on")),"notify_done": bool(s.get("notify_done", True)),@@ -1848,6 +1911,119 @@ def _safe_loras_dir() -> Path:return LORAS_DIR+# ============================================================================+# Image ingest normalization — EXIF orientation + HEIC/HEIF/AVIF (SYS-01/02)+# ============================================================================+# Phone photos (the #1 I2V/H3/A2V/Train reference source) arrive in two ways+# this panel used to mishandle:+#+# 1. EXIF-rotated JPEG. An iPhone or Android held sideways writes pixels+# in SENSOR orientation plus an EXIF Orientation tag telling a viewer+# how to rotate for display. The browser applies that tag (the picker+# preview looks right-side up); PIL — everywhere this panel opens an+# image for cropping, thumbnailing or training — does NOT, by default.+# So the render, the trainer's centre-crop, and the thumbnail all saw a+# sideways photo while the picker showed it upright, and there was no+# way for a user to tell from the UI that anything was wrong.+#+# 2. HEIC/HEIF (what AirDrop, Photos and iCloud hand a Mac user by+# default) and AVIF. Pillow, as shipped, cannot decode any of them: the+# picker preview goes blank with no toast, the file never shows up in+# "Recent uploads", and Generate passes validation (only checks the+# file EXISTS) only to fail deep in the helper after the model has+# already loaded, with an unhelpful `cannot identify image file`.+#+# `normalize_ingested_image_bytes()` is the ONE place both /upload and+# /train/upload funnel every picked image through before it touches disk:+# HEIC/HEIF/AVIF are converted to JPEG with macOS's built-in `sips` (zero+# new dependencies — the same tool `docs/` already reaches for elsewhere in+# this codebase), then every image (including formats PIL opens natively)+# is EXIF-transposed and re-saved WITHOUT the orientation tag, so nothing+# downstream — I2V/H3/A2V's cover-crop, the trainer's centre-crop, the+# thumbnail cache — can ever see a mismatch between what the tag says and+# what the pixels say again, because after this point there IS no tag.+HEIC_LIKE_EXTS = frozenset({".heic", ".heif", ".avif"})+++def _convert_heic_via_sips(data: bytes, ext: str) -> bytes | None:+ """Convert HEIC/HEIF/AVIF bytes to JPEG using macOS's built-in `sips`.++ Returns JPEG bytes, or None if `sips` is unavailable (this is a+ macOS-only tool — the panel is Apple-Silicon-only, but a CI box or a+ future non-Mac dev environment has neither) or the conversion itself+ fails (a genuinely corrupt file). The caller turns None into a clear+ refusal rather than silently writing bytes nothing downstream can+ decode."""+ if shutil.which("sips") is None:+ return None+ import tempfile+ with tempfile.TemporaryDirectory() as td:+ src = Path(td) / f"in{ext}"+ dst = Path(td) / "out.jpg"+ try:+ src.write_bytes(data)+ subprocess.run(+ ["sips", "-s", "format", "jpeg", str(src), "--out", str(dst)],+ check=True, capture_output=True, timeout=30,+ )+ if not dst.exists() or dst.stat().st_size == 0:+ return None+ return dst.read_bytes()+ except Exception: # noqa: BLE001+ return None+++def normalize_ingested_image_bytes(data: bytes, filename: str+ ) -> tuple[bytes, str, str | None]:+ """Normalize one uploaded image's bytes before they touch disk.++ Returns `(normalized_bytes, extension_with_dot, error_message)`. On+ success `error_message` is None and `extension_with_dot` is the+ extension the caller should save the file under (may differ from the+ original — HEIC in, JPEG out). On failure `normalized_bytes` is the+ original `data` unchanged, `extension_with_dot` is the original+ extension, and `error_message` explains what to do — the caller refuses+ the upload with that message rather than writing an undecodable file."""+ ext = Path(filename).suffix.lower()+ work, work_ext = data, ext+ if ext in HEIC_LIKE_EXTS:+ converted = _convert_heic_via_sips(data, ext)+ if converted is None:+ return data, ext, (+ f"{ext.upper().lstrip('.')} photo: this Mac couldn't convert "+ "it (sips unavailable or the file is unreadable). Export it "+ "as JPEG in Photos (File → Export → Export "+ "Unmodified, or choose JPEG), or share it via AirDrop with "+ "“Most Compatible” turned on, then upload that."+ )+ work, work_ext = converted, ".jpg"+ try:+ from PIL import Image, ImageOps+ import io+ with Image.open(io.BytesIO(work)) as im:+ im.load() # decode NOW — a truncated file fails here, not mid-render+ oriented = ImageOps.exif_transpose(im) or im+ has_alpha = "A" in oriented.getbands()+ buf = io.BytesIO()+ if work_ext in (".jpg", ".jpeg", ".jfif", ".jpe"):+ oriented.convert("RGB").save(buf, format="JPEG", quality=95,+ optimize=True)+ out_ext = work_ext+ elif work_ext == ".webp":+ oriented.save(buf, format="WEBP", quality=95)+ out_ext = ".webp"+ else:+ # PNG and anything else PIL can open natively (BMP/TIFF/GIF/+ # the sips JPEG above never reaches here): a lossless re-save+ # that also happens to preserve alpha when there is one.+ oriented.convert("RGBA" if has_alpha else "RGB").save(+ buf, format="PNG", optimize=True)+ out_ext = ".png"+ return buf.getvalue(), out_ext, None+ except Exception as exc: # noqa: BLE001+ return data, ext, f"could not read this as an image ({exc})."++# ============================================================================# Image thumbnail cache# ============================================================================@@ -1886,7 +2062,7 @@ def _ensure_thumbnail(src: Path, width: int) -> Path:# over the picture, which is exactly the thing the lane exists to avoid.# A source with alpha is answered in PNG; everything else keeps the JPEG# that makes the pool cheap.- from PIL import Image+ from PIL import Image, ImageOps# THE FORMAT IS DECIDED BEFORE THE CACHE IS CONSULTED, not after. Checking# the .jpg first would keep serving a thumbnail flattened by the old code# for as long as the source went unedited — the cache key is (path, mtime,@@ -1914,6 +2090,12 @@ def _ensure_thumbnail(src: Path, width: int) -> Path:return out_THUMBCACHE.mkdir(parents=True, exist_ok=True)with Image.open(src) as im:+ # SYS-01: belt-and-suspenders for anything that reaches this path+ # WITHOUT going through normalize_ingested_image_bytes at ingest — a+ # file uploaded before this fix landed, or a library image picked+ # from somewhere other than /upload. Everything new is already+ # EXIF-stripped by ingest, so exif_transpose is a no-op there.+ im = ImageOps.exif_transpose(im) or imim = im.convert("RGBA" if keep_alpha else "RGB")# PIL's thumbnail() preserves aspect ratio and only shrinks (never# upscales — passing w=2048 on a 1024-wide source returns the@@ -1930,6 +2112,126 @@ def _ensure_thumbnail(src: Path, width: int) -> Path:return out+def _ensure_video_poster(src: Path) -> Path | None:+ """Return a path to a cached JPEG poster (one representative frame) of+ a rendered clip. VC-31/36: gallery cards were live `<video+ preload="metadata">` elements — with a large library the first paint+ was black cards while each clip's moov atom downloaded. A poster lets+ the card be a plain `<img>` instead, same caching idiom as+ _ensure_thumbnail just above: keyed on (resolved path, mtime, size),+ generated once, served from disk after that.++ ffmpeg seeks to 2.5s first — LTX/H3 clips run 3s+ and the first+ half-second is often a dark fade-in, matching the representative-frame+ convention the old `<video>#t=2.5` poster already used — then falls+ back to 0s for anything shorter that seek can't reach. Returns None+ (never raises) when ffmpeg is missing or the source can't be read; the+ caller keeps the plain video element for that one clip rather than+ breaking the card."""+ try:+ st = src.stat()+ except OSError:+ return None+ raw = f"{src.resolve()}|{st.st_mtime_ns}|{st.st_size}|poster".encode()+ key = hashlib.sha1(raw).hexdigest()+ out = _THUMBCACHE / f"{key}.poster.jpg"+ if out.exists() and out.stat().st_size > 0:+ return out+ # The panel's resolved ffmpeg (FFMPEG, _resolve_ffmpeg), not a bare PATH+ # lookup: a hand-started panel's PATH may not carry Pinokio's miniforge.+ ff = str(FFMPEG) if FFMPEG else shutil.which("ffmpeg")+ if not ff:+ return None+ _THUMBCACHE.mkdir(parents=True, exist_ok=True)+ for seek in ("2.5", "0"):+ try:+ subprocess.run(+ [ff, "-loglevel", "error", "-y", "-ss", seek, "-i", str(src),+ "-frames:v", "1", "-q:v", "3", str(out)],+ capture_output=True, timeout=20,+ )+ except Exception: # noqa: BLE001+ continue+ if out.exists() and out.stat().st_size > 0:+ return out+ return None+++# ============================================================================+# Video poster cache — FILM-39+# ============================================================================+# The Editor's timeline drew a first-frame poster for a still (PIL, via+# _ensure_thumbnail above) but nothing for a video clip: video tracks were+# a name over a flat colour, on a screen whose whole point is showing what+# the picture is. This is the video half of the same idea — one JPEG frame,+# extracted with ffmpeg instead of decoded with PIL (which cannot open an+# mp4 at all), cached on disk the same way: keyed by (source path, mtime,+# size, width) so a repeat request costs one disk read.+#+# SOURCE IS ALWAYS THE PROXY, NEVER THE ORIGINAL. Two reasons, not one: the+# proxy is what the Editor already trusts a route to serve (`/storyboard/+# edit/proxy`, board-scoped, basename-only) — reusing that boundary means+# this route inherits its containment instead of inventing a second one for+# arbitrary clip paths, some of which (a relink) can point anywhere on disk.+# And a clip with no proxy yet is exactly the clip flagged "SLOW" on the+# timeline for the same reason (no fast seek without one) — asking ffmpeg to+# open the ORIGINAL for a 240px poster would be the slow decode Prepare+# exists to avoid, on every clip, on every paint.+_POSTER_CACHE = UPLOADS / ".postercache"+++def _ensure_proxy_poster(src: Path, width: int) -> Path:+ """Return a path to a `width`-px-wide JPEG of `src`'s first frame.++ (The Editor filmstrip's poster, FILM-39 — named apart from the gallery's+ _ensure_video_poster, VC-31, which has a different contract: one arg,+ a representative frame at 2.5 s, None instead of raising. The two landed+ under one name in the 4.17 merge and the later one replaced the first,+ so every gallery /poster request raised TypeError.)++ Cached on disk, keyed like `_ensure_thumbnail`. Raises on any ffmpeg+ failure (a truncated proxy, a codec ffmpeg cannot decode) — the caller+ falls back to no poster rather than serving a broken image.+ """+ width = max(16, min(1024, int(width)))+ try:+ st = src.stat()+ except OSError:+ raise FileNotFoundError(f"source not found: {src}")+ raw = f"{src.resolve()}|{st.st_mtime_ns}|{st.st_size}|{width}|poster".encode()+ key = hashlib.sha1(raw).hexdigest()+ out = _POSTER_CACHE / f"{key}.jpg"+ if out.exists() and out.stat().st_size > 0:+ return out+ _POSTER_CACHE.mkdir(parents=True, exist_ok=True)+ # `-ss 0` before `-i` is the fast (keyframe-seek) path — exactly the+ # kind of seek a clip with no proxy cannot do smoothly, which is why+ # this only ever runs against the proxy. `scale=w:-2` keeps the source+ # aspect (height rounds to an even number, which some encoders require+ # and none reject). Written to a `.part` name first so a reader can+ # never observe a half-written JPEG through the cache — and `-f mjpeg`+ # is NOT optional once the output name carries that suffix: ffmpeg picks+ # its muxer from the file EXTENSION, `foo.jpg.part-1234` has none it+ # recognises, and it refuses to write at all (exit 234, "Unable to+ # choose an output format") rather than silently guessing.+ part = out.with_suffix(out.suffix + f".part-{os.getpid()}")+ try:+ subprocess.run(+ [str(FFMPEG), "-y", "-loglevel", "error", "-ss", "0", "-i", str(src),+ "-frames:v", "1", "-vf", f"scale={width}:-2",+ "-q:v", "4", "-f", "mjpeg", str(part)],+ check=True, capture_output=True, timeout=30)+ if not part.exists() or part.stat().st_size == 0:+ raise RuntimeError("ffmpeg produced no frame")+ part.replace(out)+ finally:+ try:+ part.unlink()+ except OSError:+ pass+ return out++# ============================================================================# Train Character — dataset + job-spec plumbing# ============================================================================@@ -2242,6 +2544,14 @@ TRAIN_MIN_RAM_GB = 24# dir, it doesn't re-check the upload cap).TRAIN_MAX_IMAGES = 500TRAIN_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp"}+# SYS-02: what /train/upload ACCEPTS is wider than what ends up on disk —+# HEIC/HEIF/AVIF (macOS Photos/AirDrop's default hand-off) get converted to+# JPEG by normalize_ingested_image_bytes() before they're written into+# images_dir, so TRAIN_IMAGE_EXTS (what's actually stored, and what the+# existing-file count above scans for) stays unchanged. Without this, the+# most common way a Mac user hands over photos was silently dropped from+# the Train dataset drop zone with no message at all (characters.js).+TRAIN_IMAGE_UPLOAD_EXTS = TRAIN_IMAGE_EXTS | HEIC_LIKE_EXTSTRAIN_MAX_BYTES_PER_IMAGE = 32 * 1024 * 1024 # 32 MB per image upload# Hard cap on bodies for the generic urlencoded POST fallback (the catch-all@@ -3061,11 +3371,15 @@ def _train_required_models() -> list[dict]:{"key": "ltx_dev_transformer","label": "LTX-2.3 dev transformer (training-only, full precision)",- "blurb": "Required for training. Standard inference uses the distilled "- "transformer instead; the dev transformer has the right "- "flow-matching schedule for LoRA-from-images training. "- "Must be the full-precision (~21 GB) copy — a quantized "- "dev transformer trains a LoRA that never applies.",+ # SYS-15/SYS-42: "the dev transformer has the right flow-matching+ # schedule for LoRA-from-images training" was lab jargon a+ # creator can't act on. Outcome language: what it's for, and+ # what goes wrong if the wrong copy is used.+ "blurb": "Required for training — a different file from the one "+ "your renders already use. Must be the full-precision "+ "copy (~21 GB): a smaller, compressed copy trains a "+ "LoRA that looks fine in the log and does nothing when "+ "you use it.","repo_id": "dgrauet/ltx-2.3-mlx-q8","filename": "transformer-dev.safetensors","local_dir": str(q8_local_dir),@@ -4845,18 +5159,34 @@ _STATS_WARNED_NO_TOKEN = False_STATS_WARNED_FETCH_FAIL = False+def _stats_debug(line: str) -> None:+ """VC-33: this loop is a maintainer-only nicety (it feeds the /stats+ dashboard's historic data, nothing a regular user renders or clicks+ touches it), but it used to report through `push()` — the SAME log+ the Logs tab shows for every install. A fresh panel's Logs tab could+ read, in full: "stats: rate-limit remaining: 4848/5000" - one cryptic+ line about a feature the user has never heard of, with nothing+ app-related in it. Every message this module has ever wanted to show+ a real user ("generation is unaffected") already says that outright,+ which is itself the tell that it never belonged in the user-facing+ log. Route it to stderr instead — visible in the maintainer's own+ terminal / Pinokio process log, absent from /status.log."""+ sys.stderr.write(f"[stats] {line}\n")++def _run_stats_fetch_once() -> None:- """Spawn scripts/fetch_repo_stats.py as a subprocess. Output to the- panel's `push()` log so the user can see what happened. Idempotent —- the fetcher itself replaces today's row on re-runs in the same UTC day."""+ """Spawn scripts/fetch_repo_stats.py as a subprocess. Output goes to+ stderr via `_stats_debug()`, not the shared user-facing log — see its+ docstring. Idempotent — the fetcher itself replaces today's row on+ re-runs in the same UTC day."""global _STATS_WARNED_NO_TOKEN, _STATS_WARNED_FETCH_FAILif not STATS_FETCHER.is_file():return # repo install missing the script — fail silenttoken = _resolve_github_token()if not token:if not _STATS_WARNED_NO_TOKEN:- push(- "stats: no GitHub token resolvable (tried "+ _stats_debug(+ "no GitHub token resolvable (tried ""PHOSPHENE_REPO_STATS_TOKEN, GH_STATS_TOKEN, GH_TOKEN, ""GITHUB_TOKEN, `gh auth token`). Dashboard will be empty ""until you set one."@@ -4879,31 +5209,31 @@ def _run_stats_fetch_once() -> None:if not _STATS_WARNED_FETCH_FAIL:_detail = (cp.stderr or cp.stdout or "").strip().splitlines()_detail = _detail[-1][:160] if _detail else "unknown error"- push(f"stats: dashboard refresh skipped ({_detail}). "- "This only affects the maintainer stats panel — "- "generation, models, and training are unaffected.")+ _stats_debug(f"dashboard refresh skipped ({_detail}). "+ "This only affects the maintainer stats panel — "+ "generation, models, and training are unaffected.")_STATS_WARNED_FETCH_FAIL = Truereturn# Success — clear the one-shot warning latch so a genuine future# failure can surface again._STATS_WARNED_FETCH_FAIL = False# Last stdout line is the human-readable summary the fetcher prints- # at exit. Forward to the panel log so /status surfaces it.+ # at exit. Forward to stderr for the maintainer, never to /status.last_line = ""for line in (cp.stdout or "").splitlines():if line.strip():last_line = line.strip()if last_line:- push(f"stats: {last_line}")+ _stats_debug(last_line)except subprocess.TimeoutExpired:if not _STATS_WARNED_FETCH_FAIL:- push("stats: dashboard refresh timed out (harmless — maintainer "- "stats panel only; generation is unaffected).")+ _stats_debug("dashboard refresh timed out (harmless — maintainer "+ "stats panel only; generation is unaffected).")_STATS_WARNED_FETCH_FAIL = Trueexcept Exception as exc: # noqa: BLE001if not _STATS_WARNED_FETCH_FAIL:- push(f"stats: dashboard refresh skipped ({exc!r}). Harmless — "- "maintainer stats panel only; generation is unaffected.")+ _stats_debug(f"dashboard refresh skipped ({exc!r}). Harmless — "+ "maintainer stats panel only; generation is unaffected.")_STATS_WARNED_FETCH_FAIL = True@@ -5451,18 +5781,40 @@ def ltx_floor_canvas(width, height) -> tuple[int, int]:def ltx_fit_canvas(width, height, max_dim: int) -> tuple[int, int]:"""Fit a canvas under a hardware cap: ONE scale factor for both sides so- the long side is at most `max_dim` (0 = no cap), then ltx_floor_canvas.+ the long side is at most `max_dim` (0 = no cap), then snapped to the /64+ grid.Every hardware clamp goes through here. The A2V clamp capped each side onits own, so a 1280x704 canvas under a 768 cap became a near-square768x704 (LTX-06); the tier, keyframe and compact-profile clamps scaledproportionally but rounded to /32, undoing make_job's /64 floor and- recording dimensions the two-stage engine does not deliver (LTX-10)."""+ recording dimensions the two-stage engine does not deliver (LTX-10).++ VC-02/SYS-05: when a clamp actually fires, the two sides are snapped to+ the NEAREST /64 grid point, not floored independently. Flooring both+ sides drags whichever side is not already on a 64 boundary toward zero+ with no regard for the other, which is what turned a 16:9 request into a+ 2:1 canvas (1024x576 clamped to 768 came back 768x384, not 768x448/432) —+ the exact bug both reports caught. The long side is the one the caller+ asked to cap, so it never rounds back over `max_dim`; only the short+ side, which the scale step already put under the cap, gets the same+ "nearest, not floor" treatment. Unclamped requests (max_dim falsy, or+ already under it) are untouched — every OTHER caller of ltx_floor_canvas+ (arbitrary user W×H, source-derived canvases) keeps flooring, which is+ correct there: this function is the ONE place a hardware safety margin is+ being spent, so it is the one place allowed to round instead of floor."""w, h = float(width), float(height)- if max_dim and max(w, h) > max_dim:- scale = max_dim / max(w, h)- w, h = w * scale, h * scale- return ltx_floor_canvas(w, h)+ if not (max_dim and max(w, h) > max_dim):+ return ltx_floor_canvas(w, h)+ scale = max_dim / max(w, h)+ w, h = w * scale, h * scale+ rw = max(64, round(w / 64) * 64)+ rh = max(64, round(h / 64) * 64)+ if rw > max_dim:+ rw = max(64, int(w) // 64 * 64)+ if rh > max_dim:+ rh = max(64, int(h) // 64 * 64)+ return rw, rhdef ltx_model_dir(quant: str, version_id: str | None = None) -> str:@@ -7578,11 +7930,46 @@ def _civitai_download(download_url: str, meta: dict) -> dict:ASPECTS = {"landscape": {"label": "Landscape 16:9 (1280×704 → 720)", "w": 1280, "h": 704},"vertical": {"label": "Vertical 9:16 (704×1280 → 720)", "w": 704, "h": 1280},- "square": {"label": "Square (768×768)", "w": 768, "h": 768},+ "square": {"label": "Square 1:1 (768×768)", "w": 768, "h": 768},"test": {"label": "Quick test (512×288)", "w": 512, "h": 288},"wide": {"label": "Ultra-wide 21:9 (1408×608)", "w": 1408, "h": 608},"portrait": {"label": "Mobile portrait (576×1024)", "w": 576, "h": 1024},+ # VC-39: social creators need 1:1 and 4:5, not just the two video-shaped+ # presets above. 768x960 — an exact 4:5 pair on the engine's /64 grid+ # (w = 256k, h = 320k), 0.74 MP beside landscape's 0.90. It was 896x1120,+ # on /32 only: make_job floors every LTX canvas to /64, so the 4:5 chip+ # rendered 896x1088, not 4:5 (4.17 Codex EST-11). BOOT serves these+ # through aspect_presets_for_this_mac(), which keeps both social cells+ # exact under a hardware cap too.+ "portrait_4_5": {"label": "Portrait 4:5 (768×960)", "w": 768, "h": 960},}+# The exact ratio each fixed social cell must keep, whatever the cap.+_ASPECT_EXACT_RATIOS = {"square": (1, 1), "portrait_4_5": (4, 5)}+++def aspect_presets_for_this_mac() -> dict:+ """ASPECTS as THIS Mac renders them (4.17 Codex EST-11). run_job_inner's+ hardware clamp (Compact's t2v_max_dim) and the generation profile's+ max_dim scale a canvas and floor it to /64 — which turns 768x960 into+ 576x768, a 3:4 clip under a "4:5" chip, with a crop preview drawn for the+ wrong shape. Under a cap the fixed social cells take the largest EXACT+ pair on the /64 grid that fits, so the chip, the form's W×H, the crop+ overlay and the render all agree."""+ caps = [int(SYSTEM_CAPS.get("t2v_max_dim") or 0)]+ if SYSTEM_TIER != "base":+ caps.append(int((GENERATION_PROFILE or {}).get("max_dim") or 0))+ caps = [c for c in caps if c > 0]+ cap = min(caps) if caps else 0+ out = {k: dict(v) for k, v in ASPECTS.items()}+ for key, (rw, rh) in _ASPECT_EXACT_RATIOS.items():+ a = out.get(key)+ if not a or not cap or max(a["w"], a["h"]) <= cap:+ continue+ t = max(1, cap // (64 * max(rw, rh)))+ w, h = 64 * rw * t, 64 * rh * t+ a["label"] = a["label"].replace(f"{a['w']}×{a['h']}", f"{w}×{h}")+ a["w"], a["h"] = w, h+ return out# One-click presets (fill aspect + duration in one button)PRESETS = [@@ -7600,6 +7987,14 @@ PRESETS = [STATE: dict = {"queue": [], "current": None, "history": [],"paused": False, "log": [],+ # SYS-32: the circuit breaker paused the queue and explained why with a+ # push() line that only ever reached the Logs tab — the UI showed just+ # "queue N · paused" and a Resume button, no reason. This carries the+ # same headline into /status so the panel can show it where the user+ # actually is. Only ever set by the breaker (never by a manual Pause,+ # which has no "cause" to report) and cleared on Resume or once a job+ # after it succeeds.+ "paused_reason": None,"running": False, "pid": None, "pgid": None,# Process group of an in-flight Hailuo H3 render (the optional second# video engine — a `caffeinate → python → ffmpeg` tree outside HELPER).@@ -7816,28 +8211,12 @@ CAPABILITIES: dict[str, dict] = {"an existing clip) need more memory than this Mac has, so ""they're turned off."),- # Per-mode time estimates for a typical 5 s render (121 frames @ 24 fps),- # measured at Exact (no Boost/Turbo). The Comfortable tier is the- # measured baseline (M4 Studio 64 GB); other tiers are scaled relative- # to it using crude but defensible multipliers calibrated against- # community reports (Compact ≈ 1.6× slower from swap pressure; Roomy ≈- # 0.8× from headroom; Studio M-Ultra ≈ 0.55× from extra GPU cores).- # The `quality_times` block is what the Quality pills show; the legacy- # `times` block is what the Tier modal already uses.- "times": {- "t2v_draft": "about 3 min",- "t2v_standard": "about 12 min",- "i2v_standard": "about 12 min",- "high": None, # disabled- "keyframe": None, # disabled- "extend": None, # disabled- },- "quality_times": {- "quick": "~3 min",- "balanced": "~8 min",- "standard": "~12 min",- "high": None, # Q8 disabled at this tier- },+ # VC-12 / SYS-20: the per-mode time estimates that used to live here+ # (a "times"/"quality_times" pair of hand-typed strings, one per RAM+ # tier) are gone — they never scaled with chip speed and routinely+ # disagreed with the Quality chips on the SAME Mac. honest_tier_times()+ # computes the Tier modal's numbers from the same chip-and-RAM-aware+ # model the chips use; ltx_tiers_payload() is what the chips read.},"standard": {# 48–79 GB. 64 GB M-Studio is the canonical video-render baseline,@@ -7863,35 +8242,6 @@ CAPABILITIES: dict[str, dict] = {"48 GB machines use a compact LoRA training profile so ""training does not fall into multi-hour swap thrash."),- # Times are measured wall clocks for a 5 s render (121 frames @ 24 fps)- # at Exact speed, on the canonical Comfortable hardware (M-Studio /- # M-Max 64 GB). Y1.034 + Y1.035 added a temporal-streaming VAE decode- # patch that adds ~30 s of decode work on a 5 s clip in exchange for- # not melting on long ones; that bump is reflected in `standard` going- # from ~7 to ~8 min vs. pre-Y1.034 baselines (median 459 s observed- # across 26 Y1.013-Y1.024 runs; Y1.035 observed 493 s).- # Boost/Turbo Speed pills shave ~23%/~34% off Standard respectively.- "times": {- "t2v_draft": "about 2 min",- "t2v_standard": "about 8 min",- "i2v_standard": "about 8 min",- "high": "about 7 min",- "keyframe": "about 6 min (at 768 px)",- # Extend on Comfortable measured 16 min for +3 s at 768 px on- # M-Max 64 GB (Q8 dev transformer, CFG=1.0, 12 steps). The- # earlier "about 11 min" estimate predates the Y1.036 Q8 routing- # — pre-Y1.024 Extend ran on Q4-distilled-by-accident (faster- # weights, but technically loading the wrong model).- "extend": "about 16 min (at 768 px, +3 s)",- },- "quality_times": {- "quick": "~2 min",- "balanced": "~5 min",- "standard": "~8 min",- # 2026-05-09 lab finding: Q8 at the new 1024×576 default lands- # at ~7:48 wall vs the old 1280×704 default's ~11:51.- "high": "~7 min",- },},"high": {# 80–119 GB.@@ -7912,20 +8262,6 @@ CAPABILITIES: dict[str, dict] = {"1024 pixels (a real bump in detail over the 768 cap) ""without falling into swap."),- "times": {- "t2v_draft": "about 1 min",- "t2v_standard": "about 4 min",- "i2v_standard": "about 4 min",- "high": "about 7 min",- "keyframe": "about 6 min (at 1024 px)",- "extend": "about 9 min (at 1024 px)",- },- "quality_times": {- "quick": "~1 min",- "balanced": "~3 min",- "standard": "~4 min",- "high": "~7 min",- },},"pro": {# 128+ GB. M-Ultra Mac Studio 192/256 GB.@@ -7945,20 +8281,6 @@ CAPABILITIES: dict[str, dict] = {"and length the model supports. Bigger renders take longer, ""but nothing's capped artificially."),- "times": {- "t2v_draft": "under a minute",- "t2v_standard": "about 2 min",- "i2v_standard": "about 2 min",- "high": "about 4 min",- "keyframe": "about 3 min (full size)",- "extend": "about 5 min (full size)",- },- "quality_times": {- "quick": "<1 min",- "balanced": "~2 min",- "standard": "~3 min",- "high": "~4 min",- },},}@@ -8071,6 +8393,22 @@ def _select_generation_profile(total_ram_gb: float, tier_key: str) -> dict:}_override = os.environ.get("LTX_TIER_OVERRIDE", "").strip().lower()_override_lifts = _override in ("high", "pro")+ # NOTE (VC-02/SYS-05): this profile's `max_dim` (the RESOLUTION clamp)+ # duplicates CAPABILITIES' own tier_max_dim on the Compact tier (<48 GB)+ # — applied a second time, later, in run_job_inner — which is what+ # produced the double-clamp/floor-arithmetic bug (a 16:9 request coming+ # back 2:1) and the "48 GB fast generation" label showing on a 16 GB+ # Mac. The fix is NOT to stop this profile firing below 48 GB: several+ # OTHER fields here (`auto_temporal_after_frames`, `warn_loras`) are+ # real, still-needed Compact-tier behaviour — a2v_max_frames() reads+ # `compact` + `auto_temporal_after_frames` directly to compute the A2V+ # length refusal on an 8 GB Mac, and disabling `compact` below 48 GB+ # silently disabled that refusal gate entirely (caught by+ # test_review_416_jobs after an earlier, broader version of this fix).+ # Instead, `_apply_generation_profile_to_job` below skips ONLY its+ # resolution-clamp step when SYSTEM_TIER is already "base" — tier_max_dim+ # is the sole resolution authority there — while this function keeps+ # firing for both Compact and Comfortable exactly as before.if 0 < float(total_ram_gb or 0) < 64 and not _override_lifts:return {"key": "m5pro48_generation",@@ -8466,8 +8804,8 @@ FACE_FIX_5S_MIN = {"draft": 2.5, "preview": 2.0, "standard": 4.0, "high": 9.0}# nothing tells that user to look for a control they don't have.H3_TIER_CHAIN_NOTE = ("Every 5 s window is asked for the same prompt, so a ""one-off action happens once per window — open "- "Per-window prompts below to give each window its own "- "beat.")+ "Per-window prompts above (with the prompt box) to "+ "give each window its own beat.")H3_TIER_CHAIN_NOTE_LEGACY = ("Scripted dialogue repeats once per 5 s window — ""put dialogue cues late in the prompt. Per-window ""prompts need `--chain-prompts` on the installed "@@ -8526,12 +8864,28 @@ LTX_PREVIEW_HELP = ("byte-for-byte the clip you would have got with it switched off.")-# Only the shared T2V/I2V helper dispatch installs the live-preview callback.-# Special pipelines (Extend, Keyframe, A2V, HDR, Restore, Ingredients and-# Control) return through their own job specs and publish no preview today.-# Keep that fact server-owned so the stage never invents a warming promise for-# a lane that cannot fulfil it.+# VA-27: Keyframe and A2V are the longest single-clip lanes (Keyframe's own+# two-stage Q8 loop, A2V's 10-25 minute renders) and used to publish no+# preview at all — a frozen or mis-framed a2v shot was invisible until the+# full render finished. Both now thread live_preview through the SAME+# best-effort contract as t2v/i2v (_live_preview_params server-side,+# _thread_live_preview + _filter_unsupported_kwargs helper-side): if the+# installed pipeline build doesn't accept the kwarg, it is dropped silently+# and the render proceeds with no preview — never fatal.+# Extend, HDR, Restore, Ingredients and Control still return through their+# own job specs and publish no preview.+#+# RENDER-CHECKED 2026-09-29 (4.17.0 validation): the pinned engine's+# A2VidPipelineTwoStage.generate_and_save has no `live_preview` parameter+# (the helper logged "doesn't accept [...]; dropping") and+# KeyframeInterpolationPipeline.generate_and_save swallows it in **kwargs+# without ever calling the monitor. With the two modes in this set the Now+# card opened a preview slot that sat on "starting" for the whole 20-minute+# render. So they stay OUT until the engine threads the monitor through+# (the job-spec and helper wiring above is kept, dormant, for that day):+# a mode is listed here only when a real render has produced frames.LTX_LIVE_PREVIEW_MODES = frozenset(("t2v", "i2v", "i2v_clean_audio"))+LTX_LIVE_PREVIEW_PENDING_ENGINE = frozenset(("keyframe", "a2v"))# Motion Control's own generation sentence, server-owned like every other `?`# on this surface — one place to correct the day Lightricks publishes a 2.5@@ -8569,6 +8923,41 @@ LTX_Q8_CHARACTER_HELP = (# mechanism has to live beside the mechanism or it drifts. It names no model and# no size ON PURPOSE — repointing LTX_STORYBOARD_PLANNER at a different planner# must not turn this copy into a lie.+#: FILM-56: the default planner (gemma-3-12b-it-4bit) measured a peak of+#: ~7.9 GB resident, and that is on top of whatever the panel, the browser+#: and the OS already hold — on an 8-16 GB Mac the plan used to run for the+#: better part of the 900 s timeout and fail as an out-of-memory error+#: AFTER the wait, with no warning before it started. 16 GB is the floor a+#: 7.9 GB single-process peak can plausibly clear once the rest of the+#: machine is accounted for; below it, `storyboard_planner_ram_status()`+#: below hands the panel's own copy of "About a minute" a reason to say+#: otherwise. Deliberately a Mac-memory floor, not a model floor — see the+#: no-model-name note on STORYBOARD_RAM_HELP just below, which this follows+#: for the same reason.+PLANNER_MIN_RAM_GB = 16.0+++def storyboard_planner_ram_status() -> dict:+ """Whether THIS Mac can plausibly hold the planner without swapping.++ A prediction, not a measurement — the plan may well fit anyway if+ nothing else is using memory. So this never blocks planning; it only+ gives the "About a minute" copy and the pre-submit toast something+ honest to say instead of promising a minute and OOMing at nine.+ """+ ok = SYSTEM_RAM_GB >= PLANNER_MIN_RAM_GB+ return {+ "ram_gb": round(SYSTEM_RAM_GB, 1),+ "min_ram_gb": PLANNER_MIN_RAM_GB,+ "ok": ok,+ "message": "" if ok else (+ f"This Mac reports {SYSTEM_RAM_GB:.0f} GB of memory. The planner "+ f"can use most of that on its own — on a Mac this size, planning "+ f"can run for several minutes and then fail instead of finishing. "+ f"A smaller shot count is less likely to run out."),+ }++STORYBOARD_RAM_HELP = ("On a Mac the planner and the renderer share one pool of memory, so they ""never run at the same time. Phosphene plans the whole film in one go, in a "@@ -8757,15 +9146,24 @@ HW_SPEED_FACTOR_LTX = {"M2 Max": 1.0, "M4 Max": 1.0, "M3 Max": 1.2, "M5": 1.35, "M1 Max": 1.7, "M4 Pro": 1.7,"M4": 2.3, "M3 Pro": 2.8, "M2 Pro": 2.8, "M1 Pro": 3.3, "M1": 4.2, "M2": 5.0, "M3": 5.0,}+# H3-03: field data (one user's fleet read, M5 Pro 48 GB) put Best at 1.29-1.34x+# the panel's own Best estimate, flat across three cells — the ratio to Fast+# wasn't flat, so those renders ran Best and the table's 0.6 (a bucketed fleet+# median that lumped M5 Pro in with M5 Max) was the miscalibration, not the+# render. Raised toward the measured ~0.78-0.8; still coarse (one install), so+# _eta_calibration_factor (below) is what corrects it further on THIS Mac.HW_SPEED_FACTOR_H3 = {**HW_SPEED_FACTOR_LTX,- "M5 Max": 0.4, "M5 Pro": 0.6, "M3 Ultra": 0.7, "M2 Ultra": 1.0, "M1 Ultra": 1.4,+ "M5 Max": 0.4, "M5 Pro": 0.8, "M3 Ultra": 0.7, "M2 Ultra": 1.0, "M1 Ultra": 1.4,"M4 Pro": 2.0, "M3 Max": 2.0, "M1 Max": 3.0}def _hw_speed_factor(engine: str = "ltx") -> float:- """How many times slower than an M4 Max this Mac renders on `engine`.- Env `PHOSPHENE_SPEED_FACTOR` overrides (a number), for tests and for a- user whose machine the table misjudges."""+ """How many times slower than an M4 Max this Mac renders on `engine`:+ the fleet's per-chip median times THIS install's own correction (see+ _eta_calibration_factor). Env `PHOSPHENE_SPEED_FACTOR` overrides (a+ number) with a single total factor — for tests and for a user whose+ machine both tables misjudge — and skips calibration entirely, the same+ way an explicit override replaces _h3_ram_factor below."""raw = (os.environ.get("PHOSPHENE_SPEED_FACTOR") or "").strip()if raw:try:@@ -8773,7 +9171,367 @@ def _hw_speed_factor(engine: str = "ltx") -> float:except ValueError:passtable = HW_SPEED_FACTOR_H3 if engine == "h3" else HW_SPEED_FACTOR_LTX- return float(table.get(_hw_chip_family(), 1.0))+ chip = float(table.get(_hw_chip_family(), 1.0))+ return chip * _eta_calibration_factor(engine)+++# ---- Per-install self-calibration (VC-01 / H3-03) --------------------------+#+# The fleet tables above are medians across many Macs of the same chip class+# — real, but blind to any ONE Mac's own conditions (thermal headroom, what+# else is running, a chip the table bucketed with the wrong sibling). After+# every finished render this install compares what it actually took against+# what the CHIP-ONLY model predicted (see _record_eta_calibration_from_job)+# and keeps a running median of that ratio, clamped so a single outlier+# render — a retake, a thermal throttle, a stall — can't swing every later+# estimate. Read fresh at import (so a new boot picks up what the previous+# session learned); a panel that has been running a while does not re-price+# its already-built tier tables mid-session, same as the chip factor itself.+ETA_CALIBRATION_SAMPLES_MAX = 12+ETA_CALIBRATION_MIN = 0.5+ETA_CALIBRATION_MAX = 3.0+ETA_CALIBRATION_RATIO_MIN = 0.15 # outside this range the sample is more+ETA_CALIBRATION_RATIO_MAX = 8.0 # likely a retake/stall than true chip speed+++def _eta_calibration_path() -> Path:+ return STATE_DIR / "eta_calibration.json"+++def _load_eta_calibration() -> dict:+ try:+ return json.loads(_eta_calibration_path().read_text(encoding="utf-8"))+ except Exception: # noqa: BLE001+ return {}+++def _save_eta_calibration(data: dict) -> None:+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ tmp = _eta_calibration_path().with_suffix(".tmp")+ tmp.write_text(json.dumps(data), encoding="utf-8")+ tmp.replace(_eta_calibration_path())+ except Exception: # noqa: BLE001+ pass+++def _eta_calibration_factor(engine: str = "ltx") -> float:+ """Running median of actual/predicted wall time on THIS install for+ `engine` ("ltx" or "h3"), clamped 0.5-3x. 1.0 (no correction) until the+ first finished render reports back. An explicit PHOSPHENE_SPEED_FACTOR+ is a TOTAL override and is handled by the caller before this is reached."""+ samples = _load_eta_calibration().get(engine) or []+ ratios = sorted(float(r) for r in samples if isinstance(r, (int, float)) and r > 0)+ if not ratios:+ return 1.0+ n = len(ratios)+ median = ratios[n // 2] if n % 2 else (ratios[n // 2 - 1] + ratios[n // 2]) / 2.0+ return min(ETA_CALIBRATION_MAX, max(ETA_CALIBRATION_MIN, median))+++def _eta_calibration_sample_count(engine: str = "ltx") -> int:+ """How many finished renders this install's calibration factor for+ `engine` is actually based on. Owner ruling (2026-09-29): a fleet range+ should only be rescaled by this Mac's own calibration once it has+ rendered enough to mean something — one lucky-or-unlucky render+ shouldn't visibly skew a number built from hundreds of fleet renders."""+ samples = _load_eta_calibration().get(engine) or []+ return sum(1 for r in samples if isinstance(r, (int, float)) and r > 0)+++def _record_eta_calibration(engine: str, ratio: float) -> None:+ data = _load_eta_calibration()+ samples = [float(r) for r in (data.get(engine) or [])+ if isinstance(r, (int, float)) and r > 0]+ samples.append(round(float(ratio), 4))+ data[engine] = samples[-ETA_CALIBRATION_SAMPLES_MAX:]+ _save_eta_calibration(data)+++# The calibration factor each engine's tier table was PRICED with, captured+# right after the table is built at import (4.17 Codex H3-5). The table is not+# re-priced mid-session, so the baseline must divide by THIS factor — dividing+# by the current, freshly-updated factor fed each correction back into the+# next sample (identical 2x renders recorded 2.0, 4.0, 6.0 ... and hit the cap).+_ETA_CAL_PRICED: dict[str, float] = {}+++def _eta_calibration_baseline(job: dict) -> tuple[str, float] | None:+ """(engine, chip-only predicted minutes) for a finished render, read from+ the SAME price the user was shown for THAT recipe (job_recipe_minutes,+ calibration=True) — or None when the job's recipe has no model price to+ learn from (training, an image job, a custom length or canvas, a+ fleet-first Keyframe / Extend / Audio -> Video card, ...; 4.17 Codex+ EST-2: an A2V or Extend job matching a video cell's quality and frame+ count used to be read as a slow T2V render).++ The tier tables are priced ONCE, at import, with the factor recorded in+ _ETA_CAL_PRICED — dividing by that (never the current, freshly-updated+ factor) recovers the chip-only baseline without feeding each correction+ back into the next sample (Codex H3-5 / EST-1)."""+ p = (job or {}).get("params") or {}+ # An explicit total override priced the tables; there is nothing of this+ # Mac's own to learn from them.+ if (os.environ.get("PHOSPHENE_SPEED_FACTOR") or "").strip():+ return None+ hit = job_recipe_minutes(p, calibration=True)+ if not hit:+ return None+ engine, minutes = hit+ cal = max(0.05, _ETA_CAL_PRICED.get(engine, 1.0))+ return engine, float(minutes) / cal+++_FLEET_CAL_PREFIX = "fleet_"+++def _job_fleet_baseline_min(job: dict) -> tuple[str, float] | None:+ """(engine, UNADJUSTED fleet median minutes) for the shape a finished+ render had — the baseline its fleet-calibration sample is taken against+ (4.17 Codex EST-3). Only the shapes the tier chips show a fleet range for:+ H3 Best/Fast cells, LTX T2V/I2V cells at the cell's own canvas and tuned+ schedule (the Fast draft has no fleet range of its own)."""+ p = (job or {}).get("params") or {}+ if (os.environ.get("PHOSPHENE_SPEED_FACTOR") or "").strip():+ return None+ if not job_recipe_minutes(p, calibration=True):+ return None # not a comparable single render at all+ engine = str(p.get("engine") or "ltx").strip().lower()+ if engine == "h3":+ key = h3_resolve_tier(str(p.get("h3_tier") or "")) or h3_compose_tier(+ p.get("h3_quality"), p.get("h3_length"))+ cell = H3_TIERS.get(key) if key else None+ if not cell or not cell.get("frames"):+ return None+ fast = bool(p.get("h3_tristep") or p.get("h3_turbo"))+ hit = fleet_estimate_range("h3", "t2v", key, cell["frames"],+ speed="fast" if fast else "best")+ else:+ if str(p.get("schedule_preset") or "").strip().lower() == "fast":+ return None+ hit = fleet_estimate_range("ltx", "t2v", str(p.get("quality") or ""),+ p.get("frames"), speed="")+ if not hit or not hit.get("p50_min"):+ return None+ return engine, float(hit["p50_min"])+++def _record_eta_calibration_from_job(job: dict) -> None:+ """After a finished render, fold its actual-vs-predicted ratio into this+ install's running median (VC-01, H3-03). Best-effort and silent: it must+ never be able to turn a finished render into a failed one."""+ try:+ if (job or {}).get("status") != "done":+ return+ elapsed = job.get("elapsed_sec")+ if not elapsed or float(elapsed) <= 0:+ return+ actual_min = float(elapsed) / 60.0+ # Two separate corrections, each against its OWN baseline (4.17+ # Codex EST-3): the cost model's price, and the fleet's own median.+ model = _eta_calibration_baseline(job)+ try:+ fleet = _job_fleet_baseline_min(job)+ except Exception: # noqa: BLE001+ fleet = None # never at the cost of the model's own sample+ for key, hit in ((model[0] if model else "", model),+ (_FLEET_CAL_PREFIX + fleet[0] if fleet else "", fleet)):+ if not hit or hit[1] <= 0:+ continue+ ratio = actual_min / hit[1]+ if ETA_CALIBRATION_RATIO_MIN <= ratio <= ETA_CALIBRATION_RATIO_MAX:+ _record_eta_calibration(key, ratio)+ except Exception: # noqa: BLE001+ pass+++# ---- Fleet timings — real fleet data, not just a model ---------------------+#+# Owner ruling (2026-09-29): "If we have the fleet data, we can provide+# proper time estimations, or at least a range." Everything above this+# comment (_hw_speed_factor, ltx_estimate_minutes, h3_estimate_minutes) is a+# COST MODEL — a per-chip speed factor times a function fitted to renders+# measured on the maintainer's own Macs. This section instead reads what the+# FLEET's own installs actually measured, built offline by+# scripts/fleet_timings_build.py (real PostHog HogQL queries, the owner's+# own installs excluded) into data/fleet_timings.json, which ships IN the+# repo — a user's own panel never queries PostHog itself, it only reads the+# committed table.+#+# Three levels, most to least specific (see the build script's own+# docstring for exactly what each groups by): "cell" (this chip, this RAM,+# this exact length) -> "cell_scaled" (this chip and RAM, a DIFFERENT+# length, scaled by the cost model's own ratio between the two — computed+# here, not precomputed, since it needs the REQUESTED length) -> "chip"+# (this chip, any RAM) -> "model" (any Mac at all). The cost model above+# remains the fallback when the fleet has nothing to say at any level, and+# every one of its cells is still used for scaling.+FLEET_TIMINGS_PATH = ROOT / "data" / "fleet_timings.json"+++def _load_fleet_timings() -> dict:+ try:+ return json.loads(FLEET_TIMINGS_PATH.read_text(encoding="utf-8"))+ except Exception: # noqa: BLE001+ return {}+++FLEET_TIMINGS: dict = _load_fleet_timings()++# The wall-clock ladder render_completed reports on (docs/ANALYTICS.md+# `wall_sec_bucket`): each render sends the LOWER edge of the rung it fell+# in, never its exact time. Defined here, ahead of the tier tables that read+# the fleet table at import; the analytics sender uses the same tuple.+FLEET_WALL_SEC_LADDER = (15, 30, 45, 60, 90, 120, 180, 240, 300, 420,+ 600, 900, 1200, 1800, 2400, 3600, 5400)+++def _wall_bucket_bounds(sec: float) -> tuple[float, float]:+ """(lower, upper) edge of the ladder rung `sec` falls in. The open-ended+ top rung has no upper edge to report, so it is its own bound."""+ lo, hi = 0.0, float(FLEET_WALL_SEC_LADDER[0])+ for rung in FLEET_WALL_SEC_LADDER:+ if sec >= rung:+ lo = float(rung)+ nxt = [r for r in FLEET_WALL_SEC_LADDER if r > rung]+ hi = float(nxt[0]) if nxt else float(rung)+ else:+ break+ return lo, hi+++def _fleet_cell_seconds(cell: dict) -> tuple[float, float, float]:+ """(p25, p50, p75) seconds a fleet cell actually supports (4.17 Codex+ EST-4). scripts/fleet_timings_build.py takes quantiles of the ladder's+ LOWER edges, so a cell whose renders all landed in the 10-15 min rung+ reads 600/600/600 — shown as a tight "~10 min" that is really "somewhere+ in 10-15". The bucket width is known uncertainty, so it is kept: p25 is+ its rung's lower edge (a lower bound), p75 its rung's UPPER edge (an+ upper bound), p50 the middle of its rung. A table whose `wall_sec`+ says "seconds" (exact wall clocks) is read as is."""+ p25, p50, p75 = float(cell["p25_sec"]), float(cell["p50_sec"]), float(cell["p75_sec"])+ if str(FLEET_TIMINGS.get("wall_sec") or "bucket_lower_edge") != "bucket_lower_edge":+ return p25, p50, p75+ lo50, hi50 = _wall_bucket_bounds(p50)+ return _wall_bucket_bounds(p25)[0], (lo50 + hi50) / 2.0, _wall_bucket_bounds(p75)[1]+++def _fleet_key(engine: str, mode: str, tier: str, frames, chip: str | None = None,+ ram: float | None = None, speed: str = "") -> str:+ """Must match scripts/fleet_timings_build.py's _key_for exactly — same+ dimension order, same "any" placeholder for an absent speed axis, same+ float-string formatting for frames/ram (Python's str(float(x)) is+ deterministic, so build time and read time agree without either side+ having to know the other's exact code)."""+ parts = [str(engine), str(mode), str(tier), str(float(frames))]+ if chip is not None:+ parts.append(str(chip))+ if ram is not None:+ parts.append(str(float(ram)))+ parts.append(speed or "any")+ return "|".join(parts)+++def _fleet_scale_ratio(engine: str, tier: str, target_frames: float,+ found_frames: float) -> float | None:+ """How much longer/shorter `target_frames` prices against `found_frames`+ at the SAME canvas, from the panel's own cost model. The chip factor+ cancels in the ratio (both calls share it), so this is chip-agnostic —+ correct to scale a fleet cell measured on ANY Mac."""+ try:+ if found_frames <= 0 or target_frames <= 0:+ return None+ if engine == "h3":+ t = H3_TIERS.get(tier)+ if not t:+ return None+ w, h, steps = int(t["width"]), int(t["height"]), max(1, int(t["steps"]) - 1)+ a = h3_estimate_minutes(w, h, int(target_frames), 1, steps)+ b = h3_estimate_minutes(w, h, int(found_frames), 1, steps)+ else:+ q = LTX_QUALITIES.get(tier)+ if not q:+ return None+ w, h = int(q["width"]), int(q["height"])+ s1, s2 = int(q["stage1"]), int(q["stage2"])+ evals = int(q.get("stage2_evals") or 1)+ a = ltx_estimate_minutes(w, h, int(target_frames), s1, s2, evals)+ b = ltx_estimate_minutes(w, h, int(found_frames), s1, s2, evals)+ return (a / b) if b > 0 else None+ except Exception: # noqa: BLE001+ return None+++def fleet_estimate_range(engine: str, mode: str, tier: str, frames,+ chip: str | None = None, ram: float | None = None,+ speed: str = "") -> dict | None:+ """(p25/p50/p75 minutes, sample count, source, human basis text) for+ this exact render shape, read from real fleet data — or None when the+ fleet table has nothing at any level, in which case the caller prices+ from the cost model instead. Self-calibration is NOT applied here+ (callers that want it multiply p25/p50/p75 themselves) so this function+ stays a pure table lookup, independently testable."""+ levels = FLEET_TIMINGS.get("levels") or {}+ chip = chip if chip is not None else _hw_chip_family()+ ram = ram if ram is not None else SYSTEM_RAM_GB+ try:+ frames_f = float(frames)+ except (TypeError, ValueError):+ return None++ def _minutes(cell: dict, scale: float = 1.0) -> dict:+ p25, p50, p75 = _fleet_cell_seconds(cell)+ return {+ "p25_min": round(p25 / 60.0 * scale, 2),+ "p50_min": round(p50 / 60.0 * scale, 2),+ "p75_min": round(p75 / 60.0 * scale, 2),+ "n": int(cell["n"]),+ }++ cell_cells = (levels.get("cell") or {}).get("cells") or {}+ key = _fleet_key(engine, mode, tier, frames_f, chip=chip, ram=ram, speed=speed)+ hit = cell_cells.get(key)+ if hit:+ return {**_minutes(hit), "source": "cell",+ "basis": f"based on {hit['n']} renders on Macs like yours"}++ # cell_scaled: same chip+RAM, a DIFFERENT length of the SAME cell,+ # nearest frame count first (least extrapolation), scaled by the cost+ # model's own ratio between the two lengths.+ prefix = f"{engine}|{mode}|{tier}|"+ suffix = f"|{chip}|{float(ram)}|{speed or 'any'}"+ nearest = None+ for k, v in cell_cells.items():+ if not (k.startswith(prefix) and k.endswith(suffix)):+ continue+ try:+ kf = float(k[len(prefix):-len(suffix)])+ except ValueError:+ continue+ if nearest is None or abs(kf - frames_f) < abs(nearest[0] - frames_f):+ nearest = (kf, v)+ if nearest:+ found_frames, hit = nearest+ ratio = _fleet_scale_ratio(engine, tier, frames_f, found_frames)+ if ratio:+ return {**_minutes(hit, scale=ratio), "source": "cell_scaled",+ "basis": f"based on {hit['n']} renders on Macs like yours, "+ f"scaled from a different length"}++ chip_cells = (levels.get("chip") or {}).get("cells") or {}+ key = _fleet_key(engine, mode, tier, frames_f, chip=chip, speed=speed)+ hit = chip_cells.get(key)+ if hit:+ return {**_minutes(hit), "source": "chip",+ "basis": f"based on {hit['n']} renders on {chip} Macs"}++ model_cells = (levels.get("model") or {}).get("cells") or {}+ key = _fleet_key(engine, mode, tier, frames_f, speed=speed)+ hit = model_cells.get(key)+ if hit:+ return {**_minutes(hit), "source": "model",+ "basis": f"based on {hit['n']} renders fleet-wide"}+ return None_HW_CHIP_FAMILY: str | None = None@@ -8798,6 +9556,64 @@ def _hw_chip_family() -> str:return _HW_CHIP_FAMILY+# SYS-07 (priority item): the Metal GPU watchdog (#44/#59 — the app's #1+# fleet failure) is a first- and second-generation Apple Silicon driver+# quirk, not a speed or RAM-tier problem — it has been reported on M1 Max+# 32 GB and M2 Max 32 GB, both FAST chips (see HW_SPEED_FACTOR_LTX above:+# M1 Max=1.7x, M2 Max=1.0x — neither is a "slow Mac"). A long command+# buffer is what trips it, and a long T2V/I2V clip on the Q4 one-stage+# pipeline is exactly that: one denoise loop, one buffer, for the whole+# render. The existing Gemma-encode fallback (#44, above) only covers a+# watchdog hit DURING PROMPT ENCODING; a hit during DENOISE on a long clip+# is not caught by anything today and the render is simply lost after+# minutes. Per the review: refuse it up front with a real suggestion,+# rather than silently rendering a smaller/shorter clip than asked for —+# "no silent downgrades" is the app's own rule everywhere else.+_M1_M2_WATCHDOG_RISK_FAMILIES = frozenset({+ "M1", "M1 Pro", "M1 Max", "M2", "M2 Pro", "M2 Max",+})+# The two reported configs are 32 GB (M1 Max, M2 Max); banded rather than+# an exact match so nearby real-world hw.memsize roundoff doesn't miss it.+_M1_M2_WATCHDOG_RISK_RAM_GB = (28.0, 36.0)+# "Long" here matches the app's own Long Clip Boost boundary concept: a+# clip past the one-window native length is materially more denoise work+# in one command buffer. 121 frames = 5s at 24fps, the app's own default.+_M1_M2_WATCHDOG_RISK_MIN_FRAMES = 121+++def m1_m2_long_clip_watchdog_refusal(mode: str, quality: str, model_frames: int) -> str | None:+ """None when safe to proceed; else the refusal message for+ RenderRefused("hardware_tier", ...).++ T2V/I2V Q4 one-stage only — the HQ two-stage lane uses a different+ (shorter, per-stage) denoise loop and is not the reported failure+ shape. Takes `model_frames` — the frame count the DiT actually+ processes in ONE denoise loop / ONE GPU command buffer — not the+ requested delivery frame count, so a clip Long Clip Boost or sliding+ windows has already chunked down doesn't get refused for a workload+ it no longer runs in one piece."""+ if mode not in ("t2v", "i2v", "i2v_clean_audio"):+ return None+ if ltx_quality_uses_hq(quality):+ return None+ if _hw_chip_family() not in _M1_M2_WATCHDOG_RISK_FAMILIES:+ return None+ lo, hi = _M1_M2_WATCHDOG_RISK_RAM_GB+ if not (lo <= SYSTEM_RAM_GB <= hi):+ return None+ if model_frames <= _M1_M2_WATCHDOG_RISK_MIN_FRAMES:+ return None+ return (+ f"This {_hw_chip_family()} ({SYSTEM_RAM_GB:.0f} GB) is a chip generation "+ f"where macOS's own GPU watchdog has killed long renders outright — a "+ f"driver limit (github.com/mrbizarro/phosphene/issues/44), not a "+ f"Phosphene bug. A clip this long runs as one long GPU command buffer. "+ f"Try Quick or a 5 s clip first — if that's reliable on this Mac, "+ f"sliding windows (Video → Advanced → long clip mode) renders a longer "+ f"clip as a chain of short passes instead of one long one."+ )++# THE REDUCED-RAM LANE IS SLOWER, AND MOST SLOWER ON CHAINED LENGTHS. Every@@ -8868,6 +9684,39 @@ def h3_lowram_chain_note(windows: int, ram_gb: float | None = None) -> str:return H3_TIER_LOWRAM_CHAIN_NOTE.format(ram=int(round(ram)))+# VC-01: LTX had no equivalent of _h3_ram_factor — every estimate scaled by+# chip alone, so a 16 GB Mac (which LOW_RAM_STREAM pushes onto a slower,+# disk-streamed DiT load — see LOW_RAM_STREAM_RAM_GB above) was priced as if+# it were a 64 GB one running the identical chip. Same shape as H3's factor:+# one number, applied once, replaced entirely by an explicit override.+LTX_LOWRAM_FACTOR = 1.3+++def _ltx_ram_factor(ram_gb: float | None = None) -> float:+ """How much slower than the resident-weights lane LTX runs on this Mac's+ LOW_RAM_STREAM lane (1.0 above LOW_RAM_STREAM_RAM_GB). Same override+ contract as _h3_ram_factor: an explicit PHOSPHENE_SPEED_FACTOR is a+ TOTAL factor and replaces this."""+ raw = (os.environ.get("PHOSPHENE_SPEED_FACTOR") or "").strip()+ if raw:+ try:+ float(raw)+ return 1.0+ except ValueError:+ pass+ ram = float(SYSTEM_RAM_GB if ram_gb is None else ram_gb)+ if ram <= 0 or ram > LOW_RAM_STREAM_RAM_GB:+ return 1.0+ return LTX_LOWRAM_FACTOR+++def _ltx_speed_factor() -> float:+ """The ONE multiplier every LTX estimate carries: this Mac's chip+ (with this install's own calibration folded in — see+ _eta_calibration_factor) and the low-RAM streaming lane."""+ return _hw_speed_factor("ltx") * _ltx_ram_factor()++def h3_estimate_minutes(w: int, h: int, window_frames: int, windows: int,forwards: int) -> float:"""Wall clock, in minutes, for a render of this exact shape. The one function@@ -8896,6 +9745,59 @@ def _fmt_eta(minutes: float) -> str:return f"~{max(1, int(round(minutes)))} min{tail}"+def _fmt_eta_range(p25_min: float, p75_min: float) -> str:+ """"~12-18 min", or the single-number form when the range rounds to one+ minute (a tight, well-measured cell shouldn't print a fake range).+ Same no-decimals rule as _fmt_eta, same hours form above the same+ threshold — a range just wide enough to see, not a shape a user has to+ parse differently from every point estimate elsewhere in the panel."""+ lo, hi = max(1, int(round(p25_min))), max(1, int(round(p75_min)))+ if hi < lo:+ lo, hi = hi, lo+ if lo == hi:+ return _fmt_eta(p75_min)+ if hi >= ETA_HOURS_MIN:+ # Each end without _fmt_eta's own " · batch" tail, then the tail+ # once — "~36 min–1h 19m · batch", never "~36 min · batch–1h 19m · batch".+ def _bare(m: float) -> str:+ return _fmt_eta(m).replace(" · batch", "").lstrip("~")+ return f"~{_bare(p25_min)}–{_bare(p75_min)} · batch"+ tail = " · batch" if p75_min >= ETA_BATCH_MIN else ""+ return f"~{lo}–{hi} min{tail}"+++def fleet_calibrated_range(engine: str, mode: str, tier: str, frames,+ chip: str | None = None, ram: float | None = None,+ speed: str = "") -> dict | None:+ """fleet_estimate_range(), with this install's own self-calibration+ folded in — owner ruling (2026-09-29): only once this Mac has actually+ finished 2+ renders of its own, so one lucky-or-unlucky render can't+ visibly skew a number built from hundreds of fleet renders. Adds the+ formatted range string and, when calibration applied, says so in the+ basis text."""+ hit = fleet_estimate_range(engine, mode, tier, frames, chip=chip, ram=ram, speed=speed)+ if not hit:+ return None+ # 4.17 Codex EST-3: the correction here is THIS Mac against the FLEET's+ # own numbers (actual / unadjusted fleet median, recorded under+ # "fleet_<engine>"), never the cost model's correction — those have+ # different baselines, and applying the model's error to an accurate+ # fleet range made it wrong by exactly that error.+ cal_key = _FLEET_CAL_PREFIX + engine+ cal = 1.0+ if _eta_calibration_sample_count(cal_key) >= 2:+ cal = _eta_calibration_factor(cal_key)+ if cal != 1.0:+ hit = {**hit,+ "p25_min": round(hit["p25_min"] * cal, 2),+ "p50_min": round(hit["p50_min"] * cal, 2),+ "p75_min": round(hit["p75_min"] * cal, 2),+ "basis": hit["basis"] + ", adjusted for this Mac's own renders"}+ hit["eta_range"] = _fmt_eta_range(hit["p25_min"], hit["p75_min"])+ hit["eta_mid"] = _fmt_eta(hit["p50_min"])+ return hit++# END-TO-END WALL CLOCKS actually observed on this machine, keyed# (quality, length, turbo). Where one exists it WINS over the model and the cell# says so — `eta_measured` / `turbo_measured` — so the UI can keep making the@@ -8957,8 +9859,11 @@ def _h3_qualities() -> dict[str, dict]:"standard": {"key": "standard", "label": "Standard", "order": 1,"width": 768, "height": 448,- "blurb": "The workhorse canvas — every chained-window measurement "- "on this Mac was taken here. 12:7, so a 720p/1080p export "+ # H3-14: the old sentence cited where the dev's own measurements+ # were taken — a developer's dev-machine note, not something+ # that tells a user what THEY get. Say the trade-off instead.+ "blurb": "The workhorse canvas — the best-tested shape for "+ "chained 10s/15s clips. 12:7, so a 720p/1080p export ""trims a few pixels top and bottom to fill 16:9.","offered": True,},@@ -8998,10 +9903,15 @@ def _h3_qualities() -> dict[str, dict]:"native": {"key": "native", "label": "Native", "order": 3,"width": 1344, "height": 768,+ # H3-14: the old sentence named a Turbo on/off choice this canvas+ # no longer offers — Turbo was folded into the Fast/Best Speed+ # switch, and Native has no Fast pass at all (tristep_min is+ # null here), so it always renders on Best. Say that plainly+ # instead of pointing at a control that isn't there."blurb": "The model's own canvas at its 1.03 MP ceiling — the most ""detail H3 can produce. 7:4, so a 1080p export trims a "- "few pixels to fill 16:9. Worth it with Turbo on; a long wait "- "without.",+ "few pixels to fill 16:9. Always renders on Best — no "+ "Fast pass here — so it's a long wait for the most detail.","steps": H3_NATIVE_STEPS,"offered": True,},@@ -9052,8 +9962,14 @@ def _h3_lengths() -> dict[str, dict]:"10s": {"key": "10s", "label": "10s", "order": 2, "seconds": 10,"frames": 243, "window_frames": 124, "windows": 2,- "blurb": "Two chained 5 s windows — half the dense pass's cost, and "- "no duplicated-subject ghosting.",+ # H3-14/H3-15: this and "10s single pass" both used to claim to+ # be "the safe one" (no ghosting / no drift) in a way that read+ # as contradicting each other. This is the DEFAULT: cheaper, in+ # two joined windows — the join (below) is the trade-off, not a+ # flaw either tier "avoids" more than the other.+ "blurb": "The default 10s — two chained 5 s windows, about half "+ "the cost of the single-pass version. One join partway "+ "through, invisible on continuous motion.","note": H3_TIER_CHAIN_NOTE,"offered": True,},@@ -9086,10 +10002,13 @@ def _h3_lengths() -> dict[str, dict]:"key": "10s_dense", "label": "10s single pass", "order": 4, "seconds": 10,"frames": 243, "window_frames": 243, "windows": 1,"steps": 16,- "blurb": "A real 10 seconds in ONE pass — no seam, no chained "- "repeat, no drift between halves. Slower than the chained "- "10s; this is the one to pick when the clip has to hold "- "together as a single shot.",+ # H3-14/H3-15: rewritten alongside the chained "10s" blurb so the+ # two no longer both read as "the safe one" — this one trades+ # cost (2-4x the chained version, and Best only, no Fast pass)+ # for having no join at all.+ "blurb": "One continuous shot, no join — costs 2-4x the chained "+ "10s and always renders on Best. Pick this when the "+ "clip has to hold together with no seam at all.",# Measured to fit on every canvas up to Native (53.5 GiB peak at# 1344×768); no longer restricted to the small ones."dense": True,@@ -9231,10 +10150,22 @@ def _build_h3_tiers() -> dict[str, dict]:"offered": bool(q["offered"] and ln["offered"]),**tristep,}+ # Owner ruling (2026-09-29): real fleet ranges where there are+ # enough of them, one per speed this cell actually offers (H3's+ # Fast/Best split is a real difference in wall time, unlike+ # LTX's mode axis — see the plain LTX case above).+ fleet_best = fleet_calibrated_range("h3", "t2v", key, frames, speed="best")+ if fleet_best:+ tiers[key]["fleet_range"] = fleet_best+ if tiers[key].get("tristep_min") is not None:+ fleet_fast = fleet_calibrated_range("h3", "t2v", key, frames, speed="fast")+ if fleet_fast:+ tiers[key]["fleet_range_fast"] = fleet_fastreturn tiersH3_TIERS: dict[str, dict] = _build_h3_tiers()+_ETA_CAL_PRICED["h3"] = _eta_calibration_factor("h3") # the factor H3_TIERS was priced with# Every tier key that has ever been written into a sidecar, mapped to the cell# it means. Load Params, Draft→Finish, the ⓘ modal, list_outputs and a resumed@@ -9478,7 +10409,7 @@ def ltx_estimate_minutes(w: int, h: int, frames: int,+ max(0, int(stage2_steps)) * max(1, int(stage2_evals))* _ltx_forward_seconds(s2))fixed = LTX_LOAD_SEC + LTX_DECODE_SEC_PER_PX_FRAME * int(w) * int(h) * int(frames)- return (denoise + fixed) / 60.0 * _hw_speed_factor("ltx")+ return (denoise + fixed) / 60.0 * _ltx_speed_factor()# END-TO-END WALL CLOCKS actually observed, keyed@@ -9546,7 +10477,9 @@ LTX_MEASURED_ETA: dict[tuple[str, str, str, str], tuple[float, str]] = {# exist for them._LTX_TIER_HIGH_NOTE_BASE = ("High runs a second, larger pass over the first one — sharper detail and "- "steadier motion, for roughly twice the wait."+ "steadier motion, for roughly twice the wait. Same 1024×576 canvas as "+ "Balanced, not Standard's bigger 1280×704 — the extra pass buys "+ "detail, not size; pick High · 720p for both.")# The 49.70 GiB peak belongs to the 720p canvas it was measured on, not to# High — attaching it here told every High user they needed a 64 GB Mac for a@@ -9731,8 +10664,38 @@ def _ltx_qualities() -> dict[str, dict]:"offered": "q8" in version_cap_tiers(),},}+ # VC-02/SYS-05: chips must say what THIS MAC will actually render. On a+ # Compact-tier (<48 GB) Mac the distilled canvases above (Balanced+ # 1024x576, Standard 1280x704) get clamped a second time, deep in+ # run_job_inner, to the hardware's t2v/i2v cap — the chip kept advertising+ # the unclamped size while the Queue row showed the real, and until the+ # ltx_fit_canvas fix above, aspect-mangled one (2:1 instead of 16:9).+ # Baking the SAME clamp in here, once, means every reader of this table —+ # the chip strip, the footer estimate, the sidecar — sees the one true+ # canvas, and run_job_inner's own clamp becomes the backstop it was+ # always meant to be (custom W×H, a stale client, an old sidecar replay)+ # rather than the thing silently overriding what the user picked. The HQ+ # pipeline (High / High · 720p) is untouched: Q8 is refused outright+ # below 48 GB (allows_q8=False), and every tier that DOES allow Q8 has no+ # t2v/i2v clamp at all (CAPABILITIES: standard/high/pro all carry+ # t2v_max_dim 0).+ _t2v_cap = int(SYSTEM_CAPS.get("t2v_max_dim", 0))for q in out.values():q.setdefault("note", "")+ # The canvas this key's LTX_MEASURED_ETA rows were timed at, kept+ # before any clamp below (4.17 Codex EST-13): a clamped cell may only+ # SCALE from that measurement, never claim it.+ q["native_width"], q["native_height"] = q["width"], q["height"]+ if (_t2v_cap and q.get("pipeline") != "hq"+ and max(q["width"], q["height"]) > _t2v_cap):+ _cw, _ch = ltx_fit_canvas(q["width"], q["height"], _t2v_cap)+ if (_cw, _ch) != (q["width"], q["height"]):+ q["width"], q["height"] = _cw, _ch+ _clamp_note = (f"{SYSTEM_CAPS['label']} Mac: renders at "+ f"{_cw}×{_ch}, not the full-size canvas — "+ f"this Mac's memory limit.")+ q["note"] = (f"{q['note']} {_clamp_note}".strip()+ if q["note"] else _clamp_note)q["aspect"] = _h3_aspect(q["width"], q["height"])q["canvas"] = f"{q['width']}×{q['height']}"return out@@ -9758,18 +10721,28 @@ def _ltx_lengths() -> dict[str, dict]:publishes and the one storyboard.ltx_frames_for() already computes. 20 s isthe ceiling because it is the longest render anyone has confirmed holdingtogether (issue #46, @blackest, 640×480 × 481f)."""+ # VC-23: these used to read "One short beat." / "One full beat." / "A+ # beat with room to land." — evocative, but "beat" is a screenwriting+ # term nobody outside that craft uses, and short idioms translate+ # worse than a plain sentence naming the duration and what it's for.out: dict[str, dict] = {"3s": {"key": "3s", "label": "3s", "order": 0, "seconds": 3,- "frames": 73, "blurb": "One short beat.", "offered": True},+ "frames": 73, "blurb": "A quick 3-second clip.", "offered": True},"5s": {"key": "5s", "label": "5s", "order": 1, "seconds": 5,- "frames": 121, "blurb": "The default — one full beat.",+ # VC-11/28: "The default" used to live in THIS text, so it was+ # concatenated onto every quality's 5s cell (Quick·5s, High·5s,+ # ...) — a chip that isn't the default calling itself one.+ # "The default" is now stamped only on the one cell that+ # actually is (LTX_QUALITY_DEFAULT × LTX_LENGTH_DEFAULT), in+ # _build_ltx_tiers() below.+ "frames": 121, "blurb": "A full 5-second clip.","offered": True},"7s": {"key": "7s", "label": "7s", "order": 2, "seconds": 7,- "frames": 169, "blurb": "A beat with room to land.",+ "frames": 169, "blurb": "7 seconds — room for the shot to play out.","offered": True},"10s": {"key": "10s", "label": "10s", "order": 3, "seconds": 10,"frames": 241,- "blurb": "Long for one shot. Motion drifts at the tail.",+ "blurb": "10 seconds — motion can blur or drift near the end.","note": LTX_TIER_LONG_NOTE, "offered": True},# Offered on Quick ONLY, because that is exactly what the field report# says: 640×480 fine at 481 frames, 1024×576 dies around frame 454,@@ -9778,7 +10751,7 @@ def _ltx_lengths() -> dict[str, dict]:# every canvas."20s": {"key": "20s", "label": "20s", "order": 4, "seconds": 20,"frames": 481,- "blurb": "The longest anyone has confirmed holding together, "+ "blurb": "The longest clip that reliably holds together, ""and only at Quick.","note": LTX_TIER_LONG_NOTE,"qualities": ("quick",), "offered": True},@@ -9812,14 +10785,52 @@ def _build_ltx_tiers() -> dict[str, dict]:key = f"{q['key']}_{ln['key']}"w, h = int(q["width"]), int(q["height"])frames = int(ln["frames"])+ # VC-01: every measured/anchored row below is an M4 Max wall+ # clock (or a ratio taken between two model calls that share the+ # same factor and so cancel it out), and NEITHER path used to+ # multiply by this Mac's own speed — every chip saw the M4 Max+ # number. `hw` is applied once, explicitly, on every branch, the+ # same idiom _h3_speed_factor already uses for H3's tiers.+ hw = _ltx_speed_factor()eta_min = ltx_estimate_minutes(w, h, frames, int(q["stage1"]), int(q["stage2"]),int(q.get("stage2_evals") or 1))eta, eta_measured = _fmt_eta(eta_min), False+ # 4.17 Codex EST-13: the measured rows are keyed by quality, and+ # a quality's canvas can be clamped on this Mac (Compact renders+ # Balanced AND Standard at 768×448 — same canvas, same schedule).+ # Reading each key's own full-size row priced two identical+ # renders 2.7 vs 3.8 min and called both "measured". A clamped+ # cell prices from the measurement of the SAME-schedule quality+ # whose timed canvas is nearest its own (so equal recipes get+ # equal prices), scaled by the model's ratio between the two+ # canvases — and is not "measured".+ nw = int(q.get("native_width") or w)+ nh = int(q.get("native_height") or h)+ native = (nw, nh) == (w, h)+ ref_key, geo = q["key"], 1.0+ if not native:+ _sched = (q["pack"], q["pipeline"], int(q["stage1"]), int(q["stage2"]),+ int(q.get("stage2_evals") or 1))+ _peers = [o for o in LTX_QUALITIES.values()+ if (o["pack"], o["pipeline"], int(o["stage1"]), int(o["stage2"]),+ int(o.get("stage2_evals") or 1)) == _sched]+ _ref = min(_peers or [q], key=lambda o: (+ abs(int(o.get("native_width") or o["width"])+ * int(o.get("native_height") or o["height"]) - w * h),+ int(o.get("order") or 0)))+ ref_key = _ref["key"]+ nw = int(_ref.get("native_width") or _ref["width"])+ nh = int(_ref.get("native_height") or _ref["height"])+ _m_native = ltx_estimate_minutes(+ nw, nh, frames, int(q["stage1"]), int(q["stage2"]),+ int(q.get("stage2_evals") or 1))+ geo = (eta_min / _m_native) if _m_native > 0 else 1.0hit = LTX_MEASURED_ETA.get(- (version_id, q["key"], ln["key"], q["pack"]))+ (version_id, ref_key, ln["key"], q["pack"]))if hit:- eta_min, eta, eta_measured = hit[0], hit[1], True+ eta_min, eta_measured = hit[0] * hw * geo, native+ eta = hit[1] if (hw == 1.0 and native) else _fmt_eta(eta_min)else:# No measurement at this exact geometry — but if this QUALITY# has a measured 5s row, scale that anchor by the model's own@@ -9829,20 +10840,44 @@ def _build_ltx_tiers() -> dict[str, dict]:# 161.8 s measured vs 96.7 s modelled); those biases are# per-quality and roughly proportional across lengths, so the# ratio cancels them to first order. eta_measured stays False- # — this is still an estimate, just an anchored one.+ # — this is still an estimate, just an anchored one. Both+ # `eta_min` and `model_5s` already carry `hw` (same factor,+ # same call), so it cancels in the ratio — multiply the+ # anchor by `hw` explicitly or every anchored cell is priced+ # at the M4 Max number again.anchor = LTX_MEASURED_ETA.get(- (version_id, q["key"], "5s", q["pack"]))+ (version_id, ref_key, "5s", q["pack"]))if anchor and ln["key"] != "5s":+ # At the canvas the anchor was TIMED at (EST-13): on a+ # clamped cell the ratio then carries the canvas change+ # as well as the length change.model_5s = ltx_estimate_minutes(- w, h, int(LTX_LENGTHS["5s"]["frames"]),+ nw, nh, int(LTX_LENGTHS["5s"]["frames"]),int(q["stage1"]), int(q["stage2"]),int(q.get("stage2_evals") or 1))if model_5s > 0:- eta_min = anchor[0] * (eta_min / model_5s)+ eta_min = anchor[0] * hw * (eta_min / model_5s)eta = _fmt_eta(eta_min)allowed = ln.get("qualities") or ()restricted = bool(allowed) and q["key"] not in allowednotes = [n for n in (q["note"], ln["note"]) if n]+ # VC-11: "Quick" saves nothing at 5s — the per-forward and decode+ # floors that make Quick 5s a MEASURED row in the first place+ # (see LTX_MEASURED_ETA above) put it within a second of+ # Balanced's own measured 5s row, while Quick also renders a+ # smaller, non-16:9 canvas (640x448 vs Balanced's 1024x576). A+ # user scouting composition on Quick gets a worse, differently-+ # framed clip for no time saved, and the chip used to say+ # nothing about it. Comparing against Balanced's OWN row (not a+ # hardcoded threshold) keeps this honest if the schedules ever+ # change relative speed again.+ if q["key"] == "quick" and ln["key"] != "20s":+ _bal = LTX_MEASURED_ETA.get((version_id, "balanced", ln["key"], "q4"))+ if _bal and eta_min > 0 and eta_min >= _bal[0] * hw * 0.9:+ notes.append(+ f"No faster than Balanced at {ln['label']} — Quick's "+ f"real time saving is on 20s clips."+ )# 'fast' preset pricing — stamped ONLY on cells that can run it# (2.5 + distilled), which is also how the client gates the# control: a cell without fast_eta offers no Fast draft, so the@@ -9877,7 +10912,16 @@ def _build_ltx_tiers() -> dict[str, dict]:"preview_meaningful_at": int(q["preview_meaningful_at"]),"eta": eta, "eta_min": round(eta_min, 2),"eta_measured": eta_measured,- "blurb": f"{q['blurb']} {ln['blurb']}".strip(),+ # VC-11: "The default" used to live in the LENGTH blurb+ # ("The default -- one full beat."), so it was concatenated+ # onto EVERY quality's blurb at 5s — Quick's chip claimed to+ # be "The default" too. Stamped here, once, only on the cell+ # that actually IS both the default quality and the default+ # length.+ "blurb": (f"{q['blurb']} {ln['blurb']}".strip()+ + (" The default." if (q["key"] == LTX_QUALITY_DEFAULT+ and ln["key"] == LTX_LENGTH_DEFAULT)+ else "")),"notes": notes,"note": " ".join(notes),"offered": bool(q["offered"] and ln["offered"] and not restricted),@@ -9895,10 +10939,108 @@ def _build_ltx_tiers() -> dict[str, dict]:f"end. Smaller canvases hold together longer."if restricted else ""),}+ # Owner ruling (2026-09-29): "If we have the fleet data, we can+ # provide proper time estimations, or at least a range." — real+ # fleet renders where there are enough of them, layered on top+ # of the cost-model point estimate above (kept as eta/eta_min+ # either way, for every existing reader). t2v is the+ # representative mode: the cost model prices t2v and i2v+ # identically (VC-12), and the tier table is shared across both.+ fleet = fleet_calibrated_range("ltx", "t2v", q["key"], frames,+ speed="")+ if fleet:+ tiers[key]["fleet_range"] = fleetreturn tiersLTX_TIERS: dict[str, dict] = _build_ltx_tiers()+_ETA_CAL_PRICED["ltx"] = _eta_calibration_factor("ltx") # the factor LTX_TIERS was priced with+++# VA-11 / VA-12 / VC-12 / SYS-20: Keyframe (FFLF) and Extend each run a+# DIFFERENT pipeline than the Quality strip's cells — keyframe always renders+# at Q8 two-stage HQ (LTX_HQ_STAGE1/2) regardless of the `quality` the UI+# shows, and both clamp their canvas to this tier's own max-dim+# (tier_max_dim) at RUN TIME. Before this pair of functions, the ONLY prices+# either mode showed were the hand-typed CAPABILITIES["...]["times"] strings+# — one hardcoded number per RAM TIER, oblivious to chip speed, and+# disagreeing with both the real clamp and the real step count. These reuse+# the SAME cost model (ltx_estimate_minutes) the honest Quality-strip chips+# now use (VC-01), at the geometry and step count that actually runs.+def ltx_keyframe_estimate_minutes(frames: int, width: int | None = None,+ height: int | None = None) -> tuple[int, int, float]:+ """(clamped width, clamped height, minutes) for a keyframe/FFLF render on+ THIS Mac's tier — mirrors the exact clamp run_job_inner applies+ (tier_max_dim("keyframe")) and the fixed Q8 two-stage step count+ (quality is always "high" for this mode, independent of the UI pill)."""+ w = int(width or LTX_QUALITIES["balanced"]["width"])+ h = int(height or LTX_QUALITIES["balanced"]["height"])+ kf_max = tier_max_dim("keyframe")+ if kf_max and max(w, h) > kf_max:+ w, h = ltx_fit_canvas(w, h, kf_max)+ minutes = ltx_estimate_minutes(w, h, int(frames), LTX_HQ_STAGE1, LTX_HQ_STAGE2)+ return w, h, minutes+++def ltx_extend_estimate_minutes(extend_frames: int, steps: int = 8,+ width: int | None = None,+ height: int | None = None) -> tuple[int, int, float]:+ """(clamped width, clamped height, minutes) for an Extend render on THIS+ Mac's tier — mirrors tier_max_dim("extend") and the validated 8-step+ default (owner ruling 2026-05-21; the UI's old "Draft = 12 steps" pill+ was 50% slower than what actually ships — VA-12). `extend_frames` is+ LATENT frames (each = 8 video frames, the same unit the extend_frames+ form field uses); the dev transformer runs one pass over the SOURCE+ clip's own length plus the added frames, so this prices the delivered+ clip at a representative 121-frame (5 s) source — the number is a+ per-added-second rate, not tied to any one source length."""+ w = int(width or LTX_QUALITIES["balanced"]["width"])+ h = int(height or LTX_QUALITIES["balanced"]["height"])+ ext_max = tier_max_dim("extend")+ if ext_max and max(w, h) > ext_max:+ w, h = ltx_fit_canvas(w, h, ext_max)+ added_frames = max(1, int(extend_frames)) * 8+ total_frames = int(LTX_LENGTHS["5s"]["frames"]) + added_frames+ minutes = ltx_estimate_minutes(w, h, total_frames, max(1, int(steps)), 0)+ return w, h, minutes+++def ltx_a2v_estimate_minutes(frames: int, width: int | None = None,+ height: int | None = None) -> tuple[int, int, float, bool]:+ """(clamped width, clamped height, minutes, uses_q8) for an+ Audio->Video render on THIS Mac — VA-06: the A2V footer showed NO time+ estimate at all (the #audioStudioEstimate span existed and nothing+ wrote to it). Mirrors run_job_inner's a2v branch exactly: Q8 two-stage+ (20+3 steps) when the Q8 pack is present, else the Q4 distilled+ pipeline (8+3), clamped to tier_max_dim("t2v") like the render itself."""+ w = int(width or LTX_QUALITIES["balanced"]["width"])+ h = int(height or LTX_QUALITIES["balanced"]["height"])+ max_dim = tier_max_dim("t2v")+ if max_dim and max(w, h) > max_dim:+ w, h = ltx_fit_canvas(w, h, max_dim)+ uses_q8 = bool(SYSTEM_CAPS.get("allows_q8")) and not hq_surface_missing()+ stage1, stage2 = (20, 3) if uses_q8 else (8, 3)+ minutes = ltx_estimate_minutes(w, h, int(frames), stage1, stage2)+ return w, h, minutes, uses_q8+++def ltx_a2v_price(frames: int, width: int | None = None,+ height: int | None = None) -> dict:+ """The Audio -> Video price GET /a2v/estimate shows — fleet first, the+ model only scaling the fleet's range to a canvas other than the default+ one the fleet mostly rendered (4.17 integration). One function so the+ queue row prices an A2V job with the SAME number (4.17 Codex EST-5)."""+ w, ht, minutes, uses_q8 = ltx_a2v_estimate_minutes(frames, width=width, height=height)+ eta, basis = _fmt_eta(minutes), "estimated"+ fleet = fleet_calibrated_range("ltx", "a2v", "high" if uses_q8 else "balanced", frames)+ if fleet:+ ref = ltx_a2v_estimate_minutes(frames)[2] or minutes or 1.0+ r = (minutes / ref) if ref else 1.0+ eta = _fmt_eta_range(fleet["p25_min"] * r, fleet["p75_min"] * r)+ minutes = fleet["p50_min"] * r+ basis = fleet["basis"]+ return {"width": w, "height": ht, "minutes": round(minutes, 2), "eta": eta,+ "basis": basis, "pack": "q8" if uses_q8 else "q4"}TAE_CHECKPOINT = MODELS_DIR / "tae" / "taeltx2_3.safetensors"@@ -10035,7 +11177,13 @@ def pack_offers(version_id: str | None = None) -> dict:"size": (f"{gb:g} GB" if isinstance(gb, (int, float)) else "?"),# Same registry-derived answer the Models modal uses, so a CTA# cannot disable a download the modal would happily start.- "needs_hf": not bool(r.get("mirror"))}+ "needs_hf": not bool(r.get("mirror")),+ # SYS-11: without this, the "Base models needed" card had no+ # way to tell WHICH of base/encoder was actually incomplete —+ # it named both unconditionally, even when only one file from+ # one pack was missing. `base_missing` entries are+ # `<local_dir>/<file>`, so the card can filter by prefix.+ "local_dir": r.get("local_dir")}base_key = (version_pack("q4", ver["id"]) or {}).get("repo_key")q8_key = (version_pack("q8", ver["id"]) or {}).get("repo_key")@@ -10055,10 +11203,27 @@ def q8_character_install_copy(version_id: str | None = None) -> str:surfaces (Manual Character and Storyboard cast). Values originate in thelocal registry, but are escaped anyway so a future pack label cannot turninto markup by accident.++ SYS-18: this used to offer the "Install {name} ({size}) ->" link on every+ Mac unconditionally — including ones the panel's own tier table already+ refuses Q8 on (`SYSTEM_CAPS["allows_q8"]`, the same gate the High quality+ chip and pinokio.js's `q8Capable()` use). A Compact-tier user could click+ through, sit through a 30+ GB download, and land back on the exact+ approximate-face render they started with, because run_job_inner refuses+ HQ on their hardware regardless. Below the threshold this now says why,+ with the real floor, and drops the dead CTA instead of dangling it."""offer = pack_offers(version_id).get("q8") or {}name = html.escape(str(offer.get("name") or "Q8 weights"))size = html.escape(str(offer.get("size") or "?"))+ if not SYSTEM_CAPS.get("allows_q8"):+ floor = min_ram_gb_for("allows_q8") or 48+ return (+ f"<b>Trained characters render sharpest with {name}.</b> This "+ f"{SYSTEM_CAPS.get('label', 'Mac')} doesn't have enough memory for it "+ f"({name} needs {floor} GB or more) — the trained face renders on the "+ "base pack instead, which is a real result, just softer on fine detail."+ )return (f"<b>Trained characters need {name}.</b> Right now this Mac has the ""base pack, so the trained face comes out approximate. "@@ -10233,6 +11398,252 @@ def ltx_compose_tier(quality: str | None, length: str | None) -> str | None:return key if key in LTX_TIERS else None+def _ltx_length_key_for_frames(frames: object) -> str | None:+ """The length axis is keyed by name ("5s"), a queued job's params only+ carry the resolved `frames` count — this is the inverse lookup, used+ once per queue row by job_priced_eta_sec() below."""+ try:+ f = int(frames)+ except (TypeError, ValueError):+ return None+ for ln in LTX_LENGTHS.values():+ if int(ln["frames"]) == f:+ return str(ln["key"])+ return None+++def _job_i2v(params: dict) -> bool:+ return str((params or {}).get("mode") or "").strip().lower() == "i2v"+++def job_recipe_minutes(params: dict, *, calibration: bool = False) -> tuple[str, float] | None:+ """(engine, minutes) — the price of the render these params actually+ describe, read from the SAME numbers the pre-submit controls show+ (4.17 Codex EST-2 / EST-5). One function, two readers:++ * the queue (job_priced_eta_sec): every row and the queue total. It+ used to read only the quality × length cell, so a Fast H3 job, a+ Fast-draft LTX job, an Extend / Keyframe / Audio -> Video job all+ showed the default T2V cell's price.+ * self-calibration (calibration=True): only recipes whose price IS the+ tier table's own model number — the thing the calibration factor+ corrects. A fleet-first price card (Keyframe, Extend, Audio -> Video),+ a canvas other than the cell's own, a pinned step count, sliding+ windows, a 12 fps interpolated render or a model upscale pass is a+ different workload; letting it in turns a recipe difference into a+ machine-wide speed correction.++ None (never a guess) when the recipe can't be priced reliably."""+ p = params or {}+ mode = str(p.get("mode") or "t2v").strip().lower()+ if mode in ("image", "train", "upscale", "sharp_export", "music"):+ return None+ engine = str(p.get("engine") or "ltx").strip().lower()+ if engine == "music":+ return None+ if engine == "h3":+ key = h3_resolve_tier(str(p.get("h3_tier") or "")) or h3_compose_tier(+ p.get("h3_quality"), p.get("h3_length"))+ cell = H3_TIERS.get(key) if key else None+ if not cell:+ return None+ if calibration and p.get("take"):+ return None # a One Shot is many renders and joins+ try:+ pinned = int(p.get("h3_steps") or 0)+ except (TypeError, ValueError):+ return None+ # make_job's own precedence: Fast, then Turbo, then a pinned count.+ fast = bool(p.get("h3_tristep")) and cell.get("tristep_min") is not None+ if fast:+ # Fast is priced by its OWN number (Codex H3-4), per mode where a+ # receipt says T2V and I2V differ — engines.js _h3TriStepMin.+ minutes = (cell.get("tristep_min_i2v")+ if _job_i2v(p) and cell.get("tristep_min_i2v") is not None+ else cell.get("tristep_min"))+ elif p.get("h3_turbo"):+ minutes = cell.get("turbo_min")+ elif pinned:+ if calibration:+ return None # a workload no cell prices (Codex H3-4)+ win = max(1, int(cell.get("chain_windows") or 1))+ fwd = max(1, pinned - 1)+ minutes = (win * fwd * float(cell.get("per_forward_sec") or 0)+ + win * float(cell.get("fixed_sec") or 0)) / 60.0+ else:+ minutes = cell.get("eta_min")+ return ("h3", float(minutes)) if minutes else None+ if engine != "ltx":+ return None+ try:+ frames = int(p.get("frames") or 0)+ width = int(p.get("width") or 0) or None+ height = int(p.get("height") or 0) or None+ except (TypeError, ValueError):+ return None+ if mode in ("keyframe", "extend", "a2v"):+ # Fleet-first price cards: not the model number calibration corrects.+ if calibration:+ return None+ if mode == "a2v":+ if frames <= 0:+ return None+ return "ltx", float(ltx_a2v_price(frames, width, height)["minutes"])+ if mode == "keyframe":+ card = ltx_mode_price_card("keyframe", frames=frames or None,+ width=width, height=height)+ else:+ try:+ steps = int(p.get("extend_steps") or 8)+ latents = int(p.get("extend_frames") or 5)+ except (TypeError, ValueError):+ return None+ card = ltx_mode_price_card("extend", steps=steps, extend_frames=latents)+ return ("ltx", float(card["eta_min"])) if card and card.get("eta_min") else None+ if mode not in ("t2v", "i2v", "i2v_clean_audio"):+ return None # retake, restore, ingredients, control, ...+ length_key = _ltx_length_key_for_frames(frames)+ key = ltx_compose_tier(p.get("quality"), length_key) if length_key else None+ cell = LTX_TIERS.get(key) if key else None+ if not cell or not cell.get("eta_min"):+ return None+ minutes = float(cell["eta_min"])+ if str(p.get("schedule_preset") or "").strip().lower() == "fast":+ if cell.get("fast_min") is None:+ return None+ minutes = float(cell["fast_min"])+ if calibration:+ if (str(p.get("long_mode") or "native") != "native"+ or str(p.get("temporal_mode") or "native") != "native"+ or str(p.get("upscale") or "off") == "x2"+ or (str(p.get("upscale") or "off") != "off"+ and str(p.get("upscale_method") or "lanczos") == "pipersr")):+ return None+ cw, ch = int(cell["width"]), int(cell["height"])+ if width and height and sorted((width, height)) != sorted((cw, ch)):+ # Another canvas (1:1, 4:5, a custom W×H): the cell does not price it.+ if calibration:+ return None+ q = LTX_QUALITIES.get(str(cell.get("quality") or "")) or {}+ s1, s2 = int(q.get("stage1") or 0), int(q.get("stage2") or 0)+ ev = int(q.get("stage2_evals") or 1)+ here = ltx_estimate_minutes(width, height, frames, s1, s2, ev)+ ref = ltx_estimate_minutes(cw, ch, frames, s1, s2, ev)+ if not (here > 0 and ref > 0):+ return None+ minutes *= here / ref+ return "ltx", minutes+++def job_priced_eta_sec(params: dict) -> float | None:+ """VC-26: a precise per-queued-job ETA, read from the SAME priced+ numbers the pre-submit controls show (job_recipe_minutes — the actual+ recipe: speed, mode, schedule, canvas) instead of the coarse per-kind+ average /status already falls back to for anything this can't price.+ Returns None (never a guess) for image, train, upscale, sharp_export,+ music jobs, or a frame count that isn't on either axis (a power-user+ custom duration) — those keep the existing average-based estimate in+ routes_queue.py's _eta_for()."""+ hit = job_recipe_minutes(params)+ return hit[1] * 60.0 if hit and hit[1] > 0 else None+++#: VC-13: a light, reliable signal for "this prompt is not in a Latin-script+#: language" — used for the prompt box's language hint and Enhance's+#: translate toggle. Deliberately narrow: French/Spanish/German etc. stay+#: Latin-script and are NOT flagged, because telling "English" apart from+#: another Latin-script language by character range alone is unreliable and+#: would misfire on ordinary accented text. CJK / Hangul / Cyrillic / Arabic+#: / Hebrew / Thai are unambiguous.+_NON_LATIN_SCRIPT_RE = re.compile(+ "[-ヿ㐀-䶿一-鿿가-" # Hiragana/Katakana, CJK, Hangul+ "Ѐ-ӿ-ۿ--]" # Cyrillic, Arabic, Hebrew, Thai+)+++def prompt_looks_non_latin(text: str) -> bool:+ """See _NON_LATIN_SCRIPT_RE."""+ return bool(_NON_LATIN_SCRIPT_RE.search(text or ""))+++def current_render_busy_reason() -> str:+ """VC-16: what Enhance's GPU-conflict refusal says instead of the flat+ "A render is using the GPU right now." The single in-process _GPU_LOCK+ (worker_loop) covers every engine's whole job — including sending a+ concurrent request into the SAME warm-helper subprocess a render is+ mid-generate on, which the helper's stdin/stdout protocol isn't built+ to interleave — so there is no genuinely safe window to run Enhance+ DURING an active render on this architecture. What VC-16 asks for+ ("stays available... otherwise it says why") is delivered honestly+ here: a real reason instead of a generic one, naming what is+ rendering and — when the priced tier table (VC-28/VC-26) can price it+ — how much longer."""+ cur = STATE.get("current")+ if not cur:+ return "A render is using the GPU right now."+ p = cur.get("params") or {}+ _prompt = (p.get("prompt") or "").strip()+ label = ((p.get("label") or "").strip()+ or (_prompt[:40] + "…" if len(_prompt) > 40 else _prompt)+ or "A render")+ eta_sec = job_priced_eta_sec(p)+ tail = ""+ started_ts = cur.get("started_ts")+ if eta_sec and started_ts:+ remaining = eta_sec - (time.time() - float(started_ts))+ if remaining > 20:+ tail = f", about {max(1, round(remaining / 60))} min left"+ elif remaining > 0:+ tail = ", almost done"+ return f"“{label}” is rendering{tail}."+++def _ltx_price_delivered_size_and_time_range(tiers: list[dict]) -> None:+ """VC-28: the chip's canvas is the RENDER size, which is not always what+ lands on disk — Balanced defaults to a `fit_720p` export (1024x576 ->+ 1280x720), the same gap VC-19 closed for the info modal after the fact.+ Priced here (a request-time helper, never called at LTX_TIERS' own+ import-time build) so the chip tells the truth before Generate is+ clicked, not after — compute_upscale_plan is defined later in this file+ and is unreachable from module-level code.++ Also stamps the honest "The default" (VC-11/28: it used to live in the+ 5s length's own blurb, so it was concatenated onto every quality's 5s+ cell, not only the one that actually is the default) and a time RANGE+ beside the point estimate — modelled cells bias optimistic (see+ LTX_MEASURED_ETA's own commentary above), so their range skews upward;+ a real measurement gets a narrow +/-10% band instead. Mutates `tiers`+ in place; each entry is already this function's caller's own copy."""+ for t in tiers:+ default_upscale = "fit_720p" if t["quality"] == "balanced" else "off"+ plan = compute_upscale_plan(t["width"], t["height"], default_upscale)+ t["delivered_width"] = plan["target_w"] if plan else t["width"]+ t["delivered_height"] = plan["target_h"] if plan else t["height"]+ t["delivered_spec"] = f"{t['delivered_width']}×{t['delivered_height']}"+ t["delivered_differs"] = bool(plan)+ eta_min = float(t.get("eta_min") or 0)+ if eta_min > 0:+ lo, hi = ((eta_min * 0.9, eta_min * 1.1) if t.get("eta_measured")+ else (eta_min, eta_min * 1.4))+ t["eta_range"] = _fmt_eta_range(lo, hi)+ is_default = (t["quality"] == LTX_QUALITY_DEFAULT+ and t["length"] == LTX_LENGTH_DEFAULT)+ t["is_default"] = is_default+ if is_default:+ t["blurb"] = ("The default. " + t["blurb"]).strip()+++def _ltx_price_delivered_quality_canvases(qualities: list[dict]) -> None:+ """The per-quality sibling of the above — same delivered-size question,+ asked once per canvas instead of once per (quality x length) cell, for+ the quality strip's own chip (which prices against `item.canvas`, not a+ cell). Mutates `qualities` in place."""+ for q in qualities:+ default_upscale = "fit_720p" if q["key"] == "balanced" else "off"+ plan = compute_upscale_plan(int(q["width"]), int(q["height"]), default_upscale)+ q["delivered_canvas"] = f"{plan['target_w']}×{plan['target_h']}" if plan else q["canvas"]++def ltx_tiers_payload() -> dict:"""The LTX table as the page sees it.@@ -10272,10 +11683,13 @@ def ltx_tiers_payload() -> dict:f"upscaler stage doesn't fit in this Mac's memory. "f"Standard and Quick run here; High needs "f"{min_ram_gb_for('allows_q8') or 48} GB or more.")+ _ltx_price_delivered_size_and_time_range(tiers) # VC-28+ qualities = [dict(q) for q in sorted(+ LTX_QUALITIES.values(), key=lambda x: x["order"]) if q["offered"]]+ _ltx_price_delivered_quality_canvases(qualities) # VC-28return {"tiers": tiers,- "qualities": [dict(q) for q in sorted(- LTX_QUALITIES.values(), key=lambda x: x["order"]) if q["offered"]],+ "qualities": qualities,"lengths": [dict(l) for l in sorted(LTX_LENGTHS.values(), key=lambda x: x["order"]) if l["offered"]],"default_quality": LTX_QUALITY_DEFAULT,@@ -11319,9 +12733,17 @@ def h3_turbo_status() -> dict:# claims idle while a fetch is streaming."install_available": bool(supported),"installing": _h3_turbo_dl_state.get("status") == "downloading",- "install_note": (f"Downloads the digest-pinned {H3_TURBO_LORA_FILE} "- f"release asset (~{H3_TURBO_DOWNLOAD_GB} GB); raw "- f"{H3_TURBO_RAW_V01_FILE} is not compatible."),+ # H3-29: this named H3_TURBO_LORA_FILE (the retired v1.0 LightX2V+ # GitHub release asset) unconditionally, while the actual one-click+ # install (_h3_turbo_asset() with no key) has fetched+ # H3_TURBO_DEFAULT_ASSET = "v4-600-EMA" straight from its author's HF+ # repo since 2026-09-05 — a different file, a different host, a+ # different download mechanism than the sentence described. Read the+ # SAME resolver the install action uses so the two can't diverge again.+ "install_note": (lambda _a: (+ f"Downloads {_a['file']} from {H3_TURBO_V4_REPO} on Hugging Face "+ f"(~{H3_TURBO_DOWNLOAD_GB} GB, checksum-verified)."+ ))(_h3_turbo_asset()),"dir": str(paths["dir"]),"missing": paths["missing"],"note": h3_turbo_note(paths),@@ -13056,6 +14478,51 @@ def h3_normalize_chain_prompts(raw, windows: int) -> list[str]:return out if any(out) else []+def h3_compose_window_prompts(prompt: str, asked: list, windows: int) -> list[str]:+ """H3-06: what actually gets sent to the runner for each chained window.++ Before this, a typed window box REPLACED the main prompt outright — a+ beat like "he raises his glass" lost the subject, setting, soundscape+ and any LoRA trigger words the main prompt carried, risking identity+ drift across a 10-27 minute chained render (LTX's own windowed path has+ a shared-text field for exactly this; H3 didn't).++ Now every non-empty box is SHARED TEXT + BEAT: `f"{prompt} {beat}"`. An+ empty box still falls back to the bare main prompt (a blank box has+ always meant "use the main prompt", and the runner refuses an empty+ window prompt outright). A box that happens to equal the main prompt+ verbatim is not doubled.+ """+ prompt = (prompt or "").strip()++ def _compose(beat) -> str:+ beat = ("" if beat is None else str(beat)).strip()+ if not beat or beat == prompt:+ return prompt+ return f"{prompt} {beat}"++ filled = [_compose(x) for x in list(asked or [])[:windows]]+ filled += [prompt] * (windows - len(filled))+ return filled+++def h3_window_prompts_for_job(prompt: str, asked: list, windows: int, *,+ complete: bool = False) -> list[str]:+ """The per-window prompts a job sends. A person's typed window boxes are+ BEATS that add to the main prompt (H3-06, h3_compose_window_prompts); a+ caller that already builds WHOLE per-window prompts — a One Shot's beats,+ a storyboard shot's continuation chain — marks them `complete`, and they+ replace the main prompt as they always did (4.17 Codex H3-2: composing+ them repeated window 1's action and dialogue in every later window).+ A blank entry falls back to the main prompt either way."""+ prompt = (prompt or "").strip()+ if not complete:+ return h3_compose_window_prompts(prompt, asked, windows)+ items = [("" if x is None else str(x)).strip() for x in list(asked or [])[:windows]]+ items = [x or prompt for x in items]+ return items + [prompt] * (windows - len(items))++_H3_EXPORT_NOTES: dict[tuple[int, int], dict[str, str]] = {}@@ -13081,12 +14548,17 @@ def _h3_export_notes(w: int, h: int) -> dict[str, str]:_cap = 0_sc = min(2.0, _cap / float(max(w, h))) if _cap else 2.0_tw, _th = ltx_floor_canvas(int(w * _sc), int(h * _sc))- out[mode] = (f"{FACE_FIX_NAME}: after the draft, a second job re-renders it at "+ # H3-26: this said "after the draft" / "the draft's time again"+ # unconditionally, but h3FaceFixAfterRow is shown whenever+ # H3.upscale_modes allows ltx_x2 — not only on the Draft tier —+ # so a Standard or High render offering this checkbox got copy+ # naming the wrong tier.+ out[mode] = (f"{FACE_FIX_NAME}: after this render, a second job re-renders it at "f"{_tw}×{_th} with LTX-2.5 detail, keeps the face and the sound, and "- "lands beside the draft. "+ "lands beside it. "+ (f"About {FACE_FIX_DRAFT_5S_MIN:g} min more for a 5 s Draft."if (int(w), int(h)) == (640, 384) else- "About the draft's time again.")+ "About the same time again.")+ ("" if _adapter_ok else" Needs the 0.3 GB Upscale adapter first — Settings → Models."))continue@@ -13129,7 +14601,7 @@ def h3_visible_tiers() -> list[dict]:tab still cannot queue an unrenderable job."""out = []# The chained note is written for the install that HAS the fix ("open- # Per-window prompts below"). A pack whose runner predates+ # Per-window prompts above"). A pack whose runner predates# `--chain-prompts` has no such control, so it gets the original warning# instead — swapped here rather than in the browser because the cell's# `notes` list is the one place the text lives, and a JS-side string match@@ -13232,6 +14704,27 @@ def h3_status() -> dict:# The `?` copy for that control, so the sentence explaining the# mechanic lives next to the mechanic."chain_prompt_help": H3_CHAIN_PROMPT_HELP,+ # H3-07: the Video tab's dialogue word-budget counter reads THIS+ # number rather than a JS-side copy, so it can never disagree with+ # storyboard's own validator (docs/H3_ENGINE.md: "~2.4 words a+ # second... storyboard.SPEECH_WORDS_PER_SEC is the same budget the+ # board validator enforces").+ "speech_words_per_sec": storyboard.SPEECH_WORDS_PER_SEC,+ # H3-19: the worker already reads this same lock to HOLD the render+ # queue while a Pinokio-side build/install runs (_external_build_hold,+ # written by scripts/pinokio/h3_build_q8.sh for its whole duration) —+ # it just never told the UI why. Surfacing it turns "install/build+ # from the Pinokio sidebar" from a silent handoff into an in-panel+ # progress signal: the user starts it in Pinokio, then watches it+ # from here without babysitting the sidebar tab. Not a real in-panel+ # installer (the actual clone/venv/download still runs as a Pinokio+ # script, same as every other optional engine) — the honest middle+ # ground when triggering the install FROM inside the panel would mean+ # re-deriving Pinokio's own PATH/env resolution from scratch with no+ # way to validate it against a real ~75 GB install in this session.+ "external_build": (lambda _w: (+ {"active": True, "what": _w} if _w else {"active": False, "what": None}+ ))(_external_build_hold()),# H3 publishes its own versioned file schema rather than LTX's helper# event shape. `on` is the only fact the browser needs to promise a# warming stage before the first status file arrives; older optional@@ -14443,7 +15936,12 @@ ENGINES: tuple[dict, ...] = (# its own line — see `generation_from` below."label": "LTX","sublabel": "built in",- "tagline": "every mode, LoRAs, characters",+ # H3-16: this used to read "every mode, LoRAs, characters" — true, but+ # it implied LoRAs and audio were LTX-exclusive next to H3's own+ # tagline. Neither is: H3 has its own LoRA library, and LTX 2.3/2.5+ # already generate audio jointly in the same forward pass. Naming+ # both here so switching engines doesn't read as losing either.+ "tagline": "every mode · LoRAs, characters, its own joint audio",# Rendered as the chip's generation line and nowhere else. Read from the# ACTIVE version so a user pinned back with LTX_MODEL_VERSION=ltx23 sees# the truth rather than a constant. This is the one field in the table@@ -14476,7 +15974,10 @@ ENGINES: tuple[dict, ...] = ("id": "h3","label": "Hailuo H3","sublabel": "video + dialogue",- "tagline": "joint video + dialogue + sound. Text and Image only.",+ # H3-16: named the modes it lacks (Text and Image only) but not that+ # it takes LoRAs from its own library, the one real capability a+ # user comparing rows would want stated next to LTX's.+ "tagline": "joint video + dialogue + sound, its own LoRAs. Text and Image only.","mark": "eng-mark-h3","accent": "#FF2E9F","accent_dim": "rgba(255,46,159,0.14)",@@ -14803,6 +16304,28 @@ def _analytics_enabled() -> bool:return bool(get_settings().get("analytics_enabled", True))+def _analytics_is_test_rig() -> bool:+ """SYS-41: the owner's own dev machine, a release-gate run, or a+ clean-room test install all send REAL telemetry — unlike an agent's+ review worktree, which sets PHOSPHENE_ANALYTICS_DISABLED=1 and sends+ nothing. That's deliberate: verifying an event actually fires is part+ of testing it. But the fleet dashboard cannot tell those installs+ apart from real users, and they skew hard toward one machine class —+ the reviewer found ~410 "new installs that never rendered" reporting+ 64 GB, mostly the owner's own M4 Max, inflating 64 GB to the biggest+ RAM class and non-activation from ~32% to ~54%.++ PHOSPHENE_TEST_RIG=1 is the fix at the source: any of the owner's own+ worktrees, gate scripts, or clean-room installers sets it, every event+ from that run carries `test_rig: true`, and a fleet query excludes+ those rows with one `WHERE NOT test_rig` instead of an ad hoc "M4 Max+ + no-geo-or-IL" heuristic re-derived by hand each time (see+ sys-fleet/q.py in the flow-review folder for that heuristic — this+ replaces the need for it going forward, on every install that sets+ the var)."""+ return _optional_bool_env("PHOSPHENE_TEST_RIG") is True++def _analytics_key() -> str:"""Resolve the PostHog PROJECT key used for capture, in priority order:1. PHOSPHENE_ANALYTICS_KEY env var (maintainer / CI override)@@ -14864,6 +16387,27 @@ def _analytics_install_id() -> str:return new+def _bug_report_scrub_line(line: str) -> str:+ """Strip home-folder paths (which usually carry the macOS username, and+ that username is frequently the person's real name) from ONE line of a+ log tail bound for a public GitHub issue.++ SYS-12: `/panel/bug-context` used to hand back `STATE["log"][-50:]`+ verbatim into the description textarea — `_analytics_scrub_text` exists+ and does exactly this substitution, but was never applied here because+ it's built for a single-line telemetry string (truncates to line 1 and+ to ANALYTICS_STR_MAX chars), which would destroy a 50-line diagnostic+ tail. This reuses the SAME path regexes, per line, keeping every line+ and the tail's full diagnostic shape."""+ try:+ s = str(line or "")+ for rx in _ANALYTICS_PATH_RES:+ s = rx.sub("<path>", s)+ return s+ except Exception:+ return str(line or "")++def _analytics_scrub_text(text, secrets=()) -> str:"""Reduce free text to a safe one-line signature.@@ -15181,6 +16725,11 @@ def _analytics_capture(event: str, props: dict | None = None) -> None:"at": iso_now(),"utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),}+ # SYS-41: tag every event from a marked test rig — after cleaning,+ # so the whitelist pass can't drop it and it isn't subject to the+ # truncation rules meant for caller-supplied strings.+ if _analytics_is_test_rig():+ payload["props"]["test_rig"] = Trueexcept Exception:returntry:@@ -15326,6 +16875,13 @@ def _analytics_install_step(step: str, outcome: str, error_class: str = "") -> Nprops = {"step": step, "outcome": outcome, "version": running_version()}if error_class:props["error_class"] = error_class+ # SYS-16: "first_queue" vs "first_render" (render_completed's own+ # first_render prop) is the funnel this event exists to answer, and+ # the reviewer's own finding is that activation is LOWEST on the+ # machines that struggle most — but neither event carried a+ # hardware signal, so answering "per tier" needed a join against+ # app_boot by install_id. ram_gb here makes that a direct GROUP BY.+ props["ram_gb"] = int(round(SYSTEM_RAM_GB))_analytics_capture("install_step", props)except Exception: # noqa: BLE001pass@@ -15439,8 +16995,9 @@ def _analytics_job_secrets(job: dict) -> list:# sharp enough that a 8:19 -> 12:00 regression moves buckets (the old# 5-value duration_bucket could not see it — spec F7), far too coarse to be# a timing fingerprint. Numeric so PostHog's percentile aggregation works.-_ANALYTICS_WALL_LADDER = (15, 30, 45, 60, 90, 120, 180, 240, 300, 420,- 600, 900, 1200, 1800, 2400, 3600, 5400)+# ONE ladder: the fleet table's reader (_fleet_cell_seconds) must know the+# exact rungs these lower edges came from (4.17 Codex EST-4).+_ANALYTICS_WALL_LADDER = FLEET_WALL_SEC_LADDERdef _analytics_wall_sec_bucket(seconds):@@ -15480,7 +17037,15 @@ def _analytics_source(p: dict, job: dict | None = None) -> str:_ANALYTICS_FEATURES = ("storyboard_plan", "storyboard_export", "editor_open","editor_export", "civitai_download", "sample_character",- "train_start", "enhance_prompt")+ "train_start", "enhance_prompt",+ # SYS-41: train_start used to fire at the top of+ # /train/start, before the RAM refusal below it, so+ # the fleet's "255 train starts / 50 installs" figure+ # counted refused clicks as attempts. train_start now+ # fires only past the refusal; train_refused counts+ # the clicks that never got there, so neither number+ # silently absorbs the other.+ "train_refused")def _analytics_feature(feature: str, detail: str = "") -> None:@@ -16463,12 +18028,23 @@ def _apply_generation_profile_to_job(job: dict) -> None:# requested quality. Asked of the registry, not of the name: a second HQ# tier is still an HQ tier.if not ltx_quality_uses_hq(quality):- max_dim = int(profile.get("max_dim") or 0)- new_w, new_h = (ltx_fit_canvas(width, height, max_dim)- if max_dim and max(width, height) > max_dim else (width, height))- if (new_w, new_h) != (width, height):- params["width"], params["height"] = new_w, new_h- new_notes.append(f"resolution {width}x{height} -> {new_w}x{new_h}")+ # VC-02/SYS-05: on the Compact tier (<48 GB), CAPABILITIES' own+ # tier_max_dim clamp (applied later, in run_job_inner) is already+ # the resolution authority — it fires unconditionally, keeps aspect+ # via ltx_fit_canvas, and _ltx_qualities() now bakes it into the+ # chip's advertised canvas too. Applying THIS profile's max_dim+ # (1024) on top of that was a second, independent clamp: two floors+ # in a row is how a 16:9 request came back a 2:1 canvas, and it+ # relabelled the result "48 GB fast generation" on a 16 GB Mac. Skip+ # it here — Comfortable tier (48-63 GB) still needs it, since+ # CAPABILITIES leaves t2v/i2v uncapped there by design.+ if SYSTEM_TIER != "base":+ max_dim = int(profile.get("max_dim") or 0)+ new_w, new_h = (ltx_fit_canvas(width, height, max_dim)+ if max_dim and max(width, height) > max_dim else (width, height))+ if (new_w, new_h) != (width, height):+ params["width"], params["height"] = new_w, new_h+ new_notes.append(f"resolution {width}x{height} -> {new_w}x{new_h}")auto_after = int(profile.get("auto_temporal_after_frames") or 0)if (mode in ("t2v", "i2v") and auto_after and frames > auto_after@@ -16499,6 +18075,121 @@ def tier_max_dim(kind: str) -> int:return int(SYSTEM_CAPS.get(f"{kind}_max_dim", 0))+def honest_tier_times() -> dict:+ """The Tier modal's per-mode estimates — VC-12 / SYS-20: this used to be+ CAPABILITIES[tier]["times"], a second table of hand-typed strings, one+ per RAM TIER, that never scaled with chip speed and routinely+ disagreed with the Quality strip's own chips on the SAME Mac (the+ strip said "~3 min", the modal said "about 12 min"). Every string here+ is now read from or derived with the same chip-and-RAM-aware model the+ chips use (ltx_estimate_minutes / LTX_TIERS), so the two can't drift+ apart again."""+ def _min_str(minutes: float) -> str:+ return _fmt_eta(minutes).lstrip("~") # the modal's own template adds "~ "++ t2v_standard = LTX_TIERS.get("standard_5s", {})+ out = {+ "t2v_draft": _min_str(LTX_TIERS["quick_5s"]["eta_min"]),+ "t2v_standard": _min_str(t2v_standard.get("eta_min", 0)) if t2v_standard else None,+ # LTX prices t2v and i2v identically (no mode term in the cost model).+ "i2v_standard": _min_str(t2v_standard.get("eta_min", 0)) if t2v_standard else None,+ "high": None,+ "keyframe": None,+ "extend": None,+ }+ if SYSTEM_CAPS.get("allows_q8") and "high_5s" in LTX_TIERS:+ out["high"] = _min_str(LTX_TIERS["high_5s"]["eta_min"])+ if SYSTEM_CAPS.get("allows_keyframe"):+ kf_w, kf_h, kf_min = ltx_keyframe_estimate_minutes(+ int(LTX_LENGTHS["5s"]["frames"]))+ out["keyframe"] = f"{_min_str(kf_min)} (at {max(kf_w, kf_h)} px)"+ if SYSTEM_CAPS.get("allows_extend"):+ ext_w, ext_h, ext_min = ltx_extend_estimate_minutes(5, 8)+ out["extend"] = f"{_min_str(ext_min)} (at {max(ext_w, ext_h)} px, +1.7s)"+ return out+++def ltx_mode_price_card(mode: str, steps: int | None = None, *,+ frames: int | None = None, width: int | None = None,+ height: int | None = None,+ extend_frames: int | None = None) -> dict | None:+ """Structured price for the keyframe/extend Shot setup summary and+ footer (VA-11 / VA-12) — the browser must not price these itself+ (Structure Law §6): it reads this instead of the Quality-strip cell,+ which prices a DIFFERENT pipeline (keyframe always runs Q8 two-stage at+ LTX_HQ_STAGE1/2 regardless of the selected quality pill; extend runs its+ own step count, not stage1/stage2). Returns None when the mode isn't+ available on this tier.++ FLEET FIRST (4.17 integration). The cost model below is the distilled-Q4+ t2v model; it has no term for Extend's Q8 dev transformer and prices a+ keyframe render at the HQ step count only — on a 64 GB M4 Max it said+ Extend "~1.5 min" and Keyframe "~2 min" where the fleet's own wall+ clocks (data/fleet_timings.json, fleet_calibrated_range) say ~20 min and+ ~10 min, and the pills this replaced said "~16 min". Where the fleet has+ this shape, its p25-p75 range is the price; the model only supplies the+ RATIO between Extend's added-length / step-count variants.++ Keyframe is priced for the frames and canvas the form actually holds+ (4.17 Codex EST-7: it was pinned to 5 s at the default canvas, so a+ 10 s keyframe showed the 5 s price) — BOOT carries the default shape for+ first paint, GET /keyframe/estimate prices any other. `extend_frames`+ (latents) prices one Extend length for the queue (EST-5)."""+ default_frames = int(LTX_LENGTHS["5s"]["frames"])+ if mode == "keyframe":+ if not SYSTEM_CAPS.get("allows_keyframe"):+ return None+ kf_frames = int(frames) if frames and int(frames) > 1 else default_frames+ w, h, minutes = ltx_keyframe_estimate_minutes(kf_frames, width, height)+ card = {"mode": "keyframe", "width": w, "height": h, "frames": kf_frames,+ "eta": _fmt_eta(minutes), "eta_min": round(minutes, 2),+ "pipeline_note": "Q8 two-stage", "basis": "estimated"}+ fleet = fleet_calibrated_range("ltx", "keyframe", LTX_QUALITY_DEFAULT, kf_frames)+ if fleet:+ # The fleet rendered the default canvas; the model only supplies+ # the ratio to another one (the /a2v/estimate idiom).+ ref = ltx_keyframe_estimate_minutes(kf_frames)[2]+ r = (minutes / ref) if ref > 0 else 1.0+ card.update(eta=_fmt_eta_range(fleet["p25_min"] * r, fleet["p75_min"] * r),+ eta_min=round(fleet["p50_min"] * r, 2), basis=fleet["basis"])+ return card+ if mode == "extend":+ if not SYSTEM_CAPS.get("allows_extend"):+ return None+ # latent frames; the form's own default is 5+ extend_frames = max(1, int(extend_frames)) if extend_frames else 5+ step_count = max(1, int(steps)) if steps else 8+ w, h, minutes = ltx_extend_estimate_minutes(extend_frames, step_count)+ added_s = round(extend_frames * 8 / float(FPS), 1)+ base_s = round(default_frames / float(FPS), 1)+ fleet = fleet_calibrated_range("ltx", "extend", LTX_QUALITY_DEFAULT, default_frames)+ ref_min = ltx_extend_estimate_minutes(extend_frames, 8)[2] or 1.0++ def _price(latents: int) -> tuple[str, float]:+ m = ltx_extend_estimate_minutes(latents, step_count)[2]+ if not fleet:+ return _fmt_eta(m), m+ r = m / ref_min+ return (_fmt_eta_range(fleet["p25_min"] * r, fleet["p75_min"] * r),+ fleet["p50_min"] * r)++ # The form's "Extend by" field is live (0.5-10 s -> 2-30 latents);+ # price every value it can hold so the footer's ETA follows the+ # seconds actually typed (VC-25's live line x VA-12's real price)+ # without the browser pricing anything itself.+ eta_by_latents = {str(_lat): _price(_lat)[0] for _lat in range(1, 31)}+ eta, eta_min = _price(extend_frames)+ return {"mode": "extend", "width": w, "height": h,+ "eta": eta, "eta_min": round(eta_min, 2),+ "steps": step_count, "added_seconds": added_s,+ "extend_frames": extend_frames,+ "total_seconds": round(base_s + added_s, 1),+ "eta_by_latents": eta_by_latents,+ "basis": fleet["basis"] if fleet else "estimated",+ "pipeline_note": f"Q8 extend · {step_count} steps"}+ return None++def get_memory() -> dict:info = {"total_gb": 0.0, "used_gb": 0.0, "pressure_pct": 0, "swap_gb": 0.0}try:@@ -16527,6 +18218,27 @@ def get_memory() -> dict:info["swap_gb"] = v * multexcept Exception:pass+ # SYS-19: `pressure_pct` above (active+wired+compressed / total) is a+ # USED ratio, not a pressure signal — plan_memory_policy() above+ # deliberately keeps using it exactly as-is (its 82%+swap>=4GB+ # threshold is proven, and changing what it means is out of scope+ # here). But the health CHIP colored itself off the same number, and+ # macOS routinely sits at 75-90% "used" by this measure while+ # completely idle (it fills RAM with reclaimable cache on purpose) —+ # so the chip read amber/red most of the day on 8-16 GB Macs. This is+ # the OS's own signal instead: kern.memorystatus_vm_pressure_level is+ # what macOS itself uses to decide whether to reclaim, compress, or+ # jetsam-kill (1 normal / 2 warning / 3 critical) — a genuine pressure+ # level, not a used ratio. New field, additive; nothing that reads+ # pressure_pct changes.+ try:+ lvl = subprocess.run(+ ["sysctl", "-n", "kern.memorystatus_vm_pressure_level"],+ capture_output=True, text=True, errors="replace", timeout=1,+ ).stdout.strip()+ info["pressure_level"] = int(lvl) if lvl.isdigit() else 1+ except Exception:+ info["pressure_level"] = 1return info@@ -16665,6 +18377,98 @@ def _probe_video_dims(path: str) -> tuple[int, int]:return 0, 0+# Codex UI-8 / EST-12: the gallery card's size chip printed the QUALITY+# PRESET's default canvas (`q.delivered_canvas || q.canvas`) or the H3 tier's+# canonical spec — a square or portrait Balanced clip, a native (export off)+# render, a Sharp export or a clip made on another Mac's tier all claimed+# "1280×720". The card now prints the dimensions of the FILE, read from its+# own mp4 header: the video track's tkhd box, a few KB, no subprocess — cheap+# enough for the /status gallery page, and cached per (mtime, size) so a poll+# re-reads nothing. None (chip shows no size) when the header can't say.+_MP4_MOOV_MAX = 64 * 1024 * 1024+_OUTPUT_DIMS_CACHE: dict[str, tuple[int, int, tuple[int, int] | None]] = {}+++def _mp4_boxes(buf: bytes, start: int = 0, end: int | None = None):+ end = len(buf) if end is None else end+ pos = start+ while pos + 8 <= end:+ size, typ = struct.unpack(">I4s", buf[pos:pos + 8])+ hlen = 8+ if size == 1:+ if pos + 16 > end:+ return+ size = struct.unpack(">Q", buf[pos + 8:pos + 16])[0]+ hlen = 16+ elif size == 0:+ size = end - pos+ if size < hlen or pos + size > end:+ return+ yield typ, pos + hlen, pos + size+ pos += size+++def _mp4_display_dims(path) -> tuple[int, int] | None:+ """(width, height) of an mp4's first video track, from its tkhd box."""+ try:+ with open(path, "rb") as fh:+ total = os.fstat(fh.fileno()).st_size+ pos = 0+ moov = None+ while pos + 8 <= total: # top level: seek, never read mdat+ fh.seek(pos)+ hdr = fh.read(16)+ if len(hdr) < 8:+ return None+ size, typ = struct.unpack(">I4s", hdr[:8])+ hlen = 8+ if size == 1 and len(hdr) == 16:+ size, hlen = struct.unpack(">Q", hdr[8:16])[0], 16+ elif size == 0:+ size = total - pos+ if size < hlen:+ return None+ if typ == b"moov":+ if size > _MP4_MOOV_MAX:+ return None+ fh.seek(pos + hlen)+ moov = fh.read(size - hlen)+ break+ pos += size+ except OSError:+ return None+ if not moov:+ return None+ for typ, a, b in _mp4_boxes(moov):+ if typ != b"trak":+ continue+ for ctyp, ca, cb in _mp4_boxes(moov, a, b):+ if ctyp != b"tkhd" or cb - ca < 84:+ continue+ off = ca + (88 if moov[ca] == 1 else 76)+ if off + 8 > cb:+ continue+ w, h = struct.unpack(">II", moov[off:off + 8])+ w, h = w >> 16, h >> 16+ if w > 0 and h > 0: # audio tracks carry 0×0+ return int(w), int(h)+ return None+++def _output_dims(path) -> tuple[int, int] | None:+ try:+ st = os.stat(path)+ except OSError:+ return None+ key = str(path)+ hit = _OUTPUT_DIMS_CACHE.get(key)+ if hit and hit[0] == st.st_mtime_ns and hit[1] == st.st_size:+ return hit[2]+ dims = _mp4_display_dims(path)+ _OUTPUT_DIMS_CACHE[key] = (st.st_mtime_ns, st.st_size, dims)+ return dims++def _probe_video_frames(path: str) -> int:"""Frame count of a video via ffprobe (0 when unknown)."""try:@@ -16679,6 +18483,44 @@ def _probe_video_frames(path: str) -> int:return 0+def _probe_video_fps(path: str) -> float:+ """Average frame rate of a video via ffprobe (0.0 when unknown)."""+ try:+ out = subprocess.run(+ [str(FFPROBE), "-v", "error", "-select_streams", "v:0",+ "-show_entries", "stream=avg_frame_rate", "-of", "csv=p=0", path],+ capture_output=True, text=True, errors="replace", timeout=10,+ ).stdout.strip().splitlines()+ num, _, den = (out[0] if out else "").partition("/")+ fps = float(num) / float(den or 1)+ return fps if fps > 0 else 0.0+ except Exception:+ return 0.0+++def _retake_delivered_geometry(out_path, result: dict | None) -> dict:+ """LIPSYNC-11: the size, frame count and rate a Retake output really has,+ as params-shaped keys (width/height/frames/frame_rate) so every reader+ of a sidecar's params — the gallery's clip_sec, Load Params, the next+ Retake's range — sees the delivered clip. ffprobe first; the helper's+ done-event report second; a key neither knows is left out (and the+ caller's params keep whatever they had)."""+ result = result or {}+ got: dict = {}+ w, h = _probe_video_dims(str(out_path))+ if not (w and h):+ w, h = int(result.get("width") or 0), int(result.get("height") or 0)+ if w and h:+ got["width"], got["height"] = w, h+ n = _probe_video_frames(str(out_path)) or int(result.get("frames") or 0)+ if n:+ got["frames"] = n+ fps = _probe_video_fps(str(out_path)) or float(result.get("fps") or 0.0)+ if fps:+ got["frame_rate"] = round(fps, 3)+ return got++def _probe_audio_state(path: str) -> str:""""audio", "none", or "unknown" (ffprobe failed or could not read it).@@ -17179,7 +19021,11 @@ def _output_search_text(meta: dict, params: dict) -> str:"character_id", "trigger", "seed", "seed_used", "h3_tier"):v = params.get(k)if v not in (None, "", [], {}):- bits.append(str(v)[:400])+ # VC-31: 400 chars of headroom per field was rarely used (most+ # prompts run well under it) and, at 60 rows every /status+ # poll, was real bytes for nothing — 160 still comfortably+ # covers a typical prompt for substring search.+ bits.append(str(v)[:160])w, h = params.get("width"), params.get("height")if w and h:bits.append(f"{int(w)}x{int(h)}")@@ -17406,11 +19252,34 @@ def list_outputs(engine = Nonemodel = None # which weights made this clip (sidecar-derived)h3_tier = None+ render_mode = None # sidecar params.mode ("a2v", "t2v", "keyframe", …); VA-36+ lipsync_score = None # a2v's own mouth-vs-voice verdict, when scored; VA-14+ windows_partial = None # {"completed", "total"} when this is a partial windows join; VA-38+ # VC-18/37: the LTX side of the same "is this a finishable draft"+ # question h3_tier already answers for H3 — an LTX render's own+ # quality key + frame count, straight from the sidecar params it+ # already has (make_job's `quality` field, the Job Spec table's+ # `frames`). Lets ltxFinishTargets() gate without a /sidecar fetch+ # per gallery click, same reason h3_tier is lifted here.+ ltx_quality = None+ ltx_frames = None+ # VC-36: a short prompt snippet for the gallery card — "richer+ # cards" without re-growing the payload the way embedding the full+ # prompt would (see the 400->160 trim on _output_search_text just+ # above this loop). 80 chars is plenty for "first ~6 words".+ prompt_snippet = None+ out_mode = None # t2v / i2v / image / music / ... — the card's "mode" chip# Which film this clip is a shot of, if any — {"id": ..., "n": 3} or None.# Derived from the sidecar read already happening below, so it costs# nothing, and it is what puts an S03 badge on a gallery card. None for# every clip that isn't part of a storyboard, which is most of them.sb_tag = None+ # VA-17: does this un-hidden card carry a One Shot recovery manifest+ # (run_take_job_inner's except clause stamps this on the last kept+ # part when a take stops or fails)? Only a small count, so counting+ # it here costs nothing and the gallery card can offer Resume / Join+ # what's done without a second /sidecar fetch per card.+ one_shot_unfinished = Falsesearch = ""music_meta = Nonesidecar = p.with_suffix(p.suffix + ".json")@@ -17467,6 +19336,28 @@ def list_outputs(_eng = meta.get("engine") or _sc_params.get("engine")if isinstance(_eng, str) and _eng:engine = _eng+ # The render mode ("a2v", "t2v", "keyframe", …) — the player+ # uses this to swap Extend for "Continue the song" on a2v+ # clips (VA-36: Extend regenerates joint LTX audio on an a2v+ # source, so a singing shot "continues" with invented+ # gibberish instead of the next stretch of the song).+ _rmode = _sc_params.get("mode")+ if isinstance(_rmode, str) and _rmode:+ render_mode = _rmode+ # VA-14: the lip-sync verdict, when this clip has one+ # (a2v only — see run_job_inner's a2v branch). A rough+ # check, never a gate: the player shows it as a chip,+ # labelled to match, and nothing is ever auto-deleted+ # because of it.+ _lss = meta.get("lipsync_score")+ if isinstance(_lss, (int, float)):+ lipsync_score = float(_lss)+ # VA-38: which windows chains stopped partway, and how far+ # they got — the player's "Continue from here" action reads+ # this to offer resuming instead of a silent orphaned file.+ _wp = meta.get("windows_partial")+ if isinstance(_wp, dict):+ windows_partial = _wp# WHICH WEIGHTS MADE THIS CLIP. The sidecar has always known —# the LTX path records its job spec's model_dir and the H3 path# records its DiT — but the credit under the player was a@@ -17485,7 +19376,30 @@ def list_outputs(_tier = h3_resolve_tier(_sc_params.get("h3_tier"))if _tier:h3_tier = _tier+ # LTX's own two axes, lifted only when this clip actually IS+ # an LTX render (engine None or "ltx") — an H3 clip's sidecar+ # has no `quality` key in this sense (h3_tier already covers+ # it), and a stray `quality` on some other engine's params+ # must not be misread as an LTX finish candidate.+ if engine in (None, "ltx"):+ _q = _sc_params.get("quality")+ if isinstance(_q, str) and _q:+ ltx_quality = _q+ _fr2 = _sc_params.get("frames")+ if isinstance(_fr2, (int, float)):+ ltx_frames = int(_fr2)+ # VC-36: prompt snippet, engine-agnostic (works for LTX, H3,+ # One Shot alike — all three write `prompt` under params).+ _pr = _sc_params.get("prompt") or meta.get("prompt")+ if isinstance(_pr, str) and _pr.strip():+ prompt_snippet = _pr.strip()[:80]+ _md = _sc_params.get("mode") or meta.get("mode")+ if isinstance(_md, str) and _md:+ out_mode = _md+ elif engine == "music":+ out_mode = "music"sb_tag = _sb_tag_from(_sc_params.get("session_tag"))+ one_shot_unfinished = bool(meta.get("one_shot_unfinished"))# Clip LENGTH, derived — frames/frame_rate are already in the# sidecar params for both engines, so the card can lead with# what the file IS (a 10 s clip) instead of only how long it@@ -17528,6 +19442,15 @@ def list_outputs(# the RESOLVED cell key, so the two axes below are just its halves# and the browser can gate on quality without splitting a string."engine": engine,+ # Render mode ("a2v", "t2v", "keyframe", …) — VA-36. None for a+ # clip that predates the field or has no sidecar.+ "mode": render_mode,+ # VA-14: the lip-sync verdict (a2v only), or None when unscored+ # (predates the field, cv2 unavailable, or no face found).+ "lipsync_score": lipsync_score,+ # VA-38: {"completed", "total"} for a Windows chain that failed+ # partway and was published anyway; None for every other clip.+ "windows_partial": windows_partial,# Which weights made this clip. The credit under the player reads# it; None for a clip that predates the field, and the client falls# back to BOOT.model silently.@@ -17535,6 +19458,14 @@ def list_outputs("h3_tier": h3_tier,"h3_quality": (H3_TIERS[h3_tier]["quality"] if h3_tier else None),"h3_length": (H3_TIERS[h3_tier]["length"] if h3_tier else None),+ # VC-18/37: the LTX Finish affordance's own gate — see ltx_quality/+ # ltx_frames' definition above for why these two only ever come+ # from an actual LTX clip's sidecar.+ "quality": ltx_quality,+ "frames": ltx_frames,+ # VC-36: the gallery card's prompt snippet + mode chip.+ "prompt": prompt_snippet,+ "mode": out_mode,# Storyboard provenance, or None. One badge on the card, one click# back to the film it belongs to — and invisible for every clip# that isn't part of one.@@ -17542,6 +19473,7 @@ def list_outputs(# Music Studio's song facts, None for everything that is not a song."music": music_meta,"hidden": is_hidden,+ "one_shot_unfinished": one_shot_unfinished,# 'kind' lets the right-pane viewer + filter chips branch# without re-parsing the filename. Mirrors isPhotoOutput() on# the agent-stage pane (commit af5c184).@@ -17559,6 +19491,11 @@ def list_outputs(sliced = out[offset:]else:sliced = out[offset:offset + limit]+ # UI-8 / EST-12: the file's own dimensions, for the card's size chip —+ # only for the page actually returned (cached; see _output_dims).+ for _e in sliced:+ _d = _output_dims(_e["path"]) if _e.get("kind") == "video" else None+ _e["width"], _e["height"] = (_d if _d else (None, None))if return_total:return sliced, totalreturn sliced@@ -18953,6 +20890,11 @@ def run_tracked_subprocess(cmd: list[str], *, pgid_key: str, label: str,def run_postprocess_tracked(cmd: list[str], label: str) -> tuple[str, str]:"""Run a post-process in its own process group so /stop can kill it."""+ film_job = _sb_film_job_ctx()+ if film_job is not None:+ # An Editor film render (FILM-28's job) — tracked on its own job so+ # its Cancel can stop it, and never in the generation queue's slot.+ return _sb_film_job_ffmpeg(cmd, label, film_job)push(f"{label}: " + " ".join(shlex.quote(c) for c in cmd))env = os.environ.copy()env["PATH"] = f"{FFMPEG_BIN}:{env.get('PATH', '')}"@@ -18988,6 +20930,25 @@ def run_pipersr_tracked(source: Path, output: Path, mode: str, crf: str,], "Sharp upscale")+def probe_media_duration(path) -> float | None:+ """Duration in seconds of any media file (audio or video) via ffprobe, or+ None when the file can't be read. Used by /upload (VA-03): the A2V+ Duration slider and "Audio start" have always been blind to the length+ of the file the user just dropped, so a 4 s vocal defaulted to a 7 s+ render — 43% of it silence, which is also exactly where a lip-sync+ mouth freezes."""+ try:+ out = subprocess.run(+ [str(FFPROBE), "-v", "error", "-show_entries", "format=duration",+ "-of", "csv=p=0", str(path)],+ capture_output=True, text=True, errors="replace", timeout=30,+ ).stdout.strip()+ val = float(out)+ return val if val > 0 else None+ except Exception: # noqa: BLE001+ return None++def video_duration(frames: int) -> float:# LTX 2.x uses frame counts shaped like 8k+1. The encoded file contains# the intervals between those endpoints, so 121 means exactly 5.0s at@@ -19006,11 +20967,19 @@ def _duration_to_8k_frames(duration_sec: float, fps: float) -> int:return k * 8 + 1-def stop_current_job(timeout: float = 5.0) -> None:+def stop_current_job(timeout: float = 5.0, expect_id: str | None = None) -> bool:"""Kill the warm helper (and any in-flight ffmpeg mux/upscale + training- subprocess). Worker advances."""+ subprocess). Worker advances.++ `expect_id` (4.17 Codex SAFETY-3): the job the user confirmed stopping.+ A Stop dialog can sit open while that job finishes and the next one+ starts; an untargeted stop then killed the successor. When given and it+ is no longer the current job, nothing is touched and this returns False+ — checked under LOCK, the same section that flags the cancel."""with LOCK:cur = STATE["current"]+ if expect_id and (cur is None or cur.get("id") != expect_id):+ return False# Set BEFORE the pgids are read, in the same section: a worker that# spawns right now either registers its pgid first (read below and# killed) or sees this flag when it registers (and kills itself) —@@ -19098,6 +21067,7 @@ def stop_current_job(timeout: float = 5.0) -> None:target=_force_kill_after, args=(8.0, train_pgid),daemon=True, name=f"sigkill-train-{train_pgid}",).start()+ return True_JOB_COUNTER = 0@@ -19112,6 +21082,74 @@ def _new_job_id() -> str:return f"j-{int(time.time()*1000):x}-{n:03d}"+# 4.17 Codex SAFETY-8/9/10 — Clear queue's Undo restores what the SERVER+# removed, under the SAME ids. It used to replay the browser's last /status+# snapshot through /queue/restore with freshly minted ids, which (9) requeued+# a job the worker had already started between the poll and the Clear, and+# lost one another tab added in that gap; (10) minted ids from a millisecond+# clock + randrange(0xfff), so a 200-job restore produced duplicate ids; and+# (8) left every restored storyboard shot pointing at its OLD job id — the+# restored job rendered, the shot never received it and went back to pending.+# Now /queue/clear keeps the removed job dicts here behind a single-use token+# and /queue/restore puts exactly those back, original ids and all. While the+# token is live, _sb_job_index() still reports those jobs as queued, so the+# board reconciler (FILM-18) does not orphan a shot during the Undo window.+QUEUE_UNDO_TTL_SEC = 60.0+_QUEUE_UNDO: dict = {} # {"token", "jobs", "at"} — the one undoable Clear+++def _queue_undo_live_locked() -> list:+ """The jobs the last Clear removed, while its Undo is still offered.+ Caller holds LOCK."""+ if not _QUEUE_UNDO:+ return []+ if time.monotonic() - float(_QUEUE_UNDO.get("at") or 0) > QUEUE_UNDO_TTL_SEC:+ _QUEUE_UNDO.clear()+ return []+ return list(_QUEUE_UNDO.get("jobs") or [])+++def queue_clear_with_undo() -> dict:+ """Empty the queue; keep what was removed for one Undo."""+ with LOCK:+ removed = list(STATE["queue"])+ STATE["queue"] = []+ _QUEUE_UNDO.clear()+ token = None+ if removed:+ token = os.urandom(8).hex()+ _QUEUE_UNDO.update(token=token, jobs=removed, at=time.monotonic())+ return {"cleared": len(removed), "ids": [j.get("id") for j in removed],+ "undo_token": token}+++def queue_restore_cleared(token: str) -> dict:+ """Put back exactly the jobs the Clear behind `token` removed — once."""+ with QUEUE_COND:+ live = _queue_undo_live_locked()+ if not token or not live or _QUEUE_UNDO.get("token") != token:+ return {"ok": False, "status": 410,+ "error": "This Undo has expired — the cleared renders "+ "can't be brought back any more."}+ _QUEUE_UNDO.clear()+ known = {j.get("id") for j in STATE["queue"]} | \+ {j.get("id") for j in STATE["history"]}+ if STATE.get("current"):+ known.add(STATE["current"].get("id"))+ restored = []+ for j in live:+ if j.get("id") in known:+ continue # the same job is already back/running — never twice+ j["status"] = "queued"+ restored.append(j)+ # Ahead of anything queued since the Clear: these were waiting first.+ STATE["queue"][0:0] = restored+ if restored:+ QUEUE_COND.notify_all()+ return {"ok": True, "restored": len(restored),+ "ids": [j.get("id") for j in restored]}++# =============================================================================# STORYBOARD — the server side# =============================================================================@@ -19138,6 +21176,134 @@ _SB_PLANNERS: dict = {} # board_id -> {"session", "thread", "cancelled"_SB_RENDERS: dict = {} # board_id -> {"thread", "stop", "pass", "queued"}_SB_TAG_RX = re.compile(r"^sb:([^#]+)#(\d+)$")+# FILM-28: THE EDITOR'S OWN FILM ASSEMBLY, AS A JOB — deliberately a SEPARATE+# registry from _SB_RENDERS above (the Storyboard tab's own shot-by-shot+# render pass) and its own lock, never _SB_LOCK: the two features share+# nothing but the word "render", and giving film assembly its own namespace+# means neither can deadlock or race the other's lock ordering. Before this,+# `/storyboard/edit/render` ran the whole ffmpeg pass on the HTTP handler+# thread — the request simply did not answer until the encode finished, no+# progress, no way to leave the tab and come back, no way to change your+# mind partway through. Now the route starts a background thread and+# answers immediately with a job id; the client polls+# `/storyboard/edit/render/status`.+_SB_FILM_JOB_LOCK = threading.Lock()+_SB_FILM_JOBS: dict = {} # job_id -> {"board_id", "state", "started_at",+ # "cancel", "result", "error"}+# A job dict lives long enough for the client to see its final state at+# least once; anything idle past this is swept the next time a job starts,+# so the registry cannot grow across a long session of many renders.+_SB_FILM_JOB_TTL = 3600.0+# Which film job (if any) THIS thread is assembling. Set only by+# _sb_film_job_run's own thread, so every ffmpeg the assembler starts under it+# is tracked on the FILM JOB — never in STATE["mux_pgid"], the generation+# queue's own slot, which a film render used to overwrite (and a queue Stop+# could then kill the film's encode, or the film's Cancel reach nothing).+_SB_FILM_JOB_CTX = threading.local()+++def _sb_film_job_ctx() -> dict | None:+ return getattr(_SB_FILM_JOB_CTX, "job", None)+++class FilmRenderCanceled(RuntimeError):+ """The Editor's Cancel ended this film render's ffmpeg."""+++def _sb_film_job_ffmpeg(cmd: list, label: str, job: dict,+ timeout: float | None = None) -> tuple[str, str]:+ """ffmpeg for a film JOB: its own process group, its pgid recorded on the+ job dict (under _SB_FILM_JOB_LOCK), so /storyboard/edit/render/cancel can+ kill it mid-encode. Same return/raise shape as run_postprocess_tracked."""+ push(f"{label}: " + " ".join(shlex.quote(str(c)) for c in cmd))+ env = os.environ.copy()+ env["PATH"] = f"{FFMPEG_BIN}:{env.get('PATH', '')}"+ with _SB_FILM_JOB_LOCK:+ if job.get("cancel"):+ raise FilmRenderCanceled(f"{label}: canceled before it started")+ proc = subprocess.Popen([str(c) for c in cmd], stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, text=True, errors="replace",+ start_new_session=True, env=env)+ job.setdefault("pgids", []).append(proc.pid)+ try:+ try:+ stdout, stderr = proc.communicate(timeout=timeout)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except (ProcessLookupError, PermissionError, OSError):+ pass+ proc.communicate()+ raise+ finally:+ with _SB_FILM_JOB_LOCK:+ try:+ job.get("pgids", []).remove(proc.pid)+ except ValueError:+ pass+ if proc.returncode != 0:+ if job.get("cancel"):+ raise FilmRenderCanceled(f"{label}: canceled")+ push((stderr or stdout or "").strip())+ raise RuntimeError(f"{label.lower()} exited with code {proc.returncode}")+ return stdout or "", stderr or ""+++def _sb_film_job_sweep() -> None:+ now = time.time()+ with _SB_FILM_JOB_LOCK:+ stale = [jid for jid, j in _SB_FILM_JOBS.items()+ if j.get("state") in ("done", "error", "canceled")+ and now - j.get("finished_at", now) > _SB_FILM_JOB_TTL]+ for jid in stale:+ _SB_FILM_JOBS.pop(jid, None)+++def _sb_film_job_run(job_id: str, board: dict, edit: dict, *, music,+ music_mode, out_name: str, deliver: dict,+ reserved: str | None = None) -> None:+ """Runs `_sbe_render_edit` off the HTTP handler thread and files the+ result. A cancel that lands before this finishes discards the output —+ including deleting the file the assembler wrote — rather than presenting+ a film the user asked to stop; a cancel that lands after is simply too+ late and the job's real result stands, the same race every async+ "cancel" button already lives with.+ """+ with _SB_FILM_JOB_LOCK:+ job_ref = _SB_FILM_JOBS.get(job_id)+ _SB_FILM_JOB_CTX.job = job_ref+ try:+ film = _sbe_render_edit(board, edit, music=music, music_mode=music_mode,+ out_name=out_name, deliver=deliver)+ except Exception as exc: # noqa: BLE001+ film = {"ok": False, "error": str(exc)}+ finally:+ _SB_FILM_JOB_CTX.job = None+ # EDITOR-6: the claimed version name is free again — the file is on+ # disk now (and `exists()` holds it), or it never will be.+ _sb_film_name_release(reserved)+ with _SB_FILM_JOB_LOCK:+ job = _SB_FILM_JOBS.get(job_id)+ if job is None:+ return+ if job.get("cancel"):+ # Best-effort cleanup — a partial or complete file nobody asked+ # to keep. Never fatal: a file that fails to delete just sits in+ # the film folder, same as any other leftover this lane already+ # tolerates (AFailedRenderKeepsTheLastFilm's own territory).+ path = film.get("path") if film.get("ok") else None+ if path:+ try:+ Path(path).unlink(missing_ok=True)+ except OSError:+ pass+ job["state"] = "canceled"+ else:+ job["state"] = "done" if film.get("ok") else "error"+ job["result"] = film+ job["error"] = None if film.get("ok") else film.get("error")+ job["finished_at"] = time.time()+def _sb_tag_from(session_tag) -> dict | None:"""`"sb:<board>#3"` -> `{"id": "<board>", "n": 3}`. Anything else -> None.@@ -19630,9 +21796,14 @@ def take_expects_speech(params: dict, beats: list[str] | None = None) -> bool:return bool(re.search(r'[“"][^”"]{2,}[”"]', text))-def take_lipsync_score(path) -> float | None:- """How well the mouth follows the voice in one clip, or None when there is- no face or no speech to judge (or cv2 is not importable).+def _take_lipsync_score_and_lag(path) -> tuple[float, int, float] | None:+ """`(best correlation, the lag in FRAMES that produced it, fps)`, or None.++ The shared engine behind `take_lipsync_score` (Storyboard's KEEP/RE-ROLL+ gate) and `take_lipsync_best_lag` (FILM-05's Auto-align, Editor). One+ face-detect + audio-decode pass, not two: the lag search already finds+ the best offset to compute the score, and until now that offset was+ thrown away the instant the score was returned.The face is found once a second with OpenCV's frontal cascade; inside thelower third of the face box, the fraction of pixels darker than the box's@@ -19683,17 +21854,389 @@ def take_lipsync_score(path) -> float | None:if sp.sum() < 24:return Nonebest = None+ best_lag = 0for lag in range(-6, 7):x_ = m[lag:][sp[:n - lag]] if lag >= 0 else m[:n + lag][sp[-lag:]]y_ = r[:n - lag][sp[:n - lag]] if lag >= 0 else r[-lag:][sp[-lag:]]if len(x_) >= 24 and x_.std() > 1e-6 and y_.std() > 1e-6:c = float(np.corrcoef(x_, y_)[0, 1])- best = c if best is None else max(best, c)- return best+ if best is None or c > best:+ best, best_lag = c, lag+ if best is None:+ return None+ return (best, best_lag, float(fps))except Exception: # noqa: BLE001return None+# --- Mouth-openness (lip-sync anchor picking) -------------------------------+# Reuses take_lipsync_score's face cascade + mouth-ROI-darkness metric on a+# SINGLE frame rather than a whole clip. Two callers:+# 1. mouth_open_ratio() on a still image — the "this picture's mouth is+# open" warning when a user picks an a2v start frame (2026-09-22 anchor+# lesson: an open-mouth first-frame anchor freezes the performance).+# 2. find_closed_mouth_frame() on a finished a2v clip — "Continue the+# song": the next clip should anchor on the previous clip's+# most-closed-mouth frame near its end, not its literal last frame+# (usually mid-syllable).+MOUTH_OPEN_WARN = 0.06 # ratio above which the mouth reads as visibly open+++def _mouth_open_ratio_from_gray(gray, casc) -> float | None:+ """Mouth-openness ratio (0..1) from one grayscale frame, or None when no+ face is found. Same ROI + threshold as take_lipsync_score's per-frame+ metric, kept identical so the two are comparable."""+ try:+ import numpy as np+ except Exception: # noqa: BLE001+ return None+ faces = casc.detectMultiScale(gray, 1.1, 5, minSize=(80, 80))+ if not len(faces):+ return None+ x, y, w, h = max(faces, key=lambda b: b[2] * b[3])+ roi = gray[y + int(h * 0.62):y + h, x + int(w * 0.25):x + int(w * 0.75)]+ if roi.size == 0:+ return None+ return float((roi < (np.median(roi) - 40)).mean())+++def mouth_open_ratio(image_path) -> float | None:+ """Mouth-openness ratio for a single still image, or None when cv2 is+ unavailable or no face is found (caller should not warn in that case —+ an unmeasured picture is not a bad picture)."""+ try:+ import cv2 # noqa: F401+ except Exception: # noqa: BLE001+ return None+ try:+ img = cv2.imread(str(image_path))+ if img is None:+ return None+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)+ casc = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")+ return _mouth_open_ratio_from_gray(gray, casc)+ except Exception: # noqa: BLE001+ return None+++def find_closed_mouth_frame(video_path, window_s: float = 0.5, fps_hint: float = FPS):+ """Scan the last `window_s` seconds of `video_path` for the frame with the+ LOWEST mouth-openness ratio, and return+ {"time_s": float, "openness": float} for it, or None when no face is+ found anywhere in the window (or cv2 is unavailable).++ Used by "Continue the song": the model's own last frame is usually+ mid-syllable (mouth open), and anchoring the next clip there freezes an+ open mouth for its whole duration (the 2026-09-22 anchor lesson). The+ most-closed frame near the end is a far safer handoff point.+ """+ try:+ import cv2 # noqa: F401+ except Exception: # noqa: BLE001+ return None+ try:+ cap = cv2.VideoCapture(str(video_path))+ fps = cap.get(cv2.CAP_PROP_FPS) or fps_hint or 24.0+ total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)+ if total <= 0:+ cap.release()+ return None+ duration = total / fps+ start_s = max(0.0, duration - max(0.1, float(window_s)))+ start_frame = int(start_s * fps)+ cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)+ casc = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")+ best = None+ i = start_frame+ while i < total:+ ok, fr = cap.read()+ if not ok:+ break+ gray = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY)+ ratio = _mouth_open_ratio_from_gray(gray, casc)+ if ratio is not None and (best is None or ratio < best[1]):+ best = (i, ratio)+ i += 1+ cap.release()+ if best is None:+ return None+ frame_idx, ratio = best+ return {"time_s": round(frame_idx / fps, 3), "openness": round(ratio, 4)}+ except Exception: # noqa: BLE001+ return None+++def take_lipsync_score(path) -> float | None:+ """How well the mouth follows the voice in one clip, or None when there is+ no face or no speech to judge (or cv2 is not importable). See+ `_take_lipsync_score_and_lag` for the method."""+ got = _take_lipsync_score_and_lag(path)+ return None if got is None else got[0]+++def _lipsync_best_lag_core(mouth_series, ref_series, head: int, search: int):+ """PURE: the lag search `_take_lipsync_score_and_lag` runs, generalised+ to an external reference series and an explicit "lag zero" index —+ tested with synthetic arrays (`test_editor_film_sync.py`) precisely so+ the sign convention below can be trusted without a real face and voice+ on hand to check it against. `head` is the index into `ref_series`+ where the clip is CURRENTLY placed; a positive returned lag means the+ mouth matches reference content further ALONG `ref_series` — later —+ than where the clip sits today.++ Returns `(best correlation, best lag in samples)`, or `None` when no+ window in range has enough signal to correlate.+ """+ import numpy as np # noqa: PLC0415+ m = np.asarray(mouth_series, dtype=float)+ r = np.asarray(ref_series, dtype=float)+ n = len(m)+ if n < 8:+ return None+ best = None+ best_lag = 0+ for lag in range(-search, search + 1):+ start = head + lag+ if start < 0 or start + n > len(r):+ continue+ y_ = r[start:start + n]+ if len(y_) == n and m.std() > 1e-6 and y_.std() > 1e-6:+ c = float(np.corrcoef(m, y_)[0, 1])+ if best is None or c > best:+ best, best_lag = c, lag+ return None if best is None else (best, best_lag)+++def _lipsync_align_measure(src_opens: dict, vfps: float, song, sr: int, *,+ film_start: float, film_end: float,+ src_start: float = 0.0, speed: float = 1.0,+ song_offset: float = 0.0, play_start: float = 0.0,+ play_end: float | None = None, fps: float = FPS,+ search_frames: int = 6) -> dict | None:+ """PURE (numpy only): the Auto-align measurement on the FILM'S clock.++ `src_opens` is {source frame index: mouth openness} for the take, as+ decoded (`vfps` its frame rate); `song` is the soundtrack FILE's mono+ samples from track second 0 at `sr`. The clip plays source seconds+ `src_start + (t - film_start) * speed` at film second t, and the track+ second at film second t is `t + song_offset` (music_window's `offset`),+ audible only inside [play_start, play_end).++ EDITOR-9 (Codex 4.17.0): the caller used to decode the WHOLE take from+ frame 0 and compare it with the song around the clip's SLOT — a ten-+ second take trimmed to four compared 240 mouth samples with ~108 song+ samples and returned None, which the route reported as "already+ matches". The mouth series here is the source WINDOW actually on the+ film, resampled to the film's frames at the clip's speed.++ Returns {"score", "lag_frames", "fps", "delta_sec"} or None when the+ window cannot be measured (too short, no face, no signal).++ EDITOR-8 (Codex 4.17.0): `lag_frames` > 0 means the mouth matches song+ content LATER than where the clip sits — the picture is early — so the+ correction plays EARLIER source at each film second: `delta_sec`, the+ slip to apply to the source in-point, is `-lag / fps * speed`. The+ route used to hand the client `+lag / fps` and the slip doubled the+ error it measured.+ """+ import numpy as np # noqa: PLC0415+ fps = float(fps or FPS)+ sp = float(speed or 1.0)+ n = int(round((float(film_end) - float(film_start)) * fps))+ if n < 24 or not src_opens:+ return None+ m = np.full(n, np.nan)+ for k in range(n):+ i = int(round((float(src_start) + k * sp / fps) * float(vfps)))+ v = src_opens.get(i)+ if v is not None:+ m[k] = v+ if np.isnan(m).all():+ return None+ m = np.where(np.isnan(m), np.nanmean(m), m)+ m = np.convolve(m, np.ones(3) / 3, "same")+ margin = search_frames / fps+ s0 = max(0.0, float(film_start) - margin)+ head = int(round((float(film_start) - s0) * fps))+ n_ref = head + n + search_frames + 1+ a = np.asarray(song, dtype=np.float32)+ hi = float(play_end) if play_end is not None else len(a) / float(sr)+ rms = np.zeros(n_ref)+ for j in range(n_ref):+ t0 = s0 + j / fps + float(song_offset) # track seconds+ t1 = t0 + 1.0 / fps+ if t1 <= float(play_start) or t0 >= hi:+ continue+ i0 = max(0, int(round(max(t0, float(play_start)) * sr)))+ i1 = min(len(a), int(round(min(t1, hi) * sr)))+ if i1 > i0:+ rms[j] = float(np.sqrt(np.mean(a[i0:i1] ** 2) + 1e-12))+ r = np.convolve(rms, np.ones(3) / 3, "same")+ got = _lipsync_best_lag_core(m, r, head, search_frames)+ if got is None:+ return None+ score, lag = got+ return {"score": round(score, 3), "lag_frames": int(lag), "fps": fps,+ "delta_sec": round(-lag / fps * sp, 4)}+++_LIPSYNC_SONG_CACHE: dict = {}+++def _lipsync_song_16k(song_path):+ """The soundtrack as mono 16 kHz float samples from track second 0 —+ decoded ONCE per file (and mtime) rather than once per singing shot."""+ import numpy as np # noqa: PLC0415+ try:+ st = Path(song_path).stat()+ except OSError:+ return None+ key = (str(song_path), st.st_mtime_ns, st.st_size)+ got = _LIPSYNC_SONG_CACHE.get("song")+ if got is not None and got[0] == key:+ return got[1]+ raw = subprocess.run([str(FFMPEG), "-loglevel", "error", "-i", str(song_path),+ "-vn", "-ac", "1", "-ar", "16000", "-f", "s16le", "-"],+ capture_output=True, check=True, timeout=120).stdout+ song = np.frombuffer(raw, np.int16).astype(np.float32) / 32768.0+ _LIPSYNC_SONG_CACHE["song"] = (key, song)+ return song+++def _sbe_edit_for_analysis(sedit, bdir, raw: str):+ """EDITOR-13 (Codex 4.17.0): WHAT MATCH COLOUR AND AUTO-ALIGN MEASURE.++ Both used to read edit.json — the last SAVE — while their proposals were+ applied to the clips on screen by id. A clip replaced or trimmed since+ the save kept its id, so the correction measured on the old file or+ window landed on the new one; a clip added since was never measured.+ The Editor now sends the arrangement on screen (`edit`, the same JSON a+ save carries); it is validated exactly as a save is and measured as+ sent. Without it (a script, an older tab) the saved file is used.++ Returns `(edit, None)` or `(None, (message, status))`.+ """+ if raw:+ try:+ doc = json.loads(raw)+ except (TypeError, ValueError) as exc:+ return None, (f"bad edit JSON: {exc}", 400)+ if not isinstance(doc, dict):+ return None, ("bad edit JSON: not an object", 400)+ blocking = sedit.blocking_errors(sedit.validate_edit(doc))+ if blocking:+ return None, ("the timeline has a problem to fix first: "+ + blocking[0]["message"], 400)+ return sedit.normalise_edit(doc), None+ try:+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ return None, (str(exc), 500)+ return edit, None+++def take_lipsync_best_lag_vs_song(video_path, song_path, film_start: float,+ film_end: float, *, src_start: float = 0.0,+ speed: float = 1.0, song_offset: float = 0.0,+ play_start: float = 0.0,+ play_end: float | None = None,+ search_frames: int = 6) -> dict | None:+ """FILM-05 "Auto-align lip-sync": where in the SONG does this clip's own+ mouth motion actually line up, against where it sits on the film today?++ Deliberately NOT a self-correlation against the clip's own embedded+ audio (that is what `take_lipsync_score` answers, and a linked a2v+ clip's picture and its own track are one file — slipping the picture+ would carry both, changing nothing about how they agree with each+ other). This is the same face-tracking pass, correlated instead against+ the EXTERNAL song around the clip's current position — the only+ reference a slip on the FILM can actually be measured against. CPU+ only: no render, a few seconds of ffmpeg and OpenCV per clip.++ Only the source window on the film is decoded (`src_start` for+ `(film_end - film_start) * speed` source seconds); the measurement is+ `_lipsync_align_measure`, which owns the clock and the sign.+ """+ try:+ import cv2 # noqa: PLC0415+ import numpy as np # noqa: PLC0415+ except Exception: # noqa: BLE001+ return None+ try:+ sp = float(speed or 1.0)+ casc = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")+ cap = cv2.VideoCapture(str(video_path)); vfps = cap.get(cv2.CAP_PROP_FPS) or 24.0+ src_end = float(src_start) + (float(film_end) - float(film_start)) * sp+ first_i = max(0, int(float(src_start) * vfps) - 1)+ last_i = int(src_end * vfps) + 2+ opens: dict = {}+ box = None; i = 0+ while i <= last_i:+ if i < first_i:+ if not cap.grab():+ break+ i += 1+ continue+ ok, fr = cap.read()+ if not ok:+ break+ g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY)+ if box is None or (i - first_i) % max(1, int(vfps)) == 0:+ f = casc.detectMultiScale(g, 1.1, 5, minSize=(80, 80))+ if len(f):+ box = max(f, key=lambda b: b[2] * b[3])+ if box is not None:+ x, y, w, h = box+ roi = g[y + int(h * 0.62):y + h, x + int(w * 0.25):x + int(w * 0.75)]+ if roi.size:+ opens[i] = float((roi < (np.median(roi) - 40)).mean())+ i += 1+ cap.release()+ if not opens:+ return None+ song = _lipsync_song_16k(song_path)+ if song is None:+ return None+ return _lipsync_align_measure(+ opens, vfps, song, 16000, film_start=film_start, film_end=film_end,+ src_start=src_start, speed=sp, song_offset=song_offset,+ play_start=play_start, play_end=play_end, fps=FPS,+ search_frames=search_frames)+ except Exception: # noqa: BLE001+ return None+++def extract_frame_png(video_path, at_sec: float, out_path) -> bool:+ """Write the frame at `at_sec` to `out_path` (PNG) via ffmpeg. True on+ success. Used by "Continue the song" to turn a picked closed-mouth+ timestamp into an anchor image file."""+ try:+ out_path = Path(out_path)+ out_path.parent.mkdir(parents=True, exist_ok=True)+ subprocess.run(+ [str(FFMPEG), "-y", "-loglevel", "error", "-ss", f"{max(0.0, at_sec):.3f}",+ "-i", str(video_path), "-frames:v", "1", str(out_path)],+ check=True, timeout=60)+ return out_path.exists() and out_path.stat().st_size > 0+ except Exception: # noqa: BLE001+ return False+++def take_lipsync_best_lag(path) -> dict | None:+ """FILM-05: the lag (in FRAMES, positive = the mouth is AHEAD of the+ voice — the picture needs to slip LATER) that best matches the clip's+ own mouth-aperture series against its own audio, plus the clip's fps —+ the CPU-only "Auto-align lip-sync" the app already had the parts for and+ never assembled: the scorer already computed a best lag on every call,+ it just answered the wrong half of its own result.+ """+ got = _take_lipsync_score_and_lag(path)+ if got is None:+ return None+ score, lag, fps = got+ return {"score": round(score, 3), "lag_frames": int(lag), "fps": fps}++def take_frame_light(path, at_sec: float) -> tuple[float, float] | None:"""(mean luma 0..1, warmth = mean R − mean B, −1..1) of one frame."""try:@@ -19710,6 +22253,129 @@ def take_frame_light(path, at_sec: float) -> tuple[float, float] | None:return None+def take_frame_rgb(path, at_sec: float) -> tuple[float, float, float] | None:+ """(mean R, mean G, mean B), each 0..1, of one frame — FILM-14's "Match+ colour": the per-channel means `color_seam_fade` (scripts/join_smooth.py)+ already matches seams with, sampled once per clip instead of once per cut.+ """+ try:+ raw = subprocess.run([str(FFMPEG), "-loglevel", "error", "-ss", f"{max(0.0, at_sec):.3f}",+ "-i", str(path), "-frames:v", "1", "-vf", "scale=64:36", "-f", "rawvideo",+ "-pix_fmt", "rgb24", "-"], capture_output=True, check=True, timeout=60).stdout+ if len(raw) < 64 * 36 * 3:+ return None+ px = list(raw)+ n = len(px) / 3+ r = sum(px[0::3]) / n; g = sum(px[1::3]) / n; b = sum(px[2::3]) / n+ return (r / 255.0, g / 255.0, b / 255.0)+ except Exception: # noqa: BLE001+ return None+++def _sb_crop_to_aspect(path, aspect_key: str, deliver: dict | None = None) -> str | None:+ """FILM-58: sequence aspect. Center-crops an already-assembled film to+ `aspect_key` ('9:16' | '1:1') in place — a `.tmp` sibling, then+ `os.replace`, so a failed crop never leaves a half-written file where+ the real one was. '16:9' (and anything else unknown) is a no-op: every+ film already renders at its own native shape, and this never pads or+ stretches — only crops, so nothing outside the frame is invented.++ Deliberately a POST-PROCESS pass rather than a change to the assembly+ filtergraph: the crop applies to the FINISHED frame the same way for+ every kind of segment (video, still, slug, a transition's dissolve),+ with none of the per-kind branching `_sb_film_filtergraph` would need+ to thread it through correctly.++ `deliver` is the render's resolved delivery (`_sb_deliver`). EDITOR-7+ (Codex 4.17.0): the crop re-encodes the picture, and it used to do that+ with ffmpeg's defaults into a `.mp4` temp that then REPLACED the+ delivery — a HEVC or ProRes master with 9:16 or 1:1 on came out as+ default-H.264 in whatever container the name said. The crop now encodes+ with the delivery's own video settings (`_sb_encode_args`), into a temp+ of the delivery's own container, and copies the sound untouched.+ """+ ratio = {"9:16": 9.0 / 16.0, "1:1": 1.0}.get(str(aspect_key or ""))+ if ratio is None:+ return None+ try:+ import storyboard_edit as _se # noqa: PLC0415+ info = _se.probe_media(path)+ except Exception as exc: # noqa: BLE001+ return f"could not read the rendered film: {exc}"+ w, h = int((info or {}).get("w") or 0), int((info or {}).get("h") or 0)+ if w <= 0 or h <= 0:+ return "could not read the rendered film's size"+ # Fit the target ratio INSIDE the source frame. Keep the full height and+ # derive the width first — right for a portrait/square target cropped+ # from a wider source, which is the shape every one of these presets is+ # for. If that width would not fit (a target WIDER than the source,+ # which none of today's presets are, but a future one could be), fall+ # back to keeping the full width instead. Either way only ever crops,+ # never pads.+ tw, th = round(h * ratio), h+ if tw > w:+ tw, th = w, round(w / ratio)+ tw -= tw % 2+ th -= th % 2+ if tw <= 0 or th <= 0 or (tw == w and th == h):+ return None+ src = Path(path)+ tmp = str(src.with_name(f".{src.stem}.aspect-{os.urandom(4).hex()}{src.suffix}"))+ dl = deliver or _sb_deliver(None, None)+ enc = _sb_encode_args(dl, output_codec_settings())+ # The encoder's VIDEO half only: every `-c:a`/`-b:a` pair is dropped and+ # the already-mixed (and, if asked, loudness-normalised) sound is copied.+ venc: list[str] = []+ k = 0+ while k < len(enc):+ if enc[k] in ("-c:a", "-b:a"):+ k += 2+ continue+ venc.append(enc[k])+ k += 1+ crop_cmd = [str(FFMPEG), "-y", "-loglevel", "error", "-i", str(path),+ "-vf", f"crop={tw}:{th}:(iw-{tw})/2:(ih-{th})/2",+ *venc, "-c:a", "copy", tmp]+ try:+ film_job = _sb_film_job_ctx()+ if film_job is not None:+ # Inside an Editor film job: the crop is Cancel-able too.+ _sb_film_job_ffmpeg(crop_cmd, "Film aspect crop", film_job, timeout=300)+ else:+ subprocess.run(crop_cmd, check=True, capture_output=True, timeout=300)+ except Exception as exc: # noqa: BLE001+ try:+ Path(tmp).unlink(missing_ok=True)+ except Exception: # noqa: BLE001+ pass+ return f"the {aspect_key} crop failed: {exc}"+ os.replace(tmp, str(path))+ return None+++def _sb_match_colour_grade(rgb: tuple[float, float, float],+ ref: tuple[float, float, float]) -> dict:+ """FILM-14 "Match colour": the correction that brings `rgb`'s mean+ toward `ref`'s mean — `color_seam_fade`'s own per-channel OFFSET maths+ (scripts/join_smooth.py: mean only, deliberately no std/contrast+ rescale, so a high-key frame does not clip its own highlights),+ expressed as the grade fields `_sb_grade_term` already renders, at full+ (100%) strength. A strength slider on the client scales these down;+ nothing here decides how much of the correction to apply.+ """+ r, g, b = rgb+ rr, rg, rb = ref+ dr, dg, db = rr - r, rg - g, rb - b+ exposure = max(-0.5, min(0.5, (dr + dg + db) / 3.0))+ # Warmth is R vs B; tint is G vs the R/B average. The 2x is the same+ # "half of half" scaling `_sb_grade_term`'s colorbalance mapping already+ # uses (rm/bm/gm at 0.4x of temp/tint) — undone here so a full-strength+ # correction actually closes the measured gap rather than a quarter of it.+ temp = max(-1.0, min(1.0, (dr - db) * 2.0))+ tint = max(-1.0, min(1.0, -(dg - (dr + db) / 2.0) * 2.0))+ return {"exposure": round(exposure, 6), "temp": round(temp, 6), "tint": round(tint, 6)}++def take_drift(path, duration: float | None = None) -> dict:"""How far the light moved across one clip: first frame vs last frame."""if duration is None:@@ -19752,6 +22418,48 @@ def take_estimate_minutes(engine: str, quality: str, seconds) -> float | None:return round(total, 1)+# VA-16: take_estimate_minutes priced only the base render. At run time each+# part can ALSO get one light-drift retake (_sb_reconcile's per-part check)+# and, for a spoken part, up to TAKE_LIPSYNC_RETAKES fresh-seed lip-sync+# retakes (_sb_lipsync_gate) — the UI's own copy said only "a part that+# drifts is rendered once more" and never mentioned the lip-sync retakes at+# all. A 1-min dialogue take priced at 28 min can take up to ~4x that in the+# worst case.+TAKE_LIGHT_DRIFT_RETAKES = 1+++def _take_retry_seed(original: object, offset: int) -> str:+ """The seed a take retry (light-drift or lip-sync) should submit.++ An EXPLICIT seed gets the historical deterministic offset, so a user who+ pinned a seed to reproduce a take still gets a reproducible retake seed+ that doesn't collide with the first attempt. "-1" (random — the default,+ and what most One Shot renders use) stays "-1": a fresh roll, same as+ the base part got. Before this, int("-1") + offset never raised (a+ valid int), so the deterministic branch ran unconditionally and every+ random take's retakes landed on the exact same seed, every time, on+ every install (VA-16)."""+ raw = str(original if original is not None else "-1").strip()+ if raw in ("", "-1"):+ return "-1"+ try:+ return str(int(raw) + int(offset))+ except (TypeError, ValueError):+ return "-1"+++def take_estimate_minutes_worst(engine: str, quality: str, seconds) -> float | None:+ """The ceiling take_estimate_minutes doesn't show: every part hitting+ its worst case (one light-drift retake plus every TAKE_LIPSYNC_RETAKES+ lip-sync retake). This is a mechanism-derived CEILING, not a fleet-+ measured rate — the UI must label it "up to", never a plain estimate."""+ base = take_estimate_minutes(engine, quality, seconds)+ if base is None:+ return None+ worst_factor = 1 + TAKE_LIGHT_DRIFT_RETAKES + TAKE_LIPSYNC_RETAKES+ return round(base * worst_factor, 1)++def _sb_h3_cost(quality_key: str, length_key: str):"""The MEASURED wall clock for one H3 cell, in seconds — the hookstoryboard.estimate() takes so the cost model lives in exactly one place.@@ -19818,6 +22526,12 @@ def _sb_job_index() -> dict:idx[j["id"]] = {"status": j.get("status"),"output_path": j.get("output_path"),"error": j.get("error")}+ # SAFETY-8: a job the last Clear removed is still "queued" while its+ # Undo is offered — otherwise FILM-18 unhooks its shot in that window+ # and the restored job's clip never reaches the board.+ for j in _queue_undo_live_locked():+ if j.get("id") and j["id"] not in idx:+ idx[j["id"]] = {"status": "queued", "output_path": None, "error": None}return idx@@ -19842,6 +22556,46 @@ def _sb_sidecar_seed(path) -> int | None:return None+def _sb_patch_board(board_id: str, *, shots: dict | None = None,+ board_fields: dict | None = None) -> dict | None:+ """Re-load the board FRESH from disk and merge in only the given fields —+ never a whole board object a caller has been holding across a wait.++ FILM-20: the lip-sync gate and auto-film both load a board once, spend+ minutes on a wait (a retake render, an ffmpeg assembly), then saved that+ SAME stale in-memory board back — silently reverting any edit (a prompt+ change, a reorder, a grade, a shot added or removed) the user made on+ the Storyboard tab in the meantime. This is the single write path both+ now use: it reloads the CURRENT board, patches only the fields the+ caller owns, and saves that.++ `shots` is `{shot_uid_or_n: {field: value, ...}}` — a shot is matched by+ `uid` first (stable across a reorder mid-wait) and falls back to `n`+ only for a legacy board with no uid yet. `board_fields` is+ `{field: value, ...}` applied at the top level (e.g. `auto_film`).+ Returns the merged, saved board, or None when the board is gone.+ """+ try:+ board = storyboard.load_storyboard(STATE_DIR, board_id)+ except Exception:+ return None+ if board_fields:+ board.update(board_fields)+ if shots:+ rows = [s for s in (board.get("shots") or []) if isinstance(s, dict)]+ by_uid = {s.get("uid"): s for s in rows if s.get("uid")}+ by_n = {s.get("n"): s for s in rows}+ for key, fields in shots.items():+ target = by_uid.get(key) if key in by_uid else by_n.get(key)+ if target is None:+ # The shot this job was working on is gone from the CURRENT+ # board (deleted while the job ran) — nothing to patch.+ continue+ target.update(fields)+ storyboard.save_storyboard(STATE_DIR, board)+ return board++def _sb_lipsync_gate(board_id: str, batch: list, key: str, out_key: str, policy: dict,h3_ok: bool, chain_ok: bool, wait) -> None:"""Score every spoken shot of a rendered bucket and retake the ones that miss.@@ -19858,6 +22612,15 @@ def _sb_lipsync_gate(board_id: str, batch: list, key: str, out_key: str, policy:ns = [s.get("n") for s in batch if isinstance(s, dict)]board = storyboard.load_storyboard(STATE_DIR, board_id)shots = {s.get("n"): s for s in (board.get("shots") or []) if isinstance(s, dict)}+ # FILM-20: this board snapshot is read ONCE and this function runs for+ # minutes (a retake render, more than once). Every save below goes+ # through _sb_patch_board, which re-reads the CURRENT board and writes+ # only these shots' OWN fields — never this stale snapshot whole — so an+ # edit made on the Storyboard tab while this gate runs survives. `uid`+ # is what keeps a patch addressed to the right shot even if the user+ # reordered the board in the meantime; `n` is the fallback for a shot+ # that predates uid.+ uid_for = {n: (shots[n].get("uid") or n) for n in shots}best: dict = {} # n -> (score, path)# The job id and seed that MADE the kept take travel with it. Without# this the shot keeps pointing at the LAST retake's job, and the next@@ -19882,7 +22645,9 @@ def _sb_lipsync_gate(board_id: str, batch: list, key: str, out_key: str, policy:s["lipsync"] = {"score": round(sc, 3), "attempts": 0, "kept": str(out)}push(f"[storyboard] shot {n}: lip-sync {sc:+.2f}"+ ("" if sc >= TAKE_LIPSYNC_MIN else f" — under {TAKE_LIPSYNC_MIN:.2f}, the voice is not on the mouth"))- storyboard.save_storyboard(STATE_DIR, board)+ if best:+ _sb_patch_board(board_id, shots={uid_for[n]: {"lipsync": shots[n]["lipsync"]}+ for n in best})attempts: dict = {}for _round in range(TAKE_LIPSYNC_RETAKES):plan = sb_lipsync_retake_plan([shots[n] for n in best], {n: best[n][0] for n in best}, attempts)@@ -19899,7 +22664,7 @@ def _sb_lipsync_gate(board_id: str, batch: list, key: str, out_key: str, policy:h3_chain_prompts=chain_ok, h3_first_frame=bool(h3_ok and h3_supports_first_frame()),locations=storyboard.board_locations(board),wardrobe=storyboard.board_wardrobe(board), long_windows=bool(board.get("long_windows")),- style=str(board.get("style") or ""))+ style=str(board.get("style") or ""), light=storyboard.board_light(board))try:jid = _sb_enqueue({k: ("" if v is None else str(v)) for k, v in form.items()})except Exception as exc: # noqa: BLE001@@ -19910,7 +22675,11 @@ def _sb_lipsync_gate(board_id: str, batch: list, key: str, out_key: str, policy:ids.append((n, jid))push(f"[storyboard] shot {n}: retaking it for lip-sync with a fresh seed "f"({attempts[n]} of {TAKE_LIPSYNC_RETAKES})")- storyboard.save_storyboard(STATE_DIR, board)+ if ids:+ _sb_patch_board(board_id, shots={+ uid_for[n]: {"seed": shots[n]["seed"], key: shots[n][key],+ "status": "queued"}+ for n, _jid in ids})if not ids:breakif not wait([j for _, j in ids]):@@ -19946,7 +22715,11 @@ def _sb_lipsync_gate(board_id: str, batch: list, key: str, out_key: str, policy:s["status"] = "done"s["error"] = Nones["lipsync"] = {"score": round(best[n][0], 3), "attempts": attempts.get(n, 0), "kept": best[n][1]}- storyboard.save_storyboard(STATE_DIR, board)+ _sb_patch_board(board_id, shots={+ uid_for[n]: {out_key: shots[n][out_key], key: shots[n].get(key),+ "seed": shots[n]["seed"], "status": shots[n]["status"],+ "error": shots[n]["error"], "lipsync": shots[n]["lipsync"]}+ for n, _jid in ids})def _sb_reconcile(board: dict) -> bool:@@ -19958,9 +22731,23 @@ def _sb_reconcile(board: dict) -> bool:"""idx = _sb_job_index()changed = False+ seen_uids: set = set()for s in (board.get("shots") or []):if not isinstance(s, dict):continue+ # FILM-10 migration: a board saved before shots carried a stable+ # `uid` gets one here too, not only on the next full save — this is+ # the path a plain GET /storyboard/get takes, and it must not hand+ # back shots the save route (which merges by uid) can't yet match.+ if not s.get("uid") or s["uid"] in seen_uids:+ # BOARD-3: a duplicate (a retake saved by an earlier build) is+ # given its own identity; the FIRST holder keeps the old one.+ s["uid"] = storyboard.new_shot_uid()+ changed = True+ seen_uids.add(s["uid"])+ if s.get("still_source") != "user" and storyboard.is_user_still(s):+ s["still_source"] = "user" # BOARD-10+ changed = True# A CUT IS THE USER'S, NOT THE QUEUE'S (SB5-10). `status: "skipped"`# is what scheduling and export read, and the queue history still# holds the finished draft job of a shot cut after it rendered — so@@ -19980,14 +22767,52 @@ def _sb_reconcile(board: dict) -> bool:continuejob = idx.get(jid)if not job:- # The job is gone from queue AND history (history is capped).- # Leave the shot alone: if it has an output it is done, and if- # it doesn't, it is renderable again.+ # FILM-18: /queue/remove and /queue/clear drop a job with NO+ # history at all — it does not land here as "cancelled", it+ # is simply gone from `idx`. A shot whose status was already+ # "queued" or "rendering" for this job had nothing left to+ # ever move it out of that status: it read "queued" forever,+ # locked (the card and the trash button both gate on+ # non-done status) with no way to re-render or delete it. A+ # cut shot stays cut; anything else with no output from this+ # job goes back to pending — renderable again, deletable+ # again — and its dead job id is cleared.+ if not cut and not s.get(out_key) and s.get("status") in ("queued", "rendering"):+ s["status"] = "pending"+ s.pop(key, None)+ changed = Truecontinuest = (job.get("status") or "").lower()if st == "done" and job.get("output_path"):if s.get(out_key) != job["output_path"]:+ # FILM-07: a re-render (Rewrite, Retry, New still, Render+ # remaining) used to overwrite this key with no memory of+ # what it replaced — so a shot already on the timeline+ # kept pointing at a path that was now stale, and Export+ # shipped the old take. The old path goes into `takes`+ # (capped; oldest first) so `_sbe_relinks` can still find+ # a timeline clip that names it and offer this shot's+ # CURRENT output against it, the same one-clip-at-a-time+ # shape a retake already offers.+ old = s.get(out_key)+ if old and isinstance(old, str) and old != job["output_path"]:+ takes = s.setdefault("takes", [])+ if old not in {storyboard.take_path(t) for t in takes}:+ takes.append(old)+ del takes[:-20]s[out_key] = job["output_path"]+ # FILM-42: the "Draft"/"Delivery" badge used to be read+ # off the PASS that queued the clip, not the clip+ # itself — a shot re-queued as a retake, or one whose+ # pass and canvas disagree for any other reason, was+ # badged wrong. Stamp the clip's REAL, ffprobe'd pixel+ # size once here (on every new output, not every poll)+ # so the card can show and verify what actually rendered.+ dims = _probe_video_dims(job["output_path"])+ if dims != (0, 0):+ s["output_dims"] = list(dims)+ else:+ s.pop("output_dims", None)changed = Trueif cut:continue@@ -20027,15 +22852,32 @@ def _sb_reconcile(board: dict) -> bool:sj = s.get("still_job_id")if sj and not s.get("still"):job = idx.get(sj)- st = ((job or {}).get("status") or "").lower()- if st == "done" and (job or {}).get("output_path"):- s["still"] = job["output_path"]- s["still_error"] = None+ if job is None and sj != "skipped":+ # FILM-18, same class: the still's own job vanished from the+ # queue with no history (queue/remove, queue/clear). Left+ # alone, `still_job_id` stays set forever and the render+ # thread's `need` list — which skips any shot that already+ # carries one — never queues a replacement, so the shot can+ # never get its still. ("skipped" is a deliberate sentinel+ # for "could not even be queued, render unanchored" and is+ # never a real job id — never clear that one back off.)+ s.pop("still_job_id", None)changed = True- elif st in ("failed", "error", "cancelled"):- if s.get("still_error") != ((job or {}).get("error") or "the still could not be made"):- s["still_error"] = (job or {}).get("error") or "the still could not be made"+ else:+ st = ((job or {}).get("status") or "").lower()+ if st == "done" and (job or {}).get("output_path"):+ s["still"] = job["output_path"]+ s["still_error"] = None+ # FILM-46: a freshly-landed still always needs its own+ # approval, even if an earlier still on this same shot+ # was already approved — approving one composition must+ # never be read as approving whatever renders next.+ s["still_approved"] = Falsechanged = True+ elif st in ("failed", "error", "cancelled"):+ if s.get("still_error") != ((job or {}).get("error") or "the still could not be made"):+ s["still_error"] = (job or {}).get("error") or "the still could not be made"+ changed = Truefj = s.get("final_job_id")if fj and not s.get("final_output") and not cut:fst = ((idx.get(fj) or {}).get("status") or "").lower()@@ -20076,8 +22918,24 @@ def _sb_normalize(board: dict) -> dict:mode = storyboard.DEFAULT_ENGINE_MODEboard["engine_mode"] = modeshots = [s for s in (board.get("shots") or []) if isinstance(s, dict)]+ seen_uids: set = set()for i, s in enumerate(shots, start=1):s["n"] = i+ # FILM-10 / Priority 0: every shot needs a stable identity that+ # survives reorder/delete so server-side merges (the save route)+ # and client-side lookups (retake, relink, music-video layout) key+ # on IT, not on `n`. Boards saved before this field existed get one+ # assigned here and it is persisted back on the next save.+ # BOARD-3: a DUPLICATE uid is a second shot wearing the first's+ # identity (a retake cloned by an earlier build) — it gets its own;+ # the first holder keeps the original.+ if not s.get("uid") or s["uid"] in seen_uids:+ s["uid"] = storyboard.new_shot_uid()+ seen_uids.add(s["uid"])+ # BOARD-10: a music-video still set from the uploaded cast photo is+ # the user's, whether or not the board predates the marker.+ if s.get("still_source") != "user" and storyboard.is_user_still(s):+ s["still_source"] = "user"smode = s.get("mode")if smode not in storyboard.VALID_MODES:smode = "text"@@ -20190,9 +23048,19 @@ def _sb_board_summary(board: dict) -> dict:with _SB_LOCK:running = board.get("id") in _SB_RENDERSplanning = board.get("id") in _SB_PLANNERS+ # FILM-43: the board list had no dates and no thumbnail — every row+ # read the same as every other until you opened it. The first shot+ # with a clip stands in for a thumbnail; `created_at`/`updated_at`+ # are already written on every save, just not carried to the client.+ thumb = next((s.get("final_output") or s.get("draft_output")+ for s in shots if s.get("final_output") or s.get("draft_output")),+ None)return {"id": board.get("id"),"title": board.get("title") or "",+ "created_at": board.get("created_at") or 0,+ "updated_at": board.get("updated_at") or board.get("created_at") or 0,+ "thumb": thumb,"shots": len(shots),"done": sum(1 for s in shots if s.get("status") == "done"),# `done` counts shots THIS PANEL rendered as jobs. A board can hold@@ -20212,9 +23080,30 @@ def _sb_board_summary(board: dict) -> dict:# A board that has produced a film says so on its row. Cheap by# construction — see `_sb_film_summary`."film": _sb_film_summary(board),+ # FILM-43: `clips` above is board SHOTS with an output file on disk —+ # right for "X of Y rendered", wrong for "does this film have+ # something to edit". A film cut from Video-tab or imported clips (no+ # shots of its own) has a timeline and zero rendered shots, so the+ # Editor's film switcher — which filtered on `clips > 0` alone —+ # dropped it from the list entirely. A `Path.is_file()` stat, not a+ # parse: this is read once per board on every list.+ "has_timeline": _sb_has_timeline(board),}+def _sb_has_timeline(board: dict) -> bool:+ """Cheap and never fatal — a board summary must survive an editor+ module that failed to import (see `_sbe_import`'s own rule: that is a+ 503 on the editor routes, never a dead board list)."""+ bid = board.get("id")+ if not bid:+ return False+ try:+ return _sbe_import().edit_path(_sbe_board_dir(bid)).is_file()+ except Exception: # noqa: BLE001+ return False++def _sb_all_summaries() -> list:"""The one-line-per-board payload /status carries.@@ -20257,6 +23146,7 @@ def storyboard_status() -> dict:"planner_model_name": Path(model).name if model else "","planner_present": present,"ram_help": STORYBOARD_RAM_HELP,+ "ram_status": storyboard_planner_ram_status(),"engine_help": STORYBOARD_ENGINE_HELP,"engine_note": STORYBOARD_ENGINE_NOTE,"engine_note_no_h3": STORYBOARD_ENGINE_NOTE_NO_H3,@@ -20312,6 +23202,8 @@ def _sb_import_shots(board: dict, src: dict, only: set[int] | None = None) -> tunxt += 1copy = dict(s)copy["n"] = nxt+ # BOARD-3: an imported copy is a new shot on THIS board — its own uid.+ copy["uid"] = storyboard.new_shot_uid()# Provenance stays ON the shot. Without it an imported clip is# indistinguishable from one this film planned, and a re-plan would# rewrite somebody else's shot.@@ -20352,13 +23244,27 @@ def _sb_parse_locations(text: str) -> list[dict]:raw = line.strip()if not raw:continue+ # FILM-45/SYS-27: partition(":") missed ":" (U+FF1A, the fullwidth+ # colon Japanese input methods produce for regular typing) — a+ # Japanese "場所:説明" line fell through to the no-colon branch and+ # lost its intended name/description split. Try ASCII first (the+ # common case, and partition's short-circuit is cheap), then the+ # fullwidth form.name, _, desc = raw.partition(":")+ if not desc:+ name, _, desc = raw.partition(":")+ if not desc.strip():+ # FILM-45: a Japanese location line uses the full-width colon+ # (":", U+FF1A), never the ASCII one — without this, every such+ # line fell straight through to the no-colon fallback below and+ # lost its name/description split.+ name, _, desc = raw.partition(":")if not desc.strip():name, desc = re.split(r"[,.]", raw, 1)[0], rawname, desc = name.strip()[:60], desc.strip()[:storyboard.LOCATION_DESC_MAX]if not name or not desc:continue- lid = re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")[:40]+ lid = _unicode_slug(name, max_chars=40, fallback="")if not lid:lid = f"loc{len(out) + 1}"if not lid[0].isalnum():@@ -20435,6 +23341,44 @@ def _sb_claim_planner(board_id: str):return None+def _sb_board_busy_reason(board_id: str, board: dict | None = None) -> str | None:+ """Why this board cannot be REPLACED right now, or None when it can.++ BOARD-1: re-planning a music video swapped the whole board while its+ dispatcher and its shots' jobs were still live — the job ids and the+ render intent vanished with the old shots, finished jobs had nothing to+ land on, and Stop could no longer find them. A board is busy while it+ has a render/plan slot, OR while any job its shots point at is still+ queued or rendering (a dispatcher that already queued its last bucket+ has left, but its jobs have not). Call under `_SB_LOCK` and keep holding+ it through the save, so no render can be claimed between the check and+ the replacement.+ """+ with _SB_LOCK:+ if board_id in _SB_RENDERS:+ return ("This music video is rendering. Stop it on the Storyboard "+ "tab first, then plan it again.")+ if board_id in _SB_PLANNERS:+ return "This film is still being planned. Try again when it's finished."+ ids = set()+ for s in ((board or {}).get("shots") or []):+ if isinstance(s, dict):+ for k in ("draft_job_id", "final_job_id", "still_job_id"):+ if s.get(k) and s.get(k) != "skipped":+ ids.add(s[k])+ if ids:+ with LOCK:+ live = {j.get("id") for j in (STATE.get("queue") or [])+ if isinstance(j, dict)}+ cur = STATE.get("current")+ if isinstance(cur, dict):+ live.add(cur.get("id"))+ if ids & live:+ return ("Shots from this music video are still in the queue. Stop "+ "it on the Storyboard tab first, then plan it again.")+ return None++def _sb_release_planner(*board_ids) -> None:"""Hand the planner slot back. Used on every early return AFTER a claim."""with _SB_LOCK:@@ -20716,25 +23660,87 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:push(f"[storyboard] planning {n_shots} shots — "f"the renderer's memory is borrowed for about a minute")- result = storyboard_planner.plan_film(- concept,- n_shots=n_shots,- style=brief.get("style") or "",- characters=brief.get("characters") or None,- must_include=must or None,- feedback=brief.get("feedback") or None,- previous=previous,- # The film's own choice, and it is a PLANNING input: the planner- # writes H3's three-field dialect or LTX prose depending on it, so- # this cannot be applied after the fact. With no H3 pack installed- # there is only one answer it could honestly give.- engine=(brief.get("engine_mode") or "auto") if _sb_h3_available() else "ltx",- board_id=board_id,- locations=brief.get("locations") or None,- known_character_ids=_sb_known_character_ids(),- max_dim=_sb_max_dim(),- session=session,- )+ reroll_ns_list = list(brief.get("reroll_ns") or [])+ shot_notes = brief.get("shot_notes") or {}+ if reroll_ns_list and shot_notes:+ # FILM-01: "Rewrite N shots" used to join every shot's note into+ # ONE feedback string ("shot 3: ...\nshot 7: ...") and make a+ # single shot-mode planner call. The parser's "shot N:" pattern+ # only ever matches the FIRST header, and (re.DOTALL) folds every+ # note after it into that one shot's note — shot 3 got rewritten,+ # every other named shot never reached the model at all, and it+ # re-rendered on its old prompt and old pinned seed: the same+ # clip again, burning the render for nothing.+ #+ # Fixed by running ONE shot-mode rewrite per n, in this one+ # planner session (one model load): each call replaces exactly+ # its own shot and carries every other shot across unchanged+ # (plan_film's own per-shot contract — see _coerce_for_mode),+ # which is also what resets that shot's seed, so a genuinely+ # rewritten shot renders as a genuinely different clip.+ spec = {"schema": (previous or {}).get("schema", 1), "id": board_id,+ "title": (previous or board).get("title"),+ "cast": (previous or board).get("cast"),+ "policy": (previous or board).get("policy"),+ "shots": (previous or board).get("shots")}+ attempts_total, elapsed_total, all_warnings, last_meta = 0, 0.0, [], {}+ result = spec+ for _rn in reroll_ns_list:+ note = shot_notes.get(_rn)+ if note is None:+ note = shot_notes.get(str(_rn))+ if note is None:+ continue+ one = storyboard_planner.plan_film(+ concept, n_shots=n_shots, style=brief.get("style") or "",+ characters=brief.get("characters") or None,+ must_include=must or None,+ feedback={"shot": _rn, "note": note},+ previous=spec,+ engine=(brief.get("engine_mode") or "auto") if _sb_h3_available() else "ltx",+ board_id=board_id,+ locations=brief.get("locations") or None,+ known_character_ids=_sb_known_character_ids(),+ max_dim=_sb_max_dim(),+ session=session,+ )+ with _SB_LOCK:+ cancelled = (_SB_PLANNERS.get(board_id) or {}).get("cancelled")+ if cancelled:+ return+ if storyboard_planner.is_plan_error(one):+ result = one+ break+ spec = one+ last_meta = one.get("_planner") or {}+ attempts_total += int(last_meta.get("attempts") or 1)+ elapsed_total += float(last_meta.get("elapsed_s") or 0.0)+ all_warnings.extend(last_meta.get("warnings") or [])+ else:+ result = spec+ result["_planner"] = {**last_meta, "attempts": attempts_total,+ "elapsed_s": round(elapsed_total, 2),+ "warnings": all_warnings}+ else:+ result = storyboard_planner.plan_film(+ concept,+ n_shots=n_shots,+ style=brief.get("style") or "",+ characters=brief.get("characters") or None,+ must_include=must or None,+ feedback=brief.get("feedback") or None,+ previous=previous,+ # The film's own choice, and it is a PLANNING input: the planner+ # writes H3's three-field dialect or LTX prose depending on it, so+ # this cannot be applied after the fact. With no H3 pack installed+ # there is only one answer it could honestly give.+ engine=(brief.get("engine_mode") or "auto") if _sb_h3_available() else "ltx",+ board_id=board_id,+ locations=brief.get("locations") or None,+ known_character_ids=_sb_known_character_ids(),+ max_dim=_sb_max_dim(),+ session=session,+ )with _SB_LOCK:cancelled = (_SB_PLANNERS.get(board_id) or {}).get("cancelled")@@ -20816,7 +23822,10 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:_spans = storyboard.spoken_spans(_s.get("prompt") or "")if not _spans:continue- _words = sum(len(x.split()) for x in _spans)+ # FILM-45: CJK words have no spaces between them — a plain+ # .split() folded a whole unspaced Japanese/Chinese/Korean line+ # into "1 word" and left it drastically under-timed.+ _words = sum(storyboard.spoken_word_count(x) for x in _spans)_need = storyboard.speech_fit_frames(_words, slow=storyboard.is_slow_read(_s.get("prompt") or ""))if int(_s.get("frames") or 0) < _need:@@ -20915,7 +23924,8 @@ def _sb_still_job_form(shot: dict, board: dict, policy: dict) -> dict:the still is the face on the sheet. Anything else takes the default imageengine. One image, the shot's seed when it has one."""prompt = storyboard.compose_shot_prompt(shot, storyboard.board_locations(board),- storyboard.board_wardrobe(board))+ storyboard.board_wardrobe(board),+ storyboard.board_light(board))still_prompt = storyboard.still_prompt(prompt)w = int(policy.get("width") or 0) or 1280hh = int(policy.get("height") or 0) or 704@@ -20949,15 +23959,35 @@ def _sb_still_job_form(shot: dict, board: dict, policy: dict) -> dict:def _sb_clear_still(board: dict, n: int, pass_name: str = "draft") -> dict | None:- """Forget shot `n`'s anchor still AND the clip that was rendered from it,- so the next render of that shot makes a new still first and starts the- clip from it. Returns the shot, or None when there is no shot `n`."""+ """Forget shot `n`'s clip and, for a MACHINE-MADE still, the still too —+ so the next render makes a new still first and starts the clip from it.+ Returns the shot, or None when there is no shot `n`.++ FILM-11: a music-video shot's still is the user's OWN uploaded cast+ photo (`still_source == "user"`, set by music_video.py), not disposable+ render cache. Popping it here used to (a) delete the user's picture with+ no replacement ever made — `shot_wants_still()` refuses a still for a2v+ shots because they're supposed to already have their own media, so the+ next render of a singing shot ran lip-sync with NO image at all — and+ (b) since the shot's `seed` stayed pinned, a second press rendered the+ exact same clip again. A user still is now kept as-is; only its job/+ output bookkeeping is cleared, and the shot is always reseeded so this+ is a genuine "New take", not a repeat of the last one.+ """shot = next((x for x in (board.get("shots") or [])if isinstance(x, dict) and x.get("n") == n), None)if shot is None:return None- for k in ("still", "still_job_id", "still_error"):- shot.pop(k, None)+ if storyboard.is_user_still(shot):+ # BOARD-10: legacy boards carry the provenance as music_video.image+ # only — recognised too, and the marker written back.+ shot["still_source"] = "user"+ shot.pop("still_job_id", None)+ shot.pop("still_error", None)+ else:+ for k in ("still", "still_job_id", "still_error", "still_approved"):+ shot.pop(k, None)+ shot["seed"] = random.randint(0, 2**31 - 1)key = "draft_job_id" if pass_name == "draft" else "final_job_id"out_key = "draft_output" if pass_name == "draft" else "final_output"shot.pop(key, None)@@ -20967,6 +23997,79 @@ def _sb_clear_still(board: dict, n: int, pass_name: str = "draft") -> dict | Nonreturn shot+def _sb_new_take(board: dict, n: int) -> dict | None:+ """Archive shot `n`'s current clip(s) into `takes[]` and put it back to+ pending with a fresh seed. Returns the shot, or None when there is no+ shot `n`.++ FILM-22: a "done" shot could only be changed through an LLM Rewrite,+ which refuses outright while the queue is non-empty — there was no way+ to simply ask for a plain re-render, or to unlock the prompt/duration/+ seed for a hand edit, without spending a planner call. This is that+ escape hatch: no planner, no LLM, just the shot put back to a renderable+ state with a genuinely different seed (a repeat press must not produce+ the same clip again).++ The clip on disk is never deleted, only archived on the shot: `takes[]`+ entries are `{"path", "pass", "seed", "at"}` (file, which pass made it,+ the seed that made it, unix time archived) — a small, stable shape other+ UI (a future "swap in a take" picker, FILM-07/08) can read without+ knowing anything about how a take got there.+ """+ shot = next((x for x in (board.get("shots") or [])+ if isinstance(x, dict) and x.get("n") == n), None)+ if shot is None:+ return None+ takes = shot.setdefault("takes", [])+ for out_key, pass_name in (("draft_output", "draft"), ("final_output", "final")):+ path = shot.get(out_key)+ if path:+ takes.append({"path": path, "pass": pass_name,+ "seed": shot.get("seed"), "at": int(time.time())})+ for k in ("draft_output", "final_output", "draft_job_id", "final_job_id",+ "error", "stale_output"):+ shot.pop(k, None)+ shot["seed"] = random.randint(0, 2**31 - 1)+ shot["status"] = "pending"+ shot["grade"] = None+ return shot+++def _sb_set_render_intent(board: dict, pass_name: str, only: list | None,+ auto: bool = False) -> None:+ """Record that a render was STARTED, so a panel restart mid-render is+ visible (and recoverable) instead of silent. See FILM-17.++ `_sb_render_thread` queues one bucket of shots at a time and lives only+ in the memory of the running process (`_SB_RENDERS`). A Pinokio update,+ crash or restart during an overnight render kills that thread — the+ shots already queued still finish (panel_queue.json re-queues them and+ `_sb_reconcile` folds the result back onto the board), but nothing is+ left to queue the NEXT bucket, so a 52-shot board quietly stops at+ "18 of 52" with no thread, no error, and no film. `_sb_boot_reconcile`+ reads this back and resumes.+ """+ board["render_intent"] = {"pass": pass_name, "only": list(only) if only else None,+ "auto": bool(auto)}+++def _sb_clear_render_intent(board: dict) -> None:+ board.pop("render_intent", None)+++def _sb_render_intent_done(board: dict, intent: dict) -> bool:+ """True when every shot the intent covers already has this pass's output+ (or is skipped) — nothing left to resume."""+ pass_name = intent.get("pass") or "draft"+ only = intent.get("only")+ out_key = "draft_output" if pass_name == "draft" else "final_output"+ shots = [s for s in (board.get("shots") or []) if isinstance(s, dict)+ and s.get("status") != "skipped"]+ if only:+ shots = [s for s in shots if s.get("n") in only]+ return all(s.get(out_key) for s in shots)++def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:"""Submit the film ONE BUCKET AT A TIME, then wait for it.@@ -20988,6 +24091,25 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:# bucket waited. It stays failed, with its error on the card, until the# user presses Render (or Retry) again, which is a new run.attempted: set = set()++ def _wait(ids_):+ """Wait for `ids_` to go terminal. False when the run was stopped."""+ while ids_:+ with _SB_LOCK:+ entry = _SB_RENDERS.get(board_id)+ if not entry or entry.get("stop"):+ return False+ idx = _sb_job_index()+ live = [j for j in ids_+ if (idx.get(j) or {}).get("status") in ("queued", "running")]+ if not live:+ break+ time.sleep(5.0)+ return True++ # BOARD-6: jobs this thread already waited out (or started waiting on) as+ # "in flight from before" — never waited on twice.+ awaited: set = set()try:while True:with _SB_LOCK:@@ -21007,11 +24129,49 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:if only:pending = [s for s in pending if s.get("n") in only]# A shot already carrying a live job id for this pass is in flight.+ inflight = [s for s in pending+ if s.get("status") in ("queued", "rendering") and s.get(key)]pending = [s for s in pendingif s.get("status") not in ("queued", "rendering") or not s.get(key)]pending = [s for s in pending if s.get("n") not in attempted]if not pending:- break+ # BOARD-6: nothing left to QUEUE is not the same as nothing+ # left to WAIT FOR. A resume after a restart finds the last+ # bucket's jobs restored to the queue — the pass is not over+ # until they land. Ending here cleared the render intent and+ # ran auto-film on a board with missing outputs, and nothing+ # retried it when those jobs finished.+ idx = _sb_job_index()+ live = [s for s in inflight+ if s.get(key) not in awaited+ and (idx.get(s.get(key)) or {}).get("status") in ("queued", "running")]+ if not live:+ break+ ids = [s.get(key) for s in live]+ awaited.update(ids)+ push(f"[storyboard] waiting for {len(ids)} shot(s) already in "+ f"the queue — {board.get('title')}")+ if not _wait(ids):+ return+ try:+ board = storyboard.load_storyboard(STATE_DIR, board_id)+ if _sb_reconcile(board):+ storyboard.save_storyboard(STATE_DIR, board)+ except Exception: # noqa: BLE001+ pass+ # The same completion gate a bucket queued by this thread gets.+ try:+ policy = (board.get("policy") or {}).get(pass_name) or {}+ h3_ok = _sb_h3_available()+ try:+ chain_ok = bool(h3_ok and h3_supports_chain_prompts())+ except Exception: # noqa: BLE001+ chain_ok = False+ _sb_lipsync_gate(board_id, live, key, out_key, policy,+ h3_ok, chain_ok, _wait)+ except Exception as exc: # noqa: BLE001+ push(f"[storyboard] lip-sync gate skipped: {type(exc).__name__}: {exc}")+ continuepolicy = (board.get("policy") or {}).get(pass_name) or {}h3_ok = _sb_h3_available()@@ -21070,6 +24230,43 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:_sb_reconcile(board)storyboard.save_storyboard(STATE_DIR, board)continue+ # FILM-46: "Stills first" — a still exists to let the user+ # decide the composition before the video (the expensive part)+ # spends any minutes on it. Any shot whose still has landed but+ # not yet been approved is held back from the video queue here;+ # the render pauses (not fails — a later Render/Retry, or the+ # user approving from the card, picks it back up) once nothing+ # left in this pass can proceed without an approval.+ #+ # BOARD-9: the hold used to require a still to EXIST, so a shot+ # whose still failed (or could not be queued) satisfied neither+ # this test nor the still batch above and went straight to the+ # expensive video, unanchored and unapproved — the one thing the+ # mode promises cannot happen. Every shot that should start from+ # a still is held until it is approved; for a failed still the+ # card offers "Try again" (restill) or "Render without a still"+ # (approve-still, which then allows the unanchored render).+ if board.get("stills_first") and board.get("anchor_stills"):+ _emode = board.get("engine_mode") or "auto"+ held = [s for s in pending+ if storyboard.shot_wants_still(s)+ and not s.get("still_approved")+ # The user's own photo has nothing to approve — the+ # card offers no Approve for it (FILM-11).+ and not storyboard.is_user_still(s)+ and storyboard.resolve_engine(+ s, engine_mode=_emode, h3_available=h3_ok) != "h3"]+ awaiting = {s.get("n") for s in held}+ if awaiting:+ pending = [s for s in pending if s.get("n") not in awaiting]+ if not pending:+ ready = sum(1 for s in held if s.get("still"))+ failed = len(held) - ready+ push(f"[storyboard] {ready} still(s) ready for approval"+ + (f", {failed} could not be made (try again, or "+ f"render without a still)" if failed else "")+ + f" — {board.get('title')}")+ breakbucket = storyboard.bucket_key(pending[0])batch = [s for s in pending if storyboard.bucket_key(s) == bucket]h3_ok = _sb_h3_available()@@ -21095,7 +24292,8 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:locations=storyboard.board_locations(board),wardrobe=storyboard.board_wardrobe(board),long_windows=bool(board.get("long_windows")),- style=str(board.get("style") or ""))+ style=str(board.get("style") or ""),+ light=storyboard.board_light(board))# make_job reads a form: every value is a string (or a list of# them). Normalise here so a bool/int never reaches f().job_form = {k: ("" if v is None else str(v)) for k, v in form.items()}@@ -21130,20 +24328,6 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:f"{bucket[0].upper()} — {board.get('title')}")# Wait for this bucket to go terminal before submitting the next.- def _wait(ids_):- while ids_:- with _SB_LOCK:- entry = _SB_RENDERS.get(board_id)- if not entry or entry.get("stop"):- return False- idx = _sb_job_index()- live = [j for j in ids_- if (idx.get(j) or {}).get("status") in ("queued", "running")]- if not live:- break- time.sleep(5.0)- return True-if not _wait(ids):return@@ -21184,7 +24368,16 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:stopped = bool((_entry or {}).get("stop"))try:board = storyboard.load_storyboard(STATE_DIR, board_id)- if _sb_reconcile(board):+ changed = _sb_reconcile(board)+ # FILM-17: this thread reaching its own end — normally, stopped,+ # or on an exception above — means there is nothing left for a+ # boot to resume. Only a hard kill of the whole process skips+ # this `finally`, which is exactly the case render_intent exists+ # to catch.+ if "render_intent" in board:+ _sb_clear_render_intent(board)+ changed = True+ if changed:storyboard.save_storyboard(STATE_DIR, board)# Delivered shots don't need their draft's Stage-A cache any more._sb_sweep_stage_a(board)@@ -21215,6 +24408,12 @@ def _sb_auto_after_plan(board_id: str) -> None:return_SB_RENDERS[board_id] = {"stop": False, "pass": "draft", "queued": 0,"auto": True}+ try:+ _b = storyboard.load_storyboard(STATE_DIR, board_id)+ _sb_set_render_intent(_b, "draft", None, auto=True) # FILM-17+ storyboard.save_storyboard(STATE_DIR, _b)+ except Exception:+ passpush(f"[storyboard] auto: rendering every shot of the plan")th = threading.Thread(target=_sb_render_thread, daemon=True,name=f"phos-sb-render-{board_id}",@@ -21247,8 +24446,11 @@ def _sb_auto_film(board: dict) -> dict | None:+ (" on the beat" if edit.get("beats") else "") + " — assembling the film")film = _sbe_render_edit(board, edit)if film.get("ok"):- board["auto_film"] = film.get("path")- storyboard.save_storyboard(STATE_DIR, board)+ # FILM-20: `board` was loaded by the CALLER, possibly a while ago —+ # the cut and the ffmpeg assembly above both take real time. Patch+ # only `auto_film` onto whatever is on disk NOW rather than saving+ # this whole (possibly stale) snapshot back over it.+ board = _sb_patch_board(board["id"], board_fields={"auto_film": film.get("path")}) or boardpush(f"[storyboard] auto: film ready — {Path(str(film['path'])).name}")else:push(f"[storyboard] auto: the film could not be assembled: {film.get('error')}")@@ -21325,9 +24527,17 @@ def _sb_boot_reconcile() -> None:planning screen forever waiting for a stage that can never advance. Caughtlive: the owner started a plan seconds before a restart.- Render state needs no equivalent, and that is the whole point of riding the- normal queue: panel_queue.json already re-queues an interrupted job, and- _sb_reconcile() re-attaches it to its shot on the next read.+ FILM-17: render state DOES need an equivalent. `_sb_render_thread` queues+ one bucket of shots at a time and lives only in `_SB_RENDERS`, in this+ process's memory — riding the normal queue covers the jobs already+ queued (panel_queue.json re-queues them, `_sb_reconcile` folds the+ result back), but nothing survives to queue the NEXT bucket. A 52-shot+ overnight render silently stopped at "18 of 52" after a Pinokio update,+ crash or restart, with no thread, no error and no film. Every render+ start now writes `board["render_intent"]` before the thread does+ anything, and the thread's own `finally` clears it — so a restart mid+ render is the ONE way it can still be set when this runs, and here it+ is auto-resumed exactly as if Render had been pressed again."""try:rows = storyboard.list_storyboards(STATE_DIR)@@ -21339,18 +24549,53 @@ def _sb_boot_reconcile() -> None:except Exception:continuep = board.get("planner") or {}- if p.get("state") != "running":+ if p.get("state") == "running":+ if not (board.get("shots") or []) and board.get("title") in ("", "Planning…", None):+ words = (board.get("concept") or "").split()+ board["title"] = " ".join(words[:6]) or "Untitled film"+ _sb_set_planner(board, state="failed", stage=None,+ error="the panel restarted while the planner was running",+ error_kind="restarted")+ try:+ storyboard.save_storyboard(STATE_DIR, board)+ push(f"[storyboard] {board.get('title')!r} was mid-plan when the panel "+ f"stopped — press Try again when you're ready")+ except Exception:+ pass+ continue++ intent = board.get("render_intent")+ if not isinstance(intent, dict):continue- if not (board.get("shots") or []) and board.get("title") in ("", "Planning…", None):- words = (board.get("concept") or "").split()- board["title"] = " ".join(words[:6]) or "Untitled film"- _sb_set_planner(board, state="failed", stage=None,- error="the panel restarted while the planner was running",- error_kind="restarted")try:- storyboard.save_storyboard(STATE_DIR, board)- push(f"[storyboard] {board.get('title')!r} was mid-plan when the panel "- f"stopped — press Try again when you're ready")+ if _sb_reconcile(board):+ storyboard.save_storyboard(STATE_DIR, board)+ if _sb_render_intent_done(board, intent):+ # Every job finished before the boot; only the thread's own+ # bookkeeping (and a possible auto-film) never ran.+ _sb_clear_render_intent(board)+ storyboard.save_storyboard(STATE_DIR, board)+ if intent.get("auto"):+ _sb_auto_film(board)+ push(f"[storyboard] {board.get('title')!r} had finished "+ f"rendering when the panel stopped — nothing to resume")+ continue+ pass_name = intent.get("pass") or "draft"+ only = intent.get("only")+ with _SB_LOCK:+ if r["id"] in _SB_RENDERS or r["id"] in _SB_PLANNERS:+ continue+ _SB_RENDERS[r["id"]] = {"stop": False, "pass": pass_name,+ "queued": 0, "auto": bool(intent.get("auto")),+ "resumed": True}+ th = threading.Thread(target=_sb_render_thread, daemon=True,+ name=f"phos-sb-render-{r['id']}",+ args=(r["id"], pass_name, only))+ with _SB_LOCK:+ _SB_RENDERS[r["id"]]["thread"] = th+ th.start()+ push(f"[storyboard] {board.get('title')!r} was still rendering "+ f"when the panel stopped — resuming automatically")except Exception:pass@@ -21395,7 +24640,25 @@ def _sb_sweep_stage_a(board: dict) -> int:def _sb_slug(text: str, words: int = 5) -> str:- parts = re.sub(r"[^a-z0-9]+", " ", (text or "").lower()).split()+ """FILM-45 / SYS-27: this used to be `[^a-z0-9]+ -> ' '` on the+ lowercased text — ASCII-only. A Japanese film title produced ZERO+ parts and fell straight to the bare "shot" fallback, so every shot+ in the film shared the same filename stem (shot_film.mp4,+ shot_film_2.mp4, ...) instead of one named for its own title.+ Splits on any run of non-letter/non-digit characters — Unicode-aware,+ so non-Latin scripts survive — and NFC-normalizes first, same as+ _unicode_slug (the sibling used for uploads and output filenames)."""+ s = unicodedata.normalize("NFC", (text or ""))+ parts: list[str] = []+ cur: list[str] = []+ for ch in s:+ if ch.isalnum():+ cur.append(ch.lower())+ elif cur:+ parts.append("".join(cur))+ cur = []+ if cur:+ parts.append("".join(cur))return "-".join(parts[:words]) or "shot"@@ -22095,6 +25358,48 @@ def _sb_brightness_term(adjust) -> str:return f"eq=brightness={b:.6f},"+def _sb_grade_term(adjust) -> str:+ """FILM-14: exposure/contrast/saturation/temp/tint — the 5-slider grade,+ a SEPARATE lever from the legacy single `adjust.brightness`+ (`_sb_brightness_term`), chained right after it. ffmpeg's `eq=` applies+ brightness, then contrast, then saturation to whatever pixels reach it,+ so two chained `eq=` nodes (the legacy one, then this one) compose+ exactly the way one combined call would — this reads only+ exposure/contrast/saturation, never `brightness`, and vice versa.++ `temp`/`tint` have no term in `eq=`; they ride `colorbalance`'s midtone+ channels instead — warmth on red/blue, tint on green — the same trick+ every NLE's own grade wheel uses under the hood. "The empty string is+ the point" still holds: an ungraded clip adds no filter at all.+ """+ if not isinstance(adjust, dict):+ return ""++ def f(key: str, default: float, lo: float, hi: float) -> float:+ try:+ v = float(adjust.get(key, default))+ except (TypeError, ValueError):+ return default+ if v != v or v in (float("inf"), float("-inf")):+ return default+ return max(lo, min(hi, v))++ exposure = f("exposure", 0.0, -0.5, 0.5)+ contrast = f("contrast", 1.0, 0.5, 1.8)+ saturation = f("saturation", 1.0, 0.0, 2.5)+ temp = f("temp", 0.0, -1.0, 1.0)+ tint = f("tint", 0.0, -1.0, 1.0)+ out = ""+ if abs(exposure) >= 1e-9 or abs(contrast - 1.0) >= 1e-9 or abs(saturation - 1.0) >= 1e-9:+ out += f"eq=brightness={exposure:.6f}:contrast={contrast:.6f}:saturation={saturation:.6f},"+ if abs(temp) >= 1e-9 or abs(tint) >= 1e-9:+ rm = max(-1.0, min(1.0, temp * 0.4))+ bm = max(-1.0, min(1.0, -temp * 0.4))+ gm = max(-1.0, min(1.0, -tint * 0.4))+ out += f"colorbalance=rm={rm:.6f}:gm={gm:.6f}:bm={bm:.6f},"+ return out++def _sb_film_segments(probes: list[tuple], cuts: dict | None) -> list[dict]:"""The legacy `probes` list, expressed as segments.@@ -22515,7 +25820,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,info = sg.get("info") or {}inp = sg.get("input")cut = sg.get("window")- bright = _sb_brightness_term(sg.get("adjust"))+ bright = _sb_brightness_term(sg.get("adjust")) + _sb_grade_term(sg.get("adjust"))reframe = _sb_frame_term(sg.get("frame"))fx = sg.get("fx")has_audio = bool(info.get("has_audio")) and kind == "video"@@ -22892,7 +26197,19 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:if kind == "still":info = _sb_probe_still(path)if info is None:+ # FILM-15: A MISSING OR UNREADABLE SLOT IS NOT NOTHING. This+ # used to `continue` — dropping the segment shrank the film+ # by exactly its length, sliding every later clip earlier+ # off the beat it was cut to, silently: the success toast+ # still said "Rendered N clips" and nothing on screen named+ # the file that was missing. Filling the slot with black at+ # its EXACT length keeps the film's total duration, and+ # every other clip's position, honest — `unreadable` still+ # carries the name so the caller can disclose it.unreadable.append(Path(path).name)+ segs.append({"kind": "slug", "input": None, "info": None,+ "window": None, "adjust": None,+ "duration": round(length, 6)})continueseg = {"kind": "still", "input": len(inputs), "info": info,"window": None, "adjust": adjust,@@ -22913,20 +26230,36 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:inputs.append(["-loop", "1", "-framerate", str(FPS),"-t", f"{length + tx_in + tx_out:.6f}", "-i", path])continue- info = _sb_probe_clip(path)- if info is None:- unreadable.append(Path(path).name)- continuetry:speed = float(entry.get("speed") or 1.0)except (TypeError, ValueError):speed = 1.0if speed <= 0:speed = 1.0+ info = _sb_probe_clip(path)+ if info is None:+ # FILM-15: see the still branch above — same fix, same reason.+ unreadable.append(Path(path).name)+ segs.append({"kind": "slug", "input": None, "info": None,+ "window": None, "adjust": None,+ "duration": round(length / speed, 6)})+ continue+ # THE FILE IS SHORTER THAN THE SLOT IT WAS CUT TO. `avail` is+ # everything the source actually has; `short_by` is what is missing.+ # This used to just render `avail` and let the slot quietly shrink —+ # the same "everything after it slides earlier" defect FILM-27 fixes+ # for an EMPTY hole, reproduced here for a TRUNCATED file (a clip+ # trimmed outside its own length, or media that was overwritten+ # shorter after the cut was made). The real footage still plays for+ # as long as it exists; black pads exactly the missing tail, so the+ # slot's length — and every later clip's position — stays what the+ # timeline says it is.+ avail = min(length, float(info["duration"]))+ short_by = length - availseg = {"kind": "video", "input": len(inputs), "info": info,"window": {"start": start, "end": end},"adjust": adjust,- "duration": min(length, float(info["duration"])) / speed,+ "duration": avail / speed,"path": path}if abs(speed - 1.0) > 1e-9:seg["speed"] = speed@@ -22962,6 +26295,11 @@ def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:passsegs.append(seg)inputs.append(["-i", path])+ if short_by > 1e-6:+ unreadable.append(Path(path).name + " (short — padded with black)")+ segs.append({"kind": "slug", "input": None, "info": None,+ "window": None, "adjust": None,+ "duration": round(short_by / speed, 6)})# A TRANSITION NEEDS BOTH OF ITS CLIPS. If the incoming one was dropped as# unreadable, the outgoing one is left describing a dissolve into nothing# — so the pair is reconciled here, on the list the graph will actually@@ -23006,9 +26344,17 @@ DELIVER_SIZES = {"native": 0, "1080p": 1080, "2160p": 2160}DELIVER_FINISH = {"none": 0, "grain": 9, "heavy_grain": 18}-def _sb_deliver(fmt, size, finish=None) -> dict:+def _sb_deliver(fmt, size, finish=None, loudnorm=False) -> dict:"""The delivery choice, resolved: `{format, size, height, ext, label,- finish, grain}`."""+ finish, grain, loudnorm}`.++ FILM-28: `loudnorm` is OFF by default — a mix the owner graded by ear is+ not something a render should quietly retarget. On, it asks the encode+ for -14 LUFS (streaming's own convention: Spotify, YouTube and TikTok+ all normalise around there), so a film meant for one of those does not+ need a second pass in another tool just to stop sounding quiet next to+ everything around it.+ """f = str(fmt or "h264").strip().lower()if f not in DELIVER_FORMATS:f = "h264"@@ -23021,9 +26367,12 @@ def _sb_deliver(fmt, size, finish=None) -> dict:label = DELIVER_FORMATS[f]["label"] + ("" if s == "native" else f" · {s}")if fin != "none":label += " · " + fin.replace("_", " ")+ if loudnorm:+ label += " · -14 LUFS"return {"format": f, "size": s, "height": DELIVER_SIZES[s],"ext": DELIVER_FORMATS[f]["ext"], "finish": fin,- "grain": DELIVER_FINISH[fin], "label": label}+ "grain": DELIVER_FINISH[fin], "loudnorm": bool(loudnorm),+ "label": label}def _sb_encode_args(deliver: dict, codec: dict) -> list[str]:@@ -23206,7 +26555,7 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,+ (1 if music else 0)codec = output_codec_settings()dl = _sb_deliver((deliver or {}).get("format"), (deliver or {}).get("size"),- (deliver or {}).get("finish"))+ (deliver or {}).get("finish"), (deliver or {}).get("loudnorm"))# ProRes is 4:2:2 10-bit; the graph's segments are normalised to the# requested pix_fmt, so ask for the one the encoder will write.graph_pix = "yuv422p10le" if dl["format"] == "prores" else codec["pix_fmt"]@@ -23253,9 +26602,27 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,# and only a finished, non-empty file replaces the old one.part = out_path.with_name(f".{out_path.stem}.part-{os.urandom(4).hex()}{out_path.suffix}")+ alabel = "[aout]"+ if dl.get("loudnorm"):+ # FILM-28: ONE SIMPLE PASS, on the already-mixed sum — after every+ # branch that decides what `[aout]` even IS (silent/under/replace,+ # split lanes, extra tracks) has settled on one signal, so it is one+ # link appended to the graph rather than four places to keep in sync.+ # Single-pass rather than the two-pass linear form: this is a+ # delivery convenience for a platform's loudness target, not a+ # broadcast QC pass, and a second full decode to measure first would+ # double the encode time for the last few tenths of a dB of accuracy.+ # EDITOR-2 (Codex 4.17.0): it used to be `-af` on the mapped+ # stream, and ffmpeg refuses that outright — "Simple and complex+ # filtering cannot be used together for the same stream" — so every+ # film rendered with -14 LUFS on failed before writing a frame.+ graph += ";[aout]loudnorm=I=-14:TP=-1.5:LRA=11[aoutln]"+ alabel = "[aoutln]"cmd += ["-filter_complex", graph,- "-map", vlabel, "-map", "[aout]",+ "-map", vlabel, "-map", alabel,+ ]+ cmd += [*_sb_encode_args(dl, codec),"-ar", str(rate),str(part),@@ -23387,8 +26754,9 @@ def _sb_plan_auto_edit(clips: list, *, music=None,f"on the grid")-def _sb_film_name(board: dict, deliver: dict | None = None) -> str:- """ONE film per board, one name — per DELIVERY.+def _sb_film_name(board: dict, deliver: dict | None = None, *,+ dest: Path | None = None) -> str:+ """ONE film per board, one name — per DELIVERY, per VERSION.Export wrote `<slug>_film.mp4` and the timeline's render wrote`<slug>_timeline.mp4`, into the same folder, from the same assembler — so@@ -23399,6 +26767,18 @@ def _sb_film_name(board: dict, deliver: dict | None = None) -> str:A different delivery IS a different file — `_film_hevc.mp4`,`_film_1080p.mp4`, `_film_prores.mov` — because a 4K ProRes master andthe H.264 the panel previews are both wanted, side by side.++ FILM-28: A SECOND RENDER AT THE SAME DELIVERY used to be the same+ question asked twice — three renders of "The car wash" wrote the same+ `…/the-car-wash-bizarro-aria_film.mp4` three times, and only the mtime+ changed. `dest`, when given, is scanned for the plain name and, failing+ that, `_r2`, `_r3`, … — the first free one. `_sb_films()` already lists+ every non-shot-copy file in the folder newest-first (the Film screen's+ own "other films" row), so this is the whole of "a Films list": once+ renders stop overwriting each other, there is more than one to list.+ `dest=None` (the default) keeps every existing caller's behaviour+ byte-for-byte — the plain name, always — which matters for callers that+ read a specific delivery's file back out by its predictable name."""base = f"{_sb_slug(board.get('title') or 'storyboard', 6)}_film"dl = deliver or {}@@ -23408,7 +26788,41 @@ def _sb_film_name(board: dict, deliver: dict | None = None) -> str:base += "_" + dl["size"]if dl.get("finish") and dl["finish"] != "none":base += "_" + dl["finish"]- return base + (dl.get("ext") or ".mp4")+ ext = dl.get("ext") or ".mp4"+ name = base + ext+ if dest is not None:+ n = 2+ # EDITOR-6: a name an unfinished render has claimed is as taken as+ # a file on disk — see `_sb_film_name_reserve`.+ while (dest / name).exists() or str(dest / name) in _SB_FILM_NAMES_IN_USE:+ name = f"{base}_r{n}{ext}"+ n += 1+ return name+++# EDITOR-6 (Codex 4.17.0): A VERSION NAME IS CLAIMED WHEN THE RENDER STARTS,+# not when its file lands. `_sb_film_name(dest=...)` picks the first name+# with no file behind it, and the film file does not exist until assembly+# finishes (`os.replace(part, out_path)`) — so two renders at the same+# delivery started before the first finished (a second tab, or a reload)+# both chose `…_film.mp4` and the later one replaced the earlier instead of+# becoming `_r2`. Choosing and claiming happen under one lock; the claim is+# released when the render ends, however it ends.+_SB_FILM_NAME_LOCK = threading.Lock()+_SB_FILM_NAMES_IN_USE: set = set()+++def _sb_film_name_reserve(board: dict, deliver: dict | None, dest: Path) -> str:+ with _SB_FILM_NAME_LOCK:+ name = _sb_film_name(board, deliver, dest=dest)+ _SB_FILM_NAMES_IN_USE.add(str(dest / name))+ return name+++def _sb_film_name_release(key: str | None) -> None:+ if key:+ with _SB_FILM_NAME_LOCK:+ _SB_FILM_NAMES_IN_USE.discard(str(key))def _sbe_render_edit(board: dict, edit: dict, *, music=None,@@ -23423,6 +26837,25 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,different films depending on which button was nearer."""sedit = _sbe_import()+ # FILM-51: VALIDATE, THEN HEAL — never the other way round. A document+ # that fails validate_edit is refused here exactly as save_edit refuses+ # it; only once it is known-good does heal_subframe_lengths get to touch+ # a clip's own `end`, so a corrupt document can never be laundered into+ # a plausible one before anything checks it (the hazard that made this+ # unsafe to run unconditionally on every load — see load_edit's comment).+ # A document reaching this function came from load_edit (already saved+ # through save_edit once, so already valid) or the Editor's own posted+ # body (validated by the /edit/render route before this is called) —+ # but a render can also be asked for an OLDER edit.json saved before+ # this fix existed, which is exactly the case this re-check and heal is+ # for: today's render of yesterday's film is frame-exact too.+ blocking = sedit.blocking_errors(sedit.validate_edit(edit))+ if blocking:+ return {"ok": False, "status": 400,+ "error": "; ".join(e["message"] for e in blocking[:6])}+ edit = dict(edit)+ edit["clips"] = [dict(c) if isinstance(c, dict) else c for c in (edit.get("clips") or [])]+ sedit.heal_subframe_lengths(edit)cuts = sedit.edit_to_cuts(edit)if not cuts:# `status` rides along so the HTTP seam can keep telling a bad request@@ -23458,7 +26891,7 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,win = sedit.music_window(audio)dest = _sb_film_dir_for_write(board)dl = _sb_deliver((deliver or {}).get("format"), (deliver or {}).get("size"),- (deliver or {}).get("finish"))+ (deliver or {}).get("finish"), (deliver or {}).get("loudnorm"))name = out_name or _sb_film_name(board, deliver=dl)gaps = sedit.edit_gaps(edit)kinds = {}@@ -23496,16 +26929,39 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,music_gain=sedit.bed_render_gain(edit),overlays=sedit.overlay_items(edit),deliver=dl, sound_strips=strips or None, declick=SB_DECLICK_S)+ # FILM-58: SEQUENCE ASPECT — a post-process crop of the finished film,+ # not a change to the assembly graph above (see `_sb_crop_to_aspect`).+ # Only on a render that actually produced a file: a failed assembly has+ # nothing to crop, and a crop failure here must not turn a successful+ # render into a reported failure — it is disclosed instead.+ aspect = str((edit.get("settings") or {}).get("aspect") or "16:9")+ if film.get("ok") and film.get("path") and aspect != "16:9":+ crop_err = _sb_crop_to_aspect(film["path"], aspect, deliver=dl)+ if crop_err:+ film["aspect_note"] = f"{aspect} crop could not be applied: {crop_err}"+ else:+ film["aspect"] = aspect+ # Same fit `_sb_crop_to_aspect` just applied — see its own+ # comment for why height is kept first.+ ratio = {"9:16": 9.0 / 16.0, "1:1": 1.0}[aspect]+ w0, h0 = int(film.get("width") or 0), int(film.get("height") or 0)+ if w0 > 0 and h0 > 0:+ tw, th = round(h0 * ratio), h0+ if tw > w0:+ tw, th = w0, round(w0 / ratio)+ film["width"], film["height"] = tw - tw % 2, th - th % 2film["gaps"] = gapsif gaps:- # An honest limitation, disclosed rather than discovered: this- # assembler concatenates, so a hole in the timeline closes and- # everything after it slides earlier — off the beat it was cut to.+ # FILM-27: disclosed rather than discovered, still — but `cuts`+ # (built by `edit_to_cuts`, above) now fills every one of these with+ # a black slug at its exact length, so the film is no longer+ # shorter than the timeline and nothing after a gap slides. Said+ # here because a silent fix is still a surprise the first time+ # someone notices black on screen.film["gaps_note"] = (f"{len(gaps)} gap(s) totalling "- f"{sum(g['duration'] for g in gaps):.2f}s were closed by the "- f"concatenation — the film is that much shorter than the "- f"timeline.")+ f"{sum(g['duration'] for g in gaps):.2f}s play as black — the "+ f"film is the same length as the timeline.")film["timeline_duration"] = sedit.edit_duration(edit)# Say it out loud: `replace` means the clips are mute in the delivered# file, and that must not be something a caller has to infer.@@ -23645,7 +27101,14 @@ def _sb_export(board: dict, *, auto_edit: bool = False, music=None,f"shots joined, {film['width']}×{film['height']} @ {FPS} fps, "f"{film['duration']:g} s.")if film.get("unreadable"):- film_md += (" Left out of the cut (unreadable): "+ # FILM-15: the timeline path (an edit.json exists) now PADS a+ # missing or short slot with black at its exact length instead+ # of dropping it — "left out" stopped being true for that path.+ # The whole-clip path below (no edit.json) still drops one.+ verb = ("played as black where the timeline used them"+ if sedit_edit and (sedit_edit.get("clips") or [])+ else "left out of the cut")+ film_md += (f" Unreadable, {verb}: "+ ", ".join(f"`{u}`" for u in film["unreadable"]) + ".")if sedit_edit and (sedit_edit.get("clips") or []):film_md += (f" Assembled from the timeline in the Editor "@@ -23920,6 +27383,7 @@ def _sbe_board_clips(board: dict) -> list[dict]:from a different selection than the export's would show the user a filmthey cannot render."""+ policy = board.get("policy") or storyboard.default_policy()out: list[dict] = []for s in sorted((board.get("shots") or []), key=lambda x: x.get("n") or 0):if not isinstance(s, dict) or s.get("status") == "skipped":@@ -23929,6 +27393,7 @@ def _sbe_board_clips(board: dict) -> list[dict]:continueout.append({"n": s.get("n"),+ "uid": s.get("uid"),"path": str(src),"title": (s.get("title") or s.get("prompt") or "")[:80],"pass": "delivery" if s.get("final_output") else "draft",@@ -23941,6 +27406,19 @@ def _sbe_board_clips(board: dict) -> list[dict]:# is what the row shows."prompt": s.get("prompt") or "","character_id": s.get("character_id") or "",+ # FILM-53: what a Retake dialog needs to say what will actually+ # render, instead of the prompt and a length. `mode`/`audio*` are+ # what the lip-sync contract is written against; `est_min` is the+ # same per-shot cost model the board's own estimate uses, at+ # both passes, so the dialog can show a number before queueing.+ "mode": s.get("mode") or "",+ "audio": s.get("audio") or "",+ "audio_start_time": s.get("audio_start_time"),+ "est_min": {+ pn: round(storyboard.shot_render_secs(+ s, (policy.get(pn) or {}), h3_cost=_sb_h3_cost) / 60.0, 1)+ for pn in ("draft", "final")+ },})return out@@ -24569,21 +28047,42 @@ def _sbe_music_video_edit(board: dict, clips: list, block: dict, sedit, _se,master `/music/video/film` lays down. No room tone: under a replaced mixit would be noise on top of the song."""+ # FILM-10 class: match the timeline clip back to its board shot by the+ # shot's stable `uid`, not its position `n` (reorder/delete renumbers+ # `n`, which would pair a clip with the wrong shot's music_video block).+ # `n` fallback only covers a clip carried over before `uid` existed.+ by_uid = {s.get("uid"): s for s in (board.get("shots") or []) if isinstance(s, dict)}by_n = {s.get("n"): s for s in (board.get("shots") or []) if isinstance(s, dict)}- plan = []- cursor = 0.0+ # FILM-21: this used to walk `clips` in `n` (array/board) order and lay+ # each one at `max(its own film_start, the running cursor)` — a drag+ # reorder changes `n`/array order but never recalculates+ # music_video.film_start (a singing shot was rendered against one exact+ # stretch of the song), so a clip now earlier in array order than its+ # true film_start got dragged forward to fill the gap, and everything+ # after it inherited the shift. Rows are placed by their OWN film_start+ # now — array order plays no part — so a reorder in the Editor changes+ # what plays next to what without moving anything's true position in+ # the song. `fs = max(fs, cursor)` remains only as a last-resort guard+ # against two rows whose windows genuinely overlap.+ rows = []for c in clips:- shot = by_n.get(c.get("n")) or {}+ shot = (by_uid.get(c.get("uid")) if c.get("uid") else None) or by_n.get(c.get("n")) or {}mvs = shot.get("music_video") if isinstance(shot.get("music_video"), dict) else {}try:fs = float(mvs["film_start"])want = max(0.0, float(mvs["film_end"]) - fs)except (KeyError, TypeError, ValueError):- fs = cursor+ fs = Nonewant = max(0.0, float(c.get("duration_s") or 0.0))- fs = max(fs, cursor) # never overlap the shot before it+ rows.append({"c": c, "fs": fs, "want": want})+ rows.sort(key=lambda r: (r["fs"] is None, r["fs"] if r["fs"] is not None else 0.0))+ plan = []+ cursor = 0.0+ for row in rows:+ c = row["c"]+ fs = cursor if row["fs"] is None else max(row["fs"], cursor)dur = (_se.probe_media(c["path"]) or {}).get("duration")- length = min(want, float(dur)) if dur else want+ length = min(row["want"], float(dur)) if dur else row["want"]if length <= 0:continueplan.append({"path": c["path"], "n": c.get("n"), "start": 0.0,@@ -24662,6 +28161,39 @@ def _sbe_relinks(board: dict, edit: dict) -> list[dict]:"to": str(new), "n": s.get("n"),"title": (s.get("title") or s.get("prompt") or "")[:80],"retake": True})+ # FILM-07: A BOARD RE-RENDER, offered the same way a retake is. Rewrite,+ # Retry, New still and "Render remaining" all land on a shot's+ # draft_output/final_output with no relation to what is already on a+ # timeline that named the OLD path — this is that relation, built from+ # `takes` (the history `_sb_reconcile` now keeps every time either output+ # key is overwritten). One offer per clip whose path is a superseded+ # take of a shot that has since rendered again, flagged the same as a+ # retake because the old take may still be the one the cutter wants.+ offered = {(row["id"], row["to"]) for row in out if row.get("retake")}+ for s in (board.get("shots") or []):+ if not isinstance(s, dict):+ continue+ takes = s.get("takes") or []+ if not takes:+ continue+ current = s.get("final_output") or s.get("draft_output")+ if not current or not Path(str(current)).is_file():+ continue+ # BOARD-4: both take shapes (bare path / `{"path", ...}` dict).+ stale = {p for p in (storyboard.take_path(t) for t in takes)+ if p and p != current}+ if not stale:+ continue+ for c in (edit.get("clips") or []):+ if not isinstance(c, dict):+ continue+ cid, path = c.get("id"), str(c.get("path") or "")+ if path in stale and path != current and (cid, str(current)) not in offered:+ out.append({"id": cid, "path": path, "to": str(current),+ "n": s.get("n"),+ "title": (s.get("title") or s.get("prompt") or "")[:80],+ "retake": True})+ offered.add((cid, str(current)))# UPSCALE & FACE FIX ordered from a clip on this timeline — the same# one-clip-at-a-time offer as a retake.try:@@ -24710,6 +28242,18 @@ def _sbe_payload(board: dict, edit: dict) -> dict:"edit": edit,"duration": sedit.edit_duration(edit),"gaps": sedit.edit_gaps(edit),+ # FILM-15: WHICH CLIPS ARE OFFLINE — a moved or trashed file, the+ # normal shape of the bug. A `Path.is_file()` stat is what this can+ # afford on every read (unlike ffprobe, called only at render); it+ # catches the case the report reproduced ("media missing" — a whole+ # folder gone) and leaves a file that exists but will not PROBE (torn,+ # zero-byte) to the assembler's own check, which still pads it with+ # black rather than shortening the film. One row per offline id, so+ # the client can badge a clip without a second lookup.+ "offline": sorted({str(c.get("id") or c.get("path"))+ for c in (edit.get("clips") or [])+ if isinstance(c, dict) and c.get("path")+ and not Path(str(c["path"])).is_file()}),# ...and the same kind of answer for the SOUND: which unlinked strips# no longer line up with their own picture, and where each one goes# back to. Never an error — a J-cut is a deliberate drift — but the@@ -25232,9 +28776,10 @@ def a2v_length_refusal(frames: int, cap: int) -> str:A2V_STEM_DIR = "a2v_stems"A2V_STEM_TIMEOUT_S = 900A2V_STEM_MISSING_NOTE = (- "Auto vocal stem is on but demucs is not installed, so this clip was "- "conditioned on the full mix. Install the stems extra from the Pinokio "- "sidebar (scripts/pinokio/a2v_stems_deps.sh) to separate the vocal."+ "Voice-only is on but demucs is not installed, so this clip was "+ "conditioned on the full mix instead. Run scripts/pinokio/"+ "a2v_stems_deps.sh once (from a Terminal, inside this install's "+ "engine venv) to add vocal separation, then try again.")@@ -25825,6 +29370,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,form["h3_chain_prompts"] = [json.dumps([_take["beat_prompts"][i] or (TAKE_HOLD + (" " + _lock if _lock else ""))for i in _take["parts"][0]])]+ form["h3_chain_prompts_complete"] = ["1"]else:# An LTX take is 10 s parts by last-frame handoff, NOT the# windows chain: the parent job carries one part's frames@@ -26203,6 +29749,13 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,# trap as every key in this dict: leave it out and the whole# control looks wired and silently no-ops on /queue/add."h3_chain_prompts": _h3_chain_prompts,+ # 4.17 (Codex H3-2): H3-06 made a typed per-window box ADD to the+ # main prompt. Callers that already send COMPLETE per-window+ # prompts — a One Shot's beats, a storyboard shot's chain — set+ # this so their windows are not prefixed with window 1's+ # action/dialogue. Same allowlist trap: leave it out and it no-ops.+ "h3_chain_prompts_complete": f("h3_chain_prompts_complete", "").strip().lower()+ in ("1", "true", "on", "yes"),"take": _take,# LTX-2.5 distilled schedule preset — "" (tuned default) or# "fast"/"vendor", already gated above to the lane that defines@@ -26223,6 +29776,12 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,# Empty unless LTX_DEFAULT_IMAGE names a file that exists — see# default_reference_image() for why this used to be a phantom."image": f("image", default_reference_image()),+ # Where the reference picker's crop-preview overlay was dragged+ # to, 0..1 along whichever axis the cover-crop cuts (0.5 =+ # centre, the old fixed behaviour). Read by _job_crop_focus() in+ # the H3/I2V/A2V pre-fit crop. SAME allowlist trap as every key+ # in this dict: leave it out and the drag silently no-ops.+ "image_crop_focus": f("image_crop_focus", "0.5"),"audio": f("audio", str(AUDIO_DEFAULT)),# A2V VOCAL STEM. What the model LISTENS to, when it should not be# the same file the clip plays: `audio_stem` names a separated@@ -26231,8 +29790,22 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,# the make_job allowlist trap this file warns about throughout."audio_stem": f("audio_stem", ""),"audio_stem_auto": f("audio_stem_auto", ""),+ # A2V multi-anchor images (fd2356d, mlx_warm_helper._a2v_anchor_images):+ # JSON list of {path, frame_idx, strength}. The manual UI only ever+ # sends frame_idx 0 (the "Continue the song" flow — see+ # continue_song_anchor() and /a2v/continue_song) since an end/mid+ # anchor pins a pose at a known time and fights the audio for the+ # mouth (2026-09-22 anchor lesson); a full multi-anchor list stays+ # reachable for the storyboard/agent API only. SAME allowlist trap+ # as every key in this dict: leave it out and the control silently+ # no-ops on /queue/add.+ "anchors_json": f("anchors_json", ""),# extend mode params"video_path": f("video_path", ""),+ # VA-13: "Also run Upscale & Face Fix after" — queued once this+ # Extend job finishes (worker_loop). SAME allowlist trap as every+ # key here: leave it out and the checkbox silently no-ops.+ "extend_face_fix_after": f("extend_face_fix_after", "") in ("1", "true", "on"),# restore (Colorize) mode — the B&W source clip to colorize. MUST# be in this allowlist or the path silently no-ops on /queue/add# (the known make_job allowlist trap — see CLAUDE.md).@@ -26271,6 +29844,15 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,"extend_direction": f("extend_direction", "after"),"extend_steps": max(1, int(f("extend_steps", "8") or 8)),"extend_cfg": float(f("extend_cfg", "1.0") or 1.0),+ # Segment Retake (VA-26) — mode="retake", shares video_path with+ # Extend above. "Fix just the bad two seconds" instead of+ # re-rendering the whole clip. SAME allowlist trap: leave any of+ # these out and the control silently no-ops on /queue/add.+ "retake_start_sec": f("retake_start_sec", "0"),+ "retake_end_sec": f("retake_end_sec", ""),+ "retake_audio_action": f("retake_audio_action", "keep"),+ "retake_steps": f("retake_steps", ""),+ "retake_cfg": f("retake_cfg", ""),# keyframe (FFLF) mode params.# Two-keyframe path (start_image + end_image) is the legacy panel# contract still used by the manual UI. The agent SDK can pass@@ -28101,7 +31683,52 @@ def run_train_job_inner(job: dict) -> None:push(f"[train.audio] done: {audio_lora_path} (elapsed {audio_elapsed}s)")-def _h3_fit_first_frame(src: Path, width: int, height: int, job_id: str) -> Path:+def _job_crop_focus(p: dict) -> float:+ """The user's crop position for a cover-crop, 0..1 along whichever axis+ gets cropped (0 = keep the top/left edge fully visible, 0.5 = centred —+ the historical, and still default, behaviour — 1 = keep the bottom/right+ edge). Set from the reference-picker's crop-preview overlay (drag, or the+ Top/Center quick buttons); `image_crop_focus` MUST be in make_job's+ allowlist or a drag silently no-ops on /queue/add."""+ try:+ v = float(p.get("image_crop_focus", 0.5) or 0.5)+ except (TypeError, ValueError):+ return 0.5+ if v != v: # NaN+ return 0.5+ return min(1.0, max(0.0, v))+++def _cover_crop_image(im, width: int, height: int, focus: float = 0.5):+ """Cover-crop a PIL image onto `width`x`height` and return the crop.++ Max-scale so the image covers the canvas, LANCZOS, then crop. The axis+ that lands exactly on the canvas after scaling has nothing to choose —+ the OTHER axis is where the crop happens, and `focus` (0..1) says where+ along it: 0 keeps the leading edge, 0.5 centres (the original, and still+ default, behaviour — floor division, kept byte-identical at focus=0.5 so+ existing renders don't shift a pixel), 1 keeps the trailing edge. Callers+ pass the position the user dragged on the crop-preview overlay (VC-29/+ H3-01/VA-02) so a portrait photo's face — not its chin — survives a+ landscape crop."""+ from PIL import Image+ scale = max(width / im.size[0], height / im.size[1])+ resized_size = (max(width, round(im.size[0] * scale)),+ max(height, round(im.size[1] * scale)))+ dx = resized_size[0] - width+ dy = resized_size[1] - height+ if focus == 0.5:+ left, top = max(0, dx // 2), max(0, dy // 2)+ else:+ f = min(1.0, max(0.0, float(focus)))+ left, top = max(0, round(dx * f)), max(0, round(dy * f))+ left, top = min(left, dx), min(top, dy)+ return im.resize(resized_size, Image.Resampling.LANCZOS).crop(+ (left, top, left + width, top + height))+++def _h3_fit_first_frame(src: Path, width: int, height: int, job_id: str,+ focus: float = 0.5) -> Path:"""Cover-crop `src` onto the H3 canvas and return the path to use.Why the panel does this instead of the runner: upstream's@@ -28123,29 +31750,27 @@ def _h3_fit_first_frame(src: Path, width: int, height: int, job_id: str) -> Pathwithout touching the engine, and costs the render nothing — it replacesupstream's resize with ours rather than adding a second one.- The arithmetic below is a deliberate line-for-line port of upstream's own- non-stretch branch (`packing.py`): max-scale so the image covers the- canvas, LANCZOS, centre crop with floor division. Faithfulness is the- point — the panel is standing in for the runner's cover-crop, so it should- produce what a second keyframe would have produced, not a lookalike.- `ImageOps.fit` is close but rounds and centres differently.+ The crop itself (`_cover_crop_image`) is a deliberate line-for-line port+ of upstream's own non-stretch branch (`packing.py`): max-scale so the+ image covers the canvas, LANCZOS, centre crop with floor division at the+ default focus. Faithfulness is the point — the panel is standing in for+ the runner's cover-crop, so it should produce what a second keyframe+ would have produced, not a lookalike. `ImageOps.fit` is close but rounds+ and centres differently. `focus` (H3-01) moves that crop off-centre when+ the user dragged the crop-preview overlay, so a portrait photo's face —+ not the chin the old hardcoded centre crop kept — survives.Best-effort by construction: any failure returns the ORIGINAL path, so theworst case is the stretch we have today rather than a render that dies ona reference image."""try:- from PIL import Image+ from PIL import Image, ImageOpswith Image.open(src) as im:+ im = ImageOps.exif_transpose(im) or imim = im.convert("RGB")if im.size == (width, height):return src # runner's own early-return handles it- scale = max(width / im.size[0], height / im.size[1])- resized_size = (max(width, round(im.size[0] * scale)),- max(height, round(im.size[1] * scale)))- left = max(0, (resized_size[0] - width) // 2)- top = max(0, (resized_size[1] - height) // 2)- fitted = im.resize(resized_size, Image.Resampling.LANCZOS).crop(- (left, top, left + width, top + height))+ fitted = _cover_crop_image(im, width, height, focus)UPLOADS.mkdir(parents=True, exist_ok=True)out = UPLOADS / f".h3_{job_id}_firstframe_{width}x{height}.png"fitted.save(out, format="PNG")@@ -28157,6 +31782,39 @@ def _h3_fit_first_frame(src: Path, width: int, height: int, job_id: str) -> Pathreturn src+def _fit_reference_image_to_canvas(src: Path, width: int, height: int,+ job_id: str, focus: float = 0.5) -> Path:+ """Cover-crop `src` onto an LTX i2v/A2V canvas before it reaches the+ pipeline, and return the path to use.++ The vendored i2v/A2V encoders do their own cover-crop (upstream+ `resize_and_center_crop`) and always centre it, with no way for the+ panel to say otherwise — the same shape of problem `_h3_fit_first_frame`+ exists for. Pre-fitting here, honouring the user's crop-preview+ position, makes the pipeline's own crop a no-op (the image already IS+ the canvas) and means the panel — not the vendored package — decides+ where a portrait photo gets cropped (VA-02).++ Best-effort by construction: any failure returns the ORIGINAL path."""+ try:+ from PIL import Image, ImageOps+ with Image.open(src) as im:+ im = ImageOps.exif_transpose(im) or im+ im = im.convert("RGB")+ if im.size == (width, height):+ return src+ fitted = _cover_crop_image(im, width, height, focus)+ UPLOADS.mkdir(parents=True, exist_ok=True)+ out = UPLOADS / f".ref_{job_id}_{width}x{height}.png"+ fitted.save(out, format="PNG")+ return out+ except Exception as exc: # noqa: BLE001 - never fatal+ push(f"warn: couldn't pre-fit the reference image to {width}x{height} "+ f"({exc}); passing it through — the engine's own crop will "+ f"centre it instead of your chosen position.")+ return src++def _h3_clip_is_complete(path: Path, started_at: float,expect_frames: int | None = None) -> bool:"""True when the H3 output at `path` is a whole clip written by THIS run:@@ -28206,6 +31864,54 @@ def _h3_clip_is_complete(path: Path, started_at: float,return False+def _h3_partial_clip_info(path: Path, started_at: float) -> dict | None:+ """H3-11: what `_h3_clip_is_complete` answers as a bool, this answers as+ the measurements themselves — for a chained render stopped between+ windows, where "complete" is the wrong question (the file is SUPPOSED to+ be short). Same validity bar (exists, written by this run, ffprobe reads+ a real video stream with a positive duration); returns the ACTUAL frame+ count and duration off the file itself rather than trusting metrics.json+ (which may not have been written, or may still describe the FULL chain+ the runner never finished), so a published partial never claims a length+ it doesn't have. None when nothing on disk is salvageable."""+ try:+ st = path.stat()+ except OSError:+ return None+ if st.st_mtime < started_at - 1 or st.st_size < 50_000:+ return None+ ffprobe = str(FFPROBE) if Path(str(FFPROBE)).is_file() else shutil.which("ffprobe")+ if not ffprobe:+ return None+ try:+ out = subprocess.run(+ [ffprobe, "-v", "error", "-select_streams", "v:0",+ "-show_entries", "stream=codec_type,nb_frames,avg_frame_rate:format=duration",+ "-of", "json", str(path)],+ capture_output=True, text=True, errors="replace", timeout=20)+ if out.returncode != 0:+ return None+ info = json.loads(out.stdout or "{}")+ streams = [x for x in (info.get("streams") or [])+ if x.get("codec_type") == "video"]+ if not streams:+ return None+ duration = float((info.get("format") or {}).get("duration") or 0)+ if duration <= 0:+ return None+ try:+ frames_seen = int(streams[0].get("nb_frames") or 0)+ except (TypeError, ValueError):+ frames_seen = 0+ if frames_seen <= 0:+ # Some encoders omit nb_frames in a container muxed under a+ # signal; fall back to duration × the fps the file itself reports.+ frames_seen = max(1, round(duration * H3_FPS))+ return {"frames": frames_seen, "duration_sec": round(duration, 3)}+ except Exception: # noqa: BLE001+ return None++def _h3_runner_error_message(metrics_path: Path) -> str | None:"""The runner's own readable failure, when it wrote one.@@ -28388,6 +32094,27 @@ def _face_fix_offers(board_id: str, edit: dict) -> list[dict]:return out+def face_fix_adapter_ready() -> bool:+ """Is the Pixel Spatial Upscaler adapter Upscale & Face Fix needs on disk?"""+ adapter_path = CURATED_LORAS["upscale_x2"].get("local_path") or ""+ return bool(adapter_path and Path(adapter_path).exists())+++def extend_face_fix_refusal(params: dict) -> str | None:+ """The sentence /run and /queue/add refuse an Extend with, when it asks+ for "Also run Upscale & Face Fix after" on a Mac without the adapter —+ or None. 4.17 Codex EST-10: the Extend used to render for many minutes+ and only then find, in the log, that the follow-up could never queue."""+ p = params or {}+ if p.get("mode") != "extend" or not p.get("extend_face_fix_after"):+ return None+ if face_fix_adapter_ready():+ return None+ return (f"“Also run {FACE_FIX_NAME} after” needs the LTX-2.5 Pixel Spatial "+ "Upscaler adapter (0.3 GB), which isn't on this Mac yet. Download it "+ "in Settings → Models, or uncheck the box to render the Extend alone.")++def queue_face_fix(source_path: str, *, board_id: str = "",clip_id: str = "") -> dict:"""Queue one Upscale & Face Fix of a finished clip — the one-click action.@@ -28404,13 +32131,18 @@ def queue_face_fix(source_path: str, *, board_id: str = "",return {"ok": False, "error": "unknown film"}if board_id and not (_sbe_board_dir(board_id) / "storyboard.json").is_file():return {"ok": False, "error": "unknown film"}- adapter_path = CURATED_LORAS["upscale_x2"].get("local_path") or ""- if not (adapter_path and Path(adapter_path).exists()):+ if not face_fix_adapter_ready():return {"ok": False, "code": "pack_missing","error": f"{FACE_FIX_NAME} needs the LTX-2.5 Pixel Spatial Upscaler ""adapter (0.3 GB). Open Settings → Models and download it."}sw, sh = _probe_video_dims(str(src))src_frames = _probe_video_frames(str(src)) or 0+ # VA-22: the target canvas, so the client's queued-toast can say what+ # this render actually becomes instead of nothing. Real numbers, not an+ # invented time estimate — the source dims + frame count are cheap and+ # exact (already probed above for the refusal checks); a wall-clock+ # guess is not (one measurement at 1024×576 exists, not a table).+ target_w = target_h = Noneif sw and sh:cap = int(tier_max_dim("i2v") or 0) or max(sw, sh) * 2scale = min(2.0, cap / float(max(sw, sh)))@@ -28425,6 +32157,7 @@ def queue_face_fix(source_path: str, *, board_id: str = "",return {"ok": False, "code": "hardware_tier","error": f"{src.name} is too long to fix at {up_w}×{up_h} ""(the video decoder's limit). Cut it shorter first."}+ target_w, target_h = up_w, up_hmeta = _face_fix_source_meta(src)form = face_fix_form(src, prompt=meta.get("prompt", ""),seed=meta.get("seed", "-1"), label=meta.get("label", ""),@@ -28468,9 +32201,11 @@ def queue_face_fix(source_path: str, *, board_id: str = "",if dup is not None:return {"ok": True, "id": dup["id"], "label": dup["params"].get("label"),"duplicate": True,- "running": dup is STATE.get("current")}+ "running": dup is STATE.get("current"),+ "target_w": target_w, "target_h": target_h}push(f"{FACE_FIX_NAME} queued for {src.name} → job {job['id']}")- return {"ok": True, "id": job["id"], "label": job["params"].get("label")}+ return {"ok": True, "id": job["id"], "label": job["params"].get("label"),+ "target_w": target_w, "target_h": target_h}def _chain_upscale_after_h3(job: dict, p: dict, native_path: Path) -> None:@@ -28506,6 +32241,18 @@ def _chain_upscale_after_h3(job: dict, p: dict, native_path: Path) -> None:f"the gallery; use its {FACE_FIX_NAME} button.")+# H3-11 "Stop after this window" on a PLAIN chained H3 render (not a One+# Shot) needs the runner to hand back the windows it finished. It does not:+# minimax-h3-mlx's generate_staged.py keeps every window in memory and writes+# the single stitched output only after the last one (--chain-keep-windows+# writes per-window files, but unstitched, into the outputs folder, and not+# for the draft-fps time-stretch). Until the runner stops cooperatively and+# publishes what finished, the panel does not offer the option for plain+# chains — /stop/after_part refuses it and the Stop dialog leaves it out.+# (4.17 Codex review, H3-1.) The panel-side machinery below stays, gated.+H3_RUNNER_KEEPS_WINDOWS_ON_STOP = False++def run_h3_job_inner(job: dict) -> None:"""Render one job on the Hailuo H3 engine (optional subprocess pack).@@ -28625,9 +32372,12 @@ def run_h3_job_inner(job: dict) -> None:if isinstance(_asked, str):_asked = h3_normalize_chain_prompts(_asked, chain_windows)if isinstance(_asked, (list, tuple)):- _filled = [("" if x is None else str(x)).strip() or prompt- for x in list(_asked)[:chain_windows]]- _filled += [prompt] * (chain_windows - len(_filled))+ # H3-06: see h3_compose_window_prompts's docstring — a typed+ # window box used to REPLACE the main prompt outright instead of+ # adding to it.+ _filled = h3_window_prompts_for_job(+ prompt, list(_asked), chain_windows,+ complete=bool(p.get("h3_chain_prompts_complete")))if any(x != prompt for x in _filled):if h3_supports_chain_prompts():chain_prompts = _filled@@ -28870,7 +32620,8 @@ def run_h3_job_inner(job: dict) -> None:# runs (#53). See _h3_fit_first_frame for the mechanism; it returns# the original path unchanged when the image is already the canvas# size or when anything goes wrong.- first_frame = _h3_fit_first_frame(Path(src), width, height, job["id"])+ first_frame = _h3_fit_first_frame(Path(src), width, height, job["id"],+ _job_crop_focus(p))if str(first_frame) != src:push(f"[h3] reference cover-cropped to {width}x{height} before "f"conditioning (keeps its proportions — the runner would "@@ -29167,6 +32918,9 @@ def run_h3_job_inner(job: dict) -> None:# which looks like a broken estimate.denoise_t0: float | None = Noneproc: subprocess.Popen | None = None+ # H3-11: fires once, the first time a stop-after-window request is seen+ # at a window boundary — see the m_window block below.+ _stop_after_window_sent = Falsestep_rx = re.compile(r"^step (\d+)/(\d+):")phase_rx = re.compile(r"^== (.+) ==$")# A chained run prints `### window 2/3 ###` between windows and prefixes@@ -29185,6 +32939,26 @@ def run_h3_job_inner(job: dict) -> None:_decode_est = (H3_DECODE_SEC_PER_PX_FRAME * int(width) * int(height)* int(window_frames) * _hw_speed_factor("h3"))_load_est = H3_LOAD_SEC * _h3_speed_factor(chain_windows)+ # H3-23: staged weight loads (the 26 GB text encoder, then the transformer)+ # can take minutes on a 48 GB Mac, and the load phase used to show ONLY+ # "X elapsed" with no ETA at all — eta was hardcoded to 0.0 below, and+ # 0.0 is falsy in JS, so the Now card's own "elapsed / ~eta" branch never+ # fired. Seeded from the SAME cell estimate the Speed chip already+ # promised (Fast's tristep_min when this render is running Fast, else+ # the cell's own eta_min), so the number on screen before the first+ # denoise step matches the number the user picked the render on.+ _load_eta_seed_min = (+ (tier.get("tristep_min") if tristep and tier.get("tristep_min") is not None+ else tier.get("eta_min")) or 0.0)+ _load_eta_seed = max(0.0, float(_load_eta_seed_min)) * 60.0+ # H3-04: what one denoise forward SHOULD cost on this Mac, at this+ # shape — the same per-forward model h3_estimate_minutes prices the+ # chip on. Compared against the MEASURED per-step time once a step has+ # landed, so a render that is quietly swapping (memory pressure, a+ # background app, thermal throttling) can say so instead of just+ # running long with no explanation.+ _modeled_per_step = (_h3_forward_seconds(_h3_packed_rows(width, height, window_frames))+ * _h3_speed_factor(chain_windows))last_step, total_steps = 0, max(1, steps - 1)# Last look before the GPU: a Stop pressed during any of the preparation# above (the companion fetch, the reference crop) ends the job here.@@ -29268,6 +33042,7 @@ def run_h3_job_inner(job: dict) -> None:_h3_tail.append(line.strip())m_window = window_rx.match(line.strip())if m_window:+ _prev_window = cur_windowtry:cur_window = max(1, int(m_window.group(1)))tot_windows = max(cur_window, int(m_window.group(2)))@@ -29278,6 +33053,29 @@ def run_h3_job_inner(job: dict) -> None:# it or the ETA prices this window off the previous one's load.denoise_t0 = Nonelast_step = 0+ # H3-11 (plain chained windows, not a One Shot): the runner+ # writes ONE file for the whole chain and has no per-window+ # checkpoint API, so the only boundary this panel can act on+ # is "a new window just started in the log" — the window+ # before it is as done as this engine is ever going to report.+ # /stop/after_part sets `stop_after_part` on the live job;+ # honour it here, at the FIRST window transition seen after+ # it was set, by asking the whole process group to stop.+ # SIGTERM, not the hard-stop's immediate kill — ffmpeg is+ # piped raw frames and needs the signal to flush and close+ # the moov atom on whatever windows it already muxed. What+ # lands at out_path afterward is checked below and, if+ # playable, published instead of thrown away.+ if (cur_window > _prev_window and cur_window > 1+ and job.get("stop_after_part") and not _stop_after_window_sent):+ _stop_after_window_sent = True+ push(f"[h3] stop-after-window requested — asking the engine to stop "+ f"before window {cur_window} of {tot_windows} (window "+ f"{_prev_window} already rendered)")+ try:+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)+ except (ProcessLookupError, PermissionError, OSError):+ passm_phase = phase_rx.match(line.strip())if m_phase:raw_phase = m_phase.group(1).strip()@@ -29320,6 +33118,11 @@ def run_h3_job_inner(job: dict) -> None:pct = win_base + win_span * (last_step / float(total_steps))spent = elapsed if denoise_t0 is None else max(0.0, time.time() - denoise_t0)per_step = spent / max(1, last_step)+ # H3-04: pace check. Needs a couple of steps before the+ # measured per-step time means anything (the first step+ # after a phase change often carries residual setup cost).+ _slow_pace = (last_step >= 2 and _modeled_per_step > 0+ and per_step > _modeled_per_step * 1.5)# Remaining steps in this window, plus every step of every# window still to come — and the decodes still owed, so the# clock does not read 0 through a minutes-long VAE decode.@@ -29336,8 +33139,26 @@ def run_h3_job_inner(job: dict) -> None:label = (f"{win_tag}{phase_label}" if post elsef"{win_tag}{phase_label} · step {last_step} / {total_steps}")else:- pct, eta = max(3.0, win_base), 0.0+ pct = max(3.0, win_base)+ # H3-23: counts down from the cell's own estimate rather+ # than sitting on a hardcoded 0.0 (which the client reads+ # as falsy and shows no ETA at all for).+ eta = max(0.0, _load_eta_seed - elapsed)label = f"{win_tag}{phase_label}"+ _slow_pace = False+ # H3-04: "expected 18, waited 43+" (Pinokio, 2026-09-20) matched a+ # Standard 10s on an M4 Pro 48 GB exactly — the render was+ # quietly running Best (2.6x Fast's price on that cell) with no+ # sign of it anywhere on screen, AND running slower than even+ # Best's own estimate (memory pressure). Named here so the Now+ # card can say both: which speed is actually rendering, and+ # whether it is keeping pace with what that speed promised.+ _pace_note = ""+ if _slow_pace:+ _fast_alt = tier.get("tristep_min")+ _pace_note = "running slower than estimated — may be swapping"+ if not tristep and _fast_alt is not None:+ _pace_note += f"; Fast would take about {_fmt_eta(_fast_alt)}"with LOCK:cur = STATE.get("current")if cur and cur.get("id") == job["id"]:@@ -29352,8 +33173,16 @@ def run_h3_job_inner(job: dict) -> None:# printed it as "27m 23s / ~18m 21s", which a user read# as an 18-minute total (Pinokio, 2026-09-20). Handing# it over as remaining_sec makes the card say- # "27m 23s in · ~18m 21s left".- "remaining_sec": eta if last_step else None,+ # "27m 23s in · ~18m 21s left". Populated during load+ # too now (H3-23) — the seeded cell estimate, not a+ # per-step extrapolation, but a real number beats none.+ "remaining_sec": eta,+ # H3-04: which speed is actually rendering (a Now+ # card had no way to show this before) and, when the+ # render is running meaningfully slower than even+ # that speed's own estimate, why and what would help.+ "h3_speed": ("fast" if tristep else "best"),+ "h3_pace_warning": _pace_note,"denoise_step": last_step,"denoise_total": total_steps,"window": cur_window,@@ -29365,6 +33194,24 @@ def run_h3_job_inner(job: dict) -> None:STATE["pid"] = NoneSTATE["h3_pgid"] = None_proc_guard_clear("h3")+ if _stop_after_window_sent:+ # H3-11: the engine was asked to stop between windows. Whatever+ # it left at out_path is the whole answer — "publish what it+ # wrote to disk" if that's a real, playable clip; if the runner+ # can't hand back partial windows (nothing there, or too short+ # to probe), say so plainly rather than pretending it worked.+ _partial = _h3_partial_clip_info(out_path, t0)+ if _partial is not None:+ push(f"[h3] stop-after-window: kept {_partial['frames']} frames "+ f"({_partial['duration_sec']}s) written before the stop — "+ f"publishing as a shorter clip.")+ job["_h3_stopped_after_window"] = _partial+ rc = 0+ else:+ raise JobStopped(+ "Stopped after this window, but this H3 engine build didn't "+ "leave a usable clip on disk to keep — nothing was rendered "+ "long enough to publish.")if rc == 75:# H3's file-sentinel contract uses the same dedicated exit code as# LTX. It is a viewer decision, not a crash; worker_loop maps this@@ -29660,6 +33507,19 @@ def run_h3_job_inner(job: dict) -> None:{k: v for k, v in upscale_plan.items() if k != "vf"}| {"source": str(native_path), "codec": dict(job_codec)})+ # H3-11: the sidecar built above assumes a completed chain — delivered_frames+ # and video_duration_sec fall back to the FULL requested `frames` when+ # metrics.json doesn't say otherwise, which is wrong for a clip that was+ # deliberately cut short. Overwrite both with what ffprobe measured on the+ # actual file (_h3_partial_clip_info, set when the stop fired above), and+ # say so on the label the gallery/Load Params show.+ _partial_stop = job.get("_h3_stopped_after_window")+ if _partial_stop:+ sidecar["stopped_early"] = True+ sidecar["h3"]["delivered_frames"] = _partial_stop["frames"]+ sidecar["video_duration_sec"] = _partial_stop["duration_sec"]+ _base_label = p.get("label") or tier["label"]+ sidecar["params"]["label"] = f"{_base_label} (stopped early — kept what rendered)"write_sidecar(final_target.with_suffix(final_target.suffix + ".json"), sidecar)job["output_path"] = str(final_target)p["elapsed_seconds"] = elapsed@@ -29679,6 +33539,60 @@ def ffconcat_line(path) -> str:return "file '" + str(path).replace("'", "'\\''") + "'\n"+def _publish_windows_partial(job: dict, p: dict, plan: dict, pieces: list,+ completed: int, raw_out: Path, codec: dict,+ fps: float) -> None:+ """VA-38: on a Windows-chain failure, join whatever windows finished+ into a real, VISIBLE gallery entry instead of leaving only hidden+ working files behind ("the difference between a resumable clip and a+ lost hour" — the docstring on _run_windows_chain — minus the part where+ nobody could find them). `completed` is windows AFTER the first that+ finished; `pieces` always has at least the first window's own file.+ The player's "Continue from here" action (queue.js) reads+ sidecar.windows_partial and pre-fills Extend from this file — a+ pragmatic equivalent to re-entering the exact chain state, built on+ Extend's own already-proven path rather than new resume plumbing in+ the failure-prone chain loop itself."""+ total = int(plan.get("count") or 1)+ stem = raw_out.stem+ partial_name = f"{stem}_windows_partial_{completed + 1}of{total}{raw_out.suffix}"+ partial_out = OUTPUT / partial_name+ lst = OUTPUT / ".windows" / str(job.get("id") or "take") / f"{stem}_partial_join.txt"+ lst.parent.mkdir(parents=True, exist_ok=True)+ lst.write_text("".join(ffconcat_line(x) for x in pieces), encoding="utf-8")+ run_ffmpeg_tracked([+ str(FFMPEG), "-y", "-f", "concat", "-safe", "0", "-i", str(lst),+ "-c:v", "libx264", "-pix_fmt", codec["pix_fmt"], "-crf", codec["crf"],+ "-preset", "medium", *BT709_FLAGS, "-c:a", "aac", "-b:a", "192k",+ "-movflags", "+faststart", str(partial_out)], "Windows: partial join (on failure)")+ if not partial_out.is_file():+ return+ # 4.17.0 render check: the sidecar kept the ASKED frame count, so the+ # gallery card (clip_sec = params.frames / frame_rate) called a 5 s+ # partial of a 10 s ask a "10s clip". Record what the file holds.+ params = {**p, "command": "windows_partial"}+ try:+ _got = int(_probe_video_frames(str(partial_out)) or 0)+ except Exception: # noqa: BLE001+ _got = 0+ if _got > 0:+ params["frames_asked"] = p.get("frames")+ params["frames"] = _got+ sidecar = {+ "output": str(partial_out), "raw_output": str(partial_out),+ "params": params,+ "fps": FPS, "queue_id": job.get("id"),+ "output_codec": output_codec_settings(),+ "windows_partial": {+ "completed": completed + 1, "total": total,+ "prompt": p.get("prompt") or "",+ },+ }+ write_sidecar(partial_out.with_suffix(partial_out.suffix + ".json"), sidecar)+ push(f"[windows] {completed + 1} of {total} windows finished before the failure — "+ f"published as {partial_out.name} (visible in Outputs, not just on disk)")++def _run_windows_chain(job: dict, p: dict, plan: dict, first: Path,raw_out: Path, total_frames: int) -> dict:"""Windows 2..N as `extend` passes, each on ONLY the last window of the@@ -29717,61 +33631,79 @@ def _run_windows_chain(job: dict, p: dict, plan: dict, first: Path,pieces = [str(first)]cur = firstcur_frames = ctx # the first pass is one window+ completed = 0for w in plan["windows"][1:]:k = w["index"]- # 1. THE CONTEXT: the last `ctx` frames of the previous output, its- # `discard` tail dropped first. Frame-exact through `select`.- end = cur_frames - discard - 1- start = max(0, end - ctx + 1)- tail = work / f"{raw_out.stem}_w{k - 1}t{raw_out.suffix}"- run_ffmpeg_tracked([- str(FFMPEG), "-y", "-i", str(cur),- "-vf", f"select='between(n\\,{start}\\,{end})',setpts=N/FRAME_RATE/TB",- "-af", f"atrim=start={start / fps:.6f}:end={(end + 1) / fps:.6f},asetpts=PTS-STARTPTS",- *enc, "-movflags", "+faststart", str(tail)], f"Windows: tail {k - 1}")- ctx_frames = end - start + 1- out = work / f"{raw_out.stem}_w{k}{raw_out.suffix}"- seed = p.get("seed_used") if p.get("seed_used") is not None else p.get("seed")try:- seed = int(seed)- except (TypeError, ValueError):- seed = -1- spec = {- "action": "extend",- "id": job["id"],- "params": {- "model_dir": str(pack_path("q8")),- "dev_transformer": hq_weights()["dev_transformer"],- "prompt": prompts[k],- "negative_prompt": p.get("negative_prompt", ""),- "video_path": str(tail),- "extend_frames": _lw.extend_latents(w["new_frames"]),- "direction": "after",- "output_path": str(out),- "seed": (seed + k) if seed >= 0 else -1,- "steps": int(p.get("extend_steps") or 8),- "cfg_scale": 1.0,- "loras": p.get("loras") or [],- },- }- push(f"[windows] window {k + 1}/{plan['count']}: +{w['new_frames']}f "- f"after {ctx_frames}f of context · \"{prompts[k][:60]}\"")- res = HELPER.run(spec)- if not out.is_file():- raise RuntimeError(f"window {k + 1} produced no file ({res.get('error') or 'no output'})")- plan["files"].append(str(out))- # 2. THE PIECE: only the frames this window added.- piece = work / f"{raw_out.stem}_w{k}p{raw_out.suffix}"- run_ffmpeg_tracked([- str(FFMPEG), "-y", "-i", str(out),- "-vf", f"select='gte(n\\,{ctx_frames})',setpts=N/FRAME_RATE/TB",- "-af", f"atrim=start={ctx_frames / fps:.6f},asetpts=PTS-STARTPTS",- *enc, "-movflags", "+faststart", str(piece)], f"Windows: piece {k}")- pieces.append(str(piece))- for f in (str(cur), str(tail), str(out), str(piece)):- set_hidden(f, True)- cur = out- cur_frames = ctx_frames + int(w["new_frames"])+ # 1. THE CONTEXT: the last `ctx` frames of the previous output, its+ # `discard` tail dropped first. Frame-exact through `select`.+ end = cur_frames - discard - 1+ start = max(0, end - ctx + 1)+ tail = work / f"{raw_out.stem}_w{k - 1}t{raw_out.suffix}"+ run_ffmpeg_tracked([+ str(FFMPEG), "-y", "-i", str(cur),+ "-vf", f"select='between(n\\,{start}\\,{end})',setpts=N/FRAME_RATE/TB",+ "-af", f"atrim=start={start / fps:.6f}:end={(end + 1) / fps:.6f},asetpts=PTS-STARTPTS",+ *enc, "-movflags", "+faststart", str(tail)], f"Windows: tail {k - 1}")+ ctx_frames = end - start + 1+ out = work / f"{raw_out.stem}_w{k}{raw_out.suffix}"+ seed = p.get("seed_used") if p.get("seed_used") is not None else p.get("seed")+ try:+ seed = int(seed)+ except (TypeError, ValueError):+ seed = -1+ spec = {+ "action": "extend",+ "id": job["id"],+ "params": {+ "model_dir": str(pack_path("q8")),+ "dev_transformer": hq_weights()["dev_transformer"],+ "prompt": prompts[k],+ "negative_prompt": p.get("negative_prompt", ""),+ "video_path": str(tail),+ "extend_frames": _lw.extend_latents(w["new_frames"]),+ "direction": "after",+ "output_path": str(out),+ "seed": (seed + k) if seed >= 0 else -1,+ "steps": int(p.get("extend_steps") or 8),+ "cfg_scale": 1.0,+ "loras": p.get("loras") or [],+ },+ }+ push(f"[windows] window {k + 1}/{plan['count']}: +{w['new_frames']}f "+ f"after {ctx_frames}f of context · \"{prompts[k][:60]}\"")+ res = HELPER.run(spec)+ if not out.is_file():+ raise RuntimeError(f"window {k + 1} produced no file ({res.get('error') or 'no output'})")+ plan["files"].append(str(out))+ # 2. THE PIECE: only the frames this window added.+ piece = work / f"{raw_out.stem}_w{k}p{raw_out.suffix}"+ run_ffmpeg_tracked([+ str(FFMPEG), "-y", "-i", str(out),+ "-vf", f"select='gte(n\\,{ctx_frames})',setpts=N/FRAME_RATE/TB",+ "-af", f"atrim=start={ctx_frames / fps:.6f},asetpts=PTS-STARTPTS",+ *enc, "-movflags", "+faststart", str(piece)], f"Windows: piece {k}")+ pieces.append(str(piece))+ for f in (str(cur), str(tail), str(out), str(piece)):+ set_hidden(f, True)+ cur = out+ cur_frames = ctx_frames + int(w["new_frames"])+ completed += 1+ except Exception as exc: # noqa: BLE001+ # VA-38: a chain that dies at window k used to leave windows+ # 1..k-1 on disk (the docstring above) but INVISIBLE — hidden+ # working files nobody could find. Join what exists into a+ # real, VISIBLE, labelled output before re-raising, so the+ # completed minutes are not just present on disk but usable.+ # Never lets a failure IN this recovery path shadow the real+ # error — it is caught, logged, and the original exception+ # still propagates either way.+ try:+ _publish_windows_partial(job, p, plan, pieces, completed,+ raw_out, codec, fps)+ except Exception as pub_exc: # noqa: BLE001+ push(f"[windows] could not publish the partial result ({pub_exc})")+ raise exc# 3. THE JOIN, trimmed to the asked length.keep = min(int(total_frames), int(plan["delivered_frames"]))lst = work / f"{raw_out.stem}_windows.txt"@@ -29825,15 +33757,19 @@ def _gemma4_tower_supported() -> bool | None:return res-def _take_ffmpeg(cmd: list[str], label: str, job: dict | None) -> None:+def _take_ffmpeg(cmd: list[str], label: str, job: dict | None,+ pgid_key: str = "mux_pgid") -> None:"""A One Shot ffmpeg step that Stop can end (LTX-01).These ran as bare `subprocess.run(check=True)`: no process group Stopknew about, so Stop during the final join waited for the whole encode,and the take was then published and filed done. Registered under`mux_pgid` like every other post-process; raises JobCancelled when Stop- ended it and RuntimeError on any other non-zero exit (check=True)."""- r = run_tracked_subprocess(cmd, pgid_key="mux_pgid", label=label, job=job)+ ended it and RuntimeError on any other non-zero exit (check=True).+ `pgid_key`: the recovery join (/take/join_partial) runs OUTSIDE the+ queue and must never take the generation queue's `mux_pgid` slot+ (4.17 Codex SAFETY-7) — it passes its own."""+ r = run_tracked_subprocess(cmd, pgid_key=pgid_key, label=label, job=job)if r.returncode != 0:tail = (r.stderr or r.stdout or "").strip()[-300:]raise RuntimeError(f"{label} failed (ffmpeg exit {r.returncode})"@@ -29841,7 +33777,7 @@ def _take_ffmpeg(cmd: list[str], label: str, job: dict | None) -> None:def _join_take_parts(ff: str, parts: list[str], final: Path, fps: float = 24.0,- job: dict | None = None) -> None:+ job: dict | None = None, pgid_key: str = "mux_pgid") -> None:"""Join the parts of a one-shot take with the sound locked to the picture.Every part's audio comes out of the model a few hundredths of a second@@ -29856,7 +33792,7 @@ def _join_take_parts(ff: str, parts: list[str], final: Path, fps: float = 24.0,_take_ffmpeg([ff, "-loglevel", "error", "-y", "-i", parts[0],"-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p","-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", str(final)],- "One Shot join", job)+ "One Shot join", job, pgid_key)returncmd = [ff, "-loglevel", "error", "-y"]graph = []@@ -29873,7 +33809,7 @@ def _join_take_parts(ff: str, parts: list[str], final: Path, fps: float = 24.0,cmd += ["-filter_complex", ";".join(graph), "-map", "[v]", "-map", "[a]","-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p","-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", str(final)]- _take_ffmpeg(cmd, "One Shot join", job)+ _take_ffmpeg(cmd, "One Shot join", job, pgid_key)def _take_preview_follows(job: dict, child: dict | None) -> None:@@ -29909,9 +33845,53 @@ def run_take_job_inner(job: dict) -> None:take_dir = STATE_DIR / "take" / job["id"]take_dir.mkdir(parents=True, exist_ok=True)ff = str(FFMPEG)- outs: list[str] = []- rendered_out = ""+ # RESUME (VA-17 / H3-11): a prior take that was stopped or crashed left+ # its finished parts un-hidden with a `one_shot_unfinished` block on the+ # last part's sidecar — see the except clause below. /take/resume reads+ # that block and re-queues with `take["_resume"]` carrying exactly what+ # is needed to pick the take back up instead of starting over at part 1.+ resume = take.get("_resume") or {}+ resume_outs = [str(x) for x in (resume.get("outs") or []) if x]+ # 4.17 Codex SAFETY-5: `outs` are the files the join uses — for a speech+ # handoff, trimmed/J-cut intermediates under STATE_DIR/take/ with no+ # sidecar and no gallery card. `visible` are the same parts AS RENDERED+ # (in outputs/, with sidecars): what recovery shows and hides.+ resume_visible = [str(x) for x in (resume.get("visible") or []) if x]+ if len(resume_visible) != len(resume_outs):+ resume_visible = list(resume_outs)+ start_k = 0+ if resume_outs:+ try:+ start_k = max(0, min(n_parts, int(resume.get("start_k") or len(resume_outs))))+ except (TypeError, ValueError):+ start_k = min(n_parts, len(resume_outs))+ # Resuming re-arms the normal "working file" contract: parts are+ # hidden while the take is live, un-hidden only if it stops again.+ for _ro in dict.fromkeys(resume_outs + resume_visible):+ try:+ set_hidden(_ro, True)+ except Exception: # noqa: BLE001+ pass+ push(f"[take] resuming one shot at part {start_k + 1} of {n_parts} "+ f"({len(resume_outs)} part(s) already on disk)")+ outs: list[str] = list(resume_outs)+ visible_outs: list[str] = list(resume_visible)+ if resume_outs:+ # VA-28 x VA-17: parts_meta is indexed by part — a resumed take must+ # carry the seeds of the parts it did NOT re-render, or part 1's seed+ # (the take's restored seed) would be the first RESUMED part's.+ # SAFETY-12: the recovery manifest records them (a speech-handoff+ # intermediate has no sidecar at all); otherwise they come from the+ # rendered part's sidecar, where both engines write `params.seed_used`+ # (a top-level read found nothing) — _sb_sidecar_seed reads both.+ _prior_seeds = resume.get("part_seeds")+ if not isinstance(_prior_seeds, list) or len(_prior_seeds) != len(resume_outs):+ _prior_seeds = [_sb_sidecar_seed(_rv) for _rv in resume_visible]+ job["take_part_seeds"] = list(_prior_seeds)+ rendered_out = visible_outs[-1] if visible_outs else ""tail_wav: str | None = None # speech handoff: the previous part's last word, mixed over this part's head+ if resume_outs and resume.get("tail_wav") and Path(str(resume.get("tail_wav"))).is_file():+ tail_wav = str(resume["tail_wav"])last_png: str | None = None# The continuity lock: "" when the user switched it off (then blank beats# hold with TAKE_HOLD alone and a retake does not double anything).@@ -29927,9 +33907,21 @@ def run_take_job_inner(job: dict) -> None:if first_image and not Path(first_image).is_file():first_image = ""render_part = run_h3_job_inner if engine == "h3" else run_job_inner- push(f"[take] one shot · {take['seconds']} s · {take['beats']} beats · {n_parts} parts on "- f"{'H3' if engine == 'h3' else 'LTX'}"- + (" · opens on the reference image" if first_image else ""))+ if resume_outs and start_k < n_parts:+ # SAFETY-6: the handoff frame is rebuilt from the last kept part, never+ # trusted from the manifest — a Stop during (or before) the previous+ # run's frame extraction recorded a path that was never written, and+ # the resumed part then started from a missing image and failed again.+ if not Path(resume_outs[-1]).is_file():+ raise RuntimeError(f"part {start_k} of this take is no longer on disk — "+ "it can't be resumed")+ last_png = str(take_dir / f"part{start_k}_last.png")+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-sseof", "-0.05", "-i", resume_outs[-1],+ "-frames:v", "1", "-update", "1", last_png], "One Shot handoff frame", job)+ if not resume_outs:+ push(f"[take] one shot · {take['seconds']} s · {take['beats']} beats · {n_parts} parts on "+ f"{'H3' if engine == 'h3' else 'LTX'}"+ + (" · opens on the reference image" if first_image else ""))def _child_params(k: int, idxs: list[int], chain: list[str]) -> dict:cp = dict(p)@@ -29955,6 +33947,7 @@ def run_take_job_inner(job: dict) -> None:cp["mode"] = "t2v"if engine == "h3":cp["h3_chain_prompts"] = chain+ cp["h3_chain_prompts_complete"] = True # each beat is a whole window's promptcp["prompt"] = chain[0]else:# One prompt per part: its beats in order. A part is a plain LTX@@ -29970,215 +33963,522 @@ def run_take_job_inner(job: dict) -> None:cp["i2v_reference_mode"] = "anchor"return cp- for k, idxs in enumerate(parts):- if job.get("cancel_requested"):- raise RuntimeError("stopped between parts")- chain = [(beats[i] if i < len(beats) else "") or hold for i in idxs]- child_params = _child_params(k, idxs, chain)- child = {"id": f"{job['id']}-p{k + 1}", "params": child_params,- "status": "running", "created_at": job.get("created_at"),- "started_ts": time.time()}- push(f"[take] beats {idxs[0] + 1}–{idxs[-1] + 1} of {take['beats']} · part {k + 1} of {n_parts}"- + (" · continues from the last frame" if last_png else ""))- _take_preview_follows(job, child)- render_part(child)- out = child.get("output_path")- if not out or not Path(out).is_file():- raise RuntimeError(f"part {k + 1} produced no clip")- # CONTINUITY CHECK: did the light move across this part? One retake- # with the lock said twice and a fresh seed; keep the steadier clip.- # Skipped when the user turned retakes off.- drift = take_drift(out)- if drift.get("drifted") and retake_allowed and not job.get("cancel_requested"):- push(f"[take] part {k + 1}: the light drifted (luma {drift['luma_first']} → "- f"{drift['luma_last']}) — retaking it once"- + (" with the continuity lock doubled" if lock else " with a fresh seed"))- chain2 = [(c + " " + lock) if (c and lock) else c for c in chain]- retry_params = _child_params(k, idxs, chain2)- try:- retry_params["seed"] = str(int(retry_params.get("seed") or 0) + 101)- except (TypeError, ValueError):- retry_params["seed"] = "-1"- retry = {"id": f"{job['id']}-p{k + 1}r", "params": retry_params,+ try:+ for k, idxs in enumerate(parts):+ if k < start_k:+ continue # already rendered before the stop this resumes+ if job.get("cancel_requested"):+ raise RuntimeError("stopped between parts")+ chain = [(beats[i] if i < len(beats) else "") or hold for i in idxs]+ child_params = _child_params(k, idxs, chain)+ child = {"id": f"{job['id']}-p{k + 1}", "params": child_params,"status": "running", "created_at": job.get("created_at"),"started_ts": time.time()}- _take_preview_follows(job, retry)- render_part(retry)- out2 = retry.get("output_path")- d2 = take_drift(out2) if out2 and Path(out2).is_file() else {"delta": 9.0}- if d2.get("delta", 9.0) < drift["delta"]:- push(f"[take] part {k + 1}: the retake holds the light better "- f"(Δ {d2.get('delta')} vs {drift['delta']}) — using it")- try:- set_hidden(str(out), True)- except Exception: # noqa: BLE001- pass- out = out2- else:- push(f"[take] part {k + 1}: the retake did not help (Δ {d2.get('delta')}) — keeping the first")- if out2:+ push(f"[take] beats {idxs[0] + 1}–{idxs[-1] + 1} of {take['beats']} · part {k + 1} of {n_parts}"+ + (" · continues from the last frame" if last_png else ""))+ _take_preview_follows(job, child)+ render_part(child)+ out = child.get("output_path")+ if not out or not Path(out).is_file():+ raise RuntimeError(f"part {k + 1} produced no clip")+ # VA-28: which seed actually rendered the part that gets kept — reset+ # whenever a retake below wins, so this always tracks `out`. Recorded+ # in take_block.parts_meta at the end; a random parent seed (-1) used+ # to leave every part's real seed unrecorded, so Load Params on a+ # random-seed take could not reproduce it.+ winning_seed = child_params.get("seed_used")+ # CONTINUITY CHECK: did the light move across this part? One retake+ # with the lock said twice and a fresh seed; keep the steadier clip.+ # Skipped when the user turned retakes off.+ drift = take_drift(out)+ if drift.get("drifted") and retake_allowed and not job.get("cancel_requested"):+ push(f"[take] part {k + 1}: the light drifted (luma {drift['luma_first']} → "+ f"{drift['luma_last']}) — retaking it once"+ + (" with the continuity lock doubled" if lock else " with a fresh seed"))+ chain2 = [(c + " " + lock) if (c and lock) else c for c in chain]+ retry_params = _child_params(k, idxs, chain2)+ # VA-16: with the form's seed left on "-1" (random), every retake+ # of every part landed on the SAME seed — int("-1") + 101 == 100,+ # every time, for every part, on every install. "-1" never hit+ # the except branch this was clearly meant to fall back to; it's+ # a valid int, so the arithmetic silently "succeeded" into a+ # fixed number. -1 now stays -1 (a genuine fresh random roll,+ # same as the first attempt); only an EXPLICIT seed gets the+ # deterministic +101 offset (so a user who pinned a seed to+ # reproduce a take still gets a reproducible, DIFFERENT retake+ # seed rather than colliding with the first attempt).+ retry_params["seed"] = _take_retry_seed(retry_params.get("seed"), 101)+ retry = {"id": f"{job['id']}-p{k + 1}r", "params": retry_params,+ "status": "running", "created_at": job.get("created_at"),+ "started_ts": time.time()}+ _take_preview_follows(job, retry)+ render_part(retry)+ out2 = retry.get("output_path")+ d2 = take_drift(out2) if out2 and Path(out2).is_file() else {"delta": 9.0}+ if d2.get("delta", 9.0) < drift["delta"]:+ push(f"[take] part {k + 1}: the retake holds the light better "+ f"(Δ {d2.get('delta')} vs {drift['delta']}) — using it")try:- set_hidden(str(out2), True)- except Exception: # noqa: BLE001+ set_hidden(str(out), True)+ except Exception: # noqa: BLE001pass- elif drift.get("drifted"):- push(f"[take] part {k + 1}: the light drifted (luma {drift.get('luma_first')} → "- f"{drift.get('luma_last')}) — retakes are off, keeping it")- job.setdefault("take_drift", []).append(drift)- # LIP-SYNC GATE: a spoken part whose mouth does not follow its voice is- # retaken once with a fresh seed, and the better-scoring clip is kept.- # Measured 2026-09-07: identical settings gave +0.41 on one line and- # −0.27 on the next, so this is not something the words can secure.- ls = take_lipsync_score(out) if take_expects_speech(p, chain) else None- if ls is not None:- push(f"[take] part {k + 1}: lip-sync {ls:+.2f}" + ("" if ls >= TAKE_LIPSYNC_MIN else- f" — under {TAKE_LIPSYNC_MIN:.2f}, the voice is not on his mouth"))- attempt = 0- while (ls is not None and ls < TAKE_LIPSYNC_MIN and retake_allowed- and attempt < TAKE_LIPSYNC_RETAKES and not job.get("cancel_requested")):- attempt += 1- push(f"[take] part {k + 1}: retaking it for lip-sync with a fresh seed "- f"({attempt} of {TAKE_LIPSYNC_RETAKES})")- ls_params = _child_params(k, idxs, chain)+ out = out2+ winning_seed = retry_params.get("seed_used")+ else:+ push(f"[take] part {k + 1}: the retake did not help (Δ {d2.get('delta')}) — keeping the first")+ if out2:+ try:+ set_hidden(str(out2), True)+ except Exception: # noqa: BLE001+ pass+ elif drift.get("drifted"):+ push(f"[take] part {k + 1}: the light drifted (luma {drift.get('luma_first')} → "+ f"{drift.get('luma_last')}) — retakes are off, keeping it")+ job.setdefault("take_drift", []).append(drift)+ # LIP-SYNC GATE: a spoken part whose mouth does not follow its voice is+ # retaken once with a fresh seed, and the better-scoring clip is kept.+ # Measured 2026-09-07: identical settings gave +0.41 on one line and+ # −0.27 on the next, so this is not something the words can secure.+ ls = take_lipsync_score(out) if take_expects_speech(p, chain) else None+ if ls is not None:+ push(f"[take] part {k + 1}: lip-sync {ls:+.2f}" + ("" if ls >= TAKE_LIPSYNC_MIN else+ f" — under {TAKE_LIPSYNC_MIN:.2f}, the voice is not on his mouth"))+ attempt = 0+ while (ls is not None and ls < TAKE_LIPSYNC_MIN and retake_allowed+ and attempt < TAKE_LIPSYNC_RETAKES and not job.get("cancel_requested")):+ attempt += 1+ push(f"[take] part {k + 1}: retaking it for lip-sync with a fresh seed "+ f"({attempt} of {TAKE_LIPSYNC_RETAKES})")+ ls_params = _child_params(k, idxs, chain)+ # VA-16: same fixed-seed bug as the light-drift retake above —+ # a random ("-1") take's lip-sync retakes always landed on 210+ # then 421, identically, for every part, on every install.+ ls_params["seed"] = _take_retry_seed(ls_params.get("seed"), 211 * attempt)+ ls_retry = {"id": f"{job['id']}-p{k + 1}l" + (str(attempt) if attempt > 1 else ""),+ "params": ls_params, "status": "running",+ "created_at": job.get("created_at"), "started_ts": time.time()}+ _take_preview_follows(job, ls_retry)+ render_part(ls_retry)+ out3 = ls_retry.get("output_path")+ ls2 = take_lipsync_score(out3) if out3 and Path(out3).is_file() else None+ if ls2 is not None and ls2 > ls:+ push(f"[take] part {k + 1}: the retake syncs better ({ls2:+.2f} vs {ls:+.2f}) — using it")+ try:+ set_hidden(str(out), True)+ except Exception: # noqa: BLE001+ pass+ out, ls = out3, ls2+ winning_seed = ls_params.get("seed_used")+ else:+ push(f"[take] part {k + 1}: the retake did not sync better ({ls2}) — keeping the earlier one")+ if out3:+ try:+ set_hidden(str(out3), True)+ except Exception: # noqa: BLE001+ pass+ job.setdefault("take_lipsync", []).append(ls)+ job.setdefault("take_part_seeds", []).append(winning_seed)+ outs.append(out)+ visible_outs.append(out)+ rendered_out = out # the part as rendered — the one with a sidecar+ # Parts are working files: kept, hidden from the gallery. The one shot+ # is the output.try:- ls_params["seed"] = str(int(ls_params.get("seed") or 0) + 211 * attempt)- except (TypeError, ValueError):- ls_params["seed"] = "-1"- ls_retry = {"id": f"{job['id']}-p{k + 1}l" + (str(attempt) if attempt > 1 else ""),- "params": ls_params, "status": "running",- "created_at": job.get("created_at"), "started_ts": time.time()}- _take_preview_follows(job, ls_retry)- render_part(ls_retry)- out3 = ls_retry.get("output_path")- ls2 = take_lipsync_score(out3) if out3 and Path(out3).is_file() else None- if ls2 is not None and ls2 > ls:- push(f"[take] part {k + 1}: the retake syncs better ({ls2:+.2f} vs {ls:+.2f}) — using it")+ set_hidden(str(out), True)+ except Exception: # noqa: BLE001+ pass+ if take.get("handoff") == "speech" and tail_wav and Path(tail_wav).is_file():+ # The previous part's last word finishes over this part's opening+ # silence (a J-cut): its sound tail is mixed onto the head of this+ # clip, at level, before this clip is cut or anchored.+ led = str(take_dir / f"part{k + 1}_lead.mp4")+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-i", out, "-i", tail_wav,+ "-filter_complex", "[1:a]apad[t];[0:a][t]amix=inputs=2:duration=first:normalize=0[a]",+ "-map", "0:v", "-map", "[a]", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", led],+ "One Shot speech handoff", job)+ outs[-1] = led+ out = led+ tail_wav = None+ if take.get("handoff") == "speech" and k + 1 < n_parts:+ # Hand off on a TALKING frame, not where the part ends: the picture+ # is cut a moment before the line ends (the mouth still mid-word,+ # the only anchor measured to carry the voice onto the next part's+ # mouth), the sound runs to the end of the line, and the silent tail+ # after it is dropped. The last part keeps its written silence.+ pts = take_handoff_points(out)+ if pts is not None:+ cut, end = pts+ try:+ dur = float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",+ "-of", "csv=p=0", out], capture_output=True, text=True, errors="replace", timeout=30).stdout.strip())+ except Exception: # noqa: BLE001+ dur = 0.0+ if dur and 0.5 < cut < end <= dur:+ trimmed = str(take_dir / f"part{k + 1}_speech.mp4")+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-i", out, "-t", f"{cut:.3f}",+ "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-b:a", "192k", trimmed],+ "One Shot speech handoff", job)+ tail = str(take_dir / f"part{k + 1}_tail.wav")+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-ss", f"{cut:.3f}", "-to", f"{end:.3f}",+ "-i", out, "-vn", "-c:a", "pcm_s16le", tail],+ "One Shot speech handoff", job)+ push(f"[take] part {k + 1}: hands off at {cut:.1f} s on a talking frame; the last word "+ f"finishes over the next part ({dur - end:.1f} s of silent tail dropped)")+ outs[-1] = trimmed+ out = trimmed+ tail_wav = tail+ # SAFETY-6: assigned only once the frame is on disk — a Stop inside+ # this ffmpeg left `last_png` naming a file that was never written.+ _png = str(take_dir / f"part{k + 1}_last.png")+ _take_ffmpeg([ff, "-loglevel", "error", "-y", "-sseof", "-0.05", "-i", out,+ "-frames:v", "1", "-update", "1", _png], "One Shot handoff frame", job)+ last_png = _png+ job["take_progress"] = {"part": k + 1, "parts": n_parts}+ # H3-11 / VA-17's chained-window ask: "stop after this part — keep+ # what's finished" is a CLEAN finish, not a cancel. cancel_requested+ # (above) still hard-stops mid-part and loses it; this only takes+ # effect at a part boundary, once the part just rendered is already+ # safely on disk, and it joins everything done so far instead of+ # raising. /stop/after_part sets the flag on the live job.+ if job.get("stop_after_part") and k + 1 < n_parts:+ push(f"[take] stopping after part {k + 1} of {n_parts} — keeping what "+ f"finished (requested, not a failure)")+ break+ _take_preview_follows(job, None) # the join has no preview+ if job.get("cancel_requested"):+ raise RuntimeError("stopped before the join")+ lst = take_dir / "concat.txt"+ lst.write_text("".join(ffconcat_line(o) for o in outs), encoding="utf-8")+ final = _unique_output_path(+ OUTPUT, _descriptive_filename(label, p.get("prompt") or "", fallback="take") + f"_take{take['seconds']}s")+ stopped_early = len(outs) < n_parts+ push(f"[take] joining {len(outs)} of {n_parts} parts → {final.name}"+ + (" (stopped early)" if stopped_early else ""))+ _join_take_parts(ff, outs, final, job=job)+ # Stop during the join ends it (JobCancelled above); a Stop that lands as+ # the encode finishes must not be published and filed done either.+ _raise_if_cancelled(job, "the one shot was published")+ # THE TAKE'S SIDECAR IS THE TAKE'S, NOT ITS LAST PART'S (LTX-02). The+ # technical fields (canvas, seed, model) still come from the last part as+ # rendered — outs[-1] can be a speech-handoff remux with no sidecar of its+ # own, which is why the rendered file is tracked separately. But Load+ # Params reads `params`, and that used to be the last part's: a short i2v+ # of the final beats on a handoff frame, so reopening a One Shot restored+ # a different, smaller render. `params` is now the parent job's own+ # intent with the full take block, and every output field names the take.+ side: dict = {}+ try:+ side = json.loads(Path((rendered_out or outs[-1]) + ".json").read_text())+ except (OSError, ValueError):+ side = {}+ # VA-28: the real seed that rendered each kept part, so Load Params on a+ # random-seed (-1) take can reproduce it instead of drawing n fresh+ # random seeds on the next Generate. First part's seed becomes the+ # take's own restored seed (oneshot.js); a NEW take derives the rest as+ # seed + k, matching Windows' own `seed + k` convention+ # (ltx_windows.py) rather than each part rolling its own random draw.+ part_seeds = job.get("take_part_seeds") or []+ take_block = {"seconds": take["seconds"], "beats": beats, "parts": outs, "engine": engine,+ "beats_per_part": take.get("beats_per_part")+ or (TAKE_H3_BEATS_PER_PART if engine == "h3" else TAKE_LTX_BEATS_PER_PART),+ "part_frames": take.get("part_frames"),+ "light_lock": lock, "retake": retake_allowed,+ "camera": take.get("camera") or "",+ "handoff": take.get("handoff") or "last",+ "stopped_early": stopped_early,+ "parts_meta": [{"seed_used": s} for s in part_seeds]}+ side.update({+ "output": str(final), "raw_output": str(final), "native_output": str(final),+ "mode": p.get("mode", "t2v"), "engine": engine, "prompt": p.get("prompt") or "",+ "label": label, "elapsed_sec": round(time.time() - t0, 1),+ "frames": take["frames"], "seconds": take["seconds"],+ "take": take_block,+ "temporal_mode": "native", "long_mode": "native", "window_prompts": [],+ "queue_id": job["id"], "started": job.get("started_at"),+ "params": {**p, "take": {**(p.get("take") or {}), **take_block},+ "image": first_image or None,+ "temporal_mode": "native", "long_mode": "native",+ "window_prompts": []},+ })+ if isinstance(side.get("upscale"), dict):+ # Its `source` named the last part's native file, not this take.+ side["upscale"] = {k: v for k, v in side["upscale"].items() if k != "source"}+ if engine == "h3":+ side["h3_chain_prompts"] = beats+ side["params"]["h3_chain_prompts"] = beats+ # The last part's sidecar names ITS image — a handoff frame in the state+ # dir. The one shot's own image is the user's anchor, or nothing.+ if first_image:+ side["image"] = first_image+ else:+ side.pop("image", None)+ write_sidecar(final.with_suffix(final.suffix + ".json"), side)+ job["output_path"] = str(final)+ push(f"[take] one shot done in {round(time.time() - t0)}s → {final.name}")+ except Exception:+ # RECOVERY (VA-17 / H3-11): a One Shot that stops or fails partway+ # must not disappear the minutes already spent. Every completed+ # part up to here is a real, playable clip that was hidden as a+ # "working file" on the assumption the take would finish; since it+ # didn't, un-hide them, relabel them as unfinished, and stash a+ # resume manifest on the last one so /take/resume and+ # /take/join_partial (routes_queue.py) can pick this take back up+ # or salvage what's there without the user losing anything.+ if outs:+ # SAFETY-5: the cards, labels and the manifest live on the parts AS+ # RENDERED (outputs/, with sidecars) — a speech handoff's outs[] are+ # intermediates under STATE_DIR/take/ that the gallery never lists+ # and /take/* refuses, so its recovery card never appeared.+ for _i, _op in enumerate(visible_outs):try:- set_hidden(str(out), True)+ set_hidden(_op, False)except Exception: # noqa: BLE001pass- out, ls = out3, ls2- else:- push(f"[take] part {k + 1}: the retake did not sync better ({ls2}) — keeping the earlier one")- if out3:- try:- set_hidden(str(out3), True)- except Exception: # noqa: BLE001- pass- job.setdefault("take_lipsync", []).append(ls)- outs.append(out)- rendered_out = out # the part as rendered — the one with a sidecar- # Parts are working files: kept, hidden from the gallery. The one shot- # is the output.- try:- set_hidden(str(out), True)- except Exception: # noqa: BLE001- pass- if take.get("handoff") == "speech" and tail_wav and Path(tail_wav).is_file():- # The previous part's last word finishes over this part's opening- # silence (a J-cut): its sound tail is mixed onto the head of this- # clip, at level, before this clip is cut or anchored.- led = str(take_dir / f"part{k + 1}_lead.mp4")- _take_ffmpeg([ff, "-loglevel", "error", "-y", "-i", out, "-i", tail_wav,- "-filter_complex", "[1:a]apad[t];[0:a][t]amix=inputs=2:duration=first:normalize=0[a]",- "-map", "0:v", "-map", "[a]", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", led],- "One Shot speech handoff", job)- outs[-1] = led- out = led- tail_wav = None- if take.get("handoff") == "speech" and k + 1 < n_parts:- # Hand off on a TALKING frame, not where the part ends: the picture- # is cut a moment before the line ends (the mouth still mid-word,- # the only anchor measured to carry the voice onto the next part's- # mouth), the sound runs to the end of the line, and the silent tail- # after it is dropped. The last part keeps its written silence.- pts = take_handoff_points(out)- if pts is not None:- cut, end = ptstry:- dur = float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",- "-of", "csv=p=0", out], capture_output=True, text=True, errors="replace", timeout=30).stdout.strip())+ _sc = Path(_op + ".json")+ if _sc.is_file():+ _meta = json.loads(_sc.read_text(encoding="utf-8"))+ else:+ _meta = {}+ except (OSError, ValueError):+ _meta = {}+ _base_label = (_meta.get("label") or f"{label or 'one shot'} · part {_i + 1} of {n_parts}")+ if not str(_base_label).endswith("(unfinished)"):+ _meta["label"] = f"{_base_label} (unfinished)"+ if _i == len(visible_outs) - 1:+ # Only the LAST part carries the resume manifest — the+ # others just need to be visible and honestly labelled.+ # `outs` = what a join/resume stitches (intermediates+ # included); `visible` = the cards; `part_seeds` survive+ # parts with no sidecar (SAFETY-12). `last_png` is kept+ # for reference only — Resume rebuilds it (SAFETY-6).+ _seeds = list(job.get("take_part_seeds") or [])+ _meta["one_shot_unfinished"] = {+ "job_id": job["id"], "done_parts": len(outs), "total_parts": n_parts,+ "outs": list(outs), "visible": list(visible_outs),+ "part_seeds": _seeds if len(_seeds) == len(outs) else None,+ "last_png": last_png if last_png and Path(last_png).is_file() else None,+ "tail_wav": tail_wav if tail_wav and Path(tail_wav).is_file() else None,+ "take": {k: v for k, v in take.items() if k != "_resume"},+ "label": label, "engine": engine,+ "p": {k: v for k, v in p.items() if k != "take"},+ }+ try:+ write_sidecar(Path(_op + ".json"), _meta)except Exception: # noqa: BLE001- dur = 0.0- if dur and 0.5 < cut < end <= dur:- trimmed = str(take_dir / f"part{k + 1}_speech.mp4")- _take_ffmpeg([ff, "-loglevel", "error", "-y", "-i", out, "-t", f"{cut:.3f}",- "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p",- "-c:a", "aac", "-b:a", "192k", trimmed],- "One Shot speech handoff", job)- tail = str(take_dir / f"part{k + 1}_tail.wav")- _take_ffmpeg([ff, "-loglevel", "error", "-y", "-ss", f"{cut:.3f}", "-to", f"{end:.3f}",- "-i", out, "-vn", "-c:a", "pcm_s16le", tail],- "One Shot speech handoff", job)- push(f"[take] part {k + 1}: hands off at {cut:.1f} s on a talking frame; the last word "- f"finishes over the next part ({dur - end:.1f} s of silent tail dropped)")- outs[-1] = trimmed- out = trimmed- tail_wav = tail- last_png = str(take_dir / f"part{k + 1}_last.png")- _take_ffmpeg([ff, "-loglevel", "error", "-y", "-sseof", "-0.05", "-i", out,- "-frames:v", "1", "-update", "1", last_png], "One Shot handoff frame", job)- job["take_progress"] = {"part": k + 1, "parts": n_parts}- _take_preview_follows(job, None) # the join has no preview- if job.get("cancel_requested"):- raise RuntimeError("stopped before the join")- lst = take_dir / "concat.txt"- lst.write_text("".join(ffconcat_line(o) for o in outs), encoding="utf-8")- final = _unique_output_path(- OUTPUT, _descriptive_filename(label, p.get("prompt") or "", fallback="take") + f"_take{take['seconds']}s")- push(f"[take] joining {n_parts} parts → {final.name}")- _join_take_parts(ff, outs, final, job=job)- # Stop during the join ends it (JobCancelled above); a Stop that lands as- # the encode finishes must not be published and filed done either.- _raise_if_cancelled(job, "the one shot was published")- # THE TAKE'S SIDECAR IS THE TAKE'S, NOT ITS LAST PART'S (LTX-02). The- # technical fields (canvas, seed, model) still come from the last part as- # rendered — outs[-1] can be a speech-handoff remux with no sidecar of its- # own, which is why the rendered file is tracked separately. But Load- # Params reads `params`, and that used to be the last part's: a short i2v- # of the final beats on a handoff frame, so reopening a One Shot restored- # a different, smaller render. `params` is now the parent job's own- # intent with the full take block, and every output field names the take.- side: dict = {}- try:- side = json.loads(Path((rendered_out or outs[-1]) + ".json").read_text())- except (OSError, ValueError):- side = {}- take_block = {"seconds": take["seconds"], "beats": beats, "parts": outs, "engine": engine,- "beats_per_part": take.get("beats_per_part")- or (TAKE_H3_BEATS_PER_PART if engine == "h3" else TAKE_LTX_BEATS_PER_PART),- "part_frames": take.get("part_frames"),- "light_lock": lock, "retake": retake_allowed,- "camera": take.get("camera") or "",- "handoff": take.get("handoff") or "last"}- side.update({- "output": str(final), "raw_output": str(final), "native_output": str(final),- "mode": p.get("mode", "t2v"), "engine": engine, "prompt": p.get("prompt") or "",- "label": label, "elapsed_sec": round(time.time() - t0, 1),- "frames": take["frames"], "seconds": take["seconds"],- "take": take_block,- "temporal_mode": "native", "long_mode": "native", "window_prompts": [],- "queue_id": job["id"], "started": job.get("started_at"),- "params": {**p, "take": {**(p.get("take") or {}), **take_block},- "image": first_image or None,- "temporal_mode": "native", "long_mode": "native",- "window_prompts": []},- })- if isinstance(side.get("upscale"), dict):- # Its `source` named the last part's native file, not this take.- side["upscale"] = {k: v for k, v in side["upscale"].items() if k != "source"}- if engine == "h3":- side["h3_chain_prompts"] = beats- side["params"]["h3_chain_prompts"] = beats- # The last part's sidecar names ITS image — a handoff frame in the state- # dir. The one shot's own image is the user's anchor, or nothing.- if first_image:- side["image"] = first_image- else:- side.pop("image", None)- write_sidecar(final.with_suffix(final.suffix + ".json"), side)- job["output_path"] = str(final)- push(f"[take] one shot done in {round(time.time() - t0)}s → {final.name}")+ pass+ push(f"[take] one shot stopped — {len(outs)} of {n_parts} part(s) kept and "+ f"un-hidden (Resume or Join what's done from the last part's card)")+ raise+++_QUEUE_MOVE_DIRECTIONS = ("up", "down", "top")+++def queue_move_job(job_id: str, direction: str) -> dict:+ """VC-26: reorder the QUEUED list — a job's position is the only thing+ that changes; params/id/queued_at are untouched. `direction` is "up"+ (swap with the previous row), "down" (swap with the next), or "top"+ (move to the front — the "prioritise this shot" gesture the review+ named directly). A no-op at either end (already first for up/top,+ already last for down) is `ok: True, moved: False`, not an error —+ the client doesn't have to guess the list's own boundaries."""+ direction = (direction or "").strip().lower()+ if direction not in _QUEUE_MOVE_DIRECTIONS:+ return {"ok": False, "error": f"direction must be one of {_QUEUE_MOVE_DIRECTIONS}"}+ moved = False+ with LOCK:+ q = STATE["queue"]+ idx = next((i for i, j in enumerate(q) if j.get("id") == job_id), None)+ if idx is None:+ return {"ok": False, "error": "That job is no longer queued."}+ if direction == "top" and idx > 0:+ q.insert(0, q.pop(idx))+ moved = True+ elif direction == "up" and idx > 0:+ q[idx - 1], q[idx] = q[idx], q[idx - 1]+ moved = True+ elif direction == "down" and idx < len(q) - 1:+ q[idx + 1], q[idx] = q[idx], q[idx + 1]+ moved = True+ persist_queue()+ return {"ok": True, "moved": moved}+++def queue_update_job(job_id: str, form: dict) -> dict:+ """VC-26: edit a QUEUED job in place — "Click a row to load it into the+ form and Update job." Re-validates the submitted form through+ make_job(), the single source of truth for what a job spec is, so an+ edited job passes exactly the checks a brand-new one would; only the+ id/status/queued_at/position survive from the original. Refuses (does+ not silently no-op) a job that already started rendering or finished —+ it is no longer in STATE["queue"] by the time that happens, so the+ lookup itself is the guard."""+ with LOCK:+ job = next((j for j in STATE["queue"] if j.get("id") == job_id), None)+ if job is None:+ return {"ok": False,+ "error": "That job is no longer queued — it may already "+ "be rendering or finished."}+ try:+ fresh = make_job(form)+ except CharacterRequestError as exc:+ return {"ok": False, "error": str(exc)}+ # 4.17 Codex SAFETY-4: the form re-derives every field it HAS; what it+ # cannot express (where the job came from, a storyboard session tag,+ # a retry's face-fix targets, …) is carried over from the original+ # instead of being dropped. H3-only extras stay behind when the edit+ # moved the job off H3.+ old = job.get("params") or {}+ new_params = fresh["params"]+ new_is_h3 = str(new_params.get("engine") or "").lower() == "h3"+ for k, v in old.items():+ if k in new_params or (k.startswith("h3_") and not new_is_h3):+ continue+ new_params[k] = v+ if old.get("session_tag") and not new_params.get("session_tag"):+ new_params["session_tag"] = old["session_tag"]+ job["params"] = new_params+ persist_queue()+ return {"ok": True, "id": job_id}+++_SHARP_EXPORT_VIDEO_SUFFIXES = {".mp4"}+++def _sharp_export_contained(source_path: str) -> bool:+ """True when a Sharp export source is a clip of this panel's own.++ Codex UI-1: the route took any path on disk, so a POST could export a private video from anywhere (or through a symlink+ placed in outputs/) into the served gallery, sidecar included. Same+ containment as every other media route (/poster, /queue/load_params,+ /uploads/last_frame): resolve first — which follows symlinks — then+ require outputs/ or uploads/. The job keeps the path as given (the+ gallery's own spelling, e.g. through a symlinked outputs folder)."""+ if not source_path:+ return False+ try:+ src = Path(str(source_path)).resolve()+ roots = [OUTPUT.resolve(), UPLOADS.resolve()]+ except (OSError, RuntimeError, ValueError):+ return False+ return any(src.is_relative_to(r) for r in roots)+++def queue_sharp_export(source_path: str) -> dict:+ """Queue one Sharp (PiperSR ANE) export of a finished clip.++ Same shape as queue_face_fix(): refuse up front what the worker would+ only refuse after a wait, dedupe a double click on the same source+ while it's already queued/running. Returns {ok, id} or {ok: False, error}.+ """+ src = Path(str(source_path or ""))+ if source_path and not _sharp_export_contained(source_path):+ return {"ok": False, "error": "Sharp export works on clips in outputs or uploads only."}+ if not source_path or not src.is_file():+ return {"ok": False, "error": "That clip is not on disk any more."}+ if src.suffix.lower() not in _SHARP_EXPORT_VIDEO_SUFFIXES:+ return {"ok": False, "error": "Sharp export works on video clips, not stills."}+ if not PIPERSR_UPSCALE_ENABLED:+ return {"ok": False, "code": "pack_missing",+ "error": "Sharp export needs PiperSR (Apple Neural Engine "+ "upscaler), which isn't installed on this Mac yet. "+ "Open Settings → Models to install it."}+ job = {+ "id": _new_job_id(),+ "status": "queued",+ "queued_at": time.strftime("%Y-%m-%d %H:%M:%S"),+ "started_at": None, "finished_at": None, "elapsed_sec": None,+ "params": {"mode": "sharp_export", "source_path": str(src),+ "open_when_done": False},+ "raw_path": None, "output_path": None, "error": None,+ }+ with QUEUE_COND:+ cands = list(STATE["queue"])+ if STATE.get("current"):+ cands.insert(0, STATE["current"])+ for j in cands:+ jp = (j or {}).get("params") or {}+ if jp.get("mode") == "sharp_export" and jp.get("source_path") == str(src):+ return {"ok": True, "id": j["id"], "duplicate": True}+ STATE["queue"].append(job)+ QUEUE_COND.notify_all()+ persist_queue()+ return {"ok": True, "id": job["id"]}+++# VC-18/37: "Sharp export" on an ALREADY-RENDERED clip. Sharp (PiperSR, a real+# ANE-accelerated 2x detail-recovery pass) has always existed — but only as a+# pre-render "Method" choice under After the render's Export row, so the only+# way to get it on a clip you already like was to re-render the whole thing+# from scratch, hoping for the same take. This queues the SAME+# run_pipersr_tracked() call the render-time path uses (mlx_ltx_panel.py, the+# `upscale_method == 'pipersr'` branch below `compute_upscale_plan`), pointed+# at an existing file instead of a job's own fresh output. No diffusion, no+# helper subprocess, no GPU proper (PiperSR runs on the Neural Engine) — it+# still runs through the ordinary queue/worker/_GPU_LOCK path for the same+# reason every other post-render pass does: one job at a time, visible in+# Now/Queue, Stop-able, and never racing a real render's own ffmpeg mux.+def run_sharp_export_job_inner(job: dict) -> None:+ p = job["params"]+ src = p.get("source_path") or ""+ # UI-1: revalidate at run time — a queue persisted across restarts (or a+ # symlink swapped in while the job waited) must not reach outside+ # outputs/uploads either.+ if src and not _sharp_export_contained(src):+ raise RuntimeError("Sharp export works on clips in outputs or uploads only.")+ if not src or not Path(src).is_file():+ raise RuntimeError(f"source clip for Sharp export not found: {src!r}.")+ if not PIPERSR_UPSCALE_ENABLED:+ raise RenderRefused(+ "pack_missing",+ "Sharp export needs PiperSR (Apple Neural Engine upscaler), which "+ "isn't installed on this Mac yet. Open Settings → Models to "+ "install it, then try again.")+ source = Path(src)+ sw, sh = _probe_video_dims(str(source))+ if not (sw and sh):+ raise RuntimeError(f"could not read the size of {source.name}")+ # Same auto-pick the render-time Export row uses: fit to 720p unless the+ # clip is already at or past that on its long side, in which case there+ # is nothing to "fit" to — x2 is the only move left that does something.+ export_mode = "x2" if max(sw, sh) >= 1280 else "fit_720p"+ if p.get("sharp_mode") in ("fit_720p", "fit_1080p", "x2"):+ export_mode = str(p["sharp_mode"])+ codec = output_codec_settings()+ preset = os.environ.get("LTX_UPSCALE_PRESET", "medium")+ out_name = f"{source.stem}_sharp_{time.strftime('%Y%m%d_%H%M%S')}.mp4"+ final_out = _unique_output_path(OUTPUT, Path(out_name).stem, ".mp4")+ job["raw_path"] = str(final_out)+ push(f"Sharp export: {source.name} → {export_mode}, PiperSR/CoreML on the Neural Engine.")+ run_pipersr_tracked(source, final_out, export_mode, codec["crf"], codec["pix_fmt"], preset)+ if not final_out.exists() or final_out.stat().st_size == 0:+ raise RuntimeError("Sharp export produced no output — see Logs for the PiperSR error.")+ # Carry the source's own generation params forward (same prompt/seed/+ # mode/etc as the clip this was exported FROM) so the info modal and+ # Load Params still describe the shot, not just the export pass.+ src_sidecar_path = Path(str(source) + ".json")+ src_params: dict = {}+ if src_sidecar_path.is_file():+ try:+ src_params = (json.loads(src_sidecar_path.read_text(encoding="utf-8")) or {}).get("params") or {}+ except (OSError, json.JSONDecodeError):+ src_params = {}+ sidecar = {+ "output": str(final_out), "raw_output": str(final_out),+ "params": {**src_params, "mode": src_params.get("mode", "t2v"),+ "sharp_export_source": str(source), "sharp_export_mode": export_mode},+ "started": job.get("started_at"),+ "elapsed_sec": round(time.time() - job["started_ts"], 2) if job.get("started_ts") else None,+ "fps": FPS, "queue_id": job["id"],+ "output_codec": output_codec_settings(),+ }+ write_sidecar(final_out.with_suffix(final_out.suffix + ".json"), sidecar)+ job["output_path"] = str(final_out)+ push(f"Sharp export done → {final_out.name}")+ if p.get("open_when_done"):+ subprocess.run(["open", str(final_out)], check=False)def run_job_inner(job: dict) -> None:@@ -30193,6 +34493,8 @@ def run_job_inner(job: dict) -> None:return run_image_job_inner(job)if mode == "train":return run_train_job_inner(job)+ if mode == "sharp_export":+ return run_sharp_export_job_inner(job)# Second video engine. H3 is a self-contained subprocess pack with its own# geometry rules (17n+5 frames, 32-aligned dims) and no warm helper, so it# dispatches BEFORE every LTX-only clamp/validation below — none of which@@ -30255,7 +34557,7 @@ def run_job_inner(job: dict) -> None:# - extend / keyframe use stage1_steps + stage2_steps via two-stage path# - every HQ-pipeline quality uses two-stage HQ with its own schedule# - a2v uses A2VidPipelineTwoStage's stage1/stage2 walks- if mode not in ("extend", "keyframe", "a2v", "restore", "ingredients", "control", "upscale") and not ltx_quality_uses_hq(quality) and int(p.get("steps", 8)) < 8:+ if mode not in ("extend", "retake", "keyframe", "a2v", "restore", "ingredients", "control", "upscale") and not ltx_quality_uses_hq(quality) and int(p.get("steps", 8)) < 8:raise RuntimeError(f"steps={p.get('steps')} is below the 8-step minimum for the Q4 distilled ""schedule. Fewer steps truncates the sigma walk and leaves >70% noise in "@@ -30267,7 +34569,7 @@ def run_job_inner(job: dict) -> None:# has 9 points, so the helper dies minutes in with "cannot thin a 9-point# schedule (8 steps) up to 16 steps" (fleet, 4.11.1: i2v at 9 and 16 steps).# Refuse here, at no cost, and say where more steps actually live.- if mode not in ("extend", "keyframe", "a2v", "restore", "ingredients", "control", "upscale") and not ltx_quality_uses_hq(quality) and int(p.get("steps", 8)) > 8:+ if mode not in ("extend", "retake", "keyframe", "a2v", "restore", "ingredients", "control", "upscale") and not ltx_quality_uses_hq(quality) and int(p.get("steps", 8)) > 8:raise RuntimeError(f"steps={p.get('steps')} is above the 8-step distilled schedule: the Q4 ""distilled model has a fixed 9-point sigma table and cannot take more "@@ -30459,6 +34761,133 @@ def run_job_inner(job: dict) -> None:subprocess.run(["open", str(final_out)], check=False)return+ if mode == "retake":+ # Segment Retake (VA-26): "fix just the bad two seconds" — regenerate+ # one interior stretch of a clip while the rest is preserved, via the+ # SAME RetakePipeline / Q8 dev transformer Extend already uses (the+ # engine has always had this; the product surface did not). Same+ # hardware gate as Extend (the dev transformer's CFG-guided denoise+ # needs the same headroom regardless of which of the two APIs on+ # that pipeline object is called).+ if not SYSTEM_CAPS["allows_extend"]:+ raise RenderRefused(+ "hardware_tier",+ f"Retake isn't supported on the {SYSTEM_CAPS['label']} hardware "+ f"tier — the dev transformer needs more headroom than this Mac "+ f"has. It works from {min_ram_gb_for('allows_extend') or 48} GB."+ )+ ret_missing = hq_surface_missing()+ if ret_missing:+ raise RenderRefused(+ "pack_missing",+ f"Retake needs the LTX-2.5 High add-on (the Q8 model), which "+ f"isn't downloaded on this Mac yet. "+ f"Missing {len(ret_missing)} file(s): {', '.join(ret_missing[:3])}"+ f"{' …' if len(ret_missing) > 3 else ''}. "+ f"Open Settings → Models and download it, then render again."+ )+ src = p.get("video_path") or ""+ if not src or not Path(src).exists():+ raise RuntimeError(f"source video for retake not found: {src}")+ # Same native-render preference and resolution clamp as Extend+ # (issue #48 lineage; tier_max_dim("extend") — the two share a+ # memory profile, so the same clamp number is correct here).+ picked_src = Path(src)+ native_src = _native_render_for(picked_src)+ if native_src != picked_src:+ src = str(native_src)+ push(f"Retake: using the native render {native_src.name} instead of "+ f"the export {picked_src.name}.")+ original_src = Path(src)+ ret_max = tier_max_dim("extend")+ if ret_max:+ downscaled_src = _ensure_downscaled(original_src, max_dim=ret_max)+ if downscaled_src != original_src:+ push(f"Retake: source {original_src.name} downscaled to "+ f"{downscaled_src.name} (≤{ret_max} max-side, "+ f"{SYSTEM_CAPS['label']} tier).")+ src = str(downscaled_src)+ # Refuse a nonsense range before it ever reaches the helper — a+ # refusal costs nothing, a bad job spec costs a render.+ try:+ retake_start_sec = max(0.0, float(p.get("retake_start_sec") or 0.0))+ except (TypeError, ValueError):+ retake_start_sec = 0.0+ try:+ retake_end_sec = float(p.get("retake_end_sec") or 0.0)+ except (TypeError, ValueError):+ retake_end_sec = 0.0+ if retake_end_sec <= retake_start_sec:+ raise RuntimeError(+ f"Retake needs an end time after the start time "+ f"(got {retake_start_sec:.1f}s → {retake_end_sec:.1f}s)."+ )+ out_name = Path(src).stem + f"_retake_{stamp}.mp4"+ final_out = OUTPUT / out_name+ job["raw_path"] = str(final_out)+ cfg_scale = float(p.get("retake_cfg") or 1.0)+ steps = int(p["retake_steps"]) if p.get("retake_steps") else 8+ job_spec = {+ "action": "retake_segment",+ "id": job["id"],+ "params": {+ "model_dir": str(pack_path("q8")),+ "dev_transformer": hq_weights()["dev_transformer"],+ "prompt": p["prompt"],+ "negative_prompt": p.get("negative_prompt", ""),+ "video_path": src,+ "retake_start_sec": retake_start_sec,+ "retake_end_sec": retake_end_sec,+ "retake_audio_action": (p.get("retake_audio_action") or "keep"),+ "output_path": str(final_out),+ "seed": p["seed"],+ "steps": steps,+ "cfg_scale": cfg_scale,+ "loras": list(p.get("loras") or []),+ "frame_rate": float(FPS),+ },+ }+ push(f"Retake via helper: id={job['id']} src={Path(src).name} "+ f"{retake_start_sec:.1f}s→{retake_end_sec:.1f}s · steps={steps} "+ f"cfg={cfg_scale} · audio="+ f"{'regenerate' if p.get('retake_audio_action') == 'regenerate' else 'keep original'} "+ f"(Q8 dev transformer)")+ result = HELPER.run(job_spec)+ if "seed_used" in result:+ push(f"seed used: {result['seed_used']}")+ p["seed_used"] = result["seed_used"]+ # LIPSYNC-11: record what was DELIVERED, not make_job's defaults —+ # submitRetake sends no size or length, so p carried 1280x704 / 121+ # frames / the panel FPS whatever the source was, and the gallery's+ # clip_sec (frames / frame_rate) and the next retake's range bounds+ # read those. Measured from the file; the helper's own report+ # (source rate, its 1 + 8k cut, source size) is the fallback.+ ret_meas = _retake_delivered_geometry(final_out, result)+ sidecar = {+ "output": str(final_out), "raw_output": str(final_out),+ "params": {**p, **ret_meas, "command": "retake"},+ "started": job.get("started_at"),+ "elapsed_sec": round(time.time() - job["started_ts"], 2) if job.get("started_ts") else None,+ "fps": ret_meas.get("frame_rate") or FPS,+ "model": str(pack_path("q8")), "queue_id": job["id"],+ "helper_elapsed_sec": result.get("elapsed_sec"),+ "output_codec": output_codec_settings(),+ # Lineage, same shape as Extend's — a retake chain (or a retake+ # on an extended clip) stays diagnosable from the sidecar alone.+ "retake_picked": str(picked_src),+ "retake_source": src,+ "retake_start_sec": retake_start_sec,+ "retake_end_sec": retake_end_sec,+ "retake_start_frame": result.get("retake_start_frame"),+ "retake_end_frame": result.get("retake_end_frame"),+ }+ write_sidecar(final_out.with_suffix(final_out.suffix + ".json"), sidecar)+ job["output_path"] = str(final_out)+ push(f"Retake done in {sidecar['elapsed_sec']}s → {final_out.name}")+ if p.get("open_when_done"):+ subprocess.run(["open", str(final_out)], check=False)+ return+if mode == "control":# Control (Union) — drive a render's motion / structure / composition# from a control video, via the OFFICIAL un-gated Union-Control IC-LoRA.@@ -31297,6 +35726,12 @@ def run_job_inner(job: dict) -> None:"prompt": p["prompt"],"negative_prompt": p.get("negative_prompt", ""),"output_path": str(out_path),+ # VA-27: live preview on Keyframe's stage-1 loop. Wired the+ # same way as generate_hq (**_live_preview_params); the+ # helper side threads it through _filter_unsupported_kwargs,+ # which drops the kwarg silently if the installed pipeline+ # build doesn't accept it — never fatal, never a stale value.+ **_live_preview_params(job, p),**kf_helper_params,"height": height,"width": width,@@ -31427,12 +35862,42 @@ def run_job_inner(job: dict) -> None:passif ref_image_path and not Path(ref_image_path).exists():ref_image_path = None+ # What the user picked — the sidecar records THIS, the engine gets+ # the fitted copy below (4.17 Codex EST-9).+ ref_image_original = ref_image_path+ if ref_image_path:+ # VA-02: A2V kept the reference at a fixed 1024×576 whatever the+ # picture was, so a 9:16 phone selfie lost the mouth and chin to+ # the vendored encoder's hardcoded centre crop — the input this+ # mode exists for. Pre-fit here the same way I2V does, honouring+ # the crop-preview position the user dragged.+ _fitted = _fit_reference_image_to_canvas(+ Path(ref_image_path), width, height, job["id"], _job_crop_focus(p))+ if str(_fitted) != ref_image_path:+ push(f"A2V: reference cover-cropped to {width}×{height} "+ f"before conditioning (keeps your crop position — the "+ f"engine's own crop would always centre it).")+ # The engine gets the fitted copy; p["image"] (the sidecar,+ # Load Params) keeps the original upload (Codex EST-9).+ ref_image_path = str(_fitted)a2v_loras = list(p.get("loras") or [])if p.get("hdr"):a2v_loras.append({"path": CURATED_LORAS["hdr"]["repo_id"],"strength": float(CURATED_LORAS["hdr"]["default_strength"]),})+ # THE A2V PROMPT LAW, applied to every a2v render, not just the ones+ # the Storyboard/music-video planners compose (VA-05). Those two+ # already run compose_shot_prompt → a2v_prompt() before the job is+ # queued, so this is a no-op for them (a2v_prompt is idempotent: the+ # contract-key check skips re-adding, and a prompt already cleaned of+ # stillness words and under the word cap matches nothing a second+ # time). The manual Audio tab is the one path that used to send its+ # prompt straight to the engine — "he stands perfectly still, static+ # camera" rendered verbatim and came back a freeze frame with a+ # closed mouth. `silent=False`: the manual form has no per-window+ # silence signal, so it always gets the singing contract.+ a2v_safe_prompt = storyboard.a2v_prompt(p["prompt"], silent=False)a2v_params = {"model_dir": model_dir,# Only the Q8 branch builds A2VidPipelineTwoStage and reads these;@@ -31440,7 +35905,7 @@ def run_job_inner(job: dict) -> None:# set unconditionally. Per generation: see hq_weights()."dev_transformer": hq_weights()["dev_transformer"],"distilled_lora": hq_weights()["distilled_lora"],- "prompt": p["prompt"],+ "prompt": a2v_safe_prompt,"negative_prompt": p.get("negative_prompt", ""),"output_path": str(out_path),"audio_path": cond_audio,@@ -31459,11 +35924,53 @@ def run_job_inner(job: dict) -> None:# load_audio(start_time=…); it defaulted to 0.0 here only because# the key was absent (#46)."audio_start_time": max(0.0, float(p.get("audio_start_time", 0.0) or 0.0)),+ # VA-27: live preview on A2V's stage-1 loop — the composition+ # monitor saves the most time on exactly the lane that runs+ # longest (10-25 min) and used to publish nothing until the+ # whole render finished. Best-effort: dropped silently by the+ # helper's _filter_unsupported_kwargs if the installed pipeline+ # build doesn't take the kwarg.+ **_live_preview_params(job, p),}# Both lanes attach the stack. Only Q8 used to receive it, so the# same selection silently vanished when this Mac (or a missing High# add-on) put the render on the Q4 distilled lane (LTX-03).a2v_params["loras"] = a2v_loras+ # Multi-anchor images (fd2356d, mlx_warm_helper._a2v_anchor_images).+ # The product surface is "Continue the song" (frame_idx 0 only — see+ # continue_song_anchor()); a general multi-anchor list stays reachable+ # for the storyboard/agent API. Malformed entries are dropped rather+ # than raising — a stale anchor path from a deleted upload must not+ # turn into a failed render when the plain a2v request underneath it+ # is still valid.+ a2v_anchors: list[dict] = []+ _anchors_raw = p.get("anchors_json") or ""+ if _anchors_raw:+ try:+ _parsed = json.loads(_anchors_raw)+ except (TypeError, ValueError, json.JSONDecodeError):+ _parsed = []+ if isinstance(_parsed, list):+ for _a in _parsed:+ if not isinstance(_a, dict):+ continue+ _path = str(_a.get("path") or "").strip()+ if not _path or not Path(_path).exists():+ continue+ try:+ _idx = int(_a.get("frame_idx", 0))+ except (TypeError, ValueError):+ continue+ if _idx < 0 or _idx >= frames:+ continue+ try:+ _strength = float(_a.get("strength", 1.0))+ except (TypeError, ValueError):+ _strength = 1.0+ a2v_anchors.append({"path": _path, "frame_idx": _idx,+ "strength": max(0.0, min(1.0, _strength))})+ if a2v_anchors:+ a2v_params["anchors"] = a2v_anchorsif uses_q8:a2v_params["cfg_scale"] = float(p.get("cfg_scale", 3.0))a2v_params["stg_scale"] = float(p.get("stg_scale", 1.0))@@ -31515,12 +36022,34 @@ def run_job_inner(job: dict) -> None:except Exception as exc: # noqa: BLE001push(f"[a2v] could not mux the original song back ({exc}) — "f"this clip plays the vocal stem")+ # VA-14: the lip-sync verdict. Scores the FINAL delivered file (the+ # audience's own audio — the original song when a stem was muxed+ # back, the conditioning file otherwise), not the stage-1 conditioning+ # waveform, since that is what a "does this one sync?" check is+ # actually asking. Reuses take_lipsync_score, the same CPU-only+ # mouth-aperture-vs-vocal-envelope scorer One Shot has used per part+ # since 2026-09-07 — nothing here touches the engine or the GPU.+ # Guarded: a scoring failure (corrupt frame, cv2 hiccup) must never+ # turn a finished render into a failed job.+ a2v_lipsync_score = None+ try:+ a2v_lipsync_score = take_lipsync_score(out_path)+ if a2v_lipsync_score is not None:+ push(f"[a2v] lip-sync {a2v_lipsync_score:+.2f}"+ + ("" if a2v_lipsync_score >= TAKE_LIPSYNC_MIN else+ f" — under {TAKE_LIPSYNC_MIN:.2f}, rough check, not a gate"))+ except Exception as exc: # noqa: BLE001+ push(f"[a2v] lip-sync scoring skipped ({exc})")sidecar = {"output": str(out_path), "raw_output": str(out_path),+ "lipsync_score": a2v_lipsync_score,"params": {**p, "command": action, "audio": audio_src,"audio_conditioning": cond_audio,"audio_stem_used": cond_audio != audio_src,- "image": ref_image_path},+ "image": ref_image_original,+ # `prompt` above (from **p) is the caller's literal+ "prompt_used": a2v_safe_prompt,+ "anchors": a2v_anchors},# The number the engine actually ran with. `params` keeps what# the caller sent — blank when the slider was on Auto — so a# re-run resolves against its own lane again; this line is the@@ -31697,6 +36226,14 @@ def run_job_inner(job: dict) -> None:push(f"[windows] {note}")memory_plan = plan_memory_policy(model_frames, mode=mode, quality=quality)+ # SYS-07: preflight refusal for the M1/M2-class Metal-watchdog risk —+ # checked AFTER Long Clip Boost and sliding windows have already had a+ # chance to shrink model_frames, so a clip that's already chunked down+ # to a safe size is never refused for a workload it no longer runs.+ _watchdog_refusal = m1_m2_long_clip_watchdog_refusal(mode, quality, model_frames)+ if _watchdog_refusal:+ raise RenderRefused("hardware_tier", _watchdog_refusal)+# T2V/I2V resolution clamp — only applies on the base tier (< 48 GB).# Standard / high / pro tiers pass full user-requested W×H through.t2v_max = tier_max_dim("t2v" if mode == "t2v" else "i2v")@@ -31708,6 +36245,41 @@ def run_job_inner(job: dict) -> None:)width, height = new_w, new_hp["width"], p["height"] = width, height+ # VC-02/SYS-05: this clamp usually never fires for a quality-chip+ # pick any more — _ltx_qualities() bakes the same clamp into the+ # canvas the chip advertised, so the job already arrived at this+ # size. It still fires for a custom W×H, an external /queue/add+ # caller, or a Load Params replay of an older sidecar — and when it+ # does, the Queue row and Now card should say so instead of only the+ # log (the note used to be pushed to the log and nowhere else).+ note = f"resolution clamped to {width}x{height} ({SYSTEM_CAPS['label']} tier)"+ notes = list(p.get("generation_clamp_notes") or [])+ if note not in notes:+ notes.append(note)+ p["generation_clamp_notes"] = notes++ # Pre-fit the reference image to the canvas that will actually render+ # (VC-29/H3-01/VA-02: faces survive every crop). The vendored i2v+ # encoder does its own cover-crop with no way to tell it where to+ # centre, so the panel does the cover-crop itself, honouring the+ # crop-preview position the user dragged, and hands the pipeline an+ # image that is ALREADY the target canvas — a no-op crop on the+ # engine's side, the same mechanism _h3_fit_first_frame uses for H3.+ #+ # The fitted copy goes to the ENGINE only (4.17 Codex EST-9): p["image"]+ # is what the sidecar records and Load Params reopens, so it stays the+ # user's ORIGINAL upload — overwriting it with the cropped scratch file+ # meant a reloaded recipe could never move the crop to show anything the+ # first crop had cut away.+ _engine_image = p.get("image")+ if mode in ("i2v", "i2v_clean_audio") and (p.get("image") or "").strip():+ _fitted = _fit_reference_image_to_canvas(+ Path(p["image"]), width, height, job["id"], _job_crop_focus(p))+ if str(_fitted) != p["image"]:+ push(f"{mode.upper()}: reference cover-cropped to {width}×{height} "+ f"before conditioning (keeps your crop position — the "+ f"engine's own crop would always centre it).")+ _engine_image = str(_fitted)pad_w, pad_h, pad_filter = compute_pad(width, height)# The clean-audio mux pads 1280x704 to 1280x720 with 8 px of black. When@@ -31899,7 +36471,7 @@ def run_job_inner(job: dict) -> None:"width": width,"frames": frames,"seed": p["seed"],- "image": p["image"] if mode != "t2v" else None,+ "image": _engine_image if mode != "t2v" else None,"loras": hq_loras,# Inspire on the HQ lane — this is the lane where the owner# first hit the loose-reference behavior (High / High·720p),@@ -32031,7 +36603,7 @@ def run_job_inner(job: dict) -> None:"frame_rate": model_fps,"steps": p["steps"],"seed": p["seed"],- "image": p["image"] if mode != "t2v" else None,+ "image": _engine_image if mode != "t2v" else None,"loras": loras,"accel": p.get("accel", "off"),# The 2.5 distilled schedule preset, already lane-gated by@@ -32432,6 +37004,35 @@ def _external_build_hold() -> str:return str(rec.get("what") or "an engine build")+def _queue_extend_face_fix_after(job: dict) -> None:+ """VA-13's follow-up for a finished Extend (worker_loop calls it). Any+ reason it can't queue lands on the job as `warning` (4.17 Codex EST-10)."""+ _ep = job.get("params") or {}+ if (_ep.get("mode") == "extend" and _ep.get("extend_face_fix_after")+ and job.get("output_path")):+ # A follow-up that could not queue is recorded ON THE JOB+ # (4.17 Codex EST-10): the history row shows `warning`, so the+ # user learns it without reading the log — and the clip's own+ # Upscale & Face Fix button is the way to retry it.+ _ff_err = ""+ try:+ _ff = queue_face_fix(job["output_path"])+ if _ff.get("ok"):+ push(f"Extend: queued {FACE_FIX_NAME} on "+ f"{Path(job['output_path']).name} (Also run "+ f"Upscale & Face Fix after was checked).")+ else:+ _ff_err = str(_ff.get("error") or "unknown reason")+ except Exception as _ff_exc: # noqa: BLE001+ _ff_err = str(_ff_exc)+ if _ff_err:+ push(f"Extend: couldn't queue {FACE_FIX_NAME} — {_ff_err}")+ _ff_warn = (f"{FACE_FIX_NAME} was not queued: {_ff_err} "+ f"Use the clip's {FACE_FIX_NAME} button to try again.")+ job["warning"] = " ".join(+ x for x in (job.get("warning"), _ff_warn) if x)++def worker_loop() -> None:held_note = ""while True:@@ -32480,6 +37081,17 @@ def worker_loop() -> None:_JOB_CTX.job = Nonejob["status"] = "done"_CONSEC_FAIL.update(sig="", n=0)+ STATE["paused_reason"] = None+ # VA-13: "Also run Upscale & Face Fix after" — an Extend that had+ # to clamp to this Mac's tier cap (768/1024 px) comes back softer+ # than the source it extended, and the fix for that (Upscale &+ # Face Fix) is a one-click action the user would otherwise have+ # to remember and do by hand once the wait is over. Mirrors the+ # H3 "upscale after" checkbox's shape, one queue hop later+ # because Extend and Face Fix are different pipelines (H3's+ # ltx_x2 folds into the SAME job's post-processing; Extend's+ # dev-transformer pass can't).+ _queue_extend_face_fix_after(job)except JobStopped as stop:# EXIT 75 IS A CANCEL, NOT A FAILURE. The user looked at the live# preview, saw the wrong shot and stopped it. Nothing was saved —@@ -32519,6 +37131,14 @@ def worker_loop() -> None:_CONSEC_FAIL.update(sig=_sig, n=1)if _CONSEC_FAIL["n"] >= 3 and STATE["queue"] and not STATE["paused"]:STATE["paused"] = True+ # SYS-32: this used to live ONLY in the push() log line+ # below (Logs tab only) -- the UI showed just "queue N ·+ # paused" and a Resume button, with no way to see WHY+ # short of opening Logs. Carried into /status so the+ # panel can put it in a persistent notice above Generate.+ STATE["paused_reason"] = (+ f"The last {_CONSEC_FAIL['n']} renders failed the same way: {_sig}"+ )_analytics_capture("queue_paused_breaker", {"n_failed": int(_CONSEC_FAIL["n"]),"queued": len(STATE["queue"]),@@ -32545,6 +37165,9 @@ def worker_loop() -> None:# analytics section's contract; it must never be able to turn# a finished render into a failed one._analytics_render_event(job)+ # Per-install self-calibration (VC-01 / H3-03) — local only,+ # independent of analytics being on. Same never-raise contract.+ _record_eta_calibration_from_job(job)with LOCK:STATE["history"].insert(0, job)STATE["history"] = STATE["history"][:HISTORY_LIMIT]@@ -33424,6 +38047,36 @@ def _save_agent_image_config(updates: dict) -> agent_image_engine.ImageEngineConreturn cfg+def _unicode_slug(text: str, *, max_chars: int = 50, fallback: str = "") -> str:+ """A filename-safe slug that KEEPS non-Latin letters and digits.++ SYS-26 / cross-package (VC-13's _descriptive_filename, FILM-45's+ _sb_slug): every slugger in the app used to be `[^a-z0-9]+ -> "_"` or+ similar — ASCII-only. A Japanese or Chinese prompt has ZERO ASCII+ letters, so it fell straight through to a bare fallback ("t2v"),+ Finder filled up with t2v.mp4 / t2v_2.mp4 / t2v_3.mp4 ..., and an+ uploaded テスト画像_猫.jpg became ____.jpg. This is the one shared+ slugger: NFC-normalize first (so combining-mark variants of the same+ character collapse together), keep any Unicode letter or digit+ (`str.isalnum()`, any script), collapse every run of anything else to+ one underscore. `max_chars` counts CHARACTERS, not bytes — a caller+ writing to a filesystem with a byte-length limit caps separately."""+ s = unicodedata.normalize("NFC", str(text or ""))+ out: list[str] = []+ prev_us = False+ for ch in s:+ if ch.isalnum():+ out.append(ch)+ prev_us = False+ elif not prev_us:+ out.append("_")+ prev_us = True+ slug = "".join(out).strip("_")+ if not slug:+ slug = fallback+ return slug[:max_chars].rstrip("_") or fallback++def _descriptive_filename(label: str, prompt: str, *, fallback: str) -> str:"""Build a descriptive output stem from the user-set label or prompt.@@ -33435,20 +38088,22 @@ def _descriptive_filename(label: str, prompt: str, *, fallback: str) -> str:filename too.Order of preference: label → first 6 words of prompt → fallback.- Sanitized to lowercase ASCII alnum + underscore, capped at 50 chars.- Caller appends a uniqueness suffix and the extension.+ Sanitized via _unicode_slug (keeps non-Latin scripts; SYS-26/VC-13 —+ a Japanese or Chinese prompt used to extract zero words here and fall+ straight to "t2v", filling Finder with t2v.mp4, t2v_2.mp4, ...),+ capped at 50 characters. Caller appends a uniqueness suffix and the+ extension."""src = (label or "").strip()if not src and prompt:- # Take the first ~6 words of the prompt; strip dialogue ('...').- words = re.findall(r"[A-Za-z0-9]+", prompt)[:6]+ # First ~6 whitespace-separated words. Unicode-aware: `\w` (with+ # Python 3's default Unicode mode) matches CJK ideographs and+ # every other script's letters, not just A-Za-z0-9.+ words = re.findall(r"\w+", prompt, re.UNICODE)[:6]src = " ".join(words) if words else ""if not src:src = fallback- safe = re.sub(r"[^a-z0-9]+", "_", src.lower()).strip("_")- if not safe:- safe = fallback- return safe[:50].rstrip("_")+ return _unicode_slug(src, max_chars=50, fallback=fallback)def _unique_output_path(base: Path, stem: str, ext: str = ".mp4") -> Path:@@ -33744,6 +38399,30 @@ class Handler(BaseHTTPRequestHandler):self._json({"ok": True, "id": bid, "prepare": _sbe_job_state(bid)})return True+ if path == "/storyboard/edit/render/status":+ # FILM-28: what the Editor's Render button polls once it has+ # started a job via `edit/render/start`. `result` and `error`+ # only ever carry a value once `state` has left "running" — a+ # client polling early gets a clean "still going", never a+ # half-filled result to guess about.+ job_id = (q.get("job") or [""])[0].strip()+ with _SB_FILM_JOB_LOCK:+ job = _SB_FILM_JOBS.get(job_id)+ if job is None:+ self._json({"ok": False, "error": "unknown job"}, 404)+ return True+ state = job.get("state")+ payload = {"ok": True, "state": state,+ "elapsed_sec": round(+ (job.get("finished_at") or time.time())+ - job.get("started_at", 0), 1)}+ if state == "done":+ payload["result"] = job.get("result")+ elif state == "error":+ payload["error"] = job.get("error")+ self._json(payload)+ return True+if path == "/storyboard/edit/proxy":name = (q.get("name") or [""])[0].strip()# The name is a BASENAME the server itself minted, so anything@@ -33770,6 +38449,54 @@ class Handler(BaseHTTPRequestHandler):self._serve_video_with_range(target)return True+ if path == "/storyboard/edit/poster":+ # FILM-39: the video half of /image?w= — a cached first-frame+ # JPEG, same containment as /storyboard/edit/proxy above (which+ # this route deliberately mirrors line for line): a basename the+ # server itself minted, resolved under the SAME proxy_dir, never+ # an arbitrary clip path. A clip with no proxy has no poster —+ # the client only ever asks for one when `c.proxy` is set.+ name = (q.get("name") or [""])[0].strip()+ if not bid or not re.fullmatch(r"[A-Za-z0-9._-]{1,120}\.mp4", name):+ self.send_error(400)+ return True+ try:+ w_raw = (q.get("w") or [""])[0] or ""+ req_w = int(w_raw) if w_raw else 240+ except (TypeError, ValueError):+ req_w = 240+ try:+ sedit = _sbe_import()+ except Exception: # noqa: BLE001+ self.send_error(503)+ return True+ root = sedit.proxy_dir(_sbe_board_dir(bid)).resolve()+ try:+ target = (root / name).resolve()+ except OSError:+ self.send_error(400)+ return True+ if not target.is_relative_to(root) or not target.is_file():+ self.send_error(404)+ return True+ try:+ poster = _ensure_proxy_poster(target, req_w)+ except Exception as exc: # noqa: BLE001+ # A truncated or foreign-codec proxy is not worth a 500 over+ # — the timeline just goes without a poster for that clip,+ # the same as a clip with no proxy at all.+ push(f"poster extract failed for {target.name}: {exc}")+ self.send_error(404)+ return True+ self.send_response(200)+ self.send_header("Content-Type", "image/jpeg")+ self.send_header("Content-Length", str(poster.stat().st_size))+ self.send_header("Cache-Control", "public, max-age=31536000, immutable")+ self.end_headers()+ with poster.open("rb") as fh:+ self.wfile.write(fh.read())+ return True+try:sedit = _sbe_import()except Exception as exc: # noqa: BLE001@@ -34088,6 +38815,17 @@ class Handler(BaseHTTPRequestHandler):# on a still that takes seconds, not a clip that takes minutes.if "anchor_stills" in form:board["anchor_stills"] = str(f("anchor_stills", "")).strip().lower() in ("1", "on", "true", "yes")+ # FILM-46: STILLS FIRST — the anchor still decides the+ # composition; without an approve step the render thread went+ # straight from still to (expensive) video, so you only saw+ # the still after the minutes were already spent. On, the+ # render thread holds a shot back once its still lands until+ # the user approves it (or asks for a new one). Implies+ # anchor_stills — a still to approve has to exist first.+ if "stills_first" in form:+ board["stills_first"] = str(f("stills_first", "")).strip().lower() in ("1", "on", "true", "yes")+ if board["stills_first"]:+ board["anchor_stills"] = True# LONG WINDOWS: a shot longer than one LTX window renders as a# chain of windows on the Q8 dev transformer instead of being# cut to fit (see ltx_windows.py).@@ -34102,6 +38840,11 @@ class Handler(BaseHTTPRequestHandler):# (Confirmed by the 2026-08-17 UX review, red-team verified.)if "locations" in form:board["locations"] = _sb_parse_locations(f("locations", ""))+ # FILM-14 (item 4): same patch-never-overwrite shape as+ # locations, one line above — a re-plan that never mentions+ # `light` must not erase a light note the user already set.+ if "light" in form:+ board["light"] = f("light", "")board["shots_target"] = shots_n# One wardrobe line for the whole film, attached to the cast# member rather than repeated per shot — the same fix locations@@ -34209,11 +38952,33 @@ class Handler(BaseHTTPRequestHandler):if not isinstance(incoming, dict):self._json({"ok": False, "error": "no board"}, 400)return+ # FILM-19: `sbFlushSave` posts `{id: SB.id, board:+ # SB.payload.board}` — two reads of client state that are+ # supposed to name the same board but are not atomic. A+ # switch-boards race (2 s poll landing after a row click, a+ # stale sbLoad reply) can leave SB.payload holding board A's+ # shots while SB.id has already moved to board B; without+ # this check that save would write board A's shots into+ # board B's file. `incoming["id"]` only exists once a board+ # has round-tripped through a GET, so an absent or blank one+ # (a brand-new board's first save) is not a mismatch.+ incoming_id = str(incoming.get("id") or "").strip()+ if incoming_id and incoming_id != bid:+ self._json({"ok": False,+ "error": f"this save is for board {incoming_id!r} "+ f"but the request named {bid!r} — refused "+ f"rather than write one film's shots into "+ f"another's file."}, 400)+ returnboard = load(bid)# Only the fields the plan screen can edit. Everything else on# disk (job ids, outputs, planner metadata) is the server's and# a stale tab must not be able to roll it back.- for k in ("title", "concept", "style", "must", "shots_target", "policy"):+ # "light" (FILM-14 item 4) rides here too, not only on the+ # plan form: the whole point is a light note the user can+ # change on an already-planned board without re-planning it.+ for k in ("title", "concept", "style", "must", "shots_target",+ "policy", "light"):if k in incoming:board[k] = incoming[k]if isinstance(incoming.get("shots"), list):@@ -34229,16 +38994,31 @@ class Handler(BaseHTTPRequestHandler):"final_output", "error",# the anchor still is server-owned too"still", "still_job_id", "still_error"}- by_n = {s.get("n"): s for s in (board.get("shots") or [])- if isinstance(s, dict)}+ # FILM-10: this used to merge by `n` (position), which+ # is renumbered on every reorder/insert/delete — an up+ # arrow or a delete next to a rendered shot would graft+ # that shot's draft_output/final_output/still onto a+ # completely different, unrendered shot at the same new+ # position. `uid` is a stable per-shot identity that+ # never changes, so it is the only safe merge key.+ by_uid = {s.get("uid"): s for s in (board.get("shots") or [])+ if isinstance(s, dict) and s.get("uid")}merged = []for s in incoming["shots"]:if not isinstance(s, dict):continue- old = by_n.get(s.get("n")) or {}- for k in keep:- if k in old and k not in s:- s[k] = old[k]+ uid = s.get("uid")+ old = by_uid.get(uid) if uid else None+ if old is None:+ # No uid (a shot just created client-side) or no+ # match on disk (a genuinely new shot) — never+ # fall back to matching by `n`, that is exactly+ # the bug above. Give it a fresh identity.+ s["uid"] = uid or storyboard.new_shot_uid()+ else:+ for k in keep:+ if k in old and k not in s:+ s[k] = old[k]merged.append(s)board["shots"] = merged_sb_normalize(board)@@ -34256,6 +39036,19 @@ class Handler(BaseHTTPRequestHandler):if grade not in (None, "keep", "reroll", "cut"):self._json({"ok": False, "error": "bad grade"}, 400)return+ # BOARD-2: the client names the shot's uid too. A shot number+ # that now belongs to a DIFFERENT shot (a stale screen, a+ # reply from another board) is refused rather than graded.+ want_uid = f("uid", "")+ if want_uid:+ target = next((s for s in (board.get("shots") or [])+ if isinstance(s, dict) and s.get("n") == n), None)+ if target is None or (target.get("uid") and target.get("uid") != want_uid):+ self._json({"ok": False,+ "error": "That shot changed since this screen "+ "was drawn — nothing was graded. "+ "Look again and retry."}, 409)+ returnfor s in (board.get("shots") or []):if isinstance(s, dict) and s.get("n") == n:s["grade"] = grade@@ -34276,6 +39069,28 @@ class Handler(BaseHTTPRequestHandler):self._json(_sb_payload(board))return+ if action == "keep-all-ungraded":+ # FILM-47: Finish needed KEEP pressed on every single shot —+ # 52 presses for a 52-shot board. This is the bulk version,+ # ONE save rather than one request per shot (grading N shots+ # as N separate load-mutate-save round trips would race each+ # other — see FILM-19/20 — this does it as one).+ bid = f("id", "")+ board = load(bid)+ count = 0+ for s in (board.get("shots") or []):+ if not isinstance(s, dict):+ continue+ if (s.get("draft_output") or s.get("final_output")) \+ and s.get("status") != "skipped" and not s.get("grade"):+ s["grade"] = "keep"+ count += 1+ if count:+ board["updated_at"] = int(time.time())+ storyboard.save_storyboard(STATE_DIR, board)+ self._json({**_sb_payload(board), "kept": count})+ return+if action == "estimate":board = load(f("id", ""))pass_name = f("pass", "draft")@@ -34295,6 +39110,65 @@ class Handler(BaseHTTPRequestHandler):return# ---- render --------------------------------------------------+ if action == "new-take":+ # FILM-22: "Edit & re-render" / "New take (new seed)" on a+ # done card — unlock it and reseed, no planner call. The+ # user's next Render picks it up like any other pending+ # shot; this route does not queue one itself.+ bid = f("id", "")+ board = load(bid)+ try:+ n = int(f("n", "0") or 0)+ except ValueError:+ n = 0+ if _sb_new_take(board, n) is None:+ self._json({"ok": False, "error": f"there is no shot {n}"}, 404)+ return+ storyboard.save_storyboard(STATE_DIR, board)+ self._json(_sb_payload(board))+ return++ if action == "approve-still":+ # FILM-46: "Stills first" — one composition approved, so the+ # render thread's next pass is free to spend the (expensive)+ # video minutes on this shot. No render is queued here; the+ # user's own Render/Retry does that, same as any other+ # pending shot.+ bid = f("id", "")+ board = load(bid)+ try:+ n = int(f("n", "0") or 0)+ except ValueError:+ n = 0+ shot = next((s for s in (board.get("shots") or [])+ if isinstance(s, dict) and s.get("n") == n), None)+ if shot is None:+ self._json({"ok": False, "error": f"there is no shot {n}"}, 404)+ return+ if not shot.get("still") and not shot.get("still_error"):+ self._json({"ok": False, "error": f"shot {n} has no still yet"}, 400)+ return+ # BOARD-9: approving a shot whose still FAILED is the user's+ # explicit choice to render it without one (Stills first+ # holds it until then).+ shot["still_approved"] = True+ storyboard.save_storyboard(STATE_DIR, board)+ self._json(_sb_payload(board))+ return++ if action == "approve-all-stills":+ bid = f("id", "")+ board = load(bid)+ count = 0+ for shot in (board.get("shots") or []):+ if (isinstance(shot, dict) and shot.get("still")+ and not shot.get("still_approved")):+ shot["still_approved"] = True+ count += 1+ storyboard.save_storyboard(STATE_DIR, board)+ self._json({**_sb_payload(board), "approved": count})+ return+if action == "restill":# NEW STILL for one shot: forget its still and the clip made# from it, then take the ordinary render path for that shot@@ -34362,7 +39236,11 @@ class Handler(BaseHTTPRequestHandler):for s in (board.get("shots") or []):if isinstance(s, dict) and (not only or s.get("n") in only):s.pop("final_job_id", None)- storyboard.save_storyboard(STATE_DIR, board)+ # FILM-17: written BEFORE the thread starts, so a restart+ # between here and the thread's own first save still has+ # something for _sb_boot_reconcile to resume from.+ _sb_set_render_intent(board, pass_name, only, auto=bool(board.get("auto")))+ storyboard.save_storyboard(STATE_DIR, board)th = threading.Thread(target=_sb_render_thread, daemon=True,name=f"phos-sb-render-{bid}",args=(bid, pass_name, only or None))@@ -34443,12 +39321,22 @@ class Handler(BaseHTTPRequestHandler):if err:self._json({"ok": False, "busy": True, "error": err}, 409)return- notes = []+ # FILM-01: this used to join every shot's note into ONE string+ # ("shot 3: ...\nshot 7: ...") and hand it to a single+ # shot-mode planner call. `_parse_feedback`'s regex matches+ # only the FIRST "shot N:" header and (with re.DOTALL) folds+ # every note after it into that one shot's note — shot 3 got+ # a real rewrite and every other named shot was never touched+ # by the planner at all, so it re-rendered on its old prompt+ # and old seed: the same clip again. `shot_notes` keeps each+ # note addressed to its own shot; `_sb_plan_thread` runs one+ # shot-mode rewrite per n, in one planner session.+ shot_notes = {}for s in (board.get("shots") or []):if isinstance(s, dict) and s.get("n") in ns:- notes.append("shot %d: %s" % (s["n"], (s.get("note") or "").strip()- or "the director rejected this shot — "- "write a different one"))+ shot_notes[s["n"]] = ((s.get("note") or "").strip()+ or "the director rejected this shot — "+ "write a different one")previous = {k: board.get(k) for k in("schema", "id", "title", "cast", "policy", "shots")}chars = [c for c in (list_characters() or [])@@ -34461,7 +39349,7 @@ class Handler(BaseHTTPRequestHandler):"characters": chars,"must": board.get("must") or [],"locations": board.get("locations") or [],- "feedback": "\n".join(notes),+ "shot_notes": shot_notes,"engine_mode": board.get("engine_mode") or "auto","reroll_ns": ns},previous))@@ -34623,6 +39511,34 @@ class Handler(BaseHTTPRequestHandler):self._json({"ok": True})return+ if action == "duplicate":+ # FILM-43: the board list had no way to branch off a plan —+ # only rename (via the ordinary save route) and delete. A+ # full copy: same shots, same cast, same rendered clips+ # (the files are untouched; a re-render on either board+ # writes a NEW file under its own job id), fresh id and+ # shot uids so a save on one board can never merge onto the+ # other's shots (FILM-10's uid contract).+ bid = f("id", "")+ board = load(bid)+ import copy as _copy+ new_board = _copy.deepcopy(board)+ title = (board.get("title") or "Untitled film").strip()+ new_board["title"] = f"{title} (copy)" if title else "Untitled film (copy)"+ new_board["id"] = _sb_new_id(new_board["title"])+ new_board["created_at"] = int(time.time())+ new_board["updated_at"] = int(time.time())+ for s in (new_board.get("shots") or []):+ if isinstance(s, dict):+ s["uid"] = storyboard.new_shot_uid()+ # Server-only bookkeeping the copy must start clean.+ new_board.pop("render_intent", None)+ new_board.pop("planner", None)+ new_board.pop("auto_film", None)+ storyboard.save_storyboard(STATE_DIR, new_board)+ self._json({"ok": True, "id": new_board["id"], "title": new_board["title"]})+ return+if action == "delete":bid = f("id", "")with _SB_LOCK:@@ -34859,6 +39775,136 @@ class Handler(BaseHTTPRequestHandler):"proxy": proxied})return+ if sub == "match-colour":+ # FILM-14: "Match colour across the film". One mid-frame+ # sample per clip, the same maths `color_seam_fade`+ # (scripts/join_smooth.py) matches seams with — proposals+ # only, same shape as auto-align: the client applies what+ # it likes, scaled by its own strength slider, as one+ # undo step.+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ edit, problem = _sbe_edit_for_analysis(sedit, bdir, f("edit", ""))+ if problem:+ self._json({"ok": False, "error": problem[0]}, problem[1])+ return+ if not edit:+ self._json({"ok": False, "error": "no timeline to match"}, 404)+ return+ ref_id = f("ref", "")+ samples: dict[str, tuple] = {}+ for c in (edit.get("clips") or []):+ if not isinstance(c, dict) or sedit.clip_kind(c) != "video" or not c.get("path"):+ continue+ mid = (float(c.get("start") or 0.0) + float(c.get("end") or 0.0)) / 2.0+ got = take_frame_rgb(c["path"], mid)+ if got:+ samples[str(c.get("id"))] = got+ if len(samples) < 2:+ self._json({"ok": False,+ "error": "not enough readable clips to match colour"}, 400)+ return+ if ref_id and ref_id in samples:+ ref = samples[ref_id]+ else:+ # The film's own median, per channel — robust to one+ # outlier shot (a solid-black slug's neighbour, a+ # blown-out insert) pulling a straight mean off-centre.+ rs = sorted(v[0] for v in samples.values())+ gs = sorted(v[1] for v in samples.values())+ bs = sorted(v[2] for v in samples.values())+ mid_i = len(samples) // 2+ ref = (rs[mid_i], gs[mid_i], bs[mid_i])+ proposals = []+ for cid, rgb in samples.items():+ if cid == ref_id:+ continue+ got = _sb_match_colour_grade(rgb, ref)+ if (abs(got["exposure"]) < 0.01 and abs(got["temp"]) < 0.01+ and abs(got["tint"]) < 0.01):+ continue+ proposals.append(dict(got, id=cid))+ self._json({"ok": True, "reference": {"r": ref[0], "g": ref[1], "b": ref[2]},+ "proposals": proposals})+ return++ if sub == "auto-align":+ # FILM-05: "Auto-align lip-sync". CPU only, no render — the+ # scorer's best-lag search (`take_lipsync_best_lag_vs_song`)+ # against the song already on this edit, for every a2v+ # clip on the timeline. Proposals only: the arrangement is+ # the human's, so nothing here writes anything — the+ # client applies what it likes as one undo step, same as+ # every other verb in this file's own docstring rule.+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ edit, problem = _sbe_edit_for_analysis(sedit, bdir, f("edit", ""))+ if problem:+ self._json({"ok": False, "error": problem[0]}, problem[1])+ return+ if not edit:+ self._json({"ok": False, "error": "no timeline to align"}, 404)+ return+ aud = edit.get("audio") or {}+ song = str(aud.get("path") or "")+ if not song or not Path(song).is_file():+ self._json({"ok": False,+ "error": "this film has no song loaded to align against"}, 400)+ return+ by_path: dict[str, dict] = {}+ for s in (board.get("shots") or []):+ if not isinstance(s, dict):+ continue+ for key in ("final_output", "draft_output"):+ v = s.get(key)+ if v:+ by_path.setdefault(str(v), s)+ # WHERE THE SONG SITS: track second = film second ++ # offset, audible only inside the trimmed window — the+ # same numbers the render plays (music_window).+ win = sedit.music_window(aud)+ proposals = []+ skipped = []+ checked = 0+ for c in (edit.get("clips") or []):+ if not isinstance(c, dict) or sedit.clip_kind(c) != "video":+ continue+ shot = by_path.get(str(c.get("path") or ""))+ if not shot or str(shot.get("mode") or "").lower() != "a2v":+ continue+ title = (shot.get("title") or shot.get("prompt") or "")[:80]+ # EDITOR-9: the clip's own source window and speed —+ # never the whole take from frame 0.+ got = take_lipsync_best_lag_vs_song(+ c["path"], song, float(c.get("film_start") or 0.0),+ float(c.get("film_end") or 0.0),+ src_start=float(c.get("start") or 0.0),+ speed=sedit.clip_speed(c),+ song_offset=float(aud.get("offset") or 0.0),+ play_start=float(win.get("start") or 0.0),+ play_end=win.get("end"))+ if not got:+ # NOT MEASURED is not "in sync": no face held, or+ # too little voice/motion to correlate.+ skipped.append({"id": c.get("id"), "n": shot.get("n"),+ "title": title})+ continue+ checked += 1+ if not got.get("lag_frames"):+ continue+ # EDITOR-8: the SOURCE slip that corrects the lag —+ # the opposite sign of the lag, at the clip's speed.+ proposals.append({"id": c.get("id"), "n": shot.get("n"),+ "title": title,+ "lag_frames": got["lag_frames"],+ "delta_sec": got["delta_sec"],+ "score": got["score"]})+ self._json({"ok": True, "proposals": proposals,+ "skipped": skipped, "checked": checked})+ return+if sub == "relink":# Draft → delivery, on the user's word. Server-side because# it is one write: load, rewrite the paths the GET already@@ -34899,6 +39945,28 @@ class Handler(BaseHTTPRequestHandler):if not swaps:self._json(_sbe_payload(board, edit))return+ # FILM-15: RE-PROBE ON RELINK. `c["duration"]` is the+ # OLD take's length — a draft and its delivered swap are+ # not guaranteed to run the same seconds (a re-render, a+ # different pass, a retake), and until now nothing here+ # asked the new file how long it actually is. A trim+ # window built against the stale number could point past+ # the end of the file it now names; the assembler pads+ # that silently with black (see `_sb_timeline_segments`),+ # which is safe but still a number in the Inspector that+ # was quietly wrong from the moment this route answered.+ probed_durations: dict[str, float | None] = {}++ def _relink_duration(path: str) -> float | None:+ if path not in probed_durations:+ try:+ import storyboard_edit as _se # noqa: PLC0415+ probed_durations[path] = (+ _se.probe_media(path) or {}).get("duration")+ except Exception: # noqa: BLE001+ probed_durations[path] = None+ return probed_durations[path]+for c in (edit.get("clips") or []):if not isinstance(c, dict):continue@@ -34910,6 +39978,24 @@ class Handler(BaseHTTPRequestHandler):# stops the player showing yesterday's file under# today's path until the rebuild lands.c["proxy"] = None+ dur = _relink_duration(to)+ # NEVER TURN A WORKING RELINK INTO A REFUSED ONE.+ # `clip_past_the_end` is a BLOCKING validator —+ # `save_edit` below refuses the whole write if the+ # window now reads past this number. Relink has+ # always succeeded unconditionally (the cuts stay+ # exactly what the human left, only the file+ # changes — see the sibling test on this class),+ # and a delivered pass coming back SHORTER than+ # its draft must not be the one case that leaves+ # the timeline stuck relinking to nothing. Apply+ # the honest number only when it cannot trip that+ # check; the assembler pads the gap with black+ # regardless (`_sb_timeline_segments`), so the+ # unclamped case stays exactly as safe as this one.+ if (dur is not None and dur > 0+ and float(c.get("end") or 0.0) <= dur + 1e-3):+ c["duration"] = round(float(dur), 6)try:sedit.save_edit(bdir, edit)edit = sedit.load_edit(bdir)@@ -35300,11 +40386,26 @@ class Handler(BaseHTTPRequestHandler):"GET /storyboard/edit first"}, 404)returndeliver = {"format": f("format", ""), "size": f("size", ""),- "finish": f("finish", "")}- name = f("out", "") or _sb_film_name(- board, deliver=_sb_deliver(deliver["format"], deliver["size"],- deliver["finish"]))+ "finish": f("finish", ""),+ "loudnorm": f("loudnorm", "") == "on"}+ # FILM-28: VERSIONED, so three renders at the same+ # delivery do not silently overwrite one another. Only+ # when the client did not ask for a specific filename —+ # `out=` (used to re-render a NAMED delivery in place) is+ # still honoured exactly as given.+ explicit_out = f("out", "")+ reserved = None+ if explicit_out:+ name = explicit_out+ else:+ film_dir = _sb_film_dir_for_write(board)+ name = _sb_film_name_reserve(+ board, _sb_deliver(deliver["format"], deliver["size"],+ deliver["finish"], deliver["loudnorm"]),+ film_dir)+ reserved = str(film_dir / name)if not re.fullmatch(r"[A-Za-z0-9._-]{1,120}\.(mp4|mov)", name):+ _sb_film_name_release(reserved)self._json({"ok": False,"error": "out must be a plain .mp4 or .mov ""filename"}, 400)@@ -35312,15 +40413,108 @@ class Handler(BaseHTTPRequestHandler):# The SAME assembler the export uses, given one plan entry# per timeline clip — repeats included, which is why# `_sb_cut_index` keeps a list per path.- film = _sbe_render_edit(- board, edit, music=f("music", "") or None,- music_mode=f("music_mode", "") or None,- out_name=name, deliver=deliver)+ try:+ film = _sbe_render_edit(+ board, edit, music=f("music", "") or None,+ music_mode=f("music_mode", "") or None,+ out_name=name, deliver=deliver)+ finally:+ _sb_film_name_release(reserved)self._json(film if film.get("ok") else (film | {"ok": False}),200 if film.get("ok")else int(film.get("status") or 500))return+ if sub == "render/start":+ # FILM-28: THE SAME RENDER, AS A JOB. A deliberate second+ # door beside "render" above rather than a change to it —+ # "render" stays exactly as it always was (a curl, a+ # script, an agent calling it still gets the finished+ # film back in one response), and the Editor's own+ # Render button is the one caller that moved to this+ # door, for progress and Cancel. Validation is identical+ # to "render" — a job never starts on a name the sync+ # path would have refused.+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ try:+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 500)+ return+ if not edit:+ self._json({"ok": False,+ "error": "no edit to render — "+ "GET /storyboard/edit first"}, 404)+ return+ deliver = {"format": f("format", ""), "size": f("size", ""),+ "finish": f("finish", ""),+ "loudnorm": f("loudnorm", "") == "on"}+ explicit_out = f("out", "")+ reserved = None+ if explicit_out:+ name = explicit_out+ else:+ film_dir = _sb_film_dir_for_write(board)+ name = _sb_film_name_reserve(+ board, _sb_deliver(deliver["format"], deliver["size"],+ deliver["finish"], deliver["loudnorm"]),+ film_dir)+ reserved = str(film_dir / name)+ if not re.fullmatch(r"[A-Za-z0-9._-]{1,120}\.(mp4|mov)", name):+ _sb_film_name_release(reserved)+ self._json({"ok": False,+ "error": "out must be a plain .mp4 or .mov "+ "filename"}, 400)+ return+ import uuid as _uuid # noqa: PLC0415+ job_id = _uuid.uuid4().hex[:12]+ music = f("music", "") or None+ music_mode = f("music_mode", "") or None+ _sb_film_job_sweep()+ with _SB_FILM_JOB_LOCK:+ _SB_FILM_JOBS[job_id] = {"board_id": bid, "state": "running",+ "started_at": time.time(),+ "cancel": False, "result": None,+ "error": None}+ th = threading.Thread(+ target=_sb_film_job_run,+ args=(job_id, board, edit),+ kwargs={"music": music, "music_mode": music_mode,+ "out_name": name, "deliver": deliver,+ "reserved": reserved},+ daemon=True)+ th.start()+ self._json({"ok": True, "job": job_id})+ return++ if sub == "render/cancel":+ job_id = f("job", "")+ with _SB_FILM_JOB_LOCK:+ job = _SB_FILM_JOBS.get(job_id)+ if job is None:+ self._json({"ok": False, "error": "unknown job"}, 404)+ return+ already_done = job.get("state") != "running"+ job["cancel"] = True+ state = job.get("state")+ # Cancel STOPS the encode, not just its result: every+ # ffmpeg this job has running is its own process+ # group, recorded on the job (_sb_film_job_ffmpeg).+ pgids = list(job.get("pgids") or [])+ for _pg in pgids:+ try:+ os.killpg(_pg, signal.SIGTERM)+ except (ProcessLookupError, PermissionError, OSError):+ pass+ # A cancel that lands after the job already finished is+ # simply too late — the result it already filed stands,+ # the same race every async "cancel" already lives with.+ self._json({"ok": True, "state": state,+ "already_done": already_done})+ return+if sub == "export-nle":# THE FILM, AS A PROJECT SOMEBODY ELSE'S EDITOR CAN OPEN.# A folder next to the film: one FCP7 XML (the single@@ -35353,11 +40547,34 @@ class Handler(BaseHTTPRequestHandler):return _sb_probe_clip(p) or _sb_probe_still(p)try:+ # FILM-50: export_nle() has taken `overlays=` since it+ # was written (storyboard_editor.py) — this call just+ # never passed them, so every title and card the+ # Editor shows disappeared the moment a film left for+ # Premiere, Resolve or After Effects. EDITOR_EFFECTS_+ # MODEL.md's rule is that every effect reaches all+ # three outputs; this was the one call that broke it.+ # `transitions=` closes the same gap for a dissolve+ # or fade-through-black: FCP7 gets a real+ # transitionitem, After Effects an equivalent+ # opacity ramp (it has no importable transition+ # object) — both resolved from the SAME+ # `resolve_transitions` the render itself uses, so+ # an unrenderable boundary is silently absent rather+ # than exported as something the render would+ # refuse.res = sedit.export_nle(edit.get("clips") or [], dest,name=Path(_sb_film_name(board)).stem,fps=FPS, audio=audio, probe=_probe,- audio_tracks=edit.get("audio_tracks") or None)+ overlays=edit.get("overlays") or None,+ audio_tracks=edit.get("audio_tracks") or None,+ transitions=edit.get("transitions") or None,+ markers=sedit.markers_of(edit),+ # EDITOR-14: the whole-film look the render+ # folds into every clip's grade.+ film_look=(edit.get("settings") or {}).get("film_look")+ or None)except sedit.EditError as exc:self._json({"ok": False, "error": str(exc)}, 400)return@@ -35444,31 +40661,62 @@ class Handler(BaseHTTPRequestHandler):retake_of = f("retake_of", "")source = Noneif retake_of:- try:- _edit = sedit.load_edit(_sbe_board_dir(bid)) or {}- except sedit.EditError:- _edit = {}- _clip = next((c for c in (_edit.get("clips") or [])- if isinstance(c, dict)- and str(c.get("id")) == retake_of), None)- if not _clip:- self._json({"ok": False,- "error": "that clip is not on this "- "timeline any more"}, 400)- return- _p = str(_clip.get("path") or "")+ # FILM-35: THE CLIENT ALREADY KNOWS THE PATH — it is+ # reading the clip off the SCREEN, not off disk — so+ # sending it is what lets this route skip the ONE+ # thing that used to make it fail on a live timeline:+ # re-deriving the path by loading edit.json and+ # looking the clip id up in it. A clip split,+ # duplicated or added since the last manual Save+ # (the ordinary state of a timeline, under the save+ # model — nothing autosaves to edit.json) simply was+ # not IN that file yet, and the retake refused with+ # "that clip is not on this timeline any more" for a+ # clip that plainly was. `retake_path` is optional so+ # an older client (or a script) still works the old+ # way.+ _p = f("retake_path", "")+ if not _p:+ try:+ _edit = sedit.load_edit(_sbe_board_dir(bid)) or {}+ except sedit.EditError:+ _edit = {}+ _clip = next((c for c in (_edit.get("clips") or [])+ if isinstance(c, dict)+ and str(c.get("id")) == retake_of), None)+ if not _clip:+ self._json({"ok": False,+ "error": "that clip is not on this "+ "timeline any more"}, 400)+ return+ _p = str(_clip.get("path") or "")source = next((s for s in shotsif _p and _p in (str(s.get("draft_output") or ""),str(s.get("final_output") or ""))),None)if source:+ # FILM-09: this excluded "draft_job"/"final_job" and+ # anything ending "_job" — but the real keys are+ # draft_job_id/final_job_id/still_job_id, so NONE of+ # them were excluded and a retake shot inherited the+ # source's final_job_id. The reconciler then folded+ # the OLD final clip back onto the "new" retake, so+ # "Retake (Delivery)" silently handed back the same+ # clip it started from. `error` and `lipsync` are+ # server-written verdicts about the SOURCE's own+ # render and must not travel onto a shot that hasn't+ # rendered yet either.+ # BOARD-3: `uid` is excluded too — a retake is a+ # DISTINCT shot, and sharing the source's identity let+ # every uid-keyed merge collapse the two into one.shot = {k: v for k, v in source.items()- if k not in ("n", "status", "draft_output",+ if k not in ("n", "uid", "status", "draft_output","final_output", "stale_output",- "grade", "draft_job", "final_job",- "edit_slot")- and not str(k).endswith("_job")}- shot.update({"n": n, "prompt": prompt,+ "grade", "edit_slot",+ "error", "lipsync")+ and not str(k).endswith("_job_id")}+ shot.update({"n": n, "uid": storyboard.new_shot_uid(),+ "prompt": prompt,"duration_s": dur, "seed": seed,"status": "pending","title": (f("title", "") or source.get("title")@@ -35521,7 +40769,8 @@ class Handler(BaseHTTPRequestHandler):h3_chain_prompts=chain_ok,h3_first_frame=bool(h3_ok and h3_supports_first_frame()),locations=storyboard.board_locations(board),- wardrobe=storyboard.board_wardrobe(board))+ wardrobe=storyboard.board_wardrobe(board),+ light=storyboard.board_light(board))job_form = {k: ("" if v is None else str(v))for k, v in form_out.items()}try:@@ -36294,7 +41543,7 @@ def page(theme: str = "") -> str:is light — the module that applies Appearance runs after parse."""cap_tier = _resolve_cap_tier()bootstrap = json.dumps({- "presets": PRESETS, "aspects": ASPECTS,+ "presets": PRESETS, "aspects": aspect_presets_for_this_mac(),"default_image": str(REFERENCE),"default_audio": str(AUDIO_DEFAULT),# Same fix as the sidecar: the model chip should name the generation@@ -36317,15 +41566,33 @@ def page(theme: str = "") -> str:# The longest a2v render this Mac accepts (0 = uncapped); the Audio# tab warns against the same number the worker refuses on."a2v_max_frames": a2v_max_frames(),- # Hardware-aware time estimates for the Quality pills. The pill HTML- # ships with the Comfortable-tier defaults; on boot we rewrite the- # subtext using the active tier's quality_times. Compact users see- # honest "~12 min" instead of the M-Studio's "~7 min" optimism."tier": {"key": SYSTEM_TIER,"label": SYSTEM_CAPS["label"],+ # VA-11 / VA-12: real, clamped-canvas prices for keyframe/extend+ # on first paint, so the Shot setup summary never shows the+ # Quality-strip's number for a pipeline that isn't the one that+ # will run. /status refreshes these too (routes_queue.py).+ "keyframe_price": ltx_mode_price_card("keyframe"),+ "extend_price_draft": ltx_mode_price_card("extend", steps=8),+ "extend_price_pro": ltx_mode_price_card("extend", steps=30),+ # VA-13: Extend's own hardware clamp (0 = unclamped, i.e. Extend+ # is disabled entirely below Comfortable — see allows_extend).+ # Shipped so the form can say the real size BEFORE Generate,+ # instead of only in the log once the render is already running.+ "extend_max_dim": int(SYSTEM_CAPS.get("extend_max_dim", 0)),+ # H3-11: whether "Stop after this window" can be offered on a+ # plain chained H3 render (see H3_RUNNER_KEEPS_WINDOWS_ON_STOP).+ "h3_stop_after_window": bool(H3_RUNNER_KEEPS_WINDOWS_ON_STOP),+ "allows_extend": bool(SYSTEM_CAPS.get("allows_extend")),+ # VA-35: client-side canvas clamps, mirroring /status's tier+ # block (routes_queue.py) so the FIRST paint already knows them —+ # the A2V form used to show the raw 1024×576 it would submit and+ # warn/estimate against that, while the server silently clamped+ # to this number at render time on Compact-tier Macs.+ "t2v_max_dim": SYSTEM_CAPS["t2v_max_dim"],+ "i2v_max_dim": SYSTEM_CAPS["i2v_max_dim"],},- "quality_times": SYSTEM_CAPS.get("quality_times", {}),# Capability tier — drives the Q4-vs-Q8 surface split that the# body[data-cap-tier="..."] CSS rules key off of. JS can also read# window.PHOSPHENE_CAP_TIER for any runtime branches.@@ -36353,6 +41620,11 @@ def page(theme: str = "") -> str:# this list — adding an engine is one entry there, not a UI rewrite."engines": engines_payload(),"default_engine": ENGINE_DEFAULT,+ # SYS-16: "has this install ever finished a render" is exactly what+ # analytics_first_render_reported already tracks (set once, on the+ # first render_completed), so the first-run card reuses that flag+ # rather than adding a second one that could drift from it.+ "first_run": not bool(get_settings().get("analytics_first_render_reported")),})# Profile badge — only visible in the dev panel. Lets Mr Bizarro tell at a# glance which install he's looking at when both panels are open.@@ -36580,7 +41852,20 @@ if __name__ == "__main__":print(" re-download; Repair also works.", flush=True)print("-" * 64, flush=True)else:- print(f"model integrity: OK ({_integ['checked']} weight files verified)", flush=True)+ # VC-10: this used to print bare "OK" even when a required file+ # was simply ABSENT — _model_integrity() only hashes files that+ # exist (a missing model is deliberately the download flow's+ # job, not integrity's), so "OK (19 weight files verified)" was+ # technically true and dangerously reassuring on an install+ # missing, say, transformer-distilled.safetensors: nothing in+ # the boot log said so. Fold in the render capability's own+ # missing-file count so a reader of the raw log sees the whole+ # picture in one line.+ _render_missing = len(capability_missing("render"))+ _integ_suffix = (f", {_render_missing} missing"+ if _render_missing else "")+ print(f"model integrity: OK ({_integ['checked']} weight files "+ f"verified{_integ_suffix})", flush=True)# Render-level codec audit (the v3.8.1 class) — the newest render's# actual encoding vs what its sidecar says was requested. Not part of# bad[] (that list is the re-download Repair flow); warned separately.diff --git a/mlx_warm_helper.py b/mlx_warm_helper.pyindex 41b3b58..e5466e4 100644--- a/mlx_warm_helper.py+++ b/mlx_warm_helper.py@@ -351,6 +351,57 @@ def _apply_vae_streaming_decision(num_frames: int) -> None:# Long clip: let the patched decoder default ("auto") pick streaming.os.environ.pop("LTX_VAE_STREAMING", None)++def _source_fps(video_path: str, fallback=None) -> float:+ """The frame rate a source clip really has (ffprobe via the engine's own+ probe_video_info — the call Retake/Extend encode the source with);+ `fallback` (the panel's delivery rate) only when the probe fails."""+ try:+ from ltx_core_mlx.utils.ffmpeg import probe_video_info+ fps = float(probe_video_info(video_path).fps)+ if fps > 0:+ return fps+ except Exception: # noqa: BLE001+ pass+ try:+ return float(fallback) if fallback and float(fallback) > 0 else 24.0+ except (TypeError, ValueError):+ return 24.0+++def _retake_latent_window(start_sec: float, end_sec: float, fps: float,+ source_frames: int) -> dict:+ """Seconds on the source clip -> RetakePipeline's LATENT frame interval.++ retake.py's contract (pinned engine): the source is cut to+ `1 + 8k` pixel frames, k = (num_frames - 1) // 8, and+ compute_video_latent_shape() gives (pixels + 7) // 8 = k + 1 latent+ frames — latent 0 is pixel 0 alone, latent j >= 1 is pixels+ 8(j-1)+1 .. 8j. start_frame is inclusive, end_frame exclusive, both+ latent indices in [0, k + 1]. LIPSYNC-5: the old `(num_frames-1)//8`+ count was one short, so the last latent frame could never be retaken.++ The window COVERS the requested seconds: every latent that holds a+ requested pixel frame is regenerated (latents are 8 frames wide, so the+ edges round outward, never inward)."""+ k = max(1, (int(source_frames) - 1) // 8)+ pixels = 1 + 8 * k+ latents = (pixels + 7) // 8+ fps = float(fps) if fps and float(fps) > 0 else 24.0+ start_sec = max(0.0, float(start_sec))+ end_sec = max(start_sec, float(end_sec))+ px_start = min(pixels - 1, int(math.floor(start_sec * fps + 1e-6)))+ px_end = max(px_start + 1, min(pixels, int(math.ceil(end_sec * fps - 1e-6))))++ def _lat(px: int) -> int:+ return 0 if px <= 0 else (px - 1) // 8 + 1++ start_frame = _lat(px_start)+ end_frame = min(latents, _lat(px_end - 1) + 1)+ return {"start_frame": start_frame, "end_frame": end_frame,+ "latent_frames": latents, "pixel_frames": pixels, "fps": fps}++_real_stdout = sys.stdout_emit_lock = threading.Lock()@@ -1424,6 +1475,33 @@ def _attach_loras(pipe, loras: list[dict] | None) -> None:pipe._pending_loras = pairs+def _a2v_anchor_images(p: dict, num_frames: int):+ """Multi-anchor image conditioning for a2v: ``anchors`` = [{path, frame_idx, strength}].++ The engine's A2V pipelines take ``images=[ImageConditioningInput]`` —+ frame_idx 0 replaces the first latent frame, any other PIXEL frame index+ appends a keyframe there (the same mechanism as Keyframe interpolation).+ Returns None when the job carries no anchors, so the legacy single+ ``image`` path is untouched.+ """+ raw = p.get("anchors")+ if not raw:+ return None+ from ltx_pipelines_mlx.utils.args import ImageConditioningInput+ out = []+ for a in raw:+ path = a.get("path") if isinstance(a, dict) else None+ if not path or not os.path.exists(path):+ raise RuntimeError(f"anchor image not found: {path}")+ idx = int(a.get("frame_idx", 0))+ if idx < 0 or idx >= num_frames:+ raise RuntimeError(f"anchor frame_idx {idx} out of range [0, {num_frames - 1}]")+ out.append(ImageConditioningInput(path=path, frame_idx=idx,+ strength=float(a.get("strength", 1.0))))+ out.sort(key=lambda c: c.frame_idx)+ return out++def _a2v_pad_audio_to(audio_path: str, need_s: float,start_s: float = 0.0) -> tuple[str, bool]:"""(path, padded). When `audio_path` from `start_s` runs out before@@ -2201,6 +2279,26 @@ def _build_live_preview(kwargs: dict):return None+def _thread_live_preview(p: dict, kwargs: dict) -> None:+ """VA-27: the best-effort live-preview wiring shared by Keyframe and A2V+ (generate_keyframe / generate_a2v / generate_a2v_distilled) — the same+ contract the t2v/i2v `generate` action already used (see the inline copy+ of these three lines there, kept separate on purpose since that call+ site also emits its own "live preview on" log line at a different point+ in its flow). Mutates `kwargs` in place. The `live_preview` key this adds+ is dropped by the caller's own `_filter_unsupported_kwargs(pipe.+ generate_and_save, kwargs)` if the installed pipeline build doesn't+ accept it — this function never raises and never blocks the render."""+ for _k in ("live_preview_dir", "live_preview_tae", "live_preview_every"):+ if p.get(_k) is not None:+ kwargs[_k] = p[_k]+ kwargs["live_preview"] = _build_live_preview(kwargs)+ if kwargs["live_preview"] is not None:+ emit({"event": "log",+ "line": f"live preview on — every {kwargs.get('live_preview_every', 1)} "+ f"estimate(s) → {p.get('live_preview_dir')}"})++def _generate_latents(pipe, *, needs_image: bool, kwargs: dict):# On second+ runs the video/audio decoders (~2.5 GB combined) remain# resident from the previous job's decode phase. During the@@ -3489,7 +3587,11 @@ for line in sys.__stdin__:# deallocator chain. See the same comment in the `generate`# action above.# FIX 2026-05-14: upstream made frame_rate= keyword-only required.- pipe._decode_and_save_video(video_lat, audio_lat, p["output_path"], frame_rate=float(p.get("frame_rate", 24.0)))+ # LIPSYNC-3 (same class as Retake): extend_from_video encodes the+ # source at ITS OWN rate, so decode at it too — a 12-fps native+ # render saved at the panel's 24 played twice as fast.+ pipe._decode_and_save_video(video_lat, audio_lat, p["output_path"],+ frame_rate=_source_fps(video_path, p.get("frame_rate")))elapsed = round(time.time() - t0, 2)_last_activity = time.time()emit({@@ -3508,6 +3610,131 @@ for line in sys.__stdin__:_is_busy = Falsecontinue+ if action == "retake_segment":+ # Segment Retake (VA-26): regenerate ONE interior stretch of a clip+ # while the rest is preserved — the engine's RetakePipeline.retake()+ # / retake_from_video(), already the Extend backend (`ExtendPipeline+ # = RetakePipeline`, same get_pipe("extend") cache slot and weights).+ # "Fix just the bad two seconds" instead of re-rendering the whole+ # clip. NEEDS RENDER CHECK (see ledger_lipsync.txt): this action has+ # not been exercised against a real GPU render — the seconds-to-+ # latent-frame conversion (_retake_latent_window) is written against+ # retake.py's own contract (start_frame/end_frame are LATENT indices;+ # the source is cut to 1 + 8k pixel frames = k + 1 latent frames) and+ # pinned by a pure test, but unverified end-to-end. Every failure mode here (bad frame math, a signature+ # the installed pipeline build doesn't have, an OOM) surfaces as an+ # ordinary job error — the same try/except every other action uses+ # — never a helper crash.+ job_id = msg.get("id", "?")+ p = msg.get("params", {}) or {}+ seed = int(p.get("seed", -1))+ if seed == -1:+ seed = random.randint(0, 2**31 - 1)+ _is_busy = True+ try:+ t0 = time.time()+ _mlx_mem_reset_run()+ configure_acceleration("off")+ video_path = p.get("video_path") or ""+ if not video_path or not os.path.exists(video_path):+ raise RuntimeError(f"source video not found: {video_path}")+ loras = p.get("loras") or []+ ret_model_dir = p.get("model_dir")+ # Same pipeline class + cache slot as Extend — RetakePipeline is+ # both APIs on one object (retake() and extend()), so a user+ # bouncing between Retake and Extend on the same session never+ # pays a second pipeline load.+ pipe = get_pipe("extend", loras=loras, model_dir=ret_model_dir,+ dev_transformer=p.get("dev_transformer"))+ # Probe the source for its real fps + frame count, so the seconds+ # the user dragged on the scrubber land on the right latent+ # indices (_retake_latent_window: retake.py's own 1 + 8k cut and+ # k + 1 latent frames). The actual encode still happens inside+ # retake_from_video, which probes the same file. LIPSYNC-3: the+ # probed fps is ALSO the decode rate below — a 12-fps native+ # render (Long Clip Boost's raw) saved at the panel's 24 played+ # twice as fast and drifted off its preserved audio.+ try:+ from ltx_core_mlx.utils.ffmpeg import probe_video_info+ info = probe_video_info(video_path)+ fps = float(info.fps) or 0.0+ src_frames = int(info.num_frames)+ src_w, src_h = int(info.width), int(info.height)+ except Exception as exc: # noqa: BLE001+ fps = float(p.get("frame_rate") or 24.0)+ emit({"event": "log",+ "line": f"[retake] source probe failed ({exc}); assuming {fps:g}fps."})+ src_frames = int(p.get("frames", 121))+ src_w = src_h = 0+ if not fps or fps <= 0:+ fps = float(p.get("frame_rate") or 24.0)+ start_sec = max(0.0, float(p.get("retake_start_sec", 0.0)))+ end_sec = max(start_sec + 0.1, float(p.get("retake_end_sec", start_sec + 1.0)))+ win = _retake_latent_window(start_sec, end_sec, fps, src_frames)+ start_frame, end_frame = win["start_frame"], win["end_frame"]+ k = win["latent_frames"]+ cfg_scale = float(p.get("cfg_scale", 1.0))+ num_steps = int(p.get("steps", 8))+ # Default False: KEEP the original sound. A user retaking a+ # visual moment (a warped hand, a flat expression) does not+ # expect the audio to change under them; True is the explicit+ # "new sound too" opt-in the UI's "keep sound / new sound"+ # choice sends.+ regenerate_audio = (p.get("retake_audio_action") == "regenerate")+ _apply_vae_streaming_decision(win["pixel_frames"])+ emit({+ "event": "log",+ "line": (+ f"step:retake_segment latent[{start_frame}:{end_frame}] of {k} "+ f"({start_sec:.1f}s-{end_sec:.1f}s at {fps:.1f}fps) "+ f"steps={num_steps} cfg={cfg_scale} "+ f"audio={'regenerate' if regenerate_audio else 'keep original'}"+ ),+ })+ with _override_default_negative_prompt(p.get("negative_prompt")) as neg_active:+ if neg_active:+ emit({"event": "log", "line": "Avoid terms active via native CFG negative prompt."})+ video_lat, audio_lat = pipe.retake_from_video(+ prompt=p["prompt"],+ video_path=video_path,+ start_frame=start_frame,+ end_frame=end_frame,+ seed=seed,+ num_steps=num_steps,+ cfg_scale=cfg_scale,+ regenerate_audio=regenerate_audio,+ )+ # Decode + save — identical shape to the "extend" action above.+ from ltx_core_mlx.utils.memory import aggressive_cleanup+ if pipe.low_memory:+ pipe.dit = None+ pipe.text_encoder = None+ pipe.feature_extractor = None+ pipe._loaded = False+ aggressive_cleanup()+ pipe._load_decoders()+ pipe._decode_and_save_video(video_lat, audio_lat, p["output_path"],+ frame_rate=fps)+ elapsed = round(time.time() - t0, 2)+ _last_activity = time.time()+ emit({+ "event": "done", "id": job_id,+ "output": p["output_path"], "elapsed_sec": elapsed,+ "seed_used": seed,+ "retake_start_frame": start_frame, "retake_end_frame": end_frame,+ # What was actually written (LIPSYNC-11): the source's own+ # rate, its 1 + 8k frame cut and its size — the panel's+ # sidecar records these instead of make_job's defaults.+ "fps": fps, "frames": win["pixel_frames"],+ "width": src_w, "height": src_h,+ })+ except Exception as exc:+ _last_activity = time.time()+ emit({"event": "error", "id": job_id, "error": str(exc), "trace": traceback.format_exc()})+ finally:+ _is_busy = False+ continue+if action == "generate_hq":# Q8 two-stage HQ + optional TeaCache. Same TwoStageHQPipeline handles# T2V (image=None) and I2V via the `image` kwarg.@@ -3803,6 +4030,7 @@ for line in sys.__stdin__:with _override_default_negative_prompt(p.get("negative_prompt")) as neg_active:if neg_active:emit({"event": "log", "line": "Avoid terms active via native CFG negative prompt."})+ _thread_live_preview(p, kwargs) # VA-27kwargs = _filter_unsupported_kwargs(pipe.generate_and_save, kwargs)out_path = pipe.generate_and_save(**kwargs)elapsed = round(time.time() - t0, 2)@@ -3896,6 +4124,12 @@ for line in sys.__stdin__:if not os.path.exists(ref_image):raise RuntimeError(f"reference image not found: {ref_image}")kwargs["image"] = ref_image+ _anchors = _a2v_anchor_images(p, num_frames)+ if _anchors:+ kwargs["images"] = _anchors+ kwargs.pop("image", None)+ emit({"event": "log", "line": "[a2v] anchors: " + ", ".join(+ f"{os.path.basename(a.path)}@{a.frame_idx}" for a in _anchors)})# audio_max_duration defaults inside the pipeline to# num_frames / frame_rate when omitted. The form may pin a# tighter clamp (e.g. user dragged a 30 s mp3 but only wants 5 s).@@ -3940,6 +4174,7 @@ for line in sys.__stdin__:with _override_default_negative_prompt(p.get("negative_prompt")) as neg_active:if neg_active:emit({"event": "log", "line": "Avoid terms active via native CFG negative prompt."})+ _thread_live_preview(p, kwargs) # VA-27kwargs = _filter_unsupported_kwargs(pipe.generate_and_save, kwargs)out_path = pipe.generate_and_save(**kwargs)elapsed = round(time.time() - t0, 2)@@ -4010,6 +4245,12 @@ for line in sys.__stdin__:if not os.path.exists(ref_image):raise RuntimeError(f"reference image not found: {ref_image}")kwargs["image"] = ref_image+ _anchors = _a2v_anchor_images(p, num_frames)+ if _anchors:+ kwargs["images"] = _anchors+ kwargs.pop("image", None)+ emit({"event": "log", "line": "[a2v] anchors: " + ", ".join(+ f"{os.path.basename(a.path)}@{a.frame_idx}" for a in _anchors)})amd = p.get("audio_max_duration")if amd is not None:try:@@ -4027,6 +4268,7 @@ for line in sys.__stdin__:f"{' image=' + os.path.basename(ref_image) if ref_image else ''}"),})+ _thread_live_preview(p, kwargs) # VA-27kwargs = _filter_unsupported_kwargs(pipe.generate_and_save, kwargs)out_path = pipe.generate_and_save(**kwargs)elapsed = round(time.time() - t0, 2)@@ -4583,6 +4825,12 @@ for line in sys.__stdin__:if not isinstance(preserve_tokens, list):preserve_tokens = []preserve_tokens = [str(t).strip() for t in preserve_tokens if str(t).strip()]+ # VC-13: the "Translate to English" toggle. True (the shipped+ # default, unchanged) keeps the upstream system prompt's own+ # instruction to answer in English. False adds an addendum line+ # overriding it — the panel's prompt-box toggle only shows once a+ # non-Latin-script prompt is typed, so this only ever fires there.+ translate = bool(p.get("translate", True))if not user_prompt:emit({"event": "error", "id": job_id, "error": "empty prompt"})continue@@ -4609,6 +4857,14 @@ for line in sys.__stdin__:"- Audio sentence stays as one trailing line that begins"," with 'Audio:'.",]+ if not translate:+ addendum_lines += [+ "",+ "#### Language (overrides the base instruction above):",+ "- Write the enhanced prompt in the SAME language the",+ " user's original prompt is written in. Do NOT",+ " translate it to English.",+ ]if preserve_tokens:addendum_lines += ["",diff --git a/music_video.py b/music_video.pyindex 8ef57c5..25a6fcf 100644--- a/music_video.py+++ b/music_video.py@@ -71,6 +71,42 @@ ROLE_LINES = {("room", "broll"): "wide, small room, warm light",}+#: FILM-12: the same ROLE_LINES sentence repeated on every B-roll slot is+#: what an 8-shot plan with one picture per role looked like — "8 shots, all+#: the same prompt." Each role gets a small rotation of framing/subject/+#: motion so consecutive B-roll shots of the same picture do not read as+#: duplicates; `_broll_variant_line` below picks one per slot, deterministic+#: on the slot's own turn number so a re-plan of the same cast is stable.+#: `ROLE_LINES` stays the single-entry fallback for a role with no rotation.+ROLE_LINE_VARIANTS = {+ "singer": [+ "close-up, still, eyes down between lines",+ "medium close-up, three-quarter turn, still",+ "close-up, a slow breath before the next line, still",+ "medium shot, hands resting, looking past the camera, still",+ ],+ "instrument": [+ "hands on the piano keys, slow push-in",+ "close on the strings, fingers resting, warm light",+ "wide on the instrument at rest in the room, still",+ "over the shoulder on the hands, slow pull-back",+ ],+ "room": [+ "wide, small room, warm light",+ "medium wide, low angle across the room, warm light",+ "wide, drifting slowly across the room, warm light",+ "close on one detail of the room, warm light",+ ],+}+++def _broll_variant_line(role: str, turn: int) -> str:+ """The `turn`-th B-roll direction for `role` — see ROLE_LINE_VARIANTS."""+ variants = ROLE_LINE_VARIANTS.get(role)+ if variants:+ return variants[turn % len(variants)]+ return ROLE_LINES.get((role, "broll")) or ROLE_LINES[("room", "broll")]+# ---------------------------------------------------------------------------# THE DURATION AXIS# ---------------------------------------------------------------------------@@ -649,7 +685,7 @@ def _with_style(line: str, style: str) -> str:def _prompt_for(image: dict, kind: str, style: str, *,- silent: bool = False) -> str:+ silent: bool = False, variant: int = 0) -> str:"""The shot's direction: the picture's own line, then the film's look.An image carries `prompt` when the user typed one for it, and that REPLACES@@ -662,22 +698,48 @@ def _prompt_for(image: dict, kind: str, style: str, *,words are scrubbed, the direction is capped, and the literal synccontract is appended LAST so a user's own line cannot paraphrase it away.`silent=True` swaps that contract for the relaxed-closed-lips one.++ FILM-12: for a B-roll shot with no picture-level `prompt`, `variant`+ (the shot's own turn in the B-roll rotation) picks one of that role's+ ROLE_LINE_VARIANTS instead of always the same single sentence — the same+ picture cut to twice in a row reads as two different shots, not a loop."""- line = (str(image.get("prompt") or "").strip()- or ROLE_LINES.get((image.get("role"), kind))- or ROLE_LINES[("room", "broll")])- return _sing_prompt(_with_style(line, style), kind, silent=silent)+ typed = str(image.get("prompt") or "").strip()+ if typed:+ line = typed+ elif kind == "broll":+ line = _broll_variant_line(image.get("role") or "room", variant)+ else:+ line = ROLE_LINES.get((image.get("role"), kind)) or ROLE_LINES[("room", "broll")]+ return _sing_prompt(line, style, kind, silent=silent)-def _sing_prompt(text: str, kind: str, *, silent: bool = False) -> str:+def _sing_prompt(line: str, style: str, kind: str, *, silent: bool = False) -> str:"""One direction, put through the a2v law when the shot is audio-driven.B-roll is untouched: an i2v shot has no waveform, so a contract about- syllables would be a sentence about a sound that is not there.+ syllables would be a sentence about a sound that is not there — B-roll+ still gets `line + style` joined the ordinary way, uncapped.++ FILM-13/FILM-14: for a SINGING shot the LINE is capped FIRST+ (`a2v_direction`, `storyboard.A2V_MAX_WORDS`), and the style is appended+ ONLY AFTER — the join used to happen before the cap+ (`_with_style(line, style)` handed straight to the a2v pipeline), so a+ line already near the 40-word limit silently lost the whole style+ suffix the cap trimmed off the end. A singing shot rendered with no+ style is a singing shot with different (or no) lighting from the film's+ B-roll, which is uncapped and always keeps it — the lighting mismatch+ this fixes."""if kind != "singing":- return text- return storyboard.a2v_prompt(text, silent=silent)+ return _with_style(line, style)+ capped_line = storyboard.a2v_direction(line, max_words=storyboard.A2V_MAX_WORDS)+ combined = _with_style(capped_line, style)+ # max_words=None: the direction was already capped above; this second+ # pass only re-scrubs stillness in the (uncapped) style clause and+ # appends the literal lip-sync contract last, per storyboard.a2v_prompt's+ # own contract.+ return storyboard.a2v_prompt(combined, silent=silent, max_words=None)def slice_is_silent(sections, t0: float, t1: float) -> bool:@@ -841,7 +903,8 @@ def plan_music_video(sections, images, *, style: str, bpm_grid,singer_turn = 0broll_turn = 0- def emit(image: dict, kind: str, frames: int, section: dict) -> None:+ def emit(image: dict, kind: str, frames: int, section: dict,+ variant: int = 0) -> None:nonlocal cursordur = frames / float(FPS)n = len(shots) + 1@@ -865,13 +928,18 @@ def plan_music_video(sections, images, *, style: str, bpm_grid,# have to know that rule."mode": "a2v" if kind == "singing" else "text","engine": "ltx",- "prompt": _sing_prompt(_with_style(line, style), kind,- silent=silent) if line- else _prompt_for(image, kind, style, silent=silent),+ "prompt": _sing_prompt(line, style, kind, silent=silent) if line+ else _prompt_for(image, kind, style, silent=silent,+ variant=variant),"duration_s": round(dur, 4),"seed": -1,"refs": [],"still": image["path"],+ # FILM-11: this is the user's OWN uploaded cast picture, not a+ # machine-generated anchor still — "New still" must never treat+ # it as disposable render-cache the way it treats a planner's+ # own still.+ "still_source": "user","status": "pending","music_video": {"kind": kind,@@ -931,7 +999,8 @@ def plan_music_video(sections, images, *, style: str, bpm_grid,cursor += new_dur - old_durcontinueframes = max(_frames_for(max(span, MIN_SHOT_S)), _frames_for(MIN_SHOT_S))- emit(ring[broll_turn % len(ring)], "broll", frames, sec)+ emit(ring[broll_turn % len(ring)], "broll", frames, sec,+ variant=broll_turn)broll_turn += 1if not shots:@@ -1139,11 +1208,13 @@ def _recast(shot: dict, image: dict, style: str, overrides: dict) -> None:"""block = shot["music_video"]shot["still"] = image["path"]+ shot["still_source"] = "user" # FILM-11 — see emit()block["image"] = image["path"]block["role"] = image["role"]line = overrides.get(int(shot["n"]))shot["prompt"] = (_with_style(line, style) if line- else _prompt_for(image, "broll", style))+ else _prompt_for(image, "broll", style,+ variant=int(shot.get("n") or 0)))def _pin_broll(shots: list[dict], pool: list[dict], style: str,diff --git a/panel/routes_characters.py b/panel/routes_characters.pyindex 63cbe2f..8a4e66f 100644--- a/panel/routes_characters.py+++ b/panel/routes_characters.py@@ -376,9 +376,17 @@ def post_character_generate(h, path, qs, ctype) -> None:# Optional image / audio paths for i2v and i2v+clean-audio modes.# Frontend uploads files via /upload, gets back a path, and# passes it here. Mode auto-switches:- # image + audio → i2v_clean_audio (character lip-syncs to audio)+ # image + audio → i2v_clean_audio (audio MUXED onto the render —+ # not lip-sync; the mouth does not follow this file,+ # see VA-20/webapp/docs/audio.md)# image only → i2v (character animates from still)- # audio only → t2v + audio (audio drives generation; rare)+ # audio only → REFUSED (VA-37) — t2v never reads the audio field,+ # so this used to queue a silent-audio render with+ # no indication anything was dropped. For real+ # lip-sync (audio-conditioned generation, the mouth+ # actually follows the track) use the Video tab's+ # Lip-sync mode (a2v), which takes a character's face+ # LoRA as an ordinary LoRA pick.# neither → t2v (default)image_path = (form.get("image", [""])[0] or "").strip()audio_path = (form.get("audio", [""])[0] or "").strip()@@ -386,6 +394,13 @@ def post_character_generate(h, path, qs, ctype) -> None:h._json({"error": f"image not found: {image_path}"}, 400); returnif audio_path and not P.Path(audio_path).exists():h._json({"error": f"audio not found: {audio_path}"}, 400); return+ if audio_path and not image_path:+ h._json({"error": "audio needs an image to make a mux (image + "+ "audio); without one the audio would be silently "+ "dropped. For a character that talks or sings to "+ "your audio, use Lip-sync on the Video tab "+ "instead — that's audio-conditioned generation, "+ "not a mux."}, 400); returnif image_path and audio_path:mode = "i2v_clean_audio"elif image_path:diff --git a/panel/routes_files.py b/panel/routes_files.pyindex 8e4c72a..5f10faa 100644--- a/panel/routes_files.py+++ b/panel/routes_files.py@@ -62,6 +62,23 @@ def post_upload_delete(h, path, qs, ctype) -> None:"uploads": P.list_uploads(limit=24)})+# 4.17 Codex SAFETY-13: the draft restore brings back an Image/Keyframe/+# Extend/audio source path saved in localStorage — possibly one deleted since.+# Images validate themselves in the picker (/image 404s); an audio upload or+# an Extend source has no preview to fail, so the restore asks here. Bound to+# outputs/ and uploads/ like every file route; answers only a boolean.+@get("/file/exists")+def get_file_exists(h, parsed) -> None:+ raw = (P.parse_qs(parsed.query).get("path", [""])[0] or "").strip()+ try:+ path = P.Path(raw).resolve() if raw else None+ roots = [P.OUTPUT.resolve(), P.UPLOADS.resolve()]+ except Exception:+ path, roots = None, []+ ok = bool(path) and any(path.is_relative_to(r) for r in roots) and path.is_file()+ h._json({"exists": ok})++@get("/file")def get_file(h, parsed) -> None:qs = P.parse_qs(parsed.query)@@ -178,6 +195,55 @@ def get_image(h, parsed) -> None:h.wfile.write(fh.read())+#: VC-31/36: video containers the poster route will generate a frame for.+#: Everything else under OUTPUT/UPLOADS (images, audio) has no poster to+#: make and is refused rather than silently 404ing from inside+#: _ensure_video_poster.+POSTER_ROUTE_EXTS = frozenset({".mp4", ".mov", ".m4v", ".webm"})+++@get("/poster")+def get_poster(h, parsed) -> None:+ """One cached JPEG frame of a rendered clip — what lets a gallery card+ be a plain `<img>` instead of a live `<video preload="metadata">`+ (VC-31/36). Same containment rule as /image; generation itself is+ _ensure_video_poster's job (idempotent, cached in the same+ _THUMBCACHE _ensure_thumbnail already uses)."""+ qs = P.parse_qs(parsed.query)+ try:+ path = P.Path(qs.get("path", [""])[0]).resolve()+ except Exception:+ h.send_error(400); return+ try:+ roots = [P.OUTPUT.resolve(), P.UPLOADS.resolve()]+ except Exception:+ roots = []+ if not any(path.is_relative_to(r) for r in roots):+ h.send_error(403); return+ if path.suffix.lower() not in POSTER_ROUTE_EXTS:+ h.send_error(403); return+ if not path.exists() or not path.is_file():+ h.send_error(404); return+ try:+ poster = P._ensure_video_poster(path)+ except Exception as exc: # noqa: BLE001+ P.push(f"poster generation failed for {path.name}: {exc}")+ poster = None+ if poster is None:+ h.send_error(404); return+ h.send_response(200)+ h.send_header("Content-Type", "image/jpeg")+ h.send_header("Content-Length", str(poster.stat().st_size))+ # Cacheable — the file only changes if the SOURCE clip's mtime/size+ # changes, and the cache key already encodes that (a rewritten source+ # gets a new key, this response for the old one is simply never+ # requested again).+ h.send_header("Cache-Control", "public, max-age=604800, immutable")+ h.end_headers()+ with poster.open("rb") as fh:+ h.wfile.write(fh.read())++@get("/sidecar")def get_sidecar(h, parsed) -> None:qs = P.parse_qs(parsed.query)@@ -242,7 +308,30 @@ def get_sidecar(h, parsed) -> None:if companion is None:h.send_error(404); returnsidecar = companion- h._ok(sidecar.read_bytes(), "application/json")+ # VC-19: the modal's "Format" line used to read straight from+ # params.width/height — the RENDER canvas, not the DELIVERED file.+ # Balanced's default 720p-fit export (or any upscale) changes the two,+ # and the modal reported the render size as if it were the file on+ # disk: "Format 1024x576" for a 1280x720 video. `sidecar` is always+ # `<media>.json`, so its own stem names the real media file — probe+ # THAT and attach the answer as a sibling field the params never had a+ # reason to carry (an ffprobe on render's own output would just repeat+ # the request; this asks the file, not the memory of the request).+ # One ffprobe, only when a human opens the info modal — never on the+ # gallery's poll path.+ try:+ payload = P.json.loads(sidecar.read_bytes())+ except (ValueError, OSError):+ h._ok(sidecar.read_bytes(), "application/json")+ return+ if isinstance(payload, dict) and "actual_width" not in payload:+ media_path = sidecar.parent / sidecar.stem # "<media>.json" -> "<media>"+ if media_path.suffix.lower() == ".mp4" and media_path.is_file():+ aw, ah = P._probe_video_dims(str(media_path))+ if aw and ah:+ payload["actual_width"] = aw+ payload["actual_height"] = ah+ h._json(payload)@get("/library/images")@@ -617,6 +706,87 @@ def post_output_open_folder(h, path, qs, ctype) -> None:h._json({"error": f"open failed: {e}"}, 500)+# VC-18/37: per-clip "Reveal in Finder" — the toolbar/lightbox "More" menu+# action. `/output/open_folder` above only ever reveals the newest file+# across the whole gallery; this reveals the SPECIFIC clip the user has+# selected, wherever it lives (a plain render, a Sharp export, a face-fix+# pass, an uploaded reference — same containment rule as /image).+@post("/output/reveal")+def post_output_reveal(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ raw = (form.get("path", [""])[0] or qs.get("path", [""])[0] or "").strip()+ if not raw:+ h._json({"ok": False, "error": "no path given"}, 400); return+ try:+ target = P.Path(raw).resolve()+ except Exception:+ h._json({"ok": False, "error": "bad path"}, 400); return+ try:+ roots = [P.OUTPUT.resolve(), P.UPLOADS.resolve()]+ except Exception:+ roots = []+ if not any(target.is_relative_to(r) for r in roots):+ h._json({"ok": False, "error": "that path is outside the outputs/uploads folders"}, 403)+ return+ if not target.is_file():+ h._json({"ok": False, "error": "that file is not on disk any more"}, 404)+ return+ P.subprocess.run(["open", "-R", str(target)], check=False)+ h._json({"ok": True, "opened": str(target)})+++# VC-18/37: "Use last frame" — extract the clip's final frame as a new+# reference image so the player can offer it straight into i2v ("continue+# from here on a fresh roll of the dice", the non-Extend way of picking up+# where a take left off). Same ffmpeg recipe One Shot's own take-to-take+# handoff already uses (`-sseof -0.05 -frames:v 1`), just pointed at+# UPLOADS instead of a private take-dir so the picker can show it.+@post("/output/last_frame")+def post_output_last_frame(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ raw = (form.get("path", [""])[0] or qs.get("path", [""])[0] or "").strip()+ if not raw:+ h._json({"ok": False, "error": "no path given"}, 400); return+ try:+ src = P.Path(raw).resolve()+ except Exception:+ h._json({"ok": False, "error": "bad path"}, 400); return+ try:+ roots = [P.OUTPUT.resolve(), P.UPLOADS.resolve()]+ except Exception:+ roots = []+ if not any(src.is_relative_to(r) for r in roots):+ h._json({"ok": False, "error": "that path is outside the outputs/uploads folders"}, 403)+ return+ if not src.is_file() or src.suffix.lower() != ".mp4":+ h._json({"ok": False, "error": "Use last frame works on rendered video clips."}, 400)+ return+ ff = P.shutil.which("ffmpeg")+ if not ff:+ h._json({"ok": False, "error": "ffmpeg is not available"}, 500); return+ out_dir = P.UPLOADS / "library" / "manual" / P.time.strftime("%Y-%m-%d")+ out_dir.mkdir(parents=True, exist_ok=True)+ out_path = out_dir / f"{src.stem}_lastframe_{int(P.time.time())}.png"+ try:+ P.subprocess.run(+ [ff, "-loglevel", "error", "-y", "-sseof", "-0.05", "-i", str(src),+ "-frames:v", "1", "-update", "1", str(out_path)],+ check=True, capture_output=True, timeout=30,+ )+ except Exception as e:+ h._json({"ok": False, "error": f"could not extract the last frame: {e}"}, 500)+ return+ if not out_path.is_file() or out_path.stat().st_size == 0:+ h._json({"ok": False, "error": "ffmpeg produced no image"}, 500); return+ h._json({"ok": True, "path": str(out_path), "url": f"/image?path={P.quote(str(out_path))}"})++@post("/external/open")def post_external_open(h, path, qs, ctype) -> None:_rb = h._read_form_body()@@ -740,10 +910,56 @@ def post_upload(h, path, qs, ctype) -> None:if not getattr(fld, "filename", None):h._json({"error": "no filename"}, 400); returnP.UPLOADS.mkdir(parents=True, exist_ok=True)- safe_name = P.re.sub(r"[^A-Za-z0-9._-]+", "_", fld.filename)+ raw = fld.file.read()+ _orig = P.Path(fld.filename)+ out_ext = _orig.suffix+ # SYS-01/SYS-02: normalize every picked IMAGE (not the audio field —+ # i2v_clean_audio's external track shares this endpoint) once, here,+ # before it ever reaches a picker preview, a render, or a thumbnail.+ # EXIF orientation is applied and stripped; HEIC/HEIF/AVIF (what+ # AirDrop/Photos hand a Mac by default, and what Pillow cannot open+ # at all) is converted to JPEG. A failure here — a genuinely corrupt+ # file, or HEIC on a Mac without sips — refuses the upload with a+ # clear reason instead of writing bytes the render will die on 30 s+ # into a helper's model load.+ if field_name == "image":+ raw, out_ext, err = P.normalize_ingested_image_bytes(raw, fld.filename)+ if err:+ h._json({"error": err}, 400); return+ # SYS-26: this used to be `[^A-Za-z0-9._-]+ -> "_"`, ASCII-only, so+ # テスト画像_猫.jpg landed as ____.jpg and "Recent uploads" listed+ # it the same way — unsearchable, indistinguishable from every+ # other erased name. _unicode_slug keeps any script's letters and+ # digits; the extension is kept separately (conventionally ASCII,+ # and matters for the server's own extension checks elsewhere).+ # The extension is the NORMALIZED one (a HEIC converted above is+ # written as .jpg), not the name the file arrived with.+ _stem = P._unicode_slug(_orig.stem, max_chars=120, fallback="upload")+ _ext = P.re.sub(r"[^A-Za-z0-9.]", "", out_ext or "")[:10]+ safe_name = f"{_stem}{_ext}"+ # Cap the FULL name (this slug + the millisecond timestamp prefix+ # below) at 200 bytes, well under the 255-byte filesystem limit on+ # APFS — a multi-byte-per-character script (CJK, emoji) can blow+ # past a character-count cap in byte terms even at a modest+ # character count.+ while len(safe_name.encode("utf-8")) > 200 and _stem:+ _stem = _stem[:-1]+ safe_name = f"{_stem}{_ext}"dest = P.UPLOADS / f"{int(P.time.time()*1000)}_{safe_name}"- dest.write_bytes(fld.file.read())- h._json({"ok": True, "path": str(dest)})+ dest.write_bytes(raw)+ resp = {"ok": True, "path": str(dest)}+ # Audio duration (VA-03): the A2V form's Duration slider and Audio+ # start have always been blind to the length of what was just+ # dropped — an uploaded 4s vocal silently defaulted to a 7s render,+ # 43% of it silence rendered against nothing (exactly where a+ # lip-sync mouth freezes). The client already reads duration_sec+ # when present (AUDIO_STUDIO.audioDuration in characters.js); this+ # is the half of that contract the server never filled in.+ if field_name == "audio":+ dur = P.probe_media_duration(dest)+ if dur is not None:+ resp["duration_sec"] = dur+ h._json(resp)except Exception as exc:h._json({"error": f"upload failed: {exc}"}, 500)diff --git a/panel/routes_meta.py b/panel/routes_meta.pyindex fa04efa..11aac25 100644--- a/panel/routes_meta.py+++ b/panel/routes_meta.py@@ -14,6 +14,68 @@ from panel.routes import get, get_when, post, post_whenP = None # the running mlx_ltx_panel module; assigned at wiring time+# Codex UI-6: the crash-report filter (SYS-12) matched on the FILE NAME —+# "python3*" / "python*" / "phosphene*" — so any other Python program that+# crashed on the Mac (another app's script, a notebook kernel, a CLI tool)+# was counted in the modal and zipped verbatim into a Phosphene bug report,+# its own paths and content included. A name says which interpreter+# crashed, not whose process it was. The reliable signal is inside the+# report: an .ips body lists `procPath` and every loaded image+# (`usedImages[].path`), and a Phosphene process always runs a binary or+# loads extension modules (mlx, the engines' venvs) from under this+# install. A report that shows nothing under these roots is ambiguous and+# is left out — the opt-in checkbox never attaches it.+_CRASH_NAME_PREFIXES = ("python3", "python", "phosphene")+_CRASH_MAX_READ_BYTES = 32 * 1024 * 1024+++def _phosphene_crash_roots() -> tuple[str, ...]:+ roots: set[str] = set()+ for name in ("ROOT", "H3_ROOT", "LORA_LAB_ROOT"):+ base = getattr(P, name, None)+ if not base:+ continue+ for cand in (P.Path(base), P.Path(base) / "ltx-2-mlx"):+ for form in (cand, cand.resolve() if cand.exists() else None):+ if form is not None and str(form) not in ("", "/"):+ roots.add(str(form).rstrip("/") + "/")+ return tuple(sorted(roots))+++def _is_phosphene_crash(path, roots: tuple[str, ...]) -> bool:+ """True only when the .ips shows a process of THIS install."""+ try:+ if path.stat().st_size > _CRASH_MAX_READ_BYTES:+ return False+ text = path.read_text(encoding="utf-8", errors="replace")+ except OSError:+ return False+ _header, _, body = text.partition("\n")+ try:+ doc = P.json.loads(body)+ except ValueError:+ return False+ if not isinstance(doc, dict):+ return False+ paths = [doc.get("procPath")]+ images = doc.get("usedImages")+ if isinstance(images, list):+ paths.extend(i.get("path") for i in images if isinstance(i, dict))+ return any(isinstance(p, str) and p.startswith(roots) for p in paths)+++def _phosphene_crash_reports(diag) -> list:+ """This install's own crash reports in `diag`, newest first."""+ roots = _phosphene_crash_roots()+ if not roots:+ return []+ cands = [p for p in diag.iterdir()+ if p.is_file() and p.suffix.lower() == ".ips"+ and p.name.lower().startswith(_CRASH_NAME_PREFIXES)]+ cands.sort(key=lambda p: p.stat().st_mtime, reverse=True)+ return [p for p in cands if _is_phosphene_crash(p, roots)]++@get("/sw.js")def get_service_worker(h, parsed) -> None:"""The push service worker, served from the ROOT so its scope covers the@@ -165,16 +227,25 @@ def get_panel_bug_context(h, parsed) -> None:ram_gb = round(float(mem.get("total_gb") or 0.0))with P.LOCK:tail = list(P.STATE["log"])[-50:]+ # SYS-12, privacy: this pre-fills the bug-report textarea that+ # opens a PUBLIC GitHub issue. Log lines routinely carry+ # /Users/<username>/... paths (panel_uploads, output paths), and+ # the macOS username is often the person's real name. Scrub before+ # it ever reaches the browser, not after.+ tail = [P._bug_report_scrub_line(line) for line in tail]# Crash count — the modal hides the "Include crash reports"# checkbox when zero so the user doesn't see an empty zip.+ # SYS-12: counted every .ips on the Mac, regardless of which process+ # crashed — mismatched what /panel/bug-report actually zips (now+ # filtered to python3*/Python*/phosphene*; see there). Same filter+ # here so the modal's count matches what "Include crash reports"+ # would actually attach.crash_count = 0try:diag = P.Path.home() / "Library" / "Logs" / "DiagnosticReports"if diag.is_dir():- crash_count = sum(- 1 for p in diag.iterdir()- if p.is_file() and p.suffix.lower() == ".ips"- )+ # UI-6: the SAME positive-identification filter the zip uses.+ crash_count = len(_phosphene_crash_reports(diag))except OSError:passh._json({@@ -734,15 +805,19 @@ def post_panel_bug_report(h, path, qs, ctype) -> None:# method and break the bundle endpoint.diag = P.Path.home() / "Library" / "Logs" / "DiagnosticReports"if diag.is_dir():- # Latest 5 ips files (any process; .ips is the only- # universal extension across crash sources). Sorted- # by mtime descending.- ips = sorted(- (p for p in diag.iterdir()- if p.is_file() and p.suffix.lower() == ".ips"),- key=lambda p: p.stat().st_mtime,- reverse=True,- )[:5]+ # SYS-12: this used to take the latest 5 .ips from ANY+ # process on the Mac — Safari, Mail, a game, whatever last+ # crashed — and zip it into a Phosphene bug report. The+ # panel's own crashes are always "python3*" or "Python*"+ # (see the watchdog error copy: python3.11_*.ips), so+ # filter to those; an unrelated app's crash tells the+ # Phosphene maintainer nothing and is a real, unnecessary+ # privacy cost for the reporter (another app's crash log+ # can carry its own paths/content, unrelated to this bug).+ # UI-6: ...and a "python*" name alone is not Phosphene —+ # _phosphene_crash_reports() reads each report and keeps+ # only the ones whose process ran from this install.+ ips = _phosphene_crash_reports(diag)[:5]if ips:# 2026-05-31 review fix: crash .ips files can carry# home paths / usernames. The old predictablediff --git a/panel/routes_music.py b/panel/routes_music.pyindex 74e48cf..1372ebf 100644--- a/panel/routes_music.py+++ b/panel/routes_music.py@@ -651,6 +651,22 @@ def _shot_rows(shots: list) -> list:return rows+++def _board_title_from_song(raw) -> str:+ """A song's name as a BOARD title (4.17): never its file extension+ ("song40.wav"), the upload's millisecond prefix ("1790123456789_take 3")+ or the composer's "music_YYYYMMDD_HHMMSS_" stamp — the client strips the+ same three (music.js _songNameFromFile), this is the authoritative copy+ for any caller that posts a raw filename."""+ import re as _re # noqa: PLC0415+ t = str(raw or "").strip()+ t = t.rsplit("/", 1)[-1]+ t = _re.sub(r"\.(wav|mp3|m4a|flac|aac|ogg|opus|aiff?)$", "", t, flags=_re.I)+ t = _re.sub(r"^\d{10,}_", "", t)+ t = _re.sub(r"^music_\d{8}_\d{6}_", "", t)+ return t.replace("_", " ").strip()+@post("/music/video/plan")def post_music_video_plan(h, path, qs, ctype) -> None:"""Song + pictures -> a storyboard board, and the shot list to show.@@ -693,8 +709,9 @@ def post_music_video_plan(h, path, qs, ctype) -> None:h._json({"error": f"the vocal stem is not a file this panel has "f"({vocal_stem_raw!r}). {_where_to_put_files()}"}, 400)return- title = _one(form, "title").strip() or (_sidecar(str(song)) or {}).get("title") \- or song.stem+ title = _board_title_from_song(+ _one(form, "title").strip() or (_sidecar(str(song)) or {}).get("title")+ or song.stem) or "Music video"meta = _sidecar(str(song)) or {}sections_raw = _one(form, "sections").strip()lyrics = _one(form, "lyrics")@@ -734,6 +751,34 @@ def post_music_video_plan(h, path, qs, ctype) -> None:lyrics=lyrics if lyrics.strip() else meta.get("lyrics"),score_abc=score_abc if score_abc.strip() else meta.get("score_abc"),beats=beats)+ # FILM-12: a real 40 s vocal track with a Singer picture cast+ # planned "0 singing shots · 8 identical B-roll" and said+ # nothing — the band-energy classifier is crude (one ratio+ # against the track's own median) and got this one wrong with+ # no way for the user to notice before the render was spent.+ # Only fires for the CLASSIFIER's own guess (no explicit+ # `sections`/lyrics/score — those are the user's own word on+ # it) and only when a Singer is actually cast — an+ # instrumental-only cast is correctly all B-roll and must not+ # be nagged. `plan_anyway` is the escape hatch once the user+ # has seen the sections and still wants to proceed as-is.+ plan_anyway = _one(form, "plan_anyway").strip().lower() in ("1", "on", "true", "yes")+ has_singer = any(isinstance(im, dict)+ and str(im.get("role") or "").strip().lower() == "singer"+ for im in images)+ no_lyrics_or_score = not (lyrics.strip() or score_abc.strip()+ or meta.get("lyrics") or meta.get("score_abc"))+ if (has_singer and no_lyrics_or_score and not plan_anyway+ and not any(str(r.get("kind") or "").strip().lower() == "vocal"+ for r in sections)):+ h._json({+ "error": "I heard no singing in this track, so nobody "+ "would be filmed singing — mark the sung parts "+ "below, or plan it as B-roll only.",+ "no_vocal_detected": True,+ "sections": sections,+ }, 409)+ returnnote = mv.tempo_disagreement(beats, (score_abc if score_abc.strip() else meta.get("score_abc")) or "")if note:@@ -745,9 +790,34 @@ def post_music_video_plan(h, path, qs, ctype) -> None:# QUALITY too — the table's own `qualities` column says the 20 s cell# is Quick-only, and a 481-frame a2v shot on the standard 1024×576# canvas dies around frame 454.+ #+ # FILM-43: re-planning (a new song, a cast change, "Plan again"+ # after marking sections) used to mint a brand-new board every+ # time — the board list filled up with identically-named copies of+ # the same music video instead of the plan just updating. A caller+ # that names an EXISTING music-video board (`board_id`, the id+ # /music/video/plan itself returned last time) gets that board+ # UPDATED in place; anything else — a fresh plan, or a board_id+ # that turns out not to be a music-video board at all — still gets+ # a new one, exactly as before.+ reuse_id = _one(form, "board_id").strip()+ if reuse_id:+ try:+ existing = P.storyboard.load_storyboard(P.STATE_DIR, reuse_id)+ except Exception: # noqa: BLE001+ existing = None+ if not (isinstance(existing, dict) and existing.get("music_video")):+ reuse_id = ""+ if reuse_id:+ # BOARD-1: never swap a board out from under its own render.+ busy = P._sb_board_busy_reason(reuse_id, existing)+ if busy:+ h._json({"error": busy, "busy": True}, 409)+ return+ board_id = reuse_id or P._sb_new_id(title)out = mv.plan_music_video(sections, images, style=style, bpm_grid=beats, song=str(song),- title=title, board_id=P._sb_new_id(title), quality=quality,+ title=title, board_id=board_id, quality=quality,shot_prompts=shot_prompts, shot_images=shot_images,vocal_stem=str(vocal_stem) if vocal_stem else "",cells=mv.cells_from_lengths(P.LTX_LENGTHS, quality=quality))@@ -757,6 +827,11 @@ def post_music_video_plan(h, path, qs, ctype) -> None:h._json({"error": f"could not plan that video: {exc}"}, 500); returnboard = out["board"]+ if reuse_id:+ # The board is being UPDATED, not born — keep its original+ # "created" time; `updated_at` (set by _sb_normalize below) is+ # what moves it to the top of a Recent sort.+ board["created_at"] = existing.get("created_at") or board["created_at"]# The pass policy is the user's saved Quality, exactly as a planned film# gets it — `new_storyboard` hands back the module default, which ignores# this machine's canvas cap.@@ -766,7 +841,37 @@ def post_music_video_plan(h, path, qs, ctype) -> None:board["music_video"]["notes"] = list(out["notes"]) + notesboard["music_video"]["quality"] = qualityP._sb_normalize(board)- P.storyboard.save_storyboard(P.STATE_DIR, board)+ with P._SB_LOCK:+ if reuse_id:+ # BOARD-1: re-checked under the lock the render route claims its+ # slot with, and held through the save — a render started while+ # this plan was being computed wins, and the old board stays.+ try:+ current = P.storyboard.load_storyboard(P.STATE_DIR, reuse_id)+ except Exception: # noqa: BLE001+ current = existing+ busy = P._sb_board_busy_reason(reuse_id, current)+ if busy:+ h._json({"error": busy, "busy": True}, 409)+ return+ P.storyboard.save_storyboard(P.STATE_DIR, board)+ if reuse_id:+ # BOARD-7: the Editor's timeline was cut from the OLD plan, and+ # Export prefers a saved timeline over the shots — it would have+ # assembled the previous version. It is kept as a draft of its own;+ # the new plan starts a fresh timeline.+ try:+ aside = P._sbe_import().set_aside_for_replan(+ P._sbe_board_dir(board["id"]),+ time.strftime("%b %d %H:%M"))+ except Exception as exc: # noqa: BLE001+ aside = None+ P.push(f"[music video] could not set the old timeline aside: {exc}")+ if aside:+ board["music_video"]["notes"].append(+ f"Your earlier Editor timeline is kept as the draft "+ f"“{aside['kept']}” — the new plan starts a fresh one.")+ P.storyboard.save_storyboard(P.STATE_DIR, board)P.push(f"[music video] {out['summary']} — {title}")h._json({"ok": True, "board_id": board["id"], "title": title,"summary": out["summary"], "quality": quality,@@ -810,12 +915,27 @@ def post_music_video_film(h, path, qs, ctype) -> None:h._json({"error": "that film was not planned as a music video, so ""there is no song to lay under it"}, 409)return- song = _panel_file(block.get("song"))- if song is None:- h._json({"error": f"the song is no longer at {block.get('song')!r}"},- 404)- return+ # BOARD-8: A SAVED TIMELINE OWNS THE FILM'S AUDIO. Somebody who changed+ # the soundtrack or chose the "under" mix in the Editor made the film's+ # sound decisions there; forcing the planning song and `replace` here+ # made Storyboard Export and Editor Render two different films. The+ # board's song is the fallback only when no timeline with clips exists —+ # `_sb_export` then hands the timeline to `_sbe_render_edit`, which reads+ # the soundtrack and the mode off the document, exactly as Render does.+ try:+ edit = P._sbe_import().load_edit(P._sbe_board_dir(board.get("id") or ""))+ except Exception: # noqa: BLE001+ edit = None+ timeline_owns_audio = bool(edit and (edit.get("clips") or []))+ music, music_mode = None, None+ if not timeline_owns_audio:+ song = _panel_file(block.get("song"))+ if song is None:+ h._json({"error": f"the song is no longer at {block.get('song')!r}"},+ 404)+ return+ music, music_mode = str(song), "replace"auto = _one(form, "auto_edit") in ("1", "true", "on", "yes")P._analytics_feature("music_video_film")- h._json(P._sb_export(board, auto_edit=auto, music=str(song),- music_mode="replace"))+ h._json(P._sb_export(board, auto_edit=auto, music=music,+ music_mode=music_mode))diff --git a/panel/routes_oneshot.py b/panel/routes_oneshot.pyindex 5dcf885..d5042d0 100644--- a/panel/routes_oneshot.py+++ b/panel/routes_oneshot.py@@ -102,11 +102,17 @@ def get_oneshot_estimate(h, parsed) -> None:h._json({"ok": False, "error": f"seconds must be one of {list(P.TAKE_SECONDS)}","choices": list(P.TAKE_SECONDS)}, 400); returnminutes = P.take_estimate_minutes(engine, quality, seconds)+ # VA-16: the ceiling if every part hits its worst case (a light-drift+ # retake plus every lip-sync retake) — a mechanism-derived bound, shown+ # as "up to", not a second point estimate.+ minutes_worst = P.take_estimate_minutes_worst(engine, quality, seconds)h._json({"ok": True, "seconds": plan["seconds"], "beats": plan["beats"],"parts": len(plan["parts"]), "beats_per_part": plan["beats_per_part"],"part_seconds": (15 if plan["engine"] == "h3" else P.TAKE_LTX_PART_FRAMES // 24),"engine": plan["engine"], "minutes": minutes,- "eta": (P._fmt_eta(minutes) if minutes else None)})+ "eta": (P._fmt_eta(minutes) if minutes else None),+ "minutes_worst": minutes_worst,+ "eta_worst": (P._fmt_eta(minutes_worst) if minutes_worst else None)})@post("/oneshot/plan")diff --git a/panel/routes_queue.py b/panel/routes_queue.pyindex d70a14c..c9ddd3d 100644--- a/panel/routes_queue.py+++ b/panel/routes_queue.py@@ -7,12 +7,16 @@ panel/__init__.py for why P is assigned rather than imported."""from __future__ import annotations+import threadingfrom urllib.parse import parse_qsfrom panel.routes import get, postP = None # the running mlx_ltx_panel module; assigned at wiring time+# SAFETY-7: one recovery join at a time owns STATE["take_join_pgid"].+_TAKE_JOIN_LOCK = threading.Lock()+@get("/status")def get_status(h, parsed) -> None:@@ -29,6 +33,7 @@ def get_status(h, parsed) -> None:avg_video = P._avg_elapsed("video")payload = _copy.deepcopy({"running": P.STATE["running"], "paused": P.STATE["paused"],+ "paused_reason": P.STATE.get("paused_reason"),"current": P.STATE["current"], "queue": P.STATE["queue"],"history": P.STATE["history"][:P.HISTORY_API_LIMIT], "log": P.STATE["log"],"pid": P.STATE["pid"], "pgid": P.STATE["pgid"],@@ -80,12 +85,24 @@ def get_status(h, parsed) -> None:# when history is empty (90s for images, 420s for videos).def _eta_for(job: dict) -> float:params = job.get("params") or {}+ # VC-26: prefer the PRICED number the quality chips themselves show+ # (LTX_TIERS/H3_TIERS eta_min) over the coarse per-kind average —+ # it is the same table VC-28 already made honest, and a queue row+ # showing a different number than the chip it was submitted from+ # would just be a second class of the VC-28 bug.+ priced = P.job_priced_eta_sec(params)+ if priced is not None:+ return pricedif params.get("engine") == "music":return P.music_estimate(params["music_quality"], params["music_max_seconds"])["eta_sec"]if params.get("mode") == "image":return float(avg_image) if avg_image else 90.0return float(avg_video) if avg_video else 420.0- payload["eta_sec"] = round(sum(_eta_for(j) for j in payload["queue"]))+ # Stamped per-row (VC-26: "an ETA per job") as well as summed for the+ # existing total — one call per job either way, just captured once.+ for _j in payload["queue"]:+ _j["eta_sec"] = round(_eta_for(_j))+ payload["eta_sec"] = round(sum(_j["eta_sec"] for _j in payload["queue"]))# Y1.039 — per-job progress for the Now-card. Phase-aware,# config-bucketed ETA, denoise-step extrapolation. Replaces the# old elapsed/global-avg ratio that mis-paced Quick/High renders.@@ -174,9 +191,20 @@ def get_status(h, parsed) -> None:# matches the modal's per-repo rows (Q4 + Gemma + Q8 = 3 in the# default manifest). Avoids the pill claiming "2/2 ready" while# the modal shows three rows.+ #+ # VC-32: this used to count ALL of required_files.json's repos (12,+ # once the 2.5 generation and four IC-LoRA/tae extras joined the 2.3+ # trio the comment above still describes) — so a complete, working 2.5+ # install with no IC-LoRAs read "models 4/12", and a partial-but-+ # correctly-green pill (every REQUIRED file present) still showed a+ # scary-looking fraction. relevant_repo_keys() scopes this to the+ # ACTIVE generation's own packs plus the version-agnostic extras —+ # never another generation's base pack the install isn't running._repo_snap = P.repo_status_list()- payload["repos_total"] = len(_repo_snap)- payload["repos_ready"] = sum(1 for r in _repo_snap if r.get("complete"))+ _relevant_keys = P.relevant_repo_keys()+ _relevant_snap = [r for r in _repo_snap if r.get("key") in _relevant_keys]+ payload["repos_total"] = len(_relevant_snap)+ payload["repos_ready"] = sum(1 for r in _relevant_snap if r.get("complete"))# Structural integrity of installed weights — corrupt/partial# safetensors decode to a garbage "mosaic". Cached + header-only.payload["model_integrity"] = P._model_integrity(force=False)@@ -203,7 +231,23 @@ def get_status(h, parsed) -> None:"i2v_max_dim": P.SYSTEM_CAPS["i2v_max_dim"],"keyframe_max_dim": P.SYSTEM_CAPS["keyframe_max_dim"],"extend_max_dim": P.SYSTEM_CAPS["extend_max_dim"],- "times": P.SYSTEM_CAPS.get("times", {}),+ # VC-12 / SYS-20: computed live from the same model the Quality+ # chips use, not the old hand-typed CAPABILITIES[tier]["times"]+ # table that disagreed with them on every tier.+ "times": P.honest_tier_times(),+ # VA-11 / VA-12: keyframe/extend price the ACTUAL pipeline that+ # runs (Q8 two-stage at a clamped canvas; the extend step count),+ # not whatever Quality pill happens to be selected in the strip.+ "keyframe_price": P.ltx_mode_price_card("keyframe"),+ "extend_price_draft": P.ltx_mode_price_card("extend", steps=8),+ "extend_price_pro": P.ltx_mode_price_card("extend", steps=30),+ # SYS-03: the Train tab needs the exact RAM figure (not just the+ # tier label) to gate itself before a Mac under TRAIN_MIN_RAM_GB+ # can even see the 41 GB download offer. One number, one source+ # (SYSTEM_RAM_GB / TRAIN_MIN_RAM_GB), so the client never hardcodes+ # its own copy of the threshold.+ "ram_gb": round(P.SYSTEM_RAM_GB, 1),+ "train_min_ram_gb": P.TRAIN_MIN_RAM_GB,}# Hailuo H3 — the optional second video engine. Re-read every tick# (it's a handful of stat() calls) so an install finishing in the@@ -298,36 +342,69 @@ def post_queue_retry(h, path, qs, ctype) -> None:if source is None:h._json({"error": f"job {source_id!r} not found in history/queue"}, 404); returnsrc_params = source.get("params") or {}+ new_params = dict(src_params)+ # VC-08: the OOM/jetsam failure card's ONLY action used to be "Retry"+ # of the identical job — same size, same length, same failure, another+ # 10+ minutes on a memory-pressured Mac. "Retry smaller" sends a small,+ # explicit allowlist of overrides (never an arbitrary form) that the+ # client fills in from the SAME quality ladder and frame-count math the+ # render form itself uses — this route never invents a size, it only+ # accepts one the client already knows how to produce.+ overrides_raw = (form.get("overrides", [""])[0] or "").strip()+ if overrides_raw:+ try:+ overrides = P.json.loads(overrides_raw)+ except (TypeError, ValueError):+ h._json({"error": "overrides must be JSON"}, 400); return+ if not isinstance(overrides, dict):+ h._json({"error": "overrides must be a JSON object"}, 400); return+ allowed = {"quality", "frames"}+ unknown = set(overrides) - allowed+ if unknown:+ h._json({"error": f"overrides may only set {sorted(allowed)}, "+ f"got {sorted(unknown)}"}, 400); return+ if "quality" in overrides and overrides["quality"] not in (+ "quick", "balanced", "standard", "high"):+ h._json({"error": f"unknown quality {overrides['quality']!r}"}, 400); return+ if "frames" in overrides:+ try:+ overrides["frames"] = int(overrides["frames"])+ except (TypeError, ValueError):+ h._json({"error": "frames override must be an int"}, 400); return+ new_params.update(overrides)# Defense-in-depth: re-queuing a historical job with character_id# + balanced quality (or a raw train_character LoRA + non-high# quality) reproduces the bug /queue/add already rejects. Wrap- # src_params into the form-shape the validator expects: it reads+ # new_params into the form-shape the validator expects: it reads# `character_id`, `quality`, and `loras`. The first two are- # already strings; `loras` lives in src_params as a parsed list+ # already strings; `loras` lives in new_params as a parsed list# and needs to be re-encoded as JSON so parse_loras_from_form- # round-trips it cleanly.+ # round-trips it cleanly. Validated against new_params (post-+ # overrides) — a "smaller" retry must not reintroduce the exact+ # character+quality combination this gate exists to refuse._retry_form = {- "character_id": src_params.get("character_id") or "",- "quality": src_params.get("quality") or "",- "loras": P.json.dumps(src_params.get("loras") or []),- "engine": src_params.get("engine") or P.ENGINE_DEFAULT,- "mode": src_params.get("mode") or "t2v",- "no_voice": src_params.get("no_voice") or "off",+ "character_id": new_params.get("character_id") or "",+ "quality": new_params.get("quality") or "",+ "loras": P.json.dumps(new_params.get("loras") or []),+ "engine": new_params.get("engine") or P.ENGINE_DEFAULT,+ "mode": new_params.get("mode") or "t2v",+ "no_voice": new_params.get("no_voice") or "off",}err = P._validate_character_quality(_retry_form)if err:h._json({"error": err}, 400); return- # Build a fresh job — copy params verbatim, mint a new id, drop- # any open_when_done flag (retries are usually background; user- # is mid-other-work and doesn't want the OS jumping windows).+ # Build a fresh job — copy params (verbatim, or with the validated+ # overrides applied above), mint a new id, drop any open_when_done+ # flag (retries are usually background; user is mid-other-work and+ # doesn't want the OS jumping windows).new_job = {- "id": f"j-{int(P.time.time() * 1000):x}-{P.random.randrange(0xfff):03x}",+ "id": P._new_job_id(),"status": "queued","queued_at": P.time.strftime("%Y-%m-%d %H:%M:%S"),"started_at": None,"finished_at": None,"elapsed_sec": None,- "params": dict(src_params),+ "params": new_params,"raw_path": None,"output_path": None,"error": None,@@ -337,6 +414,35 @@ def post_queue_retry(h, path, qs, ctype) -> None:if new_job["params"].get("face_fix_targets"):new_job["params"]["face_fix_targets"] = [list(x) for x in new_job["params"]["face_fix_targets"]]new_job["params"]["source"] = "retry"+ # SYS-07: "Retry smaller" — the failure card for the Metal-watchdog /+ # jetsam classes (the two biggest fleet failures) used to offer only a+ # plain Retry, which re-queues the SAME size and SAME length that just+ # died of a GPU timeout or an OOM kill. This re-queues one quality rung+ # down, at a scaled-and-grid-snapped canvas (via the same ltx_fit_canvas+ # every hardware clamp goes through, so the result is never an+ # off-grid size the pipeline would reject), and roughly halves the+ # clip length toward the 8k+1 frame grid — real, not cosmetic, relief+ # for the two failure classes it's offered on.+ if (form.get("smaller", ["0"])[0] or "0") == "1":+ p = new_job["params"]+ step_down = {"pro": "high", "high": "standard", "standard": "balanced", "balanced": "quick"}+ p["quality"] = step_down.get(str(p.get("quality") or "balanced").lower(), "quick")+ # 4.17 Codex SAFETY-2: the height used to be bound to `h` — the HTTP+ # handler — so the reply below raised AttributeError AFTER the+ # smaller job was queued: the button reported failure and a second+ # click queued a second replacement.+ try:+ w, ht = int(p.get("width") or 0), int(p.get("height") or 0)+ if w > 0 and ht > 0:+ p["width"], p["height"] = P.ltx_fit_canvas(w, ht, int(max(w, ht) * 0.75))+ except (TypeError, ValueError):+ pass+ try:+ frames = int(p.get("frames") or 121)+ if frames > 41:+ p["frames"] = max(41, ((frames // 2) // 8) * 8 + 1)+ except (TypeError, ValueError):+ passwith P.QUEUE_COND:P.STATE["queue"].append(new_job)P.QUEUE_COND.notify_all()@@ -406,13 +512,44 @@ def post_queue_remove(h, path, qs, ctype) -> None:h._json({"removed": removed}); return+@post("/queue/reorder")+def post_queue_reorder(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ job_id = (form.get("id", [""])[0] or qs.get("id", [""])[0] or "").strip()+ direction = (form.get("direction", [""])[0] or qs.get("direction", [""])[0] or "").strip()+ if not job_id:+ h._json({"ok": False, "error": "no job id given"}, 400); return+ out = P.queue_move_job(job_id, direction)+ h._json(out, 200 if out.get("ok") else 400)+++@post("/queue/update")+def post_queue_update(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ job_id = (form.get("id", [""])[0] or qs.get("id", [""])[0] or "").strip()+ if not job_id:+ h._json({"ok": False, "error": "no job id given"}, 400); return+ try:+ out = P.queue_update_job(job_id, form)+ except Exception as exc: # noqa: BLE001+ h._json({"ok": False, "error": f"could not update job: {exc}"}, 500)+ return+ h._json(out, 200 if out.get("ok") else 400)++@post("/queue/clear")def post_queue_clear(h, path, qs, ctype) -> None:- with P.LOCK:- count = len(P.STATE["queue"])- P.STATE["queue"] = []+ # SAFETY-9: the reply carries a single-use `undo_token` for exactly the+ # jobs this call removed (see P.queue_clear_with_undo).+ out = P.queue_clear_with_undo()P.persist_queue()- h._json({"cleared": count}); return+ h._json(out); return@post("/queue/pause")@@ -428,6 +565,10 @@ def post_queue_pause(h, path, qs, ctype) -> None:def post_queue_resume(h, path, qs, ctype) -> None:with P.QUEUE_COND:P.STATE["paused"] = False+ # SYS-32: clear the breaker's reason on any resume, manual or not —+ # otherwise a stale "last 3 renders failed" notice would keep+ # showing after the user fixed the cause and pressed Resume.+ P.STATE["paused_reason"] = NoneP.QUEUE_COND.notify_all()P.persist_queue()h._json({"paused": False}); return@@ -460,7 +601,25 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:# the dev transformer.user_prompt = (form.get("prompt", [""])[0] or "").strip()mode = (form.get("mode", ["t2v"])[0] or "t2v").lower()- if mode not in ("t2v", "i2v"):+ # VC-13: default TRUE (unchanged behaviour — Enhance has always+ # translated to English). "0"/"false"/"off" is the explicit opt-out+ # from the prompt box's "Translate to English" toggle, which only+ # shows once a non-Latin-script prompt is typed.+ translate = (form.get("translate", ["1"])[0] or "1").strip().lower() not in ("0", "false", "off")+ source_non_latin = P.prompt_looks_non_latin(user_prompt)+ # A2V (VA-24): the t2v Gemma prompt asks for "describe the scene AND the+ # sound" and readily invents camera-restraint sentences — both wrong on a+ # shot driven by supplied audio (a sound description competes with the+ # real track; a stillness sentence freezes the mouth, the exact bug this+ # week's A2V prompt law exists to prevent). There is no dedicated a2v+ # Gemma system prompt, so this borrows the i2v one (closer: an image+ # anchors the shot, the prompt directs motion, no "and the sound" ask)+ # and then runs the result through the same stillness-cleanup + word-cap+ # every other a2v prompt gets before it reaches the engine.+ a2v_mode = (mode == "a2v")+ if a2v_mode:+ mode = "i2v"+ elif mode not in ("t2v", "i2v"):mode = "t2v"if not user_prompt:h._json({"error": "no prompt provided"}, 400); return@@ -508,15 +667,17 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:# job, so during any render this answers "busy" at once instead of# queueing behind it until the enhance timeout.if not P._GPU_LOCK.acquire(timeout=3.0):- P.push("[enhance] skipped: a render is using the GPU")- h._json({"error": "A render is using the GPU right now — Enhance "- "works again when it finishes."}, 409); return+ # VC-16: name what's actually rendering (and how long, when the+ # priced tier table can say) instead of a flat "a render" refusal.+ reason = P.current_render_busy_reason()+ P.push(f"[enhance] skipped: {reason}")+ h._json({"error": f"{reason} Enhance works again when it finishes."}, 409); returntry:result = P.HELPER.run({"action": "enhance_prompt","id": f"enh-{int(P.time.time()*1000)}","params": {"prompt": user_prompt, "mode": mode, "seed": 10,- "preserve_tokens": preserve_tokens},+ "preserve_tokens": preserve_tokens, "translate": translate},}, timeout=P.PROMPT_ENHANCE_TIMEOUT)except Exception as exc:P.push(f"[enhance] failed: {exc}")@@ -532,6 +693,12 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:if not isinstance(enhanced_raw, str):h._json({"error": "Gemma returned an invalid enhanced prompt"}, 500); returnenhanced = enhanced_raw.strip()+ if a2v_mode:+ # Same law every other a2v prompt goes through (storyboard.a2v_prompt):+ # stillness words out, capped to the direction word budget, the+ # lip-sync contract appended. Gemma's i2v system prompt has no reason+ # to know any of that.+ enhanced = P.storyboard.a2v_prompt(enhanced, silent=False)if not enhanced:h._json({"error": "Gemma returned empty result"}, 500); returnP.push(f"[enhance] → {enhanced[:120]}… ({result.get('elapsed_sec','?')}s)")@@ -539,8 +706,12 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:"ok": True,"original": user_prompt,"enhanced": enhanced,- "mode": mode,+ "mode": "a2v" if a2v_mode else mode,"elapsed_sec": result.get("elapsed_sec"),+ # VC-13: lets the client say "Translated to English." without+ # re-deriving the same script check the toggle's visibility used.+ "source_non_latin": source_non_latin,+ "translated": bool(source_non_latin and translate),})@@ -566,6 +737,11 @@ def post_run(h, path, qs, ctype) -> None:job = P.make_job(form)except P.CharacterRequestError as exc:h._json({"error": str(exc)}, 400); return+ # 4.17 Codex EST-10: a follow-up that can never queue is refused NOW,+ # not discovered in the log after a long Extend render.+ refusal = P.extend_face_fix_refusal(job["params"])+ if refusal:+ h._json({"error": refusal, "code": "pack_missing"}, 400); returnwith P.QUEUE_COND:P.STATE["queue"].append(job)P.QUEUE_COND.notify_all()@@ -600,6 +776,21 @@ def post_queue_facefix(h, path, qs, ctype) -> None:h._json(out, 200 if out.get("ok") else 400)+@post("/queue/sharp_export")+def post_queue_sharp_export(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ src = (form.get("path", [""])[0] or qs.get("path", [""])[0] or "").strip()+ try:+ out = P.queue_sharp_export(src)+ except Exception as exc: # noqa: BLE001+ h._json({"ok": False, "error": f"could not queue Sharp export: {exc}"}, 500)+ return+ h._json(out, 200 if out.get("ok") else 400)++# The chain held /stop as TWO arms split on ?mode=early; one path, one# handler, the same two branches.@post("/stop")@@ -626,6 +817,10 @@ def post_stop(h, path, qs, ctype) -> None:preview_id = P.live_preview_job_id(cur) if cur else ""if not job_id:h._json({"error": "nothing is rendering"}, 404); return+ expect = (qs.get("id", [""])[0] or "").strip()+ if expect and expect != job_id: # SAFETY-3, same as below+ h._json({"ok": False, "stale": True,+ "error": "That render already finished — nothing was stopped."}, 409); returnd = P.live_preview_dir(preview_id)if not d.is_dir():h._json({"error": "this render has no live preview to stop "@@ -636,7 +831,556 @@ def post_stop(h, path, qs, ctype) -> None:h._json({"error": f"could not write the stop sentinel: {exc}"}, 500); returnP.push("Stop early requested — finishing the current step, then stopping.")h._json({"ok": True, "id": job_id}); return- # The HARD stop: kill the helper. Unchanged, and still what the- # Stop button does.- P.stop_current_job()+ # The HARD stop: kill the helper. Still what the Stop button does.+ # SAFETY-3: `id` names the job the user confirmed; if it already+ # finished and another started, nothing is stopped (409, stale).+ expect = (qs.get("id", [""])[0] or "").strip() or None+ if not P.stop_current_job(expect_id=expect):+ h._json({"ok": False, "stale": True,+ "error": "That render already finished — nothing was stopped."}, 409); returnh._json({"ok": True})+++@get("/a2v/estimate")+def get_a2v_estimate(h, parsed) -> None:+ """VA-06: the Audio -> Video footer showed no time estimate at all.+ Priced the same way /oneshot/estimate and /take/estimate already are —+ server-side, from the exact pipeline (Q8 two-stage vs Q4 distilled)+ and the exact clamp run_job_inner applies — so the browser computes+ nothing of its own (Structure Law)."""+ qs = P.parse_qs(parsed.query)+ try:+ frames = int((qs.get("frames", ["121"])[0] or "121"))+ except (TypeError, ValueError):+ frames = 121+ try:+ width = int((qs.get("width", ["0"])[0] or "0")) or None+ except (TypeError, ValueError):+ width = None+ try:+ height = int((qs.get("height", ["0"])[0] or "0")) or None+ except (TypeError, ValueError):+ height = None+ # Fleet first (4.17 integration): the cost model runs ~2x low for a2v+ # against the fleet's own wall clocks. ltx_a2v_price is the one pricing+ # function — the queue row reads it too (4.17 Codex EST-5).+ h._json({"ok": True, **P.ltx_a2v_price(frames, width, height)})+++@get("/keyframe/estimate")+def get_keyframe_estimate(h, parsed) -> None:+ """4.17 Codex EST-7: Keyframe's footer and Shot setup summary read ONE+ price card priced at 5 s on the default canvas, whatever duration and+ aspect the form held. This prices the frames and canvas actually asked+ for (ltx_mode_price_card — clamp, pipeline and fleet range as the+ render and BOOT's first-paint card); the browser prices nothing."""+ qs = P.parse_qs(parsed.query)++ def _int(name: str) -> int | None:+ try:+ return int((qs.get(name, ["0"])[0] or "0")) or None+ except (TypeError, ValueError):+ return None+ card = P.ltx_mode_price_card("keyframe", frames=_int("frames"),+ width=_int("width"), height=_int("height"))+ if not card:+ h._json({"ok": False, "error": "keyframe is not available on this Mac"}); return+ h._json({"ok": True, **card})+++# ====== Lip-sync keyframe helpers (VA "Continue the song") =================+# Both routes are pure reads (plus one PNG write for the anchor image) — no+# job queued, no GPU lock taken. See mlx_ltx_panel.py's mouth_open_ratio /+# find_closed_mouth_frame / extract_frame_png for the cv2 mechanics, and the+# "Keyframe + lip-sync" section of report_video-advanced.txt for why a+# lip-sync anchor is frame_idx-0-only and closed-mouth-only.+def _lipsync_media_path(raw: str):+ """LIPSYNC-1: the lip-sync helpers open a picture/clip by path and write a+ frame of it into uploads (served by /image). Same boundary as /image:+ resolve (symlinks and .. included) and require the file to live under+ outputs, uploads or state — anything else would copy private media out.+ Returns the resolved path, or None when it is outside the roots."""+ try:+ media = P.Path(raw).resolve()+ roots = [P.OUTPUT.resolve(), P.UPLOADS.resolve(), P.STATE_DIR.resolve()]+ except Exception: # noqa: BLE001+ return None+ if not any(media.is_relative_to(r) for r in roots):+ return None+ return media+++@post("/a2v/mouth_check")+def post_a2v_mouth_check(h, path, qs, ctype) -> None:+ """Open-mouth warning for a picked lip-sync start frame. The 2026-09-22+ anchor lesson: a still with the mouth open, pinned as a strength-1.0+ frame-0 anchor, freezes the performance open-mouthed for the whole clip —+ this is the one check that catches it before a 10-25 minute render."""+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ img = (form.get("image", [""])[0] or "").strip()+ if not img:+ h._json({"error": "image not found"}, 400); return+ media = _lipsync_media_path(img)+ if media is None:+ h._json({"error": "pick a picture from your uploads or outputs"}, 403); return+ if not media.is_file():+ h._json({"error": "image not found"}, 400); return+ img = str(media)+ ratio = P.mouth_open_ratio(img)+ if ratio is None:+ # No face found, or cv2 unavailable — not a verdict either way.+ h._json({"ok": True, "measured": False}); return+ h._json({"ok": True, "measured": True, "ratio": round(ratio, 4),+ "open": ratio > P.MOUTH_OPEN_WARN,+ "threshold": P.MOUTH_OPEN_WARN})+++@post("/a2v/continue_song")+def post_a2v_continue_song(h, path, qs, ctype) -> None:+ """"Continue the song": scans the last ~0.5s of a finished a2v clip for+ its most-closed-mouth frame, saves that frame as a new upload, and+ returns where in the song the NEXT clip should start reading. The+ picture is deliberately NOT the clip's literal last frame — a2v's own+ last frame is usually mid-syllable, and anchoring the next clip there+ pins an open mouth for its whole duration (see the "Keyframe ++ lip-sync" section of report_video-advanced.txt). Queues nothing; the+ caller uses the returned anchor_image + audio_start_time to fill the+ next lip-sync job."""+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ src = (form.get("clip", [""])[0] or "").strip()+ if not src:+ h._json({"error": "clip not found"}, 400); return+ media = _lipsync_media_path(src)+ if media is None:+ h._json({"error": "only a clip from your outputs or uploads can be continued"}, 403); return+ if not media.is_file():+ h._json({"error": "clip not found"}, 400); return+ src = str(media)+ hit = P.find_closed_mouth_frame(src)+ if hit is None:+ h._json({"error": "could not find a face in the last half-second of "+ "this clip — pick a start frame by hand instead."},+ 422); return+ P.UPLOADS.mkdir(parents=True, exist_ok=True)+ dest = P.UPLOADS / f"{int(P.time.time() * 1000)}_continue_anchor.png"+ if not P.extract_frame_png(src, hit["time_s"], dest):+ h._json({"error": "could not extract the anchor frame"}, 500); return+ # Where the NEXT clip should start reading the song: the source clip's+ # own offset into the file, plus how far into the CLIP the anchor sits+ # (the anchor is picked from the last ~0.5s, not necessarily the very+ # last frame, so this is a few frames short of "start + full duration").+ src_start = 0.0+ sidecar_path = P.Path(str(src) + ".json")+ if sidecar_path.exists():+ try:+ meta = P.json.loads(sidecar_path.read_text())+ src_start = float((meta.get("params") or {}).get("audio_start_time") or 0.0)+ except Exception: # noqa: BLE001+ src_start = 0.0+ h._json({+ "ok": True,+ "anchor_image": str(dest),+ "anchor_time_s": hit["time_s"],+ "anchor_openness": hit["openness"],+ "audio_start_time": round(src_start + hit["time_s"], 3),+ })+++@get("/ltx/windows_plan")+def get_ltx_windows_plan(h, parsed) -> None:+ """VA-18: the REAL per-window schedule (start_sec/end_sec, count), so the+ Windows UI can render one labelled box per window ("Window 2 · 0:05-0:09")+ instead of a free-text textarea whose first typed line silently replaces+ the main prompt (ltx_windows.window_prompts: index 0 blank means "use the+ main prompt" — the UI used to invite a user to put THEIR first line+ there). Pure read: ltx_windows.plan_windows is a pure function, no job,+ no render."""+ qs = parse_qs(parsed.query)+ try:+ frames = int((qs.get("frames", ["121"])[0] or "121"))+ except (TypeError, ValueError):+ frames = 121+ frames = max(1, frames)+ import ltx_windows as _lw # noqa: PLC0415+ try:+ plan = _lw.plan_windows(frames)+ except ValueError as exc:+ h._json({"error": str(exc)}, 400); return+ h._json({+ "ok": True,+ "count": plan["count"],+ "windows": [{"index": w["index"], "start_sec": w["start_sec"],+ "end_sec": w["end_sec"]} for w in plan["windows"]],+ "notes": plan["notes"],+ })+++@post("/a2v/prompt_check")+def post_a2v_prompt_check(h, path, qs, ctype) -> None:+ """Live stillness-phrase check for the lip-sync prompt box (VA-05, the+ client half — the server ALWAYS applies storyboard.a2v_prompt() before a+ render regardless of what this endpoint says, so a client that never+ calls this is still safe). Pure read: no job, no render."""+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ prompt = (form.get("prompt", [""])[0] or "")+ problems = P.storyboard.a2v_stillness_problems(prompt)+ h._json({+ "ok": True,+ "problems": problems,+ "cleaned": P.storyboard.a2v_clean_prompt(prompt) if problems else prompt,+ })+++# VC-05 / H3-11: the third stop shape, next to hard-kill and stop-early.+# Neither of those is right mid-chain — a hard kill loses the part/window+# rendering right now AND every part/window already finished, and stop-early+# only reaches through a live preview. This sets a flag the render loop+# checks at each PART/WINDOW BOUNDARY (never mid-part, never mid-window):+# what's in flight finishes (or is asked to stop as cleanly as the engine+# allows), the loop stops there instead of starting the next one, and+# whatever is done gets published — a clean finish, not a failure.+#+# Two shapes share this one endpoint and one flag:+# - a One Shot (params.take): run_take_job_inner joins the finished parts.+# - a plain H3 chained render (no take, 2+ windows): run_h3_job_inner asks+# the engine's own process group to stop at the next window boundary and+# publishes whatever landed on disk, honestly labelled if the engine+# can't hand back a clean partial.+# Refused outside both so the button can't appear to do something on an+# ordinary single-shot render.+@post("/stop/after_part")+def post_stop_after_part(h, path, qs, ctype) -> None:+ # SAFETY-3: `id` = the job whose dialog the user confirmed. Checked in+ # the same LOCK section that sets the flag, so a dialog left open while+ # that job finished can never flag its successor.+ expect = (qs.get("id", [""])[0] or "").strip()+ with P.LOCK:+ cur = P.STATE.get("current")+ if cur is None:+ h._json({"error": "nothing is rendering"}, 404); return+ if expect and cur.get("id") != expect:+ h._json({"ok": False, "stale": True,+ "error": "That render already finished — nothing was stopped."}, 409); return+ cur_params = cur.get("params") or {}+ is_take = bool(cur_params.get("take"))+ window_total = (cur.get("progress") or {}).get("window_total") or 1+ is_h3_chain = (not is_take+ and (cur_params.get("engine") or "").strip().lower() == "h3"+ and window_total > 1)+ if not is_take and not is_h3_chain:+ h._json({"error": "this render has no parts or windows to stop "+ "between — use Stop."}, 409); return+ if is_h3_chain and not P.H3_RUNNER_KEEPS_WINDOWS_ON_STOP:+ # 4.17 Codex review: the H3 runner stitches and writes its ONE+ # output only after the last window (generate_staged.py), so a+ # SIGTERM between windows leaves nothing to publish — promising+ # "keep what's done" would throw the finished windows away.+ h._json({"error": "this H3 engine can't keep finished windows when "+ "stopped mid-chain yet — use Stop, or let it finish."},+ 409); return+ cur["stop_after_part"] = True+ job_id = cur.get("id")+ P.push("Stop-after-this-part requested — finishing what's in progress, "+ "then keeping what's done." if is_take else+ "Stop-after-this-window requested — asking the engine to stop "+ "before the next window, then keeping what rendered.")+ h._json({"ok": True, "id": job_id, "shape": "take" if is_take else "h3_chain"})+++# VC-03: the #1 creator gesture, one click. Sourced from the clip's own+# sidecar on disk (not job history, which rotates) so New Take works on any+# clip still in the gallery, not only a recent one. The ONLY thing this+# changes from the original recipe is the seed — same prompt, size, quality,+# LoRAs, character, engine — so what comes back answers "another one like+# this" rather than "something different." Shared by the board's own New+# Take (FILM-22): both read a sidecar's `params` and replay it with seed=-1+# through this one endpoint, so the two features can't drift into two+# different ideas of what "the same recipe" means.+#+# A One Shot clip (params.take) gets the same answer at the SHOT level: the+# whole take re-runs from part 1 with a fresh seed, same beats/camera/lock/+# handoff — not a per-part reseed, which would need each part's own retake+# logic to agree on what "the same take" means and wasn't verified. See the+# take-rebuild block below for why the sidecar's take block can't be reused+# verbatim.+@post("/queue/newtake")+def post_queue_newtake(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ raw = (form.get("path", [""])[0] or qs.get("path", [""])[0] or "").strip()+ if not raw:+ h._json({"error": "path required"}, 400); return+ try:+ media = P.Path(raw).resolve()+ except Exception:+ h._json({"error": "bad path"}, 400); return+ try:+ roots = [P.OUTPUT.resolve(), P.UPLOADS.resolve()]+ except Exception:+ roots = []+ if not any(media.is_relative_to(r) for r in roots):+ h._json({"error": "path must resolve under outputs/ or uploads/"}, 404); return+ sidecar = media.with_suffix(media.suffix + ".json")+ if not sidecar.is_file():+ h._json({"error": "no sidecar for this clip — nothing to replay"}, 404); return+ try:+ side = P.json.loads(sidecar.read_text(encoding="utf-8"))+ except (OSError, P.json.JSONDecodeError):+ h._json({"error": "sidecar is unreadable"}, 500); return+ src_params = side.get("params") or {}+ if not src_params:+ h._json({"error": "sidecar has no params to replay"}, 400); return+ new_params = dict(src_params)+ stored_take = new_params.get("take")+ if stored_take:+ # A One Shot's New Take means what it means everywhere else: the same+ # recipe, a fresh seed, re-run from scratch — not a per-part reseed+ # (each part's own seed is derived by run_take_job_inner from the+ # parent's, and letting that reroll independently was the half-+ # verified idea this endpoint used to refuse over). The sidecar's+ # `take.parts`/`take.beats` are POST-COMPLETION fields — parts is the+ # rendered file list, beats is the resolved text list — not the+ # beat-index/part-count shape run_take_job_inner needs to start a+ # fresh take, so that shape is rebuilt from take_plan() (exactly what+ # a fresh One Shot submit does) rather than replayed as-is.+ fresh = P.take_plan(stored_take.get("seconds"), stored_take.get("engine"))+ if fresh is None:+ h._json({"error": "This One Shot's length isn't valid anymore — "+ "use Params, then Generate, instead."}, 400); return+ stored_beat_texts = stored_take.get("beats")+ if not isinstance(stored_beat_texts, list):+ # SAFETY-11: a take joined from a stopped One Shot before this fix+ # kept the INPUT shape — `beats` a count, the text in+ # `beat_prompts` — and New Take dropped every written beat.+ stored_beat_texts = stored_take.get("beat_prompts")+ fresh["beat_prompts"] = (list(stored_beat_texts)+ if isinstance(stored_beat_texts, list) else [])+ fresh["light_lock"] = stored_take.get("light_lock") or ""+ fresh["retake"] = stored_take.get("retake", True) is not False+ fresh["camera"] = stored_take.get("camera") or ""+ fresh["handoff"] = stored_take.get("handoff") or "last"+ new_params["take"] = fresh+ new_params["seed"] = "-1"+ new_params.pop("seed_used", None)+ new_params["open_when_done"] = False+ new_params.pop("face_fix_result", None)+ new_params["source"] = "new_take"+ new_job = {+ "id": P._new_job_id(),+ "status": "queued",+ "queued_at": P.time.strftime("%Y-%m-%d %H:%M:%S"),+ "started_at": None, "finished_at": None, "elapsed_sec": None,+ "params": new_params, "raw_path": None, "output_path": None, "error": None,+ }+ with P.QUEUE_COND:+ P.STATE["queue"].append(new_job)+ P.QUEUE_COND.notify_all()+ P.persist_queue()+ # The real elapsed time of the clip being re-rolled — the honest ETA for+ # "about the same again", cheaper than re-deriving one from the tier table.+ h._json({"ok": True, "id": new_job["id"], "eta_sec": side.get("elapsed_sec")})+++# VC-06's undo path. `{"token": ...}` (what the panel sends) restores the+# exact jobs /queue/clear removed, under their original ids — see+# P.queue_clear_with_undo for why the browser's own snapshot was wrong.+# `{"jobs": [{"params": ...}, ...]}` still re-queues arbitrary params, in+# order, with fresh ids (P._new_job_id — never a clock + small random suffix,+# which collided inside a 200-job restore). Accepts a JSON body so a queue of+# arbitrary size/shape round-trips without URL-length limits.+@post("/queue/restore")+def post_queue_restore(h, path, qs, ctype) -> None:+ try:+ length = int(h.headers.get("Content-Length") or "0")+ except ValueError:+ h._json({"error": "invalid Content-Length"}, 400); return+ if length <= 0:+ h._json({"error": "Content-Length required for JSON body"}, 411); return+ if length > 2_000_000:+ h._json({"error": "body too large (max 2000000 bytes)"}, 413); return+ try:+ payload = P.json.loads(h.rfile.read(length).decode() or "{}")+ except (P.json.JSONDecodeError, UnicodeDecodeError):+ h._json({"error": "invalid JSON body"}, 400); return+ # SAFETY-8/9/10: the Undo toast sends the token /queue/clear returned —+ # the server puts back exactly the jobs it removed, original ids and+ # all, once. The `jobs` list form below stays for API callers.+ token = payload.get("token") if isinstance(payload, dict) else None+ if token:+ out = P.queue_restore_cleared(str(token))+ if not out.get("ok"):+ h._json({"ok": False, "error": out.get("error")}, out.get("status") or 410); return+ P.persist_queue()+ h._json(out); return+ jobs = payload.get("jobs") if isinstance(payload, dict) else None+ if not isinstance(jobs, list) or not jobs:+ h._json({"error": "jobs: [...] required"}, 400); return+ if len(jobs) > 200:+ h._json({"error": "too many jobs to restore at once"}, 400); return+ restored = []+ with P.QUEUE_COND:+ for entry in jobs:+ params = entry.get("params") if isinstance(entry, dict) else None+ if not isinstance(params, dict) or not params:+ continue+ new_job = {+ "id": P._new_job_id(),+ "status": "queued",+ "queued_at": P.time.strftime("%Y-%m-%d %H:%M:%S"),+ "started_at": None, "finished_at": None, "elapsed_sec": None,+ "params": dict(params), "raw_path": None, "output_path": None, "error": None,+ }+ P.STATE["queue"].append(new_job)+ restored.append(new_job["id"])+ if restored:+ P.QUEUE_COND.notify_all()+ P.persist_queue()+ h._json({"ok": True, "restored": len(restored), "ids": restored})+++# VA-17: the two ways back for a One Shot that stopped or failed mid-chain.+# Both read the `one_shot_unfinished` block run_take_job_inner's recovery+# path stashes on the LAST finished part's sidecar — see the except clause+# there. `path` names that part (the un-hidden card the user is looking at).+def _load_take_manifest(h, form_or_qs) -> dict | None:+ raw = (form_or_qs.get("path", [""])[0] or "").strip()+ if not raw:+ h._json({"error": "path required"}, 400); return None+ try:+ media = P.Path(raw).resolve()+ except Exception:+ h._json({"error": "bad path"}, 400); return None+ try:+ roots = [P.OUTPUT.resolve(), P.UPLOADS.resolve()]+ except Exception:+ roots = []+ if not any(media.is_relative_to(r) for r in roots):+ h._json({"error": "path must resolve under outputs/ or uploads/"}, 404); return None+ sidecar = media.with_suffix(media.suffix + ".json")+ if not sidecar.is_file():+ h._json({"error": "no sidecar for this part"}, 404); return None+ try:+ side = P.json.loads(sidecar.read_text(encoding="utf-8"))+ except (OSError, P.json.JSONDecodeError):+ h._json({"error": "sidecar is unreadable"}, 500); return None+ manifest = side.get("one_shot_unfinished")+ if not manifest or not manifest.get("outs"):+ h._json({"error": "this clip has no unfinished One Shot to resume — "+ "it may already have been joined or resumed."}, 404); return None+ return manifest+++@post("/take/resume")+def post_take_resume(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ manifest = _load_take_manifest(h, form)+ if manifest is None:+ return+ take = dict(manifest.get("take") or {})+ take["_resume"] = {+ "outs": manifest.get("outs") or [],+ # SAFETY-5/6/12: the rendered parts' own files, their seeds, and the+ # speech handoff's pending tail; the handoff frame is rebuilt by the+ # take itself from the last part, so `last_png` is informational.+ "visible": manifest.get("visible") or [],+ "part_seeds": manifest.get("part_seeds"),+ "tail_wav": manifest.get("tail_wav"),+ "last_png": manifest.get("last_png"),+ "start_k": manifest.get("done_parts"),+ }+ base_params = dict(manifest.get("p") or {})+ base_params["take"] = take+ base_params["label"] = manifest.get("label") or base_params.get("label") or ""+ base_params["open_when_done"] = False+ new_job = {+ "id": P._new_job_id(),+ "status": "queued",+ "queued_at": P.time.strftime("%Y-%m-%d %H:%M:%S"),+ "started_at": None, "finished_at": None, "elapsed_sec": None,+ "params": base_params, "raw_path": None, "output_path": None, "error": None,+ }+ with P.QUEUE_COND:+ P.STATE["queue"].append(new_job)+ P.QUEUE_COND.notify_all()+ P.persist_queue()+ h._json({"ok": True, "id": new_job["id"],+ "resumed_from_part": manifest.get("done_parts"),+ "total_parts": manifest.get("total_parts")})+++@post("/take/join_partial")+def post_take_join_partial(h, path, qs, ctype) -> None:+ _rb = h._read_form_body()+ if _rb is None:+ return+ body, form = _rb+ manifest = _load_take_manifest(h, form)+ if manifest is None:+ return+ outs = [str(o) for o in (manifest.get("outs") or []) if o and P.Path(o).is_file()]+ if not outs:+ h._json({"error": "none of this take's parts are still on disk"}, 404); return+ label = manifest.get("label") or ""+ prompt = ((manifest.get("p") or {}).get("prompt")) or ""+ take = manifest.get("take") or {}+ final = P._unique_output_path(+ P.OUTPUT,+ P._descriptive_filename(label, prompt, fallback="take")+ + f"_take{take.get('seconds', len(outs) * 10)}s_partial")+ # SAFETY-7: this join runs on the HTTP thread, outside the queue. It used+ # `mux_pgid` — the generation queue's slot — so a join overlapping a+ # queued render's encode overwrote that render's registration (Stop then+ # killed the join and left the encode running, unstoppable). It has its+ # own slot now, and one join at a time owns it.+ if not _TAKE_JOIN_LOCK.acquire(blocking=False):+ h._json({"error": "Another “Join what’s done” is still running — "+ "try again when it finishes."}, 409); return+ try:+ P._join_take_parts(str(P.FFMPEG), outs, final, job=None,+ pgid_key="take_join_pgid")+ except Exception as exc: # noqa: BLE001+ h._json({"error": f"join failed: {exc}"}, 500); return+ finally:+ _TAKE_JOIN_LOCK.release()+ # SAFETY-11: the joined clip's take block has the COMPLETED shape (what a+ # finished One Shot writes): `beats` is the beat TEXT, not the manifest's+ # input-shaped count — New Take and Load Params read it as text.+ beat_texts = take.get("beat_prompts") if isinstance(take.get("beat_prompts"), list) \+ else (take.get("beats") if isinstance(take.get("beats"), list) else [])+ seeds = manifest.get("part_seeds") if isinstance(manifest.get("part_seeds"), list) else []+ done_take = {**{k: v for k, v in take.items() if k != "_resume"},+ "beats": list(beat_texts), "parts": outs, "stopped_early": True,+ "joined_partial": True,+ "parts_meta": [{"seed_used": sd} for sd in seeds]}+ side = {+ "output": str(final), "raw_output": str(final), "native_output": str(final),+ "mode": (manifest.get("p") or {}).get("mode", "t2v"),+ "engine": manifest.get("engine"), "prompt": prompt,+ "label": f"{label or 'one shot'} · {len(outs)} of {manifest.get('total_parts')} parts (stopped early)",+ "take": done_take,+ "params": {**(manifest.get("p") or {}), "take": done_take},+ }+ P.write_sidecar(final.with_suffix(final.suffix + ".json"), side)+ # The joined file is now the canonical output; the raw parts go back to+ # being hidden working files, same as a take that finished normally —+ # the rendered cards (SAFETY-5) as well as any speech intermediates.+ for o in dict.fromkeys(outs + [str(v) for v in (manifest.get("visible") or []) if v]):+ try:+ P.set_hidden(o, True)+ except Exception: # noqa: BLE001+ pass+ h._json({"ok": True, "output": str(final), "parts_joined": len(outs)})diff --git a/panel/routes_train.py b/panel/routes_train.pyindex b9bead4..69366cc 100644--- a/panel/routes_train.py+++ b/panel/routes_train.py@@ -169,7 +169,12 @@ def get_train_file(h, parsed) -> None:# ====== Train Character — start training (enqueue a mode='train' job)@post("/train/start")def post_train_start(h, path, qs, ctype) -> None:- P._analytics_feature("train_start")+ # SYS-41: this used to fire train_start unconditionally, before the RAM+ # refusal a few lines down — so a Mac under TRAIN_MIN_RAM_GB clicking+ # Start (SYS-03: now gated at the tab entry for the UI, but this route+ # is also reachable directly) counted as a "train start" the fleet+ # dashboard could not tell apart from a real attempt. Moved past the+ # refusal; the refusal itself now counts separately as train_refused._rb = h._read_form_body()if _rb is None:return@@ -178,9 +183,11 @@ def post_train_start(h, path, qs, ctype) -> None:if not train_job_id:h._json({"error": "train_job_id required"}, 400); returnif float(P.SYSTEM_RAM_GB or 0) and float(P.SYSTEM_RAM_GB) < P.TRAIN_MIN_RAM_GB:+ P._analytics_feature("train_refused", "ram")h._json({"error": f"Training needs at least {P.TRAIN_MIN_RAM_GB} GB of memory; this Mac has "f"{float(P.SYSTEM_RAM_GB):.0f} GB. On this machine the trainer runs out of memory "f"before it finishes."}, 409); return+ P._analytics_feature("train_start")try:train_job_id = P._safe_job_id(train_job_id)except ValueError as e:@@ -683,10 +690,13 @@ def post_train_upload(h, path, qs, ctype) -> None:h._json({"error": "no filename"}, 400); returnext = P.Path(fld.filename).suffix.lower()original_stem = P.Path(fld.filename).stem- if ext not in P.TRAIN_IMAGE_EXTS and ext not in P.TRAIN_CAPTION_EXTS:+ # SYS-02: TRAIN_IMAGE_UPLOAD_EXTS also accepts HEIC/HEIF/AVIF — the+ # image branch below converts them to JPEG before writing to disk,+ # so TRAIN_IMAGE_EXTS (what actually lands in images_dir) is unchanged.+ if ext not in P.TRAIN_IMAGE_UPLOAD_EXTS and ext not in P.TRAIN_CAPTION_EXTS:h._json({"error": f"unsupported file type {ext!r}; want one of "- f"{sorted(P.TRAIN_IMAGE_EXTS | P.TRAIN_CAPTION_EXTS)}"+ f"{sorted(P.TRAIN_IMAGE_UPLOAD_EXTS | P.TRAIN_CAPTION_EXTS)}"}, 400)return@@ -739,13 +749,23 @@ def post_train_upload(h, path, qs, ctype) -> None:}, 409)return+ # SYS-01/SYS-02: normalize before it lands in the dataset — EXIF+ # orientation applied + stripped, HEIC/HEIF/AVIF converted to JPEG.+ # Without this the trainer's own thumbnails (which promise "the 1:1+ # centre-crop the trainer will see") looked upright in the browser+ # while the trainer centre-cropped sideways faces from the same+ # bytes, and a HEIC drop silently vanished from the grid.+ raw = fld.file.read()+ raw, out_ext, norm_err = P.normalize_ingested_image_bytes(raw, fld.filename)+ if norm_err:+ h._json({"error": norm_err}, 400); return# Numeric ordering: char_001.jpg, char_002.jpg, ...# Lets the lab side load them in a deterministic order.next_idx = len(existing) + 1- saved_name = f"char_{next_idx:03d}{ext}"+ saved_name = f"char_{next_idx:03d}{out_ext}"saved_stem = f"char_{next_idx:03d}"dest = images_dir / saved_name- dest.write_bytes(fld.file.read())+ dest.write_bytes(raw)# Record original_stem → saved_stem so a later caption with# the original filename pairs on arrival.P._train_set_caption_map_entry(ds, original_stem, saved_stem)diff --git a/patch_ltx_codec.py b/patch_ltx_codec.pyindex f04410b..99e0c57 100644--- a/patch_ltx_codec.py+++ b/patch_ltx_codec.py@@ -34,7 +34,7 @@ The helper already calls the new API defensively (`hasattr` guard onRe-implementing them against the pinned tag would only re-introduce divergence — thewhole point of the catch-up was to let pinned-upstream own this behaviour.-What REMAINS is the one preference upstream doesn't share:+What REMAINS is two preferences upstream doesn't share:1. Output codec. Upstream emits `yuv420p crf 18` — 4:2:0 chroma subsamplingproduces visible JPEG-style block artifacts on faces / skin. We patch to@@ -43,8 +43,23 @@ What REMAINS is the one preference upstream doesn't share:without downloading the whole clip). Override via `LTX_OUTPUT_PIX_FMT` /`LTX_OUTPUT_CRF`.-If a future pin restructures `decode_and_stream`'s ffmpeg line, this fails-LOUD (exit non-zero) rather than silently shipping a 4:2:0 install.+2. Gemma truncation direction (VC-14, 2026-09-29). `GemmaEncoder.tokenize()`+ left-pads to `max_length` and, on an over-length prompt, kept the LAST+ `max_length` tokens ("truncate from the left"). That reads as a sane+ default of left-padding for the common case (nothing to trim), but on the+ watchdog fallback path (`GEMMA_FALLBACK_MAX_LENGTH = 256`, armed on chips+ whose Metal watchdog kills the full 1024-token encode — typically the+ low-end Macs) it silently drops the BEGINNING of any prompt over 256+ tokens, i.e. the subject. We patch to keep the first `max_length` tokens+ instead — the model still sees a coherent, if shortened, prompt starting+ from its subject rather than a random tail. Optional: a future pin may+ restructure this method, and losing the fix only degrades long-prompt+ quality on the fallback path, so a drift here logs a note and lets+ install continue rather than blocking it (unlike the codec patch above).++If a future pin restructures `decode_and_stream`'s ffmpeg line, the codec+patch fails LOUD (exit non-zero) rather than silently shipping a 4:2:0+install.Safe to re-run — checks for its marker before touching anything."""@@ -151,6 +166,25 @@ PATCH_CODEC_NEW = ()+# ---- Patch: keep the SUBJECT, not the tail, when a prompt is truncated ------+# VC-14. `tokenize()` left-pads to max_length; on the fallback path+# (256 tokens, armed by the Metal-watchdog encode-length guard) an+# over-length prompt kept its LAST 256 tokens, dropping the subject the+# user actually wrote first. Keep the first max_length tokens instead.+PATCH_GEMMA_TRUNCATE_OLD = (+ ' if len(tokens) > max_length:\n'+ ' tokens = tokens[-max_length:] # Keep last tokens (left-pad = truncate from left)'+)+PATCH_GEMMA_TRUNCATE_NEW = (+ ' if len(tokens) > max_length:\n'+ ' # PATCHED (LTX23MLX, VC-14): keep the FIRST max_length tokens — the\n'+ ' # subject of the prompt is almost always near the start, and on the\n'+ ' # watchdog fallback path (256 tokens) the old "keep last" behaviour\n'+ ' # silently dropped it on any prompt over ~256 tokens.\n'+ ' tokens = tokens[:max_length] # Keep first tokens (keeps the subject)'+)++# Outcome codes for apply_patch — three-valued (vs the old True/False) so# main() can distinguish a genuinely missing target / drifted upstream from# the no-op "already patched" case. Without this distinction the install@@ -255,7 +289,7 @@ def _shout(*lines: str) -> None:def main() -> int:- print("Applying LTX23MLX codec patch (ltx-2-mlx v0.14.19+ltx25.6 — only the codec edit remains):")+ print("Applying LTX23MLX patches (ltx-2-mlx v0.14.19+ltx25.7 — codec + Gemma truncation):")# `upgrade_marker="+faststart"` lets us upgrade installs where the# earlier version of this patch was applied (LTX_OUTPUT_PIX_FMT marker@@ -309,6 +343,24 @@ def main() -> int:print(f"Done — codec patch applied and verified in {verify}")else:print(f"Codec patch already applied and verified in {verify}")++ # Gemma truncation direction (VC-14) — optional: a drift here only+ # degrades long-prompt quality on the fallback path, never breaks a+ # render, so it logs a note and lets install/update continue rather+ # than failing loud like the codec patch above.+ gemma_target = _find("ltx_core_mlx/text_encoders/gemma/encoders/base_encoder.py")+ gemma_outcome = apply_patch(+ gemma_target, PATCH_GEMMA_TRUNCATE_OLD, PATCH_GEMMA_TRUNCATE_NEW,+ marker="VC-14", label="gemma-truncate (keep subject, not tail)",+ )+ if gemma_outcome in (OUTCOME_DRIFT, OUTCOME_MISSING):+ print(+ f" [gemma-truncate] note: could not apply ({gemma_outcome}) — "+ f"the fallback encode path will keep truncating from the tail "+ f"until this is re-checked against the installed ltx-2-mlx pin.",+ file=sys.stderr,+ )+return 0diff --git a/pinokio.js b/pinokio.jsindex 8a9fbf7..e74a91b 100644--- a/pinokio.js+++ b/pinokio.js@@ -51,6 +51,15 @@ function musicCapable() {try { return os.totalmem() >= 24 * 1000 * 1000 * 1000 } catch (e) { return false }}+// SYS-18: the Q8 download entry below was offered on EVERY Mac regardless+// of RAM — 30 GB of disk and bandwidth for a feature the panel's own tier+// table (SYSTEM_CAPS["allows_q8"], mlx_ltx_panel.py) refuses under 48 GB+// (the base/"Compact" tier). Same threshold, same fail-closed shape as+// h3Capable()/musicCapable() above.+function q8Capable() {+ try { return os.totalmem() >= 48 * 1000 * 1000 * 1000 } catch (e) { return false }+}+function getInstallRoot(info) {// Pinokio's `info.path` API has shifted across versions:// - older Pinokio: info.path is a STRING property (the install dir itself)@@ -594,7 +603,7 @@ module.exports = {// Escape hatch. This branch used to offer no Reset at all, so a user// whose install died before the venv existed had nothing to click except// the thing that kept failing.- if (install_attempted) m.push({ icon: "fa-regular fa-circle-xmark", text: "Reset", href: "reset.js" })+ if (install_attempted) m.push({ icon: "fa-regular fa-circle-xmark", text: "Reset engine (keeps models & outputs)", href: "reset.js" })return m}@@ -615,7 +624,7 @@ module.exports = {if (has_uploads) m.push({ icon: "fa-solid fa-image", text: "Uploads", href: "panel_uploads?fs=true" })pushLtxRepair(m)pushH3Recovery(m)- m.push({ icon: "fa-regular fa-circle-xmark", text: "Reset", href: "reset.js" })+ m.push({ icon: "fa-regular fa-circle-xmark", text: "Reset engine (keeps models & outputs)", href: "reset.js" })return m}@@ -657,7 +666,7 @@ module.exports = {{ icon: "fa-solid fa-cube", text: "Models", href: "mlx_models?fs=true" },{ icon: "fa-solid fa-image", text: "Uploads", href: "panel_uploads?fs=true" },)- if (!q8_ready) {+ if (!q8_ready && q8Capable()) {// ~30 GB and what it actually buys on 2.5: trained characters and voices.// High additionally needs the separate 29.5 GB add-on, which is offered// in Settings -> Models rather than here — one menu entry, one download.@@ -675,7 +684,12 @@ module.exports = {// failed pip step, or a pre-3.2.1 install that hasn't updated). Renamed// off "Qwen-Image-Edit" — it enables Ideogram 4 too (cocktailpeanut's// confusion: installing "Qwen" to use Ideogram).- baseMenu.push({ icon: "fa-solid fa-images", text: "Reinstall image engines (Ideogram 4 + Qwen-Edit)", href: "install_qwen.js" })+ // SYS-30: "Reinstall" implies it was here before and broke — on a+ // fresh install that never fetched this pack, that's simply untrue.+ // qwen_ready collapses both cases (never installed vs. broken) to+ // the same boolean, so the honest word covers both without+ // guessing which one this install is.+ baseMenu.push({ icon: "fa-solid fa-images", text: "Install/repair image engines (Ideogram 4 + Qwen-Edit)", href: "install_qwen.js" })}baseMenu.push(...musicMenu())// Second VIDEO engine — joint picture + dialogue + sound. Opt-in only:@@ -697,7 +711,7 @@ module.exports = {}baseMenu.push({ icon: "fa-solid fa-rotate", text: "Update", href: "update.js" },- { icon: "fa-regular fa-circle-xmark", text: "Reset", href: "reset.js" },+ { icon: "fa-regular fa-circle-xmark", text: "Reset engine (keeps models & outputs)", href: "reset.js" },)return baseMenu}diff --git a/scripts/extract_panel_js.py b/scripts/extract_panel_js.pyindex 2f4569f..a61974c 100644--- a/scripts/extract_panel_js.py+++ b/scripts/extract_panel_js.py@@ -35,6 +35,82 @@ class ExtractError(RuntimeError):pass+# Characters after which a `/` most likely OPENS a regex literal rather than+# meaning division. Not exhaustive JS grammar — just enough for this file's+# own coding style (a regex almost always follows `(`, `,`, `=`, `||`, `&&`,+# or sits at the start of a line/statement).+_REGEX_PRECEDERS = set("([{,;:=&|!?+-~^%<>*")+_REGEX_KEYWORDS = {"return", "typeof", "instanceof", "in", "of", "new",+ "delete", "void", "throw", "case", "yield", "else", "do"}+++def _looks_like_regex_start(s: str, j: int) -> bool:+ """Heuristic: does the `/` at s[j] open a regex literal?++ Found the hard way (VC-08): `friendlyJobError`'s first branch tests+ `/music engine isn't installed|.../i.test(raw)` — a regex literal+ containing an apostrophe ("isn't"). The brace-matching loop below only+ ever tracked `"`, `'` and `` ` `` as string delimiters; it had no idea+ a `/.../ ` regex literal exists, so it read that apostrophe as the+ START of a fake single-quoted string, which then swallowed the next+ real `'` (an unrelated string's OPENING quote) as its own close —+ desynchronising every string/brace boundary for the rest of the+ function. The corruption is silent: depth still reaches exactly 0+ eventually, just at the wrong `}`, so a change miles away that shifts+ the alignment can suddenly truncate an unrelated function with no+ error at the call site that owns the regex — the way editing the+ UNRELATED sigkill branch below it broke this function's extraction.+ """+ k = j - 1+ while k >= 0 and s[k] in " \t\r\n":+ k -= 1+ if k < 0:+ return True # start of the scanned region — nothing before it+ prev = s[k]+ if prev in _REGEX_PRECEDERS:+ return True+ if prev.isalnum() or prev in "_$":+ word_start = k+ while word_start >= 0 and (s[word_start].isalnum() or s[word_start] in "_$"):+ word_start -= 1+ return s[word_start + 1:k + 1] in _REGEX_KEYWORDS+ return False+++def _skip_regex_literal(s: str, j: int) -> int:+ """`s[j] == '/'` opens a regex literal — return the index of its LAST+ character (the trailing flag letters, if any), so the caller's `j += 1`+ lands just past it. Handles `\\`-escapes and `[...]` character classes,+ where an unescaped `/` does not terminate the literal."""+ k = j + 1+ in_class = False+ while k < len(s):+ ch = s[k]+ if ch == "\\":+ k += 2+ continue+ if in_class:+ if ch == "]":+ in_class = False+ elif ch == "[":+ in_class = True+ elif ch == "/":+ break+ elif ch == "\n":+ # Not actually a regex (they can't span lines) — bail out and+ # let the caller treat the `/` as an ordinary character; safer+ # than consuming the rest of the file looking for a `/` that+ # was never a regex terminator to begin with.+ return j+ k += 1+ else:+ return j+ k += 1+ while k < len(s) and s[k].isalpha():+ k += 1+ return k - 1++def panel_source() -> str:# Everything the panel serves, in the order the pieces sat in the# pre-extraction single file: Python, then the CSS, then the page@@ -61,27 +137,14 @@ def panel_source() -> str:return "\n".join(parts)-def extract_function(name: str, src: str | None = None) -> str:- """The full text of `function <name>(...) { ... }`, braces balanced."""- s = src if src is not None else panel_source()- pat = r"^(?:async\s+)?function\s+%s\s*\(" % re.escape(name)- hits = list(re.finditer(pat, s, re.M))- if not hits:- raise ExtractError("function %s() not found in mlx_ltx_panel.py" % name)- if len(hits) > 1:- # A duplicated declaration is exactly the parallel-edit accident this- # repo has now shipped twice (the health chip, both times). Returning- # the FIRST match here meant the tests covered the copy the browser- # does not run — JS hoisting makes the LAST declaration win. Refusing- # is the only honest behaviour: the caller must fix the panel, not- # pick a copy.- raise ExtractError(- "function %s() is declared %d times in mlx_ltx_panel.py — "- "duplicate definitions must be removed before it can be tested"- % (name, len(hits)))- m = hits[0]- start = m.start()- i = s.index("{", m.end() - 1)+def _balanced_brace_end(s: str, i: int) -> int:+ """Index of the `}` that closes the `{` at `s[i]`, tracking strings,+ `//`/`/* */` comments and `/regex/` literals so none of their contents+ are mistaken for real braces (or, for a regex containing a quote+ character, mistaken for a string that swallows real braces further on+ — see `_looks_like_regex_start`'s docstring). Shared by+ `extract_function` and `extract_object`, which used to carry two+ copies of this loop that both lacked regex awareness."""depth, j, in_s, esc, in_c, in_lc = 0, i, "", False, False, Falsewhile j < len(s):ch = s[j]@@ -108,14 +171,44 @@ def extract_function(name: str, src: str | None = None) -> str:elif ch == "/" and nxt == "*":in_c = Truej += 1+ elif ch == "/" and nxt not in ("/", "*") and _looks_like_regex_start(s, j):+ j = _skip_regex_literal(s, j)elif ch == "{":depth += 1elif ch == "}":depth -= 1if depth == 0:- return s[start:j + 1]+ return jj += 1- raise ExtractError("unbalanced braces while extracting %s()" % name)+ raise ExtractError("unbalanced braces from offset %d" % i)+++def extract_function(name: str, src: str | None = None) -> str:+ """The full text of `function <name>(...) { ... }`, braces balanced."""+ s = src if src is not None else panel_source()+ pat = r"^(?:async\s+)?function\s+%s\s*\(" % re.escape(name)+ hits = list(re.finditer(pat, s, re.M))+ if not hits:+ raise ExtractError("function %s() not found in mlx_ltx_panel.py" % name)+ if len(hits) > 1:+ # A duplicated declaration is exactly the parallel-edit accident this+ # repo has now shipped twice (the health chip, both times). Returning+ # the FIRST match here meant the tests covered the copy the browser+ # does not run — JS hoisting makes the LAST declaration win. Refusing+ # is the only honest behaviour: the caller must fix the panel, not+ # pick a copy.+ raise ExtractError(+ "function %s() is declared %d times in mlx_ltx_panel.py — "+ "duplicate definitions must be removed before it can be tested"+ % (name, len(hits)))+ m = hits[0]+ start = m.start()+ i = s.index("{", m.end() - 1)+ try:+ end = _balanced_brace_end(s, i)+ except ExtractError:+ raise ExtractError("unbalanced braces while extracting %s()" % name) from None+ return s[start:end + 1]def extract_object(name: str, src: str | None = None) -> str:@@ -125,40 +218,11 @@ def extract_object(name: str, src: str | None = None) -> str:if not m:raise ExtractError("window.%s not found" % name)i = s.index("{", m.end() - 1)- depth, j, in_s, esc, in_c, in_lc = 0, i, "", False, False, False- while j < len(s):- ch = s[j]- nxt = s[j + 1] if j + 1 < len(s) else ""- if in_lc:- if ch == "\n":- in_lc = False- elif in_c:- if ch == "*" and nxt == "/":- in_c = False- j += 1- elif in_s:- if esc:- esc = False- elif ch == "\\":- esc = True- elif ch == in_s:- in_s = ""- elif ch in "\"'`":- in_s = ch- elif ch == "/" and nxt == "/":- in_lc = True- j += 1- elif ch == "/" and nxt == "*":- in_c = True- j += 1- elif ch == "{":- depth += 1- elif ch == "}":- depth -= 1- if depth == 0:- return s[i:j + 1]- j += 1- raise ExtractError("unbalanced braces while extracting window.%s" % name)+ try:+ end = _balanced_brace_end(s, i)+ except ExtractError:+ raise ExtractError("unbalanced braces while extracting window.%s" % name) from None+ return s[i:end + 1]def extract_element(element_id: str, src: str | None = None) -> str:diff --git a/scripts/fleet_timings_build.py b/scripts/fleet_timings_build.pynew file mode 100644index 0000000..e240de1--- /dev/null+++ b/scripts/fleet_timings_build.py@@ -0,0 +1,255 @@+#!/usr/bin/env python3.11+"""Rebuild data/fleet_timings.json from the fleet's own real wall-clock data.++Owner direction (2026-09-29): "If we have the fleet data, we can provide+proper time estimations, or at least a range." Every estimate in the panel+before this was a MODEL — a per-chip speed factor times a cost function+fitted to a handful of measured renders, all on the maintainer's own Macs.+This script instead asks PostHog what the fleet's OWN installs actually+measured, at three levels of granularity, and the panel's runtime loader+(fleet_estimate_range() in mlx_ltx_panel.py) walks from the most specific+level down to the least specific, falling back to the model only when the+fleet has nothing to say.++WHAT IT QUERIES+ render_completed events, last WINDOW_DAYS days, this project's own+ PostHog (via HogQL — https://posthog.com/docs/hogql). Every field read+ here is documented in docs/ANALYTICS.md; nothing this script computes+ ever leaves a user's machine — the query runs from the MAINTAINER's+ own workstation using the maintainer's own read-only PostHog personal+ API key (the same key the /stats dashboard already uses, resolved the+ same way: Settings -> analytics_query_key in panel_settings.json).++THE OWNER'S OWN INSTALL IS EXCLUDED, by distinct_id (analytics_install_id+in the SAME settings file) — a maintainer boots this panel constantly for+development and testing, and that traffic would otherwise dominate every+"M4 Max 64 GB" cell it appears in.++THREE LEVELS, precomputed here (not reconstructed from each other at+runtime, because quantiles do not combine — re-deriving a coarser+quantile from finer ones would be a second, silently wrong model):+ cell — engine, mode, tier, frames, chip_family, ram_gb, speed+ (speed only distinguishes anything for H3: <=5 steps is the+ Fast/TriStep lane, per docs/ANALYTICS.md's `steps` field)+ chip — same, without ram_gb (every RAM class of one chip, pooled)+ model — engine, mode, tier, frames, speed only (every Mac, pooled) —+ the last real-data rung before the panel's own cost model++WHAT THE NUMBERS ARE: render_completed never reports an exact wall clock,+only `wall_sec_bucket` — the LOWER edge of the ladder rung the render fell+in (mlx_ltx_panel.FLEET_WALL_SEC_LADDER). The p25/p50/p75 written here are+quantiles of those lower edges, and the file says so (`"wall_sec":+"bucket_lower_edge"`). The panel's reader (_fleet_cell_seconds) turns them+back into what they support — p25 a rung's lower edge, p50 its middle, p75+its UPPER edge — so a cell whose renders all sit in the 10-15 min rung reads+"~10-15 min", not a tight "~10 min" (4.17 Codex EST-4). Keep the marker in+step with the reader if this script ever stores anything else.++WHAT'S NOT HERE: "same chip+RAM, other length, scaled" is level 2 of the+runtime fallback (VC-01's ledger) — it needs the REQUESTED cell's own+frame count to scale by, which only the running panel knows, so it lives+in fleet_estimate_range() itself, not in this precomputed table.++Run it from the repo root, with the venv that has network access:+ python3 scripts/fleet_timings_build.py++Reads the query key from the REAL install's settings (read-only) — never+prints it, never writes it to the output file, never commits it.+"""+from __future__ import annotations++import json+import sys+import time+import urllib.error+import urllib.request+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+OUT_PATH = ROOT / "data" / "fleet_timings.json"+WINDOW_DAYS = 75+# The maintainer's own live dev panel state — READ ONLY, one field pulled+# (analytics_query_key) and one more to exclude (analytics_install_id).+# Never the phosphene-dev.git CHECKOUT itself (CLAUDE.md forbids touching+# that panel); this is its persisted settings file on disk, read once.+SETTINGS_PATH = Path.home() / "pinokio" / "api" / "phosphene-dev.git" / "state" / "panel_settings.json"+POSTHOG_QUERY_URL = "https://us.posthog.com/api/projects/@current/query/"+# Render modes priced by the panel's Quality-strip / keyframe / extend / a2v+# estimates (VC-01/VA-06/VA-11/VA-12's territory) — image and training jobs+# have their own, unrelated estimate paths.+PRICED_MODES = ("t2v", "i2v", "a2v", "extend", "keyframe")+MIN_N_TO_SHIP = 3 # a cell with fewer samples than this is not written at all+++def _posthog_key_and_owner() -> tuple[str, str]:+ try:+ settings = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ raise SystemExit(+ f"Could not read {SETTINGS_PATH} — this script must run on the "+ f"maintainer's own Mac, with Settings -> analytics_query_key set."+ ) from exc+ key = str(settings.get("analytics_query_key") or "").strip()+ owner = str(settings.get("analytics_install_id") or "").strip()+ if not key:+ raise SystemExit("analytics_query_key is empty in panel_settings.json — "+ "set a PostHog personal API key in Settings first.")+ return key, owner+++def _hogql(key: str, sql: str) -> list[list]:+ body = json.dumps({"query": {"kind": "HogQLQuery", "query": sql}}).encode("utf-8")+ req = urllib.request.Request(+ POSTHOG_QUERY_URL, data=body,+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"},+ method="POST")+ try:+ with urllib.request.urlopen(req, timeout=90) as r:+ out = json.loads(r.read())+ except urllib.error.HTTPError as exc:+ detail = exc.read().decode("utf-8", "replace")[:800]+ raise SystemExit(f"PostHog query failed ({exc.code}): {detail}") from exc+ if "results" not in out:+ raise SystemExit(f"PostHog query returned no results: {out}")+ return out["results"]+++def _sql_literal(s: str) -> str:+ return "'" + s.replace("'", "''") + "'"+++_SPEED_EXPR = (+ "multiIf(properties.engine = 'h3' AND toFloat64OrNull(toString(properties.steps)) <= 5, "+ "'fast', properties.engine = 'h3', 'best', '')"+)+_MODE_LIST = "(" + ",".join(_sql_literal(m) for m in PRICED_MODES) + ")"+++def _quantile_select(group_cols: list[str]) -> str:+ cols = ",\n ".join(group_cols)+ return f"""+SELECT+ {cols},+ quantile(0.25)(toFloat64OrNull(toString(properties.wall_sec_bucket))) p25,+ quantile(0.5)(toFloat64OrNull(toString(properties.wall_sec_bucket))) p50,+ quantile(0.75)(toFloat64OrNull(toString(properties.wall_sec_bucket))) p75,+ count() n+FROM events+WHERE event = 'render_completed'+ AND timestamp > now() - INTERVAL {WINDOW_DAYS} DAY+ AND properties.mode IN {_MODE_LIST}+"""+++_CELL_COLS = [+ "properties.engine AS engine",+ "properties.mode AS mode",+ "properties.tier AS tier",+ "toFloat64OrNull(toString(properties.frames)) AS frames",+ "properties.chip_family AS chip_family",+ "toFloat64OrNull(toString(properties.ram_gb)) AS ram_gb",+ f"{_SPEED_EXPR} AS speed",+]+_CHIP_COLS = [c for c in _CELL_COLS if "ram_gb" not in c]+_MODEL_COLS = [c for c in _CHIP_COLS if "chip_family" not in c]+++def _run_level(key: str, owner_lit: str, cols: list[str], *, exclude_owner: bool,+ require_chip: bool, limit: int) -> list[list]:+ sql = _quantile_select(cols)+ if exclude_owner and owner_lit:+ sql += f" AND distinct_id != {owner_lit}\n"+ if require_chip:+ sql += " AND properties.chip_family IS NOT NULL AND toString(properties.chip_family) != ''\n"+ group_names = [c.rsplit(" AS ", 1)[-1] for c in cols]+ sql += f"GROUP BY {', '.join(group_names)}\nHAVING n >= 1\nORDER BY n DESC\nLIMIT {limit}\n"+ return _hogql(key, sql)+++def _row_to_cell(rec: dict) -> dict | None:+ p25, p50, p75, n = rec["p25"], rec["p50"], rec["p75"], int(rec["n"])+ if p25 is None or p50 is None or p75 is None or n < MIN_N_TO_SHIP:+ return None+ return {+ "p25_sec": round(float(p25), 1), "p50_sec": round(float(p50), 1),+ "p75_sec": round(float(p75), 1), "n": n,+ }+++def _key_for(rec: dict, dims: list[str]) -> str | None:+ """The pipe-joined lookup key for one row. `speed` is legitimately ""+ for LTX (the axis only exists for H3's Fast/Best split) — "" there+ means "no speed axis", not "missing data", so it becomes the token+ "any" rather than rejecting the row. Every OTHER dimension rejects a+ missing value outright (frames/chip_family/etc with nothing behind+ them is a row this table cannot key reliably)."""+ parts = []+ for d in dims:+ v = rec.get(d)+ if v is None:+ return None+ if v == "":+ if d != "speed":+ return None+ parts.append("any")+ continue+ parts.append(str(v).strip())+ return "|".join(parts)+++def build() -> dict:+ key, owner = _posthog_key_and_owner()+ owner_lit = _sql_literal(owner) if owner else ""++ levels = {+ "cell": (_CELL_COLS, ["engine", "mode", "tier", "frames", "chip_family", "ram_gb", "speed"], True, 4000),+ "chip": (_CHIP_COLS, ["engine", "mode", "tier", "frames", "chip_family", "speed"], True, 3500),+ "model": (_MODEL_COLS, ["engine", "mode", "tier", "frames", "speed"], False, 1200),+ }+ out_levels: dict[str, dict] = {}+ total_n = 0+ for level_name, (cols, dims, require_chip, limit) in levels.items():+ col_names = [c.rsplit(" AS ", 1)[-1] for c in cols]+ rows = _run_level(key, owner_lit, cols, exclude_owner=True,+ require_chip=require_chip, limit=limit)+ cells: dict[str, dict] = {}+ for row in rows:+ rec = dict(zip(col_names + ["p25", "p50", "p75", "n"], row))+ k = _key_for(rec, dims)+ if not k:+ continue+ cell = _row_to_cell(rec)+ if cell is None:+ continue+ cells[k] = cell+ total_n += cell["n"]+ out_levels[level_name] = {"dims": dims, "cells": cells}+ print(f"[fleet_timings_build] {level_name}: {len(cells)} cells "+ f"(from {len(rows)} raw rows)", file=sys.stderr)++ return {+ "schema": "fleet_timings/1",+ # Quantiles of wall_sec_bucket LOWER edges — see the docstring.+ "wall_sec": "bucket_lower_edge",+ "built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ "window_days": WINDOW_DAYS,+ "owner_excluded": bool(owner),+ "min_n_to_ship": MIN_N_TO_SHIP,+ "priced_modes": list(PRICED_MODES),+ "total_events_counted": total_n,+ "levels": out_levels,+ }+++def main() -> None:+ data = build()+ OUT_PATH.parent.mkdir(parents=True, exist_ok=True)+ OUT_PATH.write_text(json.dumps(data, indent=1, sort_keys=True) + "\n", encoding="utf-8")+ n_cells = sum(len(lv["cells"]) for lv in data["levels"].values())+ print(f"[fleet_timings_build] wrote {OUT_PATH} — {n_cells} cells across "+ f"{len(data['levels'])} levels, {data['total_events_counted']} events counted",+ file=sys.stderr)+++if __name__ == "__main__":+ main()diff --git a/scripts/measure_editor_layout.py b/scripts/measure_editor_layout.pyindex 5c932c5..a1c22df 100644--- a/scripts/measure_editor_layout.py+++ b/scripts/measure_editor_layout.py@@ -710,10 +710,43 @@ JS_MEASURE = r"""const r = e.getBoundingClientRect(); return { w: num(r.width), h: num(r.height) }; };const srcMon = el('sbeSrcMon');out.source_shown = !!(srcMon && !srcMon.hidden && srcMon.offsetParent !== null);+ // FILM-37: EMPTY IS NOT A PICTURE. The Source monitor now collapses to a+ // narrow rail (class is-empty) while nothing is loaded, rather than+ // holding the full 16:9 box open on every boot — so "on screen by+ // default" no longer means "16:9 by default"; it means "16:9 once+ // something is actually loaded into it, collapsed otherwise." Both are+ // asserted below, on this flag.+ out.source_empty = !!(srcMon && srcMon.classList.contains('is-empty'));out.program_box = box(el('sbeStage'));out.source_box = box(el('sbeSrcStage'));+ out.source_mon_box = box(srcMon);out.view_buttons = document.querySelectorAll('#sbeView .sbe-vbtn').length;+ // FILM-37: THE INSPECTOR, OPENED, MEASURED, PUT BACK. Below 1600px it is a+ // fixed drawer that costs the row no width at all (the whole point — at+ // 1366-1440px the shared-flex rail measured about 210px and clipped the+ // "2x" speed control inside it); at and above 1600px it is an ordinary+ // column again. Opened explicitly rather than trusting whatever+ // `phos_sbe_inspect` a fresh profile happens to default to — a gate that+ // sometimes measures a hidden rail is a gate that sometimes measures+ // nothing.+ try {+ if (typeof sbeInspectSet === 'function') sbeInspectSet(true);+ } catch (e) { out.errors.push('sbeInspectSet threw: ' + e); }+ await settle();+ const rail = el('sbeRail');+ // NOT box()'s own offsetParent guard: a `position: fixed` element (the+ // drawer, below 1600px) reports offsetParent === null in every engine —+ // that is fixed positioning working as specified, not the rail being+ // hidden, and box() would silently read it as absent.+ out.rail_shown = !!(rail && !rail.hidden+ && getComputedStyle(rail).display !== 'none');+ out.rail_position = rail ? getComputedStyle(rail).position : null;+ out.rail_box = (rail && out.rail_shown)+ ? (() => { const r = rail.getBoundingClientRect();+ return { w: num(r.width), h: num(r.height) }; })()+ : null;+// Put it back, so the next width does not start from a forced state.try {if (window.SBE) SBE.dirty = false;@@ -937,15 +970,50 @@ def check(width: int, m: dict) -> list[str]:if not m.get("stacked"):if m.get("source_shown") is not True:bad.append(f"{w}: the Source monitor is not on screen by default")- for name in ("program_box", "source_box"):- b = m.get(name) or {}- if not b.get("h"):- bad.append(f"{w}: {name} not measured")- elif abs(b["w"] / b["h"] - 16 / 9) > 0.02:- bad.append(f"{w}: {name} {b['w']}x{b['h']} is not 16:9")+ pb = m.get("program_box") or {}+ if not pb.get("h"):+ bad.append(f"{w}: program_box not measured")+ elif abs(pb["w"] / pb["h"] - 16 / 9) > 0.02:+ bad.append(f"{w}: program_box {pb['w']}x{pb['h']} is not 16:9")+ # FILM-37: the Source monitor is 16:9 once something is loaded into+ # it, and a narrow ~64px rail while it is empty — which is the+ # default boot state this script measures, so the collapsed width+ # is checked here rather than the aspect ratio a picture nobody+ # loaded was never going to have.+ sb = m.get("source_box") or {}+ smb = m.get("source_mon_box") or {}+ if m.get("source_empty"):+ if not smb.get("w"):+ bad.append(f"{w}: source_mon_box not measured")+ elif abs(smb["w"] - 64) > 2:+ bad.append(f"{w}: source_mon_box width {smb['w']} != 64 "+ f"while empty (collapsed rail)")+ else:+ if not sb.get("h"):+ bad.append(f"{w}: source_box not measured")+ elif abs(sb["w"] / sb["h"] - 16 / 9) > 0.02:+ bad.append(f"{w}: source_box {sb['w']}x{sb['h']} is not 16:9")if m.get("view_buttons") != 5:bad.append(f"{w}: the View group has {m.get('view_buttons')} buttons, not 5")+ # FILM-37: below 1600px the Inspector is a fixed drawer that costs the+ # row no width (checked here); at and above it, an ordinary column.+ if m.get("rail_shown") is not True:+ bad.append(f"{w}: the Inspector did not open for measurement")+ else:+ rb = m.get("rail_box") or {}+ pos = m.get("rail_position")+ if width < 1600:+ if pos != "fixed":+ bad.append(f"{w}: the Inspector is {pos!r}, not a fixed "+ f"drawer, below 1600px")+ if not rb.get("w") or rb["w"] < 300:+ bad.append(f"{w}: the Inspector drawer is {rb.get('w')}px "+ f"wide, under the 300px floor")+ elif pos == "fixed":+ bad.append(f"{w}: the Inspector is still a fixed drawer at "+ f"{w}px, where there is room for an ordinary column")+both = m.get("stage_layers_both_visible")if both is not False:bad.append(f"{w}: stage_layers_both_visible {both} != false "diff --git a/scripts/measure_hidden_elements.py b/scripts/measure_hidden_elements.pynew file mode 100644index 0000000..a96fd80--- /dev/null+++ b/scripts/measure_hidden_elements.py@@ -0,0 +1,196 @@+#!/usr/bin/env python3.11+"""A REAL browser gate: everything carrying the `hidden` attribute renders as+`display: none`, in both engines.++WHY THIS EXISTS (VC-07). `.toggle-pill { display: inline-flex }`+(panel.css) outranked the UA's built-in `[hidden] { display: none }` rule on+`#noVoicePill` in the LTX composer, and `.loras-summary .loras-browse-btn`+did the same to `#h3LoraImportBtn`. Both elements kept `.hidden === true` in+the DOM while rendering fully visible: an LTX user ticked "No voice" and the+render spoke anyway (a wasted render), and clicking the visible "Import"+button posted to the H3 LoRA importer while the LTX engine was selected.+The stylesheet had been patched selector-by-selector for months (panel.css+has two dozen `<selector>[hidden] { display: none !important }` overrides+already) instead of fixed once — the same class of bug was always one new+component away from reappearing.++The fix is a single global rule (`webapp/style/panel.css`, right after the+`* { box-sizing }` reset): `[hidden] { display: none !important; }`. A+`!important` declaration on `[hidden]` always outranks a plain `display`+declaration on any component selector, regardless of specificity, so no+future component can silently un-hide an element again.++This script is the gate a stylesheet edit can't fake: it boots the panel out+of THIS tree, drives a headless Chrome over CDP (harness borrowed from+`scripts/measure_editor_layout.py`, stdlib-only, same rule as every other+`measure_*` gate here), and after each of a few state changes (page load,+engine switched to H3 and back to LTX, a character selected so+`toggleVoicePillVisibility` runs its normal branch) walks every element in+the document that has `hasAttribute('hidden')` and asserts+`getComputedStyle(el).display === 'none'`. Anything that fails that check+under load is exactly the bug: hidden in the DOM's eyes, visible on screen.++Exit codes: 0 pass, 1 a measurement FAILED, 3 no browser (unittest skips),+4 the harness could not get far enough to measure.++ ./ltx-2-mlx/env/bin/python3.11 scripts/measure_hidden_elements.py -v+"""++from __future__ import annotations++import argparse+import importlib.util+import json+import shutil+import sys+import tempfile+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent++FORBIDDEN_PORTS = {8199}+++def _load_editor_gate():+ p = ROOT / "scripts" / "measure_editor_layout.py"+ spec = importlib.util.spec_from_file_location("_phos_editor_gate", p)+ if spec is None or spec.loader is None:+ raise RuntimeError(f"cannot load {p}")+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++G = _load_editor_gate()+HarnessError = G.HarnessError+NoBrowser = G.NoBrowser++# Walks the live DOM (not a static parse) so it catches the real cascade,+# including component CSS loaded after the global reset. `offsetParent` is+# not checked - an ancestor's own `hidden`/display:none legitimately hides a+# hidden-and-also-inside-a-closed-panel element without that being this bug;+# what must never happen is THIS element's own hidden-ness being overridden.+JS_SWEEP = r"""+(() => {+ const bad = [];+ document.querySelectorAll('[hidden]').forEach(el => {+ const disp = getComputedStyle(el).display;+ if (disp !== 'none') {+ bad.push({+ tag: el.tagName,+ id: el.id || null,+ cls: (el.className && el.className.toString()) || null,+ display: disp,+ });+ }+ });+ return { count: document.querySelectorAll('[hidden]').length, bad };+})()+"""++JS_READY = """+(() => typeof setEngine === 'function' && typeof currentEngine === 'function'+ ? 'ok' : 'app not booted')()+"""++JS_SWITCH_H3 = "(() => { setEngine('h3'); return currentEngine(); })()"+JS_SWITCH_LTX = "(() => { setEngine('ltx'); return currentEngine(); })()"+++def sweep(cdp, tag: str, verbose: bool) -> list[str]:+ deadline = time.monotonic() + 10.0+ m = None+ while time.monotonic() < deadline:+ m = cdp.evaluate(JS_SWEEP, await_promise=True, timeout=15.0)+ if isinstance(m, dict):+ break+ time.sleep(0.2)+ if not isinstance(m, dict):+ return [f"{tag}: the page returned {m!r}"]+ if verbose:+ print(f"{tag}: {m['count']} [hidden] elements, "+ f"{len(m['bad'])} rendering visible", file=sys.stderr)+ return [f"{tag}: {b['tag']}#{b['id']}.{b['cls']} has hidden but "+ f"computes display:{b['display']}" for b in m["bad"]]+++def run(verbose: bool) -> tuple[dict, int]:+ binary = G.find_browser()+ work = Path(tempfile.mkdtemp(prefix="phos-hidden-gate-"))+ profile = work / "chrome"+ profile.mkdir()+ log = work / "panel.log"+ panel = chrome = ws = None+ try:+ panel, base = G.start_panel(work, log, verbose)+ if base.rsplit(":", 1)[-1] in {str(p) for p in FORBIDDEN_PORTS}:+ raise HarnessError("refusing to measure on a forbidden port")+ chrome, devtools = G.start_chrome(binary, profile, verbose)+ ws = G.WebSocket(G.page_socket(devtools))+ cdp = G.CDP(ws)+ cdp.call("Page.enable")+ cdp.call("Runtime.enable")+ cdp.call("Emulation.setDeviceMetricsOverride",+ {"width": 1440, "height": 900, "deviceScaleFactor": 1,+ "mobile": False})+ cdp.call("Page.navigate", {"url": base + "/"})+ deadline = time.monotonic() + 45.0+ while cdp.evaluate("document.readyState") != "complete":+ if time.monotonic() > deadline:+ raise HarnessError("the panel page never finished loading")+ time.sleep(0.2)+ deadline = time.monotonic() + 30.0+ why = "never checked"+ while time.monotonic() < deadline:+ why = cdp.evaluate(JS_READY)+ if why == "ok":+ break+ time.sleep(0.3)+ if why != "ok":+ raise HarnessError(f"the app never booted: {why}")++ failures: list[str] = []+ # LTX is the default engine on a fresh boot - both elements the+ # review caught (#noVoicePill, #h3LoraImportBtn) already carry+ # `hidden` in the raw markup at this point, so this alone reproduces+ # the original bug without needing any engine switch.+ failures += sweep(cdp, "load/ltx", verbose)+ # Best-effort: also sweep with H3 selected, since a from-zero test+ # sandbox has no installed H3 weights and `setEngine('h3')` falls+ # back to LTX under that gate (by design - see queue.js setEngine).+ # Only assert the sweep, not that the switch took: an environment+ # where H3 IS available (a real Mac) still gets the real coverage,+ # and one where it isn't still exercises the DOM's actual state.+ got = cdp.evaluate(JS_SWITCH_H3, timeout=10.0)+ failures += sweep(cdp, f"engine={got}", verbose)+ cdp.evaluate(JS_SWITCH_LTX, timeout=10.0)+ failures += sweep(cdp, "engine=ltx (back)", verbose)+ return ({"ok": not failures, "failures": failures}, 1 if failures else 0)+ finally:+ if ws is not None:+ ws.close()+ G.kill(chrome)+ G.kill(panel)+ shutil.rmtree(work, ignore_errors=True)+++def main(argv: list[str]) -> int:+ ap = argparse.ArgumentParser(description=__doc__ and __doc__.splitlines()[0])+ ap.add_argument("-v", "--verbose", action="store_true")+ args = ap.parse_args(argv)+ try:+ doc, code = run(args.verbose)+ except NoBrowser as exc:+ print(f"no browser: {exc}", file=sys.stderr)+ return 3+ except HarnessError as exc:+ print(json.dumps({"ok": False, "failures": [f"harness: {exc}"]}))+ print(f"harness: {exc}", file=sys.stderr)+ return 4+ print(json.dumps(doc, indent=2))+ return code+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/scripts/measure_outputs_layout.py b/scripts/measure_outputs_layout.pyindex 6ade7ee..c3b0731 100644--- a/scripts/measure_outputs_layout.py+++ b/scripts/measure_outputs_layout.py@@ -182,6 +182,13 @@ JS_MEASURE = r"""return { x: num(r.left), y: num(r.top), w: num(r.width), h: num(r.height),b: num(r.bottom), r: num(r.right) }; };const out = { missing: [] };+ // This gate measures the VIDEO tab's gallery. The previous viewport's song+ // step (JS_SONG, VC-20) left the page on the Audio tab, whose gallery is+ // songs only — go back, and back to All, before measuring.+ if (typeof workflowSwitch === 'function' && document.body.dataset.workflow !== 'manual')+ workflowSwitch('manual');+ if (typeof setMainOutputsFilter === 'function' && mainOutputsFilter !== 'all')+ setMainOutputsFilter('all');const surface = document.querySelector('.stage-pane > .player-surface');if (!surface) { out.missing.push('.player-surface'); return out; }const shaped = () => {@@ -245,6 +252,14 @@ JS_SONG = r"""return { x: num(r.left), y: num(r.top), w: num(r.width), h: num(r.height),b: num(r.bottom), r: num(r.right) }; };const surface = document.querySelector('.stage-pane > .player-surface');+ // VC-20: the song hero (this whole scenario) is the Audio/Music tab's+ // own surface now — selectOutput() only builds it when+ // document.body.dataset.workflow === 'audio' (reached by filtering the+ // VIDEO tab's own gallery to Audio and clicking a song used to+ // transplant this same hero into the Video tab's pane, which was the+ // bug). Switch tabs first, the same way a real user (or the new "Open+ // in Audio tab" link) would, before selecting the song.+ if (typeof workflowSwitch === 'function') workflowSwitch('audio');const t0 = performance.now();let tries = 0;while (performance.now() - t0 < 10000) {diff --git a/scripts/pinokio/h3_preflight.sh b/scripts/pinokio/h3_preflight.shindex 4246b5f..c91e7ed 100644--- a/scripts/pinokio/h3_preflight.sh+++ b/scripts/pinokio/h3_preflight.sh@@ -42,3 +42,62 @@ elif [ "$MEM_BYTES" -lt 60000000000 ]; thenelseecho 'H3 memory preflight OK'fi++# ---- Disk preflight (H3-18) -------------------------------------------------+# Before this, install_h3.js's ONLY disk-space behaviour was `df -h .` printed+# after the fact — an install that ran out of space partway through failed+# loudly mid-download instead of being told up front. Refuse the same way the+# RAM check does: fail-open if `df` is unreadable, otherwise a real number and+# a real refusal.+#+# REQUIRED SPACE is context-dependent, not one constant: a Mac whose weights+# are already on disk (Repair / Build, or a resumed install) only needs room+# for the compact Q8 build (~22 GB, plus headroom for whatever weight files+# are still incomplete). A Mac starting from nothing needs the ~75 GB+# download PLUS that ~22 GB build, because both exist on disk at once before+# the build reads the download's output — ~97 GB, matching the review's+# figure. Presence of the bf16 DiT (the single largest file in the tree, and+# the same marker h3_roots.sh uses) is the cheap signal for "mostly here+# already"; it is a heuristic, not the panel's real required_files.json+# check, so it only ever WIDENS the requirement it isn't sure about.+_h3_abs() { case "$1" in /*) printf '%s' "$1" ;; *) printf '%s/%s' "$(pwd)" "$1" ;; esac; }+H3_MODELS_ROOT_PF="$(_h3_abs "${LTX_H3_MODELS:-mlx_models/hailuo-h3}")"+H3_DIT_REL_PF='deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors'+if { [ -f "$H3_MODELS_ROOT_PF/h3-dit-q8/.built_ok" ] || [ -f "$H3_MODELS_ROOT_PF/models/h3-dit-q8/.built_ok" ]; } \+ && { [ -f "$H3_MODELS_ROOT_PF/$H3_DIT_REL_PF" ] || [ -f "$H3_MODELS_ROOT_PF/models/$H3_DIT_REL_PF" ]; }; then+ # Weights AND the compact engine already built (h3_build_q8.sh's own+ # .built_ok marker): an Update / Repair only refreshes the runner and its+ # venv — a few GB, not a 22 GB build (4.17 Codex H3-6).+ NEED_GB=5+ NEED_WHY='a runner / environment refresh (weights and the compact engine are already built)'+elif [ -f "$H3_MODELS_ROOT_PF/$H3_DIT_REL_PF" ] || [ -f "$H3_MODELS_ROOT_PF/models/$H3_DIT_REL_PF" ]; then+ NEED_GB=25+ NEED_WHY='the compact Q8 engine build (weights already on disk)'+else+ NEED_GB=97+ NEED_WHY='the ~75 GB download plus the ~22 GB compact engine build it does afterward'+fi+# Measure the volume the WEIGHTS land on (LTX_H3_MODELS may point at another+# drive), via its nearest existing ancestor — not the app folder's volume+# (4.17 Codex H3-7).+_PF_DF_AT="$H3_MODELS_ROOT_PF"+while [ ! -e "$_PF_DF_AT" ] && [ "$_PF_DF_AT" != "/" ] && [ -n "$_PF_DF_AT" ]; do+ _PF_DF_AT="$(dirname "$_PF_DF_AT")"+done+[ -e "$_PF_DF_AT" ] || _PF_DF_AT=.+AVAIL_KB=$(df -Pk "$_PF_DF_AT" 2>/dev/null | awk 'NR==2 {print $4}')+if echo "$AVAIL_KB" | grep -qE '^[0-9]+$'; then+ AVAIL_GB=$((AVAIL_KB / 1024 / 1024))+ if [ "$AVAIL_GB" -lt "$NEED_GB" ]; then+ echo '=================================================================='+ echo "HAILUO H3 NEEDS ~${NEED_GB} GB FREE (this Mac has ${AVAIL_GB} GB free)"+ echo "That covers ${NEED_WHY}."+ echo 'Free up space and try again. Nothing was downloaded. Keep using the'+ echo 'built-in LTX engine until then.'+ echo '=================================================================='+ exit 1+ fi+ echo "H3 disk preflight OK - ${AVAIL_GB} GB free, needs ~${NEED_GB} GB"+else+ echo 'H3 disk preflight skipped - could not read free space (df unreadable)'+fidiff --git a/storyboard.py b/storyboard.pyindex b7f3e9a..9dda364 100644--- a/storyboard.py+++ b/storyboard.py@@ -86,11 +86,63 @@ import osimport reimport tempfileimport time+import uuidfrom pathlib import Pathfrom typing import Any, IterableSCHEMA_VERSION = 1++def is_user_still(shot) -> bool:+ """True when the shot's still is the USER'S OWN picture, never render cache.++ BOARD-10: `still_source == "user"` is written by the music-video planner+ since FILM-11, but boards planned before it carry only the provenance the+ planner always recorded — `music_video.image`, the uploaded cast photo the+ still was set from. Recognised here too, so "New still" on such a shot+ keeps the photo (a singing shot has no other image to start from) instead+ of deleting it.+ """+ if not isinstance(shot, dict):+ return False+ if shot.get("still_source") == "user":+ return True+ block = shot.get("music_video")+ still = shot.get("still")+ return bool(isinstance(block, dict) and still and block.get("image")+ and str(block.get("image")) == str(still))+++def take_path(entry) -> str:+ """The file a `takes[]` entry names, whichever shape it was written in.++ BOARD-4: take history has TWO writers — `_sb_reconcile` archives a+ superseded output as a bare path string, `_sb_new_take` ("Edit &+ re-render") as `{"path", "pass", "seed", "at"}`. The one reader,+ `_sbe_relinks`, accepted strings only, so a take archived by Edit &+ re-render was invisible and the timeline kept exporting the old clip.+ Every reader resolves entries through here; "" for anything else.+ """+ if isinstance(entry, str):+ return entry+ if isinstance(entry, dict) and isinstance(entry.get("path"), str):+ return entry["path"]+ return ""+++def new_shot_uid() -> str:+ """A stable per-shot identity, independent of `n` (display order).++ `n` is renumbered constantly (drag, delete, insert) and was, until+ FILM-10, also the merge key the save route used to graft server-owned+ fields (draft_output, final_output, still, job ids, ...) from the old+ shot onto the incoming one — so a reorder or delete could graft one+ shot's rendered clip onto a completely different, unrendered shot.+ `uid` never changes once assigned; every merge-by-identity operation+ must key on this, not on `n`.+ """+ return f"shot_{uuid.uuid4().hex[:8]}"+# Modes a shot may use. These MUST exist as real panel modes — the planner is never trusted# to invent one. Kept as a plain tuple so validation errors can list the legal set.VALID_MODES = ("text", "character", "remix", "keyframe", "extend", "a2v")@@ -248,6 +300,12 @@ _H3_QUALITY_FOR_PASS = {# a benchmark. Tuned against observed two-stage 1536x896 ~11 min for a 5 s clip._SECS_PER_VIDEO_SEC = {"quick": 24.0, "balanced": 60.0, "standard": 96.0, "high": 132.0}_PIPELINE_LOAD_SECS = 90.0+# FILM-46: an anchor still is an ordinary image job and was priced at+# nothing — "Stills first" (and the plain anchor-stills toggle) let someone+# see "about 12 m" and have no idea a batch of stills renders before a+# single video frame does. One rough, pessimistic image-job cost, same+# spirit as _PIPELINE_LOAD_SECS above.+_STILL_RENDER_SECS = 25.0# H3 FALLBACK cost, per second of video, by canvas. The panel passes `h3_cost=` into# estimate() and that hook wins every time — it reads H3_TIERS[cell]["eta_min"], which is@@ -334,11 +392,17 @@ def list_storyboards(state_dir: Path) -> list[dict]:"id": f.get("id", d.name),"title": f.get("title", ""),"created_at": f.get("created_at", 0),+ # FILM-43: every edit, grade and render already bumps this+ # (_sb_normalize sets it on every save) — it just went unread.+ # Sorting by it is what "Recent" means; created_at alone left a+ # board you opened and worked on all day sitting wherever it was+ # first minted, below whatever else got planned since.+ "updated_at": f.get("updated_at") or f.get("created_at", 0),"shots": len(shots),"done": sum(1 for s in shots if s.get("status") == "done"),"failed": sum(1 for s in shots if s.get("status") == "failed"),})- out.sort(key=lambda r: r.get("created_at") or 0, reverse=True)+ out.sort(key=lambda r: r.get("updated_at") or 0, reverse=True)return out@@ -374,6 +438,18 @@ def validate_storyboard_detail("""errs: list[dict] = []chars = set(known_character_ids or ())+ # FILM-55: a music-video board's singing shots are lip-synced to the+ # song, not to written dialogue — the words are a waveform, same+ # reasoning as the a2v exemption below. That exemption keys off+ # `mode == "a2v"`, but a re-plan or an older save can leave a singing+ # shot's mode reading "text" while `shot["audio"]` (set once by+ # music_video.emit and never touched by the speech lint) still says+ # what it really is. Reading the mode alone reproduced the owner's own+ # board: real singing shots flagged as "'sings' implies someone is+ # speaking, but no spoken line is written." A board carrying a song at+ # all is judged the same way, since nothing on a music-video board's+ # B-roll ever implies speech (ROLE_LINES has no speech verb for it).+ _has_song = bool((board.get("music_video") or {}).get("song"))def add(code: str, message: str, *, n: int | None = None,field: str | None = None, **data: Any) -> None:@@ -589,7 +665,8 @@ def validate_storyboard_detail(f"shot renders as a freeze frame with a closed mouth. "f"Say what the performer DOES instead.",n=n_for_ui, field="prompt", phrase=phrase)- verb = shot_speech_problem(prompt) if mode != "a2v" else None+ _sung = mode == "a2v" or bool(s.get("audio")) or _has_song+ verb = shot_speech_problem(prompt) if not _sung else Noneif verb:add("speech_without_words",f"{where}: {verb!r} implies someone is speaking, but no spoken "@@ -870,6 +947,14 @@ def estimate(board: dict, *, pass_name: str = "final", h3_cost=None) -> dict:policy = (board.get("policy") or {}).get(pass_name) or {}render = sum(shot_render_secs(s, policy, h3_cost=h3_cost) for s in shots)+ # FILM-46: shots that still need an anchor still made cost that render+ # too — LTX only; an H3 shot never starts from a still.+ still_secs = 0.0+ if board.get("anchor_stills"):+ still_secs = sum(+ _STILL_RENDER_SECS for s in shots+ if shot_wants_still(s) and not s.get("still") and shot_engine(s) != "h3")+ render += still_secsgrouped = {bucket_key(s) for s in shots}grouped_loads = len(grouped)@@ -895,6 +980,7 @@ def estimate(board: dict, *, pass_name: str = "final", h3_cost=None) -> dict:"pass": pass_name,"shots": len(shots),"render_secs": round(render),+ "still_secs": round(still_secs),"pipeline_loads": grouped_loads,"total_secs": round(render + grouped_ltx * _PIPELINE_LOAD_SECS),"naive_total_secs": round(render + naive_ltx * _PIPELINE_LOAD_SECS),@@ -969,8 +1055,18 @@ def ensure_trigger(prompt: str, trigger: str) -> str:# ARE PRESENT AT ALL, in either wrapper._SPOKEN_WORDS_RE = re.compile(r"<d>\s*(?:\[[^\]]*\]\s*)?[^<]*\w+[^<]*</d>" # H3: the tag, with content- r"|['‘“\"]\s*[^'’”\"]*\w+\s+[^'’”\"]*['’”\"]",- re.DOTALL) # LTX: a quoted phrase, 2+ words+ # LTX, space-separated languages (English, French, ...): a quoted+ # phrase, 2+ WORDS — the literal space between them is what makes this+ # "two words" rather than one long one. FILM-45: the quote-mark class+ # was Western-only; «guillemets» (French) are added here since French+ # words are space-separated just like English ones.+ r"|['‘“\"«]\s*[^'’”\"»]*\w+\s+[^'’”\"»]*['’”\"»]"+ # LTX, Japanese (「…」/『…』 — no spaces between words at all): the same+ # "not just a single interjection" bar, expressed as 2+ CHARACTERS+ # instead of 2+ space-separated words, because Japanese has no spaces+ # to require.+ r"|[「『][^」』]*\w[^」』]*\w[^」』]*[」』]",+ re.DOTALL)# Deliberately narrower than the planner's list: this one BLOCKS A RENDER, so# it only carries verbs that unambiguously mean a mouth is producing speech.@@ -1227,12 +1323,19 @@ def a2v_prompt(line: str, *, silent: bool = False,that already carries a contract does not collect a second one.`max_words=None` skips the cap, for a prompt whose direction was alreadycapped when it was written (see `a2v_direction`).++ BOARD-5 / LIPSYNC-2: a prompt that ALREADY carries a contract is a+ prepared prompt (planner: capped direction + style + contract) and is+ never capped again - the contract check runs BEFORE the cap. Capping it+ first cut the film's look off the end along with the contract, then+ appended the SINGING contract to a shot planned as silent. Such a prompt+ only gets its stillness words scrubbed, and keeps the contract it has."""- body = a2v_direction(line, max_words).strip()contract = A2V_SILENT_CONTRACT if silent else A2V_SYNC_CONTRACT- low = body.lower()- if any(key in low for key in _A2V_CONTRACT_KEYS):- return body+ raw_low = str(line or "").lower()+ if any(key in raw_low for key in _A2V_CONTRACT_KEYS):+ return a2v_direction(line, None).strip()+ body = a2v_direction(line, max_words).strip()if body and body[-1] not in ".!?":body += "."return (body + " " + contract).strip() if body else contract@@ -1252,20 +1355,60 @@ def is_sung(prompt: str) -> bool:# ("There's"), not the end of the line — without that rule the counter stops# counting at the first contraction._D_SPAN_RE = re.compile(r"<d>\s*(?:\[[^\]]*\]\s*)?(.*?)</d>", re.DOTALL)+# FILM-45: the single-quote form was Western-quotes-only. A Japanese line+# quoted the ordinary way for that language (「…」 or 『…』, a nested quote)+# or a French one («…») never matched at all — spoken_spans() returned+# empty, which silently skipped the "dialogue must fit the shot" frame-fit+# correction AND made the shot register as having no speech to judge for+# lip-sync. Each bracket pair is its own alternative (no apostrophe-guard+# needed — none of these characters double as punctuation inside a word,+# unlike the ASCII apostrophe)._Q_SPAN_RE = re.compile(- r"(?<![A-Za-z])'((?:[^']|(?<=[A-Za-z])'(?=[A-Za-z]))+?)'(?![A-Za-z])",+ r"(?<![A-Za-z])'((?:[^']|(?<=[A-Za-z])'(?=[A-Za-z]))+?)'(?![A-Za-z])"+ r"|「([^」]+)」" # 「…」+ r"|『([^』]+)』" # 『…』+ r"|«([^»]*)»", # «…»re.DOTALL)+# Every CJK block worth treating as "characters, not space-separated words"+# for pacing purposes: hiragana/katakana, the CJK unified ideographs (+ the+# compatibility block), and hangul syllables.+_CJK_CHAR_RE = re.compile(+ r"[-ヿ㐀-䶿一-鿿豈-가-]")+++def spoken_word_count(text: str) -> int:+ """How many "words" of spoken `text` there are, for pacing/frame-fit.++ FILM-45: a plain `.split()` count assumes words are separated by+ whitespace, which is false for Japanese, Chinese and Korean — a spoken+ line with no spaces in it at all counted as ONE word, so+ `speech_fit_frames` (and the overstuffed-line check) massively+ under-timed CJK dialogue. Every CJK character counts as its own word+ here (a working proxy: CJK words run 1-2 characters); anything else+ still splits on whitespace exactly as before, so an English/French/+ German/... line is unaffected.+ """+ t = text or ""+ cjk = len(_CJK_CHAR_RE.findall(t))+ rest = _CJK_CHAR_RE.sub(" ", t)+ return cjk + sum(1 for tok in rest.split() if any(c.isalnum() for c in tok))+def spoken_spans(prompt: str) -> list[str]:- """Every spoken line in `prompt`, tag form and quote form both."""+ """Every spoken line in `prompt`, tag form and every quote form."""p = prompt or ""out = [m.group(1).strip() for m in _D_SPAN_RE.finditer(p)]stripped = _D_SPAN_RE.sub(" ", p)- out += [m.group(1).strip() for m in _Q_SPAN_RE.finditer(stripped)]+ for m in _Q_SPAN_RE.finditer(stripped):+ g = next((grp for grp in m.groups() if grp is not None), None)+ if g:+ out.append(g.strip())return [s for s in out if s]++def speech_fit_frames(word_count: int, fps: int = 24, slow: bool = False,sung: bool = False) -> int:"""The smallest legal frame count (fps*n+1) that fits `word_count` words."""@@ -1288,9 +1431,10 @@ def shot_pacing_problem(prompt: str, duration_s: float) -> str | None:spans = spoken_spans(prompt)if not spans:return None- # Punctuation-only tokens are not words — an em-dash between clauses was- # counted once and pushed a delivered-fine line over the budget.- words = sum(1 for sp in spans for t in sp.split() if any(c.isalnum() for c in t))+ # FILM-45: CJK words have no spaces between them — spoken_word_count()+ # counts each CJK character as its own word rather than folding a whole+ # unspaced line into one giant "word" that .split() would never catch.+ words = sum(spoken_word_count(sp) for sp in spans)try:dur = float(duration_s or 0)except (TypeError, ValueError):@@ -1497,6 +1641,18 @@ def board_wardrobe(board: dict) -> dict[str, str]:return out+def board_light(board: dict) -> str:+ """The board's one shared lighting note (FILM-14, item 4), or "".++ `locations` and `board_wardrobe` fixed the same failure on two other+ axes — a description re-invented per shot drifts across a film that+ renders one shot at a time. `light` is the third: written once, read+ here, and appended by `compose_shot_prompt` to every shot that has not+ rendered yet.+ """+ return str((board or {}).get("light") or "").strip()++_H3_FIELD_BOUNDARY_RE = re.compile(r"\n\s*(?:overall_soundscape|non_diegetic_music)\s*:", re.IGNORECASE)@@ -1519,8 +1675,9 @@ def split_h3_fields(prompt: str) -> tuple[str, str]:def compose_shot_prompt(shot: dict, locations: dict[str, dict] | None = None,- wardrobe: dict[str, str] | None = None) -> str:- """The prompt that is actually rendered: subject, action, FRAME, PLACE.+ wardrobe: dict[str, str] | None = None,+ light: str = "") -> str:+ """The prompt that is actually rendered: subject, action, FRAME, PLACE, LIGHT.Order is deliberate and matches how these models read a prompt — thesubject and what it is doing first, then how it is framed, then where it@@ -1532,6 +1689,14 @@ def compose_shot_prompt(shot: dict, locations: dict[str, dict] | None = None,the shot keeps the sentence a human wrote and editing a location — orflipping an eyeline to fix the 180-degree line — re-flows every shot thatuses it without rewriting anybody's text.++ FILM-14 (item 4): `light` is the same idea as a location, one axis over —+ a cut jumps visibly when each shot re-invents its own lighting the way+ four shots of "dim room" came back as four different rooms before+ locations existed. Written ONCE on the board and appended here, so every+ shot not yet rendered picks it up at its next render with no re-plan —+ a shot already rendered keeps the clip it has; this only reaches the+ ones still to come."""# THE LAST PLACE A PROMPT CAN BE MADE SAFE. Every shot passes through here# on its way to a render, so an a2v shot gets its sync contract here even@@ -1576,6 +1741,14 @@ def compose_shot_prompt(shot: dict, locations: dict[str, dict] | None = None,if scene:parts.append(scene)+ # FILM-14 (item 4): the board's one shared light line, last — same+ # "written once, injected everywhere" shape as the location above, and+ # skipped when the shot already names it so a hand-written lighting+ # note is never doubled.+ light_note = str(light or "").strip().rstrip(",")+ if light_note and light_note.lower() not in ", ".join(parts).lower():+ parts.append(light_note)+if tail:# The description's closing full stop moves to the end of the composed# sentence, so the sound field still follows a finished sentence.@@ -1737,7 +1910,8 @@ def shot_to_job(shot: dict, policy_pass: dict, *,long_windows: bool = False,style: str = "",locations: dict[str, dict] | None = None,- wardrobe: dict[str, str] | None = None) -> dict:+ wardrobe: dict[str, str] | None = None,+ light: str = "") -> dict:"""Translate one storyboard shot into the panel's ORDINARY job form fields.Deliberately produces the same shape a human clicking Generate would produce, so shots@@ -1755,7 +1929,7 @@ def shot_to_job(shot: dict, policy_pass: dict, *,# through on its way to a render. Doing it at the call sites instead would# mean the estimate, the re-render and the gap-fill each getting their own# chance to forget.- prompt = compose_shot_prompt(shot, locations, wardrobe)+ prompt = compose_shot_prompt(shot, locations, wardrobe, light)# The engine. Without this the job dict has no `engine` key, make_job falls back to# ENGINE_DEFAULT ("ltx"), and every H3 shot the planner wrote renders silently on a@@ -1795,6 +1969,9 @@ def shot_to_job(shot: dict, policy_pass: dict, *,chain = h3_chain_prompts_for(shot)if chain:job["h3_chain_prompts"] = json.dumps(chain)+ # Each entry is the WHOLE window's prompt (a continuation+ # holds the settled pose), not a beat to add to window 1's.+ job["h3_chain_prompts_complete"] = "1"# make_job re-stamps geometry from the resolved cell; carrying the cell's own frame# count means the job dict is already self-consistent (and honest in a log or a test)# before it gets there.@@ -1870,7 +2047,7 @@ def shot_to_job(shot: dict, policy_pass: dict, *,if take_secs:job["take_seconds"] = str(take_secs)job["beats"] = json.dumps([- compose_shot_prompt(dict(shot, prompt=b), locations, wardrobe) if b else ""+ compose_shot_prompt(dict(shot, prompt=b), locations, wardrobe, light) if b else ""for b in take_beats_for(shot, take_secs)])if engine != "h3":job["frames"] = take_secs * 24 + 1diff --git a/storyboard_editor.py b/storyboard_editor.pyindex d836853..8324464 100644--- a/storyboard_editor.py+++ b/storyboard_editor.py@@ -73,7 +73,10 @@ __all__ = ["peaks_path", "compute_peaks", "save_peaks", "load_peaks","clip_peaks_path", "clip_peaks", "prune_clip_peaks","edit_path", "load_edit", "save_edit", "validate_edit", "normalise_edit",- "migrate_edit", "clip_kind", "clip_brightness", "clip_carries_media",+ "migrate_edit", "clip_kind", "clip_brightness", "clip_grade",+ "clip_grade_is_neutral", "EXPOSURE_LIMIT", "GRADE_CONTRAST_RANGE",+ "GRADE_SATURATION_RANGE", "GRADE_TEMP_TINT_LIMIT", "FILM_LOOK_PRESETS",+ "film_look_stack", "SEQ_ASPECTS", "markers_of", "clip_carries_media","clip_audio", "clip_audio_drift", "clip_audio_resync", "clip_muted","clip_effects", "clip_length","SOUND_LANES", "clip_sound_lane", "sound_lane_label", "alternate_sound_lanes",@@ -101,11 +104,13 @@ __all__ = ["history_dir", "archive_edit", "prune_history", "list_history","restore_edit","drafts_dir", "load_draft_index", "list_drafts", "create_draft",+ "set_aside_for_replan","duplicate_draft", "rename_draft", "delete_draft", "activate_draft","write_backup", "pending_backup", "recover_backup", "discard_backup","DRAFT_NAME_MAX","export_nle", "NLE_FPS","film_fps", "frame_seconds", "quantise_gap", "heal_subframe_gaps",+ "heal_subframe_lengths",]@@ -134,6 +139,55 @@ CLIP_KINDS = ("video", "still", "slug")# saved document from rendering an hour of white.BRIGHTNESS_LIMIT = 0.5+# FILM-14: the 5-slider grade — exposure, contrast, saturation, temp, tint —+# a sibling of `brightness` under the same `adjust` dict, not a new EDIT_VERSION+# (absent is still neutral, the migration-free rule every field here follows).+# `exposure` shares ffmpeg's `eq=brightness` LEVER with the legacy single+# slider but is a SEPARATE stored number and a separate chained filter node+# (`_sb_grade_term` in mlx_ltx_panel.py) — the two never read each other.+EXPOSURE_LIMIT = 0.5+GRADE_CONTRAST_RANGE = (0.5, 1.8)+GRADE_SATURATION_RANGE = (0.0, 2.5)+GRADE_TEMP_TINT_LIMIT = 1.0++# FILM-14, Render ▾'s "Film look": a whole-film grade next to Grain, applied+# ON TOP of each clip's own per-clip grade — not a hand-authored .cube LUT+# (a real `lut3d` needs a file to ship and calibrate; a preset needs neither+# and reaches the same "one consistent light for the whole film" goal for+# the sizes this app ships at). Fixed points, not deltas from each clip's+# current grade — `film_look_stack` below is what combines the two.+FILM_LOOK_PRESETS: dict[str, dict] = {+ "warm_tungsten": {"temp": 0.30, "tint": -0.05, "saturation": 1.10},+ "neutral": {"tint": -0.04},+}++# FILM-58: the sequence aspect — a whole-film choice, `settings.aspect`,+# next to `settings.film_look`. width/height as a ratio; the render+# center-crops to it (never stretches, never pads) and '16:9' is a no-op —+# every film already renders at its own native shape.+SEQ_ASPECTS: dict[str, tuple[int, int]] = {"16:9": (16, 9), "9:16": (9, 16), "1:1": (1, 1)}+++def film_look_stack(adjust: dict | None, preset_key: str | None) -> dict:+ """A clip's own `adjust` with a Film-look preset folded in — additive+ fields (exposure, temp, tint) sum, the two 1.0-centred fields (contrast,+ saturation) sum their DISTANCE from neutral. The same result a second,+ chained ffmpeg `eq=`/`colorbalance=` node would produce (`_sb_grade_term`+ called twice), done here in the dict because the preset is resolved once+ per film rather than once per low-level filter string.+ """+ out = dict(adjust) if isinstance(adjust, dict) else {}+ preset = FILM_LOOK_PRESETS.get(str(preset_key or "").strip().lower())+ if not preset:+ return out+ for key in ("exposure", "temp", "tint"):+ if key in preset:+ out[key] = round(_f(out.get(key), 0.0) + _f(preset.get(key), 0.0), 6)+ for key in ("contrast", "saturation"):+ if key in preset:+ out[key] = round(_f(out.get(key), 1.0) + (_f(preset.get(key), 1.0) - 1.0), 6)+ return out+# Bumped whenever the proxy RECIPE changes. It is part of the content hash, so# a bump rebuilds every proxy on the next prepare instead of leaving a mixed# population of old and new files that all look equally valid.@@ -171,7 +225,18 @@ TOUCH_TOLERANCE = 1.0 / 48.0# note on a document that is going to disk either way — the rule is that# persisting the user's work always wins, because the alternative was a red# banner over an afternoon of cutting that could not be stored anywhere.-WARNING_CODES = frozenset({"clips_audio_overlap"})+#+# FILM-31: `still_missing` joined this set once it stopped being catastrophic+# to leave in a document. It was blocking because a still with no image "can+# never play" — true when it was written, and no longer true: the assembler+# now renders a missing still's slot as black at its exact length instead of+# dropping it (`_sb_timeline_segments`, FILM-15), and the same check that+# flags the clip is what the Editor now badges "offline" and reads the render+# will be safe with (`_sbe_payload`'s `offline` list). One trashed still used+# to make the WHOLE FILM impossible to save or back up — `write_backup` and+# `save_edit` both refuse on a blocking error — which is a strictly worse+# outcome than the thing it was trying to prevent.+WARNING_CODES = frozenset({"clips_audio_overlap", "still_missing"})class EditError(Exception):@@ -303,6 +368,36 @@ def clip_brightness(clip) -> float:return max(-BRIGHTNESS_LIMIT, min(BRIGHTNESS_LIMIT, b))+def clip_grade(clip) -> dict:+ """`{exposure, contrast, saturation, temp, tint}`, clamped — FILM-14's+ 5-slider grade. `{0.0, 1.0, 1.0, 0.0, 0.0}` (neutral) for a clip that has+ none, the same "absent is neutral" rule `clip_brightness` follows.+ """+ if not isinstance(clip, dict):+ adj = {}+ else:+ adj = clip.get("adjust")+ adj = adj if isinstance(adj, dict) else {}+ lo_c, hi_c = GRADE_CONTRAST_RANGE+ lo_s, hi_s = GRADE_SATURATION_RANGE+ t = GRADE_TEMP_TINT_LIMIT+ return {+ "exposure": round(max(-EXPOSURE_LIMIT, min(EXPOSURE_LIMIT,+ _f(adj.get("exposure"), 0.0))), 6),+ "contrast": round(max(lo_c, min(hi_c, _f(adj.get("contrast"), 1.0))), 6),+ "saturation": round(max(lo_s, min(hi_s, _f(adj.get("saturation"), 1.0))), 6),+ "temp": round(max(-t, min(t, _f(adj.get("temp"), 0.0))), 6),+ "tint": round(max(-t, min(t, _f(adj.get("tint"), 0.0))), 6),+ }+++def clip_grade_is_neutral(clip) -> bool:+ g = clip_grade(clip)+ return (abs(g["exposure"]) < 1e-9 and abs(g["contrast"] - 1.0) < 1e-9+ and abs(g["saturation"] - 1.0) < 1e-9+ and abs(g["temp"]) < 1e-9 and abs(g["tint"]) < 1e-9)++def clip_audio(clip) -> dict:"""The clip's SOUND window: `{start, end, film_start, linked}`.@@ -549,8 +644,14 @@ def clip_effects(clip) -> dict:# ramp", and silently zeroing the out-fade is not that.total = fin + foutfin, fout = fin - over * (fin / total), fout - over * (fout / total)- return {"fade_in": round(fin, 6), "fade_out": round(fout, 6),- "brightness": clip_brightness(c)}+ # FILM-14: the 5-slider grade rides the same accessor brightness does —+ # "every output reads this and nothing else" is the whole point, and a+ # second accessor for a second adjustment would just be the brightness+ # mistake (three code paths that can disagree) made again on purpose.+ out = {"fade_in": round(fin, 6), "fade_out": round(fout, 6),+ "brightness": clip_brightness(c)}+ out.update(clip_grade(c))+ return out# ---------------------------------------------------------------------------@@ -790,6 +891,26 @@ def overlay_items(edit) -> list[dict]:return out+def markers_of(edit) -> list[dict]:+ """FILM-58: every marker, on the film's clock, in time order. Absent is+ no markers — the same "empty lane" rule `overlay_items` follows."""+ rows = (edit or {}).get("markers")+ if not isinstance(rows, list):+ return []+ out = []+ for m in rows:+ if not isinstance(m, dict):+ continue+ at = _f(m.get("at"))+ if at < 0:+ continue+ kind = m.get("kind") if m.get("kind") in ("beat", "lyric", "note") else "note"+ out.append({"id": m.get("id") or "", "at": round(at, 6), "kind": kind,+ "label": str(m.get("label") or "")})+ out.sort(key=lambda m: (m["at"], m["id"]))+ return out++# ---------------------------------------------------------------------------# THE SOUND'S OWN ENVELOPE — fades, and the keyframes underneath them# ---------------------------------------------------------------------------@@ -2575,17 +2696,38 @@ def validate_edit(edit) -> list[dict]:if not isinstance(adj, dict):bad("clip_adjust", f"clip {i + 1}: adjust must be an object "f"or absent", i)- elif adj.get("brightness") is not None:- b = adj.get("brightness")- if not isinstance(b, (int, float)) or isinstance(b, bool) \- or b != b or b in (float("inf"), float("-inf")):- bad("clip_brightness",- f"clip {i + 1}: adjust.brightness must be a number", i)- elif abs(float(b)) > BRIGHTNESS_LIMIT + 1e-9:- bad("clip_brightness_range",- f"clip {i + 1}: adjust.brightness is {float(b):+.3f} — "- f"it must be between {-BRIGHTNESS_LIMIT:+.1f} and "- f"{BRIGHTNESS_LIMIT:+.1f}", i)+ else:+ if adj.get("brightness") is not None:+ b = adj.get("brightness")+ if not isinstance(b, (int, float)) or isinstance(b, bool) \+ or b != b or b in (float("inf"), float("-inf")):+ bad("clip_brightness",+ f"clip {i + 1}: adjust.brightness must be a number", i)+ elif abs(float(b)) > BRIGHTNESS_LIMIT + 1e-9:+ bad("clip_brightness_range",+ f"clip {i + 1}: adjust.brightness is {float(b):+.3f} — "+ f"it must be between {-BRIGHTNESS_LIMIT:+.1f} and "+ f"{BRIGHTNESS_LIMIT:+.1f}", i)+ # FILM-14: the 5-slider grade. Same shape as brightness —+ # absent is neutral, present must be a finite number inside+ # its own range.+ for key, lo, hi in (+ ("exposure", -EXPOSURE_LIMIT, EXPOSURE_LIMIT),+ ("contrast", *GRADE_CONTRAST_RANGE),+ ("saturation", *GRADE_SATURATION_RANGE),+ ("temp", -GRADE_TEMP_TINT_LIMIT, GRADE_TEMP_TINT_LIMIT),+ ("tint", -GRADE_TEMP_TINT_LIMIT, GRADE_TEMP_TINT_LIMIT)):+ v = adj.get(key)+ if v is None:+ continue+ if not isinstance(v, (int, float)) or isinstance(v, bool) \+ or v != v or v in (float("inf"), float("-inf")):+ bad("clip_grade",+ f"clip {i + 1}: adjust.{key} must be a number", i)+ elif not (lo - 1e-9 <= float(v) <= hi + 1e-9):+ bad("clip_grade_range",+ f"clip {i + 1}: adjust.{key} is {float(v):+.3f} — "+ f"it must be between {lo:+.2f} and {hi:+.2f}", i)fr = c.get("frame")if fr is not None:if not isinstance(fr, dict):@@ -2837,6 +2979,32 @@ def validate_edit(edit) -> list[dict]:if t.get("problem"):bad(t["problem"]["code"], t["problem"]["message"],t.get("out_index"))+ # FILM-58: MARKERS. A marker names a SECOND on the film, not a clip, so+ # it has nothing to overlap and nothing to be too short — the only+ # things worth refusing are the shape and an `at` that is not a real+ # number.+ mkr = edit.get("markers") if isinstance(edit, dict) else None+ if mkr is not None and not isinstance(mkr, list):+ bad("markers_shape", "markers must be a list or absent")+ elif isinstance(mkr, list):+ for n, m in enumerate(mkr):+ if not isinstance(m, dict):+ bad("marker_shape", f"marker {n + 1}: must be an object")+ continue+ at = m.get("at")+ if not isinstance(at, (int, float)) or isinstance(at, bool) \+ or at != at or at in (float("inf"), float("-inf")):+ bad("marker_at", f"marker {n + 1}: at must be a number")+ elif float(at) < 0:+ bad("marker_at_range", f"marker {n + 1}: at must be >= 0")+ if m.get("kind") is not None and m.get("kind") not in ("beat", "lyric", "note"):+ bad("marker_kind",+ f"marker {n + 1}: kind must be beat, lyric or note")+ # FILM-58: SEQUENCE ASPECT — a whole-film choice, not a per-clip one.+ aspect = (edit.get("settings") or {}).get("aspect") if isinstance(edit.get("settings"), dict) else None+ if aspect is not None and aspect not in SEQ_ASPECTS:+ bad("settings_aspect", "settings.aspect must be one of "+ + ", ".join(sorted(SEQ_ASPECTS)))spans.sort()for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(spans, spans[1:]):if b_s < a_e - TOUCH_TOLERANCE:@@ -2899,6 +3067,87 @@ def _digest_clip(c) -> dict:return out+# FILM-54: what to CALL a field, in the recovery bar's own words — never the+# document's key. "adjust" is handled separately (it is one number a person+# actually watches move).+_DIFF_FIELD_LABELS = {+ "mute": "mute", "locked": "lock", "speed": "speed",+ "frame": "reframe", "fx": "fade", "audio": "sound",+ "path": "file", "kind": "kind", "adjust": "brightness",+}+++def _clip_diff_fields(old: dict, new: dict) -> list[str]:+ """Field-level differences between two digest-normalised clips, named+ the way a person would say them rather than the way the document does.+ """+ out: list[str] = []+ for k in sorted(set(old) | set(new)):+ if old.get(k) == new.get(k):+ continue+ if k == "adjust":+ ob = _f((old.get("adjust") or {}).get("brightness"))+ nb = _f((new.get("adjust") or {}).get("brightness"))+ if abs(ob - nb) < 1e-6:+ continue # something else under "adjust" moved+ delta = nb - ob+ out.append("brightness " + (f"+{delta:.2f}" if delta >= 0 else f"{delta:.2f}"))+ elif k in ("film_start", "film_end"):+ if "moved" not in out:+ out.append("moved")+ elif k in ("start", "end"):+ if "trimmed" not in out:+ out.append("trimmed")+ else:+ out.append(_DIFF_FIELD_LABELS.get(k, k))+ return out+++def edit_diff_summary(old: dict, new: dict) -> str:+ """One line: what changed between two documents, in the vocabulary a+ person used to make the change — "1 clip changed: 02 brightness +0.30" —+ built from the exact normalised shape `edit_digest` already hashes, so+ the two can never disagree about whether there IS a difference.++ THE BUG THIS EXISTS FOR: the recovery bar could say a backup and the+ saved draft held the same clip count and the same duration and STILL be+ the reason a chip was up — because what actually differed was one+ brightness value, and the bar had no vocabulary for that: "a backup from+ 3 min ago holds 10 clip(s), 2:51 — the saved draft has 10, 2:51." A+ question about a difference it could not name.+ """+ o = old if isinstance(old, dict) else {}+ n = new if isinstance(new, dict) else {}+ o_clips = [_digest_clip(c) for c in (o.get("clips") or []) if isinstance(c, dict)]+ n_clips = [_digest_clip(c) for c in (n.get("clips") or []) if isinstance(c, dict)]+ o_by_id = {c.get("id"): (i, c) for i, c in enumerate(o_clips) if c.get("id")}+ n_by_id = {c.get("id"): (i, c) for i, c in enumerate(n_clips) if c.get("id")}+ changed: list[tuple[int, list[str]]] = []+ for cid, (idx, nc) in n_by_id.items():+ if cid in o_by_id:+ oc = o_by_id[cid][1]+ if oc != nc:+ changed.append((idx, _clip_diff_fields(oc, nc)))+ added = [cid for cid in n_by_id if cid not in o_by_id]+ removed = [cid for cid in o_by_id if cid not in n_by_id]+ other_labels = {"audio": "soundtrack", "overlays": "titles/cards",+ "transitions": "transitions", "audio_tracks": "sound tracks",+ "beats": "beat grid"}+ other = [label for key, label in other_labels.items() if o.get(key) != n.get(key)]+ if len(changed) == 1 and not added and not removed and not other:+ idx, fields = changed[0]+ return f"1 clip changed: {idx + 1:02d} {fields[0] if fields else 'changed'}"+ bits = []+ if changed:+ bits.append(f"{len(changed)} clip{'s' if len(changed) != 1 else ''} changed")+ if added:+ bits.append(f"{len(added)} added")+ if removed:+ bits.append(f"{len(removed)} removed")+ bits.extend(other)+ return ", ".join(bits) if bits else "changed"++def edit_digest(edit) -> str:"""A canonical fingerprint of the ARRANGEMENT, and nothing else.@@ -3197,7 +3446,23 @@ def normalise_edit(edit: dict) -> dict:adj = c.get("adjust")if isinstance(adj, dict):b = clip_brightness(c)- rest = {k: v for k, v in adj.items() if k != "brightness"}+ g = clip_grade(c)+ rest = {k: v for k, v in adj.items()+ if k not in ("brightness", "exposure", "contrast",+ "saturation", "temp", "tint")}+ # FILM-14: the grade, written back CLAMPED and neutral-is-absent+ # per field — the same rule brightness follows, applied five+ # more times rather than reinvented for them.+ if abs(g["exposure"]) >= 1e-9:+ rest["exposure"] = g["exposure"]+ if abs(g["contrast"] - 1.0) >= 1e-9:+ rest["contrast"] = g["contrast"]+ if abs(g["saturation"] - 1.0) >= 1e-9:+ rest["saturation"] = g["saturation"]+ if abs(g["temp"]) >= 1e-9:+ rest["temp"] = g["temp"]+ if abs(g["tint"]) >= 1e-9:+ rest["tint"] = g["tint"]# NEUTRAL IS ABSENT. Dragging the slider back to zero must leave a# document identical to one that never had a slider, or every clip# anyone ever touched carries a dead field forever.@@ -3452,6 +3717,24 @@ def save_edit(board_dir, edit: dict, *, bump: bool = True,raise EditError("; ".join(e["message"] for e in errs[:6])+ (f" (+{len(errs) - 6} more)" if len(errs) > 6 else ""))doc = normalise_edit(edit)+ # FILM-51: heal AFTER validate_edit has passed, never before — healing+ # can rewrite a clip's own `end`, and running it on a document nothing+ # has checked yet can recompute a plausible `end` for one that should+ # have been refused (see heal_subframe_lengths' own docstring). Every+ # manual save is a frame-exact document from here on, so an edit that+ # never triggers this function's OTHER call site (the render path, for+ # a film saved before this existed) still converges the next time a+ # human saves it.+ # EDITOR-3 (Codex 4.17.0): ...AND CHECK WHAT THE HEAL PRODUCED before it+ # is written. Validation used to run only on the document as sent, so a+ # heal that moved a clip into a locked one was saved as `clips_overlap`+ # and every render afterwards refused the film. The heal is bounded now;+ # this is the backstop — a healed document that no longer validates is+ # never written, and the user's own (valid) arrangement is saved as sent.+ healed = json.loads(json.dumps(doc))+ heal_subframe_lengths(healed)+ if not blocking_errors(validate_edit(healed)):+ doc = healedwith board_write_lock(board_dir):return _save_edit_locked(board_dir, doc, bump=bump, origin=origin,expect=expect, expect_draft=expect_draft)@@ -3546,6 +3829,19 @@ _AUTO_PREFIX = "edit-r"# appeared. A lane that stops is not a safety net. See# docs/EDITOR_SAVE_MODEL.md §2._SNAP_PREFIX = "snap-"+# FILM-57: RETENTION BY TIME, NOT COUNT. A flat count of 20 read as "about+# 30 s of active editing" once the digest dedup above stopped burning slots+# on no-op re-backups — the SAME 20-file cap that used to protect against a+# runaway loop was, once that loop was fixed at the source, just a small+# window on real work. A day of cutting a film now keeps its own history;+# `SNAPSHOT_HARD_CAP` stays as the one thing that still counts files, and+# only so a genuinely pathological burst (a bug elsewhere hammering the+# backup route) cannot fill a disk — it is far above anything a real+# editing session reaches.+SNAPSHOT_KEEP_HOURS = 24+SNAPSHOT_HARD_CAP = 500+# Retained for anything that still imports the old name (docs, older+# comments); prune_snapshots no longer keys off it by default.SNAPSHOT_KEEP = 20_KEPT_PREFIX = "keep-r"_MANUAL_PREFIX = "save-r"@@ -3914,6 +4210,142 @@ def heal_subframe_gaps(edit: dict) -> list[dict]:return closed+def heal_subframe_lengths(edit: dict) -> list[dict]:+ """FILM-51: round every clip's FILM length to the frame grid. Mutates+ `edit`. Returns one row per clip corrected, so a caller can say what it+ did — the same shape `heal_subframe_gaps` answers with.++ MEASURED (`test_editor_film_frame_lock.py`): the render trims each+ segment on its OWN local clock (`setpts=PTS-STARTPTS` then `fps=`), so+ ffmpeg's `fps=` filter rounds a sub-frame-length segment to the nearest+ frame INDEPENDENTLY of every other segment, while the song is laid out+ on the exact (unrounded) timeline. On a synthetic 52-cut film built from+ realistic non-frame-aligned windows the two clocks drifted apart by+ more than a frame well before the last cut. Once every clip's length+ already IS a whole number of frames, `fps=` has nothing left to round+ and the picture cannot come apart from the song no matter how many cuts+ follow — fixed here, at the model, rather than in the render graph,+ so nothing about how a segment is trimmed, faded or transitioned has+ to change to get it.++ A clip's length grows or shrinks at its TAIL — `end` moves, `start`+ never does — the same convention every other tail-trim in this file+ already uses; a still or a slug has no source window of its own,+ `normalise_edit` derives theirs from the slot. Gaps are UNTOUCHED+ (this is a length fix, not `heal_subframe_gaps`'s job); a locked clip+ is an anchor exactly as it is there, and the shift a length correction+ hands to everything after it is reset at one.++ STILL NOT CALLED FROM `load_edit`. Unlike the gap heal, this can+ rewrite a clip's own `end` — and doing that unconditionally on every+ read can recompute a PLAUSIBLE `end` for a clip whose document has not+ been validated yet, which is worse than the drift it fixes: a+ genuinely corrupt saved/history document could stop looking corrupt+ before `validate_edit` ever saw it (see+ test_a_genuinely_broken_version_is_STILL_refused,+ test_storyboard_editor_api.py — the regression that proved this).+ CALL THIS ONLY AFTER `validate_edit` HAS PASSED THE DOCUMENT. Its two+ callers: `save_edit` (right after `validate_edit`/`normalise_edit`, so+ every document a human saves converges) and+ `mlx_ltx_panel._sbe_render_edit` (its own `validate_edit` check, then+ this, before `edit_to_cuts` — so an OLDER film saved before this fix+ existed still renders frame-exact without needing a resave first).+ """+ if not isinstance(edit, dict):+ return []+ clips = [c for c in (edit.get("clips") or []) if isinstance(c, dict)]+ clips.sort(key=lambda c: _f(c.get("film_start")))+ frame = frame_seconds(edit)+ # Below this, a length is ALREADY frame-exact — everything here is+ # stored `round(x, 6)`, and 1/24 has no exact 6-decimal form, so a+ # value built from a whole number of frames can read back a few+ # microseconds off its own target. Comparing at raw float precision+ # (1e-9) would "fix" that noise forever, reporting a repair that did+ # nothing and never reaching a stable, idempotent document. Real drift+ # — the thing this function exists to remove — is one to two orders of+ # magnitude larger (up to half a frame, ~20 ms at 24 fps).+ NOISE = 1e-4++ def _plan(run: list[dict], floor: bool) -> list[tuple]:+ """What healing `run` would do, WITHOUT touching it: one row per+ clip — (clip, new source end or None, film start, film length,+ length change, frames, old length, old start)."""+ rows: list[tuple] = []+ shift = 0.0+ for c in run:+ fs0, fe0 = _f(c.get("film_start")), _f(c.get("film_end"))+ length = fe0 - fs0+ if length <= 0:+ continue+ if floor:+ frames = max(1, math.floor(length / frame + NOISE / frame))+ else:+ frames = max(1, round(length / frame))+ length_q = frames * frame+ d = length_q - length+ new_end = None+ # NEVER PAST THE TAKE'S OWN END. A correction that would ask for+ # source the file does not have is skipped rather than clamped — a+ # clamp would silently leave the stored film length and the source+ # window disagreeing by the very sub-frame amount this pass exists+ # to remove. Skipping costs nothing downstream: `shift` (below)+ # still carries whatever earlier clips already corrected, so this+ # clip's POSITION stays right even when its own length does not.+ if abs(d) > NOISE and clip_kind(c) == "video":+ sp = clip_speed(c)+ ne = _f(c.get("start")) + length_q * sp+ dur = c.get("duration")+ if isinstance(dur, (int, float)) and dur > 0 and ne > float(dur) + 1e-6:+ d, length_q = 0.0, length+ else:+ new_end = ne+ rows.append((c, new_end, fs0 + shift, length_q, d, frames, length, fs0))+ shift += d+ return rows++ # A LOCKED CLIP IS AN ANCHOR, and the clips between two anchors are one+ # run: their corrections accumulate as a `shift` that moves everything+ # after them in the run, and the next anchor does not move. EDITOR-3+ # (Codex 4.17.0): that shift used to be reset at the anchor WITHOUT ever+ # being checked against it, so two 0.98 s clips before a clip locked at+ # 1.96 s (24 fps) each grew to 1.0 s and the second one ran 40 ms INTO+ # the locked clip — a `clips_overlap` document, written by Save after+ # validation had passed, that the render then refused. A run whose+ # rounded-to-nearest lengths would cross the next anchor is healed by+ # rounding DOWN instead: every length change is then ≤ 0, so nothing in+ # the run moves later and nothing can reach the anchor.+ fixed: list[dict] = []+ runs: list[tuple[list[dict], float | None]] = []+ cur: list[dict] = []+ for c in clips:+ if c.get("locked"):+ runs.append((cur, _f(c.get("film_start"))))+ cur = []+ else:+ cur.append(c)+ runs.append((cur, None))+ for run, anchor in runs:+ if not run:+ continue+ rows = _plan(run, floor=False)+ if anchor is not None and rows and \+ max(r[2] + r[3] for r in rows) > max(anchor, max(r[7] + r[6] for r in rows)) + NOISE:+ rows = _plan(run, floor=True)+ for c, new_end, fs, length_q, d, frames, length, fs0 in rows:+ if new_end is not None:+ c["end"] = round(new_end, 6)+ if abs(d) > NOISE:+ fixed.append({"id": c.get("id"), "was": round(length, 6),+ "now": round(length_q, 6), "frames": frames})+ if abs(fs - fs0) > NOISE or abs(d) > NOISE:+ c["film_start"] = round(fs, 6)+ c["film_end"] = round(fs + length_q, 6)+ aud = c.get("audio")+ if isinstance(aud, dict) and aud.get("film_start") is not None:+ aud["film_start"] = round(_f(aud.get("film_start")) + (fs - fs0), 6)+ return fixed++def heal_mix(edit: dict) -> bool:"""Write the render's old hidden levels onto a document that predates thecontrols. Mutates `edit`; True when it wrote something.@@ -4033,6 +4465,18 @@ def migrate_edit(edit: dict) -> dict:edit["healed_subframe_gaps"] = healedelse:edit.pop("healed_subframe_gaps", None)+ # FILM-51's `heal_subframe_lengths` is deliberately NOT run here yet.+ # Unlike the gap heal above (which only ever moves `film_start`), it can+ # rewrite a clip's own `end` — and wiring it into every load surfaced a+ # real hazard in this suite: a save-history entry deliberately corrupted+ # for `test_a_genuinely_broken_version_is_STILL_refused` stopped being+ # refused, because the heal recomputed a plausible `end` for the clip+ # BEFORE validation ever saw the corrupt one. It is correct and tested on+ # its own (`test_editor_film_frame_lock.py`) and ready to call explicitly+ # once it runs strictly after `validate_edit` has passed a document, not+ # before. Do not wire this into `load_edit` without that ordering fixed+ # and a full-suite pass proving no other read path can hand it a+ # not-yet-validated document.return edit@@ -4090,8 +4534,37 @@ def edit_to_cuts(edit: dict) -> list[dict]:if kind != "video":entry["kind"] = kindb = clip_brightness(c)+ adj_out: dict = {}if abs(b) >= 1e-9:- entry["adjust"] = {"brightness": round(b, 6)}+ adj_out["brightness"] = round(b, 6)+ # FILM-14: the grade reaches the render the same way brightness+ # does — through this same plan entry, which `_sb_grade_term`+ # (mlx_ltx_panel.py) reads — so "match colour", the per-clip+ # sliders AND the whole-film Film-look preset all land in the film+ # render, not only the preview. A slug has no colour to grade, and+ # the preset applies even to a clip with no grade of its own — it is+ # a whole-film choice, not conditional on the clip already having one.+ if kind != "slug":+ settings = (edit or {}).get("settings")+ settings = settings if isinstance(settings, dict) else {}+ look = settings.get("film_look")+ stacked = film_look_stack(c.get("adjust"), look) if look else clip_grade(c)+ if not look:+ pass # `stacked` is already clip_grade(c)'s clamped shape+ else:+ # `film_look_stack` returns the RAW combination; run it back+ # through `clip_grade` so it is clamped the same way a+ # hand-set value would be.+ stacked = clip_grade({"adjust": stacked})+ neutral = (abs(stacked["exposure"]) < 1e-9+ and abs(stacked["contrast"] - 1.0) < 1e-9+ and abs(stacked["saturation"] - 1.0) < 1e-9+ and abs(stacked["temp"]) < 1e-9 and abs(stacked["tint"]) < 1e-9)+ if not neutral:+ for key in ("exposure", "contrast", "saturation", "temp", "tint"):+ adj_out[key] = stacked[key]+ if adj_out:+ entry["adjust"] = adj_outif kind != "slug" and not clip_frame_is_neutral(c):entry["frame"] = clip_frame(c)if kind == "video":@@ -4132,6 +4605,26 @@ def edit_to_cuts(edit: dict) -> list[dict]:if c.get("id"):by_id[str(c["id"])] = entryout.sort(key=lambda e: e["film_start"])+ # FILM-27: A HOLE IS NOT NOTHING. The assembler below CONCATENATES — it+ # lays these entries end to end with no notion of the film-second each+ # was cut to — so a gap between two clips used to vanish rather than+ # play: everything after it slid earlier, off the beat it was cut to,+ # behind a native confirm() that only ever fired once, at Render, and+ # said nothing about WHERE. `edit_gaps` is the exact list the timeline+ # already computes for its own "N holes" disclosure (`edit_to_cuts` and+ # the header's hole count now agree by construction, not by two people+ # reimplementing the same cursor walk). Filling each one with a slug —+ # the same synthetic entry "Add black" already produces by hand — is the+ # one change that makes the export match what every later clip's+ # `film_start` already claimed, instead of quietly breaking that promise.+ for g in edit_gaps(edit):+ dur = round(g["duration"], 6)+ if dur <= 0:+ continue+ out.append({"path": None, "start": 0.0, "end": dur,+ "film_start": round(g["film_start"], 6), "kind": "slug"})+ if out:+ out.sort(key=lambda e: e["film_start"])# THE TRANSITIONS RIDE ON THE ENTRIES THEY JOIN: `transition` on the# outgoing entry, `tx_in` (the extra head, in seconds) on the incoming.# Only a transition that resolved without a problem is stamped — one the@@ -4406,12 +4899,18 @@ def _link_or_copy(src: Path, dest: Path, *, link=None) -> str:return "copy"-def _nle_segments(clips, *, probe=None) -> list[dict]:+def _nle_segments(clips, *, probe=None, film_look: str | None = None) -> list[dict]:"""The export's own view of the timeline: one row per clip, in film order.`probe` answers {"w","h","duration"} for a file and is injected rather thanimported, for the same reason `compute_peaks` takes a decoder: this moduleruns no subprocess of its own, and the panel already owns ffprobe.++ `film_look` is `settings.film_look`. EDITOR-14 (Codex 4.17.0): the render+ folds the whole-film look into every picture's grade (`film_look_stack`,+ in the render plan) and the export never saw it — a Warm-tungsten film+ reached After Effects neutral. Folded here the same way, clamped the+ same way, so each row's `fx` grade is the one the render draws."""rows: list[dict] = []for c in clips or []:@@ -4434,7 +4933,11 @@ def _nle_segments(clips, *, probe=None) -> list[dict]:info = probe(path) or {}except Exception: # noqa: BLE001info = {}+ fx = clip_effects(c)+ if film_look and kind != "slug":+ fx.update(clip_grade({"adjust": film_look_stack(c.get("adjust"), film_look)}))rows.append({+ "id": str(c.get("id") or ""),"kind": kind,"path": path,"title": str(c.get("title") or (Path(path).stem if path else "black")),@@ -4442,7 +4945,7 @@ def _nle_segments(clips, *, probe=None) -> list[dict]:"film_start": fs, "film_end": fe,"brightness": clip_brightness(c),"frame": clip_frame(c),- "fx": clip_effects(c),+ "fx": fx,"w": int(info.get("w") or 0), "h": int(info.get("h") or 0),"has_audio": bool(info.get("has_audio")),"gain": audio_gain_points(c, clip_audio(c)["len"])@@ -4555,6 +5058,43 @@ def _fcp7_motion(seg: dict) -> str:"</effect></filter>")+def _fcp7_transitionitem(entry: dict, fps: int = NLE_FPS) -> str:+ """The `<transitionitem>` bridging two clipitems the caller has already+ extended to overlap by `entry['half_frames']` on each side.++ `Cross Dissolve` and `Dip to Color Dissolve` are FCP7's own standard+ transition names/effect ids — the two Premiere and Resolve both ship —+ so this needs no custom effect definition to be understood on either+ side. `Dip to Color Dissolve` carries an explicit `Color` parameter+ (defaulted black by the effect itself, stated here anyway rather than+ relied upon) since "dip to WHAT colour" is the one thing the name alone+ does not say.+ """+ at = entry["at_frames"]+ half = entry["half_frames"]+ start, end = at - half, at + half+ is_black = entry["kind"] == "fade_black"+ name = "Dip to Color Dissolve" if is_black else "Cross Dissolve"+ color_param = (+ "<parameter><parameterid>Color</parameterid><name>Color</name>"+ "<value><alpha>255</alpha><red>0</red><green>0</green><blue>0</blue>"+ "</value></parameter>") if is_black else ""+ return (+ "<transitionitem>"+ f"<start>{start}</start><end>{end}</end>"+ "<alignment>center</alignment>"+ f"{_fcp7_rate(fps)}"+ "<effect>"+ f"<name>{_xml_text(name)}</name>"+ f"<effectid>{_xml_text(name)}</effectid>"+ "<effectcategory>Dissolve</effectcategory>"+ "<effecttype>transition</effecttype>"+ "<mediatype>video</mediatype>"+ f"{color_param}"+ "</effect>"+ "</transitionitem>")++def _fcp7_rate(fps: int = NLE_FPS) -> str:# ntsc FALSE is load-bearing: at ntsc TRUE an NLE reads timebase 24 as# 23.976 and every cut past the first drifts one frame per 1000.@@ -4593,10 +5133,65 @@ def _fcp7_file(fid: str, seg: dict, media_abs: Path, *, fps: int,return "".join(body)+def _fcp7_markers(markers: list[dict] | None, fps: int) -> str:+ """FILM-58: every `markers_of(edit)` row as a SEQUENCE-level `<marker>` —+ xmeml's own kind, the one both Premiere and Resolve show on the ruler+ rather than on a track. `<out>-1</out>` is xmeml's own spelling of "this+ is a point, not a range" — the only kind FILM-58's markers are.++ The label is the marker's NAME (blank reads as "Marker N" in the NLE,+ which is not nothing but is not what the editor typed either); the kind+ always goes in the COMMENT, so "beat"/"lyric"/"note" survives even when+ the editor never gave the marker its own words.+ """+ if not markers:+ return ""+ out = []+ for m in markers:+ label = str(m.get("label") or "").strip() or m["kind"].capitalize()+ out.append(+ "<marker>"+ f"<name>{_xml_text(label)}</name>"+ f"<comment>{_xml_text(m['kind'])}</comment>"+ f"<in>{_frames(m['at'], fps)}</in>"+ "<out>-1</out>"+ "</marker>")+ return "".join(out)+++def _nle_transitions(clips, transitions, fps: int = NLE_FPS) -> dict:+ """The document's transitions, resolved and keyed for the export.++ Reuses `resolve_transitions` — the SAME resolver the render and the+ validator use — rather than re-deriving handle math here, so a boundary+ the render can draw is a boundary the export can draw and a boundary the+ render refuses (no spare source, an unknown clip, a duplicate) is simply+ absent from the XML/JSX rather than exported as a transition that would+ then need its own re-validation. Returns `{"out": {clip_id: entry},+ "in": {clip_id: entry}}`, each entry `{kind, half_frames, at_frames,+ half_sec, at_sec}` — both units, since FCP7 XML counts frames and the AE+ script (seconds throughout, like the rest of `ae_jsx`) does not.+ """+ edit = {"clips": clips, "transitions": transitions}+ out_map: dict = {}+ in_map: dict = {}+ for t in resolve_transitions(edit):+ if t.get("problem"):+ continue+ entry = {"kind": t["kind"], "half_frames": _frames(t["half"], fps),+ "at_frames": _frames(t["at"], fps),+ "half_sec": t["half"], "at_sec": t["at"]}+ out_map[t["after_clip"]] = entry+ in_map[t["before_clip"]] = entry+ return {"out": out_map, "in": in_map}++def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,base, fps: int = NLE_FPS, audio: dict | None = None,overlays: list | None = None,- audio_tracks: list | None = None) -> str:+ audio_tracks: list | None = None,+ transitions: dict | None = None,+ markers: list[dict] | None = None) -> str:"""The sequence, as the one XML both Premiere and Resolve import.SLUGS ARE GAPS. A slug could be written as a `<generatoritem>` with the@@ -4626,6 +5221,8 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,mdir = Path(str(base)) / "media"file_ids: dict = {}total = max([_frames(s["film_end"], fps) for s in segments] or [0])+ tx = transitions or {"out": {}, "in": {}}+ v_entries: list = [] # (clip_id, xml) — post-processed into v_items belowv_items, a_items, b_items = [], [], []for i, seg in enumerate(segments):if seg["kind"] == "slug":@@ -4642,7 +5239,25 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,# the film plays, in the wrong order, at the wrong lengths.f_in, f_out = _frames(seg["start"], fps), _frames(seg["end"], fps)f_s, f_e = _frames(seg["film_start"], fps), _frames(seg["film_end"], fps)- v_items.append(+ # THE AUDIO CLIPITEM KEEPS ITS OWN, UNEXTENDED NUMBERS — "the audio+ # plan never sees the extension" (TRANSITION_KINDS' own docstring):+ # only the PICTURE crossfades; the clip's sound stays a hard cut at+ # the original boundary, exactly as the render already does it.+ av_in, av_out, av_s, av_e = f_in, f_out, f_s, f_e+ # FILM-50: A TRANSITION EXTENDS THE CLIPITEM, NEVER THE SEGMENT. The+ # extra picture comes from spare SOURCE material beyond the trim+ # (the render's own model — see TRANSITION_KINDS' docstring) so only+ # the local frame numbers written into THIS tag grow; `seg` itself+ # stays untouched, which matters because `_fcp7_opacity` below reads+ # `seg`'s own film_start/film_end for an unrelated fade and must not+ # see a boundary that moved for a different reason.+ out_tx = tx["out"].get(seg.get("id"))+ in_tx = tx["in"].get(seg.get("id"))+ if out_tx:+ f_e += out_tx["half_frames"]; f_out += out_tx["half_frames"]+ if in_tx:+ f_s -= in_tx["half_frames"]; f_in -= in_tx["half_frames"]+ v_entries.append((seg.get("id"),f'<clipitem id="clipitem-{i + 1}">'f"<name>{_xml_text(seg['title'])}</name>"f"<enabled>TRUE</enabled>"@@ -4654,7 +5269,7 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,f"<compositemode>normal</compositemode>"f"{_fcp7_motion(seg)}"f"{_fcp7_opacity(seg, fps)}"- f"</clipitem>")+ f"</clipitem>"))if seg["has_audio"]:# DISABLED, NOT DELETED. A muted clip whose audio clipitem was# simply omitted would arrive in Premiere as a shot that never had@@ -4666,15 +5281,32 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,f'<clipitem id="clipitem-a{i + 1}">'f"<name>{_xml_text(seg['title'])}</name>"f"<enabled>{'FALSE' if seg.get('muted') else 'TRUE'}</enabled>"- f"<duration>{max(1, f_out - f_in)}</duration>"+ f"<duration>{max(1, av_out - av_in)}</duration>"f"{_fcp7_rate(fps)}"- f"<start>{f_s}</start><end>{f_e}</end>"- f"<in>{f_in}</in><out>{f_out}</out>"+ f"<start>{av_s}</start><end>{av_e}</end>"+ f"<in>{av_in}</in><out>{av_out}</out>"f'<file id="{_xml_text(fid)}"/>'f"<sourcetrack><mediatype>audio</mediatype>"f"<trackindex>1</trackindex></sourcetrack>"f"{_fcp7_levels(seg.get('gain'), fps)}"f"</clipitem>")+ # A TRANSITIONITEM ONLY WHEN BOTH SIDES ACTUALLY PRODUCED A CLIPITEM. A+ # transition resolved against a slug (TRANSITION_KINDS allows one — a+ # slug has no source clock, so `_spare_source` never refuses it) has+ # nothing on the OTHER side to bridge: a slug is a GAP in this track, not+ # a clipitem, so it is left as the plain cut it already was rather than+ # exported as a half-transition with nothing to dissolve into.+ for k in range(len(v_entries) - 1):+ cur_id, cur_xml = v_entries[k]+ nxt_id, _ = v_entries[k + 1]+ entry = tx["out"].get(cur_id)+ if entry is not None and entry is tx["in"].get(nxt_id):+ v_items.append(cur_xml)+ v_items.append(_fcp7_transitionitem(entry, fps))+ else:+ v_items.append(cur_xml)+ if v_entries:+ v_items.append(v_entries[-1][1])# ---- V2: the overlay lane ------------------------------------------ov_items = []for j, o in enumerate(overlays or []):@@ -4822,6 +5454,9 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,f"{extra_tracks}""</audio>""</media>"+ # SEQUENCE-level, after </media> and before </sequence> — the slot+ # xmeml defines for them, and the one both importers read from.+ f"{_fcp7_markers(markers, fps)}""</sequence>\n""</xmeml>\n")@@ -4829,7 +5464,9 @@ def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,def ae_jsx(segments, *, name: str, media: dict, width: int, height: int,fps: int = NLE_FPS, audio: dict | None = None,overlays: list | None = None,- audio_tracks: list | None = None) -> str:+ audio_tracks: list | None = None,+ transitions: dict | None = None,+ markers: list[dict] | None = None) -> str:"""An ExtendScript that BUILDS the comp, because AE cannot import a timeline.It locates its own folder (`File($.fileName).parent`) and imports from the@@ -4855,19 +5492,34 @@ def ae_jsx(segments, *, name: str, media: dict, width: int, height: int," if (!f.exists) { throw new Error('missing media: ' + f.fsName); }"," return proj.importFile(new ImportOptions(f));"," }",- " function bright(layer, v) {",- " // Brightness & Contrast. AE's Brightness is roughly [-150, 150]",- " // against a 0-255 pixel; ffmpeg's eq=brightness is an additive",- " // offset in [-1, 1] against a 0-1 pixel. 0.5 -> 75 is the same",- " // half-of-half. APPROXIMATE, not a match: AE and ffmpeg do not",- " // agree on gamma, and the render is the one that is exact.",+ " function bright(layer, v, con) {",+ " // Brightness & Contrast. AE's Brightness/Contrast are each",+ " // roughly [-150, 150] against a 0-255 pixel; ffmpeg's",+ " // eq=brightness is additive in [-1, 1] and eq=contrast a",+ " // 1.0-centred multiplier in [0.5, 1.8] against a 0-1 pixel.",+ " // 0.5 -> 75 and (contrast-1) -> (contrast-1)*150 are the same",+ " // half-of-half scaling. APPROXIMATE, not a match: AE and ffmpeg",+ " // do not agree on gamma, and the render is the one that is exact."," var fx = layer.property('ADBE Effect Parade')"," .addProperty('ADBE Brightness & Contrast 2');"," fx.property(1).setValue(v);",+ " if (con) { fx.property(2).setValue(con); }",+ " }",+ " function satur(layer, v) {",+ " // FILM-14's saturation slider. ffmpeg's eq=saturation is a",+ " // 1.0-centred multiplier in [0, 2.5]; AE's Master Saturation is",+ " // roughly [-100, 100] around 0. APPROXIMATE, like brightness.",+ " var fx = layer.property('ADBE Effect Parade')",+ " .addProperty('ADBE HUE SATURATION');",+ " fx.property('Master Saturation').setValue(v);"," }",]+ tx = transitions or {"out": {}, "in": {}}for i, seg in enumerate(segments):- ae_b = round(seg["brightness"] * 150.0, 3)+ fxseg = seg.get("fx") or {}+ ae_b = round((seg["brightness"] + _f(fxseg.get("exposure"), 0.0)) * 150.0, 3)+ ae_con = round((_f(fxseg.get("contrast"), 1.0) - 1.0) * 150.0, 3)+ ae_sat = round((_f(fxseg.get("saturation"), 1.0) - 1.0) * 100.0, 3)if seg["kind"] == "slug":lines += [f" // {i + 1}: black slug",@@ -4888,12 +5540,28 @@ def ae_jsx(segments, *, name: str, media: dict, width: int, height: int,# clamp any hold longer than that.lines.append(" lay.startTime = %.6f;"% (seg["film_start"] - seg["start"]))+ # FILM-50: A TRANSITION EXTENDS THE LAYER'S PRESENCE WINDOW, never+ # `seg` itself — the same rule fcp7_xml follows, for the same reason+ # (the fx fade block just below reads seg's own film_start/film_end+ # for an UNRELATED fade and must not see a boundary that moved for a+ # different reason). AE has no separate source-in/out clock the way+ # FCP7's XML does: `startTime` already anchors where the untrimmed+ # footage's own frame 0 sits, so extending inPoint/outPoint alone+ # reveals more of the SAME footage already loaded — nothing else to+ # recompute.+ out_tx = tx["out"].get(seg.get("id"))+ in_tx = tx["in"].get(seg.get("id"))+ ae_out = seg["film_end"] + (out_tx["half_sec"] if out_tx else 0.0)+ ae_in = seg["film_start"] - (in_tx["half_sec"] if in_tx else 0.0)lines += [- " lay.inPoint = %.6f;" % seg["film_start"],- " lay.outPoint = %.6f;" % seg["film_end"],+ " lay.inPoint = %.6f;" % ae_in,+ " lay.outPoint = %.6f;" % ae_out,]- if abs(seg["brightness"]) >= 1e-9:- lines.append(" bright(lay, %s);" % ae_b)+ if abs(ae_b) >= 1e-9 or abs(ae_con) >= 1e-9:+ lines.append(" bright(lay, %s%s);"+ % (ae_b, (", %s" % ae_con) if abs(ae_con) >= 1e-9 else ""))+ if abs(ae_sat) >= 1e-9:+ lines.append(" satur(lay, %s);" % ae_sat)fr = seg.get("frame") or {}z = _f(fr.get("zoom"), 1.0)if abs(z - 1.0) >= 1e-9:@@ -4928,6 +5596,38 @@ def ae_jsx(segments, *, name: str, media: dict, width: int, height: int,".property('ADBE Opacity');")for when, val in pts:lines.append(" op.setValueAtTime(%.6f, %d);" % (when, val))+ # FILM-50: THE TRANSITION, AS OPACITY — AE has no importable+ # transition object, so this is the same "the decision travels"+ # promise the fade block just above keeps, for a boundary instead of+ # an edge. `comp.layers.add()` always inserts at the TOP of the+ # stack, so a clip added LATER in film order (the INCOMING side of+ # any boundary) ends up ABOVE the one before it — every transition+ # here is built around that, not against it:+ # dissolve: only the INCOMING layer animates, 0->100 across the+ # WHOLE overlap. It is on top, so fading it up from transparent+ # progressively reveals the outgoing layer sitting static+ # underneath — a standard crossfade, without needing the two+ # layers' opacities to sum to anything in particular.+ # fade_black: OUTGOING fades 100->0 over the FIRST half only,+ # INCOMING fades 0->100 over the SECOND half only — the two+ # windows never overlap, so which layer is on top does not+ # matter; at the midpoint both read 0, which is what makes it a+ # dip through black rather than a dissolve.+ tx_pts = []+ if out_tx and out_tx["kind"] == "fade_black":+ a, h = out_tx["at_sec"], out_tx["half_sec"]+ tx_pts += [(max(0.0, a - h), 100), (a, 0)]+ if in_tx:+ a, h = in_tx["at_sec"], in_tx["half_sec"]+ if in_tx["kind"] == "fade_black":+ tx_pts += [(a, 0), (a + h, 100)]+ else:+ tx_pts += [(max(0.0, a - h), 0), (a + h, 100)]+ if tx_pts:+ lines.append(" op = lay.property('ADBE Transform Group')"+ ".property('ADBE Opacity');")+ for when, val in tx_pts:+ lines.append(" op.setValueAtTime(%.6f, %d);" % (when, val))gain = seg.get("gain") or []if len(gain) >= 2:# AE'S AUDIO LEVELS ARE dB, so the linear curve is converted here@@ -5040,6 +5740,16 @@ def ae_jsx(segments, *, name: str, media: dict, width: int, height: int,% (w["film_start"] + t, db, db))if strip_muted(s) or track_muted(trk):lines.append(" lay.audioEnabled = false;")+ # ---- FILM-58: MARKERS, on the comp's own ruler ------------------------+ # `comp.markerProperty` is the one AE property every composition already+ # has — no layer to attach them to, no extra import — and MarkerValue's+ # comment is what the Timeline panel shows under the flag.+ for m in (markers or []):+ label = str(m.get("label") or "").strip() or m["kind"].capitalize()+ lines.append(+ " comp.markerProperty.setValueAtTime(%.6f, new MarkerValue(%s));"+ % (_f(m["at"]), _jsx_string(label + " (" + m["kind"] + ")"+ if m.get("label") else label)))lines += [" comp.openInViewer();"," app.endUndoGroup();",@@ -5053,7 +5763,10 @@ def export_nle(clips, dest_dir, *, name: str, fps: int = NLE_FPS,audio: dict | None = None, probe=None, link=None,width: int = 0, height: int = 0,overlays: list | None = None,- audio_tracks: list | None = None) -> dict:+ audio_tracks: list | None = None,+ transitions: list | None = None,+ markers: list[dict] | None = None,+ film_look: str | None = None) -> dict:"""Write `<name>_project/` — one XML, one AE script, and the media beside them.Returns {"ok", "dir", "xml", "jsx", "clips", "linked", "copied",@@ -5061,11 +5774,23 @@ def export_nle(clips, dest_dir, *, name: str, fps: int = NLE_FPS,`audio_tracks` is `edit["audio_tracks"]`: each track becomes its own audiotrack in the XML and its strips their own layers in the AE script.++ `transitions` is `edit["transitions"]` — the raw rows, resolved here+ (once, via `_nle_transitions`) into the same `{"out", "in"}` map both+ `fcp7_xml` and `ae_jsx` read, so the XML's transitionitem and the+ script's opacity ramp always describe the SAME boundary the render will+ actually draw, never two independent readings of the document.++ `markers` is `markers_of(edit)` — FILM-58's beat/lyric/note flags, each+ written as a sequence-level FCP7 marker and a composition marker on the+ AE comp. They cost the caller nothing to omit: no markers is no markers,+ the same rule `overlays` and `audio_tracks` already follow."""import shutil # noqa: PLC0415, F401- segs = _nle_segments(clips, probe=probe)+ segs = _nle_segments(clips, probe=probe, film_look=film_look)if not segs:raise EditError("there is nothing on the timeline to export")+ tx_map = _nle_transitions(clips, transitions, fps)root = Path(str(dest_dir)) / f"{_slug(name, 60)}_project"media_dir = root / "media"media_dir.mkdir(parents=True, exist_ok=True)@@ -5111,15 +5836,18 @@ def export_nle(clips, dest_dir, *, name: str, fps: int = NLE_FPS,xml_path = root / f"{_slug(name, 60)}.xml"jsx_path = root / f"{_slug(name, 60)}_ae.jsx"+ mks = [m for m in (markers or []) if isinstance(m, dict)]xml_path.write_text(fcp7_xml(segs, name=name, media=media, width=width, height=height,overlays=ovs,base=root, fps=fps, audio=a_arg,- audio_tracks=trks or None), encoding="utf-8")+ audio_tracks=trks or None, transitions=tx_map,+ markers=mks or None), encoding="utf-8")jsx_path.write_text(ae_jsx(segs, name=name, media=media, width=width, height=height,overlays=ovs,- fps=fps, audio=a_arg, audio_tracks=trks or None), encoding="utf-8")+ fps=fps, audio=a_arg, audio_tracks=trks or None,+ transitions=tx_map, markers=mks or None), encoding="utf-8")return {"ok": True, "dir": str(root), "xml": str(xml_path),"jsx": str(jsx_path), "clips": len(segs),@@ -5127,6 +5855,7 @@ def export_nle(clips, dest_dir, *, name: str, fps: int = NLE_FPS,"media": sorted(media.values()),"sound_strips": sum(1 for t in trks for s in track_strips(t)if str(s.get("path") or "") in media),+ "markers": len(mks),"width": width, "height": height,"duration": round(max([s["film_end"] for s in segs] or [0.0]), 3),}@@ -5321,6 +6050,46 @@ def create_draft(board_dir, name: str, *, from_current: bool = False) -> dict:return _land_draft(board_dir, idx, slug, text, doc)+@_under_board_lock+def set_aside_for_replan(board_dir, when: str = "") -> dict | None:+ """Keep the current timeline as a draft of its own and start the next one+ fresh. Returns `{"kept": <name>, "active": <name>}`, or None when there+ was no timeline with clips to keep.++ BOARD-7: a music video re-planned through the Audio tab replaced the+ board's shots but left `edit.json` — the cut of the OLD plan — as the+ active timeline, and Export prefers a saved timeline over the shot list,+ so it silently assembled the previous version. The old cut is not thrown+ away (it is somebody's arrangement): `edit.json` is MOVED to the draft+ file an inactive draft lives in, renamed so the list says what it is,+ and a new active draft with no file takes its place — so the next Editor+ open builds the new plan's timeline the ordinary way, and Export uses the+ new shots until then.+ """+ cur = edit_path(board_dir)+ doc = _read_json(cur)+ if not isinstance(doc, dict) or not (doc.get("clips") or []):+ return None+ idx = load_draft_index(board_dir)+ old = idx["active"]+ drafts_dir(board_dir).mkdir(parents=True, exist_ok=True)+ os.replace(cur, _draft_file(board_dir, old))+ stamp = f" ({when})" if when else ""+ kept_name = ""+ for d in idx["drafts"]:+ if d["slug"] == old:+ base = str(d.get("name") or old)+ d["name"] = (base + " — before re-plan" + stamp)[:DRAFT_NAME_MAX]+ kept_name = d["name"]+ text = ("New plan" + stamp)[:DRAFT_NAME_MAX]+ slug = _draft_slug(text, {d["slug"] for d in idx["drafts"]})+ idx["drafts"].append({"slug": slug, "name": text,+ "created_at": int(time.time())})+ idx["active"] = slug+ _save_draft_index(board_dir, idx)+ return {"kept": kept_name, "active": text}++@_under_board_lockdef duplicate_draft(board_dir, slug: str, name: str = "") -> dict:"""Copy a draft under a new name. The copy becomes active."""@@ -5502,13 +6271,54 @@ def latest_snapshot(board_dir, slug: str = "") -> tuple[Path, dict] | None:return None-def prune_snapshots(board_dir, *, keep: int = SNAPSHOT_KEEP) -> int:- """Drop the oldest snapshots past the cap. Losing one is not an event."""+def _snapshot_stamp_ms(path) -> int | None:+ """The clock the snapshot was written at, straight off its own name —+ `snap-<13-digit-ms>-<bump>.json` — rather than the filesystem's mtime,+ which a copy, a backup tool or a slow disk can all disturb. None for+ anything that does not match (a legacy or foreign file `_snapshot_paths`+ should not have handed back, but pruning must not crash on one either)."""+ m = re.match(r"^" + re.escape(_SNAP_PREFIX) + r"(\d{13})-\d{3}\.json$",+ Path(path).name)+ return int(m.group(1)) if m else None+++def prune_snapshots(board_dir, *, keep_hours: float = SNAPSHOT_KEEP_HOURS,+ hard_cap: int = SNAPSHOT_HARD_CAP) -> int:+ """Drop snapshots older than `keep_hours`, and — ONLY past `hard_cap`+ files — the oldest ones regardless of age. Losing one is not an event.++ FILM-57: the lane used to be a flat count (`keep`, formerly 20), which+ read as "about 30 s of active editing" on a document that re-backs up+ itself every debounce tick even with nothing new to save (fixed at the+ source: sbeTick's watchdog no longer re-arms sbeQueueSave once the+ current state is already covered). Time is the axis a person actually+ reasons about ("what did this look like an hour ago"), not "the 14th+ most recent write" — so age is now the primary rule. `hard_cap` is a+ backstop, not a design target: it exists only so a bug elsewhere that+ hammers the backup route cannot fill a disk, and at 500 files it is far+ above anything a real editing session reaches inside a day.+ """paths = _snapshot_paths(board_dir)+ now_ms = int(time.time() * 1000)+ cutoff_ms = now_ms - int(keep_hours * 3600 * 1000)gone = 0- for stale in paths[:max(0, len(paths) - int(keep))]:+ # Oldest-past-the-hard-cap first (paths is already oldest-first — see+ # _snapshot_paths' sort), so a burst that is ALSO too big loses its+ # oldest files whether or not they have aged past the time window yet.+ over = max(0, len(paths) - int(hard_cap))+ stale = set(paths[:over])+ for p in paths:+ if p in stale:+ continue+ stamp = _snapshot_stamp_ms(p)+ # An unparsable name is never aged out by the clock — only the hard+ # cap above can remove it — so a foreign or legacy file is never+ # silently deleted by a rule it was not named for.+ if stamp is not None and stamp < cutoff_ms:+ stale.add(p)+ for p in stale:try:- stale.unlink()+ p.unlink()gone += 1except OSError:continue@@ -5639,7 +6449,10 @@ def pending_backup(board_dir) -> dict | None:return Nonereturn {"file": p.name, "at": int(doc.get("backed_up_at") or 0),"draft": idx["active"], "clips": stats["clips"],- "duration": stats["duration"]}+ "duration": stats["duration"],+ # FILM-54: what actually changed, so the chip can say it instead+ # of asking a question it cannot name.+ "diff": edit_diff_summary(saved, doc)}def recover_backup(board_dir) -> dict:diff --git a/storyboard_planner.py b/storyboard_planner.pyindex 7f3dea6..b82f431 100644--- a/storyboard_planner.py+++ b/storyboard_planner.py@@ -3741,7 +3741,18 @@ def _coerce_for_mode(obj, fb_mode, fb_shot, previous, *, concept, n_shots, style# A re-roll should look different: nudge the seed rather than re-render the# same latent with new words.replacement["seed"] = _seed_for(seed_base + int(time.time()) % 9973, fb_shot)- for carry in ("status",):+ # FILM-21: the model that writes a single-shot re-roll knows+ # nothing about music-video structure — it returns an ordinary+ # planner shot. Carrying only `status` across meant a Rewrite on+ # a singing shot silently dropped its music_video block, its+ # audio/audio_start_time/audio_stem (the second of the SONG it+ # was rendered against), its still (the cast picture), and its+ # `a2v` mode itself — the fresh shot came back as silent i2v/t2v+ # text with no idea it was ever supposed to sing. These fields+ # are the shot's structural identity, not its creative content,+ # so they ride across a rewrite exactly like `status` always did.+ for carry in ("status", "uid", "mode", "music_video", "audio",+ "audio_start_time", "audio_stem", "still", "still_source"):if carry in s:replacement[carry] = s[carry]spec["shots"][i] = replacementdiff --git a/test_a2v_sync_fixes.py b/test_a2v_sync_fixes.pyindex cd74424..61c3287 100644--- a/test_a2v_sync_fixes.py+++ b/test_a2v_sync_fixes.py@@ -181,7 +181,10 @@ class ConditioningAudioIsNotAlwaysTheSoundtrack(unittest.TestCase):got, note = P.a2v_conditioning_audio({"audio_stem_auto": "on"}, str(self.song))self.assertEqual(got, str(self.song))- self.assertIn("stems extra", note)+ # VA-21: the note used to claim a Pinokio sidebar entry that does not+ # exist (a2v_stems_deps.sh has no pinokio.js menu item). Reworded to+ # name the real path — running the script directly.+ self.assertIn("a2v_stems_deps.sh", note)def test_auto_that_fails_mid_separation_never_fails_the_job(self):with mock.patch.object(P, "_resolve_demucs",diff --git a/test_anchor_stills.py b/test_anchor_stills.pyindex 6cb0f74..db46267 100644--- a/test_anchor_stills.py+++ b/test_anchor_stills.py@@ -159,7 +159,7 @@ def test_sidecar_guide_survives_the_reader(tmp_path):def test_clear_still_forgets_the_still_and_the_clip_made_from_it():board = {"shots": [{"n": 1, "still": "/a.png", "still_job_id": "j", "draft_job_id": "d",- "draft_output": "/o.mp4", "status": "done"},+ "draft_output": "/o.mp4", "status": "done", "seed": 42},{"n": 2, "still": "/b.png"}]}shot = p._sb_clear_still(board, 1)assert shot is board["shots"][0]@@ -168,3 +168,37 @@ def test_clear_still_forgets_the_still_and_the_clip_made_from_it():assert shot["status"] == "pending"assert board["shots"][1]["still"] == "/b.png" # only shot 1assert p._sb_clear_still(board, 9) is None+++def test_clear_still_reseeds_so_a_second_press_is_not_the_same_clip():+ # FILM-11: the still job form pins the shot's own seed — without a+ # reseed here, pressing "New still" twice rendered the same image twice.+ board = {"shots": [{"n": 1, "still": "/a.png", "seed": 424242}]}+ shot = p._sb_clear_still(board, 1)+ assert shot["seed"] != 424242+ assert isinstance(shot["seed"], int)+++def test_clear_still_never_deletes_a_user_uploaded_photo():+ # FILM-11: a music-video shot's still is the user's own uploaded cast+ # picture (music_video.py tags it still_source="user"). "New still" used+ # to pop it unconditionally — on an a2v (singing) shot shot_wants_still()+ # refuses to make a replacement, so the shot rendered lip-sync with NO+ # image at all, silently discarding the user's photo for good.+ board = {"shots": [{"n": 1, "mode": "a2v", "still": "/singer.png",+ "still_source": "user", "still_job_id": "j",+ "draft_job_id": "d", "draft_output": "/o.mp4",+ "status": "done", "seed": 7}]}+ shot = p._sb_clear_still(board, 1)+ assert shot["still"] == "/singer.png" # kept — never deleted+ assert shot["still_source"] == "user"+ for k in ("still_job_id", "draft_job_id", "draft_output"):+ assert k not in shot+ assert shot["status"] == "pending"+ assert shot["seed"] != 7 # still reseeded++ # A machine-made still (no still_source) keeps clearing as before, so a+ # planner-authored board still gets a genuinely new composition.+ board2 = {"shots": [{"n": 1, "still": "/anchor.png", "seed": 7}]}+ shot2 = p._sb_clear_still(board2, 1)+ assert "still" not in shot2diff --git a/test_audio_filter_tab_leak.py b/test_audio_filter_tab_leak.pynew file mode 100644index 0000000..2ad35e0--- /dev/null+++ b/test_audio_filter_tab_leak.py@@ -0,0 +1,167 @@+#!/usr/bin/env python3+"""VC-20 [P2] [BUG] The "Audio" gallery filter turns the Video tab's player+into the Music studio and relabels the model as YuE2.++WHAT THIS GUARDS. selectOutput() runs for every gallery selection on every+tab (it is the one function behind clicking any card). For a song+(kind=='audio', engine=='music') it unconditionally: (1) swapped the whole+player pane for songHero() - cover art, transport, the Music tab's own+chrome; (2) filled the Song card underneath with New take / Re-roll the+sound / New style on this score / Cover it / Sheet music; (3) via+updateModelCredit(), relabelled the header's model chip "YuE2 · MLX by+vanch007", even though the LTX form on the left was still the one about to+run. None of that is wrong on the Audio tab itself - it is the Audio tab's+whole purpose. It was wrong on the Video tab: filtering Outputs to Audio and+clicking a song transplanted another tab's UI into this one.++Fixed by gating all three on `document.body.dataset.workflow === 'audio'`:+off that tab a song gets the same compact inline <audio> player any other+audio clip gets, with an "Open in Audio tab" link (openSongInAudioTab, new)+that switches tabs and re-selects the same clip - which DOES get the full+treatment, because now onAudioTab is true.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+BOOT_JS = (ROOT / "webapp" / "js" / "boot.js").read_text(encoding="utf-8")+MUSIC_JS = (ROOT / "webapp" / "js" / "music.js").read_text(encoding="utf-8")+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++# ---------------------------------------------------------------- 1+# updateModelCredit: a real node execution, since the function is small and+# self-contained (one DOM element, BOOT, currentOutputs, activePath).+class TestModelCreditFollowsTheTabNotJustTheClip(unittest.TestCase):+ def _fn(self) -> str:+ return extract_function("updateModelCredit", BOOT_JS) + "\n" + \+ extract_function("_modelCreditLabel", BOOT_JS)++ def _run(self, workflow: str) -> dict:+ script = f"""+const BOOT = {{ model: "mlx_models/ltx-2.5-mlx-q4/transformer-distilled.safetensors" }};+let activePath = '/out/song1.mp3';+const currentOutputs = [+ {{ path: '/out/song1.mp3', kind: 'audio', engine: 'music', model: 'yue2' }},+];+const modelTagEl = {{ textContent: '', title: '', href: '' }};+const document = {{+ body: {{ dataset: {{ workflow: {workflow!r} }} }},+ getElementById(id) {{+ if (id !== 'modelTag') return null;+ return modelTagEl;+ }},+}};+{self._fn()}+updateModelCredit();+console.log(JSON.stringify({{ text: modelTagEl.textContent, title: modelTagEl.title }}));+"""+ return _run_node(script)++ def test_on_the_audio_tab_the_song_is_named(self):+ out = self._run('audio')+ self.assertIn('YuE2', out['text'])++ def test_off_the_audio_tab_the_forms_engine_wins_instead(self):+ out = self._run('manual')+ self.assertNotIn('YuE2', out['text'])+ self.assertIn('ltx-2.5-mlx-q4', out['text'])+++# ---------------------------------------------------------------- 2+class TestSongCardGatedOnTab(unittest.TestCase):+ def _fn(self) -> str:+ return extract_function("songCardRender", MUSIC_JS)++ def test_is_song_requires_the_audio_tab(self):+ fn = self._fn()+ i = fn.index("const isSong")+ line = fn[i:fn.index("\n", i)]+ self.assertIn("onAudioTab", line)+ self.assertIn("document.body.dataset.workflow === 'audio'", fn)++ def test_card_still_hides_for_a_non_song(self):+ fn = self._fn()+ self.assertIn("card.hidden = !isSong", fn)+++# ---------------------------------------------------------------- 3+class TestPlayerPaneGatedOnTab(unittest.TestCase):+ def _fn(self) -> str:+ return extract_function("selectOutput", QUEUE_JS)++ def test_songhero_swap_requires_the_audio_tab(self):+ fn = self._fn()+ i = fn.index("if (isAudio && o && o.engine === 'music'")+ line = fn[i:fn.index("\n", i)]+ self.assertIn("onAudioTab", line)++ def test_off_tab_audio_gets_a_compact_player_and_an_open_link(self):+ fn = self._fn()+ self.assertIn("player-audio-inline", fn)+ self.assertIn("openSongInAudioTab", fn)+ # the open link is conditional on it actually being a song — a plain+ # (non-music) audio clip gets the inline player with no dead link+ i = fn.index("const openLink")+ block = fn[i:fn.index(";", i)]+ self.assertIn("o.engine === 'music'", block)++ def test_no_autoplay_regression_for_the_inline_player(self):+ fn = self._fn()+ i = fn.index("player-audio-inline")+ block = fn[fn.rindex("wrap.innerHTML", 0, i):fn.index("</div>", i)]+ self.assertIn("autoplay ? ' autoplay' : ''", block)+++# ---------------------------------------------------------------- 4+class TestOpenSongInAudioTab(unittest.TestCase):+ def test_switches_tab_before_selecting(self):+ fn = extract_function("openSongInAudioTab", MUSIC_JS)+ self.assertIn("workflowSwitch('audio')", fn)+ self.assertIn("selectOutput(path)", fn)+ self.assertLess(fn.index("workflowSwitch"), fn.index("selectOutput(path)"))++ def test_published_on_globalthis(self):+ self.assertIn(+ "openSongInAudioTab",+ MUSIC_JS[MUSIC_JS.index("Object.assign(globalThis"):])++ def test_path_argument_is_safely_escaped_in_the_open_link(self):+ # Consistent with every other per-item onclick in this file: JSON+ # stringify + HTML-escape the quotes, never a raw string concat that+ # would break on an apostrophe in the filename.+ fn = extract_function("selectOutput", QUEUE_JS)+ i = fn.index("player-audio-open")+ block = fn[fn.rindex("const pathAttr", 0, i):i]+ self.assertIn("JSON.stringify(path)", block)+ self.assertIn(""", block)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_avoid_ignored_indicator.py b/test_avoid_ignored_indicator.pynew file mode 100644index 0000000..1bbd678--- /dev/null+++ b/test_avoid_ignored_indicator.py@@ -0,0 +1,193 @@+"""VC-15: the Avoid box shows when it's being ignored, instead of quietly+doing nothing.++WHAT THIS GUARDS. The Avoid (negative prompt) textarea took input at every+quality, but the distilled Q4 lane (Quick/Balanced/Standard, T2V/I2V) has no+unconditional branch to run it against — the ONLY place that said so was 10px+grey hint text above the box. A user opens Avoid on the default (Balanced),+types something, clicks Generate, and gets a clip that ignores every word of+it with zero feedback anywhere on the control itself.++Fixed with three pieces, all reading the same `_qualityUsesHq` fact the+quality chips themselves use (so this can never disagree with them):+ 1. `avoidIsIgnored()` / `updateAvoidIgnoredState()` (queue.js, called from+ updateDerived() and toggleAvoidRow()) - dims the textarea+ (.is-ignored) and shows an inline note ("Ignored at Balanced — Use+ High") with a working shortcut into High quality.+ 2. The collapsed toggle label itself gains "(off at Balanced)" whenever+ the row is closed and guidance would be ignored.+ 3. Submitting a non-empty, ignored Avoid box shows a one-line toast+ instead of silently rendering without it.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+JS_DIR = ROOT / "webapp" / "js"+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class MarkupHasTheNote(unittest.TestCase):+ def test_ignored_note_exists_between_label_and_textarea(self):+ self.assertIn('id="avoidIgnoredNote"', HTML)+ self.assertIn('id="avoidIgnoredQuality"', HTML)+ i = HTML.index('id="avoidRow"')+ j = HTML.index('id="avoidIgnoredNote"')+ k = HTML.index('id="negative_prompt"')+ self.assertLess(i, j)+ self.assertLess(j, k)++ def test_use_high_shortcut_calls_setquality(self):+ i = HTML.index('id="avoidIgnoredNote"')+ j = HTML.index('</div>', i)+ snippet = HTML[i:j]+ self.assertIn("setQuality('high')", snippet)+++DOM_SHIM = r"""+function makeEl(id, value) {+ return { id, value, textContent: '', innerHTML: '', hidden: false,+ className: '', classList: { _s: new Set(),+ toggle(c, force) { if (force === undefined) { this._s.has(c) ? this._s.delete(c) : this._s.add(c); }+ else if (force) this._s.add(c); else this._s.delete(c);+ return this._s.has(c); },+ contains(c) { return this._s.has(c); },+ add(c) { this._s.add(c); }, remove(c) { this._s.delete(c); } },+ addEventListener(){}, getAttribute(){ return null; }, dataset: {}, style: {} };+}+const FIELDS = { mode: 't2v', quality: 'balanced' };+const ELS = {};+for (const [id, value] of Object.entries(FIELDS)) ELS[id] = makeEl(id, value);+ELS.avoidIgnoredNote = makeEl('avoidIgnoredNote');+ELS.negative_prompt = makeEl('negative_prompt');+ELS.avoidIgnoredQuality = makeEl('avoidIgnoredQuality');+ELS.avoidToggleLabel = makeEl('avoidToggleLabel');+ELS.avoidRow = makeEl('avoidRow');+global.document = { getElementById: (id) => (ELS[id] || (ELS[id] = makeEl(id, ''))) };+global.currentMode = FIELDS.mode;+global._qualityUsesHq = (q) => q === 'high';+global.ltxCurrentCell = () => (global.__cell || null);+"""+++class AvoidIgnoredLogic(unittest.TestCase):+ def _fns(self) -> str:+ src = (JS_DIR / "queue.js").read_text(encoding="utf-8")+ return (extract_function("avoidIsIgnored", src) + "\n"+ + extract_function("updateAvoidIgnoredState", src))++ def _run(self, mode: str, quality: str, *, row_open: bool = False,+ cell: dict | None = None) -> dict:+ fns = self._fns()+ script = DOM_SHIM + f"""+global.currentMode = {json.dumps(mode)};+ELS.mode.value = {json.dumps(mode)};+ELS.quality.value = {json.dumps(quality)};+ELS.avoidRow.classList.toggle('show', {json.dumps(row_open)});+global.__cell = {json.dumps(cell)};+{fns}+updateAvoidIgnoredState();+console.log(JSON.stringify({{+ noteHidden: ELS.avoidIgnoredNote.hidden,+ taIgnored: ELS.negative_prompt.classList.contains('is-ignored'),+ toggleLabel: ELS.avoidToggleLabel.textContent,+}}));+"""+ return _run_node(script)++ def test_balanced_t2v_is_ignored(self):+ out = self._run("t2v", "balanced", cell={"quality_label": "Balanced"})+ self.assertFalse(out["noteHidden"])+ self.assertTrue(out["taIgnored"])++ def test_high_t2v_is_not_ignored(self):+ out = self._run("t2v", "high", cell={"quality_label": "High"})+ self.assertTrue(out["noteHidden"])+ self.assertFalse(out["taIgnored"])++ def test_i2v_balanced_is_also_ignored(self):+ out = self._run("i2v", "balanced", cell={"quality_label": "Balanced"})+ self.assertFalse(out["noteHidden"])++ def test_extend_is_never_flagged_ignored(self):+ """Extend always renders on Q8 with guidance - never dim it, even+ though its own #quality field (if any leftover value) might read+ as a distilled quality string."""+ out = self._run("extend", "balanced", cell=None)+ self.assertTrue(out["noteHidden"])++ def test_collapsed_toggle_label_shows_the_off_quality(self):+ out = self._run("t2v", "balanced", row_open=False,+ cell={"quality_label": "Balanced"})+ self.assertIn("off at Balanced", out["toggleLabel"])++ def test_open_toggle_label_is_unchanged(self):+ out = self._run("t2v", "balanced", row_open=True,+ cell={"quality_label": "Balanced"})+ self.assertEqual(out["toggleLabel"], "Avoid −")+++class CrossModulePublishing(unittest.TestCase):+ """boot.js's toggleAvoidRow() calls updateAvoidIgnoredState() from a+ DIFFERENT module than the one that defines it (queue.js) - a top-level+ `function` in an ES module is module-private unless explicitly+ published (Object.assign(globalThis, {...}) at the bottom of the file,+ the pattern every other cross-module call in this codebase follows).+ Caught live: without this, toggleAvoidRow's own `typeof+ updateAvoidIgnoredState === 'function'` guard silently evaluated false+ and the toggle label never grew its "(off at Balanced)" suffix -- no+ error anywhere, just a no-op."""++ def test_both_functions_are_on_the_publish_block(self):+ src = (JS_DIR / "queue.js").read_text(encoding="utf-8")+ i = src.index("Object.assign(globalThis, {")+ j = src.index("\n});", i)+ block = src[i:j]+ self.assertIn("avoidIsIgnored", block)+ self.assertIn("updateAvoidIgnoredState", block)++ def test_boot_js_actually_calls_it_from_toggle(self):+ boot = (JS_DIR / "boot.js").read_text(encoding="utf-8")+ fn = extract_function("toggleAvoidRow", boot)+ self.assertIn("updateAvoidIgnoredState", fn)+++class SubmitTimeToast(unittest.TestCase):+ def test_submit_handler_warns_on_ignored_nonempty_avoid(self):+ src = (JS_DIR / "queue.js").read_text(encoding="utf-8")+ i = src.index("genForm').addEventListener('submit'")+ j = src.index("engine payload scrub", i)+ snippet = src[i:j]+ self.assertIn("negative_prompt", snippet)+ self.assertIn("avoidIsIgnored", snippet)+ self.assertIn("phosToast", snippet)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_base_pack_gate.py b/test_base_pack_gate.pynew file mode 100644index 0000000..a2dda88--- /dev/null+++ b/test_base_pack_gate.py@@ -0,0 +1,234 @@+"""VC-10: a missing base (Q4) pack can no longer queue with Generate armed.++WHAT WAS ACTUALLY WRONG, AND WHAT WASN'T. The review's steps ("boot with+only transformer-distilled.safetensors missing ... Generate is enabled;+clicking it adds 'Queue 1' ... a user whose first download was interrupted+can queue a batch that FAILS JOB BY JOB") describe each queued job failing,+not rendering mosaic garbage — because `run_job_inner`'s existing+`ltx_pack_preflight(_char_pack, "This render")` call (the Quick/Standard+Q4-one-stage branch, unconditional, not character-gated despite the+variable's name) already refuses an incomplete Q4 pack before the helper+ever starts, for T2V/I2V exactly like every other mode. That part was+already correct and test_a_real_missing_base_pack_refuses_before_the_helper+below pins it (nothing in the existing suite proved this end to end).++THE REAL BUG was client-side, in `queue.js`'s `applyPackIncompleteGate`: it+returned early for a Q4/base pack on the theory that "an incomplete BASE+pack is already a hard block in the models card above" — but that card+(`updateModelsCard`'s red "Base models needed" state) only ever rendered a+Download button; it never touched `#genBtn`. So Generate stayed clickable,+a batch could be queued, and each entry burned a round trip to the server+(job dequeued, helper NOT started, refused) before failing — needless+churn compared to the button simply being disabled up front, the same way+Q8-incomplete already disables it.++Fixed: `applyPackIncompleteGate` now checks `!s.base_available` FIRST,+ahead of the q8-specific logic, and disables `#genBtn` with the missing+filename(s) named.++Also fixed while in the area: "(1 files left)" (settings.js) always said+"files" regardless of count, and the boot log's "model integrity: OK (19+weight files verified)" said so even when a required file was outright+missing (integrity deliberately only hashes files that exist — a missing+model is the download flow's job — so the line was technically true and+dangerously reassuring); it now folds in the render capability's own+missing-file count.+"""+from __future__ import annotations++import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+++class _Helper:+ ready_info: dict = {}++ def __init__(self):+ self.sent: list[dict] = []++ def is_alive(self):+ return True++ def kill(self, *a, **k):+ pass++ def run(self, spec, *a, **k):+ self.sent.append(spec)+ out = (spec.get("params") or {}).get("output_path")+ if out:+ Path(out).write_bytes(b"x")+ return {"seed_used": 1, "elapsed_sec": 0.1}+++class ServerAlreadyRefusesAMissingBasePack(unittest.TestCase):+ """Not a fix - a gap-filling regression pin for a real path nothing in+ the existing suite exercised end to end."""++ def _form(self, **extra) -> dict:+ # upscale=off: this class only cares whether the helper was reached,+ # not the export tail - Balanced's default fit_720p export would+ # shell out to a REAL ffmpeg against the fake 1-byte helper output+ # written by _Helper.run(), which is a different (and irrelevant)+ # way for this test to fail.+ form = {"mode": "t2v", "prompt": "a lighthouse keeper", "width": "1024",+ "height": "576", "frames": "121", "seed": "-1",+ "quality": "balanced", "accel": "off", "enhance": "off",+ "upscale": "off"}+ form.update(extra)+ return form++ def test_a_missing_base_pack_refuses_before_the_helper(self):+ helper = _Helper()+ job = P.make_job(self._form())+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", Path(tempfile.mkdtemp(prefix="basepack-"))), \+ mock.patch.object(P, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(P, "write_sidecar", lambda *a, **k: True), \+ mock.patch.object(P, "_canonical_layout", return_value=True), \+ mock.patch.object(P, "pack_repo", return_value={"repo_id": "org/pack"}), \+ mock.patch.object(P, "pack_available_anywhere", return_value=False), \+ mock.patch.object(P, "pack_missing_files",+ return_value=["transformer-distilled.safetensors"]), \+ mock.patch.object(P, "pack_path", return_value=Path("/fake/pack")):+ with self.assertRaises(RuntimeError) as cm:+ P.run_job_inner(job)+ self.assertEqual(helper.sent, [], "the helper must never start on an incomplete pack")+ self.assertIn("transformer-distilled.safetensors", str(cm.exception))+ self.assertIn("incomplete", str(cm.exception))++ def test_a_complete_pack_reaches_the_helper(self):+ helper = _Helper()+ job = P.make_job(self._form())+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", Path(tempfile.mkdtemp(prefix="basepack-ok-"))), \+ mock.patch.object(P, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(P, "write_sidecar", lambda *a, **k: True), \+ mock.patch.object(P, "ltx_pack_preflight", lambda *a, **k: None):+ P.run_job_inner(job)+ self.assertEqual(len(helper.sent), 1)+++class ClientGateDisablesGenerate(unittest.TestCase):+ """The actual VC-10 fix. Run in node via extract_panel_js: confirms the+ base check runs FIRST (ahead of the q8-specific logic) and that a+ complete base pack leaves the rest of the function reachable exactly+ as before."""++ def _fn(self) -> str:+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ return extract_function("applyPackIncompleteGate", src)++ def _run_node(self, script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)++ def _shim(self, quality: str = "balanced") -> str:+ return r"""+function makeEl(id) {+ return { id, value: '', innerHTML: '', textContent: '', hidden: true,+ disabled: false, dataset: {}, title: '',+ removeAttribute(n) { delete this[n]; },+ classList: { toggle(){}, add(){}, remove(){} } };+}+const ELS = { engineRowNote: makeEl('engineRowNote'), genBtn: makeEl('genBtn'),+ characterIdInput: makeEl('characterIdInput'), quality: makeEl('quality') };+ELS.quality.value = %(quality)s;+global.document = {+ getElementById: (id) => ELS[id] || (ELS[id] = makeEl(id)),+ querySelector: () => null,+ body: { dataset: { engine: 'ltx' } },+};+global.escapeHtml = (s) => String(s);+global._qualityUsesHq = (q) => q === 'high';+""" % {"quality": json.dumps(quality)}++ def test_base_missing_disables_generate_and_names_the_file(self):+ fn = self._fn()+ out = self._run_node(self._shim() + fn + r"""+applyPackIncompleteGate({ base_available: false,+ base_missing: ['ltx-2.5-mlx-q4/transformer-distilled.safetensors'] });+console.log(JSON.stringify({+ disabled: ELS.genBtn.disabled,+ blocked: ELS.genBtn.dataset.packBlocked,+ note: ELS.engineRowNote.innerHTML,+ hidden: ELS.engineRowNote.hidden,+}));+""")+ self.assertTrue(out["disabled"])+ self.assertEqual(out["blocked"], "1")+ self.assertIn("transformer-distilled.safetensors", out["note"])+ self.assertIn("1 file", out["note"])+ self.assertNotIn("1 files", out["note"])+ self.assertFalse(out["hidden"])++ def test_base_available_leaves_generate_enabled(self):+ fn = self._fn()+ out = self._run_node(self._shim() + fn + r"""+applyPackIncompleteGate({ base_available: true, q8_missing: [] });+console.log(JSON.stringify({ disabled: ELS.genBtn.disabled,+ blocked: ELS.genBtn.dataset.packBlocked }));+""")+ self.assertFalse(out["disabled"])+ self.assertIsNone(out.get("blocked"))++ def test_base_missing_takes_priority_over_the_q8_check(self):+ """Even mid-High-quality-selection, a missing BASE pack is the+ blocker to report - not silently ignored because the code used to+ assume the models card "already" handled it."""+ fn = self._fn()+ out = self._run_node(self._shim("high") + fn + r"""+applyPackIncompleteGate({ base_available: false, base_missing: ['x.safetensors'],+ q8_missing: [] });+console.log(JSON.stringify({ disabled: ELS.genBtn.disabled,+ note: ELS.engineRowNote.innerHTML }));+""")+ self.assertTrue(out["disabled"])+ self.assertIn("Finish the model download", out["note"])++ def test_stale_comment_about_the_models_card_is_gone(self):+ """The specific wrong assumption that broke this - pinned so it+ can't quietly come back in a future edit."""+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ self.assertNotIn("already a hard block in the models card", src)+++class CopyFixes(unittest.TestCase):+ def test_settings_js_pluralizes_the_missing_count(self):+ src = (ROOT / "webapp" / "js" / "settings.js").read_text(encoding="utf-8")+ self.assertIn("missing === 1 ? '' : 's'", src)++ def test_boot_log_mentions_missing_files_not_bare_ok(self):+ src = ROOT.joinpath("mlx_ltx_panel.py").read_text(encoding="utf-8")+ m = re.search(r'print\(f"model integrity: OK[^\n]*\n[^\n]*\n[^\n]*\)', src)+ self.assertIsNotNone(m, "boot integrity OK print not found")+ self.assertIn("capability_missing", src[m.start() - 400:m.end()])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_board_list_management.py b/test_board_list_management.pynew file mode 100644index 0000000..bada001--- /dev/null+++ b/test_board_list_management.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+"""FILM-43 (server half): the board list gets dates, a thumbnail, rename+(already possible via the ordinary save route — locked here) and a real+duplicate action; a music-video re-plan updates its own board instead of+minting a duplicate.+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _board(bid, shots, **kw):+ b = {"schema": 1, "id": bid, "title": "T", "created_at": 1,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "shots": shots}+ b.update(kw)+ return b+++def _shot(n, **kw):+ s = {"n": n, "uid": f"shot_{n:08x}", "mode": "text", "engine": "ltx",+ "prompt": f"shot {n}", "duration_s": 5.0, "seed": n, "refs": [],+ "status": "pending"}+ s.update(kw)+ return s+++class FakeHandler:+ def __init__(self):+ self.status = None+ self.payload = None++ def _json(self, payload, status: int = 200):+ self.payload, self.status = payload, status+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def post(self, action, form):+ h = FakeHandler()+ panel.Handler._storyboard_post(h, action, "", form)+ return h+++class TheSummaryCarriesDatesAndAThumbnail(Sandbox):+ def test_updated_at_created_at_and_thumb_are_exposed(self):+ board = _board("sb_1", [+ _shot(1),+ _shot(2, draft_output="/o/s2.mp4"),+ ], created_at=100, updated_at=200)+ summary = panel._sb_board_summary(board)+ self.assertEqual(summary["created_at"], 100)+ self.assertEqual(summary["updated_at"], 200)+ self.assertEqual(summary["thumb"], "/o/s2.mp4")++ def test_no_clips_means_no_thumbnail(self):+ board = _board("sb_2", [_shot(1)])+ summary = panel._sb_board_summary(board)+ self.assertIsNone(summary["thumb"])+++class TheDuplicateAction(Sandbox):+ def test_duplicate_makes_a_full_independent_copy(self):+ board = self.save(_board("sb_orig", [+ _shot(1, draft_output="/o/s1.mp4", status="done", uid="shot_aaaa"),+ ], title="My Film"))+ h = self.post("duplicate", {"id": ["sb_orig"]})+ self.assertEqual(h.status, 200, h.payload)+ new_id = h.payload["id"]+ self.assertNotEqual(new_id, "sb_orig")+ self.assertEqual(h.payload["title"], "My Film (copy)")++ copy = storyboard.load_storyboard(self.state, new_id)+ self.assertEqual(copy["title"], "My Film (copy)")+ # the clip reference travels — nothing is re-rendered by duplicating+ self.assertEqual(copy["shots"][0]["draft_output"], "/o/s1.mp4")+ # but the shot's identity does NOT — a save on one board must never+ # be able to merge onto the other's shots (FILM-10's uid contract)+ self.assertNotEqual(copy["shots"][0]["uid"], "shot_aaaa")++ original = storyboard.load_storyboard(self.state, "sb_orig")+ self.assertEqual(original["title"], "My Film") # untouched++ def test_duplicate_does_not_inherit_server_only_bookkeeping(self):+ board = self.save(_board("sb_orig2", [_shot(1)], title="X",+ render_intent={"pass": "draft", "only": None},+ planner={"state": "running"},+ auto_film="/o/old_film.mp4"))+ h = self.post("duplicate", {"id": ["sb_orig2"]})+ copy = storyboard.load_storyboard(self.state, h.payload["id"])+ self.assertNotIn("render_intent", copy)+ self.assertNotIn("planner", copy)+ self.assertNotIn("auto_film", copy)++ def test_duplicating_an_untitled_board_is_still_sensible(self):+ board = self.save(_board("sb_orig3", [_shot(1)], title=""))+ h = self.post("duplicate", {"id": ["sb_orig3"]})+ self.assertEqual(h.status, 200)+ self.assertIn("copy", h.payload["title"].lower())++ def test_an_unknown_board_is_a_404_style_error(self):+ h = self.post("duplicate", {"id": ["sb_nope"]})+ self.assertFalse(h.payload.get("ok", True))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_board_list_ui.py b/test_board_list_ui.pynew file mode 100644index 0000000..5ce045a--- /dev/null+++ b/test_board_list_ui.py@@ -0,0 +1,105 @@+#!/usr/bin/env python3+"""FILM-43 (client half): the board title keeps its filename extension+("song40.wav"), and the board list has no search or duplicate/rename UI.++Extracts the real _songNameFromFile (music.js) and sbFilterBoardList/+sbBoardRow (storyboard.js) and proves: any common audio extension is+stripped from an auto-derived title, and the search box actually filters+the rendered board list by title.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+MUSIC_JS = (ROOT / "webapp" / "js" / "music.js").read_text(encoding="utf-8")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _node(script: str) -> str:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return result.stdout+ finally:+ path.unlink(missing_ok=True)+++class TheTitleLosesItsExtension(unittest.TestCase):+ def test_every_common_audio_extension_is_stripped(self):+ fn = extract_function("_songNameFromFile", MUSIC_JS)+ script = fn + r"""+console.log(JSON.stringify({+ wav: _songNameFromFile('song40.wav'),+ mp3: _songNameFromFile('my track.mp3'),+ m4a: _songNameFromFile('Voice Memo.m4a'),+ flac: _songNameFromFile('master.flac'),+ noext: _songNameFromFile('Already Clean'),+ prefixed: _songNameFromFile('music_20260101_120000_lullaby.wav'),+}));+"""+ out = json.loads(_node(script))+ self.assertEqual(out["wav"], "song40")+ self.assertEqual(out["mp3"], "my track")+ self.assertEqual(out["m4a"], "Voice Memo")+ self.assertEqual(out["flac"], "master")+ self.assertEqual(out["noext"], "Already Clean")+ self.assertEqual(out["prefixed"], "lullaby")+++class TheBoardListSearchFilters(unittest.TestCase):+ def test_filtering_hides_non_matching_titles(self):+ if NODE is None:+ self.skipTest("node not on PATH")+ fns = "\n\n".join(extract_function(n, STORYBOARD_JS) for n in+ ("sbFilterBoardList", "sbRenderBoardLists", "sbBoardRowMenu", "sbBoardRow",+ "sbBoardRowMini", "sbFmtAgo", "sbBoardChip", "sbRowAction"))+ script = f"""+'use strict';+function escapeHtml(s) {{ return String(s == null ? '' : s); }}+const _els = {{}};+function mk(id) {{ return {{ id, innerHTML: '' }}; }}+function sbEl(id) {{ if (!_els[id]) _els[id] = mk(id); return _els[id]; }}+globalThis.SB = {{ boards: [+ {{ id: 'a', title: 'Lighthouse Keeper', shots: 3, done: 3, clips: 3 }},+ {{ id: 'b', title: 'Harbour at Dawn', shots: 5, done: 0, clips: 0 }},+ {{ id: 'c', title: 'Kitchen Table Talk', shots: 2, done: 2, clips: 2 }},+] }};+let _sbBoardFilter = '';+{fns}+sbFilterBoardList('lighthouse');+const afterSearch = sbEl('sbBoardList').innerHTML;+sbFilterBoardList('');+const afterClear = sbEl('sbBoardList').innerHTML;+console.log(JSON.stringify({{+ searchFindsIt: afterSearch.includes('Lighthouse Keeper'),+ searchHidesOthers: !afterSearch.includes('Harbour at Dawn'),+ clearedShowsAll: ['Lighthouse Keeper', 'Harbour at Dawn', 'Kitchen Table Talk']+ .every(t => afterClear.includes(t)),+}}));+"""+ out = json.loads(_node(script))+ self.assertTrue(out["searchFindsIt"])+ self.assertTrue(out["searchHidesOthers"])+ self.assertTrue(out["clearedShowsAll"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_board_save_id_refusal.py b/test_board_save_id_refusal.pynew file mode 100644index 0000000..dc9f063--- /dev/null+++ b/test_board_save_id_refusal.py@@ -0,0 +1,113 @@+#!/usr/bin/env python3+"""FILM-19 (server half): a save must never write one board's shots into+another board's file.++`sbFlushSave` posts `{id: SB.id, board: SB.payload.board}` — two reads of+client state that are supposed to name the same board but are not read+atomically. A switch-boards race (the 2 s poll landing after a row click, a+stale `sbLoad` reply — see FILM-02/test_storyboard_tab_race.py for the+client-side half of the same race class) can leave `SB.payload` holding+board A's shots while `SB.id` has already moved to board B. Before this fix+the save route trusted `id` alone and merged `incoming["shots"]` onto+whatever board `id` named — happily overwriting board B with board A's plan.++The route now refuses (400) whenever the posted board's own `id` disagrees+with the id the request is addressed to.+"""+from __future__ import annotations++import json+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _board(bid, shots):+ return {"schema": 1, "id": bid, "title": "T", "created_at": 1,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "shots": shots}+++class FakeHandler:+ def __init__(self):+ self.status = None+ self.payload = None++ def _json(self, payload, status: int = 200):+ self.payload, self.status = payload, status+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def post_save(self, url_id, board_payload):+ h = FakeHandler()+ body = json.dumps({"id": url_id, "board": board_payload})+ panel.Handler._storyboard_post(h, "save", body, {})+ return h+++class AMismatchedBoardIdIsRefused(Sandbox):+ def test_the_urls_board_and_the_bodys_board_must_agree(self):+ a = self.save(_board("sb_aaaa", [{"n": 1, "prompt": "board A shot"}]))+ b = self.save(_board("sb_bbbb", [{"n": 1, "prompt": "board B shot"}]))+ # SB.id has moved to board B, but SB.payload.board is stale board A.+ h = self.post_save("sb_bbbb", a)+ self.assertEqual(h.status, 400)+ self.assertIn("sb_aaaa", h.payload["error"])+ self.assertIn("sb_bbbb", h.payload["error"])+ # Neither board was touched.+ self.assertEqual(storyboard.load_storyboard(self.state, "sb_aaaa")["shots"],+ a["shots"])+ self.assertEqual(storyboard.load_storyboard(self.state, "sb_bbbb")["shots"],+ b["shots"])++ def test_a_matching_id_saves_normally(self):+ board = self.save(_board("sb_cccc", [{"n": 1, "prompt": "original"}]))+ edited = dict(board, shots=[{"n": 1, "prompt": "edited"}])+ h = self.post_save("sb_cccc", edited)+ self.assertEqual(h.status, 200, h.payload)+ self.assertEqual(+ storyboard.load_storyboard(self.state, "sb_cccc")["shots"][0]["prompt"],+ "edited")++ def test_a_board_with_no_id_yet_is_not_a_mismatch(self):+ # A brand-new board's very first save may post a board sub-object+ # that has never round-tripped through a GET and so carries no id+ # of its own yet — that must not be refused as a mismatch.+ board = self.save(_board("sb_dddd", []))+ fresh_shots = {"shots": [{"n": 1, "prompt": "new shot"}]}+ h = self.post_save("sb_dddd", fresh_shots)+ self.assertEqual(h.status, 200, h.payload)++ def test_an_empty_url_id_with_a_real_board_id_is_still_refused(self):+ board = self.save(_board("sb_eeee", [{"n": 1, "prompt": "x"}]))+ h = self.post_save("", board)+ self.assertEqual(h.status, 400)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_codex_4170.py b/test_codex_4170.pynew file mode 100644index 0000000..ef685c5--- /dev/null+++ b/test_codex_4170.py@@ -0,0 +1,231 @@+#!/usr/bin/env python3+"""4.17.0 Codex review (one round, seven parallel passes) — every real finding+fixed gets its pin here. Findings: ~/AI/projects/phosphene/review-2026-09-29-ux/+codex/findings_<area>.md. JS is executed in node where it is behaviour.+"""+from __future__ import annotations++import json+import os+import shutil+import stat+import subprocess+import sys+import tempfile+from pathlib import Path+from unittest import mock++import pytest++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as p # noqa: E402+import storyboard as sb # noqa: E402+from extract_panel_js import extract_function # noqa: E402++routes_queue = sys.modules["panel.routes_queue"]+NODE = shutil.which("node")+JS = ROOT / "webapp" / "js"+++def _node(script: str):+ if NODE is None:+ pytest.skip("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ assert r.returncode == 0, r.stderr[-3000:]+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class _H:+ def __init__(self):+ self.status, self.payload = None, None++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++# ---- H3-1: "Stop after this window" is not offered on a plain H3 chain -----+def test_h3_1_plain_chain_stop_after_window_is_refused_until_the_runner_keeps_windows():+ assert p.H3_RUNNER_KEEPS_WINDOWS_ON_STOP is False+ job = {"id": "j1", "params": {"engine": "h3"}, "progress": {"window_total": 3}}+ with p.LOCK:+ prev = p.STATE.get("current")+ p.STATE["current"] = job+ try:+ h = _H()+ routes_queue.post_stop_after_part(h, "/stop/after_part", {}, "")+ assert h.status == 409 and "stop_after_part" not in job+ assert "finished windows" in h.payload["error"]+ finally:+ with p.LOCK:+ p.STATE["current"] = prev+ js = (JS / "queue.js").read_text(encoding="utf-8")+ fn = js[js.index("function requestStop(opts) {"):]+ assert "h3_stop_after_window" in fn[:fn.index("\n}\n")]+ assert '"h3_stop_after_window": bool(H3_RUNNER_KEEPS_WINDOWS_ON_STOP)' in \+ (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+++# ---- H3-2: complete per-window prompts are not prefixed with window 1 -------+def test_h3_2_complete_window_prompts_replace_typed_beats_add():+ beats = ['She says <d>[English] Hello.</d>', "She silently waves goodbye.", "She exits."]+ got = p.h3_window_prompts_for_job(beats[0], beats, 3, complete=True)+ assert got == beats+ assert all("Hello" not in w for w in got[1:])+ # a person's typed boxes still ADD to the main prompt (H3-06)+ assert p.h3_window_prompts_for_job("A cat.", ["", "It jumps."], 2) == ["A cat.", "A cat. It jumps."]+ # blanks fall back to the main prompt either way+ assert p.h3_window_prompts_for_job("M", ["", "x"], 3, complete=True) == ["M", "x", "M"]+++def test_h3_2_every_complete_caller_marks_its_prompts():+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ assert 'cp["h3_chain_prompts_complete"] = True' in src # One Shot parts+ assert 'form["h3_chain_prompts_complete"] = ["1"]' in src # One Shot parent job+ job = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "x",+ "h3_chain_prompts_complete": "1"})+ assert job["params"]["h3_chain_prompts_complete"] is True # make_job allowlist+ assert 'job["h3_chain_prompts_complete"] = "1"' in (ROOT / "storyboard.py").read_text(encoding="utf-8")+++# ---- H3-3: Finish and Load Params keep the saved crop framing --------------+def test_h3_3_finish_fields_carry_the_crop_focus():+ src = (JS / "queue.js").read_text(encoding="utf-8")+ deps = "global.h3TierByKeyExact = () => ({ key: 'high_5s', quality: 'high', length: '5s' });\n" \+ "global._h3FinishSteps = () => 0;\n"+ fn = extract_function("h3FinishFieldsFromSidecar", src)+ out = _node(deps + fn + """+const base = { engine: 'h3', mode: 'i2v', image: '/u/a.png', prompt: 'x' };+console.log(JSON.stringify([+ h3FinishFieldsFromSidecar(Object.assign({}, base, { image_crop_focus: '0' }), 'high_5s').image_crop_focus,+ h3FinishFieldsFromSidecar(Object.assign({}, base, { image_crop_focus: 1 }), 'high_5s').image_crop_focus,+ h3FinishFieldsFromSidecar(base, 'high_5s').image_crop_focus]));+""")+ assert out == [0, 1, 0.5]+ lp = extract_function("loadParams", src)+ assert "_setCropFocus('image', _cropFocusFromParams(p));" in lp+ assert src.count("_setCropFocus('image', fields.image_crop_focus);") == 2 # both Finish paths+ assert "_setCropFocus('a2v_image', _cropFocusFromParams(p));" in (JS / "characters.js").read_text(encoding="utf-8")+++# ---- H3-4 / H3-5: self-calibration measures against the right price --------+def calib(tmp_path, monkeypatch):+ path = tmp_path / "eta_calibration.json"+ monkeypatch.setattr(p, "_eta_calibration_path", lambda: path)+ monkeypatch.delenv("PHOSPHENE_SPEED_FACTOR", raising=False)+ monkeypatch.setattr(p, "H3_TIERS", {"draft_5s": {"eta_min": 10.0, "tristep_min": 4.0}})+ monkeypatch.setattr(p, "_ETA_CAL_PRICED", {"h3": 1.0, "ltx": 1.0})+ return path+++def _h3_job(minutes, fast):+ return {"status": "done", "elapsed_sec": minutes * 60.0,+ "params": {"engine": "h3", "h3_tier": "draft_5s", "h3_tristep": fast}}+++def test_h3_4_fast_and_best_each_calibrate_against_their_own_price(calib):+ p._record_eta_calibration_from_job(_h3_job(4.0, True)) # Fast, exactly as priced+ p._record_eta_calibration_from_job(_h3_job(10.0, False)) # Best, exactly as priced+ assert json.loads(calib.read_text())["h3"] == [1.0, 1.0]+++def test_h3_5_identical_renders_record_identical_ratios(calib):+ for _ in range(4):+ p._record_eta_calibration_from_job(_h3_job(20.0, False))+ assert json.loads(calib.read_text())["h3"] == [2.0, 2.0, 2.0, 2.0]+ assert p._eta_calibration_factor("h3") == pytest.approx(2.0)+++def test_h3_4_pinned_steps_and_one_shots_are_not_samples(calib):+ j = _h3_job(20.0, False); j["params"]["h3_steps"] = 12+ p._record_eta_calibration_from_job(j)+ j = _h3_job(20.0, False); j["params"]["take"] = {"seconds": 30}+ p._record_eta_calibration_from_job(j)+ assert not calib.exists()+++# ---- H3-6 / H3-7: H3 disk preflight ---------------------------------------+PREFLIGHT = ROOT / "scripts" / "pinokio" / "h3_preflight.sh"+DIT_REL = "deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors"+++def _preflight(tmp: Path, models: Path, avail_gb_for: dict):+ fb = tmp / "fakebin"+ fb.mkdir(exist_ok=True)+ cases = "".join(f' "{k}"*) A={v};;\n' for k, v in avail_gb_for.items())+ (fb / "df").write_text(+ "#!/bin/sh\nfor last; do :; done\nA=500\ncase \"$last\" in\n" + cases + "esac\n"+ "echo 'Filesystem 1024-blocks Used Available Capacity Mounted'\n"+ "echo \"/dev/x 1 1 $((A*1024*1024)) 1% /\"\n")+ (fb / "sysctl").write_text("#!/bin/sh\necho 68719476736\n")+ for f in ("df", "sysctl"):+ (fb / f).chmod(0o755)+ env = dict(os.environ, PATH=f"{fb}:{os.environ['PATH']}", LTX_H3_MODELS=str(models))+ app = tmp / "app"; app.mkdir(exist_ok=True)+ return subprocess.run(["bash", str(PREFLIGHT)], cwd=str(app), env=env,+ capture_output=True, text=True, timeout=15)+++def test_h3_6_a_built_install_updates_with_little_free_space(tmp_path):+ models = tmp_path / "models"+ (models / DIT_REL).parent.mkdir(parents=True)+ (models / DIT_REL).write_bytes(b"x")+ (models / "h3-dit-q8").mkdir()+ (models / "h3-dit-q8" / ".built_ok").write_text("ok")+ r = _preflight(tmp_path, models, {str(models): 10})+ assert r.returncode == 0, r.stdout+ (models / "h3-dit-q8" / ".built_ok").unlink() # Q8 not built: needs the build room+ r = _preflight(tmp_path, models, {str(models): 10})+ assert r.returncode == 1 and "NEEDS ~25 GB" in r.stdout+++def test_h3_7_the_weights_volume_is_what_is_measured(tmp_path):+ models = tmp_path / "ext" / "h3models" # does not exist yet: nearest ancestor+ (tmp_path / "ext").mkdir()+ r = _preflight(tmp_path, models, {str(tmp_path / "ext"): 20}) # app volume roomy (500)+ assert r.returncode == 1 and "NEEDS ~97 GB" in r.stdout+ r = _preflight(tmp_path, models, {str(tmp_path / "ext"): 200})+ assert r.returncode == 0, r.stdout+++# ---- H3-8 / H3-9: the prompt helper ---------------------------------------+def test_h3_8_dialogue_budget_is_one_window_not_one_per_tag():+ fn = extract_function("h3SyncPromptHelper", (JS / "engines.js").read_text(encoding="utf-8"))+ ten = " ".join(["word"] * 10)+ out = _node(fn + f"""+const els = {{ prompt: {{ value: 'A <d>[English] {ten}</d> and <d>[English] {ten}</d>' }},+ h3DialogueWordCount: {{ hidden: true, textContent: '', classList: {{ on: false, toggle(c, v) {{ this.on = v; }} }} }},+ h3QuoteWarning: null }};+global.document = {{ getElementById: id => els[id] || null }};+global.H3 = {{ speech_words_per_sec: 2.4 }};+global.h3CurrentCell = () => ({{ seconds: 5, chain_windows: 1 }});+h3SyncPromptHelper();+console.log(JSON.stringify([els.h3DialogueWordCount.textContent, els.h3DialogueWordCount.classList.on]));+""")+ assert out == ["20/12 dialogue words", True]+++def test_h3_9_plus_line_selects_its_placeholder_at_the_start():+ fn = extract_function("h3InsertDialogueLine", (JS / "engines.js").read_text(encoding="utf-8"))+ out = _node(fn + """+const res = [];+for (const [val, at] of [['', 0], ['Hi there.', 9], ['Hi there.', 0]]) {+ const ta = { value: val, selectionStart: at, selectionEnd: at, sel: null,+ focus() {}, dispatchEvent() {}, setSelectionRange(a, b) { this.sel = [a, b]; } };+ global.document = { getElementById: id => id === 'prompt' ? ta : (id === 'h3DialogueLang' ? { value: 'English' } : null) };+ global.Event = function () {};+ h3InsertDialogueLine();+ res.push(ta.value.slice(ta.sel[0], ta.sel[1]));+}+console.log(JSON.stringify(res));+""")+ assert out == ["line here", "line here", "line here"]diff --git a/test_codex_4170_board.py b/test_codex_4170_board.pynew file mode 100644index 0000000..bc3101f--- /dev/null+++ b/test_codex_4170_board.py@@ -0,0 +1,609 @@+#!/usr/bin/env python3+"""4.17.0 Codex review — board area (Storyboard + Music video) fixes, one pin+per finding. Findings: ~/AI/projects/phosphene/review-2026-09-29-ux/codex/+findings_board.md (+ LIPSYNC-2 from findings_lipsync.md, same a2v prompt path+as BOARD-5). JS is executed in node where it is behaviour.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import music_video as mv # noqa: E402+import storyboard as sb # noqa: E402++NODE = shutil.which("node")+JS = ROOT / "webapp" / "js"+++def _node(script: str):+ if NODE is None:+ pytest.skip("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ assert r.returncode == 0, r.stderr[-3000:]+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++# ---- BOARD-5 / LIPSYNC-2: the worker's a2v safety pass keeps a prepared prompt --+_LOOK = "cobalt and amber neon lighting, heavy film grain"+_LONG = " ".join(["she sways"] * 20) + ", eyes on the lens" # > 40 words+++def _worker(prompt: str) -> str:+ # The worker's exact call (mlx_ltx_panel.run_job_inner, a2v branch).+ return sb.a2v_prompt(prompt, silent=False)++[email protected]("silent", [False, True])+def test_board5_lipsync2_prepared_prompt_survives_the_worker_pass(silent):+ planned = mv._sing_prompt(_LONG, _LOOK, "singing", silent=silent)+ assert "cobalt and amber" in planned+ shot = {"n": 1, "mode": "a2v", "engine": "ltx", "prompt": planned,+ "duration": 5, "audio": "/tmp/song.wav", "still": "/tmp/a.png"}+ job = sb.shot_to_job(shot, sb.default_policy()["final"], engine_mode="ltx")+ assert "cobalt and amber" in job["prompt"]+ sent = _worker(job["prompt"])+ # The look reaches the engine, and so does whatever compose appended.+ assert "cobalt and amber neon lighting" in sent+ assert sent == job["prompt"]+ # The contract the planner chose survives, once, and is not swapped.+ if silent:+ assert sent.count("relaxed closed lips") == 1+ assert "lip-syncs" not in sent+ else:+ assert sent.count("lip-syncs every vocal syllable") == 1+ assert "relaxed closed lips" not in sent+++def test_board5_manual_audio_prompt_is_still_capped_and_contracted():+ # The manual Audio tab (no contract yet) keeps VA-05's law: cap + contract.+ raw = " ".join(["word"] * 60) + " while he stands perfectly still"+ out = _worker(raw)+ assert out.count("lip-syncs every vocal syllable") == 1+ body = out.split("The singer lip-syncs")[0].split()+ assert len(body) <= sb.A2V_MAX_WORDS+ assert "perfectly still" not in out+++# ---- BOARD-1: re-planning refuses to replace a board that is rendering ---------+import mlx_ltx_panel as P # noqa: E402+from panel import routes_music as RM # noqa: E402+from test_music_video_routes import _Fixture, _Handler # noqa: E402++RM.P = P+++def _plan(fx, **over):+ h = _Handler(fx.form(**over))+ RM.post_music_video_plan(h, "/music/video/plan", {}, "")+ return h+++def _mark_rendering(bid):+ board = sb.load_storyboard(P.STATE_DIR, bid)+ for i, s in enumerate(board["shots"]):+ s["draft_job_id"] = f"job_b1_{i}"+ s["status"] = "queued"+ board["render_intent"] = {"pass": "draft", "only": [], "auto": False}+ sb.save_storyboard(P.STATE_DIR, board)+ return board++[email protected]("how", ["dispatcher", "queued_jobs", "claimed_mid_plan"])+def test_board1_replan_refuses_while_the_board_renders(how):+ with _Fixture() as fx:+ h1 = _plan(fx)+ assert h1.status == 200, h1.body+ bid = h1.body["board_id"]+ before = _mark_rendering(bid)+ saved_queue = list(P.STATE["queue"])+ try:+ if how == "dispatcher":+ with P._SB_LOCK:+ P._SB_RENDERS[bid] = {"stop": False, "pass": "draft", "queued": 1}+ h2 = _plan(fx, board_id=bid, style="a different look")+ elif how == "queued_jobs":+ with P.LOCK:+ P.STATE["queue"] = saved_queue + [{"id": "job_b1_0", "params": {}}]+ h2 = _plan(fx, board_id=bid, style="a different look")+ else:+ # The render is claimed WHILE the replacement is being planned.+ real = mv.plan_music_video++ def planning(*a, **k):+ with P._SB_LOCK:+ P._SB_RENDERS[bid] = {"stop": False, "pass": "draft", "queued": 0}+ return real(*a, **k)+ from unittest import mock+ with mock.patch.object(mv, "plan_music_video", planning):+ h2 = _plan(fx, board_id=bid, style="a different look")+ assert h2.status == 409, h2.body+ assert h2.body.get("busy") is True+ after = sb.load_storyboard(P.STATE_DIR, bid)+ assert [s.get("draft_job_id") for s in after["shots"]] == \+ [s.get("draft_job_id") for s in before["shots"]]+ assert after.get("render_intent") == before["render_intent"]+ finally:+ with P._SB_LOCK:+ P._SB_RENDERS.pop(bid, None)+ with P.LOCK:+ P.STATE["queue"] = saved_queue+++def test_board1_replan_of_an_idle_board_still_updates_in_place():+ with _Fixture() as fx:+ bid = _plan(fx).body["board_id"]+ h2 = _plan(fx, board_id=bid, style="a different look")+ assert h2.status == 200 and h2.body["board_id"] == bid+++# ---- BOARD-2: a late reply for board A never paints under board B ---------------+from extract_panel_js import extract_function # noqa: E402+++def _sb_js(*names):+ src = (JS / "storyboard.js").read_text(encoding="utf-8")+ return "\n".join(extract_function(n, src) for n in names)+++def test_board2_late_keep_all_and_grade_replies_are_dropped_after_a_switch():+ fns = _sb_js("sbKeepAllUngraded", "sbGrade", "sbFlushSave", "sbShotById")+ out = _node(fns + r"""+const calls = [];+let painted = [];+const SB = { id: 'board-A', payload: { board: { id: 'board-A', shots: [+ { n: 1, uid: 'shot_A1' }] } }, saveInFlight: false, saveAgain: false };+function sbRenderPlan(r) { painted.push(r.board.id); }+function phosToast() {}+function sbAdoptLiveEdits() { return false; }+function sbQueueSave() {}+let release;+const gate = new Promise(res => { release = res; });+globalThis.fetch = async (url, init) => {+ const body = init && init.body;+ calls.push([url, body && body.toString ? body.toString() : String(body)]);+ if (url.includes('keep-all')) await gate; // A's reply is slow+ if (url.includes('save')) await gate;+ const id = url.includes('save') ? JSON.parse(body).id : body.get('id');+ return { json: async () => ({ ok: true, kept: 1,+ board: { id, shots: [{ n: 1, uid: id === 'board-A' ? 'shot_A1' : 'shot_B1' }] } }) };+};+(async () => {+ const keep = sbKeepAllUngraded(); // pressed on A+ const save = sbFlushSave(); // a save of A in flight+ // The user opens B before either reply lands.+ SB.id = 'board-B';+ SB.payload = { board: { id: 'board-B', shots: [{ n: 1, uid: 'shot_B1' }] } };+ release();+ await keep; await save;+ const shown = SB.payload.board.id;+ await sbGrade(1, 'cut', ''); // CUT on what is displayed+ const grade = calls.find(c => c[0] === '/storyboard/grade')[1];+ console.log(JSON.stringify({ shown, painted, grade }));+})();+""")+ assert out["shown"] == "board-B"+ assert "board-A" not in out["painted"]+ assert "id=board-B" in out["grade"] and "uid=shot_B1" in out["grade"]+++def _post_sb(action, form, body=""):+ h = _H()+ P.Handler._storyboard_post(h, action, body, {k: [v] for k, v in form.items()})+ return h.status, h.payload+++class _H:+ def __init__(self):+ self.status, self.payload = None, None++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++def test_board2_server_refuses_a_grade_whose_uid_is_another_shot():+ board = sb.new_storyboard("sb_b2_grade", "Grade target")+ board["shots"] = [{"n": 1, "prompt": "a", "mode": "text", "uid": sb.new_shot_uid()}]+ sb.save_storyboard(P.STATE_DIR, board)+ status, body = _post_sb("grade", {"id": "sb_b2_grade", "n": "1",+ "grade": "cut", "uid": "shot_someone_else"})+ assert status == 409 and body["ok"] is False+ assert sb.load_storyboard(P.STATE_DIR, "sb_b2_grade")["shots"][0].get("grade") is None+ status, body = _post_sb("grade", {"id": "sb_b2_grade", "n": "1", "grade": "cut",+ "uid": board["shots"][0]["uid"]})+ assert status in (None, 200) and body["ok"] is True+ assert sb.load_storyboard(P.STATE_DIR, "sb_b2_grade")["shots"][0].get("grade") == "cut"+++# ---- BOARD-3: a retake (and an imported copy) is a shot with its OWN uid --------+import test_retake as _tr # noqa: E402+from unittest import mock # noqa: E402+++def test_board3_retake_gets_a_fresh_uid_and_patches_stay_apart():+ t = _tr.TheRetake("test_the_pool_carries_the_prompt")+ t.setUp()+ try:+ t.board["shots"][0]["uid"] = "shot_original"+ h = _tr.FakeHandler()+ with mock.patch.object(P, "_sb_known_character_ids", return_value=["bizarrotrn"]), \+ mock.patch.object(P, "_sb_h3_available", return_value=False), \+ mock.patch.object(sb, "shot_to_job", return_value={"mode": "t2v", "prompt": "p"}):+ h.post("edit/generate", {"id": "sb_t", "prompt": "he turns, slower",+ "duration": "4", "film_start": "0",+ "retake_of": "c1"})+ assert h.status == 202, h.payload+ orig, take = t.board["shots"][0], t.board["shots"][-1]+ assert orig["uid"] == "shot_original"+ assert take["uid"] and take["uid"] != "shot_original"+ P._sb_patch_board("sb_t", shots={"shot_original": {"draft_output": "/o/a.mp4"}})+ assert orig.get("draft_output") == "/o/a.mp4"+ assert take.get("draft_output") is None+ P._sb_patch_board("sb_t", shots={take["uid"]: {"draft_output": "/o/b.mp4"}})+ assert take.get("draft_output") == "/o/b.mp4"+ assert orig.get("draft_output") == "/o/a.mp4"+ finally:+ t.tearDown()+++def test_board3_normalize_splits_a_duplicate_uid_first_holder_keeps_it():+ board = sb.new_storyboard("sb_b3_dup", "Dup")+ board["shots"] = [{"n": 1, "prompt": "a", "mode": "text", "uid": "shot_same"},+ {"n": 2, "prompt": "b", "mode": "text", "uid": "shot_same"}]+ P._sb_normalize(board)+ uids = [s["uid"] for s in board["shots"]]+ assert uids[0] == "shot_same" and uids[1] != "shot_same" and len(set(uids)) == 2+ # The GET path (reconcile) repairs a board saved by an earlier build too.+ board["shots"][1]["uid"] = "shot_same"+ with mock.patch.object(P, "_sb_job_index", return_value={}):+ assert P._sb_reconcile(board) is True+ assert len({s["uid"] for s in board["shots"]}) == 2+++def test_board3_imported_copy_gets_its_own_uid(tmp_path):+ clip = tmp_path / "a.mp4"+ clip.write_bytes(b"x")+ src = {"id": "sb_src", "title": "Src",+ "shots": [{"n": 1, "uid": "shot_src1", "draft_output": str(clip), "prompt": "a"}]}+ dst = {"id": "sb_dst", "shots": []}+ imported, _ = P._sb_import_shots(dst, src)+ assert imported and dst["shots"][0]["uid"] != "shot_src1"+ assert src["shots"][0]["uid"] == "shot_src1"+++# ---- BOARD-4: "Edit & re-render" take history reaches the Editor's relink offer --+import storyboard_editor as _sedit # noqa: E402+from test_storyboard_editor_api import _board as _ed_board, _clip as _ed_clip, \+ _edit as _ed_edit # noqa: E402+++def test_board4_new_take_then_render_offers_exactly_one_replacement(tmp_path):+ old, new = tmp_path / "old.mp4", tmp_path / "new.mp4"+ old.write_bytes(b"x")+ new.write_bytes(b"y")+ board = _ed_board([old])+ edit = _sedit.normalise_edit(_ed_edit([_ed_clip(str(old), 0.0, 4.0, 0.0, id="c1")]))+ shot = P._sb_new_take(board, 1) # Storyboard "Edit & re-render"+ assert shot["takes"] and isinstance(shot["takes"][0], dict)+ shot["draft_job_id"] = "j-new"+ with mock.patch.object(P, "_sb_job_index",+ return_value={"j-new": {"status": "done",+ "output_path": str(new)}}), \+ mock.patch.object(P, "_probe_video_dims", return_value=(0, 0)):+ P._sb_reconcile(board)+ assert shot["draft_output"] == str(new)+ rows = [r for r in P._sbe_relinks(board, edit) if r.get("id") == "c1"]+ assert len(rows) == 1, rows+ assert rows[0]["path"] == str(old) and rows[0]["to"] == str(new)+++def test_board4_take_path_reads_both_shapes_and_reconcile_dedupes_across_them():+ assert sb.take_path("/o/a.mp4") == "/o/a.mp4"+ assert sb.take_path({"path": "/o/a.mp4", "pass": "draft"}) == "/o/a.mp4"+ assert sb.take_path({"pass": "draft"}) == "" and sb.take_path(None) == ""+ board = _ed_board([Path("/o/s1_v1.mp4")])+ board["shots"][0]["takes"] = [{"path": "/o/s1_v1.mp4", "pass": "draft"}]+ board["shots"][0]["draft_job_id"] = "j2"+ with mock.patch.object(P, "_sb_job_index",+ return_value={"j2": {"status": "done",+ "output_path": "/o/s1_v2.mp4"}}), \+ mock.patch.object(P, "_probe_video_dims", return_value=(0, 0)):+ P._sb_reconcile(board)+ assert [sb.take_path(t) for t in board["shots"][0]["takes"]] == ["/o/s1_v1.mp4"]+++# ---- BOARD-6: a resumed render waits for the jobs a restart restored ------------+def test_board6_resume_waits_for_restored_jobs_then_films_once(tmp_path):+ state = tmp_path / "state"+ state.mkdir()+ a, b = tmp_path / "s1.mp4", tmp_path / "s2.mp4"+ a.write_bytes(b"x")+ board = _ed_board([a], bid="sb_b6")+ board["shots"].append({"n": 2, "title": "shot 2", "mode": "text", "engine": "ltx",+ "prompt": "shot 2 happens", "duration_s": 5.0, "seed": 7,+ "refs": [], "status": "queued", "draft_job_id": "j2"})+ board["auto"] = True+ board["render_intent"] = {"pass": "draft", "only": None, "auto": True}+ qstate = {"queue": [{"id": "j2", "status": "queued", "params": {}}],+ "current": None, "history": []}+ films, intent_while_waiting = [], []++ def fake_sleep(_s):+ # The restored job is still queued: the intent must still be on disk.+ intent_while_waiting.append(+ "render_intent" in sb.load_storyboard(state, "sb_b6"))+ b.write_bytes(b"y")+ qstate["queue"] = []+ qstate["history"] = [{"id": "j2", "status": "done", "output_path": str(b)}]++ with mock.patch.object(P, "STATE_DIR", state), \+ mock.patch.object(P, "STATE", qstate), \+ mock.patch.object(P, "push", lambda *a_, **k: None), \+ mock.patch.object(P, "persist_queue", lambda: None), \+ mock.patch.object(P, "_sb_h3_available", return_value=False), \+ mock.patch.object(P, "_probe_video_dims", return_value=(0, 0)), \+ mock.patch.object(P, "_sb_lipsync_gate", lambda *a_, **k: None), \+ mock.patch.object(P, "_sb_sweep_stage_a", lambda *a_, **k: None), \+ mock.patch.object(P, "_sb_enqueue", side_effect=AssertionError("re-queued")), \+ mock.patch.object(P, "_sb_auto_film",+ side_effect=lambda bd: films.append(+ [s.get("draft_output") for s in bd["shots"]])), \+ mock.patch.object(P.time, "sleep", fake_sleep):+ sb.save_storyboard(state, board)+ with P._SB_LOCK:+ P._SB_RENDERS["sb_b6"] = {"stop": False, "pass": "draft", "queued": 0,+ "auto": True, "resumed": True}+ try:+ P._sb_render_thread("sb_b6", "draft", None)+ finally:+ with P._SB_LOCK:+ P._SB_RENDERS.pop("sb_b6", None)+ after = sb.load_storyboard(state, "sb_b6")+ assert intent_while_waiting and all(intent_while_waiting)+ assert films == [[str(a), str(b)]] # ONE film, every output+ assert "render_intent" not in after+++# ---- BOARD-7: re-planning sets the old timeline aside instead of exporting it ----+def test_board7_replan_keeps_old_timeline_as_a_draft_and_export_leaves_it(tmp_path):+ old_clip = tmp_path / "old-plan.mp4"+ old_clip.write_bytes(b"x")+ with _Fixture() as fx:+ bid = _plan(fx).body["board_id"]+ bdir = P._sbe_board_dir(bid)+ bdir.mkdir(parents=True, exist_ok=True)+ edit = _sedit.normalise_edit(_ed_edit([_ed_clip(str(old_clip), 0.0, 4.0, 0.0, id="c1")]))+ _sedit.save_edit(bdir, edit)+ assert _sedit.load_edit(bdir)["clips"]++ h2 = _plan(fx, board_id=bid, style="a different look")+ assert h2.status == 200, h2.body+ # Export's rule is "a saved timeline with clips wins" — there is none now.+ assert _sedit.load_edit(bdir) is None+ rows = _sedit.list_drafts(bdir)+ kept = [r for r in rows if not r["active"]]+ assert len(kept) == 1 and kept[0]["clips"] == 1+ assert "before re-plan" in kept[0]["name"]+ assert any("kept as the draft" in n for n in h2.body["notes"])+ # The old cut is intact and can be switched back to.+ _sedit.activate_draft(bdir, kept[0]["slug"])+ assert _sedit.load_edit(bdir)["clips"][0]["path"] == str(old_clip)++ # A re-plan with no timeline yet sets nothing aside.+ h3 = _plan(fx, board_id=bid)+ assert h3.status == 200+ n_drafts = len(_sedit.list_drafts(bdir))+ _sedit.activate_draft(bdir, [r for r in _sedit.list_drafts(bdir)+ if "New plan" in r["name"]][0]["slug"])+ h4 = _plan(fx, board_id=bid)+ assert h4.status == 200 and len(_sedit.list_drafts(bdir)) == n_drafts+++def test_board7_export_uses_the_new_plans_shots_after_replan(tmp_path):+ old_clip = tmp_path / "old-plan.mp4"+ old_clip.write_bytes(b"x")+ with _Fixture() as fx:+ bid = _plan(fx).body["board_id"]+ bdir = P._sbe_board_dir(bid)+ bdir.mkdir(parents=True, exist_ok=True)+ _sedit.save_edit(bdir, _sedit.normalise_edit(+ _ed_edit([_ed_clip(str(old_clip), 0.0, 4.0, 0.0, id="c1")])))+ assert _plan(fx, board_id=bid, style="another").status == 200+ board = sb.load_storyboard(P.STATE_DIR, bid)+ timeline_used = []+ with mock.patch.object(P, "_sbe_render_edit",+ side_effect=lambda *a, **k: timeline_used.append(a) or+ {"ok": False, "error": "mocked"}), \+ mock.patch.object(P, "_sb_assemble_film",+ return_value={"ok": False, "error": "mocked"}):+ P._sb_export(board)+ assert timeline_used == [], "Export assembled the old plan's timeline"+++# ---- BOARD-8: Storyboard Export honours the Editor's soundtrack and mix ---------+def test_board8_both_export_entrances_send_the_saved_audio(tmp_path):+ clip = tmp_path / "s1.mp4"+ clip.write_bytes(b"x")+ edited_song = tmp_path / "edited-song.wav"+ edited_song.write_bytes(b"RIFF")+ with _Fixture() as fx:+ board = sb.new_storyboard("sb_b8_mv", "Music film")+ board["music_video"] = {"song": str(fx.song), "images": []}+ board["shots"] = [{"n": 1, "uid": "shot_b8", "mode": "text", "engine": "ltx",+ "prompt": "a", "duration_s": 4.0, "status": "done",+ "draft_output": str(clip)}]+ sb.save_storyboard(P.STATE_DIR, board)+ bdir = P._sbe_board_dir("sb_b8_mv")+ bdir.mkdir(parents=True, exist_ok=True)+ edit = _sedit.normalise_edit(_ed_edit([_ed_clip(str(clip), 0.0, 4.0, 0.0, id="c1")]))+ edit["audio"] = {"path": str(edited_song), "offset": 0.0, "mode": "under"}+ _sedit.save_edit(bdir, edit)+ got = []++ def capture(*a, **k):+ got.append((str(k.get("music")), k.get("music_mode")))+ return {"ok": False, "error": "mocked"}++ with mock.patch.object(P, "_sb_assemble_film", side_effect=capture), \+ mock.patch.object(P, "_sb_crop_to_aspect", return_value=None):+ # Storyboard's Export button on a music-video board:+ h = _Handler({"board_id": "sb_b8_mv"})+ RM.post_music_video_film(h, "/music/video/film", {}, "")+ # The Editor's Render (the client posts the document's own values):+ P._sbe_render_edit(sb.load_storyboard(P.STATE_DIR, "sb_b8_mv"),+ _sedit.load_edit(bdir), music=str(edited_song),+ music_mode="under")+ assert got == [(str(edited_song), "under"), (str(edited_song), "under")], got+++# ---- BOARD-9: Stills first never renders video past a failed still -------------+import test_stills_first as _tsf # noqa: E402+import test_stills_first_ui as _tsfui # noqa: E402+++def _hold_case():+ t = _tsf.TheRenderThreadHoldsForApproval("test_an_approved_shot_proceeds_to_video")+ t.setUp()+ return t+++def _teardown(t):+ t.doCleanups()+++def _run9(t, board, *, index, refuse_first=False):+ """The render thread, with the still job's REAL verdict in the index."""+ bid = board["id"]+ t.save(board)+ P._SB_RENDERS[bid] = {"stop": False, "queued": 0}+ video_forms, calls = [], []++ def enqueue(form):+ calls.append(form)+ if refuse_first and len(calls) == 1:+ raise RuntimeError("image engine refused") # the still+ video_forms.append(form)+ return f"video-{len(video_forms)}"+ with mock.patch.object(P, "_sb_enqueue", side_effect=enqueue), \+ mock.patch.object(P, "_sb_job_index", return_value=index), \+ mock.patch.object(P, "_sb_h3_available", return_value=False), \+ mock.patch.object(P, "h3_supports_chain_prompts", return_value=False), \+ mock.patch.object(P, "h3_supports_first_frame", return_value=False), \+ mock.patch.object(P, "_sb_lipsync_gate", lambda *a, **k: None), \+ mock.patch.object(P, "_sb_sweep_stage_a", lambda *a, **k: None):+ P._sb_render_thread(bid, "draft", None)+ return video_forms+++_FAILED_STILL = {"j-still": {"status": "failed", "output_path": None,+ "error": "the still could not be made"}}+++def test_board9_a_failed_still_holds_the_video():+ t = _hold_case()+ try:+ board = _tsf._board("sb_b9_fail", [_tsf._shot(1, still_job_id="j-still")])+ assert _run9(t, board, index=_FAILED_STILL) == []+ shot = t.load("sb_b9_fail")["shots"][0]+ assert shot.get("draft_job_id") is None and shot.get("still_error")+ finally:+ _teardown(t)+++def test_board9_a_still_that_could_not_be_queued_holds_the_video():+ t = _hold_case()+ try:+ board = _tsf._board("sb_b9_refused", [_tsf._shot(1)])+ assert _run9(t, board, index={}, refuse_first=True) == []+ shot = t.load("sb_b9_refused")["shots"][0]+ assert shot.get("still_job_id") == "skipped" and shot.get("still_error")+ finally:+ _teardown(t)+++def test_board9_render_without_a_still_is_an_explicit_approval():+ t = _hold_case()+ try:+ board = _tsf._board("sb_b9_ok", [+ _tsf._shot(1, still_job_id="j-still", still_error="the still could not be made")])+ t.save(board)+ h = t.post("approve-still", {"id": ["sb_b9_ok"], "n": ["1"]})+ assert h.status in (None, 200), h.payload+ assert t.load("sb_b9_ok")["shots"][0]["still_approved"] is True+ # Now it may render — unanchored, because the user said so.+ assert len(_run9(t, t.load("sb_b9_ok"), index=_FAILED_STILL)) == 1+ finally:+ _teardown(t)+++def test_board9_the_failed_still_card_offers_retry_and_unanchored():+ c = _tsfui.TheCardShowsApproveWhenAwaiting("test_an_unapproved_still_shows_an_approve_button")+ html = c._card({"still_job_id": "j", "still_error": "boom"})+ assert 'data-act="restill"' in html and 'data-act="approve-still"' in html+ assert "Render without a still" in html+ html_off = c._card({"still_job_id": "j", "still_error": "boom"},+ board_over={"stills_first": False})+ assert 'data-act="approve-still"' not in html_off+++# ---- BOARD-10: a pre-FILM-11 music-video still is still the user's photo --------+def _legacy_singing_shot(fx):+ bid = _plan(fx).body["board_id"]+ board = sb.load_storyboard(P.STATE_DIR, bid)+ shot = next(s for s in board["shots"] if s["music_video"]["kind"] == "singing")+ for s in board["shots"]:+ s.pop("still_source", None) # the pre-change shape+ return board, shot+++def test_board10_new_still_keeps_a_legacy_cast_photo_and_it_reaches_the_job():+ with _Fixture() as fx:+ board, shot = _legacy_singing_shot(fx)+ photo = shot["still"]+ assert photo == shot["music_video"]["image"] and "still_source" not in shot+ # Defensive: the clear-still path recognises the provenance on its own.+ P._sb_clear_still(board, shot["n"])+ assert shot["still"] == photo and shot["still_source"] == "user"+ job = sb.shot_to_job(shot, sb.default_policy()["draft"], engine_mode="ltx")+ assert job["mode"] == "a2v" and job["image"] == photo+++def test_board10_normalize_migrates_the_marker_and_stills_first_never_holds_it():+ with _Fixture() as fx:+ board, shot = _legacy_singing_shot(fx)+ P._sb_normalize(board)+ assert all(s.get("still_source") == "user" for s in board["shots"]+ if s.get("still") == (s.get("music_video") or {}).get("image"))+ board2, _ = _legacy_singing_shot(fx)+ with mock.patch.object(P, "_sb_job_index", return_value={}):+ assert P._sb_reconcile(board2) is True+ assert all(s.get("still_source") == "user" for s in board2["shots"])+ # A machine-made still is NOT the user's.+ assert not sb.is_user_still({"still": "/o/gen.png", "music_video": {"image": "/u/a.png"}})+ assert not sb.is_user_still({"still": "/o/gen.png"})+++def test_board10_stills_first_does_not_hold_a_broll_shot_on_the_users_photo():+ t = _hold_case()+ try:+ board = _tsf._board("sb_b10_broll", [_tsf._shot(+ 1, still="/u/piano.png", music_video={"image": "/u/piano.png", "kind": "broll"})])+ assert len(_run9(t, board, index={})) == 1+ finally:+ _teardown(t)diff --git a/test_codex_4170_editor.py b/test_codex_4170_editor.pynew file mode 100644index 0000000..64a853e--- /dev/null+++ b/test_codex_4170_editor.py@@ -0,0 +1,990 @@+#!/usr/bin/env python3+"""4.17.0 Codex review — the Editor area (findings_editor.md, EDITOR-1..14).++Every fixed finding is pinned here with a test that fails on e724af7 and+passes after its fix. JS runs in node against the REAL functions, extracted+by scripts/extract_panel_js.py, on the same DOM shim the Editor's own gates+use (test_storyboard_editor_ui.SHIM + test_editor_save_integrity's fetch).+"""+from __future__ import annotations++import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function, panel_source # noqa: E402++import storyboard_editor as sedit # noqa: E402+import test_storyboard_editor_ui as ui # noqa: E402+import test_editor_save_integrity as si # noqa: E402++JS = ROOT / "webapp" / "js"+++def run(body: str, extra: tuple = (), stubs: tuple = (), shim: str = "") -> dict:+ """Like test_editor_save_integrity.run, plus `stubs`: no-op functions for+ the painters a real function reaches that this gate is not about. A stub+ is declared BEFORE the extractions, so an extracted function of the same+ name (the shim's `sbeAdopt` stub included) wins."""+ if ui.NODE is None:+ raise unittest.SkipTest("node not on PATH")+ source = panel_source()+ names = list(ui.FUNCTIONS) + [n for n in extra if n not in ui.FUNCTIONS]+ stub_js = "".join(f"function {n}() {{ return null; }}\n"+ for n in stubs if n not in names)+ script = (ui.SHIM + si.HELD_FETCH + shim + stub_js+ + "\n".join(extract_function(n, source) for n in names)+ + "\n(async () => {\nconst out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out));\n})();\n")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = subprocess.run([ui.NODE, str(path)], capture_output=True,+ text=True, timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ if not res.stdout.strip():+ raise AssertionError("the script never finished\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)+++def _clip(cid, path, start, end, film_start, **kw):+ c = sedit.new_clip(path, start, end, film_start, id=cid, duration=10.0,+ source="human")+ c.update(kw)+ return c+++def _doc(clips, **kw):+ d = {"version": sedit.EDIT_VERSION, "board_id": "sb_e", "revision": 0,+ "source": "human", "audio": None, "beats": None, "clips": clips,+ "settings": {}}+ d.update(kw)+ return d+++# Everything sbeAdopt / sbeCloseDoc reach that is paint, audio or network.+ADOPT_STUBS = (+ "sbeKeyedDismiss", "sbePaintNotices", "sbePaintMusicName", "sbeSetMusicMode",+ "sbeSyncMusic", "sbePaintRelink", "sbePaintOffline", "sbeDeliverPaint",+ "edPoolRefresh", "sbeFetchPeaks", "sbeRestoreUndoIfFresh", "sbeZoomMin",+ "sbeShowFrameAt", "sbeStop", "sbeVersionsClose", "edRemember", "edShowPicker",+ "sbePaintRenderChip",+)+ADOPT_SHIM = r"""+const ED = { src: 'board' };+global.window = { addEventListener() {}, removeEventListener() {} };+"""+++# =============================================================================+# EDITOR-1 [P0] — markers survive Save, backup, unload, reopen; films isolated+# =============================================================================+class Editor1MarkersTravel(unittest.TestCase):++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(r"""+const beacons = [];+global.navigator = { sendBeacon: (url, blob) => { beacons.push({ url, blob }); return true; } };+function filmA() {+ return { title: 'A', edit: { revision: 3, clips: [clip({ id: 'a', end: 2 })],+ markers: [{ id: 'm0', at: 0.5, kind: 'beat', label: 'drop' }] } };+}+SBE.id = 'film-A'; SBE.open = true; SBE.session = 's1';+sbeAdopt(filmA(), false);+out.adoptedA = (SBE.markers || []).map(m => m.id);+// The real M-key handler.+SBE.playhead = 1.25;+sbeMarkerAtPlayhead();+out.liveAfterAdd = (SBE.markers || []).map(m => m.at);+// Save: the request, and the response comparison ("did anything move?").+FETCHES = [];+NEXT = { status: 200, body: { ok: true, edit: { revision: 4, clips: [],+ markers: [{ id: 'm0', at: 0.5, kind: 'beat', label: 'drop' }] } } };+await sbeSave(false);+out.saved = (JSON.parse(FETCHES[0].body).edit.markers || []).map(m => m.at);+out.dirtyAfterSave = SBE.dirty;+// The crash backup (debounced lane) and the unload beacon.+SBE.dirty = true; SBE.backedUpAt = 0; SBE.lastBackupSig = '';+FETCHES = [];+NEXT = { status: 200, body: { ok: true } };+await sbeBackup(true);+out.backup = (JSON.parse(FETCHES[0].body).edit.markers || []).map(m => m.at);+sbeBeaconBackup();+out.beacon = (JSON.parse(await beacons[0].blob.text()).edit.markers || []).map(m => m.at);+// Another film: its own markers (none), not A's.+SBE.id = 'film-B';+sbeAdopt({ title: 'B', edit: { revision: 1, clips: [clip({ id: 'b', end: 2 })] } }, false);+out.adoptedB = (SBE.markers || []).length;+// Back to A, then close.+SBE.id = 'film-A';+sbeAdopt(filmA(), false);+SBE.dirty = false;+sbeCloseDoc({ quiet: true });+out.afterClose = (SBE.markers || []).length;+""", extra=("sbeAdopt", "sbeCloseDoc", "sbeMarkerAtPlayhead", "sbeMarkerMutate",+ "sbeMarkerAdd", "sbeBackup", "sbeBeaconBackup", "sbeTsCopy",+ "sbeQueueSave"),+ stubs=ADOPT_STUBS, shim=ADOPT_SHIM)++ def test_a_reopened_film_shows_its_markers(self):+ self.assertEqual(self.r["adoptedA"], ["m0"])+ self.assertEqual(self.r["liveAfterAdd"], [0.5, 1.25])++ def test_save_backup_and_unload_all_carry_them(self):+ self.assertEqual(self.r["saved"], [0.5, 1.25])+ self.assertEqual(self.r["backup"], [0.5, 1.25])+ self.assertEqual(self.r["beacon"], [0.5, 1.25])++ def test_the_save_response_is_compared_with_the_markers_too(self):+ # Same serialisation on both sides of the wire: nothing moved.+ self.assertFalse(self.r["dirtyAfterSave"])++ def test_films_do_not_share_markers(self):+ self.assertEqual(self.r["adoptedB"], 0)+ self.assertEqual(self.r["afterClose"], 0)++ def test_every_save_body_caller_passes_every_collection_it_reads(self):+ src = (JS / "editor.js").read_text(encoding="utf-8")+ calls = src.split("sbeSaveBody({")[1:]+ self.assertGreaterEqual(len(calls), 4)+ for c in calls:+ head = c[:c.index("})")]+ for key in ("clips:", "overlays:", "tracks:", "transitions:",+ "markers:"):+ self.assertIn(key, head, head)++ def test_the_saved_document_reaches_the_nle_export(self):+ body = {"edit": _doc([_clip("a", "/x/a.mp4", 0, 2, 0)],+ markers=[{"id": "m1", "at": 1.25, "kind": "note",+ "label": ""}])}+ with tempfile.TemporaryDirectory() as d:+ sedit.save_edit(d, body["edit"])+ back = sedit.load_edit(d)+ self.assertEqual([m["at"] for m in sedit.markers_of(back)], [1.25])+++# =============================================================================+# EDITOR-2 [P1] — "-14 LUFS" delivers a film instead of an ffmpeg refusal+# =============================================================================+def _ffmpeg():+ import mlx_ltx_panel as panel # noqa: PLC0415+ return str(panel.FFMPEG) if panel.FFMPEG else None+++def _av_clip(path: Path, secs=3, w=320, h=180, vol_db=-32, freq=440) -> None:+ subprocess.run([_ffmpeg(), "-y", "-loglevel", "error",+ "-f", "lavfi", "-i", f"testsrc2=s={w}x{h}:d={secs}:r=24",+ "-f", "lavfi", "-i", f"sine=f={freq}:d={secs}:sample_rate=48000",+ "-af", f"volume={vol_db}dB", "-c:v", "libx264", "-pix_fmt",+ "yuv420p", "-c:a", "aac", "-shortest", str(path)], check=True)+++def _integrated_lufs(path: Path) -> float:+ r = subprocess.run([_ffmpeg(), "-hide_banner", "-nostats", "-i", str(path),+ "-map", "0:a:0", "-af", "ebur128", "-f", "null", "-"],+ capture_output=True, text=True)+ import re # noqa: PLC0415+ vals = re.findall(r"I:\s+(-?[\d.]+) LUFS", r.stderr)+ assert vals, r.stderr[-2000:]+ return float(vals[-1])+++class Editor2LoudnormRenders(unittest.TestCase):+ def test_a_real_encode_with_loudnorm_writes_a_levelled_film(self):+ import mlx_ltx_panel as panel # noqa: PLC0415+ if not _ffmpeg():+ raise unittest.SkipTest("no ffmpeg")+ with tempfile.TemporaryDirectory() as d:+ src = Path(d) / "a.mp4"+ _av_clip(src)+ out = Path(d) / "film.mp4"+ res = panel._sb_assemble_film(+ [str(src)], out,+ timeline=[{"path": str(src), "start": 0.0, "end": 3.0,+ "film_start": 0.0}],+ deliver={"format": "h264", "size": "native", "loudnorm": True})+ self.assertTrue(res.get("ok"), res)+ self.assertTrue(out.is_file() and out.stat().st_size > 0)+ before, after = _integrated_lufs(src), _integrated_lufs(out)+ self.assertLess(before, -25.0)+ self.assertAlmostEqual(after, -14.0, delta=2.5)+++# =============================================================================+# EDITOR-3 [P1] — the frame heal never pushes a clip into a locked one+# =============================================================================+class Editor3HealRespectsLockedClips(unittest.TestCase):+ def _fixture(self):+ return _doc([+ _clip("a", "/x/a.mp4", 0.0, 0.98, 0.0),+ _clip("b", "/x/b.mp4", 0.0, 0.98, 0.98),+ _clip("c", "/x/c.mp4", 0.0, 2.0, 1.96, locked=True),+ ], settings={"fps": 24})++ def _save_twice(self, doc):+ with tempfile.TemporaryDirectory() as d:+ sedit.save_edit(d, doc)+ first = sedit.load_edit(d)+ sedit.save_edit(d, json.loads(json.dumps(first)))+ second = sedit.load_edit(d)+ return first, second++ def test_the_saved_document_validates_and_the_lock_does_not_move(self):+ self.assertEqual(sedit.blocking_errors(sedit.validate_edit(self._fixture())), [])+ first, second = self._save_twice(self._fixture())+ self.assertEqual(sedit.blocking_errors(sedit.validate_edit(first)), [],+ [(c["id"], c["film_start"], c["film_end"]) for c in first["clips"]])+ by = {c["id"]: c for c in first["clips"]}+ self.assertEqual((by["c"]["film_start"], by["c"]["film_end"]), (1.96, 3.96))+ self.assertLessEqual(by["b"]["film_end"], 1.96 + 1e-6)+ # ...and the healed lengths are whole frames.+ for cid in ("a", "b"):+ n = (by[cid]["film_end"] - by[cid]["film_start"]) * 24+ self.assertAlmostEqual(n, round(n), places=3)++ def test_repeated_saves_are_stable(self):+ first, second = self._save_twice(self._fixture())+ shape = lambda d: [(c["id"], c["start"], c["end"], c["film_start"],+ c["film_end"]) for c in d["clips"]]+ self.assertEqual(shape(first), shape(second))++ def test_the_heal_itself_is_bounded_by_the_anchor(self):+ doc = self._fixture()+ sedit.heal_subframe_lengths(doc)+ self.assertEqual(sedit.blocking_errors(sedit.validate_edit(doc)), [])++ def test_a_run_with_room_still_rounds_to_nearest(self):+ doc = _doc([_clip("a", "/x/a.mp4", 0.0, 0.98, 0.0),+ _clip("b", "/x/b.mp4", 0.0, 0.98, 0.98)], settings={"fps": 24})+ sedit.heal_subframe_lengths(doc)+ self.assertEqual([c["film_end"] for c in doc["clips"]], [1.0, 2.0])++ def test_a_heal_that_would_not_validate_is_never_written(self):+ # Backstop: even a heal that misbehaves cannot write an invalid file.+ def bad_heal(edit):+ edit["clips"][1]["film_end"] = 5.0+ return []+ from unittest import mock # noqa: PLC0415+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(sedit, "heal_subframe_lengths", bad_heal):+ sedit.save_edit(d, self._fixture())+ back = sedit.load_edit(d)+ self.assertEqual(sedit.blocking_errors(sedit.validate_edit(back)), [])+++# =============================================================================+# EDITOR-4 [P1] — every Replace result is a document Save accepts+# =============================================================================+class Editor4ReplaceStaysSaveable(unittest.TestCase):+ CASES = [+ # (name, old clip kwargs, new item) — the old clip sits at 10..15 s.+ ("shorter", dict(start=0.0, end=5.0), {"duration_s": 4.0}),+ ("shorter_in_point", dict(start=5.0, end=10.0), {"duration_s": 4.9}),+ ("in_point_clamped", dict(start=5.0, end=10.0), {"duration_s": 7.0}),+ ("in_point_kept", dict(start=2.0, end=7.0), {"duration_s": 30.0}),+ ("speed_2x_fits", dict(start=3.0, end=13.0, speed=2.0), {"duration_s": 12.0}),+ ("speed_2x_short", dict(start=0.0, end=10.0, speed=2.0), {"duration_s": 8.0}),+ ("speed_half", dict(start=1.0, end=3.5, speed=0.5), {"duration_s": 3.0}),+ ("exact", dict(start=0.0, end=5.0), {"duration_s": 5.0}),+ ("still", dict(start=0.0, end=10.0, speed=2.0),+ {"duration_s": 3.0, "kind": "still", "path": "/x/p.png"}),+ ]++ @classmethod+ def setUpClass(cls) -> None:+ cases = []+ for name, kw, item in cls.CASES:+ c = dict(id="b", path="/x/old.mp4", film_start=10.0, film_end=15.0,+ duration=30.0, source="human", locked=False)+ c.update(kw)+ it = {"path": "/x/new.mp4"}+ it.update(item)+ cases.append([name, [dict(id="a", path="/x/a.mp4", start=0.0, end=10.0,+ film_start=0.0, film_end=10.0, duration=10.0,+ source="human", locked=False), c], it])+ cls.r = run("out.res = {};\nfor (const [name, cs, it] of %s) {\n"+ " const r = sbeReplaceClip(cs, 'b', it);\n"+ " out.res[name] = { ok: r.ok, why: r.why || '', "+ "clips: r.clips.map(sbeCleanClip) };\n}\n" % json.dumps(cases),+ extra=("sbeReplaceClip",))["res"]++ def test_every_accepted_replacement_validates(self):+ for name, _kw, _it in self.CASES:+ with self.subTest(name):+ res = self.r[name]+ doc = _doc(res["clips"])+ errs = sedit.blocking_errors(sedit.validate_edit(doc))+ self.assertEqual(errs, [], (name, res))+ b = [c for c in res["clips"] if c["id"] == "b"][0]+ self.assertEqual((b["film_start"], b["film_end"]), (10.0, 15.0))+ if res["ok"]:+ self.assertNotEqual(b["path"], "/x/old.mp4")++ def test_a_take_that_cannot_fill_the_slot_is_refused_with_the_numbers(self):+ for name in ("shorter", "shorter_in_point", "speed_2x_short"):+ with self.subTest(name):+ self.assertFalse(self.r[name]["ok"])+ self.assertRegex(self.r[name]["why"], r"needs \d")+ for name in ("in_point_clamped", "in_point_kept", "speed_2x_fits",+ "speed_half", "exact", "still"):+ self.assertTrue(self.r[name]["ok"], name)++ def test_in_points_and_speed_are_kept_where_the_take_allows(self):+ b = lambda n: [c for c in self.r[n]["clips"] if c["id"] == "b"][0]+ self.assertEqual((b("in_point_kept")["start"], b("in_point_kept")["end"]), (2.0, 7.0))+ self.assertEqual((b("in_point_clamped")["start"], b("in_point_clamped")["end"]), (2.0, 7.0))+ self.assertEqual((b("speed_2x_fits")["start"], b("speed_2x_fits")["end"]), (2.0, 12.0))+ self.assertEqual(b("speed_2x_fits").get("speed"), 2.0)+ self.assertEqual(b("still").get("kind"), "still")+ self.assertNotIn("speed", b("still"))+++# =============================================================================+# EDITOR-5 [P1] — Paste Attributes applies speed as timing, not as a field+# =============================================================================+class Editor5PasteAttributesSpeed(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(r"""+function film() {+ return lay([clip({ id: 'fast', start: 0, end: 10, speed: 2, duration: 30, source: 'human' }),+ clip({ id: 'norm', start: 0, end: 5, duration: 30, source: 'human' }),+ clip({ id: 'pic', kind: 'still', path: '/x/p.png', start: 0, end: 3,+ duration: null, source: 'human' }),+ clip({ id: 'tail', start: 0, end: 2, duration: 30, source: 'human' })]);+}+out.cases = {};+for (const [name, from, to] of [['2x_onto_1x', 'fast', ['norm']],+ ['1x_onto_2x', 'norm', ['fast']],+ ['2x_onto_still', 'fast', ['pic']],+ ['2x_onto_two', 'fast', ['norm', 'tail']]]) {+ SBE.clips = film(); SBE.undo = []; SBE.redo = [];+ SBE.overlays = []; SBE.tracks = []; SBE.transitions = []; SBE.markers = [];+ const src = sbeClipboardCopy(SBE.clips, [from])[0];+ const ok = sbeMutate(cs => sbeClipboardPasteAttrs(cs, to, src));+ out.cases[name] = { ok, undo: SBE.undo.length, clips: SBE.clips.map(sbeCleanClip) };+}+""", extra=("sbeClipboardCopy", "sbeClipboardPasteAttrs"))["cases"]++ def _by(self, name, cid):+ return [c for c in self.r[name]["clips"] if c["id"] == cid][0]++ def test_every_paste_leaves_a_saveable_timeline_in_one_undo_step(self):+ for name, res in self.r.items():+ with self.subTest(name):+ self.assertTrue(res["ok"])+ self.assertEqual(res["undo"], 1)+ errs = sedit.blocking_errors(sedit.validate_edit(_doc(res["clips"])))+ self.assertEqual(errs, [], (name, res["clips"]))++ def test_speed_changes_the_slot_not_the_window(self):+ n = self._by("2x_onto_1x", "norm")+ self.assertEqual(n.get("speed"), 2.0)+ self.assertEqual((n["start"], n["end"]), (0.0, 5.0))+ self.assertAlmostEqual(n["film_end"] - n["film_start"], 2.5)+ back = self._by("1x_onto_2x", "fast")+ self.assertNotIn("speed", back) # back to 1x = no field+ self.assertAlmostEqual(back["film_end"] - back["film_start"], 10.0)++ def test_a_still_never_gets_a_video_speed(self):+ self.assertNotIn("speed", self._by("2x_onto_still", "pic"))+++# =============================================================================+# EDITOR-6 [P1] — two renders at one delivery become two versions+# =============================================================================+from test_render_job import Sandbox as _RenderSandbox # noqa: E402+++class Editor6ConcurrentRendersAreVersions(_RenderSandbox):+ def setUp(self):+ super().setUp()+ import threading # noqa: PLC0415+ from unittest import mock # noqa: PLC0415+ import mlx_ltx_panel as panel # noqa: PLC0415+ self.panel = panel+ self.gate = threading.Event()+ self.entered = []++ def held_ffmpeg(cmd, label):+ self.entered.append(cmd[-1])+ k = len(self.entered)+ self.gate.wait(10)+ Path(cmd[-1]).write_bytes(b"film-" + str(k).encode())+ p = mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=held_ffmpeg)+ p.start()+ self.addCleanup(p.stop)+ self.addCleanup(self.gate.set)++ def _status(self, job):+ return self._get(f"/storyboard/edit/render/status?job={job}").payload++ def test_both_films_survive_with_their_own_sidecars(self):+ a = self._post("edit/render/start", {"id": "sb_t"}).payload["job"]+ self.assertTrue(self._wait_until(lambda: len(self.entered) >= 1))+ b = self._post("edit/render/start", {"id": "sb_t"}).payload["job"]+ self.assertTrue(self._wait_until(lambda: len(self.entered) >= 2))+ self.gate.set()+ for j in (a, b):+ self.assertTrue(self._wait_until(lambda: self._status(j)["state"] != "running",+ timeout=20))+ ra, rb = self._status(a), self._status(b)+ self.assertEqual((ra["state"], rb["state"]), ("done", "done"), (ra, rb))+ pa, pb = Path(ra["result"]["path"]), Path(rb["result"]["path"])+ self.assertNotEqual(pa, pb)+ self.assertTrue(pa.is_file() and pb.is_file())+ self.assertNotEqual(pa.read_bytes(), pb.read_bytes())+ sa, sb_ = self.panel._sb_film_sidecar(pa), self.panel._sb_film_sidecar(pb)+ self.assertNotEqual(sa, sb_)+ self.assertTrue(sa.is_file() and sb_.is_file())+ # Nothing stays claimed once both are finished.+ self.assertEqual(self.panel._SB_FILM_NAMES_IN_USE, set())++ def test_a_running_render_holds_its_name_until_it_ends(self):+ a = self._post("edit/render/start", {"id": "sb_t"}).payload["job"]+ self.assertTrue(self._wait_until(lambda: len(self.entered) >= 1))+ claimed = set(self.panel._SB_FILM_NAMES_IN_USE)+ self.assertEqual(len(claimed), 1)+ held = Path(next(iter(claimed)))+ # The next name offered for the same delivery is not the held one.+ self.assertNotEqual(self.panel._sb_film_name({"title": "Night Drive"}, None,+ dest=held.parent), held.name)+ self.gate.set()+ self.assertTrue(self._wait_until(lambda: self._status(a)["state"] != "running",+ timeout=20))+ self.assertEqual(self.panel._SB_FILM_NAMES_IN_USE, set())+++# =============================================================================+# EDITOR-7 [P1] — the aspect crop keeps the delivery's codec and container+# =============================================================================+def _probe_stream(path: Path) -> dict:+ import mlx_ltx_panel as panel # noqa: PLC0415+ out = subprocess.run([str(panel.FFPROBE), "-v", "error", "-show_entries",+ "stream=codec_type,codec_name,pix_fmt,width,height,codec_tag_string"+ ":format=format_name", "-of", "json", str(path)],+ capture_output=True, text=True, check=True).stdout+ j = json.loads(out)+ v = [st for st in j["streams"] if st["codec_type"] == "video"][0]+ a = [st for st in j["streams"] if st["codec_type"] == "audio"]+ return {"codec": v["codec_name"], "pix_fmt": v["pix_fmt"], "w": v["width"],+ "h": v["height"], "tag": v.get("codec_tag_string"),+ "audio": a[0]["codec_name"] if a else None,+ "format": j["format"]["format_name"]}+++class Editor7AspectCropKeepsTheDelivery(unittest.TestCase):+ WANT = {"h264": ("h264", None, "mp4"), "hevc": ("hevc", "yuv420p", "mp4"),+ "prores": ("prores", "yuv422p10le", "mov")}++ def _one(self, fmt):+ import mlx_ltx_panel as panel # noqa: PLC0415+ if not (_ffmpeg() and panel.FFPROBE):+ raise unittest.SkipTest("no ffmpeg/ffprobe")+ dl = panel._sb_deliver(fmt, "native")+ with tempfile.TemporaryDirectory() as d:+ src = Path(d) / "a.mp4"+ _av_clip(src, secs=1, w=320, h=180)+ master = Path(d) / f"film_{fmt}{dl['ext']}"+ # The delivery exactly as the assembler encodes it.+ subprocess.run([_ffmpeg(), "-y", "-loglevel", "error", "-i", str(src),+ *panel._sb_encode_args(dl, panel.output_codec_settings()),+ str(master)], check=True)+ before = _probe_stream(master)+ err = panel._sb_crop_to_aspect(master, "9:16", deliver=dl)+ self.assertIsNone(err)+ after = _probe_stream(master)+ left = sorted(x.name for x in Path(d).iterdir())+ return before, after, left++ def test_h264_hevc_and_prores_stay_what_was_asked_for(self):+ for fmt, (codec, pix, container) in self.WANT.items():+ with self.subTest(fmt):+ try:+ before, after, left = self._one(fmt)+ except subprocess.CalledProcessError as exc:+ if fmt == "hevc":+ raise unittest.SkipTest(f"no HEVC encoder here: {exc}")+ raise+ self.assertEqual(after["codec"], codec)+ self.assertEqual(after["codec"], before["codec"])+ self.assertEqual(after["pix_fmt"], before["pix_fmt"])+ if pix:+ self.assertEqual(after["pix_fmt"], pix)+ self.assertIn(container, after["format"])+ self.assertEqual(after["tag"], before["tag"])+ self.assertEqual(after["audio"], before["audio"])+ self.assertEqual((after["w"], after["h"]), (100, 180))+ # No temp file of any kind is left beside the master.+ self.assertEqual(len(left), 2, left)+++# =============================================================================+# EDITOR-8 / EDITOR-9 [P1] — Auto-align measures the window on the film, and+# its proposal corrects the lag instead of doubling it+# =============================================================================+class Editor8And9AutoAlign(unittest.TestCase):+ VFPS = 24.0+ SR = 16000++ def _world(self, *, src_true, film_start, film_len, speed, offset, seed=7):+ """A 10 s take whose mouth signal is S, and a song whose loudness+ envelope at film second t follows S at source second+ `src_true + (t - film_start) * speed` — so `src_true` is THE in-point+ that puts the picture on the song."""+ import numpy as np # noqa: PLC0415+ rng = np.random.default_rng(seed)+ S = np.convolve(rng.standard_normal(int(12 * self.VFPS)), np.ones(4) / 4, "same")+ S = 0.05 + (S - S.min())+ opens = {i: float(v) for i, v in enumerate(S[:int(10 * self.VFPS)])}+ T = np.arange(int(20 * self.SR)) / self.SR # track seconds+ u = src_true + (T - offset - film_start) * speed # source seconds+ idx = np.clip(np.floor(u * self.VFPS + 1e-6).astype(int), 0, len(S) - 1)+ env = np.where((T - offset >= film_start - 1) & (T - offset <= film_start + film_len + 1),+ S[idx], 0.05)+ song = (rng.standard_normal(len(T)) * env).astype(np.float32)+ return opens, song++ def _measure(self, opens, song, src_start, **kw):+ import mlx_ltx_panel as panel # noqa: PLC0415+ return panel._lipsync_align_measure(opens, self.VFPS, song, self.SR,+ src_start=src_start, **kw)++ def _roundtrip(self, *, placed, src_true, speed=1.0, offset=0.0,+ film_start=5.0, film_len=4.0):+ opens, song = self._world(src_true=src_true, film_start=film_start,+ film_len=film_len, speed=speed, offset=offset)+ kw = dict(film_start=film_start, film_end=film_start + film_len, speed=speed,+ song_offset=offset, play_start=0.0, play_end=None, fps=24.0)+ first = self._measure(opens, song, placed, **kw)+ self.assertIsNotNone(first)+ fixed = placed + first["delta_sec"]+ second = self._measure(opens, song, fixed, **kw)+ return first, fixed, second++ def test_a_trimmed_take_early_or_late_is_corrected_to_zero_residual(self):+ # A 10 s take trimmed to 4 s starting 3 s in (EDITOR-9's case) —+ # the picture 3 frames early, then 2 frames late.+ for placed, true in ((3.0, 3.0 - 3 / 24), (3.0, 3.0 + 2 / 24)):+ with self.subTest(placed=placed, true=true):+ first, fixed, second = self._roundtrip(placed=placed, src_true=true)+ self.assertNotEqual(first["lag_frames"], 0)+ self.assertAlmostEqual(fixed, true, places=3)+ self.assertEqual(second["lag_frames"], 0)++ def test_speed_and_a_moved_soundtrack_are_on_the_same_clock(self):+ first, fixed, second = self._roundtrip(placed=2.0, src_true=2.0 + 0.25,+ speed=2.0, offset=1.5)+ self.assertEqual(first["lag_frames"], -3)+ self.assertAlmostEqual(fixed, 2.25, places=3)+ self.assertEqual(second["lag_frames"], 0)++ def test_an_unmeasurable_window_is_none_not_zero(self):+ import numpy as np # noqa: PLC0415+ song = np.zeros(20 * self.SR, dtype=np.float32)+ self.assertIsNone(self._measure({}, song, 0.0, film_start=0.0, film_end=4.0))+ self.assertIsNone(self._measure({i: 0.3 for i in range(240)}, song, 0.0,+ film_start=0.0, film_end=4.0))++ def test_the_route_passes_the_window_and_reports_unmeasured_shots(self):+ from unittest import mock # noqa: PLC0415+ import mlx_ltx_panel as panel # noqa: PLC0415+ import test_editor_film_sync as fs # noqa: PLC0415+ case = fs.TheAutoAlignRoute("test_a_lagging_shot_is_proposed")+ case.setUp()+ try:+ edit = sedit.load_edit(case.root / "sb_t")+ edit["clips"][0].update(start=3.0, end=7.0, speed=1.0)+ sedit.save_edit(case.root / "sb_t", edit)+ with mock.patch.object(panel, "take_lipsync_best_lag_vs_song",+ return_value=None) as fn:+ h = case.FakeHandler()+ h.post("edit/auto-align", {"id": "sb_t"})+ kw = fn.call_args.kwargs+ self.assertEqual(kw["src_start"], 3.0)+ self.assertEqual(kw["speed"], 1.0)+ self.assertEqual(h.payload["proposals"], [])+ self.assertEqual([s["id"] for s in h.payload["skipped"]], ["c1"])+ self.assertEqual(h.payload["checked"], 0)+ finally:+ case.doCleanups()+ case.tmp.cleanup()+++class Editor9UnmeasuredIsNotInSync(unittest.TestCase):+ def test_the_toast_says_not_measured_never_already_matches(self):+ r = run(r"""+SBE.clips = lay([clip({ id: 'c1', end: 4 })]);+out.toasts = [];+for (const body of [{ ok: true, proposals: [], skipped: [{ id: 'c1' }], checked: 0 },+ { ok: true, proposals: [], skipped: [], checked: 0 },+ { ok: true, proposals: [], skipped: [], checked: 2 }]) {+ toasts.length = 0;+ NEXT = { status: 200, body: body };+ await sbeAutoAlign();+ out.toasts.push(toasts.slice());+}+""", extra=("sbeAutoAlign", "sbeAnalysisSnapshot", "sbeAnalysisFp", "sbeAnalysisFresh"))+ unmeasured, none, matched = r["toasts"]+ self.assertIn("could not be measured", unmeasured[0])+ self.assertNotIn("already", unmeasured[0])+ self.assertIn("no singing", none[0])+ self.assertIn("already matches", matched[0])+++# =============================================================================+# EDITOR-10 [P1] — Keep never names another tab's arrangement+# =============================================================================+class Editor10KeepDuringAConflict(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(r"""+function setUp(conflict, dirty) {+ SBE.clips = lay([clip({ id: 'a', end: 2 })]);+ SBE.edit = { clips: SBE.clips }; SBE.overlays = []; SBE.tracks = [];+ SBE.transitions = []; SBE.markers = [];+ SBE.conflict = conflict; SBE.dirty = dirty; SBE.dirtyAt = dirty ? 1 : 0;+ SBE.saving = false; SBE.savePending = false; SBE.revision = 1;+ sbeEl('sbeVersName').value = 'my cut';+ FETCHES = []; toasts.length = 0;+}+out.runs = {};+for (const [name, conflict, dirty] of [['revision_conflict', 2, true],+ ['conflict_clean', 2, false],+ ['dirty_no_conflict', 0, true]]) {+ setUp(conflict, dirty);+ NEXT = { status: 200, body: { ok: true, revision: 2, edit: { revision: 2, clips: [] } } };+ await sbeKeepVersion();+ out.runs[name] = { urls: FETCHES.map(f => f.url), toasts: toasts.slice() };+}+""", extra=("sbeKeepVersion",), stubs=("sbeNameMode",))["runs"]++ def test_a_conflicted_tab_is_refused_and_nothing_is_named(self):+ for name in ("revision_conflict", "conflict_clean"):+ with self.subTest(name):+ run_ = self.r[name]+ self.assertEqual(run_["urls"], [])+ self.assertTrue(any("Keep mine" in t for t in run_["toasts"]), run_)+ self.assertFalse(any(t.startswith("Kept") for t in run_["toasts"]))++ def test_without_a_conflict_it_saves_then_names(self):+ self.assertEqual(self.r["dirty_no_conflict"]["urls"],+ ["/storyboard/edit/save", "/storyboard/edit/version"])+++# =============================================================================+# EDITOR-11 [P1] — after Save, the browser plays the cut the server saved+# =============================================================================+class Editor11SaveAdoptsHealedTimings(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ sent = [_clip("a", "/x/a.mp4", 0.0, 0.98, 0.0), _clip("b", "/x/b.mp4", 1.0, 2.97, 0.98),+ _clip("c", "/x/c.mp4", 0.0, 1.49, 2.95)]+ with tempfile.TemporaryDirectory() as d:+ sedit.save_edit(d, _doc(json.loads(json.dumps(sent)), settings={"fps": 24}))+ cls.saved = sedit.load_edit(d)+ cls.r = run(r"""+const SENT = %s, SAVED = %s;+function film() {+ SBE.clips = lay(JSON.parse(JSON.stringify(SENT)).map(c => clip(c)));+ SBE.edit = { clips: SBE.clips, settings: { fps: 24 } };+ SBE.overlays = []; SBE.tracks = []; SBE.transitions = []; SBE.markers = [];+ SBE.dirty = true; SBE.dirtyAt = 1; SBE.conflict = 0; SBE.saving = false;+ SBE.savePending = false; SBE.revision = 1; SBE.sel = 'b';+ SBE.undo = ['u1']; SBE.redo = [];+}+film();+NEXT = { status: 200, body: { ok: true, edit: SAVED } };+await sbeSave(false);+out.after = SBE.clips.map(sbeCleanClip);+out.dirty = SBE.dirty; out.sel = SBE.sel; out.undo = SBE.undo.length;+// The next save sends exactly what is on disk.+out.next = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips }).edit.clips;+// An edit made while the save was on the wire is never overwritten.+film();+HOLD = true; FETCHES = [];+NEXT = { status: 200, body: { ok: true, edit: SAVED } };+const p = sbeSave(false);+await tick();+sbeMutate(cs => sbeTrim(cs, 'c', 'r', 4.0));+out.trimmedEnd = sbeById(SBE.clips, 'c').film_end;+await release();+HOLD = false;+await p;+out.afterRaceEnd = sbeById(SBE.clips, 'c').film_end;+out.afterRaceDirty = SBE.dirty;+""" % (json.dumps(sent), json.dumps(cls.saved)))++ def _shape(self, clips):+ return [(c["id"], round(c["start"], 6), round(c["end"], 6),+ round(c["film_start"], 6), round(c["film_end"], 6)) for c in clips]++ def test_the_healed_timings_are_what_the_browser_now_holds(self):+ # The fixture is one the heal really rewrites...+ self.assertNotEqual([c["film_end"] for c in self.saved["clips"]], [0.98, 2.95, 4.44])+ self.assertEqual(self._shape(self.r["after"]), self._shape(self.saved["clips"]))+ self.assertEqual(self._shape(self.r["next"]), self._shape(self.saved["clips"]))+ self.assertFalse(self.r["dirty"])+ self.assertEqual(self.r["sel"], "b")+ self.assertEqual(self.r["undo"], 1)++ def test_a_concurrent_edit_is_kept(self):+ self.assertEqual(self.r["afterRaceEnd"], self.r["trimmedEnd"])+ self.assertTrue(self.r["afterRaceDirty"])+++# =============================================================================+# EDITOR-12 [P1] — a finished render belongs to the film it rendered+# =============================================================================+RENDER_SHIM = r"""+const opened = [], revealed = [], lastToastEls = [];+function mkEl() {+ return { children: [], hidden: false, dataset: {}, innerHTML: '', textContent: '',+ appendChild(c) { this.children.push(c); }, remove() {} };+}+global.document = { createElement: () => mkEl() };+function phosToast(m, o) { toasts.push(String(m)); const e = mkEl(); lastToastEls.push(e); return e; }+async function sbeOpenFilmScreen(id, focus) { opened.push([id, focus]); }+async function sbeRevealRender(id, focus) { revealed.push([id, focus]); }+"""+++class Editor12RenderBelongsToItsFilm(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(r"""+SBE.id = 'film-A'; SBE.title = 'Film A';+els.sbeRenderBtn = Object.assign(stubEl('sbeRenderBtn'), { textContent: 'Render' });+els.sbeRenderChip = Object.assign(stubEl('sbeRenderChip', true),+ { appendChild() {} });+SBE.renderJob = 'j1'; SBE.rendering = true;+// A's render is running; the user opens film B before it lands.+SBE.id = 'film-B'; SBE.title = 'Film B';+NEXT = { status: 200, body: { ok: true, state: 'done',+ result: { ok: true, path: '/out/film-A_film.mp4', duration: 12 } } };+await sbeRenderPoll('j1', els.sbeRenderBtn, 'Render', 'film-A', 'Film A');+out.chipHiddenOnB = els.sbeRenderChip.hidden;+out.chipBoardOnB = els.sbeRenderChip.dataset.board || '';+out.toast = toasts[toasts.length - 1];+// The toast's two actions.+const t = lastToastEls[lastToastEls.length - 1];+for (const a of t.children) a.onclick({ preventDefault() {} });+out.opened = opened; out.revealed = revealed;+// Back on A, its chip is there; on B again, it is not.+sbeRenderChipFor('film-A');+out.chipOnA = [els.sbeRenderChip.hidden, els.sbeRenderChip.dataset.board];+sbeRenderChipFor('film-B');+out.chipOnBAgain = els.sbeRenderChip.hidden;+""", extra=("sbeRenderPoll", "sbeRenderSettle", "sbeRenderFinish", "sbePaintRenderChip",+ "sbeRenderChipFor"), shim=RENDER_SHIM)++ def test_the_open_film_does_not_get_the_other_films_chip(self):+ self.assertTrue(self.r["chipHiddenOnB"])+ self.assertEqual(self.r["chipBoardOnB"], "")+ self.assertIn("Film A", self.r["toast"])++ def test_open_and_show_in_finder_target_the_rendered_film(self):+ self.assertEqual(self.r["opened"], [["film-A", "film-A_film.mp4"]])+ self.assertEqual(self.r["revealed"], [["film-A", "film-A_film.mp4"]])++ def test_the_chip_follows_the_film(self):+ self.assertEqual(self.r["chipOnA"], [False, "film-A"])+ self.assertTrue(self.r["chipOnBAgain"])+++# =============================================================================+# EDITOR-13 [P1] — Match colour and Auto-align measure the arrangement on+# screen, and a proposal only lands on the clip it was measured on+# =============================================================================+class Editor13RoutesMeasureTheSentArrangement(unittest.TestCase):+ def _case(self, mod, cls, name):+ case = getattr(mod, cls)(name)+ case.setUp()+ self.addCleanup(case.doCleanups)+ self.addCleanup(case.tmp.cleanup)+ return case++ def test_match_colour_samples_the_replaced_clip_not_the_saved_one(self):+ from unittest import mock # noqa: PLC0415+ import mlx_ltx_panel as panel # noqa: PLC0415+ import test_editor_film_grade as fg # noqa: PLC0415+ case = self._case(fg, "TheMatchColourRoute", "test_no_ref_uses_the_films_median")+ live = json.loads(json.dumps(case.edit))+ new = case.root / "b_retake.mp4"+ new.write_bytes(b"x")+ live["clips"][1].update(path=str(new), start=2.0, end=6.0, duration=10.0)+ live["clips"].append(dict(live["clips"][2], id="d", film_start=12.0, film_end=16.0))+ seen = []++ def rgb(path, at):+ seen.append((Path(path).name, at))+ return (0.5, 0.5, 0.5)+ with mock.patch.object(panel, "take_frame_rgb", side_effect=rgb):+ h = case.FakeHandler()+ h.post("edit/match-colour", {"id": "sb_g", "edit": json.dumps(live)})+ self.assertEqual(h.status, 200, h.payload)+ self.assertIn(("b_retake.mp4", 4.0), seen)+ self.assertNotIn("b.mp4", [n for n, _ in seen])+ self.assertEqual(len(seen), 4) # the unsaved clip too++ def test_auto_align_measures_the_sent_window(self):+ from unittest import mock # noqa: PLC0415+ import mlx_ltx_panel as panel # noqa: PLC0415+ import test_editor_film_sync as fs # noqa: PLC0415+ case = self._case(fs, "TheAutoAlignRoute", "test_a_lagging_shot_is_proposed")+ live = json.loads(json.dumps(case.edit))+ live["clips"][0].update(start=1.5, end=5.5, duration=10.0)+ with mock.patch.object(panel, "take_lipsync_best_lag_vs_song",+ return_value=None) as fn:+ h = case.FakeHandler()+ h.post("edit/auto-align", {"id": "sb_t", "edit": json.dumps(live)})+ self.assertEqual(h.status, 200, h.payload)+ self.assertEqual(fn.call_args.kwargs["src_start"], 1.5)++ def test_an_arrangement_that_would_not_save_is_not_measured(self):+ import test_editor_film_grade as fg # noqa: PLC0415+ case = self._case(fg, "TheMatchColourRoute", "test_no_ref_uses_the_films_median")+ live = json.loads(json.dumps(case.edit))+ live["clips"][1]["end"] = 9.0 # window != slot+ h = case.FakeHandler()+ h.post("edit/match-colour", {"id": "sb_g", "edit": json.dumps(live)})+ self.assertEqual(h.status, 400)+ self.assertIn("problem", h.payload["error"])+++ANALYSIS_SHIM = r"""+let _sbeMatchProposals = [], _sbeMatchFp = {};+const toastEls = [];+function mkEl() {+ return { children: [], hidden: false, dataset: {}, className: '', classList: { add() {}, remove() {} },+ appendChild(c) { this.children.push(c); }, remove() {} };+}+global.document = { createElement: () => mkEl() };+function phosToast(m, o) { toasts.push(String(m)); const e = mkEl(); toastEls.push(e); return e; }+"""+++class Editor13ProposalsOnlyLandWhereMeasured(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(r"""+function film() {+ SBE.clips = lay([clip({ id: 'a', end: 4, duration: 10 }), clip({ id: 'b', end: 4, duration: 10 })]);+ SBE.edit = { clips: SBE.clips }; SBE.overlays = []; SBE.tracks = [];+ SBE.transitions = []; SBE.markers = []; SBE.undo = []; SBE.redo = [];+ SBE.open = true; SBE.id = 'sb_t';+}+// ---- Auto-align: the request carries the screen; a clip replaced after the+// measurement is not slipped by it.+film();+sbeMutate(cs => sbeReplaceClip(cs, 'a', { path: '/o/a2.mp4', duration_s: 10 })); // unsaved+sbeMutate(cs => sbeSlip(cs, 'a', 1.0)); // in-point 1 s+FETCHES = []; toasts.length = 0;+NEXT = { status: 200, body: { ok: true, checked: 2, skipped: [],+ proposals: [{ id: 'a', delta_sec: -0.125 }, { id: 'b', delta_sec: 0.25 }] } };+await sbeAutoAlign();+const sent = new URLSearchParams(FETCHES[0].body.toString());+out.sentPaths = JSON.parse(sent.get('edit')).clips.map(c => c.path);+// ...then b is trimmed before Accept.+sbeMutate(cs => sbeSlip(cs, 'b', 1.0));+const bStart = sbeById(SBE.clips, 'b').start;+const accept = toastEls[toastEls.length - 1].children[0];+accept.onclick({ preventDefault() {} });+out.aStart = sbeById(SBE.clips, 'a').start;+out.bStart = sbeById(SBE.clips, 'b').start;+out.bStartBefore = bStart;+out.acceptToast = toasts[toasts.length - 1];+// ---- Match colour: a clip replaced while the dialog is open is left alone.+film();+FETCHES = []; toasts.length = 0;+NEXT = { status: 200, body: { ok: true, reference: { r: .5, g: .5, b: .5 },+ proposals: [{ id: 'a', exposure: 0.2, temp: 0, tint: 0 },+ { id: 'b', exposure: 0.2, temp: 0, tint: 0 }] } };+els.sbeMatchModal = Object.assign(stubEl('sbeMatchModal'), { classList: { add() {}, remove() {} } });+els.sbeMatchStrength = Object.assign(stubEl('sbeMatchStrength'), { value: 100 });+await sbeMatchColourOpen();+out.mcSent = new URLSearchParams(FETCHES[0].body.toString()).has('edit');+sbeMutate(cs => sbeReplaceClip(cs, 'b', { path: '/o/b2.mp4', duration_s: 10 }));+sbeMatchApply();+out.aGrade = sbeGrade(sbeById(SBE.clips, 'a')).exposure;+out.bGrade = sbeGrade(sbeById(SBE.clips, 'b')).exposure;+out.mcToast = toasts[toasts.length - 1];+""", extra=("sbeAutoAlign", "sbeAnalysisSnapshot", "sbeAnalysisFp", "sbeAnalysisFresh",+ "sbeReplaceClip", "sbeSlip", "sbeMutateEach", "sbeMatchColourOpen",+ "sbeMatchApply", "sbeMatchClose", "sbeGrade", "sbeSetGrade"),+ stubs=("sbeNiceName", "sbeSelCount"), shim=ANALYSIS_SHIM)++ def test_the_request_carries_the_unsaved_replacement(self):+ self.assertEqual(self.r["sentPaths"], ["/o/a2.mp4", "/o/b.mp4"])+ self.assertTrue(self.r["mcSent"])++ def test_a_clip_changed_after_measuring_is_left_alone(self):+ self.assertAlmostEqual(self.r["aStart"], 0.875) # the measured clip is slipped+ self.assertEqual(self.r["bStart"], self.r["bStartBefore"])+ self.assertIn("changed after", self.r["acceptToast"])++ def test_match_colour_skips_the_replaced_clip(self):+ self.assertAlmostEqual(self.r["aGrade"], 0.2)+ self.assertAlmostEqual(self.r["bGrade"], 0.0)+ self.assertIn("changed after", self.r["mcToast"])+++# =============================================================================+# EDITOR-14 [P1] — Film Look reaches the After Effects export+# =============================================================================+class Editor14FilmLookReachesAfterEffects(unittest.TestCase):+ def _export(self, look):+ from unittest import mock # noqa: PLC0415+ c = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, adjust={"saturation": 1.2})+ probe = lambda p: {"w": 768, "h": 416, "duration": 10.0, "has_audio": True}+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(sedit.Path, "is_file", return_value=True), \+ mock.patch.object(sedit, "_link_or_copy", return_value="link"):+ res = sedit.export_nle([c], d, name="m", probe=probe, film_look=look)+ return Path(res["jsx"]).read_text()++ def test_warm_tungsten_changes_the_ae_saturation_the_render_uses(self):+ off, on = self._export(None), self._export("warm_tungsten")+ self.assertIn("satur(lay, 20.0);", off) # the clip's own 1.2+ self.assertIn("satur(lay, 30.0);", on) # + the look's 1.1+ # ...and the stacked grade is the one the render plan draws.+ seg = sedit._nle_segments([_clip("a", "/x/a.mp4", 0.0, 4.0, 0.0)],+ film_look="warm_tungsten")[0]+ self.assertEqual((seg["fx"]["saturation"], seg["fx"]["temp"], seg["fx"]["tint"]),+ (1.1, 0.3, -0.05))++ def test_a_slug_gets_no_look(self):+ slug = dict(_clip("s", "", 0.0, 2.0, 0.0), kind="slug")+ seg = sedit._nle_segments([slug], film_look="warm_tungsten")+ self.assertEqual(len(seg), 1)+ self.assertEqual(seg[0]["fx"]["saturation"], 1.0)+++class Editor14TheRoutePassesTheLook(_RenderSandbox):+ def test_export_nle_route_sends_settings_film_look(self):+ from unittest import mock # noqa: PLC0415+ edit = sedit.load_edit(self.bdir)+ edit["settings"] = {"film_look": "warm_tungsten"}+ sedit.save_edit(self.bdir, edit)+ fake = {"ok": True, "dir": "/x/p", "clips": 1, "linked": 1, "copied": 0,+ "missing": []}+ with mock.patch.object(sedit, "export_nle", return_value=fake) as fn:+ h = self._post("edit/export-nle", {"id": "sb_t"})+ self.assertEqual(h.status, 200, h.payload)+ self.assertEqual(fn.call_args.kwargs.get("film_look"), "warm_tungsten")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_codex_4170_est.py b/test_codex_4170_est.pynew file mode 100644index 0000000..1f62fbd--- /dev/null+++ b/test_codex_4170_est.py@@ -0,0 +1,532 @@+#!/usr/bin/env python3+"""4.17.0 Codex review — the estimates + sizes area (findings_est.md). Every+real finding fixed gets its pin here; JS is executed in node where it is+behaviour. Findings: ~/AI/projects/phosphene/review-2026-09-29-ux/codex/+findings_est.md.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as p # noqa: E402+from extract_panel_js import extract_function # noqa: E402++routes_queue = sys.modules["panel.routes_queue"]+NODE = shutil.which("node")+JS = ROOT / "webapp" / "js"+++def _node(script: str):+ if NODE is None:+ pytest.skip("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ assert r.returncode == 0, r.stderr[-3000:]+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class _H:+ def __init__(self):+ self.status, self.payload = None, None++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++class _Parsed:+ def __init__(self, query: str):+ self.query = query+++def calib(tmp_path, monkeypatch):+ path = tmp_path / "eta_calibration.json"+ monkeypatch.setattr(p, "_eta_calibration_path", lambda: path)+ monkeypatch.delenv("PHOSPHENE_SPEED_FACTOR", raising=False)+ monkeypatch.setattr(p, "_ETA_CAL_PRICED", {"h3": 1.0, "ltx": 1.0})+ return path+++def _ltx_job(minutes, **params):+ base = {"engine": "ltx", "mode": "t2v", "quality": "balanced",+ "frames": p.LTX_TIERS["balanced_5s"]["frames"],+ "width": p.LTX_TIERS["balanced_5s"]["width"],+ "height": p.LTX_TIERS["balanced_5s"]["height"]}+ base.update(params)+ return {"status": "done", "elapsed_sec": minutes * 60.0, "params": base}+++# ---- EST-2: calibration prices the LTX recipe that actually ran -------------+def test_est_2_ltx_fast_draft_and_default_each_calibrate_against_their_own_price(calib):+ cell = p.LTX_TIERS["balanced_5s"]+ if cell.get("fast_min") is None:+ pytest.skip("this registry has no Fast draft schedule")+ p._record_eta_calibration_from_job(_ltx_job(cell["fast_min"], schedule_preset="fast"))+ p._record_eta_calibration_from_job(_ltx_job(cell["eta_min"]))+ assert json.loads(calib.read_text())["ltx"] == [1.0, 1.0]+++def test_est_2_other_recipes_do_not_contaminate_t2v_calibration(calib):+ slow = p.LTX_TIERS["balanced_5s"]["eta_min"] * 3+ for extra in ({"mode": "a2v"}, {"mode": "extend"}, {"mode": "keyframe"},+ {"mode": "retake"}, {"width": 768, "height": 768}, # a 1:1 canvas+ {"long_mode": "windows"}, {"temporal_mode": "fps12_interp24"},+ {"upscale": "x2"}):+ p._record_eta_calibration_from_job(_ltx_job(slow, **extra))+ assert not calib.exists()+ # Portrait is the cell's own canvas turned — same pixels, same price.+ w, h = p.LTX_TIERS["balanced_5s"]["width"], p.LTX_TIERS["balanced_5s"]["height"]+ p._record_eta_calibration_from_job(_ltx_job(p.LTX_TIERS["balanced_5s"]["eta_min"],+ width=h, height=w))+ assert json.loads(calib.read_text())["ltx"] == [1.0]+++# ---- EST-5: a queued job's ETA is the price of its own recipe ---------------+def test_est_5_queue_eta_prices_h3_fast_and_turbo_by_their_own_numbers():+ key, cell = next((k, c) for k, c in p.H3_TIERS.items() if c.get("tristep_min") is not None)+ base = {"engine": "h3", "mode": "t2v", "h3_tier": key}+ assert p.job_priced_eta_sec(base) == pytest.approx(cell["eta_min"] * 60)+ assert p.job_priced_eta_sec({**base, "h3_tristep": True}) == pytest.approx(cell["tristep_min"] * 60)+ assert p.job_priced_eta_sec({**base, "h3_turbo": True}) == pytest.approx(cell["turbo_min"] * 60)+ if cell.get("tristep_min_i2v") is not None:+ assert p.job_priced_eta_sec({**base, "mode": "i2v", "h3_tristep": True}) == \+ pytest.approx(cell["tristep_min_i2v"] * 60)+ win = max(1, cell["chain_windows"])+ pinned = (win * 11 * cell["per_forward_sec"] + win * cell["fixed_sec"])+ assert p.job_priced_eta_sec({**base, "h3_steps": 12}) == pytest.approx(pinned)+++def test_est_5_queue_eta_prices_ltx_schedule_and_modes_like_their_pre_submit_price():+ cell = p.LTX_TIERS["balanced_5s"]+ t2v = {"engine": "ltx", "mode": "t2v", "quality": "balanced", "frames": cell["frames"],+ "width": cell["width"], "height": cell["height"]}+ assert p.job_priced_eta_sec(t2v) == pytest.approx(cell["eta_min"] * 60)+ if cell.get("fast_min") is not None:+ assert p.job_priced_eta_sec({**t2v, "schedule_preset": "fast"}) == \+ pytest.approx(cell["fast_min"] * 60)+ got = {}+ if p.SYSTEM_CAPS.get("allows_extend"):+ card = p.ltx_mode_price_card("extend", steps=30, extend_frames=12)+ got["extend"] = p.job_priced_eta_sec({**t2v, "mode": "extend",+ "extend_steps": 30, "extend_frames": 12})+ assert got["extend"] == pytest.approx(card["eta_min"] * 60)+ if p.SYSTEM_CAPS.get("allows_keyframe"):+ card = p.ltx_mode_price_card("keyframe", frames=241, width=cell["width"],+ height=cell["height"])+ got["keyframe"] = p.job_priced_eta_sec({**t2v, "mode": "keyframe", "frames": 241})+ assert got["keyframe"] == pytest.approx(card["eta_min"] * 60)+ a2v = p.ltx_a2v_price(cell["frames"], cell["width"], cell["height"])+ got["a2v"] = p.job_priced_eta_sec({**t2v, "mode": "a2v"})+ assert got["a2v"] == pytest.approx(a2v["minutes"] * 60)+ # None of them is the default T2V cell's price any more.+ assert all(abs(v - cell["eta_min"] * 60) > 1 for v in got.values())+++def test_est_5_a2v_route_and_queue_share_one_price():+ h = _H()+ routes_queue.get_a2v_estimate(h, _Parsed("frames=121&width=1024&height=576"))+ assert h.payload["ok"] is True+ assert h.payload["minutes"] == p.ltx_a2v_price(121, 1024, 576)["minutes"]+++# ---- EST-7: Keyframe is priced for the duration and canvas asked for -------+def keyframe_on(monkeypatch):+ monkeypatch.setitem(p.SYSTEM_CAPS, "allows_keyframe", True)+++def test_est_7_keyframe_card_follows_frames_and_canvas(keyframe_on):+ five = p.ltx_mode_price_card("keyframe")+ ten = p.ltx_mode_price_card("keyframe", frames=241)+ assert five["frames"] == 121 and ten["frames"] == 241+ assert ten["eta_min"] > five["eta_min"]+ wide = p.ltx_mode_price_card("keyframe", width=640, height=448)+ assert (wide["width"], wide["height"]) == p.ltx_keyframe_estimate_minutes(121, 640, 448)[:2]+ assert wide["eta_min"] < five["eta_min"]+ h = _H()+ routes_queue.get_keyframe_estimate(h, _Parsed("frames=241&width=1024&height=576"))+ assert h.payload["ok"] and h.payload["eta_min"] == \+ p.ltx_mode_price_card("keyframe", frames=241, width=1024, height=576)["eta_min"]+++def test_est_7_footer_and_summary_reprice_when_the_duration_changes():+ q = (JS / "queue.js").read_text(encoding="utf-8")+ c = (JS / "characters.js").read_text(encoding="utf-8")+ fns = "\n".join([extract_function("keyframePriceFor", q),+ extract_function("updateDerivedForClampedMode", q),+ extract_function("updateShotSetupSummary", c)])+ out = _node("""+const _kfPriceCache = {}; let _kfPriceSeq = 0; let _kfPriceTimer = null;+const els = {};+const el = (id, v) => (els[id] = els[id] || { id, value: v, innerHTML: '', textContent: '' });+el('mode', 'keyframe'); el('frames', '121'); el('width', '1024'); el('height', '576');+el('derivedFooter'); el('qualityMeta'); el('shotSetupSummary'); el('seed', '-1');+global.document = { getElementById: id => els[id] || null, body: { dataset: { engine: 'ltx' } } };+global.escapeHtml = s => String(s);+let currentMode = 'keyframe';+const BOOT = { tier: { keyframe_price: { width: 768, height: 448, frames: 121,+ eta: '~8–10 min', pipeline_note: 'Q8 two-stage' } } };+const asked = [];+global.fetch = async (url) => { asked.push(url);+ const f = /frames=(\\d+)/.exec(url)[1];+ return { json: async () => ({ ok: true, width: 768, height: 448, frames: +f,+ eta: f === '241' ? '~17–21 min' : '~8–10 min', pipeline_note: 'Q8 two-stage' }) }; };+""" + fns + """+const wait = () => new Promise(r => setTimeout(r, 220));+(async () => {+ const res = {};+ updateDerivedForClampedMode('keyframe'); await wait();+ res.five = [els.derivedFooter.innerHTML, els.shotSetupSummary.textContent];+ els.frames.value = '241';+ updateDerivedForClampedMode('keyframe');+ res.pending = els.derivedFooter.innerHTML;+ await wait();+ res.ten = [els.derivedFooter.innerHTML, els.shotSetupSummary.textContent];+ res.asked = asked;+ console.log(JSON.stringify(res));+})();+""")+ assert "~8–10 min" in out["five"][0] and "~8–10 min" in out["five"][1]+ assert "pricing" in out["pending"] and "~8–10" not in out["pending"]+ assert "~17–21 min" in out["ten"][0] and "~17–21 min" in out["ten"][1]+ assert any("frames=241" in u for u in out["asked"])+++# ---- EST-3: fleet ranges calibrate against the fleet, not the cost model ----+def _fleet_table(wall_sec=None):+ t = {"schema": "fleet_timings/1", "levels": {"cell": {"cells": {+ "ltx|t2v|balanced|121.0|M4 Max|64.0|any":+ {"p25_sec": 220.0, "p50_sec": 244.0, "p75_sec": 270.0, "n": 50},+ "h3|t2v|standard_5s|124.0|M4 Max|64.0|best":+ {"p25_sec": 600.0, "p50_sec": 600.0, "p75_sec": 600.0, "n": 7},+ }}}}+ if wall_sec:+ t["wall_sec"] = wall_sec+ return t+++def test_est_3_renders_matching_the_fleet_leave_the_fleet_range_alone(calib, monkeypatch):+ monkeypatch.setattr(p, "FLEET_TIMINGS", _fleet_table("seconds"))+ monkeypatch.setattr(p, "_hw_chip_family", lambda: "M4 Max")+ monkeypatch.setattr(p, "SYSTEM_RAM_GB", 64.0)+ cell = p.LTX_TIERS["balanced_5s"]+ fleet_p50 = 244.0 / 60.0+ # Local renders take exactly the fleet median, i.e. 1.5x the model.+ monkeypatch.setitem(cell, "eta_min", round(fleet_p50 / 1.5, 4))+ for _ in range(3):+ p._record_eta_calibration_from_job(_ltx_job(fleet_p50))+ assert p._eta_calibration_factor("ltx") == pytest.approx(1.5, abs=0.01) # model learns+ r = p.fleet_calibrated_range("ltx", "t2v", "balanced", 121)+ assert r["p50_min"] == pytest.approx(fleet_p50, abs=0.01) # fleet stays+++def test_est_3_a_mac_slower_than_its_fleet_moves_only_the_fleet_factor(calib, monkeypatch):+ monkeypatch.setattr(p, "FLEET_TIMINGS", _fleet_table("seconds"))+ monkeypatch.setattr(p, "_hw_chip_family", lambda: "M4 Max")+ monkeypatch.setattr(p, "SYSTEM_RAM_GB", 64.0)+ fleet_p50 = 244.0 / 60.0+ monkeypatch.setitem(p.LTX_TIERS["balanced_5s"], "eta_min", round(fleet_p50 * 2, 4))+ for _ in range(2):+ p._record_eta_calibration_from_job(_ltx_job(fleet_p50 * 2))+ assert p._eta_calibration_factor("ltx") == pytest.approx(1.0, abs=0.01)+ r = p.fleet_calibrated_range("ltx", "t2v", "balanced", 121)+ assert r["p50_min"] == pytest.approx(fleet_p50 * 2, abs=0.02)+ assert "adjusted for this Mac's own renders" in r["basis"]+++# ---- EST-4: a fleet cell keeps its timing bucket's width --------------------+def test_est_4_one_bucket_cell_reads_as_that_bucket_not_its_lower_edge(monkeypatch):+ monkeypatch.setattr(p, "FLEET_TIMINGS", _fleet_table()) # as built: lower edges+ r = p.fleet_estimate_range("h3", "t2v", "standard_5s", 124, chip="M4 Max",+ ram=64.0, speed="best")+ assert (r["p25_min"], r["p50_min"], r["p75_min"]) == (10.0, 12.5, 15.0)+ assert p._fmt_eta_range(r["p25_min"], r["p75_min"]) == "~10–15 min"+ # A render just under the rung's top reports the rung's lower edge ...+ assert p._analytics_wall_sec_bucket(1199) == 900+ # ... and the displayed range still contains it.+ lo, hi = p._wall_bucket_bounds(900)+ assert lo <= 1199 / 1.0 and 1199 <= hi == 1200+++def test_est_4_the_reader_and_the_sender_share_one_ladder():+ assert p._ANALYTICS_WALL_LADDER is p.FLEET_WALL_SEC_LADDER+ build = (ROOT / "scripts" / "fleet_timings_build.py").read_text(encoding="utf-8")+ assert '"wall_sec": "bucket_lower_edge"' in build+ shipped = json.loads((ROOT / "data" / "fleet_timings.json").read_text(encoding="utf-8"))+ assert shipped.get("wall_sec", "bucket_lower_edge") == "bucket_lower_edge"+++# ---- EST-6: film time left counts the current shot and survives mixed queues -+def _film_time_left(*, current, queue, per_shot, shots):+ sb_js = (JS / "storyboard.js").read_text(encoding="utf-8")+ fns = "\n".join(extract_function(n, sb_js) for n in ("sbFmtWall", "_sbTagOf", "sbRenderRunBar"))+ return _node(f"""+globalThis.SB = {{ id: 'film1' }};+const _els = {{}};+function el(id) {{ return _els[id] || (_els[id] = {{ id, textContent: '', innerHTML: '', hidden: true }}); }}+const document = {{ getElementById: el }};+function sbEl(id) {{ return el(id); }}+function snippet(s, n) {{ return String(s || '').slice(0, n); }}+function escapeHtml(s) {{ return String(s || ''); }}+{fns}+const queue = {json.dumps(queue)};+const LAST_STATUS = {{ current: {json.dumps(current)}, queue, paused: false,+ eta_sec: queue.reduce((a, j) => a + (j.eta_sec || 0), 0) }};+sbRenderRunBar({{ rendering: true, pass: 'draft', board: {{ shots: {json.dumps(shots)} }},+ per_shot_est: {json.dumps(per_shot)} }});+console.log(JSON.stringify({{ sub: el('sbRunSub').textContent, want: sbFmtWall(1500) }}));+""")+++def _tag(n, eta=None, board="film1"):+ j = {"params": {"session_tag": f"sb:{board}#{n}"}}+ if eta is not None:+ j["eta_sec"] = eta+ return j+++def test_est_6_the_current_shot_counts_toward_the_film_time_left():+ shots = [{"n": 1, "draft_output": None, "status": "rendering"},+ {"n": 2, "draft_output": None, "status": "pending"}]+ cur = {**_tag(1), "progress": {"remaining_sec": 1200}}+ out = _film_time_left(current=cur, queue=[], per_shot={"1": 1500, "2": 300}, shots=shots)+ assert out["sub"].endswith(f"{out['want']} left") # 20 min + 5 min+++def test_est_6_an_unrelated_queued_job_does_not_erase_the_films_queued_work():+ shots = [{"n": 1, "draft_output": "a.mp4", "status": "done"},+ {"n": 2, "draft_output": None, "status": "pending"},+ {"n": 3, "draft_output": None, "status": "pending"}]+ film_only = [_tag(2, 1200), _tag(3, 300)]+ mixed = film_only + [_tag(9, 4000, board="other")]+ a = _film_time_left(current=None, queue=film_only, per_shot={"2": 1200, "3": 300}, shots=shots)+ b = _film_time_left(current=None, queue=mixed, per_shot={"2": 1200, "3": 300}, shots=shots)+ assert a["sub"] == b["sub"] and a["sub"].endswith(f"{a['want']} left")+++# ---- EST-8: moving the crop never opens the file chooser -------------------+def test_est_8_crop_clicks_do_not_browse_but_the_tile_still_does():+ fn = extract_function("pickerWire", (JS / "queue.js").read_text(encoding="utf-8"))+ out = _node(fn + """+const handlers = {};+const mk = (name) => ({ name, addEventListener(t, f) { (handlers[name + ':' + t] = f); } });+let browsed = 0;+const els = { drop: mk('drop'), file: { ...mk('file'), click() { browsed++; } },+ clear: mk('clear'), preview: mk('preview') };+function pickerEls() { return els; }+function _pickerCropSupported() { return true; }+function pickerUploadFile() {}+function _renderCropOverlay() {}+pickerWire('image');+// A target inside `sel` (and every ancestor selector it belongs to).+const target = (...inside) => ({ closest: s => s.split(',').some(x => inside.includes(x.trim())) ? {} : null });+const res = {};+for (const [name, t] of [['overlay', target('.crop-overlay')],+ ['window', target('.crop-overlay')],+ ['quick', target('.crop-overlay-controls')],+ ['clear', target('.picker-clear')],+ ['tile', target()]]) {+ browsed = 0; handlers['drop:click']({ target: t }); res[name] = browsed;+}+console.log(JSON.stringify(res));+""")+ assert out == {"overlay": 0, "window": 0, "quick": 0, "clear": 0, "tile": 1}+++# ---- EST-9: the sidecar keeps the ORIGINAL reference, the engine the crop ---+class _Helper:+ ready_info: dict = {}++ def __init__(self):+ self.sent: list[dict] = []++ def is_alive(self):+ return True++ def kill(self, *a, **k):+ pass++ def run(self, spec, *a, **k):+ self.sent.append(spec)+ out = (spec.get("params") or {}).get("output_path")+ if out:+ Path(out).write_bytes(b"x")+ return {"seed_used": 1, "elapsed_sec": 0.1}+++def _fake_ffmpeg(cmd, *a, **k):+ Path(cmd[-1]).write_bytes(b"enc")+ return "", ""++[email protected]("mode", ["i2v", "a2v"])+def test_est_9_load_params_reopens_the_original_upload_not_the_crop(tmp_path, mode):+ from unittest import mock+ from PIL import Image+ portrait = tmp_path / "portrait.png"+ Image.new("RGB", (360, 640), (200, 30, 30)).save(portrait)+ wav = tmp_path / "song.wav"+ wav.write_bytes(b"RIFF0000WAVE")+ form = {"mode": mode, "prompt": "a singer", "image": str(portrait), "quality": "balanced",+ "width": "1024", "height": "576", "frames": "49", "image_crop_focus": "0.2"}+ if mode == "a2v":+ form["audio"] = str(wav)+ helper, sidecars = _Helper(), []+ job = p.make_job(form)+ job["started_ts"] = __import__("time").time()+ with mock.patch.object(p, "HELPER", helper), \+ mock.patch.object(p, "OUTPUT", tmp_path), \+ mock.patch.object(p, "SYSTEM_TIER", "pro"), \+ mock.patch.object(p, "SYSTEM_CAPS", p.CAPABILITIES["pro"]), \+ mock.patch.object(p, "GENERATION_PROFILE", p._select_generation_profile(128.0, "pro")), \+ mock.patch.object(p, "ltx_pack_preflight", lambda *a, **k: None), \+ mock.patch.object(p, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(p, "run_ffmpeg_tracked", _fake_ffmpeg), \+ mock.patch.object(p, "set_hidden", lambda *a, **k: None), \+ mock.patch.object(p, "write_sidecar", lambda _p, data: sidecars.append(data) or True):+ p.run_job_inner(job)+ engine_image = helper.sent[0]["params"]["image"]+ assert engine_image and Path(engine_image) != portrait # the crop rendered+ with Image.open(engine_image) as im:+ assert im.size[0] > im.size[1] # landscape canvas+ assert sidecars[-1]["params"]["image"] == str(portrait) # the pick is kept+ assert job["params"]["image"] == str(portrait)+ assert sidecars[-1]["params"]["image_crop_focus"] in ("0.2", 0.2)+++# ---- EST-10: an Extend's Face Fix follow-up never disappears silently -------+class _FormH(_H):+ def __init__(self, form):+ super().__init__()+ self._form = form++ def _read_form_body(self):+ return b"", self._form+++def test_est_10_extend_asking_for_face_fix_without_the_adapter_is_refused_up_front(monkeypatch, tmp_path):+ monkeypatch.setattr(p, "face_fix_adapter_ready", lambda: False)+ src = tmp_path / "src.mp4"+ src.write_bytes(b"x")+ form = {"mode": ["extend"], "prompt": ["more"], "video_path": [str(src)],+ "extend_face_fix_after": ["1"]}+ before = list(p.STATE["queue"])+ h = _FormH(form)+ routes_queue.post_run(h, "/queue/add", {}, "")+ assert h.status == 400 and h.payload["code"] == "pack_missing"+ assert "Settings → Models" in h.payload["error"]+ assert p.STATE["queue"] == before+ # Without the follow-up the same Extend is accepted.+ form.pop("extend_face_fix_after")+ h = _FormH(form)+ monkeypatch.setattr(p, "persist_queue", lambda: None)+ routes_queue.post_run(h, "/queue/add", {}, "")+ try:+ assert h.status == 200 and h.payload["ok"]+ finally:+ with p.QUEUE_COND:+ p.STATE["queue"][:] = before+++def test_est_10_a_follow_up_that_cannot_queue_stays_on_the_finished_job(monkeypatch):+ monkeypatch.setattr(p, "queue_face_fix", lambda path: {+ "ok": False, "code": "hardware_tier", "error": "clip.mp4 is already 1280×704."})+ job = {"status": "done", "output_path": "/x/clip.mp4",+ "params": {"mode": "extend", "extend_face_fix_after": True}}+ p._queue_extend_face_fix_after(job)+ assert "was not queued" in job["warning"] and "1280×704" in job["warning"]+ js = (JS / "queue.js").read_text(encoding="utf-8")+ assert "(j.warning || '')" in js # the history row repaints for it+++def test_est_10_the_submit_shows_the_servers_refusal_not_offline():+ fn = extract_function("api", (JS / "queue.js").read_text(encoding="utf-8"))+ out = _node(fn + """+global.fetch = async () => ({ ok: false, status: 400,+ json: async () => ({ error: 'needs the adapter', code: 'pack_missing' }) });+(async () => {+ try { await api('/queue/add', 'POST', null); }+ catch (e) { console.log(JSON.stringify({ msg: e.message, code: e.code, status: e.status })); }+})();+""")+ assert out == {"msg": "needs the adapter", "code": "pack_missing", "status": 400}+ js = (JS / "queue.js").read_text(encoding="utf-8")+ sub = js[js.index("document.getElementById('genForm').addEventListener('submit'"):]+ sub = sub[:sub.index("\n});\n")]+ assert "e.code === 'pack_missing'" in sub and "openModelsModal()" in sub+++# ---- EST-11: every orientation preset survives normalization and the clamp --[email protected]("tier,ram", [("pro", 128.0), ("high", 96.0), ("standard", 48.0), ("base", 16.0)])+def test_est_11_social_presets_keep_their_exact_ratio_on_every_tier(monkeypatch, tier, ram):+ from unittest import mock+ caps = p.CAPABILITIES[tier]+ profile = p._select_generation_profile(ram, tier)+ with mock.patch.object(p, "SYSTEM_TIER", tier), \+ mock.patch.object(p, "SYSTEM_CAPS", caps), \+ mock.patch.object(p, "GENERATION_PROFILE", profile):+ presets = p.aspect_presets_for_this_mac()+ for key, (rw, rh) in (("square", (1, 1)), ("portrait_4_5", (4, 5))):+ a = presets[key]+ assert a["w"] * rh == a["h"] * rw, (tier, key, a)+ assert f"{a['w']}×{a['h']}" in a["label"]+ job = p.make_job({"mode": "t2v", "prompt": "x", "quality": "balanced",+ "width": str(a["w"]), "height": str(a["h"]), "frames": "121"})+ got = (job["params"]["width"], job["params"]["height"])+ assert got == (a["w"], a["h"]), (tier, key, got) # make_job's /64 floor+ p._apply_generation_profile_to_job(job) # the profile clamp+ got = (job["params"]["width"], job["params"]["height"])+ cap = int(caps.get("t2v_max_dim") or 0) # run_job_inner's clamp+ if cap and max(got) > cap:+ got = p.ltx_fit_canvas(*got, cap)+ assert got == (a["w"], a["h"]), (tier, key, got)+++# ---- EST-13: a clamped canvas never claims another canvas's measurement -----+def _tiers_on(monkeypatch, tier):+ from unittest import mock+ monkeypatch.setenv("PHOSPHENE_SPEED_FACTOR", "1.0") # neutral speed+ with mock.patch.object(p, "SYSTEM_CAPS", p.CAPABILITIES[tier]):+ quals = p._ltx_qualities()+ with mock.patch.object(p, "LTX_QUALITIES", quals), \+ mock.patch.object(p, "FLEET_TIMINGS", {}):+ return quals, p._build_ltx_tiers()+++def test_est_13_compact_equal_recipes_get_equal_unmeasured_prices(monkeypatch):+ quals, tiers = _tiers_on(monkeypatch, "base")+ bal, std = tiers["balanced_5s"], tiers["standard_5s"]+ if (bal["width"], bal["height"]) != (std["width"], std["height"]):+ pytest.skip("this registry clamps Balanced and Standard to different canvases")+ assert (bal["width"], bal["height"]) != (quals["balanced"]["native_width"],+ quals["balanced"]["native_height"])+ assert bal["eta_measured"] is False and std["eta_measured"] is False+ assert bal["eta_min"] == pytest.approx(std["eta_min"])+ for key, cell in tiers.items(): # every measured hit+ if cell["eta_measured"]:+ q = quals[cell["quality"]]+ assert (cell["width"], cell["height"]) == (q["native_width"], q["native_height"]), key+++def test_est_13_uncapped_macs_keep_every_measured_row(monkeypatch):+ _, tiers = _tiers_on(monkeypatch, "pro")+ assert tiers["balanced_5s"]["eta_measured"] is True+ assert tiers["standard_5s"]["eta_measured"] is True+ assert tiers["balanced_5s"]["eta_min"] == pytest.approx(+ p.LTX_MEASURED_ETA[(p.ACTIVE_MODEL_VERSION, "balanced", "5s", "q4")][0])diff --git a/test_codex_4170_lipsync.py b/test_codex_4170_lipsync.pynew file mode 100644index 0000000..08f19e3--- /dev/null+++ b/test_codex_4170_lipsync.py@@ -0,0 +1,501 @@+#!/usr/bin/env python3+"""4.17.0 Codex review — lipsync area (a2v lip-sync, Continue the song, Split+into clips, segment Retake, Windows plan, Load Params for a2v / One Shot).+Findings: ~/AI/projects/phosphene/review-2026-09-29-ux/codex/findings_lipsync.md.+JS is executed in node where the behaviour is a function's.+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path+from unittest import mock++import pytest++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as p # noqa: E402,F401+from extract_panel_js import extract_function # noqa: E402++routes_queue = sys.modules["panel.routes_queue"]+NODE = shutil.which("node")+JS = ROOT / "webapp" / "js"+++def _node(script: str):+ if NODE is None:+ pytest.skip("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ assert r.returncode == 0, r.stderr[-3000:]+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class _H:+ def __init__(self, form=None):+ self.status, self.payload, self._form = None, None, form or {}++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status++ def _read_form_body(self):+ return b"", self._form+++# ---- LIPSYNC-1: lip-sync helpers stay inside outputs/uploads/state ----------+def _roots(tmp_path):+ P = routes_queue.P+ out, up, st, priv = (tmp_path / n for n in ("out", "up", "state", "private"))+ for d in (out, up, st, priv):+ d.mkdir()+ with mock.patch.object(P, "OUTPUT", out), mock.patch.object(P, "UPLOADS", up), \+ mock.patch.object(P, "STATE_DIR", st):+ yield P, out, up, priv+++def test_lipsync_1_continue_song_refuses_media_outside_the_roots(_roots):+ P, out, up, priv = _roots+ secret = priv / "private.mp4"+ secret.write_bytes(b"x")+ link = out / "escape.mp4"+ link.symlink_to(secret)+ calls = []+ with mock.patch.object(P, "find_closed_mouth_frame",+ side_effect=lambda s: calls.append(("find", s)) or+ {"time_s": 4.8, "openness": 0.01}), \+ mock.patch.object(P, "extract_frame_png",+ side_effect=lambda s, t, d: calls.append(("extract", s)) or True):+ for raw in (str(secret), str(link), str(out / ".." / "private" / "private.mp4")):+ h = _H({"clip": [raw]})+ routes_queue.post_a2v_continue_song(h, "/a2v/continue_song", {}, "")+ assert h.status == 403, (raw, h.status, h.payload)+ assert calls == []+ # A real output clip still works, and its sidecar offset is read.+ clip = out / "a2v_1.mp4"+ clip.write_bytes(b"x")+ (out / "a2v_1.mp4.json").write_text(json.dumps({"params": {"audio_start_time": 10.0}}))+ h = _H({"clip": [str(clip)]})+ routes_queue.post_a2v_continue_song(h, "/a2v/continue_song", {}, "")+ assert h.status == 200 and h.payload["ok"], h.payload+ assert h.payload["audio_start_time"] == 14.8+ assert [c[0] for c in calls] == ["find", "extract"]+++def test_lipsync_1_mouth_check_refuses_media_outside_the_roots(_roots):+ P, out, up, priv = _roots+ secret = priv / "face.png"+ secret.write_bytes(b"x")+ (up / "link.png").symlink_to(secret)+ seen = []+ with mock.patch.object(P, "mouth_open_ratio", side_effect=lambda i: seen.append(i) or 0.1):+ for raw in (str(secret), str(up / "link.png")):+ h = _H({"image": [raw]})+ routes_queue.post_a2v_mouth_check(h, "/a2v/mouth_check", {}, "")+ assert h.status == 403, (raw, h.payload)+ assert seen == []+ ok = up / "face.png"+ ok.write_bytes(b"x")+ h = _H({"image": [str(ok)]})+ routes_queue.post_a2v_mouth_check(h, "/a2v/mouth_check", {}, "")+ assert h.status == 200 and h.payload["measured"] is True+ assert seen == [str(ok.resolve())]+++# ---- LIPSYNC-3 / 5 / 11: segment Retake -------------------------------------+import ast # noqa: E402+import math # noqa: E402++HELPER_SRC = (ROOT / "mlx_warm_helper.py").read_text(encoding="utf-8")+++def _helper_fns(*names, extra=None):+ tree = ast.parse(HELPER_SRC)+ defs = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names]+ assert sorted(d.name for d in defs) == sorted(names), names+ ns: dict = {"math": math, **(extra or {})}+ exec(compile(ast.Module(body=defs, type_ignores=[]), "mlx_warm_helper.py", "exec"), ns)+ return ns+++def _engine_latent_count(pixel_frames: int) -> int:+ # compute_video_latent_shape() in the pinned ltx-core-mlx (patchifiers.py):+ # F = (num_frames + temporal_compression - 1) // temporal_compression.+ return (pixel_frames + 8 - 1) // 8+++def test_lipsync_5_retake_window_matches_the_engine_latent_count():+ win = _helper_fns("_retake_latent_window")["_retake_latent_window"]+ # 121-frame source: retake.py keeps 1 + 8*15 = 121 pixels = 16 latents.+ w = win(4.9, 5.0, 24.0, 121)+ assert w["pixel_frames"] == 121 and w["latent_frames"] == _engine_latent_count(121) == 16+ # The end of the clip reaches the LAST latent (15), exclusive end 16.+ assert (w["start_frame"], w["end_frame"]) == (15, 16)+ # First stretch: pixel 0 is latent 0 alone; 0-1 s = pixels 0..23 = latents 0..3, exclusive end 4.+ w = win(0.0, 1.0, 24.0, 121)+ assert (w["start_frame"], w["end_frame"]) == (0, 4)+ # Interior 2.0-3.0 s = pixels 48..71 -> latents 6..9, end 10 (48 is in latent 6 = px 41..48).+ w = win(2.0, 3.0, 24.0, 121)+ assert (w["start_frame"], w["end_frame"]) == (6, 10)+ # Whole clip: every latent.+ w = win(0.0, 99.0, 24.0, 121)+ assert (w["start_frame"], w["end_frame"]) == (0, 16)+ # Every requested pixel frame lands inside the regenerated latents, for+ # any range, rate and source length (the cover never rounds inward).+ for frames, fps in ((121, 24.0), (241, 24.0), (61, 12.0), (100, 25.0), (97, 30.0)):+ k = (frames - 1) // 8+ pixels = 1 + 8 * k+ for a10 in range(0, int(pixels / fps * 10)):+ for b10 in range(a10 + 1, int(pixels / fps * 10) + 2):+ w = win(a10 / 10, b10 / 10, fps, frames)+ assert 0 <= w["start_frame"] < w["end_frame"] <= w["latent_frames"]+ assert w["latent_frames"] == _engine_latent_count(pixels)+ lat = lambda px: 0 if px <= 0 else (px - 1) // 8 + 1 # noqa: E731+ first = min(pixels - 1, math.floor(a10 / 10 * fps + 1e-6))+ last = min(pixels, math.ceil(b10 / 10 * fps - 1e-6)) - 1+ if last >= first:+ assert w["start_frame"] <= lat(first)+ assert lat(last) < w["end_frame"]+++def test_lipsync_3_retake_and_extend_decode_at_the_source_rate():+ # The probe helper returns the source's own rate, the panel rate only on failure.+ fake_mod = type(sys)("ltx_core_mlx.utils.ffmpeg")+ fake_mod.probe_video_info = lambda path: type("I", (), {"fps": 12.0})()+ with mock.patch.dict(sys.modules, {"ltx_core_mlx": type(sys)("ltx_core_mlx"),+ "ltx_core_mlx.utils": type(sys)("ltx_core_mlx.utils"),+ "ltx_core_mlx.utils.ffmpeg": fake_mod}):+ src_fps = _helper_fns("_source_fps")["_source_fps"]+ assert src_fps("/x.mp4", 24.0) == 12.0+ fake_mod.probe_video_info = lambda path: (_ for _ in ()).throw(OSError("no"))+ assert src_fps("/x.mp4", 24.0) == 24.0+ # Retake: probed fps drives BOTH the latent window and the decode.+ blk = HELPER_SRC[HELPER_SRC.index('if action == "retake_segment":'):]+ blk = blk[:blk.index('if action == "generate_hq":')]+ assert "_retake_latent_window(start_sec, end_sec, fps, src_frames)" in blk+ assert "frame_rate=fps)" in blk+ assert 'frame_rate=float(p.get("frame_rate", 24.0))' not in blk+ assert '"fps": fps, "frames": win["pixel_frames"]' in blk+ # Extend: same class — the decode reads the source rate.+ ext = HELPER_SRC[HELPER_SRC.index('if action == "extend":'):HELPER_SRC.index('if action == "retake_segment":')]+ assert "frame_rate=_source_fps(video_path, p.get(\"frame_rate\"))" in ext+ assert 'frame_rate=float(p.get("frame_rate", 24.0))' not in ext+++def test_lipsync_11_retake_sidecar_records_the_delivered_clip(tmp_path):+ P = p+ src = tmp_path / "clip.mp4"+ src.write_bytes(b"x" * 4096)+ job = P.make_job({"mode": ["retake"], "prompt": ["fix the hand"],+ "video_path": [str(src)], "retake_start_sec": ["2.0"],+ "retake_end_sec": ["3.0"]})+ job["id"] = "rt1"+ assert job["params"]["frames"] == 121 # make_job's default — not the source+ written = {}++ def _fake_run(spec):+ return {"seed_used": 7, "elapsed_sec": 1.0, "fps": 12.0, "frames": 241,+ "width": 768, "height": 432, "retake_start_frame": 6, "retake_end_frame": 9}++ def _probe_dims(path):+ return (768, 432)++ with mock.patch.object(P, "OUTPUT", tmp_path), \+ mock.patch.dict(P.SYSTEM_CAPS, {"allows_extend": True}), \+ mock.patch.object(P, "hq_surface_missing", return_value=[]), \+ mock.patch.object(P, "hq_weights", return_value={"dev_transformer": "/dev"}), \+ mock.patch.object(P, "tier_max_dim", return_value=0), \+ mock.patch.object(P, "_apply_generation_profile_to_job"), \+ mock.patch.object(P, "_gemma4_tower_supported", return_value=True), \+ mock.patch.object(P.HELPER, "run", side_effect=_fake_run), \+ mock.patch.object(P, "_probe_video_dims", side_effect=_probe_dims), \+ mock.patch.object(P, "_probe_video_frames", return_value=241), \+ mock.patch.object(P, "_probe_video_fps", return_value=12.0), \+ mock.patch.object(P, "write_sidecar",+ side_effect=lambda path, data: written.update({str(path): data}) or True):+ P.run_job_inner(job)+ (sc,) = written.values()+ prm = sc["params"]+ assert (prm["width"], prm["height"], prm["frames"], prm["frame_rate"]) == (768, 432, 241, 12.0)+ assert sc["fps"] == 12.0+ # The gallery's clip length (frames / frame_rate) is the delivered 20 s.+ assert round(prm["frames"] / prm["frame_rate"], 2) == 20.08+ # Probe failure: the helper's own report fills in.+ with mock.patch.object(P, "_probe_video_dims", return_value=(0, 0)), \+ mock.patch.object(P, "_probe_video_frames", return_value=0), \+ mock.patch.object(P, "_probe_video_fps", return_value=0.0):+ got = P._retake_delivered_geometry(tmp_path / "none.mp4",+ {"fps": 12.0, "frames": 241, "width": 768, "height": 432})+ assert got == {"width": 768, "height": 432, "frames": 241, "frame_rate": 12.0}+++# ---- LIPSYNC-4 / 6 / 7: Split into clips ------------------------------------+def _split_harness(body: str) -> dict:+ src = (JS / "characters.js").read_text(encoding="utf-8")+ names = ["_a2vFramesForSeconds", "audioStudioSplitCancel", "_waitForJob",+ "audioStudioSplitIntoClips"]+ if "function _a2vSplitChain(" in src:+ names.append("_a2vSplitChain")+ fns = "\n".join(extract_function(n, src) for n in names)+ has_chain = "_a2vSplitRunning" in src+ return _node(r"""+let _a2vSplitCancel = false;+""" + ("let _a2vSplitRunning = false;\n" if has_chain else "") + r"""+const els = {};+function el(id, v) { els[id] = { id, value: v, checked: false, dataset: {}, textContent: '' }; return els[id]; }+el('audioStudioStart', '0'); el('audioStudioWidth', '1024'); el('audioStudioHeight', '576');+el('audioStudioPrompt', 'She sings.'); el('a2v_image', '/up/face.png');+el('a2v_image_crop_focus', '0.2'); el('audioStudioStatus', '');+const acs = el('audioConditioningScale', '3'); acs.dataset.auto = '1';+el('audioStudioStemAuto', '');+const document = { getElementById: id => els[id] || null };+const AUDIO_STUDIO = { busy: false, audioDuration: 30, audioPath: '/up/song.wav' };+let _activeLoras = [{ path: '/loras/me.safetensors', strength: 0.9, name: 'me' }];+const toasts = [];+function phosToast(m, o) { toasts.push([m, (o || {}).kind]); }+function confirm() { return true; }+function alert(m) { toasts.push([m, 'alert']); }+const setTimeout = (fn) => Promise.resolve().then(fn);+const adds = [];+let anchorFor = (start, clip) => ({ ok: true, anchor_image: '/up/anchor_' + adds.length + '.png',+ audio_start_time: +(start + 9.542).toFixed(3) });+let holdAdd = null;+let failAdd = false;+async function fetch(url, opts) {+ if (url === '/queue/add') {+ const fd = Object.fromEntries(opts.body.entries());+ adds.push(fd);+ if (holdAdd) await holdAdd;+ if (failAdd) return { ok: false, status: 500, json: async () => ({ error: 'boom' }) };+ return { ok: true, json: async () => ({ id: 'j' + adds.length }) };+ }+ if (url === '/status') {+ return { json: async () => ({ history: adds.map((a, k) => ({ id: 'j' + (k + 1), status: 'done',+ output_path: '/out/p' + (k + 1) + '.mp4' })) }) };+ }+ if (url === '/a2v/continue_song') {+ const clip = opts.body.get('clip');+ const k = parseInt(clip.match(/p(\d+)/)[1], 10);+ return { json: async () => anchorFor(parseFloat(adds[k - 1].audio_start_time), clip) };+ }+ throw new Error('unexpected ' + url);+}+""" + fns + "\n(async () => {\n" + body + "\n})().catch(e => { console.log(JSON.stringify({error: String(e.stack || e)})); });\n")+++def test_lipsync_4_split_covers_the_whole_song_with_overlapping_anchors():+ got = _split_harness(r"""+ await audioStudioSplitIntoClips(10);+ const starts = adds.map(a => parseFloat(a.audio_start_time));+ const ends = adds.map(a => parseFloat(a.audio_start_time) + parseInt(a.frames, 10) / 24);+ const plain = { status: els.audioStudioStatus.textContent, toasts: toasts.slice() };+ // A non-advancing anchor (same start as the part) falls back to the plain cut.+ adds.length = 0; toasts.length = 0;+ anchorFor = (start) => ({ ok: true, anchor_image: '/up/a.png', audio_start_time: start });+ await audioStudioSplitIntoClips(10);+ console.log(JSON.stringify({ starts, ends, plain,+ stuckStarts: adds.map(a => parseFloat(a.audio_start_time)),+ stuckStatus: els.audioStudioStatus.textContent }));+ """)+ assert "error" not in got, got+ assert got["starts"] == [0, 9.542, 19.084, 28.626]+ assert max(got["ends"]) >= 30 - 0.05+ assert got["plain"]["status"].startswith("Split into 4 clips done")+ assert got["stuckStarts"] == [0, 10, 20]+ assert got["stuckStatus"].startswith("Split into 3 clips done")+++def test_lipsync_6_split_parts_carry_loras_and_the_first_crop():+ got = _split_harness(r"""+ await audioStudioSplitIntoClips(10);+ console.log(JSON.stringify({ adds }));+ """)+ assert "error" not in got, got+ adds = got["adds"]+ assert len(adds) >= 3+ lor = json.loads(adds[0]["loras"])+ assert lor == [{"path": "/loras/me.safetensors", "strength": 0.9}]+ assert all(a.get("loras") == adds[0]["loras"] for a in adds)+ assert adds[0]["image"] == "/up/face.png" and adds[0]["image_crop_focus"] == "0.2"+ for a in adds[1:]:+ assert a["image"].startswith("/up/anchor_")+ assert "image_crop_focus" not in a+++def test_lipsync_7_only_one_split_chain_runs_and_the_guard_is_released():+ got = _split_harness(r"""+ let release; holdAdd = new Promise(r => { release = r; });+ const first = audioStudioSplitIntoClips(10);+ await Promise.resolve();+ const second = audioStudioSplitIntoClips(10); // while part 1 is still queueing+ await second;+ const whileHeld = adds.length;+ release(); holdAdd = null;+ await first;+ const afterFirst = adds.length;+ // A failed chain releases the guard too.+ adds.length = 0; failAdd = true;+ await audioStudioSplitIntoClips(10);+ failAdd = false;+ const afterFail = adds.length;+ adds.length = 0;+ await audioStudioSplitIntoClips(10);+ console.log(JSON.stringify({ whileHeld, afterFirst, afterFail, again: adds.length,+ toasts }));+ """)+ assert "error" not in got, got+ assert got["whileHeld"] == 1+ assert got["afterFirst"] == 4+ assert got["afterFail"] == 1 and got["again"] == 4+ assert any("already running" in t[0] for t in got["toasts"])+++# ---- LIPSYNC-8: One Shot Load Params on first visit keeps the take's length --+def _oneshot_harness(body: str) -> dict:+ import re+ src = (JS / "oneshot.js").read_text(encoding="utf-8")+ state = re.search(r"^const OS = \{.*?^\};", src, re.M | re.S).group(0)+ consts = "\n".join(re.search(r"^const %s = .*?;$" % n, src, re.M).group(0)+ for n in ("OS_SECONDS_LS_KEY", "OS_SECONDS"))+ names = ["_osStoredSeconds", "oneshotOpenFromParams", "osWire"]+ if "function _osApplyStoredPrefs(" in src:+ names.append("_osApplyStoredPrefs")+ fns = "\n".join(extract_function(n, src) for n in names)+ return _node(r"""+let _store = {};+const localStorage = { getItem: k => (k in _store ? _store[k] : null), setItem: (k, v) => { _store[k] = String(v); } };+const document = { getElementById: () => null, querySelectorAll: () => [], querySelector: () => null };+function osEl() { return null; }+function workflowSwitch(w) { if (w === 'oneshot') osWire(); }+""" + consts + "\n" + state + "\n" + fns + "\n" + body)++[email protected]("stored", [None, "45", "30"])+def test_lipsync_8_first_use_load_params_keeps_the_saved_duration(stored):+ pre = "" if stored is None else "_store.phos_oneshot_seconds = %s;" % json.dumps(stored)+ got = _oneshot_harness(pre + r"""+ oneshotOpenFromParams({ prompt: 'x', take: { seconds: 90, engine: 'ltx' } });+ const restored = OS.seconds;+ osWire(); // a later tab entry never re-applies the stored length+ console.log(JSON.stringify({ restored, after: OS.seconds }));+ """)+ assert got == {"restored": 90, "after": 90}+++def test_lipsync_8_plain_first_visit_still_uses_the_stored_length():+ got = _oneshot_harness(r"""+ _store.phos_oneshot_seconds = '45';+ osWire();+ console.log(JSON.stringify({ seconds: OS.seconds }));+ """)+ assert got == {"seconds": 45}+++# ---- LIPSYNC-9: a stale Windows plan never replaces the current one ---------+def test_lipsync_9_out_of_order_windows_plans_apply_only_the_current_length():+ src = (JS / "characters.js").read_text(encoding="utf-8")+ fn = extract_function("windowPromptsInput", src)+ got = _node(r"""+let _windowsPlanCache = { frames: null, plan: null };+let _windowsPlanFetching = null;+const els = { window_prompts: { value: '' }, windowsDynamicSlots: {}, temporal_mode: { value: 'windows' },+ frames: { value: '241' } };+const document = { getElementById: id => els[id] || null };+const rendered = [];+function _renderWindowsSlotsFromPlan(plan) { rendered.push(plan.count); }+const pending = {};+function fetch(url) {+ const f = url.split('frames=')[1];+ return new Promise(res => { pending[f] = () => res({ json: async () => ({ ok: true, count: f === '241' ? 3 : 7 }) }); });+}+""" + fn + r"""+(async () => {+ windowPromptsInput(); // 241 in flight+ els.frames.value = '721';+ windowPromptsInput(); // 721 in flight+ pending['721'](); await new Promise(r => setTimeout(r, 10));+ pending['241'](); await new Promise(r => setTimeout(r, 10)); // the older answer lands last+ const cached = _windowsPlanCache.frames;+ const before = rendered.slice();+ // Back to 241: fetched fresh and applied (a stale answer never blocks the next one).+ els.frames.value = '241';+ windowPromptsInput();+ pending['241'](); await new Promise(r => setTimeout(r, 10));+ console.log(JSON.stringify({ before, rendered, cached, now: _windowsPlanCache.frames, fetching: _windowsPlanFetching }));+})();+""")+ assert got["before"] == [7], got # the stale 3-window plan was dropped+ assert got["rendered"] == [7, 3], got+ assert got["cached"] == 721 and got["now"] == 241 and got["fetching"] is None+++# ---- LIPSYNC-10: A2V Load Params restores "Listen to the voice only" ---------+def _a2v_roundtrip(params: dict, checked_before: bool, via_continue: bool = False) -> dict:+ import test_review_416_ltx as r416 # the shared A2V DOM shim+ from extract_panel_js import panel_source # noqa: PLC0415+ src = panel_source()+ fns = ["_a2vFramesForSeconds", "audioStudioDurationChanged", "a2vLaneAudioScale",+ "audioConditioningScaleChanged", "audioConditioningScaleReset",+ "a2vLoadParams", "loadParams", "audioStudioGenerate"]+ if via_continue:+ fns.append("continueSongFromClip")+ js = r416.A2V_DOM + (+ "el('audioStudioStemAuto'); els.audioStudioStemAuto.checked = %s;\n"+ "function requestAnimationFrame(f) { f(); }\n" % json.dumps(checked_before)+ ) + "\n".join(extract_function(n, src) for n in fns) + """+const sidecar = %s;+(async () => {+ globalThis.fetch = async (url) => ({ok: true, json: async () => (String(url).startsWith('/a2v/continue_song')+ ? {ok: true, anchor_image: '/up/anchor.png', audio_start_time: 12.5} : sidecar)});+ if (%s) await continueSongFromClip('/x.mp4'); else await loadParams();+ const restored = els.audioStudioStemAuto.checked;+ globalThis.fetch = async (url, opts) => { posted = Object.fromEntries(opts.body); return {ok: true}; };+ await audioStudioGenerate();+ console.log(JSON.stringify({restored, stem: posted.audio_stem_auto || null, start: posted.audio_start_time}));+})();+""" % (json.dumps({"output": "/x.mp4", "params": params}), "true" if via_continue else "false")+ return _node(js)+++def _a2v_params(**over):+ base = {"mode": "a2v", "prompt": "a singer", "audio": "/songs/take.wav",+ "image": "/uploads/singer.png", "width": 832, "height": 480, "frames": 241,+ "seed": "7", "audio_start_time": 0, "audio_conditioning_scale": ""}+ base.update(over)+ return base++[email protected]("via_continue", [False, True])[email protected]("saved,before,want", [+ ("", True, False), # rendered with the full mix; the form had it on+ ("on", False, True), # rendered voice-only; the form had it off+ ("true", False, True),+])+def test_lipsync_10_load_params_restores_voice_only(saved, before, want, via_continue):+ got = _a2v_roundtrip(_a2v_params(audio_stem_auto=saved), before, via_continue)+ assert got["restored"] is want+ assert got["stem"] == ("on" if want else None)+ if via_continue:+ assert got["start"] == "12.5"+++def test_lipsync_10_legacy_and_explicit_stem_sidecars():+ # No field at all: the clip predates the control and heard the full mix.+ p = _a2v_params()+ got = _a2v_roundtrip(p, True)+ assert got["restored"] is False and got["stem"] is None+ # A music-video shot rendered from an explicit vocal stem listened to the voice alone.+ got = _a2v_roundtrip(_a2v_params(audio_stem="/stems/vocals.wav", audio_stem_auto=""), False)+ assert got["restored"] is True and got["stem"] == "on"diff --git a/test_codex_4170_safety.py b/test_codex_4170_safety.pynew file mode 100644index 0000000..d51d6fc--- /dev/null+++ b/test_codex_4170_safety.py@@ -0,0 +1,675 @@+#!/usr/bin/env python3+"""4.17.0 Codex review — the SAFETY area (Stop, queue, job lifecycle, One Shot+recovery, Retry smaller, queue edit/restore, draft autosave). Every finding+fixed gets its pin here. Findings:+~/AI/projects/phosphene/review-2026-09-29-ux/codex/findings_safety.md.+JS is executed in node where it is behaviour.+"""+from __future__ import annotations++import copy+import os+import io+import json+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path+from unittest import mock++import pytest++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as p # noqa: E402+from extract_panel_js import extract_function # noqa: E402++routes_queue = sys.modules["panel.routes_queue"]+NODE = shutil.which("node")+JS = ROOT / "webapp" / "js"+++def _node(script: str):+ if NODE is None:+ pytest.skip("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ assert r.returncode == 0, r.stderr[-3000:]+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class _H:+ """A route handler double: a form body in, the JSON reply captured."""++ def __init__(self, form=None, body=b""):+ self.status, self.payload = None, None+ self._form = form or {}+ self.headers = {"Content-Length": str(len(body))}+ self.rfile = io.BytesIO(body)++ def _read_form_body(self):+ return b"", self._form++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++def queue_state():+ """A private queue/history/current for the test; the real one comes back."""+ with p.LOCK:+ saved = {k: copy.deepcopy(p.STATE.get(k)) for k in ("queue", "history", "current", "paused")}+ p.STATE["queue"], p.STATE["history"], p.STATE["current"] = [], [], None+ p.STATE["paused"] = True+ undo = getattr(p, "_QUEUE_UNDO", {})+ undo.clear()+ with mock.patch.object(p, "persist_queue", lambda: None):+ yield p.STATE+ with p.LOCK:+ for k, v in saved.items():+ p.STATE[k] = v+ undo.clear()+++# ---- SAFETY-2: Retry smaller answers success, queues exactly one ----------+def test_safety_2_retry_smaller_replies_ok_and_queues_one(queue_state):+ queue_state["history"].append({+ "id": "j-src", "status": "failed", "error": "GPU watchdog",+ "params": {"mode": "t2v", "engine": "ltx", "prompt": "a fox", "quality": "high",+ "width": 1280, "height": 704, "frames": 121}})+ h = _H({"id": ["j-src"], "smaller": ["1"]})+ routes_queue.post_queue_retry(h, "/queue/retry", {}, "")+ assert h.status == 200 and h.payload["ok"] is True, h.payload+ assert len(queue_state["queue"]) == 1+ got = queue_state["queue"][0]["params"]+ assert got["quality"] == "standard"+ assert max(got["width"], got["height"]) < 1280 and got["frames"] < 121+ assert h.payload["id"] == queue_state["queue"][0]["id"]+++# ---- SAFETY-8/9/10: Clear queue -> Undo restores the server's own removal --+def _qjob(jid, prompt="x"):+ return {"id": jid, "status": "queued", "params": {"mode": "t2v", "prompt": prompt}}+++def _clear():+ h = _H()+ routes_queue.post_queue_clear(h, "/queue/clear", {}, "")+ assert h.status == 200+ return h.payload+++def _restore(body: dict):+ raw = json.dumps(body).encode()+ h = _H(body=raw)+ routes_queue.post_queue_restore(h, "/queue/restore", {}, "application/json")+ return h+++def test_safety_9_undo_restores_exactly_what_clear_removed(queue_state):+ # The browser's last poll showed [A, B]; the worker then started A, and+ # another tab added C — all before Clear reached the server.+ queue_state["queue"][:] = [_qjob("j-B", "b"), _qjob("j-C", "c")]+ queue_state["current"] = dict(_qjob("j-A", "a"), status="running")+ out = _clear()+ assert out["cleared"] == 2 and out["ids"] == ["j-B", "j-C"] and out["undo_token"]+ assert queue_state["queue"] == []+ h = _restore({"token": out["undo_token"]})+ assert h.status == 200 and h.payload["restored"] == 2, h.payload+ assert [j["id"] for j in queue_state["queue"]] == ["j-B", "j-C"] # A not duplicated, C kept+ # single use+ h2 = _restore({"token": out["undo_token"]})+ assert h2.status == 410 and [j["id"] for j in queue_state["queue"]] == ["j-B", "j-C"]+++def test_safety_9_an_expired_or_superseded_undo_restores_nothing(queue_state):+ queue_state["queue"][:] = [_qjob("j-1")]+ first = _clear()+ queue_state["queue"][:] = [_qjob("j-2")]+ _clear() # a second Clear supersedes the first Undo+ assert _restore({"token": first["undo_token"]}).status == 410+ assert queue_state["queue"] == []+++def test_safety_9_the_undo_toast_sends_the_server_token_not_a_snapshot():+ src = (JS / "queue.js").read_text(encoding="utf-8")+ fn = extract_function("requestClearQueue", src)+ out = _node(r"""+const sent = [];+let toastEl = null;+global.LAST_STATUS = { queue: [{ id: 'stale-A', params: { prompt: 'a' } }] };+global.poll = () => {};+global.api = async (path) => { sent.push(['api', path]); return { cleared: 2, ids: ['j-B', 'j-C'], undo_token: 'tok123' }; };+global.fetch = async (path, opts) => { sent.push(['fetch', path, opts.body]);+ return { ok: true, status: 200, json: async () => ({ ok: true, restored: 2 }) }; };+const toasts = [];+global.phosToast = (msg) => { toasts.push(msg); if (toastEl) return null;+ toastEl = { children: [], appendChild(c) { this.children.push(c); }, remove() {} }; return toastEl; };+global.document = { createElement: () => ({}) };+""" + fn + r"""+(async () => {+ requestClearQueue();+ await new Promise(r => setTimeout(r, 10));+ await toastEl.children[0].onclick({ preventDefault() {} });+ console.log(JSON.stringify({ sent, toasts }));+})();+""")+ assert out["sent"][0] == ["api", "/queue/clear"]+ assert out["sent"][1][:2] == ["fetch", "/queue/restore"]+ assert json.loads(out["sent"][1][2]) == {"token": "tok123"}+ assert out["toasts"][0].startswith("Cleared 2 queued renders") # the server's count+ assert out["toasts"][1] == "Restored 2 renders"+++def test_safety_10_restoring_200_jobs_keeps_every_id_unique(queue_state):+ queue_state["queue"][:] = [_qjob(f"j-orig-{i:03d}", f"p{i}") for i in range(200)]+ tok = _clear()["undo_token"]+ with mock.patch.object(p.time, "time", return_value=1_700_000_000.0), \+ mock.patch.object(p.random, "randrange", return_value=7):+ h = _restore({"token": tok})+ assert h.status == 200+ assert [j["id"] for j in queue_state["queue"]] == [f"j-orig-{i:03d}" for i in range(200)]+ # the API's params-only form mints ids too — through the one allocator+ queue_state["queue"][:] = []+ h = _restore({"jobs": [{"params": {"prompt": f"q{i}"}} for i in range(200)]})+ assert h.status == 200+ ids = [j["id"] for j in queue_state["queue"]]+ assert len(ids) == 200 and len(set(ids)) == 200+++def test_safety_10_no_route_mints_ids_from_a_clock_and_a_small_random():+ for f in (ROOT / "panel" / "routes_queue.py", ROOT / "mlx_ltx_panel.py"):+ src = f.read_text(encoding="utf-8")+ assert "randrange(0xfff):03x}" not in src, f+++def test_safety_8_undo_reattaches_restored_storyboard_jobs(queue_state):+ board = {"id": "sb_20260929_abcdef", "shots": [+ {"n": 1, "uid": "shot_00000001", "status": "queued", "draft_job_id": "j-shot1"}]}+ queue_state["queue"][:] = [_qjob("j-shot1")]+ tok = _clear()["undo_token"]+ # the board polls between Clear and Undo: the shot must NOT be unhooked+ p._sb_reconcile(board)+ shot = board["shots"][0]+ assert shot.get("draft_job_id") == "j-shot1" and shot["status"] == "queued"+ assert _restore({"token": tok}).status == 200+ # the restored job (same id) finishes — its clip lands on the original shot+ job = queue_state["queue"].pop(0)+ job.update(status="done", output_path="/o/shot1.mp4")+ queue_state["history"].insert(0, job)+ with mock.patch.object(p, "_probe_video_dims", return_value=(0, 0)), \+ mock.patch.object(p, "_sb_sidecar_seed", return_value=None):+ p._sb_reconcile(board)+ p._sb_reconcile(board)+ assert shot["draft_output"] == "/o/shot1.mp4" and shot["status"] == "done"+ assert shot.get("takes") in (None, []) # attached exactly once+++def test_safety_8_after_the_undo_window_film_18_still_unhooks_the_shot(queue_state):+ board = {"id": "sb_x", "shots": [+ {"n": 1, "uid": "shot_00000002", "status": "queued", "draft_job_id": "j-gone"}]}+ queue_state["queue"][:] = [_qjob("j-gone")]+ _clear()+ with mock.patch.object(p.time, "monotonic", return_value=p.time.monotonic() + p.QUEUE_UNDO_TTL_SEC + 1):+ p._sb_reconcile(board)+ assert board["shots"][0]["status"] == "pending" and "draft_job_id" not in board["shots"][0]+++# ---- SAFETY-3: a Stop confirmation only ever stops the job it described ----+def test_safety_3_stale_stop_ids_leave_the_successor_running(queue_state):+ queue_state["current"] = {"id": "j-B", "status": "running",+ "params": {"take": {"seconds": 20}}, "progress": {}}+ with mock.patch.object(p.HELPER, "kill") as kill:+ h = _H()+ routes_queue.post_stop(h, "/stop", {"id": ["j-A"]}, "")+ assert h.status == 409 and h.payload.get("stale") is True+ assert not kill.called and "cancel_requested" not in queue_state["current"]+ h = _H()+ routes_queue.post_stop_after_part(h, "/stop/after_part", {"id": ["j-A"]}, "")+ assert h.status == 409 and "stop_after_part" not in queue_state["current"]+ # the job the dialog named is still stoppable, both ways+ h = _H()+ routes_queue.post_stop_after_part(h, "/stop/after_part", {"id": ["j-B"]}, "")+ assert h.status == 200 and queue_state["current"]["stop_after_part"] is True+ with mock.patch.object(p.agent_image_engine, "kill_active_image_procs", return_value=0):+ h = _H()+ routes_queue.post_stop(h, "/stop", {"id": ["j-B"]}, "")+ assert h.status == 200 and kill.called and queue_state["current"]["cancel_requested"]+++def test_safety_3_the_dialog_sends_the_id_it_was_opened_for():+ src = (JS / "queue.js").read_text(encoding="utf-8")+ fn = extract_function("requestStop", src)+ out = _node(r"""+const sent = []; let modal = null;+global.BOOT = { tier: {} };+global.LAST_STATUS = { server_now: 1000, current: { id: 'j-A', started_ts: 1,+ params: { prompt: 'a fox', take: { parts: [1, 2, 3] } }, take_progress: { part: 1, parts: 3 } } };+global._phModalShow = (o) => { modal = o; };+global.phosToast = () => {};+global.poll = () => {};+global.snippet = (s) => s;+global.api = async (path, m) => { sent.push(path); return { ok: true }; };+global.fetch = async (path) => { sent.push(path); return { json: async () => ({ ok: true }) }; };+""" + fn + r"""+(async () => {+ requestStop();+ // A finishes, B starts, THEN the user confirms either button+ LAST_STATUS.current = { id: 'j-B', params: { prompt: 'b' } };+ modal.onPrimary(); modal.onSecondary();+ await new Promise(r => setTimeout(r, 10));+ console.log(JSON.stringify(sent));+})();+""")+ assert out == ["/stop/after_part?id=j-A", "/stop?id=j-A"]+++# ---- SAFETY-4: editing a queued job keeps its engine and whole recipe -------+_RECORDING_SHIM = r"""+globalThis.calls = [];+globalThis._els = {};+globalThis._mk = function (id, v) {+ return _els[id] = {id, value: v === undefined ? '' : String(v), textContent: '', dataset: {},+ hidden: false, style: {}, innerHTML: '', checked: false,+ classList: {toggle(){}, add(){}, remove(){}, contains(){ return false; }},+ querySelector(){ return null; }, querySelectorAll(){ return []; },+ setAttribute(){}, getAttribute(){ return null; }, addEventListener(){}, focus(){}};+};+globalThis.document = {getElementById: id => _els[id] || _mk(id), querySelector: () => null,+ querySelectorAll: () => [], body: {dataset: {}, classList: {toggle(){}}}};+globalThis.window = globalThis;+Object.assign(globalThis, {BOOT: {tier: {}}, activePath: '/some/other/clip.mp4', FPS: 24, ASPECTS: {}});+_mk('prompt', 'FORM PROMPT'); _mk('seed', '99'); _mk('steps', '30');+globalThis.RECORD = ['setEngine', 'setMode', 'setQuality', 'setH3Speed', 'setH3Steps', 'setH3Upscale',+ 'setH3Orientation', '_h3ApplyShape', 'setH3Tier', 'setH3ChainPrompts', 'setUpscale',+ 'setUpscaleMethod', 'setTemporalMode', 'setAccel', '_flashActionDone', '_restoreLoraPicker',+ 'charactersLoadParams', 'workflowSwitch'];+globalThis.SHIM = new Proxy({}, {+ has: (_, k) => k !== Symbol.unscopables && typeof k === 'string' && !(k in globalThis),+ get: (_, k) => {+ if (k === 'engineById') return () => true;+ if (k === 'h3CellFor') return () => true;+ if (k === 'h3SpeedOfParams') return (p) => (p.h3_tristep ? 'fast' : 'quality');+ if (k === 'setH3Quality') return function () {};+ if (k === 'framesToDuration') return (f) => f / 24;+ if (RECORD.includes(k)) return function () { calls.push([k].concat([].slice.call(arguments)));+ return k === 'setEngine' ? arguments[0] : undefined; };+ return function () {};+ },+});+globalThis.fetch = async () => { calls.push(['fetch']); return { ok: false }; };+"""+++def _load_recipe(params):+ from extract_panel_js import panel_source # noqa: PLC0415+ fn = extract_function("loadParams", panel_source())+ return _node(_RECORDING_SHIM + "with (SHIM) {\n" + fn + """+loadParams({ params: %s }).then(() => console.log(JSON.stringify({ calls,+ prompt: document.getElementById('prompt').value, seed: document.getElementById('seed').value,+ steps: document.getElementById('steps').value })),+ e => { console.error(e && e.stack || e); process.exit(1); });+}""" % json.dumps(params))+++def test_safety_4_a_queued_h3_job_restores_its_engine_and_h3_recipe():+ h3 = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "a hen skates",+ "h3_quality": "high", "h3_length": "15s", "h3_tristep": "1",+ "h3_chain_prompts": json.dumps(["w1", "w2", "w3"]), "seed": "-1"})["params"]+ out = _load_recipe(h3)+ names = [c[0] for c in out["calls"]]+ assert "fetch" not in names # a queued job has no sidecar+ assert ["setEngine", "h3", {"persist": False}] in out["calls"]+ assert any(c[0] in ("_h3ApplyShape", "setH3Tier") for c in out["calls"])+ assert ["setH3Speed", "fast" if h3.get("h3_tristep") else "quality"] in out["calls"]+ assert any(c[0] == "setH3ChainPrompts" for c in out["calls"])+ assert "_flashActionDone" not in names and "charactersLoadParams" not in names+ assert out["prompt"] == "a hen skates"+++def test_safety_4_a_queued_ltx_job_restores_steps_and_export_method():+ ltx = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "a fox", "steps": "12",+ "upscale": "fit_720p", "upscale_method": "pipersr", "quality": "standard"})["params"]+ ltx["source"] = "characters" # would have jumped to the Characters tab+ out = _load_recipe(ltx)+ assert ["setEngine", "ltx", {"persist": False}] in out["calls"]+ assert ["setUpscaleMethod", "pipersr"] in out["calls"]+ assert str(out["steps"]) == "12" and out["prompt"] == "a fox"+ assert "charactersLoadParams" not in [c[0] for c in out["calls"]]+++def test_safety_4_edit_row_restores_through_load_params():+ src = (JS / "queue.js").read_text(encoding="utf-8")+ fn = extract_function("editQueuedJob", src)+ out = _node(r"""+let got = null; let editingSeen = 'unset';+var _editingQueuedJobId = null;+const _EDITABLE_QUEUE_MODES = ['t2v', 'i2v', 'i2v_clean_audio', 'extend', 'keyframe'];+global.LAST_STATUS = { queue: [{ id: 'j-h3', params: { mode: 't2v', engine: 'h3', prompt: 'p',+ h3_tier: 'high_15s', h3_chain_prompts: ['a', 'b', 'c'] } }] };+global.loadParams = async (recipe) => { got = recipe; editingSeen = _editingQueuedJobId; };+global.phosToast = () => {};+global.document = { getElementById: () => ({ hidden: true }), querySelector: () => null };+""" + fn + r"""+editQueuedJob('j-h3').then(() => console.log(JSON.stringify({ got, editingSeen, after: _editingQueuedJobId })));+""")+ assert out["got"]["params"]["engine"] == "h3" and out["got"]["params"]["h3_tier"] == "high_15s"+ assert out["editingSeen"] is None and out["after"] == "j-h3"+++def test_safety_4_update_keeps_what_the_form_cannot_express(queue_state):+ orig = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "old", "h3_quality": "high",+ "h3_length": "10s", "session_tag": "sb:sb_1#2"})+ orig["params"]["source"] = "storyboard"+ queue_state["queue"].append(orig)+ form = {"mode": ["t2v"], "engine": ["h3"], "prompt": ["new"], "h3_quality": ["high"],+ "h3_length": ["10s"]}+ out = p.queue_update_job(orig["id"], form)+ assert out["ok"] is True+ got = queue_state["queue"][0]["params"]+ assert got["prompt"] == "new" and got["engine"] == "h3"+ assert got["source"] == "storyboard" and got["session_tag"] == "sb:sb_1#2"+++# ---- One Shot recovery: SAFETY-5 / 6 / 7 / 11 / 12 -------------------------+def _clip(path: Path, secs: float = 0.2) -> None:+ subprocess.run(+ ["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", f"color=c=red:s=32x32:d={secs}",+ "-f", "lavfi", "-i", "anullsrc=r=8000:cl=mono", "-t", str(secs),+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", str(path)],+ check=True)+++def take_env(tmp_path, monkeypatch, queue_state):+ if shutil.which("ffmpeg") is None:+ pytest.skip("ffmpeg not on PATH")+ out_dir = tmp_path / "out"; out_dir.mkdir()+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "UPLOADS", tmp_path / "up")+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")+ monkeypatch.setattr(p, "HIDDEN_PATHS", set())+ monkeypatch.setattr(p, "persist_hidden", lambda: None)+ monkeypatch.setattr(p, "take_drift", lambda *a, **k: {"delta": 0.0, "drifted": False})+ monkeypatch.setattr(p, "take_expects_speech", lambda *a, **k: False)+ env = {"made": [], "fail_at": None, "secs": 0.2}++ def fake_render(child):+ n = len(env["made"]) + 1+ if env["fail_at"] == n:+ raise RuntimeError("the engine died")+ out = out_dir / f"{child['id']}.mp4"+ _clip(out, env["secs"])+ seed = 700 + n+ child["output_path"] = str(out)+ child["params"]["seed_used"] = seed+ # both engines write the seed under params (not top level)+ (out.parent / (out.name + ".json")).write_text(json.dumps(+ {"output": str(out), "params": {**child["params"], "seed_used": seed}}))+ env["made"].append(out)++ monkeypatch.setattr(p, "run_h3_job_inner", fake_render)+ monkeypatch.setattr(p, "run_job_inner", fake_render)+ return env+++def _take_job(handoff="last"):+ job = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "a hen skates",+ "take_seconds": "45", "take_handoff": handoff,+ "beats": json.dumps([f"beat {i}" for i in range(9)])})+ job["params"]["take"]["handoff"] = handoff+ return job+++def _manifest_of(path):+ return json.loads(Path(str(path) + ".json").read_text())["one_shot_unfinished"]+++def test_safety_5_speech_handoff_recovery_card_is_a_visible_output(take_env, monkeypatch):+ take_env["secs"] = 1.0+ take_env["fail_at"] = 2+ monkeypatch.setattr(p, "take_handoff_points", lambda out: (0.6, 0.8))+ job = _take_job("speech")+ assert job["params"]["take"]["handoff"] == "speech"+ with pytest.raises(RuntimeError, match="engine died"):+ p.run_take_job_inner(job)+ part1 = take_env["made"][0]+ assert str(part1).startswith(str(p.OUTPUT))+ assert str(part1) not in p.HIDDEN_PATHS # the card is shown+ man = _manifest_of(part1) # manifest on the VISIBLE part+ assert man["visible"] == [str(part1)]+ assert man["outs"][0].endswith("part1_speech.mp4") # join input kept separately+ assert man["part_seeds"] == [701]+ # /outputs lists it with the recovery flag+ old = p.time.time() - 60+ os.utime(part1, (old, old))+ items = p.list_outputs(limit=0)+ card = next(o for o in items if o.get("path") == str(part1))+ assert card["one_shot_unfinished"] is True+ # both recovery actions accept that path+ h = _H({"path": [str(part1)]})+ routes_queue.post_take_resume(h, "/take/resume", {}, "")+ assert h.status == 200, h.payload+ h = _H({"path": [str(part1)]})+ routes_queue.post_take_join_partial(h, "/take/join_partial", {}, "")+ assert h.status == 200, h.payload+ assert str(part1) in p.HIDDEN_PATHS # the joined clip replaces it+++def test_safety_6_resume_rebuilds_a_handoff_frame_stop_never_wrote(take_env, monkeypatch):+ real = p._take_ffmpeg+ calls = {"n": 0}++ def stop_during_frame(cmd, label, job, pgid_key="mux_pgid"):+ if label == "One Shot handoff frame" and calls["n"] == 0:+ calls["n"] += 1+ raise p.JobCancelled("Stopped during One Shot handoff frame.")+ return real(cmd, label, job) if pgid_key == "mux_pgid" else real(cmd, label, job, pgid_key)++ monkeypatch.setattr(p, "_take_ffmpeg", stop_during_frame)+ job = _take_job()+ with pytest.raises(p.JobCancelled):+ p.run_take_job_inner(job)+ part1 = take_env["made"][0]+ man = _manifest_of(part1)+ assert man["done_parts"] == 1+ assert man["last_png"] is None or Path(man["last_png"]).is_file()+ h = _H({"path": [str(part1)]})+ routes_queue.post_take_resume(h, "/take/resume", {}, "")+ assert h.status == 200+ resumed = p.STATE["queue"][-1]+ seen = []+ orig_render = p.run_h3_job_inner++ def check_anchor(child):+ seen.append(child["params"].get("image"))+ assert Path(child["params"]["image"]).is_file(), "part 2 started from a missing frame"+ orig_render(child)++ monkeypatch.setattr(p, "run_h3_job_inner", check_anchor)+ p.run_take_job_inner(resumed)+ assert len(seen) == 2 and resumed.get("output_path")+++def test_safety_12_resumed_parts_keep_their_params_seed_used(take_env):+ take_env["fail_at"] = 3+ job = _take_job()+ with pytest.raises(RuntimeError):+ p.run_take_job_inner(job)+ last = take_env["made"][-1]+ man = _manifest_of(last)+ # an older manifest with no part_seeds: seeds come from params.seed_used+ man.pop("part_seeds", None)+ side = json.loads(Path(str(last) + ".json").read_text())+ side["one_shot_unfinished"] = man+ Path(str(last) + ".json").write_text(json.dumps(side))+ h = _H({"path": [str(last)]})+ routes_queue.post_take_resume(h, "/take/resume", {}, "")+ assert h.status == 200+ take_env["fail_at"] = None+ resumed = p.STATE["queue"][-1]+ p.run_take_job_inner(resumed)+ final = Path(resumed["output_path"])+ meta = json.loads(Path(str(final) + ".json").read_text())["take"]["parts_meta"]+ assert meta == [{"seed_used": 701}, {"seed_used": 702}, {"seed_used": 703}]+++def test_safety_11_new_take_after_join_keeps_every_beat(take_env):+ take_env["fail_at"] = 2+ job = _take_job()+ with pytest.raises(RuntimeError):+ p.run_take_job_inner(job)+ part1 = take_env["made"][0]+ written = list(job["params"]["take"]["beat_prompts"])+ assert len(written) == 9 and all(w.startswith(f"beat {i}") for i, w in enumerate(written))+ h = _H({"path": [str(part1)]})+ routes_queue.post_take_join_partial(h, "/take/join_partial", {}, "")+ assert h.status == 200+ joined = h.payload["output"]+ jt = json.loads(Path(joined + ".json").read_text())["take"]+ assert jt["beats"] == written+ assert jt["parts_meta"] == [{"seed_used": 701}]+ h = _H({"path": [joined]})+ routes_queue.post_queue_newtake(h, "/queue/newtake", {}, "")+ assert h.status == 200, h.payload+ assert p.STATE["queue"][-1]["params"]["take"]["beat_prompts"] == written+++def test_safety_11_new_take_reads_an_old_input_shaped_partial_sidecar(take_env, tmp_path):+ clip = p.OUTPUT / "old_partial.mp4"+ _clip(clip)+ beats = [f"old beat {i}" for i in range(6)]+ take = {"seconds": 30, "beats": 6, "beat_prompts": beats, "engine": "h3", "parts": [str(clip)]}+ (p.OUTPUT / "old_partial.mp4.json").write_text(json.dumps(+ {"take": take, "params": {"prompt": "x", "engine": "h3", "mode": "t2v", "take": take}}))+ h = _H({"path": [str(clip)]})+ routes_queue.post_queue_newtake(h, "/queue/newtake", {}, "")+ assert h.status == 200, h.payload+ assert p.STATE["queue"][-1]["params"]["take"]["beat_prompts"] == beats+++def test_safety_7_a_recovery_join_never_takes_the_queues_mux_slot(take_env, monkeypatch):+ take_env["fail_at"] = 2+ job = _take_job()+ with pytest.raises(RuntimeError):+ p.run_take_job_inner(job)+ part1 = take_env["made"][0]+ seen_keys = []+ real = p.run_tracked_subprocess++ def spy(cmd, *, pgid_key, label, job=None, **kw):+ seen_keys.append(pgid_key)+ with p.LOCK:+ during = p.STATE.get("mux_pgid")+ assert during == 111, "the join overwrote the queue's mux registration"+ return real(cmd, pgid_key=pgid_key, label=label, job=job, **kw)++ with p.LOCK:+ p.STATE["mux_pgid"] = 111 # a queued render's encode is live+ try:+ monkeypatch.setattr(p, "run_tracked_subprocess", spy)+ h = _H({"path": [str(part1)]})+ routes_queue.post_take_join_partial(h, "/take/join_partial", {}, "")+ assert h.status == 200, h.payload+ with p.LOCK:+ assert p.STATE.get("mux_pgid") == 111 # still registered, still stoppable+ assert seen_keys and all(k == "take_join_pgid" for k in seen_keys)+ # and only one join owns that slot at a time+ assert routes_queue._TAKE_JOIN_LOCK.acquire(blocking=False)+ try:+ h = _H({"path": [str(part1)]})+ routes_queue.post_take_join_partial(h, "/take/join_partial", {}, "")+ assert h.status in (404, 409)+ finally:+ routes_queue._TAKE_JOIN_LOCK.release()+ finally:+ with p.LOCK:+ p.STATE["mux_pgid"] = None+++# ---- SAFETY-13: a restored draft brings back its mode's source inputs ------+_DRAFT_SHIM = r"""+globalThis._els = {};+globalThis._mk = (id, v) => (_els[id] = { id, value: v === undefined ? '' : String(v) });+globalThis.document = { getElementById: (id) => _els[id] || null };+['mode', 'i2vMode', 'quality', 'prompt', 'negative_prompt', 'seed', 'width', 'height', 'frames',+ 'duration', 'image', 'audio', 'video_path', 'start_image', 'end_image', 'extendSrcSelect']+ .forEach(id => _mk(id, ''));+globalThis.store = {};+globalThis.localStorage = { getItem: k => store[k] || null, setItem: (k, v) => { store[k] = v; } };+globalThis.DRAFT_LS_KEY = 'draft';+globalThis.activePath = null;+globalThis.calls = [];+globalThis.toasts = [];+globalThis.phosToast = (m, o) => toasts.push([m, (o || {}).kind || '']);+globalThis.setMode = (m) => { calls.push(['setMode', m]); _els.mode.value = m; };+globalThis.setQuality = () => {};+globalThis.pickerSetImage = (k, v) => { calls.push(['pickerSetImage', k, v]); _els[k].value = v; };+globalThis.i2vAudioSet = (v) => { calls.push(['i2vAudioSet', v]); _els.audio.value = v; };+globalThis.MISSING = new Set();+globalThis.fetch = async (url) => { const path = decodeURIComponent(url.split('path=')[1]);+ calls.push(['fetch', url.split('?')[0]]);+ return { json: async () => ({ exists: !MISSING.has(path) }) }; };+"""+++def _draft_run(form: dict, missing=()):+ src = (JS / "queue.js").read_text(encoding="utf-8")+ fns = "\n".join(extract_function(n, src) for n in+ ("_draftSnapshot", "saveDraftNow", "_draftDropIfMissing", "restoreDraftOnBoot"))+ return _node(_DRAFT_SHIM + fns + """+const form = %s;+for (const [k, v] of Object.entries(form)) _els[k].value = v;+saveDraftNow();+Object.keys(_els).forEach(k => _els[k].value = ''); // a reload: a blank form+MISSING = new Set(%s);+restoreDraftOnBoot();+setTimeout(() => console.log(JSON.stringify({ calls, toasts,+ vals: Object.fromEntries(Object.entries(_els).map(([k, e]) => [k, e.value])) })), 20);+""" % (json.dumps(form), json.dumps(list(missing))))+++def test_safety_13_image_keyframe_and_extend_drafts_keep_their_inputs():+ out = _draft_run({"mode": "i2v_clean_audio", "i2vMode": "i2v_clean_audio", "prompt": "a",+ "image": "/u/a.png", "audio": "/u/song.wav"})+ assert ["pickerSetImage", "image", "/u/a.png"] in out["calls"]+ assert out["vals"]["audio"] == "/u/song.wav" and out["vals"]["mode"] == "i2v_clean_audio"+ out = _draft_run({"mode": "keyframe", "prompt": "b", "start_image": "/u/s.png",+ "end_image": "/u/e.png"})+ assert ["pickerSetImage", "start_image", "/u/s.png"] in out["calls"]+ assert ["pickerSetImage", "end_image", "/u/e.png"] in out["calls"]+ out = _draft_run({"mode": "extend", "prompt": "c", "video_path": "/o/clip.mp4"})+ assert out["vals"]["video_path"] == "/o/clip.mp4" and out["vals"]["extendSrcSelect"] == "/o/clip.mp4"+++def test_safety_13_a_source_deleted_since_is_cleared_out_loud():+ out = _draft_run({"mode": "extend", "prompt": "c", "video_path": "/o/gone.mp4"},+ missing=["/o/gone.mp4"])+ assert out["vals"]["video_path"] == ""+ assert any("gone.mp4 from your draft is no longer on disk" in t[0] and t[1] == "warning"+ for t in out["toasts"])+++def test_safety_13_file_exists_route_is_bound_to_outputs_and_uploads(tmp_path, monkeypatch):+ from urllib.parse import urlparse, quote+ routes_files = sys.modules["panel.routes_files"]+ out_dir = tmp_path / "o"; out_dir.mkdir()+ up = tmp_path / "u"; up.mkdir()+ (up / "song.wav").write_bytes(b"x")+ (tmp_path / "secret.txt").write_bytes(b"x")+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "UPLOADS", up)+ got = []+ for f in (up / "song.wav", out_dir / "nope.mp4", tmp_path / "secret.txt"):+ h = _H()+ routes_files.get_file_exists(h, urlparse("/file/exists?path=" + quote(str(f))))+ got.append(h.payload["exists"])+ assert got == [True, False, False]diff --git a/test_codex_4170_ui.py b/test_codex_4170_ui.pynew file mode 100644index 0000000..7f7e691--- /dev/null+++ b/test_codex_4170_ui.py@@ -0,0 +1,509 @@+#!/usr/bin/env python3+"""4.17.0 Codex review — UI area (Video-tab UI + system / i18n / privacy).++Findings: ~/AI/projects/phosphene/review-2026-09-29-ux/codex/findings_ui.md+(UI-1..UI-10) + EST-12 (duplicate of UI-8). Every pin here fails on e724af7+and passes after the fix. JS is executed in node where it is behaviour.+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path+from unittest import mock+from urllib.parse import urlencode++import pytest++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as p # noqa: E402+from extract_panel_js import extract_function # noqa: E402+from panel.routes import POST_ROUTES # noqa: E402++NODE = shutil.which("node")+JS = ROOT / "webapp" / "js"+++def _node(script: str):+ if NODE is None:+ pytest.skip("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ assert r.returncode == 0, r.stderr[-3000:]+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class _H:+ def __init__(self, body: str = ""):+ self.body, self.out = body, None++ def _read_form_body(self):+ from urllib.parse import parse_qs+ return self.body, parse_qs(self.body)++ def _json(self, obj, code=200):+ self.out = (code, obj)+++# ---- UI-1: Sharp export only reads clips in outputs/ or uploads/ ----------+def sharp_env(tmp_path):+ saved = (p.PIPERSR_UPSCALE_ENABLED, p.persist_queue)+ p.PIPERSR_UPSCALE_ENABLED = True+ p.persist_queue = lambda: None+ with p.QUEUE_COND:+ before = list(p.STATE["queue"])+ dirs = []+ for root in (p.OUTPUT, p.UPLOADS):+ root.mkdir(parents=True, exist_ok=True)+ dirs.append(Path(tempfile.mkdtemp(prefix="ui1-", dir=root)))+ outside = tmp_path / "private"+ outside.mkdir()+ yield dirs, outside+ for d in dirs:+ shutil.rmtree(d, ignore_errors=True)+ p.PIPERSR_UPSCALE_ENABLED, p.persist_queue = saved+ with p.QUEUE_COND:+ p.STATE["queue"] = before+++def test_ui1_sharp_export_refuses_files_and_symlinks_outside_outputs_uploads(sharp_env):+ (out_dir, up_dir), outside = sharp_env+ secret = outside / "private.mp4"+ secret.write_bytes(b"\0" * 64)+ r = p.queue_sharp_export(str(secret))+ assert r["ok"] is False and "outputs or uploads" in r["error"]+ link = out_dir / "innocent.mp4" # a symlink in outputs/ escaping it+ link.symlink_to(secret)+ r = p.queue_sharp_export(str(link))+ assert r["ok"] is False and "outputs or uploads" in r["error"]+ h = _H(urlencode({"path": str(secret)}))+ POST_ROUTES["/queue/sharp_export"](h, "/queue/sharp_export", {}, "")+ assert h.out[0] == 400 and h.out[1]["ok"] is False+ with p.QUEUE_COND:+ assert not any((j.get("params") or {}).get("mode") == "sharp_export"+ and "private" in str(j["params"].get("source_path"))+ for j in p.STATE["queue"])+++def test_ui1_sharp_export_accepts_clips_in_both_roots(sharp_env):+ (out_dir, up_dir), _ = sharp_env+ for d in (out_dir, up_dir):+ clip = d / "ok.mp4"+ clip.write_bytes(b"\0" * 64)+ r = p.queue_sharp_export(str(clip))+ assert r["ok"] is True, r+++def test_ui1_sharp_export_revalidates_when_the_job_runs(sharp_env):+ _, outside = sharp_env+ secret = outside / "private.mp4"+ secret.write_bytes(b"\0" * 64)+ job = {"id": "j1", "params": {"mode": "sharp_export", "source_path": str(secret)},+ "started_at": None, "started_ts": None}+ ran = []+ with mock.patch.object(p, "run_pipersr_tracked", lambda *a, **k: ran.append(a)), \+ mock.patch.object(p, "_probe_video_dims", lambda path: (640, 480)):+ with pytest.raises(RuntimeError, match="outputs or uploads"):+ p.run_sharp_export_job_inner(job)+ assert ran == []+++# ---- UI-2 / UI-3: LTX Finish keeps the source's mode, aspect and export ----+QJS = (JS / "queue.js").read_text(encoding="utf-8")+CJS = (JS / "characters.js").read_text(encoding="utf-8")+EJS = (JS / "engines.js").read_text(encoding="utf-8")++_FINISH_DEPS = """+const CELLS = {+ balanced_5s: { key: 'balanced_5s', quality: 'balanced', length: '5s', width: 1024, height: 576,+ frames: 121, seconds: 5, label: 'Balanced · 5s', eta: '~3 min', available: true },+ standard_5s: { key: 'standard_5s', quality: 'standard', length: '5s', width: 1280, height: 704,+ frames: 121, seconds: 5, label: 'Standard · 5s', eta: '~5 min', available: true },+};+global.ltxTierByKeyExact = k => CELLS[k] || null;+global.ltxCellFor = (q, l) => CELLS[q + '_' + l] || null;+global._ltxLengthKeyForFrames = f => (f === 121 ? '5s' : null);+global.ltxFinishTierKey = src => (src.quality === 'balanced' ? 'standard_5s' : null);+global.ltxFinishTargets = src => (src.quality === 'balanced' ? [CELLS.standard_5s] : []);+global.escapeHtml = s => String(s);+"""+++def test_ui2_finish_refuses_every_mode_but_t2v_and_i2v():+ fns = "\n".join(extract_function(n, QJS) for n in+ ("ltxFinishFieldsFromSidecar", "_ltxFinishableMode", "_syncLtxFinishAffordance"))+ out = _node(_FINISH_DEPS + fns + """+const els = {};+global.document = { getElementById: id => (els[id] = els[id] || { style: {}, dataset: {} }) };+global.ltxFinishActive = () => {}; global.ltxFinishSetTier = () => {};+const base = { engine: 'ltx', prompt: 'x', seed_used: 7, width: 1024, height: 576,+ image: '/u/a.png', start_image: '/u/a.png', end_image: '/u/b.png' };+const res = {};+for (const m of ['keyframe', 'extend', 'a2v', 'i2v_clean_audio', 'remix', 't2v', 'i2v', undefined]) {+ const f = ltxFinishFieldsFromSidecar(Object.assign({}, base, { mode: m }), 'standard_5s');+ const o = { engine: 'ltx', quality: 'balanced', frames: 121, mode: m };+ res[String(m)] = [f ? f.mode : null, _syncLtxFinishAffordance(o)];+}+console.log(JSON.stringify(res));+""")+ for m in ("keyframe", "extend", "a2v", "i2v_clean_audio", "remix"):+ assert out[m] == [None, False], (m, out[m])+ assert out["t2v"] == ["t2v", True]+ assert out["i2v"] == ["i2v", True]+ assert out["undefined"] == ["t2v", True] # old sidecars with no mode = t2v+++def _finish_harness(sidecar: dict, form_aspect: str) -> dict:+ fns = "\n".join([+ extract_function("ltxFinishFieldsFromSidecar", QJS),+ extract_function("_ltxFinishableMode", QJS),+ extract_function("ltxFinishActive", QJS),+ extract_function("applyAspect", QJS),+ extract_function("_aspectDims", QJS),+ extract_function("setQuality", CJS),+ extract_function("setAspect", CJS),+ extract_function("setUpscale", CJS),+ extract_function("setUpscaleMethod", CJS),+ extract_function("_ltxApplyShape", EJS),+ ])+ return _node(_FINISH_DEPS + """+const els = {};+const el = id => (els[id] = els[id] || { id, value: '', style: {}, dataset: {}, classList: { toggle() {} } });+global.document = {+ getElementById: el, querySelectorAll: () => [], querySelector: () => null,+ body: { dataset: { engine: 'ltx' } },+};+global.window = global;+global.ASPECTS = { landscape: { w: 1280, h: 704 }, vertical: { w: 704, h: 1280 },+ square: { w: 768, h: 768 }, portrait_4_5: { w: 896, h: 1120 } };+global.QUALITY_PRESETS = {+ quick: { w: 640, h: 448, upscale: 'off' }, balanced: { w: 1024, h: 576, upscale: 'fit_720p' },+ standard: { w: 1280, h: 704, upscale: 'off' }, high: { w: 1024, h: 576, upscale: 'off' } };+global.PIPERSR_UPSCALE_ENABLED = true;+global.LAST_STATUS = null;+for (const n of ['applyQuality', 'updateAccelAvailability', 'updateTemporalAvailability',+ 'updateCustomizeSummary', 'updateDerived', 'renderTierAxes', 'workflowSwitch',+ 'setMode', '_restoreLoraPicker', '_syncSeedLockChip', 'syncAvoidRowFromValue',+ 'phosToast', 'pickerSetImage', '_setCropFocus']) global[n] = () => {};+global.setEngine = () => 'ltx';+global.activePath = '/out/clip.mp4';+global.findOutputByPath = () => ({ engine: 'ltx', quality: 'balanced', frames: 121, mode: SIDE.mode });+const SIDE = %s;+global.fetch = async () => ({ ok: true, json: async () => ({ params: SIDE }) });+el('aspect').value = %s;+let submitted = null;+el('genForm').requestSubmit = () => {+ submitted = { width: el('width').value, height: el('height').value, aspect: el('aspect').value,+ upscale: el('upscale').value, method: el('upscale_method').value,+ quality: el('quality').value };+};+%s+ltxFinishActive().then(() => console.log(JSON.stringify(submitted)));+""" % (json.dumps(sidecar), json.dumps(form_aspect), fns))+++def test_ui3_finish_submits_the_source_orientation_and_export():+ side = {"engine": "ltx", "mode": "t2v", "quality": "balanced", "frames": 121,+ "width": 1024, "height": 576, "prompt": "x", "seed_used": 9,+ "upscale": "fit_720p", "upscale_method": "pipersr"}+ got = _finish_harness(side, "vertical")+ assert got["quality"] == "standard"+ assert (got["width"], got["height"], got["aspect"]) == (1280, 704, "landscape")+ assert (got["upscale"], got["method"]) == ("fit_720p", "pipersr")+ # and the other way round: a portrait draft stays portrait with a landscape form+ side.update(width=576, height=1024)+ got = _finish_harness(side, "landscape")+ assert (got["width"], got["height"], got["aspect"]) == (704, 1280, "vertical")+ # a square draft stays square+ side.update(width=768, height=768)+ assert _finish_harness(side, "vertical")["aspect"] == "square"+++# ---- UI-4: Train's "Download all" runs every missing pack, in order --------+def test_ui4_download_all_button_starts_each_download_sequentially():+ fns = "\n".join(extract_function(n, CJS) for n in+ ("trainCheckPreflight", "trainInstallAll", "trainInstallAndWait"))+ out = _node("""+global.LAST_STATUS = { q8_available: true };+const btn = { disabled: false, textContent: '' };+const box = { style: {}, _html: '',+ set innerHTML(v) { this._html = v; }, get innerHTML() { return this._html; },+ querySelector(sel) { return (sel === '#trainInstallAllBtn' && this._html.includes('id="trainInstallAllBtn"')) ? btn : null; } };+global.document = { getElementById: id => (id === 'trainPreflight' ? box+ : id === 'trainInstallAllBtn' ? btn : null) };+global.fetch = async () => ({ json: async () => ({ ok: true, required: [+ { key: 'ltx23_dev', label: 'Dev transformer', size_gb: 21, blurb: 'x', ready: false },+ { key: 'ltx23_gemma', label: 'Text encoder', size_gb: 20, blurb: 'y', ready: false },+ { key: 'done_one', label: 'Z', size_gb: 1, blurb: 'z', ready: true }] }) });+const started = [];+let active = 0, overlap = false;+global.trainInstall = (key, onDone) => {+ started.push(key); active += 1; if (active > 1) overlap = true;+ setTimeout(() => { active -= 1; onDone(); }, 5);+};+""" + fns + """+(async () => {+ await trainCheckPreflight();+ // every inline handler left in the markup must at least be valid JS+ const bad = [];+ for (const m of box.innerHTML.matchAll(/onclick="([^"]*)"/g)) {+ try { new Function(m[1]); } catch (e) { bad.push(m[1]); }+ }+ let clicked = false;+ if (typeof btn.onclick === 'function') { clicked = true; await btn.onclick(); }+ global.trainCheckPreflight = async () => {};+ await new Promise(r => setTimeout(r, 50));+ console.log(JSON.stringify({ bad, clicked, started, overlap }));+})();+""")+ assert out["bad"] == []+ assert out["clicked"] is True+ assert out["started"] == ["ltx23_dev", "ltx23_gemma"]+ assert out["overlap"] is False+++# ---- UI-5: keys on a card's own buttons reach those buttons ----------------+def test_ui5_card_keydown_ignores_keys_aimed_at_nested_controls():+ import re+ i = QJS.index('class="car-card${o.path')+ tpl = QJS[i:QJS.index("</div>`;", i)]+ handler = re.search(r'onkeydown="([^"]*)"', tpl).group(1).replace("${pathAttr}", "'/o/c.mp4'")+ out = _node("""+const calls = [];+function selectOutput(p) { calls.push(p); }+const card = { tag: 'card' };+function run(key, target) {+ let prevented = false;+ const event = { key, target, currentTarget: card, preventDefault: () => { prevented = true; } };+ (function () { %s })();+ return prevented;+}+const res = {+ card_enter: run('Enter', card), card_space: run(' ', card),+ info_enter: run('Enter', { tag: 'button' }), trash_space: run(' ', { tag: 'button' }),+ audio_space: run(' ', { tag: 'audio' }),+};+res.calls = calls.length;+console.log(JSON.stringify(res));+""" % handler)+ assert out == {"card_enter": True, "card_space": True, "info_enter": False,+ "trash_space": False, "audio_space": False, "calls": 2}+++# ---- UI-6: crash reports = only this install's own, positively identified --+def _ips(path: Path, proc: str, images: list[str]) -> None:+ header = json.dumps({"app_name": path.name.split("-")[0], "bug_type": "309"})+ body = json.dumps({"procPath": proc, "procName": "python3.11",+ "usedImages": [{"path": x, "name": Path(x).name} for x in images]})+ path.write_text(header + "\n" + body, encoding="utf-8")+++def test_ui6_crash_count_and_zip_hold_only_phosphene_processes(tmp_path):+ import io+ import zipfile+ from panel.routes import GET_ROUTES+ routes_meta = sys.modules["panel.routes_meta"]+ diag = tmp_path / "Library" / "Logs" / "DiagnosticReports"+ diag.mkdir(parents=True)+ ours = str(p.ROOT / "ltx-2-mlx" / "env" / "lib" / "python3.11" / "site-packages"+ / "mlx" / "core.cpython-311-darwin.so")+ _ips(diag / "python3.11-2026-09-29-100000.ips", "/opt/uv/python3.11/bin/python3.11",+ ["/usr/lib/dyld", ours]) # the helper+ _ips(diag / "python3.12-2026-09-29-110000.ips", "/opt/homebrew/bin/python3.12",+ ["/usr/lib/dyld", "/Users/x/other-app/.venv/lib/site-packages/torch/_C.so"])+ _ips(diag / "Python-2026-09-29-120000.ips", "/Users/x/notebook/bin/python",+ ["/usr/lib/dyld"]) # another app+ (diag / "python3.11-2026-09-29-130000.ips").write_text("{}\nnot json", encoding="utf-8")+ _ips(diag / "Safari-2026-09-29-140000.ips", "/Applications/Safari.app", [ours])+ with mock.patch.object(p.Path, "home", classmethod(lambda cls: tmp_path)):+ h = _H()+ GET_ROUTES["/panel/bug-context"](h, None)+ assert h.out[1]["crashCount"] == 1+ body = json.dumps({"title": "t", "body": "b", "includeCrashReports": True}).encode()+ h = _H()+ h.headers = {"Content-Length": str(len(body))}+ h.rfile = io.BytesIO(body)+ POST_ROUTES["/panel/bug-report"](h, "/panel/bug-report", {}, "application/json")+ zp = h.out[1]["zipPath"]+ assert zp, h.out+ with zipfile.ZipFile(zp) as zf:+ assert zf.namelist() == ["python3.11-2026-09-29-100000.ips"]+ shutil.move(str(Path(zp).parent), str(tmp_path / "zipdir")) # keep /tmp clean+ assert routes_meta._phosphene_crash_reports(diag)[0].name.startswith("python3.11-2026-09-29-10")+++# ---- UI-7: status polls never re-show Style training's hidden Voice card --+def test_ui7_ram_gate_leaves_feature_owned_visibility_alone():+ fn = extract_function("trainApplyRamGate", CJS)+ out = _node("""+const mk = id => ({ id, hidden: false, textContent: '' });+const card = mk('trainGateCard'), voice = mk('trainVoiceCard'), drop = mk('trainDropCard');+const classes = new Set();+const section = { children: [card, drop, voice],+ classList: { toggle(c, on) { if (on) classes.add(c); else classes.delete(c); } } };+const els = { trainGateCard: card, trainSection: section, trainVoiceCard: voice,+ trainGateTitle: mk('t'), trainGateBody: mk('b') };+global.document = { getElementById: id => els[id] || null };+global.LAST_STATUS = { tier: { ram_gb: 64, train_min_ram_gb: 24 } };+""" + fn + """+voice.hidden = true; // setTrainType('style')+for (let i = 0; i < 3; i++) trainApplyRamGate(); // three status polls+const roomy = { voice: voice.hidden, drop: drop.hidden, card: card.hidden, gated: classes.has('train-ram-gated') };+LAST_STATUS.tier.ram_gb = 16;+const gatedRet = trainApplyRamGate();+const small = { voice: voice.hidden, drop: drop.hidden, card: card.hidden, gated: classes.has('train-ram-gated'), ret: gatedRet };+console.log(JSON.stringify({ roomy, small }));+""")+ assert out["roomy"] == {"voice": True, "drop": False, "card": True, "gated": False}+ assert out["small"] == {"voice": True, "drop": False, "card": False, "gated": True, "ret": True}+ css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+ assert "#trainSection.train-ram-gated > :not(#trainGateCard) { display: none !important; }" in css+++# ---- UI-8 / EST-12: gallery size = the saved file's own dimensions ---------+def _box(t: bytes, payload: bytes) -> bytes:+ import struct+ return struct.pack(">I4s", 8 + len(payload), t) + payload+++def _tkhd(w: int, h: int, version: int = 0) -> bytes:+ import struct+ head = bytes([version, 0, 0, 7]) + b"\0" * (20 if version == 0 else 32)+ return _box(b"tkhd", head + b"\0" * 8 + b"\0" * 8 + b"\0" * 36+ + struct.pack(">II", w << 16, h << 16))+++def _fake_mp4(path: Path, w: int, h: int, *, version: int = 0, moov_last: bool = True) -> None:+ moov = _box(b"moov", _box(b"mvhd", b"\0" * 100)+ + _box(b"trak", _tkhd(0, 0, version)) # the audio track+ + _box(b"trak", _tkhd(w, h, version))) # the video track+ parts = [_box(b"ftyp", b"isom\0\0\0\0isom"), _box(b"mdat", b"\x55" * 50000)]+ parts.insert(2 if moov_last else 1, moov)+ path.write_bytes(b"".join(parts))+++def test_ui8_list_outputs_reports_each_files_own_dimensions():+ d = Path(tempfile.mkdtemp(prefix="ui8-", dir=p.OUTPUT))+ try:+ cases = {"square": (768, 768, 0, True), "portrait": (704, 1280, 1, False),+ "native": (1024, 576, 0, True), "fit": (1280, 720, 0, False),+ "sharp": (2048, 1152, 1, True)}+ for name, (w, h, ver, last) in cases.items():+ clip = p.OUTPUT / f"ui8_{name}_{d.name}.mp4"+ _fake_mp4(clip, w, h, version=ver, moov_last=last)+ os.utime(clip, (1_700_000_000, 1_700_000_000)) # past the in-flight cutoff+ # every sidecar claims a landscape Balanced render — the card must not care+ Path(str(clip) + ".json").write_text(json.dumps({"params": {+ "mode": "t2v", "quality": "balanced", "frames": 121,+ "width": 1024, "height": 576, "upscale": "fit_720p"}}), encoding="utf-8")+ garbage = p.OUTPUT / f"ui8_garbage_{d.name}.mp4"+ garbage.write_bytes(b"not an mp4 at all")+ os.utime(garbage, (1_700_000_000, 1_700_000_000))+ rows = {o["name"]: o for o in p.list_outputs(limit=0)}+ for name, (w, h, _, _) in cases.items():+ o = rows[f"ui8_{name}_{d.name}.mp4"]+ assert (o["width"], o["height"]) == (w, h), name+ g = rows[garbage.name]+ assert (g["width"], g["height"]) == (None, None)+ # a clip replaced at the same path re-reads (cache keyed on mtime/size)+ sq = p.OUTPUT / f"ui8_square_{d.name}.mp4"+ _fake_mp4(sq, 896, 1120, moov_last=False)+ os.utime(sq, (1, 1))+ assert p._output_dims(sq) == (896, 1120)+ finally:+ for f in p.OUTPUT.glob(f"ui8_*_{d.name}.mp4*"):+ f.unlink()+ shutil.rmtree(d, ignore_errors=True)++[email protected](shutil.which("ffmpeg") is None, reason="ffmpeg not on PATH")+def test_ui8_reads_a_real_ffmpeg_file():+ with tempfile.TemporaryDirectory() as td:+ clip = Path(td) / "real.mp4"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=704x1280:d=0.2",+ "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-shortest",+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", str(clip)], check=True)+ assert p._mp4_display_dims(clip) == (704, 1280)+++def test_ui8_card_chip_prints_the_files_size_or_none():+ fn = extract_function("_cardModeSizeChip", QJS)+ out = _node("""+const BOOT = { ltx: { qualities: [{ key: 'balanced', canvas: '1024×576', delivered_canvas: '1280×720' }] } };+function h3TierByKeyExact() { return { spec: '1344×768', width: 1344, height: 768 }; }+""" + fn + """+console.log(JSON.stringify([+ _cardModeSizeChip({ mode: 't2v', quality: 'balanced', width: 768, height: 768 }),+ _cardModeSizeChip({ mode: 't2v', quality: 'balanced', width: 704, height: 1280 }),+ _cardModeSizeChip({ mode: 'i2v', h3_tier: 'high_5s', width: 768, height: 448 }),+ _cardModeSizeChip({ mode: 't2v', quality: 'balanced', width: null, height: null })]));+""")+ assert out == ["t2v · 768×768", "t2v · 704×1280", "i2v · 768×448", "t2v"]+++# ---- UI-9: a replaced clip gets a new poster URL ---------------------------+def test_ui9_poster_url_changes_when_the_source_changes():+ fn = extract_function("_posterVersionQuery", (JS / "queue.js").read_text(encoding="utf-8"))+ out = _node(fn + """+const a = { path: '/o/c.mp4', url: '/file?path=%2Fo%2Fc.mp4&v=1700000000', size_mb: 1.5 };+const b = Object.assign({}, a, { url: '/file?path=%2Fo%2Fc.mp4&v=1700000123' }); // re-rendered+const c = Object.assign({}, a, { size_mb: 1.75 }); // same second, new bytes+console.log(JSON.stringify([_posterVersionQuery(a), _posterVersionQuery(b), _posterVersionQuery(c),+ _posterVersionQuery({ path: '/o/x.mp4' })]));+""")+ assert out[0] == "&v=1700000000-1572864"+ assert len(set(out[:3])) == 3+ assert out[3] == ""+ qjs = (JS / "queue.js").read_text(encoding="utf-8")+ assert 'src="/poster?path=${encodeURIComponent(o.path)}${_posterVersionQuery(o)}"' in qjs+++# ---- UI-10: a refused restart leaves "Restart now" usable -------------------+def test_ui10_refused_restart_rearms_the_banner_button():+ hjs = (JS / "health.js").read_text(encoding="utf-8")+ fns = extract_function("_ubRestartState", hjs) + "\n" + extract_function("panelRestart", hjs)+ out = _node("""+const mk = () => ({ hidden: false, disabled: false, textContent: '', classList: { add() {} } });+const els = { updateBanner: mk(), ubStar: mk(), ubTitle: mk(), ubSub: mk(), ubUpdate: mk(), ubLater: mk(), versionPill: mk() };+global.document = { getElementById: id => els[id] || null };+global._uiEvent = () => {};+const toasts = [];+global.phosToast = (t) => toasts.push(t);+let reloaded = false;+global.location = { reload: () => { reloaded = true; } };+const replies = [+ { status: 409, body: { ok: false, error: 'A render is running — stop it first.' } },+ { status: 200, body: { ok: true } },+];+global.fetch = async (url) => {+ if (url === '/version') return { ok: true };+ const r = replies.shift();+ return { status: r.status, json: async () => r.body };+};+global.setTimeout = (fn) => fn();+""" + fns + """+(async () => {+ _ubRestartState('4.17.0', false);+ const go = els.ubUpdate;+ await go.onclick();+ const afterRefusal = { disabled: go.disabled, label: go.textContent };+ await go.onclick();+ console.log(JSON.stringify({ afterRefusal, reloaded, toasts: toasts.length }));+})();+""")+ assert out["afterRefusal"] == {"disabled": False, "label": "Restart now"}+ assert out["reloaded"] is True # the second click restarts for real+ assert out["toasts"] == 1diff --git a/test_deliver.py b/test_deliver.pyindex 1ed2650..eeec0b9 100644--- a/test_deliver.py+++ b/test_deliver.py@@ -60,6 +60,119 @@ class TheChoice(unittest.TestCase):self.assertNotIn("+faststart", p)+class TheLoudness(unittest.TestCase):+ """FILM-28: loudnorm is a fourth, independent delivery axis — off by+ default, on request it names the file, labels the pill, and appends+ one `-af loudnorm` pass after the mix ffmpeg already built."""++ def test_off_by_default_and_not_in_the_label(self):+ d = panel._sb_deliver("h264", "native")+ self.assertEqual(d["loudnorm"], False)+ self.assertNotIn("LUFS", d["label"])++ def test_on_asks_for_minus_14_lufs_and_says_so(self):+ d = panel._sb_deliver("h264", "1080p", None, True)+ self.assertEqual(d["loudnorm"], True)+ self.assertEqual(d["label"], "H.264 · 1080p · -14 LUFS")++ def test_it_does_not_rename_the_file(self):+ # Unlike format/size/finish, loudnorm is not a different picture —+ # it's the same file, just leveled. Naming it would mean a repeat+ # render with loudnorm toggled silently orphans the un-leveled one+ # instead of replacing it.+ b = {"title": "The car wash"}+ self.assertEqual(+ panel._sb_film_name(b, panel._sb_deliver("h264", "native", None, True)),+ panel._sb_film_name(b, panel._sb_deliver("h264", "native", None, False)))++ def test_the_assembler_appends_one_loudnorm_link_only_when_asked(self):+ info = {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,+ "sample_rate": 48000}+ seen = {}++ def fake_ffmpeg(cmd, label):+ seen["cmd"] = cmd+ Path(cmd[-1]).write_bytes(b"x")+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(panel, "_sb_probe_clip", return_value=info), \+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \+ mock.patch.object(panel, "_sb_write_film_sidecar"):+ panel._sb_assemble_film(+ ["/x/a.mp4"], Path(d) / "f.mp4",+ timeline=[{"path": "/x/a.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0}],+ deliver={"format": "h264", "size": "native", "loudnorm": True})+ cmd = seen["cmd"]+ # EDITOR-2 (Codex 4.17.0): NOT `-af` on the mapped stream — ffmpeg+ # refuses simple filtering on a stream fed from -filter_complex. One+ # link appended to the graph after the final mix, and its label is+ # what gets mapped.+ self.assertNotIn("-af", cmd)+ graph = cmd[cmd.index("-filter_complex") + 1]+ self.assertEqual(graph.count("loudnorm"), 1)+ self.assertTrue(graph.endswith(";[aout]loudnorm=I=-14:TP=-1.5:LRA=11[aoutln]"))+ maps = [cmd[i + 1] for i, a in enumerate(cmd) if a == "-map"]+ self.assertIn("[aoutln]", maps)+ self.assertNotIn("[aout]", maps)++ def test_off_leaves_the_old_command_untouched(self):+ info = {"has_audio": True, "duration": 10.0, "w": 768, "h": 416,+ "sample_rate": 48000}+ seen = {}++ def fake_ffmpeg(cmd, label):+ seen["cmd"] = cmd+ Path(cmd[-1]).write_bytes(b"x")+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(panel, "_sb_probe_clip", return_value=info), \+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \+ mock.patch.object(panel, "_sb_write_film_sidecar"):+ panel._sb_assemble_film(+ ["/x/a.mp4"], Path(d) / "f.mp4",+ timeline=[{"path": "/x/a.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0}], deliver=None)+ self.assertNotIn("-af", seen["cmd"])+ self.assertNotIn("loudnorm", " ".join(seen["cmd"]))+ self.assertIn("[aout]", seen["cmd"])+++class TheVersioning(unittest.TestCase):+ """FILM-28: a second render at the same delivery gets `_r2`, not a+ silent overwrite of the first."""++ def test_dest_none_keeps_every_caller_byte_for_byte(self):+ b = {"title": "The car wash"}+ self.assertEqual(panel._sb_film_name(b), "the-car-wash_film.mp4")++ def test_first_render_takes_the_plain_name(self):+ b = {"title": "The car wash"}+ with tempfile.TemporaryDirectory() as d:+ self.assertEqual(panel._sb_film_name(b, dest=Path(d)),+ "the-car-wash_film.mp4")++ def test_repeat_renders_at_the_same_delivery_count_up(self):+ b = {"title": "The car wash"}+ with tempfile.TemporaryDirectory() as d:+ dest = Path(d)+ (dest / "the-car-wash_film.mp4").write_bytes(b"x")+ self.assertEqual(panel._sb_film_name(b, dest=dest),+ "the-car-wash_film_r2.mp4")+ (dest / "the-car-wash_film_r2.mp4").write_bytes(b"x")+ self.assertEqual(panel._sb_film_name(b, dest=dest),+ "the-car-wash_film_r3.mp4")++ def test_versioning_is_per_delivery_not_global(self):+ b = {"title": "The car wash"}+ with tempfile.TemporaryDirectory() as d:+ dest = Path(d)+ (dest / "the-car-wash_film.mp4").write_bytes(b"x")+ # A different delivery (HEVC) is a different name and so gets+ # the plain name, not "_r2" — the counters don't share state.+ self.assertEqual(+ panel._sb_film_name(b, panel._sb_deliver("hevc", None), dest=dest),+ "the-car-wash_film_hevc.mp4")++class TheGraph(unittest.TestCase):def test_no_size_is_the_graph_it_always_was(self):with mock.patch.object(panel, "bt709_vf", return_value=""):@@ -149,7 +262,10 @@ class TheRoute(unittest.TestCase):self.assertEqual(h.status, 200, h.payload)kw = rend.call_args.kwargsself.assertEqual(kw["out_name"], "the-car-wash_film_prores_2160p.mov")- self.assertEqual(kw["deliver"], {"format": "prores", "size": "2160p", "finish": ""})+ # FILM-28: loudnorm rides the same deliver dict, off unless the+ # client sends `loudnorm=on`.+ self.assertEqual(kw["deliver"], {"format": "prores", "size": "2160p",+ "finish": "", "loudnorm": False})if __name__ == "__main__":diff --git a/test_derived_summary_merge.py b/test_derived_summary_merge.pynew file mode 100644index 0000000..f3f70d6--- /dev/null+++ b/test_derived_summary_merge.py@@ -0,0 +1,157 @@+"""VC-27: the same render summary no longer prints three times, and the one+line that's left (the sticky footer, right above Generate) carries the+quality label and the ETA.++WHAT THIS GUARDS. A plain Balanced 5s T2V render showed essentially the+same numbers in three places at once:+ - the Shot-setup disclosure's collapsed summary ("Balanced · 5s · 16:9 ·+ ~3 min") - a real `<summary>` collapsed-state indicator, kept+ - a standalone always-visible box, #derived ("Duration 5.00s @ 24fps ·+ 1024x576 -> 1280x720 fit · Steps 8") - never inside any collapsed+ disclosure, so nothing was lost by dropping it; removed outright+ - the sticky footer's own line, #derivedFooter ("5.00s · 1024x576 ->+ 1280x720 fit") - kept, and now the one true summary++Removing #derived wins back real vertical space at 1280-1440px (VC-09) and+ends the duplication. The surviving footer line was upgraded to match the+finding's own suggested shape - "Balanced · 5 s · 1280x720 · ~3 min" -+reading its quality label and ETA from the SAME cell the quality chip+strip renders from (engines.js's ltxCurrentCell/ltxCellEta), so it cannot+disagree with what the chips themselves say.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+JS_DIR = ROOT / "webapp" / "js"+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class TheStandaloneDuplicateIsGone(unittest.TestCase):+ def test_derived_div_removed_from_markup(self):+ self.assertNotIn('id="derived"', HTML)+ self.assertNotIn('class="derived"', HTML)++ def test_derived_css_rule_removed(self):+ self.assertNotRegex(CSS, r"\n\s*\.derived\s*\{")++ def test_update_derived_no_longer_writes_it(self):+ src = (JS_DIR / "queue.js").read_text(encoding="utf-8")+ fn = extract_function("updateDerived", src)+ self.assertNotIn("getElementById('derived')", fn)+ self.assertNotIn('getElementById("derived")', fn)++ def test_the_two_real_disclosure_summaries_survive(self):+ """#shotSetupSummary and #customizeSummary are <summary> collapsed-+ state text for their OWN <details> - not the redundant box - and+ must not have been swept up by the same cleanup."""+ self.assertIn('id="shotSetupSummary"', HTML)+ self.assertIn('id="customizeSummary"', HTML)+++DOM_SHIM = r"""+function makeEl(id, value) {+ return { id, value, textContent: '', innerHTML: '', hidden: false,+ classList: { toggle(){}, add(){}, remove(){} },+ addEventListener(){}, getAttribute(){ return null; },+ dataset: {}, style: {} };+}+const FIELDS = {+ mode: 't2v', width: '1024', height: '576', frames: '121',+ steps: '8', upscale: 'fit_720p', accel: 'off', temporal_mode: 'native',+ extend_seconds: '2', extend_direction: 'after', extend_frames: '6',+ derivedFooter: '', qualityMeta: '', warnBanner: '',+};+const ELS = {};+for (const [id, value] of Object.entries(FIELDS)) ELS[id] = makeEl(id, value);+ELS.warnBanner.classList = { _cls: new Set(), add(c){this._cls.add(c);}, remove(c){this._cls.delete(c);}, toggle(){} };+global.document = {+ getElementById: (id) => (ELS[id] || (ELS[id] = makeEl(id, ''))),+ querySelector: () => null,+ body: { dataset: { engine: 'ltx' } },+};+global.escapeHtml = (s) => String(s);+global.framesToDuration = (f) => (f > 1 ? (f - 1) / 24 : 0).toFixed(2);+global.FPS = 24;+global.renderKeyframeDynamicSlots = () => {};+global.syncKeyframeTiming = () => {};+global.maybeScaleTouchedKeyframeTiming = () => {};+global._updateKeyframeFramesGate = () => {};+global.window = { _kfTimingLastFrames: 0 };+"""+++class FooterLineCarriesQualityAndEta(unittest.TestCase):+ def _updateDerived_src(self) -> str:+ src = (JS_DIR / "queue.js").read_text(encoding="utf-8")+ return extract_function("updateDerived", src)++ def _run(self, mode: str, *, cell) -> str:+ fn = self._updateDerived_src()+ script = DOM_SHIM + f"""+global.currentMode = {json.dumps(mode)};+ELS.mode.value = {json.dumps(mode)};+global.ltxCurrentCell = () => ({json.dumps(cell)});+global.ltxCellEta = (c) => c && c.eta || '';+{fn}+updateDerived();+console.log(JSON.stringify({{ footer: ELS.derivedFooter.innerHTML }}));+"""+ return _run_node(script)["footer"]++ def test_t2v_footer_matches_the_findings_own_example_shape(self):+ cell = {"quality_label": "Balanced", "eta": "~3 min"}+ footer = self._run("t2v", cell=cell)+ self.assertIn("Balanced", footer)+ self.assertIn("5.00s", footer)+ self.assertIn("1280×720", footer)+ self.assertIn("~3 min", footer)++ def test_i2v_also_gets_the_quality_line(self):+ cell = {"quality_label": "Standard", "eta": "~7 min"}+ footer = self._run("i2v", cell=cell)+ self.assertIn("Standard", footer)+ self.assertIn("~7 min", footer)++ def test_no_cell_falls_back_to_the_plain_line(self):+ footer = self._run("t2v", cell=None)+ self.assertIn("5.00s", footer)+ self.assertNotIn("undefined", footer)++ def test_other_modes_are_unaffected(self):+ """Restore/Control/etc. don't sit on the quality ladder - keep the+ plain dimensions+duration line, cell or not."""+ cell = {"quality_label": "Balanced", "eta": "~3 min"}+ footer = self._run("restore", cell=cell)+ self.assertNotIn("Balanced", footer)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_director.py b/test_director.pyindex 0651bed..09d2013 100644--- a/test_director.py+++ b/test_director.py@@ -205,12 +205,20 @@ class TheAutoPipeline(unittest.TestCase):{"n": 2, "status": "skipped"},{"n": 3, "final_output": "/x/c.mp4"}]}edit = {"version": 2, "clips": [{"id": "a"}, {"id": "c"}], "beats": {"bpm": 120}}+ # FILM-20: the final save now goes through _sb_patch_board, which+ # RE-LOADS the board rather than trusting this in-memory copy — the+ # whole point being that anything changed on disk in the meantime+ # (here: nothing) is what gets `auto_film` patched onto it, not this+ # possibly-stale object. load_storyboard is mocked to hand back an+ # equivalent copy of the board, as it would from disk.with mock.patch.object(panel, "_sbe_auto_edit", return_value=edit) as ae, \mock.patch.object(panel, "_sbe_board_dir", return_value=Path("/tmp/x")), \mock.patch("storyboard_editor.save_edit") as save, \mock.patch("storyboard_editor.load_edit", return_value=edit), \mock.patch.object(panel, "_sbe_render_edit",return_value={"ok": True, "path": "/x/film.mp4"}) as rend, \+ mock.patch.object(panel.storyboard, "load_storyboard",+ return_value=dict(board, shots=list(board["shots"]))) as sb_load, \mock.patch.object(panel.storyboard, "save_storyboard") as sb_save, \mock.patch.object(panel, "push"):film = panel._sb_auto_film(board)@@ -218,5 +226,7 @@ class TheAutoPipeline(unittest.TestCase):save.assert_called_once()rend.assert_called_once()self.assertEqual(film["path"], "/x/film.mp4")- self.assertEqual(board["auto_film"], "/x/film.mp4")+ sb_load.assert_called_once_with(panel.STATE_DIR, "b")sb_save.assert_called_once()+ saved_board = sb_save.call_args[0][1]+ self.assertEqual(saved_board["auto_film"], "/x/film.mp4")diff --git a/test_docs_and_shortcuts.py b/test_docs_and_shortcuts.pyindex 8690088..4486862 100644--- a/test_docs_and_shortcuts.py+++ b/test_docs_and_shortcuts.py@@ -162,7 +162,7 @@ _KEY = {"space": " ", "escape": "Escape", "backspace": "Backspace", "delete": "D"arrowleft": "ArrowLeft", "arrowright": "ArrowRight", "arrowup": "ArrowUp","arrowdown": "ArrowDown", "home": "Home", "end": "End", "plus": "+", "minus": "-","equals": "=", "underscore": "_", "backslash": "\\", "enter": "Enter",- "backquote": "`"}+ "backquote": "`", "comma": ",", "period": "."}# State each row needs for its branch to be the one that answers._STATE = {diff --git a/test_editor_film_findings.py b/test_editor_film_findings.pynew file mode 100644index 0000000..4536867--- /dev/null+++ b/test_editor_film_findings.py@@ -0,0 +1,350 @@+#!/usr/bin/env python3+"""The FILM package (2026-09-29 mega review): slip and roll edits, the frame+timecode, takes/replace, and the toast that stops stacking.++Locked here:+ * FILM-03 — `sbeSlip` moves `start`/`end` together and leaves `film_start`/+ `film_end` alone, clamped to the source; `sbeRollEdit` moves a shared cut+ without moving the pair's total length; a repeated identical toast bumps+ a counter instead of stacking a new element.+ * FILM-52 — `sbeFmtTC` is HH:MM:SS:FF at the given fps.+ * FILM-07/08 — `sbeReplaceClip` keeps the slot (`film_start`/`film_end`,+ adjustments, fades) and only swaps the source window.++Run: ./ltx-2-mlx/env/bin/python3.11 -m pytest -q test_editor_film_findings.py+"""+from __future__ import annotations++import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++from test_storyboard_editor_ui import (FUNCTIONS, NODE, SHIM, # noqa: E402+ extract_function, panel_source)+++def _clip(cid, path, start, end, film_start, **kw):+ c = {"id": cid, "path": path, "start": start, "end": end,+ "film_start": film_start, "film_end": film_start + (end - start),+ "source": "human", "locked": False}+ c.update(kw)+ return c+++def run_client(body: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = panel_source()+ script = (SHIM + "\n".join(extract_function(n, src) for n in FUNCTIONS)+ + "\nconst out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out));\n")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = subprocess.run([NODE, str(path)], capture_output=True,+ text=True, timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)+++# =============================================================================+# FILM-52 — frame timecode+# =============================================================================+class TheTimecode(unittest.TestCase):+ def test_hh_mm_ss_ff(self):+ r = run_client("""+out.zero = sbeFmtTC(0, 24);+out.one_frame = sbeFmtTC(1 / 24, 24);+out.round_trip = sbeFmtTC(171.96, 24); // 2:51.96 from the report+out.hour = sbeFmtTC(3661.5, 24);+""")+ self.assertEqual(r["zero"], "00:00:00:00")+ self.assertEqual(r["one_frame"], "00:00:00:01")+ self.assertEqual(r["round_trip"], "00:02:51:23")+ self.assertEqual(r["hour"], "01:01:01:12")++ def test_default_fps_is_24_never_zero(self):+ r = run_client("out.v = sbeFmtTC(1, 0);")+ self.assertEqual(r["v"], "00:00:01:00")+++# =============================================================================+# FILM-03 — SLIP+# =============================================================================+class TheSlip(unittest.TestCase):+ def test_slip_moves_the_window_not_the_slot(self):+ clips = [_clip("a", "/x/a.mp4", 2.0, 6.0, 0.0, duration=10.0)]+ r = run_client("out.r = sbeSlip(%s, 'a', 1.0);" % json.dumps(clips))+ self.assertTrue(r["r"]["ok"])+ c = r["r"]["clips"][0]+ self.assertAlmostEqual(c["start"], 3.0)+ self.assertAlmostEqual(c["end"], 7.0)+ self.assertAlmostEqual(c["film_start"], 0.0)+ self.assertAlmostEqual(c["film_end"], 4.0)++ def test_slip_clamps_to_the_source(self):+ clips = [_clip("a", "/x/a.mp4", 2.0, 6.0, 0.0, duration=10.0)]+ r = run_client("out.r = sbeSlip(%s, 'a', 100);" % json.dumps(clips))+ c = r["r"]["clips"][0]+ self.assertAlmostEqual(c["start"], 6.0) # duration(10) - len(4)+ self.assertAlmostEqual(c["end"], 10.0)++ def test_slip_at_the_wall_refuses_cleanly(self):+ clips = [_clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, duration=10.0)]+ r = run_client("out.r = sbeSlip(%s, 'a', -1);" % json.dumps(clips))+ self.assertFalse(r["r"]["ok"])+ self.assertIn("start", r["r"]["why"])++ def test_slip_refuses_a_locked_clip(self):+ clips = [_clip("a", "/x/a.mp4", 2.0, 6.0, 0.0, duration=10.0, locked=True)]+ r = run_client("out.r = sbeSlip(%s, 'a', 1.0);" % json.dumps(clips))+ self.assertFalse(r["r"]["ok"])+ self.assertEqual(r["r"]["why"], "locked")+++# =============================================================================+# FILM-03 — ROLL+# =============================================================================+class TheRoll(unittest.TestCase):+ def test_roll_moves_the_cut_without_moving_the_pair(self):+ # a: 0..4 of a 10s take, b: 4..7 of a 10s take, sharing the cut at 4.+ a = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, duration=10.0)+ b = _clip("b", "/x/b.mp4", 0.0, 3.0, 4.0, duration=10.0)+ r = run_client("out.r = sbeRollEdit(%s, 'a', 'b', 1.0);"+ % json.dumps([a, b]))+ self.assertTrue(r["r"]["ok"])+ ca, cb = r["r"]["clips"]+ self.assertAlmostEqual(ca["film_end"], 5.0)+ self.assertAlmostEqual(cb["film_start"], 5.0)+ # The pair's total span and each one's HEAD did not move.+ self.assertAlmostEqual(ca["film_start"], 0.0)+ self.assertAlmostEqual(cb["film_end"], 7.0)+ self.assertAlmostEqual(ca["end"], 5.0) # grew into its own take+ self.assertAlmostEqual(cb["start"], 1.0) # gave up its head++ def test_roll_refuses_two_clips_that_do_not_share_a_cut(self):+ a = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, duration=10.0)+ b = _clip("b", "/x/b.mp4", 0.0, 3.0, 5.0, duration=10.0) # 1s hole+ r = run_client("out.r = sbeRollEdit(%s, 'a', 'b', 1.0);"+ % json.dumps([a, b]))+ self.assertFalse(r["r"]["ok"])++ def test_roll_clamps_to_the_shorter_sides_room(self):+ a = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, duration=4.0) # no tail room+ b = _clip("b", "/x/b.mp4", 0.0, 3.0, 4.0, duration=10.0)+ r = run_client("out.r = sbeRollEdit(%s, 'a', 'b', 2.0);"+ % json.dumps([a, b]))+ self.assertFalse(r["r"]["ok"]) # a has nothing more to give+++# =============================================================================+# FILM-04 — the song as master clock+# =============================================================================+class TheSongClock(unittest.TestCase):+ def test_master_only_when_replace_and_playing(self):+ r = run_client("""+SBE.audio = { mode: 'replace', offset: 0 };+SBE.musicOk = true;+SBE.musicEl = { currentTime: 5, paused: false };+out.a = sbeMusicMaster();+SBE.musicEl.paused = true;+out.b = sbeMusicMaster();+SBE.musicEl.paused = false;+SBE.audio.mode = 'under';+out.c = sbeMusicMaster();+SBE.audio.mode = 'replace';+SBE.musicOk = false;+out.d = sbeMusicMaster();+""")+ self.assertEqual([r["a"], r["b"], r["c"], r["d"]], [True, False, False, False])++ def test_song_playhead_is_the_inverse_of_music_at(self):+ r = run_client("""+SBE.audio = { mode: 'replace', offset: 0, trim_start: 0 };+SBE.peaks = { duration: 100 };+SBE.musicEl = { currentTime: 12.5, paused: false };+out.t = sbeSongPlayhead();+out.roundtrip = sbeMusicAt(out.t);+""")+ self.assertAlmostEqual(r["t"], 12.5)+ self.assertAlmostEqual(r["roundtrip"], 12.5)++ def test_song_playhead_honours_a_head_trim(self):+ r = run_client("""+SBE.audio = { mode: 'replace', offset: 0, trim_start: 3.0 };+SBE.peaks = { duration: 100 };+SBE.musicEl = { currentTime: 3.0, paused: false };+out.at_head = sbeSongPlayhead();+SBE.musicEl.currentTime = 10.0;+out.later = sbeSongPlayhead();+""")+ self.assertAlmostEqual(r["at_head"], 3.0)+ self.assertAlmostEqual(r["later"], 10.0)++ def test_song_playhead_is_null_once_the_song_runs_out(self):+ r = run_client("""+SBE.audio = { mode: 'replace', offset: 0 };+SBE.peaks = { duration: 20 };+SBE.musicEl = { currentTime: 25, paused: false };+out.t = sbeSongPlayhead();+""")+ self.assertIsNone(r["t"])+++# =============================================================================+# FILM-07/08 — REPLACE keeps the slot+# =============================================================================+class TheReplace(unittest.TestCase):+ def test_replace_keeps_the_slot_and_swaps_the_source(self):+ clips = [_clip("a", "/x/old.mp4", 1.0, 4.0, 10.0, duration=20.0,+ adjust={"brightness": 0.2}, fx={"fade_in": 0.5})]+ item = {"path": "/x/new.mp4", "duration_s": 8.0, "n": 3}+ r = run_client("out.r = sbeReplaceClip(%s, 'a', %s);"+ % (json.dumps(clips), json.dumps(item)))+ self.assertTrue(r["r"]["ok"])+ c = r["r"]["clips"][0]+ self.assertEqual(c["path"], "/x/new.mp4")+ self.assertAlmostEqual(c["film_start"], 10.0)+ self.assertAlmostEqual(c["film_end"], 13.0) # slot unchanged: 3s+ self.assertAlmostEqual(c["end"] - c["start"], 3.0)+ self.assertEqual(c["adjust"], {"brightness": 0.2})+ self.assertEqual(c["fx"], {"fade_in": 0.5})++ def test_replace_clamps_the_in_point_to_a_shorter_take(self):+ clips = [_clip("a", "/x/old.mp4", 5.0, 10.0, 0.0, duration=30.0)] # 5s slot+ item = {"path": "/x/short.mp4", "duration_s": 7.0}+ r = run_client("out.r = sbeReplaceClip(%s, 'a', %s);"+ % (json.dumps(clips), json.dumps(item)))+ c = r["r"]["clips"][0]+ self.assertAlmostEqual(c["start"], 2.0)+ self.assertAlmostEqual(c["end"], 7.0)+ self.assertAlmostEqual(c["film_start"], 0.0)+ self.assertAlmostEqual(c["film_end"], 5.0) # the slot itself is untouched++ def test_replace_refuses_a_take_shorter_than_the_slot(self):+ # EDITOR-4 (Codex 4.17.0): this used to answer ok with a 4 s window+ # in a 5 s slot — a document Save refuses as clip_length_mismatch.+ clips = [_clip("a", "/x/old.mp4", 5.0, 10.0, 0.0, duration=30.0)] # 5s slot+ item = {"path": "/x/short.mp4", "duration_s": 4.0}+ r = run_client("out.r = sbeReplaceClip(%s, 'a', %s);"+ % (json.dumps(clips), json.dumps(item)))+ self.assertFalse(r["r"]["ok"])+ self.assertIn("longer take", r["r"]["why"])+ self.assertEqual(r["r"]["clips"][0]["path"], "/x/old.mp4")++ def test_replace_refuses_a_locked_clip(self):+ clips = [_clip("a", "/x/old.mp4", 0.0, 3.0, 0.0, duration=10.0, locked=True)]+ item = {"path": "/x/new.mp4", "duration_s": 10.0}+ r = run_client("out.r = sbeReplaceClip(%s, 'a', %s);"+ % (json.dumps(clips), json.dumps(item)))+ self.assertFalse(r["r"]["ok"])+ self.assertEqual(r["r"]["why"], "locked")+++# =============================================================================+# FILM-03 — toast de-duplication+# =============================================================================+TOAST_SHIM = r"""+'use strict';+class FakeClassList {+ constructor() { this._s = new Set(); }+ add(...c) { c.forEach(x => this._s.add(x)); }+ remove(...c) { c.forEach(x => this._s.delete(x)); }+ contains(c) { return this._s.has(c); }+}+function mkEl(tag) {+ const el = { tagName: tag, children: [], dataset: {}, parentElement: null };+ el.classList = new FakeClassList();+ Object.defineProperty(el, 'className', {+ get() { return Array.from(el.classList._s).join(' '); },+ set(v) { el.classList._s = new Set(String(v || '').split(/\s+/).filter(Boolean)); },+ });+ el.appendChild = (child) => { child._connected = true; child.parentElement = el; el.children.push(child); return child; };+ el.remove = () => { el._connected = false; if (el.parentElement) { const i = el.parentElement.children.indexOf(el); if (i >= 0) el.parentElement.children.splice(i, 1); } };+ el.addEventListener = () => {};+ Object.defineProperty(el, 'isConnected', { get() { return !!el._connected; } });+ el.querySelector = (sel) => {+ const cls = sel.replace('.', '');+ return el.children.find(c => c.classList.contains(cls)) || null;+ };+ let _text = '';+ Object.defineProperty(el, 'textContent', {+ get() { return _text; }, set(v) { _text = String(v); },+ });+ Object.defineProperty(el, 'innerHTML', {+ get() { return ''; },+ set(html) {+ el.children = [];+ const re = /class="([^"]+)"/g; let m;+ while ((m = re.exec(html))) {+ const child = mkEl('span');+ m[1].split(/\s+/).forEach(c => child.classList.add(c));+ child.parentElement = el;+ el.children.push(child);+ }+ },+ });+ return el;+}+const container = mkEl('div');+container._connected = true;+global.document = {+ getElementById: (id) => (id === 'phosToast' ? container : null),+ createElement: (tag) => mkEl(tag),+};+global.setTimeout = () => 0;+global.clearTimeout = () => {};+"""+++class TheToastDedup(unittest.TestCase):+ def _run(self, calls: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = panel_source()+ fn = extract_function("phosToast", src)+ script = (TOAST_SHIM + fn + "\n" + calls+ + "\nprocess.stdout.write(JSON.stringify({"+ + "n: container.children.length,"+ + "counts: container.children.map(c => c.dataset.count),"+ + "}));\n")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = subprocess.run([NODE, str(path)], capture_output=True,+ text=True, timeout=30)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)++ def test_three_identical_toasts_are_one_element_with_a_counter(self):+ r = self._run(+ "phosToast('Already hard against what comes after it.', {duration: 0});\n"+ "phosToast('Already hard against what comes after it.', {duration: 0});\n"+ "phosToast('Already hard against what comes after it.', {duration: 0});\n")+ self.assertEqual(r["n"], 1)+ self.assertEqual(r["counts"], ["3"])++ def test_a_different_message_still_stacks(self):+ r = self._run(+ "phosToast('one', {duration: 0});\n"+ "phosToast('two', {duration: 0});\n")+ self.assertEqual(r["n"], 2)+ self.assertEqual(r["counts"], ["1", "1"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_film_frame_lock.py b/test_editor_film_frame_lock.pynew file mode 100644index 0000000..4322072--- /dev/null+++ b/test_editor_film_frame_lock.py@@ -0,0 +1,365 @@+#!/usr/bin/env python3+"""FILM-51 — does rounding clips to whole frames drift the picture against+the song over many cuts? Measured here, analytically, instead of with a+GPU render: the render trims each segment on its OWN local clock+(`setpts=PTS-STARTPTS` then `fps={FPS}` in `mlx_ltx_panel.py`'s film+filtergraph), which is exactly `round(length * fps) / fps` per segment,+independently of every other segment — the same arithmetic this file+simulates without spending a render on it.++Locked here:+ * `TheMeasurement` — the drift IS real: a synthetic 52-cut film with+ non-frame-aligned windows accumulates more than a frame of drift+ between the (frame-rounded) picture and the (exact) song well before+ the last cut, confirming the report's own estimate ("potentially 1 to+ 2 frames... late in the film").+ * `heal_subframe_lengths` — the fix. Every clip's FILM length becomes an+ exact multiple of 1/fps, so the render's `fps=` filter has nothing+ left to round and the simulated drift is zero at every cut, not just+ the last one. Gaps are untouched, a locked clip is an anchor, an+ unlinked sound strip keeps its exact drift, the take's own source+ bound is respected (a fix that cannot fit is skipped, not clamped into+ a mismatch), and a second pass is a no-op.+ * `load_edit` deliberately does NOT call it. Wiring it in there first+ surfaced a real hazard: unlike the gap heal, it can rewrite a clip's+ own `end`, and a save-history entry hand-corrupted for+ `test_a_genuinely_broken_version_is_STILL_refused`+ (test_storyboard_editor_api.py) stopped being refused, because the+ heal recomputed a plausible `end` before `validate_edit` ever saw the+ corrupt one.+ * `TheSaveHeals` / `TheRenderPathHealsAndValidates` — where it IS wired,+ both strictly after their own `validate_edit`/`blocking_errors` check:+ `storyboard_editor.save_edit` (right after `validate_edit` ++ `normalise_edit`, so every manual save converges to frame-exact) and+ `mlx_ltx_panel._sbe_render_edit` (its own `validate_edit` check, refuse+ on failure, heal on success, THEN `edit_to_cuts` — so a film saved+ before this fix existed still renders frame-exact without a resave).+ Both re-prove the exact regression above stays fixed on the path that+ now runs unconditionally.++Run: ./ltx-2-mlx/env/bin/python3.11 -m pytest -q test_editor_film_frame_lock.py+"""+from __future__ import annotations++import random+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard_editor as sedit # noqa: E402++FPS = 24.0+++def _clip(cid, path, start, end, film_start, **kw):+ c = sedit.new_clip(path, start, end, film_start, id=cid,+ duration=kw.pop("duration", 999.0), source="human")+ c.update(kw)+ return c+++def _doc(clips, **kw):+ d = {"version": sedit.EDIT_VERSION, "board_id": "sb_lock", "revision": 0,+ "source": "human", "audio": None, "beats": None, "clips": clips,+ "settings": {}}+ d.update(kw)+ return d+++def _realistic_52_cut_film(seed: int = 42) -> list[dict]:+ """52 clips, each 2-8s, non-frame-aligned — the shape a music-video+ board actually produces (durations come from planned beats and a2v+ audio segments, not from the editor's own frame grid)."""+ rng = random.Random(seed)+ clips = []+ cursor = 0.0+ for i in range(52):+ length = round(rng.uniform(2.0, 8.0) + rng.random() / FPS * rng.choice([0.3, 0.7, 1.3]), 6)+ clips.append(_clip(f"c{i}", f"/x/s{i}.mp4", 0.0, length, cursor, duration=length + 5.0))+ cursor = round(cursor + length, 6)+ return clips+++def _simulate_render_cumulative(clips: list[dict], fps: float = FPS) -> list[float]:+ """What the render's picture clock reads after each cut: each segment's+ length independently rounded to the nearest frame (ffmpeg's `fps=`+ filter on its own local PTS), then summed — exactly `_sb_film_filtergraph`'s+ per-segment `trim=...,fps={FPS}` behaviour."""+ cum = 0.0+ out = []+ for c in clips:+ length = c["end"] - c["start"]+ frames = round(length * fps)+ cum += frames / fps+ out.append(cum)+ return out+++def _exact_cumulative(clips: list[dict]) -> list[float]:+ cum = 0.0+ out = []+ for c in clips:+ cum += c["end"] - c["start"]+ out.append(cum)+ return out+++class TheMeasurement(unittest.TestCase):+ def test_a_52_cut_film_drifts_more_than_a_frame_before_the_last_cut(self):+ clips = _realistic_52_cut_film()+ rendered = _simulate_render_cumulative(clips)+ exact = _exact_cumulative(clips)+ drift_frames = [abs(r - e) * FPS for r, e in zip(rendered, exact)]+ # The report's own estimate: "potentially 1 to 2 frames of lip+ # drift late in the film, and only in the render."+ self.assertGreater(max(drift_frames), 1.0,+ "expected the unhealed film to drift past a full frame")+ self.assertLess(max(drift_frames), 6.0,+ "a multi-frame drift this large would mean the simulation is wrong, "+ "not that the bug is worse than reported")++ def test_the_drift_is_not_an_artifact_of_this_one_seed(self):+ # Three more seeds, same shape of film — the bug is structural+ # (independent per-segment rounding), not a one-off.+ for seed in (1, 7, 99):+ clips = _realistic_52_cut_film(seed)+ rendered = _simulate_render_cumulative(clips)+ exact = _exact_cumulative(clips)+ max_drift = max(abs(r - e) * FPS for r, e in zip(rendered, exact))+ self.assertGreater(max_drift, 0.3, f"seed {seed}: expected measurable drift")+++class TheFix(unittest.TestCase):+ def test_every_clip_length_becomes_frame_exact(self):+ doc = _doc(_realistic_52_cut_film())+ fixed = sedit.heal_subframe_lengths(doc)+ self.assertEqual(len(fixed), 52) # none of these 52 started frame-exact+ for c in doc["clips"]:+ length = c["film_end"] - c["film_start"]+ frames = length * FPS+ # Millisecond precision: comfortably above the residual noise a+ # 6-decimal-place store leaves on a repeating fraction like+ # 1/24, comfortably below anything a viewer could perceive.+ self.assertAlmostEqual(frames, round(frames), places=3)++ def test_the_simulated_drift_is_zero_at_every_cut_after_the_fix(self):+ doc = _doc(_realistic_52_cut_film())+ sedit.heal_subframe_lengths(doc)+ clips = [dict(c, start=c["film_start"], end=c["film_end"]) for c in doc["clips"]]+ rendered = _simulate_render_cumulative(clips)+ exact = _exact_cumulative(clips)+ for r, e in zip(rendered, exact):+ self.assertAlmostEqual(r, e, places=6)++ def test_gaps_are_preserved_not_closed(self):+ a = _clip("a", "/x/a.mp4", 0.0, 3.001, 0.0, duration=99.0)+ b = _clip("b", "/x/b.mp4", 0.0, 4.0, 5.0, duration=99.0) # ~2s deliberate gap+ doc = _doc([a, b])+ sedit.heal_subframe_lengths(doc)+ got = sedit.load_edit # not called; direct healer test+ a2, b2 = doc["clips"]+ gap = b2["film_start"] - a2["film_end"]+ self.assertGreater(gap, 1.9) # still roughly 2s, not zeroed++ def test_a_locked_clip_is_never_moved(self):+ a = _clip("a", "/x/a.mp4", 0.0, 3.001, 0.0, duration=99.0)+ b = _clip("b", "/x/b.mp4", 0.0, 4.002, 3.001, locked=True, duration=99.0)+ c = _clip("c", "/x/c.mp4", 0.0, 2.003, 7.003, duration=99.0)+ doc = _doc([a, b, c])+ sedit.heal_subframe_lengths(doc)+ b2 = next(x for x in doc["clips"] if x["id"] == "b")+ self.assertEqual(b2["film_start"], 3.001)+ self.assertEqual(b2["film_end"], 7.003)++ def test_an_unlinked_strip_keeps_its_exact_drift(self):+ a = _clip("a", "/x/a.mp4", 0.0, 3.003, 0.0, duration=99.0,+ audio={"start": 0.2, "end": 3.2, "film_start": 0.15})+ b = _clip("b", "/x/b.mp4", 0.0, 4.0, 3.003, duration=99.0)+ doc = _doc([a, b])+ before_drift = sedit.clip_audio_drift(a)+ sedit.heal_subframe_lengths(doc)+ a2 = next(x for x in doc["clips"] if x["id"] == "a")+ after_drift = sedit.clip_audio_drift(a2)+ self.assertAlmostEqual(before_drift, after_drift, places=6)++ def test_a_correction_past_the_takes_own_end_is_skipped_not_clamped(self):+ # 3.03s is 72.72 frames -> rounds UP to 73 (3.041667s), needing+ # ~0.0117s more than the take has (duration leaves 0.005s of room).+ a = _clip("a", "/x/a.mp4", 0.0, 3.03, 0.0, duration=3.035)+ doc = _doc([a])+ fixed = sedit.heal_subframe_lengths(doc)+ self.assertEqual(fixed, [])+ a2 = doc["clips"][0]+ self.assertEqual(a2["end"], 3.03) # untouched+ # Document stays internally consistent — no length_mismatch.+ self.assertEqual([e["code"] for e in sedit.validate_edit(doc)], [])++ def test_idempotent(self):+ doc = _doc(_realistic_52_cut_film())+ sedit.heal_subframe_lengths(doc)+ second = sedit.heal_subframe_lengths(doc)+ self.assertEqual(second, [])++ def test_a_frame_exact_film_reports_nothing_to_fix(self):+ a = _clip("a", "/x/a.mp4", 0.0, 3.0, 0.0, duration=99.0) # 72 frames exactly+ b = _clip("b", "/x/b.mp4", 0.0, 2.0 + 1 / FPS, 3.0, duration=99.0)+ doc = _doc([a, b])+ self.assertEqual(sedit.heal_subframe_lengths(doc), [])++ def test_load_edit_does_not_call_it_yet(self):+ # Deliberately NOT wired into the automatic read path — see the+ # comment above the (absent) call in `load_edit`. Rewriting a+ # clip's own `end` turned out to be able to launder a genuinely+ # corrupt history entry (a hand-set `end: -1.0`) into a plausible+ # one before `validate_edit` ever saw it+ # (`test_a_genuinely_broken_version_is_STILL_refused` in+ # test_storyboard_editor_api.py), which is a worse defect than the+ # drift this function fixes. It is correct and available for a+ # caller that has already validated its document; this pins that+ # `load_edit` is not (yet) that caller.+ tmp = Path(tempfile.mkdtemp())+ doc = _doc(_realistic_52_cut_film())+ sedit.save_edit(tmp, doc)+ raw = sedit.edit_path(tmp)+ import json+ on_disk = json.loads(raw.read_text())+ on_disk["clips"][3]["film_end"] = on_disk["clips"][3]["film_start"] + 3.3003+ raw.write_text(json.dumps(on_disk))+ loaded = sedit.load_edit(tmp)+ self.assertNotIn("healed_subframe_lengths", loaded)+ length = loaded["clips"][3]["film_end"] - loaded["clips"][3]["film_start"]+ self.assertAlmostEqual(length, 3.3003, places=6) # untouched+++# =============================================================================+# WHERE IT IS ACTUALLY WIRED — save_edit and the render path, both AFTER+# validate_edit, never before.+# =============================================================================+class TheSaveHeals(unittest.TestCase):+ """`save_edit`: validate, normalise, THEN heal — so every manual save is+ a frame-exact document, and a corrupt one is still refused before this+ ever touches it."""++ def test_a_saved_film_is_frame_exact(self):+ import tempfile+ tmp = Path(tempfile.mkdtemp())+ doc = _doc(_realistic_52_cut_film())+ sedit.save_edit(tmp, doc)+ loaded = sedit.load_edit(tmp)+ for c in loaded["clips"]:+ length = c["film_end"] - c["film_start"]+ frames = length * FPS+ self.assertAlmostEqual(frames, round(frames), places=3)++ def test_a_second_save_is_stable(self):+ import tempfile+ tmp = Path(tempfile.mkdtemp())+ sedit.save_edit(tmp, _doc(_realistic_52_cut_film()))+ first = sedit.load_edit(tmp)+ sedit.save_edit(tmp, dict(first))+ second = sedit.load_edit(tmp)+ self.assertEqual(+ [(c["film_start"], c["film_end"]) for c in first["clips"]],+ [(c["film_start"], c["film_end"]) for c in second["clips"]])++ def test_a_genuinely_broken_document_is_still_refused(self):+ # The exact regression that made auto-wiring into load_edit unsafe,+ # now proven against the path this DOES run on: a bad `end` must+ # still be refused by save_edit, not silently repaired into+ # something plausible.+ a = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, duration=10.0)+ broken = _doc([a])+ broken["clips"][0]["end"] = -1.0+ import tempfile+ tmp = Path(tempfile.mkdtemp())+ with self.assertRaises(sedit.EditError):+ sedit.save_edit(tmp, broken)+++class TheRenderPathHealsAndValidates(unittest.TestCase):+ """`_sbe_render_edit`: its own validate_edit check refuses a corrupt+ document before heal_subframe_lengths ever sees it; a valid one is+ healed before `edit_to_cuts` builds the plan, so a 52-cut film saved+ BEFORE this fix existed still renders frame-exact without a resave."""++ def _mocked(self, edit, extra=None):+ board = {"id": "b1", "shots": []}+ fake_film = {"ok": True, "path": "/out/film.mp4", "width": 1920, "height": 1080}+ patches = [+ mock.patch.object(panel, "_sbe_import", return_value=sedit),+ mock.patch.object(panel, "_sb_film_dir_for_write", return_value=Path("/out")),+ mock.patch.object(panel, "_sb_deliver", return_value={"format": "h264", "size": "native",+ "finish": "none", "label": "H.264"}),+ mock.patch.object(panel, "_sb_film_name", return_value="film.mp4"),+ ]+ for p in patches:+ p.start()+ self.addCleanup(p.stop)+ captured = {}++ def fake_assemble(paths, out, *, timeline=None, **kw):+ captured["timeline"] = timeline+ return dict(fake_film)+ m = mock.patch.object(panel, "_sb_assemble_film", side_effect=fake_assemble)+ m.start()+ self.addCleanup(m.stop)+ got = panel._sbe_render_edit(board, edit)+ return got, captured.get("timeline")++ def test_a_corrupted_edit_is_refused_before_rendering(self):+ a = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0, duration=10.0)+ edit = _doc([a])+ edit["clips"][0]["end"] = -1.0+ with mock.patch.object(panel, "_sbe_import", return_value=sedit), \+ mock.patch.object(panel, "_sb_assemble_film") as assemble:+ got = panel._sbe_render_edit({"id": "b1", "shots": []}, edit)+ self.assertFalse(got["ok"])+ self.assertEqual(got.get("status"), 400)+ assemble.assert_not_called() # never reached the assembler++ def test_a_52_cut_film_renders_with_no_cumulative_drift(self):+ edit = sedit.normalise_edit(_doc(_realistic_52_cut_film()))+ got, timeline = self._mocked(edit)+ self.assertTrue(got["ok"])+ self.assertIsNotNone(timeline)+ # The plan `_sb_assemble_film` actually receives: every entry's own+ # film length (end - start, at 1x — none of these clips are+ # retimed) is frame-exact, and the simulated picture clock (what+ # ffmpeg's fps= filter would produce from these windows) never+ # drifts from the exact sum by more than float noise, at ANY cut —+ # not just the last one.+ exact_cum = 0.0+ render_cum = 0.0+ for seg in timeline:+ length = seg["end"] - seg["start"]+ frames = length * FPS+ self.assertAlmostEqual(frames, round(frames), places=3)+ exact_cum += length+ render_cum += round(length * FPS) / FPS+ self.assertAlmostEqual(render_cum, exact_cum, places=3)++ def test_an_already_frame_exact_film_asks_nothing_new_of_the_assembler(self):+ # A film saved AFTER save_edit's own healing lands here unchanged —+ # this is the "old edit, rendered today" case converging without a+ # human ever having to resave it first.+ clips = _realistic_52_cut_film()+ edit = sedit.normalise_edit(_doc(clips))+ import tempfile+ tmp = Path(tempfile.mkdtemp())+ sedit.save_edit(tmp, edit) # heals it+ healed = sedit.load_edit(tmp)+ got, timeline = self._mocked(healed)+ self.assertTrue(got["ok"])+ for seg in timeline:+ length = seg["end"] - seg["start"]+ self.assertAlmostEqual(length * FPS, round(length * FPS), places=3)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_film_grade.py b/test_editor_film_grade.pynew file mode 100644index 0000000..ef99a1d--- /dev/null+++ b/test_editor_film_grade.py@@ -0,0 +1,433 @@+#!/usr/bin/env python3+"""FILM-14 — colour: the 5-slider grade, Match colour, and Film look.++Locked here:+ * `clip_grade` / `clip_grade_is_neutral` — the model, mirroring+ `clip_brightness` exactly (absent is neutral, clamped, a sibling under+ the same `adjust` dict, no EDIT_VERSION bump).+ * `_sb_grade_term` — the render filter, chained AFTER the legacy+ `_sb_brightness_term` and never reading `adjust.brightness` (the two+ would double-apply otherwise); neutral clips add no filter at all.+ * `film_look_stack` — a whole-film preset combined with a clip's own+ grade, additive fields sum and the two 1.0-centred fields sum their+ distance from neutral.+ * `edit_to_cuts` — the grade (and a Film-look preset) reaches the plan the+ same way brightness always has, so the film render sees exactly what+ the Inspector's sliders show.+ * The AE (After Effects) export gets contrast and saturation alongside+ the existing brightness mapping, without disturbing the exact string+ the pre-existing brightness-only test still checks.+ * `_sb_match_colour_grade` and the `/storyboard/edit/match-colour` route.++Run: ./ltx-2-mlx/env/bin/python3.11 -m pytest -q test_editor_film_grade.py+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard_editor as sedit # noqa: E402+++def _clip(cid, path, start, end, film_start, **kw):+ c = sedit.new_clip(path, start, end, film_start, id=cid, duration=10.0, source="human")+ c.update(kw)+ return c+++def _doc(clips, **kw):+ d = {"version": sedit.EDIT_VERSION, "board_id": "sb_g", "revision": 0, "source": "human",+ "audio": None, "beats": None, "clips": clips, "settings": {}}+ d.update(kw)+ return d+++def _codes(doc):+ return [e["code"] for e in sedit.validate_edit(doc)]+++# =============================================================================+# THE MODEL+# =============================================================================+class TheGradeModel(unittest.TestCase):+ def test_absent_is_neutral(self):+ g = sedit.clip_grade({})+ self.assertEqual(g, {"exposure": 0.0, "contrast": 1.0, "saturation": 1.0,+ "temp": 0.0, "tint": 0.0})+ self.assertTrue(sedit.clip_grade_is_neutral({}))++ def test_reads_and_clamps_every_field(self):+ c = {"adjust": {"exposure": 9, "contrast": 9, "saturation": 9, "temp": 9, "tint": -9}}+ g = sedit.clip_grade(c)+ self.assertEqual(g["exposure"], sedit.EXPOSURE_LIMIT)+ self.assertEqual(g["contrast"], sedit.GRADE_CONTRAST_RANGE[1])+ self.assertEqual(g["saturation"], sedit.GRADE_SATURATION_RANGE[1])+ self.assertEqual(g["temp"], sedit.GRADE_TEMP_TINT_LIMIT)+ self.assertEqual(g["tint"], -sedit.GRADE_TEMP_TINT_LIMIT)+ self.assertFalse(sedit.clip_grade_is_neutral(c))++ def test_brightness_and_exposure_are_independent_fields(self):+ c = {"adjust": {"brightness": 0.2, "exposure": 0.1}}+ self.assertEqual(sedit.clip_brightness(c), 0.2)+ self.assertEqual(sedit.clip_grade(c)["exposure"], 0.1)++ def test_clip_effects_is_the_one_accessor_for_the_grade_too(self):+ c = {"adjust": {"brightness": 0.2, "saturation": 1.4}, "fx": {"fade_in": 0.5}}+ e = sedit.clip_effects(c)+ self.assertEqual(e["brightness"], 0.2)+ self.assertEqual(e["saturation"], 1.4)+ self.assertEqual(e["fade_in"], 0.5)++ def test_validation_accepts_a_legal_grade(self):+ c = _clip("a", "/x/a.mp4", 0, 4, 0, adjust={"exposure": 0.2, "contrast": 1.3,+ "saturation": 0.8, "temp": 0.3, "tint": -0.2})+ self.assertEqual(_codes(_doc([c])), [])++ def test_validation_refuses_an_out_of_range_field(self):+ c = _clip("a", "/x/a.mp4", 0, 4, 0, adjust={"contrast": 9})+ self.assertIn("clip_grade_range", _codes(_doc([c])))+ c2 = _clip("a", "/x/a.mp4", 0, 4, 0, adjust={"temp": "warm"})+ self.assertIn("clip_grade", _codes(_doc([c2])))++ def test_normalise_writes_back_clamped_and_drops_neutral_fields(self):+ c = _clip("a", "/x/a.mp4", 0, 4, 0, adjust={"contrast": 9, "saturation": 1.0, "tint": 0.0})+ norm = sedit.normalise_edit(_doc([c]))+ adj = norm["clips"][0].get("adjust") or {}+ self.assertEqual(adj.get("contrast"), sedit.GRADE_CONTRAST_RANGE[1])+ self.assertNotIn("saturation", adj) # neutral — dropped+ self.assertNotIn("tint", adj) # neutral — dropped++ def test_normalise_preserves_unknown_adjust_keys(self):+ # Forward-compat: a future field this code does not know about yet+ # must not be silently deleted on every save.+ c = _clip("a", "/x/a.mp4", 0, 4, 0, adjust={"exposure": 0.1, "mystery_future_field": 42})+ norm = sedit.normalise_edit(_doc([c]))+ self.assertEqual(norm["clips"][0]["adjust"].get("mystery_future_field"), 42)+++# =============================================================================+# THE RENDER TERM+# =============================================================================+class TheGradeTerm(unittest.TestCase):+ def test_neutral_adds_no_filter(self):+ self.assertEqual(panel._sb_grade_term(None), "")+ self.assertEqual(panel._sb_grade_term({}), "")+ self.assertEqual(panel._sb_grade_term({"exposure": 0.0, "contrast": 1.0}), "")++ def test_exposure_contrast_saturation_share_one_eq_node(self):+ term = panel._sb_grade_term({"exposure": 0.1, "contrast": 1.2, "saturation": 0.8})+ self.assertEqual(term, "eq=brightness=0.100000:contrast=1.200000:saturation=0.800000,")++ def test_it_never_reads_legacy_brightness(self):+ # Only `brightness` set — no exposure/contrast/saturation/temp/tint —+ # must produce nothing; `_sb_brightness_term` owns that field alone.+ self.assertEqual(panel._sb_grade_term({"brightness": 0.4}), "")++ def test_temp_and_tint_ride_colorbalance_and_clamp(self):+ term = panel._sb_grade_term({"temp": 1.0, "tint": -1.0})+ self.assertIn("colorbalance=", term)+ self.assertIn("rm=0.400000", term)+ self.assertIn("bm=-0.400000", term)+ self.assertIn("gm=0.400000", term)++ def test_out_of_range_and_nan_are_clamped_not_raised(self):+ term = panel._sb_grade_term({"exposure": 999, "contrast": float("nan")})+ self.assertIn("brightness=0.500000", term)+ self.assertIn("contrast=1.000000", term) # nan -> default (neutral)++ def test_brightness_and_grade_chain_without_double_applying(self):+ # The render-graph assignment: bright = brightness_term + grade_term.+ adjust = {"brightness": 0.1, "exposure": 0.1}+ combined = panel._sb_brightness_term(adjust) + panel._sb_grade_term(adjust)+ self.assertEqual(combined,+ "eq=brightness=0.100000,eq=brightness=0.100000:contrast=1.000000:saturation=1.000000,")+++# =============================================================================+# FILM LOOK+# =============================================================================+class TheFilmLook(unittest.TestCase):+ def test_no_preset_is_a_no_op(self):+ adj = {"exposure": 0.1}+ self.assertEqual(sedit.film_look_stack(adj, None), adj)+ self.assertEqual(sedit.film_look_stack(adj, "not_a_real_preset"), adj)++ def test_additive_fields_sum(self):+ out = sedit.film_look_stack({"temp": 0.1}, "warm_tungsten")+ self.assertAlmostEqual(out["temp"], 0.1 + sedit.FILM_LOOK_PRESETS["warm_tungsten"]["temp"])++ def test_multiplicative_fields_sum_their_distance_from_neutral(self):+ out = sedit.film_look_stack({"saturation": 1.2}, "warm_tungsten")+ # preset saturation 1.10 -> +0.10 distance from neutral+ self.assertAlmostEqual(out["saturation"], 1.2 + 0.10)++ def test_a_clip_with_no_grade_of_its_own_still_gets_the_preset(self):+ rows = panel._sbe_board_clips if False else None # not used; direct edit_to_cuts test below+ c = _clip("a", "/x/a.mp4", 0, 4, 0) # no adjust at all+ doc = _doc([c], settings={"film_look": "warm_tungsten"})+ plan = sedit.edit_to_cuts(doc)+ self.assertIn("adjust", plan[0])+ self.assertAlmostEqual(plan[0]["adjust"]["temp"],+ sedit.FILM_LOOK_PRESETS["warm_tungsten"]["temp"])++ def test_a_slug_is_never_graded_by_the_preset(self):+ s = {"id": "s", "kind": "slug", "path": None, "start": 0, "end": 2, "film_start": 0,+ "film_end": 2, "source": "human", "locked": False}+ doc = _doc([s], settings={"film_look": "warm_tungsten"})+ plan = sedit.edit_to_cuts(doc)+ self.assertNotIn("adjust", plan[0])++ def test_the_plan_stays_identical_with_no_preset_selected(self):+ c = _clip("a", "/x/a.mp4", 0, 4, 0, adjust={"exposure": 0.05})+ without = sedit.edit_to_cuts(_doc([c]))+ with_none = sedit.edit_to_cuts(_doc([c], settings={"film_look": "none"}))+ self.assertEqual(without, with_none)+++# =============================================================================+# THE AE (AFTER EFFECTS) EXPORT+# =============================================================================+class TheAeExport(unittest.TestCase):+ def setUp(self):+ import tempfile+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.mp4 = self.root / "a.mp4"+ self.mp4.write_bytes(b"v" * 64)++ def tearDown(self):+ self.tmp.cleanup()++ @staticmethod+ def _probe(_p):+ return {"w": 1024, "h": 576, "duration": 10.0, "has_audio": True}++ def _clip_row(self, **adjust):+ row = {"id": "1", "path": str(self.mp4), "title": "Open",+ "start": 0.0, "end": 4.0, "film_start": 0.0, "film_end": 4.0}+ if adjust:+ row["adjust"] = adjust+ return row++ def _export(self, clips):+ return sedit.export_nle(clips, self.root, name="grade test", probe=self._probe)++ def test_brightness_only_is_unchanged_from_before_the_grade_existed(self):+ # The exact assertion test_storyboard_editor_api.py's own brightness+ # test makes — this file re-proves it is untouched by the grade work.+ jsx = Path(self._export([self._clip_row(brightness=0.25)])["jsx"]).read_text()+ self.assertIn("bright(lay, 37.5);", jsx)+ self.assertEqual(jsx.count("bright(lay,"), 1)++ def test_contrast_rides_alongside_brightness_in_one_call(self):+ c = self._clip_row(brightness=0.1, contrast=1.2)+ jsx = Path(self._export([c])["jsx"]).read_text()+ # (0.1)*150 = 15.0; (1.2-1)*150 = 30.0+ self.assertIn("bright(lay, 15.0, 30.0);", jsx)++ def test_saturation_gets_its_own_call(self):+ c = self._clip_row(saturation=1.5)+ jsx = Path(self._export([c])["jsx"]).read_text()+ self.assertIn("ADBE HUE SATURATION", jsx)+ self.assertIn("satur(lay, 50.0);", jsx) # (1.5-1)*100++ def test_a_neutral_clip_gets_neither_call(self):+ c = self._clip_row()+ jsx = Path(self._export([c])["jsx"]).read_text()+ self.assertNotIn("bright(lay,", jsx)+ self.assertNotIn("satur(lay,", jsx)+++# =============================================================================+# MATCH COLOUR+# =============================================================================+class TheMatchColourMaths(unittest.TestCase):+ def test_identical_frames_propose_nothing(self):+ got = panel._sb_match_colour_grade((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))+ self.assertEqual(got, {"exposure": 0.0, "temp": 0.0, "tint": 0.0})++ def test_a_darker_clip_gets_positive_exposure(self):+ got = panel._sb_match_colour_grade((0.3, 0.3, 0.3), (0.5, 0.5, 0.5))+ self.assertGreater(got["exposure"], 0)++ def test_a_cool_clip_toward_a_warm_reference_gets_positive_temp(self):+ # This clip is cool (low R, high B) vs a neutral reference.+ got = panel._sb_match_colour_grade((0.3, 0.4, 0.5), (0.4, 0.4, 0.4))+ self.assertGreater(got["temp"], 0)++ def test_clamped_to_the_grade_ranges(self):+ got = panel._sb_match_colour_grade((0.0, 0.0, 1.0), (1.0, 1.0, 0.0))+ self.assertLessEqual(got["exposure"], 0.5)+ self.assertLessEqual(abs(got["temp"]), 1.0)+ self.assertLessEqual(abs(got["tint"]), 1.0)+++class TheMatchColourRoute(unittest.TestCase):+ def setUp(self):+ import tempfile+ from unittest import mock+ import storyboard++ from test_storyboard_editor_api import FakeHandler, _board, _edit++ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.a = self.root / "a.mp4"; self.a.write_bytes(b"x")+ self.b = self.root / "b.mp4"; self.b.write_bytes(b"x")+ self.c = self.root / "c.mp4"; self.c.write_bytes(b"x")+ clips = [_clip("a", str(self.a), 0.0, 4.0, 0.0),+ _clip("b", str(self.b), 0.0, 4.0, 4.0),+ _clip("c", str(self.c), 0.0, 4.0, 8.0)]+ self.edit = sedit.normalise_edit(_edit(clips))+ bdir = self.root / "sb_g"+ bdir.mkdir()+ sedit.save_edit(bdir, self.edit)+ self.FakeHandler = FakeHandler+ self.patches = [+ mock.patch.object(panel, "STATE_DIR", self.root),+ mock.patch.object(panel, "_sbe_board_dir", return_value=bdir),+ mock.patch.object(storyboard, "load_storyboard",+ return_value=_board([self.a, self.b, self.c])),+ ]+ for p in self.patches:+ p.start()+ self.addCleanup(p.stop)++ def _rgb_by_path(self, mapping):+ def fn(path, at):+ return mapping.get(str(path))+ return fn++ def test_proposals_exclude_the_reference_and_near_matches(self):+ from unittest import mock+ rgb = {str(self.a): (0.5, 0.5, 0.5), # the reference+ str(self.b): (0.5, 0.5, 0.5), # already matches -> no proposal+ str(self.c): (0.2, 0.2, 0.2)} # darker -> proposed+ with mock.patch.object(panel, "take_frame_rgb", side_effect=self._rgb_by_path(rgb)):+ h = self.FakeHandler()+ h.post("edit/match-colour", {"id": "sb_g", "ref": "a"})+ self.assertEqual(h.status, 200, h.payload)+ ids = [p["id"] for p in h.payload["proposals"]]+ self.assertEqual(ids, ["c"])+ self.assertGreater(h.payload["proposals"][0]["exposure"], 0)++ def test_no_ref_uses_the_films_median(self):+ from unittest import mock+ rgb = {str(self.a): (0.2, 0.2, 0.2),+ str(self.b): (0.5, 0.5, 0.5),+ str(self.c): (0.8, 0.8, 0.8)}+ with mock.patch.object(panel, "take_frame_rgb", side_effect=self._rgb_by_path(rgb)):+ h = self.FakeHandler()+ h.post("edit/match-colour", {"id": "sb_g"})+ self.assertEqual(h.status, 200, h.payload)+ self.assertAlmostEqual(h.payload["reference"]["r"], 0.5)+ ids = sorted(p["id"] for p in h.payload["proposals"])+ self.assertEqual(ids, ["a", "c"]) # b IS the median, no proposal++ def test_unreadable_clips_are_skipped_not_fatal(self):+ from unittest import mock+ rgb = {str(self.a): (0.5, 0.5, 0.5), str(self.b): (0.2, 0.2, 0.2)}+ # c returns None (unreadable)+ with mock.patch.object(panel, "take_frame_rgb", side_effect=self._rgb_by_path(rgb)):+ h = self.FakeHandler()+ h.post("edit/match-colour", {"id": "sb_g", "ref": "a"})+ self.assertEqual(h.status, 200, h.payload)+ ids = [p["id"] for p in h.payload["proposals"]]+ self.assertEqual(ids, ["b"])+++# =============================================================================+# THE CLIENT MODEL — sbeGrade / sbeSetGrade / sbeCopyGrade / sbeGradeCss+# =============================================================================+def run_client(body: str) -> dict:+ import json+ import subprocess as sp+ import tempfile+ from test_storyboard_editor_ui import (FUNCTIONS, NODE, SHIM,+ extract_function, panel_source)+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = panel_source()+ script = (SHIM + "\n".join(extract_function(n, src) for n in FUNCTIONS)+ + "\nconst out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out));\n")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = sp.run([NODE, str(path)], capture_output=True, text=True, timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)+++class TheClientGradeModel(unittest.TestCase):+ def test_absent_is_neutral_and_matches_the_server(self):+ r = run_client("out.g = sbeGrade({});")+ self.assertEqual(r["g"], {"exposure": 0.0, "contrast": 1.0, "saturation": 1.0,+ "temp": 0.0, "tint": 0.0})++ def test_set_clamps_and_drops_neutral(self):+ r = run_client("""+const clips = [{ id: 'a', kind: 'video', adjust: { contrast: 1.5 } }];+sbeSetGrade(clips, 'a', 'contrast', 999);+out.after_clamp = clips[0].adjust.contrast;+sbeSetGrade(clips, 'a', 'contrast', 1.0);+out.after_neutral = clips[0].adjust;+""")+ self.assertEqual(r["after_clamp"], 1.8)+ self.assertNotIn("contrast", r.get("after_neutral") or {})++ def test_set_refuses_a_locked_clip(self):+ r = run_client("""+const clips = [{ id: 'a', kind: 'video', locked: true }];+out.r = sbeSetGrade(clips, 'a', 'exposure', 0.2);+""")+ self.assertFalse(r["r"]["ok"])+ self.assertEqual(r["r"]["why"], "locked")++ def test_copy_grade_stamps_every_other_selected_clip(self):+ r = run_client("""+const clips = [+ { id: 'a', kind: 'video', adjust: { exposure: 0.2, temp: -0.1 } },+ { id: 'b', kind: 'video' },+ { id: 'c', kind: 'video', locked: true },+];+out.r = sbeCopyGrade(clips, 'a', ['a', 'b', 'c']);+out.b = sbeGrade(sbeById(clips, 'b'));+out.c_untouched = clips[2].adjust;+""")+ self.assertTrue(r["r"]["ok"])+ self.assertEqual(r["b"]["exposure"], 0.2)+ self.assertEqual(r["b"]["temp"], -0.1)+ self.assertIsNone(r.get("c_untouched")) # locked — skipped++ def test_grade_css_uses_multiplicative_css_functions_directly(self):+ r = run_client("""+out.css = sbeGradeCss({ adjust: { contrast: 1.2, saturation: 0.7 } });+""")+ self.assertIn("contrast(1.200)", r["css"])+ self.assertIn("saturate(0.700)", r["css"])+ self.assertNotIn("temp", r["css"]) # no CSS term for temp/tint++ def test_grade_css_folds_exposure_into_brightness(self):+ r = run_client("""+out.css = sbeGradeCss({ adjust: { brightness: 0.1, exposure: 0.1 } });+""")+ # total = 0.2 -> CSS brightness() = 1 + 2*0.2 = 1.4+ self.assertIn("brightness(1.4)", r["css"])++ def test_neutral_clip_has_no_css_at_all(self):+ r = run_client("out.css = sbeGradeCss({});")+ self.assertEqual(r["css"], "")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_film_markers.py b/test_editor_film_markers.pynew file mode 100644index 0000000..4002e00--- /dev/null+++ b/test_editor_film_markers.py@@ -0,0 +1,414 @@+#!/usr/bin/env python3+"""FILM-58 — markers, copy/paste, sequence aspect.++Locked here:+ * `markers_of` — the read accessor: absent is no markers, an invalid+ entry is dropped rather than crashing the payload, sorted by time.+ * `validate_edit` — a marker's shape and `at`/`kind` are checked the same+ way an overlay's are; `settings.aspect` is checked against `SEQ_ASPECTS`.+ * `_sb_crop_to_aspect` — the sequence aspect's render-time effect: a+ center crop of the FINISHED film, '16:9' and an unknown key are a+ no-op, the wider dimension is the one cropped (never padded).+ * The client model (`sbeMarkerAdd`/`Remove`/`SetKind`, the copy/paste+ functions, `sbeSeqAspect`) run in node against the real functions.+ * NLE marker export (coordinator follow-up, 2026-09-29) — `_fcp7_markers`+ and `ae_jsx`'s marker lines, and `export_nle` actually threading+ `markers_of(edit)` through to both files: a marker lands on the FCP7+ sequence ruler as a point marker (`<out>-1</out>`) and on the AE comp's+ own `markerProperty`, in film-clock order, an empty lane writing neither+ a `<marker>` nor a `setValueAtTime` line.++Run: ./ltx-2-mlx/env/bin/python3.11 -m pytest -q test_editor_film_markers.py+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard_editor as sedit # noqa: E402+++def _clip(cid, path, start, end, film_start, **kw):+ c = sedit.new_clip(path, start, end, film_start, id=cid, duration=10.0, source="human")+ c.update(kw)+ return c+++def _doc(clips, **kw):+ d = {"version": sedit.EDIT_VERSION, "board_id": "sb_m", "revision": 0, "source": "human",+ "audio": None, "beats": None, "clips": clips, "settings": {}}+ d.update(kw)+ return d+++def _codes(doc):+ return [e["code"] for e in sedit.validate_edit(doc)]+++# =============================================================================+# THE MODEL — markers_of+# =============================================================================+class TheMarkersAccessor(unittest.TestCase):+ def test_absent_is_no_markers(self):+ self.assertEqual(sedit.markers_of({}), [])+ self.assertEqual(sedit.markers_of({"markers": None}), [])++ def test_reads_sorts_and_defaults_kind(self):+ doc = {"markers": [{"id": "b", "at": 5.0}, {"id": "a", "at": 1.0, "kind": "beat"}]}+ got = sedit.markers_of(doc)+ self.assertEqual([m["id"] for m in got], ["a", "b"])+ self.assertEqual(got[0]["kind"], "beat")+ self.assertEqual(got[1]["kind"], "note") # default++ def test_a_bad_entry_is_dropped_not_fatal(self):+ doc = {"markers": ["not a dict", {"id": "a", "at": -5}, {"id": "b", "at": 3.0}]}+ got = sedit.markers_of(doc)+ self.assertEqual([m["id"] for m in got], ["b"])+++class TheMarkerValidation(unittest.TestCase):+ def test_a_legal_marker_validates(self):+ doc = _doc([], markers=[{"id": "m1", "at": 3.0, "kind": "beat", "label": "drop"}])+ self.assertEqual(_codes(doc), [])++ def test_bad_shape_is_refused(self):+ self.assertIn("markers_shape", _codes(_doc([], markers="nope")))+ self.assertIn("marker_shape", _codes(_doc([], markers=["nope"])))++ def test_bad_at_is_refused(self):+ self.assertIn("marker_at", _codes(_doc([], markers=[{"id": "m", "at": "soon"}])))+ self.assertIn("marker_at_range", _codes(_doc([], markers=[{"id": "m", "at": -1}])))++ def test_bad_kind_is_refused(self):+ self.assertIn("marker_kind", _codes(_doc([], markers=[{"id": "m", "at": 1, "kind": "chorus"}])))+++# =============================================================================+# NLE MARKER EXPORT — FCP7 XML + the AE script+# =============================================================================+class TheNleMarkerExport(unittest.TestCase):+ """Coordinator follow-up, 2026-09-29: the drift fix (FILM-51) had to+ reach users; this is FILM-58's own last deferral — markers measured and+ validated, but never written into the project folder `export_nle`+ produces. Now `export_nle` takes `markers` (the caller passes+ `markers_of(edit)`) and both writers place them."""++ def _export(self, markers):+ c = _clip("a", "/x/a.mp4", 0.0, 4.0, 0.0)+ probe = lambda p: {"w": 768, "h": 416, "duration": 10.0, "has_audio": True}+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(sedit.Path, "is_file", return_value=True), \+ mock.patch.object(sedit, "_link_or_copy", return_value="link"):+ res = sedit.export_nle([c], d, name="m", probe=probe, markers=markers)+ xml = Path(res["xml"]).read_text()+ jsx = Path(res["jsx"]).read_text()+ return res, xml, jsx++ def test_no_markers_writes_neither_element(self):+ res, xml, jsx = self._export(None)+ self.assertEqual(res["markers"], 0)+ self.assertNotIn("<marker>", xml)+ self.assertNotIn("markerProperty", jsx)++ def test_a_labelled_beat_lands_on_both(self):+ res, xml, jsx = self._export(+ sedit.markers_of({"markers": [{"id": "m1", "at": 1.5, "kind": "beat",+ "label": "drop"}]}))+ self.assertEqual(res["markers"], 1)+ # FCP7: point marker (out=-1), NAME is the label, COMMENT is the kind+ # — the frame is `at` on the SAME clock `_frames` uses everywhere+ # else in the file (fps defaults to NLE_FPS here).+ self.assertIn("<marker>", xml)+ self.assertIn("<name>drop</name>", xml)+ self.assertIn("<comment>beat</comment>", xml)+ self.assertIn(f"<in>{sedit._frames(1.5, sedit.NLE_FPS)}</in>", xml)+ self.assertIn("<out>-1</out>", xml)+ # AE: a comp-level marker, not a layer marker — no layer to hang it+ # off that would survive every segment being a different shape.+ self.assertIn("comp.markerProperty.setValueAtTime(1.500000,", jsx)+ self.assertIn("drop (beat)", jsx)++ def test_an_unlabelled_marker_falls_back_to_its_kind(self):+ res, xml, jsx = self._export(+ sedit.markers_of({"markers": [{"id": "m1", "at": 0.0, "kind": "lyric"}]}))+ self.assertIn("<name>Lyric</name>", xml)+ self.assertIn("<comment>lyric</comment>", xml)+ self.assertIn("new MarkerValue(\"Lyric\")", jsx)+ self.assertNotIn("Lyric (lyric)", jsx) # no redundant kind suffix++ def test_several_markers_stay_in_film_order_and_none_are_dropped(self):+ res, xml, jsx = self._export(+ sedit.markers_of({"markers": [+ {"id": "z", "at": 3.0, "kind": "note", "label": "outro"},+ {"id": "a", "at": 0.5, "kind": "beat", "label": "intro"},+ ]}))+ self.assertEqual(res["markers"], 2)+ self.assertEqual(xml.count("<marker>"), 2)+ self.assertEqual(jsx.count("markerProperty.setValueAtTime"), 2)+ # markers_of already sorts by `at`; the writers must not re-shuffle.+ self.assertLess(xml.index("intro"), xml.index("outro"))+ self.assertLess(jsx.index("intro"), jsx.index("outro"))++ def test_markers_sit_after_media_and_before_the_sequence_closes(self):+ res, xml, jsx = self._export(+ sedit.markers_of({"markers": [{"id": "m1", "at": 1.0, "kind": "note"}]}))+ self.assertLess(xml.index("</media>"), xml.index("<marker>"))+ self.assertLess(xml.index("<marker>"), xml.index("</sequence>"))+++class TheAspectValidation(unittest.TestCase):+ def test_a_legal_aspect_validates(self):+ for a in ("16:9", "9:16", "1:1"):+ self.assertEqual(_codes(_doc([], settings={"aspect": a})), [])++ def test_an_unknown_aspect_is_refused(self):+ self.assertIn("settings_aspect", _codes(_doc([], settings={"aspect": "4:3"})))+++# =============================================================================+# THE RENDER-TIME CROP+# =============================================================================+class TheAspectCrop(unittest.TestCase):+ def test_16_9_is_a_no_op(self):+ self.assertIsNone(panel._sb_crop_to_aspect("/x/f.mp4", "16:9"))++ def test_an_unknown_key_is_a_no_op(self):+ self.assertIsNone(panel._sb_crop_to_aspect("/x/f.mp4", "4:3"))++ def test_9_16_crops_the_width_not_the_height(self):+ with mock.patch("storyboard_edit.probe_media", return_value={"w": 1920, "h": 1080}), \+ mock.patch.object(panel.subprocess, "run") as run, \+ mock.patch.object(panel.os, "replace") as replace:+ err = panel._sb_crop_to_aspect("/x/f.mp4", "9:16")+ self.assertIsNone(err)+ run.assert_called_once()+ cmd = run.call_args[0][0]+ vf = cmd[cmd.index("-vf") + 1]+ # target height stays 1080 (the full source height fits), target+ # width = 1080 * 9/16 = 607.5 -> round-half-to-even -> 608.+ self.assertIn("crop=608:1080:", vf)+ replace.assert_called_once()++ def test_1_1_crops_the_taller_dimension(self):+ with mock.patch("storyboard_edit.probe_media", return_value={"w": 1920, "h": 1080}), \+ mock.patch.object(panel.subprocess, "run") as run, \+ mock.patch.object(panel.os, "replace"):+ panel._sb_crop_to_aspect("/x/f.mp4", "1:1")+ cmd = run.call_args[0][0]+ vf = cmd[cmd.index("-vf") + 1]+ self.assertIn("crop=1080:1080:", vf)++ def test_unreadable_source_reports_an_error_not_an_exception(self):+ with mock.patch("storyboard_edit.probe_media", return_value=None):+ err = panel._sb_crop_to_aspect("/x/f.mp4", "9:16")+ self.assertIsNotNone(err)++ def test_ffmpeg_failure_reports_and_cleans_up_the_temp_file(self):+ import subprocess as sp+ with mock.patch("storyboard_edit.probe_media", return_value={"w": 1920, "h": 1080}), \+ mock.patch.object(panel.subprocess, "run",+ side_effect=sp.CalledProcessError(1, "ffmpeg")), \+ mock.patch.object(panel.Path, "unlink") as unlink:+ err = panel._sb_crop_to_aspect("/x/f.mp4", "9:16")+ self.assertIsNotNone(err)+ unlink.assert_called_once()+++# =============================================================================+# THE RENDER PATH WIRES THE CROP IN+# =============================================================================+class TheRenderEditAppliesAspect(unittest.TestCase):+ def test_aspect_is_applied_after_a_successful_assembly(self):+ edit = sedit.normalise_edit(_doc(+ [_clip("a", "/x/a.mp4", 0.0, 4.0, 0.0)], settings={"aspect": "9:16"}))+ board = {"id": "b1", "shots": []}+ fake_film = {"ok": True, "path": "/out/film.mp4", "width": 1920, "height": 1080}+ with mock.patch.object(panel, "_sbe_import", return_value=sedit), \+ mock.patch.object(panel, "_sb_film_dir_for_write", return_value=Path("/out")), \+ mock.patch.object(panel, "_sb_deliver", return_value={"format": "h264", "size": "native",+ "finish": "none", "label": "H.264"}), \+ mock.patch.object(panel, "_sb_film_name", return_value="film.mp4"), \+ mock.patch.object(panel, "_sb_assemble_film", return_value=dict(fake_film)), \+ mock.patch.object(panel, "_sb_crop_to_aspect", return_value=None) as crop:+ got = panel._sbe_render_edit(board, edit)+ crop.assert_called_once_with("/out/film.mp4", "9:16", deliver=mock.ANY)+ self.assertEqual(got["aspect"], "9:16")+ self.assertEqual(got["width"], 608)+ self.assertEqual(got["height"], 1080)++ def test_a_crop_failure_is_disclosed_not_fatal(self):+ edit = sedit.normalise_edit(_doc(+ [_clip("a", "/x/a.mp4", 0.0, 4.0, 0.0)], settings={"aspect": "1:1"}))+ board = {"id": "b1", "shots": []}+ fake_film = {"ok": True, "path": "/out/film.mp4", "width": 1920, "height": 1080}+ with mock.patch.object(panel, "_sbe_import", return_value=sedit), \+ mock.patch.object(panel, "_sb_film_dir_for_write", return_value=Path("/out")), \+ mock.patch.object(panel, "_sb_deliver", return_value={"format": "h264", "size": "native",+ "finish": "none", "label": "H.264"}), \+ mock.patch.object(panel, "_sb_film_name", return_value="film.mp4"), \+ mock.patch.object(panel, "_sb_assemble_film", return_value=dict(fake_film)), \+ mock.patch.object(panel, "_sb_crop_to_aspect", return_value="ffmpeg is missing"):+ got = panel._sbe_render_edit(board, edit)+ self.assertTrue(got["ok"]) # the render itself still succeeded+ self.assertIn("ffmpeg is missing", got["aspect_note"])+ self.assertEqual(got["width"], 1920) # unmodified — the crop never landed++ def test_16_9_never_calls_the_crop_at_all(self):+ edit = sedit.normalise_edit(_doc([_clip("a", "/x/a.mp4", 0.0, 4.0, 0.0)]))+ board = {"id": "b1", "shots": []}+ fake_film = {"ok": True, "path": "/out/film.mp4", "width": 1920, "height": 1080}+ with mock.patch.object(panel, "_sbe_import", return_value=sedit), \+ mock.patch.object(panel, "_sb_film_dir_for_write", return_value=Path("/out")), \+ mock.patch.object(panel, "_sb_deliver", return_value={"format": "h264", "size": "native",+ "finish": "none", "label": "H.264"}), \+ mock.patch.object(panel, "_sb_film_name", return_value="film.mp4"), \+ mock.patch.object(panel, "_sb_assemble_film", return_value=dict(fake_film)), \+ mock.patch.object(panel, "_sb_crop_to_aspect") as crop:+ panel._sbe_render_edit(board, edit)+ crop.assert_not_called()+++# =============================================================================+# THE CLIENT MODEL+# =============================================================================+def run_client(body: str) -> dict:+ import json+ import subprocess as sp+ import tempfile+ from test_storyboard_editor_ui import (FUNCTIONS, NODE, SHIM,+ extract_function, panel_source)+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = panel_source()+ script = (SHIM + "\n".join(extract_function(n, src) for n in FUNCTIONS)+ + "\nconst out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out));\n")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = sp.run([NODE, str(path)], capture_output=True, text=True, timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)+++class TheClientMarkerModel(unittest.TestCase):+ def test_add_sorts_by_time(self):+ r = run_client("""+let ms = [];+ms = sbeMarkerAdd(ms, 5.0, 'beat', '');+ms = sbeMarkerAdd(ms, 1.0, 'lyric', 'hey');+out.order = ms.map(m => m.at);+out.kinds = ms.map(m => m.kind);+""")+ self.assertEqual(r["order"], [1.0, 5.0])+ self.assertEqual(r["kinds"], ["lyric", "beat"])++ def test_remove_and_set_kind(self):+ r = run_client("""+let ms = sbeMarkerAdd([], 2.0, 'note', '');+const id = ms[0].id;+ms = sbeMarkerSetKind(ms, id, 'beat');+out.kind = ms[0].kind;+ms = sbeMarkerRemove(ms, id);+out.left = ms.length;+""")+ self.assertEqual(r["kind"], "beat")+ self.assertEqual(r["left"], 0)++ def test_negative_at_clamps_to_zero(self):+ r = run_client("out.m = sbeMarkerAdd([], -5, 'note', '')[0];")+ self.assertEqual(r["m"]["at"], 0)+++class TheClientCopyPaste(unittest.TestCase):+ def test_paste_attrs_copies_grade_frame_fx_speed_only(self):+ r = run_client("""+const src = { id: 'a', kind: 'video', path: '/x/a.mp4', start: 0, end: 8, film_start: 0, film_end: 4,+ adjust: { exposure: 0.2 }, frame: { zoom: 2 }, fx: { fade_in: 0.5 }, speed: 2.0 };+const dst = { id: 'b', kind: 'video', path: '/x/b.mp4', start: 1, end: 5, film_start: 10, film_end: 14 };+const r = sbeClipboardPasteAttrs(lay([src, dst]), ['b'], src);+out.ok = r.ok;+const b = sbeById(r.clips, 'b');+out.adjust = b.adjust; out.frame = b.frame; out.fx = b.fx; out.speed = b.speed;+out.film_start = b.film_start; out.path = b.path; // position and identity untouched+// EDITOR-5: speed is timing — the window stays, the slot follows it.+out.window = [b.start, b.end]; out.film_end = b.film_end;+""")+ self.assertTrue(r["ok"])+ self.assertEqual(r["adjust"], {"exposure": 0.2})+ self.assertEqual(r["frame"], {"zoom": 2})+ self.assertEqual(r["fx"], {"fade_in": 0.5})+ self.assertEqual(r["speed"], 2.0)+ self.assertEqual(r["film_start"], 10) # the cut never moves+ self.assertEqual(r["path"], "/x/b.mp4") # identity never changes+ self.assertEqual(r["window"], [1, 5]) # nor does the source window+ self.assertEqual(r["film_end"], 12) # 4 s at 2x plays in 2 s++ def test_paste_attrs_refuses_a_locked_clip(self):+ r = run_client("""+const src = { id: 'a', kind: 'video', adjust: { exposure: 0.1 } };+const dst = { id: 'b', kind: 'video', locked: true };+const r = sbeClipboardPasteAttrs([src, dst], ['b'], src);+out.ok = r.ok;+""")+ self.assertFalse(r["r"]["ok"] if "r" in r else r["ok"])++ def test_paste_clips_inserts_new_clips_with_the_sources_look(self):+ r = run_client("""+const src = { id: 'a', kind: 'video', path: '/x/a.mp4', start: 1, end: 4, film_start: 0, film_end: 3,+ duration: 20, adjust: { exposure: 0.1 } };+const r = sbeClipboardPasteClips([], [src], 0);+out.ok = r.ok;+out.n = r.clips.length;+out.newId = r.clips[0].id !== 'a';+out.adjust = r.clips[0].adjust;+out.path = r.clips[0].path;+""")+ self.assertTrue(r["ok"])+ self.assertEqual(r["n"], 1)+ self.assertTrue(r["newId"])+ self.assertEqual(r["adjust"], {"exposure": 0.1})+ self.assertEqual(r["path"], "/x/a.mp4")+++class TheClientSeqAspect(unittest.TestCase):+ def test_default_is_16_9(self):+ r = run_client("""+SBE.edit = {};+out.a = sbeSeqAspect();+""")+ self.assertEqual(r["a"], "16:9")++ def test_set_reads_back(self):+ r = run_client("""+SBE.open = true; SBE.id = 'sb_1'; SBE.edit = {};+SBE.dirty = false;+sbeSetSeqAspect('9:16');+out.a = sbeSeqAspect();+out.dirty = SBE.dirty;+""")+ self.assertEqual(r["a"], "9:16")+ self.assertTrue(r["dirty"])++ def test_an_unknown_key_is_ignored(self):+ r = run_client("""+SBE.open = true; SBE.id = 'sb_1'; SBE.edit = {};+sbeSetSeqAspect('4:3');+out.a = sbeSeqAspect();+""")+ self.assertEqual(r["a"], "16:9")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_film_switcher.py b/test_editor_film_switcher.pyindex 535bed8..83b7f24 100644--- a/test_editor_film_switcher.py+++ b/test_editor_film_switcher.py@@ -38,7 +38,8 @@ FETCHES = [];NEXT = { status: 200, body: { boards: [{ id: 'sb_a', title: 'Night Drive', clips: 3 },{ id: 'sb_b', title: 'Divorce <v2>', clips: 1 },- { id: 'sb_c', title: 'Not rendered yet', clips: 0 } ] } };+ { id: 'sb_c', title: 'Not rendered yet', clips: 0 },+ { id: 'sb_d', title: 'Cut from imports', clips: 0, has_timeline: true } ] } };await sbeFilmsToggle();out.asked = FETCHES.map(f => f.url);out.open = !els.sbeFilmsMenu.hidden;@@ -93,6 +94,10 @@ function escapeHtml(s) {self.assertNotIn("Not rendered yet", html)self.assertEqual(html.count('aria-current="true"'), 1)self.assertIn("sbeFilmsPick('sb_b')", html)+ # FILM-43: a film cut from imported/Video-tab clips has a timeline+ # and zero rendered shots of its own — `has_timeline` keeps it in+ # the list where `clips > 0` alone would have dropped it.+ self.assertIn("Cut from imports", html)self.assertTrue(self.r["noteHidden"])def test_picking_another_film_opens_it_and_the_open_one_is_a_no_op(self):diff --git a/test_editor_film_sync.py b/test_editor_film_sync.pynew file mode 100644index 0000000..47179a0--- /dev/null+++ b/test_editor_film_sync.py@@ -0,0 +1,365 @@+#!/usr/bin/env python3+"""FILM-05 — "sync to song" and "Auto-align lip-sync".++Locked here:+ * `_lipsync_best_lag_core` — the pure cross-correlation search shared by+ the self-check (`take_lipsync_score`) and the new song check+ (`take_lipsync_best_lag_vs_song`). Tested with synthetic series so the+ SIGN of the returned lag can be trusted without a real face and voice+ on hand: a positive lag means the mouth matches reference content+ further ALONG the reference — later — than where the clip sits today.+ * `take_lipsync_score` / `_take_lipsync_score_and_lag` — the refactor+ that split the lag out of the score keeps the score identical (the gate+ that already ships mocks this function; this file checks the real+ implementation is still the same shape it was).+ * The client's `sbeSongSyncOffset` / `sbeSnapToSong` — measured against a+ synthetic shot whose `audio_start_time` is known, the same numbers the+ report published for the owner's cut.+ * FILM-05 item 4 — `sbeSongLocked` (the pure predicate) run live in node+ against synthetic shots, and `sbeOnTrackDown`'s guard checked against+ the real extracted source: move/movemany/reorder refuse a song-locked+ clip, trim/roll/slip do not (coordinator follow-up, 2026-09-29 — Editor+ side only, board's own lock is FILM-21).++Run: ./ltx-2-mlx/env/bin/python3.11 -m pytest -q test_editor_film_sync.py+"""+from __future__ import annotations++import inspect+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+from test_storyboard_editor_ui import (FUNCTIONS, NODE, SHIM, # noqa: E402+ extract_function, panel_source)++try:+ import numpy as np+ HAVE_NUMPY = True+except Exception: # noqa: BLE001+ HAVE_NUMPY = False++[email protected](HAVE_NUMPY, "numpy not importable")+class TheLagSearchCore(unittest.TestCase):+ def test_a_shifted_slice_recovers_its_own_shift_as_the_lag(self):+ # A reference series long enough to search ±6 either side of head=50,+ # with enough structure (not a pure sine, which is its own alias at+ # some lag) that only one offset correlates near 1.0.+ rng = np.random.default_rng(7)+ ref = rng.normal(size=100).cumsum()+ head = 50+ shift = 3+ mouth = ref[head + shift: head + shift + 20]+ got = panel._lipsync_best_lag_core(mouth, ref, head, 6)+ self.assertIsNotNone(got)+ score, lag = got+ self.assertEqual(lag, shift)+ self.assertGreater(score, 0.99)++ def test_a_negative_shift_recovers_a_negative_lag(self):+ rng = np.random.default_rng(11)+ ref = rng.normal(size=100).cumsum()+ head = 50+ mouth = ref[head - 4: head - 4 + 20]+ score, lag = panel._lipsync_best_lag_core(mouth, ref, head, 6)+ self.assertEqual(lag, -4)++ def test_no_match_in_range_returns_none_rather_than_a_guess(self):+ rng = np.random.default_rng(3)+ ref = rng.normal(size=40) # too short to hold head+search+n+ mouth = rng.normal(size=20)+ self.assertIsNone(panel._lipsync_best_lag_core(mouth, ref, 30, 6))++ def test_flat_series_refuses_rather_than_correlating_noise(self):+ ref = [0.0] * 100+ mouth = [0.0] * 20+ self.assertIsNone(panel._lipsync_best_lag_core(mouth, ref, 50, 6))+++class TheScoreRefactorIsIdentical(unittest.TestCase):+ """The split into `_take_lipsync_score_and_lag` must not change what+ `take_lipsync_score` returns — the gate's mocks stand in for it, so+ nothing else proves the real function is unchanged in shape."""++ def test_take_lipsync_score_still_exists_and_reads_the_lag_helper(self):+ src = inspect.getsource(panel.take_lipsync_score)+ self.assertIn("_take_lipsync_score_and_lag", src)++ def test_missing_cv2_is_none_not_an_exception(self):+ import unittest.mock as mock+ import builtins+ real_import = builtins.__import__++ def blocked(name, *a, **kw):+ if name == "cv2":+ raise ImportError("no cv2")+ return real_import(name, *a, **kw)++ with mock.patch.object(builtins, "__import__", side_effect=blocked):+ self.assertIsNone(panel.take_lipsync_score("/x/nope.mp4"))+ self.assertIsNone(panel.take_lipsync_best_lag("/x/nope.mp4"))+ self.assertIsNone(+ panel.take_lipsync_best_lag_vs_song("/x/nope.mp4", "/x/song.wav", 0.0, 4.0))+++# =============================================================================+# The client half — sbeSongSyncOffset / sbeSnapToSong+# =============================================================================+def run_client(body: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ import json+ import subprocess as sp+ import tempfile+ src = panel_source()+ script = (SHIM + "\n".join(extract_function(n, src) for n in FUNCTIONS)+ + "\nconst out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out));\n")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = sp.run([NODE, str(path)], capture_output=True, text=True, timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)+++class TheSongSyncReadout(unittest.TestCase):+ def test_offset_matches_the_reports_own_measurement_shape(self):+ # Owner's cut: audio_start_time + source_in is the expected film+ # position; the clip sat 0.19s LATE of it (one of the report's+ # measured offsets).+ r = run_client("""+const shot = { mode: 'a2v', audio_start_time: 10.0 };+const c = { id: 'a', kind: 'video', start: 0.0, end: 4.0,+ film_start: 10.19, film_end: 14.19 };+out.off = sbeSongSyncOffset(c, shot);+""")+ self.assertAlmostEqual(r["off"], 0.19, places=6)++ def test_offset_accounts_for_a_trimmed_head(self):+ r = run_client("""+const shot = { mode: 'a2v', audio_start_time: 10.0 };+const c = { id: 'a', kind: 'video', start: 1.5, end: 5.0,+ film_start: 11.5, film_end: 15.0 };+out.off = sbeSongSyncOffset(c, shot);+""")+ self.assertAlmostEqual(r["off"], 0.0, places=6)++ def test_non_a2v_shots_have_no_song_offset(self):+ r = run_client("""+const shot = { mode: 'text', audio_start_time: 10.0 };+const c = { id: 'a', kind: 'video', start: 0, end: 4, film_start: 10.19, film_end: 14.19 };+out.off = sbeSongSyncOffset(c, shot);+""")+ self.assertIsNone(r["off"])++ def test_snap_to_song_is_a_slip_that_zeroes_the_offset(self):+ r = run_client("""+const shot = { mode: 'a2v', audio_start_time: 10.0 };+SBE.clips = [{ id: 'a', kind: 'video', start: 0.0, end: 4.0, duration: 20.0,+ film_start: 10.19, film_end: 14.19, locked: false }];+SBE.pool = [{ path: undefined, ...shot }];+// sbeShotForClip matches by path; give the clip and the pool row the same one.+SBE.clips[0].path = '/x/a.mp4';+SBE.pool[0].path = '/x/a.mp4';+sbeSnapToSong('a');+const c = sbeById(SBE.clips, 'a');+out.start = c.start;+out.film_start = c.film_start; // the slot must not move+out.offset_after = sbeSongSyncOffset(c, shot);+""")+ self.assertAlmostEqual(r["film_start"], 10.19)+ self.assertAlmostEqual(r["offset_after"], 0.0, places=2)+++class TheSongLockPredicate(unittest.TestCase):+ """`sbeSongLocked` — the pure check behind FILM-05 item 4's move guard."""++ def test_an_a2v_clip_with_a_known_start_time_is_locked(self):+ r = run_client("""+SBE.pool = [{ path: '/x/a.mp4', mode: 'a2v', audio_start_time: 10.0 }];+const c = { id: 'a', kind: 'video', path: '/x/a.mp4', start: 0.0, end: 4.0,+ film_start: 10.0, film_end: 14.0 };+out.locked = sbeSongLocked(c);+""")+ self.assertTrue(r["locked"])++ def test_a_non_a2v_shot_is_never_locked(self):+ r = run_client("""+SBE.pool = [{ path: '/x/a.mp4', mode: 'text', audio_start_time: 10.0 }];+const c = { id: 'a', kind: 'video', path: '/x/a.mp4', start: 0.0, end: 4.0,+ film_start: 10.0, film_end: 14.0 };+out.locked = sbeSongLocked(c);+""")+ self.assertFalse(r["locked"])++ def test_an_a2v_shot_with_no_audio_start_time_yet_is_not_locked(self):+ # The song offset is undefined without a start time — nothing to+ # protect, and nothing sbeSongSyncOffset could even measure.+ r = run_client("""+SBE.pool = [{ path: '/x/a.mp4', mode: 'a2v', audio_start_time: null }];+const c = { id: 'a', kind: 'video', path: '/x/a.mp4', start: 0.0, end: 4.0,+ film_start: 10.0, film_end: 14.0 };+out.locked = sbeSongLocked(c);+""")+ self.assertFalse(r["locked"])++ def test_a_clip_with_no_matching_shot_is_not_locked(self):+ r = run_client("""+SBE.pool = [];+const c = { id: 'a', kind: 'video', path: '/x/a.mp4', start: 0.0, end: 4.0,+ film_start: 10.0, film_end: 14.0 };+out.locked = sbeSongLocked(c);+""")+ self.assertFalse(r["locked"])+++class TheSongLockGuardsMoveNotTrimOrSlip(unittest.TestCase):+ """FILM-05 item 4: `sbeOnTrackDown` refuses move/movemany/reorder on a+ song-locked clip and leaves trim/roll/slip alone — trim and roll can+ never move the offset (film side and source side move together; see+ the trim comment), and slip is the sanctioned way to correct it.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()+ cls.down = extract_function("sbeOnTrackDown", cls.src)++ def test_the_guard_runs_after_mode_is_decided_and_before_the_drag_starts(self):+ # It must see the FINAL mode (roll/slip/trim already excluded by the+ # ternary above it), and it must run before `SBE.drag = {` so a+ # refused clip never enters a drag at all.+ mode_at = self.down.index("const mode = rollWith ? 'roll'")+ guard_at = self.down.index("sbeSongLocked")+ drag_at = self.down.index("SBE.drag = { id: id, mode: mode")+ self.assertLess(mode_at, guard_at)+ self.assertLess(guard_at, drag_at)++ def test_the_three_gestures_that_move_the_slot_are_all_covered(self):+ guard = self.down[self.down.index("if (mode === 'move' || mode === 'movemany'"):]+ guard = guard[:guard.index("SBE.drag = { id: id, mode: mode")]+ for m in ("'move'", "'movemany'", "'reorder'"):+ self.assertIn(m, guard)+ # ...and only those three — a bare `return` inside a wider `if` would+ # silently also catch trim/roll/slip if the boundaries ever moved.+ self.assertNotIn("'trimL'", guard)+ self.assertNotIn("'trimR'", guard)+ self.assertNotIn("'roll'", guard)+ self.assertNotIn("'slip'", guard)++ def test_movemany_checks_every_id_in_the_selection_not_just_the_primary(self):+ guard = self.down[self.down.index("if (mode === 'move' || mode === 'movemany'"):]+ guard = guard[:guard.index("SBE.drag = { id: id, mode: mode")]+ self.assertIn("sbeSelIds()", guard)+ self.assertIn(".find(", guard)++ def test_a_blocked_drag_returns_before_pointer_capture_or_undo_snapshot(self):+ guard = self.down[self.down.index("if (mode === 'move' || mode === 'movemany'"):]+ guard = guard[:guard.index("SBE.drag = { id: id, mode: mode")]+ self.assertIn("return;", guard)+ self.assertNotIn("setPointerCapture", guard)++ def test_the_toast_names_the_way_out(self):+ guard = self.down[self.down.index("if (mode === 'move' || mode === 'movemany'"):]+ guard = guard[:guard.index("SBE.drag = { id: id, mode: mode")]+ self.assertIn("phosToast(", guard)+ self.assertIn("Snap to song", guard)+ self.assertIn("slip", guard)+++# =============================================================================+# The route — /storyboard/edit/auto-align+# =============================================================================+class TheAutoAlignRoute(unittest.TestCase):+ def setUp(self):+ import tempfile+ from unittest import mock++ from test_storyboard_editor_api import FakeHandler, _board, _clip, _edit+ import storyboard+ import storyboard_editor as sedit++ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.song = self.root / "song.wav"+ self.song.write_bytes(b"x")+ self.clipfile = self.root / "s1.mp4"+ self.clipfile.write_bytes(b"x")+ self.board = _board([self.clipfile])+ self.board["shots"][0]["mode"] = "a2v"+ c = _clip(str(self.clipfile), 0.0, 4.0, 0.0, id="c1")+ self.edit = sedit.normalise_edit(+ _edit([c], audio={"path": str(self.song), "mode": "replace", "offset": 0.0}))+ bdir = self.root / "sb_t"+ bdir.mkdir()+ sedit.save_edit(bdir, self.edit)+ self.FakeHandler = FakeHandler+ self.patches = [+ mock.patch.object(panel, "STATE_DIR", self.root),+ mock.patch.object(panel, "_sbe_board_dir", return_value=bdir),+ mock.patch.object(storyboard, "load_storyboard", return_value=self.board),+ ]+ for p in self.patches:+ p.start()+ self.addCleanup(p.stop)++ def test_a_lagging_shot_is_proposed(self):+ from unittest import mock+ with mock.patch.object(panel, "take_lipsync_best_lag_vs_song",+ return_value={"score": 0.7, "lag_frames": 3, "fps": 24.0,+ "delta_sec": -0.125}):+ h = self.FakeHandler()+ h.post("edit/auto-align", {"id": "sb_t"})+ self.assertEqual(h.status, 200, h.payload)+ self.assertEqual(len(h.payload["proposals"]), 1)+ p = h.payload["proposals"][0]+ self.assertEqual(p["id"], "c1")+ self.assertEqual(p["lag_frames"], 3)+ # EDITOR-8 (Codex 4.17.0): the slip that CORRECTS a +3 frame lag is+ # three frames EARLIER in the source — the helper owns the sign.+ self.assertAlmostEqual(p["delta_sec"], -0.125)++ def test_a_shot_already_aligned_is_not_proposed(self):+ from unittest import mock+ with mock.patch.object(panel, "take_lipsync_best_lag_vs_song",+ return_value={"score": 0.9, "lag_frames": 0, "fps": 24.0,+ "delta_sec": 0.0}):+ h = self.FakeHandler()+ h.post("edit/auto-align", {"id": "sb_t"})+ self.assertEqual(h.payload["proposals"], [])++ def test_a_non_a2v_shot_is_never_scored(self):+ from unittest import mock+ self.board["shots"][0]["mode"] = "text"+ with mock.patch.object(panel, "take_lipsync_best_lag_vs_song") as fn:+ h = self.FakeHandler()+ h.post("edit/auto-align", {"id": "sb_t"})+ fn.assert_not_called()+ self.assertEqual(h.payload["proposals"], [])++ def test_no_song_refuses_with_a_reason(self):+ import storyboard_editor as sedit+ from unittest import mock+ c = sedit.new_clip(str(self.clipfile), 0.0, 4.0, 0.0, id="c1")+ edit = sedit.normalise_edit(+ {"version": sedit.EDIT_VERSION, "board_id": "sb_t", "revision": 0,+ "source": "auto", "audio": None, "beats": None, "clips": [c], "settings": {}})+ sedit.save_edit(self.root / "sb_t", edit)+ h = self.FakeHandler()+ h.post("edit/auto-align", {"id": "sb_t"})+ self.assertEqual(h.status, 400)+ self.assertIn("song", h.payload["error"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_film_takes.py b/test_editor_film_takes.pynew file mode 100644index 0000000..87f8c1c--- /dev/null+++ b/test_editor_film_takes.py@@ -0,0 +1,166 @@+#!/usr/bin/env python3+"""FILM-07 — a board re-render reaches the timeline.++Before this: re-rolling a shot already on the timeline (Rewrite, Retry, New+still, "Render remaining") overwrote `draft_output`/`final_output` with no+memory of what it replaced, so a clip on the timeline that named the OLD+path was never told anything had changed — Export shipped the old take, and+the new one sat in the "rendered, not placed" list whose only action was+Place (which appends, FILM-08).++Locked here:+ * `_sb_reconcile` keeps the superseded path in `shots[n]["takes"]` every+ time a re-render changes `draft_output` or `final_output`, capped, and+ never records a no-op (same path twice).+ * `_sbe_relinks` offers the shot's CURRENT output against any timeline+ clip whose path is one of those superseded takes — flagged `retake`,+ the same one-clip-at-a-time shape an actual retake already has, and+ never re-offered once adopted.+ * `_sbe_board_clips` carries what a Retake dialog needs to say what will+ render (FILM-53): `mode`, `audio`, `audio_start_time`, `est_min`.++Run: ./ltx-2-mlx/env/bin/python3.11 -m pytest -q test_editor_film_takes.py+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+import storyboard_editor as sedit # noqa: E402+from test_storyboard_editor_api import FakeHandler, _board, _clip, _edit # noqa: E402+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.state = Path(self.tmp.name) / "state"+ self.state.mkdir()+ self.queue_state = {"queue": [], "current": None, "history": []}+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "STATE", self.queue_state),+ mock.patch.object(panel, "persist_queue", lambda: None),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def load(self, bid):+ return storyboard.load_storyboard(self.state, bid)+++def _reconcile(board, index):+ with mock.patch.object(panel, "_sb_job_index", return_value=index):+ return panel._sb_reconcile(board)+++class TheTakeHistory(Sandbox):+ def test_a_rerender_records_the_old_path_in_takes(self):+ board = self.save(_board([Path("/o/s1_v1.mp4")]))+ board["shots"][0]["draft_job_id"] = "j2"+ index = {"j2": {"status": "done", "output_path": "/o/s1_v2.mp4"}}+ self.assertTrue(_reconcile(board, index))+ self.assertEqual(board["shots"][0]["draft_output"], "/o/s1_v2.mp4")+ self.assertEqual(board["shots"][0]["takes"], ["/o/s1_v1.mp4"])++ def test_a_second_rerender_appends_and_never_duplicates(self):+ board = self.save(_board([Path("/o/s1_v1.mp4")]))+ board["shots"][0]["takes"] = ["/o/s1_v0.mp4"]+ board["shots"][0]["draft_job_id"] = "j3"+ index = {"j3": {"status": "done", "output_path": "/o/s1_v2.mp4"}}+ _reconcile(board, index)+ self.assertEqual(board["shots"][0]["takes"], ["/o/s1_v0.mp4", "/o/s1_v1.mp4"])+ # the SAME output landing twice (a stale queue re-poll) is a no-op+ board["shots"][0]["draft_job_id"] = "j3"+ changed = _reconcile(board, index)+ self.assertFalse(changed)+ self.assertEqual(board["shots"][0]["takes"], ["/o/s1_v0.mp4", "/o/s1_v1.mp4"])++ def test_takes_history_is_capped(self):+ board = self.save(_board([Path("/o/s1_v0.mp4")]))+ board["shots"][0]["takes"] = [f"/o/s1_v{i}.mp4" for i in range(1, 20)]+ board["shots"][0]["draft_job_id"] = "jN"+ index = {"jN": {"status": "done", "output_path": "/o/s1_vNEW.mp4"}}+ _reconcile(board, index)+ self.assertLessEqual(len(board["shots"][0]["takes"]), 20)+ self.assertEqual(board["shots"][0]["takes"][-1], "/o/s1_v0.mp4")+++class TheRelinkOffer(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.old = self.root / "s1_v1.mp4"+ self.old.write_bytes(b"x")+ self.new = self.root / "s1_v2.mp4"+ self.new.write_bytes(b"y")+ self.board = _board([self.old])+ self.board["shots"][0]["takes"] = [str(self.old)]+ self.board["shots"][0]["draft_output"] = str(self.new) # the CURRENT output+ c = _clip(str(self.old), 0.0, 4.0, 0.0, id="c1")+ self.edit = sedit.normalise_edit(_edit([c]))++ def test_a_stale_take_on_the_timeline_is_offered_flagged(self):+ rows = panel._sbe_relinks(self.board, self.edit)+ self.assertEqual(len(rows), 1)+ self.assertTrue(rows[0]["retake"])+ self.assertEqual([rows[0]["id"], rows[0]["path"], rows[0]["to"]],+ ["c1", str(self.old), str(self.new)])++ def test_a_clip_already_playing_the_current_take_is_not_offered(self):+ c = _clip(str(self.new), 0.0, 4.0, 0.0, id="c1")+ edit = sedit.normalise_edit(_edit([c]))+ self.assertEqual(panel._sbe_relinks(self.board, edit), [])++ def test_a_take_whose_file_is_gone_is_never_offered(self):+ self.new.unlink()+ self.assertEqual(panel._sbe_relinks(self.board, self.edit), [])++ def test_adopting_it_keeps_film_start_and_the_trim(self):+ bdir = self.root / "sb_t"+ bdir.mkdir()+ sedit.save_edit(bdir, self.edit)+ with mock.patch.object(panel, "STATE_DIR", self.root), \+ mock.patch.object(panel, "_sbe_board_dir", return_value=bdir), \+ mock.patch.object(storyboard, "load_storyboard", return_value=self.board), \+ mock.patch.object(storyboard, "save_storyboard"), \+ mock.patch.object(panel, "_sbe_proxy_now"):+ h = FakeHandler()+ h.post("edit/relink", {"id": "sb_t", "only": "c1"})+ self.assertEqual(h.status, 200, h.payload)+ got = sedit.load_edit(bdir)["clips"][0]+ self.assertEqual(got["path"], str(self.new))+ self.assertEqual([got["start"], got["end"], got["film_start"]], [0.0, 4.0, 0.0])+ # adopted — no longer offered+ self.assertEqual(panel._sbe_relinks(self.board, sedit.load_edit(bdir)), [])+++class TheBoardClipsCarryRetakeContext(unittest.TestCase):+ def test_mode_audio_and_estimate_ride_along(self):+ p = Path(tempfile.mkdtemp()) / "s1.mp4"+ p.write_bytes(b"x")+ board = _board([p])+ board["shots"][0].update({"mode": "a2v", "audio": "/x/song.wav",+ "audio_start_time": 12.5, "duration_s": 4.0})+ rows = panel._sbe_board_clips(board)+ self.assertEqual(rows[0]["mode"], "a2v")+ self.assertEqual(rows[0]["audio"], "/x/song.wav")+ self.assertEqual(rows[0]["audio_start_time"], 12.5)+ self.assertIn("draft", rows[0]["est_min"])+ self.assertIn("final", rows[0]["est_min"])+ self.assertGreaterEqual(rows[0]["est_min"]["draft"], 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_save_integrity.py b/test_editor_save_integrity.pyindex c78a9e6..07d6d44 100644--- a/test_editor_save_integrity.py+++ b/test_editor_save_integrity.py@@ -230,15 +230,22 @@ global.confirm = () => true;const SB = { id: '' };function workflowSwitch() {}function sbFilmOpen() {}+function sbeNoticeHoles() {}+function sbePaintRenderChip() {}+function sbeOpenFilmScreen() {}+function sbeRevealRender() {}+global.document = { createElement: () => ({ appendChild() {} }) };""")def test_render_waits_for_the_save_in_flight(self):self.assertEqual(self.r["urlsWhileSaving"], ["/storyboard/edit/save"])+ # FILM-28: the render is a job now — the door it knocks on once the+ # save lands is /render/start, not the old one-shot /render.self.assertEqual(self.r["urlsAfter"],- ["/storyboard/edit/save", "/storyboard/edit/render"])+ ["/storyboard/edit/save", "/storyboard/edit/render/start"])def test_a_save_that_does_not_land_stops_the_render(self):- self.assertNotIn("/storyboard/edit/render", self.r["urlsAfterConflict"])+ self.assertNotIn("/storyboard/edit/render/start", self.r["urlsAfterConflict"])@@ -323,6 +330,7 @@ out.cleanAdopted = adopted.length;""", extra=("sbeLoad", "sbeAdoptMeta"), shim=r"""const ED = { src: 'gallery' };function sbePaintRelink() {}+function sbePaintOffline() {}function edPoolRefresh() {}async function sbeFetchPeaks() {}function sbeShowDocError() {}@@ -367,7 +375,7 @@ async function renderMusic() {FETCHES = []; SBE.dirty = false; SBE.rendering = false;NEXT = { status: 200, body: { ok: false, error: 'stop here' } };await sbeRenderFilm();- const f = FETCHES.find(x => x.url === '/storyboard/edit/render');+ const f = FETCHES.find(x => x.url === '/storyboard/edit/render/start');return f ? (f.body.get('music') || '') : null;}// Film A, with song A.@@ -403,6 +411,7 @@ function sbFilmOpen() {}function sbeSetMusicMode() {}function sbeSyncMusic() {}function sbePaintRelink() {}+function sbePaintOffline() {}function sbeDeliverPaint() {}function edPoolRefresh() {}async function sbeFetchPeaks() {}@@ -411,6 +420,8 @@ function sbeStop() {}function sbeVersionsClose() {}function edRemember() {}function edShowPicker() {}+function sbeNoticeHoles() {}+function sbePaintRenderChip() {}global.window = { addEventListener() {}, removeEventListener() {} };""")@@ -431,5 +442,486 @@ global.window = { addEventListener() {}, removeEventListener() {} };self.assertEqual(self.r["typedKept"], "/songs/typed.wav")+class RenderStaysOnTheTimeline(unittest.TestCase):+ """FILM-24 — a finished render used to switch to Storyboard and open the+ Film screen unconditionally. Driven: the render must not navigate, and+ must paint the "last render" chip instead.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+els.sbeMusic = Object.assign(stubEl('sbeMusic'), { value: '' });+els.sbeRenderBtn = Object.assign(stubEl('sbeRenderBtn'), { textContent: 'Render' });+function mkNode() {+ return { textContent: '', className: '', onclick: null, href: '',+ _kids: [], appendChild(c) { this._kids.push(c); } };+}+global.document = { createElement: () => mkNode() };+els.sbeRenderChip = Object.assign(stubEl('sbeRenderChip', true),+ { _kids: [], appendChild(c) { this._kids.push(c); } });+SBE.open = true; SBE.id = 'F'; SBE.activeDraft = 'draft-1'; SBE.session = 's1';+// FILM-28: the render is a job now — /start answers with a job id, and+// sbeRenderPoll (kicked off, not awaited, inside sbeRenderFilm) is what+// actually reaches a terminal state. The fetch mock answers every URL with+// the SAME body regardless of which route asked, so one body that already+// carries both a "job" (what /start reads) and a "done" status (what+// /status reads) lets the very first poll settle immediately — sbeRenderFilm+// itself only awaits the /start leg, so the test drives the rest with tick().+NEXT = { status: 200, body: { ok: true, job: 'j1', state: 'done',+ result: { ok: true, clips: 2, duration: 12.4,+ path: '/out/sb/f_film.mp4',+ deliver: { format: 'h264' } } } };+await sbeRenderFilm();+for (let i = 0; i < 8; i++) await tick();+out.switched = switched.slice();+out.chipHidden = els.sbeRenderChip.hidden;+out.chipKids = els.sbeRenderChip._kids.length;+out.toastSaysReady = toasts.some(t => t.indexOf('Film ready') === 0);+out.renderingClearedAfter = SBE.rendering;+""", extra=("sbeRenderFilm", "sbeRenderPoll", "sbeRenderSettle",+ "sbeRenderCancel", "sbeRenderFinish", "sbeOpenFilmScreen",+ "sbePaintRenderChip", "sbeRevealRender", "sbeNoticeHoles",+ "sbeCloseAllGaps", "sbeCloseGapAt"), shim=r"""+const ED = { src: 'gallery' };+function sbeDeliverGet() { return { format: 'h264', size: 'native', finish: 'none' }; }+function sbeMusicMode() { return 'under'; }+global.confirm = () => true;+const SB = { id: '' };+const switched = [];+function workflowSwitch(n) { switched.push(n); }+function sbFilmOpen() { switched.push('sbFilmOpen'); }+async function sbOpen() { switched.push('sbOpen'); }+global.window = { addEventListener() {}, removeEventListener() {} };+""")++ def test_a_finished_render_never_switches_tabs_or_opens_the_film(self):+ self.assertEqual(self.r["switched"], [])++ def test_it_paints_the_last_render_chip_instead(self):+ self.assertFalse(self.r["chipHidden"])+ # a label plus two actions (Open, Show in Finder)+ self.assertEqual(self.r["chipKids"], 3)++ def test_the_toast_still_says_the_film_is_ready(self):+ self.assertTrue(self.r["toastSaysReady"])++ def test_rendering_clears_once_the_job_settles(self):+ # FILM-28: the poll loop must leave SBE.rendering behind it, not+ # stuck true because the job split left some path that forgot to+ # settle.+ self.assertFalse(self.r["renderingClearedAfter"])+++class OfflineMediaBlocksTheRender(unittest.TestCase):+ """FILM-15 — an offline clip used to render silently: a shorter,+ out-of-sync film behind a success toast, and a black preview with no+ explanation. Render now refuses, named, before spending an encode.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+SBE.clips[0].id = 'a'; SBE.clips[0].title = 'The bow shot';+els.sbeMusic = Object.assign(stubEl('sbeMusic'), { value: '' });+els.sbeRenderBtn = Object.assign(stubEl('sbeRenderBtn'), { textContent: 'Render' });+els.sbeOffline = Object.assign(stubEl('sbeOffline', true), {});+els.sbeOfflineText = stubEl('sbeOfflineText');+global.document = { createElement: () => ({ appendChild() {} }) };+SBE.open = true; SBE.id = 'F'; SBE.activeDraft = 'draft-1';+SBE.dirty = false; // isolate the offline gate from the save gate+SBE.offline = ['a'];+FETCHES = [];+const before = toasts.length;+await sbeRenderFilm();+out.hitRender = FETCHES.some(f => f.url === '/storyboard/edit/render');+out.toasted = toasts.slice(before);+out.barHidden = els.sbeOffline.hidden;+out.barText = els.sbeOfflineText.textContent;+out.rendering = !!SBE.rendering;+""", extra=("sbeRenderFilm", "sbeClipOffline", "sbePaintOffline",+ "sbeNoticeHoles", "sbeOpenFilmScreen", "sbePaintRenderChip",+ "sbeRevealRender", "sbeNiceName"), shim=r"""+const ED = { src: 'gallery' };+function sbeDeliverGet() { return { format: 'h264', size: 'native', finish: 'none' }; }+function sbeMusicMode() { return 'under'; }+global.confirm = () => true;+const SB = { id: '' };+function workflowSwitch() {}+function sbFilmOpen() {}+async function sbOpen() {}+global.window = { addEventListener() {}, removeEventListener() {} };+""")++ def test_the_render_never_reaches_the_server(self):+ self.assertFalse(self.r["hitRender"])+ self.assertFalse(self.r["rendering"]) # the button never went into flight++ def test_it_names_the_offline_clip_in_a_danger_toast(self):+ self.assertEqual(len(self.r["toasted"]), 1)+ self.assertIn("offline", self.r["toasted"][0])+ self.assertIn("bow shot", self.r["toasted"][0])++ def test_the_offline_bar_is_shown_too(self):+ self.assertFalse(self.r["barHidden"])+ self.assertIn("offline", self.r["barText"])+++class ClipOfflineFlag(unittest.TestCase):+ """`sbeClipOffline` — matched by id first, path second (a clip with no+ id yet, e.g. mid-mutation, still has to be findable by what it plays)."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(r"""+SBE.offline = ['c1', '/x/by-path.mp4'];+out.byId = sbeClipOffline({ id: 'c1', path: '/x/a.mp4' });+out.byPath = sbeClipOffline({ id: 'c9', path: '/x/by-path.mp4' });+out.neither = sbeClipOffline({ id: 'c2', path: '/x/b.mp4' });+out.noPath = sbeClipOffline({ id: 'c1' });+""", extra=("sbeClipOffline",))++ def test_matches_by_id_or_by_path(self):+ self.assertTrue(self.r["byId"])+ self.assertTrue(self.r["byPath"])+ self.assertFalse(self.r["neither"])++ def test_a_slug_with_no_path_is_never_offline(self):+ self.assertFalse(self.r["noPath"])+++class PoolAddIgnoresAFilmSwitchMidFlight(unittest.TestCase):+ """FILM-32 — `edPoolAdd` awaits the proxy build (the slow part — real+ footage, sometimes several seconds) and used to mutate `SBE.clips` with+ no check that the film it was building for is still the one open. A+ clip dropped on film A, added after the user switched to film B, landed+ in B instead.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(r"""+const _rows = [{ path: '/x/clip.mp4', kind: 'video', title: 'A clip' }];+global.document = {+ getElementById: (id) => id === 'edPoolList' ? { _rows }+ : (id === 'edPoolNote' ? els.edPoolNote : null),+};+els.edPoolNote = stubEl('edPoolNote');+async function tryIt(sameFilm) {+ SBE.open = true; SBE.id = 'A'; SBE.clips = []; SBE.edit = { clips: [] };+ SBE.dirty = false; SBE.dirtyAt = 0; SBE.saveTimer = null; SBE.backingUp = false;+ ED.suppressClick = false;+ FETCHES = []; HOLD = true;+ NEXT = { status: 200, body: { ok: true,+ clip: { path: '/x/clip.mp4', duration_s: 4, n: 1 } } };+ const p = edPoolAdd(0);+ await tick();+ if (!sameFilm) SBE.id = 'B'; // switched while the proxy built+ while (HELD.length) await release();+ await p;+ return SBE.clips.length;+}+out.landedOnSwitchedFilm = await tryIt(false);+out.landedOnSameFilm = await tryIt(true);+""", extra=("edPoolAdd",), shim=r"""+const ED = { src: 'gallery', suppressClick: false };+async function sbeLoad() {}+""")++ def test_the_clip_does_not_land_after_the_film_switched(self):+ self.assertEqual(self.r["landedOnSwitchedFilm"], 0)++ def test_the_clip_still_lands_when_the_film_did_not_change(self):+ self.assertEqual(self.r["landedOnSameFilm"], 1)+++class MusicModeSurvivesTheObjectASaveReplaces(unittest.TestCase):+ """FILM-33 — `sbeSetMusicMode` used to mutate `SBE.audio.mode` in place.+ A clean save replaces `SBE.edit` with a fresh object built from the+ server's answer but never touches `SBE.audio`, so after the FIRST save+ the two point at different objects and every mode change after that+ mutates the orphaned one — invisible to `sbeSaveBody`, which reads+ `SBE.edit.audio`. It now goes through `sbeSetAudio` (writes both+ references to the same new object) and `sbeMusicCommit` (undo + queued+ backup), like every other soundtrack gesture.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(r"""+els.sbeMusicMode = stubEl('sbeMusicMode');+els.sbeMusicWarn = Object.assign(stubEl('sbeMusicWarn', true), { textContent: '' });+SBE.audio = { path: '/x/song.wav', mode: 'under', offset: 0 };+SBE.edit = { audio: SBE.audio, clips: [] };+SBE.dirty = false; SBE.dirtyAt = 0; SBE.undo = []; SBE.saveTimer = null;+SBE.backingUp = false;+FETCHES = [];+NEXT = { status: 200, body: { ok: true, at: 1, session: {} } };+sbeSetMusicMode('replace');+for (let i = 0; i < 6; i++) await tick();+out.editAudioAfterFirst = SBE.edit.audio.mode;+out.sameObject = SBE.audio === SBE.edit.audio;+out.undoLen = SBE.undo.length;+out.backedUp = FETCHES.some(f => f.url === '/storyboard/edit/backup');++// Simulate what a clean save does: SBE.edit REPLACED, SBE.audio untouched.+SBE.edit = Object.assign({}, { audio: Object.assign({}, SBE.audio) },+ { clips: SBE.edit.clips || [] });+out.stillSameObjectAfterSave = SBE.audio === SBE.edit.audio; // expected false++// The second mode change — this is the one that used to vanish.+sbeSetMusicMode('under');+out.editAudioAfterSecond = SBE.edit.audio.mode;+out.audioAfterSecond = SBE.audio.mode;+""", extra=("sbeSetMusicMode", "sbeSetAudio", "sbeMusicCommit"))++ def test_the_first_change_lands_on_both_references(self):+ self.assertEqual(self.r["editAudioAfterFirst"], "replace")+ self.assertTrue(self.r["sameObject"])+ self.assertEqual(self.r["undoLen"], 1)+ self.assertTrue(self.r["backedUp"])++ def test_the_change_after_a_save_still_lands_where_the_save_reads_it(self):+ self.assertFalse(self.r["stillSameObjectAfterSave"]) # the save DID diverge them+ self.assertEqual(self.r["editAudioAfterSecond"], "under")+ self.assertEqual(self.r["audioAfterSecond"], "under")+++class QueueSaveWritesTheFirstEditImmediately(unittest.TestCase):+ """FILM-06 — a reload inside the 1.4s debounce used to lose the very+ first edit off a clean timeline with no backup at all. The first edit+ now writes the crash backup immediately; only the ones after it debounce.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+SBE.dirty = false; SBE.dirtyAt = 0; SBE.saveTimer = null; SBE.backingUp = false;+FETCHES = [];+NEXT = { status: 200, body: { ok: true, at: 1, session: {} } };+sbeQueueSave();+for (let i = 0; i < 8; i++) await tick();+out.firstEditTimerArmed = !!SBE.saveTimer;+out.firstEditBackedUp = FETCHES.some(f => f.url === '/storyboard/edit/backup');+// A second edit right after — this one debounces as before.+FETCHES = [];+sbeQueueSave();+out.secondEditTimerArmed = !!SBE.saveTimer;+out.secondEditBackedUpYet = FETCHES.some(f => f.url === '/storyboard/edit/backup');+""")++ def test_the_first_edit_off_clean_is_backed_up_without_waiting(self):+ self.assertTrue(self.r["firstEditBackedUp"])+ self.assertFalse(self.r["firstEditTimerArmed"])++ def test_the_edit_right_after_it_still_debounces(self):+ self.assertTrue(self.r["secondEditTimerArmed"])+ self.assertFalse(self.r["secondEditBackedUpYet"])+++class TheWatchdogStopsCallingWhenNothingChanged(unittest.TestCase):+ """FILM-57 — sbeTick's watchdog re-arms sbeQueueSave on every tick the+ document is dirty, not-saving and not-already-timered ("re-queueing is+ free"), which is correct: nothing unsaved may sit one dropped timer away+ from unprotected. What it cannot know is that the timer it just armed+ fires against content that has not changed since the last snapshot — the+ server already dedups by digest (storyboard_editor.py's `write_backup`)+ so no new file was ever written, but the reported bug was the ROUND TRIP+ itself: a fetch every 1.4s forever while the document sat dirty and+ untouched. sbeBackup now compares against its own last successful body+ and skips the network call — without a network call — when nothing+ changed; a real edit still reaches the server exactly as before."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+FETCHES = [];+NEXT = { status: 200, body: { ok: true, session: {} } };+const first = await sbeBackup(true);+out.firstCount = FETCHES.length;+out.firstOk = first;+// The watchdog's own move: re-arm and fire again with NOTHING having+// changed on screen in between.+const second = await sbeBackup(true);+out.secondCount = FETCHES.length;+out.secondOk = second;+// A real edit — a different clip end — is a different body, and reaches+// the server exactly as before.+SBE.clips = lay([clip({ id: 'a', end: 2.5 }), clip({ id: 'b', end: 3 })]);+SBE.edit = { clips: SBE.clips };+const third = await sbeBackup(true);+out.thirdCount = FETCHES.length;+out.thirdOk = third;+""")++ def test_a_repeat_with_nothing_new_never_leaves_the_tab(self):+ self.assertEqual(self.r["firstCount"], 1)+ self.assertTrue(self.r["firstOk"])+ self.assertEqual(self.r["secondCount"], 1) # unchanged — no new fetch+ self.assertTrue(self.r["secondOk"]) # still reports success++ def test_a_real_edit_still_reaches_the_server(self):+ self.assertEqual(self.r["thirdCount"], 2)+ self.assertTrue(self.r["thirdOk"])+++class UnloadBeaconsTheBackup(unittest.TestCase):+ """FILM-06 — nothing told the browser to wait for the debounce before a+ reload or close. `beforeunload`/`pagehide` now fire a `sendBeacon` at the+ same crash-backup door, with the same body `sbeSaveBody` already builds.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+const beacons = [];+global.navigator = { sendBeacon: (url, blob) => { beacons.push({ url, blob }); return true; } };+SBE.open = true; SBE.id = 'F'; SBE.activeDraft = 'draft-1'; SBE.session = 'sess1';+sbeBeaconBackup();+out.count = beacons.length;+out.url = beacons[0] && beacons[0].url;+out.body = beacons[0] ? JSON.parse(await beacons[0].blob.text()) : null;+// A clean timeline sends nothing — there is nothing to protect.+beacons.length = 0;+SBE.dirty = false;+sbeBeaconBackup();+out.cleanCount = beacons.length;+// Neither does a conflicted one — the server copy is not this tab's to send.+SBE.dirty = true; SBE.conflict = 1;+sbeBeaconBackup();+out.conflictCount = beacons.length;+""", extra=("sbeBeaconBackup",))++ def test_a_dirty_unload_sends_exactly_one_beacon_to_the_backup_door(self):+ self.assertEqual(self.r["count"], 1)+ self.assertEqual(self.r["url"], "/storyboard/edit/backup")++ def test_the_beacon_carries_the_transitions_like_any_other_backup(self):+ tx = self.r["body"]["edit"]["transitions"]+ self.assertEqual([t["after_clip"] for t in tx], ["a"])+ self.assertEqual(self.r["body"]["draft"], "draft-1")+ self.assertEqual(self.r["body"]["session"], "sess1")++ def test_a_clean_or_conflicted_tab_sends_nothing(self):+ self.assertEqual(self.r["cleanCount"], 0)+ self.assertEqual(self.r["conflictCount"], 0)+++class SuspendNeverWritesTheDocument(unittest.TestCase):+ """FILM-29 — leaving the tab is not the user pressing Save. Driven,+ because the static gate in test_storyboard_editor_ui.py only reads the+ source; this proves the actual HTTP call that lands.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+SBE.open = true; SBE.id = 'F'; SBE.activeDraft = 'draft-1';+FETCHES = [];+NEXT = { status: 200, body: { ok: true, at: 1, session: {} } };+sbeSuspend();+for (let i = 0; i < 8; i++) await tick();+out.urls = FETCHES.map(f => f.url);+""", extra=("sbeSuspend", "sbeSweepViewToasts"), shim=r"""+function sbeStop() {}+function sbeSrcStop() {}+global.window = { addEventListener() {}, removeEventListener() {} };+global.document = { querySelectorAll: () => [] };+""")++ def test_leaving_the_tab_backs_up_and_never_saves(self):+ self.assertIn("/storyboard/edit/backup", self.r["urls"])+ self.assertNotIn("/storyboard/edit/save", self.r["urls"])+++class KeepVersionNamesWhatIsOnScreen(unittest.TestCase):+ """FILM-30 — "Keep this version" named the save already on disk. A+ dirty timeline now saves first, so the label attaches to the arrangement+ the user is actually looking at.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+twoClips();+els.sbeVersName = Object.assign(stubEl('sbeVersName'), { value: 'first cut' });+SBE.open = true; SBE.id = 'F'; SBE.activeDraft = 'draft-1';+FETCHES = [];+NEXT = { status: 200, body: { ok: true, edit: { revision: 2 }, label: 'first cut',+ revision: 2, versions: [] } };+await sbeKeepVersion();+out.dirtyUrls = FETCHES.map(f => f.url);+// A clean timeline needs no save first.+twoClips();+SBE.dirty = false;+els.sbeVersName = Object.assign(stubEl('sbeVersName'), { value: 'second cut' });+FETCHES = [];+await sbeKeepVersion();+out.cleanUrls = FETCHES.map(f => f.url);+""", extra=("sbeKeepVersion",))++ def test_a_dirty_timeline_saves_before_naming_the_version(self):+ self.assertEqual(self.r["dirtyUrls"],+ ["/storyboard/edit/save", "/storyboard/edit/version"])++ def test_a_clean_timeline_only_needs_the_name(self):+ self.assertEqual(self.r["cleanUrls"], ["/storyboard/edit/version"])+++class ConflictRefusesRatherThanDiscards(unittest.TestCase):+ """FILM-23 — Restore, Retake-use and Relink all guarded with+ `SBE.dirty && !SBE.conflict && !(await sbeSave(true))`: with a conflict+ set, `!SBE.conflict` made the WHOLE condition false, so the save was+ skipped AND the action went ahead, installing the server's copy over an+ arrangement the user was never offered a way to keep. Each now refuses+ outright on a conflict, the way Face Fix already did.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run(TWO_CLIPS + r"""+async function tryIt(fn, url) {+ twoClips();+ SBE.conflict = 1;+ FETCHES = [];+ const before = toasts.length;+ adopted.length = 0;+ await fn();+ return { hitAction: FETCHES.some(f => f.url === url),+ adopted: adopted.length,+ toasted: toasts.length > before };+}+out.restore = await tryIt(() => sbeRestoreVersion('save-r00003.json'),+ '/storyboard/edit/restore');+out.retake = await tryIt(() => sbeRetakeUse('c1', 'delivery'),+ '/storyboard/edit/relink');+out.relink = await tryIt(() => sbeRelink(), '/storyboard/edit/relink');+""", extra=("sbeRestoreVersion", "sbeRetakeUse", "sbeRelink"))++ def test_restore_refuses_on_a_conflict(self):+ r = self.r["restore"]+ self.assertFalse(r["hitAction"])+ self.assertEqual(r["adopted"], 0)+ self.assertTrue(r["toasted"])++ def test_retake_use_refuses_on_a_conflict(self):+ r = self.r["retake"]+ self.assertFalse(r["hitAction"])+ self.assertEqual(r["adopted"], 0)+ self.assertTrue(r["toasted"])++ def test_relink_refuses_on_a_conflict(self):+ r = self.r["relink"]+ self.assertFalse(r["hitAction"])+ self.assertEqual(r["adopted"], 0)+ self.assertTrue(r["toasted"])++if __name__ == "__main__":unittest.main()diff --git a/test_editor_v2.py b/test_editor_v2.pyindex 6d530b7..14f7395 100644--- a/test_editor_v2.py+++ b/test_editor_v2.py@@ -105,8 +105,14 @@ class ATransitionOwnsABoundary(unittest.TestCase):def test_the_picture_lane_rule_is_untouched(self):# The invariant this whole design exists to keep: pictures may not- # overlap, and WARNING_CODES still holds exactly the one code.- self.assertEqual(sedit.WARNING_CODES, frozenset({"clips_audio_overlap"}))+ # overlap. WARNING_CODES has grown since this was written — FILM-31+ # added `still_missing` for the same reason `clips_audio_overlap` is+ # here (persisting the user's work always wins, once the thing it+ # warns about is something the assembler can render safely) — but+ # `clips_overlap` (two PICTURES claiming the same second) must never+ # join it.+ self.assertIn("clips_audio_overlap", sedit.WARNING_CODES)+ self.assertNotIn("clips_overlap", sedit.WARNING_CODES)doc = _two()doc["clips"][1]["film_start"] = 2.5doc["clips"][1]["film_end"] = 5.5diff --git a/test_empty_gallery_icon.py b/test_empty_gallery_icon.pynew file mode 100644index 0000000..83a66c6--- /dev/null+++ b/test_empty_gallery_icon.py@@ -0,0 +1,57 @@+"""VC-40: the empty gallery's blue dot doesn't read as a stuck spinner.++WHAT THIS GUARDS. `.empty-msg::before` painted a plain 28px circle in+`var(--accent-dim)` (the panel's blue accent) with a `box-shadow` glow, sitting+alone above "No outputs yet" on a first boot with nothing else on screen. It+never animated, but blue + glow + alone in an otherwise empty screen reads as+a spinner that got stuck - reported from a 16 GB first-open screenshot+(16gb_first_open_1440.png).++Fixed by giving the empty state a real icon instead: `queue.js`'s+`renderCarousel()` now renders `<svg class="ph empty-msg-icon"><use+href="#ph-…"/></svg>` picked per view (search / photos / audio / videos), and+`panel.css` drops the glowing `::before` circle for a plain muted icon style.++This file is the static half - it does not need a browser, just confirms the+dot is gone and every empty-state branch names a real icon in the sprite.+"""+from __future__ import annotations++import re+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+++class NoStrayDot(unittest.TestCase):+ def test_the_glowing_circle_is_gone(self):+ self.assertNotIn(".empty-msg::before", CSS)+ self.assertNotIn("box-shadow: 0 0 12px rgba(47,129,247", CSS)++ def test_empty_msg_renders_a_real_icon(self):+ self.assertIn("empty-msg-icon", JS)+ m = re.search(r"const icon = [\s\S]*?el\.innerHTML = [\s\S]*?</div>`;", JS)+ self.assertIsNotNone(m, "no `const icon = …` block feeding empty-msg")+ body = m.group(0)+ self.assertIn('svg class="ph empty-msg-icon"', body)+ # every branch of the icon ternary must name a symbol that actually+ # exists in the sprite - a typo here would silently render nothing+ for icon in re.findall(r"'(ph-[a-z0-9-]+)'", body):+ self.assertIn(f'<symbol id="{icon}"', HTML,+ f"{icon} referenced by the empty state isn't in the sprite")+ # and every one of the four views (search / photos / audio /+ # videos / fallback) is represented, not just the default+ for icon in ("ph-magnifying-glass", "ph-image", "ph-music-notes",+ "ph-film-strip"):+ self.assertIn(icon, body)++ def test_empty_msg_icon_has_a_style_rule(self):+ self.assertIn(".empty-msg-icon {", CSS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_enhance_inline_panel.py b/test_enhance_inline_panel.pynew file mode 100644index 0000000..9857cbe--- /dev/null+++ b/test_enhance_inline_panel.py@@ -0,0 +1,244 @@+#!/usr/bin/env python3+"""VC-16 [P2] [UX] The Enhance flow is a native confirm() with no edit, no+diff and no undo, and it's refused during any render.++Coordinator ruling, 2026-09-29: "Enhance as an inline editable result with+Accept, Undo and Keep mine (no native confirm). Stays available during+renders if the model isn't on the GPU; otherwise it says why."++WHAT THIS GUARDS.+ 1 the native confirm() dialog is gone from enhancePrompt() — replaced+ with showEnhancePanel(), which fills an inline panel instead of+ blocking on a system dialog+ 2 Accept / Undo / Keep mine: Accept writes the enhanced text into the+ prompt AND fires the textarea's 'input' event (so updateDerived() and+ everything else listening still reacts, exactly like a real edit);+ Undo (shown only after Accept) reverts to the original; Keep mine+ just closes the panel with the textarea untouched+ 3 the GPU-conflict refusal (409) now names WHAT is rendering (and how+ long, when the priced tier table can say) instead of the flat "A+ render is using the GPU right now" — current_render_busy_reason(),+ server-side — and the client shows it inline (phosToast), not a+ blocking alert()+ 4 a genuinely concurrent Enhance during an active render remains+ refused: the single in-process _GPU_LOCK covers the whole job+ including the warm helper's own request/response protocol, which+ cannot safely interleave a second concurrent request — attempting to+ bypass that would risk the exact class of OOM/Metal-contention bug+ _GPU_LOCK exists to prevent, so this is a truthful "says why", not a+ silent capability the finding's title implies was simple to add+ 5 the stale "LTX 2.3" in the Enhance button's tooltip is now the+ ACTIVE generation, read from BOOT.ltx.generation at boot+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import time+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-enhance-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8327")+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+MAINJS = (ROOT / "webapp" / "js" / "main.js").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++# ---------------------------------------------------------------- 1 & 2+class TestClientPanelReplacesConfirm(unittest.TestCase):+ def test_enhance_prompt_no_longer_calls_confirm(self):+ fn = extract_function("enhancePrompt", QJS)+ self.assertNotIn("confirm(", fn)+ self.assertIn("showEnhancePanel(res.original, res.enhanced", fn)++ def test_error_path_is_inline_not_a_blocking_alert(self):+ fn = extract_function("enhancePrompt", QJS)+ i = fn.index("if (res.error)")+ block = fn[i:fn.index("}", i) + 1]+ self.assertNotIn("alert('Enhance failed", block)+ self.assertIn("phosToast(res.error", block)++ def test_accept_writes_enhanced_and_fires_input_event(self):+ fn = extract_function("acceptEnhance", QJS)+ self.assertIn("_setPromptValue(panel.dataset.enhanced", fn)+ setval = extract_function("_setPromptValue", QJS)+ self.assertIn("dispatchEvent(new Event('input'", setval)++ def test_undo_only_reachable_after_accept_and_reverts_to_original(self):+ accept_fn = extract_function("acceptEnhance", QJS)+ self.assertIn("enhanceUndoBtn').hidden = false", accept_fn)+ undo_fn = extract_function("undoEnhance", QJS)+ self.assertIn("_setPromptValue(panel.dataset.original", undo_fn)++ def test_keep_mine_does_not_touch_the_textarea(self):+ fn = extract_function("keepMineEnhance", QJS)+ self.assertNotIn("_setPromptValue", fn)+ self.assertNotIn("prompt", fn.replace("enhancePanel", "")) # only touches the panel++ def test_functions_published_on_globalthis(self):+ pub = QJS[QJS.index("Object.assign(globalThis"):]+ for fn in ("showEnhancePanel", "acceptEnhance", "undoEnhance", "keepMineEnhance"):+ self.assertIn(fn, pub, fn)++ def test_panel_markup_wired_to_the_functions(self):+ i = HTML.index('id="enhancePanel"')+ blk = HTML[i:i + 1800]+ self.assertIn('onclick="acceptEnhance()"', blk)+ self.assertIn('onclick="keepMineEnhance()"', blk)+ self.assertIn('onclick="undoEnhance()"', blk)+ self.assertIn('id="enhanceUndoBtn" onclick="undoEnhance()" hidden', blk)++ def test_panel_behaviour_end_to_end_via_node(self):+ script = """+class FakeCL {+ constructor() { this._s = new Set(); }+ toggle(c, f) { if (f === undefined) { this._s.has(c) ? this._s.delete(c) : this._s.add(c); } else if (f) this._s.add(c); else this._s.delete(c); return this._s.has(c); }+ contains(c) { return this._s.has(c); }+}+function makeEl(extra) { return Object.assign({ hidden: true, textContent: '', value: '', dataset: {}, classList: new FakeCL(), events: {},+ addEventListener(t, fn) { this.events[t] = fn; },+ dispatchEvent(ev) { const fn = this.events[ev.type]; if (fn) fn(ev); this._lastEvent = ev.type; } }, extra || {}); }+const ELS = {+ enhancePanel: makeEl(),+ enhanceOriginalText: makeEl(),+ enhanceEnhancedText: makeEl(),+ enhanceAcceptBtn: makeEl(),+ enhanceKeepBtn: makeEl(),+ enhanceUndoBtn: makeEl(),+ enhancePanelNote: makeEl(),+ prompt: makeEl(),+};+const document = { getElementById: (id) => ELS[id] || null };+%s+%s+%s+%s+showEnhancePanel('a cat', 'a cat, cinematic lighting, 4k');+const afterShow = { hidden: ELS.enhancePanel.hidden, orig: ELS.enhanceOriginalText.textContent, enh: ELS.enhanceEnhancedText.textContent };+acceptEnhance();+const afterAccept = { promptValue: ELS.prompt.value, undoHidden: ELS.enhanceUndoBtn.hidden, acceptHidden: ELS.enhanceAcceptBtn.hidden, lastEvent: ELS.prompt._lastEvent };+undoEnhance();+const afterUndo = { promptValue: ELS.prompt.value, panelHidden: ELS.enhancePanel.hidden };+console.log(JSON.stringify({ afterShow, afterAccept, afterUndo }));+""" % (+ extract_function("showEnhancePanel", QJS),+ extract_function("_setPromptValue", QJS),+ extract_function("acceptEnhance", QJS),+ extract_function("undoEnhance", QJS),+ )+ out = _run_node(script)+ self.assertFalse(out["afterShow"]["hidden"])+ self.assertEqual(out["afterShow"]["orig"], "a cat")+ self.assertEqual(out["afterShow"]["enh"], "a cat, cinematic lighting, 4k")+ self.assertEqual(out["afterAccept"]["promptValue"], "a cat, cinematic lighting, 4k")+ self.assertFalse(out["afterAccept"]["undoHidden"])+ self.assertTrue(out["afterAccept"]["acceptHidden"])+ self.assertEqual(out["afterAccept"]["lastEvent"], "input")+ self.assertEqual(out["afterUndo"]["promptValue"], "a cat")+ self.assertTrue(out["afterUndo"]["panelHidden"])+++# ---------------------------------------------------------------- 3+class TestBusyReasonNamesTheRender(unittest.TestCase):+ def setUp(self):+ with P.LOCK:+ self._saved_current = P.STATE.get("current")++ def tearDown(self):+ with P.LOCK:+ P.STATE["current"] = self._saved_current++ def test_no_current_job_gives_the_generic_line(self):+ with P.LOCK:+ P.STATE["current"] = None+ self.assertEqual(P.current_render_busy_reason(), "A render is using the GPU right now.")++ def test_names_the_label_and_time_left_when_priceable(self):+ with P.LOCK:+ P.STATE["current"] = {+ "params": {"label": "gym scene", "mode": "t2v",+ "quality": "balanced", "frames": 121},+ "started_ts": time.time() - 5,+ }+ reason = P.current_render_busy_reason()+ self.assertIn("gym scene", reason)+ self.assertIn("min left", reason)++ def test_falls_back_to_a_prompt_snippet_with_no_label(self):+ with P.LOCK:+ P.STATE["current"] = {+ "params": {"prompt": "a" * 80, "mode": "t2v",+ "quality": "balanced", "frames": 121},+ "started_ts": time.time(),+ }+ reason = P.current_render_busy_reason()+ self.assertIn("a" * 40, reason)+ self.assertNotIn("a" * 41, reason.replace("a" * 40, "", 1))++ def test_no_time_left_claimed_when_unpriceable(self):+ with P.LOCK:+ P.STATE["current"] = {+ "params": {"label": "a song", "engine": "music"},+ "started_ts": time.time(),+ }+ reason = P.current_render_busy_reason()+ self.assertIn("a song", reason)+ self.assertNotIn("min left", reason)++ def test_route_uses_the_reason_in_the_409(self):+ src = (ROOT / "panel" / "routes_queue.py").read_text(encoding="utf-8")+ i = src.index("if not P._GPU_LOCK.acquire(timeout=3.0):")+ block = src[i:src.index("return", i)]+ self.assertIn("current_render_busy_reason()", block)+ self.assertNotIn('"A render is using the GPU right now', block)+++# ---------------------------------------------------------------- 5+class TestEnhanceTitleMatchesActiveGeneration(unittest.TestCase):+ def test_boot_time_script_reads_boot_generation(self):+ i = MAINJS.index("enhanceBtn")+ block = MAINJS[i - 50:i + 400]+ self.assertIn("BOOT.ltx || {}).generation", block)+ self.assertIn("2.3", block)+ self.assertIn("2.5", block)++ def test_static_title_no_longer_hardcodes_2_3(self):+ i = HTML.index('id="enhanceBtn"')+ tag = HTML[i - 200:i + 100]+ self.assertNotIn("LTX 2.3 was trained on", tag)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_export_music_video_routing.py b/test_export_music_video_routing.pynew file mode 100644index 0000000..043389f--- /dev/null+++ b/test_export_music_video_routing.py@@ -0,0 +1,89 @@+#!/usr/bin/env python3+"""FILM-48: Export on a music-video board must not ignore the song.++sbExport() used to post only `{id}` to /storyboard/export — with no+edit.json (the Editor never opened), the server had no song to lay under+the film and silently concatenated each clip's own audio. A music-video+board now routes straight to /music/video/film (the dedicated endpoint+that already knows where the board's song is and calls the same _sb_export+underneath with music_mode=replace); an ordinary board is unaffected.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _run(board):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ fns = "\n\n".join(extract_function(n, STORYBOARD_JS) for n in+ ("sbExport", "sbMusicVideoBlock"))+ script = f"""+'use strict';+const _els = {{}};+function mk(id) {{ return {{ id, textContent: '', dataset: {{}}, disabled: false }}; }}+function sbEl(id) {{ if (!_els[id]) _els[id] = mk(id); return _els[id]; }}+globalThis.phosToast = () => {{}};+globalThis.sbFilmOpen = () => {{}};+globalThis.SB = {{ id: 'sb_test', payload: {{ board: {json.dumps(board)} }} }};+globalThis.__fetchCalls = [];+globalThis.fetch = (url, opts) => {{+ const body = opts && opts.body ? String(opts.body) : '';+ __fetchCalls.push({{ url, body }});+ return Promise.resolve({{+ json: async () => ({{ ok: true, files: [], dir: '/out', film_name: null, film_error: 'skip' }}),+ }});+}};+{fns}+sbExport().then(() => {{+ console.log(JSON.stringify(__fetchCalls));+}});+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run(["node", str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return json.loads(result.stdout.strip().splitlines()[-1])+ finally:+ path.unlink(missing_ok=True)+++class ExportRoutesMusicVideoBoardsToTheSongAwareEndpoint(unittest.TestCase):+ def test_a_music_video_board_routes_to_music_video_film(self):+ calls = _run({"id": "sb_mv", "music_video": {"song": "/o/song.wav"}})+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0]["url"], "/music/video/film")+ self.assertIn("board_id=sb_test", calls[0]["body"])++ def test_an_ordinary_board_still_uses_the_plain_export_route(self):+ calls = _run({"id": "sb_plain"})+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0]["url"], "/storyboard/export")+ self.assertIn("id=sb_test", calls[0]["body"])++ def test_a_music_video_block_with_no_song_yet_is_not_treated_as_one(self):+ # An in-progress plan (e.g. cast chosen, no song set) must not be+ # routed at a song that does not exist.+ calls = _run({"id": "sb_partial", "music_video": {"song": ""}})+ self.assertEqual(calls[0]["url"], "/storyboard/export")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_extend_footer_summary.py b/test_extend_footer_summary.pynew file mode 100644index 0000000..e1512b4--- /dev/null+++ b/test_extend_footer_summary.py@@ -0,0 +1,187 @@+"""VC-25: the sticky footer's derived summary line is mode-aware for Extend.++WHAT THIS GUARDS. Clicking Extend from the player (`useAsExtendSourcePath` ->+`setMode('extend')` -> `updateDerived()`) switched the form to Extend (source+picked, "Extend by 2 s"), but the footer's derived line kept showing the T2V+line built from the #width/#height/#frames fields - e.g. "5.00s · 1024×576 ->+1280×720 fit" - none of which describes what Extend is about to render:+Extend's geometry comes from whatever source clip is picked (clamped by this+Mac's tier), not those fields, and it always renders through Q8.++`updateDerived()` now branches on `currentMode === 'extend'` and reports the+seconds actually being added (rounded up to the 8-video-frame latent grid,+same arithmetic as `syncExtendDuration()`), the direction, and "Q8" instead of+the T2V geometry line. `syncExtendDuration()` (fired on every #extend_seconds+input and now every #extend_direction change too) re-runs `updateDerived()`+so the footer stays live instead of showing whatever it said the moment the+mode switched.+"""+import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+JS_DIR = ROOT / "webapp" / "js"+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++# A minimal DOM shim: just enough getElementById()/value plumbing for the+# handful of fields updateDerived() and syncExtendDuration() touch, plus the+# handful of ids it defensively no-ops on when absent. No jsdom dependency -+# matches the "stdlib/no new deps" rule the rest of this suite's node+# harnesses (extract_panel_js) already follows.+DOM_SHIM = r"""+function makeEl(id, value) {+ return { id, value, textContent: '', innerHTML: '', hidden: false,+ classList: { toggle(){}, add(){}, remove(){} },+ addEventListener(){}, getAttribute(){ return null; },+ dataset: {}, style: {} };+}+const FIELDS = {+ mode: 't2v', width: '1024', height: '576', frames: '121',+ steps: '8', upscale: 'off', accel: 'off', temporal_mode: 'native',+ extend_seconds: '2', extend_direction: 'after', extend_frames: '6',+ derived: '', derivedFooter: '', qualityMeta: '', warnBanner: '',+};+const ELS = {};+for (const [id, value] of Object.entries(FIELDS)) ELS[id] = makeEl(id, value);+ELS.warnBanner.classList = { _cls: new Set(), add(c){this._cls.add(c);}, remove(c){this._cls.delete(c);}, toggle(){} };++global.document = {+ // Any id updateDerived() touches beyond the ones seeded in FIELDS above+ // (section toggles, other mode-only strips) gets a generic stub instead+ // of null - this test cares about the derivedFooter branch, not every+ // section's visibility bookkeeping, and a real page always has these+ // elements.+ getElementById: (id) => (ELS[id] || (ELS[id] = makeEl(id, ''))),+ querySelector: () => null,+ body: { dataset: { engine: 'ltx' } },+};+global.escapeHtml = (s) => String(s);+global.framesToDuration = (f) => (f > 1 ? (f - 1) / 24 : 0).toFixed(2);+global.FPS = 24;+global.currentMode = FIELDS.mode;+// updateDerived() calls these unconditionally (not typeof-guarded like the+// other cross-module calls it makes) - stub them rather than widen the shim+// with the FFLF slot/timing machinery this test has nothing to do with.+global.renderKeyframeDynamicSlots = () => {};+global.syncKeyframeTiming = () => {};+global.maybeScaleTouchedKeyframeTiming = () => {};+global._updateKeyframeFramesGate = () => {};+// VA-12 (est): Extend's footer reads the server's price card — the Mac's+// Extend clamp and a per-latent-count ETA — never a browser-side price.+global.BOOT = { tier: { extend_price_draft: {+ width: 768, height: 432, eta: '~16 min',+ eta_by_latents: { '6': '~17 min', '4': '~15 min', '9': '~19 min' } } } };+global.window = { _kfTimingLastFrames: 0, BOOT: global.BOOT };+// Records the LAST 'show' state each section was toggled to.+const SHOWN = {};+const _origGet = global.document.getElementById;+global.document.getElementById = (id) => {+ const el = _origGet(id);+ if (!el._wrapped) {+ el._wrapped = true;+ el.classList = Object.assign({}, el.classList, {+ toggle(c, on) { if (c === 'show') SHOWN[id] = !!on; } });+ }+ return el;+};+"""+++class ExtendFooterIsModeAware(unittest.TestCase):+ def _updateDerived_src(self) -> str:+ src = (JS_DIR / "queue.js").read_text(encoding="utf-8")+ return (extract_function("updateDerived", src) + "\n"+ + extract_function("updateDerivedForClampedMode", src))++ def _run(self, mode: str, extend_seconds: str = "2", extend_direction: str = "after") -> str:+ fn = self._updateDerived_src()+ script = DOM_SHIM + f"""+global.currentMode = {json.dumps(mode)};+ELS.mode.value = {json.dumps(mode)};+ELS.extend_seconds.value = {json.dumps(extend_seconds)};+ELS.extend_direction.value = {json.dumps(extend_direction)};+{fn}+updateDerived();+console.log(JSON.stringify({{ footer: ELS.derivedFooter.innerHTML, shown: SHOWN }}));+"""+ out = _run_node(script)+ self._shown = out["shown"]+ return out["footer"]++ def test_extend_mode_reports_extend_specific_summary(self):+ footer = self._run("extend", extend_seconds="2", extend_direction="after")+ self.assertIn("+2.0s after", footer)+ self.assertIn("Q8", footer)++ def test_extend_mode_never_shows_t2v_geometry(self):+ footer = self._run("extend")+ self.assertNotIn("1024", footer)+ self.assertNotIn("576", footer)+ self.assertNotIn("fit", footer)++ def test_extend_direction_before_is_reflected(self):+ footer = self._run("extend", extend_seconds="3", extend_direction="before")+ self.assertIn("before", footer)+ self.assertNotIn("after", footer)++ def test_extend_seconds_round_to_the_8_frame_latent_grid(self):+ # 1.1s * 24fps / 8 = 3.3 -> ceil 4 latents -> 4*8/24 = 1.33s, same+ # arithmetic as syncExtendDuration()'s own conversion.+ footer = self._run("extend", extend_seconds="1.1", extend_direction="after")+ self.assertIn("+1.3s after", footer)++ def test_extend_eta_follows_the_seconds_typed(self):+ # 2 s -> 6 latents; 3 s -> 9 latents (VC-25 live seconds x VA-12 price).+ self.assertIn("~17 min", self._run("extend", extend_seconds="2"))+ self.assertIn("~19 min", self._run("extend", extend_seconds="3"))++ def test_extend_still_shows_its_own_form_section(self):+ # 4.17 merge: est's first cut RETURNED from updateDerived() for+ # keyframe/extend right after pricing the footer, skipping every+ # section toggle below it — the Extend form never appeared.+ self._run("extend")+ self.assertTrue(self._shown.get("extendSection"))+ self.assertFalse(self._shown.get("sizingSection"))++ def test_t2v_mode_is_unaffected(self):+ footer = self._run("t2v")+ self.assertIn("1024", footer)+ self.assertNotIn("Q8", footer)++ def test_sync_extend_duration_now_refreshes_the_footer(self):+ src = (JS_DIR / "queue.js").read_text(encoding="utf-8")+ body = extract_function("syncExtendDuration", src)+ self.assertIn("updateDerived", body)++ def test_extend_direction_change_is_wired(self):+ src = (JS_DIR / "queue.js").read_text(encoding="utf-8")+ self.assertIn("extend_direction').addEventListener('change', syncExtendDuration)", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_extract_panel_js_regex.py b/test_extract_panel_js_regex.pynew file mode 100644index 0000000..aacef3d--- /dev/null+++ b/test_extract_panel_js_regex.py@@ -0,0 +1,105 @@+"""scripts/extract_panel_js.py's brace-matcher survives a regex literal that+contains a quote character.++WHAT THIS GUARDS. `extract_function`/`extract_object` track `"`, `'` and+`` ` `` as string delimiters but, until now, had no idea a `/.../ ` regex+literal exists. `friendlyJobError`'s own first branch —+`/music engine isn't installed|.../i.test(raw)` — contains an apostrophe+inside a regex, which the old loop read as the START of a fake string. That+fake string then swallowed the next REAL quote (an unrelated string's+opening quote) as its own close, desynchronising every string/brace+boundary for the rest of the function. The corruption was silent: total+depth still reached exactly 0 eventually, just at the wrong `}` — so+`extract_function("friendlyJobError")` happened to return the right text+right up until an unrelated edit anywhere later in the function shifted the+(accidental) alignment and truncated it mid-function, with no error raised+at the point that actually broke (this is exactly what an edit to+queue.js's OOM-copy branch did while fixing VC-08 — nothing about that edit+was wrong, it just moved the coincidental alignment).++Fixed with `_looks_like_regex_start()`/`_skip_regex_literal()`, shared by+both functions through the new `_balanced_brace_end()` helper (which also+de-duplicates what used to be two copies of the same loop).+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+import extract_panel_js as E # noqa: E402+++class RegexLiteralsDontDesyncTheParser(unittest.TestCase):+ def test_apostrophe_inside_a_regex_does_not_break_extraction(self):+ src = (+ "function probe(raw) {\n"+ " if (/it isn't here|also isn't there/i.test(raw)) {\n"+ " return { a: 'one', b: 'two' };\n"+ " }\n"+ " return { a: 'three' };\n"+ "}\n"+ )+ got = E.extract_function("probe", src)+ self.assertTrue(got.startswith("function probe(raw) {"))+ self.assertTrue(got.rstrip().endswith("}"))+ self.assertIn("return { a: 'three' };", got)++ def test_a_second_quote_carrying_regex_further_in_still_works(self):+ src = (+ "function probe2(x) {\n"+ " const a = 1;\n"+ " if (/don't match/.test(x)) { return { hit: true }; }\n"+ " const later = { nested: { deep: 2 } };\n"+ " return later;\n"+ "}\n"+ )+ got = E.extract_function("probe2", src)+ self.assertIn("const later = { nested: { deep: 2 } };", got)+ self.assertTrue(got.rstrip().endswith("}"))++ def test_division_is_not_mistaken_for_a_regex(self):+ """The heuristic must not eat ordinary division - `a / b` right+ after an identifier or digit is division, not a regex opener."""+ src = (+ "function probe3(w, h) {\n"+ " const ratio = w / h;\n"+ " const half = 10 / 2;\n"+ " return { ratio, half };\n"+ "}\n"+ )+ got = E.extract_function("probe3", src)+ self.assertIn("const half = 10 / 2;", got)+ self.assertTrue(got.rstrip().endswith("}"))++ def test_real_friendly_job_error_extracts_in_full(self):+ """The exact function that surfaced the bug - pinned end to end so+ a future regression here is caught immediately, not three edits+ later at some unrelated call site."""+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ got = E.extract_function("friendlyJobError", src)+ # H3-22 (4.17): the function takes the job's engine and the generic+ # fallback redacts local paths.+ self.assertTrue(got.startswith("function friendlyJobError(raw, engine) {"))+ self.assertTrue(got.rstrip().endswith("}"))+ # every branch's return must be present - a truncation stops partway+ self.assertIn("return { friendly: 'Job failed.', hint: _redactLocalPaths(raw) || raw };", got)+ self.assertEqual(got.count("return {"), got.count("return {")) # sanity: no crash above+ self.assertGreaterEqual(got.count("if ("), 7)++ def test_extract_object_shares_the_same_fix(self):+ src = (+ "window.PROBE = {\n"+ " re: /a'b/,\n"+ " nested: { x: 1 },\n"+ "};\n"+ )+ got = E.extract_object("PROBE", src)+ self.assertIn("nested: { x: 1 }", got)+ self.assertTrue(got.rstrip().endswith("};") or got.rstrip().endswith("}"))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_face_fix.py b/test_face_fix.pyindex d502fd9..5d90ea7 100644--- a/test_face_fix.py+++ b/test_face_fix.py@@ -159,6 +159,20 @@ class TestQueueFaceFix(_Env):self.assertEqual(p["frames"], 241)self.assertEqual(P.upscale_frame_plan(240, p["frames"]), (240, 241))+ def test_target_dims_come_back_for_the_toast(self):+ # VA-22: the queued-toast used to say nothing about size. _Env's+ # fixture clip is 640×384; queue_face_fix already computes the ×2+ # canvas for its own refusal checks, so surfacing it is free.+ r = P.queue_face_fix(str(self.clip))+ self.assertTrue(r["ok"], r)+ self.assertEqual((r["target_w"], r["target_h"]), (1280, 768))++ def test_target_dims_on_a_duplicate_too(self):+ a = P.queue_face_fix(str(self.clip))+ b = P.queue_face_fix(str(self.clip))+ self.assertTrue(b.get("duplicate"))+ self.assertEqual((b["target_w"], b["target_h"]), (a["target_w"], a["target_h"]))+def test_a_one_shot_take_uses_the_whole_takes_prompt(self):Path(str(self.clip) + ".json").write_text(json.dumps({"prompt": "the whole take", "label": "take", "take": {"seconds": 20},@@ -377,7 +391,10 @@ class TestUI(unittest.TestCase):self.assertIn("upscale_steps", fn)def test_load_params_restores_the_exact_recipe(self):- lp = QJS[QJS.index(" else if (p.mode === 'upscale') {"):]+ # VA-08: this branch used to be `else if` — now a plain `if`, because+ # loadParams() switches to the Video tab (workflowSwitch('manual'))+ # right before it, for every branch that fills #genForm.+ lp = QJS[QJS.index(" if (p.mode === 'upscale') {"):]lp = lp[:lp.index(" else if (p.mode === 'extend')")]self.assertIn("(b.dataset.start || '') === start && (b.dataset.steps || '') === steps", lp)self.assertIn("set('keep_shot', keep); set('upscale_start', start); set('upscale_steps', steps);", lp)@@ -395,7 +412,10 @@ class TestUI(unittest.TestCase):self.assertIn('type="checkbox" id="h3FaceFixAfter"', row)tag = row.split('id="h3FaceFixAfter"')[1].split(">")[0]self.assertNotRegex(tag, r'(^|\s)checked(\s|=|$)')- self.assertIn("Also run <b>Upscale & Face Fix</b> after the draft", row)+ # H3-26: this checkbox is offered whenever H3.upscale_modes allows+ # ltx_x2, not only on the Draft tier, so its label no longer says+ # "the draft" — "this render" is accurate on Standard/High too.+ self.assertIn("Also run <b>Upscale & Face Fix</b> after this render", row)self.assertIn('id="h3_upscale" value="fit_720p"', HTML)self.assertEqual(P.H3_UPSCALE_DEFAULT, "fit_720p")self.assertIn("ltx_x2", P.H3_UPSCALE_MODES) # stored value keptdiff --git a/test_film_49_time_left.py b/test_film_49_time_left.pynew file mode 100644index 0000000..1a603c2--- /dev/null+++ b/test_film_49_time_left.py@@ -0,0 +1,124 @@+"""FILM-49 [P2]: "Time left" during a film counted only the current batch.++_sb_render_thread submits a film "ONE BUCKET AT A TIME" (its own docstring),+so /status.eta_sec — the sum of per-job ETAs for whatever is queued RIGHT+NOW — only ever covered that one bucket. sbRenderRunBar's `allMine` check+is true for nearly the whole render (nothing else typically shares the+queue with a film), so the shallow bucket total was what actually+displayed: "12m left" with hours still to go once later buckets (the+report's ~19-min singing shots) were counted.++The fix combines eta_sec (what's genuinely queued) with the film's OWN+per-shot estimate for every shot that hasn't been queued at all yet.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")++[email protected](NODE, "node not on PATH")+class TimeLeftCountsTheWholeFilm(unittest.TestCase):+ def _run(self, js: str) -> dict:+ r = subprocess.run([NODE, "-e", js], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr)+ return json.loads(r.stdout.strip())++ def _harness(self, *, queue_ns, current_n, eta_sec, per_shot, shots,+ current_remaining=None) -> str:+ """queue_ns: shot numbers with a job currently queued (all tagged+ to this film). current_n: the shot rendering right now, or None.+ per_shot: {n: seconds} the film's own per-shot estimate.+ shots: [{n, out}] — out truthy means this shot already has an+ output for the pass being priced."""+ from scripts.extract_panel_js import extract_function+ fns = "\n".join(extract_function(n, STORYBOARD_JS) for n in+ ("sbFmtWall", "_sbTagOf", "sbRenderRunBar"))+ els = {}++ def _shots_js():+ return json.dumps([{"n": s["n"], "draft_output": s["out"], "status": "pending"}+ for s in shots])++ def _queue_js():+ return json.dumps([{"params": {"session_tag": f"sb:film1#{n}"}} for n in queue_ns])++ current_js = ("null" if current_n is None else+ json.dumps({"params": {"session_tag": f"sb:film1#{current_n}"},+ "progress": {"remaining_sec": current_remaining}}))+ return f"""+globalThis.SB = {{ id: 'film1' }};+const _els = {{}};+function el(id) {{ return _els[id] || (_els[id] = {{ id, textContent: '', innerHTML: '', hidden: true }}); }}+const document = {{ getElementById: el }};+function sbEl(id) {{ return el(id); }}+function snippet(s, n) {{ return String(s || '').slice(0, n); }}+function escapeHtml(s) {{ return String(s || ''); }}+{fns}+const LAST_STATUS = {{+ current: {current_js},+ queue: {_queue_js()},+ paused: false,+ eta_sec: {eta_sec},+}};+const r = {{+ rendering: true,+ pass: 'draft',+ board: {{ shots: {_shots_js()} }},+ per_shot_est: {json.dumps(per_shot)},+}};+sbRenderRunBar(r);+console.log(JSON.stringify({{ sub: el('sbRunSub').textContent }}));+"""++ def test_not_yet_queued_shots_are_added_to_the_queues_own_total(self):+ """3 shots: #1 done, #2 queued (eta_sec covers it), #3 NOT queued+ yet (the report's later-bucket singing shot, 19 min = 1140s)."""+ out = self._run(self._harness(+ queue_ns=[2], current_n=None, eta_sec=120,+ per_shot={"2": 120, "3": 1140},+ shots=[{"n": 1, "out": "a.mp4"}, {"n": 2, "out": None}, {"n": 3, "out": None}],+ ))+ # 120 (queued) + 1140 (not yet queued) = 1260s = 21 min.+ self.assertIn("21 m", out["sub"])++ def test_old_behaviour_would_have_shown_only_the_queued_bucket(self):+ """Regression pin: eta_sec ALONE (the pre-fix number) must NOT be+ what ends up on screen when a shot is still unqueued."""+ out = self._run(self._harness(+ queue_ns=[2], current_n=None, eta_sec=120,+ per_shot={"2": 120, "3": 1140},+ shots=[{"n": 1, "out": "a.mp4"}, {"n": 2, "out": None}, {"n": 3, "out": None}],+ ))+ self.assertNotIn("2 m", out["sub"]) # sbFmtWall(120) == "about 2 m"++ def test_the_currently_rendering_shot_is_not_double_counted(self):+ """The shot actively rendering counts by its OWN remaining_sec+ (4.17 Codex EST-6: it used to count as nothing at all) — never+ again from per_shot_est."""+ out = self._run(self._harness(+ queue_ns=[], current_n=2, eta_sec=0,+ per_shot={"2": 600, "3": 300}, current_remaining=60,+ shots=[{"n": 1, "out": "a.mp4"}, {"n": 2, "out": None}, {"n": 3, "out": None}],+ ))+ # Shot 2's 60 s still to go + shot 3's 300 s = 6 min; shot 2's+ # 600 s per-shot estimate is not added on top.+ self.assertIn("6 m", out["sub"])++ def test_nothing_left_shows_no_time_suffix(self):+ out = self._run(self._harness(+ queue_ns=[], current_n=None, eta_sec=0, per_shot={},+ shots=[{"n": 1, "out": "a.mp4"}],+ ))+ self.assertNotIn("left", out["sub"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_finish_keepers.py b/test_finish_keepers.pynew file mode 100644index 0000000..3fc7bc1--- /dev/null+++ b/test_finish_keepers.py@@ -0,0 +1,113 @@+#!/usr/bin/env python3+"""FILM-47: "Finish keepers" honesty and bulk-grading.++ * POST /storyboard/keep-all-ungraded marks every rendered, un-skipped,+ ungraded shot KEEP in ONE save — the bulk equivalent of pressing K on+ each one by hand, without the race risk of N separate grade calls each+ doing their own load-mutate-save.+ * A cut or already-graded shot is left alone.+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _shot(n, **kw):+ s = {"n": n, "uid": f"shot_{n:08x}", "mode": "text", "engine": "ltx",+ "prompt": f"shot {n}", "duration_s": 5.0, "seed": n, "refs": [],+ "status": "pending"}+ s.update(kw)+ return s+++def _board(bid, shots):+ return {"schema": 1, "id": bid, "title": "T", "created_at": 1,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "shots": shots}+++class FakeHandler:+ def __init__(self):+ self.status = None+ self.payload = None++ def _json(self, payload, status: int = 200):+ self.payload, self.status = payload, status+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def load(self, bid):+ return storyboard.load_storyboard(self.state, bid)++ def post(self, action, form):+ h = FakeHandler()+ panel.Handler._storyboard_post(h, action, "", form)+ return h+++class TheBulkKeepRoute(Sandbox):+ def test_every_rendered_ungraded_shot_is_kept_in_one_save(self):+ self.save(_board("sb_bulk", [+ _shot(1, draft_output="/o/s1.mp4", status="done"),+ _shot(2, draft_output="/o/s2.mp4", status="done"),+ _shot(3, draft_output="/o/s3.mp4", status="skipped", grade="cut"),+ ]))+ h = self.post("keep-all-ungraded", {"id": ["sb_bulk"]})+ self.assertEqual(h.status, 200, h.payload)+ self.assertEqual(h.payload["kept"], 2)+ reloaded = self.load("sb_bulk")+ self.assertEqual(reloaded["shots"][0]["grade"], "keep")+ self.assertEqual(reloaded["shots"][1]["grade"], "keep")+ # the cut shot is untouched+ self.assertEqual(reloaded["shots"][2]["grade"], "cut")++ def test_an_already_graded_shot_is_left_alone(self):+ self.save(_board("sb_bulk2", [+ _shot(1, draft_output="/o/s1.mp4", status="done", grade="reroll"),+ ]))+ h = self.post("keep-all-ungraded", {"id": ["sb_bulk2"]})+ self.assertEqual(h.payload["kept"], 0)+ self.assertEqual(self.load("sb_bulk2")["shots"][0]["grade"], "reroll")++ def test_an_unrendered_shot_is_never_kept(self):+ self.save(_board("sb_bulk3", [_shot(1)])) # no draft_output at all+ h = self.post("keep-all-ungraded", {"id": ["sb_bulk3"]})+ self.assertEqual(h.payload["kept"], 0)+ self.assertNotIn("grade", self.load("sb_bulk3")["shots"][0])++ def test_nothing_to_keep_still_answers_ok(self):+ self.save(_board("sb_bulk4", []))+ h = self.post("keep-all-ungraded", {"id": ["sb_bulk4"]})+ self.assertEqual(h.status, 200)+ self.assertEqual(h.payload["kept"], 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_finish_keepers_ui.py b/test_finish_keepers_ui.pynew file mode 100644index 0000000..58fc37c--- /dev/null+++ b/test_finish_keepers_ui.py@@ -0,0 +1,96 @@+#!/usr/bin/env python3+"""FILM-47 (client half): the tally bar's "Keep all ungraded" button and+the mixed-resolution warning, against the real sbRenderTally()."""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _run(shots, r_over=None):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ fn = extract_function("sbRenderTally", STORYBOARD_JS)+ r = {"rendering": False}+ if r_over:+ r.update(r_over)+ script = r"""+'use strict';+const _els = {};+function mk(id) { return { id, textContent: '', innerHTML: '', hidden: true, disabled: false, title: '' }; }+function sbEl(id) { if (!_els[id]) _els[id] = mk(id); return _els[id]; }+""" + fn + f"""+sbRenderTally({json.dumps(shots)}, {json.dumps(r)});+console.log(JSON.stringify(Object.fromEntries(Object.entries(_els).map(([k, v]) => [k, v]))));+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run(["node", str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return json.loads(result.stdout.strip())+ finally:+ path.unlink(missing_ok=True)+++def _shot(n, **kw):+ s = {"n": n, "status": "done"}+ s.update(kw)+ return s+++class TheKeepAllButton(unittest.TestCase):+ def test_shown_with_a_count_when_shots_are_ungraded(self):+ els = _run([_shot(1, draft_output="/o/1.mp4"),+ _shot(2, draft_output="/o/2.mp4", grade="keep")])+ self.assertFalse(els["sbKeepAllBtn"]["hidden"])+ self.assertIn("(1)", els["sbKeepAllBtn"]["textContent"])++ def test_hidden_when_everything_is_already_graded(self):+ els = _run([_shot(1, draft_output="/o/1.mp4", grade="keep"),+ _shot(2, draft_output="/o/2.mp4", grade="cut", status="skipped")])+ self.assertTrue(els["sbKeepAllBtn"]["hidden"])++ def test_an_unrendered_shot_does_not_count(self):+ els = _run([_shot(1, status="pending")]) # no draft_output+ self.assertTrue(els["sbKeepAllBtn"]["hidden"])+++class TheMixedResolutionWarning(unittest.TestCase):+ def test_shown_when_clip_sizes_differ(self):+ els = _run([+ _shot(1, draft_output="/o/1.mp4", output_dims=[640, 448]),+ _shot(2, final_output="/o/2.mp4", output_dims=[1024, 576]),+ ])+ self.assertFalse(els["sbMixedResWarn"]["hidden"])+ self.assertIn("640x448", els["sbMixedResWarn"]["textContent"].replace("×", "x"))++ def test_hidden_when_every_clip_is_the_same_size(self):+ els = _run([+ _shot(1, draft_output="/o/1.mp4", output_dims=[1024, 576]),+ _shot(2, final_output="/o/2.mp4", output_dims=[1024, 576]),+ ])+ self.assertTrue(els["sbMixedResWarn"]["hidden"])++ def test_hidden_when_dims_are_unmeasured_legacy_shots(self):+ els = _run([_shot(1, draft_output="/o/1.mp4")])+ self.assertTrue(els["sbMixedResWarn"]["hidden"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_first_run_gallery_card.py b/test_first_run_gallery_card.pynew file mode 100644index 0000000..727c995--- /dev/null+++ b/test_first_run_gallery_card.py@@ -0,0 +1,113 @@+#!/usr/bin/env python3+"""VC-41 + SYS-16: ONE first-run card, sized to this Mac (4.17 integration).++VC-41 (an empty-gallery card with a sample prompt and this Mac's ETA) and+SYS-16 ("Make your first clip" in the form, three starter prompts that queue+at Balanced) were two first-run cards for the same moment; VC-41's shared a+class with SYS-16's and pushed Generate off-screen, and it never showed on the+Video tab anyway (the Videos filter excluded it). Coordinator ruling: keep+SYS-16's card, give it VC-41's "sized to this Mac" price, remove VC-41's card.++Gated here (JS executed in node, not grepped, where it is behaviour):+ 1 _firstRunEta() quotes the default cell — the fleet range first, then the+ modelled range, then the point estimate+ 2 applyFirstRunCard() shows the card on a genuine first run, writes the+ price into it once, and hides it once the gallery has anything in it+ 3 VC-41's separate gallery card and its helpers are gone+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++def _node(script: str):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError(r.stderr[-3000:])+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++FNS = extract_function("_firstRunEta", QUEUE_JS) + "\n" + extract_function("applyFirstRunCard", QUEUE_JS)+++class TheEtaIsTheDefaultCells(unittest.TestCase):+ def _eta(self, tiers):+ return _node(FNS + f"""+global.BOOT = {{ ltx: {{ tiers: {json.dumps(tiers)} }} }};+console.log(JSON.stringify(_firstRunEta()));+""")++ def test_fleet_range_first(self):+ self.assertEqual(self._eta([{"key": "balanced_5s", "is_default": True, "eta": "~3 min",+ "eta_range": "~3–4 min",+ "fleet_range": {"eta_range": "~2–3 min"}}]), "~2–3 min")++ def test_then_the_modelled_range_then_the_point(self):+ self.assertEqual(self._eta([{"key": "balanced_5s", "is_default": True, "eta": "~3 min",+ "eta_range": "~3–4 min"}]), "~3–4 min")+ self.assertEqual(self._eta([{"key": "balanced_5s", "eta": "~3 min"}]), "~3 min")+ self.assertEqual(self._eta([]), "")+++class TheCardShowsOnceAndOnlyOnAFirstRun(unittest.TestCase):+ def _run(self, status):+ return _node(FNS + f"""+const els = {{ firstRunCard: {{ style: {{ display: 'none' }} }}, firstRunEta: {{ textContent: '' }} }};+global.document = {{ getElementById: id => els[id] || null }};+global.BOOT = {{ first_run: true, ltx: {{ tiers: [{{ key: 'balanced_5s', is_default: true, eta: '~3 min' }}] }} }};+applyFirstRunCard({json.dumps(status)});+applyFirstRunCard({json.dumps(status)});+console.log(JSON.stringify({{ display: els.firstRunCard.style.display, eta: els.firstRunEta.textContent }}));+""")++ def test_a_fresh_install_sees_the_card_with_this_macs_price(self):+ out = self._run({"outputs": [], "history": [], "settings": {}})+ self.assertEqual(out["display"], "")+ self.assertEqual(out["eta"], " — about 3 min on this Mac")++ def test_a_gallery_with_anything_in_it_is_not_a_first_run(self):+ out = self._run({"outputs": [{"path": "/o/a.mp4"}], "history": [], "settings": {}})+ self.assertEqual(out["display"], "none")++ def test_dismissed_or_finished_hides_it(self):+ self.assertEqual(self._run({"outputs": [], "history": [],+ "settings": {"first_run_card_dismissed": True}})["display"], "none")+ self.assertEqual(self._run({"outputs": [], "history": [{"status": "done"}],+ "settings": {}})["display"], "none")+++class OnlyOneFirstRunCardShips(unittest.TestCase):+ def test_vc41s_gallery_card_is_gone(self):+ for gone in ("firstRunCardHtml", "useFirstRunSample", "rerollFirstRunSample",+ "FIRST_RUN_SAMPLE_PROMPTS", "gallery-first-run"):+ self.assertNotIn(gone, QUEUE_JS, gone)+ self.assertNotIn(gone, CSS, gone)+ self.assertEqual(HTML.count('id="firstRunCard"'), 1)+ self.assertIn('<span id="firstRunEta"></span>', HTML)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_fleet_timings.py b/test_fleet_timings.pynew file mode 100644index 0000000..4ef6e4b--- /dev/null+++ b/test_fleet_timings.py@@ -0,0 +1,244 @@+"""Fleet timings: real fleet wall clocks, shown as a range, with a+documented fallback hierarchy and this install's own calibration layered+on top only once it has earned it.++Owner ruling (2026-09-29): "If we have the fleet data, we can provide+proper time estimations, or at least a range." scripts/fleet_timings_build.py+pulls real render_completed wall clocks from PostHog (the owner's own+installs excluded) into data/fleet_timings.json at three levels of+granularity (cell / chip / model); mlx_ltx_panel.py's+fleet_estimate_range() / fleet_calibrated_range() walk that table at+runtime, falling back to the panel's existing chip-factor cost model when+the fleet has nothing to say. This suite pins the LOADER and the FALLBACK+ORDER against a synthetic table (never the real, git-committed one — a+real-data assertion here would break every time the table is rebuilt) plus+the range-formatting and calibration-scaling helpers against the real+functions.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-fleet-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++def _synthetic_table() -> dict:+ """A small, hand-built fleet_timings table — the shape+ scripts/fleet_timings_build.py produces, with known cells at each+ level so the fallback order can be asserted exactly."""+ return {+ "schema": "fleet_timings/1",+ # Exact seconds, not ladder lower edges: this suite pins the lookup+ # order; the bucket reading is pinned in test_codex_4170_est (EST-4).+ "wall_sec": "seconds",+ "levels": {+ "cell": {+ "dims": ["engine", "mode", "tier", "frames", "chip_family", "ram_gb", "speed"],+ "cells": {+ # exact cell for (ltx, t2v, balanced, 121f, M4 Max, 64GB)+ "ltx|t2v|balanced|121.0|M4 Max|64.0|any": {+ "p25_sec": 120.0, "p50_sec": 150.0, "p75_sec": 180.0, "n": 50},+ # a DIFFERENT length, same chip+ram+tier — for cell_scaled+ "ltx|t2v|balanced|241.0|M4 Max|64.0|any": {+ "p25_sec": 240.0, "p50_sec": 280.0, "p75_sec": 320.0, "n": 40},+ # H3 fast vs best at the same shape+ "h3|t2v|draft_3s|73.0|M4 Max|64.0|fast": {+ "p25_sec": 60.0, "p50_sec": 90.0, "p75_sec": 90.0, "n": 10},+ "h3|t2v|draft_3s|73.0|M4 Max|64.0|best": {+ "p25_sec": 180.0, "p50_sec": 210.0, "p75_sec": 240.0, "n": 8},+ },+ },+ "chip": {+ "dims": ["engine", "mode", "tier", "frames", "chip_family", "speed"],+ "cells": {+ "ltx|t2v|balanced|121.0|M2 Pro|any": {+ "p25_sec": 300.0, "p50_sec": 360.0, "p75_sec": 420.0, "n": 20},+ },+ },+ "model": {+ "dims": ["engine", "mode", "tier", "frames", "speed"],+ "cells": {+ "ltx|t2v|balanced|121.0|any": {+ "p25_sec": 150.0, "p50_sec": 200.0, "p75_sec": 260.0, "n": 500},+ "ltx|t2v|quick|73.0|any": {+ "p25_sec": 50.0, "p50_sec": 60.0, "p75_sec": 70.0, "n": 100},+ },+ },+ },+ }+++class WithSyntheticTable(unittest.TestCase):+ def setUp(self):+ self._patch = mock.patch.object(P, "FLEET_TIMINGS", _synthetic_table())+ self._patch.start()+ self.addCleanup(self._patch.stop)+ # Calibration must not bleed in from a real state dir.+ self._calib_dir = Path(tempfile.mkdtemp(prefix="phos-fleet-calib-"))+ self._calib_patch = mock.patch.object(+ P, "_eta_calibration_path", lambda: self._calib_dir / "eta_calibration.json")+ self._calib_patch.start()+ self.addCleanup(self._calib_patch.stop)+++class FallbackOrder(WithSyntheticTable):+ def test_exact_cell_wins_first(self):+ r = P.fleet_estimate_range("ltx", "t2v", "balanced", 121,+ chip="M4 Max", ram=64.0)+ self.assertEqual(r["source"], "cell")+ self.assertEqual(r["n"], 50)+ self.assertAlmostEqual(r["p50_min"], 2.5, places=2) # 150s++ def test_falls_back_to_scaled_same_chip_different_length(self):+ """No exact cell at 169f on this chip+ram, but 121f and 241f both+ exist — nearest (121f) wins and is scaled by the cost model's own+ ratio between 169f and 121f (both balanced canvas)."""+ r = P.fleet_estimate_range("ltx", "t2v", "balanced", 169,+ chip="M4 Max", ram=64.0)+ self.assertEqual(r["source"], "cell_scaled")+ self.assertEqual(r["n"], 50) # from the 121f cell (nearer than 241f)+ base_121 = P.ltx_estimate_minutes(+ *[P.LTX_QUALITIES["balanced"][k] for k in ("width", "height")],+ 121, P.LTX_QUALITIES["balanced"]["stage1"], P.LTX_QUALITIES["balanced"]["stage2"])+ base_169 = P.ltx_estimate_minutes(+ *[P.LTX_QUALITIES["balanced"][k] for k in ("width", "height")],+ 169, P.LTX_QUALITIES["balanced"]["stage1"], P.LTX_QUALITIES["balanced"]["stage2"])+ expected_ratio = base_169 / base_121+ self.assertAlmostEqual(r["p50_min"], round(2.5 * expected_ratio, 2), delta=0.05)++ def test_falls_back_to_chip_level_when_ram_differs(self):+ r = P.fleet_estimate_range("ltx", "t2v", "balanced", 121,+ chip="M2 Pro", ram=999.0)+ self.assertEqual(r["source"], "chip")+ self.assertEqual(r["n"], 20)++ def test_falls_back_to_model_level_when_chip_is_unknown(self):+ r = P.fleet_estimate_range("ltx", "t2v", "balanced", 121,+ chip="SomeFutureChip", ram=999.0)+ self.assertEqual(r["source"], "model")+ self.assertEqual(r["n"], 500)++ def test_none_when_nothing_matches_at_any_level(self):+ r = P.fleet_estimate_range("ltx", "t2v", "high_720p", 481,+ chip="SomeFutureChip", ram=999.0)+ self.assertIsNone(r)++ def test_h3_fast_and_best_are_independent_cells(self):+ fast = P.fleet_estimate_range("h3", "t2v", "draft_3s", 73,+ chip="M4 Max", ram=64.0, speed="fast")+ best = P.fleet_estimate_range("h3", "t2v", "draft_3s", 73,+ chip="M4 Max", ram=64.0, speed="best")+ self.assertLess(fast["p50_min"], best["p50_min"])+++class RangeFormatting(unittest.TestCase):+ def test_tight_range_collapses_to_one_number(self):+ self.assertEqual(P._fmt_eta_range(3.0, 3.4), P._fmt_eta(3.4))++ def test_wide_range_shows_both_ends(self):+ self.assertEqual(P._fmt_eta_range(12.0, 18.0), "~12–18 min")++ def test_batch_suffix_rides_on_the_high_end(self):+ self.assertIn("batch", P._fmt_eta_range(20.0, 30.0))++ def test_hours_scale_uses_the_hour_form_on_both_ends(self):+ out = P._fmt_eta_range(65.0, 130.0)+ self.assertIn("h", out)+ self.assertIn("–", out)++ def test_never_shows_a_backwards_range(self):+ # p25 > p75 can happen with a thin, noisy sample; the function must+ # not print a range that reads lo > hi.+ out = P._fmt_eta_range(20.0, 5.0)+ self.assertNotIn("20–5", out)+++class CalibrationScaling(WithSyntheticTable):+ def test_no_calibration_before_two_samples(self):+ P._record_eta_calibration("fleet_ltx", 2.0) # only ONE sample+ r = P.fleet_calibrated_range("ltx", "t2v", "balanced", 121,+ chip="M4 Max", ram=64.0)+ self.assertAlmostEqual(r["p50_min"], 2.5, places=2) # unscaled++ def test_calibration_applies_once_two_samples_exist(self):+ P._record_eta_calibration("fleet_ltx", 2.0)+ P._record_eta_calibration("fleet_ltx", 2.0)+ r = P.fleet_calibrated_range("ltx", "t2v", "balanced", 121,+ chip="M4 Max", ram=64.0)+ self.assertAlmostEqual(r["p50_min"], 5.0, places=2) # 2.5 * 2.0+ self.assertIn("adjusted for this Mac's own renders", r["basis"])++ def test_calibration_scales_all_three_percentiles(self):+ P._record_eta_calibration("fleet_ltx", 1.5)+ P._record_eta_calibration("fleet_ltx", 1.5)+ r = P.fleet_calibrated_range("ltx", "t2v", "balanced", 121,+ chip="M4 Max", ram=64.0)+ self.assertAlmostEqual(r["p25_min"], 2.0 * 1.5, places=2)+ self.assertAlmostEqual(r["p75_min"], 3.0 * 1.5, places=2)++ def test_carries_a_formatted_range_and_midpoint(self):+ r = P.fleet_calibrated_range("ltx", "t2v", "balanced", 121,+ chip="M4 Max", ram=64.0)+ self.assertIn("eta_range", r)+ self.assertIn("eta_mid", r)++ def test_none_passes_through_cleanly(self):+ r = P.fleet_calibrated_range("ltx", "t2v", "nonexistent-tier", 999999,+ chip="NoSuchChip", ram=1.0)+ self.assertIsNone(r)+++class KeyFormatMatchesTheBuildScript(unittest.TestCase):+ def test_fleet_key_matches_build_scripts_key_for(self):+ """The runtime key-builder and the offline build script's key+ builder must produce byte-identical keys for the same row, or every+ lookup silently misses."""+ sys.path.insert(0, str(ROOT / "scripts"))+ import fleet_timings_build as B # noqa: PLC0415+ rec = {"engine": "ltx", "mode": "t2v", "tier": "balanced",+ "frames": 121.0, "chip_family": "M4 Max", "ram_gb": 64.0, "speed": ""}+ build_key = B._key_for(rec, ["engine", "mode", "tier", "frames",+ "chip_family", "ram_gb", "speed"])+ runtime_key = P._fleet_key("ltx", "t2v", "balanced", 121.0,+ chip="M4 Max", ram=64.0, speed="")+ self.assertEqual(build_key, runtime_key)+++class TheLoaderNeverRaises(unittest.TestCase):+ def test_missing_file_returns_empty_dict(self):+ with mock.patch.object(P, "FLEET_TIMINGS_PATH", Path("/no/such/file.json")):+ self.assertEqual(P._load_fleet_timings(), {})++ def test_malformed_json_returns_empty_dict(self):+ bad = Path(tempfile.mkdtemp(prefix="phos-fleet-bad-")) / "fleet_timings.json"+ bad.write_text("{not json", encoding="utf-8")+ with mock.patch.object(P, "FLEET_TIMINGS_PATH", bad):+ self.assertEqual(P._load_fleet_timings(), {})++ def test_the_real_shipped_table_loads_without_raising(self):+ """The actual committed data/fleet_timings.json — schema and+ structural sanity only, never a value assertion (real data changes+ every rebuild)."""+ data = P._load_fleet_timings()+ if not data:+ self.skipTest("no data/fleet_timings.json shipped in this checkout")+ self.assertEqual(data.get("schema"), "fleet_timings/1")+ self.assertIn("levels", data)+ for level_name in ("cell", "chip", "model"):+ self.assertIn(level_name, data["levels"])+ self.assertIn("cells", data["levels"][level_name])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_friendly_job_error.py b/test_friendly_job_error.pynew file mode 100644index 0000000..460291a--- /dev/null+++ b/test_friendly_job_error.py@@ -0,0 +1,110 @@+"""VC-24: `friendlyJobError` only calls a failure "needs the Q8 model" when+the raw error actually says so.++WHAT THIS GUARDS. The old check was `rawLower.includes('q8') ||+rawLower.includes('keyframe')`. A traceback or file path for essentially ANY+error on the High / Extend / Keyframe lanes contains one of those two+substrings - a path through `mlx_models/ltx-2.5-mlx-q8/…`, a stack frame in+`keyframe_pipeline.py` - so an unrelated OOM or shape error on those lanes was+mislabelled "This mode needs the Q8 model", sending a user who already has Q8+installed off to re-download weights they already have.++Every REAL "needs Q8" refusal (`mlx_ltx_panel.py`'s `RenderRefused` for+Extend / Keyframe / High) says one of two things verbatim:+ - "...(the Q8 model)..." when the pack isn't downloaded+ - "...<tier label> hardware tier — ..." when the Mac can't run it at all+`friendlyJobError` (webapp/js/queue.js) now matches those phrases instead of+the bare substrings.+"""+import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")++# Verbatim (trimmed) from the real refusals in mlx_ltx_panel.py, so this test+# breaks if the server-side wording ever changes without the client following.+REAL_Q8_MISSING = (+ "Keyframe mode needs the LTX-2.5 High add-on (the Q8 model), which "+ "isn't downloaded on this Mac yet. Missing 2 file(s): a, b."+)+REAL_HARDWARE_TIER = (+ "Extend isn't supported on the Compact hardware "+ "tier — the dev transformer needs more headroom than this Mac has."+)+# What a genuinely unrelated failure looks like when it happens to be+# raised WHILE rendering on the High/Extend/Keyframe lane - the traceback+# or file path routinely contains "q8" or "keyframe" with nothing to do+# with the pack being missing.+FALSE_POSITIVE_OOM = (+ "Helper killed by the OS: SIGKILL while loading "+ "mlx_models/ltx-2.5-mlx-q8/transformer-dev.safetensors"+)+FALSE_POSITIVE_SHAPE = (+ 'Traceback (most recent call last):\n File "keyframe_pipeline.py", '+ "line 214, in generate_two_stage\nRuntimeError: shape mismatch (256, 256) vs (272, 272)"+)+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-2000:], r.stderr[-2000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class FriendlyJobErrorMatchesRealRefusals(unittest.TestCase):+ def _classify(self, *raws: str) -> dict:+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ # H3-22 (4.17 merge): the generic fallback redacts local paths via+ # _redactLocalPaths, so extract it alongside.+ fn = (extract_function("_redactLocalPaths", src) + "\n"+ + extract_function("friendlyJobError", src))+ calls = ",\n ".join(f"friendlyJobError({json.dumps(r)})" for r in raws)+ return _run_node(fn + f"\nconsole.log(JSON.stringify([\n {calls}\n]));")++ def test_real_q8_pack_missing_is_labelled_correctly(self):+ got = self._classify(REAL_Q8_MISSING)[0]+ self.assertEqual(got["friendly"], "This mode needs the Q8 model.")++ def test_real_hardware_tier_refusal_is_labelled_correctly(self):+ got = self._classify(REAL_HARDWARE_TIER)[0]+ self.assertEqual(got["friendly"], "This mode needs the Q8 model.")++ def test_an_oom_on_the_q8_lane_is_not_mislabelled(self):+ got = self._classify(FALSE_POSITIVE_OOM)[0]+ self.assertNotEqual(got["friendly"], "This mode needs the Q8 model.")+ # SIGKILL is caught earlier in the function - it should still get+ # ITS OWN correct label, just never the Q8 one.+ self.assertIn("out of memory", got["friendly"].lower())++ def test_a_shape_error_naming_keyframe_pipeline_is_not_mislabelled(self):+ got = self._classify(FALSE_POSITIVE_SHAPE)[0]+ self.assertNotEqual(got["friendly"], "This mode needs the Q8 model.")+ self.assertEqual(got["friendly"], "Job failed.")++ def test_no_longer_a_bare_substring_check(self):+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ body = extract_function("friendlyJobError", src)+ self.assertNotIn("rawLower.includes('q8')", body)+ self.assertNotIn("rawLower.includes('keyframe')", body)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_gallery_card_keyboard.py b/test_gallery_card_keyboard.pynew file mode 100644index 0000000..bdfd144--- /dev/null+++ b/test_gallery_card_keyboard.py@@ -0,0 +1,133 @@+"""VC-21: gallery cards are reachable and actionable from the keyboard.++WHAT THIS GUARDS. `.car-card` was a plain `<div onclick>` with no tabindex+or role — 0 of 39 cards focusable. Tabbing from the prompt reached the+toolbar and each card's own "Show generation info" / trash buttons, but+never the card itself, so a keyboard-only user could reach Trash but never+reach "select this clip". The thumbnail `<video>` (no `controls`, hover-+scrub preview only) sat in the default tab order too — Chrome makes a bare+`<video>` focusable even without `controls` — so with ~40 cards on screen+that was ~40 extra stops before reaching anything actionable.++Fixed: the card gets `role="button" tabindex="0"` and an Enter/Space+handler that calls the same selectOutput() its onclick does; the preview+`<video>` gets `tabindex="-1"` so it no longer competes for a stop. Arrow-+key stepping through the gallery already existed as a global shortcut+(shortcuts.js `outputs.step`, arrowleft/arrowright) — this fix is scoped to+what was actually missing: reaching a card at all, and activating it once+reached.+"""+from __future__ import annotations++import json+import re+import shutil+import subprocess+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")++NODE = shutil.which("node")+++def _card_template() -> str:+ i = QUEUE_JS.index('class="car-card${o.path')+ j = QUEUE_JS.index("</div>`;", i)+ return QUEUE_JS[i - 20:j]+++class CardMarkup(unittest.TestCase):+ def test_card_is_focusable_with_a_button_role(self):+ tpl = _card_template()+ self.assertIn('role="button"', tpl)+ self.assertIn('tabindex="0"', tpl)++ def test_card_has_a_keydown_handler_for_enter_and_space(self):+ tpl = _card_template()+ m = re.search(r'onkeydown="([^"]*)"', tpl)+ self.assertIsNotNone(m, "no onkeydown handler on the card")+ handler = m.group(1)+ self.assertIn("Enter", handler)+ self.assertIn("' '", handler)+ self.assertIn("selectOutput(", handler)+ self.assertIn("preventDefault", handler, "Space must not also scroll the page")++ def test_card_has_an_accessible_label(self):+ tpl = _card_template()+ self.assertIn("aria-label=", tpl)++ def test_preview_video_is_removed_from_tab_order(self):+ # VC-31 (2026-09-29): the card's video thumbnail is a plain+ # <img src="/poster?path=..."> now, not a live <video> element —+ # an <img> was never in the tab order to begin with, so the+ # tabindex="-1" fix this test used to pin no longer has anything+ # to guard. Assert the stronger, now-true thing instead: no+ # focusable <video> ships in the card template at all.+ i = QUEUE_JS.index("const thumbHtml = isAudio")+ j = QUEUE_JS.index(";", QUEUE_JS.index('car-thumb" src="/poster', i))+ snippet = QUEUE_JS[i:j]+ self.assertNotIn("<video", snippet)++ def test_audio_element_keeps_its_own_controls_focusable(self):+ """The <audio controls> card IS meant to be tabbable/interactive -+ this fix must not blanket every media element with tabindex=-1."""+ i = QUEUE_JS.index("music-card-player")+ j = QUEUE_JS.index("></audio>", i)+ snippet = QUEUE_JS[i:j]+ self.assertNotIn('tabindex="-1"', snippet)+ self.assertIn("controls", snippet)+++class LiveKeyboardActivation(unittest.TestCase):+ """Runs the actual template logic in node against a DOM-ish stand-in to+ confirm the keydown handler string is valid JS and calls through."""++ def _run_node(self, script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-2000:], r.stderr[-2000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)++ def test_enter_and_space_both_call_selectoutput_once(self):+ tpl = _card_template()+ m = re.search(r'onkeydown="([^"]*)"', tpl)+ # The extracted string is the raw template-literal SOURCE (it still+ # contains the `${pathAttr}` placeholder); substitute a concrete+ # value to get real, runnable JS - same as what actually reaches+ # the browser once renderCarousel() interpolates it.+ handler_src = (m.group(1).replace(""", '"')+ .replace("${pathAttr}", "'/tmp/clip.mp4'"))+ script = f"""+let calls = [];+function selectOutput(p) {{ calls.push(p); }}+function run(key) {{+ let prevented = false;+ const event = {{ key, preventDefault: () => {{ prevented = true; }} }};+ (function() {{ {handler_src} }})();+ return prevented;+}}+const preventedEnter = run('Enter');+const preventedSpace = run(' ');+const preventedOther = run('Tab');+console.log(JSON.stringify({{ calls, preventedEnter, preventedSpace, preventedOther }}));+"""+ out = self._run_node(script)+ self.assertEqual(len(out["calls"]), 2)+ self.assertTrue(out["preventedEnter"])+ self.assertTrue(out["preventedSpace"])+ self.assertFalse(out["preventedOther"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_gallery_poster_cards.py b/test_gallery_poster_cards.pynew file mode 100644index 0000000..0b6862d--- /dev/null+++ b/test_gallery_poster_cards.py@@ -0,0 +1,336 @@+#!/usr/bin/env python3+"""VC-31 [P3] [PERF] `/status` is 97 KB every 1.5s, and gallery cards are+live `<video>` elements. VC-36 [P3] [UX] Gallery cards say little.++Coordinator ruling, 2026-09-29: "Gallery poster thumbnails: the ffmpeg+first frame, cached once per clip, instead of live <video> elements.+Richer cards (prompt snippet, mode, size). Trim the /status payload."++WHAT THIS GUARDS.+ 1 _ensure_video_poster(): idempotent, disk-cached (same idiom as the+ existing _ensure_thumbnail for images — sha1 of resolved path/mtime/+ size), ffmpeg extract at 2.5s with a 0s fallback for short clips,+ returns None (never raises) when ffmpeg is missing or the source is+ unreadable+ 2 GET /poster: same containment rule as /image (OUTPUT/UPLOADS only),+ video containers only, generates-then-serves the cached JPEG with a+ long-lived Cache-Control (the cache key already changes if the+ source does)+ 3 list_outputs() lifts a `prompt` snippet (capped, not the full text)+ and `mode` for the gallery card's richer info line — and+ _output_search_text's own per-field cap dropped from 400 to 160+ chars, a real trim given it runs on every /status poll+ 4 the client: gallery cards are plain <img src="/poster?path=..."> for+ video, matching photos — no more live <video> element, no more the+ IntersectionObserver/data-src dance that existed only to defer+ <video> loading (img's own loading="lazy" already does that job)+ 5 _cardTitleText() prefers the prompt snippet over the filename+ (falling back to the filename only when there is no prompt), and+ _cardModeSizeChip() builds the "mode · size" line from fields+ already in the payload — no new request per card (the size is the+ file's own, read from its mp4 header: Codex UI-8 / EST-12)+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import time+import unittest+from pathlib import Path+from urllib.parse import urlencode, urlparse++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-postercards-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8337")+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from panel.routes import GET_ROUTES # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+FFMPEG = shutil.which("ffmpeg")+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class _H:+ def _json(self, obj, code=200):+ self.out = (code, obj)++ def send_error(self, code, msg=None):+ self.out = (code, None)++ def send_response(self, code):+ self.out = (code, None)++ def send_header(self, k, v):+ self.headers = getattr(self, "headers", {})+ self.headers[k] = v++ def end_headers(self):+ pass++ class _WFile:+ def write(self, b):+ pass+ wfile = _WFile()+++# ---------------------------------------------------------------- 1[email protected](FFMPEG, "ffmpeg not on PATH")+class TestEnsureVideoPoster(unittest.TestCase):+ def setUp(self):+ P.OUTPUT.mkdir(parents=True, exist_ok=True)++ def _make_mp4(self, name, dur=5, frames=120):+ p = P.OUTPUT / name+ subprocess.run(+ [FFMPEG, "-y", "-f", "lavfi", "-i", f"color=c=blue:s=64x64:d={dur}",+ "-frames:v", str(frames), str(p)],+ capture_output=True, timeout=30, check=True,+ )+ self.addCleanup(lambda: p.unlink(missing_ok=True))+ return p++ def test_generates_and_caches_a_real_jpeg(self):+ clip = self._make_mp4(f"poster_{id(self)}.mp4")+ poster = P._ensure_video_poster(clip)+ self.assertIsNotNone(poster)+ self.assertTrue(poster.is_file())+ self.assertGreater(poster.stat().st_size, 0)+ self.addCleanup(lambda: poster.unlink(missing_ok=True))++ def test_second_call_returns_the_same_cached_file(self):+ clip = self._make_mp4(f"poster2_{id(self)}.mp4")+ p1 = P._ensure_video_poster(clip)+ p2 = P._ensure_video_poster(clip)+ self.assertEqual(p1, p2)+ self.addCleanup(lambda: p1.unlink(missing_ok=True))++ def test_short_clip_falls_back_to_0s_seek(self):+ clip = self._make_mp4(f"poster_short_{id(self)}.mp4", dur=1, frames=10)+ poster = P._ensure_video_poster(clip)+ self.assertIsNotNone(poster)+ self.addCleanup(lambda: poster.unlink(missing_ok=True))++ def test_missing_source_returns_none(self):+ self.assertIsNone(P._ensure_video_poster(P.OUTPUT / "does_not_exist_xyz.mp4"))++ def test_no_ffmpeg_returns_none_gracefully(self):+ clip = self._make_mp4(f"poster_noff_{id(self)}.mp4")+ # The poster uses the panel's resolved ffmpeg (FFMPEG) first, a PATH+ # lookup only when none was resolved — take both away.+ old, old_ff = P.shutil.which, P.FFMPEG+ P.shutil.which = lambda name: None+ P.FFMPEG = None+ try:+ self.assertIsNone(P._ensure_video_poster(clip))+ finally:+ P.shutil.which, P.FFMPEG = old, old_ff+++# ---------------------------------------------------------------- 2+class TestPosterRoute(unittest.TestCase):+ def test_route_registered(self):+ self.assertIn("/poster", GET_ROUTES)++ def test_refuses_a_path_outside_output_and_uploads(self):+ outside = Path(tempfile.mkdtemp(prefix="pc-outside-")) / "x.mp4"+ outside.write_bytes(b"x")+ h = _H()+ GET_ROUTES["/poster"](h, urlparse("/poster?" + urlencode({"path": str(outside)})))+ self.assertEqual(h.out[0], 403)++ def test_refuses_a_non_video_extension(self):+ P.UPLOADS.mkdir(parents=True, exist_ok=True)+ img = P.UPLOADS / f"pc_{id(self)}.png"+ img.write_bytes(b"x")+ h = _H()+ GET_ROUTES["/poster"](h, urlparse("/poster?" + urlencode({"path": str(img)})))+ self.assertEqual(h.out[0], 403)+ img.unlink(missing_ok=True)++ def test_refuses_a_missing_file(self):+ h = _H()+ GET_ROUTES["/poster"](h, urlparse("/poster?" + urlencode(+ {"path": str(P.OUTPUT / "nope_xyz.mp4")})))+ self.assertEqual(h.out[0], 404)++ @unittest.skipUnless(FFMPEG, "ffmpeg not on PATH")+ def test_serves_a_real_clip_as_jpeg(self):+ P.OUTPUT.mkdir(parents=True, exist_ok=True)+ clip = P.OUTPUT / f"pc_route_{id(self)}.mp4"+ subprocess.run(+ [FFMPEG, "-y", "-f", "lavfi", "-i", "color=c=green:s=64x64:d=3",+ "-frames:v", "60", str(clip)],+ capture_output=True, timeout=30, check=True,+ )+ h = _H()+ GET_ROUTES["/poster"](h, urlparse("/poster?" + urlencode({"path": str(clip)})))+ self.assertEqual(h.out[0], 200)+ self.assertEqual(h.headers["Content-Type"], "image/jpeg")+ self.assertIn("max-age", h.headers["Cache-Control"])+ clip.unlink(missing_ok=True)+++# ---------------------------------------------------------------- 3+class TestListOutputsRicherFields(unittest.TestCase):+ def setUp(self):+ P.OUTPUT.mkdir(parents=True, exist_ok=True)++ def _fixture(self, name, params):+ clip = P.OUTPUT / name+ clip.write_bytes(b"x")+ sidecar = Path(str(clip) + ".json")+ sidecar.write_text(json.dumps({"params": params}))+ old = time.time() - 10+ os.utime(clip, (old, old))+ os.utime(sidecar, (old, old))+ self.addCleanup(lambda: (clip.unlink(missing_ok=True), sidecar.unlink(missing_ok=True)))+ return clip++ def _row(self, clip):+ return next(o for o in P.list_outputs() if o["path"] == str(clip))++ def test_prompt_and_mode_are_lifted(self):+ clip = self._fixture(f"pc_rich_{id(self)}.mp4",+ {"mode": "i2v", "quality": "balanced", "frames": 121,+ "prompt": "A golden retriever runs through a meadow"})+ row = self._row(clip)+ self.assertEqual(row["prompt"], "A golden retriever runs through a meadow")+ self.assertEqual(row["mode"], "i2v")++ def test_prompt_is_capped_not_the_full_text(self):+ long_prompt = "word " * 200+ clip = self._fixture(f"pc_long_{id(self)}.mp4",+ {"mode": "t2v", "prompt": long_prompt})+ row = self._row(clip)+ self.assertLessEqual(len(row["prompt"]), 80)++ def test_music_row_gets_a_mode_even_without_a_params_mode(self):+ clip = self._fixture(f"pc_music_{id(self)}.wav",+ {"engine": "music"})+ Path(str(clip) + ".json").write_text(json.dumps(+ {"engine": "music", "params": {"engine": "music"}}))+ row = self._row(clip)+ self.assertEqual(row["mode"], "music")++ def test_search_text_field_cap_shrunk_to_160(self):+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ i = src.index("def _output_search_text")+ fn = src[i:src.index("\n\n\n", i)]+ self.assertIn("[:160]", fn)+ self.assertNotIn("[:400]", fn)+++# ---------------------------------------------------------------- 4+class TestClientCardIsPlainImg(unittest.TestCase):+ def test_no_more_video_element_in_the_card_template(self):+ i = QJS.index("const thumbHtml = isAudio")+ block = QJS[i:QJS.index(";", QJS.index("car-thumb\" src=\"/poster", i))]+ self.assertNotIn("<video", block)+ self.assertIn('/poster?path=', block)+ self.assertIn('loading="lazy"', block)++ def test_intersection_observer_removed(self):+ self.assertNotIn("_carThumbObserver", QJS)+ self.assertNotIn("new IntersectionObserver", QJS)++ def test_css_no_longer_targets_a_bare_video_selector(self):+ self.assertNotIn(".car-card video,", CSS)+ self.assertIn(".car-card img.car-thumb", CSS)+++# ---------------------------------------------------------------- 5+class TestCardTitleAndChip(unittest.TestCase):+ def test_title_prefers_prompt_over_filename(self):+ fn = "\n".join([extract_function("_cardTitleText", QJS),+ extract_function("_songCardName", QJS),+ "function escapeHtml(s) { return String(s == null ? '' : s); }"])+ script = fn + """+console.log(JSON.stringify({+ withPrompt: _cardTitleText({ name: 'ltx_20260929_120000.mp4', prompt: 'A woman walks through a rain-lit alley at night' }),+ withoutPrompt: _cardTitleText({ name: 'ltx_20260929_120000.mp4' }),+}));+"""+ out = _run_node(script)+ self.assertIn("A woman walks through", out["withPrompt"])+ self.assertNotIn("ltx_20260929", out["withPrompt"])+ self.assertEqual(out["withoutPrompt"], "ltx_20260929_120000.mp4")++ def test_title_truncates_long_prompts_with_an_ellipsis(self):+ fn = extract_function("_cardTitleText", QJS)+ script = fn + """+function escapeHtml(s) { return String(s); }+console.log(JSON.stringify({ t: _cardTitleText({ name: 'x.mp4', prompt: 'one two three four five six seven eight nine ten' }) }));+"""+ out = _run_node(script)+ self.assertTrue(out["t"].endswith('…'))+ self.assertEqual(len(out["t"].rstrip('…').split(' ')), 8)++ # Codex UI-8 / EST-12: the chip used to print the quality preset's /+ # H3 tier's DEFAULT canvas; it prints the file's own dimensions now+ # (list_outputs reads them from the mp4 header) and nothing when unknown.+ def test_chip_row_reads_the_files_own_size_not_the_preset(self):+ fn = extract_function("_cardModeSizeChip", QJS)+ script = f"""+const BOOT = {{ ltx: {{ qualities: [+ {{ key: 'balanced', label: 'Balanced', canvas: '1024×576', delivered_canvas: '1280×720' }},+] }} }};+{fn}+console.log(JSON.stringify({{+ sq: _cardModeSizeChip({{ mode: 't2v', quality: 'balanced', width: 768, height: 768 }}),+ unknown: _cardModeSizeChip({{ mode: 't2v', quality: 'balanced', width: null, height: null }}) }}));+"""+ out = _run_node(script)+ self.assertEqual(out["sq"], "t2v · 768×768")+ self.assertEqual(out["unknown"], "t2v")++ def test_chip_row_ignores_the_h3_tiers_default_geometry(self):+ fn = extract_function("_cardModeSizeChip", QJS)+ script = f"""+const BOOT = {{ ltx: {{ qualities: [] }} }};+function h3TierByKeyExact(k) {{ return k === 'standard_5s' ? {{ spec: '1280×704 · 121f' }} : null; }}+{fn}+console.log(JSON.stringify({{ chip: _cardModeSizeChip({{ mode: 't2v', h3_tier: 'standard_5s', width: 768, height: 448 }}) }}));+"""+ out = _run_node(script)+ self.assertEqual(out["chip"], "t2v · 768×448")++ def test_empty_chip_for_a_row_with_neither(self):+ fn = extract_function("_cardModeSizeChip", QJS)+ script = f"""+const BOOT = {{}};+{fn}+console.log(JSON.stringify({{ chip: _cardModeSizeChip({{}}) }}));+"""+ out = _run_node(script)+ self.assertEqual(out["chip"], "")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_gemma_truncate_patch.py b/test_gemma_truncate_patch.pynew file mode 100644index 0000000..01562ba--- /dev/null+++ b/test_gemma_truncate_patch.py@@ -0,0 +1,150 @@+#!/usr/bin/env python3+"""VC-14 [P2] [BUG] The Gemma watchdog fallback silently dropped the+*beginning* of long prompts.++Where: `ltx_core_mlx/text_encoders/gemma/encoders/base_encoder.py`'s+`tokenize()` left-pads to `max_length`; on an over-length prompt it kept the+LAST `max_length` tokens ("keep last tokens (left-pad = truncate from+left)"). The fallback path (`GEMMA_FALLBACK_MAX_LENGTH = 256`, armed on+chips whose Metal watchdog kills the full 1024-token encode — typically+low-end Macs) meant any prompt over 256 tokens dropped its subject, i.e.+whatever the user wrote FIRST.++Coordinator ruling, 2026-09-29: "truncation keeps the subject: keep the+head, cut from the tail."++This is vendored upstream code (`ltx-2-mlx`, pinned + patched per+`docs`/CLAUDE.md §5 and §20), so the fix is a new idempotent patch in+`patch_ltx_codec.py` — not a hand-edit of the installed package, which+would be silently lost on the next reinstall/update. Gated here:++ 1 the patch strings are self-consistent (OLD is the exact live upstream+ text today, NEW keeps the subject) and the grep rule from CLAUDE.md's+ "codec rule, stated correctly" holds for this patch too: exactly one+ unpatched hit in the vendored SOURCE tree, patched copy in site-packages+ 2 apply_patch() actually flips the installed file's slice direction+ 3 the behavioural claim itself: slicing `tokens[:max_length]` keeps the+ first N items (the subject) where `tokens[-max_length:]` kept the last+ N (arbitrary tail) — proven directly, no tokenizer/model needed+ 4 the patch is wired into main() as OPTIONAL (a drift note, not a hard+ install failure) — unlike the codec patch, losing this fix only+ degrades long-prompt quality on a rare fallback path, it never breaks+ a render+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import patch_ltx_codec as PC # noqa: E402++SRC = (ROOT / "patch_ltx_codec.py").read_text(encoding="utf-8")+VENDOR_SRC = (ROOT / "ltx-2-mlx" / "packages" / "ltx-core-mlx" / "src" /+ "ltx_core_mlx" / "text_encoders" / "gemma" / "encoders" /+ "base_encoder.py")+++class TestPatchStringsAreConsistent(unittest.TestCase):+ def test_old_matches_the_live_vendored_source_verbatim(self):+ vendor_text = VENDOR_SRC.read_text(encoding="utf-8")+ self.assertIn(PC.PATCH_GEMMA_TRUNCATE_OLD, vendor_text)++ def test_new_keeps_the_subject_not_the_tail(self):+ self.assertIn("tokens[:max_length]", PC.PATCH_GEMMA_TRUNCATE_NEW)+ self.assertNotIn("tokens[-max_length:]", PC.PATCH_GEMMA_TRUNCATE_NEW)+ self.assertIn("VC-14", PC.PATCH_GEMMA_TRUNCATE_NEW)++ def test_grep_rule_one_unpatched_hit_in_vendored_source(self):+ # Mirrors CLAUDE.md's "codec rule, stated correctly" for this patch:+ # the git-tracked SOURCE tree stays the unpatched upstream text —+ # only the installed site-packages copy carries the fix. A second+ # hit in the source tree would mean the patch was applied to the+ # wrong copy (the editable-install failure class the codec rule+ # already guards against).+ import subprocess+ out = subprocess.run(+ ["grep", "-rnF", "--include=*.py", "tokens[-max_length:]",+ str(ROOT / "ltx-2-mlx" / "packages" / "ltx-core-mlx")],+ capture_output=True, text=True,+ ).stdout+ self.assertEqual(len(out.strip().splitlines()), 1, out)+++class TestApplyPatchFlipsSliceDirection(unittest.TestCase):+ def test_apply_patch_on_a_fresh_copy_of_the_unpatched_file(self):+ tmp = Path(tempfile.mkdtemp(prefix="gemma-patch-")) / "base_encoder.py"+ tmp.write_text(VENDOR_SRC.read_text(encoding="utf-8"), encoding="utf-8")+ outcome = PC.apply_patch(+ tmp, PC.PATCH_GEMMA_TRUNCATE_OLD, PC.PATCH_GEMMA_TRUNCATE_NEW,+ marker="VC-14", label="gemma-truncate (test)",+ )+ self.assertEqual(outcome, PC.OUTCOME_APPLIED)+ patched = tmp.read_text(encoding="utf-8")+ self.assertIn("tokens[:max_length]", patched)+ self.assertNotIn("tokens[-max_length:]", patched)++ def test_idempotent_second_run_is_a_no_op(self):+ tmp = Path(tempfile.mkdtemp(prefix="gemma-patch-")) / "base_encoder.py"+ tmp.write_text(VENDOR_SRC.read_text(encoding="utf-8"), encoding="utf-8")+ PC.apply_patch(tmp, PC.PATCH_GEMMA_TRUNCATE_OLD, PC.PATCH_GEMMA_TRUNCATE_NEW,+ marker="VC-14", label="gemma-truncate (test)")+ outcome2 = PC.apply_patch(tmp, PC.PATCH_GEMMA_TRUNCATE_OLD, PC.PATCH_GEMMA_TRUNCATE_NEW,+ marker="VC-14", label="gemma-truncate (test)")+ self.assertEqual(outcome2, PC.OUTCOME_ALREADY)++ def test_a_missing_target_reports_missing_not_a_crash(self):+ outcome = PC.apply_patch(+ Path("/tmp/does-not-exist-gemma-encoder.py"),+ PC.PATCH_GEMMA_TRUNCATE_OLD, PC.PATCH_GEMMA_TRUNCATE_NEW,+ marker="VC-14", label="gemma-truncate (test)",+ )+ self.assertEqual(outcome, PC.OUTCOME_MISSING)+++class TestTruncationBehaviourItself(unittest.TestCase):+ """The actual claim: which end of the list survives. No tokenizer+ needed — the bug and the fix are both pure slicing."""++ def test_old_behaviour_drops_the_subject(self):+ # A "prompt" where token 0 is the subject and the rest is filler.+ tokens = ["SUBJECT"] + [f"filler{i}" for i in range(300)]+ max_length = 256+ old_kept = tokens[-max_length:]+ self.assertNotIn("SUBJECT", old_kept)++ def test_new_behaviour_keeps_the_subject(self):+ tokens = ["SUBJECT"] + [f"filler{i}" for i in range(300)]+ max_length = 256+ new_kept = tokens[:max_length]+ self.assertEqual(new_kept[0], "SUBJECT")+ self.assertEqual(len(new_kept), max_length)++ def test_short_prompts_are_unaffected_either_way(self):+ tokens = ["SUBJECT", "a", "b", "c"]+ max_length = 256+ self.assertEqual(tokens[-max_length:], tokens[:max_length])+++class TestPatchIsOptionalNotFatal(unittest.TestCase):+ def test_main_calls_gemma_patch_and_treats_drift_as_a_note(self):+ fn = SRC[SRC.index("def main() -> int:"):]+ self.assertIn("PATCH_GEMMA_TRUNCATE_OLD", fn)+ self.assertIn("PATCH_GEMMA_TRUNCATE_NEW", fn)+ # unlike the codec patch, a drift/missing outcome here must NOT+ # return a non-zero exit — assert the gemma block has no early+ # `return` between its apply_patch call and the end of main()+ i = fn.index("gemma_target = _find(")+ tail = fn[i:]+ self.assertNotIn("return 2", tail)+ self.assertNotIn("return 3", tail)+ self.assertNotIn("return 4", tail)+ self.assertIn("return 0", tail)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_ghost_btn_icon.py b/test_ghost_btn_icon.pynew file mode 100644index 0000000..3c8448c--- /dev/null+++ b/test_ghost_btn_icon.py@@ -0,0 +1,107 @@+"""VC-17: the Enhance button (and every ghost-btn like it) lays its icon and+label out side by side, and every "-fill" icon actually takes the button's+text colour instead of defaulting to black.++TWO INDEPENDENT DEFECTS, same button, both from the same review shot+(zoom_enhance_row.png).++1. LAYOUT. `#enhanceBtn`'s parent, `.composer-tools`, is `display: flex`.+ Per the CSS Display spec a flex item is blockified for layout purposes,+ so a plain `<button>` (UA-default `display: inline-block`) computes to+ `display: block` there - confirmed live: 70x30 box, 37px of content+ ("Enhance" plus its icon stacking on separate lines instead of sitting+ side by side). `panel.css` already had this exact fix applied to+ `.row-actions .ghost-btn` and `.sb-film-actions .ghost-btn` individually+ (grep either selector) - `.composer-tools .ghost-btn` was simply never+ one of the patched contexts. Putting `display: inline-flex; align-items:+ center; gap: 6px; white-space: nowrap` on the BASE `.ghost-btn` rule+ instead of another one-off selector closes the whole class: any+ ghost-btn under any flex/grid ancestor, patched or not yet discovered,+ lays out correctly.++2. COLOUR. Every "*-fill" icon in the inline Phosphor sprite is meant to+ render as a solid shape in the current text colour - and every one of+ them does that by carrying `fill="currentColor"` on its own `<path>`+ (`.ph { color: currentColor }` in panel.css does NOT set the SVG `fill`+ property, so this per-path attribute is the only thing making that+ work; SVG's own initial value for `fill` is black). ph-sparkle-fill+ (Enhance's icon), ph-info-fill, ph-pause-fill, ph-play-fill,+ ph-warning-fill and ph-x-circle-fill were all missing it - a solid+ black icon on Enhance's own light text, and on Phosphene's dark theme+ effectively invisible wherever these render. Fixed by adding+ `fill="currentColor"` to each, matching the convention every other+ "-fill" symbol in the sprite already follows.+"""+from __future__ import annotations++import re+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+_RAW_CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+# Strip comments before brace-matching below - several of them (this file's+# own .ghost-btn block included) contain example CSS with braces of their+# own, which would otherwise end a naive `{...}` capture early.+CSS = re.sub(r"/\*.*?\*/", "", _RAW_CSS, flags=re.S)+++def _symbol_body(symbol_id: str) -> str:+ m = re.search(+ r'<symbol id="' + re.escape(symbol_id) + r'"[^>]*>(.*?)</symbol>', HTML)+ assert m, f"symbol #{symbol_id} not found in the sprite"+ return m.group(1)+++class GhostBtnLaysOutInline(unittest.TestCase):+ def test_base_rule_is_inline_flex(self):+ m = re.search(r"\.ghost-btn\s*\{([^}]*)\}", CSS)+ self.assertIsNotNone(m, "no base .ghost-btn rule")+ body = m.group(1)+ self.assertIn("display: inline-flex", body)+ self.assertIn("align-items: center", body)+ self.assertIn("white-space: nowrap", body)++ def test_enhance_button_is_a_ghost_btn_under_a_flex_ancestor(self):+ """Pin the exact case the review caught: #enhanceBtn (.ghost-btn)+ sits under .composer-tools, which is display:flex - so this button+ was one of the ones the base-rule fix (above) needed to reach."""+ m = re.search(r'<button[^>]*id="enhanceBtn"[^>]*>', HTML)+ self.assertIsNotNone(m)+ self.assertIn('class="ghost-btn"', m.group(0))+ i = HTML.index('<div class="composer-tools">')+ j = HTML.index('id="enhanceBtn"')+ self.assertLess(i, j, "#enhanceBtn must be inside .composer-tools")+ ct = re.search(r"\.composer-tools\s*\{([^}]*)\}", CSS)+ self.assertIsNotNone(ct)+ self.assertIn("display: flex", ct.group(1))+++class FillIconsCarryTheirOwnColour(unittest.TestCase):+ """Every symbol whose id ends "-fill" is meant to paint as a solid shape+ in the current text colour. Assert every one of them says so, not just+ the icon the review happened to screenshot."""++ def test_every_fill_symbol_has_fill_currentcolor(self):+ ids = sorted(set(re.findall(r'<symbol id="(ph-[a-z0-9-]*-fill)"', HTML)))+ self.assertIn("ph-sparkle-fill", ids)+ self.assertGreaterEqual(len(ids), 6, ids)+ missing = []+ for sid in ids:+ body = _symbol_body(sid)+ # every drawable child (path/circle/rect/polygon/ellipse) needs+ # its own fill, since `.ph` sets no CSS `fill` of its own+ for tag in re.finditer(r"<(path|circle|rect|polygon|ellipse)\b[^>]*/>", body):+ if 'fill=' not in tag.group(0):+ missing.append(f"{sid}: {tag.group(0)[:80]}")+ self.assertEqual(missing, [], "fill icon(s) missing fill=currentColor:\n "+ + "\n ".join(missing))++ def test_sparkle_fill_is_currentcolor_not_a_literal(self):+ body = _symbol_body("ph-sparkle-fill")+ self.assertIn('fill="currentColor"', body)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_04_speed_visible.py b/test_h3_04_speed_visible.pynew file mode 100644index 0000000..a2a5f73--- /dev/null+++ b/test_h3_04_speed_visible.py@@ -0,0 +1,140 @@+"""H3-04 [P1]: Fast/Best is invisible after Generate.++Pinned by the flow review: the Now card meta (queue.js) showed mode, size,+frames and time only — no Speed. Queue rows showed nothing. A Best clip's+info modal had no Speed row at all (only Fast/tristep and the retired+Turbo earned one). Speed persists per browser (phos_h3_speed), so one Best+choice silently sticks — and the "expected 18, waited 43+" report matched a+Standard 10s on an M4 Pro 48 GB exactly: Fast was priced at 16.8 min before+4.16.2, Best on the same cell at 44.5 min, and nothing on screen said which+one was running or that it was taking even longer than THAT.++The fix: prog.h3_speed / prog.h3_pace_warning (server, mlx_ltx_panel.py's+H3 run loop) plus h3JobSpeedLabel / h3JobShapeLabel (engines.js) wired into+the Now card, the queue rows, and the info modal.+"""+from __future__ import annotations++import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-h304-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++NODE = shutil.which("node")+ENGINES = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+QUEUE = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+PANEL = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+++def _h3_run_block() -> str:+ i = PANEL.index("win_span = 87.0 / float(tot_windows)")+ j = PANEL.index("rc = proc.wait()", i)+ return PANEL[i:j]+++class ServerRecordsWhichSpeedIsRunning(unittest.TestCase):+ def test_progress_carries_h3_speed(self):+ block = _h3_run_block()+ self.assertIn('"h3_speed": ("fast" if tristep else "best")', block)++ def test_progress_carries_a_pace_note_field(self):+ block = _h3_run_block()+ self.assertIn('"h3_pace_warning": _pace_note', block)++ def test_pace_flag_compares_measured_to_modeled_per_step(self):+ block = _h3_run_block()+ self.assertIn("_modeled_per_step", block)+ self.assertIn("per_step > _modeled_per_step * 1.5", block)++ def test_pace_note_names_the_fast_alternative_when_running_best(self):+ block = _h3_run_block()+ self.assertIn("Fast would take about", block)+ self.assertIn("not tristep and _fast_alt is not None", block)++ def test_modeled_per_step_uses_the_same_cost_model_as_every_estimate(self):+ """Not a second cost model — the same _h3_forward_seconds /+ _h3_packed_rows / _h3_speed_factor h3_estimate_minutes itself uses."""+ rows = P._h3_packed_rows(768, 448, 124)+ modeled = P._h3_forward_seconds(rows) * P._h3_speed_factor(1)+ self.assertGreater(modeled, 0)+++class ClientLabelsAreSharedAcrossAllThreeSurfaces(unittest.TestCase):+ def test_now_card_reads_prog_h3_speed(self):+ self.assertIn("prog.h3_speed", QUEUE)+ self.assertIn("prog.h3_pace_warning", QUEUE)++ def test_now_card_falls_back_to_the_submitted_params(self):+ self.assertIn("h3JobSpeedLabel(cur)", QUEUE)+ self.assertIn("h3JobShapeLabel(cur)", QUEUE)++ def test_queue_rows_show_the_speed_tag(self):+ self.assertIn("h3JobSpeedLabel(j.params)", QUEUE)++ def test_info_modal_best_clips_get_a_speed_row_too(self):+ """The bug: Fast (h3_tristep) and the retired Turbo (h3_turbo) each+ pushed a <dt>Speed</dt> row; a plain Best clip fell through all+ three branches with no Speed row printed anywhere."""+ i = QUEUE.index("if (p.h3_tristep) {")+ j = QUEUE.index("if (p.accel && p.accel", i)+ block = QUEUE[i:j]+ self.assertIn("<dt>Speed</dt><dd>Best", block)+ # It must be reachable as a genuine else, not nested under a+ # condition that could also be false.+ self.assertRegex(block, r"\}\s*else\s*\{\s*\n\s*//.*H3-04")++ def test_shared_label_functions_are_published(self):+ pub = ENGINES[ENGINES.index("Object.assign(globalThis"):]+ self.assertIn("h3JobSpeedLabel", pub)+ self.assertIn("h3JobShapeLabel", pub)++[email protected](NODE, "node not on PATH")+class LabelFunctionsRunCorrectly(unittest.TestCase):+ def _run(self, js: str) -> str:+ r = subprocess.run([NODE, "-e", js], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr)+ return r.stdout.strip()++ def _harness(self) -> str:+ from scripts.extract_panel_js import extract_function+ return "\n".join(extract_function(n, ENGINES) for n in (+ "h3ResolveTierKey", "h3TierByKey", "h3SpeedOfParams",+ "h3JobSpeedLabel", "h3JobShapeLabel")) + """+var H3 = { tiers: [{ key: 'standard_10s', quality: 'standard', length: '10s',+ quality_label: 'Standard', length_label: '10s' }],+ aliases: {} };+"""++ def test_fast_and_best_labels(self):+ js = self._harness() + """+console.log(JSON.stringify([+ h3JobSpeedLabel({ engine: 'h3', h3_tristep: true }),+ h3JobSpeedLabel({ engine: 'h3', h3_tristep: false, h3_turbo: false }),+ h3JobSpeedLabel({ engine: 'ltx' }),+]));+"""+ import json as _json+ self.assertEqual(_json.loads(self._run(js)), ["Fast", "Best", ""])++ def test_shape_label_looks_up_the_real_tier(self):+ js = self._harness() + """+console.log(h3JobShapeLabel({ engine: 'h3', h3_tier: 'standard_10s' }));+"""+ self.assertEqual(self._run(js).replace('"', ''), "Hailuo H3 · Standard 10s")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_48gb_install_path.py b/test_h3_48gb_install_path.pyindex c68b527..76093df 100644--- a/test_h3_48gb_install_path.py+++ b/test_h3_48gb_install_path.py@@ -113,9 +113,14 @@ class TestPanelTellsA48GBMacTheTruth(unittest.TestCase):self.assertIn(P.H3_INSTALL_MENU_TEXT, PANEL_JS)def test_settings_card_splits_the_band(self):- branch = PANEL_JS.split("if (h3s.needs_q8_dit) {")[1][:1600]+ # H3-20: the two sub-cases (built vs never-installed) used to carry+ # different button text ("How to enable H3" / "How to install H3");+ # they now share one "Set up H3 ->" label, since both open the same+ # install card, which differentiates internally (H3-05). The band+ # split itself (missing_q8_dit vs not) is unchanged and still real.+ branch = PANEL_JS.split("if (h3s.needs_q8_dit) {")[1][:2400]self.assertIn("h3s.reason === 'missing_q8_dit'", branch)- self.assertIn("How to install H3", branch)+ self.assertIn("Set up H3", branch)def test_install_card_says_this_mac_runs_it_and_where_the_button_is(self):self.assertIn("H3.ram_lane === 'q8'", PANEL_JS)@@ -315,6 +320,14 @@ class TestPreflightLetsA48GBMacThrough(unittest.TestCase):d = Path(tempfile.mkdtemp(prefix="phos-sysctl-"))(d / "sysctl").write_text(f"#!/bin/sh\necho {GIB48}\n")(d / "sysctl").chmod(0o755)+ # H3-18: the preflight now also gates on free disk space (~97 GB for+ # a fresh install). That's this test's own machine's real free space+ # here, not the 48 GB RAM figure under test — fake `df` with plenty+ # of room so this test still isolates the RAM check, its own concern.+ (d / "df").write_text(+ "#!/bin/sh\necho 'Filesystem 1024-blocks Used Available Capacity Mounted'\n"+ "echo '/dev/disk1 1000000000 1 209715200 1% /'\n")+ (d / "df").chmod(0o755)out = subprocess.run(["bash", str(ROOT / "scripts/pinokio/h3_preflight.sh")],capture_output=True, text=True, errors="replace", timeout=30,env={**os.environ, "PATH": f"{d}:{os.environ['PATH']}"})diff --git a/test_h3_build_vs_repair_copy.py b/test_h3_build_vs_repair_copy.pynew file mode 100644index 0000000..2810e3a--- /dev/null+++ b/test_h3_build_vs_repair_copy.py@@ -0,0 +1,65 @@+#!/usr/bin/env python3+"""H3-05 / H3-18 / H3-39: the "compact engine not built" state must say+Build, everywhere, and the install card must not overclaim.++`H3.repairable` is true for TWO different real states — missing_q8_dit+(every weight present, only the local Q8 build is missing: Pinokio's+sidebar shows ONLY a "Build Hailuo H3 compact engine..." entry, no Repair+entry at all) and a genuinely broken venv/runner (Pinokio shows "Repair+Hailuo H3..."). Every UI surface that branched on `repairable` alone said+"Repair" unconditionally: the install-card CTA, its title ("Hailuo H3 · 75+GB" even though nothing downloads — H3-39), the repeat-click toast nudge,+the engine badge ('repair'), and the engine-menu tooltip. A 48 GB Mac in+exactly this state is the rescue scenario recent releases targeted, sent+looking for a sidebar button that does not exist.++Also fixes H3-18's false claim in the real-install blurb ("either engine+can drive any render you start" — H3 is Text/Image only).++Verified live (booted panel, 48 GB / weights-present / no-Q8-build+scenario, Playwright): openH3InstallCard() title reads "Build the compact+engine · ~5 min, no download", body contains "Build Hailuo H3" and not+"Repair Hailuo H3", and the engine-menu badge reads "build" not "repair".+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ENGINES_JS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+++class BuildVsRepairCopy(unittest.TestCase):+ def test_install_card_branches_on_missing_q8_dit(self):+ self.assertIn("const needsBuildOnly = H3.reason === 'missing_q8_dit';", QUEUE_JS)+ self.assertIn("fixMenuText", QUEUE_JS)+ self.assertIn("Build Hailuo H3 compact engine (weights kept — no re-download)", QUEUE_JS)++ def test_install_card_title_is_dynamic(self):+ self.assertIn("Build the compact engine · ~5 min, no download", QUEUE_JS)+ self.assertNotIn('<h2 id="h3InstallTitle">Hailuo H3 · 75 GB</h2>\n', QUEUE_JS) # sanity: title lives in html, not js+ html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+ self.assertIn('<h2 id="h3InstallTitle">Hailuo H3 · 75 GB</h2>', html,+ "markup default changed — update the JS branches too if intentional")+ self.assertIn("document.getElementById('h3InstallTitle')", QUEUE_JS,+ "nothing rewrites the title at open time")++ def test_repeat_click_nudge_branches_too(self):+ self.assertIn("build the compact engine, no download", QUEUE_JS)+ self.assertIn("repair, no download", QUEUE_JS)++ def test_no_overclaim_about_which_modes_h3_covers(self):+ self.assertNotIn("either engine can drive any render you start", QUEUE_JS)+ self.assertRegex(QUEUE_JS, r"H3 covers Text and\s+Image")++ def test_engine_badge_says_build_not_repair(self):+ self.assertIn("st.reason === 'missing_q8_dit') ? 'build'", ENGINES_JS)++ def test_engine_menu_tooltip_distinguishes_build_from_repair(self):+ self.assertIn("needs its compact engine built", ENGINES_JS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_disk_preflight.py b/test_h3_disk_preflight.pynew file mode 100644index 0000000..fbbd5af--- /dev/null+++ b/test_h3_disk_preflight.py@@ -0,0 +1,112 @@+#!/usr/bin/env python3+"""H3-18: the H3 install must refuse on a full disk, not just print `df`.++Before this, install_h3.js's only disk-space behaviour was `echo 'free disk+space:' && df -h .` — informational, never gating. A Mac without room for the+~75 GB download (plus the ~22 GB compact-engine build install.js runs+afterward) found out by watching the download fail partway through instead+of being told up front, the same class of problem the RAM preflight already+solves for memory.++scripts/pinokio/h3_preflight.sh now runs a disk check right after the RAM+check: fail-open if `df` can't be read (matching the RAM check's own+fail-open design), otherwise a real free-space number against a+context-dependent requirement — ~97 GB from nothing (download + build both+exist on disk before the build consumes the download's output), ~25 GB when+the bf16 DiT (the tree's largest file, the same marker h3_roots.sh uses) is+already on disk, meaning only the local build and stragglers remain.++Runs the REAL script under a fake `df`/`sysctl` PATH — no network, no real+disk risk, exercises the actual exit-code contract Pinokio's `shell.run`+depends on.+"""+from __future__ import annotations++import os+import shutil+import stat+import subprocess+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SCRIPT = ROOT / "scripts" / "pinokio" / "h3_preflight.sh"++PLENTY_MEM = "68719476736" # 64 GB, well above both floors+++def _fakebin(tmp: Path, *, avail_kb: int, mem_bytes: str = PLENTY_MEM) -> Path:+ fb = tmp / "fakebin"+ fb.mkdir(exist_ok=True)+ (fb / "df").write_text(+ "#!/bin/sh\n"+ "echo 'Filesystem 1024-blocks Used Available Capacity Mounted'\n"+ f"echo '/dev/disk1 1000000000 1 {avail_kb} 1% /'\n"+ )+ (fb / "sysctl").write_text(f"#!/bin/sh\necho {mem_bytes}\n")+ for f in ("df", "sysctl"):+ p = fb / f+ p.chmod(p.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)+ return fb+++def _run(cwd: Path, fakebin: Path) -> subprocess.CompletedProcess:+ env = dict(os.environ)+ env["PATH"] = f"{fakebin}:{env.get('PATH', '')}"+ return subprocess.run(["bash", str(SCRIPT)], cwd=str(cwd), env=env,+ capture_output=True, text=True, timeout=15)+++class DiskPreflightGates(unittest.TestCase):+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="phos-h3-diskpf-"))+ self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)++ def test_script_parses(self):+ subprocess.run(["bash", "-n", str(SCRIPT)], check=True)++ def test_refuses_a_fresh_install_short_of_97gb(self):+ fb = _fakebin(self.tmp, avail_kb=80 * 1024 * 1024) # 80 GB, needs ~97+ r = _run(self.tmp, fb)+ self.assertEqual(r.returncode, 1, r.stdout + r.stderr)+ self.assertIn("NEEDS ~97 GB FREE", r.stdout)+ self.assertIn("Nothing was downloaded", r.stdout)++ def test_passes_a_fresh_install_with_room(self):+ fb = _fakebin(self.tmp, avail_kb=120 * 1024 * 1024) # 120 GB+ r = _run(self.tmp, fb)+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+ self.assertIn("H3 disk preflight OK", r.stdout)+ self.assertIn("needs ~97 GB", r.stdout)++ def test_weights_already_present_only_needs_25gb(self):+ weights = self.tmp / "mlx_models" / "hailuo-h3" / "deepbeep-pruned-bf16"+ weights.mkdir(parents=True)+ (weights / "MiniMax-H3-FL2VA-pruned_bf16.safetensors").write_bytes(b"x")+ fb = _fakebin(self.tmp, avail_kb=30 * 1024 * 1024) # 30 GB: fails the+ # 97 GB bar but clears the 25 GB one+ r = _run(self.tmp, fb)+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+ self.assertIn("needs ~25 GB", r.stdout)++ def test_fails_open_when_df_is_unreadable(self):+ fb = self.tmp / "fakebin"+ fb.mkdir()+ (fb / "sysctl").write_text(f"#!/bin/sh\necho {PLENTY_MEM}\n")+ (fb / "sysctl").chmod(0o755)+ # No `df` on this PATH at all -> unreadable, must not block.+ env = dict(os.environ)+ env["PATH"] = f"{fb}:/usr/bin:/bin"+ env.pop("PATH_DF_OVERRIDE", None)+ # Force df to fail by pointing PATH at a dir with no df AND masking+ # the real one is impractical across machines; instead assert the+ # documented contract directly on the script text.+ src = SCRIPT.read_text()+ self.assertIn('grep -qE \'^[0-9]+$\'', src,+ "the disk check no longer guards against unparseable df output")+ self.assertIn("could not read free space", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_docs_tier_names_current.py b/test_h3_docs_tier_names_current.pynew file mode 100644index 0000000..35748d5--- /dev/null+++ b/test_h3_docs_tier_names_current.py@@ -0,0 +1,58 @@+#!/usr/bin/env python3+"""H3-31 (docs remainder): docs/H3_ENGINE.md's Tiers table used the+RETIRED fixed-tier vocabulary (HQ / Wide / Long) throughout, even though+the UI moved to two independent axes — Quality (canvas) x Length+(duration) — and H3_TIER_ALIASES (mlx_ltx_panel.py) only keeps those old+composite keys alive to resolve a sidecar written before the split.+Someone reading the docs to understand the current UI would learn names+that don't exist in the picker.++Rewrote the table to the current Quality/Length columns and added an+explicit legacy-key -> current-key table, sourced from the real+H3_TIER_ALIASES dict so it can't drift silently.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-h3-docsnames-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8306")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++H3_DOCS = (ROOT / "docs" / "H3_ENGINE.md").read_text(encoding="utf-8")+++class TierTableUsesCurrentNames(unittest.TestCase):+ def test_table_header_is_quality_by_length(self):+ self.assertIn("| Quality | Length | Geometry", H3_DOCS)++ def test_no_row_still_labelled_hq_wide_or_long(self):+ # The retired vocabulary may still appear in PROSE explaining the+ # alias mechanism, but not as a table row label.+ for bad in ("| HQ ", "| Wide ", "| Long ", "| Wide / High"):+ self.assertNotIn(bad, H3_DOCS)++ def test_legacy_alias_table_matches_the_real_dict(self):+ aliases = P.H3_TIER_ALIASES+ self.assertTrue(aliases, "H3_TIER_ALIASES is empty or missing")+ # Identity entries (e.g. draft_3s -> draft_3s) exist for uniform+ # lookup, not because "draft_3s" is a retired name — only the+ # genuinely renamed keys belong in a legacy/current translation table.+ renamed = {k: v for k, v in aliases.items() if k != v}+ self.assertTrue(renamed)+ for legacy, current in renamed.items():+ self.assertIn(f"`{legacy}`", H3_DOCS)+ self.assertIn(f"`{current}`", H3_DOCS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_engine_menu_keyboard.py b/test_h3_engine_menu_keyboard.pynew file mode 100644index 0000000..7f21767--- /dev/null+++ b/test_h3_engine_menu_keyboard.py@@ -0,0 +1,83 @@+#!/usr/bin/env python3+"""H3-17: the engine menu must be reachable and operable from the+keyboard.++#engineMenu is portaled to <body> (it has to be — <header> is+overflow:hidden and would slice it), which is exactly what broke+keyboard access: a portaled element sits at the END of the DOM+regardless of where its trigger lives, so Tab from the trigger button+skipped clear over the menu to whatever else the header holds (the+health chip). Opening the menu never moved focus into it, and there was+no arrow-key navigation between rows at all — Escape was the only+keyboard affordance that existed.++Fix: toggleEngineMenu() now focuses the active engine's row (or the+first row) the moment the menu opens, instead of requiring Tab to reach+a portaled element. A keydown handler scoped to the open menu adds+ArrowUp/ArrowDown (cyclic) and Home/End; Enter/Space already worked+natively since the rows are plain <button> elements. closeEngineMenu()+now returns focus to the trigger by default (opt out via+`returnFocus:false` for the click-outside and resize paths, where+yanking focus back would be surprising).++Verified live: focused the trigger, pressed Enter -> menu opened with+document.activeElement on the active engine's row (eng-opt.active,+data-engine="ltx"); ArrowDown moved focus to the next row+(data-engine="h3"); ArrowUp moved it back; Escape closed the menu and+returned focus to the trigger button.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+ENGINES_JS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class EngineMenuIsKeyboardReachable(unittest.TestCase):+ def test_opening_focuses_the_active_row(self):+ body = _function_body(ENGINES_JS, "function toggleEngineMenu() {")+ self.assertIn("opts.find(o => o.classList.contains('active')) || opts[0]", body)+ self.assertIn("target.focus();", body)++ def test_closing_returns_focus_to_the_trigger_by_default(self):+ body = _function_body(ENGINES_JS, "function closeEngineMenu(opts) {")+ self.assertIn("if (!opts || opts.returnFocus !== false) t.focus();", body)++ def test_click_outside_and_resize_dont_yank_focus_back(self):+ self.assertIn("closeEngineMenu({ returnFocus: false });", ENGINES_JS)+ self.assertIn("() => closeEngineMenu({ returnFocus: false })", ENGINES_JS)+++class EngineMenuHasArrowKeyNavigation(unittest.TestCase):+ def test_arrow_and_home_end_keys_are_handled(self):+ self.assertIn("ev.key !== 'ArrowDown' && ev.key !== 'ArrowUp'", ENGINES_JS)+ self.assertIn("ev.key === 'Home'", ENGINES_JS)+ self.assertIn("ev.key === 'End'", ENGINES_JS)++ def test_navigation_is_cyclic(self):+ self.assertIn("(cur + 1) % opts.length", ENGINES_JS)+ self.assertIn("(cur - 1 + opts.length) % opts.length", ENGINES_JS)++ def test_escape_still_closes(self):+ self.assertIn("if (ev.key === 'Escape') { closeEngineMenu(); return; }", ENGINES_JS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_estimate_honesty.py b/test_h3_estimate_honesty.pynew file mode 100644index 0000000..48cd630--- /dev/null+++ b/test_h3_estimate_honesty.py@@ -0,0 +1,166 @@+"""H3-23 / H3-24 / H3-25 / H3-40: the numbers H3 shows before and during a+render didn't agree with each other or with the mechanism they described.++H3-23 [P2]: no ETA during H3's load phase (staged weight loads — the text+encoder, then the transformer — can take minutes on a 48 GB Mac). The+progress loop hardcoded eta=0.0 until the first denoise step landed, and+0.0 is falsy in JS, so the Now card's own "elapsed / ~eta left" branch never+fired and only "X elapsed" showed.++H3-24 [P3]: one cell showed three different numbers at once — the chip and+the Shot setup summary round to the nearest WHOLE minute (the server's own+_fmt_eta / the client's h3FmtEtaMin), but the footer's h3EstimateLine()+rounded to the nearest HALF minute below 10 min, so a 6.8-min cell read+"~7" on the chip and "6.5" in the footer.++H3-25 [P3]: the Speed row said "Fast = 3 steps" (FORWARDS), but the+#steps mirror used to fall back to `tri.steps` (SIGMA POINTS, e.g. 4) —+different units, same render, two numbers on screen.++H3-40 [P2]: "Fast = 3 steps * Best = full steps" stated the mechanism, not+the trade-off a user is actually choosing between.+"""+from __future__ import annotations++import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-h3est-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++NODE = shutil.which("node")+ENGINES = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+INDEX = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+PANEL = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+++def _h3_run_block() -> str:+ i = PANEL.index('_load_est = H3_LOAD_SEC * _h3_speed_factor(chain_windows)')+ j = PANEL.index('rc = proc.wait()', i)+ return PANEL[i:j]+++class H3_23_LoadPhaseEta(unittest.TestCase):+ def test_load_eta_is_seeded_from_the_cell_not_hardcoded_zero(self):+ block = _h3_run_block()+ self.assertNotRegex(block, r"pct, eta = max\(3\.0, win_base\), 0\.0")+ self.assertIn("_load_eta_seed", block)+ self.assertIn("_load_eta_seed - elapsed", block)++ def test_seed_prefers_tristep_min_when_fast_is_on(self):+ block = _h3_run_block()+ self.assertRegex(+ block,+ r'tier\.get\("tristep_min"\) if tristep and tier\.get\("tristep_min"\) is not None')+ self.assertIn('else tier.get("eta_min")', block)++ def test_remaining_sec_no_longer_requires_a_completed_step(self):+ block = _h3_run_block()+ self.assertNotIn('"remaining_sec": eta if last_step else None', block)+ self.assertIn('"remaining_sec": eta,', block)++ def test_seed_computation_is_reachable_at_import(self):+ """The formula itself, exercised directly against the real cost+ model (not just grepped) — H3_LOAD_SEC times the same speed factor+ every other H3 estimate uses."""+ factor = P._h3_speed_factor(1)+ self.assertGreater(P.H3_LOAD_SEC * factor, 0)++[email protected](NODE, "node not on PATH")+class H3_24_OneFormatterEverywhere(unittest.TestCase):+ def _run(self, js: str):+ r = subprocess.run([NODE, "-e", js], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr)+ return r.stdout.strip()++ def test_h3_fmt_eta_min_rounds_to_a_whole_minute(self):+ from scripts.extract_panel_js import extract_function+ js = extract_function("h3FmtEtaMin", ENGINES) + """+console.log(JSON.stringify([h3FmtEtaMin(6.8), h3FmtEtaMin(6.2), h3FmtEtaMin(0.4)]));+"""+ out = self._run(js)+ vals = __import__("json").loads(out)+ for v in vals:+ self.assertNotIn(".", v, f"{v!r} is not a whole-minute string")++ def test_h3_estimate_line_now_calls_the_shared_formatter(self):+ """Regression pin: the removed CODE line was+ `Math.round(m * 2) / 2` for m < 10 (a bespoke half-minute round) —+ h3EstimateLine must now compute its number through h3FmtEtaMin,+ the same formatter the chip and the Shot setup summary use."""+ from scripts.extract_panel_js import extract_function+ fn_src = extract_function("h3EstimateLine", ENGINES)+ code_lines = [ln for ln in fn_src.splitlines() if not ln.strip().startswith("//")]+ self.assertFalse(any("Math.round(m * 2) / 2" in ln for ln in code_lines))+ self.assertIn("h3FmtEtaMin(m)", fn_src)++ def test_h3_estimate_line_matches_h3_fmt_eta_min_exactly(self):+ """End to end: run both functions on the same fractional-minute+ value and require byte-identical numbers (modulo the ~/batch+ decorations h3EstimateLine strips for its own "≈ N min" shape)."""+ from scripts.extract_panel_js import extract_function+ js = "\n".join(extract_function(n, ENGINES) for n in (+ "h3FmtEtaMin", "h3CurrentCell", "h3TriStepOn", "h3TriStepState",+ "h3SpeedPref", "_h3IsI2V", "_h3TriStepMin", "h3CellEtaMin",+ "h3FaceFixOn", "h3EstimateLine")) + """+var H3 = { tristep: { available: false } };+var document = {+ getElementById: (id) => (id === 'mode') ? { value: 't2v' }+ : (id === 'h3_upscale') ? { value: 'off' } : (id === 'h3_steps') ? { value: 'auto' } : null,+};+function h3CurrentCell() {+ return { quality_label: 'Draft', eta_min: 6.8, tristep_min: null, chain_windows: 1,+ per_forward_sec: 1, fixed_sec: 1 };+}+console.log(JSON.stringify([h3FmtEtaMin(6.8), h3EstimateLine()]));+"""+ r = self._run(js)+ import json as _json+ fmt, line = _json.loads(r)+ bare = fmt.replace('~', '').replace(' · batch', '')+ self.assertIn(bare, line)+++class H3_25_StepsMatchTheSpeedRow(unittest.TestCase):+ def test_apply_speed_no_longer_mirrors_sigma_points_as_forwards(self):+ """The old line: `if (s) s.value = tri.steps || 4;` — tri.steps is+ the ADAPTER's sigma-point count (the server's H3_TRISTEP_STEPS,+ 4), not the forwards count the Speed row's "Fast = 3 steps" text+ names. Regression-pinned by absence, then by the replacement's+ shape."""+ self.assertNotRegex(ENGINES, r"s\.value = tri\.steps \|\| 4;")+ self.assertIn("cell.tristep_forwards", ENGINES)++ def test_server_forwards_and_sigma_points_are_related_by_one(self):+ """The units the two client numbers must agree on: forwards =+ sigma points - 1, exactly the H3_TRISTEP_FORWARDS definition."""+ self.assertEqual(P.H3_TRISTEP_FORWARDS, P.H3_TRISTEP_STEPS - 1)++ def test_a_cell_carries_its_own_tristep_forwards(self):+ cell = next((c for c in P.H3_TIERS.values() if c.get("tristep_min") is not None), None)+ self.assertIsNotNone(cell, "no H3 tier offers TriStep — cannot pin the field")+ self.assertIn("tristep_forwards", cell)+ self.assertGreater(cell["tristep_forwards"], 0)+++class H3_40_TradeOffNotMechanism(unittest.TestCase):+ def test_speed_row_states_the_tradeoff(self):+ self.assertNotIn("Fast = 3 steps · Best = full steps", INDEX)+ self.assertIn("quicker, a touch softer", INDEX)+ self.assertIn("sharpest faces", INDEX)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_external_build_progress.py b/test_h3_external_build_progress.pynew file mode 100644index 0000000..1a58698--- /dev/null+++ b/test_h3_external_build_progress.py@@ -0,0 +1,114 @@+#!/usr/bin/env python3+"""H3-19: no real in-panel installer exists for H3's ~75 GB install/build+(unlike the small Fast/Turbo adapter installs, which DO run in-process) —+but the panel can now show that a Pinokio-side build IS running, instead+of a silent handoff.++Investigated "install via Pinokio's API": nothing in this codebase calls+into Pinokio's own orchestration layer (port 42000) programmatically, and+the one engine with a REAL in-panel installer (music, _music_install_env())+does not use any such API either — it spawns the actual install+subprocesses directly from the panel process. Doing the same for H3 means+re-implementing install_h3.js's clone/venv/~75 GB download/Q8 build in+Python, none of which could be validated end-to-end in this session+without real bandwidth and disk risk on a shared machine. Not attempted.++What WAS real and safe to ship: the worker already reads+scripts/pinokio/h3_build_q8.sh's lock file to HOLD the render queue while+that script runs (_external_build_hold, mlx_ltx_panel.py) — it just never+told the UI why, so a user who started the build from the Pinokio sidebar+had no way to know it was working without keeping that tab open.+h3_status() now surfaces it as h3.external_build ({active, what}), and+updateModelsCard() (settings.js) shows it as a precedence-topping inline+state: "Building <what> in Pinokio ... Generate resumes here+automatically when it finishes."++Verified live: wrote a real h3_build.lock file (the same shape+h3_build_q8.sh writes: pid + what + started) with this test process's own+pid so the liveness check passes; /status.h3.external_build reported+{"active": true, "what": "the compact Q8 engine"}; the inline models card+showed "Building the compact Q8 engine in Pinokio" with the "no need to+keep that tab open" copy. Removing the lock file made it report+{"active": false, "what": null} again.+"""+from __future__ import annotations++import json+import os+import sys+import tempfile+import time+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-h3-extbuild-boot-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8308")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++SETTINGS_JS = (ROOT / "webapp" / "js" / "settings.js").read_text(encoding="utf-8")+++class ExternalBuildIsSurfacedInStatus(unittest.TestCase):+ # STATE_DIR is resolved once at module import (whichever test file the+ # pytest session imports mlx_ltx_panel from first wins the env var) — so+ # every other test in this suite that needs a different one patches the+ # module attribute directly instead (see test_h3_build_hold.py). Same+ # pattern here, plus resetting the 3s /status memo each test.+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.state = Path(self.tmp.name)+ self.lock = self.state / "h3_build.lock"+ self.patch = mock.patch.object(P, "STATE_DIR", self.state)+ self.patch.start()+ self.addCleanup(self.patch.stop)+ self.addCleanup(self.tmp.cleanup)+ P._H3_STATUS_CACHE = (0.0, None)++ def test_inactive_by_default(self):+ self.assertFalse(self.lock.exists())+ st = P.h3_status()+ self.assertEqual(st["external_build"], {"active": False, "what": None})++ def test_active_when_a_live_lock_exists(self):+ self.lock.write_text(json.dumps({+ "pid": os.getpid(), "what": "the compact Q8 engine",+ "started": time.time(),+ }))+ st = P.h3_status()+ self.assertEqual(st["external_build"],+ {"active": True, "what": "the compact Q8 engine"})++ def test_a_dead_pid_is_not_reported_active(self):+ dead_pid = 999999+ try:+ os.kill(dead_pid, 0)+ self.skipTest(f"pid {dead_pid} unexpectedly alive on this machine")+ except (ProcessLookupError, PermissionError):+ pass+ self.lock.write_text(json.dumps({"pid": dead_pid, "what": "ghost", "started": time.time()}))+ st = P.h3_status()+ self.assertEqual(st["external_build"], {"active": False, "what": None})+++class InlineCardShowsTheBuildState(unittest.TestCase):+ def test_branch_exists_and_tops_precedence(self):+ self.assertIn("const extBuild = s.h3 && s.h3.external_build;", SETTINGS_JS)+ self.assertIn("if (extBuild && extBuild.active) {", SETTINGS_JS)+ # Must appear before the active-download branch so a build hold is+ # never masked by an unrelated model download.+ self.assertLess(SETTINGS_JS.index("if (extBuild && extBuild.active) {"),+ SETTINGS_JS.index("if (dl) {"))++ def test_copy_says_no_need_to_keep_the_tab_open(self):+ self.assertIn("No need to keep that tab open.", SETTINGS_JS)+ self.assertIn("Building ${extBuild.what", SETTINGS_JS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_facefix_and_batch_copy.py b/test_h3_facefix_and_batch_copy.pynew file mode 100644index 0000000..83f473b--- /dev/null+++ b/test_h3_facefix_and_batch_copy.py@@ -0,0 +1,54 @@+#!/usr/bin/env python3+"""H3-26 and H3-37: two small copy fixes that both named the wrong thing.++H3-26: Upscale & Face Fix's "after the draft" copy was unconditional, but+h3FaceFixAfterRow is shown whenever H3.upscale_modes allows ltx_x2 — not+only on the Draft tier (setH3Upscale in engines.js gates its visibility+on the allowed-modes list, with no quality check). A Standard or High+render offering the checkbox got copy naming the wrong tier, both in the+static label/title (index.html) and in the server-built export note+(_h3_export_notes, mlx_ltx_panel.py). Both now say "after this render" /+"about the same time again".++H3-37: h3FmtEtaMin() appended " · batch" to any chip estimated at 25++minutes, with no explanation anywhere — and "Batch" is also the name of+an unrelated real feature elsewhere in the app (queueing several+renders), so the suffix read as pointing at the wrong thing. Reworded to+say what it actually means: "· long, start and walk away".++Verified live: setH3FaceFixAfter(true) on a Standard/5s H3 render+produced the export note "after this render ... About the same time+again." (previously named "the draft").+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+INDEX_HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+ENGINES_JS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+PANEL_PY = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+++class FaceFixCopyIsTierAgnostic(unittest.TestCase):+ def test_html_label_and_title_say_this_render(self):+ self.assertIn("Also run <b>Upscale & Face Fix</b> after this render", INDEX_HTML)+ self.assertIn("about the same time again", INDEX_HTML)+ self.assertNotIn("after the draft", INDEX_HTML)++ def test_backend_export_note_says_this_render(self):+ self.assertIn('f"{FACE_FIX_NAME}: after this render, a second job re-renders it at "',+ PANEL_PY)+ self.assertIn('"About the same time again."', PANEL_PY)+ self.assertNotIn('"after the draft, a second job', PANEL_PY)+++class BatchSuffixExplainsItself(unittest.TestCase):+ def test_long_render_suffix_is_not_the_bare_word_batch(self):+ self.assertIn("long, start and walk away", ENGINES_JS)+ self.assertNotIn("' · batch'", ENGINES_JS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_fast_install_no_confirm.py b/test_h3_fast_install_no_confirm.pynew file mode 100644index 0000000..2af6124--- /dev/null+++ b/test_h3_fast_install_no_confirm.py@@ -0,0 +1,74 @@+#!/usr/bin/env python3+"""H3-27: the Fast install must not use a native confirm(), and must+mention Turbo when it's already installed and Fast isn't.++h3SpeedClick('fast') used `confirm('Install Fast (3 steps)?\\n\\n...')` — a+blocking browser dialog, not the panel's own UI (the same rule Stop's own+confirmation is held to). It also never mentioned Turbo, so a Mac with+Turbo already installed and Fast still missing was told nothing about the+quicker option sitting one click away on the exact same switch.++Fix: the panel's existing "toast + action link" confirm pattern (already+used for the engine-offer nudge) replaces confirm() — one informative+toast naming the adapter, source and license, an explicit "Install Fast"+link to proceed, nothing blocking. When h3TurboState().available is true,+the toast adds a one-line Turbo mention.++Verified live (booted the real "Fast missing, Turbo installed" scenario,+Playwright, dialog listener attached): clicking the Fast pill fired NO+native dialog, produced a toast containing "Turbo (already installed) is+a quicker option too", and clicking its "Install Fast" action link POSTed+to /h3/tristep/install and showed the real installing-toast.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+ENGINES_JS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class FastInstallHasNoNativeDialog(unittest.TestCase):+ def setUp(self):+ self.body = _function_body(ENGINES_JS, "async function h3SpeedClick(which) {")++ def test_no_confirm_call(self):+ # Check the executable statement form, not the explanatory comment+ # above it (which legitimately names confirm() as what used to run).+ self.assertNotIn("if (!confirm(", self.body,+ "h3SpeedClick still blocks the tab with a native confirm()")+ self.assertNotIn(")) return;\n try {\n const r = await fetch('/h3/tristep/install'",+ self.body)++ def test_uses_toast_with_action_link(self):+ self.assertIn("phosToast(", self.body)+ self.assertIn("phos-toast-action", self.body)+ self.assertIn("'Install Fast'", self.body)++ def test_mentions_turbo_when_available(self):+ self.assertIn("h3TurboState()", self.body)+ self.assertIn("turbo && turbo.available", self.body)+ self.assertIn("quicker option too", self.body)++ def test_the_actual_install_post_still_happens_on_confirm(self):+ self.assertIn("/h3/tristep/install", self.body)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_finish_and_params_need_h3.py b/test_h3_finish_and_params_need_h3.pynew file mode 100644index 0000000..f59706b--- /dev/null+++ b/test_h3_finish_and_params_need_h3.py@@ -0,0 +1,94 @@+#!/usr/bin/env python3+"""H3-21: Finish and Load Params must not offer/silently redo an H3 clip+on a Mac without H3.++Finish: `_syncH3FinishAffordance()` computed its target tier purely from+the client-side H3 tier registry (h3TierByKeyExact/h3FinishTierKey) — no+install check anywhere in that math — so a Mac without H3 at all still saw+"Finish at Standard 5s · ~6 min" on an H3 clip. Clicking called+h3FinishActive(), which DOES gate on setEngine('h3') actually landing on+h3, but only found out — and only told the user — after the click, via a+toast. The affordance now checks H3.available up front: unavailable, the+label reads "Finish · needs Hailuo H3" and the click opens the install+card instead of attempting a doomed render; available, behaviour and copy+are unchanged from before.++Load Params: restored geometry, prompt and every H3-specific field+(h3_quality, h3_orientation, ...) using the SIDECAR's engine string+unconditionally, while setEngine() — the actual surface swap — silently+falls back to LTX when H3 isn't installed (same gate Finish checks) and+the fallback was never read. An H3 clip's params landed silently in LTX+Image mode at H3's dimensions with H3's dialogue-tagged prompt, no+explanation. Now the function reads what setEngine() actually landed on;+when it disagrees with the sidecar's engine, a toast names the mismatch+before applying the (now conditional) H3-only setters.++Verified live (booted a 48 GB Mac with nothing installed, real+setEngine() gate): loadParams() against a synthetic H3 sidecar produced+one toast reading "This clip was made with Hailuo H3. ..." and left the+form on LTX/t2v, as it actually rendered. This file pins both code paths+statically.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class FinishSaysNeedsH3WhenUnavailable(unittest.TestCase):+ def setUp(self):+ self.body = _function_body(QUEUE_JS, "function _syncH3FinishAffordance(")++ def test_checks_h3_available(self):+ self.assertIn("const h3NotHere = !(H3 && H3.available);", self.body)++ def test_label_names_the_requirement(self):+ self.assertIn("'Finish · needs Hailuo H3'", self.body)++ def test_click_opens_install_card_instead_of_finishing(self):+ self.assertIn("btn.onclick = (ev) => { ev.preventDefault(); openH3InstallCard(); };",+ self.body)++ def test_normal_path_still_restores_the_real_handler(self):+ self.assertIn("btn.onclick = () => h3FinishActive();", self.body)+++class LoadParamsNamesTheEngineMismatch(unittest.TestCase):+ def setUp(self):+ self.body = _function_body(QUEUE_JS, "async function loadParams(recipe) {")++ def test_reads_what_setEngine_actually_landed_on(self):+ self.assertIn("_engLanded = setEngine(_eng, { persist: false }) || _eng;", self.body)++ def test_h3_only_setters_gate_on_the_landed_engine_not_the_sidecars(self):+ # The old code branched on `_eng === 'h3'` (the sidecar's claim); it+ # must now branch on where the surface actually landed, or the H3+ # setters run against an LTX form.+ self.assertIn("if (_engLanded === 'h3') {", self.body)+ self.assertNotIn("if (_eng === 'h3') {\n if (typeof setH3Upscale", self.body)++ def test_toasts_the_mismatch(self):+ self.assertIn("if (_eng === 'h3' && _engLanded !== 'h3') {", self.body)+ self.assertIn("This clip was made with Hailuo H3.", self.body)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_footer_model_credit.py b/test_h3_footer_model_credit.pynew file mode 100644index 0000000..9d4d949--- /dev/null+++ b/test_h3_footer_model_credit.py@@ -0,0 +1,76 @@+#!/usr/bin/env python3+"""H3-34: the footer model-credit chip must name H3 when H3 is what's+running, and never show a bare path fragment for it.++Two defects in updateModelCredit()/_modelCreditLabel() (boot.js):++ 1. With no clip selected (or one that predates the sidecar `model`+ field), the credit fell back to BOOT.model unconditionally — a+ server-rendered snapshot from page load that is ALWAYS the LTX pack.+ On H3, idle, the footer read "ltx-2.5-mlx-q4" while the form was set+ up to render entirely on H3.+ 2. An H3 clip's raw model path (.../mlx_models/hailuo-h3/...models/+ h3-dit-q8/...) went through the same "slice off the last two path+ segments" logic LTX paths use, producing a bare "h3-dit-q8/<file>"+ fragment with no indication it names an engine at all.++Fix: _modelCreditLabel() recognizes the hailuo-h3 tree and returns+"Hailuo H3 · compact (Q8)" / "Hailuo H3 · full (bf16)"; when nothing is+selected, updateModelCredit() falls back to the ACTIVE engine (reading+H3.dit_choice.kind) rather than always BOOT.model.++Verified live: idle on H3 -> "Hailuo H3 · compact (Q8)"; idle on LTX ->+unchanged "ltx-2.5-mlx-q4"; an H3-rendered clip selected while the form+is on LTX -> "Hailuo H3 · compact (Q8)" (follows the clip, not the+surface, as designed).+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+BOOT_JS = (ROOT / "webapp" / "js" / "boot.js").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class ModelCreditLabelRecognizesH3(unittest.TestCase):+ def test_label_function_detects_the_hailuo_h3_tree(self):+ body = _function_body(BOOT_JS, "function _modelCreditLabel(raw) {")+ self.assertIn("hailuo-h3", body)+ self.assertIn("Hailuo H3 · compact (Q8)", body)+ self.assertIn("Hailuo H3 · full (bf16)", body)+++class UpdateModelCreditFallsBackToTheActiveEngine(unittest.TestCase):+ def setUp(self):+ self.body = _function_body(BOOT_JS, "function updateModelCredit(path) {")++ def test_idle_h3_reads_dit_choice_not_boot_model(self):+ self.assertIn("document.body.dataset.engine === 'h3'", self.body)+ self.assertIn("H3.dit_choice", self.body)++ def test_still_falls_back_to_boot_model_for_ltx(self):+ self.assertIn("_modelCreditLabel(raw || BOOT.model)", self.body)++ def test_link_and_title_follow_which_engine_is_credited(self):+ self.assertIn("minimax-h3-mlx", self.body)+ self.assertIn("dgrauet/ltx-2-mlx", self.body)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_friendly_error_copy.py b/test_h3_friendly_error_copy.pynew file mode 100644index 0000000..7f7d632--- /dev/null+++ b/test_h3_friendly_error_copy.py@@ -0,0 +1,97 @@+#!/usr/bin/env python3+"""H3-22: H3 failure messages must not borrow LTX-only advice or leak+absolute local paths.++Three defects in friendlyJobError() (queue.js), shared by the Now card and+every storyboard shot:++ 1. A SIGKILL (jetsam OOM) hint said "switch Quality to Quick" on every+ engine — H3 has no Quick tier at all.+ 2. "H3 render exited with code N" (the non-signal exit path) and "H3+ render timed out — no output for 20 minutes" matched none of the+ specific branches (no signal name, no "helper exited from"), so both+ fell to the generic `{friendly: 'Job failed.', hint: raw}` — the+ exit-code one WITH its raw `metrics_path`, an absolute path under the+ user's home directory (often their real name on macOS), shown+ verbatim on screen.+ 3. storyboard.js's caller never passed an engine at all, so a failed H3+ shot on the Storyboard surface got the LTX-worded SIGKILL hint even+ when the Now-card version (fixed here too) would have known better.++Fix: friendlyJobError(raw, engine) branches SIGKILL advice on engine+('h3' -> "try Fast, a shorter length, or Draft"; else unchanged Quick+Quality advice); a new branch catches both H3-only messages with a+_redactLocalPaths() pass over the hint; the generic fallback also redacts.+Both call sites (queue.js's Now card, storyboard.js's per-shot failure)+now pass the job's engine.++Verified live: friendlyJobError() run against real backend message shapes+(booted panel) — H3 SIGKILL -> "...try Fast, a shorter length, or Draft+(all use less memory)." with no Quick-quality mention; LTX SIGKILL ->+unchanged "...switch Quality to Quick..."; H3 exit-code message with a+real /Users/... metrics path -> hint contains no /Users/ path; H3 timeout+-> a real friendly title instead of "Job failed."+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class FriendlyErrorIsEngineAware(unittest.TestCase):+ def setUp(self):+ self.body = _function_body(QUEUE_JS, "function friendlyJobError(raw, engine) {")++ def test_sigkill_branches_on_h3(self):+ self.assertIn("const onH3 = engine === 'h3';", self.body)+ self.assertIn("try Fast, a shorter length, or Draft", self.body)+ self.assertIn("switch Quality to Quick", self.body)++ def test_h3_exit_and_timeout_get_their_own_branch(self):+ self.assertIn("/h3 render (timed out|exited with code)/i.test(raw)", self.body)++ def test_redaction_helper_exists_and_is_used(self):+ self.assertIn("function _redactLocalPaths(", QUEUE_JS)+ self.assertIn("_redactLocalPaths(raw)", self.body)++ def test_generic_fallback_also_redacts(self):+ self.assertIn("hint: _redactLocalPaths(raw) || raw", self.body)++ def test_redaction_strips_users_paths_and_metrics_clause(self):+ helper = _function_body(QUEUE_JS, "function _redactLocalPaths(")+ self.assertIn("Users", helper)+ self.assertIn("metrics at", helper)+++class BothCallersPassTheEngine(unittest.TestCase):+ def test_now_card_passes_engine(self):+ self.assertIn(+ "friendlyJobError(last.error || 'unknown error',\n"+ " last.params && last.params.engine);",+ QUEUE_JS)++ def test_storyboard_passes_engine(self):+ self.assertIn("friendlyJobError(s.error || '', s.engine);", STORYBOARD_JS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_inline_banner_dismissible.py b/test_h3_inline_banner_dismissible.pynew file mode 100644index 0000000..1ca6b4b--- /dev/null+++ b/test_h3_inline_banner_dismissible.py@@ -0,0 +1,77 @@+#!/usr/bin/env python3+"""H3-20: the 36-59 GB "H3 can run here" inline banner must be dismissible+and short.++updateModelsCard()'s `h3s.needs_q8_dit` branch never added the+'dismissible' class (the only thing that makes panel.css show the ×:+`.models-inline.dismissible .models-inline-dismiss { display: inline-block+}`) and never checked the `dismissed` flag the other branches all respect+— so this banner was permanent on every 36-59 GB Mac, with no way to hide+it, once per session or ever. It also repeated its own heading: the title+said "Hailuo H3 runs on this Mac..." and the body was h3s.ram_note, the+FULL server sentence built for the install-card modal, which starts+"Hailuo H3 runs on this Mac — on its reduced-RAM lane...". Two near-+identical openings wrapped the card to ~270px at 1440x900, pushing+Generate under the Now card.++Fix: respect `dismissed` and add the 'dismissible' class like every other+branch; one short title ("Hailuo H3 can run on this Mac") and a one-line+sub with no repetition — the full explanation still lives in the install+card one click away, which reads h3s.ram_note itself.++Verified live: booted a 48 GB / weights-present / no-Q8-build panel.+Before the fix the card was 275px with a duplicated opening sentence and+an invisible dismiss button; after, it is 107px, the × is visible, and+clicking dismissModelsCard() hides the card. The empty-install (48 GB,+nothing downloaded) sub-case was checked too: correct copy, dismissible.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SETTINGS_JS = (ROOT / "webapp" / "js" / "settings.js").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class InlineH3BannerIsDismissible(unittest.TestCase):+ def setUp(self):+ self.body = _function_body(SETTINGS_JS, "if (h3s.needs_q8_dit) {")++ def test_checks_dismissed_first(self):+ self.assertIn("if (dismissed) { card.style.display = 'none'; return; }",+ self.body)++ def test_adds_the_dismissible_class(self):+ self.assertIn("card.classList.add('dismissible')", self.body)++ def test_title_no_longer_repeats_into_the_body(self):+ self.assertIn("'Hailuo H3 can run on this Mac'", self.body)+ # The old body was the raw server ram_note sentence, which itself+ # opens with "Hailuo H3 runs on this Mac" — the exact duplication.+ # Check the executable statement, not the explanatory comment above+ # it (which legitimately names ram_note as what the install card+ # still reads).+ self.assertNotIn("sub.textContent = h3s.ram_note", self.body)++ def test_button_offers_setup_not_a_long_sentence(self):+ self.assertIn("Set up H3", self.body)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_lora_count_scoping.py b/test_h3_lora_count_scoping.pynew file mode 100644index 0000000..279526c--- /dev/null+++ b/test_h3_lora_count_scoping.py@@ -0,0 +1,54 @@+#!/usr/bin/env python3+"""H3-09: the LoRA picker's header must count THIS engine's library, not+both libraries combined, and must point at the right folder.++`renderLorasList()` computed its header summary from `allRows.length` —+every LoRA in the shared fetch, LTX and H3 together — so an install with 4+H3-compatible adapters and 16 LTX ones read "20 installed" under the H3+picker. The mode-filtered `rows` array (built earlier in the same function,+purely to decide what to SHOW) already had the right count; the summary+just never used it. Same story for the Rescan button's tooltip, which named+`mlx_models/loras/` — the LTX folder — unconditionally, including while H3's+picker (a different directory, `_lorasDirs.h3`) was open.++Verified live: booted panel with 5 H3 LoRAs + 16 LTX LoRAs installed.+Switching to H3 read "5 H3 LoRAs · 0 active" and the Rescan tooltip named+the H3 loras dir; switching to LTX read "16 installed · 0 active" and the+Rescan tooltip named mlx_models/loras. This file pins the source.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+LORAS_JS = (ROOT / "webapp" / "js" / "loras.js").read_text(encoding="utf-8")+INDEX_HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+++class LoraCountsAreScopedToTheActiveEngine(unittest.TestCase):+ def test_summary_no_longer_reads_allRows_length(self):+ # The exact defect: total counted from the UNFILTERED library.+ self.assertNotIn("const total = allRows.length;", LORAS_JS)++ def test_summary_uses_mode_filtered_counts(self):+ self.assertIn("const modeFilteredCount = rows.length;", LORAS_JS)+ self.assertIn("modeFilteredCount", LORAS_JS)+ self.assertIn("modeFilteredActive", LORAS_JS)++ def test_h3_gets_its_own_unit_label(self):+ self.assertIn("(modeTag === 'video:h3') ? 'H3 LoRAs' : 'installed'", LORAS_JS)++ def test_hidden_from_other_modes_names_the_engine_on_h3(self):+ self.assertIn("won't load on H3", LORAS_JS)++ def test_rescan_tooltip_is_dynamic_and_engine_scoped(self):+ self.assertIn("lorasRescanBtn", LORAS_JS)+ self.assertIn("_lorasDirs.h3", LORAS_JS.split("rescanBtn.title")[0][-400:])++ def test_rescan_button_has_an_id_for_js_to_target(self):+ self.assertIn('id="lorasRescanBtn"', INDEX_HTML)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_lora_import_toasts.py b/test_h3_lora_import_toasts.pynew file mode 100644index 0000000..e61d4e9--- /dev/null+++ b/test_h3_lora_import_toasts.py@@ -0,0 +1,78 @@+#!/usr/bin/env python3+"""H3-10: LoRA import results must use the panel's own toasts, not native+alert(), and an LTX-style file must get plain-language guidance instead of+an engineering lecture. Also fixes the stale docs claim that kohya is+refused.++`importH3Lora()` used alert() for all three outcomes: the file-type guard,+success, and failure — each one blocks the whole tab and reads as a browser+error rather than part of the app. Worse, a diffusers/PEFT-layout file (the+shape an LTX export comes in, and the file people most often try here by+mistake) surfaced the backend's engineering explanation verbatim — "the+scale the adapter was trained with (PEFT's alpha/rank) is simply not in the+file" — which answers a question nobody but the implementer asked. Meanwhile+docs/H3_ENGINE.md said kohya files are "refused, by design", when+`_h3_lora_prepare_file` (mlx_ltx_panel.py) has converted them automatically+since 2026-09-06.++Verified live against the real backend (booted panel, real /h3/loras/import+endpoint): a synthetic diffusers-layout file (to_q/to_k/to_v keys) produced+one danger-styled toast reading "This looks like an LTX LoRA, not an H3+one..."; a real kohya-layout test fixture (lora_down/lora_up + .alpha)+imported successfully with a success-styled toast reading "Imported+kohya_import_test.safetensors (1 module pair)." — no alert() fired in+either case.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+LORAS_JS = (ROOT / "webapp" / "js" / "loras.js").read_text(encoding="utf-8")+H3_DOCS = (ROOT / "docs" / "H3_ENGINE.md").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class ImportUsesToastsNotAlerts(unittest.TestCase):+ def test_import_function_calls_no_alert(self):+ body = _function_body(LORAS_JS, "async function importH3Lora(")+ self.assertNotIn("alert(", body,+ "importH3Lora still blocks the tab with a native alert()")+ self.assertIn("phosToast(", body)++ def test_ltx_lora_detector_exists_and_is_used(self):+ self.assertIn("function _h3ImportIsLtxLora(", LORAS_JS)+ self.assertIn("diffusers layout", LORAS_JS)+ body = _function_body(LORAS_JS, "async function importH3Lora(")+ self.assertIn("_h3ImportIsLtxLora(msg)", body)+ self.assertIn("looks like an LTX LoRA", body)+++class DocsMatchTheRealBehaviour(unittest.TestCase):+ def test_kohya_is_documented_as_converted_not_refused(self):+ self.assertNotIn("refused, by design** |\n| kohya", H3_DOCS)+ self.assertIn("kohya / sd-scripts", H3_DOCS)+ self.assertIn("converted in place", H3_DOCS)++ def test_diffusers_still_documented_as_refused(self):+ self.assertIn("diffusers / PEFT", H3_DOCS)+ self.assertIn("refused, by design", H3_DOCS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_lora_import_ui.py b/test_h3_lora_import_ui.pyindex cc2044a..9607a47 100644--- a/test_h3_lora_import_ui.py+++ b/test_h3_lora_import_ui.py@@ -67,7 +67,18 @@ installShim();el('h3LoraImportBtn', {{textContent: 'Import H3 LoRA',innerHTML: '<svg></svg>Import H3 LoRA'}});el('h3LoraImportFile');+el('phosToast');globalThis._alerts = [];+globalThis.alert = (m) => globalThis._alerts.push(String(m));+// H3-10: importH3Lora() moved from alert() to the panel's own phosToast() —+// stub it the same shape the real one has (message + opts), local to this+// test file rather than the shared shim, since this is the one caller that+// needs it right now.+globalThis._toasts = [];+globalThis.phosToast = (message, opts) => {{+ globalThis._toasts.push({{message: String(message), opts: opts || {{}}}});+ return null;+}};const _userFetch = {fetch_js};globalThis._refreshed = 0;globalThis.fetch = async (url, init) => {{@@ -82,6 +93,7 @@ const btn = document.getElementById('h3LoraImportBtn');await importH3Lora({file_js});console.log(JSON.stringify({{alerts: globalThis._alerts,+ toasts: globalThis._toasts,refreshed: globalThis._refreshed,fetched: globalThis._fetched || null,btnDisabled: btn.disabled,@@ -99,11 +111,17 @@ def ok_fetch(payload: dict) -> str:class TestImportH3LoraClient(unittest.TestCase):+ # H3-10: importH3Lora() moved every outcome from alert() to the panel's+ # own phosToast() (a native dialog blocks the tab and reads as a browser+ # error, not part of the app). Every test below now reads out["toasts"]+ # and asserts out["alerts"] stayed empty — the regression this suite+ # exists to catch is the alert() coming back, not just the message text.def test_a_non_safetensors_file_never_reaches_the_network(self):out = drive(ok_fetch({"ok": True}), "{name: 'adapter.zip', size: 10}")self.assertIsNone(out["fetched"])- self.assertEqual(len(out["alerts"]), 1)- self.assertIn(".safetensors", out["alerts"][0])+ self.assertEqual(out["alerts"], [])+ self.assertEqual(len(out["toasts"]), 1)+ self.assertIn(".safetensors", out["toasts"][0]["message"])def test_a_successful_import_posts_to_the_documented_route(self):out = drive(@@ -113,15 +131,17 @@ class TestImportH3LoraClient(unittest.TestCase):self.assertEqual(out["fetched"], {"url": "/h3/loras/import","method": "POST"})self.assertEqual(out["refreshed"], 1)- self.assertIn("208 module pairs", out["alerts"][0])+ self.assertEqual(out["alerts"], [])+ self.assertIn("208 module pairs", out["toasts"][0]["message"])+ self.assertEqual(out["toasts"][0]["opts"].get("kind"), "success")def test_one_pair_is_not_reported_as_1_module_pairs(self):out = drive(ok_fetch({"ok": True, "filename": "a.safetensors", "pairs": 1,"converted": False, "recommended_strength": 1.0}),"{name: 'a.safetensors', size: 999}")- self.assertIn("1 module pair)", out["alerts"][0])- self.assertNotIn("1 module pairs", out["alerts"][0])+ self.assertIn("1 module pair)", out["toasts"][0]["message"])+ self.assertNotIn("1 module pairs", out["toasts"][0]["message"])def test_a_non_unit_scale_is_told_to_the_user_not_just_the_sidecar(self):"""The H3 loader applies no alpha, so the strength control is where the@@ -132,22 +152,24 @@ class TestImportH3LoraClient(unittest.TestCase):ok_fetch({"ok": True, "filename": "a.safetensors", "pairs": 208,"converted": True, "recommended_strength": 0.0625}),"{name: 'a.safetensors', size: 999}")- self.assertIn("0.0625", out["alerts"][0])- self.assertIn("Key namespace converted safely", out["alerts"][0])+ self.assertIn("0.0625", out["toasts"][0]["message"])+ self.assertIn("Key namespace converted safely", out["toasts"][0]["message"])def test_a_unit_scale_does_not_clutter_the_message(self):out = drive(ok_fetch({"ok": True, "filename": "a.safetensors", "pairs": 2,"converted": False, "recommended_strength": 1.0}),"{name: 'a.safetensors', size: 999}")- self.assertNotIn("Recommended strength", out["alerts"][0])+ self.assertNotIn("Recommended strength", out["toasts"][0]["message"])def test_a_server_refusal_is_shown_verbatim_and_the_button_recovers(self):fetch_js = ("async () => ({ok: false, status: 400, json: async () => ""({ok: false, error: 'my-adapter.safetensors has unmatched ""H3 LoRA tensors.'})})")out = drive(fetch_js, "{name: 'my-adapter.safetensors', size: 999}")- self.assertIn("my-adapter.safetensors has unmatched", out["alerts"][0])+ self.assertEqual(out["alerts"], [])+ self.assertIn("my-adapter.safetensors has unmatched", out["toasts"][0]["message"])+ self.assertEqual(out["toasts"][0]["opts"].get("kind"), "danger")self.assertEqual(out["refreshed"], 0)self.assertFalse(out["btnDisabled"])self.assertIn("Import H3 LoRA", out["btnHTML"])@@ -155,7 +177,8 @@ class TestImportH3LoraClient(unittest.TestCase):def test_a_thrown_network_error_still_restores_the_button(self):out = drive("async () => { throw new Error('offline'); }","{name: 'a.safetensors', size: 999}")- self.assertIn("offline", out["alerts"][0])+ self.assertEqual(out["alerts"], [])+ self.assertIn("offline", out["toasts"][0]["message"])self.assertFalse(out["btnDisabled"])self.assertIn("Import H3 LoRA", out["btnHTML"])diff --git a/test_h3_lora_row_ui_fixes.py b/test_h3_lora_row_ui_fixes.pynew file mode 100644index 0000000..f72c41f--- /dev/null+++ b/test_h3_lora_row_ui_fixes.py@@ -0,0 +1,57 @@+#!/usr/bin/env python3+"""H3-33: the "Write a guide" button wraps to three lines, and an H3 LoRA+whose OWN display name mentions LTX reads as an LTX LoRA.++1. `.lora-guide-actions` is a flex row with no `flex-shrink: 0` on its+ button — flex's default `min-width: auto` let the button shrink below+ its own text width whenever the sibling hint span wanted more room,+ wrapping "Write a guide" onto three lines. Pinned the button to its+ natural single-line size; the descriptive span (already the flexible+ one) gives ground instead.++2. A real H3 LoRA can carry "LTX 2.3" in its own display name — the+ string comes from wherever it was downloaded (e.g. a CivitAI listing+ title written before the file was adapted for H3), and the panel has+ no business silently rewriting a user's LoRA name. Added a small,+ honest "H3" lane badge instead, shown only where the name could+ actually mislead: an H3-lane row whose name mentions LTX.++Verified live: booted panel with a real installed LoRA named "H3 - LTX+2.3 - I2V T2V Video Reasoning lora VBVR" (lane h3) — its row now carries+an "H3" badge with an explanatory title; the guide button's computed+style is flex-shrink:0, white-space:nowrap.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+LORAS_JS = (ROOT / "webapp" / "js" / "loras.js").read_text(encoding="utf-8")+PANEL_CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++class GuideButtonNeverWraps(unittest.TestCase):+ def test_css_pins_the_button_to_its_own_width(self):+ self.assertIn(".lora-guide-actions .ghost-btn { flex-shrink: 0; white-space: nowrap; }",+ PANEL_CSS)+++class H3LoraNamedLikeLtxGetsALaneBadge(unittest.TestCase):+ def test_badge_condition_checks_lane_and_name(self):+ self.assertIn("r.lane === 'h3' && /\\bltx\\b/i.test(r.name || '')", LORAS_JS)++ def test_badge_text_and_explanation(self):+ self.assertIn('>H3</span>', LORAS_JS)+ self.assertIn("its own display name mentions LTX", LORAS_JS)++ def test_does_not_rewrite_the_stored_name(self):+ # The fix must not touch r.name at all — only add a badge.+ body_start = LORAS_JS.index("if (r.lane === 'h3' && /\\bltx\\b/i.test(r.name || '')) {")+ body_end = LORAS_JS.index("}", body_start) + 1+ snippet = LORAS_JS[body_start:body_end]+ self.assertNotIn("r.name =", snippet)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_lora_strength_total.py b/test_h3_lora_strength_total.pynew file mode 100644index 0000000..7a25e79--- /dev/null+++ b/test_h3_lora_strength_total.py@@ -0,0 +1,85 @@+#!/usr/bin/env python3+"""H3-08: stacked H3 LoRAs need a combined-strength warning, and the closed+Shot-setup summary needs to say a LoRA is even in the recipe.++The "keep total near 1.5" advice existed only inside renderH3LoraSlot()'s+single-adapter conflict row, which is hidden the moment the installed+runner can stack (today's default, up to 4) — so three LoRAs at 1.0 each,+a real total of 3.0, warned about nothing+(shots_h3/h64_lora_three_active.png). Separately, activating a LoRA never+touched the closed "Shot setup" summary, so a user who folded that section+had no way to see a LoRA was even part of the render.++Fixes:+ - renderLorasList() sums abs(strength) across the MODE-FILTERED active+ rows whenever 2+ are active, colours amber above 1.5 / red above 2.5,+ into #lorasStrengthTotal (new element, hidden by default).+ - addLoraToActive()/removeLoraFromActive() now call+ updateCustomizeSummary() so the count reaches the closed section on+ every activation, not only a full form re-render.+ - updateShotSetupSummary() (characters.js) appends "N LoRA(s)" on H3,+ using the same lane lookup _serializeLoras() trusts+ (_knownUserLoras[path].lane), not an unreliable property on the+ active-entry itself.++Verified live: booted panel, activated 3 real H3 LoRAs at strength 1.0+each via the actual toggleLora() click path (no direct summary calls) —+#lorasStrengthTotal read "Combined strength: 3.00 ... keep the total near+1.5 for a clean result." and #shotSetupSummary read "... 3 LoRAs".+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+LORAS_JS = (ROOT / "webapp" / "js" / "loras.js").read_text(encoding="utf-8")+CHARACTERS_JS = (ROOT / "webapp" / "js" / "characters.js").read_text(encoding="utf-8")+INDEX_HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class StrengthTotalWarning(unittest.TestCase):+ def test_total_element_exists_in_markup(self):+ self.assertIn('id="lorasStrengthTotal"', INDEX_HTML)++ def test_render_computes_and_thresholds_the_total(self):+ self.assertIn("modeFilteredActiveRows.reduce(", LORAS_JS)+ self.assertIn("total > 2.5 ? 'high' : total > 1.5 ? 'mid' : 'ok'", LORAS_JS)+ self.assertIn("keep the total near 1.5", LORAS_JS)++ def test_only_shown_with_two_or_more_active(self):+ self.assertIn("if (modeFilteredActive >= 2)", LORAS_JS)+++class ActivationReachesTheClosedSummary(unittest.TestCase):+ def test_add_calls_update_customize_summary(self):+ body = _function_body(LORAS_JS, "function addLoraToActive(")+ self.assertIn("updateCustomizeSummary()", body)++ def test_remove_calls_update_customize_summary(self):+ body = _function_body(LORAS_JS, "function removeLoraFromActive(")+ self.assertIn("updateCustomizeSummary()", body)++ def test_shot_setup_summary_names_the_lora_count_on_h3(self):+ body = _function_body(CHARACTERS_JS, "function updateShotSetupSummary(")+ self.assertIn("laneOf(a.path) === 'h3'", body)+ self.assertIn("' LoRAs'", body)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_menu_taglines_and_dense10s_docs.py b/test_h3_menu_taglines_and_dense10s_docs.pynew file mode 100644index 0000000..6dbd29c--- /dev/null+++ b/test_h3_menu_taglines_and_dense10s_docs.py@@ -0,0 +1,52 @@+#!/usr/bin/env python3+"""H3-16 and H3-15 (docs half).++H3-16: the engine-menu taglines didn't help anyone choose. LTX's "every+mode, LoRAs, characters" implied LoRAs (and, next to H3's tagline,+audio) were LTX-exclusive — neither is true: H3 has its own LoRA+library, and LTX 2.3/2.5 already generate audio jointly. Both taglines+now name the capability the other engine might make a user think they'd+lose.++H3-15 (docs half): docs/H3_ENGINE.md said `LTX_H3_DENSE_10S` (unset)+"re-adds" the dense 10 s tier — false. The tier ships `"offered": True"+unconditionally in H3_LENGTHS (mlx_ltx_panel.py) and the env var is not+read anywhere in the codebase. Docs corrected to say so.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+PANEL_PY = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+H3_DOCS = (ROOT / "docs" / "H3_ENGINE.md").read_text(encoding="utf-8")+++class EngineMenuTaglinesDontOverclaimExclusivity(unittest.TestCase):+ def test_ltx_tagline_names_h3s_lora_support_and_own_audio(self):+ self.assertIn('"tagline": "every mode · LoRAs, characters, its own joint audio",',+ PANEL_PY)++ def test_h3_tagline_names_its_own_loras(self):+ self.assertIn(+ '"tagline": "joint video + dialogue + sound, its own LoRAs. Text and Image only.",',+ PANEL_PY)+++class DenseTenSecondDocsMatchReality(unittest.TestCase):+ def test_env_var_documented_as_dead(self):+ self.assertIn("dead — not read anywhere in the code (H3-15)", H3_DOCS)++ def test_no_remaining_false_reads_restores_claim(self):+ self.assertNotIn("`LTX_H3_DENSE_10S=1` restores the old dense 10 s tier", H3_DOCS)+ self.assertIn("ships visible by default, always", H3_DOCS)++ def test_source_confirms_offered_is_unconditional(self):+ self.assertIn('"dense": True,\n "offered": True,', PANEL_PY)+ # And confirm no code path actually branches on the env var.+ self.assertNotIn('os.environ.get("LTX_H3_DENSE_10S"', PANEL_PY)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_now_card_idle_collapse.py b/test_h3_now_card_idle_collapse.pynew file mode 100644index 0000000..96cc65a--- /dev/null+++ b/test_h3_now_card_idle_collapse.py@@ -0,0 +1,53 @@+#!/usr/bin/env python3+"""H3-32: reclaim vertical space by collapsing the idle Now card's+decoration, not its information.++The review measured Shot setup's visible height at 153-178px across+1280-1440px windows, with the pinned footer plus the Now card eating+about 45% of the column, and suggested two independent fixes: "collapse+the idle Now card, or move Speed next to the ETA in the footer." The+second was already true (h3EstimateLine() has shown "<Quality> · <Speed>+<approx> <eta>" in #derivedFooter since H3-04's fix) — this closes the+first.++An idle Now card showed a 0%-filled progress bar and full padding for+nothing there is to progress: pure decoration. Collapsed that+specifically (`.now-card.idle`): tighter padding, the empty bar hidden,+tighter meta spacing. "Idle" and the meta text ("No jobs queued...")+stay exactly as visible as before — nothing informative is hidden,+which is the distinction the 2026-05-12 "remove the collapse button"+ruling drew (that button hid ACTIVE job progress and the queue; the+idle state has neither to hide).++Verified live: the idle Now card's measured height dropped from 82px to+57px (a ~30% reduction) with the progress bar's computed display: none+and both text lines still present and readable.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+PANEL_CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++class IdleNowCardIsCompact(unittest.TestCase):+ def test_idle_padding_is_tightened(self):+ self.assertIn(".now-card.idle { padding: 8px 14px; }", PANEL_CSS)++ def test_idle_progress_bar_is_hidden(self):+ self.assertIn(".now-card.idle .progress-bar { display: none; }", PANEL_CSS)++ def test_idle_meta_spacing_is_tightened(self):+ self.assertIn(".now-card.idle .meta { margin-top: 2px; }", PANEL_CSS)++ def test_non_idle_states_are_untouched(self):+ # Only the .idle variant collapses — a running/failed/stopped card+ # must keep its full progress bar and padding.+ self.assertIn(".now-card:not(.idle):not(.failed)", PANEL_CSS)+ self.assertNotIn(".now-card.failed .progress-bar { display: none; }", PANEL_CSS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_progress_time_left.py b/test_h3_progress_time_left.pyindex a8035c1..dd48419 100644--- a/test_h3_progress_time_left.py+++ b/test_h3_progress_time_left.py@@ -25,12 +25,23 @@ QUEUE = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")class H3ProgressSaysTimeLeft(unittest.TestCase):def _h3_progress_block(self) -> str:- i = PANEL.index('"window_total": tot_windows')- return PANEL[i - 2500:i]+ # Anchored on a stable start marker rather than a fixed lookback+ # offset from the end — a fixed offset silently truncates the+ # window's START as unrelated code grows between the two (it did,+ # for H3-04's pace-warning addition).+ i = PANEL.index('win_span = 87.0 / float(tot_windows)')+ j = PANEL.index('"window_total": tot_windows', i)+ return PANEL[i:j]def test_h3_progress_carries_remaining_sec(self):+ # H3-23: remaining_sec used to be None until the first denoise step+ # landed (eta if last_step else None) — the load phase (staged+ # weight loads, which can take minutes on a 48 GB Mac) showed no ETA+ # at all. It is now populated unconditionally: eta is seeded from+ # the cell's own estimate during load, then replaced by real+ # per-step extrapolation once denoising starts.self.assertRegex(self._h3_progress_block(),- r'"remaining_sec":\s*eta if last_step else None')+ r'"remaining_sec":\s*eta,')def test_later_windows_pay_their_loads(self):block = self._h3_progress_block()diff --git a/test_h3_prompt_helper.py b/test_h3_prompt_helper.pynew file mode 100644index 0000000..dd6a894--- /dev/null+++ b/test_h3_prompt_helper.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""H3-07: the Video tab needs help with H3's dialogue-tag prompt format.++Before this, index.html:847 showed LTX's audio-cue placeholder on H3 too,+and there was no control anywhere in the Video tab that named the format+docs/H3_ENGINE.md's "Dialogue on H3" describes: spoken words go ONLY+inside `<d>[Language] …</d>`, at most ~8 words per 5 s window, and the+sentence must stop the mouth in the same breath. A line written as prose+quotes (`She says: "..."`) leaves H3's voice switched off with no error —+the exact failure this control exists to prevent.++Adds, gated `data-h3-only` (webapp/index.html):+ - Structure: inserts the three-field skeleton (wraps existing text as+ the first field rather than discarding it).+ - + Line: inserts one dialogue line — the tag, a speaker id, and the+ mouth-stop clause — with the placeholder words selected so typing+ the line is one keystroke away. A language <select> tags it.+ - A live word-budget counter reading H3.speech_words_per_sec — the SAME+ number sent from storyboard.SPEECH_WORDS_PER_SEC server-side+ (mlx_ltx_panel.py), so the two validators can't disagree.+ - A quote-outside-tag warning: any `"`/curly quote whose position falls+ outside every `<d>…</d>` span.+ - An H3-specific placeholder naming the format, shown only on H3.++Verified live (booted panel, Playwright): switching to H3 unhid the+toolbar and swapped the placeholder; Structure wrapped typed text into+the three-field skeleton; + Line inserted a tagged line;+h3SyncPromptHelper() read "10/7 dialogue words" (over-budget, styled) for+a 10-word line at Draft/3s, and correctly warned only on the untagged+prose-quote case, not the properly-tagged one. Switching back to LTX+hid the toolbar and restored the original placeholder.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+INDEX_HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+ENGINES_JS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+PANEL_CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+PANEL_PY = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class MarkupAddsTheHelperGatedToH3(unittest.TestCase):+ def test_toolbar_exists_and_is_h3_only(self):+ self.assertIn('id="h3PromptHelper" data-h3-only hidden', INDEX_HTML)++ def test_structure_and_add_line_buttons_exist(self):+ self.assertIn('onclick="h3InsertPromptStructure()"', INDEX_HTML)+ self.assertIn('onclick="h3InsertDialogueLine()"', INDEX_HTML)++ def test_language_picker_and_indicators_exist(self):+ self.assertIn('id="h3DialogueLang"', INDEX_HTML)+ self.assertIn('id="h3DialogueWordCount"', INDEX_HTML)+ self.assertIn('id="h3QuoteWarning"', INDEX_HTML)++ def test_css_defines_the_toolbar_layout(self):+ self.assertIn(".h3-prompt-helper {", PANEL_CSS)+ self.assertIn(".h3-prompt-helper-words.over-budget", PANEL_CSS)+++class VisibilityAndPlaceholderSwapOnEngineChange(unittest.TestCase):+ def setUp(self):+ self.body = _function_body(QUEUE_JS, "function _syncEnginePromptTools() {")++ def test_helper_visibility_keyed_off_engine(self):+ self.assertIn("helper.hidden = (eng !== 'h3');", self.body)++ def test_placeholder_names_the_dialogue_tag_on_h3(self):+ self.assertIn("<d>[English] I thought it was ashwagandha!</d>", self.body)++ def test_ltx_placeholder_is_unchanged_text(self):+ self.assertIn("Audio is generated jointly with video", self.body)+++class StructureAndLineInsertion(unittest.TestCase):+ def test_structure_wraps_existing_text_not_discards_it(self):+ body = _function_body(ENGINES_JS, "function h3InsertPromptStructure() {")+ self.assertIn("cur.trim()", body)+ self.assertIn("overall_soundscape:", body)+ self.assertIn("non_diegetic_music:", body)++ def test_line_insertion_includes_tag_speaker_and_mouth_stop(self):+ body = _function_body(ENGINES_JS, "function h3InsertDialogueLine() {")+ self.assertIn("(S1) says: ", body)+ self.assertIn("<d>[${lang}]", body)+ self.assertIn("mouth settles closed", body)++ def test_functions_are_published_for_inline_onclick(self):+ self.assertIn("h3InsertPromptStructure, h3InsertDialogueLine, h3SyncPromptHelper,",+ ENGINES_JS)+++class WordBudgetAndQuoteWarning(unittest.TestCase):+ def setUp(self):+ self.body = _function_body(ENGINES_JS, "function h3SyncPromptHelper() {")++ def test_budget_reads_the_server_speech_rate(self):+ self.assertIn("(H3 && H3.speech_words_per_sec) || 2.4", self.body)++ def test_counts_words_inside_every_dialogue_tag(self):+ self.assertIn("tagRe", self.body)+ self.assertIn("words +=", self.body)++ def test_flags_a_quote_outside_every_tag_span(self):+ self.assertIn("tagSpans", self.body)+ self.assertIn("hasStrayQuote", self.body)++ def test_wired_to_live_input(self):+ self.assertIn("h3SyncPromptHelper()", QUEUE_JS) # called from engine sync too+ self.assertIn(".addEventListener('input'", ENGINES_JS)+++class ServerSharesTheSpeechRate(unittest.TestCase):+ def test_h3_status_carries_speech_words_per_sec(self):+ self.assertIn('"speech_words_per_sec": storyboard.SPEECH_WORDS_PER_SEC,', PANEL_PY)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_ram_floor_fallback.py b/test_h3_ram_floor_fallback.pynew file mode 100644index 0000000..bf87c4a--- /dev/null+++ b/test_h3_ram_floor_fallback.py@@ -0,0 +1,43 @@+#!/usr/bin/env python3+"""H3-28: the JS last-resort RAM-floor fallback must match the real floor.++`(st.ram_floor_gb || st.min_ram_gb || N)` only reaches the literal N when the+server's own fields are both absent — belt-and-suspenders, not the normal+path — but N still gets shown to a user in that case, and it was 46: not+H3_MIN_RAM_GB (60, the bf16 lane) and not H3_MIN_RAM_GB_Q8 (36, the real+floor, per mlx_ltx_panel.py) — a number no floor in this codebase has ever+been. Two call sites carried it (engines.js's engine-menu tooltip, queue.js's+engine-switch refusal reason); this pins both at 36 and pins the backend+constant they're supposed to agree with, so a future change to the real+floor is caught here too.+"""+from __future__ import annotations++import re+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+++class RamFloorFallbackMatchesTheRealFloor(unittest.TestCase):+ def test_backend_floor_is_36(self):+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ m = re.search(r"^H3_MIN_RAM_GB_Q8\s*=\s*([\d.]+)", src, re.M)+ self.assertIsNotNone(m, "H3_MIN_RAM_GB_Q8 constant not found")+ self.assertEqual(float(m.group(1)), 36.0)++ def test_engines_js_fallback_is_36(self):+ src = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+ self.assertIn("st.ram_floor_gb || st.min_ram_gb || 36", src)+ self.assertNotIn("st.ram_floor_gb || st.min_ram_gb || 46", src)+ self.assertNotIn("st.ram_floor_gb || st.min_ram_gb || 64", src)++ def test_queue_js_fallback_is_36(self):+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ self.assertIn("st.ram_floor_gb || st.min_ram_gb || 36", src)+ self.assertNotIn("st.ram_floor_gb || st.min_ram_gb || 46", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_speed_pill_matches_cell.py b/test_h3_speed_pill_matches_cell.pynew file mode 100644index 0000000..550dfb8--- /dev/null+++ b/test_h3_speed_pill_matches_cell.py@@ -0,0 +1,88 @@+#!/usr/bin/env python3+"""H3-13: the Fast/Best pill must show what will actually render, not just+the stored preference.++Native and the single-pass 10s have no Fast path (`cell.tristep_min == null`)+— they always render Best. Before this fix, `_h3ApplySpeed()` lit the Fast+pill from `pref === 'fast' && tri.available` alone: the adapter being+installed was enough to keep Fast pink even on a cell that cannot run it,+with only a sub-label ("Best only here") saying otherwise. A render could+take 22 min to 3h48m while the pill told the user they had picked the ~4x+faster option.++The fix lights the pill from `fastOn` (`h3TriStepOn(cell)`, which already+folds in per-cell availability) so the highlighted half always matches what+`h3_tristep` is about to post, adds a `cell-only-best` class (same+dashed/dimmed grammar as `needs-download`) so the chip itself looks+unavailable rather than relying on a sub-label, and keeps the "you prefer+Fast but this shape can't" note keyed off `pref` (not `lit`, which can no+longer disagree with the actual behaviour).++WHY THIS IS A STATIC TEST, NOT A DRIVEN ONE. `scripts/webapp_import_shim.mjs`+(the node-side DOM shim other test_h3_* files use) stubs+`document.querySelector`/`querySelectorAll` as permanent no-ops — fine for+code that only touches elements by id, but `_h3ApplySpeed()`'s pill-lighting+loop is a `querySelectorAll('#h3SpeedGroup [data-h3-speed]')`, which the shim+cannot resolve. Extending the shim's selector engine is out of scope for one+finding and risks the other packages editing shared JS in parallel this same+review. So this file pins the fixed LOGIC by reading the real function+bodies (a rename or a reverted condition fails it), and the full behaviour+was verified live against a booted panel with Playwright: switching to the+Native 3s tier with a stored Fast preference greyed the Fast pill+(`cell-only-best`), lit Best, and set `h3_tristep=0`; switching back to a+tristep-capable tier re-lit Fast without touching the stored preference.+"""+from __future__ import annotations++import re+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+ENGINES_JS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+++def _function_body(src: str, signature: str) -> str:+ start = src.index(signature)+ depth = 0+ i = src.index("{", start)+ j = i+ while True:+ if src[j] == "{":+ depth += 1+ elif src[j] == "}":+ depth -= 1+ if depth == 0:+ return src[i:j + 1]+ j += 1+++class SpeedPillMatchesWhatWillRender(unittest.TestCase):+ def test_lit_half_follows_fastOn_not_bare_preference(self):+ body = _function_body(ENGINES_JS, "function _h3ApplySpeed(")+ self.assertIn("const lit = fastOn ? 'fast' : 'best';", body,+ "the pill's lit half no longer tracks what will "+ "actually render (H3-13 regression)")+ # The old, wrong condition must not still be the one deciding `lit`.+ self.assertNotIn("const lit = (pref === 'fast' && tri.available)", body)++ def test_bestOnly_note_keys_off_preference_not_lit(self):+ body = _function_body(ENGINES_JS, "function _h3ApplySpeed(")+ self.assertIn("const bestOnly = pref === 'fast' && cell && "+ "cell.tristep_min == null;", body)++ def test_fast_pill_greys_out_on_a_best_only_cell(self):+ body = _function_body(ENGINES_JS, "function renderH3Turbo(")+ self.assertIn("cellOnlyBest", body)+ self.assertIn("cell-only-best", body)+ # It must be gated on THIS cell having no fast path, independent of+ # whether the adapter is installed (that's needs-download's job).+ self.assertIn("cell.tristep_min == null", body)++ def test_css_defines_the_greyed_state(self):+ css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+ self.assertIn(".pill-btn.cell-only-best", css)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_tier_blurbs_visible_and_accurate.py b/test_h3_tier_blurbs_visible_and_accurate.pynew file mode 100644index 0000000..625eccb--- /dev/null+++ b/test_h3_tier_blurbs_visible_and_accurate.py@@ -0,0 +1,74 @@+#!/usr/bin/env python3+"""H3-14: tier descriptions must be visible (not hover-only) and must not+be stale or contradictory.++Three copy defects, all in the blurbs `_h3_qualities()`/`_h3_lengths()`+build (mlx_ltx_panel.py), shown only via the chip's `title=` tooltip+before this fix:++ - Native said "Worth it with Turbo on; a long wait without" — Turbo was+ folded into the Fast/Best Speed switch, and Native has no Fast pass at+ all (tristep_min is null there, H3-13), so it always renders on Best.+ The sentence described a choice that no longer exists.+ - Standard said "every chained-window measurement on this Mac was taken+ here" — a developer's dev-machine note, not something that tells a+ user what THEY get.+ - The chained "10s" and the single-pass "10s single pass" both framed+ themselves as "the safe one" (no ghosting / no drift), which read as+ each contradicting the other rather than stating its own trade-off.++Fix: reworded all four blurbs in plain user terms, and added a NEW+visible line (#h3TierBlurb, cell.blurb — the exact string the tooltip+already carried) so a trackpad-averse or touch user sees it at all.++Verified live: switching Native -> the visible line reads "...Always+renders on Best — no Fast pass here..."; switching between the two 10s+tiers shows each one's own honest trade-off instead of a "safe one"+claim; the element's `hidden` flag clears whenever a cell resolves.+"""+from __future__ import annotations++import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+PANEL_PY = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+INDEX_HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+ENGINES_JS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+++class BlurbsNoLongerStaleOrContradictory(unittest.TestCase):+ def test_native_no_longer_names_turbo(self):+ self.assertNotIn("Worth it with Turbo on", PANEL_PY)+ self.assertIn("Always renders on Best", PANEL_PY)+ self.assertIn("Fast pass here", PANEL_PY)++ def test_standard_no_longer_reads_as_a_dev_machine_note(self):+ self.assertNotIn("every chained-window measurement on this Mac was taken", PANEL_PY)+ self.assertIn("the best-tested shape for", PANEL_PY)+ self.assertIn("chained 10s/15s clips", PANEL_PY)++ def test_the_two_10s_tiers_dont_both_claim_to_be_the_safe_one(self):+ self.assertIn("The default 10s — two chained 5 s windows", PANEL_PY)+ self.assertIn("One continuous shot, no join", PANEL_PY)+ self.assertIn("costs 2-4x the chained", PANEL_PY)+ self.assertNotIn("no duplicated-subject ghosting", PANEL_PY)+ self.assertNotIn("no seam, no chained repeat, no drift between halves", PANEL_PY)+++class BlurbIsNowAVisibleLine(unittest.TestCase):+ def test_markup_has_the_visible_blurb_element(self):+ self.assertIn('id="h3TierBlurb" data-h3-only hidden', INDEX_HTML)++ def test_it_sits_before_the_warning_note_not_after(self):+ blurb_i = INDEX_HTML.index('id="h3TierBlurb"')+ note_i = INDEX_HTML.index('id="h3TierNote"')+ self.assertLess(blurb_i, note_i)++ def test_js_writes_cell_blurb_into_it(self):+ self.assertIn("const blurbEl = document.getElementById('h3TierBlurb');", ENGINES_JS)+ self.assertIn("blurbEl.textContent = b;", ENGINES_JS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_tristep_draft.py b/test_h3_tristep_draft.pyindex 3d81dfe..8016114 100644--- a/test_h3_tristep_draft.py+++ b/test_h3_tristep_draft.py@@ -37,7 +37,6 @@ for _k, _d in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "out"),os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"os.environ["LTX_H3_FORCE_CAPABLE"] = "1"-os.environ["PHOSPHENE_SPEED_FACTOR"] = "1"os.environ.setdefault("LTX_PORT", "8302")sys.path.insert(0, str(ROOT))@@ -45,6 +44,26 @@ import mlx_ltx_panel as P # noqa: E402SUBSET = "50:0,16,33,49"+# PHOSPHENE_SPEED_FACTOR pins this suite's prices to the M4 Max tables. It was+# set at import time and never removed, and pytest imports every module before+# it runs any — so it leaked into every later suite in a whole-suite run+# (test_vc01_ltx_estimate_honesty's low-RAM factor read 1.0). Scope it to this+# module's own tests instead.+_SPEED_PREV = None+++def setUpModule():+ global _SPEED_PREV+ _SPEED_PREV = os.environ.get("PHOSPHENE_SPEED_FACTOR")+ os.environ["PHOSPHENE_SPEED_FACTOR"] = "1"+++def tearDownModule():+ if _SPEED_PREV is None:+ os.environ.pop("PHOSPHENE_SPEED_FACTOR", None)+ else:+ os.environ["PHOSPHENE_SPEED_FACTOR"] = _SPEED_PREV+def _safetensors(path: Path, tensors: dict) -> None:header, blobs, off = {}, [], 0@@ -339,10 +358,14 @@ class TestEstimates(unittest.TestCase):self.assertNotIn("facefix_min", cell)def test_the_face_fix_note_prices_the_draft(self):+ # H3-26: "draft's time again" was wrong on any canvas that isn't the+ # 640x384 Draft one — the checkbox this note describes is offered+ # whenever H3.upscale_modes allows ltx_x2, not only on Draft. Fixed+ # to "the same time again", tier-agnostic.P._H3_EXPORT_NOTES.clear()self.assertIn(f"About {P.FACE_FIX_DRAFT_5S_MIN:g} min more",P._h3_export_notes(640, 384)["ltx_x2"])- self.assertIn("draft's time again", P._h3_export_notes(768, 448)["ltx_x2"])+ self.assertIn("the same time again", P._h3_export_notes(768, 448)["ltx_x2"])def test_storyboard_prices_a_draft_at_three_steps_when_installed(self):with unittest.mock.patch.object(P, "h3_tristep_status", lambda: {"available": True}), \@@ -610,7 +633,11 @@ class TestUiContract(unittest.TestCase):self.assertIn('data-h3-speed="best"', html)self.assertLess(html.index('id="h3SpeedRow"'), html.index('id="qualityLabelName"'))self.assertNotIn('id="h3TurboGroup"', html)- self.assertIn("3 steps — about 4× faster, great for drafts and most shots.", html)+ # H3-40: the Fast pill's title used to state the MECHANISM ("3+ # steps"); it now states the TRADE-OFF a user is actually choosing+ # between (speed vs sharpness), matching the qs-meta line above it.+ self.assertIn("About 4× faster than Best, a touch softer on fine detail", html)+ self.assertIn("sharpest faces and detail", html)# Upscale & Face Fix beside Generate, bound to the same state.self.assertIn('id="h3FaceFixFooter" onchange="setH3FaceFixAfter(this.checked)"', html)self.assertLess(html.index('id="h3FaceFixFooter"'), html.index('id="genBtn"'))diff --git a/test_h3_turbo_adapter.py b/test_h3_turbo_adapter.pyindex a0e49a8..be3a8d8 100644--- a/test_h3_turbo_adapter.py+++ b/test_h3_turbo_adapter.py@@ -191,7 +191,14 @@ class TestH3TurboInstallContract(unittest.TestCase):status = P.h3_turbo_status()self.assertTrue(status["install_available"])self.assertFalse(status["installing"])- self.assertIn(P.H3_TURBO_LORA_FILE, status["install_note"])+ # H3-29: install_note used to hardcode H3_TURBO_LORA_FILE (the+ # retired v1.0 LightX2V asset) unconditionally, disagreeing with+ # what the install button actually fetches by default+ # (H3_TURBO_DEFAULT_ASSET = v4-600-EMA). It now names whichever+ # asset _h3_turbo_asset() (the SAME resolver the install action+ # calls) actually resolves.+ self.assertIn(P._h3_turbo_asset()["file"], status["install_note"])+ self.assertIn(P.H3_TURBO_V4_REPO, status["install_note"])def _write_lora_fixture(path: Path, adaln_modules: list[str],diff --git a/test_h3_turbo_install_note_matches_asset.py b/test_h3_turbo_install_note_matches_asset.pynew file mode 100644index 0000000..c545a17--- /dev/null+++ b/test_h3_turbo_install_note_matches_asset.py@@ -0,0 +1,59 @@+#!/usr/bin/env python3+"""H3-29: Turbo's /status install_note must name the adapter the install+button actually fetches.++h3_turbo_note() already resolves dynamically (v4-600-EMA vs v1.0, from+whichever adapter is really on disk), but the neighbouring install_note+field was a hardcoded sentence about H3_TURBO_LORA_FILE — the retired+v1.0 LightX2V GitHub release asset — while the one-click install action+(_h3_turbo_asset() with no key) has fetched H3_TURBO_DEFAULT_ASSET =+"v4-600-EMA" straight from larryvrh's Hugging Face repo since 2026-09-05.+Two sentences in the same /status.h3.turbo block named a different file,+from a different host, fetched by a different mechanism, for the same+button.++Fix: install_note is built from _h3_turbo_asset() — the SAME resolver the+install action itself uses — so the two can't diverge again.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-h3-turbonote-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8304")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class InstallNoteMatchesTheRealAsset(unittest.TestCase):+ def test_default_asset_is_v4(self):+ self.assertEqual(P.H3_TURBO_DEFAULT_ASSET, "v4-600-EMA")++ def test_install_note_names_the_default_assets_file_and_repo(self):+ asset = P._h3_turbo_asset()+ note = (lambda _a: (+ f"Downloads {_a['file']} from {P.H3_TURBO_V4_REPO} on Hugging Face "+ f"(~{P.H3_TURBO_DOWNLOAD_GB} GB, checksum-verified)."+ ))(asset)+ self.assertIn(asset["file"], note)+ self.assertIn(P.H3_TURBO_V4_REPO, note)+ self.assertNotIn(P.H3_TURBO_LORA_FILE, note)++ def test_source_no_longer_hardcodes_the_retired_v1_asset(self):+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ # The old literal sentence must be gone from the install_note builder.+ self.assertNotIn(+ 'f"Downloads the digest-pinned {H3_TURBO_LORA_FILE} "', src)+ self.assertIn("_h3_turbo_asset()", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_window_prompts_compose.py b/test_h3_window_prompts_compose.pynew file mode 100644index 0000000..e13093b--- /dev/null+++ b/test_h3_window_prompts_compose.py@@ -0,0 +1,87 @@+#!/usr/bin/env python3+"""H3-06: a typed per-window prompt must ADD TO the main prompt, not+replace it, and the tier note pointing at the control must name the+right direction.++Before this, `_filled = [x.strip() or prompt for x in _asked]` used a+typed window box VERBATIM as that window's entire prompt. A beat like+"he raises his glass" lost the subject, setting, soundscape and any LoRA+trigger words the main prompt carried — a real risk across a 10-27 minute+chained render, since LTX's own windowed path already has a shared-text+field for exactly this and H3 didn't.++h3_compose_window_prompts(prompt, asked, windows) is the extracted, pure+version of the fix: every non-empty box composes as+`f"{prompt} {beat}"`; an empty box still falls back to the bare main+prompt; a box that happens to equal the main prompt verbatim is not+doubled.++Separately, H3_TIER_CHAIN_NOTE told the user to "open Per-window prompts+below" — but the control (#h3WindowPromptsRow) sits ABOVE the note's own+container (#h3TierNote) in the page, by deliberate design (2026-09-18+layout pass: it lives with the prompt, not folded inside the closed Shot+setup section). Fixed to say "above" instead of moving a documented,+reasoned layout decision to match a wrong sentence.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-h3-winprompts-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8305")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++PROMPT = ("A woman in a red coat stands in a rainy alley, neon signs "+ "reflecting in puddles. Audio: rain, distant traffic.")+++class WindowPromptsComposeSharedTextPlusBeat(unittest.TestCase):+ def test_empty_box_falls_back_to_the_bare_prompt(self):+ out = P.h3_compose_window_prompts(PROMPT, ["", None, " "], 3)+ self.assertEqual(out, [PROMPT, PROMPT, PROMPT])++ def test_a_beat_is_appended_not_substituted(self):+ out = P.h3_compose_window_prompts(PROMPT, ["", "he raises his glass", ""], 3)+ self.assertEqual(out[1], PROMPT + " he raises his glass")+ # The critical regression: the subject/setting/soundscape must+ # survive into the composed window prompt.+ self.assertIn("red coat", out[1])+ self.assertIn("rain", out[1])++ def test_identical_box_is_not_doubled(self):+ out = P.h3_compose_window_prompts(PROMPT, [PROMPT], 1)+ self.assertEqual(out, [PROMPT])++ def test_short_list_is_padded_with_the_bare_prompt(self):+ out = P.h3_compose_window_prompts(PROMPT, ["beat one"], 3)+ self.assertEqual(len(out), 3)+ self.assertEqual(out[0], PROMPT + " beat one")+ self.assertEqual(out[1], PROMPT)+ self.assertEqual(out[2], PROMPT)++ def test_render_path_uses_the_shared_helper(self):+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ # 4.17: routed through h3_window_prompts_for_job, which composes typed+ # beats (this test's contract) and leaves a caller's COMPLETE prompts+ # (One Shot, storyboard) whole.+ self.assertIn("_filled = h3_window_prompts_for_job(", src)+ self.assertEqual(P.h3_window_prompts_for_job("A", ["", "b"], 2), ["A", "A b"])+++class ChainNotePointsTheRightDirection(unittest.TestCase):+ def test_note_says_above_not_below(self):+ self.assertIn("Per-window prompts above", P.H3_TIER_CHAIN_NOTE)+ self.assertNotIn("Per-window prompts below", P.H3_TIER_CHAIN_NOTE)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_health_chip_narrow.py b/test_health_chip_narrow.pynew file mode 100644index 0000000..000d16a--- /dev/null+++ b/test_health_chip_narrow.py@@ -0,0 +1,86 @@+"""VC-32: the header health pill names what's wrong, and never clips mid-+character with no sign anything was cut.++WHAT THIS GUARDS.+1. Below 1400px, `updateHealthChip()` set `face.dataset.short = 'attention'`+ whenever memory/models/helper had a warn/danger state - the CSS swap+ (panel.css, `@media (max-width: 1400px)`) then showed that bare word with+ ZERO indication of what needed attention, on a chip whose whole job is a+ one-glance read.+2. At widths just above that breakpoint (1440x900 - a real laptop size), the+ FULL text ("43/64 GB · 68%") still got clipped mid-number to "43/64 G" -+ not by the JS short-text swap (which doesn't apply there), but by+ #healthCluster's own `overflow: hidden` (it has `min-width: 0;+ flex-shrink: 1` so the header wraps other content instead of it). Flex+ items default to `min-width: auto`, which refuses to shrink below their+ own text's natural width, so `.hc-face` never got the chance to add an+ ellipsis - the ancestor's raw pixel clip was the only thing that ever+ fired, silently.++Fixed: (1) the short-text fallback now names the row ("models"/"helper"/+"memory") instead of the bare word. (2) `.hc-face` gets `min-width: 0;+overflow: hidden; text-overflow: ellipsis` (plus `#healthChip { min-width:+0 }` so the flex chain can actually shrink down to it) — any clip is now a+visible "…", at any width, not just below the JS breakpoint.+"""+from __future__ import annotations++import re+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+HEALTH_JS = (ROOT / "webapp" / "js" / "health.js").read_text(encoding="utf-8")+++class ShortTextNamesTheProblem(unittest.TestCase):+ def _fn(self) -> str:+ return extract_function("updateHealthChip", HEALTH_JS)++ def test_no_longer_hardcodes_the_bare_word(self):+ fn = self._fn()+ # The literal assignment this used to be - must be gone. The word+ # "attention" is still allowed to exist as a LAST-RESORT fallback+ # (see next test), just never as the unconditional value.+ self.assertNotIn("face.dataset.short = 'attention';", fn)++ def test_three_real_row_names_are_reachable(self):+ fn = self._fn()+ for label in ("'models'", "'helper'", "'memory'"):+ self.assertIn(label, fn, f"{label} not used to name the short text")++ def test_still_has_a_never_empty_fallback(self):+ """Belt and braces: if none of the three pills is even findable+ (shouldn't happen), the chip must still show SOMETHING, not an+ empty face."""+ fn = self._fn()+ self.assertIn(": 'attention'", fn)+++class NoSilentMidCharacterClip(unittest.TestCase):+ def test_hc_face_can_shrink_and_ellipsize(self):+ m = re.search(r"#healthChip \.hc-face\s*\{([^}]*)\}", CSS)+ self.assertIsNotNone(m, "no base #healthChip .hc-face rule")+ body = m.group(1)+ self.assertIn("text-overflow: ellipsis", body)+ self.assertIn("overflow: hidden", body)+ self.assertIn("min-width: 0", body)++ def test_health_chip_itself_allows_shrinking(self):+ self.assertIn("#healthChip { min-width: 0; }", CSS)++ def test_narrow_breakpoint_rule_is_unchanged(self):+ """The below-1400px data-short swap is a separate, already-correct+ mechanism - this fix must not remove it, only stop relying on it+ being the ONLY thing standing between the user and a raw clip."""+ self.assertIn("@media (max-width: 1400px)", CSS)+ self.assertIn("content: attr(data-short)", CSS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_hidden_wins.py b/test_hidden_wins.pynew file mode 100644index 0000000..0c677eb--- /dev/null+++ b/test_hidden_wins.py@@ -0,0 +1,161 @@+"""[hidden] must always win over component CSS (VC-07).++WHAT THIS GUARDS. `panel.css` had no single rule making `[hidden]` outrank a+component's own `display` declaration, so the stylesheet grew two dozen+one-off `<selector>[hidden] { display: none !important }` patches - and two+spots were missed: `.toggle-pill { display: inline-flex }` kept LTX's+"No voice" pill on screen after `queue.js` set `noVoicePill.hidden = true`+(a user ticks it, the render speaks anyway - a wasted render), and+`.loras-summary .loras-browse-btn` kept the H3 LoRA "Import" button visible+in the LTX engine (posts to `/h3/loras/import` from the wrong engine). Both+elements were correctly `.hidden === true` in the DOM the whole time; only+the paint was wrong.++The fix is ONE global rule, `[hidden] { display: none !important; }`, added+once near the top of `panel.css` (right after the `* { box-sizing }` reset,+before any component styles). A `!important` declaration on `[hidden]`+outranks a plain `display` declaration on ANY other selector regardless of+specificity, so this closes the whole class rather than the two known+instances - the next component that forgets to guard its own `[hidden]`+state is covered for free.++This file holds the static, always-runnable half of the gate (the rule+exists, sits early, and the two originally-broken selectors are still on+the books as evidence of what it now overrides). The dynamic half - a real+browser confirming `getComputedStyle` actually reports `none` for every+`[hidden]` element, in both engines - is `scripts/measure_hidden_elements.py`+/ `TestHiddenElementsRenderNone` below; it SKIPS without Chrome instead of+lying green.+"""+from __future__ import annotations++import json+import re+import subprocess+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+CSS = ROOT / "webapp" / "style" / "panel.css"+SCRIPT = ROOT / "scripts" / "measure_hidden_elements.py"+VENV_PY = ROOT / "ltx-2-mlx" / "env" / "bin" / "python3.11"+NO_BROWSER_EXIT = 3++GLOBAL_RULE = re.compile(r"\[hidden\]\s*\{\s*display:\s*none\s*!important\s*;?\s*\}")+++def _python() -> str:+ return str(VENV_PY) if VENV_PY.exists() else sys.executable+++def _browser_present() -> bool:+ import os+ import shutil++ env = os.environ.get("CHROME_PATH", "").strip()+ if env and Path(env).exists():+ return True+ for c in ("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ "/Applications/Chromium.app/Contents/MacOS/Chromium",+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"):+ if Path(c).exists():+ return True+ return any(shutil.which(n) for n in+ ("google-chrome", "chromium", "chromium-browser"))+++class GlobalHiddenRule(unittest.TestCase):+ def test_a_bare_hidden_rule_exists(self):+ css = CSS.read_text(encoding="utf-8")+ self.assertRegex(css, GLOBAL_RULE,+ "no global `[hidden] { display: none !important }` "+ "rule in panel.css")++ def test_the_rule_lands_before_any_component_style(self):+ """It must sit early so it reads as the house rule, not a patch bolted+ on after the fact - and, structurally, so every component rule below+ it is a rule this one is known to outrank."""+ css = CSS.read_text(encoding="utf-8")+ m = GLOBAL_RULE.search(css)+ self.assertIsNotNone(m)+ # ".toggle-pill" is the first of the two originally-broken component+ # rules (panel.css ~471); the global rule must precede it.+ toggle_pill_idx = css.index(".toggle-pill {")+ self.assertLess(m.start(), toggle_pill_idx,+ "[hidden] rule must appear before .toggle-pill")++ def test_previously_broken_selectors_are_still_on_the_books(self):+ """Not asserting these were deleted - only that the two elements the+ review caught are still real (a component-CSS conflict for the+ global rule to outrank), so this test can't silently stop meaning+ anything if the markup is refactored without re-checking the gate."""+ html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+ self.assertIn('id="noVoicePill"', html)+ self.assertIn('id="h3LoraImportBtn"', html)+ css = CSS.read_text(encoding="utf-8")+ self.assertIn(".toggle-pill {", css)+ self.assertIn(".loras-browse-btn", css)+++class ScriptShape(unittest.TestCase):+ def test_script_parses(self):+ compile(SCRIPT.read_text(encoding="utf-8"), str(SCRIPT), "exec")++ def test_never_binds_the_owners_port(self):+ src = SCRIPT.read_text(encoding="utf-8")+ self.assertIn("FORBIDDEN_PORTS", src)+ for line in src.splitlines():+ if "8199" in line:+ self.assertTrue(re.search(r"FORBIDDEN_PORTS\s*=", line),+ f"8199 outside the forbidden set: {line}")+++class TestHiddenElementsRenderNone(unittest.TestCase):+ """The dynamic gate: boot the real panel, walk every `[hidden]` element+ in a real browser, in both engines, and assert none of them paint."""++ doc: dict | None = None+ skip_why: str | None = None+ fail_why: str | None = None+ returncode: int | None = None++ @classmethod+ def setUpClass(cls):+ if not _browser_present():+ cls.skip_why = "no Chrome/Chromium/Edge - set CHROME_PATH"+ return+ try:+ proc = subprocess.run([_python(), str(SCRIPT)], cwd=str(ROOT),+ capture_output=True, text=True,+ errors="replace", timeout=180)+ except subprocess.TimeoutExpired:+ cls.fail_why = "the hidden-elements gate did not finish in 180s"+ return+ if proc.returncode == NO_BROWSER_EXIT:+ cls.skip_why = "no browser: " + (proc.stderr or "").strip()+ return+ try:+ cls.doc = json.loads(proc.stdout)+ except json.JSONDecodeError:+ cls.fail_why = (f"no JSON (exit {proc.returncode}): "+ f"{(proc.stderr or '').strip()[-800:]}")+ return+ cls.returncode = proc.returncode++ def setUp(self):+ if self.skip_why:+ self.skipTest(self.skip_why)+ if self.doc is None:+ self.fail(self.fail_why or "no measurement")++ def test_every_hidden_element_computes_display_none(self):+ self.assertEqual(self.doc.get("failures") or [], [],+ "an element with `hidden` is still rendering:\n "+ + "\n ".join(self.doc.get("failures") or []))+ self.assertTrue(self.doc.get("ok"))+ self.assertEqual(self.returncode, 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_i18n_film_titles.py b/test_i18n_film_titles.pynew file mode 100644index 0000000..d65a0ed--- /dev/null+++ b/test_i18n_film_titles.py@@ -0,0 +1,70 @@+#!/usr/bin/env python3+"""FILM-45 (panel-level half): a Unicode-aware slug and full-width-colon+locations, so a Japanese or accented-Latin film title is not mangled.+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+++class TheSlugKeepsNonAsciiLetters(unittest.TestCase):+ def test_a_japanese_title_is_not_reduced_to_shot(self):+ slug = panel._sb_slug("京都の夜", 6)+ self.assertNotEqual(slug, "shot")+ self.assertIn("京都の夜", slug)++ def test_an_accented_latin_title_keeps_its_accents(self):+ slug = panel._sb_slug("Café à Paris", 6)+ self.assertEqual(slug, "café-à-paris")++ def test_plain_ascii_is_unaffected(self):+ self.assertEqual(panel._sb_slug("Night Drive", 6), "night-drive")++ def test_two_different_japanese_titles_produce_different_slugs(self):+ a = panel._sb_slug("京都の夜")+ b = panel._sb_slug("東京の朝")+ self.assertNotEqual(a, b)++ def test_an_empty_or_symbols_only_title_still_falls_back_to_shot(self):+ self.assertEqual(panel._sb_slug(""), "shot")+ self.assertEqual(panel._sb_slug("!!! *** ///"), "shot")++ def test_word_count_is_still_respected(self):+ slug = panel._sb_slug("one two three four five six seven", 3)+ self.assertEqual(slug, "one-two-three")+++class LocationsAcceptTheFullWidthColon(unittest.TestCase):+ def test_a_japanese_location_line_splits_on_the_fullwidth_colon(self):+ locs = panel._sb_parse_locations("台所:戦後の家の裏にある小さな台所")+ self.assertEqual(len(locs), 1)+ self.assertEqual(locs[0]["name"], "台所")+ self.assertEqual(locs[0]["description"], "戦後の家の裏にある小さな台所")++ def test_the_ascii_colon_still_works_unchanged(self):+ locs = panel._sb_parse_locations("Kitchen: a small kitchen behind the house")+ self.assertEqual(locs[0]["name"], "Kitchen")+ self.assertEqual(locs[0]["description"], "a small kitchen behind the house")++ def test_a_line_with_neither_colon_falls_back_as_before(self):+ locs = panel._sb_parse_locations("just a plain sentence with no colon at all")+ self.assertEqual(len(locs), 1)+ self.assertTrue(locs[0]["description"])++ def test_multiple_japanese_locations_get_distinct_ids(self):+ locs = panel._sb_parse_locations(+ "台所:小さな台所\n"+ "居間:広い居間\n")+ self.assertEqual(len(locs), 2)+ self.assertNotEqual(locs[0]["id"], locs[1]["id"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_install_funnel.py b/test_install_funnel.pyindex 39b6ff3..3bc907e 100644--- a/test_install_funnel.py+++ b/test_install_funnel.py@@ -96,14 +96,19 @@ class ClosedVocabulary(unittest.TestCase):def test_no_signature_or_fingerprint_rides_along(self):"""Stated as a rule in docs/ANALYTICS.md: an install-time error lineis the likeliest place in the product for a username-bearing path to- survive scrubbing, and the class answers the question on its own."""+ survive scrubbing, and the class answers the question on its own.++ ram_gb (SYS-16) is the one deliberate addition beyond that: not a+ leak (already sent on app_installed/render_completed), just the+ hardware signal that lets first_queue be sliced "per tier" the same+ way render_completed's first_render already can be."""with _FreshInstall(), _Capture() as cap:P._analytics_install_step("engine_env", "failed", "venv_broken")props = cap.events("install_step")[0]self.assertNotIn("error_signature", props)self.assertNotIn("error_fingerprint", props)self.assertEqual(sorted(props),- ["error_class", "outcome", "step", "version"])+ ["error_class", "outcome", "ram_gb", "step", "version"])class DidTheUpdateLand(unittest.TestCase):diff --git a/test_integration_4170.py b/test_integration_4170.pynew file mode 100644index 0000000..3d120f2--- /dev/null+++ b/test_integration_4170.py@@ -0,0 +1,206 @@+#!/usr/bin/env python3+"""Integration pins for the 4.17.0 mega merge — behaviour that only exists+because two packages' fixes meet in the same code path.++1. VA-28 (lipsync: record each One Shot part's real seed in+ take.parts_meta) x VA-17 (safety: resume a stopped One Shot from the next+ part). parts_meta is indexed by part and Load Params restores part 1's+ seed as the take's own seed, so a RESUMED take must carry the seeds of+ the parts it did not re-render — read from their sidecars — instead of+ starting the list at the first resumed part.+"""+from __future__ import annotations++import json+import subprocess+import sys+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as p # noqa: E402+++def _tiny_clip(path: Path) -> None:+ subprocess.run(+ ["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=red:s=32x32:d=0.2",+ "-f", "lavfi", "-i", "anullsrc=r=8000:cl=mono", "-t", "0.2",+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", str(path)],+ check=True,+ )+++def take_env(tmp_path, monkeypatch):+ out_dir = tmp_path / "out"; out_dir.mkdir()+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")+ monkeypatch.setattr(p, "set_hidden", lambda *a, **k: None)+ monkeypatch.setattr(p, "take_drift", lambda *a, **k: {"ok": True, "delta": 0.0, "drifted": False})+ made = []++ def fake_h3(child):+ out = out_dir / f"{child['id']}.mp4"+ _tiny_clip(out)+ child["output_path"] = str(out)+ child["params"]["seed_used"] = 500 + len(made)+ made.append(out)++ monkeypatch.setattr(p, "run_h3_job_inner", fake_h3)+ return out_dir, made+++def _job():+ return p.make_job({"mode": "t2v", "engine": "h3", "prompt": "a hen skates",+ "take_seconds": "45",+ "beats": json.dumps([f"b{i}" for i in range(9)])})+++def _final_take(job) -> dict:+ final = Path(job["output_path"])+ return json.loads(final.with_suffix(final.suffix + ".json").read_text())["take"]+++def test_a_fresh_take_records_every_parts_seed(take_env):+ _, made = take_env+ job = _job()+ p.run_take_job_inner(job)+ assert len(made) == 3+ assert _final_take(job)["parts_meta"] == [+ {"seed_used": 500}, {"seed_used": 501}, {"seed_used": 502}]+++def test_a_resumed_take_keeps_the_seeds_of_the_parts_it_did_not_rerender(take_env):+ out_dir, made = take_env+ part1 = out_dir / "earlier-p1.mp4"+ _tiny_clip(part1)+ part1.with_suffix(".mp4.json").write_text(json.dumps({"seed_used": 111}))+ job = _job()+ job["params"]["take"]["_resume"] = {"outs": [str(part1)], "start_k": 1}+ p.run_take_job_inner(job)+ assert len(made) == 2 # parts 2 and 3 only+ meta = _final_take(job)["parts_meta"]+ assert meta[0] == {"seed_used": 111} # part 1's real seed, from its sidecar+ assert meta[1:] == [{"seed_used": 500}, {"seed_used": 501}]+++# 2. The page's bootstrap is `const BOOT = __BOOTSTRAP__;` in index.html's+# one inline <script>. A top-level `const` is NOT a property of `window`,+# so `window.BOOT && BOOT.tier` is always {} in a real browser. est's+# VA-11/12 read the keyframe/extend price cards that way, and every Mac —+# a 64 GB M4 Max included — was told "Needs more memory than this Mac has"+# for Keyframe and Extend (found driving the merged panel in Chrome; the+# node harnesses define BOOT as a global, so they never saw it).+def test_no_module_reads_boot_through_window():+ root = Path(__file__).resolve().parent+ html = (root / "webapp" / "index.html").read_text(encoding="utf-8")+ assert "const BOOT = __BOOTSTRAP__;" in html+ offenders = [f"{js.name}:{i}" for js in sorted((root / "webapp" / "js").glob("*.js"))+ for i, line in enumerate(js.read_text(encoding="utf-8").splitlines(), 1)+ if "window.BOOT" in line]+ assert offenders == [], offenders+++# 3. est's fleet range formatter printed _fmt_eta's " · batch" tail on BOTH+# ends of an hours-long range ("~36 min · batch–1h 19m · batch"), which+# the fleet-priced Extend Pro pill showed as soon as it was fleet-priced.+def test_an_hours_long_range_carries_one_batch_tail():+ out = p._fmt_eta_range(36.0, 79.0)+ assert out == "~36 min–1h 19m · batch", out+ assert out.count("batch") == 1+++# 4. Extend and Keyframe are priced from the fleet's own wall clocks where+# the fleet has them (est's cost model is the distilled-Q4 t2v model; it+# had Extend at ~1.5 min on a 64 GB M4 Max against a fleet median of+# ~20 min). The model only scales between Extend's variants.+def test_extend_and_keyframe_prices_follow_the_fleet(monkeypatch):+ fake = {"p25_min": 15.0, "p50_min": 20.0, "p75_min": 30.0,+ "basis": "based on 40 renders fleet-wide",+ "eta_range": "~15–30 min · batch", "eta_mid": "~20 min"}+ monkeypatch.setattr(p, "SYSTEM_CAPS", {**p.SYSTEM_CAPS, "allows_extend": True,+ "allows_keyframe": True})+ monkeypatch.setattr(p, "fleet_calibrated_range", lambda *a, **k: dict(fake))+ kf = p.ltx_mode_price_card("keyframe")+ assert kf["eta"] == fake["eta_range"] and kf["basis"] == fake["basis"]+ draft = p.ltx_mode_price_card("extend", steps=8)+ assert draft["eta_min"] == 20.0+ # more added seconds and more steps never price cheaper+ by = draft["eta_by_latents"]+ assert by["5"] == draft["eta"]+ pro = p.ltx_mode_price_card("extend", steps=30)+ assert pro["eta_min"] > draft["eta_min"]+ monkeypatch.setattr(p, "fleet_calibrated_range", lambda *a, **k: None)+ assert p.ltx_mode_price_card("keyframe")["basis"] == "estimated"+++def test_a2v_estimate_route_prices_from_the_fleet(monkeypatch):+ from urllib.parse import urlencode+ from panel.routes import GET_ROUTES++ class H:+ out = None+ def _json(self, obj, code=200):+ self.out = (code, obj)++ class Parsed:+ def __init__(self, q):+ self.query = q++ fake = {"p25_min": 7.0, "p50_min": 10.0, "p75_min": 15.0,+ "basis": "based on 82 renders fleet-wide"}+ monkeypatch.setattr(p, "fleet_calibrated_range", lambda *a, **k: dict(fake))+ h = H()+ GET_ROUTES["/a2v/estimate"](h, Parsed(urlencode({"frames": 121})))+ code, body = h.out+ assert code == 200 and body["basis"] == fake["basis"]+ assert body["eta"] == "~7–15 min" and body["minutes"] == 10.0+ monkeypatch.setattr(p, "fleet_calibrated_range", lambda *a, **k: None)+ h = H()+ GET_ROUTES["/a2v/estimate"](h, Parsed(urlencode({"frames": 121})))+ assert h.out[1]["basis"] == "estimated"+++# 5. SYS-16's form-side "Make your first clip" card and VC-41's empty-gallery+# card were both `.first-run-card`. VC-41's later rule (centred column,+# 32 px padding, max-width 420 px) restyled SYS-16's card into a tall block+# above the form, and the sticky Generate footer — which can only stick+# inside its own <form> — ended up under the Now pane at 1440x900 and off+# screen at 1366x768 on a first run (measured in Chrome; beta/main keeps+# Generate in view). One class per component, the card lives inside+# #genForm, and its prompts are chips.+def test_first_run_cards_do_not_share_a_class_and_generate_stays_reachable():+ root = Path(__file__).resolve().parent+ css = (root / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+ html = (root / "webapp" / "index.html").read_text(encoding="utf-8")+ queue_js = (root / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ assert css.count(".first-run-card {") == 1+ assert "gallery-first-run" not in queue_js # one first-run card ships (SYS-16's)+ form = html[html.index('<form id="genForm">'):]+ form = form[:form.index("</form>")]+ assert 'id="firstRunCard"' in form+ btn_rule = css[css.index(".first-run-prompt-btn {"):]+ btn_rule = btn_rule[:btn_rule.index("}")]+ assert "width: auto" in btn_rule+++# 6. VC-31 (gallery poster: one arg, 2.5 s frame, None on failure) and+# FILM-39 (Editor filmstrip poster: width arg, proxy's first frame,+# raises) were both `_ensure_video_poster`. The later definition silently+# replaced the first, and the gallery's /poster route — which calls it+# with one argument — raised TypeError for every card.+def test_gallery_poster_route_serves_a_poster(tmp_path, monkeypatch):+ import inspect+ assert list(inspect.signature(p._ensure_video_poster).parameters) == ["src"]+ assert list(inspect.signature(p._ensure_proxy_poster).parameters) == ["src", "width"]+ clip = p.OUTPUT / "int4170_poster_probe.mp4"+ clip.parent.mkdir(parents=True, exist_ok=True)+ _tiny_clip(clip)+ try:+ poster = p._ensure_video_poster(clip)+ assert poster is not None and poster.stat().st_size > 0+ finally:+ clip.unlink(missing_ok=True)diff --git a/test_integration_film_leftovers.py b/test_integration_film_leftovers.pynew file mode 100644index 0000000..4d3eb89--- /dev/null+++ b/test_integration_film_leftovers.py@@ -0,0 +1,112 @@+#!/usr/bin/env python3+"""4.17 integration leftovers — things only possible once the editor-a,+editor-b, board and music packages were combined (coordinator follow-up).++1. The queued film render (FILM-28's job) honours the sequence aspect+ (FILM-58, edit.settings.aspect).+2. Cancel on that render really stops ffmpeg: every ffmpeg the job starts is+ its own process group recorded ON THE JOB, never in STATE["mux_pgid"] (the+ generation queue's slot), and the cancel route kills it.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import time+import unittest+from pathlib import Path+from unittest import mock++import mlx_ltx_panel as panel+import storyboard_editor as sedit+from test_render_job import Sandbox, _board++FFPROBE = shutil.which("ffprobe")+++def _real_clip(path: Path, w=640, h=360, secs=1) -> None:+ subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i",+ f"testsrc2=s={w}x{h}:d={secs}", "-c:v", "libx264",+ "-pix_fmt", "yuv420p", str(path)], check=True)+++def _dims(path) -> tuple[int, int]:+ out = subprocess.run([FFPROBE, "-v", "error", "-select_streams", "v:0",+ "-show_entries", "stream=width,height", "-of", "json",+ str(path)], capture_output=True, text=True, check=True).stdout+ st = json.loads(out)["streams"][0]+ return int(st["width"]), int(st["height"])+++class TheFilmJobHonoursTheSequenceAspect(Sandbox):+ def setUp(self):+ super().setUp()+ edit = sedit.load_edit(self.bdir)+ edit["settings"] = {"aspect": "9:16"}+ sedit.save_edit(self.bdir, edit)++ def fake_assemble(cmd, label): # a real 16:9 film on disk+ _real_clip(Path(cmd[-1]))+ p = mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_assemble)+ p.start()+ self.addCleanup(p.stop)++ @unittest.skipUnless(FFPROBE, "ffprobe not on PATH")+ def test_the_job_delivers_a_9_16_film(self):+ h = self._post("edit/render/start", {"id": "sb_t"})+ job = h.payload["job"]+ self.assertTrue(self._wait_until(+ lambda: self._get(f"/storyboard/edit/render/status?job={job}")+ .payload["state"] != "running", timeout=60))+ s = self._get(f"/storyboard/edit/render/status?job={job}").payload+ self.assertEqual(s["state"], "done", s)+ res = s["result"]+ self.assertEqual(res.get("aspect"), "9:16", res)+ w, h_ = _dims(res["path"])+ self.assertAlmostEqual(w / h_, 9 / 16, delta=0.02)+++class CancelStopsTheEncode(Sandbox):+ def setUp(self):+ super().setUp()+ real_postprocess = panel.run_postprocess_tracked+ self.seen_mux = []++ def slow_real_ffmpeg(cmd, label):+ # A REAL ffmpeg that would run for minutes, through the panel's+ # own tracked runner — the path the assembler really takes.+ long_cmd = ["ffmpeg", "-y", "-loglevel", "error", "-re", "-f", "lavfi",+ "-i", "testsrc2=s=320x180:d=300", "-f", "null", "-"]+ return real_postprocess(long_cmd, label)+ p = mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=slow_real_ffmpeg)+ p.start()+ self.addCleanup(p.stop)++ def test_cancel_kills_the_running_ffmpeg_and_leaves_the_queue_slot_alone(self):+ before_mux = panel.STATE.get("mux_pgid")+ h = self._post("edit/render/start", {"id": "sb_t"})+ job = h.payload["job"]+ # wait until the job has an ffmpeg running+ self.assertTrue(self._wait_until(+ lambda: bool(panel._SB_FILM_JOBS[job].get("pgids")), timeout=10))+ pg = panel._SB_FILM_JOBS[job]["pgids"][0]+ self.assertEqual(panel.STATE.get("mux_pgid"), before_mux) # queue slot untouched+ t0 = time.time()+ c = self._post("edit/render/cancel", {"job": job})+ self.assertTrue(c.payload["ok"])+ self.assertTrue(self._wait_until(+ lambda: self._get(f"/storyboard/edit/render/status?job={job}")+ .payload["state"] != "running", timeout=10))+ self.assertLess(time.time() - t0, 10)+ self.assertEqual(+ self._get(f"/storyboard/edit/render/status?job={job}").payload["state"],+ "canceled")+ # the process group is gone+ with self.assertRaises(ProcessLookupError):+ import os+ os.killpg(pg, 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_integration_leftovers_ui.py b/test_integration_leftovers_ui.pynew file mode 100644index 0000000..8f170d4--- /dev/null+++ b/test_integration_leftovers_ui.py@@ -0,0 +1,188 @@+#!/usr/bin/env python3+"""4.17 integration leftovers, UI half (coordinator follow-up). Each one only+became possible once the editor/board/music packages were combined.++3. The Editor's SLOW flag is a button: clicking it runs Prepare (FILM-39).+4. A song's file extension (and upload / composer prefixes) never becomes a+ board title — server and client.+5. The Music-video pane (song, pictures, roles, last board) survives a reload.+6. Opening a board no longer rewrites the new-film form's shot count/engine.+7. The storyboard row delete sits behind ⋯ and uses the panel's own dialog.++JS is EXECUTED in node against small shims (scripts/extract_panel_js.py), not+grepped, wherever the behaviour is a function's.+"""+from __future__ import annotations++import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+JS = ROOT / "webapp" / "js"+++def _src(name: str) -> str:+ return (JS / name).read_text(encoding="utf-8")+++def _node(script: str):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError(r.stderr[-3000:])+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class TheSlowFlagRunsPrepare(unittest.TestCase):+ def _run(self, prepare_state):+ fn = extract_function("sbeOnTrackDown", _src("editor.js"))+ return _node(fn + f"""+const calls = [];+global.SBE = {{ prepare: {json.dumps(prepare_state)} }};+global.sbEl = () => ({{}}); global.sbeEl = () => ({{}});+global.sbePrepare = () => calls.push('prepare');+global.phosToast = (m) => calls.push('toast');+const flag = {{}};+const ev = {{ preventDefault(){{ calls.push('prevent'); }},+ target: {{ closest: (sel) => sel === '.sbe-slow-flag' ? flag : null }} }};+sbeOnTrackDown(ev);+console.log(JSON.stringify(calls));+""")++ def test_click_runs_prepare(self):+ self.assertEqual(self._run(None), ["prevent", "prepare"])++ def test_click_while_prepare_runs_says_so_instead(self):+ self.assertEqual(self._run({"state": "running"}), ["prevent", "toast"])++ def test_the_slow_flag_is_marked_as_that_button(self):+ self.assertIn('sbe-cl-flag sbe-slow-flag" role="button"', _src("editor.js"))+++class SongTitlesLoseTheirExtension(unittest.TestCase):+ CASES = [("song40.wav", "song40"), ("1790123456789_take_3.mp3", "take 3"),+ ("music_20260929_101500_neon_rain.wav", "neon rain"),+ ("/Users/x/panel_uploads/1790123456789_Café_été.flac", "Café été"),+ ("My Song", "My Song")]++ def test_server(self):+ import panel.routes_music as rm+ for raw, want in self.CASES:+ self.assertEqual(rm._board_title_from_song(raw), want, raw)+ src = (ROOT / "panel" / "routes_music.py").read_text(encoding="utf-8")+ self.assertIn("title = _board_title_from_song(", src)++ def test_client(self):+ fn = extract_function("_songNameFromFile", _src("music.js"))+ got = _node(fn + "\nconsole.log(JSON.stringify(" + json.dumps([c[0] for c in self.CASES])+ + ".map(_songNameFromFile)));")+ self.assertEqual(got, [c[1] for c in self.CASES])+ self.assertIn("|| _songNameFromFile(path);", _src("music.js"))+++class TheMusicVideoBriefSurvivesAReload(unittest.TestCase):+ def test_round_trip_through_storage(self):+ src = _src("music.js")+ consts = "\n".join(re.findall(r"^(?:const MV_DRAFT_KEY|let _mvDraftRestored).*$", src, re.M))+ script = (consts + "\n" + extract_function("mvSaveDraft", src) + "\n"+ + extract_function("mvRestoreDraft", src) + """+const store = {};+global.localStorage = { getItem: k => (k in store ? store[k] : null),+ setItem: (k, v) => { store[k] = String(v); },+ removeItem: k => { delete store[k]; } };+global.MV = { song: '/o/song.wav', songName: 'Neon rain', songSeconds: 184.2, boardId: 'sb_1',+ cast: [{ path: '/u/a.png', name: 'a.png', role: 'singer', prompt: 'close up' },+ { path: '/u/b.png', name: 'b.png', role: '', prompt: '' }], busy: false };+mvSaveDraft();+const saved = JSON.parse(JSON.stringify(MV));+global.MV = { song: null, songName: '', songSeconds: null, cast: [], busy: false, boardId: '' };+mvRestoreDraft();+const restored = { song: MV.song, songName: MV.songName, songSeconds: MV.songSeconds,+ boardId: MV.boardId, cast: MV.cast };+// never over live work, and only once+global.MV = { song: '/o/other.wav', songName: 'x', songSeconds: 1, cast: [], busy: false, boardId: '' };+_mvDraftRestored = false; mvRestoreDraft();+console.log(JSON.stringify({ saved, restored, live: MV.song }));+""")+ out = _node(script)+ s, r = out["saved"], out["restored"]+ for k in ("song", "songName", "songSeconds", "boardId"):+ self.assertEqual(r[k], s[k], k)+ self.assertEqual(r["cast"], s["cast"])+ self.assertEqual(out["live"], "/o/other.wav")++ def test_it_is_restored_on_init_and_saved_on_every_change(self):+ src = _src("music.js")+ init = extract_function("mvInit", src)+ self.assertIn("mvRestoreDraft();", init)+ for fn in ("mvRenderSong", "mvRenderCast", "mvSetPrompt"):+ self.assertIn("mvSaveDraft();", extract_function(fn, src), fn)+++class OpeningABoardLeavesTheNewFilmFormAlone(unittest.TestCase):+ def test_render_plan_does_not_touch_the_brief_length_or_engine(self):+ fn = extract_function("sbRenderPlan", _src("storyboard.js"))+ for bad in ("sbSetShots(", "sbSetTake(", "sbSetEngineMode(", "_sbShots =",+ "_sbEngineMode =", "_sbTake ="):+ self.assertNotIn(bad, fn, bad)+++class BoardRowDeleteIsBehindAMenu(unittest.TestCase):+ def test_rows_carry_a_menu_not_a_bare_delete(self):+ src = _src("storyboard.js")+ script = "\n".join(extract_function(n, src) for n in+ ("sbBoardRowMenu", "sbBoardRow", "sbBoardRowMini")) + """+global.escapeHtml = s => String(s).replace(/&/g,'&').replace(/</g,'<').replace(/"/g,'"');+global.sbFmtAgo = () => ''; global.sbBoardChip = () => ''; global.sbRowAction = () => '';+const b = { id: 'sb_1', title: "Neon's rain", shots: 3, done: 1 };+console.log(JSON.stringify([sbBoardRow(b), sbBoardRowMini(b)]));+"""+ for html in _node(script):+ self.assertIn('class="kebab-pop"', html)+ self.assertIn('role="menuitem"', html)+ # the only path to delete is the menu item+ self.assertEqual(html.count("sbDeleteBoard("), 1)+ item = html[html.index('role="menuitem"'):]+ self.assertIn("sbDeleteBoard(", item)++ def _delete(self, modal_ok: bool):+ fn = extract_function("sbDeleteBoard", _src("storyboard.js"))+ return _node(fn + f"""+const calls = [];+global._phModalShow = (o) => {{ calls.push(['modal', o.tone, o.primaryLabel]);+ if ({json.dumps(modal_ok)}) {{ o.onPrimary(); return true; }} return false; }};+global.confirm = () => {{ calls.push(['confirm']); return true; }};+global.sbDeleteBoardNow = (id) => calls.push(['delete', id]);+sbDeleteBoard('sb_1', 'Night');+console.log(JSON.stringify(calls));+""")++ def test_the_panel_dialog_confirms(self):+ self.assertEqual(self._delete(True),+ [["modal", "danger", "Delete"], ["delete", "sb_1"]])++ def test_a_busy_dialog_falls_back_to_a_confirm_never_to_none(self):+ self.assertEqual(self._delete(False),+ [["modal", "danger", "Delete"], ["confirm"], ["delete", "sb_1"]])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_language_hint_translate.py b/test_language_hint_translate.pynew file mode 100644index 0000000..9c2c753--- /dev/null+++ b/test_language_hint_translate.py@@ -0,0 +1,233 @@+#!/usr/bin/env python3+"""VC-13 [P1] [OPPORTUNITY] Non-English creators get no language guidance,+and Enhance silently translates.++Coordinator ruling, 2026-09-29: "a language hint on the prompt box. Enhance+states that it translated, with a 'Translate to English' toggle."++WHAT THIS GUARDS.+ 1 prompt_looks_non_latin() (server) / promptLooksNonLatin() (client) are+ the SAME signal (same Unicode ranges): CJK, Hangul, Cyrillic, Arabic,+ Hebrew, Thai trigger it; French/Spanish/German-style Latin-script+ accented text does NOT (character-range guessing between Latin-script+ languages would misfire constantly on ordinary text, so this is+ deliberately narrow — see the shared docstring)+ 2 the prompt box's language hint (#langHint) is hidden until+ updateLangHint() sees non-Latin text in the textarea, and carries the+ "Translate to English" toggle (checked by default — unchanged+ behaviour when nobody touches it)+ 3 enhancePrompt() sends the toggle's state as `translate` on every+ request (not just when the hint is showing), defaulting true when+ the element is absent+ 4 the server: /prompt/enhance reads `translate` (default true, "0"/+ "false"/"off" opt out), computes source_non_latin independently, and+ returns both `source_non_latin` and `translated` so the client never+ re-derives what the server already knows+ 5 the helper: translate=False appends a system-prompt addendum telling+ Gemma to keep the ORIGINAL language instead of the base instruction+ to answer in English; translate=True (default) is byte-identical to+ the pre-VC-13 behaviour (no addendum added)+ 6 the Enhance panel (VC-16) shows "Translated to English." up front —+ not buried behind Accept — when the server says it translated+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-langhint-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8329")+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+ROUTES_SRC = (ROOT / "panel" / "routes_queue.py").read_text(encoding="utf-8")+HELPER_SRC = (ROOT / "mlx_warm_helper.py").read_text(encoding="utf-8")+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++# ---------------------------------------------------------------- 1+class TestNonLatinDetection(unittest.TestCase):+ NON_LATIN = [+ "夕暮れの港で彼は今日は大漁だと笑う", # Japanese+ "안녕하세요 오늘 날씨가 좋네요", # Korean+ "Женщина идёт через лес", # Russian/Cyrillic+ "مرحبا بك في هذا المكان", # Arabic+ ]+ LATIN = [+ "A woman walks through a forest",+ "Une femme élégante marche", # French, accented Latin+ "Una mujer camina por el bosque", # Spanish+ "Eine Frau geht durch den Wald", # German+ ]++ def test_server_flags_non_latin_scripts(self):+ for s in self.NON_LATIN:+ self.assertTrue(P.prompt_looks_non_latin(s), s)++ def test_server_does_not_flag_latin_script_languages(self):+ for s in self.LATIN:+ self.assertFalse(P.prompt_looks_non_latin(s), s)++ def test_client_signal_matches_server_ranges_exactly(self):+ fn = extract_function("promptLooksNonLatin", QJS)+ import re+ m = re.search(r"/\[(.+?)\]/\.test", fn)+ self.assertTrue(m)+ client_ranges = m.group(1)+ server_pattern = P._NON_LATIN_SCRIPT_RE.pattern.strip("[]")+ # Same code points, not necessarily byte-identical escaping/order.+ self.assertEqual(+ set(client_ranges.replace("\\u", "").split("-")),+ set(server_pattern.replace("\\u", "").split("-")))+++# ---------------------------------------------------------------- 2 & 6+class TestLangHintMarkup(unittest.TestCase):+ def test_hint_hidden_by_default_with_a_translate_toggle(self):+ i = HTML.index('id="langHint"')+ blk = HTML[i - 30:i + 500]+ self.assertIn("hidden", blk[:60])+ self.assertIn('id="translateToEnglish"', blk)+ self.assertIn("checked", blk)++ def test_textarea_wires_up_the_live_check(self):+ i = HTML.index('id="prompt" class="composer-prompt"')+ blk = HTML[i:i + 400]+ self.assertIn('oninput="updateLangHint()"', blk)++ def test_css_exists(self):+ self.assertIn(".lang-hint", CSS)+ self.assertIn(".lang-hint-toggle", CSS)+++# ---------------------------------------------------------------- 3+class TestEnhancePromptSendsTranslateFlag(unittest.TestCase):+ def test_reads_the_toggle_and_defaults_true(self):+ fn = extract_function("enhancePrompt", QJS)+ self.assertIn("translateToEnglish", fn)+ self.assertIn("!translateEl || translateEl.checked", fn)+ self.assertIn("fd.set('translate'", fn)++ def test_passes_translated_flag_into_the_panel(self):+ fn = extract_function("enhancePrompt", QJS)+ self.assertIn("showEnhancePanel(res.original, res.enhanced, !!res.translated)", fn)+++# ---------------------------------------------------------------- 4+class TestRouteComputesAndReturnsBothFlags(unittest.TestCase):+ def test_translate_default_true_and_opt_out_values(self):+ i = ROUTES_SRC.index('translate = (form.get("translate"')+ line = ROUTES_SRC[i:ROUTES_SRC.index("\n", i)]+ self.assertIn('["1"]', line)+ self.assertIn('"0", "false", "off"', line)++ def test_response_carries_both_fields(self):+ i = ROUTES_SRC.index('"original": user_prompt,')+ blk = ROUTES_SRC[i:i + 400]+ self.assertIn('"source_non_latin": source_non_latin', blk)+ self.assertIn('"translated": bool(source_non_latin and translate)', blk)++ def test_translate_param_reaches_the_helper(self):+ i = ROUTES_SRC.index('"action": "enhance_prompt"')+ blk = ROUTES_SRC[i:i + 400]+ self.assertIn('"translate": translate', blk)+++# ---------------------------------------------------------------- 5+class TestHelperAddendum(unittest.TestCase):+ def test_translate_false_adds_a_same_language_addendum(self):+ i = HELPER_SRC.index('if not translate:')+ blk = HELPER_SRC[i:i + 400]+ self.assertIn("SAME language", blk)+ self.assertIn("Do NOT", blk)+ self.assertIn("translate", blk.lower())++ def test_default_is_true_unchanged_behaviour(self):+ i = HELPER_SRC.index('translate = bool(p.get("translate"')+ line = HELPER_SRC[i:HELPER_SRC.index("\n", i)]+ self.assertIn("True", line)+++# ---------------------------------------------------------------- 6+class TestEnhancePanelShowsTranslatedNote(unittest.TestCase):+ def test_panel_state_machine_with_translated_true(self):+ script = """+class FakeCL { constructor() { this._s = new Set(); } toggle(){} contains(){return false;} }+function makeEl(extra) { return Object.assign({ hidden: true, textContent: '', value: '', dataset: {}, classList: new FakeCL(), events: {},+ addEventListener(t, fn) { this.events[t] = fn; },+ dispatchEvent(ev) { const fn = this.events[ev.type]; if (fn) fn(ev); } }, extra || {}); }+const ELS = {+ enhancePanel: makeEl(), enhanceOriginalText: makeEl(), enhanceEnhancedText: makeEl(),+ enhanceAcceptBtn: makeEl(), enhanceKeepBtn: makeEl(), enhanceUndoBtn: makeEl(),+ enhancePanelNote: makeEl(), prompt: makeEl(),+};+const document = { getElementById: (id) => ELS[id] || null };+%s+%s+%s+showEnhancePanel('日本語のプロンプト', 'A Japanese-language prompt, translated', true);+const afterShow = { note: ELS.enhancePanelNote.textContent, translatedFlag: ELS.enhancePanel.dataset.translated };+acceptEnhance();+const afterAccept = { note: ELS.enhancePanelNote.textContent };+console.log(JSON.stringify({ afterShow, afterAccept }));+""" % (+ extract_function("showEnhancePanel", QJS),+ extract_function("_setPromptValue", QJS),+ extract_function("acceptEnhance", QJS),+ )+ out = _run_node(script)+ self.assertEqual(out["afterShow"]["note"], "Translated to English.")+ self.assertEqual(out["afterShow"]["translatedFlag"], "1")+ self.assertIn("Translated to English.", out["afterAccept"]["note"])+ self.assertIn("Applied.", out["afterAccept"]["note"])++ def test_panel_note_empty_when_not_translated(self):+ script = """+function makeEl(extra) { return Object.assign({ hidden: true, textContent: '', value: '', dataset: {}, classList: { toggle(){}, contains(){return false;} }, events: {},+ addEventListener(t, fn) { this.events[t] = fn; }, dispatchEvent(){} }, extra || {}); }+const ELS = {+ enhancePanel: makeEl(), enhanceOriginalText: makeEl(), enhanceEnhancedText: makeEl(),+ enhanceAcceptBtn: makeEl(), enhanceKeepBtn: makeEl(), enhanceUndoBtn: makeEl(), enhancePanelNote: makeEl(),+};+const document = { getElementById: (id) => ELS[id] || null };+%s+showEnhancePanel('a cat', 'a cat, cinematic', false);+console.log(JSON.stringify({ note: ELS.enhancePanelNote.textContent }));+""" % extract_function("showEnhancePanel", QJS)+ out = _run_node(script)+ self.assertEqual(out["note"], "")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_lipsync_mode.py b/test_lipsync_mode.pynew file mode 100644index 0000000..661002f--- /dev/null+++ b/test_lipsync_mode.py@@ -0,0 +1,604 @@+"""Lip-sync-as-a-first-class-Video-mode (review-2026-09-29-ux, video-advanced+package): findings VA-01/03/04/05/07/14/18/19/20/21/23/24/25/26/27/28/29/30/+31/32/35/36/37/38/39, plus the "Keyframe + lip-sync" build items — anchors+allowlisted, the open-mouth check, and "Continue the song".++Mostly pure-function and structural assertions, matching test_a2v_sync_fixes.py's+own approach: the alternative to a structural check is a real a2v render+(a weights pack, a helper subprocess, 10-25 minutes), and conftest.py's+sandbox does not make that safe to do in a test run. Findings that genuinely+need a GPU render to validate end-to-end (VA-14's scorer wired into a real+a2v render, VA-18's Windows chain, VA-26's Retake, VA-27's preview on a real+a2v/keyframe render, VA-30's multi-part chain, VA-38's resume) are listed in+ledger_lipsync.txt under NEEDS RENDER CHECK with the exact render to run;+this file proves the CODE PATHS are wired, guarded and syntactically sound.+"""++from __future__ import annotations++import ast+import json+import subprocess+import unittest+from pathlib import Path+from tempfile import TemporaryDirectory++import mlx_ltx_panel as P+import storyboard+from panel.routes import GET_ROUTES, POST_ROUTES++ROOT = Path(__file__).resolve().parent+PANEL_SRC = (ROOT / "mlx_ltx_panel.py").read_text()+HELPER_SRC = (ROOT / "mlx_warm_helper.py").read_text()+INDEX_HTML = (ROOT / "webapp" / "index.html").read_text()+CHARACTERS_JS = (ROOT / "webapp" / "js" / "characters.js").read_text()+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text()+BOOT_JS = (ROOT / "webapp" / "js" / "boot.js").read_text()+++def _helper_functions(*names):+ """Exec the named top-level functions of mlx_warm_helper.py in isolation+ (same technique as test_a2v_sync_fixes.py's own helper) — no mlx/ltx+ import needed for functions that only touch dicts, Path and `emit`."""+ tree = ast.parse(HELPER_SRC)+ defs = [n for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name in names]+ assert sorted(d.name for d in defs) == sorted(names), names+ ns: dict = {"Path": Path, "emit": lambda evt: None}+ exec(compile(ast.Module(body=defs, type_ignores=[]), "mlx_warm_helper.py",+ "exec"), ns)+ return ns+++def _ffmpeg_ok() -> bool:+ try:+ subprocess.run([str(P.FFMPEG), "-version"], capture_output=True,+ check=True, timeout=10)+ return True+ except Exception: # noqa: BLE001+ return False+++HAVE_FFMPEG = _ffmpeg_ok()+++def _make_solid_video(path: Path, seconds: float = 1.0, color: str = "gray"):+ subprocess.run(+ [str(P.FFMPEG), "-y", "-loglevel", "error", "-f", "lavfi",+ "-i", f"color=c={color}:s=64x64:d={seconds}:r=10",+ "-pix_fmt", "yuv420p", str(path)],+ check=True, timeout=30)+++def _make_silence(path: Path, seconds: float = 2.5):+ subprocess.run(+ [str(P.FFMPEG), "-y", "-loglevel", "error", "-f", "lavfi",+ "-i", f"anullsrc=r=16000:cl=mono", "-t", str(seconds), str(path)],+ check=True, timeout=30)+++# ---------------------------------------------------------------------------+# Mouth-openness helpers — pure functions, no face in these synthetic inputs,+# so every positive case here is "handles it without crashing and returns+# the documented None", not "measures a real mouth" (that needs a photo).+# ---------------------------------------------------------------------------+class MouthOpennessHelpers(unittest.TestCase):+ def test_mouth_open_ratio_missing_file_is_none(self):+ self.assertIsNone(P.mouth_open_ratio("/no/such/file.png"))++ def test_mouth_open_ratio_no_face_is_none(self):+ with TemporaryDirectory() as td:+ img = Path(td) / "blank.png"+ if not HAVE_FFMPEG:+ self.skipTest("ffmpeg not available")+ subprocess.run(+ [str(P.FFMPEG), "-y", "-loglevel", "error", "-f", "lavfi",+ "-i", "color=c=gray:s=64x64", "-frames:v", "1", str(img)],+ check=True, timeout=30)+ self.assertIsNone(P.mouth_open_ratio(img))++ def test_find_closed_mouth_frame_missing_file_is_none(self):+ self.assertIsNone(P.find_closed_mouth_frame("/no/such/clip.mp4"))++ def test_find_closed_mouth_frame_no_face_is_none(self):+ if not HAVE_FFMPEG:+ self.skipTest("ffmpeg not available")+ with TemporaryDirectory() as td:+ clip = Path(td) / "blank.mp4"+ _make_solid_video(clip)+ self.assertIsNone(P.find_closed_mouth_frame(clip, window_s=0.5))++ def test_extract_frame_png_writes_a_real_file(self):+ if not HAVE_FFMPEG:+ self.skipTest("ffmpeg not available")+ with TemporaryDirectory() as td:+ clip = Path(td) / "src.mp4"+ _make_solid_video(clip, seconds=1.0)+ out = Path(td) / "frame.png"+ ok = P.extract_frame_png(clip, 0.2, out)+ self.assertTrue(ok)+ self.assertTrue(out.exists())+ self.assertGreater(out.stat().st_size, 0)++ def test_extract_frame_png_bad_source_is_false(self):+ with TemporaryDirectory() as td:+ out = Path(td) / "frame.png"+ self.assertFalse(P.extract_frame_png("/no/such/clip.mp4", 0.0, out))+++# ---------------------------------------------------------------------------+# VA-03: /upload probes audio duration.+# ---------------------------------------------------------------------------+class ProbeMediaDuration(unittest.TestCase):+ def test_probe_audio_duration(self):+ if not HAVE_FFMPEG:+ self.skipTest("ffmpeg not available")+ with TemporaryDirectory() as td:+ wav = Path(td) / "clip.wav"+ _make_silence(wav, seconds=2.5)+ dur = P.probe_media_duration(wav)+ self.assertIsNotNone(dur)+ self.assertAlmostEqual(dur, 2.5, delta=0.15)++ def test_probe_missing_file_is_none(self):+ self.assertIsNone(P.probe_media_duration("/no/such/file.wav"))+++# ---------------------------------------------------------------------------+# Anchors: allowlisted on make_job, parsed + clamped in the a2v branch.+# ---------------------------------------------------------------------------+class AnchorsAllowlist(unittest.TestCase):+ def test_make_job_carries_anchors_json(self):+ job = P.make_job({+ "mode": ["a2v"], "prompt": ["a woman sings"],+ "audio": [str(P.AUDIO_DEFAULT)],+ "anchors_json": [json.dumps([{"path": "/x.png", "frame_idx": 0,+ "strength": 1.0}])],+ })+ self.assertIn("anchors_json", job["params"])+ parsed = json.loads(job["params"]["anchors_json"])+ self.assertEqual(parsed[0]["frame_idx"], 0)++ def test_run_job_inner_parses_and_clamps_anchors(self):+ # Structural: the a2v branch must parse anchors_json defensively+ # (never raise on a malformed/stale entry) and clamp frame_idx to+ # [0, frames).+ a2v_branch = PANEL_SRC[PANEL_SRC.index('if mode == "a2v":'):+ PANEL_SRC.index('# T2V / I2V / I2V+clean_audio')]+ self.assertIn("anchors_json", a2v_branch)+ self.assertIn("_idx < 0 or _idx >= frames", a2v_branch)+ self.assertIn('a2v_params["anchors"] = a2v_anchors', a2v_branch)++ def test_helper_anchor_builder_present(self, ):+ # fd2356d, cherry-picked: _a2v_anchor_images in mlx_warm_helper.py.+ helper_src = (ROOT / "mlx_warm_helper.py").read_text()+ self.assertIn("def _a2v_anchor_images(", helper_src)+ self.assertIn('kwargs["images"] = _anchors', helper_src)+++# ---------------------------------------------------------------------------+# VA-05: the A2V prompt law now runs on the manual path too.+# ---------------------------------------------------------------------------+class A2vPromptLawOnManualPath(unittest.TestCase):+ def test_run_job_inner_applies_a2v_prompt(self):+ a2v_branch = PANEL_SRC[PANEL_SRC.index('if mode == "a2v":'):+ PANEL_SRC.index('# T2V / I2V / I2V+clean_audio')]+ self.assertIn("storyboard.a2v_prompt(p[\"prompt\"], silent=False)",+ a2v_branch)+ self.assertIn('"prompt": a2v_safe_prompt', a2v_branch)++ def test_a2v_prompt_strips_stillness_and_adds_contract(self):+ unsafe = "he stands perfectly still, static camera, singing softly"+ safe = storyboard.a2v_prompt(unsafe, silent=False)+ self.assertNotIn("static camera", safe)+ self.assertNotIn("stands perfectly still", safe)+ self.assertIn("lip-sync", safe.lower())++ def test_a2v_prompt_idempotent_on_already_safe_prompt(self):+ # A storyboard/music-video-composed prompt already has the contract —+ # running it through again (which run_job_inner now always does)+ # must not double it or truncate it further.+ once = storyboard.a2v_prompt("a woman sings to camera", silent=False)+ twice = storyboard.a2v_prompt(once, silent=False, max_words=None)+ self.assertEqual(once, twice)+ self.assertEqual(once.count("lip-syncs"), 1)+++# ---------------------------------------------------------------------------+# VA-24: /prompt/enhance accepts mode=a2v and runs the a2v cleanup.+# ---------------------------------------------------------------------------+class EnhanceA2vMode(unittest.TestCase):+ def test_routes_queue_maps_a2v_to_i2v_and_cleans_result(self):+ src = (ROOT / "panel" / "routes_queue.py").read_text()+ fn = src[src.index('def post_prompt_enhance('):+ src.index('\n@post("/run")') if '\n@post("/run")' in src+ else src.index('def post_run(')]+ self.assertIn('a2v_mode = (mode == "a2v")', fn)+ self.assertIn('mode = "i2v"', fn)+ self.assertIn('P.storyboard.a2v_prompt(enhanced, silent=False)', fn)+++# ---------------------------------------------------------------------------+# New routes exist exactly once (test_routes.py covers global uniqueness;+# this just pins that these three specific ones are the a2v/lip-sync trio).+# ---------------------------------------------------------------------------+class NewRoutesRegistered(unittest.TestCase):+ def test_mouth_check_registered(self):+ self.assertIn("/a2v/mouth_check", POST_ROUTES)++ def test_continue_song_registered(self):+ self.assertIn("/a2v/continue_song", POST_ROUTES)++ def test_prompt_check_registered(self):+ self.assertIn("/a2v/prompt_check", POST_ROUTES)+++# ---------------------------------------------------------------------------+# VA-36: outputs carry their render mode; the player swaps Extend for+# "Continue the song" on a2v clips only.+# ---------------------------------------------------------------------------+class OutputRenderMode(unittest.TestCase):+ def test_list_outputs_derives_render_mode(self):+ self.assertIn('render_mode = _rmode', PANEL_SRC)+ self.assertIn('"mode": render_mode,', PANEL_SRC)++ def test_player_swaps_extend_for_continue_song_on_a2v(self):+ self.assertIn("outIsA2v = !!(o && o.mode === 'a2v')", QUEUE_JS)+ self.assertIn("continueSongBtn", QUEUE_JS)+ self.assertIn("async function continueSongFromClip(", QUEUE_JS)+++# ---------------------------------------------------------------------------+# VA-01: a first-class Lip-sync entry on the Video mode bar.+# ---------------------------------------------------------------------------+class LipSyncModeBarEntry(unittest.TestCase):+ def test_chip_present_in_mode_bar(self):+ mode_bar = INDEX_HTML[INDEX_HTML.index('id="modeGroup"'):+ INDEX_HTML.index('id="remixSubGroup"')]+ self.assertIn('data-lipsync="1"', mode_bar)+ self.assertIn('Lip-sync', mode_bar)++ def test_open_lip_sync_entry_defined_and_published(self):+ self.assertIn("function openLipSyncEntry()", CHARACTERS_JS)+ publish_block = CHARACTERS_JS[CHARACTERS_JS.index("Object.assign(globalThis, {"):]+ self.assertIn("openLipSyncEntry", publish_block)++ def test_one_shot_name_not_reused_for_lip_sync_section(self):+ # The folded section used to be titled "One shot (audio → video)",+ # colliding with the top-level One Shot tab.+ self.assertNotIn('cz-title">One shot (audio', INDEX_HTML)+++# ---------------------------------------------------------------------------+# VA-23: Remix → Character (or Image / Train) no longer leaves the Remix+# tool panel lit.+# ---------------------------------------------------------------------------+class RemixSubgroupHiddenOnEarlyReturn(unittest.TestCase):+ def test_setmode_hides_remixbar_before_early_returns(self):+ start = BOOT_JS.index("function setMode(mode) {")+ fn = BOOT_JS[start:start + 8000]+ hide_idx = fn.index("_remixBarEarly")+ train_idx = fn.index("if (mode === 'train')")+ char_idx = fn.index("if (mode === 'character')")+ self.assertLess(hide_idx, train_idx)+ self.assertLess(hide_idx, char_idx)+++# ---------------------------------------------------------------------------+# VA-32: Keyframes default to 3, not 6.+# ---------------------------------------------------------------------------+class KeyframeDefaultCount(unittest.TestCase):+ def test_three_is_selected_by_default(self):+ select = INDEX_HTML[INDEX_HTML.index('id="keyframe_count"'):+ INDEX_HTML.index('</select>', INDEX_HTML.index('id="keyframe_count"'))]+ self.assertIn('value="3" selected', select)+ self.assertNotIn('value="6" selected', select)+++# ---------------------------------------------------------------------------+# VA-37: the dead "Reference audio" row is gone; the API refuses an+# audio-only request instead of silently dropping it.+# ---------------------------------------------------------------------------+class CharactersReferenceAudioDead(unittest.TestCase):+ def test_reference_audio_row_removed(self):+ self.assertNotIn('id="charactersAudioFile"', INDEX_HTML)+ self.assertNotIn('character lip-syncs to this clip', INDEX_HTML)++ def test_routes_characters_refuses_audio_without_image(self):+ src = (ROOT / "panel" / "routes_characters.py").read_text()+ self.assertIn("if audio_path and not image_path:", src)+ self.assertIn("make a mux", src)+++# ---------------------------------------------------------------------------+# VA-19: Q8's audio-strength floor moves off the "off" value.+# ---------------------------------------------------------------------------+class AudioStrengthLaneAwareFloor(unittest.TestCase):+ def test_q8_floor_is_above_the_off_point(self):+ self.assertIn("el.min = isQ4 ? '0.5' : '1.5';", CHARACTERS_JS)+++# ---------------------------------------------------------------------------+# VA-28: One Shot Load Params restores a random-seed take's first part's+# real seed instead of leaving Seed blank.+# ---------------------------------------------------------------------------+class OneShotSeedRestore(unittest.TestCase):+ def test_parts_meta_recorded_in_take_block(self):+ # The whole function (it grew past a fixed 20k-char window once the+ # One Shot resume/recovery wrapper, VA-17, landed around the loop).+ _start = PANEL_SRC.index("def run_take_job_inner(")+ branch = PANEL_SRC[_start:PANEL_SRC.index("\ndef run_job_inner(", _start)]+ self.assertIn("take_part_seeds", branch)+ self.assertIn('"parts_meta": [{"seed_used": s} for s in part_seeds]',+ branch)++ def test_oneshot_js_restores_first_part_seed(self):+ oneshot_js = (ROOT / "webapp" / "js" / "oneshot.js").read_text()+ fn = oneshot_js[oneshot_js.index("function oneshotOpenFromParams("):+ oneshot_js.index("function oneshotOpenFromParams(") + 2500]+ self.assertIn("take.parts_meta", fn)+ self.assertIn("firstPartSeed", fn)+++# ---------------------------------------------------------------------------+# VA-07: a Draft · Final pair for lip-sync — seed-locked, duration slider+# untouched by Draft so Final reuses it at full length.+# ---------------------------------------------------------------------------+class A2vDraftFinal(unittest.TestCase):+ def test_generate_accepts_a_draft_option_and_clamps_frames(self):+ fn = CHARACTERS_JS[CHARACTERS_JS.index("async function audioStudioGenerate("):+ CHARACTERS_JS.index("async function audioStudioGenerate(") + 2200]+ self.assertIn("opts.draft", fn)+ self.assertIn("Math.min(3, dur)", fn)+ self.assertIn("seedEl.value = String(seed)", fn)++ def test_draft_button_present(self):+ self.assertIn('id="audioStudioDraftBtn"', INDEX_HTML)+ self.assertIn("audioStudioGenerate({draft:true})", INDEX_HTML)+++# ---------------------------------------------------------------------------+# VA-14: the lip-sync verdict — scored post-render, CPU-only, guarded.+# ---------------------------------------------------------------------------+class A2vLipsyncVerdict(unittest.TestCase):+ def test_a2v_branch_scores_and_guards(self):+ a2v_branch = PANEL_SRC[PANEL_SRC.index('if mode == "a2v":'):+ PANEL_SRC.index('# T2V / I2V / I2V+clean_audio')]+ self.assertIn("a2v_lipsync_score = None", a2v_branch)+ self.assertIn("take_lipsync_score(out_path)", a2v_branch)+ self.assertIn('"lipsync_score": a2v_lipsync_score,', a2v_branch)+ # Guarded: a scoring exception must not be allowed to propagate and+ # fail an otherwise-finished render.+ idx = a2v_branch.index("a2v_lipsync_score = take_lipsync_score")+ self.assertIn("except Exception", a2v_branch[idx:idx + 600])++ def test_list_outputs_surfaces_the_score(self):+ self.assertIn('lipsync_score = None # a2v', PANEL_SRC)+ self.assertIn('"lipsync_score": lipsync_score,', PANEL_SRC)++ def test_player_renders_the_verdict_chip(self):+ self.assertIn("o.mode === 'a2v' && o.lipsync_score", QUEUE_JS)+ self.assertIn("po-ls-ok", QUEUE_JS)+ css = (ROOT / "webapp" / "style" / "panel.css").read_text()+ self.assertIn(".po-ls-ok", css)+++# ---------------------------------------------------------------------------+# VA-27: live preview threaded onto Keyframe + A2V's stage-1 loops,+# guarded by the SAME _filter_unsupported_kwargs every other kwarg on+# these call sites already goes through.+# ---------------------------------------------------------------------------+class LivePreviewOnKeyframeAndA2v(unittest.TestCase):+ def test_modes_only_list_what_a_real_render_previews(self):+ # 4.17.0 render check: the pinned a2v/keyframe pipelines drop or+ # swallow `live_preview`, so listing them opened a preview slot that+ # never filled. They are held back until the engine supports it.+ self.assertIn(+ 'LTX_LIVE_PREVIEW_MODES = frozenset(("t2v", "i2v", "i2v_clean_audio"))',+ PANEL_SRC)+ self.assertIn(+ 'LTX_LIVE_PREVIEW_PENDING_ENGINE = frozenset(("keyframe", "a2v"))',+ PANEL_SRC)++ def test_a2v_and_keyframe_jobs_get_no_preview_params(self):+ for mode in ("a2v", "keyframe"):+ self.assertEqual(P._live_preview_params({"id": "j-x"}, {"mode": mode}), {})++ def test_keyframe_and_a2v_job_specs_carry_it(self):+ # run_job_inner's own keyframe branch — not the first `if mode ==+ # "keyframe":` in the file (ltx_mode_price_card, VA-11, has one too).+ _rji = PANEL_SRC.index("\ndef run_job_inner(")+ _kf = PANEL_SRC.index('if mode == "keyframe":', _rji)+ kf_branch = PANEL_SRC[_kf:_kf + 8000]+ self.assertIn("**_live_preview_params(job, p)", kf_branch)+ a2v_branch = PANEL_SRC[PANEL_SRC.index('if mode == "a2v":'):+ PANEL_SRC.index('# T2V / I2V / I2V+clean_audio')]+ self.assertIn("**_live_preview_params(job, p)", a2v_branch)++ def test_helper_threads_it_at_all_three_call_sites(self):+ self.assertEqual(HELPER_SRC.count("_thread_live_preview(p, kwargs)"), 3)++ def test_thread_live_preview_is_a_pure_best_effort_function(self):+ ns = _helper_functions("_build_live_preview", "_thread_live_preview")+ # No dir/tae in `p` -> live_preview is None, nothing raises.+ kwargs = {"output_path": "/tmp/x.mp4"}+ ns["_thread_live_preview"]({}, kwargs)+ self.assertIsNone(kwargs["live_preview"])+ # dir/tae present -> the three keys are copied in (the monitor+ # itself may still resolve to None if the checkpoint/dir don't+ # exist — that's _build_live_preview's own guarded behaviour,+ # proven by this call not raising).+ kwargs2 = {"output_path": "/tmp/y.mp4"}+ ns["_thread_live_preview"](+ {"live_preview_dir": "/no/such/dir", "live_preview_tae": "/no/such/tae.safetensors",+ "live_preview_every": 2},+ kwargs2)+ self.assertEqual(kwargs2.get("live_preview_every"), 2)+ self.assertIn("live_preview", kwargs2)+++# ---------------------------------------------------------------------------+# VA-26: segment Retake — the engine's RetakePipeline exposed as a player+# action. NEEDS RENDER CHECK (see ledger_lipsync.txt) for the actual+# pipeline call and the seconds-to-latent-frame math; these tests pin the+# allowlist, the refusal conditions and the guard shape.+# ---------------------------------------------------------------------------+class SegmentRetake(unittest.TestCase):+ def test_make_job_allowlists_retake_fields(self):+ job = P.make_job({+ "mode": ["retake"], "prompt": ["fix the hand"],+ "video_path": ["/x.mp4"],+ "retake_start_sec": ["2.5"], "retake_end_sec": ["4.0"],+ "retake_audio_action": ["regenerate"],+ })+ pr = job["params"]+ self.assertEqual(pr["retake_start_sec"], "2.5")+ self.assertEqual(pr["retake_end_sec"], "4.0")+ self.assertEqual(pr["retake_audio_action"], "regenerate")++ def test_run_job_inner_retake_branch_refuses_before_queueing(self):+ branch = PANEL_SRC[PANEL_SRC.index('if mode == "retake":'):+ PANEL_SRC.index('if mode == "control":')]+ self.assertIn("allows_extend", branch) # same hardware gate as Extend+ self.assertIn("hq_surface_missing()", branch) # same Q8-pack gate+ self.assertIn("retake_end_sec <= retake_start_sec", branch)+ self.assertIn('"action": "retake_segment"', branch)++ def test_helper_action_calls_the_real_pipeline_api_and_is_guarded(self):+ idx = HELPER_SRC.index('if action == "retake_segment":')+ block = HELPER_SRC[idx:idx + 7000]+ self.assertIn("get_pipe(\"extend\"", block)+ self.assertIn("pipe.retake_from_video(", block)+ self.assertIn("except Exception as exc:", block)+ self.assertIn('emit({"event": "error"', block)++ def test_retake_exempted_from_the_distilled_step_count_gate(self):+ self.assertIn(+ 'if mode not in ("extend", "retake", "keyframe", "a2v", "restore", '+ '"ingredients", "control", "upscale") and not ltx_quality_uses_hq(quality) '+ 'and int(p.get("steps", 8)) < 8:',+ PANEL_SRC)++ def test_ui_present(self):+ self.assertIn('id="retakeModal"', INDEX_HTML)+ self.assertIn('id="retakeBtn"', INDEX_HTML)+ self.assertIn("async function submitRetake()", QUEUE_JS)+ self.assertIn("function openRetakeModal(", QUEUE_JS)+++# ---------------------------------------------------------------------------+# VA-18: the Windows off-by-one — window 1 can no longer be overridden from+# the UI, real per-window timing from a pure-function-backed route.+# ---------------------------------------------------------------------------+class SlidingWindowsOffByOne(unittest.TestCase):+ def test_windows_plan_route_registered(self):+ self.assertIn("/ltx/windows_plan", GET_ROUTES)++ def test_windows_plan_matches_the_servers_own_planner(self):+ import ltx_windows as lw+ plan = lw.plan_windows(721)+ self.assertEqual(plan["count"], 7)+ self.assertEqual(plan["windows"][0]["start_sec"], 0.0)++ def test_windows_plan_refuses_a_bad_length_with_400_not_500(self):+ src = (ROOT / "panel" / "routes_queue.py").read_text()+ fn = src[src.index('def get_ltx_windows_plan('):+ src.index('def get_ltx_windows_plan(') + 1400]+ self.assertIn("except ValueError as exc:", fn)+ self.assertIn('h._json({"error": str(exc)}, 400)', fn)++ def test_free_text_textarea_removed_for_a_labelled_slot_list(self):+ self.assertNotIn('id="window_prompts_text"', INDEX_HTML)+ self.assertIn('id="windowsDynamicSlots"', INDEX_HTML)++ def test_index_0_is_always_blank_by_construction(self):+ fn = CHARACTERS_JS[CHARACTERS_JS.index("function _windowsSlotChanged() {"):+ CHARACTERS_JS.index("function _windowsSlotChanged() {") + 700]+ self.assertIn("[''].concat(boxes.map(", fn)++ def test_fetch_is_mode_guarded(self):+ fn = CHARACTERS_JS[CHARACTERS_JS.index("function windowPromptsInput() {"):+ CHARACTERS_JS.index("function windowPromptsInput() {") + 1200]+ self.assertIn("if (tmode !== 'windows') return;", fn)+ self.assertIn("/ltx/windows_plan?frames=", fn)++ def test_docs_cover_ltx_windows(self):+ video_md = (ROOT / "webapp" / "docs" / "video.md").read_text()+ self.assertIn("Sliding windows on LTX", video_md)+++# ---------------------------------------------------------------------------+# VA-30: "Split into N clips" — sequential a2v chain built on Continue the+# song. NEEDS RENDER CHECK (ledger_lipsync.txt) for the real multi-part+# chain; these tests pin the orchestration shape (never loses finished+# parts on a failure, always offers a cancel path).+# ---------------------------------------------------------------------------+class SplitIntoClips(unittest.TestCase):+ def test_split_function_present_and_wired_from_the_cap_warning(self):+ self.assertIn("async function audioStudioSplitIntoClips(capSec)", CHARACTERS_JS)+ self.assertIn("audioStudioSplitIntoClips(", CHARACTERS_JS)+ self.assertIn("audioStudioSplitIntoClips(' + capSec + ')", CHARACTERS_JS)++ def test_a_failed_part_stops_the_chain_without_losing_finished_ones(self):+ fn = CHARACTERS_JS[CHARACTERS_JS.index("async function audioStudioSplitIntoClips("):+ CHARACTERS_JS.index("async function audioStudioGenerate(")]+ self.assertIn("already rendered are safe in Outputs", fn)+ self.assertIn("return;", fn) # stops the loop, doesn't try the next part++ def test_continues_from_the_previous_parts_own_anchor(self):+ fn = CHARACTERS_JS[CHARACTERS_JS.index("async function audioStudioSplitIntoClips("):+ CHARACTERS_JS.index("async function audioStudioGenerate(")]+ self.assertIn("/a2v/continue_song", fn)+ self.assertIn("imagePath = cres.anchor_image", fn)++ def test_stop_button_also_cancels_the_split_loop(self):+ # Stop goes through requestStop (VC-05's confirm) and breaks the+ # split loop only when the user actually stops.+ self.assertIn("requestStop({onStop: audioStudioSplitCancel})", INDEX_HTML)+ queue_js = (ROOT / "webapp" / "js" / "queue.js").read_text()+ fn = queue_js[queue_js.index("function requestStop(opts) {"):]+ fn = fn[:fn.index("\n}\n")]+ # (4.17 SAFETY-3: the stop names the job the dialog was opened for)+ self.assertIn("if (onStop) onStop();\n api('/stop' + jobQ, 'POST')", fn)+++# ---------------------------------------------------------------------------+# VA-38: a Windows chain that fails partway publishes what finished as a+# real, visible clip instead of leaving only hidden working files.+# NEEDS RENDER CHECK (ledger_lipsync.txt) for a real failure scenario.+# ---------------------------------------------------------------------------+class WindowsChainPartialPublish(unittest.TestCase):+ def test_run_windows_chain_wraps_the_loop_and_never_swallows_the_error(self):+ fn = PANEL_SRC[PANEL_SRC.index("def _run_windows_chain("):+ PANEL_SRC.index("def _run_windows_chain(") + 8000]+ self.assertIn("except Exception as exc:", fn)+ self.assertIn("_publish_windows_partial(", fn)+ self.assertIn("raise exc", fn)++ def test_publish_partial_joins_and_marks_visible(self):+ fn = PANEL_SRC[PANEL_SRC.index("def _publish_windows_partial("):+ PANEL_SRC.index("def _publish_windows_partial(") + 3000]+ self.assertNotIn("set_hidden(str(partial_out)", fn) # stays visible, unlike working files+ self.assertIn('"windows_partial":', fn)+ self.assertIn("write_sidecar(", fn)++ def test_recovery_failure_cannot_mask_the_original_error(self):+ # The except-and-republish block itself is guarded — a bug in the+ # publish path must not turn a clear chain-failure error into a+ # confusing one from inside the recovery code.+ idx = PANEL_SRC.index("_publish_windows_partial(job, p, plan, pieces, completed,")+ surrounding = PANEL_SRC[idx - 200:idx + 300]+ self.assertIn("except Exception as pub_exc:", surrounding)++ def test_list_outputs_surfaces_windows_partial(self):+ self.assertIn('windows_partial = None', PANEL_SRC)+ self.assertIn('"windows_partial": windows_partial,', PANEL_SRC)++ def test_player_offers_continue_from_here(self):+ self.assertIn('id="windowsContinueBtn"', INDEX_HTML)+ self.assertIn("function windowsContinueFromPartial(", QUEUE_JS)+ self.assertIn("o.windows_partial", QUEUE_JS)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_loudnorm_ui.py b/test_loudnorm_ui.pynew file mode 100644index 0000000..e432882--- /dev/null+++ b/test_loudnorm_ui.py@@ -0,0 +1,114 @@+#!/usr/bin/env python3+"""FILM-28: the loudness-normalize toggle in the Render popover.++`-14 LUFS` is a fourth, independent delivery axis (server side: `test_deliver.py`,+`test_storyboard_film_integrity.py`). This file locks the client half — the+checkbox exists, persists in the same `phos_deliver` bag as format/size/finish,+survives a repaint, is reflected in the Render button's own label, and is+published so its `onchange` is not a silent no-op in the browser.+"""+from __future__ import annotations++import re+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function, panel_source # noqa: E402++from test_editor_save_integrity import run # noqa: E402++EXTRA = ("sbeDeliverGet", "sbeDeliverPick", "sbeDeliverPaint",+ "sbeDeliverToggleLoudnorm")+++class TheToggle(unittest.TestCase):++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()+ # sbeDeliverGet reads these three module-level const arrays — not+ # functions, so extract_function can't pull them; grab the exact+ # served lines instead of restating the values by hand.+ consts = "\n".join(re.findall(+ r"^const SBE_DELIVER_(?:FORMATS|SIZES|FINISH) = \[.*?\];$",+ cls.src, re.M))+ assert consts.count("const") == 3, consts+ # sbeDeliverPaint also toggles the format/size/finish pill buttons+ # via document.querySelectorAll — irrelevant to this file (that's+ # covered by hand elsewhere the same way every other popover pill+ # is), so it's a no-op query here rather than a full DOM.+ dom_shim = consts + "\nglobal.document = { querySelectorAll: () => [] };\n"+ cls.r = run(r"""+els.sbeRenderBtn = Object.assign(stubEl('sbeRenderBtn'), { textContent: 'Render' });+out.defaultLoudnorm = sbeDeliverGet().loudnorm;+sbeDeliverToggleLoudnorm(true);+out.afterOn = sbeDeliverGet().loudnorm;+out.checkboxAfterOn = els.sbeDeliverLoudnorm.checked;+out.labelOn = els.sbeRenderBtn.textContent;+out.titleOn = els.sbeRenderBtn.title;+sbeDeliverToggleLoudnorm(false);+out.afterOff = sbeDeliverGet().loudnorm;+out.checkboxAfterOff = els.sbeDeliverLoudnorm.checked;+out.labelOff = els.sbeRenderBtn.textContent;+// It rides the SAME bag as format/size/finish — one localStorage key, not two.+sbeDeliverPick('format', 'hevc');+out.survivesOtherPicks = sbeDeliverGet().loudnorm;+sbeDeliverToggleLoudnorm(true);+sbeDeliverPick('size', '1080p');+out.stillOnAfterSizePick = sbeDeliverGet().loudnorm;+out.combinedLabel = els.sbeRenderBtn.textContent;+""", extra=EXTRA, shim=dom_shim)++ def test_off_by_default(self):+ self.assertFalse(self.r["defaultLoudnorm"])++ def test_toggling_flips_the_stored_value_and_the_checkbox(self):+ self.assertTrue(self.r["afterOn"])+ self.assertTrue(self.r["checkboxAfterOn"])+ self.assertFalse(self.r["afterOff"])+ self.assertFalse(self.r["checkboxAfterOff"])++ def test_the_render_button_says_so(self):+ self.assertIn("LUFS", self.r["labelOn"])+ self.assertIn("LUFS", self.r["titleOn"])+ self.assertNotIn("LUFS", self.r["labelOff"])++ def test_it_shares_the_bag_and_survives_other_picks(self):+ self.assertFalse(self.r["survivesOtherPicks"])+ self.assertTrue(self.r["stillOnAfterSizePick"])+ self.assertIn("HEVC", self.r["combinedLabel"])+ self.assertIn("1080", self.r["combinedLabel"])+ self.assertIn("LUFS", self.r["combinedLabel"])++ def test_the_checkbox_exists_in_the_render_popover_and_calls_the_setter(self):+ m = re.search(+ r'<input type="checkbox" id="sbeDeliverLoudnorm"\s+'+ r'onchange="sbeDeliverToggleLoudnorm\(this\.checked\)">', self.src)+ self.assertIsNotNone(m, "loudnorm checkbox markup missing or "+ "not wired to sbeDeliverToggleLoudnorm")+ # It lives in the Deliver-as popover, before the Export-for-NLE+ # separator — same surface as format/size/finish, not a new one.+ pop = self.src[self.src.index('id="sbeDeliverFinish"'):+ self.src.index('id="sbeNleBtn"')]+ self.assertIn('id="sbeDeliverLoudnorm"', pop)++ def test_it_is_published_so_the_onchange_is_not_a_dead_click(self):+ publish = self.src[self.src.index("Object.assign(globalThis, {\n sbeStripY"):]+ publish = publish[:publish.index("});")]+ self.assertRegex(publish, r"\bsbeDeliverToggleLoudnorm\b")++ def test_paint_reads_the_stored_value_into_the_checkbox_on_repaint(self):+ # A repaint (e.g. after opening the popover fresh) must not fight a+ # value the setter already wrote — sbeDeliverPaint has to read the+ # SAME source of truth, not reset it to false.+ fn = extract_function("sbeDeliverPaint", self.src)+ self.assertIn("sbeDeliverLoudnorm", fn)+ self.assertIn("d.loudnorm", fn)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_ltx_finish.py b/test_ltx_finish.pynew file mode 100644index 0000000..d69fcc3--- /dev/null+++ b/test_ltx_finish.py@@ -0,0 +1,297 @@+#!/usr/bin/env python3+"""VC-18/37 — LTX Draft -> Finish, the mirror of H3's "same length, higher+quality" for LTX's own two-axis table (VC-28's honest tier chips).++Coordinator ruling, 2026-09-29 (on the mega-safety cherry-pick + toolbar+pass): "...Draft->Finish for LTX". H3's own Finish was already shipped;+this generalizes the same user concept — commit a draft at higher+quality, same length, same prompt, same seed — to LTX, sharing ONE+toolbar slot (#h3FinishWrap/#h3FinishBtn/#h3FinishTier) between both+engines via a small dispatcher rather than duplicating markup.++WHAT THIS GUARDS.+ 1 list_outputs() lifts an LTX clip's own `quality`/`frames` the same+ way it already lifts H3's `h3_tier` — needed so the Finish+ affordance can gate synchronously from the /status payload, no+ extra /sidecar fetch per gallery click. Only for an actual LTX clip+ (engine None or "ltx"); an H3 or music clip's sidecar `quality`-like+ fields (if any) must never leak into this.+ 2 ltxFinishTargets(): same length, every quality ABOVE the source's,+ offered and available on this install — never a lower or equal rung+ 3 ltxFinishTierKey(): the persisted choice wins when it's still a+ valid target, else the cheapest next rung up (never the most+ expensive by default)+ 4 ltxFinishFieldsFromSidecar(): PURE — carries prompt/seed_used(not+ the submitted -1)/upscale/accel/loras forward, refuses a non-LTX or+ i2v-without-image sidecar, and is scoped to t2v/i2v only (same+ restriction H3's own Finish has — Extend/Keyframe don't carry a+ "same length" concept the way a fixed-duration render does)+ 5 _syncFinishAffordance(): one toolbar slot, dispatches on the+ selected clip's engine — H3 clip re-points onclick/onchange to the+ H3 functions, LTX clip to the LTX functions, anything else hides+ the control entirely+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import time+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-ltxfinish-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8333")+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+EJS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++# A minimal, real-shaped BOOT.ltx fixture: three qualities, one length, so+# the target-selection logic (which quality, never which length) is what's+# under test.+_BOOT_LTX_JS = r"""+const BOOT = { ltx: {+ qualities: [+ { key: 'quick', label: 'Quick', order: 0, width: 640, height: 448, pack: 'q4', pipeline: 'distilled', canvas: '640×448', delivered_canvas: '640×448' },+ { key: 'balanced', label: 'Balanced', order: 1, width: 1024, height: 576, pack: 'q4', pipeline: 'distilled', canvas: '1024×576', delivered_canvas: '1280×720' },+ { key: 'standard', label: 'Standard', order: 2, width: 1280, height: 704, pack: 'q4', pipeline: 'distilled', canvas: '1280×704', delivered_canvas: '1280×704' },+ ],+ lengths: [ { key: '5s', label: '5s', order: 1, seconds: 5, frames: 121, offered: true } ],+ tiers: [+ { key: 'quick_5s', quality: 'quick', quality_label: 'Quick', length: '5s', length_label: '5s', width: 640, height: 448, frames: 121, eta: '~2 min', eta_range: '~2 min', spec: '640×448 · 121f', delivered_spec: '640×448', delivered_differs: false, available: true, offered: true, label: 'Quick · 5s' },+ { key: 'balanced_5s', quality: 'balanced', quality_label: 'Balanced', length: '5s', length_label: '5s', width: 1024, height: 576, frames: 121, eta: '~3 min', eta_range: '~2-3 min', spec: '1024×576 · 121f', delivered_spec: '1280×720', delivered_differs: true, available: true, offered: true, label: 'Balanced · 5s' },+ { key: 'standard_5s', quality: 'standard', quality_label: 'Standard', length: '5s', length_label: '5s', width: 1280, height: 704, frames: 121, eta: '~4 min', eta_range: '~4 min', spec: '1280×704 · 121f', delivered_spec: '1280×704', delivered_differs: false, available: true, offered: true, label: 'Standard · 5s' },+ ],+} };+const _LS = {};+const localStorage = { getItem: (k) => (k in _LS ? _LS[k] : null), setItem: (k, v) => { _LS[k] = v; } };+function escapeHtml(s) { return String(s == null ? '' : s); }+"""+++def _ltx_pure_fns() -> str:+ return "\n".join(extract_function(n, EJS if n == "ltxCellFor" else QJS)+ for n in ("ltxCellFor", "ltxTierByKeyExact",+ "_ltxLengthKeyForFrames", "ltxFinishTargets",+ "ltxFinishTierKey", "ltxFinishFieldsFromSidecar"))+++# ---------------------------------------------------------------- 1+class TestListOutputsLiftsLtxAxes(unittest.TestCase):+ def setUp(self):+ P.OUTPUT.mkdir(parents=True, exist_ok=True)++ def _fixture(self, name, params):+ clip = P.OUTPUT / name+ clip.write_bytes(b"x")+ sidecar = Path(str(clip) + ".json")+ sidecar.write_text(json.dumps({"params": params}))+ old = time.time() - 10+ os.utime(clip, (old, old))+ os.utime(sidecar, (old, old))+ self.addCleanup(lambda: (clip.unlink(missing_ok=True), sidecar.unlink(missing_ok=True)))+ return clip++ def _row(self, clip):+ outs = P.list_outputs()+ return next((o for o in outs if o["path"] == str(clip)), None)++ def test_lifts_quality_and_frames_for_a_plain_ltx_clip(self):+ clip = self._fixture(f"vc37_ltx_{id(self)}.mp4",+ {"mode": "t2v", "quality": "balanced", "frames": 121,+ "prompt": "p", "seed_used": 42})+ row = self._row(clip)+ self.assertIsNotNone(row)+ self.assertEqual(row["quality"], "balanced")+ self.assertEqual(row["frames"], 121)+ self.assertIsNone(row["h3_tier"])++ def test_explicit_ltx_engine_also_lifts(self):+ clip = self._fixture(f"vc37_ltx_explicit_{id(self)}.mp4",+ {"mode": "i2v", "engine": "ltx", "quality": "standard",+ "frames": 121, "prompt": "p"})+ row = self._row(clip)+ self.assertEqual(row["quality"], "standard")+ self.assertEqual(row["frames"], 121)++ def test_h3_clip_does_not_leak_a_quality_value(self):+ clip = self._fixture(f"vc37_h3_{id(self)}.mp4",+ {"mode": "t2v", "engine": "h3", "h3_tier": "standard_5s",+ "prompt": "p"})+ row = self._row(clip)+ self.assertIsNone(row["quality"])+ self.assertIsNone(row["frames"])+ self.assertIsNotNone(row["h3_tier"])++ def test_music_clip_does_not_leak_a_quality_value(self):+ clip = self._fixture(f"vc37_music_{id(self)}.wav",+ {"engine": "music", "quality": "high"})+ Path(str(clip) + ".json").write_text(json.dumps(+ {"engine": "music", "params": {"engine": "music", "quality": "high"}}))+ row = self._row(clip)+ self.assertIsNone(row["quality"])+++# ---------------------------------------------------------------- 2 & 3+class TestFinishTargetsAndDefaultChoice(unittest.TestCase):+ def test_targets_are_every_quality_above_source_same_length(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+const src = ltxCellFor('quick', '5s');+const targets = ltxFinishTargets(src);+console.log(JSON.stringify({ keys: targets.map(t => t.key) }));+"""+ out = _run_node(script)+ self.assertEqual(out["keys"], ["balanced_5s", "standard_5s"])++ def test_top_quality_has_no_targets(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+const src = ltxCellFor('standard', '5s');+console.log(JSON.stringify({ n: ltxFinishTargets(src).length }));+"""+ out = _run_node(script)+ self.assertEqual(out["n"], 0)++ def test_default_choice_is_one_rung_up_not_the_most_expensive(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+const src = ltxCellFor('quick', '5s');+console.log(JSON.stringify({ key: ltxFinishTierKey(src) }));+"""+ out = _run_node(script)+ self.assertEqual(out["key"], "balanced_5s")++ def test_persisted_choice_wins_when_still_valid(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+localStorage.setItem('phos_ltx_finish_quality', 'standard');+const src = ltxCellFor('quick', '5s');+console.log(JSON.stringify({ key: ltxFinishTierKey(src) }));+"""+ out = _run_node(script)+ self.assertEqual(out["key"], "standard_5s")++ def test_persisted_choice_below_source_is_ignored(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+localStorage.setItem('phos_ltx_finish_quality', 'quick');+const src = ltxCellFor('balanced', '5s');+console.log(JSON.stringify({ key: ltxFinishTierKey(src) }));+"""+ out = _run_node(script)+ self.assertEqual(out["key"], "standard_5s") # falls back to the one rung up+++# ---------------------------------------------------------------- 4+class TestFieldsFromSidecar(unittest.TestCase):+ def test_carries_seed_used_not_the_submitted_random(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+const p = { mode: 't2v', prompt: 'a cat', seed: '-1', seed_used: 424242,+ upscale: 'fit_720p', accel: 'turbo', loras: [{path:'/l.safetensors', strength: 0.8}] };+console.log(JSON.stringify(ltxFinishFieldsFromSidecar(p, 'standard_5s')));+"""+ out = _run_node(script)+ self.assertEqual(out["seed"], "424242")+ self.assertEqual(out["quality"], "standard")+ self.assertEqual(out["width"], 1280)+ self.assertEqual(out["upscale"], "fit_720p")+ self.assertEqual(out["accel"], "turbo")+ self.assertEqual(out["loras"][0]["path"], "/l.safetensors")++ def test_refuses_an_h3_sidecar(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+const p = { mode: 't2v', engine: 'h3', prompt: 'a cat' };+console.log(JSON.stringify({ out: ltxFinishFieldsFromSidecar(p, 'standard_5s') }));+"""+ out = _run_node(script)+ self.assertIsNone(out["out"])++ def test_refuses_i2v_with_no_image(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+const p = { mode: 'i2v', prompt: 'a cat' };+console.log(JSON.stringify({ out: ltxFinishFieldsFromSidecar(p, 'standard_5s') }));+"""+ out = _run_node(script)+ self.assertIsNone(out["out"])++ def test_i2v_with_image_carries_it(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+const p = { mode: 'i2v', prompt: 'a cat', image: '/up/ref.png' };+console.log(JSON.stringify(ltxFinishFieldsFromSidecar(p, 'standard_5s')));+"""+ out = _run_node(script)+ self.assertEqual(out["image"], "/up/ref.png")+ self.assertEqual(out["mode"], "i2v")++ def test_refuses_an_unknown_tier_key(self):+ script = _BOOT_LTX_JS + _ltx_pure_fns() + """+const p = { mode: 't2v', prompt: 'a cat' };+console.log(JSON.stringify({ out: ltxFinishFieldsFromSidecar(p, 'nope_5s') }));+"""+ out = _run_node(script)+ self.assertIsNone(out["out"])+++# ---------------------------------------------------------------- 5+class TestSharedDispatcher(unittest.TestCase):+ def test_h3_branch_repoints_the_shared_handlers_and_delegates(self):+ fn = extract_function("_syncFinishAffordance", QJS)+ i = fn.index("if (o && o.engine === 'h3')")+ block = fn[i:fn.index("return;", i) + 8]+ self.assertIn("btn.onclick = h3FinishActive", block)+ self.assertIn("sel.onchange = () => h3FinishSetTier(sel.value)", block)+ self.assertIn("_syncH3FinishAffordance(o)", block)++ def test_ltx_branch_tried_next_then_hides(self):+ fn = extract_function("_syncFinishAffordance", QJS)+ self.assertIn("if (_syncLtxFinishAffordance(o)) return;", fn)+ self.assertIn("wrap.style.display = 'none'", fn)++ def test_ltx_sync_repoints_handlers_too(self):+ fn = extract_function("_syncLtxFinishAffordance", QJS)+ self.assertIn("btn.onclick = ltxFinishActive", fn)+ self.assertIn("sel.onchange = () => ltxFinishSetTier(sel.value)", fn)++ def test_both_real_call_sites_use_the_dispatcher_not_the_h3_only_function(self):+ # The two selection-path call sites must route through the shared+ # dispatcher — calling _syncH3FinishAffordance directly from either+ # would silently drop LTX clips from ever showing Finish.+ for marker in ("_syncFinishAffordance(findOutputByPath(activePath))",+ "_syncFinishAffordance(isPhoto ? null : o)"):+ self.assertIn(marker, QJS, marker)++ def test_toolbar_markup_mentions_both_engines_now(self):+ i = HTML.index('id="h3FinishWrap"')+ blk = HTML[i - 1400:i]+ self.assertIn("BOTH", blk)+ self.assertIn("VC-18/37", blk)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_mega_system_findings.py b/test_mega_system_findings.pynew file mode 100644index 0000000..53c0e06--- /dev/null+++ b/test_mega_system_findings.py@@ -0,0 +1,1008 @@+"""Regression receipts for the 2026-09-29 "system" flow-review package (SYS-*).++Full findings: ~/AI/projects/phosphene/review-2026-09-29-ux/report_system.txt+(outside this repo — PM hub, not shipped). These are lightweight source-level+checks in the style of test_docs_and_shortcuts.py: grep-gate the fix so the+regression can't silently come back, without standing up a whole browser for+every one of ~35 findings. Each test names its finding ID in its docstring.+"""+from __future__ import annotations++import re+from pathlib import Path++ROOT = Path(__file__).resolve().parent+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+HEALTH_JS = (ROOT / "webapp" / "js" / "health.js").read_text(encoding="utf-8")+CHAR_JS = (ROOT / "webapp" / "js" / "characters.js").read_text(encoding="utf-8")+SETTINGS_JS = (ROOT / "webapp" / "js" / "settings.js").read_text(encoding="utf-8")+STAGE_JS = (ROOT / "webapp" / "js" / "stage.js").read_text(encoding="utf-8")+PREVIEW_JS = (ROOT / "webapp" / "js" / "preview.js").read_text(encoding="utf-8")+MAIN_JS = (ROOT / "webapp" / "js" / "main.js").read_text(encoding="utf-8")+PINOKIO_JS = (ROOT / "pinokio.js").read_text(encoding="utf-8")+PANEL_PY = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+++def test_sys08_settings_has_a_models_destination():+ """SYS-08: 'Settings -> Models' pointed nowhere -- Settings had no Models+ section. Assert the Settings modal now has one that opens the real+ Models modal, so every existing 'Settings -> Models' string in error+ copy resolves to something real."""+ settings_modal = HTML[HTML.index('id="settingsModal"'):HTML.index('id="modelsModal"')]+ assert "<h3>Models</h3>" in settings_modal+ assert "openModelsModal()" in settings_modal+++def test_sys09_toast_accepts_string_kind_shorthand():+ """SYS-09: health.js called phosToast(message, 'warn') / (message, 'error')+ -- a bare string where phosToast expected an options object. `opts.kind`+ on a string is undefined (no throw), so these silently rendered as+ neutral info toasts. phosToast must now accept the string shorthand."""+ assert "if (typeof opts === 'string') opts = { kind: opts };" in QUEUE_JS+ assert "warn: 'warning'" in QUEUE_JS+ assert "error: 'danger'" in QUEUE_JS+++def test_sys09_toast_wraps_instead_of_truncating():+ """SYS-09: .phos-toast-msg was white-space:nowrap + ellipsis inside a+ 480px cap -- 20+ literals over 70 chars were cut off mid-sentence.+ Must wrap (multi-line) instead of truncating to one line."""+ m = re.search(r"\.phos-toast \.phos-toast-msg\s*\{([^}]*)\}", CSS)+ assert m, "expected a .phos-toast .phos-toast-msg rule"+ body = m.group(1)+ assert "nowrap" not in body+ assert "text-overflow: ellipsis" not in body+++def test_sys09_toast_has_a_close_control():+ """A duration:0 (persistent) toast had no way to be dismissed -- no close+ button existed at all. Every toast now gets one."""+ assert "phos-toast-close" in QUEUE_JS+ assert ".phos-toast-close" in CSS+++def test_sys09_warning_kind_has_real_styling():+ """kind:'warning' toasts (5 existing call sites in stage.js/queue.js)+ rendered with the neutral info icon and no border tint -- only+ success/danger were ever styled. Warning needs its own look."""+ assert ".phos-toast.phos-toast-warning" in CSS+ assert "ph-warning-fill" in QUEUE_JS+++def test_sys10a_offline_banner_icon_is_inline_svg_not_a_network_image():+ """SYS-10a: the offline banner used <img src="/assets/favicon-64.png">+ -- while offline, that request also fails, so the icon showed a+ broken-image glyph. Must use the already-inlined SVG sprite instead."""+ assert "bar.innerHTML =" in QUEUE_JS+ banner_html = QUEUE_JS[QUEUE_JS.index("bar.innerHTML ="):QUEUE_JS.index("document.body.appendChild(bar)")]+ assert 'src="/assets/favicon-64.png"' not in banner_html+ assert "#ph-warning-fill" in banner_html+++def test_sys10a_generate_disabled_while_offline():+ """SYS-10a: Generate did nothing while offline (uncaught fetch failure,+ no toast, Now stuck on Idle). genBtn must now be gated + the submit+ path must catch the fetch failure instead of leaving it uncaught."""+ assert "_applyOfflineGate" in QUEUE_JS+ assert "offlineBlocked" in QUEUE_JS+ # The submit handler must catch api('/queue/add', ...) failing.+ submit_region = QUEUE_JS[QUEUE_JS.index("await api('/queue/add','POST',fd);"):]+ assert submit_region.startswith("await api('/queue/add','POST',fd);\n } catch (e) {")+++def test_sys10b_training_upload_reports_skipped_and_failed_files():+ """SYS-10b: HEIC files were dropped from the picker with zero message,+ and a 413/error on file N was overwritten by file N+1's progress text+ before anyone could read it. Both must now reach a persistent summary."""+ assert "const rejected = all.filter" in CHAR_JS+ assert "let failed = [];" in CHAR_JS+ assert "skipped: `" in CHAR_JS+ assert "train-status-warn" in CHAR_JS+ assert ".train-status-warn" in CSS+++def test_sys10c_voice_before_images_has_an_inline_error():+ """SYS-10c: dropping a voice clip before any training image produced+ 'nothing on the voice card' -- the only feedback lived in #trainStatus,+ far from the voice card and unstyled. Must show inline on the card."""+ assert "trainVoiceInlineError" in HTML+ assert "_trainVoiceInlineError" in CHAR_JS+ assert ".train-voice-inline-error" in CSS+++def test_sys10d_and_sys37_stop_disabled_when_idle():+ """SYS-10d / SYS-37: Stop was red and clickable with nothing running --+ clicking it was a silent no-op. All six copies (one per tab) must ship+ `disabled` by default and be toggled from poll()."""+ assert HTML.count('class="danger js-stop-btn" disabled') == 6+ assert "stopActive" in QUEUE_JS+ assert "js-stop-btn" in QUEUE_JS+ assert "button.danger:disabled" in CSS+++def test_sys03_train_tab_gates_the_whole_body_under_min_ram():+ """SYS-03: a Mac under TRAIN_MIN_RAM_GB could prepare a whole dataset,+ caption it, and start a 41 GB download before Start refused. The whole+ Train tab body must gate at the entry instead."""+ assert 'id="trainGateCard"' in HTML+ assert "function trainApplyRamGate" in CHAR_JS+ gate_fn = CHAR_JS[CHAR_JS.index("function trainApplyRamGate"):+ CHAR_JS.index("function trainInit")]+ assert "ram < minRam" in gate_fn+ # Codex UI-7: gated by a class on the section (panel.css hides the+ # rest), never by overwriting each child's own `hidden`.+ assert "section.classList.toggle('train-ram-gated', gated)" in gate_fn+ assert "child.hidden = gated" not in gate_fn+ # Called at the top of trainInit, before anything else wires up.+ init_fn = CHAR_JS[CHAR_JS.index("function trainInit"):CHAR_JS.index("function trainInit") + 400]+ assert "if (trainApplyRamGate()) return;" in init_fn+ # Also re-checked every poll, not just on tab-open.+ assert "trainApplyRamGate" in QUEUE_JS+ # Backend supplies the exact numbers the gate compares (no hardcoded+ # threshold duplicated client-side).+ routes_queue_py = (ROOT / "panel" / "routes_queue.py").read_text(encoding="utf-8")+ assert '"ram_gb": round(P.SYSTEM_RAM_GB, 1)' in routes_queue_py+ assert '"train_min_ram_gb": P.TRAIN_MIN_RAM_GB' in routes_queue_py+++def test_sys04_preflight_discloses_one_total_and_downloads_sequentially():+ """SYS-04: the 41 GB cost was disclosed piecemeal (two separate+ Download buttons, no total) and the further 30 GB Q8-to-use-it cost+ wasn't mentioned on this card at all. Must show one total + a+ sequential "Download all" + the Q8 disclosure."""+ assert "Get ready to train: ~${totalGb" in CHAR_JS+ assert "async function trainInstallAll(keys)" in CHAR_JS+ assert "30 GB" in CHAR_JS and "Q8 pack too" in CHAR_JS+ # The sequential download must watch the SPECIFIC key just installed,+ # not "everything missing" -- otherwise step 1 of N never resolves+ # until the last item finishes.+ install_fn = CHAR_JS[CHAR_JS.index("async function trainInstall(key, onDone)"):]+ assert "(d2.required || []).find(m => m.key === key)" in install_fn+++def test_sys12_bug_context_scrubs_home_paths_from_every_log_line():+ """SYS-12, privacy: the bug-report textarea pre-fills from a raw log+ tail, which carries /Users/<username>/... paths -- the username is+ often the person's real name -- straight into a public GitHub issue.+ Must scrub every line, not just truncate to one like the telemetry+ scrubber does."""+ import sys as _sys+ from pathlib import Path as _Path++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import mlx_ltx_panel as P++ scrubbed = P._bug_report_scrub_line(+ "error writing /Users/jane.example/Desktop/panel_uploads/photo.jpg: no space")+ assert "jane.example" not in scrubbed+ assert "<path>" in scrubbed+ # Multi-line tails must keep every line (the telemetry scrubber+ # truncates to the first line, which would gut a 50-line diagnostic).+ routes_meta_py = (ROOT / "panel" / "routes_meta.py").read_text(encoding="utf-8")+ assert "[P._bug_report_scrub_line(line) for line in tail]" in routes_meta_py+++def test_sys12_crash_zip_and_count_filter_to_phosphenes_own_crashes():+ """SYS-12: 'Include latest crash reports' zipped the 5 newest .ips from+ ANY process on the Mac (Safari, Mail, a game) into a Phosphene bug+ report -- an unrelated app's crash tells the maintainer nothing and is+ an unnecessary privacy cost. Must filter to Phosphene's own process+ names, and the displayed count must match what actually gets zipped.+ Codex UI-6 tightened the filter from a file-name prefix to a positive+ identification read out of each report (test_codex_4170_ui pins the+ behaviour); both handlers still share ONE filter."""+ routes_meta_py = (ROOT / "panel" / "routes_meta.py").read_text(encoding="utf-8")+ assert routes_meta_py.count("crash_count = len(_phosphene_crash_reports(diag))") == 1+ assert routes_meta_py.count("ips = _phosphene_crash_reports(diag)[:5]") == 1+++def test_sys12_crash_checkbox_defaults_off():+ """SYS-12: 'Include latest crash reports' was pre-ticked next to a+ Submit button someone could click fast. Zipping real crash logs into a+ public issue should be opt-in per report."""+ bug_modal = HTML[HTML.index('id="bugModal"'):HTML.index('id="bottomPane"')]+ assert '<input id="bugCrashCheck" type="checkbox">' in bug_modal+ assert '<input id="bugCrashCheck" type="checkbox" checked>' not in bug_modal+ assert "document.getElementById('bugCrashCheck').checked = false;" in SETTINGS_JS+++def test_sys40_bug_modal_offers_a_non_github_path():+ """SYS-40: 'Report a bug' assumed a GitHub account and English. Must+ offer a copy-anywhere path and a link to somewhere non-English+ creators already are."""+ assert "function copyBugDiagnostics" in SETTINGS_JS+ assert "onclick=\"copyBugDiagnostics()\"" in HTML+ assert "x.com/PhospheneAI" in HTML+++def test_sys41_train_start_counts_only_past_the_ram_refusal():+ """SYS-41: train_start fired before the RAM refusal, so the fleet's+ train-start count included refused clicks. Must fire only past it,+ with a paired train_refused for the refused clicks."""+ routes_train_py = (ROOT / "panel" / "routes_train.py").read_text(encoding="utf-8")+ refusal_idx = routes_train_py.index("TRAIN_MIN_RAM_GB} GB of memory")+ start_call_idx = routes_train_py.index('P._analytics_feature("train_start")')+ assert start_call_idx > refusal_idx+ assert 'P._analytics_feature("train_refused", "ram")' in routes_train_py+ assert '"train_refused"' in PANEL_PY+++def test_sys21_enhance_button_is_inline_flex_and_version_neutral():+ """SYS-21: #enhanceBtn inherited .ghost-btn's display:block (the file's+ own comment elsewhere documents this exact bug class), so the icon++ label wrapped to two lines in a one-line-tall button. Tooltip also+ named LTX 2.3 while the active engine has been 2.5 since v4.0."""+ assert "#enhanceBtn {" in CSS+ enhance_rule = CSS[CSS.index("#enhanceBtn {"):CSS.index("#enhanceBtn {") + 200]+ assert "inline-flex" in enhance_rule+ enhance_btn_tag = HTML[HTML.index('id="enhanceBtn"') - 20:HTML.index('id="enhanceBtn"') + 200]+ assert "LTX 2.3" not in enhance_btn_tag+ assert 'title="Use Gemma to rewrite your prompt in the style LTX was trained on"' in HTML+++def test_sys21_avoid_toggle_has_a_resting_border():+ """SYS-21: "Avoid +" (.ct-link) had border:1px solid TRANSPARENT, so it+ read as plain text next to the always-bordered No-music/No-voice+ pills right beside it."""+ ct_link_rule = CSS[CSS.index(".ct-link {"):CSS.index(".ct-link:hover")]+ assert "border: 1px solid transparent" not in ct_link_rule+ assert "border: 1px solid var(--border)" in ct_link_rule+++def test_sys38_version_pill_hides_build_internals_at_every_width():+ """SYS-38: branch + short SHA + commit date used to show inline at+ >=1440px ("HEAD - 70665d3 (2026-09-28)") -- developer detail already+ duplicated in the pill's own tooltip."""+ assert "#versionPill .vp-detail { display: none; }" in CSS+ # Must NOT be scoped inside the narrow-width media query only.+ media_block = CSS[CSS.index("@media (max-width: 1400px) {"):+ CSS.index("@media (max-width: 1400px) {") + 300]+ assert "vp-detail" not in media_block+++def test_sys39_model_tag_tooltip_clarifies_clip_vs_engine():+ """SYS-39: the Now-bar model tag follows the SELECTED clip (deliberate+ -- see boot.js's own comment, fixing a worse mis-attribution bug), but+ with no hint of that, switching selection read as "the engine+ changed". Tooltip must say which case it's in."""+ fn = (ROOT / "webapp" / "js" / "boot.js").read_text(encoding="utf-8")+ fn = fn[fn.index("function updateModelCredit"):]+ assert "This clip was rendered with" in fn+ assert "Current engine:" in fn+++def test_sys18_pinokio_q8_menu_entry_gated_by_ram():+ """SYS-18: the Pinokio sidebar's Q8 download entry was offered on+ every Mac regardless of RAM -- 30 GB of disk/bandwidth for a feature+ the panel's own tier table refuses under 48 GB. Same threshold as the+ existing h3Capable()/musicCapable() pattern."""+ pinokio_js = (ROOT / "pinokio.js").read_text(encoding="utf-8")+ assert "function q8Capable()" in pinokio_js+ assert "48 * 1000 * 1000 * 1000" in pinokio_js+ assert "if (!q8_ready && q8Capable())" in pinokio_js+++def test_sys30_reset_and_install_qwen_copy():+ """SYS-30: "Reset" sat one click from "Update" with no explanation of+ what it does (reset.js deletes the engine). "Reinstall image engines"+ showed on a fresh install that never had the pack, implying it broke."""+ pinokio_js = (ROOT / "pinokio.js").read_text(encoding="utf-8")+ assert pinokio_js.count('text: "Reset engine (keeps models & outputs)"') == 3+ assert 'text: "Reset"' not in pinokio_js.replace(+ 'text: "Reset engine (keeps models & outputs)"', '')+ assert "Install/repair image engines" in pinokio_js+++def test_sys15_delta_rms_numbers_move_behind_a_details_disclosure():+ """SYS-15: the Train tab's live preset note led with raw delta_rms+ numbers -- lab jargon a creator can't act on -- while they were still+ choosing a preset. Outcome language up front; numbers under a+ disclosure for anyone who wants them (e.g. filing a bug report)."""+ fn = CHAR_JS[CHAR_JS.index("function trainUpdatePresetNote"):+ CHAR_JS.index("function trainDisableSelectAbove")]+ lead = fn[fn.index("el.innerHTML =\n '<strong>High is the only recipe"):+ fn.index("<details")]+ assert "delta_rms" not in lead+ assert "<details class=\"h3-diag\">" in fn+ assert "delta_rms" in fn # still present, just moved+++def test_sys15_dev_transformer_blurb_is_outcome_language():+ """SYS-15/SYS-42: 'the dev transformer has the right flow-matching+ schedule for LoRA-from-images training' was lab jargon in the Train+ tab's model-download card."""+ assert "flow-matching schedule" not in PANEL_PY+ assert "looks fine in the log and does nothing" in PANEL_PY+++def test_sys33_troubleshooting_covers_the_previously_missing_sections():+ """SYS-33: docs existed but missed several top fleet failures, and+ error cards never linked to the sections that DID exist."""+ troubleshooting = (ROOT / "webapp" / "docs" / "troubleshooting.md").read_text(encoding="utf-8")+ for anchor in ("{#training-failed}", "{#offline}", "{#queue-paused}"):+ assert anchor in troubleshooting+ assert "openDocs('troubleshooting','queue-paused')" in HTML+ assert "docsAnchor: 'memory'" in QUEUE_JS+ assert "docsAnchor: 'gpu-watchdog'" in QUEUE_JS+ assert "docsAnchor: 'training-failed'" in QUEUE_JS+ assert "openDocs('troubleshooting','${docsAnchor}')" in QUEUE_JS+++def test_sys16_first_run_card_exists_and_is_gated_on_the_activation_flag():+ """SYS-16 (priority item): no first-run path -- a fresh 8 GB Mac and a+ 64 GB Studio saw the same empty prompt. BOOT.first_run must reuse the+ SAME flag render_completed's first_render prop already tracks (has+ this install ever finished a render), not a second flag that could+ drift from it."""+ assert '"first_run": not bool(get_settings().get("analytics_first_render_reported"))' in PANEL_PY+ assert 'id="firstRunCard"' in HTML+ # Three starter prompts, each queues directly (one click, per the fix).+ assert HTML.count("first-run-prompt-btn") >= 3+ assert 'onclick="useFirstRunPrompt(this)"' in HTML+ assert "downloadSampleCharacter(); return false;" in HTML+++def test_sys16_first_run_card_hides_on_first_finished_render_or_dismiss():+ """SYS-16: must disappear the moment a render finishes in this session+ (not wait for a page reload) and on manual dismiss, and must be+ re-checked every poll like the other gates in this file."""+ fn = QUEUE_JS[QUEUE_JS.index("function applyFirstRunCard"):+ QUEUE_JS.index("async function dismissFirstRunCard")]+ assert "everFinished" in fn+ assert "j.status === 'done'" in fn+ assert "applyFirstRunCard(s)" in QUEUE_JS+ assert "first_run_card_dismissed" in PANEL_PY+++def test_sys16_starter_prompt_queues_at_a_safe_default():+ """SYS-16: 'each one click to queue at this Mac's safe settings' --+ must force Balanced (not whatever quality/mode happened to be+ selected before) and actually submit, not just fill the field."""+ fn = QUEUE_JS[QUEUE_JS.index("function useFirstRunPrompt"):]+ assert "setQuality('balanced')" in fn+ assert "form.requestSubmit()" in fn+++def test_sys16_train_start_analytics_carries_ram_for_per_tier_funnels():+ """SYS-16: 'track first_queue against first_render per tier' -- the+ reviewer's own finding is that activation is lowest on the machines+ that struggle most, so the funnel needs a hardware signal on+ install_step (first_queue), matching what render_completed+ (first_render) already carries."""+ fn = PANEL_PY[PANEL_PY.index("def _analytics_install_step("):+ PANEL_PY.index("def _analytics_update_outcome(")]+ assert 'props["ram_gb"] = int(round(SYSTEM_RAM_GB))' in fn+ assert "ram_gb" in (ROOT / "docs" / "ANALYTICS.md").read_text(encoding="utf-8")[+ (ROOT / "docs" / "ANALYTICS.md").read_text(encoding="utf-8").index("install_step` (v4.16.0)"):]+++def test_sys25_workflow_tabs_have_tab_semantics():+ """SYS-25: the workflow tab strip was a plain row of <button>s -- 0+ role=tablist, 0 role=tab, 0 aria-selected. A screen reader had no way+ to know it was a tab strip or which tab was active."""+ nav_idx = HTML.index('id="workflowTabs"')+ nav = HTML[nav_idx:HTML.index('</nav>', nav_idx)]+ assert 'role="tablist"' in HTML[nav_idx:nav_idx + 60]+ assert nav.count('role="tab"') == 7+ assert nav.count('aria-selected=') == 7+ editor_js = (ROOT / "webapp" / "js" / "editor.js").read_text(encoding="utf-8")+ assert "b.setAttribute('aria-selected'" in editor_js+++def test_sys25_prompt_textarea_has_a_label():+ """SYS-25: #prompt had no label or aria-label (placeholder only) --+ a placeholder is not an accessible name."""+ assert 'aria-label="Describe your shot"' in HTML+++def test_sys25_hidden_toggle_checkbox_gets_a_visible_focus_ring():+ """SYS-25: 'No music'/'No voice' checkboxes are visually 0x0 (opacity:0,+ width/height:0), so a keyboard Tab put the focus ring on nothing+ visible. :focus-within on the wrapping pill fixes it."""+ assert ".toggle-pill:focus-within" in CSS+++def test_sys25_icon_only_header_buttons_have_static_aria_labels():+ """SYS-25: icon-only buttons had `title` only (tips.js sets it lazily+ on hover/focus) -- no static aria-label for immediate screen-reader+ announcement."""+ for marker in ('id="bugBtn"', 'id="settingsBtn"', 'id="starLink"',+ 'class="phosphene-x-link"'):+ idx = HTML.index(marker)+ tag = HTML[idx:HTML.index(">", idx)]+ assert "aria-label=" in tag, f"missing aria-label near {marker}"+++def test_sys24_generate_button_meets_contrast_floor():+ """SYS-24: white-on-#2f81f7 (the shared --accent token) measured+ 3.75:1 on the Generate button -- below the 4.5:1 AA floor for normal+ text. Scoped to #genBtn specifically."""+ def _contrast(hex1, hex2):+ def lum(h):+ r, g, b = (int(h[i:i+2], 16) for i in (0, 2, 4))+ def f(x):+ x /= 255+ return x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4+ return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b)+ l1, l2 = lum(hex1), lum(hex2)+ l1, l2 = max(l1, l2), min(l1, l2)+ return (l1 + 0.05) / (l2 + 0.05)++ assert "#genBtn { background: #1f6feb" in CSS+ assert _contrast("ffffff", "1f6feb") >= 4.5+ # The hover state must not regress below the resting state's contrast+ # (button.primary:hover brightens toward --accent-bright, which is+ # WORSE against white text).+ m = re.search(r"#genBtn:hover:not\(:disabled\) \{ background: #([0-9a-f]{6})", CSS)+ assert m, "expected a #genBtn hover rule"+ assert _contrast("ffffff", m.group(1)) >= 4.5+++def test_sys24_train_video_link_is_not_invisible_when_visited():+ """SYS-24: this is a same-page href="#" link, so after the first click+ it's :visited and inherits the browser's dull default -- reported as+ 'dark blue on navy, nearly invisible'. Must set explicit color for+ both states."""+ assert ".train-go-video-link,\n .train-go-video-link:visited {" in CSS+++def test_sys35_a_finished_training_announces_itself_with_a_working_action():+ """SYS-35: the only pointer from a finished training back to Video was+ a link at the bottom of the Train tab -- invisible to someone watching+ the Now card for their training to finish. Must announce right where+ completion is already detected, with a real 'make a clip' action."""+ assert "_trainAnnounceReady(j)" in QUEUE_JS+ assert "async function _trainAnnounceReady(job)" in CHAR_JS+ fn = CHAR_JS[CHAR_JS.index("async function _trainAnnounceReady"):+ CHAR_JS.index("function trainUseInVideo")]+ assert "trainUseInVideo(newest.path, newest.trigger, 't2v')" in fn+ assert "duration: 0" in fn # persistent, not a 3-4s toast someone can miss+++def test_sys26_upload_keeps_unicode_filenames():+ """SYS-26: /upload sanitized with [^A-Za-z0-9._-]+ -> "_", ASCII-only --+ a Japanese filename テスト画像_猫.jpg was stored as ____.jpg and+ "Recent uploads" listed it the same way. Must keep the actual+ characters via the shared _unicode_slug."""+ import sys as _sys+ from pathlib import Path as _Path++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import mlx_ltx_panel as P++ orig = P.Path("テスト画像_猫.jpg")+ stem = P._unicode_slug(orig.stem, max_chars=120, fallback="upload")+ assert stem == "テスト画像_猫"+ routes_files_py = (ROOT / "panel" / "routes_files.py").read_text(encoding="utf-8")+ assert 'safe_name = P.re.sub(r"[^A-Za-z0-9._-]+"' not in routes_files_py+ assert "P._unicode_slug(_orig.stem" in routes_files_py+++def test_sys26_descriptive_filename_and_sb_slug_keep_non_latin_scripts():+ """SYS-26/VC-13/FILM-45: _descriptive_filename and _sb_slug were both+ ASCII-only sluggers -- a Japanese or Chinese prompt/title extracted+ zero words and fell to a bare fallback ("t2v", "shot"), so every such+ render/shot in one session shared the same filename stem."""+ import sys as _sys+ from pathlib import Path as _Path++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import mlx_ltx_panel as P++ assert P._descriptive_filename("", "夕暮れの港で彼は笑う", fallback="t2v") == "夕暮れの港で彼は笑う"+ assert P._descriptive_filename("", "Une femme élégante marche", fallback="t2v") == "Une_femme_élégante_marche"+ assert P._unicode_slug("Café été") == "Café_été"+ assert P._sb_slug("夕暮れの港", words=6) != "shot"+ assert P._sb_slug("", words=6) == "shot"+++def test_sys27_speech_detection_and_extraction_cover_cjk_and_french_quotes():+ """SYS-27/FILM-45 (i18n bullet: CJK quotes in speech detection): 「」+ 『』«» were invisible to storyboard.py's speech detector and span+ extractor -- a Japanese or French dialogue line's no_voice defaulted+ to "on" (silent) and the duration-fit check never ran for it."""+ import sys as _sys+ from pathlib import Path as _Path++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import storyboard as sb++ ja = "夕暮れの港で、彼は「今日は大漁だ」と笑う。"+ assert sb.shot_speech_problem(ja) is None # speech IS present -- no problem+ assert sb.spoken_spans(ja) == ["今日は大漁だ"]+ fr = "Elle dit «je reviendrai demain sans faute» avec un sourire."+ assert sb.shot_speech_problem(fr) is None+ assert sb.spoken_spans(fr) == ["je reviendrai demain sans faute"]+ # A bare one-character interjection must not false-positive as+ # multi-word speech (mirrors the existing "2+ words" guard for+ # space-separated scripts).+ assert sb._SPOKEN_WORDS_RE.search("彼は「ん」とうなずいた。") is None+ # English straight-quote path must be unaffected.+ assert sb.shot_speech_problem("A woman says 'I will be right back' now.") is None+++def test_sys27_cjk_word_counting_does_not_undercount_speech_duration():+ """SYS-27/FILM-45: len(text.split()) treated a whole CJK sentence as+ ONE word (no whitespace between characters), so a shot with real+ dialogue was fit to a duration sized for one word -- badly too short.+ Must count CJK characters individually."""+ import sys as _sys+ from pathlib import Path as _Path++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import storyboard as sb++ six_char_phrase = "今日は大漁だ"+ assert len(six_char_phrase.split()) == 1 # the bug, if using split()+ # 4.17 merge: the board package fixed the same FILM-45 counting as+ # storyboard.spoken_word_count; one implementation ships.+ assert sb.spoken_word_count(six_char_phrase) == 6+ assert sb.spoken_word_count("hello there friend") == 3+ panel_py_snip = PANEL_PY[PANEL_PY.index("_spans = storyboard.spoken_spans"):+ PANEL_PY.index("_spans = storyboard.spoken_spans") + 400]+ assert "storyboard.spoken_word_count(x)" in panel_py_snip+++def test_sys27_fullwidth_colon_in_location_parsing():+ """SYS-27 (i18n bullet: ":" in location parsing): a Japanese+ "場所:説明" line used ASCII partition(":") only and lost its+ intended name/description split. Fixed server-side (authoritative)+ and client-side (the live-preview mirror)."""+ import sys as _sys+ from pathlib import Path as _Path++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import mlx_ltx_panel as P++ parsed = P._sb_parse_locations("港:夕暮れの漁港、静かな波の音")+ assert len(parsed) == 1+ assert parsed[0]["name"] == "港"+ assert parsed[0]["description"] == "夕暮れの漁港、静かな波の音"+ storyboard_js = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+ assert "raw.indexOf(':')" in storyboard_js+++def test_sys41_test_rig_flag_fixes_fleet_pollution_at_the_source():+ """SYS-41: the fleet numbers that steer UX were polluted by the owner's+ own test rigs (~410 installs, 64 GB, skewing non-activation from ~32%+ to ~54%), found only by an ad hoc heuristic in sys-fleet/q.py. Must be+ fixed at the source: a flag any dev/gate/clean-room run can set, tagged+ onto every event, documented for future queries to filter on."""+ import os as _os+ import sys as _sys+ from pathlib import Path as _Path+ from unittest import mock as _mock++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import mlx_ltx_panel as P++ assert P._analytics_is_test_rig() is False+ with _mock.patch.dict(_os.environ, {"PHOSPHENE_TEST_RIG": "1"}):+ assert P._analytics_is_test_rig() is True+ # Wired into the single capture choke point, after clean_props (so the+ # whitelist pass cannot drop it).+ capture_fn = PANEL_PY[PANEL_PY.index("def _analytics_capture("):+ PANEL_PY.index("def _analytics_capture(") + 1200]+ assert 'payload["props"]["test_rig"] = True' in capture_fn+ assert "PHOSPHENE_TEST_RIG" in (ROOT / "docs" / "ANALYTICS.md").read_text(encoding="utf-8")+++def test_sys19_health_chip_colors_by_pressure_level_not_used_ratio():+ """SYS-19: the health chip colored by pressure_pct (a USED ratio --+ active+wired+compressed / total), and macOS routinely sits at 75-90%+ "used" by that measure while idle, so the chip read amber/red almost+ all day on 8-16 GB Macs. Must color by the OS's own pressure level+ (kern.memorystatus_vm_pressure_level), and treat elevated pressure as+ normal while a render is actively running."""+ assert '"pressure_level"' in PANEL_PY+ assert "kern.memorystatus_vm_pressure_level" in PANEL_PY+ # plan_memory_policy's existing pressure_pct threshold must be+ # untouched -- this is additive, not a semantic change to a value+ # that also gates real render behavior.+ assert 'pressured = pressure >= 82 or swap_gb >= 4.0' in PANEL_PY+ mem_block = QUEUE_JS[QUEUE_JS.index("const m = s.memory;"):+ QUEUE_JS.index("const m = s.memory;") + 1400]+ assert "m.pressure_level" in mem_block+ assert "rendering" in mem_block+ assert "if (m.pressure_pct > 90)" not in mem_block+++def test_sys19_helper_row_renamed_to_engine_in_plain_language():+ """SYS-19: popover rows read as internal process language ("helper+ idle") rather than what a creator actually wants to know (can I+ render right now)."""+ assert ">Engine</span>" in HTML+ assert "engine ready" in QUEUE_JS+ assert "engine resting" in QUEUE_JS+++def test_sys19_popover_closes_before_its_modals_open():+ """SYS-19: clicking the Tier or Models row inside the still-open health+ popover opened that modal UNDERNEATH the popover."""+ assert "closeHealthPop," in HEALTH_JS+ settings_js = (ROOT / "webapp" / "js" / "settings.js").read_text(encoding="utf-8")+ preview_js = (ROOT / "webapp" / "js" / "preview.js").read_text(encoding="utf-8")+ tier_fn = settings_js[settings_js.index("function openTierModal()"):]+ models_fn = preview_js[preview_js.index("function openModelsModal()"):]+ assert "closeHealthPop()" in tier_fn[:300]+ assert "closeHealthPop()" in models_fn[:300]+++def test_sys29_update_banner_and_pill_self_restart_instead_of_asking():+ """SYS-29: two update mechanisms -- the banner's Update did a git pull+ then told the user to go click Stop then Start in Pinokio themselves,+ right next to panelRestart() (the one-click self-restart already used+ for the stale-process case). Must finish what it started."""+ fn = HEALTH_JS[HEALTH_JS.index("function _ubRestartState"):+ HEALTH_JS.index("async function _ubSaveSetting")]+ assert "panelRestart()" in fn+ assert "requiresFullUpdate" in fn+ pill_fn = HEALTH_JS[HEALTH_JS.index("async function versionPillClick"):+ HEALTH_JS.index("async function versionPillClick") + 1200]+ assert "await panelRestart();" in pill_fn+++def test_sys17_models_card_and_row_order_fixed():+ """SYS-17: "Models ready · 3/12" read as 25% ready (the denominator+ counts every optional add-on); duplicate "Manage models" links; the+ modal listed the previous-generation pack first and the actual+ renderer 8th; descriptions were ellipsis-truncated."""+ settings_js = (ROOT / "webapp" / "js" / "settings.js").read_text(encoding="utf-8")+ assert "Ready to render ✓" in settings_js+ assert "Manage models →" not in settings_js+ preview_js = (ROOT / "webapp" / "js" / "preview.js").read_text(encoding="utf-8")+ assert "const rank = (r) =>" in preview_js+ assert "white-space: normal" in CSS+ models_sub_rule = CSS[CSS.index(".models-list li .meta .sub"):+ CSS.index(".models-list li .meta .sub") + 200]+ assert "ellipsis" not in models_sub_rule+++def test_sys22_shot_setup_jump_opens_closed_details_then_scrolls():+ """SYS-22: Quality/Length lives inside a <details> that starts closed;+ a plain scrollIntoView on hidden content is a silent no-op. Verified+ live in a real browser session (see PR/commit notes) -- this pins the+ two things that made the live bug: opening before scrolling, and NOT+ using 'smooth' (which didn't complete reliably right after a layout+ change in the same gesture)."""+ fn = QUEUE_JS[QUEUE_JS.index("function scrollToShotSetup"):+ QUEUE_JS.index("function applyPackIncompleteGate")]+ assert "details.open = true" in fn+ assert "behavior: 'smooth'" not in fn+ assert "behavior: 'auto'" in fn+ assert 'onclick="scrollToShotSetup()"' in HTML+++def test_sys23_images_and_train_tabs_get_the_same_gutter_as_video():+ """SYS-23: .form-pane's own padding was zeroed and moved onto+ individual direct children -- #genForm (Video) got padding: 0 18px+ back, #studioSection (Images) and #trainSection (Train) never did."""+ gutter_block = CSS[CSS.index(".form-pane > #genForm { padding: 0 18px; }"):+ CSS.index(".form-pane > #genForm { padding: 0 18px; }") + 700]+ assert "#studioSection { padding: 0 18px; }" in gutter_block+ assert "#trainSection { padding: 0 18px; }" in gutter_block+ assert "#firstRunCard { margin: 0 18px 14px; }" in gutter_block+++def test_sys36_train_dataset_copy_no_longer_states_a_hard_max():+ """SYS-36: the counter/hint contradicted itself -- "0 / 50 images" at+ rest, "4 / 500 images" once JS took over (TRAIN_MAX_IMAGES is 500,+ the static markup said 50). Must not assert a specific max at all+ (20-50 is the real sweet spot; 500 is a technical ceiling)."""+ assert "0 / 50 images" not in HTML+ assert "Drop 15-50 images" not in HTML+ assert "20–50 is the sweet spot" in HTML+ assert "n} / ${TRAIN_MAX} images" not in CHAR_JS+++def test_breaker_notice_and_train_gate_card_respect_the_hidden_attribute():+ """Caught in a live browser check, not by source review alone: giving+ .breaker-notice / .train-gate-card a bare `display: flex` rule beats+ the UA stylesheet's `[hidden] { display: none }` at equal specificity+ (whichever rule is later in the cascade wins) -- so+ breakerNotice.hidden = true / trainGateCard.hidden = true left both+ visibly flex'd anyway. This is the exact bug class the review's own+ VC-07/H3-02 findings are about ("CSS lets hidden controls show").+ This codebase already has the fix pattern once+ ([data-spicy-only][hidden] { display: none !important; }); both new+ cards need the same one."""+ assert ".breaker-notice[hidden] { display: none !important; }" in CSS+ assert ".train-gate-card[hidden] { display: none !important; }" in CSS+ # Order matters for readability but not correctness here (!important+ # wins regardless of order against a non-important rule) -- still,+ # keep the guard present for both.+ for selector in (".breaker-notice", ".train-gate-card"):+ rule_start = CSS.index(f"{selector} {{")+ # The plain (non-!important) display:flex rule must exist too --+ # this test protects the co-existence, not just the guard alone.+ assert "display: flex" in CSS[rule_start:rule_start + 100]+++def test_sys32_breaker_reason_reaches_status_and_the_ui():+ """SYS-32: the circuit breaker's reason lived only in a push() log line+ (Logs tab). Must be in STATE, in the /status payload, and rendered as a+ persistent notice above Generate."""+ assert '"paused_reason"' in PANEL_PY+ assert 'STATE["paused_reason"] = (' in PANEL_PY+ routes_queue_py = (ROOT / "panel" / "routes_queue.py").read_text(encoding="utf-8")+ assert '"paused_reason": P.STATE.get("paused_reason")' in routes_queue_py+ assert 'P.STATE["paused_reason"] = None' in routes_queue_py+ assert "breakerNotice" in HTML+ assert "breakerNotice" in QUEUE_JS+++def test_sys07_watchdog_and_oom_get_actionable_copy_and_retry_smaller():+ """SYS-07: the #1 (Metal watchdog) and #3 (jetsam OOM) fleet failures+ asked for a crashlog instead of saying what to change. Must lead with+ what happened + what to try, offer a real "Retry smaller", and demote+ the crashlog ask behind Details."""+ sigkill_region = QUEUE_JS[QUEUE_JS.index("if (rawLower.includes('sigkill'))"):+ QUEUE_JS.index("if (rawLower.includes('sigsegv')")]+ assert "ran out of memory" in sigkill_region+ assert "smaller: true" in sigkill_region+ sigabrt_region = QUEUE_JS[QUEUE_JS.index("if (rawLower.includes('sigabrt'))"):]+ assert "isWatchdog" in sigabrt_region+ assert "ran out of GPU time" in sigabrt_region+ assert "smaller: true" in sigabrt_region+ # The crashlog ask must be demoted to a details/summary disclosure, not+ # inline in the headline hint.+ assert "details: '" in QUEUE_JS or 'details: "' in QUEUE_JS+ assert "Details for troubleshooting</summary>" in QUEUE_JS+ # The server-side half: /queue/retry must accept and act on smaller=1.+ routes_queue_py = (ROOT / "panel" / "routes_queue.py").read_text(encoding="utf-8")+ assert '"smaller"' in routes_queue_py+ assert "ltx_fit_canvas" in routes_queue_py+++def test_sys07_m1_m2_32gb_long_clip_gets_a_real_refusal_not_silence():+ """SYS-07 (priority item): on 32 GB M1/M2 Macs, a long T2V/I2V clip must+ either refuse with a real suggestion or default lighter -- not render+ silently into a watchdog kill. This project chose an explicit refusal+ over a silent downgrade (the app's own "no silent downgrades" rule),+ checked against model_frames (post Long-Clip-Boost/windows) so a clip+ already chunked down small isn't refused for a workload it no longer+ runs in one GPU command buffer."""+ import sys as _sys+ from pathlib import Path as _Path+ from unittest import mock as _mock++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import mlx_ltx_panel as P++ with _mock.patch.object(P, "_HW_CHIP_FAMILY", "M1 Max"), \+ _mock.patch.object(P, "SYSTEM_RAM_GB", 32.0):+ assert P.m1_m2_long_clip_watchdog_refusal("t2v", "balanced", 241) is not None+ assert "watchdog" in P.m1_m2_long_clip_watchdog_refusal("t2v", "balanced", 241).lower()+ # Short clips on the same Mac are unaffected.+ assert P.m1_m2_long_clip_watchdog_refusal("t2v", "balanced", 121) is None+ # HQ two-stage lane is a different denoise shape -- not refused.+ assert P.m1_m2_long_clip_watchdog_refusal("t2v", "high", 241) is None+ # A fast, unaffected chip is never refused, same RAM.+ with _mock.patch.object(P, "_HW_CHIP_FAMILY", "M4 Max"), \+ _mock.patch.object(P, "SYSTEM_RAM_GB", 32.0):+ assert P.m1_m2_long_clip_watchdog_refusal("t2v", "balanced", 241) is None+ # The same chip at a RAM size the reports weren't about is unaffected.+ with _mock.patch.object(P, "_HW_CHIP_FAMILY", "M1 Max"), \+ _mock.patch.object(P, "SYSTEM_RAM_GB", 64.0):+ assert P.m1_m2_long_clip_watchdog_refusal("t2v", "balanced", 241) is None+ # Wired into the real T2V/I2V dispatch path, after windows/Long Clip+ # Boost have had a chance to shrink model_frames.+ assert "m1_m2_long_clip_watchdog_refusal(mode, quality, model_frames)" in PANEL_PY+++def test_sys11_base_pack_gates_generate_before_queueing():+ """SYS-11: a half-installed BASE pack left Generate enabled -- the job+ queued and failed instantly with a Retry button that could never work.+ Must gate client-side, before anything is queued, like the existing+ q8-lane gate does."""+ gate_region = QUEUE_JS[QUEUE_JS.index("function applyPackIncompleteGate"):]+ assert "if (!s.base_available)" in gate_region.split("let cell")[0]+ assert "genBtn.disabled = true" in gate_region.split("let cell")[0]+++def test_sys11_incomplete_model_failure_offers_models_not_a_dead_retry():+ """SYS-11: a plain Retry on an incomplete-model failure re-queues the+ identical job, which fails again the same way. Must swap Retry for an+ action that actually fixes it."""+ assert "action: 'models'" in QUEUE_JS+ assert "action === 'models'" in QUEUE_JS+ assert "openModelsModal()" in QUEUE_JS+++def test_sys11_banner_copy_names_only_what_is_actually_missing():+ """SYS-11: 'Base models needed' always said BOTH base and encoder were+ required even when only one pack had a file missing (Gemma 4 present,+ still named as required). Must filter by what's actually in+ base_missing."""+ assert "const packNeeded = (p) =>" in SETTINGS_JS+ assert "needBase" in SETTINGS_JS and "needEnc" in SETTINGS_JS+ assert '"local_dir": r.get("local_dir")' in PANEL_PY+++def test_sys32_breaker_reason_clears_on_resume():+ """Functional check: post_queue_resume must clear paused_reason so a+ stale breaker notice doesn't survive past the fix + Resume click."""+ import sys as _sys+ from pathlib import Path as _Path+ from unittest import mock as _mock++ _root = _Path(__file__).resolve().parent+ if str(_root) not in _sys.path:+ _sys.path.insert(0, str(_root))+ import mlx_ltx_panel as P+ from panel import routes_queue++ routes_queue.P = P++ class _H:+ def _json(self, payload, status=200):+ self.payload, self.status = payload, status++ fake_state = {"paused": True, "paused_reason": "3 renders failed: boom", "queue": []}+ with _mock.patch.object(P, "STATE", fake_state), \+ _mock.patch.object(P, "persist_queue", lambda: None):+ routes_queue.post_queue_resume(_H(), "/queue/resume", {}, "")+ assert fake_state["paused"] is False+ assert fake_state["paused_reason"] is None+++# ---------------------------------------------------------------------------+# Follow-up round (coordinator: "the owner said 'ship everything'")+# ---------------------------------------------------------------------------++def test_sys13_images_auto_engine_names_the_default_and_its_footprint():+ """SYS-13: the Images tab's 'Auto' engine option just said "(use+ Settings)" -- it never named which engine Auto resolves to or what it+ costs on a Compact Mac. Must name the default (FLUX.2 klein) and its+ first-download size."""+ idx = HTML.index('<option value="auto">Auto')+ tag = HTML[idx:HTML.index("</option>", idx)]+ assert "FLUX.2" in tag+ assert "fits every Mac" in tag+ assert "GB" in tag+++def test_sys14_images_header_leads_with_outcome_not_jargon():+ """SYS-14: the Images tab header was 'Reference image(s) — for+ image-to-image (Reference Edit)' -- jargon before a user has decided+ to use a reference at all. Must lead in plain words."""+ assert "<h2>Make or change a picture" in HTML+++def test_sys14_missing_reference_error_offers_the_text_only_escape_hatch():+ """SYS-14: submitting an engine that composes against a photo with zero+ references said only 'Pick at least 1 reference image' -- no path+ forward for someone who wants to type a prompt instead. Must name the+ text-only engine and how to switch to it."""+ assert "composes against a photo" in STAGE_JS+ assert "switch Engine" in STAGE_JS+ assert "Ideogram 4" in STAGE_JS+++def test_sys13_low_memory_heads_up_reads_free_ram_against_the_engine_need():+ """SYS-13: on a <=24 GB Mac, an image engine that technically 'fits' by+ the hard gate could still starve the render if too much RAM is already+ used. A soft heads-up, not a hard block, using ram_need_gb from+ get_image_engine_status() against LAST_STATUS.memory."""+ assert "engInfo.ram_need_gb" in STAGE_JS+ assert "LAST_STATUS.memory" in STAGE_JS+ assert "softNotice = `Heads up:" in STAGE_JS+++def test_sys18_character_q8_nudge_names_the_floor_instead_of_a_dead_link():+ """SYS-18 (second half): q8_character_install_copy() offered an+ 'Install Q8 (...) ->' link on every Mac, including ones the panel's own+ SYSTEM_CAPS['allows_q8'] gate already refuses Q8 on -- run_job_inner+ would refuse the render regardless, so the link only wasted a 30+ GB+ download. Below the RAM floor it must explain why and drop the CTA,+ using the same gate the Pinokio-side q8Capable() menu fix and the High+ quality chip (SYSTEM_CAPS['allows_q8']) already use."""+ fn = PANEL_PY[PANEL_PY.index("def q8_character_install_copy("):+ PANEL_PY.index("def character_render_quality(")]+ assert 'if not SYSTEM_CAPS.get("allows_q8"):' in fn+ assert "min_ram_gb_for(\"allows_q8\")" in fn+ assert "doesn't have enough memory for it" in fn+ # The gated branch must not offer the same dead CTA the ungated one does.+ gated_branch = fn[fn.index('if not SYSTEM_CAPS.get("allows_q8"):'):+ fn.index("return (\n f\"<b>Trained characters need")]+ assert "openModelsModal" not in gated_branch+++def test_sys25_mode_bar_gets_tab_semantics_via_observer_not_new_call_sites():+ """SYS-25 (second bar): the mode-bar pill group (#modeGroup: T2V / I2V /+ FFLF / Extend) had 0 role=tab / aria-selected, distinct from the+ workflow tabs (#workflowTabs) SYS-25's first pass already covered. Must+ not require editing the ~6 existing .active toggle call sites spread+ across boot.js/characters.js/engines.js/settings.js -- a MutationObserver+ keeps aria-selected synced to whichever site changes .active."""+ idx = HTML.index('id="modeGroup"')+ tag = HTML[HTML.rindex("<div", 0, idx):HTML.index(">", idx) + 1]+ assert 'role="tablist"' in tag+ assert "function _wireModeGroupTabSemantics()" in MAIN_JS+ assert "new MutationObserver" in MAIN_JS+ assert "setAttribute('role', 'tab')" in MAIN_JS+ assert "_wireModeGroupTabSemantics();" in MAIN_JS[MAIN_JS.index("// ====== Init ======"):]+++def test_sys28_settings_leads_with_models_not_codec_presets():+ """SYS-28: Settings used to open on Output format's codec presets ("it+ opens on codec presets with pix_fmt=yuv420p * crf=18 lines"). Models+ (added for SYS-08) must be the first section, with the disk-facing+ Storage/Model-files rows grouped right after it rather than split apart+ by Output format and Memory/speed in between."""+ modal = HTML[HTML.index('id="settingsModal"'):HTML.index('id="tierModal"')]+ for marker in ("<h3>Models</h3>", "<h3>Storage</h3>", "<h3>Model files</h3>",+ "<h3>Memory / speed</h3>", "<h3>Output format</h3>",+ "<h3>API tokens</h3>"):+ assert marker in modal, f"missing {marker}"+ order = [modal.index(m) for m in (+ "<h3>Models</h3>", "<h3>Storage</h3>", "<h3>Model files</h3>",+ "<h3>Memory / speed</h3>", "<h3>Output format</h3>", "<h3>API tokens</h3>")]+ assert order == sorted(order), "Models/Storage/Model files must lead, in that order"+++def test_sys28_hf_token_copy_does_not_contradict_the_models_modal():+ """SYS-28: the HF-token hint claimed 'Control LoRAs' need a token, while+ CURATED_LORAS['union-control'] (mlx_ltx_panel.py) is documented as+ Lightricks' one official UN-GATED IC-LoRA, downloaded token-less at+ install time. The two surfaces must not disagree."""+ hint = HTML[HTML.index('id="hfTestResult"'):HTML.index("</div>", HTML.index('id="hfTestResult"'))]+ assert "Motion Track Control" in hint+ assert "un-gated" in hint+ assert 'CURATED_LORAS["union-control"]' in PANEL_PY+ assert "Un-gated official " in PANEL_PY+ assert "weight — no HF token needed." in PANEL_PY+++def test_sys28_live_preview_note_explains_a_missing_decoder_in_settings_too():+ """SYS-28: the Live-preview select read 'On' whenever the saved+ preference was on, even with the 22 MB TAE decoder missing from disk --+ preview.js already explains this case on the main screen+ (preview_state.reason === 'missing_decoder'); Settings had no+ equivalent."""+ assert 'id="settingsLivePreviewNote"' in HTML+ assert "ps.reason === 'missing_decoder'" in SETTINGS_JS+ assert "needs a 22 MB add-on" in SETTINGS_JS+++def test_sys24_font_size_floor_is_11px_everywhere_in_panel_css():+ """SYS-24: panel.css had 105 literal font-size declarations under 11px+ (36 of 120 visible text nodes were under 11px, 18 under 10px). Every+ literal sub-11px font-size must be gone, and the --fs-2xs token (10px)+ that fed many of them raised to the same floor."""+ assert not re.search(r"font-size:\s*(?:[6-9](?:\.\d+)?|10(?:\.\d+)?)px", CSS)+ assert "--fs-2xs: 11px;" in CSS+++def test_sys42_models_modal_row_hides_repo_path_behind_details():+ """SYS-42: a Models-modal row's always-visible line was+ 'dgrauet/ltx-2.3-mlx-q4 -> mlx_models/ltx-2.3-mlx-q4' -- a repo id and a+ filesystem path ahead of the one thing a non-engineer can act on. The+ outcome line (name/status/blurb) must lead; repo_id/local_dir move+ behind a closed <details>."""+ fn = PREVIEW_JS[PREVIEW_JS.index("async function refreshModelsModal"):+ PREVIEW_JS.index("async function startDownload")]+ row_tpl = fn[fn.index("return `\n <li"):fn.index("}).join('');")]+ assert '<details class="model-row-details">' in row_tpl+ # The outcome line (statusText/blurb) must appear before the details+ # disclosure that carries repo_id -> local_dir.+ assert row_tpl.index("${statusText}") < row_tpl.index('class="model-row-details"')+ assert ".model-row-details" in CSSdiff --git a/test_models_pill_relevance.py b/test_models_pill_relevance.pynew file mode 100644index 0000000..3863f72--- /dev/null+++ b/test_models_pill_relevance.py@@ -0,0 +1,157 @@+"""VC-32 (second half): "models N/M" counts only repos relevant to the+generation actually running, and the pill says "optional missing" in words+instead of a bare fraction once the required set is complete.++WHAT THIS GUARDS. required_files.json lists 12 repos: 2.3's own trio (q4,+gemma, q8), 2.5's trio+add-on (q4_25, gemma4_25, q8_25, hq_25), four IC-LoRA+adapters and the temporal autoencoder. The header pill's "models N/M" used+ALL twelve as the denominator regardless of which generation is active, so+a complete, fully-working 2.5 install with no IC-LoRAs installed read+"models 4/12" — and a correctly GREEN pill (every file the active render+needs is present) still showed a fraction that reads as broken, which is+the "models 10/12 shown green" confusion from the review.++Fixed: relevant_repo_keys() (mlx_ltx_panel.py) scopes the count to the+ACTIVE generation's own base pack + text encoder + High add-on, plus every+repo that isn't claimed by ANY generation (the IC-LoRAs, tae — usable+regardless of which generation is active). /status's repos_ready/+repos_total (routes_queue.py) now report against that set. The pill+(queue.js) shows "models ✓" when nothing relevant is missing, "models ✓ (N+optional not installed)" when the required set is done but extras aren't,+and only falls back to a raw fraction when the REQUIRED set itself is+incomplete (still the urgent, bad-color case).+"""+from __future__ import annotations++import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from urllib.parse import parse_qs, urlencode++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-models-pill-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8319")+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+++class RelevantRepoKeys(unittest.TestCase):+ def test_2_5_excludes_2_3s_own_trio(self):+ keys = P.relevant_repo_keys("ltx25")+ self.assertNotIn("q4", keys)+ self.assertNotIn("gemma", keys)+ self.assertNotIn("q8", keys)++ def test_2_5_includes_its_own_packs(self):+ keys = P.relevant_repo_keys("ltx25")+ for k in ("q4_25", "gemma4_25", "q8_25", "hq_25"):+ self.assertIn(k, keys)++ def test_2_5_includes_version_agnostic_extras(self):+ keys = P.relevant_repo_keys("ltx25")+ for k in ("ic_colorize", "ic_ingredients", "ic_union_control",+ "ic_upscale_x2", "tae"):+ self.assertIn(k, keys)++ def test_2_3_excludes_2_5s_own_trio_and_has_no_addon(self):+ keys = P.relevant_repo_keys("ltx23")+ self.assertNotIn("q4_25", keys)+ self.assertNotIn("gemma4_25", keys)+ self.assertNotIn("hq_25", keys)+ self.assertIn("q4", keys)+ self.assertIn("gemma", keys)+ self.assertIn("q8", keys)++ def test_total_is_nine_not_twelve(self):+ """Pins the exact number the review's own repro would have seen -+ a change to required_files.json that shifts this is worth a+ deliberate look, not a silent drift back toward "everything"."""+ self.assertEqual(len(P.relevant_repo_keys("ltx25")), 9)+++class StatusPayloadUsesTheScopedCount(unittest.TestCase):+ def test_repos_total_matches_relevant_keys_not_all_repos(self):+ all_repos = len(P._repos())+ relevant = len(P.relevant_repo_keys())+ self.assertLess(relevant, all_repos, "the fixture manifest should have irrelevant repos to exclude")+ snap = P.repo_status_list()+ keys = P.relevant_repo_keys()+ scoped = [r for r in snap if r.get("key") in keys]+ self.assertEqual(len(scoped), relevant)+++DOM_SHIM = r"""+function makeEl(id) {+ return { id, innerHTML: '', className: '', title: '',+ classList: { toggle(){}, add(){}, remove(){} } };+}+const ELS = {};+global.document = { getElementById: (id) => (ELS[id] || (ELS[id] = makeEl(id))) };+"""+++class PillTextPhrasing(unittest.TestCase):+ def _run_node(self, script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)++ def _snippet(self) -> str:+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ i = src.rindex("\n", 0, src.index("Models pill — roll-up status")) + 1+ j = src.index("\n }\n", i)+ return src[i:j + 5]++ def _run(self, *, base_available: bool, q8_available: bool, ready: int, total: int) -> str:+ snippet = self._snippet()+ script = DOM_SHIM + f"""+const s = {{ base_available: {json.dumps(base_available)}, q8_available: {json.dumps(q8_available)},+ repos_ready: {ready}, repos_total: {total}, download: null,+ server_now: 0 }};+{snippet}+console.log(JSON.stringify({{ html: ELS.modelsPill.innerHTML }}));+"""+ return self._run_node(script)["html"]++ def test_everything_ready_shows_a_checkmark(self):+ html = self._run(base_available=True, q8_available=True, ready=9, total=9)+ self.assertIn("models ✓", html)+ self.assertNotIn("9/9", html)++ def test_required_done_optional_missing_names_the_count(self):+ html = self._run(base_available=True, q8_available=False, ready=7, total=9)+ self.assertIn("models ✓ (2 optional not installed)", html)++ def test_base_incomplete_still_shows_the_raw_fraction(self):+ """The urgent case (render literally cannot happen) keeps the raw+ count - it's the ONLY case where a fraction is the right shape."""+ html = self._run(base_available=False, q8_available=False, ready=1, total=9)+ self.assertIn("models 1/9", html)+ self.assertNotIn("✓", html)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_song_actions.py b/test_music_song_actions.pyindex d848a67..1347a84 100644--- a/test_music_song_actions.py+++ b/test_music_song_actions.py@@ -226,6 +226,12 @@ class AnActionUsesItsOwnSong(unittest.TestCase):const EL = {};function _el(id) { return EL[id] || (EL[id] = { value: '', textContent: '', innerHTML: '',hidden: false, querySelectorAll: () => [] }); }+// VC-20: songCardRender() now gates on document.body.dataset.workflow —+// these are Music Studio's own actions (restyle/cover/etc), which only+// ever run from the Audio tab, so 'audio' is the correct fixed value here+// (this shim otherwise has no document at all; _el() above is the real+// _el's replacement, not a wrapper around it).+const document = { body: { dataset: { workflow: 'audio' } } };EL.musicStyle = { value: 'punk' }; EL.musicLyrics = { value: '' };EL.musicMaxSeconds = { value: '60' };const said = [];diff --git a/test_music_video.py b/test_music_video.pyindex f2f2b74..1924f24 100644--- a/test_music_video.py+++ b/test_music_video.py@@ -428,6 +428,95 @@ class ThePlan(_Planned, unittest.TestCase):self.plan(images=[])+class BrollPromptsVaryPerSlot(_Planned, unittest.TestCase):+ """FILM-12: "8 shots · 0 singing · 8 B-roll" all shared ONE sentence —+ the same picture cast on consecutive B-roll shots got the exact same+ direction every time, which reads as a loop rather than a film."""++ def test_consecutive_broll_shots_of_the_same_role_get_different_lines(self):+ # All instrumental: every shot is B-roll, cast from a 1-picture pool+ # (IMAGES has one "room" picture and one "singer"; force room-only).+ rows = [dict(r, kind="instrumental") for r in self.sections]+ out = self.plan(sections=rows,+ images=[{"path": "/tmp/mv/room_a.png", "role": "room"}])+ broll = [s for s in out["shots"] if s["music_video"]["kind"] == "broll"]+ self.assertGreaterEqual(len(broll), 3, "need several shots to prove variation")+ prompts = [s["prompt"] for s in broll]+ # Not every prompt is identical — the whole point of the fix.+ self.assertGreater(len(set(prompts)), 1, prompts)+ # Consecutive shots specifically must differ (that's what reads as+ # "the same clip 8 times" to a viewer).+ for a, b in zip(prompts, prompts[1:]):+ self.assertNotEqual(a, b)+ # Still the film's look on every one of them.+ for p in prompts:+ self.assertIn(STYLE, p)++ def test_the_rotation_is_deterministic_across_replans(self):+ rows = [dict(r, kind="instrumental") for r in self.sections]+ images = [{"path": "/tmp/mv/room_a.png", "role": "room"}]+ a = [s["prompt"] for s in self.plan(sections=rows, images=images)["shots"]]+ b = [s["prompt"] for s in self.plan(sections=rows, images=images)["shots"]]+ self.assertEqual(a, b)++ def test_a_pictures_own_typed_line_is_never_overridden_by_a_variant(self):+ rows = [dict(r, kind="instrumental") for r in self.sections]+ images = [{"path": "/tmp/mv/room_a.png", "role": "room",+ "prompt": "the empty stage after the show"}]+ out = self.plan(sections=rows, images=images)+ for s in out["shots"]:+ self.assertIn("the empty stage after the show", s["prompt"])+++class SingingShotsKeepTheStyle(_Planned, unittest.TestCase):+ """FILM-13/14: the style used to be joined onto the line BEFORE the+ 40-word a2v cap, so a long sung line silently deleted the whole style+ suffix — singing shots rendered under different (or no) light from the+ film's B-roll, which is never capped and always keeps it."""++ LONG_LINE = ("she leans into the microphone and closes her eyes, "+ "singing the chorus with her whole chest, one hand "+ "lifted, the room holding its breath around her voice "+ "as the band falls back to let her carry the whole line "+ "alone until the final note fades into silence")++ def test_a_long_sung_line_still_carries_the_style(self):+ self.assertGreaterEqual(len(self.LONG_LINE.split()), storyboard.A2V_MAX_WORDS)+ out = self.plan(images=[+ {"path": "/tmp/mv/singer_a.png", "role": "singer",+ "prompt": self.LONG_LINE}])+ sung = [s for s in out["shots"] if s["music_video"]["kind"] == "singing"]+ self.assertTrue(sung)+ for s in sung:+ self.assertIn(STYLE, s["prompt"], s["prompt"])++ def test_the_line_is_capped_and_the_contract_still_lands_last(self):+ out = self.plan(images=[+ {"path": "/tmp/mv/singer_a.png", "role": "singer",+ "prompt": self.LONG_LINE}])+ sung = [s for s in out["shots"] if s["music_video"]["kind"] == "singing"]+ self.assertTrue(sung)+ for s in sung:+ p = s["prompt"]+ # style survives, AND lands BEFORE the contract (the fix's whole+ # order requirement: line, then style, then contract, last).+ self.assertIn(STYLE, p)+ self.assertIn("lip-sync", p.lower())+ self.assertLess(p.index(STYLE), p.lower().index("lip-sync"))+ # the line was genuinely capped, not smuggled through whole+ self.assertNotIn("until the final note fades into silence", p)++ def test_a_short_sung_line_is_unaffected(self):+ out = self.plan(images=[+ {"path": "/tmp/mv/singer_a.png", "role": "singer",+ "prompt": "she looks up and sings the last line"}])+ sung = [s for s in out["shots"] if s["music_video"]["kind"] == "singing"]+ self.assertTrue(sung)+ for s in sung:+ self.assertIn("she looks up and sings the last line", s["prompt"])+ self.assertIn(STYLE, s["prompt"])++class TheQualityDecidesTheDurationAxis(_Planned, unittest.TestCase):"""The bug the first real film found: a 481-frame a2v shot planned onto a1024×576 board, where LTX dies around frame 454. The planner now knowsdiff --git a/test_music_video_editor.py b/test_music_video_editor.pyindex 1e99ebe..fdc0ba3 100644--- a/test_music_video_editor.py+++ b/test_music_video_editor.py@@ -89,7 +89,15 @@ class MusicVideoOpensOnItsPlan(EditorCase):self.assertEqual((win["start"], win["film_start"]), (0.0, 0.0))self.assertIsNone(win["end"])cuts = sedit.edit_to_cuts(edit)- self.assertEqual([round(c["film_start"], 4) for c in cuts], [0.0, 4.25, 9.5])+ # Shot 2 ends at 4.25 + (5.25 - 1/24) ≈ 9.4583, shot 3 starts at 9.5 —+ # a real, if sub-frame-adjacent, ~1-frame gap between them (bigger+ # than heal_subframe_gaps' half-frame tolerance, so it is not healed+ # on read). FILM-27 fills it with a black slug rather than letting it+ # close silently, so it is now a fourth film_start in the cut list.+ self.assertEqual([round(c["film_start"], 4) for c in cuts],+ [0.0, 4.25, 9.4583, 9.5])+ self.assertEqual([c["kind"] for c in cuts if round(c["film_start"], 4) == 9.4583],+ ["slug"])def test_an_ordinary_board_still_gets_the_auto_editor(self):board = dict(self.board)@@ -101,6 +109,34 @@ class MusicVideoOpensOnItsPlan(EditorCase):FakeHandler().get("/storyboard/edit?id=sb_t")pc.assert_called_once()+ def test_a_reorder_does_not_move_a_singing_shot_off_its_song_position(self):+ # FILM-21: a drag reorder in the board list changes `n` (array+ # order) but never recalculates music_video.film_start — a singing+ # shot was rendered against one exact stretch of the song, and only+ # THAT stretch is where its mouth is on the words. Laying clips out+ # in `n` order (the old bug) would slide shot 3 to film_start 0.0+ # just because it is now first in the array.+ board = storyboard.load_storyboard(self.state, "sb_t")+ # Swap the array positions of shot 1 and shot 3; renumber n to match+ # the new order (exactly what the client's drag-reorder does), but+ # leave every shot's own music_video.film_start/film_end untouched.+ s1, s2, s3 = board["shots"]+ reordered = [dict(s3, n=1), dict(s2, n=2), dict(s1, n=3)]+ board["shots"] = reordered+ storyboard.save_storyboard(self.state, board)+ h = self._get()+ self.assertEqual(h.status, 200, h.payload)+ clips = h.payload["edit"]["clips"]+ by_path = {c["path"]: c for c in clips}+ # Shot 1's clip (the film's FIRST singing shot) still sits at 0.0 —+ # not at the position its new array slot (n=3) would sequentially+ # imply.+ self.assertAlmostEqual(by_path[str(self.clips[0])]["film_start"], 0.0, places=3)+ # Shot 3's clip (the film's SECOND singing shot) still sits at 9.5 —+ # not dragged forward to fill the gap left by array order.+ self.assertAlmostEqual(by_path[str(self.clips[2])]["film_start"], 9.5, places=3)+ self.assertAlmostEqual(by_path[str(self.clips[1])]["film_start"], 4.25, places=3)+if __name__ == "__main__":unittest.main()diff --git a/test_music_video_entrance.py b/test_music_video_entrance.pynew file mode 100644index 0000000..e192245--- /dev/null+++ b/test_music_video_entrance.py@@ -0,0 +1,107 @@+#!/usr/bin/env python3+"""FILM-44: one music-video entrance, not two hidden from each other.++ * mvFillLibrary() only listed songs COMPOSED in-app (engine === 'music')+ — any audio the user already had never appeared. It now lists every+ audio file the gallery knows about.+ * Storyboard's raw Soundtrack path box now signposts the real Music+ Video planner (sbGoToMusicVideo switches to the Audio tab in Music+ Video mode) so a creator who starts in Storyboard can still find it.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+MUSIC_JS = (ROOT / "webapp" / "js" / "music.js").read_text(encoding="utf-8")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _node(script: str) -> str:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return result.stdout+ finally:+ path.unlink(missing_ok=True)+++class TheLibraryListsAnyAudio(unittest.TestCase):+ def test_an_uploaded_track_with_no_music_engine_still_appears(self):+ fn = extract_function("mvFillLibrary", MUSIC_JS)+ script = f"""+'use strict';+function _esc(s) {{ return String(s == null ? '' : s); }}+function _songNameFromFile(name) {{ return String(name || '').replace(/\\.(wav|mp3|m4a|flac|aac|ogg|opus)$/i, ''); }}+const _els = {{}};+function mk(id) {{ return {{ id, innerHTML: '', value: '' }}; }}+function _el(id) {{ if (!_els[id]) _els[id] = mk(id); return _els[id]; }}+globalThis.currentOutputs = [+ {{ kind: 'audio', engine: 'music', name: 'composed.wav', path: '/o/composed.wav', music: {{ title: 'Composed Song' }} }},+ {{ kind: 'audio', engine: 'upload', name: 'my_track.mp3', path: '/u/my_track.mp3' }},+ {{ kind: 'video', engine: 'ltx', name: 'clip.mp4', path: '/o/clip.mp4' }},+];+{fn}+mvFillLibrary();+console.log(_el('mvSongLibrary').innerHTML);+"""+ html = _node(script)+ self.assertIn("Composed Song", html)+ self.assertIn("my_track", html)+ self.assertNotIn("clip.mp4", html)++ def test_no_audio_at_all_says_so_honestly(self):+ fn = extract_function("mvFillLibrary", MUSIC_JS)+ script = f"""+'use strict';+function _esc(s) {{ return String(s == null ? '' : s); }}+function _songNameFromFile(name) {{ return name; }}+const _els = {{}};+function mk(id) {{ return {{ id, innerHTML: '', value: '' }}; }}+function _el(id) {{ if (!_els[id]) _els[id] = mk(id); return _els[id]; }}+globalThis.currentOutputs = [];+{fn}+mvFillLibrary();+console.log(_el('mvSongLibrary').innerHTML);+"""+ html = _node(script)+ self.assertNotIn("Nothing composed", html)+ self.assertIn("outputs or uploads", html)+++class TheSignpostSwitchesToTheRealPlanner(unittest.TestCase):+ def test_sb_go_to_music_video_switches_tab_and_mode(self):+ fn = extract_function("sbGoToMusicVideo", STORYBOARD_JS)+ script = f"""+'use strict';+const calls = [];+globalThis.workflowSwitch = (w) => calls.push(['workflowSwitch', w]);+globalThis.audioModeSet = (m) => calls.push(['audioModeSet', m]);+{fn}+sbGoToMusicVideo();+console.log(JSON.stringify(calls));+"""+ calls = json.loads(_node(script))+ self.assertIn(["workflowSwitch", "audio"], calls)+ self.assertIn(["audioModeSet", "drive"], calls)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_video_role_guess.py b/test_music_video_role_guess.pynew file mode 100644index 0000000..c46c6e3--- /dev/null+++ b/test_music_video_role_guess.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""FILM-12 (client half): a music-video picture's role must be ASKED, not+guessed, past the first (Singer) one.++Before the fix, `mvAddPictures()` defaulted every picture after the first to+role "room" with zero evidence — a photo of a guitar or a piano was silently+mislabelled "the wide, the lights, the audience" and rendered with that+prompt. This extracts the REAL mvAddPictures/mvRenderCast/mvPlan functions+from music.js and runs them in node: an uploaded cast must come back with an+UNSET role past the first picture, and mvPlan() must refuse to submit (and+never reach fetch) while any picture is unlabelled.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+MUSIC_JS = (ROOT / "webapp" / "js" / "music.js").read_text(encoding="utf-8")+FUNCTIONS = ("_el", "mvSay", "mvAddPictures", "mvRenderCast", "mvSetRole",+ "mvPlan", "_mvPlanRequest", "mvSaveDraft")++SHIM = r"""+'use strict';+// 4.17: mvRenderCast saves the brief (mvSaveDraft); node has no storage.+const MV_DRAFT_KEY = 'phos_mv_draft_v1';+global.localStorage = { getItem() { return null; }, setItem() {}, removeItem() {} };+function _esc(s) { return String(s == null ? '' : s); }+const _elMap = {};+function mkEl(id) {+ return { id, textContent: '', innerHTML: '', disabled: false,+ querySelectorAll() { return []; } };+}+globalThis.document = {+ getElementById(id) { if (!_elMap[id]) _elMap[id] = mkEl(id); return _elMap[id]; },+};+globalThis.MV = { song: 'song.wav', songName: 'x', songSeconds: 1, cast: [], busy: false, boardId: '' };+globalThis.workflowSwitch = () => {};+globalThis.sbOpen = async () => {};+const MV_ROLES = [+ ['singer', 'Singer', 'Filmed singing, in sync with the song'],+ ['instrument', 'Instrument', 'B-roll — hands, keys, strings'],+ ['room', 'Room', 'B-roll — the wide, the lights, the audience'],+];+"""+++class TheRoleIsAskedNotGuessed(unittest.TestCase):+ def setUp(self):+ if NODE is None:+ self.skipTest("node not on PATH")+ self.fns = "\n\n".join(extract_function(n, MUSIC_JS) for n in FUNCTIONS)++ def _run(self, tail: str) -> dict:+ script = SHIM + self.fns + "\n" + tail+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True,+ text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return json.loads(result.stdout.strip().splitlines()[-1])+ finally:+ path.unlink(missing_ok=True)++ def test_only_the_first_uploaded_picture_defaults_to_singer(self):+ out = self._run(r"""+globalThis.fetch = () => Promise.resolve({+ ok: true, json: async () => ({ path: '/uploads/' + Math.random() + '.png' }),+});+(async () => {+ await mvAddPictures([{ name: 'a.png' }, { name: 'b.png' }, { name: 'c.png' }]);+ console.log(JSON.stringify({ roles: MV.cast.map(c => c.role) }));+})();+""")+ self.assertEqual(out["roles"], ["singer", "", ""])++ def test_plan_refuses_and_never_calls_the_route_while_a_picture_is_unlabelled(self):+ out = self._run(r"""+globalThis.fetch = (url) => {+ if (String(url).includes('/music/video/plan')) {+ globalThis.__planCalled = true;+ }+ return Promise.resolve({+ ok: true,+ json: async () => (String(url).includes('/upload')+ ? { path: '/uploads/' + Math.random() + '.png' }+ : { ok: true, board_id: 'sb_x', summary: '1 shots', notes: [] }),+ });+};+(async () => {+ await mvAddPictures([{ name: 'a.png' }, { name: 'b.png' }]);+ await mvPlan();+ console.log(JSON.stringify({+ planCalled: !!globalThis.__planCalled,+ status: document.getElementById('mvStatus').textContent,+ needsRoleCount: MV.cast.filter(c => !c.role).length,+ }));+})();+""")+ self.assertFalse(out["planCalled"], "must not plan with an unlabelled picture")+ self.assertIn("role", out["status"])+ self.assertEqual(out["needsRoleCount"], 1)++ def test_plan_proceeds_once_every_picture_has_a_role(self):+ out = self._run(r"""+globalThis.fetch = (url) => {+ if (String(url).includes('/music/video/plan')) globalThis.__planCalled = true;+ return Promise.resolve({+ ok: true,+ json: async () => (String(url).includes('/upload')+ ? { path: '/uploads/' + Math.random() + '.png' }+ : { ok: true, board_id: 'sb_x', summary: '1 shots', notes: [] }),+ });+};+(async () => {+ await mvAddPictures([{ name: 'a.png' }, { name: 'b.png' }]);+ mvSetRole(1, 'room');+ await mvPlan();+ console.log(JSON.stringify({ planCalled: !!globalThis.__planCalled }));+})();+""")+ self.assertTrue(out["planCalled"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_music_video_routes.py b/test_music_video_routes.pyindex 39c1f5b..07d00a0 100644--- a/test_music_video_routes.py+++ b/test_music_video_routes.py@@ -264,6 +264,149 @@ class TheStructureCanBeGiven(unittest.TestCase):self.assertIn(word, h.body["error"])+class TheClassifierMustNotPlanSilentlyAgainstNoVocal(unittest.TestCase):+ """FILM-12: a real track with no voice band and a Singer picture cast+ used to plan straight through to "0 singing shots" with nothing said.+ The route now refuses (409) and hands back the phrases it looked at, so+ the client can mark them — unless the caller already gave `sections`,+ `lyrics`/`score_abc`, or explicitly says `plan_anyway`."""++ def test_a_voiceless_track_with_a_singer_cast_is_refused_not_silently_shot(self):+ with _Fixture() as fx:+ song = (P.UPLOADS / "_mvtest_novoice.wav").resolve()+ click_track(song, bars=24, vocal_bars=()) # no voice band+ try:+ h = _Handler(fx.form(song=str(song))) # a singer IS cast+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 409, h.body)+ self.assertTrue(h.body.get("no_vocal_detected"))+ self.assertTrue(h.body.get("sections"))+ self.assertTrue(all(r["kind"] == "instrumental"+ for r in h.body["sections"]))+ self.assertIn("no singing", h.body["error"])+ finally:+ song.unlink(missing_ok=True)++ def test_plan_anyway_bypasses_the_refusal(self):+ with _Fixture() as fx:+ song = (P.UPLOADS / "_mvtest_novoice2.wav").resolve()+ click_track(song, bars=24, vocal_bars=())+ try:+ h = _Handler(fx.form(song=str(song), plan_anyway="1"))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ self.assertEqual(sum(1 for s in h.body["shots"]+ if s["kind"] == "singing"), 0)+ finally:+ song.unlink(missing_ok=True)++ def test_marking_a_section_vocal_and_resubmitting_as_sections_plans_it(self):+ with _Fixture() as fx:+ song = (P.UPLOADS / "_mvtest_novoice3.wav").resolve()+ click_track(song, bars=24, vocal_bars=())+ try:+ h = _Handler(fx.form(song=str(song)))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 409)+ sections = h.body["sections"]+ sections[0]["kind"] = "vocal" # the user marks one+ h2 = _Handler(fx.form(song=str(song),+ sections=json.dumps(sections)))+ R.post_music_video_plan(h2, "/music/video/plan", {}, "")+ self.assertEqual(h2.status, 200, h2.body)+ self.assertGreater(sum(1 for s in h2.body["shots"]+ if s["kind"] == "singing"), 0)+ finally:+ song.unlink(missing_ok=True)++ def test_a_cast_with_no_singer_is_never_nagged(self):+ # All-instrumental with no Singer picture is a CORRECT plan, not a+ # miss — must not be refused.+ with _Fixture() as fx:+ song = (P.UPLOADS / "_mvtest_novoice4.wav").resolve()+ click_track(song, bars=24, vocal_bars=())+ try:+ images = [im for im in fx.images if im["role"] != "singer"]+ h = _Handler(fx.form(song=str(song), images=json.dumps(images)))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ finally:+ song.unlink(missing_ok=True)++ def test_a_song_with_lyrics_in_the_form_is_never_nagged(self):+ # Lyrics/score are the user's OWN word on which sections sing — the+ # classifier is not even consulted, so there is nothing to warn about.+ with _Fixture() as fx:+ song = (P.UPLOADS / "_mvtest_novoice5.wav").resolve()+ click_track(song, bars=24, vocal_bars=())+ try:+ h = _Handler(fx.form(song=str(song), lyrics=LYRICS, score_abc=SCORE))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ finally:+ song.unlink(missing_ok=True)+++class ReplanningUpdatesTheSameBoard(unittest.TestCase):+ """FILM-43: every re-plan used to mint a brand-new, identically-titled+ board — the board list filled up with duplicates of the same music+ video instead of the plan just updating."""++ def test_a_board_id_naming_an_existing_music_video_board_is_reused(self):+ with _Fixture() as fx:+ h1 = _Handler(fx.form())+ R.post_music_video_plan(h1, "/music/video/plan", {}, "")+ self.assertEqual(h1.status, 200, h1.body)+ first_id = h1.body["board_id"]++ h2 = _Handler(fx.form(board_id=first_id, title="Renamed cut"))+ R.post_music_video_plan(h2, "/music/video/plan", {}, "")+ self.assertEqual(h2.status, 200, h2.body)+ self.assertEqual(h2.body["board_id"], first_id, "re-plan minted a new board")++ boards = storyboard.list_storyboards(P.STATE_DIR)+ self.assertEqual(sum(1 for b in boards if b["id"] == first_id), 1)++ def test_the_original_created_at_survives_a_reused_replan(self):+ with _Fixture() as fx:+ h1 = _Handler(fx.form())+ R.post_music_video_plan(h1, "/music/video/plan", {}, "")+ first_id = h1.body["board_id"]+ before = storyboard.load_storyboard(P.STATE_DIR, first_id)["created_at"]++ h2 = _Handler(fx.form(board_id=first_id))+ R.post_music_video_plan(h2, "/music/video/plan", {}, "")+ after = storyboard.load_storyboard(P.STATE_DIR, first_id)["created_at"]+ self.assertEqual(before, after)++ def test_a_board_id_for_a_non_music_video_board_is_never_reused(self):+ with _Fixture() as fx:+ plain = P.storyboard.new_storyboard("sb_plain_board", "Not a music video")+ P.storyboard.save_storyboard(P.STATE_DIR, plain)+ h = _Handler(fx.form(board_id="sb_plain_board"))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ self.assertNotEqual(h.body["board_id"], "sb_plain_board")+ # the unrelated board is untouched+ self.assertNotIn("music_video",+ P.storyboard.load_storyboard(P.STATE_DIR, "sb_plain_board"))++ def test_an_unknown_board_id_just_plans_a_fresh_board(self):+ with _Fixture() as fx:+ h = _Handler(fx.form(board_id="sb_does_not_exist"))+ R.post_music_video_plan(h, "/music/video/plan", {}, "")+ self.assertEqual(h.status, 200, h.body)+ self.assertNotEqual(h.body["board_id"], "sb_does_not_exist")++ def test_no_board_id_at_all_still_plans_a_fresh_board_as_before(self):+ with _Fixture() as fx:+ h1 = _Handler(fx.form())+ R.post_music_video_plan(h1, "/music/video/plan", {}, "")+ h2 = _Handler(fx.form())+ R.post_music_video_plan(h2, "/music/video/plan", {}, "")+ self.assertNotEqual(h1.body["board_id"], h2.body["board_id"])++class TheShotPromptsAreParsed(unittest.TestCase):def test_both_spellings_mean_the_same_thing(self):diff --git a/test_new_take.py b/test_new_take.pynew file mode 100644index 0000000..1ea5b19--- /dev/null+++ b/test_new_take.py@@ -0,0 +1,158 @@+#!/usr/bin/env python3+"""FILM-22: a rendered ("done") shot can be edited and re-rendered without+going through the LLM Rewrite — which refuses outright while the queue is+non-empty and burns a planner call for what might be "just try again."++`_sb_new_take` is the escape hatch: archive the current clip(s) into+`takes[]` (never delete them), put the shot back to pending with a fresh+seed, and clear its grade. No planner, no LLM, and it works even while+other shots are queued (the route imposes no queue-empty check, unlike+replan-shots).+"""+from __future__ import annotations++import json+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _board(bid, shots):+ return {"schema": 1, "id": bid, "title": "T", "created_at": 1,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "shots": shots}+++class FakeHandler:+ def __init__(self):+ self.status = None+ self.payload = None++ def _json(self, payload, status: int = 200):+ self.payload, self.status = payload, status+++class TheNewTakeFunction(unittest.TestCase):+ def test_the_clip_is_archived_not_deleted(self):+ board = {"shots": [{"n": 1, "status": "done", "seed": 42,+ "draft_output": "/o/s1_draft.mp4",+ "final_output": "/o/s1_final.mp4",+ "grade": "keep"}]}+ shot = panel._sb_new_take(board, 1)+ self.assertIs(shot, board["shots"][0])+ takes = shot["takes"]+ self.assertEqual(len(takes), 2)+ by_pass = {t["pass"]: t for t in takes}+ self.assertEqual(by_pass["draft"]["path"], "/o/s1_draft.mp4")+ self.assertEqual(by_pass["draft"]["seed"], 42)+ self.assertEqual(by_pass["final"]["path"], "/o/s1_final.mp4")+ self.assertIn("at", by_pass["draft"])++ def test_the_shot_is_unlocked_and_reseeded(self):+ board = {"shots": [{"n": 1, "status": "done", "seed": 42,+ "draft_output": "/o/s1.mp4", "grade": "keep",+ "error": "an old error"}]}+ shot = panel._sb_new_take(board, 1)+ self.assertEqual(shot["status"], "pending")+ self.assertIsNone(shot["grade"])+ self.assertNotIn("error", shot)+ self.assertNotIn("draft_output", shot)+ self.assertNotEqual(shot["seed"], 42)+ self.assertIsInstance(shot["seed"], int)++ def test_a_repeat_press_never_reuses_the_same_seed(self):+ board = {"shots": [{"n": 1, "status": "done", "seed": 42,+ "draft_output": "/o/s1.mp4"}]}+ panel._sb_new_take(board, 1)+ seed1 = board["shots"][0]["seed"]+ board["shots"][0]["status"] = "done"+ board["shots"][0]["draft_output"] = "/o/s1_take2.mp4"+ panel._sb_new_take(board, 1)+ seed2 = board["shots"][0]["seed"]+ self.assertNotEqual(seed1, seed2)+ self.assertEqual(len(board["shots"][0]["takes"]), 2)++ def test_prompt_mode_and_music_video_fields_are_untouched(self):+ # Unlike a Rewrite, a New take never touches the shot's creative or+ # structural fields — only its render bookkeeping and seed.+ board = {"shots": [{"n": 1, "status": "done", "seed": 42,+ "draft_output": "/o/s1.mp4", "prompt": "she sings",+ "mode": "a2v", "music_video": {"kind": "singing"},+ "audio": "/x/song.wav"}]}+ shot = panel._sb_new_take(board, 1)+ self.assertEqual(shot["prompt"], "she sings")+ self.assertEqual(shot["mode"], "a2v")+ self.assertEqual(shot["music_video"], {"kind": "singing"})+ self.assertEqual(shot["audio"], "/x/song.wav")++ def test_no_such_shot_returns_none(self):+ board = {"shots": [{"n": 1, "status": "done"}]}+ self.assertIsNone(panel._sb_new_take(board, 9))++ def test_a_shot_with_no_clip_at_all_still_unlocks_cleanly(self):+ board = {"shots": [{"n": 1, "status": "pending", "seed": 5}]}+ shot = panel._sb_new_take(board, 1)+ self.assertEqual(shot["takes"], [])+ self.assertEqual(shot["status"], "pending")+++class TheNewTakeRoute(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def post(self, board_id, n):+ h = FakeHandler()+ panel.Handler._storyboard_post(h, "new-take", "",+ {"id": [board_id], "n": [str(n)]})+ return h++ def test_works_even_while_the_queue_is_busy(self):+ # No claim, no busy check — unlike replan-shots/render, this route+ # never refuses because something else is queued.+ board = self.save(_board("sb_nt", [+ {"n": 1, "status": "done", "seed": 1, "draft_output": "/o/s1.mp4"}]))+ with mock.patch.object(panel, "STATE", {"running": {"id": "x"}, "queue": [{}]}):+ h = self.post("sb_nt", 1)+ self.assertEqual(h.status, 200, h.payload)+ reloaded = storyboard.load_storyboard(self.state, "sb_nt")+ self.assertEqual(reloaded["shots"][0]["status"], "pending")+ self.assertEqual(len(reloaded["shots"][0]["takes"]), 1)++ def test_an_unknown_shot_is_a_404(self):+ board = self.save(_board("sb_nt2", [{"n": 1, "status": "done"}]))+ h = self.post("sb_nt2", 9)+ self.assertEqual(h.status, 404)++ def test_the_reply_carries_the_full_board_payload(self):+ board = self.save(_board("sb_nt3", [+ {"n": 1, "status": "done", "seed": 1, "draft_output": "/o/s1.mp4"}]))+ h = self.post("sb_nt3", 1)+ self.assertTrue(h.payload.get("ok"))+ self.assertEqual(h.payload["board"]["id"], "sb_nt3")+ self.assertEqual(h.payload["board"]["shots"][0]["status"], "pending")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_nle_transitions.py b/test_nle_transitions.pynew file mode 100644index 0000000..3abd5cb--- /dev/null+++ b/test_nle_transitions.py@@ -0,0 +1,260 @@+#!/usr/bin/env python3+"""FCP7/AE export carries dissolves and fade-through-black, the way the render+already does — FCP7-58 (part of the coordinator's "ship everything" pass on+top of FILM-50, which only got overlays/titles through in the first round).++Both exports read the SAME `resolve_transitions()` the render and the+validator already use (storyboard_editor.py): an unrenderable boundary — no+spare source, an unknown clip, a duplicate on one cut — is simply absent from+the project rather than exported as something the render would refuse.++Validated structurally: the FCP7 XML is real XML (parsed with+xml.etree.ElementTree, not string-matched), the transitionitem sits between+the right two clipitems, and its duration is the same one the render clamps+to. The AE script has no importable transition object, so it is checked as+opacity keyframes on the right layers at the right times instead.+"""+from __future__ import annotations++import sys+import unittest+import xml.etree.ElementTree as ET+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import storyboard_editor as sedit # noqa: E402+++def _pair(kind="dissolve", duration=1.0, a_id="a", b_id="b"):+ """Two 10s-source clips, cut at film second 4. `a` is trimmed 0-4s of its+ 10s source (6s of spare TAIL beyond its out-point); `b` is trimmed 1-5s+ (1s of spare HEAD before its in-point, plenty for a <=1s transition) —+ real handles on both sides of the cut for a transition to draw from."""+ a = sedit.new_clip("/x/a.mp4", 0.0, 4.0, 0.0, id=a_id, duration=10.0)+ b = sedit.new_clip("/x/b.mp4", 1.0, 5.0, 4.0, id=b_id, duration=10.0)+ clips = [a, b]+ transitions = [{"id": "t1", "after_clip": a_id, "kind": kind,+ "duration": duration}]+ return clips, transitions+++def _segs(clips):+ return sedit._nle_segments(clips)+++class TheResolvedMap(unittest.TestCase):+ def test_a_real_transition_resolves_into_both_sides(self):+ clips, transitions = _pair()+ m = sedit._nle_transitions(clips, transitions, fps=24)+ self.assertIn("a", m["out"])+ self.assertIn("b", m["in"])+ self.assertIs(m["out"]["a"], m["in"]["b"]) # same entry, both sides+ self.assertEqual(m["out"]["a"]["kind"], "dissolve")+ # 1.0s at 24fps, halved and rounded to an even frame count (the+ # render's own rule — TRANSITION_MIN/transition_duration).+ self.assertEqual(m["out"]["a"]["half_frames"], 12)+ self.assertAlmostEqual(m["out"]["a"]["half_sec"], 0.5)+ self.assertEqual(m["out"]["a"]["at_frames"], 96) # 4.0s * 24fps++ def test_a_boundary_with_no_spare_source_is_silently_absent(self):+ # A clip trimmed to use its ENTIRE source has no tail to draw a+ # dissolve from — resolve_transitions refuses it (transition_no_+ # handles); the export must not invent one.+ a = sedit.new_clip("/x/a.mp4", 0.0, 4.0, 0.0, id="a", duration=4.0)+ b = sedit.new_clip("/x/b.mp4", 0.0, 4.0, 4.0, id="b", duration=10.0)+ transitions = [{"id": "t1", "after_clip": "a", "kind": "dissolve",+ "duration": 1.0}]+ m = sedit._nle_transitions([a, b], transitions, fps=24)+ self.assertEqual(m["out"], {})+ self.assertEqual(m["in"], {})++ def test_an_unknown_clip_is_silently_absent(self):+ clips, transitions = _pair()+ transitions[0]["after_clip"] = "not-a-real-id"+ m = sedit._nle_transitions(clips, transitions, fps=24)+ self.assertEqual(m["out"], {})++ def test_no_transitions_is_the_empty_map(self):+ clips, _ = _pair()+ m = sedit._nle_transitions(clips, None, fps=24)+ self.assertEqual(m, {"out": {}, "in": {}})+++class TheFCP7Transitionitem(unittest.TestCase):+ """Structural: real XML, parsed, not string-matched."""++ def _xml(self, kind="dissolve", duration=1.0):+ clips, transitions = _pair(kind=kind, duration=duration)+ segs = _segs(clips)+ tx = sedit._nle_transitions(clips, transitions, fps=24)+ raw = sedit.fcp7_xml(segs, name="f", media={"/x/a.mp4": "a.mp4",+ "/x/b.mp4": "b.mp4"},+ width=1024, height=576, base="/tmp/p", fps=24,+ transitions=tx)+ return raw, ET.fromstring(raw)++ def test_it_is_well_formed_xml(self):+ raw, root = self._xml()+ self.assertEqual(root.tag, "xmeml")++ def test_the_transitionitem_sits_between_the_two_clipitems(self):+ raw, root = self._xml()+ track = root.find(".//media/video/track")+ kids = list(track)+ tags = [k.tag for k in kids]+ self.assertEqual(tags, ["clipitem", "transitionitem", "clipitem"])+ self.assertEqual(kids[0].get("id"), "clipitem-1")+ self.assertEqual(kids[2].get("id"), "clipitem-2")++ def test_the_duration_is_the_clamped_one_the_render_uses(self):+ # 1.0s / 2 = 0.5s = 12 frames at 24fps each side around the cut+ # (film second 4.0 = frame 96): 84..108.+ raw, root = self._xml()+ t = root.find(".//media/video/track/transitionitem")+ self.assertEqual(t.find("start").text, "84")+ self.assertEqual(t.find("end").text, "108")+ self.assertEqual(t.find("alignment").text, "center")++ def test_the_clipitems_extend_to_meet_it(self):+ raw, root = self._xml()+ clips = root.findall(".//media/video/track/clipitem")+ # Clip a's OUT end (film) extends from frame 96 to 108; clip b's+ # start pulls back from 96 to 84.+ self.assertEqual(clips[0].find("end").text, "108")+ self.assertEqual(clips[1].find("start").text, "84")++ def test_dissolve_and_fade_black_use_different_named_effects(self):+ _, dissolve_root = self._xml(kind="dissolve")+ _, black_root = self._xml(kind="fade_black")+ d_name = dissolve_root.find(".//transitionitem/effect/name").text+ b_name = black_root.find(".//transitionitem/effect/name").text+ self.assertEqual(d_name, "Cross Dissolve")+ self.assertEqual(b_name, "Dip to Color Dissolve")+ self.assertIsNotNone(+ black_root.find(".//transitionitem/effect/parameter[parameterid='Color']"))+ self.assertIsNone(+ dissolve_root.find(".//transitionitem/effect/parameter[parameterid='Color']"))++ def test_the_audio_clipitem_is_never_extended(self):+ # "the audio plan never sees the extension" — the clip's own sound+ # stays a hard cut at the original boundary.+ raw, root = self._xml()+ audio_clips = root.findall(".//media/audio/track/clipitem")+ # No audio in these fixtures (has_audio defaults False) unless the+ # fixture says so — assert none leaked an extended end/start instead.+ for c in audio_clips:+ self.assertNotEqual(c.find("end").text, "108")++ def test_a_boundary_the_render_would_refuse_leaves_a_plain_cut(self):+ a = sedit.new_clip("/x/a.mp4", 0.0, 4.0, 0.0, id="a", duration=4.0)+ b = sedit.new_clip("/x/b.mp4", 0.0, 4.0, 4.0, id="b", duration=10.0)+ clips = [a, b]+ segs = _segs(clips)+ transitions = [{"id": "t1", "after_clip": "a", "kind": "dissolve",+ "duration": 1.0}]+ tx = sedit._nle_transitions(clips, transitions, fps=24)+ raw = sedit.fcp7_xml(segs, name="f",+ media={"/x/a.mp4": "a.mp4", "/x/b.mp4": "b.mp4"},+ width=1024, height=576, base="/tmp/p", fps=24,+ transitions=tx)+ root = ET.fromstring(raw)+ track = root.find(".//media/video/track")+ tags = [k.tag for k in track]+ self.assertEqual(tags, ["clipitem", "clipitem"]) # no transitionitem+ self.assertEqual(track[0].find("end").text, "96") # unextended++ def test_no_transitions_argument_behaves_exactly_as_before(self):+ clips, _ = _pair()+ segs = _segs(clips)+ with_none = sedit.fcp7_xml(segs, name="f",+ media={"/x/a.mp4": "a.mp4", "/x/b.mp4": "b.mp4"},+ width=1024, height=576, base="/tmp/p", fps=24)+ self.assertNotIn("<transitionitem>", with_none)+++class TheAfterEffectsOpacityRamp(unittest.TestCase):+ def _jsx(self, kind="dissolve", duration=1.0):+ clips, transitions = _pair(kind=kind, duration=duration)+ segs = _segs(clips)+ tx = sedit._nle_transitions(clips, transitions, fps=24)+ return sedit.ae_jsx(segs, name="f",+ media={"/x/a.mp4": "a.mp4", "/x/b.mp4": "b.mp4"},+ width=1024, height=576, fps=24, transitions=tx)++ def test_dissolve_only_animates_the_incoming_layer(self):+ # comp.layers.add() always inserts at the top, so the clip added+ # LATER (the incoming side of any boundary) ends up above the one+ # before it — fading only the incoming layer up is a correct+ # crossfade over the static layer underneath.+ js = self._jsx(kind="dissolve")+ self.assertEqual(js.count("op.setValueAtTime"), 2)+ self.assertIn("op.setValueAtTime(3.500000, 0);", js)+ self.assertIn("op.setValueAtTime(4.500000, 100);", js)++ def test_fade_black_animates_both_layers_in_non_overlapping_windows(self):+ js = self._jsx(kind="fade_black")+ self.assertEqual(js.count("op.setValueAtTime"), 4)+ # Outgoing: 100 -> 0 over the FIRST half (3.5s -> 4.0s).+ self.assertIn("op.setValueAtTime(3.500000, 100);", js)+ self.assertIn("op.setValueAtTime(4.000000, 0);", js)+ # Incoming: 0 -> 100 over the SECOND half (4.0s -> 4.5s).+ self.assertIn("op.setValueAtTime(4.000000, 0);", js)+ self.assertIn("op.setValueAtTime(4.500000, 100);", js)++ def test_the_inpoint_and_outpoint_extend_to_meet_at_the_cut(self):+ js = self._jsx()+ self.assertIn("lay.outPoint = 4.500000;", js)+ self.assertIn("lay.inPoint = 3.500000;", js)++ def test_a_boundary_the_render_would_refuse_animates_nothing(self):+ a = sedit.new_clip("/x/a.mp4", 0.0, 4.0, 0.0, id="a", duration=4.0)+ b = sedit.new_clip("/x/b.mp4", 0.0, 4.0, 4.0, id="b", duration=10.0)+ clips = [a, b]+ segs = _segs(clips)+ transitions = [{"id": "t1", "after_clip": "a", "kind": "dissolve",+ "duration": 1.0}]+ tx = sedit._nle_transitions(clips, transitions, fps=24)+ js = sedit.ae_jsx(segs, name="f",+ media={"/x/a.mp4": "a.mp4", "/x/b.mp4": "b.mp4"},+ width=1024, height=576, fps=24, transitions=tx)+ self.assertNotIn("op.setValueAtTime", js)+ self.assertIn("lay.outPoint = 4.000000;", js) # unextended+++class TheFullExportRoundTrip(unittest.TestCase):+ """export_nle() end to end: the route's own call shape, with real files+ on disk (the transition resolver needs a real duration to trust the+ handles), through to a parseable XML with a transitionitem in it."""++ def test_export_nle_writes_a_transitionitem_when_the_document_has_one(self):+ import subprocess+ import tempfile+ import mlx_ltx_panel as panel+ with tempfile.TemporaryDirectory() as d:+ root = Path(d)+ a = root / "a.mp4"+ b = root / "b.mp4"+ for p in (a, b):+ subprocess.run(+ [str(panel.FFMPEG), "-y", "-loglevel", "error", "-f", "lavfi",+ "-i", "color=c=red:s=64x48:d=6:r=24", "-pix_fmt", "yuv420p",+ str(p)], check=True, capture_output=True, timeout=30)+ clip_a = sedit.new_clip(str(a), 0.0, 4.0, 0.0, id="a", duration=6.0)+ clip_b = sedit.new_clip(str(b), 1.0, 5.0, 4.0, id="b", duration=6.0)+ transitions = [{"id": "t1", "after_clip": "a", "kind": "dissolve",+ "duration": 1.0}]+ res = sedit.export_nle(+ [clip_a, clip_b], root, name="A Film", fps=24,+ probe=panel._sb_probe_clip, transitions=transitions)+ self.assertTrue(res["ok"])+ xml_text = Path(res["xml"]).read_text()+ root_el = ET.fromstring(xml_text)+ self.assertIsNotNone(root_el.find(".//transitionitem"))+ jsx_text = Path(res["jsx"]).read_text()+ self.assertIn("op.setValueAtTime", jsx_text)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_outputs_cache_invalidation.py b/test_outputs_cache_invalidation.pyindex 304c1dc..3709510 100644--- a/test_outputs_cache_invalidation.py+++ b/test_outputs_cache_invalidation.py@@ -28,7 +28,7 @@ const B = process.argv[1] + '/webapp/js/boot.js', Q = process.argv[1] + '/webapplet server = ['/o/new.mp4', '/o/old1.mp4', '/o/old2.png', '/o/hideme.mp4'];const ctx = {window: {}, console, out: {}, Set, Promise, URLSearchParams, JSON, String, Array,- currentOutputs: [], mainOutputsFilter: 'all', activePath: null,+ currentOutputs: [], mainOutputsFilter: 'all', activePath: null, filterMode: 'visible',confirm: () => true, phosToast: () => {}, renderCarousel: () => {}, paintOutputsCount: () => {},outputKind: () => 'video',document: {getElementById: () => null},diff --git a/test_plain_english_copy.py b/test_plain_english_copy.pynew file mode 100644index 0000000..b89abf1--- /dev/null+++ b/test_plain_english_copy.py@@ -0,0 +1,110 @@+#!/usr/bin/env python3+"""VC-23 [P2] [COPY] Engineering jargon and idioms in the main form.++Coordinator ruling, 2026-09-29: "rewrite the jargon in plain words+everywhere touched" — scoped to the copy this session's other fixes+already put hands on (VC-16's Enhance flow, VC-28's LTX length blurbs and+tier-chip ETA tail, VC-34's Tier dialog), rather than the full report's+broader sweep across every idiom in the app (FFLF/Speed/Upscale chip+relabelling, the OOM card, friendlyJobError) — those live in areas this+session did not touch and weren't re-opened for a copy-only pass.++Gated here:+ 1 "Loading Gemma..." -> "Loading the prompt helper..." — the model+ name means nothing to a user; what it's FOR does. Fixed in both+ enhancePrompt() (queue.js, VC-16) and Character mode's own enhance+ button + status line (characters.js) for consistency — three near-+ identical strings, not left half-fixed.+ 2 the LTX length blurbs (VC-28's own dict) dropped screenwriting+ jargon ("beat") for a plain sentence naming the duration+ 3 the tier-chip ETA's "Q8 HQ" tail (VC-28's own ltxCellEta) -> "High+ detail" — Q8/HQ are internal pipeline names+ 4 the Extend duration hint dropped its inline frame-math parenthetical+ ("6 latent frames x 8 video frames at 24 fps") for "Adds 2.0 s",+ with the math kept as a tooltip for anyone who wants it — both the+ JS-computed live text and the HTML's static default+ 5 the Tier dialog's env-var testing instruction+ (LTX_TIER_OVERRIDE=...) is gone from the user-facing dialog — it+ already lives in CLAUDE.md for developers, and had nothing to do+ with what the dialog itself shows+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+CJS = (ROOT / "webapp" / "js" / "characters.js").read_text(encoding="utf-8")+EJS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+++class TestLoadingCopy(unittest.TestCase):+ def test_no_bare_gemma_name_in_a_loading_message(self):+ for src, label in ((QJS, "queue.js"), (CJS, "characters.js")):+ self.assertNotIn("Loading Gemma", src, label)++ def test_replacement_says_what_it_does(self):+ self.assertIn("Loading the prompt helper", QJS)+ self.assertEqual(CJS.count("Loading the prompt helper"), 2)+++class TestLtxLengthBlurbs(unittest.TestCase):+ def test_no_screenwriting_jargon_remains(self):+ for key, cell in P.LTX_LENGTHS.items():+ self.assertNotIn("beat", cell["blurb"].lower(), key)++ def test_each_blurb_names_its_duration_in_plain_words(self):+ self.assertIn("3-second", P.LTX_LENGTHS["3s"]["blurb"])+ self.assertIn("5-second", P.LTX_LENGTHS["5s"]["blurb"])+ self.assertIn("7 seconds", P.LTX_LENGTHS["7s"]["blurb"])+ self.assertIn("10 seconds", P.LTX_LENGTHS["10s"]["blurb"])+++class TestTierChipEtaTail(unittest.TestCase):+ def test_q8_hq_jargon_replaced(self):+ self.assertNotIn("' · Q8 HQ'", EJS)+ self.assertIn("' · High detail'", EJS)+++class TestExtendDurationHint(unittest.TestCase):+ def test_js_drops_the_frame_math_from_the_visible_text(self):+ i = QJS.index("hint.textContent = `Adds")+ line = QJS[i:QJS.index("\n", i)]+ self.assertNotIn("latent frames", line)+ self.assertIn("${actualSec.toFixed(2)} s", line)++ def test_frame_math_survives_as_a_tooltip(self):+ i = QJS.index("hint.textContent = `Adds")+ block = QJS[i:i + 300]+ self.assertIn("hint.title = `${latents} latent frames", block)++ def test_html_default_matches(self):+ i = HTML.index('id="extendDurationHint"')+ tag = HTML[i:HTML.index(">", i) + 1]+ self.assertIn("latent frames", tag) # in the title attr+ after = HTML[HTML.index(">", i) + 1:]+ visible = after[:after.index("</div>")]+ self.assertEqual(visible.strip(), "Adds 2.0 s")+ self.assertNotIn("latent frames", visible)+++class TestTierModalFooter(unittest.TestCase):+ def test_env_var_testing_instruction_removed_from_the_dialog(self):+ i = HTML.index('id="tierModal"')+ j = HTML.index('id="h3InstallTitle"') # next unrelated dialog+ block = HTML[i:j]+ # It's fine for a comment to MENTION the old instruction while+ # explaining why it's gone; it must not still be live markup a+ # user sees — i.e. no <code> tag carrying it any more.+ self.assertNotIn("<code>LTX_TIER_OVERRIDE", block)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_prompt_enhance_endpoint.py b/test_prompt_enhance_endpoint.pyindex 649f3d6..5ff2f57 100644--- a/test_prompt_enhance_endpoint.py+++ b/test_prompt_enhance_endpoint.py@@ -270,6 +270,15 @@ class PromptEnhanceEndpointTest(unittest.TestCase):previous = {key: os.environ.get(key) for key in overrides}os.environ.update(overrides)panel = None+ # Loading the panel a second time re-points every panel.routes_*+ # module's P at THIS copy (mlx_ltx_panel wires `_routes_mod.P =+ # sys.modules[__name__]` at import). Left that way, every later+ # suite in a whole-suite run called its routes against the dead+ # copy — its own OUTPUT/STATE patches invisible, 404s all round+ # (test_routes' wiring check, the room-tone/uploads/new-take+ # route suites). Snapshot and restore the binding.+ bound_p = {name: mod.P for name, mod in list(sys.modules.items())+ if name.startswith("panel.routes_") and hasattr(mod, "P")}try:spec = importlib.util.spec_from_file_location("prompt_enhance_panel_under_test", ROOT / "mlx_ltx_panel.py"@@ -337,6 +346,10 @@ class PromptEnhanceEndpointTest(unittest.TestCase):if stream is not None and not stream.closed:stream.close()sys.modules.pop("prompt_enhance_panel_under_test", None)+ for name, bound in bound_p.items():+ mod = sys.modules.get(name)+ if mod is not None:+ mod.P = boundfor key, value in previous.items():if value is None:os.environ.pop(key, None)diff --git a/test_queue_reorder_edit_eta.py b/test_queue_reorder_edit_eta.pynew file mode 100644index 0000000..2944bb5--- /dev/null+++ b/test_queue_reorder_edit_eta.py@@ -0,0 +1,295 @@+#!/usr/bin/env python3+"""VC-26 [P2] [UX] The queue can't manage a series: no reorder, no edit, no+per-job or total time.++Coordinator ruling, 2026-09-29: "queue reorder (drag or up/down), edit a+queued job, and an ETA per job plus a total."++Gated here:+ 1 queue_move_job(): up/down/top, boundary no-ops answer ok:True+ moved:False (never a silent failure the client has to interpret), an+ unknown id is refused+ 2 queue_update_job(): edits params IN PLACE — same id, same queue+ position — by re-running make_job() on the submitted form; refuses a+ job that already started rendering or finished (it's no longer in+ STATE["queue"] the moment that happens, so the lookup is the guard)+ 3 job_priced_eta_sec(): reads the SAME priced tier cell (LTX_TIERS/+ H3_TIERS) the quality chips show (VC-28), returns None for anything+ that doesn't map to a known cell so the caller's average-based+ fallback still applies+ 4 /status stamps eta_sec on every queued job AND keeps the aggregate+ total, both fed by the one _eta_for() that now prefers the priced+ number+ 5 the two new routes are registered and answer JSON either way+ 6 the client: reorder buttons are hidden exactly at the list's own+ boundaries, the badge shows "N · ~M min", edit is gated to the modes+ editQueuedJob() actually knows how to restore, and the edit banner's+ Update/Cancel wiring+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from urllib.parse import urlencode++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-queueedit-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8326")+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from panel.routes import POST_ROUTES # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++class _H:+ def __init__(self, body: str = ""):+ self.body, self.out = body, None++ def _read_form_body(self):+ from urllib.parse import parse_qs+ return self.body, parse_qs(self.body)++ def _json(self, obj, code=200):+ self.out = (code, obj)+++class _Env(unittest.TestCase):+ def setUp(self):+ self._saved_persist = P.persist_queue+ P.persist_queue = lambda: None+ with P.QUEUE_COND:+ self._queue_before = list(P.STATE["queue"])+ P.STATE["queue"] = []++ def tearDown(self):+ P.persist_queue = self._saved_persist+ with P.QUEUE_COND:+ P.STATE["queue"] = self._queue_before+ P.STATE["current"] = None++ def _job(self, prompt="p", quality="balanced", frames=121):+ return P.make_job({"mode": ["t2v"], "prompt": [prompt],+ "quality": [quality], "frames": [str(frames)]})++ def _seed(self, n=3):+ jobs = [self._job(f"p{i}") for i in range(n)]+ with P.QUEUE_COND:+ P.STATE["queue"] = jobs+ return [j["id"] for j in jobs]+++# ---------------------------------------------------------------- 1+class TestQueueMoveJob(_Env):+ def test_up_swaps_with_the_previous_row(self):+ ids = self._seed(3)+ r = P.queue_move_job(ids[2], "up")+ self.assertEqual(r, {"ok": True, "moved": True})+ with P.QUEUE_COND:+ self.assertEqual([j["id"] for j in P.STATE["queue"]], [ids[0], ids[2], ids[1]])++ def test_down_swaps_with_the_next_row(self):+ ids = self._seed(3)+ P.queue_move_job(ids[0], "down")+ with P.QUEUE_COND:+ self.assertEqual([j["id"] for j in P.STATE["queue"]], [ids[1], ids[0], ids[2]])++ def test_top_moves_to_the_front(self):+ ids = self._seed(3)+ P.queue_move_job(ids[2], "top")+ with P.QUEUE_COND:+ self.assertEqual([j["id"] for j in P.STATE["queue"]][0], ids[2])++ def test_boundary_moves_are_a_no_op_not_a_failure(self):+ ids = self._seed(3)+ self.assertEqual(P.queue_move_job(ids[0], "up"), {"ok": True, "moved": False})+ self.assertEqual(P.queue_move_job(ids[2], "down"), {"ok": True, "moved": False})+ self.assertEqual(P.queue_move_job(ids[0], "top"), {"ok": True, "moved": False})++ def test_unknown_id_is_refused(self):+ self._seed(2)+ r = P.queue_move_job("nope", "up")+ self.assertFalse(r["ok"])++ def test_bad_direction_is_refused(self):+ ids = self._seed(1)+ r = P.queue_move_job(ids[0], "sideways")+ self.assertFalse(r["ok"])+++# ---------------------------------------------------------------- 2+class TestQueueUpdateJob(_Env):+ def test_edits_params_in_place_same_id_same_position(self):+ ids = self._seed(3)+ r = P.queue_update_job(ids[1], {"mode": ["t2v"], "prompt": ["changed"],+ "quality": ["standard"], "frames": ["121"]})+ self.assertEqual(r, {"ok": True, "id": ids[1]})+ with P.QUEUE_COND:+ q = P.STATE["queue"]+ self.assertEqual([j["id"] for j in q], ids) # position unchanged+ job = next(j for j in q if j["id"] == ids[1])+ self.assertEqual(job["params"]["prompt"], "changed")+ self.assertEqual(job["params"]["quality"], "standard")++ def test_refuses_a_job_that_already_started(self):+ ids = self._seed(1)+ with P.QUEUE_COND:+ job = P.STATE["queue"].pop(0)+ P.STATE["current"] = job+ r = P.queue_update_job(ids[0], {"mode": ["t2v"], "prompt": ["x"]})+ self.assertFalse(r["ok"])+ self.assertIn("no longer queued", r["error"])++ def test_refuses_an_unknown_id(self):+ self._seed(1)+ r = P.queue_update_job("nope", {"mode": ["t2v"], "prompt": ["x"]})+ self.assertFalse(r["ok"])++ def test_goes_through_make_job_validation(self):+ # A character request error from make_job surfaces as a refusal,+ # not an unhandled exception — same contract queue_face_fix etc.+ # already follow for CharacterRequestError.+ ids = self._seed(1)+ old = P.make_job++ def fake(form):+ raise P.CharacterRequestError("bad character")+ P.make_job = fake+ try:+ r = P.queue_update_job(ids[0], {"mode": ["t2v"]})+ finally:+ P.make_job = old+ self.assertFalse(r["ok"])+ self.assertIn("bad character", r["error"])+++# ---------------------------------------------------------------- 3+class TestJobPricedEtaSec(unittest.TestCase):+ def test_prices_a_known_ltx_cell(self):+ sec = P.job_priced_eta_sec({"mode": "t2v", "quality": "balanced", "frames": 121})+ self.assertIsNotNone(sec)+ cell = P.LTX_TIERS["balanced_5s"]+ self.assertAlmostEqual(sec, cell["eta_min"] * 60.0, places=3)++ def test_none_for_image_train_upscale_sharp_export(self):+ for mode in ("image", "train", "upscale", "sharp_export"):+ self.assertIsNone(P.job_priced_eta_sec({"mode": mode}), mode)++ def test_none_for_music(self):+ self.assertIsNone(P.job_priced_eta_sec({"mode": "t2v", "engine": "music"}))++ def test_none_for_an_off_axis_frame_count(self):+ self.assertIsNone(P.job_priced_eta_sec(+ {"mode": "t2v", "quality": "balanced", "frames": 999}))++ def test_h3_lane_prices_from_h3_tiers(self):+ # Pick any real, offered H3 cell rather than hardcoding one that+ # might not exist on every registry shape.+ cell_key = next((k for k, c in P.H3_TIERS.items() if c.get("eta_min")), None)+ if cell_key is None:+ self.skipTest("no priced H3 cell in this registry")+ q, ln = cell_key.split("_", 1)+ sec = P.job_priced_eta_sec({"mode": "h3", "engine": "h3",+ "h3_quality": q, "h3_length": ln})+ self.assertIsNotNone(sec)+++# ---------------------------------------------------------------- 4+class TestStatusStampsEta(_Env):+ def test_status_route_stamps_per_job_and_total(self):+ self._seed(2)+ from urllib.parse import urlparse+ from panel.routes import GET_ROUTES+ h = _H()+ GET_ROUTES["/status"](h, urlparse("/status"))+ code, payload = h.out+ self.assertEqual(code, 200)+ self.assertEqual(len(payload["queue"]), 2)+ for j in payload["queue"]:+ self.assertIn("eta_sec", j)+ self.assertGreater(j["eta_sec"], 0)+ self.assertEqual(payload["eta_sec"],+ round(sum(j["eta_sec"] for j in payload["queue"])))+++# ---------------------------------------------------------------- 5+class TestRoutesRegistered(_Env):+ def test_reorder_route_answers_json(self):+ self.assertIn("/queue/reorder", POST_ROUTES)+ ids = self._seed(2)+ h = _H(urlencode({"id": ids[1], "direction": "up"}))+ POST_ROUTES["/queue/reorder"](h, "/queue/reorder", {}, "")+ self.assertEqual(h.out[0], 200)+ self.assertTrue(h.out[1]["ok"])+ h = _H(urlencode({"id": "", "direction": "up"}))+ POST_ROUTES["/queue/reorder"](h, "/queue/reorder", {}, "")+ self.assertEqual(h.out[0], 400)++ def test_update_route_answers_json(self):+ self.assertIn("/queue/update", POST_ROUTES)+ ids = self._seed(1)+ h = _H(urlencode({"id": ids[0], "mode": "t2v", "prompt": "new",+ "quality": "balanced", "frames": "121"}))+ POST_ROUTES["/queue/update"](h, "/queue/update", {}, "")+ self.assertEqual(h.out[0], 200)+ self.assertTrue(h.out[1]["ok"])+ h = _H(urlencode({"id": "nope", "mode": "t2v"}))+ POST_ROUTES["/queue/update"](h, "/queue/update", {}, "")+ self.assertEqual(h.out[0], 400)+++# ---------------------------------------------------------------- 6+class TestClientMarkup(unittest.TestCase):+ def test_reorder_buttons_hidden_at_boundaries(self):+ fn = extract_function("renderCarousel", QJS)+ # renderCarousel doesn't build the queue rows (that's inline in+ # poll()); grep poll() itself for the guard instead.+ self.assertIn("i > 0", QJS)+ self.assertIn("i < s.queue.length - 1", QJS)++ def test_badge_shows_count_and_time(self):+ i = QJS.index("const qb = document.getElementById('queueBadge')")+ block = QJS[i:QJS.index("qb.style.display = ''", i) + 40]+ self.assertIn("fmtEtaCompact", block)+ self.assertIn("s.eta_sec", block)++ def test_editable_gate_excludes_batch_image_music(self):+ self.assertIn("_EDITABLE_QUEUE_MODES", QJS)+ fn = extract_function("editQueuedJob", QJS)+ self.assertIn("p.take", fn)+ self.assertIn("p.engine === 'music'", fn)++ def test_update_and_cancel_functions_exist(self):+ for fn in ("reorderQueuedJob", "editQueuedJob", "cancelEditingQueuedJob", "updateQueuedJob"):+ self.assertIn(f"function {fn}(", QJS, fn)+ self.assertIn(fn, QJS[QJS.index("Object.assign(globalThis"):], fn)++ def test_edit_banner_markup_wired_to_the_functions(self):+ i = HTML.index('id="queueEditBanner"')+ blk = HTML[i:i + 500]+ self.assertIn("updateQueuedJob()", blk)+ self.assertIn("cancelEditingQueuedJob()", blk)++ def test_css_for_new_elements_exists(self):+ for cls in ("#queueList li", ".q-eta", ".q-reorder", ".q-row-editable",+ ".queue-edit-banner"):+ self.assertIn(cls, CSS, cls)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_render_check_4170.py b/test_render_check_4170.pynew file mode 100644index 0000000..cc2daf5--- /dev/null+++ b/test_render_check_4170.py@@ -0,0 +1,200 @@+#!/usr/bin/env python3+"""4.17.0 render-check findings (real GPU renders on the integration tree).++1. Retake a moment (VA-26) shares Extend's size cap, so on a capped Mac a+ 720x1280 clip came back 416x768 while the modal said everything outside+ the stretch was "kept exactly as it was". The modal now says the cap+ before the render. The note's text is a pure function, executed in node.++(The live-preview finding from the same pass — a2v/keyframe pipelines drop+the monitor, so the Now card sat on "starting" — is pinned in+test_lipsync_mode.LivePreviewOnKeyframeAndA2v.)+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+INDEX = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+++def _node(script: str):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError(r.stderr[-3000:])+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class RetakeSaysItsSizeCap(unittest.TestCase):+ def _note(self, tier):+ fn = extract_function("retakeClampNoteText", QUEUE_JS)+ return _node(fn + f"\nconsole.log(JSON.stringify(retakeClampNoteText({json.dumps(tier)})));")++ def test_a_capped_mac_is_told_before_the_render(self):+ t = self._note({"extend_max_dim": 768, "label": "Comfortable"})+ self.assertIn("768px", t)+ self.assertIn("Comfortable", t)+ self.assertIn("smaller", t)+ self.assertIn("original stays", t)++ def test_an_uncapped_mac_gets_no_note(self):+ self.assertEqual(self._note({"extend_max_dim": 0, "label": "Studio"}), "")+ self.assertEqual(self._note(None), "")++ def test_the_modal_shows_it_and_no_longer_promises_an_identical_clip(self):+ self.assertIn('id="retakeClampNote"', INDEX)+ self.assertNotIn("everything outside it is kept exactly as it was", INDEX)+ body = extract_function("openRetakeModal", QUEUE_JS)+ self.assertIn("retakeClampNoteText(", body)+ self.assertIn("retakeClampNote", body)+++class PlayerMetaWrapsBetweenItems(unittest.TestCase):+ """A portrait clip's player header wrapped each item inside itself+ ("22 / min / ago", the lip-sync verdict on three lines)."""++ def test_meta_row_wraps_between_items_not_inside_them(self):+ css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+ start = css.index(".po-meta {")+ block = css[start:css.index("}", start)]+ self.assertIn("flex-wrap: wrap", block)+ self.assertIn(".po-meta > span:not(.po-dot) { white-space: nowrap; }", css)+++class WindowsPartialSaysWhatItHolds(unittest.TestCase):+ """VA-38 render check: the partial published after window 2 of 3 failed+ kept params.frames = 241 (the ask), so the gallery called a 5 s file a+ "10s clip". The sidecar now records the frames the file holds."""++ def test_partial_sidecar_records_the_delivered_frames(self):+ import mlx_ltx_panel as P+ from unittest import mock+ ff = str(P.FFMPEG)+ with tempfile.TemporaryDirectory() as td:+ td = Path(td)+ pieces = []+ for i in range(2):+ out = td / f"w{i}.mp4"+ subprocess.run([ff, "-v", "error", "-y", "-f", "lavfi", "-i",+ "testsrc=size=64x64:rate=24:duration=0.5", "-f", "lavfi",+ "-i", "anullsrc=r=48000:cl=stereo", "-t", "0.5",+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac",+ str(out)], check=True)+ pieces.append(str(out))+ raw_out = td / "clip.mp4"+ p = {"frames": 241, "frame_rate": 24.0, "prompt": "a lighthouse", "mode": "t2v"}+ with mock.patch.object(P, "OUTPUT", td), mock.patch.object(P, "push", lambda *a, **k: None):+ P._publish_windows_partial({"id": "j-test"}, p, {"count": 3}, pieces, 1,+ raw_out, {"pix_fmt": "yuv420p", "crf": "18"}, 24.0)+ side = json.loads((td / "clip_windows_partial_2of3.mp4.json").read_text())+ self.assertEqual(side["params"]["frames"], 24)+ self.assertEqual(side["params"]["frames_asked"], 241)+ self.assertEqual(side["windows_partial"]["completed"], 2)+ self.assertEqual(p["frames"], 241) # the job's own params untouched+++class TheGradeSurvivesSave(unittest.TestCase):+ """FILM-14 render check: Match colour applied, Save pressed, and the+ saved edit.json had `adjust: null` on all three clips — sbeCleanClip+ rebuilt `adjust` as brightness only, so no per-clip grade ever reached+ the render, the backup or an NLE export. Executed in node through the+ editor's own harness, then through the server's save/load/validate."""++ def _clean(self, clips):+ import test_codex_4170_editor as ed+ return ed.run("out.clips = %s.map(sbeCleanClip);" % json.dumps(clips))["clips"]++ def test_a_graded_clip_keeps_every_grade_key(self):+ c = {"id": "a", "path": "/x/a.mp4", "start": 0.0, "end": 5.0,+ "film_start": 0.0, "film_end": 5.0, "duration": 5.0,+ "source": "human", "locked": False,+ "adjust": {"brightness": 0.1, "exposure": 0.2, "temp": 0.3,+ "tint": -0.1, "contrast": 1.1, "saturation": 0.9}}+ out = self._clean([c])[0]+ self.assertEqual(out["adjust"], {"brightness": 0.1, "exposure": 0.2, "temp": 0.3,+ "tint": -0.1, "contrast": 1.1, "saturation": 0.9})++ def test_a_neutral_grade_is_absent(self):+ c = {"id": "a", "path": "/x/a.mp4", "start": 0.0, "end": 5.0,+ "film_start": 0.0, "film_end": 5.0, "duration": 5.0,+ "source": "human", "locked": False,+ "adjust": {"exposure": 0, "contrast": 1, "saturation": 1}}+ self.assertNotIn("adjust", self._clean([c])[0])++ def test_the_cleaned_grade_saves_validates_and_loads_back(self):+ import storyboard_editor as sedit+ import test_codex_4170_editor as ed+ c = {"id": "a", "path": "/x/a.mp4", "start": 0.0, "end": 5.0,+ "film_start": 0.0, "film_end": 5.0, "duration": 5.0,+ "source": "human", "locked": False,+ "adjust": {"exposure": 0.11234, "temp": 0.67438, "tint": 0.113021}}+ clean = self._clean([c])+ doc = ed._doc(clean)+ self.assertEqual(sedit.blocking_errors(sedit.validate_edit(doc)), [])+ with tempfile.TemporaryDirectory() as d:+ sedit.save_edit(d, doc)+ back = sedit.load_edit(d)+ self.assertEqual(back["clips"][0].get("adjust"),+ {"exposure": 0.11234, "temp": 0.67438, "tint": 0.113021})+++class TheCompactCapOutranksTheSilentTail(unittest.TestCase):+ """VA-30 render check on a 32 GB (Compact) panel: a 12.9 s voice defaulted+ Duration to 13 s, the silent-tail note ("the last 0.1 s ...") returned+ first, and the cap message with its Split link never appeared."""++ def _warn(self, cap, file_len, sec):+ src = (ROOT / "webapp" / "js" / "characters.js").read_text(encoding="utf-8")+ js = """+var A2V_AREA_KNEE = 0.45e6, A2V_KNEE_FRAMES = 450, BOOT = {a2v_max_frames: %d};+var AUDIO_STUDIO = {audioDuration: %s};+const els = {};+function el(id, v) { return els[id] = {id, value: v, style: {}, innerHTML: '', textContent: ''}; }+const document = { getElementById: id => els[id] || null };+el('audioStudioDuration', '%d'); el('audioStudioDurationVal');+el('audioStudioDurationWarn'); el('audioStudioWidth', '448'); el('audioStudioHeight', '768');+el('audioStudioStart', '0');+""" % (cap, json.dumps(file_len), sec) + "\n".join(+ extract_function(n, src) for n in ("_a2vFramesForSeconds", "audioStudioDurationChanged")) + """+audioStudioDurationChanged('%d');+console.log(JSON.stringify(els.audioStudioDurationWarn.style.display === 'none' ? '' : els.audioStudioDurationWarn.innerHTML));+""" % sec+ return _node(js)++ def test_a_compact_mac_sees_the_cap_and_the_split_link(self):+ w = self._warn(241, 12.8675, 13)+ self.assertIn("Split into 10 s clips", w)++ def test_a_blink_of_tail_is_not_a_warning(self):+ self.assertEqual(self._warn(0, 12.8675, 13), "")++ def test_a_real_silent_tail_still_warns(self):+ self.assertIn("render against silence", self._warn(0, 12.8675, 15))++ def test_the_default_duration_never_adds_a_second_of_silence(self):+ src = (ROOT / "webapp" / "js" / "characters.js").read_text(encoding="utf-8")+ self.assertIn("Math.floor(AUDIO_STUDIO.audioDuration + 0.25)", src)+ self.assertNotIn("Math.round(AUDIO_STUDIO.audioDuration)", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_render_intent_resume.py b/test_render_intent_resume.pynew file mode 100644index 0000000..ccacd8d--- /dev/null+++ b/test_render_intent_resume.py@@ -0,0 +1,219 @@+#!/usr/bin/env python3+"""FILM-17: a panel restart during an overnight board render must not+silently stop it.++`_sb_render_thread` queues one bucket of shots at a time and lives only in+`_SB_RENDERS`, this process's own memory. A restart mid-render used to leave+a board reading "Drafts · 18 of 52" with no thread, no error, and no film —+riding the ordinary queue only covers jobs already queued, nothing was left+to queue the next bucket.++Locked here: every render start writes `board["render_intent"]` before the+thread does anything real; the thread's own `finally` clears it on every+ordinary exit (done, stopped, or errored); and `_sb_boot_reconcile()` — the+one path that runs AFTER a hard kill, the only way `render_intent` can still+be set — either resumes the render (unfinished) or cleans up and runs the+auto-film step it never got to (finished, just not noticed).+"""+from __future__ import annotations++import sys+import tempfile+import threading+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _shot(n, **kw):+ s = {"n": n, "mode": "text", "engine": "ltx", "prompt": f"shot {n} happens",+ "duration_s": 5.0, "seed": 100 + n, "refs": [], "status": "pending",+ "uid": f"shot_{n:08x}"}+ s.update(kw)+ return s+++def _board(shots, bid="sb_20231115_d15bad", **kw):+ b = {"schema": 1, "id": bid, "title": "Overnight film", "created_at": 1_700_050_000,+ "policy": storyboard.default_policy(), "cast": [], "engine_mode": "ltx",+ "shots": shots}+ b.update(kw)+ return b+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.state = Path(self.tmp.name) / "state"+ self.state.mkdir()+ self.queue_state = {"queue": [], "current": None, "history": []}+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "STATE", self.queue_state),+ mock.patch.object(panel, "persist_queue", lambda: None),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)+ panel._SB_RENDERS.clear()+ panel._SB_PLANNERS.clear()+ self.addCleanup(panel._SB_RENDERS.clear)+ self.addCleanup(panel._SB_PLANNERS.clear)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def load(self, bid):+ return storyboard.load_storyboard(self.state, bid)+++class RenderIntentBookkeeping(unittest.TestCase):+ def test_set_and_clear(self):+ board = {}+ panel._sb_set_render_intent(board, "draft", [1, 2], auto=True)+ self.assertEqual(board["render_intent"],+ {"pass": "draft", "only": [1, 2], "auto": True})+ panel._sb_clear_render_intent(board)+ self.assertNotIn("render_intent", board)++ def test_only_none_stays_none(self):+ board = {}+ panel._sb_set_render_intent(board, "final", None)+ self.assertIsNone(board["render_intent"]["only"])+ self.assertFalse(board["render_intent"]["auto"])++ def test_intent_done_checks_the_right_pass_and_scope(self):+ board = _board([_shot(1, draft_output="/o/1.mp4"),+ _shot(2, draft_output="/o/2.mp4"),+ _shot(3)])+ self.assertFalse(panel._sb_render_intent_done(+ board, {"pass": "draft", "only": None}))+ self.assertTrue(panel._sb_render_intent_done(+ board, {"pass": "draft", "only": [1, 2]}))+ self.assertFalse(panel._sb_render_intent_done(+ board, {"pass": "final", "only": [1]}))+ # a skipped (cut) shot does not block "done"+ board2 = _board([_shot(1, draft_output="/o/1.mp4"),+ _shot(2, status="skipped")])+ self.assertTrue(panel._sb_render_intent_done(+ board2, {"pass": "draft", "only": None}))+++class TheThreadClearsItsOwnIntent(Sandbox):+ def test_render_intent_is_gone_when_the_thread_finishes(self):+ board = _board([_shot(1)])+ panel._sb_set_render_intent(board, "draft", None)+ self.save(board)+ bid = board["id"]+ panel._SB_RENDERS[bid] = {"stop": False, "queued": 0}+ th = threading.Thread(target=panel._sb_render_thread,+ args=(bid, "draft", None), daemon=True)+ with mock.patch.object(panel, "_sb_enqueue", return_value="j1"), \+ mock.patch.object(panel, "_sb_job_index",+ return_value={"j1": {"status": "done",+ "output_path": "/o/1.mp4"}}), \+ mock.patch.object(panel, "_sb_h3_available", return_value=False), \+ mock.patch.object(panel, "h3_supports_chain_prompts", return_value=False), \+ mock.patch.object(panel, "h3_supports_first_frame", return_value=False), \+ mock.patch.object(panel, "_sb_lipsync_gate", lambda *a, **k: None), \+ mock.patch.object(panel, "_sb_sweep_stage_a", lambda *a, **k: None), \+ mock.patch.object(storyboard, "shot_to_job",+ lambda shot, *a, **k: {"mode": "t2v",+ "prompt": shot["prompt"]}):+ th.start()+ th.join(timeout=10)+ self.assertFalse(th.is_alive())+ self.assertNotIn("render_intent", self.load(bid))++ def test_render_intent_is_gone_after_a_stop(self):+ board = _board([_shot(1), _shot(2)])+ panel._sb_set_render_intent(board, "draft", None)+ self.save(board)+ bid = board["id"]+ panel._SB_RENDERS[bid] = {"stop": True, "queued": 0} # stopped before it starts+ panel._sb_render_thread(bid, "draft", None)+ self.assertNotIn("render_intent", self.load(bid))+++class BootResumesAnInterruptedRender(Sandbox):+ def test_an_unfinished_render_intent_is_resumed(self):+ board = _board([_shot(1, draft_output="/o/1.mp4", status="done"),+ _shot(2)]) # shot 2 never queued+ panel._sb_set_render_intent(board, "draft", None, auto=False)+ self.save(board)+ with mock.patch.object(panel.threading, "Thread") as th_cls, \+ mock.patch.object(panel, "_sb_auto_film") as auto_film:+ fake_thread = mock.Mock()+ th_cls.return_value = fake_thread+ panel._sb_boot_reconcile()+ th_cls.assert_called_once()+ _, kw = th_cls.call_args+ self.assertIs(kw["target"], panel._sb_render_thread)+ self.assertEqual(kw["args"], (board["id"], "draft", None))+ fake_thread.start.assert_called_once()+ self.assertIn(board["id"], panel._SB_RENDERS)+ self.assertTrue(panel._SB_RENDERS[board["id"]].get("resumed"))+ auto_film.assert_not_called()+ # the intent stays on disk until the resumed thread's own finally+ # clears it — it is NOT the boot pass's job to clear an unfinished one+ self.assertIn("render_intent", self.load(board["id"]))++ def test_an_already_finished_render_intent_is_cleaned_up_not_resumed(self):+ board = _board([_shot(1, draft_output="/o/1.mp4", status="done"),+ _shot(2, draft_output="/o/2.mp4", status="done")])+ panel._sb_set_render_intent(board, "draft", None, auto=True)+ self.save(board)+ with mock.patch.object(panel.threading, "Thread") as th_cls, \+ mock.patch.object(panel, "_sb_auto_film") as auto_film:+ panel._sb_boot_reconcile()+ th_cls.assert_not_called()+ auto_film.assert_called_once()+ self.assertNotIn("render_intent", self.load(board["id"]))++ def test_only_is_respected_when_resuming(self):+ board = _board([_shot(1, draft_output="/o/1.mp4", status="done"),+ _shot(2), _shot(3)])+ panel._sb_set_render_intent(board, "final", [2, 3])+ self.save(board)+ with mock.patch.object(panel.threading, "Thread") as th_cls:+ fake_thread = mock.Mock()+ th_cls.return_value = fake_thread+ panel._sb_boot_reconcile()+ _, kw = th_cls.call_args+ self.assertEqual(kw["args"], (board["id"], "final", [2, 3]))++ def test_a_board_already_claimed_by_a_live_render_or_planner_is_left_alone(self):+ board = _board([_shot(1)])+ panel._sb_set_render_intent(board, "draft", None)+ self.save(board)+ panel._SB_RENDERS[board["id"]] = {"stop": False, "queued": 0}+ with mock.patch.object(panel.threading, "Thread") as th_cls:+ panel._sb_boot_reconcile()+ th_cls.assert_not_called()++ def test_a_board_with_no_render_intent_is_untouched(self):+ board = self.save(_board([_shot(1)]))+ with mock.patch.object(panel.threading, "Thread") as th_cls:+ panel._sb_boot_reconcile()+ th_cls.assert_not_called()+ self.assertEqual(self.load(board["id"]), board)++ def test_a_stuck_planner_state_is_still_healed_as_before(self):+ board = _board([_shot(1)], planner={"state": "running", "stage": "write"})+ self.save(board)+ with mock.patch.object(panel.threading, "Thread") as th_cls:+ panel._sb_boot_reconcile()+ th_cls.assert_not_called()+ reloaded = self.load(board["id"])+ self.assertEqual(reloaded["planner"]["state"], "failed")+ self.assertEqual(reloaded["planner"]["error_kind"], "restarted")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_render_job.py b/test_render_job.pynew file mode 100644index 0000000..ac5df43--- /dev/null+++ b/test_render_job.py@@ -0,0 +1,271 @@+#!/usr/bin/env python3+"""FILM-28: the Editor's Render, as a job — progress and Cancel.++Before this, `/storyboard/edit/render` ran the whole ffmpeg pass on the+HTTP handler thread: the request did not answer until the encode finished,+with no way to show progress and no way to change your mind partway+through. `edit/render/start` is a deliberate SECOND door beside the+original `edit/render` — which stays exactly as it always was, still+synchronous, for any caller that has not moved (a curl, a script, an+agent) — that answers immediately with a job id; `edit/render/status`+(GET) polls it; `edit/render/cancel` asks it to stop.++Runs against a scratch OUTPUT/STATE_DIR with ffmpeg mocked (real threading,+real file writes, real route dispatch — only the encoder itself is a+stand-in), the same sandbox test_storyboard_film_integrity.py already uses.+"""+from __future__ import annotations++import sys+import tempfile+import time+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+import storyboard_editor as sedit # noqa: E402+++def _board(bid, title="Night Drive"):+ return {"schema": 1, "id": bid, "title": title, "created_at": 1_700_000_000,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "shots": []}+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)+ # Every job registry starts empty and clean per test — the module+ # level dict would otherwise carry jobs between tests in the same+ # process.+ panel._SB_FILM_JOBS.clear()+ self.clip = root / "a.mp4"+ self.clip.write_bytes(b"clip")+ board = _board("sb_t")+ storyboard.save_storyboard(self.state, board)+ self.bdir = storyboard.board_dir(self.state, "sb_t")+ edit = {"version": sedit.EDIT_VERSION, "board_id": "sb_t", "revision": 0,+ "source": "human", "audio": None, "beats": None, "settings": {},+ "clips": [sedit.new_clip(str(self.clip), 0.0, 2.0, 0.0,+ source="human", duration=2.0)]}+ sedit.save_edit(self.bdir, edit)+ self._probe = mock.patch.object(+ panel, "_sb_probe_clip",+ return_value={"has_audio": False, "duration": 2.0, "w": 640,+ "h": 360, "sample_rate": 0})+ self._probe.start()+ self.addCleanup(self._probe.stop)++ def _post(self, action, form):+ from test_storyboard_editor_api import FakeHandler+ return FakeHandler().post(action, form)++ def _get(self, url):+ from test_storyboard_editor_api import FakeHandler+ return FakeHandler().get(url)++ def _wait_until(self, cond, timeout=5.0):+ deadline = time.time() + timeout+ while time.time() < deadline:+ if cond():+ return True+ time.sleep(0.02)+ return False+++class ASlowRender(Sandbox):+ """ffmpeg takes a moment — long enough to observe "running" for real."""++ def setUp(self):+ super().setUp()+ def fake_ffmpeg(cmd, label):+ time.sleep(0.25)+ Path(cmd[-1]).write_bytes(b"film")+ self._ffmpeg = mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=fake_ffmpeg)+ self._ffmpeg.start()+ self.addCleanup(self._ffmpeg.stop)++ def test_start_answers_immediately_with_a_job_id(self):+ t0 = time.time()+ h = self._post("edit/render/start", {"id": "sb_t"})+ elapsed = time.time() - t0+ self.assertTrue(h.payload.get("ok"), h.payload)+ self.assertIn("job", h.payload)+ # The whole point: the HTTP response does not wait for the encode+ # (0.25s in this fixture) to finish.+ self.assertLess(elapsed, 0.2)++ def test_status_reports_running_then_done(self):+ h = self._post("edit/render/start", {"id": "sb_t"})+ job = h.payload["job"]+ s1 = self._get(f"/storyboard/edit/render/status?job={job}")+ self.assertEqual(s1.payload["state"], "running")+ self.assertNotIn("result", s1.payload)+ self.assertTrue(self._wait_until(+ lambda: self._get(f"/storyboard/edit/render/status?job={job}")+ .payload["state"] != "running"))+ s2 = self._get(f"/storyboard/edit/render/status?job={job}")+ self.assertEqual(s2.payload["state"], "done")+ self.assertTrue(s2.payload["result"]["ok"])+ self.assertIn("path", s2.payload["result"])+ self.assertGreaterEqual(s2.payload["elapsed_sec"], 0)++ def test_an_unknown_job_is_404_on_status_and_cancel(self):+ s = self._get("/storyboard/edit/render/status?job=nope")+ self.assertEqual(s.status, 404)+ c = self._post("edit/render/cancel", {"job": "nope"})+ self.assertEqual(c.status, 404)++ def test_cancel_while_running_discards_the_file_and_the_result(self):+ h = self._post("edit/render/start", {"id": "sb_t"})+ job = h.payload["job"]+ c = self._post("edit/render/cancel", {"job": job})+ self.assertTrue(c.payload["ok"])+ self.assertFalse(c.payload["already_done"])+ self.assertTrue(self._wait_until(+ lambda: self._get(f"/storyboard/edit/render/status?job={job}")+ .payload["state"] != "running"))+ s = self._get(f"/storyboard/edit/render/status?job={job}")+ self.assertEqual(s.payload["state"], "canceled")+ # The file the encoder wrote must not be left behind for a render+ # nobody asked to keep.+ night_dir = panel._sb_film_dir(_board("sb_t"))+ leftover = [p for p in night_dir.glob("*.mp4")] if night_dir.is_dir() else []+ self.assertEqual(leftover, [])++ def test_cancel_after_it_already_finished_is_too_late_and_harmless(self):+ h = self._post("edit/render/start", {"id": "sb_t"})+ job = h.payload["job"]+ self.assertTrue(self._wait_until(+ lambda: self._get(f"/storyboard/edit/render/status?job={job}")+ .payload["state"] != "running"))+ c = self._post("edit/render/cancel", {"job": job})+ self.assertTrue(c.payload["ok"])+ self.assertTrue(c.payload["already_done"])+ s = self._get(f"/storyboard/edit/render/status?job={job}")+ self.assertEqual(s.payload["state"], "done") # the real result stands+ self.assertTrue(s.payload["result"]["ok"])+++class AFastRender(Sandbox):+ """The plain synchronous door is untouched — same behaviour as always."""++ def setUp(self):+ super().setUp()+ def fake_ffmpeg(cmd, label):+ Path(cmd[-1]).write_bytes(b"film")+ self._ffmpeg = mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=fake_ffmpeg)+ self._ffmpeg.start()+ self.addCleanup(self._ffmpeg.stop)++ def test_the_original_route_still_answers_with_the_finished_film(self):+ h = self._post("edit/render", {"id": "sb_t"})+ self.assertTrue(h.payload.get("ok"), h.payload)+ self.assertIn("path", h.payload)+ self.assertNotIn("job", h.payload)++ def test_a_failed_encode_is_filed_as_an_error_job(self):+ def dead(cmd, label):+ raise RuntimeError("disk is full")+ with mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=dead):+ h = self._post("edit/render/start", {"id": "sb_t"})+ job = h.payload["job"]+ self.assertTrue(self._wait_until(+ lambda: self._get(f"/storyboard/edit/render/status?job={job}")+ .payload["state"] != "running"))+ s = self._get(f"/storyboard/edit/render/status?job={job}")+ self.assertEqual(s.payload["state"], "error")+ self.assertIn("disk is full", s.payload["error"])+ self.assertNotIn("result", s.payload)+++class TheJobFunctionDirectly(unittest.TestCase):+ """_sb_film_job_run in isolation — no thread, no HTTP, just the filing+ logic three ways: success, failure, cancel-while-running."""++ def test_success_files_a_done_job(self):+ panel._SB_FILM_JOBS.clear()+ panel._SB_FILM_JOBS["j1"] = {"board_id": "b", "state": "running",+ "started_at": time.time(), "cancel": False,+ "result": None, "error": None}+ with mock.patch.object(panel, "_sbe_render_edit",+ return_value={"ok": True, "path": "/x/f.mp4"}):+ panel._sb_film_job_run("j1", {}, {}, music=None, music_mode=None,+ out_name="f.mp4", deliver={})+ job = panel._SB_FILM_JOBS["j1"]+ self.assertEqual(job["state"], "done")+ self.assertEqual(job["result"]["path"], "/x/f.mp4")+ self.assertIsNone(job["error"])++ def test_failure_files_an_error_job(self):+ panel._SB_FILM_JOBS.clear()+ panel._SB_FILM_JOBS["j1"] = {"board_id": "b", "state": "running",+ "started_at": time.time(), "cancel": False,+ "result": None, "error": None}+ with mock.patch.object(panel, "_sbe_render_edit",+ return_value={"ok": False, "error": "boom"}):+ panel._sb_film_job_run("j1", {}, {}, music=None, music_mode=None,+ out_name="f.mp4", deliver={})+ job = panel._SB_FILM_JOBS["j1"]+ self.assertEqual(job["state"], "error")+ self.assertEqual(job["error"], "boom")++ def test_an_exception_from_the_assembler_is_filed_not_raised(self):+ panel._SB_FILM_JOBS.clear()+ panel._SB_FILM_JOBS["j1"] = {"board_id": "b", "state": "running",+ "started_at": time.time(), "cancel": False,+ "result": None, "error": None}+ with mock.patch.object(panel, "_sbe_render_edit",+ side_effect=RuntimeError("kaboom")):+ panel._sb_film_job_run("j1", {}, {}, music=None, music_mode=None,+ out_name="f.mp4", deliver={})+ job = panel._SB_FILM_JOBS["j1"]+ self.assertEqual(job["state"], "error")+ self.assertIn("kaboom", job["error"])++ def test_cancel_deletes_a_successfully_written_file(self):+ with tempfile.TemporaryDirectory() as d:+ out_path = Path(d) / "f.mp4"+ out_path.write_bytes(b"film")+ panel._SB_FILM_JOBS.clear()+ panel._SB_FILM_JOBS["j1"] = {"board_id": "b", "state": "running",+ "started_at": time.time(), "cancel": True,+ "result": None, "error": None}+ with mock.patch.object(panel, "_sbe_render_edit",+ return_value={"ok": True, "path": str(out_path)}):+ panel._sb_film_job_run("j1", {}, {}, music=None, music_mode=None,+ out_name="f.mp4", deliver={})+ job = panel._SB_FILM_JOBS["j1"]+ self.assertEqual(job["state"], "canceled")+ self.assertFalse(out_path.exists())++ def test_a_job_that_has_since_vanished_is_a_no_op(self):+ # The registry can be swept between a job starting and finishing in+ # a very long-idle process — filing into nothing must not raise.+ panel._SB_FILM_JOBS.clear()+ with mock.patch.object(panel, "_sbe_render_edit",+ return_value={"ok": True, "path": "/x/f.mp4"}):+ panel._sb_film_job_run("ghost", {}, {}, music=None, music_mode=None,+ out_name="f.mp4", deliver={}) # must not raise+ self.assertEqual(panel._SB_FILM_JOBS, {})+++if __name__ == "__main__":+ unittest.main()diff --git a/test_retake.py b/test_retake.pyindex 72b1255..44c85a9 100644--- a/test_retake.py+++ b/test_retake.py@@ -83,6 +83,40 @@ class TheRetake(unittest.TestCase):self.assertNotIn("draft_output", new)stj.assert_called_once()+ def test_a_retake_does_not_inherit_the_sources_job_ids(self):+ # FILM-09: the source shot carries a FINISHED delivery job. The old+ # exclude list checked `k.endswith("_job")`, but the real field is+ # `final_job_id` — which does NOT end in "_job" — so it rode along+ # onto the "new" retake shot, and the reconciler folded the OLD+ # final clip back onto it: "Retake (Delivery)" silently handed back+ # the same clip it started from.+ self.board["shots"][0].update({+ "draft_job_id": "j-old-draft", "final_job_id": "j-old-final",+ "still_job_id": "j-old-still", "error": "a stale error",+ "lipsync": {"score": 0.9, "attempts": 1, "kept": "/x/old.mp4"},+ })+ h = FakeHandler()+ with mock.patch.object(panel, "_sb_known_character_ids", return_value=["bizarrotrn"]), \+ mock.patch.object(panel, "_sb_h3_available", return_value=False), \+ mock.patch.object(storyboard, "shot_to_job", return_value={"mode": "t2v", "prompt": "p"}):+ h.post("edit/generate", {"id": "sb_t", "prompt": "he turns, slower",+ "duration": "4", "film_start": "0",+ "retake_of": "c1"})+ self.assertEqual(h.status, 202, h.payload)+ new = self.board["shots"][-1]+ # `final_job_id`, `still_job_id`, `error` and `lipsync` must never+ # ride along at all — the new shot has not rendered yet.+ for key in ("final_job_id", "still_job_id", "error", "lipsync"):+ self.assertNotIn(key, new, f"retake inherited the source's {key!r}")+ # `draft_job_id` IS legitimately set — by queuing THIS shot's OWN+ # job a moment later — but it must be the fresh id, never the+ # source's old one.+ self.assertEqual(new.get("draft_job_id"), "j-take")+ self.assertNotEqual(new.get("draft_job_id"), "j-old-draft")+ # the clone contract for everything else still holds+ self.assertEqual(new["character_id"], "bizarrotrn")+ self.assertEqual(new["location"], "the study")+def test_a_retake_of_a_clip_that_left_is_refused(self):h = FakeHandler()h.post("edit/generate", {"id": "sb_t", "prompt": "x", "retake_of": "zz"})diff --git a/test_retry_smaller.py b/test_retry_smaller.pynew file mode 100644index 0000000..f68651a--- /dev/null+++ b/test_retry_smaller.py@@ -0,0 +1,204 @@+"""VC-08: the out-of-memory failure card offers "Retry smaller", not only a+retry of the identical job that will fail the same way.++WHAT THIS GUARDS. The failed Now-card's only action used to be Retry, which+re-submits the exact params that just OOM'd — same quality, same length,+guaranteed to fail again after another 10+ minutes on a memory-pressured Mac.++Server: /queue/retry now accepts an optional `overrides` form field (a JSON+object, allowlisted to {quality, frames} — never an arbitrary merge) applied+onto the source job's params before it's re-queued, still going through the+same _validate_character_quality gate as every other enqueue path.++Client: queue.js's smallerRetryOverrides(params) walks the quality ladder+down one rung and caps frames at 121 (5s) when the source job was longer;+the failed card shows "Retry smaller" + "Retry as is" only when the failure+looks memory-shaped (SIGKILL/jetsam) AND a smaller version actually exists,+otherwise just the original single "Retry".+"""+from __future__ import annotations++import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from urllib.parse import parse_qs, urlencode++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-retry-smaller-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8318")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+from panel.routes import POST_ROUTES # noqa: E402++sys.path.insert(0, str(ROOT / "scripts"))+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+++class _H:+ def __init__(s, body):+ s.body, s.out, s.code = body, None, None++ def _read_form_body(s):+ return s.body, parse_qs(s.body)++ def _json(s, obj, code=200):+ s.out, s.code = obj, code+++def _post_retry(**form):+ h = _H(urlencode(form))+ POST_ROUTES["/queue/retry"](h, "/queue/retry", {}, "")+ return h.code, h.out+++class ServerOverridesAreAllowlisted(unittest.TestCase):+ def setUp(self):+ with P.QUEUE_COND:+ self._before_hist = list(P.STATE["history"])+ self._before_queue = list(P.STATE["queue"])+ P.STATE["history"].insert(0, {+ "id": "srcjob1", "status": "failed",+ "params": {"mode": "t2v", "prompt": "a lighthouse", "quality": "standard",+ "frames": 241, "width": 1280, "height": 704,+ "engine": "ltx", "no_voice": "off"},+ })+ self.addCleanup(self._restore)++ def _restore(self):+ with P.QUEUE_COND:+ P.STATE["history"] = self._before_hist+ P.STATE["queue"] = self._before_queue++ def _queued_ids(self):+ with P.QUEUE_COND:+ before = {j["id"] for j in self._before_queue}+ return [j for j in P.STATE["queue"] if j["id"] not in before]++ def test_no_overrides_copies_verbatim(self):+ code, out = _post_retry(id="srcjob1")+ self.assertEqual(code, 200)+ self.assertTrue(out["ok"])+ q = self._queued_ids()+ self.assertEqual(len(q), 1)+ self.assertEqual(q[0]["params"]["quality"], "standard")+ self.assertEqual(q[0]["params"]["frames"], 241)++ def test_quality_and_frames_override_applies(self):+ overrides = json.dumps({"quality": "balanced", "frames": 121})+ code, out = _post_retry(id="srcjob1", overrides=overrides)+ self.assertEqual(code, 200)+ self.assertTrue(out["ok"])+ q = self._queued_ids()+ self.assertEqual(q[0]["params"]["quality"], "balanced")+ self.assertEqual(q[0]["params"]["frames"], 121)+ # everything else still came from the source job, untouched+ self.assertEqual(q[0]["params"]["prompt"], "a lighthouse")+ self.assertEqual(q[0]["params"]["width"], 1280)++ def test_unknown_override_key_is_refused(self):+ overrides = json.dumps({"width": 99999})+ code, out = _post_retry(id="srcjob1", overrides=overrides)+ self.assertEqual(code, 400)+ self.assertIn("width", out["error"])+ self.assertEqual(self._queued_ids(), [])++ def test_unknown_quality_value_is_refused(self):+ overrides = json.dumps({"quality": "ultra"})+ code, out = _post_retry(id="srcjob1", overrides=overrides)+ self.assertEqual(code, 400)+ self.assertEqual(self._queued_ids(), [])++ def test_malformed_json_is_refused(self):+ code, out = _post_retry(id="srcjob1", overrides="{not json")+ self.assertEqual(code, 400)+ self.assertEqual(self._queued_ids(), [])++ def test_overrides_still_run_the_character_quality_gate(self):+ P.STATE["history"].insert(0, {+ "id": "srcjob2", "status": "failed",+ "params": {"mode": "t2v", "prompt": "a hero", "quality": "high",+ "frames": 121, "character_id": "somechar",+ "engine": "ltx", "no_voice": "off"},+ })+ # Stepping this down to balanced would reproduce the exact+ # character+non-high combination /queue/add already refuses -+ # the override path must hit the same gate, not bypass it.+ overrides = json.dumps({"quality": "balanced"})+ code, out = _post_retry(id="srcjob2", overrides=overrides)+ self.assertEqual(code, 400)+ self.assertEqual(self._queued_ids(), [])+++class FailedCardOffersBothButtonsOnlyForMemoryFailures(unittest.TestCase):+ """4.17 merge: VC-08 (this suite) and SYS-07 both built "Retry smaller".+ One implementation ships: friendlyJobError flags `smaller` for the OOM+ and GPU-watchdog classes on LTX only (H3-22 — an H3 job has no LTX+ quality/canvas to step), the card shows "Retry smaller" + "Retry as is",+ and the click goes to /queue/retry with smaller=1, where the server+ shrinks the canvas too. VC-08's client ladder only stepped `quality`,+ which leaves the stored width/height — the canvas that actually decides+ memory — unchanged; it was removed. The server's allowlisted `overrides`+ field (ServerOverridesAreAllowlisted above) stays for API callers."""++ def _flags(self, *cases) -> list:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ # friendlyJobError's generic fallback calls H3-22's _redactLocalPaths.+ fn = (extract_function("_redactLocalPaths", src) + "\n"+ + extract_function("friendlyJobError", src))+ calls = ",\n ".join(+ f"(friendlyJobError({json.dumps(raw)}, {json.dumps(eng)}) || {{}}).smaller === true"+ for raw, eng in cases)+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(fn + f"\nconsole.log(JSON.stringify([\n {calls}\n]));")+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ self.assertEqual(r.returncode, 0, r.stderr[-2000:])+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)++ def test_smaller_is_offered_for_ltx_memory_and_watchdog_failures_only(self):+ got = self._flags(+ ("Helper killed by the OS: SIGKILL", "ltx"),+ ("helper exited from SIGABRT (GPU watchdog timeout)", "ltx"),+ ("Helper killed by the OS: SIGKILL", "h3"),+ ("shape mismatch (256, 256) vs (272, 272)", "ltx"),+ )+ self.assertEqual(got, [True, True, False, False])++ def test_card_offers_retry_smaller_and_retry_as_is(self):+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ self.assertIn('data-action="retry-smaller"', src)+ self.assertIn("<span>Retry as is</span>", src)+ self.assertNotIn("smallerRetryOverrides", src)++ def test_delegated_handler_sends_the_server_side_smaller_retry(self):+ main = (ROOT / "webapp" / "js" / "main.js").read_text(encoding="utf-8")+ self.assertEqual(main.count("btn.dataset.action === 'retry-smaller'"), 1)+ self.assertIn("retryJob(id, { smaller: true })", main)++ def test_oom_copy_drops_jargon(self):+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ # The sigkill branch of friendlyJobError - pull just that literal.+ self.assertIn("Your Mac ran out of memory.", src)+ self.assertNotIn("Helper killed by the OS", src)+ self.assertNotIn("(jetsam)", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_review_416_jobs.py b/test_review_416_jobs.pyindex 77642eb..83cea63 100644--- a/test_review_416_jobs.py+++ b/test_review_416_jobs.py@@ -137,11 +137,17 @@ class CompactMacsRefuseOversizedA2V(unittest.TestCase):src = panel_source()js = """var A2V_AREA_KNEE = 0.45e6, A2V_KNEE_FRAMES = 450, BOOT;+// VA-03: the window-vs-file check reads AUDIO_STUDIO.audioDuration and the+// Start at field — null/absent here means "duration unknown", the same as+// a file that hasn't been uploaded yet, so the pre-existing cap/knee checks+// below are exercised unchanged.+var AUDIO_STUDIO = {audioDuration: null};const els = {};function el(id, v) { return els[id] = {id, value: v, style: {}, innerHTML: '', textContent: ''}; }const document = { getElementById: id => els[id] || null };el('audioStudioDuration', '30'); el('audioStudioDurationVal');el('audioStudioDurationWarn'); el('audioStudioWidth', '768'); el('audioStudioHeight', '416');+el('audioStudioStart', '0');""" + "\n".join(extract_function(n, src) for n in ("_a2vFramesForSeconds", "audioStudioDurationChanged")) + """const out = {};diff --git a/test_review_416_ltx.py b/test_review_416_ltx.pyindex e35f9c8..3115963 100644--- a/test_review_416_ltx.py+++ b/test_review_416_ltx.py@@ -390,7 +390,8 @@ var AUDIO_STUDIO = {busy: false, audioPath: null, audioName: null, audioDurationwindow = globalThis; window.PHOSPHENE_CAP_TIER = 'q8';const els = {};function el(id, v) { return els[id] = {id, value: v === undefined ? '' : v, style: {}, dataset: {},- innerHTML: '', textContent: '', disabled: false, open: false}; }+ innerHTML: '', textContent: '', disabled: false, open: false,+ scrollIntoView(){}, classList: {add(){}, remove(){}, toggle(){}, contains(){ return false; }}}; }['audioStudioPrompt', 'audioStudioStatus', 'audioStudioGenBtn', 'audioStudioDurationVal','audioStudioDurationWarn', 'audioConditioningScaleVal', 'audioConditioningScaleHint','mvOneShotDetails', 'a2v_image'].forEach(i => el(i));@@ -400,6 +401,7 @@ const document = { getElementById: id => els[id] || null };function audioModeSet(m) { calls.push('audioMode:' + m); }function workflowSwitch(w) { calls.push('workflow:' + w); }function audioStudioRenderSlots() {}+function audioStudioRenderLoraNote() {}function pickerSetImage(k, v) { if (k === 'a2v_image') els.a2v_image.value = v; calls.push('picker:' + k + '=' + v); }function _restoreLoraPicker(l) { calls.push('loras:' + l.length); _activeLoras = l; }function setMode(m) { calls.push('setMode:' + m); }@@ -488,6 +490,7 @@ function _mk(id, v) {}var document = {getElementById: id => _els[id] || _mk(id), querySelector: () => null,querySelectorAll: () => [], body: {dataset: {}, classList: {toggle(){}}}};+var window = globalThis;var BOOT = {ltx: {qualities: [{key: 'balanced', pipeline: 'distilled'}]}}, currentMode = 't2v',activePath = '/x.mp4', FPS = 24;_mk('mode', 't2v'); _mk('quality', 'balanced'); _mk('frames', '481');@@ -508,12 +511,23 @@ class WindowedClipsReloadAsWindowed(unittest.TestCase):src = panel_source()fns = ("_qualityUsesHq", "temporalModeAllowed", "setTemporalMode","windowPromptsInput", "loadParams")+ # VA-18: the per-window text moved from a synchronous textarea to+ # dynamically-rendered boxes built from an async /ltx/windows_plan+ # fetch (_renderWindowsSlotsFromPlan, not extracted here — it needs+ # a real DOM's innerHTML/querySelectorAll, which this hand-rolled+ # _mk()-based shim cannot simulate). What THIS harness can still+ # prove synchronously: loadParams restores temporal_mode and+ # window_invariants correctly, and stashes the sidecar's+ # window_prompts array in window._pendingWindowPromptsRestore for+ # the (untested-here) render step to consume. The full render is+ # covered structurally in test_lipsync_mode.py's+ # SlidingWindowsOffByOne class.js = LOOSE_SHIM + "with (SHIM) {\n" + "\n".join(extract_function(n, src) for n in fns) + """globalThis.fetch = async () => ({ok: true, json: async () => (%s)});loadParams().then(() => console.log(JSON.stringify({temporal: document.getElementById('temporal_mode').value,- prompts: document.getElementById('window_prompts').value,+ pendingRestore: (typeof window !== 'undefined' ? window._pendingWindowPromptsRestore : null),invariants: document.getElementById('window_invariants').value})),e => { console.error(e); process.exit(1); });}""" % json.dumps({"output": "/x.mp4", "params": params})@@ -530,8 +544,11 @@ loadParams().then(() => console.log(JSON.stringify({self.assertEqual(saved["long_mode"], "windows")got = self._load(saved)self.assertEqual(got["temporal"], "windows")+ self.assertEqual(got["invariants"], "same pond, same dusk light")+ # The exact array from the sidecar, staged for the render step.+ self.assertEqual(got["pendingRestore"], ["opening", "", "the hen jumps", "landing"])again = P.make_job({**form, "temporal_mode": got["temporal"],- "window_prompts": got["prompts"],+ "window_prompts": json.dumps(got["pendingRestore"]),"window_invariants": got["invariants"]})["params"]self.assertEqual(again["long_mode"], "windows")self.assertEqual(again["window_prompts"], saved["window_prompts"])@@ -541,7 +558,7 @@ loadParams().then(() => console.log(JSON.stringify({saved = P.make_job({"mode": "t2v", "prompt": "x", "frames": "121"})["params"]got = self._load(saved)self.assertEqual(got["temporal"], "native")- self.assertEqual(got["prompts"], "")+ self.assertIsNone(got["pendingRestore"])self.assertEqual(got["invariants"], "")diff --git a/test_safety_mega_fixes.py b/test_safety_mega_fixes.pynew file mode 100644index 0000000..22940e9--- /dev/null+++ b/test_safety_mega_fixes.py@@ -0,0 +1,520 @@+"""Safety package (2026-09-29 mega review) — VC-03, VC-04, VC-05, VC-06,+VC-35, VC-38, H3-11, VA-08, VA-09, VA-10, VA-17.++Theme: no one-click destruction, and "another take" works. Covers the new+backend routes (/queue/newtake, /queue/restore, /stop/after_part,+/take/resume, /take/join_partial) and run_take_job_inner's partial-take+recovery. The frontend half (workflowSwitch tab fixes, the seed-lock chip,+the draft autosave, the destructive-action dialogs) is covered by+lint_webapp.mjs (every cross-module reference resolves) plus the existing+JS-extraction suites this package updated in place (test_face_fix.py,+test_review_416_ltx.py, test_outputs_cache_invalidation.py) rather than+duplicated here.+"""+from __future__ import annotations++import io+import json+import sys+import unittest+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as p # noqa: E402++routes_queue = sys.modules["panel.routes_queue"]+++class _H:+ """A fake HTTP handler good enough for both calling conventions the new+ routes use: form-encoded (_read_form_body) and raw JSON body (headers ++ rfile), matching the shape routes_oneshot.py's _read_document expects."""++ def __init__(self, form=None, json_body=None, qs=None):+ self._form = form or {}+ self.status = None+ self.payload = None+ self.qs = qs or {}+ if json_body is not None:+ raw = json.dumps(json_body).encode()+ self.headers = {"Content-Length": str(len(raw))}+ self.rfile = io.BytesIO(raw)++ def _read_form_body(self):+ return ("", {k: [v] for k, v in self._form.items()})++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++def _tiny_clip(path: Path) -> None:+ import subprocess+ subprocess.run(+ ["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=red:s=32x32:d=0.2",+ "-f", "lavfi", "-i", "anullsrc=r=8000:cl=mono", "-t", "0.2",+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", str(path)],+ check=True,+ )++[email protected](autouse=True)+def _sandbox(tmp_path, monkeypatch):+ out = tmp_path / "out"; out.mkdir()+ monkeypatch.setattr(p, "OUTPUT", out)+ monkeypatch.setattr(p, "UPLOADS", tmp_path / "up")+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")+ with p.QUEUE_COND:+ p.STATE["queue"] = []+ p.STATE["current"] = None+ p.STATE["history"] = []+ monkeypatch.setattr(p, "persist_queue", lambda: None)+ yield out+++# ---------------------------------------------------------------------------+# VC-03 — New Take: same recipe, fresh seed, one click, sourced from disk.+# ---------------------------------------------------------------------------++def _write_output_with_sidecar(out_dir: Path, name: str, params: dict) -> Path:+ clip = out_dir / name+ _tiny_clip(clip)+ (clip.with_suffix(clip.suffix + ".json")).write_text(json.dumps({"params": params}))+ return clip+++def test_newtake_replays_the_recipe_with_a_fresh_seed(_sandbox):+ out_dir = _sandbox+ clip = _write_output_with_sidecar(out_dir, "a.mp4", {+ "mode": "t2v", "prompt": "a hen skates", "seed": "42", "seed_used": 42,+ "width": 1024, "height": 576, "quality": "balanced",+ "loras": [{"path": "/l/x.safetensors", "strength": 0.8}],+ })+ h = _H(form={"path": str(clip)})+ routes_queue.post_queue_newtake(h, "/queue/newtake", {}, "")+ assert h.status == 200 and h.payload["ok"] is True+ assert len(p.STATE["queue"]) == 1+ job = p.STATE["queue"][0]+ assert job["params"]["seed"] == "-1" # the ONLY thing that changed+ assert "seed_used" not in job["params"]+ assert job["params"]["prompt"] == "a hen skates"+ assert job["params"]["width"] == 1024 and job["params"]["quality"] == "balanced"+ assert job["params"]["loras"][0]["path"] == "/l/x.safetensors"+ assert job["params"]["source"] == "new_take"+ assert job["id"] != ""+++def test_newtake_reruns_a_whole_one_shot_with_a_fresh_seed(_sandbox):+ # Coordinator review, item 2: New Take on a One Shot re-runs the whole+ # take with a new seed rather than refusing outright. The sidecar's+ # `take.parts` (rendered file paths, post-completion) and `take.beats`+ # (the resolved text list) are NOT the beat-index/part-count shape+ # run_take_job_inner needs to start fresh — that's rebuilt from+ # take_plan(), which is exactly what a first-time One Shot submit does.+ clip = _write_output_with_sidecar(_sandbox, "take.mp4", {+ "mode": "i2v", "prompt": "a hen skates", "seed": "42", "seed_used": 42,+ "engine": "h3",+ "take": {+ "seconds": 30, "beats": ["b0", "b1", "b2", "b3", "b4", "b5"],+ "parts": ["/out/take.mp4"], # post-completion: file paths, not index groups+ "engine": "h3", "beats_per_part": 3, "light_lock": "warm evening light",+ "retake": False, "camera": "slow dolly in", "handoff": "speech",+ },+ })+ h = _H(form={"path": str(clip)})+ routes_queue.post_queue_newtake(h, "/queue/newtake", {}, "")+ assert h.status == 200 and h.payload["ok"] is True+ assert len(p.STATE["queue"]) == 1+ job = p.STATE["queue"][0]["params"]+ assert job["seed"] == "-1"+ assert "seed_used" not in job+ new_take = job["take"]+ # A fresh, correctly-shaped plan for 30s/h3 (10 beats... 30/5=6 beats,+ # 2 parts of 3) — NOT the stored file-path list.+ assert new_take["parts"] == [[0, 1, 2], [3, 4, 5]]+ assert new_take["beats"] == 6 # take_plan's own count, not the text list+ assert new_take["beat_prompts"] == ["b0", "b1", "b2", "b3", "b4", "b5"]+ assert new_take["light_lock"] == "warm evening light"+ assert new_take["retake"] is False+ assert new_take["camera"] == "slow dolly in"+ assert new_take["handoff"] == "speech"+ assert "_resume" not in new_take+++def test_newtake_one_shot_with_an_invalid_stored_length_is_refused(_sandbox):+ clip = _write_output_with_sidecar(_sandbox, "take.mp4", {+ "mode": "t2v", "prompt": "x",+ "take": {"seconds": 999, "beats": ["a"], "engine": "ltx"},+ })+ h = _H(form={"path": str(clip)})+ routes_queue.post_queue_newtake(h, "/queue/newtake", {}, "")+ assert h.status == 400+ assert p.STATE["queue"] == []+++def test_newtake_404s_outside_outputs_and_uploads(_sandbox, tmp_path):+ outside = tmp_path / "elsewhere.mp4"+ outside.write_bytes(b"x")+ (tmp_path / "elsewhere.mp4.json").write_text(json.dumps({"params": {"prompt": "x"}}))+ h = _H(form={"path": str(outside)})+ routes_queue.post_queue_newtake(h, "/queue/newtake", {}, "")+ assert h.status == 404+++# ---------------------------------------------------------------------------+# VC-06 — Clear queue's Undo path: /queue/restore replays exactly what+# /queue/clear emptied, in order, with fresh ids.+# ---------------------------------------------------------------------------++def test_queue_restore_requeues_every_job_in_order(_sandbox):+ jobs = [{"params": {"prompt": f"p{i}", "mode": "t2v"}} for i in range(3)]+ h = _H(json_body={"jobs": jobs})+ routes_queue.post_queue_restore(h, "/queue/restore", {}, "application/json")+ assert h.status == 200 and h.payload["ok"] is True+ assert h.payload["restored"] == 3+ assert [j["params"]["prompt"] for j in p.STATE["queue"]] == ["p0", "p1", "p2"]+ ids = [j["id"] for j in p.STATE["queue"]]+ assert len(set(ids)) == 3 # fresh ids, no collisions+++def test_queue_restore_rejects_a_non_json_body(_sandbox):+ h = _H()+ h.headers = {"Content-Length": "9"}+ h.rfile = io.BytesIO(b"not-json!")+ routes_queue.post_queue_restore(h, "/queue/restore", {}, "application/json")+ assert h.status == 400+++def test_queue_restore_rejects_an_empty_jobs_list(_sandbox):+ h = _H(json_body={"jobs": []})+ routes_queue.post_queue_restore(h, "/queue/restore", {}, "application/json")+ assert h.status == 400+++# ---------------------------------------------------------------------------+# H3-11 — "Stop after this part": only meaningful mid-take, sets a flag the+# take loop honours at the next part boundary (see run_take_job_inner tests+# below for the loop side of this).+# ---------------------------------------------------------------------------++def test_stop_after_part_refuses_when_nothing_is_a_take(_sandbox):+ with p.LOCK:+ p.STATE["current"] = {"id": "j1", "params": {"mode": "t2v"}}+ h = _H()+ routes_queue.post_stop_after_part(h, "/stop/after_part", {}, "")+ assert h.status == 409+++def test_stop_after_part_refuses_when_idle(_sandbox):+ with p.LOCK:+ p.STATE["current"] = None+ h = _H()+ routes_queue.post_stop_after_part(h, "/stop/after_part", {}, "")+ assert h.status == 404+++def test_stop_after_part_arms_the_flag_on_a_take(_sandbox):+ job = {"id": "j1", "params": {"take": {"seconds": 30}}}+ with p.LOCK:+ p.STATE["current"] = job+ h = _H()+ routes_queue.post_stop_after_part(h, "/stop/after_part", {}, "")+ assert h.status == 200 and job["stop_after_part"] is True+++# ---------------------------------------------------------------------------+# VA-17 — a stopped/failed One Shot keeps its finished parts, with Resume+# and Join what's done. run_take_job_inner's own recovery path, end to end.+# ---------------------------------------------------------------------------++def test_take_stop_keeps_parts_unhidden_with_a_resume_manifest(tmp_path, monkeypatch):+ out_dir = tmp_path / "out"; out_dir.mkdir(exist_ok=True)+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")+ hidden_calls = []+ monkeypatch.setattr(p, "set_hidden", lambda path, flag: hidden_calls.append((path, flag)))++ made = []++ def fake_h3(child):+ out = out_dir / f"{child['id']}.mp4"+ _tiny_clip(out)+ child["output_path"] = str(out)+ made.append(out)+ if len(made) == 1:+ job["cancel_requested"] = True # Stop lands right after part 1 finishes++ monkeypatch.setattr(p, "run_h3_job_inner", fake_h3)+ monkeypatch.setattr(p, "take_drift", lambda *a, **k: {"ok": True, "delta": 0.0, "drifted": False})+ job = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "a hen skates",+ "take_seconds": "45",+ "beats": json.dumps([f"b{i}" for i in range(9)])})+ with pytest.raises(RuntimeError, match="(?i)stopped"):+ p.run_take_job_inner(job)++ # Part 1 was hidden as a normal working file, then UN-hidden again by the+ # recovery path once the take stopped — net effect: visible.+ part1 = made[0]+ unhide_calls = [c for c in hidden_calls if c[0] == str(part1)]+ assert unhide_calls[-1] == (str(part1), False)++ side = json.loads((part1.with_suffix(part1.suffix + ".json")).read_text())+ assert side["label"].endswith("(unfinished)")+ manifest = side.get("one_shot_unfinished")+ assert manifest is not None+ assert manifest["done_parts"] == 1+ assert manifest["total_parts"] == 3 # 9 beats / 3 per part on H3+ assert manifest["outs"] == [str(part1)]+ assert manifest["job_id"] == job["id"]+++def test_take_resume_route_continues_from_the_manifest(tmp_path, monkeypatch):+ out_dir = tmp_path / "out"; out_dir.mkdir(exist_ok=True)+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")+ monkeypatch.setattr(p, "UPLOADS", tmp_path / "up")+ monkeypatch.setattr(p, "set_hidden", lambda *a, **k: None)+ monkeypatch.setattr(p, "persist_queue", lambda: None)+ with p.QUEUE_COND:+ p.STATE["queue"] = []++ part1 = out_dir / "part1.mp4"+ _tiny_clip(part1)+ manifest = {+ "job_id": "j-old", "done_parts": 1, "total_parts": 3,+ "outs": [str(part1)], "last_png": None,+ "take": {"seconds": 45, "beats": ["b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8"],+ "parts": [[0, 1, 2], [3, 4, 5], [6, 7, 8]], "engine": "h3",+ "beats_per_part": 3, "light_lock": "", "retake": True,+ "camera": "", "handoff": "last"},+ "label": "ride", "engine": "h3",+ "p": {"mode": "t2v", "engine": "h3", "prompt": "a hen skates", "label": "ride"},+ }+ part1.with_suffix(part1.suffix + ".json").write_text(+ json.dumps({"label": "ride · part 1 of 3 (unfinished)", "one_shot_unfinished": manifest}))++ h = _H(form={"path": str(part1)})+ routes_queue.post_take_resume(h, "/take/resume", {}, "")+ assert h.status == 200 and h.payload["ok"] is True+ assert h.payload["resumed_from_part"] == 1+ assert len(p.STATE["queue"]) == 1+ resumed = p.STATE["queue"][0]["params"]+ assert resumed["take"]["_resume"]["outs"] == [str(part1)]+ assert resumed["take"]["_resume"]["start_k"] == 1+ assert resumed["prompt"] == "a hen skates"+++def test_take_join_partial_publishes_what_finished(tmp_path, monkeypatch):+ out_dir = tmp_path / "out"; out_dir.mkdir(exist_ok=True)+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "UPLOADS", tmp_path / "up")+ hidden_calls = []+ monkeypatch.setattr(p, "set_hidden", lambda path, flag: hidden_calls.append((path, flag)))++ part1 = out_dir / "part1.mp4"+ _tiny_clip(part1)+ manifest = {+ "job_id": "j-old", "done_parts": 1, "total_parts": 3,+ "outs": [str(part1)], "last_png": None,+ "take": {"seconds": 45}, "label": "ride", "engine": "h3",+ "p": {"mode": "t2v", "engine": "h3", "prompt": "a hen skates", "label": "ride"},+ }+ part1.with_suffix(part1.suffix + ".json").write_text(+ json.dumps({"label": "ride · part 1 of 3 (unfinished)", "one_shot_unfinished": manifest}))++ h = _H(form={"path": str(part1)})+ routes_queue.post_take_join_partial(h, "/take/join_partial", {}, "")+ assert h.status == 200 and h.payload["ok"] is True+ assert h.payload["parts_joined"] == 1+ final = Path(h.payload["output"])+ assert final.is_file()+ side = json.loads(final.with_suffix(final.suffix + ".json").read_text())+ assert side["take"]["stopped_early"] is True+ assert side["take"]["joined_partial"] is True+ assert "(stopped early)" in side["label"]+ # The raw part is a working file again now that it's been published.+ assert (str(part1), True) in hidden_calls+++def test_take_join_partial_404s_without_a_manifest(tmp_path, monkeypatch):+ out_dir = tmp_path / "out"; out_dir.mkdir(exist_ok=True)+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "UPLOADS", tmp_path / "up")+ clip = out_dir / "ordinary.mp4"+ _tiny_clip(clip)+ clip.with_suffix(clip.suffix + ".json").write_text(json.dumps({"label": "ordinary clip"}))+ h = _H(form={"path": str(clip)})+ routes_queue.post_take_join_partial(h, "/take/join_partial", {}, "")+ assert h.status == 404+++def test_take_stop_after_part_finishes_cleanly_with_fewer_parts(tmp_path, monkeypatch):+ """The OTHER half of H3-11: 'stop after this part' is not a failure —+ the take joins and publishes normally, just shorter than asked."""+ out_dir = tmp_path / "out"; out_dir.mkdir(exist_ok=True)+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")+ monkeypatch.setattr(p, "set_hidden", lambda *a, **k: None)+ made = []++ def fake_h3(child):+ out = out_dir / f"{child['id']}.mp4"+ _tiny_clip(out)+ child["output_path"] = str(out)+ made.append(out)+ if len(made) == 1:+ job["stop_after_part"] = True # asked to stop after part 1++ monkeypatch.setattr(p, "run_h3_job_inner", fake_h3)+ monkeypatch.setattr(p, "take_drift", lambda *a, **k: {"ok": True, "delta": 0.0, "drifted": False})+ job = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "a hen skates",+ "take_seconds": "45",+ "beats": json.dumps([f"b{i}" for i in range(9)])})+ p.run_take_job_inner(job) # must NOT raise+ assert len(made) == 1+ final = Path(job["output_path"])+ assert final.is_file()+ side = json.loads(final.with_suffix(final.suffix + ".json").read_text())+ assert side["take"]["stopped_early"] is True+ assert len(side["take"]["parts"]) == 1+++# ---------------------------------------------------------------------------+# H3-11 (full scope): a plain chained H3 render — no One Shot wrapper, just a+# 10/15 s tier that renders as N windows in ONE subprocess call. The coordinator+# review flagged that the first pass only covered One Shot; this covers the+# other shape it explicitly named: Stop during window 3 must not throw away+# windows 1-2. Runs the REAL run_h3_job_inner against a fake "runner" — a+# small script standing in for the vendored H3 CLI (not installed on this+# machine) — that prints the same window/phase/step log lines the real one+# does and writes a real tiny mp4 to `-o` after "finishing" window 1, then+# hangs. /stop/after_part's flag should make the panel SIGTERM it right when+# window 2 starts, and the file window 1 already wrote should get published.+import subprocess as _subprocess # noqa: E402+import tempfile # noqa: E402+import textwrap # noqa: E402+import time # noqa: E402+import unittest.mock # noqa: E402+from contextlib import ExitStack # noqa: E402++_H3_TMP = Path(tempfile.mkdtemp(prefix="phos-h3-window-stop-"))+++def _write_fake_h3_runner() -> Path:+ """A stand-in for the vendored H3 CLI: prints the exact log shape+ run_h3_job_inner parses (### window N/M ###, == phase ==, step X/Y:),+ writes a real tiny mp4 to `-o` once "window 1" is done, then announces+ window 2 and sleeps — long enough that the panel's SIGTERM (sent the+ instant it sees the window-2 line, per the stop_after_part flag) always+ lands before this script would finish on its own."""+ script = _H3_TMP / "fake_h3_runner.py"+ script.write_text(textwrap.dedent("""+ import subprocess, sys, time+ args = sys.argv[1:]+ out_path = args[args.index('-o') + 1]+ print("== text_encode_q8 ==", flush=True)+ print("### window 1/2 ###", flush=True)+ print("== w1_joint_denoise ==", flush=True)+ for s in (1, 2):+ print(f"step {s}/2:", flush=True)+ time.sleep(0.03)+ print("== w1_encode_mux ==", flush=True)+ # Real H3 output is well over the panel's 50 KB partial-clip floor+ # (_h3_partial_clip_info) even for one short window; a flat `color`+ # source (what the other fake-clip helpers in this repo use for cheap+ # presence checks) h264-compresses to a few KB regardless of+ # resolution/duration, so this needs a source with real per-frame+ # detail (testsrc's moving pattern) to size like a real clip does.+ subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",+ "-i", "testsrc=size=640x384:duration=1.5:rate=24", "-f", "lavfi",+ "-i", "anullsrc=r=8000:cl=mono", "-t", "1.5",+ "-c:v", "libx264", "-crf", "0", "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-shortest", out_path], check=True)+ print("### window 2/2 ###", flush=True)+ time.sleep(30)+ print("== w2_joint_denoise ==", flush=True)+ """), encoding="utf-8")+ return script+++def _h3_chain_dispatch_patches(stack, popen):+ """Same shape as test_h3_stop_and_companion.py's _h3_dispatch_patches,+ but h3_supports_chain() answers True (a chained tier needs it) and+ H3_ROOT is a real directory (the real renderer Popen call uses it as+ cwd, and none of the existing H3 tests reach that far)."""+ paths = dict(missing=[], repairable=False, dit=_H3_TMP / "dit",+ python=sys.executable, runner=_write_fake_h3_runner(),+ compact_root=_H3_TMP / "compact", text_config=_H3_TMP / "text")+ for name, val in {+ "h3_paths": lambda: paths, "h3_capable": lambda: True,+ "h3_supports_lora": lambda: True, "h3_dit_choice": lambda: ("bf16", None),+ "output_codec_settings": lambda: {"crf": "18", "pix_fmt": "yuv420p"},+ "_h3_runner_has_flag": lambda flag: flag == "--chain-windows",+ "h3_supports_lora_adaln": lambda: True}.items():+ stack.enter_context(unittest.mock.patch.object(p, name, val))+ for name in ("h3_supports_memory_limits", "h3_supports_prompt_cache",+ "h3_live_preview_ready", "h3_supports_stage_a", "h3_supports_tae_draft"):+ stack.enter_context(unittest.mock.patch.object(p, name, lambda: False))+ stack.enter_context(unittest.mock.patch.object(p.HELPER, "is_alive", lambda: False))+ stack.enter_context(unittest.mock.patch.object(p.subprocess, "Popen", popen))+ stack.enter_context(unittest.mock.patch.object(p, "H3_ROOT", _H3_TMP))++[email protected](not __import__("shutil").which("ffmpeg"), reason="ffmpeg not on PATH")+def test_h3_chain_stop_after_window_publishes_finished_windows():+ job = {"id": "t-h3chain", "params": {"engine": "h3", "mode": "t2v",+ "h3_tier": "draft_10s", "prompt": "a lighthouse at dusk",+ "seed": "42", "loras": []},+ "stop_after_part": True}+ real_popen = _subprocess.Popen+ spawned = []++ def popen(cmd, **kw):+ # subprocess.run() (ffprobe, the fake runner's own ffmpeg call) is+ # ITSELF implemented on top of Popen, and patching P.subprocess.Popen+ # patches the one process-wide `subprocess` module — so this sees+ # every Popen in the process, not just the H3 renderer's. Only the+ # real cmd (caffeinate -i <python> <runner> <argv...>) gets swapped+ # for the fake runner; everything else passes straight through.+ if not (isinstance(cmd, list) and cmd and cmd[0] == "caffeinate"):+ return real_popen(cmd, **kw)+ fake_cmd = [cmd[0], cmd[1], sys.executable, str(_write_fake_h3_runner())] + cmd[4:]+ p_ = real_popen(fake_cmd, **kw)+ spawned.append(p_)+ return p_++ with ExitStack() as st:+ _h3_chain_dispatch_patches(st, popen)+ with p.LOCK:+ saved = (p.STATE.get("current"), p.STATE.get("h3_pgid"))+ p.STATE["current"] = job+ try:+ t0 = time.time()+ p.run_h3_job_inner(job) # must NOT raise+ elapsed = time.time() - t0+ finally:+ with p.LOCK:+ p.STATE["current"], p.STATE["h3_pgid"] = saved++ # Killed at the window-2 boundary, not left to run its 30 s sleep.+ assert elapsed < 15, f"stop-after-window did not cut the render short ({elapsed}s)"+ assert len(spawned) == 1+ spawned[0].wait(timeout=5)++ assert job.get("_h3_stopped_after_window") is not None+ out_path = Path(job["output_path"])+ assert out_path.is_file()+ side = json.loads(out_path.with_suffix(out_path.suffix + ".json").read_text())+ assert side.get("stopped_early") is True+ assert side["h3"]["delivered_frames"] == job["_h3_stopped_after_window"]["frames"]+ # The published clip is window 1's real duration, NOT the full 10 s the+ # tier asked for — the exact bug this fix closes.+ assert side["video_duration_sec"] < 2.0+ assert "(stopped early" in side["params"]["label"]+++if __name__ == "__main__":+ unittest.main()diff --git a/test_shot_identity.py b/test_shot_identity.pynew file mode 100644index 0000000..fd61da0--- /dev/null+++ b/test_shot_identity.py@@ -0,0 +1,164 @@+#!/usr/bin/env python3+"""Priority-0 for the `board` mega-ship package: shots get a stable `uid`.++ * FILM-10 the board save route merged server-owned fields (draft_output,+ final_output, still, job ids, ...) from the OLD shot at the same+ `n` onto the incoming shot. `n` is renumbered on every reorder,+ insert or delete, so moving or deleting a shot next to a+ rendered one grafted that rendered clip onto a completely+ different, unrendered shot — which then flipped to "done" and+ locked, and its own prompt never rendered.++The fix gives every shot a stable `uid` (storyboard.new_shot_uid()) and+merges by it instead of by position. Old boards on disk get a uid assigned+on load (`_sb_reconcile`) and on normalize (`_sb_normalize`), migrated in+place and persisted on the next save.++Everything here runs against a scratch STATE_DIR; no GPU, no weights.+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _shot(n, uid=None, **kw):+ s = {"n": n, "mode": "text", "engine": "ltx", "prompt": f"shot {n}",+ "duration_s": 5.0, "seed": 1000 + n, "refs": [], "status": "pending"}+ if uid is not None:+ s["uid"] = uid+ s.update(kw)+ return s+++def _board(bid, shots):+ return {"schema": 1, "id": bid, "title": "T", "created_at": 1,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "shots": shots}+++class FakeHandler:+ def __init__(self):+ self.status = None+ self.payload = None++ def _json(self, payload, status: int = 200):+ self.payload, self.status = payload, status+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def post_save(self, board_id, shots):+ h = FakeHandler()+ import json as _json+ body = _json.dumps({"id": board_id, "board": {"shots": shots}})+ panel.Handler._storyboard_post(h, "save", body, {})+ return h+++class ReorderDoesNotGraftClips(Sandbox):+ """FILM-10: the corrupting repro from the report."""++ def test_moving_an_unrendered_shot_up_does_not_inherit_the_neighbours_clip(self):+ # Shot 2 is rendered; shot 3 is not. The user presses up-arrow on shot+ # 3 — the client renumbers locally (3 -> 2, 2 -> 3) and posts both+ # shots back with their SAME uid, just a new `n`.+ rendered = _shot(2, uid="shot_aaaaaaaa", draft_output="/out/S02.mp4",+ status="done")+ unrendered = _shot(3, uid="shot_bbbbbbbb")+ self.save(_board("sb_10", [_shot(1, uid="shot_00000000"),+ rendered, unrendered]))++ # Client-side up-arrow: swap positions, keep identities, renumber n.+ moved_up = dict(unrendered); moved_up["n"] = 2+ moved_down = dict(rendered); moved_down["n"] = 3+ h = self.post_save("sb_10", [_shot(1, uid="shot_00000000"),+ moved_up, moved_down])+ self.assertEqual(h.status, 200)+ by_uid = {s["uid"]: s for s in h.payload["board"]["shots"]}+ # The shot that was never rendered must still show no clip — the old+ # bug matched by `n`=2 and grafted rendered's draft_output onto it.+ self.assertIsNone(by_uid["shot_bbbbbbbb"].get("draft_output"))+ self.assertNotEqual(by_uid["shot_bbbbbbbb"].get("status"), "done")+ # The shot that WAS rendered keeps its own clip, just at a new n.+ self.assertEqual(by_uid["shot_aaaaaaaa"].get("draft_output"), "/out/S02.mp4")+ self.assertEqual(by_uid["shot_aaaaaaaa"]["n"], 3)++ def test_deleting_a_shot_does_not_graft_its_neighbours_clip(self):+ rendered = _shot(2, uid="shot_cccccccc", draft_output="/out/S02.mp4",+ status="done")+ after = _shot(3, uid="shot_dddddddd")+ self.save(_board("sb_10b", [_shot(1, uid="shot_11111111"),+ rendered, after]))+ # Delete shot 1: client filters it out and renumbers 2->1, 3->2.+ moved_rendered = dict(rendered); moved_rendered["n"] = 1+ moved_after = dict(after); moved_after["n"] = 2+ h = self.post_save("sb_10b", [moved_rendered, moved_after])+ by_uid = {s["uid"]: s for s in h.payload["board"]["shots"]}+ self.assertIsNone(by_uid["shot_dddddddd"].get("draft_output"))+ self.assertEqual(by_uid["shot_cccccccc"].get("draft_output"), "/out/S02.mp4")++ def test_a_genuinely_new_shot_with_no_uid_never_inherits_an_old_clip(self):+ rendered = _shot(1, uid="shot_eeeeeeee", draft_output="/out/S01.mp4",+ status="done")+ self.save(_board("sb_10c", [rendered]))+ brand_new = _shot(2) # no uid: just typed by the user, never saved+ h = self.post_save("sb_10c", [dict(rendered), brand_new])+ shots = h.payload["board"]["shots"]+ new_shot = next(s for s in shots if s["n"] == 2)+ self.assertIsNone(new_shot.get("draft_output"))+ self.assertTrue(new_shot.get("uid", "").startswith("shot_"))+++class MigrationAssignsStableUids(Sandbox):+ def test_a_pre_uid_board_gets_uids_on_reconcile_and_they_persist(self):+ legacy = _board("sb_mig", [_shot(1), _shot(2)]) # no uid field at all+ self.save(legacy)+ loaded = storyboard.load_storyboard(self.state, "sb_mig")+ self.assertNotIn("uid", loaded["shots"][0])+ changed = panel._sb_reconcile(loaded)+ self.assertTrue(changed)+ uids = [s["uid"] for s in loaded["shots"]]+ self.assertEqual(len(set(uids)), 2)+ for u in uids:+ self.assertTrue(u.startswith("shot_"))+ storyboard.save_storyboard(self.state, loaded)+ reloaded = storyboard.load_storyboard(self.state, "sb_mig")+ self.assertEqual([s["uid"] for s in reloaded["shots"]], uids)++ def test_normalize_also_assigns_missing_uids(self):+ board = _board("sb_norm", [_shot(1), _shot(2)])+ for s in board["shots"]:+ s.pop("uid", None)+ panel._sb_normalize(board)+ uids = [s["uid"] for s in board["shots"]]+ self.assertEqual(len(set(uids)), 2)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_shot_rewrite_multi.py b/test_shot_rewrite_multi.pynew file mode 100644index 0000000..96a1148--- /dev/null+++ b/test_shot_rewrite_multi.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+"""FILM-01: "Rewrite N shots" must rewrite every named shot, not just the first.++Before the fix, `replan-shots` joined every shot's note into ONE feedback+string ("shot 3: ...\\nshot 7: ...") and made a single shot-mode planner+call. `storyboard_planner._parse_feedback`'s "shot N:" pattern only ever+matches the FIRST header and (re.DOTALL) folds every later note into that+one shot's note — so only the first named shot was ever actually rewritten;+every other named shot kept its old prompt AND its old pinned seed, so it+re-rendered as an identical clip.++The fix runs one shot-mode planner call per named shot, in one session,+threading the running spec through so each call sees the previous one's+result. This test stands in for the real planner with a fake that mimics+its documented per-shot contract (replace exactly the named shot, carry+every other shot across by reference, assign that shot a fresh seed) and+proves both named shots come back genuinely different while the untouched+shot is carried over byte-identical.+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+import storyboard_planner # noqa: E402+++def _shot(n, prompt, seed):+ return {"n": n, "uid": f"shot_{n:08x}", "mode": "text", "engine": "ltx",+ "prompt": prompt, "duration_s": 5.0, "seed": seed, "refs": [],+ "status": "done", "draft_output": f"/out/S{n}.mp4"}+++def _fake_plan_film(concept, *, n_shots, style, characters, must_include,+ feedback, previous, engine, board_id, locations,+ known_character_ids, max_dim, session):+ """Stands in for the real planner's documented shot-mode contract."""+ assert isinstance(feedback, dict) and "shot" in feedback, feedback+ target_n, note = feedback["shot"], feedback["note"]+ shots = [dict(s) for s in (previous.get("shots") or [])]+ for s in shots:+ if s["n"] == target_n:+ s["prompt"] = f"rewritten for shot {target_n}: {note}"+ s["seed"] = 90000 + target_n # a fresh seed, every time+ s["status"] = "pending"+ spec = dict(previous)+ spec["shots"] = shots+ spec["_planner"] = {"model": "fake", "attempts": 1, "elapsed_s": 0.1,+ "warnings": []}+ return spec+++class RewriteMultipleShots(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None),+ mock.patch.object(panel, "_sb_h3_available", lambda: False),+ mock.patch.object(panel, "_sb_known_character_ids", lambda: []),+ mock.patch.object(panel, "_sb_max_dim", lambda: 1280)):+ p.start()+ self.addCleanup(p.stop)+ self.board = {"schema": 1, "id": "sb_rw", "title": "T", "created_at": 1,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "concept": "a test film",+ "planner": {"state": "idle"},+ "shots": [_shot(1, "shot one, untouched", 1001),+ _shot(2, "shot two, old prompt", 1002),+ _shot(3, "shot three, old prompt", 1003)]}+ storyboard.save_storyboard(self.state, self.board)+ panel._SB_PLANNERS.clear()+ panel._SB_PLANNERS["sb_rw"] = {"cancelled": False}+ self.addCleanup(panel._SB_PLANNERS.clear)++ def test_both_named_shots_get_distinct_new_prompts_and_seeds(self):+ previous = {k: self.board.get(k) for k in+ ("schema", "id", "title", "cast", "policy", "shots")}+ brief = {"concept": self.board["concept"], "n_shots": 3, "style": "",+ "characters": [], "must": [], "locations": [],+ "shot_notes": {2: "make it bluer", 3: "faster camera"},+ "engine_mode": "ltx", "reroll_ns": [2, 3]}+ with mock.patch.object(storyboard_planner, "plan_film",+ side_effect=_fake_plan_film) as pf:+ panel._sb_plan_thread("sb_rw", brief, previous)+ self.assertEqual(pf.call_count, 2, "one planner call per named shot")++ reloaded = storyboard.load_storyboard(self.state, "sb_rw")+ by_n = {s["n"]: s for s in reloaded["shots"]}++ # Shot 1 was never named — carried across untouched.+ self.assertEqual(by_n[1]["prompt"], "shot one, untouched")+ self.assertEqual(by_n[1]["seed"], 1001)++ # Shot 2 AND shot 3 both got their OWN rewrite — the bug this fixes+ # is shot 3 silently keeping its old prompt/seed while shot 2's note+ # swallowed shot 3's text too.+ self.assertIn("make it bluer", by_n[2]["prompt"])+ self.assertIn("faster camera", by_n[3]["prompt"])+ self.assertNotIn("faster camera", by_n[2]["prompt"])+ self.assertNotIn("make it bluer", by_n[3]["prompt"])++ # Every rewritten shot got a genuinely NEW seed (not the pinned one),+ # and the two rewrites are not the same seed as each other.+ self.assertNotEqual(by_n[2]["seed"], 1002)+ self.assertNotEqual(by_n[3]["seed"], 1003)+ self.assertNotEqual(by_n[2]["seed"], by_n[3]["seed"])++ # Both go back to pending, unrendered, so the next render actually+ # spends a job on them.+ self.assertEqual(by_n[2]["status"], "pending")+ self.assertEqual(by_n[3]["status"], "pending")+ self.assertIsNone(by_n[2].get("draft_output"))+ self.assertIsNone(by_n[3].get("draft_output"))+ self.assertEqual(by_n[2]["stale_output"], "/out/S2.mp4")+ self.assertEqual(by_n[3]["stale_output"], "/out/S3.mp4")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_sidecar_actual_dims.py b/test_sidecar_actual_dims.pynew file mode 100644index 0000000..11c5ae8--- /dev/null+++ b/test_sidecar_actual_dims.py@@ -0,0 +1,192 @@+"""VC-19: the info modal's "Format" line reports what the FILE actually is,+not just the render request that produced it.++WHAT THIS GUARDS. renderOutputInfoBody() built the "Format" line from+params.width/params.height alone — the RENDER canvas, not the delivered+file. Balanced's default 720p-fit export (or any upscale) changes the two:+a 1024x576 render that fit-exports to 1280x720 reported "Format 1024 x+576" for a file that actually opens at 1280x720.++Fixed at the source: GET /sidecar (panel/routes_files.py) now probes the+REAL media file with ffprobe and attaches actual_width/actual_height to+the JSON it returns (one probe, only when a human opens the info modal -+never on the gallery's poll path). The client (queue.js) prefers those+fields, and when they disagree with the render params says both:+"Delivered 1280 x 720 (rendered 1024 x 576, 720p fit)".+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from urllib.parse import urlencode, urlparse++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-sidecar-dims-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["LTX_OUTPUT_DIR"] = str(STATE / "out")+os.environ["LTX_UPLOADS_DIR"] = str(STATE / "up")+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8320")+(STATE / "out").mkdir(parents=True, exist_ok=True)+(STATE / "up").mkdir(parents=True, exist_ok=True)+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from panel.routes import GET_ROUTES # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+FFMPEG = shutil.which("ffmpeg")+++class _H:+ def __init__(s):+ s.out = None+ s.code = None++ def _json(s, obj, code=200):+ s.out, s.code = obj, code++ def send_error(s, code, msg=None):+ s.code = code+++def _get_sidecar(path: str):+ h = _H()+ parsed = urlparse("/sidecar?" + urlencode({"path": path}))+ GET_ROUTES["/sidecar"](h, parsed)+ return h.code, h.out++[email protected](FFMPEG, "ffmpeg not on PATH")+class RouteProbesTheRealFile(unittest.TestCase):+ # KNOWN TRAP (conftest.py's own docstring): mlx_ltx_panel resolves+ # P.OUTPUT/P.UPLOADS from LTX_OUTPUT_DIR/LTX_UPLOADS_DIR ONCE, at first+ # import. In a whole-suite run some earlier module has usually already+ # imported the panel (fixing those constants to ITS OWN temp dirs), so+ # writing fixtures under THIS file's own `STATE / "out"` lands outside+ # whatever P.OUTPUT actually resolved to — the /sidecar route's own+ # root check then 404s a file that is really on disk. Fixtures go under+ # the panel's OWN resolved P.OUTPUT/P.UPLOADS instead, which is correct+ # regardless of import order.+ def setUp(self):+ P.OUTPUT.mkdir(parents=True, exist_ok=True)+ P.UPLOADS.mkdir(parents=True, exist_ok=True)++ def _make_mp4(self, w: int, h: int) -> Path:+ p = Path(P.OUTPUT / f"clip_{w}x{h}_{id(self)}.mp4")+ subprocess.run(+ [FFMPEG, "-y", "-f", "lavfi", "-i", f"color=c=blue:s={w}x{h}:d=1",+ "-frames:v", "1", str(p)],+ capture_output=True, timeout=30, check=True,+ )+ return p++ def test_dims_differ_from_render_params_are_both_reported(self):+ clip = self._make_mp4(1280, 720) # delivered (post fit_720p export)+ sidecar = Path(str(clip) + ".json")+ sidecar.write_text(json.dumps({+ "params": {"mode": "t2v", "width": 1024, "height": 576,+ "upscale": "fit_720p", "seed": "-1"},+ }))+ code, out = _get_sidecar(str(clip))+ self.assertEqual(code, 200)+ self.assertEqual(out["actual_width"], 1280)+ self.assertEqual(out["actual_height"], 720)+ # the render params are untouched - only a new field was added+ self.assertEqual(out["params"]["width"], 1024)++ def test_matching_dims_still_reported(self):+ clip = self._make_mp4(640, 480)+ sidecar = Path(str(clip) + ".json")+ sidecar.write_text(json.dumps({+ "params": {"mode": "t2v", "width": 640, "height": 480, "upscale": "off"},+ }))+ code, out = _get_sidecar(str(clip))+ self.assertEqual(code, 200)+ self.assertEqual(out["actual_width"], 640)+ self.assertEqual(out["actual_height"], 480)++ def test_non_mp4_sidecars_are_untouched(self):+ """Images (.png/.webp/...) go through the same route - never run+ ffprobe against them, and never claim a bogus actual_width."""+ img = Path(P.UPLOADS / "still.png")+ img.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\0" * 16)+ sidecar = Path(str(img) + ".json")+ sidecar.write_text(json.dumps({"params": {"mode": "image", "width": 512}}))+ code, out = _get_sidecar(str(img))+ self.assertEqual(code, 200)+ self.assertNotIn("actual_width", out)+ self.assertEqual(out["params"]["width"], 512)+++class ClientFormatsBothNumbers(unittest.TestCase):+ def _snippet(self) -> str:+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ i = src.index("Compose the dimensions + duration")+ i = src.rindex("\n", 0, i) + 1+ j = src.index("\n\n let html", i)+ return src[i:j]++ def _run_node(self, script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-3000:], r.stderr[-3000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)++ def test_delivered_and_rendered_both_shown_for_a_fit_export(self):+ snippet = self._snippet()+ script = f"""+const p = {{ width: 1024, height: 576, upscale: 'fit_720p' }};+const data = {{ actual_width: 1280, actual_height: 720, video_duration_sec: 5.0, fps: 24 }};+{snippet}+console.log(JSON.stringify({{ line: formatBits[0] }}));+"""+ out = self._run_node(script)+ self.assertIn("Delivered 1280 × 720", out["line"])+ self.assertIn("rendered 1024 × 576", out["line"])+ self.assertIn("720p fit", out["line"])++ def test_matching_dims_show_once(self):+ snippet = self._snippet()+ script = f"""+const p = {{ width: 640, height: 480, upscale: 'off' }};+const data = {{ actual_width: 640, actual_height: 480 }};+{snippet}+console.log(JSON.stringify({{ line: formatBits[0] }}));+"""+ out = self._run_node(script)+ self.assertEqual(out["line"], "640 × 480")+ self.assertNotIn("Delivered", out["line"])+ self.assertNotIn("rendered", out["line"])++ def test_no_actual_dims_falls_back_to_render_params(self):+ snippet = self._snippet()+ script = f"""+const p = {{ width: 800, height: 450, upscale: 'off' }};+const data = {{}};+{snippet}+console.log(JSON.stringify({{ line: formatBits[0] }}));+"""+ out = self._run_node(script)+ self.assertEqual(out["line"], "800 × 450")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_size_faces_clamp_aspect.py b/test_size_faces_clamp_aspect.pynew file mode 100644index 0000000..d8a9087--- /dev/null+++ b/test_size_faces_clamp_aspect.py@@ -0,0 +1,184 @@+"""VC-02/SYS-05: the Compact (<48 GB) tier clamp used to floor width and+height independently, so a 16:9 request came back a 2:1 canvas (1024x576+clamped to 768 landed at 768x384, not the aspect-preserving ~768x448), and+the chips advertised the UNCLAMPED canvas while the server silently rendered+something smaller. Three things are pinned here:++ 1. ltx_fit_canvas rounds to the nearest /64 grid point once a clamp+ actually fires, instead of flooring both sides independently.+ 2. _ltx_qualities() bakes the Compact-tier clamp into the canvas it+ serves, so the chip and the render can never disagree.+ 3. The "48 GB fast generation" profile no longer double-clamps (and+ mislabels itself) on a genuinely Compact (<48 GB) Mac — that tier is+ governed by tier_max_dim alone.++Patches the panel to the Compact (base) tier so the whole module runs+under the Compact tier without needing a real 16 GB Mac.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SANDBOX = Path(tempfile.mkdtemp(prefix="phos-test-clamp-"))+for _var, _sub in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "mlx_outputs"),+ ("LTX_UPLOADS_DIR", "panel_uploads")):+ os.environ.setdefault(_var, str(SANDBOX / _sub))+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+from unittest import mock # noqa: E402++# The Compact tier is simulated by patching the panel's resolved tier for+# THIS module's tests only. It used to be LTX_TIER_OVERRIDE=base set at+# import time, which only works when this file is the first to import the+# panel: in a whole-suite run an earlier module had already resolved the+# real tier (so SYSTEM_TIER was never "base" here), and the env var then+# leaked into every suite that ran after it.+_TIER_PATCHES = []+++def setUpModule():+ for name, value in (("SYSTEM_TIER", "base"),+ ("SYSTEM_CAPS", P.CAPABILITIES["base"])):+ patcher = mock.patch.object(P, name, value)+ patcher.start()+ _TIER_PATCHES.append(patcher)+++def tearDownModule():+ while _TIER_PATCHES:+ _TIER_PATCHES.pop().stop()+++class LtxFitCanvasKeepsAspect(unittest.TestCase):+ def test_1280x704_clamped_to_768_keeps_16_9_ish(self):+ # Old (buggy) behaviour: (768, 384) — a 2:1 canvas.+ w, h = P.ltx_fit_canvas(1280, 704, 768)+ self.assertEqual((w, h), (768, 448))+ # Not the old bug.+ self.assertNotEqual((w, h), (768, 384))+ # Long side is exactly at the cap, never over it.+ self.assertLessEqual(max(w, h), 768)+ # Aspect is much closer to source (1.818) than the old 2:1.+ self.assertLess(abs(w / h - 1280 / 704), abs(768 / 384 - 1280 / 704))++ def test_1024x576_clamped_to_768_matches_1280x704s_result(self):+ # Balanced and Standard used to clamp to DIFFERENT canvases on the+ # same Mac because each request's own floor rounded differently —+ # they should land on the identical grid point now.+ a = P.ltx_fit_canvas(1024, 576, 768)+ b = P.ltx_fit_canvas(1280, 704, 768)+ self.assertEqual(a, b)++ def test_short_side_never_rounds_back_over_the_cap(self):+ # A pathological near-square ratio must not let "round" push the+ # short side above max_dim.+ w, h = P.ltx_fit_canvas(1300, 1290, 768)+ self.assertLessEqual(w, 768)+ self.assertLessEqual(h, 768)++ def test_unclamped_request_still_floors_as_before(self):+ # No cap in play (max_dim=0) — behaviour must be byte-identical to+ # the pre-existing ltx_floor_canvas (every OTHER caller of this+ # function depends on that).+ self.assertEqual(P.ltx_fit_canvas(1281, 705, 0),+ P.ltx_floor_canvas(1281, 705))++ def test_under_the_cap_is_a_no_op(self):+ self.assertEqual(P.ltx_fit_canvas(640, 448, 768), (640, 448))+++class QualitiesTableIsHonestOnCompact(unittest.TestCase):+ """_ltx_qualities() must already reflect what THIS Mac renders."""++ def test_compact_tier_clamps_balanced_and_standard(self):+ self.assertEqual(P.SYSTEM_TIER, "base")+ qualities = P._ltx_qualities()+ balanced = qualities["balanced"]+ standard = qualities["standard"]+ # Not the unclamped 1024x576 / 1280x704 any more.+ self.assertEqual((balanced["width"], balanced["height"]), (768, 448))+ self.assertEqual((standard["width"], standard["height"]), (768, 448))+ self.assertEqual(balanced["canvas"], "768×448")+ self.assertIn("768", balanced["note"])+ self.assertIn("Compact", balanced["note"])++ def test_quick_is_untouched_already_under_the_cap(self):+ qualities = P._ltx_qualities()+ self.assertEqual((qualities["quick"]["width"], qualities["quick"]["height"]),+ (640, 448))++ def test_hq_pipeline_is_never_clamped_here(self):+ # High/High-720p are gated off entirely on Compact via allows_q8 —+ # this table must not also silently shrink their advertised canvas.+ qualities = P._ltx_qualities()+ self.assertEqual((qualities["high"]["width"], qualities["high"]["height"]),+ (1024, 576))+ self.assertEqual((qualities["high_720p"]["width"], qualities["high_720p"]["height"]),+ (1280, 704))+++class GenerationProfileDoesNotDoubleClampResolution(unittest.TestCase):+ """The '48 GB fast generation' profile still fires below 48 GB — a2v_max_frames()+ and the LoRA-count warning genuinely need it there — but its RESOLUTION+ clamp must defer to tier_max_dim on the Compact tier instead of stacking+ a second, independent clamp on top of it (that stacking, each pass+ flooring its own way, is what turned a 16:9 request into a 2:1 canvas).++ An earlier version of this fix scoped `compact` itself to the+ Comfortable tier only, which looked right for the resolution bug but+ silently zeroed a2v_max_frames() on every Compact-tier Mac — caught by+ test_review_416_jobs (CompactMacsRefuseOversizedA2V) when the whole+ suite ran, not by this file's own narrower tests. Kept here as the+ regression these tests now pin against.+ """++ def test_compact_tier_still_gets_the_profile(self):+ # NOT full_generation — a2v_max_frames() reads `compact` ++ # auto_temporal_after_frames directly for the Compact-tier A2V+ # length refusal, and warn_loras still applies below 48 GB too.+ profile = P._select_generation_profile(16.0, "base")+ self.assertTrue(profile["compact"])+ self.assertEqual(profile["key"], "m5pro48_generation")+ self.assertEqual(profile["auto_temporal_after_frames"], 241)++ def test_comfortable_tier_still_gets_the_profile(self):+ profile = P._select_generation_profile(56.0, "standard")+ self.assertTrue(profile["compact"])+ self.assertEqual(profile["key"], "m5pro48_generation")+ self.assertEqual(profile["max_dim"], 1024)++ def test_roomy_and_above_are_never_compact(self):+ self.assertFalse(P._select_generation_profile(96.0, "high")["compact"])++ # a2v_max_frames() itself is NOT re-tested here: it reads the+ # module-level GENERATION_PROFILE constant, which is computed once at+ # import time from this machine's REAL sysctl RAM (LTX_TIER_OVERRIDE+ # forces SYSTEM_TIER but not SYSTEM_RAM_GB) — asserting it from this+ # file would silently depend on the dev box's actual memory size.+ # test_review_416_jobs.py (CompactMacsRefuseOversizedA2V) already pins+ # a2v_max_frames() correctly with proper RAM mocking; that suite is+ # what caught the regression an earlier version of this fix caused+ # (`compact` scoped away from Compact tier entirely) and it now passes.++ def test_profile_resolution_clamp_is_a_noop_on_compact_tier(self):+ # _apply_generation_profile_to_job's OWN max_dim clamp must not+ # touch width/height on Compact — tier_max_dim (applied later, in+ # run_job_inner) is the sole resolution authority there.+ job = {"params": {"engine": "ltx", "mode": "t2v", "quality": "balanced",+ "width": 1280, "height": 704, "frames": 121}}+ P._apply_generation_profile_to_job(job)+ self.assertEqual((job["params"]["width"], job["params"]["height"]),+ (1280, 704))+ self.assertNotIn("generation_clamp_notes", job["params"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_size_faces_crop_focus.py b/test_size_faces_crop_focus.pynew file mode 100644index 0000000..15689ac--- /dev/null+++ b/test_size_faces_crop_focus.py@@ -0,0 +1,145 @@+"""VC-29/H3-01/VA-02: reference images used to always get centre-cropped+with no way to say otherwise — a portrait photo cover-cropped onto a+landscape H3/I2V/A2V canvas lost the face, and there was no signal from the+UI (or the job spec) that a crop was even happening. Pinned here:++ 1. _cover_crop_image's focus=0.5 is byte-identical to the OLD hardcoded+ centre-crop (floor division) — the fix must not shift a single pixel+ for anyone who never touches the new control.+ 2. A non-centre focus actually moves the crop window, and 0/1 sit at the+ two edges.+ 3. _job_crop_focus() clamps/validates whatever the client sent so a bad+ or missing value can't crash a render.+ 4. _h3_fit_first_frame keeps EXIF orientation on the panel's own pre-fit+ (H3-01 also cited "the reference cover-crop keeps a sideways face").+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SANDBOX = Path(tempfile.mkdtemp(prefix="phos-test-cropfocus-"))+for _var, _sub in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "mlx_outputs"),+ ("LTX_UPLOADS_DIR", "panel_uploads")):+ os.environ.setdefault(_var, str(SANDBOX / _sub))+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++from PIL import Image, ImageOps # noqa: E402++import mlx_ltx_panel as P # noqa: E402+++def _gradient(w: int, h: int) -> Image.Image:+ """A vertical gradient (top=black, bottom=white) so a crop's vertical+ offset is visible in the mean pixel value of the result."""+ im = Image.new("L", (w, h))+ px = im.load()+ for y in range(h):+ v = int(255 * y / max(1, h - 1))+ for x in range(w):+ px[x, y] = v+ return im.convert("RGB")+++class CoverCropFocus(unittest.TestCase):+ def test_default_focus_matches_old_hardcoded_centre_crop(self):+ im = _gradient(900, 1600)+ target_w, target_h = 640, 384+ got = P._cover_crop_image(im, target_w, target_h, 0.5)+ # The OLD formula this replaces, ported verbatim for comparison.+ scale = max(target_w / im.size[0], target_h / im.size[1])+ resized_size = (max(target_w, round(im.size[0] * scale)),+ max(target_h, round(im.size[1] * scale)))+ left = max(0, (resized_size[0] - target_w) // 2)+ top = max(0, (resized_size[1] - target_h) // 2)+ want = im.resize(resized_size, Image.Resampling.LANCZOS).crop(+ (left, top, left + target_w, top + target_h))+ self.assertEqual(list(got.getdata()), list(want.getdata()))++ def test_focus_0_keeps_the_top_focus_1_keeps_the_bottom(self):+ im = _gradient(900, 1600) # portrait -> landscape crop is vertical+ top = P._cover_crop_image(im, 640, 384, 0.0)+ bottom = P._cover_crop_image(im, 640, 384, 1.0)+ # Top crop should be much darker (near black) than a bottom crop+ # (near white) on this gradient.+ top_mean = sum(top.convert("L").getdata()) / (640 * 384)+ bottom_mean = sum(bottom.convert("L").getdata()) / (640 * 384)+ self.assertLess(top_mean, 60)+ self.assertGreater(bottom_mean, 195)+ self.assertLess(top_mean, bottom_mean)++ def test_result_is_always_exactly_the_target_canvas(self):+ im = _gradient(900, 1600)+ for f in (0.0, 0.25, 0.5, 0.75, 1.0):+ out = P._cover_crop_image(im, 640, 384, f)+ self.assertEqual(out.size, (640, 384))++ def test_no_crop_needed_when_aspect_already_matches(self):+ im = _gradient(640, 384)+ out = P._cover_crop_image(im, 640, 384, 0.9)+ self.assertEqual(out.size, (640, 384))+++class JobCropFocusParsing(unittest.TestCase):+ def test_missing_defaults_to_centre(self):+ self.assertEqual(P._job_crop_focus({}), 0.5)++ def test_clamped_to_0_1(self):+ self.assertEqual(P._job_crop_focus({"image_crop_focus": "5"}), 1.0)+ self.assertEqual(P._job_crop_focus({"image_crop_focus": "-3"}), 0.0)++ def test_garbage_falls_back_to_centre(self):+ self.assertEqual(P._job_crop_focus({"image_crop_focus": "not-a-number"}), 0.5)+ self.assertEqual(P._job_crop_focus({"image_crop_focus": None}), 0.5)++ def test_valid_value_passes_through(self):+ self.assertAlmostEqual(P._job_crop_focus({"image_crop_focus": "0.2"}), 0.2)+++class H3FitFirstFrameHonoursFocusAndExif(unittest.TestCase):+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="phos-h3fit-"))++ def test_focus_moves_the_crop(self):+ src = self.tmp / "portrait.png"+ _gradient(900, 1600).save(src)+ out_top = P._h3_fit_first_frame(src, 640, 384, "jobA", focus=0.0)+ out_bottom = P._h3_fit_first_frame(src, 640, 384, "jobB", focus=1.0)+ self.assertNotEqual(out_top, src)+ with Image.open(out_top) as im_top, Image.open(out_bottom) as im_bot:+ mean_top = sum(im_top.convert("L").getdata()) / (640 * 384)+ mean_bot = sum(im_bot.convert("L").getdata()) / (640 * 384)+ self.assertLess(mean_top, mean_bot)++ def test_exif_rotated_source_is_upright_before_crop(self):+ # A landscape-pixel image tagged "rotate 90 CW to display" (the+ # classic iPhone-portrait-in-JPEG shape, SYS-01/H3-01).+ base = _gradient(1600, 900) # pixels: landscape+ exif = base.getexif()+ exif[0x0112] = 6 # Orientation: rotate 90 CW+ src = self.tmp / "sideways.jpg"+ base.save(src, exif=exif)+ # Sanity: PIL's raw open must still report the SIDEWAYS size, or the+ # rest of this test proves nothing.+ with Image.open(src) as raw:+ self.assertEqual(raw.size, (1600, 900))+ self.assertEqual(int(raw.getexif().get(0x0112, 1)), 6)+ out = P._h3_fit_first_frame(src, 384, 640, "jobC") # a PORTRAIT canvas+ with Image.open(out) as fitted:+ self.assertEqual(fitted.size, (384, 640))+ # If exif_transpose had NOT run, the source would still measure+ # 1600x900 internally and the cover-crop math would scale+ # differently — cross-check against exif_transpose'd bytes.+ with Image.open(src) as raw:+ upright = ImageOps.exif_transpose(raw)+ self.assertEqual(upright.size, (900, 1600)) # now portrait+++if __name__ == "__main__":+ unittest.main()diff --git a/test_size_faces_image_ingest.py b/test_size_faces_image_ingest.pynew file mode 100644index 0000000..caf286b--- /dev/null+++ b/test_size_faces_image_ingest.py@@ -0,0 +1,135 @@+"""SYS-01/SYS-02: EXIF-rotated JPEGs and HEIC/HEIF/AVIF used to reach the+render pipeline, the trainer and the thumbnail cache un-normalized — an+EXIF-rotated phone photo rendered sideways while its own preview looked+upright, and a HEIC upload left a blank picker with no message and later+died deep in the helper. normalize_ingested_image_bytes() is the one choke+point both /upload and /train/upload now funnel through.+"""+from __future__ import annotations++import io+import os+import shutil+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SANDBOX = Path(tempfile.mkdtemp(prefix="phos-test-ingest-"))+for _var, _sub in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "mlx_outputs"),+ ("LTX_UPLOADS_DIR", "panel_uploads")):+ os.environ.setdefault(_var, str(SANDBOX / _sub))+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++from PIL import Image # noqa: E402++import mlx_ltx_panel as P # noqa: E402+++def _gradient_jpeg_bytes(w: int, h: int, orientation: int | None = None) -> bytes:+ im = Image.new("RGB", (w, h))+ px = im.load()+ for y in range(h):+ v = int(255 * y / max(1, h - 1))+ for x in range(w):+ px[x, y] = (v, v, v)+ buf = io.BytesIO()+ if orientation is not None:+ exif = im.getexif()+ exif[0x0112] = orientation+ im.save(buf, format="JPEG", exif=exif)+ else:+ im.save(buf, format="JPEG")+ return buf.getvalue()+++class ExifOrientation(unittest.TestCase):+ def test_sideways_jpeg_comes_back_upright_and_untagged(self):+ # Pixels landscape, EXIF says "rotate 90 CW to display" — the+ # classic iPhone-portrait shape.+ data = _gradient_jpeg_bytes(1600, 900, orientation=6)+ out, ext, err = P.normalize_ingested_image_bytes(data, "IMG_0001.jpg")+ self.assertIsNone(err)+ self.assertEqual(ext, ".jpg")+ with Image.open(io.BytesIO(out)) as im:+ # Now genuinely portrait — the rotation was BAKED into pixels,+ # not left as a tag a renderer might ignore.+ self.assertEqual(im.size, (900, 1600))+ self.assertNotIn(0x0112, dict(im.getexif()))++ def test_already_upright_jpeg_is_untouched_in_shape(self):+ data = _gradient_jpeg_bytes(1280, 704)+ out, ext, err = P.normalize_ingested_image_bytes(data, "clip.jpg")+ self.assertIsNone(err)+ with Image.open(io.BytesIO(out)) as im:+ self.assertEqual(im.size, (1280, 704))++ def test_png_round_trips_and_strips_no_alpha_it_doesnt_have(self):+ im = Image.new("RGB", (64, 32), (10, 20, 30))+ buf = io.BytesIO()+ im.save(buf, format="PNG")+ out, ext, err = P.normalize_ingested_image_bytes(buf.getvalue(), "still.png")+ self.assertIsNone(err)+ self.assertEqual(ext, ".png")+ with Image.open(io.BytesIO(out)) as got:+ self.assertEqual(got.size, (64, 32))++ def test_corrupt_file_refuses_with_a_message_not_a_crash(self):+ out, ext, err = P.normalize_ingested_image_bytes(b"not an image", "broken.jpg")+ self.assertIsNotNone(err)+ self.assertIn("image", err.lower())+++class HeicHandling(unittest.TestCase):+ def test_heic_without_sips_refuses_clearly(self):+ # Simulate "sips unavailable" (a non-Mac dev box, or a sandboxed+ # test run) without depending on the real binary being absent.+ real_which = shutil.which+ try:+ shutil.which = lambda cmd: (None if cmd == "sips" else real_which(cmd))+ out, ext, err = P.normalize_ingested_image_bytes(b"\x00\x00fake heic", "IMG_1.heic")+ finally:+ shutil.which = real_which+ self.assertIsNotNone(err)+ self.assertIn("HEIC", err)+ self.assertIn("export", err.lower())++ @unittest.skipUnless(shutil.which("sips"), "sips not available on this host")+ def test_real_heic_converts_via_sips_when_available(self):+ # Build a tiny HEIC on the fly with sips itself (round-trip proof —+ # this only runs on the macOS boxes this feature targets).+ import subprocess+ with tempfile.TemporaryDirectory() as td:+ src_png = Path(td) / "in.png"+ Image.new("RGB", (32, 24), (200, 100, 50)).save(src_png)+ src_heic = Path(td) / "in.heic"+ subprocess.run(["sips", "-s", "format", "heic", str(src_png),+ "--out", str(src_heic)], check=True, capture_output=True)+ data = src_heic.read_bytes()+ out, ext, err = P.normalize_ingested_image_bytes(data, "photo.heic")+ self.assertIsNone(err)+ self.assertEqual(ext, ".jpg")+ with Image.open(io.BytesIO(out)) as im:+ self.assertEqual(im.size, (32, 24))+++class ThumbnailDefensiveTranspose(unittest.TestCase):+ def test_thumbnail_of_a_pre_existing_rotated_file_is_upright(self):+ # Simulates a file already on disk from BEFORE this fix landed —+ # never normalized at ingest — proving the belt-and-suspenders+ # exif_transpose in _ensure_thumbnail covers it too.+ tmp = Path(tempfile.mkdtemp(prefix="phos-thumb-"))+ src = tmp / "old_upload.jpg"+ src.write_bytes(_gradient_jpeg_bytes(1600, 900, orientation=6))+ thumb = P._ensure_thumbnail(src, 200)+ with Image.open(thumb) as im:+ # Portrait aspect preserved after the defensive transpose —+ # width < height, matching the EXIF-corrected orientation.+ self.assertLess(im.size[0], im.size[1])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_size_faces_misc.py b/test_size_faces_misc.pynew file mode 100644index 0000000..86416a8--- /dev/null+++ b/test_size_faces_misc.py@@ -0,0 +1,129 @@+"""Remaining size-faces package findings, grouped because each is a small,+independent assertion rather than its own scenario:++ - VC-02(c): make_job's allowlist actually carries image_crop_focus and+ extend_face_fix_after through to the job's params (the "leave it out of+ the dict and it silently no-ops" trap this codebase warns about+ everywhere — see CLAUDE.md's make_job allowlist note).+ - VA-13: BOOT exposes extend_max_dim/allows_extend so the client can say+ the clamp BEFORE Generate.+ - VC-39: the two new aspect presets exist, sit on the /32 model-safe grid,+ and are genuinely 1:1 / 4:5.+ - SYS-02: the widened upload-accept set for Train really is a superset of+ the on-disk set (nothing was silently narrowed).+ - H3-02: the fold rule that hides #aspectRow on non-LTX engines has equal+ or higher CSS specificity than the rule that turns it back on, so it+ wins regardless of source order (a real browser cascade is not run+ here — this is the hand-computed specificity check the finding itself+ asked for).+"""+from __future__ import annotations++import os+import re+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SANDBOX = Path(tempfile.mkdtemp(prefix="phos-test-misc-"))+for _var, _sub in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "mlx_outputs"),+ ("LTX_UPLOADS_DIR", "panel_uploads")):+ os.environ.setdefault(_var, str(SANDBOX / _sub))+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class MakeJobAllowlist(unittest.TestCase):+ def test_image_crop_focus_reaches_the_job(self):+ job = P.make_job({"mode": ["i2v"], "image_crop_focus": ["0.15"]})+ self.assertEqual(job["params"]["image_crop_focus"], "0.15")++ def test_image_crop_focus_defaults_to_centre(self):+ job = P.make_job({"mode": ["i2v"]})+ self.assertEqual(job["params"]["image_crop_focus"], "0.5")++ def test_extend_face_fix_after_reaches_the_job(self):+ job = P.make_job({"mode": ["extend"], "video_path": ["/tmp/x.mp4"],+ "extend_face_fix_after": ["1"]})+ self.assertTrue(job["params"]["extend_face_fix_after"])++ def test_extend_face_fix_after_defaults_off(self):+ job = P.make_job({"mode": ["extend"], "video_path": ["/tmp/x.mp4"]})+ self.assertFalse(job["params"]["extend_face_fix_after"])+++class ExtendClampBootData(unittest.TestCase):+ def test_capabilities_table_has_extend_max_dim_per_tier(self):+ for tier_key, caps in P.CAPABILITIES.items():+ self.assertIn("extend_max_dim", caps, tier_key)+ self.assertIn("allows_extend", caps, tier_key)+++class AspectPresetsForSocialFormats(unittest.TestCase):+ def test_square_is_exactly_1_to_1_on_the_32_grid(self):+ a = P.ASPECTS["square"]+ self.assertEqual(a["w"], a["h"])+ self.assertEqual(a["w"] % 32, 0)++ def test_portrait_4_5_is_exactly_4_to_5_on_the_64_grid(self):+ # /64, not /32: make_job floors every LTX canvas to /64, and the+ # /32-only 896x1120 rendered 896x1088 (4.17 Codex EST-11).+ a = P.ASPECTS["portrait_4_5"]+ self.assertEqual(a["w"] % 64, 0)+ self.assertEqual(a["h"] % 64, 0)+ self.assertEqual(a["w"] * 5, a["h"] * 4)+++class TrainUploadAcceptsHeicSupersetOfOnDisk(unittest.TestCase):+ def test_upload_exts_are_a_strict_superset(self):+ self.assertTrue(P.TRAIN_IMAGE_EXTS.issubset(P.TRAIN_IMAGE_UPLOAD_EXTS))+ for heic_ext in (".heic", ".heif", ".avif"):+ self.assertIn(heic_ext, P.TRAIN_IMAGE_UPLOAD_EXTS)+ self.assertNotIn(heic_ext, P.TRAIN_IMAGE_EXTS) # never written as-is+++def _specificity(selector: str) -> tuple[int, int, int]:+ """Cheap (ids, classes/attrs/pseudo-classes, elements) specificity+ count for the small, single-compound-selector-chain subset of CSS this+ file's two #aspectRow rules use — not a general CSS parser."""+ ids = len(re.findall(r"#[\w-]+", selector))+ classes = len(re.findall(r"\.[\w-]+", selector))+ attrs = len(re.findall(r"\[[^\]]+\]", selector))+ # :not(X) counts as X's specificity, not an extra pseudo-class of its+ # own — approximate by counting the attribute selectors INSIDE :not()+ # (already caught by the attrs count above) and any bare pseudo-class.+ pseudo = len(re.findall(r":(?!not\()[\w-]+", selector))+ elements = len(re.findall(r"(?:^|[\s>+~])(?!\.|\#|\[|:)[a-zA-Z][\w-]*", selector))+ return (ids, classes + attrs + pseudo, elements)+++class H3AspectRowFoldSpecificity(unittest.TestCase):+ def setUp(self):+ self.css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")++ def test_both_aspectrow_rules_are_present(self):+ self.assertIn('.cz-body > #aspectRow.mode-only.show { display: flex !important', self.css)+ self.assertIn('body:not([data-engine="ltx"]) .cz-body > #aspectRow.mode-only.show { display: none !important', self.css)++ def test_fold_rule_specificity_beats_the_show_rule(self):+ show_rule = '.cz-body > #aspectRow.mode-only.show'+ fold_rule = 'body:not([data-engine="ltx"]) .cz-body > #aspectRow.mode-only.show'+ self.assertGreater(_specificity(fold_rule), _specificity(show_rule))++ def test_generated_engine_fold_rule_alone_was_the_old_losing_rule(self):+ # The ORIGINAL bug: _engine_css()'s generated fold rule for+ # data-ltx-only elements has lower specificity than the show rule —+ # this is what let #aspectRow leak through on H3. Confirms the new+ # ID-qualified rule was necessary, not just cosmetic.+ show_rule = '.cz-body > #aspectRow.mode-only.show'+ generated_fold = 'body:not([data-engine="ltx"]) [data-ltx-only]'+ self.assertLess(_specificity(generated_fold), _specificity(show_rule))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_stats_fetch_quiet.py b/test_stats_fetch_quiet.pynew file mode 100644index 0000000..0af97c6--- /dev/null+++ b/test_stats_fetch_quiet.py@@ -0,0 +1,83 @@+"""VC-33: the maintainer's GitHub-stats refresh never writes into a user's+Logs tab.++WHAT THIS GUARDED AGAINST. `_run_stats_fetch_once()` (feeds the /stats+dashboard's historic data — a maintainer-only nicety, nothing a Phosphene+user renders or clicks touches it) reported through `push()`, the SAME+in-memory log `/status.log` and the panel's Logs tab read. A fresh install+with a resolvable GitHub token (a maintainer's own machine, or any dev box+with `gh auth token` set) got exactly one line in an otherwise-empty Logs+tab: "stats: rate-limit remaining: 4848/5000" - cryptic, about a feature the+user has never heard of, and indistinguishable from a real warning.++Fixed by routing every message in `_run_stats_fetch_once()` through+`_stats_debug()`, which writes to stderr (the maintainer's own terminal /+Pinokio process log) instead of the shared `push()` log.+"""+from __future__ import annotations++import io+import sys+import unittest+from unittest import mock++import mlx_ltx_panel as p+++class StatsFetchNeverTouchesTheSharedLog(unittest.TestCase):+ def setUp(self):+ # These two module-level warned-once latches persist across tests+ # in a whole-suite run; reset so each case actually exercises the+ # branch it means to.+ p._STATS_WARNED_NO_TOKEN = False+ p._STATS_WARNED_FETCH_FAIL = False+ self.addCleanup(setattr, p, "_STATS_WARNED_NO_TOKEN", False)+ self.addCleanup(setattr, p, "_STATS_WARNED_FETCH_FAIL", False)++ def _log_len(self) -> int:+ with p.LOCK:+ return len(p.STATE["log"])++ def test_no_token_case_does_not_push(self):+ before = self._log_len()+ with mock.patch.object(p, "_resolve_github_token", return_value=""), \+ mock.patch.object(sys, "stderr", io.StringIO()) as err:+ p._run_stats_fetch_once()+ self.assertEqual(self._log_len(), before, "no-token case wrote to the shared log")+ self.assertIn("no GitHub token resolvable", err.getvalue())++ def test_successful_fetch_does_not_push(self):+ before = self._log_len()+ fake = mock.Mock(returncode=0, stdout="repo stats: rate-limit remaining: 4848/5000\n", stderr="")+ with mock.patch.object(p, "_resolve_github_token", return_value="ghp_fake"), \+ mock.patch.object(p, "STATS_FETCHER") as fetcher, \+ mock.patch.object(p.subprocess, "run", return_value=fake), \+ mock.patch.object(sys, "stderr", io.StringIO()) as err:+ fetcher.is_file.return_value = True+ p._run_stats_fetch_once()+ self.assertEqual(self._log_len(), before, "a successful fetch wrote to the shared log")+ self.assertIn("rate-limit remaining", err.getvalue())++ def test_fetch_failure_does_not_push(self):+ before = self._log_len()+ fake = mock.Mock(returncode=1, stdout="", stderr="HTTP 403: rate limited")+ with mock.patch.object(p, "_resolve_github_token", return_value="ghp_fake"), \+ mock.patch.object(p, "STATS_FETCHER") as fetcher, \+ mock.patch.object(p.subprocess, "run", return_value=fake), \+ mock.patch.object(sys, "stderr", io.StringIO()) as err:+ fetcher.is_file.return_value = True+ p._run_stats_fetch_once()+ self.assertEqual(self._log_len(), before, "a failed fetch wrote to the shared log")+ self.assertIn("dashboard refresh skipped", err.getvalue())++ def test_the_function_source_never_calls_push(self):+ """Belt + braces: even a future edit that adds a new branch can't+ reintroduce push() without this failing, independent of which+ branches the tests above happen to exercise."""+ import inspect+ src = inspect.getsource(p._run_stats_fetch_once)+ self.assertNotIn("push(", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_stills_first.py b/test_stills_first.pynew file mode 100644index 0000000..fd12d79--- /dev/null+++ b/test_stills_first.py@@ -0,0 +1,236 @@+#!/usr/bin/env python3+"""FILM-46: anchor stills get an approve step.++Before this, the render thread went straight from still to (expensive)+video with no way to look at the still first — the composition was only+ever seen after the minutes were already spent, and the estimate never+counted the stills at all.++Locked here: the render thread holds a shot back once its still lands until+it is approved; the /storyboard/approve-still and /approve-all-stills+routes; a freshly-landed still always needs its own approval even if an+earlier one on the same shot was approved; and the estimate counts still+generation.+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _shot(n, **kw):+ s = {"n": n, "uid": f"shot_{n:08x}", "mode": "text", "engine": "ltx",+ "prompt": f"a shot {n} happens", "duration_s": 5.0, "seed": 100 + n,+ "refs": [], "status": "pending"}+ s.update(kw)+ return s+++def _board(bid, shots, **kw):+ b = {"schema": 1, "id": bid, "title": "T", "created_at": 1,+ "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "anchor_stills": True, "stills_first": True,+ "shots": shots}+ b.update(kw)+ return b+++class FakeHandler:+ def __init__(self):+ self.status = None+ self.payload = None++ def _json(self, payload, status: int = 200):+ self.payload, self.status = payload, status+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ self.queue_state = {"queue": [], "current": None, "history": []}+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "STATE", self.queue_state),+ mock.patch.object(panel, "persist_queue", lambda: None),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)+ panel._SB_RENDERS.clear()+ self.addCleanup(panel._SB_RENDERS.clear)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def load(self, bid):+ return storyboard.load_storyboard(self.state, bid)++ def post(self, action, form):+ h = FakeHandler()+ panel.Handler._storyboard_post(h, action, "", form)+ return h+++class TheEstimateCountsStills(unittest.TestCase):+ def test_a_shot_with_no_still_yet_is_charged_the_still_cost(self):+ board = {"shots": [_shot(1)], "anchor_stills": True,+ "policy": storyboard.default_policy()}+ est = storyboard.estimate(board, pass_name="draft")+ self.assertEqual(est["still_secs"], round(storyboard._STILL_RENDER_SECS))++ def test_a_shot_that_already_has_its_still_is_not_charged_again(self):+ board = {"shots": [_shot(1, still="/o/s1_still.png")], "anchor_stills": True,+ "policy": storyboard.default_policy()}+ est = storyboard.estimate(board, pass_name="draft")+ self.assertEqual(est["still_secs"], 0)++ def test_anchor_stills_off_charges_nothing(self):+ board = {"shots": [_shot(1)], "anchor_stills": False,+ "policy": storyboard.default_policy()}+ est = storyboard.estimate(board, pass_name="draft")+ self.assertEqual(est["still_secs"], 0)++ def test_an_h3_shot_is_never_charged_a_still_it_cannot_use(self):+ board = {"shots": [_shot(1, engine="h3")], "anchor_stills": True,+ "policy": storyboard.default_policy()}+ est = storyboard.estimate(board, pass_name="draft")+ self.assertEqual(est["still_secs"], 0)++ def test_the_still_cost_is_folded_into_the_render_total(self):+ board = {"shots": [_shot(1)], "anchor_stills": True,+ "policy": storyboard.default_policy()}+ est = storyboard.estimate(board, pass_name="draft")+ self.assertGreaterEqual(est["render_secs"], est["still_secs"])+++class ANewStillAlwaysNeedsItsOwnApproval(Sandbox):+ def test_reconcile_resets_approval_on_a_fresh_still(self):+ board = _board("sb_re1", [_shot(1, still_job_id="j1", still_approved=True)])+ with mock.patch.object(panel, "_sb_job_index",+ return_value={"j1": {"status": "done",+ "output_path": "/o/new_still.png"}}):+ panel._sb_reconcile(board)+ shot = board["shots"][0]+ self.assertEqual(shot["still"], "/o/new_still.png")+ self.assertFalse(shot["still_approved"])+++class TheRenderThreadHoldsForApproval(Sandbox):+ def _run(self, board, *, still_status="done", still_dims_ok=True):+ bid = board["id"]+ self.save(board)+ panel._SB_RENDERS[bid] = {"stop": False, "queued": 0}+ queued_forms = []++ def enqueue(form):+ queued_forms.append(form)+ return f"video-{len(queued_forms)}"++ def job_index():+ return {}++ with mock.patch.object(panel, "_sb_enqueue", side_effect=enqueue), \+ mock.patch.object(panel, "_sb_job_index", side_effect=job_index), \+ mock.patch.object(panel, "_sb_h3_available", return_value=False), \+ mock.patch.object(panel, "h3_supports_chain_prompts", return_value=False), \+ mock.patch.object(panel, "h3_supports_first_frame", return_value=False), \+ mock.patch.object(panel, "_sb_lipsync_gate", lambda *a, **k: None), \+ mock.patch.object(panel, "_sb_sweep_stage_a", lambda *a, **k: None), \+ mock.patch.object(storyboard, "shot_to_job",+ lambda shot, *a, **k: {"mode": "t2v", "prompt": shot["prompt"]}):+ panel._sb_render_thread(bid, "draft", None)+ return queued_forms++ def test_a_shot_awaiting_approval_never_gets_a_video_job_queued(self):+ board = _board("sb_hold", [+ _shot(1, still="/o/s1_still.png", still_approved=False),+ ])+ forms = self._run(board)+ self.assertEqual(forms, [])+ after = self.load("sb_hold")+ self.assertEqual(after["shots"][0]["status"], "pending")++ def test_an_approved_shot_proceeds_to_video(self):+ board = _board("sb_go", [+ _shot(1, still="/o/s1_still.png", still_approved=True),+ ])+ forms = self._run(board)+ self.assertEqual(len(forms), 1)++ def test_only_the_unapproved_shots_are_held_others_still_render(self):+ board = _board("sb_mixed", [+ _shot(1, still="/o/s1.png", still_approved=True),+ _shot(2, still="/o/s2.png", still_approved=False),+ ])+ forms = self._run(board)+ self.assertEqual(len(forms), 1)+ self.assertIn("shot 1", forms[0]["prompt"])++ def test_stills_first_off_renders_straight_through_as_before(self):+ board = _board("sb_plain", [+ _shot(1, still="/o/s1.png", still_approved=False),+ ], stills_first=False)+ forms = self._run(board)+ self.assertEqual(len(forms), 1)+++class TheApproveRoutes(Sandbox):+ def test_approve_still_marks_one_shot(self):+ board = self.save(_board("sb_ap1", [+ _shot(1, still="/o/s1.png"), _shot(2, still="/o/s2.png")]))+ h = self.post("approve-still", {"id": ["sb_ap1"], "n": ["1"]})+ self.assertEqual(h.status, 200, h.payload)+ reloaded = self.load("sb_ap1")+ self.assertTrue(reloaded["shots"][0]["still_approved"])+ self.assertNotIn("still_approved", reloaded["shots"][1])++ def test_approve_still_refuses_a_shot_with_no_still_yet(self):+ board = self.save(_board("sb_ap2", [_shot(1)]))+ h = self.post("approve-still", {"id": ["sb_ap2"], "n": ["1"]})+ self.assertEqual(h.status, 400)++ def test_approve_still_404s_for_an_unknown_shot(self):+ board = self.save(_board("sb_ap3", [_shot(1, still="/o/s1.png")]))+ h = self.post("approve-still", {"id": ["sb_ap3"], "n": ["9"]})+ self.assertEqual(h.status, 404)++ def test_approve_all_stills_marks_every_pending_one(self):+ board = self.save(_board("sb_ap4", [+ _shot(1, still="/o/s1.png"),+ _shot(2, still="/o/s2.png", still_approved=True),+ _shot(3), # no still at all+ ]))+ h = self.post("approve-all-stills", {"id": ["sb_ap4"]})+ self.assertEqual(h.status, 200, h.payload)+ self.assertEqual(h.payload["approved"], 1)+ reloaded = self.load("sb_ap4")+ self.assertTrue(reloaded["shots"][0]["still_approved"])+ self.assertTrue(reloaded["shots"][1]["still_approved"])+ self.assertNotIn("still_approved", reloaded["shots"][2])+++class NewStillClearsApproval(unittest.TestCase):+ def test_clearing_a_machine_still_drops_its_approval_flag_too(self):+ board = {"shots": [_shot(1, still="/o/s1.png", still_approved=True,+ seed=42)]}+ shot = panel._sb_clear_still(board, 1)+ self.assertNotIn("still_approved", shot)+ self.assertNotIn("still", shot)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_stills_first_ui.py b/test_stills_first_ui.pynew file mode 100644index 0000000..d9584e9--- /dev/null+++ b/test_stills_first_ui.py@@ -0,0 +1,124 @@+#!/usr/bin/env python3+"""FILM-46 (client half): the Stills-first checkbox implies Anchor stills,+and a card shows Approve for a still awaiting one."""+from __future__ import annotations++import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _node(script: str) -> str:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run(["node", str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return result.stdout+ finally:+ path.unlink(missing_ok=True)+++class TheCheckboxImpliesAnchorStills(unittest.TestCase):+ def test_checking_stills_first_forces_and_locks_anchor_stills(self):+ fn = extract_function("sbStillsFirstSync", STORYBOARD_JS)+ script = f"""+'use strict';+const els = {{+ sbStillsFirst: {{ checked: true }},+ sbAnchorStills: {{ checked: false, disabled: false }},+}};+function sbEl(id) {{ return els[id]; }}+{fn}+sbStillsFirstSync();+console.log(JSON.stringify(els));+"""+ out = json.loads(_node(script))+ self.assertTrue(out["sbAnchorStills"]["checked"])+ self.assertTrue(out["sbAnchorStills"]["disabled"])++ def test_unchecking_stills_first_re_enables_anchor_stills(self):+ # Anchor stills was locked (checked + disabled) while Stills first+ # was on; turning Stills first back off must free it again so the+ # user can independently decide whether to keep anchor stills.+ fn = extract_function("sbStillsFirstSync", STORYBOARD_JS)+ script = f"""+'use strict';+const els = {{+ sbStillsFirst: {{ checked: false }},+ sbAnchorStills: {{ checked: true, disabled: true }},+}};+function sbEl(id) {{ return els[id]; }}+{fn}+sbStillsFirstSync();+console.log(JSON.stringify(els));+"""+ out = json.loads(_node(script))+ self.assertFalse(out["sbAnchorStills"]["disabled"])+ # still checked — turning Stills first off does not itself uncheck+ # anchor stills, it only unlocks the choice+ self.assertTrue(out["sbAnchorStills"]["checked"])+++class TheCardShowsApproveWhenAwaiting(unittest.TestCase):+ def _card(self, shot_over, board_over=None):+ fn = extract_function("sbShotCard", STORYBOARD_JS)+ shot = {"n": 1, "mode": "text", "prompt": "x", "status": "pending",+ "duration_s": 5, "seed": -1}+ shot.update(shot_over)+ board = {"shots": [shot], "stills_first": True}+ if board_over:+ board.update(board_over)+ r = {"per_shot_est": {}, "characters": [], "h3_available": False, "board": board}+ script = r"""+'use strict';+function escapeHtml(s) { if (!s) return ''; return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }+function friendlyJobError(raw) { return { friendly: String(raw || ''), hint: '' }; }+function sbEngineChip() { return ''; }+function sbFmtClock(s) { return '0:00'; }+function sbShotEst() { return ''; }+globalThis.BOOT = { ltx: { lengths: [] }, h3: { lengths: [] } };+""" + fn + f"""+console.log(sbShotCard({json.dumps(shot)}, {json.dumps(r)}, []));+"""+ return _node(script)++ def test_an_unapproved_still_shows_an_approve_button(self):+ html = self._card({"still": "/o/s1.png", "still_approved": False})+ self.assertIn('data-act="approve-still"', html)+ self.assertIn("sb-still-awaiting", html)++ def test_an_approved_still_shows_no_approve_button(self):+ html = self._card({"still": "/o/s1.png", "still_approved": True})+ self.assertNotIn('data-act="approve-still"', html)++ def test_stills_first_off_shows_no_approve_button_either(self):+ html = self._card({"still": "/o/s1.png", "still_approved": False},+ board_over={"stills_first": False})+ self.assertNotIn('data-act="approve-still"', html)++ def test_a_user_photo_never_shows_approve(self):+ html = self._card({"still": "/o/singer.png", "still_source": "user",+ "still_approved": False})+ self.assertNotIn('data-act="approve-still"', html)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard.py b/test_storyboard.pyindex 4a6c44c..6d2a3aa 100644--- a/test_storyboard.py+++ b/test_storyboard.py@@ -457,6 +457,36 @@ class Persistence(unittest.TestCase):self.assertEqual(rows[0]["id"], "sb_test")self.assertEqual(rows[0]["shots"], 1)+ def test_list_is_sorted_by_updated_not_created(self):+ # FILM-43: "Recent" means "touched most recently", not "minted+ # first" — a board planned days ago that you edited a minute ago+ # belongs at the top.+ with tempfile.TemporaryDirectory() as d:+ old_but_touched = _board([_shot(1)])+ old_but_touched["id"] = "sb_old_touched"+ old_but_touched["created_at"] = 1000+ old_but_touched["updated_at"] = 9000+ sb.save_storyboard(Path(d), old_but_touched)++ new_untouched = _board([_shot(1)])+ new_untouched["id"] = "sb_new_untouched"+ new_untouched["created_at"] = 5000+ new_untouched["updated_at"] = 5000+ sb.save_storyboard(Path(d), new_untouched)++ rows = sb.list_storyboards(Path(d))+ self.assertEqual([r["id"] for r in rows],+ ["sb_old_touched", "sb_new_untouched"])++ def test_a_board_with_no_updated_at_falls_back_to_created_at(self):+ with tempfile.TemporaryDirectory() as d:+ board = _board([_shot(1)])+ board["created_at"] = 42+ board.pop("updated_at", None)+ sb.save_storyboard(Path(d), board)+ rows = sb.list_storyboards(Path(d))+ self.assertEqual(rows[0]["updated_at"], 42)+def test_additive_fields_survive_and_do_not_invalidate(self):board = _board([_shot(1, grade="keep", note="more light", draft_job_id="j-1")],concept="a film", style="16mm", must=["the beam"], shots_target=6,@@ -554,6 +584,64 @@ class DialogueFitsTheShot(unittest.TestCase):self.assertIn("dialogue_does_not_fit", codes)+class JapaneseAndFrenchDialogueIsNotInvisible(unittest.TestCase):+ """FILM-45: English-only parsing broke non-Latin and accented films.++ A Japanese line was quoted with 「…」/『…』, never the ASCII apostrophe+ the old regexes required — so `_SPOKEN_WORDS_RE` (drives the a2v+ stillness/lip-sync gate) and `spoken_spans`/`shot_pacing_problem`+ (drives the dialogue-fits-the-shot check and the frame-fit correction)+ both saw "no speech at all" on a shot that plainly had some. A French+ line in «guillemets» hit the same wall. And even once a span WAS found,+ `.split()` on an unspaced CJK line counted it as one giant "word".+ """++ def test_a_japanese_corner_bracket_quote_registers_as_speech(self):+ p = "彼女は微笑んで、「こんにちは、世界」と言った。"+ self.assertTrue(sb._SPOKEN_WORDS_RE.search(p), p)+ spans = sb.spoken_spans(p)+ self.assertEqual(spans, ["こんにちは、世界"])++ def test_a_japanese_white_corner_bracket_quote_registers_too(self):+ p = "彼は『さようなら』と静かに言った。"+ self.assertTrue(sb._SPOKEN_WORDS_RE.search(p), p)+ self.assertEqual(sb.spoken_spans(p), ["さようなら"])++ def test_a_french_guillemet_quote_registers_as_speech(self):+ p = "Elle sourit et dit «bonjour tout le monde»."+ self.assertTrue(sb._SPOKEN_WORDS_RE.search(p), p)+ self.assertEqual(sb.spoken_spans(p), ["bonjour tout le monde"])++ def test_western_quotes_still_work_unchanged(self):+ p = "She says: 'hello there, friend.'"+ self.assertTrue(sb._SPOKEN_WORDS_RE.search(p), p)+ self.assertEqual(sb.spoken_spans(p), ["hello there, friend."])++ def test_a_single_word_western_quote_does_not_count_as_speech(self):+ # "2+ words" is still the bar for the Western form — this must not+ # regress while fixing the CJK/French forms.+ self.assertFalse(sb._SPOKEN_WORDS_RE.search("she says 'no'"))++ def test_cjk_characters_count_as_individual_words_for_pacing(self):+ # No spaces between these ten characters; a plain .split() would+ # have counted this as ONE word and badly under-timed the shot.+ self.assertEqual(sb.spoken_word_count("こんにちは世界また会いましょう"), 15)++ def test_western_word_counting_is_unaffected(self):+ self.assertEqual(sb.spoken_word_count("hello there my friend"), 4)++ def test_a_mixed_cjk_and_latin_line_counts_both(self):+ self.assertEqual(sb.spoken_word_count("hello 世界"), 3)++ def test_an_unspaced_japanese_line_gets_a_real_pacing_check(self):+ # A 20-character sung/spoken CJK line inside a 1-second shot must be+ # flagged as overstuffed — under the old .split() count it looked+ # like "1 word", which no duration would ever flag as too long.+ p = "「" + ("あ" * 20) + "」" + "と彼女は言った。"+ prob = sb.shot_pacing_problem(p, 1.0)+ self.assertIsNotNone(prob)++class TrainedVoiceActuallyLoads(unittest.TestCase):"""`no_voice` gates the trained voice LoRA, and it was engine-blind.@@ -767,6 +855,44 @@ class SpeechLawAtBoardLevel(unittest.TestCase):self.assertIn("Write the line", msg)+class SingingIsNotFlaggedAsUnwrittenSpeech(unittest.TestCase):+ """FILM-55: the owner's own board flagged real singing shots — "'sings'+ implies someone is speaking, but no spoken line is written" — because a+ re-plan (or an older save, from before FILM-21) had left the shot's mode+ reading "text" while it was still lip-synced to the song. mode == "a2v"+ was already exempt; this pins two more paths to the same exemption:+ the shot's own `audio` field (set once by music_video.emit, untouched by+ a mode drift) and the board simply carrying a song at all.+ """+ PROMPT = "close-up, singing to camera"++ def test_an_a2v_shot_was_already_exempt(self):+ board = _board([dict(_shot(1), prompt=self.PROMPT, mode="a2v")])+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertNotIn("speech_without_words", codes)++ def test_a_mode_drifted_shot_is_exempt_if_it_still_carries_audio(self):+ # The exact shape of the owner's bug: mode says "text" (a re-plan+ # dropped it) but the shot is still, in fact, singing.+ board = _board([dict(_shot(1), prompt=self.PROMPT, mode="text",+ audio="/out/song.wav")])+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertNotIn("speech_without_words", codes)++ def test_any_shot_on_a_board_with_a_song_is_exempt(self):+ board = _board([dict(_shot(1), prompt=self.PROMPT, mode="text")],+ music_video={"song": "/out/song.wav"})+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertNotIn("speech_without_words", codes)++ def test_an_ordinary_board_with_no_song_is_still_protected(self):+ # The exemption must not swallow the real bug it exists to catch.+ board = _board([dict(_shot(1), prompt="bizarrotrn addresses the camera",+ mode="text", character_id=None, trigger=None)])+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertIn("speech_without_words", codes)++class Locations(unittest.TestCase):"""The same room in every shot that claims to be in it.@@ -843,6 +969,60 @@ class Locations(unittest.TestCase):self.assertEqual(sb.validate_storyboard(board), [])+class Light(unittest.TestCase):+ """FILM-14 (item 4): the same fix as Locations, one axis over — a cut+ jumps visibly when each shot re-invents its own lighting. Written ONCE+ on the board and appended by compose_shot_prompt to every shot not yet+ rendered, same "patch never overwrite, injected at render time" shape.+ """+ NOTE = "warm practical lamps, single source, deep shadows"++ def test_the_light_note_reaches_the_rendered_prompt(self):+ shot = {"n": 1, "trigger": "bizarrotrn", "prompt": "speaks to camera"}+ got = sb.compose_shot_prompt(shot, light=self.NOTE)+ self.assertIn(self.NOTE, got)+ self.assertTrue(got.startswith("bizarrotrn speaks to camera"),+ "subject and action still come first")++ def test_it_lands_after_the_location_not_instead_of_it(self):+ loc = {"id": "study", "name": "The study",+ "description": "a dark oak-panelled study"}+ shot = {"n": 1, "trigger": "x", "prompt": "leans on the desk",+ "location_id": "study"}+ got = sb.compose_shot_prompt(shot, {"study": loc}, light=self.NOTE)+ self.assertIn("oak-panelled", got)+ self.assertIn(self.NOTE, got)+ self.assertLess(got.index("oak-panelled"), got.index(self.NOTE))++ def test_a_board_with_no_light_note_is_completely_unchanged(self):+ shot = {"n": 1, "trigger": "x", "prompt": "does a thing"}+ self.assertEqual(sb.compose_shot_prompt(shot, light=""), "x does a thing")+ self.assertEqual(sb.compose_shot_prompt(shot), "x does a thing")++ def test_a_shot_that_already_wrote_its_own_light_is_not_doubled(self):+ shot = {"n": 1, "trigger": "x",+ "prompt": f"stands by the window, {self.NOTE}"}+ got = sb.compose_shot_prompt(shot, light=self.NOTE)+ self.assertEqual(got.lower().count(self.NOTE.lower()), 1)++ def test_shot_to_job_injects_it_because_that_is_the_only_choke_point(self):+ shot = {"n": 1, "mode": "character", "trigger": "bizarrotrn",+ "prompt": "speaks", "framing": "medium close-up"}+ job = sb.shot_to_job(shot, {"quality": "balanced", "width": 1024,+ "height": 576, "frames": 121},+ light=self.NOTE)+ self.assertIn(self.NOTE, job["prompt"])+ self.assertIn("medium close-up", job["prompt"])++ def test_board_light_reads_the_boards_own_field(self):+ board = _board([_shot(1)], light=self.NOTE)+ self.assertEqual(sb.board_light(board), self.NOTE)++ def test_board_light_is_empty_string_not_none_when_absent(self):+ board = _board([_shot(1)])+ self.assertEqual(sb.board_light(board), "")++class LocationViews(unittest.TestCase):"""THE CAR WASH — the acceptance benchmark, on the deterministic half.diff --git a/test_storyboard_assembly.py b/test_storyboard_assembly.pyindex 13081e1..9e07003 100644--- a/test_storyboard_assembly.py+++ b/test_storyboard_assembly.py@@ -39,6 +39,7 @@ sys.path.insert(0, str(ROOT / "scripts"))from extract_panel_js import extract_function # noqa: E402import mlx_ltx_panel as panel # noqa: E402+import storyboard_editor as sedit # noqa: E402import storyboard # noqa: E402NODE = shutil.which("node")@@ -1500,6 +1501,13 @@ function phosToast(msg, opts) { CALLS.toasts.push({ msg: String(msg), opts: opts// what is under test here is that the export goes there at all — the screen// itself is locked by test_storyboard_film.py.function sbFilmOpen(opts) { CALLS.landed.push(opts || {}); }+// FILM-48: sbExport() now asks sbMusicVideoBlock() whether this board is a+// music video before choosing its route — the real function, not a stub,+// so a change to what counts as "is one" cannot drift from what this test+// exercises. None of these fixtures set SB.payload.board.music_video, so it+// reads null and every case here takes the ordinary /storyboard/export+// route (the music-video route itself is test_export_music_video_routing.py).+__SB_MUSIC_VIDEO_BLOCK__class URLSearchParams { constructor() { this.v = {}; } set(k, x) { this.v[k] = x; } }let RESPONSE = null;async function fetch(url) {@@ -1530,8 +1538,9 @@ class ExportButton(unittest.TestCase):@classmethoddef setUpClass(cls):- cls.script = SB_EXPORT_SHIM.replace("__SB_EXPORT__",- extract_function("sbExport"))+ cls.script = (SB_EXPORT_SHIM+ .replace("__SB_MUSIC_VIDEO_BLOCK__", extract_function("sbMusicVideoBlock"))+ .replace("__SB_EXPORT__", extract_function("sbExport")))def run_export(self, response: dict) -> dict:with tempfile.TemporaryDirectory() as tmp:@@ -1781,14 +1790,23 @@ class SegmentIndexIsNotInputIndex(unittest.TestCase):self.assertNotIn("[4:a]atrim", g, mode)self.assertEqual(len(inputs), 3)- def test_an_unreadable_still_is_dropped_and_the_indices_close_up(self):+ def test_an_unreadable_still_plays_as_black_at_its_own_length(self):+ # FILM-15: this used to DROP the segment — the film came out one+ # still's length shorter, indices closed up, and nothing said why.+ # It now pads the slot with a slug of the still's own duration+ # instead, so the film's total length and every later clip's+ # position stay exactly what the timeline said they were.with mock.patch.object(panel, "_sb_probe_clip",side_effect=lambda p: _probe(1024, 576, 10.0)), \mock.patch.object(panel, "_sb_probe_still", return_value=None):segs, unreadable, inputs = panel._sb_timeline_segments(self.TIMELINE)self.assertEqual(unreadable, ["card.png"])- self.assertEqual([s["kind"] for s in segs], ["video", "slug", "video"])- self.assertEqual([s["input"] for s in segs], [0, None, 1])+ self.assertEqual([s["kind"] for s in segs],+ ["video", "slug", "slug", "video"])+ # The still's own input index is gone; the video after it shifts+ # down to 1 (not 2), since only TWO `-i`s were ever needed now.+ self.assertEqual([s["input"] for s in segs], [0, None, None, 1])+ self.assertEqual(segs[2]["duration"], 3.0) # the still's own lengthself.assertEqual(len(inputs), 2)def test_a_slug_needs_no_probe_at_all(self):@@ -1806,6 +1824,120 @@ class SegmentIndexIsNotInputIndex(unittest.TestCase):self.assertEqual(segs[0]["duration"], 2.0)+class MissingAndShortMediaPlayAsBlack(unittest.TestCase):+ """FILM-15 — an offline or truncated file used to shrink the film by+ exactly its length, silently, with every later clip sliding earlier to+ meet it. It now pads the slot with black at the slot's own length.+ """++ TIMELINE = [+ {"path": "/x/a.mp4", "start": 0.0, "end": 2.0, "film_start": 0.0},+ {"path": "/x/gone.mp4", "start": 0.0, "end": 4.0, "film_start": 2.0},+ {"path": "/x/b.mp4", "start": 1.0, "end": 3.0, "film_start": 6.0},+ ]++ def test_an_unreadable_video_clip_plays_as_black_at_its_own_length(self):+ def probe(path):+ return None if "gone" in str(path) else _probe(1024, 576, 10.0)+ with mock.patch.object(panel, "_sb_probe_clip", side_effect=probe):+ segs, unreadable, inputs = panel._sb_timeline_segments(self.TIMELINE)+ self.assertEqual(unreadable, ["gone.mp4"])+ self.assertEqual([s["kind"] for s in segs], ["video", "slug", "video"])+ self.assertEqual([s["input"] for s in segs], [0, None, 1])+ self.assertEqual(segs[1]["duration"], 4.0) # the missing clip's own slot+ self.assertEqual(len(inputs), 2)++ def test_an_unreadable_clip_with_speed_fills_its_FILM_length_not_its_source_length(self):+ timeline = [dict(self.TIMELINE[1], speed=2.0)] # 4.0 source / 2.0 = 2.0 on film+ with mock.patch.object(panel, "_sb_probe_clip", return_value=None):+ segs, unreadable, _inputs = panel._sb_timeline_segments(timeline)+ self.assertEqual(unreadable, ["gone.mp4"])+ self.assertEqual(segs[0]["duration"], 2.0)++ def test_a_file_shorter_than_its_slot_plays_real_footage_then_black(self):+ # The source has only 3.0s; the slot asks for 4.0 (0.0-4.0).+ with mock.patch.object(panel, "_sb_probe_clip",+ side_effect=lambda p: _probe(1024, 576, 3.0)):+ segs, unreadable, inputs = panel._sb_timeline_segments(+ [{"path": "/x/short.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0}])+ self.assertEqual(unreadable, ["short.mp4 (short — padded with black)"])+ self.assertEqual([s["kind"] for s in segs], ["video", "slug"])+ self.assertEqual(segs[0]["duration"], 3.0) # everything the file has+ self.assertEqual(segs[1]["duration"], 1.0) # the missing tail, in black+ self.assertEqual(len(inputs), 1) # the slug needs no `-i`++ def test_a_file_at_least_as_long_as_its_slot_gets_no_padding(self):+ with mock.patch.object(panel, "_sb_probe_clip",+ side_effect=lambda p: _probe(1024, 576, 10.0)):+ segs, unreadable, _inputs = panel._sb_timeline_segments(+ [{"path": "/x/plenty.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0}])+ self.assertEqual(unreadable, [])+ self.assertEqual([s["kind"] for s in segs], ["video"])+ self.assertEqual(segs[0]["duration"], 4.0)+++class EditToCutsFillsItsOwnGaps(unittest.TestCase):+ """FILM-27 — `edit_to_cuts` used to describe only the clips; a hole+ between two of them simply had no entry, so the concat-based assembler+ closed it and slid everything after it earlier. It now emits a slug+ for every gap `edit_gaps` (the same list the header's hole count reads)+ reports, so the assembler sees the film's real length.+ """++ def _clip(self, cid, path, fs, fe, **kw):+ return dict({"id": cid, "path": path, "proxy": None, "start": 0.0,+ "end": fe - fs, "film_start": fs, "film_end": fe,+ "source": "human", "locked": False, "duration": 20.0},+ **kw)++ def test_a_mid_timeline_gap_becomes_a_slug_of_the_right_length_and_place(self):+ edit = {"clips": [self._clip("a", "/x/a.mp4", 0.0, 2.0),+ self._clip("b", "/x/b.mp4", 5.0, 7.0)]}+ cuts = sedit.edit_to_cuts(edit)+ self.assertEqual([(c.get("kind", "video"), round(c["film_start"], 3))+ for c in cuts],+ [("video", 0.0), ("slug", 2.0), ("video", 5.0)])+ gap = cuts[1]+ self.assertIsNone(gap["path"])+ self.assertEqual(gap["end"] - gap["start"], 3.0)++ def test_a_head_gap_becomes_a_leading_slug(self):+ edit = {"clips": [self._clip("a", "/x/a.mp4", 6.0, 10.0)]}+ cuts = sedit.edit_to_cuts(edit)+ self.assertEqual([c.get("kind", "video") for c in cuts], ["slug", "video"])+ self.assertEqual(cuts[0]["film_start"], 0.0)+ self.assertEqual(cuts[0]["end"] - cuts[0]["start"], 6.0)++ def test_no_gap_no_extra_entry(self):+ edit = {"clips": [self._clip("a", "/x/a.mp4", 0.0, 2.0),+ self._clip("b", "/x/b.mp4", 2.0, 4.0)]}+ cuts = sedit.edit_to_cuts(edit)+ self.assertEqual(len(cuts), 2)+ self.assertNotIn("kind", cuts[0])++ def test_a_transition_next_to_a_gap_is_not_confused_for_one_across_it(self):+ # A transition can only ever exist between clips that already touch+ # (the UI offers it nowhere else), so a gap elsewhere in the film+ # must not disturb it. Every clip carries a little source handle+ # (start/end past the visible window) — a dissolve needs room to+ # pull from, or `resolve_transitions` refuses it for THAT reason,+ # which is not the thing under test here.+ def handled(cid, path, fs, fe):+ return dict(self._clip(cid, path, fs, fe), start=0.5, end=fe - fs + 0.5)+ edit = {"clips": [handled("a", "/x/a.mp4", 0.0, 2.0),+ handled("b", "/x/b.mp4", 2.0, 4.0),+ handled("c", "/x/c.mp4", 7.0, 9.0)],+ "transitions": [{"after_clip": "a", "before_clip": "b",+ "kind": "dissolve", "duration": 0.5}]}+ cuts = sedit.edit_to_cuts(edit)+ by_id = {c.get("path"): c for c in cuts}+ self.assertIn("transition", by_id["/x/a.mp4"])+ self.assertEqual([c.get("kind", "video") for c in cuts],+ ["video", "video", "slug", "video"])++class StillsAndSlugsInTheGraph(unittest.TestCase):def graph(self, segments, **kw):return panel._sb_film_filtergraph([], 1024, 576, 48000, "yuv420p",diff --git a/test_storyboard_dispatch_integrity.py b/test_storyboard_dispatch_integrity.pyindex f3aea7b..15fb977 100644--- a/test_storyboard_dispatch_integrity.py+++ b/test_storyboard_dispatch_integrity.py@@ -199,6 +199,43 @@ class StopFilmStopsItsStills(Sandbox):self.assertEqual(len(queued), 1)+class TheRealResolutionIsStamped(Sandbox):+ """FILM-42: the Draft/Delivery badge used to be read off whichever pass+ queued the clip, board-wide — not the clip itself. _sb_reconcile now+ ffprobes a shot's REAL pixel size the moment a new output lands, once,+ so the client can judge each shot on its own clip."""++ def _reconcile(self, board, index, dims=(1024, 576)):+ with mock.patch.object(panel, "_sb_job_index", return_value=index), \+ mock.patch.object(panel, "_probe_video_dims", return_value=dims):+ return panel._sb_reconcile(board)++ def test_a_newly_landed_output_is_measured(self):+ board = _board([_shot(1, uid="shot_00000001", draft_job_id="j1")])+ self._reconcile(board, {"j1": {"status": "done", "output_path": "/o/s1.mp4"}},+ dims=(1280, 704))+ self.assertEqual(board["shots"][0]["output_dims"], [1280, 704])++ def test_a_failed_probe_is_silent_and_clears_any_stale_dims(self):+ board = _board([_shot(1, uid="shot_00000001", draft_job_id="j1",+ output_dims=[999, 999])])+ self._reconcile(board, {"j1": {"status": "done", "output_path": "/o/s1.mp4"}},+ dims=(0, 0))+ self.assertNotIn("output_dims", board["shots"][0])++ def test_an_unchanged_output_is_not_reprobed(self):+ board = _board([_shot(1, uid="shot_00000001", draft_job_id="j1",+ draft_output="/o/s1.mp4", status="done",+ output_dims=[1024, 576])])+ with mock.patch.object(panel, "_sb_job_index",+ return_value={"j1": {"status": "done",+ "output_path": "/o/s1.mp4"}}), \+ mock.patch.object(panel, "_probe_video_dims") as probe:+ panel._sb_reconcile(board)+ probe.assert_not_called()+ self.assertEqual(board["shots"][0]["output_dims"], [1024, 576])++class ACutShotStaysCut(Sandbox):"""SB5-10."""@@ -245,5 +282,75 @@ class ACutShotStaysCut(Sandbox):self.assertEqual(self.load(board["id"])["shots"][0]["status"], "done")+class AShotWhoseJobVanishedIsUnstuck(Sandbox):+ """FILM-18. /queue/remove and /queue/clear drop a job with NO history —+ it is not "cancelled", it simply vanishes from `_sb_job_index()`. A shot+ still pointing at that job id used to be left alone forever: stuck+ reading "queued" (or "rendering"), locked in the UI (the card and the+ trash button both gate on non-done status) with no way to re-render or+ delete it."""++ def _reconcile(self, board, index):+ with mock.patch.object(panel, "_sb_job_index", return_value=index):+ return panel._sb_reconcile(board)++ def test_a_queued_shot_whose_job_vanished_goes_back_to_pending(self):+ board = _board([_shot(1, status="queued", draft_job_id="ghost")])+ changed = self._reconcile(board, {})+ self.assertTrue(changed)+ shot = board["shots"][0]+ self.assertEqual(shot["status"], "pending")+ self.assertNotIn("draft_job_id", shot)++ def test_a_rendering_shot_whose_job_vanished_goes_back_to_pending_too(self):+ board = _board([_shot(1, status="rendering", final_job_id="ghost")])+ self._reconcile(board, {})+ shot = board["shots"][0]+ self.assertEqual(shot["status"], "pending")+ self.assertNotIn("final_job_id", shot)++ def test_a_shot_that_already_has_its_output_is_left_alone(self):+ # The job that MADE this output can legitimately age out of history+ # after the shot is done — that must never un-finish it.+ board = _board([_shot(1, status="done", draft_job_id="ghost",+ draft_output="/o/s1.mp4")])+ self._reconcile(board, {})+ shot = board["shots"][0]+ self.assertEqual(shot["status"], "done")+ self.assertEqual(shot["draft_job_id"], "ghost")+ self.assertEqual(shot["draft_output"], "/o/s1.mp4")++ def test_a_cut_shot_stays_cut_even_with_a_vanished_job(self):+ board = _board([_shot(1, status="skipped", grade="cut",+ draft_job_id="ghost")])+ self._reconcile(board, {})+ self.assertEqual(board["shots"][0]["status"], "skipped")++ def test_a_pending_shot_with_no_job_id_is_unaffected(self):+ board = _board([_shot(1, status="pending", uid="shot_00000001")])+ changed = self._reconcile(board, {})+ self.assertFalse(changed)+ self.assertEqual(board["shots"][0]["status"], "pending")++ def test_a_vanished_still_job_is_cleared_so_a_new_one_can_be_queued(self):+ board = _board([_shot(1, still_job_id="ghost-still")])+ changed = self._reconcile(board, {})+ self.assertTrue(changed)+ self.assertNotIn("still_job_id", board["shots"][0])++ def test_the_skipped_still_sentinel_is_never_treated_as_a_vanished_job(self):+ # "skipped" means "could not even be queued, render unanchored" —+ # it was never a real job id, and clearing it would silently retry+ # a still the render thread deliberately gave up on.+ board = _board([_shot(1, still_job_id="skipped",+ still_error="no engine for stills",+ uid="shot_00000002")])+ changed = self._reconcile(board, {})+ self.assertFalse(changed)+ shot = board["shots"][0]+ self.assertEqual(shot["still_job_id"], "skipped")+ self.assertEqual(shot["still_error"], "no engine for stills")++if __name__ == "__main__":unittest.main()diff --git a/test_storyboard_editor_api.py b/test_storyboard_editor_api.pyindex 580e27f..9de92ec 100644--- a/test_storyboard_editor_api.py+++ b/test_storyboard_editor_api.py@@ -101,6 +101,11 @@ class FakeHandler:# complete 404 response onto the same socket — was invisible to 250# green tests.self.handled = None+ # A raw (send_response/send_header/end_headers/wfile.write) response+ # — the poster route's own shape, not the _json/_serve_video_with_+ # range doors every other route here already stands in for.+ self.headers_sent = {}+ self.body = b""def _json(self, payload, status: int = 200):self.payload, self.status = payload, status@@ -111,6 +116,26 @@ class FakeHandler:def _serve_video_with_range(self, path):self.served = Path(path)+ def send_response(self, code, *a):+ self.status = code++ def send_header(self, key, value):+ self.headers_sent[key] = value++ def end_headers(self):+ pass++ class _Wfile:+ def __init__(self, outer):+ self._outer = outer++ def write(self, data):+ self._outer.body += data++ @property+ def wfile(self):+ return FakeHandler._Wfile(self)+# the two methods under test, bound to this stand-indef get(self, url: str):self.handled = panel.Handler._storyboard_edit_get(self, urlparse(url))@@ -1020,14 +1045,17 @@ class RenderRoute(EditorCase):self.assertEqual(af.call_args.kwargs["music"], str(song))self.assertEqual(af.call_args.kwargs["music_start"], 12.5)- def test_gaps_are_DISCLOSED_because_the_concat_closes_them(self):+ def test_gaps_are_DISCLOSED_because_they_now_play_as_black(self):+ # FILM-27: the assembler pads a gap with black instead of closing+ # it, so the note says that instead of warning the film will be+ # shorter than the timeline.self.edit_with([_clip(str(self.clips[0]), 0.0, 2.0, 0.0),_clip(str(self.clips[1]), 0.0, 2.0, 7.0)])with mock.patch.object(panel, "_sb_assemble_film",return_value={"ok": True, "duration": 4.0}):h = FakeHandler().post("edit/render", {"id": "sb_t"})self.assertEqual(len(h.payload["gaps"]), 1)- self.assertIn("closed by the concatenation", h.payload["gaps_note"])+ self.assertIn("play as black", h.payload["gaps_note"])self.assertEqual(h.payload["timeline_duration"], 9.0)def test_an_empty_timeline_is_an_honest_refusal(self):@@ -1194,6 +1222,74 @@ class GenerateIntoAGap(EditorCase):self.assertEqual(board["shots"][-1]["final_job_id"], h.payload["job_id"])+class RetakeResolvesByPathNotByTheSavedFile(EditorCase):+ """FILM-35 — a retake used to resolve `retake_of` by loading the SAVED+ edit.json and looking the clip id up in it. A clip split, duplicated or+ added since the last manual Save — the ordinary state of a timeline+ under the save model — was not IN that file yet, so the retake refused+ with "that clip is not on this timeline any more" for a clip plainly+ selected on screen. The client now sends the clip's own path too, which+ is everything this route actually needed.+ """++ def setUp(self):+ super().setUp()+ self._q = mock.patch.dict(panel.STATE, {"queue": [], "history": [],+ "current": None}, clear=False)+ self._q.start()+ self._pq = mock.patch.object(panel, "persist_queue", lambda: None)+ self._pq.start()++ def tearDown(self):+ self._pq.stop()+ self._q.stop()+ super().tearDown()++ def gen(self, **form):+ f = {"id": "sb_t", "prompt": "a slow push in on the gate",+ "duration": "5", "film_start": "12.5"}+ f.update(form)+ return FakeHandler().post("edit/generate", f)++ def test_the_path_alone_resolves_the_source_shot(self):+ # No edit.json on disk at all — the retake still finds shot 1 (whose+ # draft_output is self.clips[0]) by the path the client sent.+ h = self.gen(retake_of="not-in-any-saved-file", retake_path=str(self.clips[0]))+ self.assertEqual(h.status, 202)+ new_shot = storyboard.load_storyboard(self.state, "sb_t")["shots"][-1]+ self.assertEqual(new_shot["title"], "shot 1") # source resolved via clips[0]+ self.assertEqual(new_shot["edit_slot"]["retake_of"], "not-in-any-saved-file")++ def test_a_stale_saved_timeline_does_not_block_it_either(self):+ # edit.json IS on disk, but it does not carry the id the client is+ # retaking (a split made after that save) — retake_path still wins.+ sedit.save_edit(self.bdir, _edit([+ {"id": "other-clip", "path": str(self.clips[1]), "proxy": None,+ "start": 0.0, "end": 5.0, "film_start": 0.0, "film_end": 5.0,+ "source": "human", "locked": False, "duration": 10.0}]))+ h = self.gen(retake_of="c-split-after-save", retake_path=str(self.clips[0]))+ self.assertEqual(h.status, 202)+ new_shot = storyboard.load_storyboard(self.state, "sb_t")["shots"][-1]+ self.assertEqual(new_shot["title"], "shot 1")++ def test_with_no_path_at_all_it_falls_back_to_the_saved_file_as_before(self):+ # Backward compatible: an older client, or a script, that sends only+ # retake_of still works exactly as it always did.+ sedit.save_edit(self.bdir, _edit([+ {"id": "c1", "path": str(self.clips[2]), "proxy": None,+ "start": 0.0, "end": 5.0, "film_start": 0.0, "film_end": 5.0,+ "source": "human", "locked": False, "duration": 10.0}]))+ h = self.gen(retake_of="c1")+ self.assertEqual(h.status, 202)+ new_shot = storyboard.load_storyboard(self.state, "sb_t")["shots"][-1]+ self.assertEqual(new_shot["title"], "shot 3") # source resolved via clips[2]++ def test_neither_path_nor_a_matching_saved_clip_is_still_refused_cleanly(self):+ h = self.gen(retake_of="ghost")+ self.assertEqual(h.status, 400)+ self.assertEqual(panel.STATE["queue"], [])++class PrepareRun(EditorCase):"""The build loop itself — with ffmpeg mocked, but every decision real."""@@ -1495,6 +1591,86 @@ class AddClipRoute(EditorCase):self.assertTrue(str(clip["proxy"]).startswith("proxy/"))+# =============================================================================+# OFFLINE MEDIA — FILM-15+# =============================================================================+class OfflineMedia(EditorCase):+ """A moved or trashed file, named — instead of a black preview and a+ "Rendered N clips" toast over a film that quietly came out shorter.+ """++ def test_a_clip_whose_file_is_gone_is_flagged_offline(self):+ gone = self.root / "gone.mp4" # never written+ sedit.save_edit(self.bdir, _edit([dict(_clip(gone, 0, 4, 0), id="c1")]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.payload["offline"], ["c1"])++ def test_a_clip_whose_file_exists_is_not_flagged(self):+ sedit.save_edit(self.bdir, _edit([+ dict(_clip(self.clips[0], 0, 4, 0), id="c1")]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.payload["offline"], [])++ def test_a_slug_has_no_file_and_is_never_flagged(self):+ slug = {"id": "s1", "kind": "slug", "path": None, "start": 0.0,+ "end": 2.0, "film_start": 0.0, "film_end": 2.0,+ "source": "human", "locked": False}+ sedit.save_edit(self.bdir, _edit([slug]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.payload["offline"], [])++ def test_going_offline_and_coming_back_both_show_up_live(self):+ real = self.root / "flickers.mp4"+ real.write_bytes(b"x")+ sedit.save_edit(self.bdir, _edit([dict(_clip(real, 0, 4, 0), id="c1")]))+ self.assertEqual(+ FakeHandler().get("/storyboard/edit?id=sb_t").payload["offline"], [])+ real.unlink()+ self.assertEqual(+ FakeHandler().get("/storyboard/edit?id=sb_t").payload["offline"], ["c1"])+ real.write_bytes(b"x")+ self.assertEqual(+ FakeHandler().get("/storyboard/edit?id=sb_t").payload["offline"], [])+++class BoardSummaryCarriesWhetherThereIsATimeline(EditorCase):+ """FILM-43 — the Editor's film switcher filtered on `clips` (board+ SHOTS with an output file), so a film cut from Video-tab or imported+ clips — a real timeline, zero shots of its own — vanished from the+ list. `has_timeline` is edit.json's own existence, which is the+ question "does this film have something to edit" actually asks.+ """++ def test_a_board_with_an_edit_json_has_a_timeline(self):+ sedit.save_edit(self.bdir, _edit([_clip(self.clips[0], 0.0, 2.0, 0.0)]))+ row = panel._sb_board_summary(self.board)+ self.assertTrue(row["has_timeline"])++ def test_a_board_with_no_edit_json_does_not(self):+ empty = _board([], bid="sb_empty")+ storyboard.save_storyboard(self.state, empty)+ row = panel._sb_board_summary(empty)+ self.assertFalse(row["has_timeline"])+ self.assertEqual(row["clips"], 0) # the OLD signal agrees here++ def test_a_board_cut_from_imported_clips_has_a_timeline_but_no_rendered_shots(self):+ # The exact case that vanished: no shot of its own ever rendered+ # (clips == 0, no shots at all) but there is a real cut on the+ # timeline, imported from elsewhere.+ empty = _board([], bid="sb_imported")+ storyboard.save_storyboard(self.state, empty)+ sedit.save_edit(panel._sbe_board_dir(empty["id"]),+ _edit([_clip(self.clips[0], 0.0, 2.0, 0.0)]))+ row = panel._sb_board_summary(empty)+ self.assertEqual(row["clips"], 0)+ self.assertTrue(row["has_timeline"])++ def test_a_broken_editor_module_answers_false_not_a_500(self):+ with mock.patch.object(panel, "_sbe_import", side_effect=RuntimeError("boom")):+ row = panel._sb_board_summary(self.board)+ self.assertFalse(row["has_timeline"])++# =============================================================================# RELINK — the drafts a delivery pass left behind# =============================================================================@@ -1590,6 +1766,66 @@ class RelinkDraftToDelivery(EditorCase):h = FakeHandler().post("edit/relink", {"id": "sb_t"})self.assertEqual(h.status, 404)+ def test_relink_reprobes_the_new_files_duration(self):+ # FILM-15: a draft and its delivered swap are not guaranteed to run+ # the same length (a re-render, a different pass) — this used to+ # leave `duration` at the DRAFT's number forever. Here the new file+ # is longer than the existing window, so there is nothing to lose by+ # believing it — the Inspector's number stops being stale.+ final = self.deliver(1, "S01_final.mp4")+ sedit.save_edit(self.bdir, _edit([+ dict(_clip(self.clips[0], 0, 4, 0), duration=4.5)]))++ def fake_probe(path):+ return {"duration": 9.0} if str(path) == str(final) else None++ with mock.patch("storyboard_edit.probe_media", side_effect=fake_probe), \+ mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=lambda c, l: (Path(c[-1])+ .write_bytes(b"p"), ("", ""))[1]):+ h = FakeHandler().post("edit/relink", {"id": "sb_t"})+ self.assertTrue(h.payload["ok"])+ clip = sedit.load_edit(self.bdir)["clips"][0]+ self.assertEqual(clip["duration"], 9.0)++ def test_relink_to_a_SHORTER_file_still_succeeds_and_leaves_duration_alone(self):+ # The other half: a delivered pass that came back shorter than its+ # draft must not turn a relink that always worked into one that+ # refuses. `save_edit` blocks on `clip_past_the_end`, so applying the+ # honest (shorter) number here would refuse the whole write — the+ # timeline would be stuck pointing at the OLD file, unable to adopt+ # the new one at all. The stale duration is kept; the assembler pads+ # the now-short slot with black regardless (a different test class),+ # so nothing about the FILM is less safe for it.+ final = self.deliver(1, "S01_final.mp4")+ sedit.save_edit(self.bdir, _edit([+ dict(_clip(self.clips[0], 0, 4, 0), duration=20.0)]))++ def fake_probe(path):+ return {"duration": 3.5} if str(path) == str(final) else None++ with mock.patch("storyboard_edit.probe_media", side_effect=fake_probe), \+ mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=lambda c, l: (Path(c[-1])+ .write_bytes(b"p"), ("", ""))[1]):+ h = FakeHandler().post("edit/relink", {"id": "sb_t"})+ self.assertTrue(h.payload["ok"], h.payload)+ clip = sedit.load_edit(self.bdir)["clips"][0]+ self.assertEqual(clip["path"], str(final)) # the swap still landed+ self.assertEqual(clip["duration"], 20.0) # the stale number, on purpose+ self.assertEqual(sedit.validate_edit(sedit.load_edit(self.bdir)), [])++ def test_relink_leaves_duration_alone_when_the_new_file_cannot_be_probed(self):+ final = self.deliver(1, "S01_final.mp4")+ sedit.save_edit(self.bdir, _edit([+ dict(_clip(self.clips[0], 0, 4, 0), duration=20.0)]))+ with mock.patch("storyboard_edit.probe_media", return_value=None), \+ mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=lambda c, l: (Path(c[-1])+ .write_bytes(b"p"), ("", ""))[1]):+ FakeHandler().post("edit/relink", {"id": "sb_t"})+ self.assertEqual(sedit.load_edit(self.bdir)["clips"][0]["duration"], 20.0)+class UnknownActions(EditorCase):def test_an_unknown_editor_action_is_a_404_not_a_500(self):@@ -2103,6 +2339,39 @@ class NleExportRoute(EditorCase):self.assertEqual(h.status, 404)self.assertFalse(h.payload["ok"])+ def test_titles_and_cards_reach_the_project_FILM_50(self):+ # export_nle() has taken `overlays=` since it was written — this+ # route just never passed them, so every title and card vanished the+ # moment a film left for Premiere, Resolve or After Effects.+ card = self.out / "title.png"+ card.write_bytes(b"i" * 32)+ sedit.save_edit(self.bdir, _edit(+ [_clip(str(self.clips[0]), 0.0, 3.0, 0.0)],+ overlays=[{"id": "ov1", "kind": "image", "path": str(card),+ "title": "Chapter One", "start": 0.0, "end": 1.0,+ "film_start": 0.5, "film_end": 1.5}]))+ with mock.patch.object(panel, "_sb_probe_clip",+ return_value={"w": 1024, "h": 576,+ "duration": 9.0,+ "has_audio": True,+ "sample_rate": 48000}), \+ mock.patch.object(panel, "_sb_probe_still",+ return_value={"w": 800, "h": 600,+ "duration": 0.0,+ "has_audio": False,+ "sample_rate": 0}):+ h = FakeHandler().post("edit/export-nle", {"id": "sb_t"})+ self.assertTrue(h.payload["ok"], h.payload)+ xml = Path(h.payload["xml"]).read_text(encoding="utf-8")+ self.assertIn("Chapter One", xml)+ jsx = Path(h.payload["jsx"]).read_text(encoding="utf-8")+ self.assertIn('bring("/media/title.png")', jsx)+ self.assertIn("overlay 1:", jsx)+ # The card's own file was carried into the project's media/ folder,+ # not left pointing at the source gallery.+ self.assertTrue(any(p.name.startswith("title")+ for p in (Path(h.payload["dir"]) / "media").iterdir()))+def test_reveal_computes_its_own_path_from_the_board_id_alone(self):# The client sends nothing but the board id, so this can never become# an argument to `open` pointing outside the board's folder.@@ -2933,6 +3202,52 @@ class DraftsAreTheUsersOwn(unittest.TestCase):sedit.recover_backup(self.d)self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 6)+ # ---- FILM-54: the offer can say WHAT changed ---------------------------+ def test_a_single_brightness_change_is_named_precisely(self):+ sedit.save_edit(self.d, self._doc(n=2))+ bright = self._doc(n=2)+ bright["clips"][1]["adjust"] = {"brightness": 0.3}+ sedit.write_backup(self.d, bright)+ offer = sedit.pending_backup(self.d)+ self.assertEqual(offer["diff"], "1 clip changed: 02 brightness +0.30")++ def test_a_negative_brightness_change_keeps_its_sign(self):+ base = self._doc(n=1)+ base["clips"][0]["adjust"] = {"brightness": 0.3}+ sedit.save_edit(self.d, base)+ darker = self._doc(n=1)+ darker["clips"][0]["adjust"] = {"brightness": -0.1}+ sedit.write_backup(self.d, darker)+ self.assertEqual(sedit.pending_backup(self.d)["diff"],+ "1 clip changed: 01 brightness -0.40")++ def test_several_kinds_of_change_summarise_by_count(self):+ sedit.save_edit(self.d, self._doc(n=3))+ moved = self._doc(n=4) # one added+ moved["clips"][0]["locked"] = True # and one changed+ sedit.write_backup(self.d, moved)+ diff = sedit.pending_backup(self.d)["diff"]+ self.assertIn("1 clip changed", diff)+ self.assertIn("1 added", diff)++ def test_a_removed_clip_is_named_as_removed(self):+ sedit.save_edit(self.d, self._doc(n=3))+ fewer = self._doc(n=2)+ sedit.write_backup(self.d, fewer)+ self.assertEqual(sedit.pending_backup(self.d)["diff"], "1 removed")++ def test_the_soundtrack_alone_is_named_not_miscounted_as_a_clip(self):+ sedit.save_edit(self.d, self._doc(n=1))+ with_song = self._doc(n=1)+ with_song["audio"] = {"path": "/x/song.wav", "offset": 0.0}+ sedit.write_backup(self.d, with_song)+ self.assertEqual(sedit.pending_backup(self.d)["diff"], "soundtrack")++ def test_a_digest_equal_backup_is_not_offered_so_there_is_nothing_to_diff(self):+ sedit.save_edit(self.d, self._doc(n=2))+ sedit.write_backup(self.d, self._doc(n=2))+ self.assertIsNone(sedit.pending_backup(self.d))+class DraftRoutes(EditorCase):def _prime(self):@@ -3354,12 +3669,18 @@ class LinkingFreezesTheOffset(unittest.TestCase):def test_the_cut_list_carries_a_coupled_window_too(self):# An assembler that ignored it would render the sound back under the# picture — the J-cut would exist in the timeline and not in the film.+ # This fixture's clip starts at film_start=6.0 (see `_clip` above),+ # so FILM-27's gap-fill now leads the cut list with a black slug for+ # the head gap — real behaviour, not noise; find the clip's own+ # entry by its path rather than assuming index 0.cuts = sedit.edit_to_cuts(_edit([self._coupled()]))- self.assertEqual(cuts[0]["audio"],+ mine = next(c for c in cuts if c.get("path"))+ self.assertEqual(mine["audio"],{"start": 0.0, "end": 4.0, "film_start": 4.0})# ...and an ordinary clip still says nothing at all.plain = sedit.edit_to_cuts(_edit([self._clip()]))- self.assertNotIn("audio", plain[0])+ plain_mine = next(c for c in plain if c.get("path"))+ self.assertNotIn("audio", plain_mine)ENDCARD = Path("/Users/salo/pinokio/api/phosphene-dev.git/mlx_outputs/"@@ -3972,18 +4293,28 @@ class AHoleShorterThanAFrame(unittest.TestCase):def test_the_render_and_the_timeline_now_agree_on_the_length(self):"""Where the black frame came from, and where it did not.- The assembler consumes `start`/`end` per clip and CONCATENATES, so a- hole never reached ffmpeg at all — the rendered film was already the- healed length. The PREVIEW is the half that painted black in it. The- two therefore disagreed by exactly the hole, silently, and healing is- what makes the number on the header the number that comes out.+ FILM-27: `edit_to_cuts` now fills any gap `edit_gaps` reports (bigger+ than half a frame, the same threshold `heal_subframe_gaps` uses) with+ a black slug of its own — so of this doc's three gaps (0.02094,+ 0.01584, 0.004), the ffmpeg-visible one (0.02094, just OVER the+ threshold) now reaches the render as a slug and is no longer part of+ the gap between "declared duration" and "what plays". The remaining+ difference is exactly the two SUB-frame gaps healing already closes+ on read — `migrate_edit` erases the rest."""doc = self._doc(0.02094, 0.01584, 0.004)- rendered = sum(c["end"] - c["start"] for c in sedit.edit_to_cuts(doc))- self.assertAlmostEqual(sedit.edit_duration(doc) - rendered, 0.04078,+ cuts = sedit.edit_to_cuts(doc)+ rendered = sum(c["end"] - c["start"] for c in cuts)+ # The real gap is IN the cut list now, as a slug — not missing from it.+ self.assertEqual([c["kind"] for c in cuts if c.get("kind") == "slug"],+ ["slug"])+ self.assertAlmostEqual(sedit.edit_duration(doc) - rendered, 0.01984,places=5)healed = sedit.migrate_edit(doc)- self.assertAlmostEqual(sedit.edit_duration(healed), rendered, places=6)+ healed_rendered = sum(c["end"] - c["start"]+ for c in sedit.edit_to_cuts(healed))+ self.assertAlmostEqual(sedit.edit_duration(healed), healed_rendered,+ places=6)# =============================================================================@@ -4610,9 +4941,15 @@ class TheSameTakeTwiceIsOrdinaryEditing(unittest.TestCase):sedit.save_edit(bdir, dict(first))second = sedit.load_edit(bdir)self.assertEqual(json.dumps(second["clips"], sort_keys=True), clips_a)+ # FILM-51: `save_edit` now snaps every clip's length to the+ # frame grid (heal_subframe_lengths) — clip "five"'s 4.042s is+ # 97.008 frames, so it becomes 97 frames exactly (4.041667s),+ # and clip "six"'s unlinked strip carries the same tiny shift+ # its picture just took, keeping its drift (IN SYNC) unchanged.self.assertEqual(second["clips"][1]["audio"],- {"start": 0.0, "end": 4.042, "film_start": 30.35})- # ...and a third pass changes nothing either.+ {"start": 0.0, "end": 4.042, "film_start": 30.349667})+ # ...and a third pass changes nothing either — the document is+ # already frame-exact, so healing it again is a no-op.sedit.save_edit(bdir, dict(second))self.assertEqual(json.dumps(sedit.load_edit(bdir)["clips"],sort_keys=True), clips_a)@@ -4854,15 +5191,64 @@ class TheSaveModel(unittest.TestCase):self.assertTrue(first.is_file()) # the older one survivesself.assertEqual(sedit.pending_backup(bdir)["duration"], 2.0)- def test_the_lane_is_bounded(self):+ def test_the_lane_is_bounded_by_time_not_by_a_small_count(self):+ # FILM-57: a flat count of 20 read as "about 30 s of active editing"+ # once no-op re-backups stopped burning slots — the same cap that+ # protected against a runaway loop was, once that loop was fixed at+ # the source (sbeTick no longer re-arms once nothing has changed),+ # just a small window on real work. More than the OLD count-20 cap+ # of genuinely distinct, RECENT snapshots must all survive now.+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ self._save(bdir, self._doc())+ n = sedit.SNAPSHOT_KEEP + 6+ for i in range(n):+ sedit.write_backup(bdir, self._doc(end=4.0 - i * 0.01,+ film_end=4.0 - i * 0.01))+ self.assertEqual(len(sedit._snapshot_paths(bdir)), n)++ def test_snapshots_older_than_the_window_are_dropped(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ self._save(bdir, self._doc())+ sedit.write_backup(bdir, self._doc(end=3.0, film_end=3.0))+ old = sedit.latest_snapshot(bdir)[0]+ # Rename it back in time — same trick `_snapshot_stamp_ms` reads,+ # so this ages the file without touching the filesystem's mtime.+ aged = old.with_name(sedit._SNAP_PREFIX+ + f"{1:013d}-000.json") # 1970, unmissable+ old.replace(aged)+ gone = sedit.prune_snapshots(bdir, keep_hours=24, hard_cap=500)+ self.assertEqual(gone, 1)+ self.assertFalse(aged.exists())++ def test_a_name_the_pruner_cannot_parse_is_never_aged_out(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ self._save(bdir, self._doc())+ hist = sedit.history_dir(bdir, sedit.load_draft_index(bdir)["active"])+ hist.mkdir(parents=True, exist_ok=True)+ foreign = hist / (sedit._SNAP_PREFIX + "not-a-timestamp.json")+ foreign.write_text("{}")+ gone = sedit.prune_snapshots(bdir, keep_hours=0, hard_cap=500)+ self.assertEqual(gone, 0)+ self.assertTrue(foreign.exists())++ def test_the_hard_cap_still_bounds_a_pathological_burst(self):+ # Not the everyday rule — the backstop for a bug elsewhere hammering+ # the backup route. All of these are "now", so only the count-based+ # backstop can be why any of them go.with tempfile.TemporaryDirectory() as d:bdir = Path(d)self._save(bdir, self._doc())- for i in range(sedit.SNAPSHOT_KEEP + 6):+ n = 12+ for i in range(n):sedit.write_backup(bdir, self._doc(end=4.0 - i * 0.01,film_end=4.0 - i * 0.01))- self.assertLessEqual(len(sedit._snapshot_paths(bdir)),- sedit.SNAPSHOT_KEEP)+ self.assertEqual(len(sedit._snapshot_paths(bdir)), n)+ gone = sedit.prune_snapshots(bdir, keep_hours=24, hard_cap=5)+ self.assertEqual(gone, n - 5)+ self.assertEqual(len(sedit._snapshot_paths(bdir)), 5)def test_snapshots_are_listed_in_the_versions_browser_and_marked(self):# Rule 3: manual saves, named versions and snapshots together, and@@ -5005,9 +5391,12 @@ class MutingAClipsOwnSound(unittest.TestCase):w = sedit.clip_audio(c)self.assertTrue(w["split"]) # the strip stays putself.assertEqual(w["film_start"], 3.0)+ # film_start=4.0 leaves a head gap FILM-27 now fills with a black+ # slug at cuts[0] — find this clip's own entry by its path.cuts = sedit.edit_to_cuts(_edit([c]))- self.assertTrue(cuts[0]["mute"])- self.assertEqual(cuts[0]["audio"]["film_start"], 3.0)+ mine = next(cc for cc in cuts if cc.get("path"))+ self.assertTrue(mine["mute"])+ self.assertEqual(mine["audio"]["film_start"], 3.0)def test_the_cut_list_says_nothing_when_nothing_is_muted(self):self.assertNotIn("mute", sedit.edit_to_cuts(_edit([self._clip()]))[0])@@ -5148,7 +5537,10 @@ class SavingIsNeverBlockedByOverlappingSound(unittest.TestCase):sedit.save_edit(bdir, self._pair()) # must not raisegot = sedit.load_edit(bdir)self.assertEqual(got["revision"], 1)- self.assertEqual(got["clips"][1]["audio"]["film_start"], 3.104)+ # FILM-51: clip "a"'s 3.354s (80.496 frames) becomes 80 frames+ # exactly on save, shifting "b" and its strip by the same+ # amount — the quarter-second J-cut lead is unchanged.+ self.assertEqual(got["clips"][1]["audio"]["film_start"], 3.083333)sedit.write_backup(bdir, self._pair(lead=0.5)) # nor thisself.assertIsNotNone(sedit.pending_backup(bdir))@@ -5201,6 +5593,53 @@ class SavingIsNeverBlockedByOverlappingSound(unittest.TestCase):sedit.restore_edit(bdir, "save-r00009.json")+class SavingIsNeverBlockedByAMissingStill(unittest.TestCase):+ """FILM-31 — one trashed still image made the WHOLE FILM unsaveable and+ unbackupable: `still_missing` was blocking, and `write_backup`/`save_edit`+ both refuse on a blocking error. `still_missing` joins `WARNING_CODES` for+ the same reason `clips_audio_overlap` did — persisting the user's work+ always wins — now that it is also SAFE to: the assembler renders a+ missing still's slot as black at its own length instead of dropping it+ (FILM-15, `_sb_timeline_segments`), and the same file-exists check that+ flags the clip is what the Editor badges "offline" (`_sbe_payload`).+ """++ def _board(self, missing_path):+ return _edit([{"id": "s", "kind": "still", "path": str(missing_path),+ "proxy": None, "start": 0.0, "end": 3.0,+ "film_start": 0.0, "film_end": 3.0,+ "source": "human", "locked": False}])++ def test_a_missing_still_is_a_WARNING_not_an_error(self):+ errs = sedit.validate_edit(self._board(Path("/x/gone.png")))+ self.assertEqual([e["code"] for e in errs], ["still_missing"])+ self.assertEqual(errs[0].get("severity"), "warning")+ self.assertEqual(sedit.blocking_errors(errs), [])++ def test_a_real_defect_on_the_same_document_still_blocks(self):+ broken = self._board(Path("/x/gone.png"))+ broken["clips"][0]["film_end"] = broken["clips"][0]["film_start"]+ self.assertTrue(sedit.blocking_errors(sedit.validate_edit(broken)))++ def test_save_and_backup_both_write_it(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ edit = self._board(Path(d) / "gone.png")+ sedit.save_edit(bdir, edit) # must not raise+ got = sedit.load_edit(bdir)+ self.assertEqual(got["clips"][0]["kind"], "still")+ changed = json.loads(json.dumps(edit))+ changed["clips"][0]["film_end"] = 3.5 # a real, backup-worthy edit+ sedit.write_backup(bdir, changed) # must not raise+ self.assertIsNotNone(sedit.pending_backup(bdir))++ def test_the_still_that_DOES_exist_is_not_flagged(self):+ with tempfile.TemporaryDirectory() as d:+ img = Path(d) / "here.png"+ img.write_bytes(b"x")+ self.assertEqual(sedit.validate_edit(self._board(img)), [])++class TheDuplicatedStripArtifactIsRepairedOnLoad(unittest.TestCase):"""A board split before the J-cut fix carries two strips claiming the sameseconds of the same take. It was legal when it was written and becamediff --git a/test_storyboard_editor_ui.py b/test_storyboard_editor_ui.pyindex 7dee8d5..1739daf 100644--- a/test_storyboard_editor_ui.py+++ b/test_storyboard_editor_ui.py@@ -173,6 +173,8 @@ FUNCTIONS = ("sbeGroupLimits", "sbeMoveGroup",# The save that cannot be dropped, and the failure that cannot be missed."sbeSaveInner", "sbeSaveAlarm", "sbeSaveAlarmClear", "sbeQueueSave",+ # EDITOR-11: a save adopts the healed timings the server wrote.+ "sbeAdoptSavedTimings",# The crash lane itself, so save → backup → recovery can be DRIVEN rather# than grepped for the presence of its guards."sbeBackup", "sbeDraftOp", "sbeNameMode",@@ -184,6 +186,22 @@ FUNCTIONS = (# these, so every harness that extracts those needs them too."sbeSoundLane", "sbeLaneName", "sbeSetSoundLane", "sbeAlternateLanes","sbeLaneAfter", "sbeLaneFit",+ # FILM package (2026-09-29 mega review) — slip and roll edits, the+ # frame timecode, and the take/replace maths. Pure by the same rule as+ # everything above: arithmetic nobody should have to check by dragging.+ "sbeFmtTC", "sbeSlip", "sbeRollEdit", "sbeReplaceClip",+ # FILM-04 — the song as the film's master clock in Replace mode.+ "sbeMusicAt", "sbeMusicMaster", "sbeSongPlayhead",+ # FILM-05 — the per-clip song-sync readout and Snap to song.+ "sbeShotForClip", "sbeSongSyncOffset", "sbeSnapToSong",+ # FILM-05 item 4 — auto-lock a2v clips against moves that break sync.+ "sbeSongLocked",+ # FILM-14 — the 5-slider grade.+ "sbeGrade", "sbeGradeIsNeutral", "sbeSetGrade", "sbeCopyGrade", "sbeGradeCss",+ # FILM-58 — markers, copy/paste, sequence aspect.+ "sbeMarkerAdd", "sbeMarkerRemove", "sbeMarkerSetLabel", "sbeMarkerSetKind",+ "sbeClipboardCopy", "sbeClipboardPasteAttrs", "sbeClipboardPasteClips",+ "sbeSeqAspect", "sbeSetSeqAspect",)SHIM = r"""@@ -222,6 +240,21 @@ const SBE_SNAP_PX = 9;const SBE_GUESS_CONFIDENCE = 0.4;const SBE_BRIGHT_MAX = 0.5;const SBE_STILL_SECONDS = 3.0;+// FILM-14. Keep equal to the panel's — test_editor_film_grade reads both.+const SBE_GRADE_EXPOSURE_MAX = 0.5;+const SBE_GRADE_CONTRAST_MIN = 0.5, SBE_GRADE_CONTRAST_MAX = 1.8;+const SBE_GRADE_SATURATION_MIN = 0.0, SBE_GRADE_SATURATION_MAX = 2.5;+const SBE_GRADE_TEMP_TINT_MAX = 1.0;+// FILM-58.+const SBE_SEQ_ASPECTS = { '16:9': 16 / 9, '9:16': 9 / 16, '1:1': 1 };+const SBE_PASTE_ATTR_FIELDS = ['adjust', 'frame', 'fx', 'speed'];+const SBE_GRADE_FIELDS = {+ exposure: [-SBE_GRADE_EXPOSURE_MAX, SBE_GRADE_EXPOSURE_MAX, 0],+ contrast: [SBE_GRADE_CONTRAST_MIN, SBE_GRADE_CONTRAST_MAX, 1],+ saturation: [SBE_GRADE_SATURATION_MIN, SBE_GRADE_SATURATION_MAX, 1],+ temp: [-SBE_GRADE_TEMP_TINT_MAX, SBE_GRADE_TEMP_TINT_MAX, 0],+ tint: [-SBE_GRADE_TEMP_TINT_MAX, SBE_GRADE_TEMP_TINT_MAX, 0],+};// Editor v2. Keep equal to the panel's — test_editor_v2 reads both.const SBE_SPEED_MIN = 0.25;const SBE_SPEED_MAX = 4.0;@@ -1042,6 +1075,15 @@ out.backupLivesAfterASave = [!!(await sbeBackup(true)), FETCHES.length,out.backupNamesItsDraft = JSON.parse(FETCHES[0].body || '{}').draft;// A backup that does not land is the safety net gone, and only the alarm says so.SBE.dirty = true;+// FILM-57: sbeBackup now skips the network call for CONTENT it already+// backed up successfully — the watchdog's own re-arm-every-tick loop used to+// re-POST the same unchanged document every 1.4s forever. This scenario is a+// genuinely new attempt (whatever failed here is not what the previous line+// already has safely on the server), so it clears the memory that dedup+// reads rather than changing the content — the alarm this asserts is about+// a NEW write failing, not about the dedup skip, which is covered on its+// own in test_editor_save_integrity.TheWatchdogStopsCallingWhenNothingChanged.+SBE.lastBackupSig = '';NEXT = { status: 500, body: { ok: false, error: 'disk is full' } };out.backupFailureIsLoud = [await sbeBackup(true), !!SBE.saveFailed];SBE.saveFailed = ''; els.sbeAlarm.hidden = true;@@ -1321,14 +1363,23 @@ out.holeCounterOnHisFilm = (() => {// ---- THE NET'S OWN STATE ------------------------------------------------out.protectedChip = (() => {const read = () => ({ text: sbeEl('sbeProtected').textContent,+ hidden: !!sbeEl('sbeProtected').hidden,+ tooltip: sbeEl('sbeState').title,cold: sbeEl('sbeProtected').classList.contains('is-cold') });const was = { open: SBE.open, id: SBE.id, dirty: SBE.dirty,dirtyAt: SBE.dirtyAt, backedUpAt: SBE.backedUpAt };SBE.open = true; SBE.id = 'sb_t'; SBE.otherEditor = '';+ // FILM-38: cold is stated in the WATCHDOG's own terms now — the oldest+ // unwritten change (dirtyAt) is older than the grace AND no backup has+ // landed since it. Ageing only `backedUpAt` while `dirtyAt` stayed fresh+ // used to read as cold anyway (the bug this fixture now exercises the fix+ // for) — a brand new edit with no backup yet is "backing up…", not alarmed.SBE.dirty = true; SBE.dirtyAt = Date.now();SBE.backedUpAt = Date.now() - 3000; sbePaintProtected(); const fresh = read();- SBE.backedUpAt = Date.now() - 40000; sbePaintProtected(); const cold = read();- SBE.backedUpAt = 0; sbePaintProtected(); const never = read();+ SBE.dirtyAt = Date.now() - 40000; SBE.backedUpAt = 0;+ sbePaintProtected(); const cold = read();+ SBE.dirtyAt = Date.now(); SBE.backedUpAt = 0;+ sbePaintProtected(); const never = read();Object.assign(SBE, was);return [fresh, cold, never];})();@@ -1958,7 +2009,13 @@ out.musicDragNowhereChangesNothing = (() => {out.draftSwitchRefusesWhenTheBackupCannotWrite = await (async () => {// A REAL write failure, not an unanswered offer: the snapshot POST fails,// so the work on screen has nowhere to go and the switch must not proceed.- SBE.backup = null;+ // FILM-06 made the FIRST edit off a clean timeline fire its own+ // fire-and-forget sbeBackup() (previously that write waited out a 1.4s+ // debounce that never elapsed inside this script, so nothing upstream+ // could still be "in flight" here) — an earlier scenario's own first edit+ // may still be an unsettled promise holding SBE.backingUp, which this+ // scenario does not own and must not inherit.+ SBE.backup = null; SBE.backingUp = false;SBE.dirty = true; SBE.conflict = 0;FETCHES = [];NEXT = { status: 500, body: { ok: false, error: 'disk is full' } };@@ -4251,24 +4308,84 @@ class TheNetSaysWhenItLastCaughtYou(unittest.TestCase):def test_fresh_reads_as_protected_and_stale_reads_as_NOT(self):fresh, cold, never = self.r["protectedChip"]- self.assertIn("protected", fresh["text"])+ # FILM-37: the routine case used to sit in the header as its own+ # always-visible text, permanently spending width the title/state/+ # draft-chip needed — at 1366-1440px that was what truncated+ # "saved · rev7" down to "saved · r", well above the breakpoint that+ # was supposed to fold the state text first. It still says the same+ # thing, just in the status pill's tooltip rather than on screen.+ self.assertTrue(fresh["hidden"])+ self.assertEqual(fresh["text"], "")+ self.assertIn("protected", fresh["tooltip"])self.assertFalse(fresh["cold"])# Past the watchdog's own grace, the chip goes cold on the SAME# threshold the banner alarms on — two indicators that can disagree- # are one indicator and one bug.+ # are one indicator and one bug. An ALARM earns the width back: it+ # is the one case in this chip that is actionable.+ self.assertFalse(cold["hidden"])self.assertIn("NOT PROTECTED", cold["text"])+ self.assertEqual(cold["tooltip"], cold["text"])self.assertTrue(cold["cold"])- self.assertIn("not backed up yet", never["text"])-- def test_cold_is_stated_against_the_last_SUCCESSFUL_write(self):- # Not against `dirtyAt`: the outage froze that pair in a way that read- # "protected" for seven hours. How long ago the net actually caught- # this tab cannot be faked by a stuck flag.+ # FILM-38: a BRAND NEW edit, no backup landed yet, is not alarming —+ # it is the normal half-second between an edit and the (now+ # near-immediate, FILM-06) snapshot reaching the server. Red is+ # reserved for a write that is actually late, so this one is quiet+ # on screen too — "backing up…" lives in the tooltip.+ self.assertTrue(never["hidden"])+ self.assertIn("backing up", never["tooltip"])+ self.assertFalse(never["cold"])++ def test_cold_now_AGREES_with_the_watchdog_instead_of_only_claiming_to(self):+ # FILM-38: the comment used to say "the SAME threshold the watchdog+ # alarms on" while comparing only against `backedUpAt` — which is+ # cold the instant `dirty` becomes true, before the snapshot has had+ # one network round trip. `dirtyAt` was avoided because the old+ # stale-session outage froze it in a way that read "protected" for+ # seven hours — that outage is closed (docs/EDITOR_SAVE_MODEL.md §5),+ # and the watchdog (sbeTick) has safely compared `dirtyAt` this whole+ # time. The chip now uses the identical expression.fn = extract_function("sbePaintProtected", self.src)- self.assertIn("SBE.backedUpAt", fn)cold = fn[fn.index("const cold"):]- cold = cold[:cold.index(";")]- self.assertNotIn("dirtyAt", cold)+ cold = cold[:cold.index(";", cold.index("SBE.dirtyAt"))]+ self.assertIn("SBE.dirtyAt", cold)+ self.assertIn("SBE_SAVE_GRACE_MS", cold)+ self.assertIn("SBE.backedUpAt", cold)+ tick = extract_function("sbeTick", self.src)+ self.assertIn("SBE.backedUpAt < SBE.dirtyAt", tick)+++class ThePoolFiltersAreOneRow(unittest.TestCase):+ """FILM-37: five sources (This __SEQCAP__ / Other __SEQS__ / Generations /+ Images / Sound) at a 40% flex-basis wrapped into up to three rows —+ measured 1.5 rows at 1366x768 — eating vertical space the pool's own+ list needed. They are a single non-wrapping row now."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()++ def test_the_row_does_not_wrap(self):+ css = self.src[self.src.index(".ed-pool-tabs {"):]+ rule = css[:css.index("}") + 1]+ self.assertIn("flex-wrap: nowrap", rule)++ def test_the_five_sources_are_one_select_that_fits_the_pool(self):+ # 4.17: five pills in one row clipped into each other in the ~260 px+ # pool at 1280-1440 px; a labelled select names every source in full.+ tabs = self.src[self.src.index('id="edPoolTabs"'):]+ tabs = tabs[:tabs.index("</select>")]+ self.assertIn('<select id="edPoolSrcSelect"', tabs)+ self.assertIn('onchange="edPoolSrc(this.value)"', tabs)+ self.assertEqual(tabs.count("<option "), 5)+ css = self.src[self.src.index(".ed-pool-tabs .ed-pool-src {"):]+ rule = css[:css.index("}") + 1]+ self.assertIn("min-width: 0", rule)++ def test_all_five_tabs_are_still_there(self):+ tabs = self.src[self.src.index('id="edPoolTabs"'):]+ tabs = tabs[:tabs.index("</div>")]+ for src in ("film", "other", "gallery", "images", "sound"):+ self.assertIn('data-src="%s"' % src, tabs)class OneNoticeSurface(unittest.TestCase):@@ -4998,9 +5115,12 @@ class TimelineVersions(unittest.TestCase):# sbeAdopt sets the mode dropdown to agree with the document on every# load, and that call was marking the document dirty and queueing a# write — so every OPEN of every film produced a save nobody made.+ # FILM-33 moved the actual dirtying into sbeMusicCommit (the shared+ # writer every soundtrack gesture now goes through), so the guard's+ # job is to return before THAT is ever reached.fn = extract_function("sbeSetMusicMode", self.src)self.assertIn("if (String(SBE.audio.mode || 'under') === mode) return;", fn)- self.assertLess(fn.index("=== mode) return"), fn.index("SBE.dirty = true"))+ self.assertLess(fn.index("=== mode) return"), fn.index("sbeMusicCommit("))def test_the_lane_has_nothing_left_to_guard(self):# The guard is gone because the thing it guarded is gone: snapshots@@ -5066,6 +5186,14 @@ class TimelineVersions(unittest.TestCase):# name. See docs/EDITOR_SAVE_MODEL.md §4.self.assertIn("your saved draft is untouched", paint)self.assertNotIn("Nothing has been changed", paint)++ def test_the_bar_says_WHAT_changed_when_the_server_names_it(self):+ # FILM-54: `b.diff` is `edit_diff_summary`'s answer, server-side —+ # "1 clip changed: 02 brightness +0.30" instead of the two counts+ # matching being the only thing on screen.+ paint = extract_function("sbePaintRecovery", self.src)+ self.assertIn("b.diff", paint)+ self.assertLess(paint.index("b.diff"), paint.index("your saved draft"))# The offer is painted on adopt; nothing calls sbeRecover for you.adopt = extract_function("sbeAdopt", self.src)self.assertIn("sbePaintRecovery()", adopt)@@ -6252,6 +6380,31 @@ class TheEverydayGesturesThatWereMissing(unittest.TestCase):# dirty, push an undo step that undoes nothing and queue a save.self.assertIn("nothing to give", fn)+ def test_a_chord_is_let_through_a_field_because_it_cannot_be_a_character(self):+ # FILM-36: dragging the Brightness or Zoom slider leaves focus on a+ # range input, and the field guard used to hide ⌘S/⌘Z/⌘⇧Z/⌘E behind+ # it entirely — the browser's own "Save Page As" fired instead, or+ # nothing did. These four chords are let through BEFORE the field+ # guard because a modifier held is never someone typing a character.+ before_guard = self.keys[:self.keys.index("if (inField) return;")]+ self.assertIn("sbeSaveNow()", before_guard)+ self.assertIn("sbeUndo()", before_guard)+ self.assertIn("sbeRedo()", before_guard)+ self.assertIn("sbeRenderFilm()", before_guard)+ # ...and it is scoped to those four, not every modifier chord — a+ # text field's own ⌘A (select its text) or ⌘Z (undo typing) must+ # keep working, which a blanket "any modifier" exemption would break.+ self.assertNotIn("sbeSelectAll()", before_guard)+ self.assertNotIn("sbeInspectToggle()", before_guard)++ def test_space_plays_from_a_range_or_checkbox_but_not_a_text_field(self):+ # A range or checkbox never uses Space to enter TEXT, so play/pause+ # is not competing with anything the field would otherwise do with+ # it — unlike a text input, where Space has to keep typing a space.+ before_guard = self.keys[:self.keys.index("if (inField) return;")]+ self.assertIn("t.type === 'range' || t.type === 'checkbox'", before_guard)+ self.assertIn("sbeTogglePlay()", before_guard)+def test_home_end_and_the_zoom_keys_exist(self):for bit in ("ev.key === 'Home'", "ev.key === 'End'", "sbeZoom("):self.assertIn(bit, self.keys, bit)@@ -6334,10 +6487,26 @@ class TimelineMarkup(unittest.TestCase):fn = extract_function("sbeAuto", self.src)self.assertIn("THROWS AWAY", fn)- def test_the_render_discloses_that_the_concat_closes_gaps(self):+ def test_the_render_warns_about_holes_without_blocking_it(self):+ # FILM-27: the assembler now pads a hole with black at its exact+ # length instead of closing it, so a native confirm() gating the+ # render on "are you sure" was the wrong weight — and the wrong+ # surface — for "this will show some black". The warning is in-app+ # and does not stop the render.+ # FILM-28: gaps_note is read once the JOB finishes (sbeRenderFinish),+ # not in sbeRenderFilm itself, which now only starts it — the+ # disclosure has to hold across the whole chain, same as the+ # "never navigates" claim above.fn = extract_function("sbeRenderFilm", self.src)- self.assertIn("gaps_note", fn)- self.assertIn("CONCATENATES", fn)+ self.assertIn("sbeNoticeHoles", fn)+ self.assertNotIn("confirm(", fn)+ chain = fn + extract_function("sbeRenderPoll", self.src) \+ + extract_function("sbeRenderFinish", self.src)+ self.assertIn("gaps_note", chain)+ self.assertNotIn("confirm(", chain)+ notice = extract_function("sbeNoticeHoles", self.src)+ self.assertIn("play as black", notice)+ self.assertIn("phos-toast-action", notice)def test_generate_shows_the_params_that_will_ACTUALLY_render(self):# make_job silently drops any form field it does not name, so the@@ -6347,6 +6516,28 @@ class TimelineMarkup(unittest.TestCase):self.assertIn("r.params", fn)self.assertIn("sbeGenParams", fn)+ def test_a_retake_sends_its_own_path_not_just_its_id(self):+ # FILM-35: the server used to resolve retake_of by loading the SAVED+ # edit.json and looking the clip id up in it — a clip split,+ # duplicated or added since the last manual Save was not in that+ # file yet, and the retake refused for a clip plainly on screen. The+ # client already has the path; sending it is what lets the server+ # skip the stale file entirely.+ self.assertIn("retakePath: c.path", extract_function("sbeRetakeSel", self.src))+ open_fn = extract_function("sbeGenOpen", self.src)+ self.assertIn("_sbeRetakePath = (opts && opts.retakePath) || ''", open_fn)+ submit = extract_function("sbeGenSubmit", self.src)+ self.assertIn("fd.set('retake_path', _sbeRetakePath)", submit)++ def test_the_landed_take_poll_no_longer_waits_for_a_clean_timeline(self):+ # FILM-35: unsaved is the NORMAL state of a timeline someone is+ # cutting — gating this on `!SBE.dirty` meant the notice almost+ # never fired. sbeLoad(true) is already safe while dirty (it never+ # adopts the arrangement, only refreshes facts around it).+ tick = extract_function("sbeTick", self.src)+ self.assertIn("if (SBE.awaitingClip && !SBE.drag && !SBE.saving) {", tick)+ self.assertNotIn("SBE.awaitingClip && !SBE.dirty", tick)+def test_the_preview_prefers_the_proxy_and_labels_the_fallback(self):fn = extract_function("sbeClipUrl", self.src)self.assertIn("c.proxy", fn)@@ -6409,6 +6600,37 @@ class TimelineMarkup(unittest.TestCase):# The source is a player, not a second editor: no track, no trim.self.assertNotIn("sbe-track", row)+ def test_the_source_monitor_collapses_while_nothing_is_loaded(self):+ # FILM-37: "Nothing loaded" used to sit in the full 16:9 box+ # regardless — about a third of the row, permanently. Collapsed to a+ # 64px rail while empty, and it can never disagree with the bar's+ # own "Nothing loaded" text: both read the exact same `!row`.+ css = self.src[self.src.index(".sbe-monitors > .sbe-mon-src {"):]+ css = css[:css.index(".sbe-monitors > .sbe-mon-prog")]+ self.assertIn(".sbe-mon-src.is-empty { width: 64px; }", css)+ fn = extract_function("sbePaintSource", self.src)+ self.assertIn("mon.classList.toggle('is-empty', !row)", fn)+ # The toggle happens before the SAME `if (!row)` branch that writes+ # "Nothing loaded" — one test of the state, not two that could drift.+ self.assertLess(fn.index("classList.toggle('is-empty'"),+ fn.index("'Nothing loaded'"))++ def test_the_inspector_is_a_drawer_below_1600px(self):+ # FILM-37: at 1366-1440px the rail shared width with the monitors+ # through a JS-computed --sbe-rail-w that measured about 210px there+ # — the "2x" speed control clipped inside it. Below 1600px it comes+ # out of that row's width budget entirely (position: fixed) at a+ # width wide enough to read every control: 320px.+ css = self.src[self.src.index("@media (max-width: 1599px) {\n .sbe-rail {"):]+ css = css[:css.index("/* ---- the stage:")]+ self.assertIn("position: fixed", css)+ self.assertIn("width: 320px", css)+ # It still toggles on the exact mechanism sbeInspectSet already+ # flips — nothing about opening/closing it changed, only where an+ # open one sits.+ fn = extract_function("sbeInspectSet", self.src)+ self.assertIn("rail.hidden = !SBE.inspect", fn)+def test_only_one_monitor_ever_plays(self):# Two elements is two decoders only if both decode. sbePlay stops the# source and sbeSrcPlay stops the program, so it is one at a time —@@ -6669,7 +6891,12 @@ class TimelineMarkup(unittest.TestCase):self.assertNotIn("sbeTeardown()", wf)susp = extract_function("sbeSuspend", self.src)self.assertIn("sbeStop()", susp) # the picture stops- self.assertIn("sbeSave(true)", susp) # the work is kept+ # FILM-29: a tab switch is not the user pressing Save — it is the+ # backup lane's job, same as sbeCloseDoc next to it. `sbeSave(true)`+ # here would be a silent write to edit.json the owner explicitly+ # refused ("autosave to edit.json" — docs/EDITOR_SAVE_MODEL.md §"Deliberately not built").+ self.assertIn("sbeBackup(true)", susp) # the work is kept…+ self.assertNotIn("sbeSave(true)", susp) # …without a silent manual saveself.assertNotIn("SBE.open = false", susp) # the document is notdef test_the_document_only_closes_when_the_document_is_closed(self):@@ -6691,7 +6918,7 @@ class TimelineMarkup(unittest.TestCase):def test_the_editor_tab_exists_and_is_always_reachable(self):# A tab with no board open is the whole point: "an editor that only# exists inside a storyboard is an editor most clips can never reach".- self.assertIn('<button data-workflow="editor">', self.src)+ self.assertIn('<button data-workflow="editor"', self.src)self.assertIn(">Editor<", self.src)# It MUST be in the localStorage restore list or the tab never comes# back across a reload — the trap the comment beside it documents.@@ -6718,6 +6945,22 @@ class TimelineMarkup(unittest.TestCase):self.assertIn("edDoc()", fn) # last document, rememberedself.assertIn("edRemember(want)", fn)+ def test_opening_the_already_open_film_resumes_it_rather_than_reloading(self):+ # FILM-16: falling through to `sbeLoad()` below is a NON-QUIET load,+ # which always adopts the server's last SAVED document — so "Open in+ # Editor" on the film already open (the rail's step 3, or coming back+ # from Storyboard to check a prompt) silently threw away every edit+ # since the last Save. sbeResume() re-reads QUIETLY, which protects+ # unsaved work; this must be checked and returned from BEFORE the+ # unconditional `sbeLoad()` a few lines down.+ fn = extract_function("sbeOpen", self.src)+ self.assertIn("if (SBE.open && SBE.id === want) { sbeResume(); return; }", fn)+ self.assertLess(fn.index("SBE.id === want) { sbeResume(); return; }"),+ fn.index("sbeLoad();"))+ # sbeResume, in turn, re-reads quiet — never the adopting load.+ resume = extract_function("sbeResume", self.src)+ self.assertIn("sbeLoad(true)", resume)+def test_the_narrow_layout_stops_stretching_so_the_page_can_scroll(self):# .layout is `flex: 1 1 auto` in a flex body, so the breakpoint's# `height: auto` never did anything: the grid kept the full viewport@@ -6752,7 +6995,7 @@ class TimelineMarkup(unittest.TestCase):shots = extract_function("edPoolLoadFilmShots", self.src)self.assertIn("'/storyboard/get?id='", shots)- def test_adding_a_clip_lands_it_on_the_TRACK_and_saves(self):+ def test_adding_a_clip_lands_it_on_the_TRACK_and_backs_up(self):# Not on the board, and not in a chip row waiting to be placed: the# click said "put this in my film", so it goes on the timeline.fn = extract_function("edPoolAdd", self.src)@@ -6760,7 +7003,11 @@ class TimelineMarkup(unittest.TestCase):self.assertIn("sbePlaceUnplaced", fn)self.assertIn("sbeFilmDuration(cs)", fn) # a CLICK: at the ENDself.assertIn("sbeInsertAt(cs, item, at)", fn) # a DROP: where it fell- self.assertIn("sbeSave(true)", fn)+ # FILM-29: `sbeMutate` above already marked this dirty and queued the+ # crash backup. A follow-up `sbeSave(true)` here was a second, silent+ # write to edit.json the user never pressed Save for.+ self.assertNotIn("sbeSave(true)", fn)+ self.assertIn("sbeMutate(cs =>", fn)def test_adding_a_clip_from_another_film_uses_the_import_subset_param(self):# `only=` has been on the server since the import shipped and no@@ -6790,6 +7037,32 @@ class TimelineMarkup(unittest.TestCase):# intersection callbacks do not run in an occluded tab.self.assertIn(".slice(0, 12)", obs)+ def test_the_pool_plus_lands_at_the_playhead_not_always_the_end(self):+ # FILM-40: "+" always meant "put this at the end" — a clip swapped+ # in mid-cut meant a click here and then a drag all the way back to+ # where you actually were. ⌥+click keeps the old behaviour for the+ # one time "the end" is actually wanted.+ fn = extract_function("edPoolPaint", self.src)+ self.assertIn("edPoolAdd(' + i +\n ', event.altKey ? undefined : SBE.playhead)", fn)++ def test_the_empty_pool_does_not_contradict_a_timeline_that_has_clips(self):+ # FILM-40: "This __SEQ__ has no rendered clips yet" while 9 clips+ # sat on the timeline — a film cut from imported or Video-tab clips+ # has nothing of its OWN in this pool source, which is a different,+ # true sentence.+ fn = extract_function("edPoolPaint", self.src)+ self.assertIn("(SBE.clips || []).length", fn)+ self.assertIn("Nothing left to add from this __SEQ__", fn)++ def test_the_60_row_cap_has_a_way_past_it(self):+ # FILM-40: "60 of 75 shown." with no way to see the rest.+ fn = extract_function("edPoolPaint", self.src)+ self.assertIn("edPoolShowAll()", fn)+ self.assertIn("Show all ", fn)+ show_all = extract_function("edPoolShowAll", self.src)+ self.assertIn("ED.limit = Infinity", show_all)+ self.assertIn("edPoolPaint()", show_all)+# ---- relink ---------------------------------------------------------def test_the_relink_banner_says_how_many_and_offers_one_button(self):fn = extract_function("sbePaintRelink", self.src)@@ -6880,6 +7153,60 @@ class TimelineMarkup(unittest.TestCase):self.assertIn(".sbe-clip.is-slug", css)self.assertIn(".sbe-clip.is-still", css)+ def test_a_video_clip_shows_a_poster_from_its_proxy_only(self):+ # FILM-39: video clips had no filmstrip at all — one first-frame+ # poster now, taken from the PROXY (never the original: a clip with+ # no proxy is exactly the one flagged SLOW for the same reason, no+ # fast seek), and never requested for offline media (that file is+ # already known not to answer).+ fn = extract_function("sbePaintTrack", self.src)+ self.assertIn("kind === 'video' && c.proxy && !offline", fn)+ self.assertIn("/storyboard/edit/poster?id=", fn)+ self.assertIn("String(c.proxy).split('/').pop()", fn)+ # The route is board-scoped like the proxy video route it mirrors —+ # `id=` before `name=`, not a bare clip path.+ route = fn[fn.index("/storyboard/edit/poster?id="):]+ self.assertLess(route.index("&name="), route.index("&w="))++ def test_the_two_clip_sound_lanes_are_not_both_called_A1(self):+ # FILM-39: "Clip sound A" and "Clip sound B" were both labelled+ # <i>A1</i> in the gutter — the one place a glance is supposed to+ # tell the two lanes apart.+ gutter = self.src[self.src.index('id="sbeGutter"'):]+ gutter = gutter[:gutter.index('sbe-mix-row')]+ self.assertIn("<i>A1a</i>", gutter)+ self.assertIn("<i>A1b</i>", gutter)+ self.assertNotIn("<i>A1</i>", gutter)++ def test_the_slow_flag_explains_itself_instead_of_saying_SLOW(self):+ # FILM-39: "SLOW" was jargon with no tooltip and no action. It means+ # no proxy yet — scrubbing decodes from the source GOP — which is+ # exactly what Prepare fixes.+ fn = extract_function("sbePaintTrack", self.src)+ self.assertNotIn("'SLOW'", fn)+ # 4.17: the flag is also the fix — its title says a click runs it.+ self.assertIn("click to run Prepare", fn)++ def test_a_genuine_open_lands_at_the_top_and_fits_a_long_film(self):+ # FILM-57/39: the playhead used to survive a switch to a different+ # film (a short film opened after a long one could land PAST ITS+ # OWN END, on black) and the zoom stayed at the default regardless+ # of length (a 2:52 film opened showing about 10s of it). Neither+ # may fire on a quiet re-read, which must not move anything the+ # user is already looking at.+ fn = extract_function("sbeAdopt", self.src)+ self.assertIn("if (!quiet) SBE.playhead = 0;", fn)+ self.assertIn("if (!quiet) {\n const fit = sbeZoomMin();", fn)+ # The switch branch of sbeOpen (a DIFFERENT film already open) falls+ # through to a bare `sbeLoad()` — no `quiet` argument, so it lands on+ # sbeLoad's non-quiet default and reaches this same `!quiet` branch.+ # A switch between two open films is not a special case; it is one+ # more genuine open.+ op = extract_function("sbeOpen", self.src)+ self.assertIn("if (SBE.open && SBE.id && SBE.id !== want) sbeCloseDoc({ quiet: true });", op)+ self.assertIn("sbeLoad();", op)+ self.assertNotIn("sbeLoad(true)", op)+def test_the_brightness_slider_previews_live_and_commits_once(self):# oninput at pointer speed would push eighty undo steps and eighty# saves for one gesture; onchange fires once, when the drag ends.@@ -6929,11 +7256,12 @@ class TimelineMarkup(unittest.TestCase):self.assertIn("ev.preventDefault()", start)add = extract_function("edPoolAdd", self.src)self.assertIn("if (ED.suppressClick && dropAt === undefined)", add)- # Add-at-the-end still works and still lands at the end — it is the +- # on the row now rather than the whole row, because clicking the row- # previews. `stopPropagation` is what keeps one press from doing both.+ # The + is on the row now rather than the whole row, because+ # clicking the row previews. `stopPropagation` is what keeps one+ # press from doing both. FILM-40: it lands at the playhead now, not+ # always the end — ⌥+click is the escape hatch back to "the end".pool = extract_function("edPoolPaint", self.src)- self.assertIn("edPoolAdd(' + i + ')", pool)+ self.assertIn("edPoolAdd(' + i +\n ', event.altKey ? undefined : SBE.playhead)", pool)self.assertIn("event.stopPropagation()", pool)self.assertIn('onpointerdown="edPoolDragStart(event,', pool)@@ -7072,6 +7400,7 @@ ONESHOT_FUNCTIONS = ("osPartsText", "osPartsShort","osRenderSummary", "osRenderAll", "osSetEngine", "osSetSeconds", "osSetQuality", "osSetCharacter","osToggle", "osSplitPrompt", "osVerdict", "osPaintStatus", "oneshotOpenFromParams", "osWire",+ "_osStoredSeconds", "_osApplyStoredPrefs",# the async ones osWire binds; the shim's fetch answers {ok:false}, so they are inert here"osPlanBeats", "osGenerate", "osUpload", "osClearAnchor", "osEstimate", "osStatusTick","osStartStatus", "osStopStatus", "osLoadOptions", "oneshotTabEnter", "oneshotTabLeave",@@ -7492,19 +7821,22 @@ class OneShotIsATab(unittest.TestCase):self.assertNotRegex(text, r"\btake\b", "the user reads 'one shot', never 'take'")# ---- the module, run ------------------------------------------------------ def test_entering_the_tab_is_one_minute_on_ltx_with_nothing_written(self):+ def test_entering_the_tab_defaults_to_thirty_seconds_on_ltx_with_nothing_written(self):+ # VA-15: the default was 60 s (6 parts, ~28 min committed before any+ # price showed near Generate). Now 30 s (3 parts, ~15 min — the+ # owner's own sample length).e = self.r["enter"]- self.assertEqual((e["engine"], e["seconds"], e["quality"]), ("ltx", 60, "balanced"))+ self.assertEqual((e["engine"], e["seconds"], e["quality"]), ("ltx", 30, "balanced"))self.assertEqual(e["lengths"], ["30", "45", "60", "90", "120"])- self.assertEqual(e["activeLength"], ["60"])+ self.assertEqual(e["activeLength"], ["30"])self.assertEqual(e["parts"], ["3 × 10 s", "4 × 10 s + 5 s", "6 × 10 s", "9 × 10 s", "12 × 10 s"])self.assertEqual(e["qualities"], ["quick", "balanced", "standard", "high"])self.assertEqual(e["characters"], ["", "bizarrotrn"])self.assertEqual(e["beats"], [])self.assertIn("the prompt carries the whole shot", e["beatsHint"])- self.assertEqual((e["rows"], e["first"]), (12, "0:00"))+ self.assertEqual((e["rows"], e["first"]), (6, "0:00"))self.assertEqual((e["handoff"], e["handoffChips"]), ("last", ["last"]))- self.assertIn("1 min", e["summary"]); self.assertIn("6 parts of 10 s", e["summary"])+ self.assertIn("30 s", e["summary"]); self.assertIn("3 parts of 10 s", e["summary"])self.assertEqual(self.r["len45"]["chip"], "4 × 10 s + 5 s")self.assertIn("4 × 10 s + 5 s", self.r["len45"]["summary"])self.assertFalse(e["characterBlockHidden"])@@ -7512,7 +7844,7 @@ class OneShotIsATab(unittest.TestCase):def test_one_paragraph_is_a_complete_document(self):d = self.r["docPromptOnly"]self.assertEqual(d["prompt"], "A hen skates down Broadway at night.")- self.assertEqual((d["seconds"], d["engine"], d["quality"]), (60, "ltx", "balanced"))+ self.assertEqual((d["seconds"], d["engine"], d["quality"]), (30, "ltx", "balanced"))self.assertNotIn("beats", d); self.assertNotIn("character_id", d); self.assertNotIn("image", d)self.assertEqual((d["light_lock"], d["retake"], d["handoff"]), ("on", "on", "last"))diff --git a/test_storyboard_film.py b/test_storyboard_film.pyindex e939729..220fd35 100644--- a/test_storyboard_film.py+++ b/test_storyboard_film.py@@ -526,17 +526,187 @@ class FilmMarkup(unittest.TestCase):# soundtrack nobody can see.self.assertIn("v.pause()", extract_function("sbShow"))- def test_both_assemblies_end_on_the_film(self):- # A toast that fades is what made the finished film invisible.- self.assertIn("sbFilmOpen", extract_function("sbeRenderFilm"))+ def test_the_boards_own_export_still_ends_on_the_film(self):+ # sbExport is the Storyboard tab's one-button export — there is no+ # timeline open to stay on, so landing on the Film screen is still+ # the right destination for it.self.assertIn("sbFilmOpen", extract_function("sbExport"))- def test_the_render_still_discloses_that_the_concat_closes_gaps(self):- # The disclosure the editor gate already locks — proving the landing- # was added to it, not swapped for it.- fn = extract_function("sbeRenderFilm")- self.assertIn("gaps_note", fn)- self.assertIn("CONCATENATES", fn)+ def test_the_editors_render_stays_on_the_timeline_now(self):+ # FILM-24: this used to end by switching to Storyboard and opening+ # the Film screen unconditionally — which, combined with the+ # tab-entry race (FILM-02), sometimes landed on a DIFFERENT film's+ # Film screen behind a "Rendered N clips" toast. Rendering to check+ # a cut is the normal loop, not a reason to leave it: the render now+ # stays on the timeline and offers "Open"/"Show in Finder" instead+ # of forcing the trip.+ # FILM-28: the render is a JOB now — sbeRenderFilm only starts it;+ # sbeRenderPoll watches it and sbeRenderFinish is where a finished+ # film actually lands. The "never navigates" claim has to hold for+ # the whole chain, not just the function that kicks it off.+ chain = "".join(extract_function(n) for n in+ ("sbeRenderFilm", "sbeRenderPoll", "sbeRenderSettle",+ "sbeRenderFinish"))+ self.assertNotIn("workflowSwitch", chain)+ self.assertNotIn("sbFilmOpen", chain)+ self.assertIn("sbePaintRenderChip", chain)+ opener = extract_function("sbeOpenFilmScreen")+ self.assertIn("workflowSwitch", opener)+ self.assertIn("sbFilmOpen", opener)++ def test_the_render_still_discloses_holes_without_blocking(self):+ # FILM-27: the hole disclosure the editor gate locks in detail —+ # proving the "stay on the timeline" landing (FILM-24) was added to+ # the same chain, not swapped for it.+ chain = "".join(extract_function(n) for n in+ ("sbeRenderFilm", "sbeRenderPoll", "sbeRenderFinish"))+ self.assertIn("gaps_note", chain)+ self.assertIn("sbeNoticeHoles", chain)+ self.assertNotIn("confirm(", chain)++ def test_open_the_timeline_calls_a_step_sbGo_actually_handles(self):+ # FILM-25: sbGo() handles exactly 'plan', 'shots', 'edit' and 'film'+ # (see FilmClient's "every door" case above) — 'arrange' was never+ # one of them, so the Film screen's "Open the timeline" button did+ # nothing at all.+ self.assertIn("sbGo('edit')", extract_function("sbFilmPaint"))+ self.assertNotIn("sbGo('arrange')", extract_function("sbFilmPaint"))+++# =============================================================================+# "To film" from the Video tab — FILM-26+# =============================================================================+ADD_TO_FILM_SHIM = r"""+'use strict';+function escapeHtml(s) { return String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<'); }+function mkSelect() {+ return { style: { display: 'none' }, innerHTML: '', value: '',+ opened: false, showPicker() { this.opened = true; }, focus() {} };+}+const _els = { sbAddSelect: mkSelect() };+function sbEl(id) { return _els[id]; }+const _ls = {};+const localStorage = {+ getItem(k) { return Object.prototype.hasOwnProperty.call(_ls, k) ? _ls[k] : null; },+ setItem(k, v) { _ls[k] = v; },+ removeItem(k) { delete _ls[k]; },+};+const fetches = [];+let NEXT = { ok: true, title: 'My Film', n: 4 };+async function fetch(url, opts) {+ fetches.push({ url, body: opts && opts.body });+ return { json: async () => NEXT };+}+const toasts = [];+function phosToast(m) { toasts.push(String(m)); }+function _flashActionDone() {}+function sbRefreshBoards() {}+let activePath = '/out/clip_007.mp4';+__FN__+async function main() {+ const out = {};++ // ---- more than one film: reveal, don't add -----------------------------+ SB.boards = [{ id: 'a', title: 'Film A' }, { id: 'b', title: 'Film B' }];+ _ls.phos_sb_open = 'b'; // last-used+ fetches.length = 0;+ await sbAddActiveToBoard();+ out.revealedNotFetched = fetches.length;+ out.selShown = _els.sbAddSelect.style.display;+ out.selOpened = _els.sbAddSelect.opened;+ out.selHtml = _els.sbAddSelect.innerHTML;++ // ---- picking the FIRST real film (the one that used to be pre-selected,+ // so choosing it fired no onchange at all) now goes through -------------+ fetches.length = 0;+ await sbAddActiveToBoard('b');+ out.pickedFirstListedUrl = (fetches[0] || {}).url;+ out.pickedFirstListedId = fetches[0] && fetches[0].body.get('id');+ out.selHiddenAfter = _els.sbAddSelect.style.display;++ // ---- exactly one film: adds straight through, no select ---------------+ SB.boards = [{ id: 'only', title: 'Only Film' }];+ _els.sbAddSelect.style.display = 'none';+ fetches.length = 0;+ await sbAddActiveToBoard();+ out.oneFilmUrl = (fetches[0] || {}).url;+ out.oneFilmId = fetches[0] && fetches[0].body.get('id');+ out.oneFilmSelShown = _els.sbAddSelect.style.display;++ // ---- no films at all: goes to "new" ------------------------------------+ SB.boards = [];+ fetches.length = 0;+ await sbAddActiveToBoard();+ out.noFilmsId = fetches[0] && fetches[0].body.get('id');++ process.stdout.write(JSON.stringify(out));+}+main();+"""+++def run_add_to_film() -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ script = "const SB = { id: '', boards: [] };\n" + ADD_TO_FILM_SHIM.replace(+ "__FN__", extract_function("sbAddActiveToBoard"))+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = subprocess.run([NODE, str(path)], capture_output=True, text=True,+ timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)++[email protected](NODE, "needs node")+class AddToFilmPicker(unittest.TestCase):+ """FILM-26 — the picker opened already showing its first real film+ selected, so choosing exactly that film fired no `onchange` and the+ button looked broken. A leading placeholder makes every real choice a+ change; `showPicker()` opens the native list instead of leaving a+ revealed-but-closed 20px control behind.+ """++ @classmethod+ def setUpClass(cls):+ cls.r = run_add_to_film()++ def test_more_than_one_film_reveals_the_picker_rather_than_guessing(self):+ self.assertEqual(self.r["revealedNotFetched"], 0)+ self.assertEqual(self.r["selShown"], "")+ self.assertTrue(self.r["selOpened"])++ def test_the_first_option_is_a_placeholder_nobody_can_land_on_by_accident(self):+ html = self.r["selHtml"]+ self.assertLess(html.index('value=""'), html.index('value="a"'))+ self.assertIn("disabled", html.split("</option>")[0])++ def test_the_last_used_film_is_offered_first(self):+ html = self.r["selHtml"]+ self.assertLess(html.index('value="b"'), html.index('value="a"'))++ def test_new_film_is_still_the_last_option(self):+ html = self.r["selHtml"]+ self.assertLess(html.index('value="a"'), html.index('value="new"'))+ self.assertIn("new film", html)++ def test_picking_the_film_that_used_to_be_pre_selected_now_actually_adds(self):+ self.assertEqual(self.r["pickedFirstListedUrl"], "/storyboard/add-shot")+ self.assertEqual(self.r["pickedFirstListedId"], "b")+ self.assertEqual(self.r["selHiddenAfter"], "none")++ def test_exactly_one_film_skips_the_picker_entirely(self):+ self.assertEqual(self.r["oneFilmUrl"], "/storyboard/add-shot")+ self.assertEqual(self.r["oneFilmId"], "only")+ self.assertEqual(self.r["oneFilmSelShown"], "none")++ def test_no_films_at_all_offers_a_new_one(self):+ self.assertEqual(self.r["noFilmsId"], "new")if __name__ == "__main__":diff --git a/test_storyboard_film_integrity.py b/test_storyboard_film_integrity.pyindex dbc3037..cc3c6ba 100644--- a/test_storyboard_film_integrity.py+++ b/test_storyboard_film_integrity.py@@ -245,5 +245,100 @@ class StillFadesReachTheEncoder(unittest.TestCase):self.assertIn("fade=t=out", still_chain)+class RepeatRendersDoNotOverwriteEachOther(unittest.TestCase):+ """FILM-28, through the real `/storyboard/edit/render` route: three+ renders of the same board at the same delivery used to write the same+ file three times, with only the mtime to tell them apart. Now the+ second and third get `_r2`, `_r3` — versioned, never clobbered."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)+ self.clip = root / "a.mp4"+ self.clip.write_bytes(b"clip")+ board = _board("sb_t", "Night Drive")+ storyboard.save_storyboard(self.state, board)+ self.bdir = storyboard.board_dir(self.state, "sb_t")+ edit = {"version": sedit.EDIT_VERSION, "board_id": "sb_t", "revision": 0,+ "source": "human", "audio": None, "beats": None, "settings": {},+ "clips": [sedit.new_clip(str(self.clip), 0.0, 2.0, 0.0,+ source="human", duration=2.0)]}+ sedit.save_edit(self.bdir, edit)++ def fake_ffmpeg(cmd, label):+ Path(cmd[-1]).write_bytes(b"film")+ self._probe = mock.patch.object(+ panel, "_sb_probe_clip",+ return_value={"has_audio": False, "duration": 2.0, "w": 640,+ "h": 360, "sample_rate": 0})+ self._ffmpeg = mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=fake_ffmpeg)+ self._probe.start(); self._ffmpeg.start()+ self.addCleanup(self._probe.stop)+ self.addCleanup(self._ffmpeg.stop)++ def _render(self, **form):+ from test_storyboard_editor_api import FakeHandler+ h = FakeHandler()+ h.post("edit/render", {"id": "sb_t", **form})+ self.assertTrue(h.payload.get("ok"), h.payload)+ return Path(h.payload["path"])++ def test_three_renders_at_the_same_delivery_are_three_files(self):+ p1 = self._render()+ p2 = self._render()+ p3 = self._render()+ self.assertEqual(p1.name, "night-drive_film.mp4")+ self.assertEqual(p2.name, "night-drive_film_r2.mp4")+ self.assertEqual(p3.name, "night-drive_film_r3.mp4")+ # All three are real, distinct files — nothing got overwritten.+ for p in (p1, p2, p3):+ self.assertTrue(p.is_file(), p)+ names = {f["name"] for f in panel._sb_films(_board("sb_t", "Night Drive"),+ probe=False)}+ self.assertEqual(names, {p1.name, p2.name, p3.name})++ def test_an_explicit_out_still_renders_in_place(self):+ # `out=` is the deliberate escape hatch (re-render a NAMED delivery+ # over itself); versioning must not fight it.+ p1 = self._render(out="custom.mp4")+ p2 = self._render(out="custom.mp4")+ self.assertEqual(p1, p2)++ def test_loudnorm_reaches_the_encoder_through_the_route(self):+ with mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=lambda cmd, label:+ (self._seen.__setitem__("cmd", cmd),+ Path(cmd[-1]).write_bytes(b"film"))):+ self._seen = {}+ self._render(loudnorm="on")+ # EDITOR-2 (Codex 4.17.0): one link inside -filter_complex, mapped by+ # its label — `-af` on a stream fed from the complex graph is refused+ # by ffmpeg outright.+ cmd = self._seen["cmd"]+ self.assertNotIn("-af", cmd)+ graph = cmd[cmd.index("-filter_complex") + 1]+ self.assertIn("[aout]loudnorm=I=-14:TP=-1.5:LRA=11[aoutln]", graph)+ self.assertIn("[aoutln]", cmd)++ def test_loudnorm_off_by_default_through_the_route(self):+ with mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=lambda cmd, label:+ (self._seen.__setitem__("cmd", cmd),+ Path(cmd[-1]).write_bytes(b"film"))):+ self._seen = {}+ self._render()+ self.assertNotIn("-af", self._seen["cmd"])++if __name__ == "__main__":unittest.main()diff --git a/test_storyboard_light_persistence.py b/test_storyboard_light_persistence.pynew file mode 100644index 0000000..d9a5221--- /dev/null+++ b/test_storyboard_light_persistence.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""FILM-14 (item 4, server half): the board's shared "Light" line can be set+and changed on an already-planned board through the ordinary save route —+no re-plan needed — and, like `locations`, a re-plan that never mentions+`light` at all must not erase it.+"""+from __future__ import annotations++import json+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _shot(n, **kw):+ s = {"n": n, "uid": f"shot_{n:08x}", "mode": "text", "engine": "ltx",+ "prompt": f"shot {n}", "duration_s": 5.0, "seed": n, "refs": [],+ "status": "pending"}+ s.update(kw)+ return s+++def _board(bid, shots, **kw):+ b = {"schema": storyboard.SCHEMA_VERSION, "id": bid, "title": "T",+ "created_at": 1, "policy": storyboard.default_policy(), "cast": [],+ "engine_mode": "ltx", "concept": "a film", "shots": shots}+ b.update(kw)+ return b+++class FakeHandler:+ def __init__(self):+ self.status = None+ self.payload = None++ def _json(self, payload, status: int = 200):+ self.payload, self.status = payload, status+++class Sandbox(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state, self.out = root / "state", root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ for p in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None),+ # The "plan" action patches board["light"] synchronously,+ # then hands off to a background thread that actually+ # talks to the planner model — irrelevant here and, with+ # no real model on disk, liable to leave the one global+ # planner slot claimed if it is allowed to run for real.+ mock.patch.object(panel, "_sb_plan_thread", lambda *a, **k: None)):+ p.start()+ self.addCleanup(p.stop)+ panel._SB_PLANNERS.clear()+ self.addCleanup(panel._SB_PLANNERS.clear)++ def save(self, board):+ storyboard.save_storyboard(self.state, board)+ return board++ def load(self, bid):+ return storyboard.load_storyboard(self.state, bid)++ def post_save(self, bid, board_payload):+ h = FakeHandler()+ body = json.dumps({"id": bid, "board": board_payload})+ panel.Handler._storyboard_post(h, "save", body, {})+ return h++ def post(self, action, form):+ h = FakeHandler()+ panel.Handler._storyboard_post(h, action, "", form)+ return h+++class LightReachesAnUnrenderedShotWithNoReplan(Sandbox):+ def test_saving_a_light_note_on_an_existing_board_needs_no_replan(self):+ self.save(_board("sb_light1", [_shot(1)]))+ h = self.post_save("sb_light1", {"id": "sb_light1",+ "light": "cold blue moonlight"})+ self.assertEqual(h.status, 200, h.payload)+ self.assertEqual(self.load("sb_light1")["light"], "cold blue moonlight")++ def test_it_reaches_the_shots_prompt_at_render_time(self):+ self.save(_board("sb_light2", [_shot(1, prompt="he waits by the door")],+ light="a single hard sidelight, long shadow"))+ board = self.load("sb_light2")+ job = storyboard.shot_to_job(+ board["shots"][0], board["policy"]["draft"],+ locations=storyboard.board_locations(board),+ wardrobe=storyboard.board_wardrobe(board),+ light=storyboard.board_light(board))+ self.assertIn("a single hard sidelight, long shadow", job["prompt"])++ def test_a_replan_that_never_mentions_light_keeps_it(self):+ # Same shape as locations/wardrobe: sbReplan()'s form never sends+ # `light`, so an absent field must not erase the board's value.+ self.save(_board("sb_light3", [_shot(1)], light="firelight, warm"))+ h = self.post("plan", {"id": ["sb_light3"], "concept": ["a film"],+ "shots": ["1"]})+ self.assertTrue(h.payload.get("ok"), h.payload)+ self.assertEqual(self.load("sb_light3").get("light"), "firelight, warm")++ def test_a_plan_form_that_does_send_light_replaces_it(self):+ self.save(_board("sb_light4", [_shot(1)], light="firelight, warm"))+ h = self.post("plan", {"id": ["sb_light4"], "concept": ["a film"],+ "shots": ["1"], "light": ["cold fluorescent"]})+ self.assertTrue(h.payload.get("ok"), h.payload)+ self.assertEqual(self.load("sb_light4").get("light"), "cold fluorescent")++ def test_a_board_with_no_light_note_still_saves_and_renders_unchanged(self):+ self.save(_board("sb_light5", [_shot(1, prompt="he waits")]))+ h = self.post_save("sb_light5", {"id": "sb_light5", "title": "Renamed"})+ self.assertEqual(h.status, 200, h.payload)+ board = self.load("sb_light5")+ self.assertEqual(board.get("light", ""), "")+ job = storyboard.shot_to_job(+ board["shots"][0], board["policy"]["draft"],+ light=storyboard.board_light(board))+ self.assertEqual(job["prompt"], "he waits")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_lipsync_gate.py b/test_storyboard_lipsync_gate.pyindex f970d14..bd4f603 100644--- a/test_storyboard_lipsync_gate.py+++ b/test_storyboard_lipsync_gate.py@@ -118,3 +118,78 @@ class KeptTakeSurvivesReconcile(unittest.TestCase):finally:for k, v in saved.items():setattr(p, k, v)+++class EditsMadeWhileTheGateRunsSurvive(unittest.TestCase):+ """FILM-20: the gate used to hold ONE board snapshot across its whole+ run (a retake render can take minutes) and save that stale snapshot+ back at each step — silently reverting any edit made on the Storyboard+ tab in the meantime. Every save now re-reads the current board and+ patches in only the fields the gate itself owns."""++ def test_a_board_edit_made_mid_gate_is_not_reverted(self):+ import mlx_ltx_panel as p+ import storyboard+ tmp = Path(tempfile.mkdtemp(prefix="phos_gate_edit_"))+ files = {}+ for name in ("a", "b"):+ f = tmp / f"take_{name}.mp4"; f.write_bytes(b"x"); files[name] = str(f)+ board = {"id": "sb_test_gate_edit", "title": "Original title", "shots": [+ {"n": 1, "mode": "text", "engine": "h3", "duration_s": 5, "seed": 1,+ "status": "pending", "prompt": "an untouched B-roll shot", "uid": "shot_00000001"},+ {"n": 9, "mode": "text", "engine": "h3", "duration_s": 5, "seed": 100,+ "status": "done", "uid": "shot_00000009",+ "prompt": "He whispers: <d>[English] This is not ashwagandha.</d>",+ "final_job_id": "j1", "final_output": files["a"]}]}+ storyboard.save_storyboard(p.STATE_DIR, board)+ scores = {files["a"]: -0.35, files["b"]: 0.20}+ queued, jobs = [], {"j1": {"status": "done", "output_path": files["a"]}}++ def fake_enqueue(form):+ jid = f"j{len(queued) + 2}"; queued.append((jid, int(form["seed"])))+ jobs[jid] = {"status": "done", "output_path": files["b"]}+ return jid++ def wait_and_edit(job_ids):+ # Simulate the user editing the board on the Storyboard tab+ # WHILE this render is in flight: rewrite shot 1's prompt, the+ # board's title, and add a brand-new shot 2.+ live = storyboard.load_storyboard(p.STATE_DIR, "sb_test_gate_edit")+ live["title"] = "Retitled while the gate ran"+ for s in live["shots"]:+ if s["n"] == 1:+ s["prompt"] = "edited while the gate ran"+ live["shots"].append({"n": 2, "mode": "text", "engine": "h3",+ "duration_s": 3, "seed": 2, "status": "pending",+ "prompt": "a shot added mid-gate", "uid": "shot_00000002"})+ storyboard.save_storyboard(p.STATE_DIR, live)+ return True++ saved = {k: getattr(p, k) for k in ("take_lipsync_score", "_sb_enqueue", "_sb_job_index", "set_hidden", "push")}+ try:+ p.take_lipsync_score = lambda path: scores.get(str(path))+ p._sb_enqueue = fake_enqueue+ p._sb_job_index = lambda: dict(jobs)+ p.set_hidden = lambda path, hidden: None+ p.push = lambda line: None+ p._sb_lipsync_gate("sb_test_gate_edit", [board["shots"][1]],+ "final_job_id", "final_output",+ {"quality": "standard", "width": 1024, "height": 576},+ False, False, wait_and_edit)+ finally:+ for k, v in saved.items():+ setattr(p, k, v)++ after = storyboard.load_storyboard(p.STATE_DIR, "sb_test_gate_edit")+ self.assertEqual(after["title"], "Retitled while the gate ran")+ by_n = {s["n"]: s for s in after["shots"]}+ self.assertEqual(by_n[1]["prompt"], "edited while the gate ran")+ self.assertIn(2, by_n, "the shot added mid-gate must not be lost")+ self.assertEqual(by_n[2]["prompt"], "a shot added mid-gate")+ # and the gate's own shot still got its result+ self.assertEqual(by_n[9]["final_output"], files["b"])+ self.assertEqual(by_n[9]["lipsync"]["kept"], files["b"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_locations_i18n.py b/test_storyboard_locations_i18n.pynew file mode 100644index 0000000..e9239ef--- /dev/null+++ b/test_storyboard_locations_i18n.py@@ -0,0 +1,49 @@+#!/usr/bin/env python3+"""FILM-45 (client half): sbParseLocations mirrors the server's full-width+colon acceptance for Japanese location lines."""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++class TheClientMirrorsTheFullWidthColon(unittest.TestCase):+ def test_a_japanese_line_splits_on_the_fullwidth_colon(self):+ if NODE is None:+ self.skipTest("node not on PATH")+ fn = extract_function("sbParseLocations", STORYBOARD_JS)+ script = f"""+'use strict';+{fn}+console.log(JSON.stringify(sbParseLocations('台所:小さな台所')));+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ out = json.loads(result.stdout.strip())+ finally:+ path.unlink(missing_ok=True)+ self.assertEqual(len(out), 1)+ self.assertEqual(out[0]["name"], "台所")+ self.assertEqual(out[0]["description"], "小さな台所")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_planner.py b/test_storyboard_planner.pyindex cec2d12..70749a1 100644--- a/test_storyboard_planner.py+++ b/test_storyboard_planner.py@@ -670,6 +670,65 @@ class TestFeedback(unittest.TestCase):json.dumps(before["shots"][i], sort_keys=True),"shot %d drifted during a per-shot re-roll" % (i + 1))+ def test_a_reroll_of_a_singing_shot_keeps_its_music_video_identity(self):+ # FILM-21: the single-shot re-roll model has no idea a shot is a+ # music-video singing shot — it returns an ordinary planner shot,+ # with no awareness that the result needs to stay a2v-safe (that+ # pass, _enforce_laws, is deliberately skipped for a per-shot+ # re-roll — see the "Skipped on a per-shot re-roll" comment above).+ # Before this fix only `status` carried across the splice, so a+ # Rewrite on a singing shot silently dropped its music_video block,+ # its audio linkage (the second of the SONG it was rendered+ # against) and its `a2v` mode itself. This exercises the splice+ # directly (_coerce_for_mode), the exact mechanism that changed.+ previous = copy.deepcopy(self.base)+ previous["shots"][3].update({+ "n": 4, "mode": "a2v", "uid": "shot_deadbeef",+ "music_video": {"kind": "singing", "role": "singer",+ "film_start": 12.5, "film_end": 22.5,+ "panel_mode": "a2v"},+ "audio": "/x/song.wav", "audio_start_time": 12.5,+ "audio_stem": "/x/song_vocals.wav",+ "still": "/x/singer.png", "still_source": "user",+ })+ reply_obj = {"title": "The Key", "shots": [_shot(+ 4, description="Live-action, cinematic, a different scene entirely.")]}+ spec, _warnings = P._coerce_for_mode(+ reply_obj, "shot", 4, previous, concept="x", n_shots=6, style="",+ cast=[], board_id="sb_x", engine="ltx", tier="draft",+ duration_s=5.0, seed_base=1, max_dim=None, sb=storyboard)+ rewritten = next(s for s in spec["shots"] if s["n"] == 4)+ self.assertIn("different scene", rewritten["prompt"].lower()) # the rewrite+ # everything that makes this shot a singing shot of THIS song+ # survives the rewrite untouched+ self.assertEqual(rewritten["mode"], "a2v")+ self.assertEqual(rewritten["uid"], "shot_deadbeef")+ self.assertEqual(rewritten["music_video"]["film_start"], 12.5)+ self.assertEqual(rewritten["audio"], "/x/song.wav")+ self.assertEqual(rewritten["audio_start_time"], 12.5)+ self.assertEqual(rewritten["audio_stem"], "/x/song_vocals.wav")+ self.assertEqual(rewritten["still"], "/x/singer.png")+ self.assertEqual(rewritten["still_source"], "user")+ # every other shot is untouched+ for i in (0, 1, 2, 4, 5):+ self.assertEqual(spec["shots"][i], previous["shots"][i])++ def test_a_reroll_of_an_ordinary_shot_still_only_carries_status(self):+ # An ordinary (non-music-video) shot must not suddenly start+ # inheriting fields it never had — the carry list is additive+ # (`if carry in s`), so a plain shot with no music_video/audio/still+ # keys is unaffected.+ previous = copy.deepcopy(self.base)+ reply_obj = {"title": "The Key", "shots": [_shot(4, description="A door, not a key.")]}+ spec, _warnings = P._coerce_for_mode(+ reply_obj, "shot", 4, previous, concept="x", n_shots=6, style="",+ cast=[], board_id="sb_x", engine="ltx", tier="draft",+ duration_s=5.0, seed_base=1, max_dim=None, sb=storyboard)+ rewritten = next(s for s in spec["shots"] if s["n"] == 4)+ self.assertNotIn("music_video", rewritten)+ self.assertNotIn("audio", rewritten)+ self.assertEqual(rewritten.get("mode"), "text")+def test_shot_reroll_prompt_carries_the_neighbours_but_asks_for_one_shot(self):_, stub = _plan([json.dumps({"title": "T", "shots": [_shot(4)]})],feedback={"shot": 4, "note": "colder"},diff --git a/test_storyboard_planner_ram.py b/test_storyboard_planner_ram.pynew file mode 100644index 0000000..831712c--- /dev/null+++ b/test_storyboard_planner_ram.py@@ -0,0 +1,57 @@+#!/usr/bin/env python3+"""FILM-56: an up-front, plain-language warning when this Mac is unlikely to+clear the planner's own memory footprint, instead of a 900 s wait ending in+an out-of-memory failure with nothing said beforehand.++`storyboard_planner_ram_status()` is the one function both the boot payload+(`storyboard_status()["ram_status"]`, read by the client as+`SB_BOOT.ram_status`) and any future server-side check read — so the two can+never disagree about what this Mac can do.+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+++class PlannerRamStatus(unittest.TestCase):+ def test_a_roomy_mac_gets_no_message(self):+ with mock.patch.object(panel, "SYSTEM_RAM_GB", 64.0):+ status = panel.storyboard_planner_ram_status()+ self.assertTrue(status["ok"])+ self.assertEqual(status["message"], "")+ self.assertEqual(status["ram_gb"], 64.0)++ def test_a_tight_mac_gets_a_plain_warning(self):+ with mock.patch.object(panel, "SYSTEM_RAM_GB", 8.0):+ status = panel.storyboard_planner_ram_status()+ self.assertFalse(status["ok"])+ self.assertIn("8 GB", status["message"])+ # Naming Gemma specifically would go stale the moment+ # LTX_STORYBOARD_PLANNER points somewhere else (see the no-model-name+ # note on STORYBOARD_RAM_HELP, which this status follows).+ self.assertNotIn("Gemma", status["message"])+ self.assertNotIn("gemma", status["message"])++ def test_the_floor_is_sixteen_gb(self):+ with mock.patch.object(panel, "SYSTEM_RAM_GB", 16.0):+ self.assertTrue(panel.storyboard_planner_ram_status()["ok"])+ with mock.patch.object(panel, "SYSTEM_RAM_GB", 15.9):+ self.assertFalse(panel.storyboard_planner_ram_status()["ok"])++ def test_it_is_wired_into_the_boot_payload(self):+ status = panel.storyboard_status()+ self.assertIn("ram_status", status)+ self.assertIn("ok", status["ram_status"])+ self.assertIn("message", status["ram_status"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_planning_copy.py b/test_storyboard_planning_copy.pynew file mode 100644index 0000000..e673d69--- /dev/null+++ b/test_storyboard_planning_copy.py@@ -0,0 +1,71 @@+#!/usr/bin/env python3+"""FILM-56 (client half): the planning-modal copy scales with the shot+count actually submitted, and folds in a low-RAM notice — against the real+`_sbPlanningTimeCopy()`, not a re-implementation of its rules."""+from __future__ import annotations++import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _run(shots_submitted, ram_status):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ fn = extract_function("_sbPlanningTimeCopy", STORYBOARD_JS)+ script = f"""+'use strict';+let _sbPlanShotsSubmitted = {shots_submitted};+const SB_BOOT = {{ ram_status: {ram_status} }};+{fn}+console.log(_sbPlanningTimeCopy());+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run(["node", str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return result.stdout.strip()+ finally:+ path.unlink(missing_ok=True)+++class PlanningCopyScalesWithShotCount(unittest.TestCase):+ def test_a_small_board_still_says_about_a_minute(self):+ text = _run(4, "{ ok: true }")+ self.assertIn("About a minute", text)++ def test_a_medium_board_names_its_own_shot_count(self):+ text = _run(8, "{ ok: true }")+ self.assertIn("8 shots", text)+ self.assertNotIn("About a minute", text)++ def test_a_large_board_says_several_minutes(self):+ text = _run(20, "{ ok: true }")+ self.assertIn("Several minutes", text)+ self.assertIn("20 shots", text)++ def test_a_ram_short_mac_keeps_saying_so_through_every_stage(self):+ text = _run(4, "{ ok: false, message: 'This Mac reports 8 GB.' }")+ self.assertIn("short on memory", text)++ def test_a_capable_mac_says_nothing_about_memory(self):+ text = _run(4, "{ ok: true }")+ self.assertNotIn("memory", text)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_player_playlist.py b/test_storyboard_player_playlist.pynew file mode 100644index 0000000..c244255--- /dev/null+++ b/test_storyboard_player_playlist.py@@ -0,0 +1,149 @@+#!/usr/bin/env python3+"""FILM-41 (playlist half): "Player" must play the BOARD's own shots, in+order, not whatever the Video tab happened to have selected.++Before this fix, the "Player" toggle just revealed the shared stage pane —+which still showed whatever `selectOutput()` was last called with globally,+anywhere in the panel. This extracts the REAL sbPlayBoard/sbPlaylistPlay/+sbPlaylistPaths and runs them in node against a fake selectOutput + a fake+player <video> element whose 'ended' event is fired manually, proving the+playlist advances through the board's own clips in order and stops advancing+the moment the user (or anything else) picks a different clip.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+FUNCTIONS = ("sbPlaylistPaths", "sbPlayBoard", "sbPlaylistPlay")++SHIM = r"""+'use strict';+globalThis.activePath = null;+globalThis.__selectCalls = [];+let _currentVideo = null;+function _mkVideo() {+ const listeners = {};+ return {+ addEventListener(ev, cb) { listeners[ev] = cb; },+ _fireEnded() { if (listeners.ended) listeners.ended(); },+ };+}+globalThis.selectOutput = (path, opts) => {+ globalThis.activePath = path;+ globalThis.__selectCalls.push({ path, opts });+ _currentVideo = _mkVideo();+};+globalThis.document = {+ querySelector(sel) { return sel === '#playerWrap video' ? _currentVideo : null; },+};+globalThis.sbSetStage = () => {}; // layout-only; not the concern here+globalThis.phosToast = () => {};+globalThis.SB = { id: 'sb_test', payload: null, playlist: null };+"""+++def _run(board_shots, drive: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ fns = "\n\n".join(extract_function(n, STORYBOARD_JS) for n in FUNCTIONS)+ script = SHIM + fns + f"""+SB.payload = {{ board: {{ shots: {json.dumps(board_shots)} }} }};+{drive}+console.log(JSON.stringify({{+ selectCalls: __selectCalls.map(c => c.path),+ autoplays: __selectCalls.map(c => !!(c.opts && c.opts.autoplay)),+ playlist: SB.playlist,+}}));+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return json.loads(result.stdout.strip().splitlines()[-1])+ finally:+ path.unlink(missing_ok=True)+++SHOTS = [+ {"n": 1, "status": "done", "draft_output": "/o/s1.mp4"},+ {"n": 2, "status": "done", "final_output": "/o/s2_final.mp4",+ "draft_output": "/o/s2_draft.mp4"},+ {"n": 3, "status": "skipped", "draft_output": "/o/s3_cut.mp4"},+ {"n": 4, "status": "pending"}, # no clip yet+ {"n": 5, "status": "done", "draft_output": "/o/s5.mp4"},+]+++class ThePlaylistPlaysTheBoardsOwnShots(unittest.TestCase):+ def test_pressing_player_starts_at_the_first_shots_clip(self):+ out = _run(SHOTS, "sbPlayBoard();")+ self.assertEqual(out["selectCalls"][0], "/o/s1.mp4")+ self.assertTrue(out["autoplays"][0])++ def test_final_output_beats_draft_output(self):+ out = _run(SHOTS, """+sbPlayBoard();+document.querySelector('#playerWrap video')._fireEnded();+""")+ self.assertIn("/o/s2_final.mp4", out["selectCalls"])+ self.assertNotIn("/o/s2_draft.mp4", out["selectCalls"])++ def test_cut_and_unrendered_shots_are_skipped(self):+ out = _run(SHOTS, "sbPlayBoard();")+ paths = out["playlist"]["paths"]+ self.assertNotIn("/o/s3_cut.mp4", paths)+ self.assertEqual(len(paths), 3) # shots 1, 2, 5 only++ def test_ended_advances_to_the_next_clip_in_order(self):+ out = _run(SHOTS, """+sbPlayBoard();+document.querySelector('#playerWrap video')._fireEnded();+document.querySelector('#playerWrap video')._fireEnded();+""")+ self.assertEqual(out["selectCalls"],+ ["/o/s1.mp4", "/o/s2_final.mp4", "/o/s5.mp4"])++ def test_playlist_ends_cleanly_after_the_last_clip(self):+ out = _run(SHOTS, """+sbPlayBoard();+document.querySelector('#playerWrap video')._fireEnded();+document.querySelector('#playerWrap video')._fireEnded();+document.querySelector('#playerWrap video')._fireEnded();+""")+ self.assertIsNone(out["playlist"])++ def test_a_manual_selection_mid_playback_stops_the_advance(self):+ out = _run(SHOTS, """+sbPlayBoard();+const v1 = document.querySelector('#playerWrap video');+// the user clicks something else entirely while shot 1 plays+activePath = '/somewhere/else.mp4';+v1._fireEnded();+""")+ # never reached shot 2 — the playlist noticed activePath moved+ self.assertEqual(out["selectCalls"], ["/o/s1.mp4"])++ def test_an_empty_board_does_not_start_a_playlist(self):+ out = _run([{"n": 1, "status": "pending"}], "sbPlayBoard();")+ self.assertEqual(out["selectCalls"], [])+ self.assertIsNone(out["playlist"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_shot_grid.py b/test_storyboard_shot_grid.pynew file mode 100644index 0000000..a1ee351--- /dev/null+++ b/test_storyboard_shot_grid.py@@ -0,0 +1,127 @@+#!/usr/bin/env python3+"""FILM-41 (grid half): a dense contact-sheet view for a long board, so+finding a shot doesn't mean scrolling a 54,540 px column of full cards.++Extracts the real sbShotGridTile and sbSetShotView and proves the tile+carries a thumbnail, number, duration, status and grade badge, and that the+List/Grid toggle actually switches the shot list's rendered layout.+"""+from __future__ import annotations++import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _esc(s):+ return (s or "").replace("&", "&").replace("<", "<").replace(">", ">") \+ .replace('"', """).replace("'", "'")+++def _tile(shot: dict) -> str:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ fn = extract_function("sbShotGridTile", STORYBOARD_JS)+ script = f"""+'use strict';+function escapeHtml(s) {{ return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({{'&':'&','<':'<','>':'>','"':'"',"'":'''}}[c])); }}+{fn}+console.log(sbShotGridTile({json.dumps(shot)}));+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return result.stdout+ finally:+ path.unlink(missing_ok=True)+++class TheGridTile(unittest.TestCase):+ def test_a_rendered_shot_shows_a_thumbnail_number_length_and_status(self):+ html = _tile({"n": 7, "duration_s": 5.2, "status": "done",+ "draft_output": "/o/s7.mp4", "title": "S7"})+ self.assertIn('data-n="7"', html)+ self.assertIn("07", html)+ self.assertIn("5.2s", html)+ self.assertIn("sb-grid-status-done", html)+ self.assertIn("<video", html)+ self.assertIn("path=%2Fo%2Fs7.mp4", html)++ def test_a_shot_with_no_clip_gets_an_empty_thumbnail_not_a_broken_video(self):+ html = _tile({"n": 3, "status": "pending"})+ self.assertNotIn("<video", html)+ self.assertIn("sb-grid-thumb-empty", html)++ def test_the_grade_shows_as_a_letter_badge(self):+ html = _tile({"n": 1, "status": "done", "grade": "keep", "draft_output": "/o/s1.mp4"})+ self.assertIn("sb-grid-grade-keep", html)+ self.assertIn(">K<", html)++ def test_no_grade_means_no_badge(self):+ html = _tile({"n": 1, "status": "pending"})+ self.assertNotIn("sb-grid-grade", html)++ def test_clicking_a_tile_opens_it_in_the_full_list(self):+ html = _tile({"n": 12, "status": "done", "draft_output": "/o/s12.mp4"})+ self.assertIn("sbGridTileOpen(12)", html)+++class TheViewToggle(unittest.TestCase):+ def test_switching_to_grid_adds_the_grid_class_and_repaints(self):+ if NODE is None:+ self.skipTest("node not on PATH")+ fn = extract_function("sbSetShotView", STORYBOARD_JS)+ script = f"""+'use strict';+globalThis.SB = {{ shotView: 'list', payload: {{}} }};+globalThis.sessionStorage = {{ setItem() {{}}, getItem() {{ return null; }} }};+let _class = new Set();+const shotsBox = {{+ classList: {{ toggle(c, on) {{ on ? _class.add(c) : _class.delete(c); }},+ contains(c) {{ return _class.has(c); }} }},+}};+globalThis.sbEl = (id) => (id === 'sbShots' ? shotsBox : {{ querySelectorAll: () => [] }});+let repainted = false;+globalThis.sbRenderPlan = () => {{ repainted = true; }};+let _sbShotsHtml = 'stale';+{fn}+sbSetShotView('grid');+console.log(JSON.stringify({{+ view: SB.shotView, hasGridClass: shotsBox.classList.contains('sb-shots-grid'),+ repainted,+}}));+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ out = json.loads(result.stdout.strip().splitlines()[-1])+ finally:+ path.unlink(missing_ok=True)+ self.assertEqual(out["view"], "grid")+ self.assertTrue(out["hasGridClass"])+ self.assertTrue(out["repainted"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_singing_lock.py b/test_storyboard_singing_lock.pynew file mode 100644index 0000000..e656699--- /dev/null+++ b/test_storyboard_singing_lock.py@@ -0,0 +1,138 @@+#!/usr/bin/env python3+"""FILM-21 (client half): a singing shot's mode/length/order/Rewrite are+locked in the card, not just fixed up server-side.++`sbShotCard()` used to show the same editable Text/Character toggle, length+select, ↑/↓ reorder buttons and RE-ROLL grade button on every shot alike.+For a music-video singing (a2v) shot — rendered against ONE exact stretch of+the song — any of those could silently knock it (and every later singing+shot) off its own words: the toggle could flip it to silent i2v, a length+change or reorder desyncs its film_start, and Rewrite drops its+music_video/audio block entirely (see FILM-01/13 fixes in+storyboard_planner.py). This extracts the REAL sbShotCard/sbFmtClock/+sbShotEst and runs them in node to prove the locked controls are actually+disabled (or replaced) in the rendered markup for a singing shot, and that+an ordinary shot is completely unaffected.+"""+from __future__ import annotations++import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+FUNCTIONS = ("sbShotCard", "sbFmtClock", "sbShotEst")++SHIM = r"""+'use strict';+function escapeHtml(s) { if (!s) return ''; return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }+function friendlyJobError(raw) { return { friendly: String(raw || ''), hint: '' }; }+function sbEngineChip(id) { return '<span class="sb-chip-engine-stub"></span>'; }+globalThis.BOOT = { ltx: { lengths: [] }, h3: { lengths: [] } };+"""+++def _card(shot_over, r_over=None):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ fns = "\n\n".join(extract_function(n, STORYBOARD_JS) for n in FUNCTIONS)+ shot = {"n": 3, "mode": "text", "prompt": "a plain shot", "status": "pending",+ "duration_s": 5, "seed": -1, "draft_output": "/out/s3.mp4"}+ shot.update(shot_over)+ r = {"per_shot_est": {}, "characters": [], "h3_available": False,+ "board": {"shots": [{"n": 1}, {"n": 2}, shot, {"n": 4}]}}+ if r_over:+ r.update(r_over)+ import json as _json+ script = SHIM + fns + f"""+const out = sbShotCard({_json.dumps(shot)}, {_json.dumps(r)}, []);+console.log(out);+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return result.stdout+ finally:+ path.unlink(missing_ok=True)+++class SingingShotIsLocked(unittest.TestCase):+ def test_the_mode_toggle_is_replaced_by_a_readonly_chip(self):+ html = _card({"mode": "a2v",+ "music_video": {"kind": "singing", "section": "verse 2",+ "film_start": 31.0}})+ self.assertNotIn('data-act="mode"', html)+ self.assertIn("sb-chip-singing", html)+ self.assertIn("Singing", html)+ self.assertIn("verse 2", html)+ self.assertIn("0:31", html)++ def test_duration_up_down_and_reroll_are_disabled(self):+ html = _card({"mode": "a2v",+ "music_video": {"kind": "singing", "film_start": 0.0}})+ dur = re.search(r'<select class="sb-select sb-shot-dur"[^>]*>', html).group(0)+ self.assertIn("disabled", dur)+ up = re.search(r'data-act="up"[^>]*>', html).group(0)+ down = re.search(r'data-act="down"[^>]*>', html).group(0)+ self.assertIn("disabled", up)+ self.assertIn("disabled", down)+ reroll = re.search(r'data-act="grade" data-g="reroll"[^>]*>', html).group(0)+ self.assertIn("disabled", reroll)++ def test_the_card_is_not_draggable(self):+ html = _card({"mode": "a2v",+ "music_video": {"kind": "singing", "film_start": 0.0}})+ self.assertIn('draggable="false"', html)++ def test_an_ordinary_shot_is_completely_unaffected(self):+ html = _card({"mode": "text"})+ self.assertIn('data-act="mode"', html)+ self.assertNotIn("sb-chip-singing", html)+ dur = re.search(r'<select class="sb-select sb-shot-dur"[^>]*>', html).group(0)+ self.assertNotIn("disabled", dur)+ up = re.search(r'data-act="up"[^>]*>', html).group(0)+ self.assertNotIn("disabled", up)+ reroll = re.search(r'data-act="grade" data-g="reroll"[^>]*>', html).group(0)+ self.assertNotIn("disabled", reroll)+ self.assertIn('draggable="true"', html)++ def test_a_broll_music_video_shot_is_not_locked(self):+ # Only SINGING (a2v) music-video shots lock — B-roll shots on the+ # same board are ordinary i2v shots and stay fully editable.+ html = _card({"mode": "text",+ "music_video": {"kind": "broll", "film_start": 4.0}})+ self.assertNotIn("sb-chip-singing", html)+ dur = re.search(r'<select class="sb-select sb-shot-dur"[^>]*>', html).group(0)+ self.assertNotIn("disabled", dur)+++class NewTakeButton(unittest.TestCase):+ """FILM-22: a done card gets an "Edit & re-render" action — no planner+ call, just archives the clip and reseeds."""++ def test_the_button_only_appears_on_a_done_shot(self):+ html = _card({"status": "done"})+ self.assertIn('data-act="newtake"', html)++ def test_the_button_is_absent_on_a_pending_or_queued_shot(self):+ for status in ("pending", "queued", "rendering", "failed"):+ html = _card({"status": status})+ self.assertNotIn('data-act="newtake"', html, status)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_status_model.py b/test_storyboard_status_model.pynew file mode 100644index 0000000..fbed84b--- /dev/null+++ b/test_storyboard_status_model.py@@ -0,0 +1,204 @@+#!/usr/bin/env python3+"""FILM-42: board status numbers must not contradict each other, and a+shot's Draft/Delivery badge must reflect its OWN clip, not whichever pass+the board happens to be on.++Two specific contradictions locked here, against the REAL sbShotCard /+sbRenderPlan-shaped status logic:++ * "Finished · 0 shots" next to a rail correctly reading every draft+ rendered — the old status line unconditionally called the delivery+ pass "Finished" the moment it was current, even with zero delivered+ shots.+ * a clip probed at the Delivery canvas size badged "Draft" — the badge+ used to read one board-wide `r.pass`, not the shot's own measured size.+"""+from __future__ import annotations++import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _run(script: str) -> str:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run(["node", str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return result.stdout+ finally:+ path.unlink(missing_ok=True)+++def _status_snippet() -> str:+ """Pulls just the status-line block out of sbRenderPlan by locating it+ between its own start/end comments would be brittle; instead this runs+ the block through a tiny stand-in that mirrors its inputs exactly, by+ extracting the WHOLE function and stubbing everything else it touches.+ """+ return extract_function("sbRenderPlan", STORYBOARD_JS)+++SHIM = r"""+'use strict';+function escapeHtml(s) { return String(s == null ? '' : s); }+const _els = {};+function mk(id) {+ return { id, textContent: '', value: '', innerHTML: '', hidden: false, disabled: false, title: '',+ checked: false, classList: { toggle() {}, add() {}, remove() {}, contains() { return false; } },+ style: {}, dataset: {}, childElementCount: 0,+ querySelectorAll() { return []; } };+}+function sbEl(id) { if (!_els[id]) _els[id] = mk(id); return _els[id]; }+globalThis.document = { activeElement: null, querySelectorAll: () => [] };+function sbSetShots() {}+function sbSetTake() {}+function sbSyncBriefGates() {}+function sbFmtRuntime() { return ''; }+function sbFmtWall() { return ''; }+function sbHasClip() { return false; }+function sbAutoGrowPrompts() {}+function sbSyncStage() {}+function sbRenderRunBar() {}+function sbRenderTally() {}+function sbTypingInShots() { return false; }+function sbSelectOpen() { return false; }+function sbShotCard() { return ''; }+function sbShotGridTile() { return ''; }+function sbErrRow() { return ''; }+// FILM-46: sbRenderPlan() syncs the Stills-first checkbox pair on every+// render — irrelevant to the status-line math this file locks, so a no-op+// stub is correct (sbStillsFirst.js exercises the real function).+function sbStillsFirstSync() {}+let _sbShotsHtml = '';+const SB_BOOT = {};+const SB = { shotView: 'list' };+"""+++class TheStatusLineNeverContradictsTheRail(unittest.TestCase):+ def _status(self, board_over, r_over=None):+ board = {"shots": [], "policy": {}}+ board.update(board_over)+ r = {"board": board, "pass": "draft", "rendering": False, "estimate": {}, "errors": []}+ if r_over:+ r.update(r_over)+ script = SHIM + _status_snippet() + f"""+sbRenderPlan({json.dumps(r)});+console.log(sbEl('sbPlanStatus').textContent);+"""+ return _run(script).strip()++ def test_a_delivery_pass_with_nothing_delivered_never_says_finished(self):+ shots = [{"n": i, "draft_output": f"/o/s{i}.mp4"} for i in range(1, 76)]+ status = self._status({"shots": shots}, {"pass": "final", "rendering": False})+ self.assertNotIn("Finished", status)+ self.assertIn("ready for delivery", status)++ def test_a_delivery_pass_fully_delivered_says_finished_with_the_right_count(self):+ shots = [{"n": i, "draft_output": f"/o/s{i}.mp4", "final_output": f"/o/s{i}_f.mp4"}+ for i in range(1, 76)]+ status = self._status({"shots": shots}, {"pass": "final", "rendering": False})+ self.assertEqual(status, "Finished · 75 shots")++ def test_a_delivery_pass_partway_through_says_so_honestly(self):+ shots = ([{"n": i, "draft_output": f"/o/s{i}.mp4", "final_output": f"/o/s{i}_f.mp4"}+ for i in range(1, 5)]+ + [{"n": i, "draft_output": f"/o/s{i}.mp4"} for i in range(5, 11)])+ status = self._status({"shots": shots}, {"pass": "final", "rendering": False})+ self.assertEqual(status, "Delivery · 4 of 10")++ def test_draft_pass_status_is_unaffected(self):+ shots = [{"n": i, "draft_output": f"/o/s{i}.mp4"} for i in range(1, 4)]+ status = self._status({"shots": shots}, {"pass": "draft", "rendering": False})+ self.assertEqual(status, "Drafts done · 3 of 3")+++CARD_SHIM = r"""+'use strict';+function escapeHtml(s) { if (!s) return ''; return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }+function friendlyJobError(raw) { return { friendly: String(raw || ''), hint: '' }; }+function sbEngineChip() { return ''; }+function sbFmtClock(s) { const t = Math.max(0, Math.round(s || 0)); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, '0')}`; }+function sbShotEst() { return ''; }+globalThis.BOOT = { ltx: { lengths: [] }, h3: { lengths: [] } };+"""+++class TheBadgeJudgesEachShotOnItsOwnClip(unittest.TestCase):+ """FILM-42: the Draft/Delivery badge used to be ONE label for the whole+ board (r.pass) — a shot that had already delivered read "Draft" the+ moment any OTHER shot on the board still needed delivery, and vice+ versa. Each shot is judged on its own measured clip now."""++ def _card(self, shot_over, board_policy=None):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ fn = extract_function("sbShotCard", STORYBOARD_JS)+ shot = {"n": 1, "mode": "text", "prompt": "x", "status": "done",+ "duration_s": 5, "seed": -1, "draft_output": "/o/s1.mp4"}+ shot.update(shot_over)+ r = {"per_shot_est": {}, "characters": [], "h3_available": False,+ "board": {"shots": [shot],+ "policy": {"final": board_policy or {"width": 1280, "height": 704}}}}+ script = CARD_SHIM + fn + f"""+console.log(sbShotCard({json.dumps(shot)}, {json.dumps(r)}, []));+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ result = subprocess.run(["node", str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return result.stdout+ finally:+ path.unlink(missing_ok=True)++ def test_a_shot_probed_at_the_delivery_canvas_is_badged_delivery(self):+ html = self._card({"output_dims": [1280, 704]})+ chip = re.search(r'<span class="sb-chip sb-chip-pass"[^>]*>([^<]*)</span>', html)+ self.assertEqual(chip.group(1), "Delivery")++ def test_a_shot_probed_below_the_delivery_canvas_is_badged_draft(self):+ html = self._card({"output_dims": [640, 448]})+ chip = re.search(r'<span class="sb-chip sb-chip-pass"[^>]*>([^<]*)</span>', html)+ self.assertEqual(chip.group(1), "Draft")++ def test_badging_does_not_depend_on_any_other_shots_pass(self):+ # This is the actual reported bug: two shots, each measured, must+ # each get their OWN right answer — neither one is judged by+ # "what pass is the BOARD on" (which this function never even+ # receives — a deliberate structural fix, not just better data).+ delivered = self._card({"output_dims": [1280, 704]})+ still_draft = self._card({"output_dims": [640, 448]})+ d_chip = re.search(r'<span class="sb-chip sb-chip-pass"[^>]*>([^<]*)</span>', delivered).group(1)+ s_chip = re.search(r'<span class="sb-chip sb-chip-pass"[^>]*>([^<]*)</span>', still_draft).group(1)+ self.assertEqual((d_chip, s_chip), ("Delivery", "Draft"))++ def test_an_unmeasured_legacy_shot_falls_back_to_which_file_it_shows(self):+ html = self._card({"final_output": "/o/s1_final.mp4"})+ chip = re.search(r'<span class="sb-chip sb-chip-pass"[^>]*>([^<]*)</span>', html)+ self.assertEqual(chip.group(1), "Delivery")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_tab_race.py b/test_storyboard_tab_race.pynew file mode 100644index 0000000..065ef0a--- /dev/null+++ b/test_storyboard_tab_race.py@@ -0,0 +1,199 @@+#!/usr/bin/env python3+"""FILM-02 / FILM-19: the storyboard tab-entry race.++`sbInit()` runs on every entry into the Storyboard tab. It reads the last+board the user had open from localStorage, awaits `/storyboard/list`, and+then (with the old code) unconditionally opens that board — even when a+caller (Plan the video in music.js, a finished render in editor.js, the+gallery's "open this film" badge) already called `workflowSwitch('storyboard')`+then `sbOpen(theBoardItMeans)` in between. Because `sbOpen` sets `SB.id`+SYNCHRONOUSLY before its own await, the caller's board is on screen the+instant it runs — and then the slower `/storyboard/list` restore used to+land anyway and silently swap it back to whatever tab was open last time.+`sbLoad()` had the matching half of the same bug: it adopted whatever reply+came back with no check that it was still the board the user is looking at,+so a slow `/storyboard/get` reply for a board the user has since navigated+away from could overwrite the screen (and, via a later save, the board on+disk — FILM-19) with stale data.++This extracts the REAL `sbInit`/`sbOpen`/`sbLoad`/`sbRefreshBoards`/+`sbBackToList` functions from storyboard.js and runs them in node against a+`fetch` mock whose timing is controlled, so the race is reproduced (or not)+by the actual client code, not by a re-description of it.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")++FUNCTIONS = ("sbInit", "sbOpen", "sbLoad", "sbRefreshBoards", "sbBackToList")++STORYBOARD_JS = (ROOT / "webapp" / "js" / "storyboard.js").read_text(encoding="utf-8")+++def _run(js: str) -> dict:+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(js)+ path = Path(fh.name)+ try:+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=30)+ if result.returncode:+ raise AssertionError(result.stdout + "\n" + result.stderr)+ return json.loads(result.stdout.strip().splitlines()[-1])+ finally:+ path.unlink(missing_ok=True)+++# Minimal shim: real SB state shape, real _sbShots/_sbEngineMode module+# globals sbInit touches, and stubs for everything sbInit/sbLoad call out to+# that is NOT part of the race itself (rendering, the run poller, etc).+SHIM = r"""+'use strict';+const _ls = {};+globalThis.localStorage = {+ getItem: k => (k in _ls ? _ls[k] : null),+ setItem: (k, v) => { _ls[k] = String(v); },+ removeItem: k => { delete _ls[k]; },+};+globalThis.sessionStorage = globalThis.localStorage;+globalThis.setInterval = () => 0;+globalThis.clearInterval = () => {};+globalThis.activePath = null;+function stub(name) { globalThis[name] = () => {}; }+['sbRenderDraftQualities', 'sbRenderFinalQualities', 'sbSetShots', 'sbRenderEnginePicker',+ 'sbRenderCast', 'sbConceptInput', 'sbMustInput', 'sbShow', 'sbRenderPlan', 'sbSetPlanningStage',+ 'sbPlanBtnReset', 'sbAdoptLiveEdits', 'selectOutput', 'sbRenderBoardLists', 'sbRenderRunBar',+ 'sbTick',+].forEach(stub);+globalThis.sbEl = () => null;+globalThis.sbTypingInShots = () => false;++globalThis.SB = {+ id: '', payload: null, timer: null, saveTimer: null, saveInFlight: false,+ saveAgain: false, stageMode: 'auto', primed: false, boards: [], lastUndo: null,+ stage: '', films: [], filmsFor: '', filmDir: '', filmShort: '', filmOpen: '',+ boardsSig: '',+};+const SB_BOOT = {};+let _sbShots = 12;+let _sbEngineMode = 'auto';+"""+++class TheTabRestoreRace(unittest.TestCase):+ """FILM-02: a caller's own sbOpen must win over the tab's last-board restore."""++ def setUp(self):+ if NODE is None:+ self.skipTest("node not on PATH")+ self.fns = "\n\n".join(extract_function(n, STORYBOARD_JS) for n in FUNCTIONS)++ def _script(self, list_delay_ms: int, get_delay_ms: int) -> str:+ return SHIM + f"""+globalThis.__fetchLog = [];+globalThis.fetch = (url) => {{+ __fetchLog.push(url);+ if (url === '/storyboard/list') {{+ return new Promise(resolve => setTimeout(() => resolve({{+ json: async () => ({{ ok: true, boards: [{{ id: 'old_board' }}] }}),+ }}), {list_delay_ms}));+ }}+ const m = /^\\/storyboard\\/get\\?id=(.+)$/.exec(url);+ if (m) {{+ const id = decodeURIComponent(m[1]);+ return new Promise(resolve => setTimeout(() => resolve({{+ json: async () => ({{ ok: true, board: {{ id, shots: [] }}, planner: {{ state: 'idle' }} }}),+ }}), {get_delay_ms}));+ }}+ return Promise.resolve({{ json: async () => ({{ ok: false }}) }});+}};++{self.fns}++// The exact caller pattern of music.js's Plan the video, editor.js's+// render-finished redirect, and the gallery's "open this film" badge:+// workflowSwitch('storyboard') (which runs sbInit) THEN sbOpen(target),+// with a board already remembered in localStorage from a previous tab.+_ls['phos_sb_open'] = 'old_board';+sbInit();+sbOpen('new_board');++setTimeout(() => {{+ console.log(JSON.stringify({{+ finalId: SB.id,+ finalPayloadBoardId: SB.payload && SB.payload.board && SB.payload.board.id,+ }}));+}}, 150);+"""++ def test_the_callers_board_wins_when_the_list_restore_is_slower(self):+ out = _run(self._script(list_delay_ms=40, get_delay_ms=5))+ self.assertEqual(out["finalId"], "new_board")+ self.assertEqual(out["finalPayloadBoardId"], "new_board")++ def test_the_callers_board_wins_even_when_the_list_restore_is_faster(self):+ # The restore's OWN sbOpen(last) is also async (sbLoad); even if+ # /storyboard/list comes back quickly, sbInit's snapshot guard must+ # have already bailed before issuing it.+ out = _run(self._script(list_delay_ms=1, get_delay_ms=30))+ self.assertEqual(out["finalId"], "new_board")+ self.assertEqual(out["finalPayloadBoardId"], "new_board")+++class StaleLoadRepliesAreDropped(unittest.TestCase):+ """FILM-19 (client half): a slow /storyboard/get for a board the user has+ since navigated away from must not repaint the screen or seed a save."""++ def setUp(self):+ if NODE is None:+ self.skipTest("node not on PATH")+ self.fns = "\n\n".join(extract_function(n, STORYBOARD_JS)+ for n in ("sbLoad",))++ def test_a_stale_reply_never_overwrites_the_newer_board(self):+ script = SHIM + """+globalThis.fetch = (url) => {+ const m = /^\\/storyboard\\/get\\?id=(.+)$/.exec(url);+ const id = decodeURIComponent(m[1]);+ const delay = id === 'stale_target' ? 40 : 5;+ return new Promise(resolve => setTimeout(() => resolve({+ json: async () => ({ ok: true, board: { id, shots: [] }, planner: { state: 'idle' } }),+ }), delay));+};++""" + self.fns + """++SB.id = 'stale_target';+sbLoad('stale_target');+// While that fetch is still in flight, another sbOpen moves SB.id on.+setTimeout(() => { SB.id = 'someone_else_opened_this'; }, 10);++setTimeout(() => {+ console.log(JSON.stringify({+ finalId: SB.id,+ payloadAdopted: !!(SB.payload && SB.payload.board),+ payloadBoardId: SB.payload && SB.payload.board && SB.payload.board.id,+ }));+}, 80);+"""+ out = _run(script)+ self.assertEqual(out["finalId"], "someone_else_opened_this")+ self.assertFalse(out["payloadAdopted"],+ "a reply for a board nobody is looking at anymore "+ "must never be adopted into SB.payload")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_take.py b/test_take.pyindex 6d8bc41..b89c11d 100644--- a/test_take.py+++ b/test_take.py@@ -175,6 +175,43 @@ def test_take_runner_chains_parts_and_joins(tmp_path, monkeypatch):assert [f for f, flag in hidden if flag] == side["take"]["parts"]+def test_take_runner_records_each_parts_seed(tmp_path, monkeypatch):+ # VA-28: a random parent seed (-1) drew a fresh random seed per part with+ # nothing recorded anywhere, so Load Params on a random-seed take could+ # not reproduce it. Each part's REAL seed_used (as run_job_inner/+ # run_h3_job_inner already stamp on the child's own params) now lands in+ # take.parts_meta.+ out_dir = tmp_path / "out"; out_dir.mkdir()+ monkeypatch.setattr(p, "OUTPUT", out_dir)+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")+ monkeypatch.setattr(p, "set_hidden", lambda *a, **k: None)+ seen = []++ def fake_h3(child):+ seen.append(child)+ out = out_dir / f"{child['id']}.mp4"+ _tiny_clip(out, "red" if len(seen) == 1 else "blue")+ (out_dir / f"{child['id']}.mp4.json").write_text(json.dumps({"width": 64, "height": 64, "seed": 5}))+ child["output_path"] = str(out)+ # The real code path stamps this on the SAME params dict the take+ # runner holds a reference to (mlx_ltx_panel.py:29052 and siblings).+ child["params"]["seed_used"] = 1000 + len(seen)+ monkeypatch.setattr(p, "run_h3_job_inner", fake_h3)+ monkeypatch.setattr(p, "take_drift", lambda *a, **k: {"ok": True, "delta": 0.0, "drifted": False})+ j = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "a hen skates", "take_seconds": "30",+ "beats": json.dumps(["b1", "b2", "b3", "b4", "b5", "b6"]), "seed": "-1",+ "preset_label": "ride"})+ p.run_take_job_inner(j)+ final = Path(j["output_path"])+ side = json.loads(final.with_suffix(final.suffix + ".json").read_text())+ parts_meta = side["take"]["parts_meta"]+ assert [m["seed_used"] for m in parts_meta] == [1001, 1002]+ # Load Params (oneshot.js) restores the FIRST part's seed as the take's+ # own Seed field when the parent seed was random (-1).+ assert side["params"]["seed"] == "-1"+ assert side["params"]["take"]["parts_meta"][0]["seed_used"] == 1001++def test_take_runner_stops_between_parts(tmp_path, monkeypatch):out_dir = tmp_path / "out"; out_dir.mkdir()monkeypatch.setattr(p, "OUTPUT", out_dir)diff --git a/test_tier_chip_honesty.py b/test_tier_chip_honesty.pynew file mode 100644index 0000000..86bb279--- /dev/null+++ b/test_tier_chip_honesty.py@@ -0,0 +1,164 @@+#!/usr/bin/env python3+"""VC-28 [P2] [UX] The quality ladder names contradict their sizes.++Coordinator ruling, 2026-09-29: "DON'T rename the tiers. Show the real+output size and the time range on each chip, and fix the 'The default'+tooltip." (The "default" tooltip bug is VC-11's own text: the length axis's+5s blurb said "The default — one full beat." unconditionally, so it was+concatenated onto EVERY quality's 5s cell — Quick·5s, High·5s, ... — not+only Balanced·5s, the one combination that actually is the shipped default.)++Gated here:+ 1 ltx_tiers_payload() prices the DELIVERED size (post fit_720p export for+ Balanced, the same gap VC-19 closed for the info modal) beside the+ render canvas, for both the per-quality items and the per-cell tiers —+ and leaves every non-exporting quality's delivered size equal to its+ render canvas (a no-op there)+ 2 each cell carries an honest time RANGE (_fmt_eta_range), narrow for a+ real measurement, biased upward for a modelled estimate (this table's+ own history is estimates running optimistic, never pessimistic)+ 3 "The default" is stamped on exactly one cell — balanced_5s — server+ side, and the 5s length item's own blurb no longer claims it+ unconditionally+ 4 the client: qualitySpec shows the delivered size (with an arrow from+ the render canvas when they differ) and ltxCellEta prefers the range+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-tierhonesty-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8323")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++EJS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+++class TestDeliveredSize(unittest.TestCase):+ def setUp(self):+ self.payload = P.ltx_tiers_payload()+ self.tiers = {t["key"]: t for t in self.payload["tiers"]}+ self.qualities = {q["key"]: q for q in self.payload["qualities"]}++ def test_balanced_delivers_720p_not_its_render_canvas(self):+ q = self.qualities["balanced"]+ self.assertEqual(q["canvas"], "1024×576")+ self.assertEqual(q["delivered_canvas"], "1280×720")+ t = self.tiers["balanced_5s"]+ self.assertEqual((t["width"], t["height"]), (1024, 576))+ self.assertEqual((t["delivered_width"], t["delivered_height"]), (1280, 720))+ self.assertEqual(t["delivered_spec"], "1280×720")+ self.assertTrue(t["delivered_differs"])++ def test_non_exporting_qualities_are_unaffected(self):+ for key in ("quick", "standard"):+ q = self.qualities[key]+ self.assertEqual(q["canvas"], q["delivered_canvas"], key)+ t = self.tiers["standard_5s"]+ self.assertFalse(t["delivered_differs"])+ self.assertEqual(t["delivered_spec"], f"{t['width']}×{t['height']}")++ def test_high_720p_is_already_at_its_delivered_size(self):+ # high_720p renders 1280x704 with no export — its own canvas already+ # is what lands in Outputs.+ if "high_720p" in self.qualities:+ q = self.qualities["high_720p"]+ self.assertEqual(q["canvas"], q["delivered_canvas"])+++class TestEtaRange(unittest.TestCase):+ def setUp(self):+ self.tiers = {t["key"]: t for t in P.ltx_tiers_payload()["tiers"]}++ def test_every_priced_cell_has_a_range(self):+ for key, t in self.tiers.items():+ if t.get("eta_min"):+ self.assertIn("eta_range", t, key)+ self.assertTrue(t["eta_range"].startswith("~"), (key, t["eta_range"]))++ def test_modelled_cell_range_skews_upward_never_downward(self):+ # Find a cell with a real measurement and one that is purely modelled+ # (eta_measured False) and check the range shape directly via the+ # formatter, independent of which exact cells happen to be measured+ # today.+ # One range formatter for the whole panel (est's fleet ranges and+ # this chip band share it since the 4.17 merge): en dash, "~3–4 min".+ lo, hi = P._fmt_eta_range(3.0, 4.2).replace("~", "").split(" min")[0].split("–")+ self.assertEqual(int(lo), 3)+ self.assertEqual(int(hi), 4)++ def test_measured_cell_gets_a_narrow_band(self):+ s = P._fmt_eta_range(9.0, 9.0 * 1.1)+ self.assertIn("9", s)++ def test_identical_ends_collapse_to_one_number(self):+ self.assertEqual(P._fmt_eta_range(3.0, 3.0), "~3 min")++ def test_hours_range_format(self):+ s = P._fmt_eta_range(70.0, 95.0)+ self.assertTrue(s.startswith("~1h"), s)+ self.assertIn("–", s)+++class TestTheDefaultStamp(unittest.TestCase):+ def setUp(self):+ self.tiers = {t["key"]: t for t in P.ltx_tiers_payload()["tiers"]}++ def test_only_balanced_5s_is_the_default(self):+ defaults = [k for k, t in self.tiers.items() if t.get("is_default")]+ self.assertEqual(defaults, ["balanced_5s"])++ def test_only_balanced_5s_blurb_claims_it(self):+ for key, t in self.tiers.items():+ if key == "balanced_5s":+ self.assertTrue(t["blurb"].startswith("The default."), t["blurb"])+ else:+ self.assertNotIn("The default", t["blurb"], key)++ def test_quick_5s_no_longer_claims_the_default(self):+ # This is the exact VC-11 repro: Quick's chip used to combine its own+ # blurb with the 5s length's "The default — one full beat.", so+ # hovering Quick (never the default quality) said it was one.+ self.assertNotIn("The default", self.tiers["quick_5s"]["blurb"])+ self.assertIn("fastest", self.tiers["quick_5s"]["blurb"])++ def test_length_item_no_longer_hardcodes_the_default(self):+ # VC-23: re-worded again in plain English ("beat" was a+ # screenwriting idiom) — the assertion that matters here is+ # "The default" is gone, not the exact remaining wording.+ self.assertNotIn("The default", P.LTX_LENGTHS["5s"]["blurb"])++ def test_default_constants_agree_with_the_stamp(self):+ self.assertEqual(P.LTX_QUALITY_DEFAULT, "balanced")+ self.assertEqual(P.LTX_LENGTH_DEFAULT, "5s")+++class TestClientRendering(unittest.TestCase):+ def test_quality_spec_shows_delivered_size_with_an_arrow(self):+ fn = EJS[EJS.index("qualitySpec: (item, cell) => {"):]+ fn = fn[:fn.index("\n },")]+ self.assertIn("delivered_canvas", fn)+ self.assertIn("→", fn)++ def test_eta_prefers_the_range(self):+ fn = EJS[EJS.index("function ltxCellEta("):]+ fn = fn[:fn.index("\n}\n")]+ self.assertIn("cell.eta_range", fn)+ # the fast-draft / Q8-HQ special cases are unchanged+ self.assertIn("fast_eta", fn)+ # VC-23: relabelled "Q8 HQ" -> "High detail" (plain English)+ self.assertIn("High detail", fn)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_tier_quick_link.py b/test_tier_quick_link.pynew file mode 100644index 0000000..e2dc52c--- /dev/null+++ b/test_tier_quick_link.py@@ -0,0 +1,58 @@+"""VC-34: a second, visible door into the Tier dialog ("What this Mac can+do"), next to the Quality label where the decision actually happens.++WHAT THIS GUARDS. The only way to reach the Tier dialog was Health pill ->+the Tier row inside its popover (#tierPill is not visible until that+popover is opened) — despite the docs already sending people with memory+questions there. Added a plain-text link, "On this Mac: <tier label>",+next to the Quality chip strip's own label, reusing the existing+openTierModal() (the same function #tierPill already calls) and BOOT.tier+(already shipped in the bootstrap payload, fixed at boot since RAM+doesn't change at runtime).+"""+from __future__ import annotations++import re+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+MAIN_JS = (ROOT / "webapp" / "js" / "main.js").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++class MarkupAndWiring(unittest.TestCase):+ def test_link_sits_next_to_the_quality_label(self):+ i = HTML.index('id="qualityLabelName"')+ j = HTML.index('id="qualityMeta"')+ k = HTML.index('id="qualityTierLink"')+ self.assertLess(i, k)+ self.assertLess(k, j)++ def test_link_calls_the_same_opener_the_health_pill_uses(self):+ i = HTML.index('id="qualityTierLink"')+ j = HTML.index('</a>', i)+ snippet = HTML[i:j]+ self.assertIn("openTierModal()", snippet)+ # the pre-existing door, still there, still calling the same function+ self.assertIn('onclick="openTierModal()"', HTML)++ def test_label_populated_from_the_boot_payload_not_a_second_fetch(self):+ self.assertIn("qualityTierLinkLabel", MAIN_JS)+ self.assertIn("BOOT.tier", MAIN_JS)+ self.assertNotIn("fetch('/status')", MAIN_JS)++ def test_css_rule_exists(self):+ self.assertIn(".tier-quick-link {", CSS)+++class BootPayloadCarriesTheLabel(unittest.TestCase):+ def test_boot_tier_label_field_exists_in_server_source(self):+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ m = re.search(r'"tier":\s*\{\s*"key":\s*SYSTEM_TIER,\s*"label":\s*SYSTEM_CAPS\["label"\]', src)+ self.assertIsNotNone(m, "BOOT.tier.label wiring not found server-side")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_toolbar_more_menu.py b/test_toolbar_more_menu.pynew file mode 100644index 0000000..72122a1--- /dev/null+++ b/test_toolbar_more_menu.py@@ -0,0 +1,326 @@+#!/usr/bin/env python3+"""VC-18 / VC-37 (clip toolbar) + VC-42 (LoRA row menu) — coordinator ruling+2026-09-29: "the clip toolbar... Add Sharp export, Use last frame, Open in+Editor, Reveal in Finder, To film, lightbox actions" and "move the per-row+'Delete from disk' into a ⋯ menu with confirm."++Gated here:+ 1 Sharp export — queue_sharp_export() refuses what the worker would only+ refuse late (missing file, non-video, PiperSR not installed), dedupes a+ double click, and /queue/sharp_export answers JSON either way+ 2 run_sharp_export_job_inner() picks fit_720p/x2 the same way the+ render-time Export row does, calls run_pipersr_tracked, and writes a+ sidecar that carries the SOURCE clip's own params forward+ 3 /output/reveal and /output/last_frame are contained to OUTPUT/UPLOADS+ (the same rule /image already enforces) and refuse a path outside them+ 4 the toolbar markup: one "More" popover with all four actions, plus the+ same row rendered (flat) inside the expand lightbox for video only+ 5 the LoRA row's "Delete from disk" is no longer a bare flat danger+ button — it is one item inside a per-row ⋯ popover, confirm() untouched++No renders, no GPU, no ffmpeg required for the unit-level tests (the+ffmpeg-dependent route test skips cleanly where ffmpeg is absent).+"""+from __future__ import annotations++import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from urllib.parse import urlencode++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-moremenu-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8321")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+from panel.routes import POST_ROUTES # noqa: E402++HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+LJS = (ROOT / "webapp" / "js" / "loras.js").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+FFMPEG = shutil.which("ffmpeg")+++class _H:+ """Minimal fake handler matching the POST_ROUTES contract used elsewhere+ (see test_face_fix.py's `H`)."""++ def __init__(self, body: str = ""):+ self.body, self.out = body, None++ def _read_form_body(self):+ from urllib.parse import parse_qs+ return self.body, parse_qs(self.body)++ def _json(self, obj, code=200):+ self.out = (code, obj)+++class _Env(unittest.TestCase):+ def setUp(self):+ self.dir = Path(tempfile.mkdtemp(prefix="mm-", dir=P.OUTPUT)) # UI-1: outputs/uploads only+ self.clip = self.dir / "gym_draft.mp4"+ self.clip.write_bytes(b"\0" * 64)+ Path(str(self.clip) + ".json").write_text(json.dumps({"params": {+ "prompt": "A woman lifts a dumbbell", "seed": "-1",+ "seed_used": 52190, "mode": "t2v"}}), encoding="utf-8")+ self._saved = (P.PIPERSR_UPSCALE_ENABLED, P.persist_queue)+ P.PIPERSR_UPSCALE_ENABLED = True+ P.persist_queue = lambda: None+ with P.QUEUE_COND:+ self._queue_before = list(P.STATE["queue"])++ def tearDown(self):+ shutil.rmtree(self.dir, ignore_errors=True) # a temp dir under the sandboxed OUTPUT+ P.PIPERSR_UPSCALE_ENABLED, P.persist_queue = self._saved+ with P.QUEUE_COND:+ P.STATE["queue"] = self._queue_before+ P.STATE["current"] = None++ def queued(self):+ with P.QUEUE_COND:+ return [j for j in P.STATE["queue"] if j not in self._queue_before]+++# ---------------------------------------------------------------- 1+class TestQueueSharpExport(_Env):+ def test_queues_with_source_path_recorded(self):+ r = P.queue_sharp_export(str(self.clip))+ self.assertTrue(r["ok"], r)+ jobs = self.queued()+ self.assertEqual(len(jobs), 1)+ p = jobs[0]["params"]+ self.assertEqual(p["mode"], "sharp_export")+ self.assertEqual(p["source_path"], str(self.clip))++ def test_double_click_is_one_job(self):+ a = P.queue_sharp_export(str(self.clip))+ b = P.queue_sharp_export(str(self.clip))+ self.assertEqual(a["id"], b["id"])+ self.assertTrue(b.get("duplicate"))+ self.assertEqual(len(self.queued()), 1)++ def test_refuses_a_missing_file(self):+ r = P.queue_sharp_export(str(self.dir / "gone.mp4"))+ self.assertFalse(r["ok"])+ self.assertEqual(self.queued(), [])++ def test_refuses_a_still_image(self):+ still = self.dir / "still.png"+ still.write_bytes(b"x")+ r = P.queue_sharp_export(str(still))+ self.assertFalse(r["ok"])+ self.assertIn("video", r["error"])++ def test_refuses_when_pipersr_is_not_installed(self):+ P.PIPERSR_UPSCALE_ENABLED = False+ r = P.queue_sharp_export(str(self.clip))+ self.assertFalse(r["ok"])+ self.assertEqual(r.get("code"), "pack_missing")+ self.assertEqual(self.queued(), [])++ def test_route_is_registered_and_answers_json(self):+ self.assertIn("/queue/sharp_export", POST_ROUTES)+ h = _H(urlencode({"path": str(self.clip)}))+ POST_ROUTES["/queue/sharp_export"](h, "/queue/sharp_export", {}, "")+ self.assertEqual(h.out[0], 200)+ self.assertTrue(h.out[1]["ok"])+ h = _H(urlencode({"path": str(self.dir / "nope.mp4")}))+ POST_ROUTES["/queue/sharp_export"](h, "/queue/sharp_export", {}, "")+ self.assertEqual(h.out[0], 400)+++# ---------------------------------------------------------------- 2+class TestRunSharpExportJobInner(_Env):+ def _job(self, **extra):+ p = {"mode": "sharp_export", "source_path": str(self.clip)}+ p.update(extra)+ return {"id": "j1", "params": p, "started_at": None, "started_ts": None}++ def test_picks_fit_720p_for_a_small_source_and_writes_a_sidecar(self):+ calls = []++ def fake_pipersr(source, output, mode, crf, pix_fmt, preset):+ calls.append(mode)+ Path(output).write_bytes(b"x")++ old_probe, old_pipersr = P._probe_video_dims, P.run_pipersr_tracked+ P._probe_video_dims = lambda path: (640, 480)+ P.run_pipersr_tracked = fake_pipersr+ try:+ job = self._job()+ P.run_sharp_export_job_inner(job)+ finally:+ P._probe_video_dims, P.run_pipersr_tracked = old_probe, old_pipersr+ self.assertEqual(calls, ["fit_720p"])+ out = Path(job["output_path"])+ self.assertTrue(out.is_file())+ sidecar = json.loads(Path(str(out) + ".json").read_text())+ self.assertEqual(sidecar["params"]["prompt"], "A woman lifts a dumbbell")+ self.assertEqual(sidecar["params"]["sharp_export_source"], str(self.clip))+ self.assertEqual(sidecar["params"]["sharp_export_mode"], "fit_720p")++ def test_picks_x2_for_a_source_already_at_720p(self):+ calls = []+ old_probe, old_pipersr = P._probe_video_dims, P.run_pipersr_tracked+ P._probe_video_dims = lambda path: (1280, 720)+ P.run_pipersr_tracked = lambda source, output, mode, crf, pix_fmt, preset: (+ calls.append(mode), Path(output).write_bytes(b"x"))+ try:+ P.run_sharp_export_job_inner(self._job())+ finally:+ P._probe_video_dims, P.run_pipersr_tracked = old_probe, old_pipersr+ self.assertEqual(calls, ["x2"])++ def test_an_explicit_sharp_mode_overrides_the_auto_pick(self):+ calls = []+ old_probe, old_pipersr = P._probe_video_dims, P.run_pipersr_tracked+ P._probe_video_dims = lambda path: (640, 480)+ P.run_pipersr_tracked = lambda source, output, mode, crf, pix_fmt, preset: (+ calls.append(mode), Path(output).write_bytes(b"x"))+ try:+ P.run_sharp_export_job_inner(self._job(sharp_mode="x2"))+ finally:+ P._probe_video_dims, P.run_pipersr_tracked = old_probe, old_pipersr+ self.assertEqual(calls, ["x2"])++ def test_dispatches_from_run_job_inner(self):+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ self.assertIn('if mode == "sharp_export":\n return run_sharp_export_job_inner(job)', src)+++# ---------------------------------------------------------------- 3+class TestRevealAndLastFrameRoutes(_Env):+ def test_reveal_refuses_a_path_outside_output_and_uploads(self):+ self.assertIn("/output/reveal", POST_ROUTES)+ outside = Path(tempfile.mkdtemp(prefix="mm-outside-")) / "x.mp4"+ outside.write_bytes(b"x")+ h = _H(urlencode({"path": str(outside)}))+ POST_ROUTES["/output/reveal"](h, "/output/reveal", {}, "")+ self.assertFalse(h.out[1]["ok"])+ self.assertEqual(h.out[0], 403)++ def test_reveal_refuses_a_missing_file_inside_the_root(self):+ h = _H(urlencode({"path": str(self.dir / "nope.mp4")}))+ POST_ROUTES["/output/reveal"](h, "/output/reveal", {}, "")+ # self.dir lives under STATE_DIR, not OUTPUT/UPLOADS -> containment+ # refusal (403) rather than a not-found (404) is equally correct here;+ # assert it is refused either way, never a silent 200.+ self.assertFalse(h.out[1]["ok"])++ def test_reveal_opens_a_real_file_under_output(self):+ target = P.OUTPUT / f"mm_reveal_{id(self)}.mp4"+ P.OUTPUT.mkdir(parents=True, exist_ok=True)+ target.write_bytes(b"x")+ old_run = P.subprocess.run+ seen = []+ P.subprocess.run = lambda argv, **kw: seen.append(argv)+ try:+ h = _H(urlencode({"path": str(target)}))+ POST_ROUTES["/output/reveal"](h, "/output/reveal", {}, "")+ finally:+ P.subprocess.run = old_run+ target.unlink(missing_ok=True)+ self.assertTrue(h.out[1]["ok"], h.out)+ self.assertEqual(seen[0][:2], ["open", "-R"])++ def test_last_frame_refuses_a_non_mp4(self):+ still = P.UPLOADS / f"mm_{id(self)}.png"+ P.UPLOADS.mkdir(parents=True, exist_ok=True)+ still.write_bytes(b"x")+ try:+ h = _H(urlencode({"path": str(still)}))+ POST_ROUTES["/output/last_frame"](h, "/output/last_frame", {}, "")+ finally:+ still.unlink(missing_ok=True)+ self.assertFalse(h.out[1]["ok"])++ @unittest.skipUnless(FFMPEG, "ffmpeg not on PATH")+ def test_last_frame_extracts_a_real_png(self):+ P.OUTPUT.mkdir(parents=True, exist_ok=True)+ clip = P.OUTPUT / f"mm_lf_{id(self)}.mp4"+ subprocess.run(+ [FFMPEG, "-y", "-f", "lavfi", "-i", "color=c=red:s=64x64:d=1",+ "-frames:v", "24", str(clip)],+ capture_output=True, timeout=30, check=True,+ )+ try:+ h = _H(urlencode({"path": str(clip)}))+ POST_ROUTES["/output/last_frame"](h, "/output/last_frame", {}, "")+ self.assertTrue(h.out[1]["ok"], h.out)+ out = Path(h.out[1]["path"])+ self.assertTrue(out.is_file())+ self.assertGreater(out.stat().st_size, 0)+ out.unlink(missing_ok=True)+ finally:+ clip.unlink(missing_ok=True)+++# ---------------------------------------------------------------- 4+class TestToolbarMarkup(unittest.TestCase):+ def test_more_menu_has_all_four_actions(self):+ i = HTML.index('id="playerMoreWrap"')+ blk = HTML[i:i + 2600]+ self.assertIn("kebabToggle('playerMorePop')", blk)+ self.assertIn("sharpExportActive()", blk)+ self.assertIn("useLastFrameActive()", blk)+ self.assertIn("openActiveInEditor()", blk)+ self.assertIn("revealActive()", blk)++ def test_lightbox_has_its_own_actions_row(self):+ self.assertIn('id="expandActions"', HTML)+ fn = QJS[QJS.index("function openExpandLightbox()"):]+ fn = fn[:fn.index("\nfunction closeExpandLightbox")]+ self.assertIn("expandActions", fn)+ self.assertIn("sharpExportActive()", fn)+ self.assertIn("!isPhoto && !isAudio", fn)++ def test_client_functions_exist_and_are_published(self):+ for fn in ("queueSharpExport", "sharpExportActive", "useLastFramePath",+ "useLastFrameActive", "revealClipInFinder", "revealActive",+ "openClipInEditor", "openActiveInEditor", "kebabToggle"):+ self.assertIn(f"function {fn}(", QJS, fn)+ self.assertIn(fn, QJS[QJS.index("Object.assign(globalThis"):], fn)++ def test_kebab_css_component_exists(self):+ self.assertIn(".kebab-pop", CSS)+ self.assertIn(".kebab-pop.open", CSS)+++# ---------------------------------------------------------------- 5+class TestLoraRowMenu(unittest.TestCase):+ def test_delete_from_disk_lives_in_a_kebab_menu(self):+ fn = LJS[LJS.index("function loraRowHtml("):]+ fn = fn[:fn.index("\nfunction ", 20)]+ self.assertIn("kebab-wrap", fn)+ self.assertIn("_loraRowKebabId(r.path)", fn)+ self.assertIn("Delete from disk", fn)+ # no longer a bare flat danger icon button in the corner row+ self.assertNotIn('class="lora-icon-btn danger"', fn)+ self.assertIn("kebabToggle(", fn)++ def test_confirm_is_unchanged(self):+ fn = LJS[LJS.index("async function deleteLora("):]+ fn = fn[:fn.index("\n}\n")]+ self.assertIn("confirm(", fn)++ def test_kebab_id_helper_is_deterministic_and_distinct(self):+ i = LJS.index("function _loraRowKebabId(")+ self.assertGreater(i, -1)+ # Two different paths must not collide on the trivial empty-string case+ self.assertIn("loraMore", LJS[i:i + 400])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_unavailable_chip_click_feedback.py b/test_unavailable_chip_click_feedback.pynew file mode 100644index 0000000..e17cbb3--- /dev/null+++ b/test_unavailable_chip_click_feedback.py@@ -0,0 +1,55 @@+"""VC-22 (REJECTED — already fixed, verified against this exact commit; test+added as a regression lock so it can't quietly regress).++The finding: "Clicking an unavailable chip does nothing visible; the reason+exists only as a hover tooltip... On 16 GB, click 'High · UNAVAILABLE'.+Selection stays on Balanced; no message."++Verified live against beta/main 70665d3 (this package's base) with+LTX_TIER_OVERRIDE=base (a 16 GB-class Mac): clicking the disabled High chip+DOES show a message — `_ltxApplyShape()` (engines.js) writes the chip's own+`unavailable_reason` into #engineRowNote and leaves the selection on+Balanced. The code carries an explicit comment dated to an "owner ruling+2026-08-23" describing exactly this fix ("a click has to SAY the reason+rather than swallow it — a tooltip is not discoverable on a chip a user has+just tapped"), which predates the review. Nothing in this package's diff+touches this path; this file exists to prove the claim was checked, not+assumed, and to catch a real future regression.+"""+from __future__ import annotations++import re+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+ENGINES_JS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")+++class UnavailableChipAlreadySaysWhy(unittest.TestCase):+ def test_ltx_apply_shape_writes_the_reason_on_an_unavailable_cell(self):+ i = ENGINES_JS.index("function _ltxApplyShape")+ j = ENGINES_JS.index("\n}\n", i)+ body = ENGINES_JS[i:j]+ self.assertIn("cell.available === false", body)+ self.assertIn("unavailable_reason", body)+ self.assertIn("engineRowNote", body)+ self.assertIn("note.hidden = false", body)+ # and it must NOT silently switch the selection - the whole point+ self.assertIn("return;", body)++ def test_the_note_write_does_not_set_packnote_so_the_pack_gate_cant_clobber_it(self):+ """applyPackIncompleteGate's clear() only wipes the note when+ dataset.packNote === '1' - it READS that flag here (to avoid+ overwriting an existing pack note), but must never ASSIGN it, or+ the next 1.5s poll would erase the reason it just showed."""+ i = ENGINES_JS.index("function _ltxApplyShape")+ j = ENGINES_JS.index("\n}\n", i)+ body = ENGINES_JS[i:j]+ self.assertIn("dataset.packNote !== '1'", body)+ self.assertNotIn("dataset.packNote = ", body)+ self.assertNotIn('dataset.packNote=', body)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_undo_persistence.py b/test_undo_persistence.pynew file mode 100644index 0000000..c892671--- /dev/null+++ b/test_undo_persistence.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""FILM-57: undo survives a reload, only when it is safe to trust.++The stack (SBE.undo/SBE.redo) is in-memory only, so a reload always starts+both empty — indistinguishable from "the history is gone" unless something+persists it. What makes restoring it safe is not the film's id alone: a+reload re-adopts the last SAVED document, and if the tab had unsaved edits,+the screen coming back is NOT the screen the stack was built for — an undo+stack pointing at states the current arrangement never passed through is+worse than no undo (sbeUndo would jump the arrangement to something+unrelated to what's on screen). So the persisted entry carries a+fingerprint of the exact content it was written beside, and is only ever+adopted when that fingerprint matches what the server just handed back.+"""+from __future__ import annotations++import re+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function, panel_source # noqa: E402++from test_editor_save_integrity import run # noqa: E402++EXTRA = ("sbePersistUndo", "sbeRestoreUndoIfFresh", "sbeUndoFingerprint",+ "sbeUndoStoreKey")++SESSION_SHIM = r"""+// A module-level `let`, not a function — extract_function only pulls+// function bodies by name, so the two functions' shared bit of state has+// to be declared here, at the same top-level scope they will sit in.+let _sbeUndoLastFingerprint = '';+const SESSION_STORE = new Map();+const setItemCalls = [];+global.sessionStorage = {+ getItem: (k) => (SESSION_STORE.has(k) ? SESSION_STORE.get(k) : null),+ setItem: (k, v) => { setItemCalls.push(k); SESSION_STORE.set(k, String(v)); },+ removeItem: (k) => { SESSION_STORE.delete(k); },+};+"""+++class ThePersistedStack(unittest.TestCase):++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()+ consts = "\n".join(re.findall(+ r"^const SBE_UNDO_STORE_PREFIX = .*?;$", cls.src, re.M))+ assert consts.count("const") == 1, consts+ cls.r = run(r"""+SBE.open = true; SBE.id = 'sb_t';+SBE.clips = [{ id: 'a', path: '/x/a.mp4', start: 0, end: 2, film_start: 0 }];+SBE.overlays = []; SBE.tracks = []; SBE.transitions = [];+SBE.undo = []; SBE.redo = [];++// Nothing persisted yet for a fresh tab — restore is a no-op.+out.restoreWithNothingStored = (() => {+ sbeRestoreUndoIfFresh();+ return [SBE.undo.length, SBE.redo.length];+})();++// A real persist writes an entry keyed to the CURRENT content.+SBE.undo = [{ clips: [] }]; SBE.redo = [];+sbePersistUndo();+out.storedAfterFirstPersist = sessionStorage.getItem(sbeUndoStoreKey('sb_t')) !== null;+out.setItemCallsAfterFirst = setItemCalls.length;++// Calling it again with NOTHING changed costs no write.+sbePersistUndo();+out.setItemCallsAfterRepeat = setItemCalls.length;++// The content changes — a new persist DOES write.+SBE.clips = [{ id: 'a', path: '/x/a.mp4', start: 0, end: 3, film_start: 0 }];+sbePersistUndo();+out.setItemCallsAfterRealChange = setItemCalls.length;++// Simulate a reload: fresh in-memory stacks, same on-screen content (the+// server handed back the same document — nothing was lost).+const savedUndo = SBE.undo.slice(), savedRedo = SBE.redo.slice();+SBE.undo = []; SBE.redo = [];+sbeRestoreUndoIfFresh();+out.restoredWhenFingerprintMatches = [SBE.undo.length, SBE.redo.length,+ JSON.stringify(SBE.undo) === JSON.stringify(savedUndo)];++// Simulate a reload where the on-screen content is DIFFERENT from what the+// stack was persisted against (unsaved edits that did not survive) — the+// stack must NOT be restored.+SBE.undo = []; SBE.redo = [];+SBE.clips = [{ id: 'a', path: '/x/a.mp4', start: 0, end: 99, film_start: 0 }];+sbeRestoreUndoIfFresh();+out.notRestoredWhenFingerprintDiffers = [SBE.undo.length, SBE.redo.length];++// An empty stack removes its entry rather than leaving a stale write.+SBE.clips = [{ id: 'a', path: '/x/a.mp4', start: 0, end: 3, film_start: 0 }];+SBE.undo = []; SBE.redo = [];+sbePersistUndo();+out.emptyStackClearsTheEntry = sessionStorage.getItem(sbeUndoStoreKey('sb_t'));++// A corrupt entry (oversized undo) is capped on the way back in.+const big = [];+for (let i = 0; i < 200; i++) big.push({ i });+sessionStorage.setItem(sbeUndoStoreKey('sb_t'),+ JSON.stringify({ fp: sbeUndoFingerprint(), undo: big, redo: [] }));+SBE.undo = []; SBE.redo = [];+sbeRestoreUndoIfFresh();+out.restoredIsCapped = SBE.undo.length;++// try/catch: a sessionStorage that throws never breaks the caller.+const realGet = sessionStorage.getItem, realSet = sessionStorage.setItem;+sessionStorage.getItem = () => { throw new Error('blocked'); };+sessionStorage.setItem = () => { throw new Error('blocked'); };+let threw = false;+try { sbePersistUndo(); sbeRestoreUndoIfFresh(); } catch (e) { threw = true; }+out.neverThrowsWhenStorageIsBlocked = threw;+sessionStorage.getItem = realGet; sessionStorage.setItem = realSet;+""", extra=EXTRA, shim=consts + "\n" + SESSION_SHIM)++ def test_a_fresh_tab_has_nothing_to_restore(self):+ self.assertEqual(self.r["restoreWithNothingStored"], [0, 0])++ def test_a_real_persist_writes_and_a_repeat_does_not(self):+ self.assertTrue(self.r["storedAfterFirstPersist"])+ self.assertEqual(self.r["setItemCallsAfterFirst"], 1)+ self.assertEqual(self.r["setItemCallsAfterRepeat"], 1) # unchanged — no write+ self.assertEqual(self.r["setItemCallsAfterRealChange"], 2) # changed — writes++ def test_matching_content_restores_the_exact_stack(self):+ n_undo, n_redo, identical = self.r["restoredWhenFingerprintMatches"]+ self.assertEqual(n_undo, 1)+ self.assertEqual(n_redo, 0)+ self.assertTrue(identical)++ def test_a_screen_that_moved_on_gets_nothing_restored(self):+ self.assertEqual(self.r["notRestoredWhenFingerprintDiffers"], [0, 0])++ def test_an_empty_stack_clears_its_own_entry(self):+ self.assertIsNone(self.r["emptyStackClearsTheEntry"])++ def test_a_restored_stack_is_capped(self):+ self.assertLessEqual(self.r["restoredIsCapped"], 80) # SBE_UNDO_MAX++ def test_a_blocked_storage_never_throws(self):+ self.assertFalse(self.r["neverThrowsWhenStorageIsBlocked"])++ def test_it_is_session_scoped_not_local(self):+ # "did I just reload THIS TAB", not "remember my edits across a+ # browser restart days later" — that promise belongs to the+ # crash-backup lane, which already uses a server-side archive.+ fn = extract_function("sbePersistUndo", self.src)+ self.assertIn("sessionStorage", fn)+ self.assertNotIn("localStorage", fn)+ fn = extract_function("sbeRestoreUndoIfFresh", self.src)+ self.assertIn("sessionStorage", fn)+ self.assertNotIn("localStorage", fn)++ def test_restore_only_runs_on_a_genuine_open_not_a_quiet_reread(self):+ fn = extract_function("sbeAdopt", self.src)+ self.assertIn("if (!quiet) sbeRestoreUndoIfFresh();", fn)++ def test_persist_rides_the_ticks_own_clock(self):+ fn = extract_function("sbeTick", self.src)+ self.assertIn("sbePersistUndo()", fn)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_va06_a2v_estimate.py b/test_va06_a2v_estimate.pynew file mode 100644index 0000000..e42fde6--- /dev/null+++ b/test_va06_a2v_estimate.py@@ -0,0 +1,113 @@+"""VA-06 [P1]: A2V showed no time estimate before a 10-25 minute render.++`#audioStudioEstimate` (index.html:3645, roughly) existed in the markup and+nothing wrote to it — Generate, then "Submitted. Watch Now / Recent." with+no price shown anywhere, unlike the Video tab and One Shot which always+price a render first. ltx_a2v_estimate_minutes prices the LANE that+actually runs (Q8 two-stage 20+3 steps vs Q4 distilled 8+3 — the branch in+run_job_inner's `mode == "a2v"` arm) at the real clamped canvas+(tier_max_dim("t2v"), the same clamp the render applies), and GET+/a2v/estimate exposes it the same way /oneshot/estimate and /take/estimate+already price their own modes.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock+from urllib.parse import urlencode++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-va06-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class EstimateMatchesTheLaneThatRuns(unittest.TestCase):+ def test_q4_distilled_when_q8_missing(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_q8": True}), \+ mock.patch.object(P, "hq_surface_missing", lambda: ["some.safetensors"]):+ w, h, minutes, uses_q8 = P.ltx_a2v_estimate_minutes(121)+ self.assertFalse(uses_q8)+ distilled = P.ltx_estimate_minutes(w, h, 121, 8, 3)+ self.assertAlmostEqual(minutes, distilled, delta=0.01)++ def test_q8_two_stage_when_available(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_q8": True}), \+ mock.patch.object(P, "hq_surface_missing", lambda: []):+ w, h, minutes, uses_q8 = P.ltx_a2v_estimate_minutes(121)+ self.assertTrue(uses_q8)+ hq = P.ltx_estimate_minutes(w, h, 121, 20, 3)+ self.assertAlmostEqual(minutes, hq, delta=0.01)+ # Q8's 20+3 must price slower than Q4's 8+3 at the same shape.+ q4 = P.ltx_estimate_minutes(w, h, 121, 8, 3)+ self.assertGreater(minutes, q4)++ def test_falls_back_to_q4_when_q8_disallowed_by_tier(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_q8": False}):+ _, _, _, uses_q8 = P.ltx_a2v_estimate_minutes(121)+ self.assertFalse(uses_q8)++ def test_clamps_to_tier_max_dim_like_the_real_render(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "t2v_max_dim": 768}):+ w, h, _, _ = P.ltx_a2v_estimate_minutes(121, width=1280, height=704)+ self.assertLessEqual(max(w, h), 768)++ def test_longer_duration_prices_higher(self):+ _, _, short, _ = P.ltx_a2v_estimate_minutes(97)+ _, _, long_, _ = P.ltx_a2v_estimate_minutes(241)+ self.assertGreater(long_, short)+++class TheRoute(unittest.TestCase):+ class H:+ def __init__(self):+ self.out = None++ def _json(self, obj, code=200):+ self.out = (code, obj)++ class Parsed:+ def __init__(self, query):+ self.query = query++ def get(self, **qs):+ from panel.routes import GET_ROUTES+ h = self.H()+ GET_ROUTES["/a2v/estimate"](h, self.Parsed(urlencode(qs)))+ return h.out++ def test_route_is_registered(self):+ import panel.routes_queue # noqa: F401+ from panel.routes import GET_ROUTES+ self.assertIn("/a2v/estimate", GET_ROUTES)++ def test_default_frames_and_canvas(self):+ code, body = self.get()+ self.assertEqual(code, 200)+ self.assertTrue(body["ok"])+ self.assertIn("eta", body)+ self.assertIn("minutes", body)+ self.assertIn("pack", body)+ self.assertGreater(body["minutes"], 0)++ def test_explicit_frames_and_canvas_are_honoured(self):+ code, body = self.get(frames=241, width=1024, height=576)+ self.assertEqual(code, 200)+ self.assertEqual(body["width"], 1024)+ self.assertEqual(body["height"], 576)++ def test_garbage_query_does_not_crash(self):+ code, body = self.get(frames="not-a-number", width="also-not")+ self.assertEqual(code, 200)+ self.assertTrue(body["ok"])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_va11_va12_keyframe_extend_honesty.py b/test_va11_va12_keyframe_extend_honesty.pynew file mode 100644index 0000000..afeb211--- /dev/null+++ b/test_va11_va12_keyframe_extend_honesty.py@@ -0,0 +1,132 @@+"""VA-11 [P1] / VA-12 [P2]: FFLF/Keyframe and Extend priced a DIFFERENT+pipeline than the one that actually runs.++Keyframe always renders the Q8 two-stage pass (LTX_HQ_STAGE1/2) regardless+of the selected Quality pill, and clamps its canvas to tier_max_dim+("keyframe") at RUN TIME (mlx_ltx_panel.py's keyframe branch). Before this+fix the Shot setup summary and #derivedFooter showed whatever the Quality+strip's SELECTED cell said — e.g. "Balanced * 5s * 9:16 * ~3 min" for a+448x768 FFLF request that actually rendered Q8 two-stage, clamped to+432x768, at a real ~5 min. Extend similarly showed hardcoded "~16 min" /+"~38 min" pill text and sent 12 steps on "Draft" when the server's own+validated default (owner ruling 2026-05-21) is 8 — 50% slower than what+was supposed to ship.++ltx_keyframe_estimate_minutes / ltx_extend_estimate_minutes /+ltx_mode_price_card give both surfaces ONE real number apiece, computed+from the exact clamp and exact step count run_job_inner uses.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-va11-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class KeyframeEstimateMatchesTheRealClamp(unittest.TestCase):+ def test_clamps_to_the_tier_max_dim(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "keyframe_max_dim": 768}):+ w, h, minutes = P.ltx_keyframe_estimate_minutes(121, width=1280, height=704)+ self.assertLessEqual(max(w, h), 768)+ self.assertGreater(minutes, 0)++ def test_uncapped_tier_passes_the_requested_shape_through(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "keyframe_max_dim": 0}):+ w, h, _ = P.ltx_keyframe_estimate_minutes(121, width=1280, height=704)+ self.assertEqual((w, h), (1280, 704))++ def test_prices_at_hq_two_stage_steps_not_whatever_quality_is_selected(self):+ """The bug: the UI could show a Quick/Balanced (8-step distilled)+ price for a render that always runs LTX_HQ_STAGE1/2. Confirm the+ keyframe estimate is strictly the HQ-step price, by comparing+ against a same-shape distilled estimate."""+ w, h, kf_minutes = P.ltx_keyframe_estimate_minutes(121, width=768, height=432)+ distilled_minutes = P.ltx_estimate_minutes(+ w, h, 121, P.LTX_DISTILLED_STAGE1, P.LTX_DISTILLED_STAGE2)+ hq_minutes = P.ltx_estimate_minutes(w, h, 121, P.LTX_HQ_STAGE1, P.LTX_HQ_STAGE2)+ self.assertAlmostEqual(kf_minutes, hq_minutes, delta=0.01)+ self.assertNotAlmostEqual(kf_minutes, distilled_minutes, delta=0.01)+++class ExtendEstimateMatchesTheRealDefault(unittest.TestCase):+ def test_default_steps_is_eight_not_twelve(self):+ """VA-12: the client used to send 12 on Draft — 50% slower than the+ validated 8-step default. The price function's own default must be+ the validated one, so a caller that forgets `steps=` can't silently+ reintroduce the regression."""+ w, h, eight = P.ltx_extend_estimate_minutes(5)+ _, _, twelve = P.ltx_extend_estimate_minutes(5, steps=12)+ self.assertLess(eight, twelve)++ def test_clamps_to_the_tier_max_dim(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "extend_max_dim": 768}):+ w, h, _ = P.ltx_extend_estimate_minutes(5, steps=8, width=1280, height=704)+ self.assertLessEqual(max(w, h), 768)++ def test_prices_the_delivered_length_not_just_the_added_seconds(self):+ w, h, five_latents = P.ltx_extend_estimate_minutes(5, steps=8)+ _, _, ten_latents = P.ltx_extend_estimate_minutes(10, steps=8)+ self.assertGreater(ten_latents, five_latents)+++class ModePriceCard(unittest.TestCase):+ def test_keyframe_card_is_none_when_tier_disallows_it(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_keyframe": False}):+ self.assertIsNone(P.ltx_mode_price_card("keyframe"))++ def test_extend_card_is_none_when_tier_disallows_it(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_extend": False}):+ self.assertIsNone(P.ltx_mode_price_card("extend"))++ def test_keyframe_card_shape(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_keyframe": True,+ "keyframe_max_dim": 768}):+ card = P.ltx_mode_price_card("keyframe")+ self.assertEqual(card["mode"], "keyframe")+ self.assertIn("width", card)+ self.assertIn("height", card)+ self.assertIn("eta", card)+ self.assertEqual(card["pipeline_note"], "Q8 two-stage")++ def test_extend_card_carries_added_and_total_seconds(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_extend": True,+ "extend_max_dim": 768}):+ draft = P.ltx_mode_price_card("extend", steps=8)+ pro = P.ltx_mode_price_card("extend", steps=30)+ self.assertEqual(draft["steps"], 8)+ self.assertEqual(pro["steps"], 30)+ self.assertGreater(draft["added_seconds"], 0)+ self.assertGreater(draft["total_seconds"], draft["added_seconds"])+ # Pro (more steps, same shape) must never be cheaper than Draft.+ self.assertGreaterEqual(pro["eta_min"], draft["eta_min"])++ def test_unknown_mode_returns_none(self):+ self.assertIsNone(P.ltx_mode_price_card("t2v"))+++class BootAndStatusExposeTheCards(unittest.TestCase):+ def test_boot_payload_has_the_keyframe_and_extend_prices(self):+ page_src = P.page()+ self.assertIn('"keyframe_price"', page_src)+ self.assertIn('"extend_price_draft"', page_src)+ self.assertIn('"extend_price_pro"', page_src)++ def test_routes_queue_exposes_the_same_fields(self):+ import panel.routes_queue as rq+ src = Path(rq.__file__).read_text(encoding="utf-8")+ self.assertIn("ltx_mode_price_card", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_va15_va16_oneshot_honesty.py b/test_va15_va16_oneshot_honesty.pynew file mode 100644index 0000000..d24e8ab--- /dev/null+++ b/test_va15_va16_oneshot_honesty.py@@ -0,0 +1,115 @@+"""VA-15 [P1] / VA-16 [P2]: One Shot's default committed ~28 minutes of GPU+before showing a price, and the price it eventually showed was always the+best case.++VA-15: oneshot.js defaulted to seconds: 60 (6 parts, ~28 min) with no price+in the sticky footer next to Generate — only in the composer card above,+easy to scroll past. VA-16: take_estimate_minutes priced the base render+only; at run time each part can ALSO get one light-drift retake+(_take_retry_seed's caller in mlx_ltx_panel.py's take-part loop) plus, for a+spoken part, up to TAKE_LIPSYNC_RETAKES lip-sync retakes — up to ~4x the+base render — and the copy said only "a part that drifts is rendered once+more", never mentioning lip-sync retakes. Separately: with the form's seed+left on "-1" (random, the default), every retake of every part landed on+the exact same fixed seed (int("-1") + 101 == 100, every time) instead of a+fresh random roll.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock+from urllib.parse import urlencode++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-va1516-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class WorstCaseEstimate(unittest.TestCase):+ def test_worst_is_a_multiple_of_the_base(self):+ base = P.take_estimate_minutes("ltx", "balanced", 60)+ worst = P.take_estimate_minutes_worst("ltx", "balanced", 60)+ self.assertIsNotNone(base)+ self.assertIsNotNone(worst)+ factor = 1 + P.TAKE_LIGHT_DRIFT_RETAKES + P.TAKE_LIPSYNC_RETAKES+ self.assertAlmostEqual(worst, round(base * factor, 1), delta=0.05)++ def test_worst_is_never_smaller_than_base(self):+ base = P.take_estimate_minutes("h3", "standard", 30)+ worst = P.take_estimate_minutes_worst("h3", "standard", 30)+ if base is not None:+ self.assertGreaterEqual(worst, base)++ def test_none_when_base_is_none(self):+ self.assertIsNone(P.take_estimate_minutes_worst("ltx", "balanced", 999999))+++class RouteExposesBoth(unittest.TestCase):+ class H:+ def __init__(self):+ self.out = None++ def _json(self, obj, code=200):+ self.out = (code, obj)++ class Parsed:+ def __init__(self, query):+ self.query = query++ def test_estimate_route_carries_the_worst_case(self):+ from panel.routes import GET_ROUTES+ h = self.H()+ GET_ROUTES["/oneshot/estimate"](h, self.Parsed(urlencode(+ {"engine": "ltx", "quality": "balanced", "seconds": 60})))+ code, body = h.out+ self.assertEqual(code, 200)+ self.assertTrue(body["ok"])+ self.assertIn("minutes_worst", body)+ self.assertIn("eta_worst", body)+ self.assertGreaterEqual(body["minutes_worst"], body["minutes"])+++class RetakeSeedIsRandomWhenTheTakeWasRandom(unittest.TestCase):+ def test_random_seed_stays_random_on_retry(self):+ """The bug: int('-1') never raised, so the deterministic +offset+ branch ran even for a random take, landing every retry on the same+ fixed seed (100, then 210, then 421) regardless of part or install."""+ self.assertEqual(P._take_retry_seed("-1", 101), "-1")+ self.assertEqual(P._take_retry_seed(-1, 101), "-1")+ self.assertEqual(P._take_retry_seed(None, 101), "-1")+ self.assertEqual(P._take_retry_seed("", 211), "-1")++ def test_explicit_seed_still_gets_the_deterministic_offset(self):+ """A user who pinned a seed to reproduce a take must still get a+ reproducible (not colliding) retake seed."""+ self.assertEqual(P._take_retry_seed("7", 101), "108")+ self.assertEqual(P._take_retry_seed("7", 211), "218")+ self.assertEqual(P._take_retry_seed(7, 422), "429")++ def test_garbage_seed_falls_back_to_random(self):+ self.assertEqual(P._take_retry_seed("not-a-number", 101), "-1")++ def test_two_random_retries_no_longer_collide_by_construction(self):+ """Regression pin: the OLD code computed int('-1') + 101 == 100 and+ int('-1') + 211 == 210 — always the same two numbers. The new+ behaviour returns '-1' for both, deferring the actual random draw+ to wherever '-1' is resolved (a fresh roll per render), so the two+ calls are no longer forced to the same fixed values."""+ light_drift_seed = P._take_retry_seed("-1", 101)+ lipsync_seed = P._take_retry_seed("-1", 211)+ self.assertEqual(light_drift_seed, "-1")+ self.assertEqual(lipsync_seed, "-1")+ self.assertNotEqual(light_drift_seed, "100")+ self.assertNotEqual(lipsync_seed, "210")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_vc01_ltx_estimate_honesty.py b/test_vc01_ltx_estimate_honesty.pynew file mode 100644index 0000000..cd8a382--- /dev/null+++ b/test_vc01_ltx_estimate_honesty.py@@ -0,0 +1,218 @@+"""VC-01 [P0]: every LTX estimate skipped the per-chip speed factor.++Pinned by the flow review (2026-09-29, report_video-core.txt VC-01): boot as+a 16 GB "Apple M3" and the Shot setup chips show the SAME "~3 min" the panel+shows on a real M4 Max — because `_build_ltx_tiers` returned the measured+row's raw M4 Max seconds (`hit[0]`) unmultiplied, and the anchored branch's+own `eta_min / model_5s` ratio cancelled the factor out (both sides came+from `ltx_estimate_minutes`, which carried the identical factor). H3's+tiers already multiplied their measured rows by the chip factor+(`_h3_speed_factor`); LTX's never did.++The fix adds three things, all exercised here:+ 1. the chip factor actually reaches both the measured and the anchored+ LTX tier cells (mirrors the fix already proven for H3);+ 2. a low-RAM factor (`_ltx_ram_factor`), the LTX equivalent of+ `_h3_ram_factor`, for Macs LOW_RAM_STREAM pushes onto the+ disk-streamed DiT load;+ 3. per-install self-calibration: a running median of actual/estimate,+ clamped 0.5-3x, folded into `_hw_speed_factor` so it corrects BOTH+ engines' estimates without a second call site.++H3-03 (48 GB M5 Pro Best estimates ~30% low) is pinned alongside: the+table's M5 Pro entry was a fleet bucket shared with M5 Max.+"""+from __future__ import annotations++import json+import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-vc01-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class _Mac:+ """Rebuild the LTX tier table as a given Mac (chip + RAM) would at boot,+ with this install's calibration state isolated to a throwaway file so+ one test's recorded ratios can never leak into another's."""++ def __init__(self, ram_gb: float, chip: str, calib_path: Path | None = None):+ self.ram_gb, self.chip = ram_gb, chip+ self.calib_path = calib_path or Path(+ tempfile.mkdtemp(prefix="phos-vc01-calib-")) / "eta_calibration.json"++ def __enter__(self):+ self.saved = (P.SYSTEM_RAM_GB, P._HW_CHIP_FAMILY,+ os.environ.pop("PHOSPHENE_SPEED_FACTOR", None))+ self._path_patch = mock.patch.object(+ P, "_eta_calibration_path", lambda: self.calib_path)+ self._path_patch.start()+ P.SYSTEM_RAM_GB = self.ram_gb+ P._HW_CHIP_FAMILY = self.chip+ return P._build_ltx_tiers()++ def __exit__(self, *exc):+ self._path_patch.stop()+ P.SYSTEM_RAM_GB, P._HW_CHIP_FAMILY, env = self.saved+ if env is not None:+ os.environ["PHOSPHENE_SPEED_FACTOR"] = env+++class MeasuredAndAnchoredCellsCarryTheChipFactor(unittest.TestCase):+ def test_m3_balanced_5s_is_at_least_4x_the_m4_max_cell(self):+ """The gate the finding itself proposes."""+ with _Mac(64.0, "M4 Max") as t64:+ m4max = t64["balanced_5s"]["eta_min"]+ with _Mac(64.0, "M3") as t3:+ m3 = t3["balanced_5s"]["eta_min"]+ self.assertGreaterEqual(m3, m4max * 4)++ def test_measured_row_scales_with_chip(self):+ """balanced_5s is a MEASURED cell (LTX_MEASURED_ETA) — hit[0] must+ not be returned raw."""+ with _Mac(64.0, "M4 Max") as t64:+ cell64 = t64["balanced_5s"]+ self.assertTrue(cell64["eta_measured"])+ with _Mac(64.0, "M2") as t2: # HW_SPEED_FACTOR_LTX["M2"] == 5.0+ cell2 = t2["balanced_5s"]+ self.assertAlmostEqual(cell2["eta_min"], cell64["eta_min"] * 5.0, delta=0.05)++ def test_anchored_row_scales_with_chip_too(self):+ """10s/20s cells have no direct measurement and are anchored off the+ quality's 5s row — the ratio used to cancel the factor out."""+ with _Mac(64.0, "M4 Max") as t64:+ cell64 = t64.get("balanced_10s") or t64.get("quick_20s")+ key = "balanced_10s" if "balanced_10s" in t64 else "quick_20s"+ self.assertFalse(cell64["eta_measured"])+ with _Mac(64.0, "M1") as t1: # HW_SPEED_FACTOR_LTX["M1"] == 4.2+ cell1 = t1[key]+ self.assertAlmostEqual(cell1["eta_min"], cell64["eta_min"] * 4.2, delta=0.05)++ def test_unknown_chip_is_unchanged_from_before(self):+ with _Mac(64.0, "unknown") as t:+ self.assertGreater(t["balanced_5s"]["eta_min"], 0)+++class LowRamFactor(unittest.TestCase):+ def test_low_ram_mac_prices_slower_than_the_same_chip_at_full_ram(self):+ with _Mac(64.0, "M4 Max") as t64:+ full = t64["balanced_5s"]["eta_min"]+ with _Mac(16.0, "M4 Max") as t16:+ low = t16["balanced_5s"]["eta_min"]+ self.assertAlmostEqual(low, full * P.LTX_LOWRAM_FACTOR, delta=0.05)++ def test_above_the_low_ram_threshold_is_unaffected(self):+ self.assertEqual(P._ltx_ram_factor(ram_gb=48.0), 1.0)+ self.assertEqual(P._ltx_ram_factor(ram_gb=P.LOW_RAM_STREAM_RAM_GB + 1), 1.0)+ self.assertGreater(P._ltx_ram_factor(ram_gb=16.0), 1.0)++ def test_explicit_override_replaces_the_ram_factor_too(self):+ os.environ["PHOSPHENE_SPEED_FACTOR"] = "2.0"+ try:+ self.assertEqual(P._ltx_ram_factor(ram_gb=8.0), 1.0)+ finally:+ del os.environ["PHOSPHENE_SPEED_FACTOR"]+++class SelfCalibration(unittest.TestCase):+ def setUp(self):+ self.calib_dir = Path(tempfile.mkdtemp(prefix="phos-vc01-calib-"))+ self.calib_path = self.calib_dir / "eta_calibration.json"+ self._patch = mock.patch.object(P, "_eta_calibration_path", lambda: self.calib_path)+ self._patch.start()+ self.addCleanup(self._patch.stop)++ def test_no_data_means_no_correction(self):+ self.assertEqual(P._eta_calibration_factor("ltx"), 1.0)++ def test_recording_a_ratio_moves_the_factor(self):+ P._record_eta_calibration("ltx", 2.0)+ self.assertAlmostEqual(P._eta_calibration_factor("ltx"), 2.0, delta=0.001)++ def test_median_of_several_samples(self):+ for r in (1.5, 2.0, 2.5):+ P._record_eta_calibration("ltx", r)+ self.assertAlmostEqual(P._eta_calibration_factor("ltx"), 2.0, delta=0.001)++ def test_clamped_to_half_and_triple(self):+ P._record_eta_calibration("ltx", 0.05)+ self.assertEqual(P._eta_calibration_factor("ltx"), P.ETA_CALIBRATION_MIN)+ P._record_eta_calibration("ltx", 50.0)+ # median of [0.05, 50.0] is ~25, still clamps to the ceiling+ self.assertEqual(P._eta_calibration_factor("ltx"), P.ETA_CALIBRATION_MAX)++ def test_engines_are_independent(self):+ P._record_eta_calibration("ltx", 2.0)+ self.assertEqual(P._eta_calibration_factor("h3"), 1.0)++ def test_oldest_samples_drop_off(self):+ for _ in range(P.ETA_CALIBRATION_SAMPLES_MAX):+ P._record_eta_calibration("ltx", 1.0)+ P._record_eta_calibration("ltx", 3.0)+ data = json.loads(self.calib_path.read_text())+ self.assertEqual(len(data["ltx"]), P.ETA_CALIBRATION_SAMPLES_MAX)+ self.assertIn(3.0, data["ltx"])++ def test_folds_into_hw_speed_factor(self):+ with mock.patch.object(P, "_hw_chip_family", lambda: "M4 Max"):+ before = P._hw_speed_factor("ltx")+ P._record_eta_calibration("ltx", 1.5)+ after = P._hw_speed_factor("ltx")+ self.assertAlmostEqual(after, before * 1.5, delta=0.001)++ def test_explicit_override_skips_calibration_entirely(self):+ P._record_eta_calibration("ltx", 3.0)+ os.environ["PHOSPHENE_SPEED_FACTOR"] = "1.0"+ try:+ self.assertEqual(P._hw_speed_factor("ltx"), 1.0)+ finally:+ del os.environ["PHOSPHENE_SPEED_FACTOR"]++ def test_record_from_job_computes_the_right_ratio(self):+ """A finished balanced/5s job that took exactly 2x the chip-only+ prediction should record a ~2.0 ratio."""+ with mock.patch.object(P, "_hw_chip_family", lambda: "M4 Max"), \+ mock.patch.object(P, "SYSTEM_RAM_GB", 64.0):+ base_min = P.LTX_TIERS["balanced_5s"]["eta_min"] # cal factor 1.0 here+ job = {"status": "done", "elapsed_sec": base_min * 60.0 * 2.0,+ "params": {"engine": "ltx", "quality": "balanced",+ "frames": P.LTX_TIERS["balanced_5s"]["frames"]}}+ P._record_eta_calibration_from_job(job)+ self.assertAlmostEqual(P._eta_calibration_factor("ltx"), 2.0, delta=0.05)++ def test_record_from_job_ignores_unfinished_or_unmapped_jobs(self):+ P._record_eta_calibration_from_job({"status": "failed", "elapsed_sec": 999,+ "params": {"engine": "ltx"}})+ self.assertEqual(P._eta_calibration_factor("ltx"), 1.0)+ P._record_eta_calibration_from_job({"status": "done", "elapsed_sec": 999,+ "params": {"engine": "ltx", "quality": "balanced",+ "frames": 999999}})+ self.assertEqual(P._eta_calibration_factor("ltx"), 1.0)++ def test_record_from_job_never_raises(self):+ P._record_eta_calibration_from_job(None)+ P._record_eta_calibration_from_job({})+ P._record_eta_calibration_from_job({"status": "done"})+++class H3M5ProFactor(unittest.TestCase):+ def test_m5_pro_raised_toward_the_measured_ratio(self):+ """Field data: Best ran ~1.29-1.34x the panel's own estimate at the+ old 0.6 factor, flat across three cells — i.e. the real factor is+ close to 0.6 * 1.3 =~ 0.78. Table now prices closer to that."""+ self.assertGreaterEqual(P.HW_SPEED_FACTOR_H3["M5 Pro"], 0.75)+ self.assertLessEqual(P.HW_SPEED_FACTOR_H3["M5 Pro"], 0.85)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_vc11_quick_honesty.py b/test_vc11_quick_honesty.pynew file mode 100644index 0000000..5b44eb5--- /dev/null+++ b/test_vc11_quick_honesty.py@@ -0,0 +1,73 @@+"""VC-11 [P1]: "Quick" isn't quick at 5s, and its chip claimed to be "The+default" (a claim that belongs to Balanced/5s, the actual default cell).++Pinned by the flow review: LTX_MEASURED_ETA has Quick 5s at 161.8s and+Balanced 5s at 162.5s — 0.7s apart — while Quick also renders a smaller,+non-16:9 canvas (640x448 vs Balanced's 1024x576). The chip's blurb used to+read "The fastest look at the shot. The default -- one full beat." because+"The default" lived in the 5s LENGTH's blurb and got concatenated onto+EVERY quality's blurb at that length, not just the actual default quality+(Balanced).+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-vc11-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class TheDefaultClaimBelongsToOneCell(unittest.TestCase):+ def test_only_the_true_default_cell_says_the_default(self):+ default_key = f"{P.LTX_QUALITY_DEFAULT}_{P.LTX_LENGTH_DEFAULT}"+ for key, cell in P.LTX_TIERS.items():+ with self.subTest(cell=key):+ if key == default_key:+ self.assertIn("The default.", cell["blurb"])+ else:+ self.assertNotIn("The default", cell["blurb"])++ def test_quick_5s_no_longer_claims_to_be_the_default(self):+ self.assertNotIn("The default", P.LTX_TIERS["quick_5s"]["blurb"])++ def test_balanced_5s_is_the_one_that_does(self):+ self.assertTrue(P.LTX_TIERS["balanced_5s"]["blurb"].endswith("The default."))+++class QuickHonestlyNamesItsRealSaving(unittest.TestCase):+ def test_quick_5s_carries_a_no_faster_than_balanced_note(self):+ note = " ".join(P.LTX_TIERS["quick_5s"]["notes"])+ self.assertIn("No faster than Balanced", note)+ self.assertIn("20s", note)++ def test_quick_20s_carries_no_such_note(self):+ """20s is Quick's real saving (Balanced doesn't even offer 20s) —+ the note must not apply there."""+ note = " ".join(P.LTX_TIERS["quick_20s"]["notes"])+ self.assertNotIn("No faster than Balanced", note)++ def test_the_note_is_conditioned_on_the_real_gap_not_hardcoded(self):+ """If Quick's schedule ever gets meaningfully faster than Balanced's+ at 5s again, the note must stop firing — it compares against+ Balanced's OWN measured row, not a fixed string."""+ with_note = " ".join(P.LTX_TIERS["quick_5s"]["notes"])+ self.assertIn("No faster than Balanced", with_note)+ # The comparison key exists and is what the note is conditioned on.+ bal = P.LTX_MEASURED_ETA.get(("ltx25", "balanced", "5s", "q4"))+ quick = P.LTX_MEASURED_ETA.get(("ltx25", "quick", "5s", "q4"))+ self.assertIsNotNone(bal)+ self.assertIsNotNone(quick)+ self.assertGreaterEqual(quick[0], bal[0] * 0.9)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_vc12_tier_modal_honest.py b/test_vc12_tier_modal_honest.pynew file mode 100644index 0000000..e7ea4cf--- /dev/null+++ b/test_vc12_tier_modal_honest.py@@ -0,0 +1,102 @@+"""VC-12 [P1] / SYS-20 [P2]: the Tier modal and the Quality chips priced the+SAME render two different ways and disagreed.++Pinned by the flow review: on a 64 GB Mac the chips said "Balanced ~3, Quick+~3, High ~4, High·720p ~8" while the Tier modal said "Text->video about 8+min, Quick about 2 min, High about 7 min" — because the modal read+CAPABILITIES[tier]["times"], a hand-typed table keyed by RAM TIER only+(oblivious to chip speed, and never updated when the chip-aware cost model+changed underneath it), while the chips read LTX_TIERS (ltx_estimate_minutes++ VC-01's chip factor). SYS-20 is the same bug from the system-flow review,+plus a stray dev instruction line the modal doesn't need to show.++The fix retires CAPABILITIES[...]['times'] / ['quality_times'] entirely and+has BOTH surfaces read from the SAME model: honest_tier_times() for the+modal (panel/routes_queue.py's /status 'tier.times'), ltx_tiers_payload()+for the chips (BOOT.ltx / already covered by test_vc01_*). This suite pins+that the two now agree, and that honest_tier_times reprices with chip speed+(closing the loophole where a RAM-tier-only table could drift again).+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-vc12-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class CapabilitiesNoLongerCarriesAStaticPriceTable(unittest.TestCase):+ def test_times_and_quality_times_are_gone(self):+ for tier, caps in P.CAPABILITIES.items():+ with self.subTest(tier=tier):+ self.assertNotIn("times", caps)+ self.assertNotIn("quality_times", caps)+++class HonestTierTimesAgreesWithTheChips(unittest.TestCase):+ def test_t2v_standard_matches_the_standard_5s_chip(self):+ chip = P._fmt_eta(P.LTX_TIERS["standard_5s"]["eta_min"]).lstrip("~")+ self.assertEqual(P.honest_tier_times()["t2v_standard"], chip)++ def test_t2v_draft_matches_the_quick_5s_chip(self):+ chip = P._fmt_eta(P.LTX_TIERS["quick_5s"]["eta_min"]).lstrip("~")+ self.assertEqual(P.honest_tier_times()["t2v_draft"], chip)++ def test_i2v_prices_identically_to_t2v(self):+ times = P.honest_tier_times()+ self.assertEqual(times["i2v_standard"], times["t2v_standard"])++ def test_high_is_none_when_q8_not_allowed(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_q8": False,+ "allows_keyframe": False,+ "allows_extend": False}):+ times = P.honest_tier_times()+ self.assertIsNone(times["high"])+ self.assertIsNone(times["keyframe"])+ self.assertIsNone(times["extend"])++ def test_keyframe_and_extend_carry_a_real_clamped_canvas(self):+ with mock.patch.object(P, "SYSTEM_CAPS", {**P.SYSTEM_CAPS, "allows_q8": True,+ "allows_keyframe": True,+ "allows_extend": True,+ "keyframe_max_dim": 768,+ "extend_max_dim": 768}):+ times = P.honest_tier_times()+ self.assertIn("768", times["keyframe"])+ self.assertIn("768", times["extend"])++ def test_reprices_with_chip_speed(self):+ """The old bug: a hand-typed table keyed by RAM tier only, blind to+ chip. honest_tier_times reads LTX_TIERS, which test_vc01_* already+ proves is chip-scaled — rebuild it here (LTX_TIERS is a module+ constant fixed at import, like every other tier table) to confirm+ honest_tier_times tracks whatever LTX_TIERS says rather than+ carrying its own second number."""+ with mock.patch.object(P, "LTX_TIERS", {+ **P.LTX_TIERS,+ "standard_5s": {**P.LTX_TIERS["standard_5s"], "eta_min": 40.0},+ }):+ slow = P.honest_tier_times()["t2v_standard"]+ self.assertIn("40", slow)+ self.assertNotEqual(slow, P.honest_tier_times()["t2v_standard"])+++class RouteExposesTheHonestTable(unittest.TestCase):+ def test_status_tier_times_is_honest_tier_times(self):+ import panel.routes_queue as rq+ self.assertIn("P.honest_tier_times()",+ Path(rq.__file__).read_text(encoding="utf-8"))+++if __name__ == "__main__":+ unittest.main()diff --git a/test_video_docs_match_dom.py b/test_video_docs_match_dom.pynew file mode 100644index 0000000..9d51bd9--- /dev/null+++ b/test_video_docs_match_dom.py@@ -0,0 +1,94 @@+"""VC-30: the Video docs describe controls where they actually live.++WHAT THIS GUARDS. webapp/docs/video.md and getting-started.md described a+UI that had moved on:+ - "under Customize -> Export" / "under Customize -> Upscale" - the section+ is called "After the render" (index.html #finishDetails, cz-title "After+ the render"); "Customize" survives only as an internal CSS class name+ (.customize-section) and in code comments, never as a visible label.+ - "Native (default)" for LTX Export - the actual default (set by+ setQuality('balanced') at boot, QUALITY_PRESETS.balanced.upscale) is+ fit_720p, confirmed by the hidden #upscale input's own value="fit_720p".+ - "the action row under the player" - the toolbar is CSS-positioned OVER+ the player (an overlay), not below it.+ - "All / Videos / Photos filter" - missing Audio, a real fourth filter+ (#mainOutputsFilterAudio exists in the DOM).+ - "The switch at the top right of the header" - a specific position claim+ that doesn't hold up across viewports; softened to stop promising a+ corner the switch doesn't reliably occupy.+ - No mention of the Hide icon, which permanently removes a clip from the+ gallery with no UI way back (VC-04's own subject).++This file pins each correction against the real markup, not just against+the new doc text in isolation - so a future rename has to touch both.+"""+from __future__ import annotations++import re+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+DOCS = ROOT / "webapp" / "docs"+HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+VIDEO_MD = (DOCS / "video.md").read_text(encoding="utf-8")+GETTING_STARTED_MD = (DOCS / "getting-started.md").read_text(encoding="utf-8")+++class SectionNamesMatchRealDisclosures(unittest.TestCase):+ def test_after_the_render_is_a_real_cz_title(self):+ self.assertIn('<span class="cz-title">After the render</span>', HTML)++ def test_advanced_is_a_real_cz_title(self):+ self.assertIn('<span class="cz-title">Advanced</span>', HTML)++ def test_docs_no_longer_claim_a_customize_section(self):+ for md, name in ((VIDEO_MD, "video.md"), (GETTING_STARTED_MD, "getting-started.md")):+ self.assertNotIn("Customize", md, f"{name} still claims a 'Customize' section")++ def test_docs_point_export_and_upscale_at_after_the_render(self):+ self.assertIn("After the render** → **Export**", VIDEO_MD)+ self.assertIn("After the render** → **Upscale**", VIDEO_MD)+++class DefaultUpscaleIsFit720p(unittest.TestCase):+ def test_hidden_upscale_input_defaults_to_fit_720p(self):+ m = re.search(r'name="upscale" id="upscale" value="([^"]+)"', HTML)+ self.assertIsNotNone(m)+ self.assertEqual(m.group(1), "fit_720p")++ def test_balanced_preset_upscale_is_fit_720p(self):+ src = (ROOT / "webapp" / "js" / "characters.js").read_text(encoding="utf-8")+ m = re.search(r"balanced:\s*\{[^}]*upscale:\s*'([^']+)'", src)+ self.assertIsNotNone(m)+ self.assertEqual(m.group(1), "fit_720p")++ def test_docs_say_720p_fit_is_the_default_not_native(self):+ self.assertIn("720p fit** (default)", VIDEO_MD)+ self.assertNotIn("Native** (default)", VIDEO_MD)+++class ActionRowIsOverNotUnder(unittest.TestCase):+ def test_docs_say_over_the_player(self):+ self.assertIn("over the player", VIDEO_MD)+ self.assertIn("Over the player", GETTING_STARTED_MD)+ self.assertNotIn("under the player", VIDEO_MD.lower())+ self.assertNotIn("under the player", GETTING_STARTED_MD.lower())+++class AudioFilterIsDocumented(unittest.TestCase):+ def test_audio_filter_exists_in_markup(self):+ self.assertIn('id="mainOutputsFilterAudio"', HTML)++ def test_docs_mention_it(self):+ self.assertIn("Photos / Audio", GETTING_STARTED_MD)+++class HideIconIsDocumented(unittest.TestCase):+ def test_hide_mentioned_in_video_docs(self):+ self.assertIn("Hide", VIDEO_MD)+ self.assertIn("eye icon", VIDEO_MD + GETTING_STARTED_MD)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_video_poster.py b/test_video_poster.pynew file mode 100644index 0000000..69c1ed1--- /dev/null+++ b/test_video_poster.py@@ -0,0 +1,160 @@+#!/usr/bin/env python3+"""FILM-39: a first-frame poster for a video clip, taken from its proxy.++`_ensure_proxy_poster` (Editor filmstrip, FILM-39) mirrors `_ensure_thumbnail` (images) for video, using+ffmpeg instead of PIL since PIL cannot open an mp4. The route+`/storyboard/edit/poster` mirrors `/storyboard/edit/proxy` line for line:+same containment (a basename the server itself minted, resolved under+proxy_dir, never an arbitrary clip path).++Runs real ffmpeg against a synthetic 1-frame clip — not mocked, so a broken+ffmpeg invocation (wrong flags, wrong order) fails this test the same way it+would fail in the field.+"""+from __future__ import annotations++import shutil+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++def _make_clip(path: Path, w: int = 64, h: int = 48, color: str = "red") -> None:+ """One second of a solid colour, real ffmpeg, no mocking."""+ import subprocess+ subprocess.run(+ [str(panel.FFMPEG), "-y", "-loglevel", "error", "-f", "lavfi",+ "-i", f"color=c={color}:s={w}x{h}:d=1:r=1",+ "-pix_fmt", "yuv420p", str(path)],+ check=True, capture_output=True, timeout=30)++[email protected](shutil.which("ffmpeg") or Path(panel.FFMPEG).is_file(),+ "ffmpeg not available in this environment")+class TheCache(unittest.TestCase):+ def test_a_real_frame_is_extracted_and_cached(self):+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(panel, "_POSTER_CACHE", Path(d) / "cache"):+ src = Path(d) / "proxy.mp4"+ _make_clip(src)+ out = panel._ensure_proxy_poster(src, 32)+ self.assertTrue(out.is_file())+ self.assertGreater(out.stat().st_size, 0)+ # A real JPEG, not just a file that happens to exist.+ self.assertEqual(out.read_bytes()[:2], b"\xff\xd8")+ first_mtime = out.stat().st_mtime_ns+ out2 = panel._ensure_proxy_poster(src, 32)+ self.assertEqual(out, out2)+ self.assertEqual(out.stat().st_mtime_ns, first_mtime) # not rewritten++ def test_a_different_source_or_width_is_a_different_file(self):+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(panel, "_POSTER_CACHE", Path(d) / "cache"):+ a = Path(d) / "a.mp4"; _make_clip(a, color="red")+ b = Path(d) / "b.mp4"; _make_clip(b, color="blue")+ out_a = panel._ensure_proxy_poster(a, 32)+ out_b = panel._ensure_proxy_poster(b, 32)+ out_a_wide = panel._ensure_proxy_poster(a, 64)+ self.assertNotEqual(out_a, out_b)+ self.assertNotEqual(out_a, out_a_wide)++ def test_a_source_that_changes_gets_a_new_poster(self):+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(panel, "_POSTER_CACHE", Path(d) / "cache"):+ src = Path(d) / "proxy.mp4"+ _make_clip(src, color="red")+ out1 = panel._ensure_proxy_poster(src, 32)+ import time+ time.sleep(0.01)+ src.unlink()+ _make_clip(src, color="green")+ out2 = panel._ensure_proxy_poster(src, 32)+ self.assertNotEqual(out1, out2)++ def test_a_file_ffmpeg_cannot_read_raises_rather_than_serving_junk(self):+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(panel, "_POSTER_CACHE", Path(d) / "cache"):+ junk = Path(d) / "not-a-video.mp4"+ junk.write_bytes(b"not a real mp4 at all")+ with self.assertRaises(Exception):+ panel._ensure_proxy_poster(junk, 32)++ def test_a_missing_source_raises_file_not_found(self):+ with tempfile.TemporaryDirectory() as d, \+ mock.patch.object(panel, "_POSTER_CACHE", Path(d) / "cache"):+ with self.assertRaises(FileNotFoundError):+ panel._ensure_proxy_poster(Path(d) / "nope.mp4", 32)++[email protected](shutil.which("ffmpeg") or Path(panel.FFMPEG).is_file(),+ "ffmpeg not available in this environment")+class TheRoute(unittest.TestCase):+ """Mirrors test_storyboard_editor_api.py's proxy-route tests exactly —+ same containment, same shape checks — plus one real end-to-end 200."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.state = root / "state"+ self.state.mkdir()+ self._patches = [+ mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "push", lambda *a, **k: None),+ ]+ for p in self._patches:+ p.start()+ self.addCleanup(p.stop)+ board = {"schema": 1, "id": "sb_t", "title": "A Film",+ "created_at": 1_700_000_000, "policy": storyboard.default_policy(),+ "cast": [], "engine_mode": "ltx", "shots": []}+ storyboard.save_storyboard(self.state, board)++ def _get(self, url: str):+ from test_storyboard_editor_api import FakeHandler+ return FakeHandler().get(url)++ def test_a_poster_is_served_as_a_real_jpeg(self):+ import storyboard_editor as sedit+ bdir = storyboard.board_dir(self.state, "sb_t")+ d = sedit.proxy_dir(bdir)+ d.mkdir(parents=True)+ _make_clip(d / "a_1234.mp4")+ h = self._get("/storyboard/edit/poster?id=sb_t&name=a_1234.mp4&w=32")+ self.assertEqual(h.status, 200)+ self.assertEqual(h.headers_sent.get("Content-Type"), "image/jpeg")+ self.assertEqual(h.body[:2], b"\xff\xd8")+ self.assertIn("immutable", h.headers_sent.get("Cache-Control", ""))++ def test_a_missing_proxy_is_404(self):+ h = self._get("/storyboard/edit/poster?id=sb_t&name=nope_1234.mp4")+ self.assertEqual(h.status, 404)+ self.assertEqual(h.body, b"")++ def test_the_name_cannot_escape_the_board_folder(self):+ for name in ("../../../../etc/passwd", "..%2Fx.mp4", "/etc/hosts",+ "sub/dir.mp4", "", "x.mp4x"):+ h = self._get(f"/storyboard/edit/poster?id=sb_t&name={name}")+ self.assertIn(h.status, (400, 404), name)+ self.assertEqual(h.body, b"", name)++ def test_a_broken_proxy_is_404_not_500(self):+ import storyboard_editor as sedit+ bdir = storyboard.board_dir(self.state, "sb_t")+ d = sedit.proxy_dir(bdir)+ d.mkdir(parents=True)+ (d / "broken_1234.mp4").write_bytes(b"not a real video")+ h = self._get("/storyboard/edit/poster?id=sb_t&name=broken_1234.mp4")+ self.assertEqual(h.status, 404)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_view_toasts.py b/test_view_toasts.pynew file mode 100644index 0000000..dd7a838--- /dev/null+++ b/test_view_toasts.py@@ -0,0 +1,102 @@+#!/usr/bin/env python3+"""FILM-57: a toast describing the screen does not outlive the screen.++Reported: "Picture mode —…" appeared over Storyboard after a fast tab+switch. `phosToast` (queue.js) is a shared, global stack with no notion of+which tab asked — and it should stay that way, since most of this file's+100+ toasts (a save failed, a take landed, a render finished) are exactly+as true after a tab switch as before it. Only the handful that describe the+CURRENT ON-SCREEN LAYOUT (Picture/Sound mode, side panels hidden) are wrong+once you have left, so only those go through `sbeViewToast`, tagged and+swept by `sbeSweepViewToasts` on the one signal this file already has for+"the user is leaving" — `sbeSuspend`, called from `workflowSwitch` whenever+the active tab stops being 'editor'.+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function, panel_source # noqa: E402++from test_editor_save_integrity import run # noqa: E402++EXTRA = ("sbeViewToast", "sbeSweepViewToasts", "sbeSoundModeToggle",+ "sbePanelsToggle", "sbeSoundMode", "sbeSoundModeSet")++DOC_SHIM = r"""+// A toast is a plain object carrying a dataset bag and a self-remove, the+// two things sbeViewToast/sbeSweepViewToasts touch — not a real DOM.+const TOASTS = [];+function makeToast() {+ const t = { dataset: {}, removed: false, remove() { t.removed = true; } };+ TOASTS.push(t);+ return t;+}+let TOAST_KIND = null; // last call's opts, for the mode-toggle assertions+function phosToast(msg, opts) { TOAST_KIND = { msg, opts }; return makeToast(); }+global.document = {+ querySelectorAll(sel) {+ if (sel === '.phos-toast[data-sbe-view-toast="1"]') {+ return TOASTS.filter(t => !t.removed && t.dataset.sbeViewToast === '1');+ }+ return [];+ },+ body: { classList: { contains: () => false } },+};+"""+++class TheScopedToast(unittest.TestCase):++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()+ cls.r = run(r"""+const t1 = sbeViewToast('Picture mode — the picture takes the height.', { duration: 4000 });+out.tagged = t1.dataset.sbeViewToast;+const t2 = phosToast('The film could not be assembled.', { kind: 'danger' });+out.untaggedByDefault = t2.dataset.sbeViewToast || null;+out.beforeSweep = TOASTS.filter(t => !t.removed).length;+sbeSweepViewToasts();+out.afterSweep = TOASTS.filter(t => !t.removed).length;+out.taggedRemoved = t1.removed;+out.untaggedSurvives = !t2.removed;+""", extra=EXTRA, shim=DOC_SHIM)++ def test_a_view_toast_is_tagged_and_a_normal_one_is_not(self):+ self.assertEqual(self.r["tagged"], "1")+ self.assertIsNone(self.r["untaggedByDefault"])++ def test_sweeping_removes_only_the_tagged_ones(self):+ self.assertEqual(self.r["beforeSweep"], 2)+ self.assertEqual(self.r["afterSweep"], 1)+ self.assertTrue(self.r["taggedRemoved"])+ self.assertTrue(self.r["untaggedSurvives"])++ def test_the_mode_toggle_and_panels_toggle_use_the_scoped_helper(self):+ fn = extract_function("sbeSoundModeToggle", self.src)+ self.assertIn("sbeViewToast(", fn)+ self.assertNotIn("phosToast(", fn)+ fn = extract_function("sbePanelsToggle", self.src)+ self.assertIn("sbeViewToast(", fn)+ self.assertNotIn("phosToast(", fn)++ def test_leaving_the_editor_sweeps(self):+ fn = extract_function("sbeSuspend", self.src)+ self.assertIn("sbeSweepViewToasts()", fn)+ # sbeSuspend is exactly what workflowSwitch calls the moment the+ # active tab stops being 'editor' — the mechanism this test locks+ # is reached by every ordinary tab switch, not just Storyboard's.+ switch = self.src[self.src.index("function workflowSwitch"):]+ switch = switch[:switch.index("\n}\n")]+ self.assertIn("name !== 'editor'", switch)+ self.assertIn("sbeSuspend()", switch)+++if __name__ == "__main__":+ unittest.main()diff --git a/webapp/docs/audio.md b/webapp/docs/audio.mdindex 0bf9668..0440ef3 100644--- a/webapp/docs/audio.md+++ b/webapp/docs/audio.md@@ -1,16 +1,20 @@-# Audio+# Audio — lip-sync, talking photos, dubbing a songThe Audio tab makes a **video driven by a sound file you bring** — a voice line, a song. The sound steers the picture while it is generated (it is not laid on afterwards), so a mouth moves to the words and motion follows the music. It does not make sound from text; for that, describe the sound in any Video prompt.+This is Phosphene's lip-sync: a picture (optional) and a stretch of audio become one clip whose mouth follows the track — the same idea as a "talking photo" or dubbing a performance to a new soundtrack. There is also a **Lip-sync** chip on the Video tab's mode bar that jumps straight here.+## Making one {#make}-1. Drop the **Audio** — WAV, MP3, M4A or FLAC.-2. Optional: a **Reference image** to open the clip on that frame — a portrait for a talking head. Leave it empty for pure audio-to-video.-3. Write the prompt. **Enhance** rewrites it for the model.-4. Set **Width** and **Height** (default 1024×576), **Audio start** (seconds into the file, e.g. 30 to drive the clip from 0:30) and **Duration** (1–30 s, default 7).-5. **Audio conditioning strength** (0.5–5.0, default 1.0): higher holds the picture to the audio more tightly and leaves it less free.+1. Drop the **Audio** — WAV, MP3, M4A or FLAC. The panel reads its length and defaults Duration to match it.+2. Optional: a **Reference image** to open the clip on that frame — a portrait for a talking head. Leave it empty for pure audio-to-video. A closed-mouth, face-forward picture works best — see the tip below.+3. Write the prompt. **Enhance** rewrites it for the model. Keep it short (under ~40 words) and describe the performance (expression, gesture, breathing) rather than the scene or the sound — a sync sentence is appended automatically.+4. Set **Width** and **Height** (default 1024×576), **Start at** (seconds into the file, e.g. 30 to drive the clip from 0:30) and **Duration** (1–30 s). A start or a window that runs past the end of the file is refused or warned about before you render — that stretch would be silence, and silence is exactly where the mouth freezes.+5. **Audio conditioning strength**: leave it on **Auto** unless the mouth is clearly too loose or too stiff — the two render lanes (Q8 / Q4) read this number differently, and Auto is the only value that is always correct for the Mac you're on.6. **Generate**.-> **Tip** Some seeds do not take — if the mouth does not move, retry with a new seed. A large canvas with a long duration is a very long render; the tab warns you and suggests a smaller size.+> **Tip** If the mouth does not move: (1) start on a closed-mouth, face-forward picture — an open-mouth anchor tends to freeze open, and the panel warns when it detects one; (2) remove "static" / "holds still" / "motionless" language from the prompt — a stillness word freezes the whole scene, mouth included; (3) for a song, try the vocal-only option so the model listens to the voice instead of the full mix. A large canvas with a long duration is a very long render; the tab warns you and suggests a smaller size.++**Continue the song** (on the finished clip's player): starts the next clip on THIS clip's most-closed-mouth frame near its end — not the literal last frame, which is usually mid-syllable — with Start at advanced to match. Chain a whole song this way without a jump cut at every join.-Audio always renders on LTX: on the High (Q8) pipeline when it is installed, otherwise on the fast pipeline.+Audio always renders on LTX: on the High (Q8) pipeline when it is installed, otherwise on the fast Q4 pipeline (also the lane used on Macs under 64 GB).diff --git a/webapp/docs/getting-started.md b/webapp/docs/getting-started.mdindex 8254246..d6a6349 100644--- a/webapp/docs/getting-started.md+++ b/webapp/docs/getting-started.md@@ -18,7 +18,7 @@ The row of tabs at the top of the left column is where you choose what to make.## The engine {#engine}-The switch at the top right of the header chooses which model renders: **LTX** or **Hailuo H3**. They are two different engines with different strengths, not a good one and a spare:+The engine switch in the header chooses which model renders: **LTX** or **Hailuo H3**. They are two different engines with different strengths, not a good one and a spare:- **LTX** — every Video mode, LoRAs and trained characters.- **Hailuo H3** — joint video, dialogue and sound. Text and Image modes.@@ -31,7 +31,7 @@ Everything you generate goes into one queue and renders one job at a time. The p- **Now** — the render in progress, with a live preview of the shot as it forms. **Stop early** (on the preview) asks first, then stops it: *"nothing is saved"*, and the queue carries on with the next job.- **Queue** — the jobs waiting. The × on a card removes it.-- **Recent** — what finished, filtered by All / Videos / Photos.+- **Recent** — what finished, filtered by All / Videos / Photos / Audio.- **Logs** — the render log. See [Reading the log](#docs/troubleshooting/logs).Under the Generate button: **⊞ Batch** pastes many prompts at once and queues them all; **Pause queue** holds the queue (the button then reads **Resume queue**); **Clear** removes every waiting job — the one running carries on.@@ -40,11 +40,11 @@ Under the Generate button: **⊞ Batch** pastes many prompts at once and queuesThe gallery on the right shows what you have made. Click a card to put it on the player.-- **All / Videos / Photos** filter it, and the search box finds outputs by prompt words, model, LoRA, size or seed ([[sc:search.focus]] jumps to it).+- **All / Videos / Photos / Audio** filter it, and the search box finds outputs by prompt words, model, LoRA, size or seed ([[sc:search.focus]] jumps to it).- **Show all** loads older renders than the newest 60.- [[sc:outputs.step]] steps through the gallery, [[sc:player.toggle]] plays and pauses, [[sc:outputs.expand]] expands the player to full screen.-- Under the player, the action row offers what you can do next with that clip: **Extend** it, run **Upscale & Face Fix** on it, send it **To film**, **Animate** a still, see its **Params**.-- The trash button on a card moves the file to the macOS Trash after asking — restore it from Finder if you change your mind. [[sc:outputs.trash]] does the same for the selected output.+- Over the player, the action row offers what you can do next with that clip: **Extend** it, run **Upscale & Face Fix** on it, send it **To film**, **Animate** a still, see its **Params**.+- The eye icon hides a clip from the gallery (there is currently no way to bring it back from the UI — see [Video](#docs/video/more) for the manual restore). The trash button on a card moves the file to the macOS Trash after asking — restore it from Finder if you change your mind. [[sc:outputs.trash]] does the same for the selected output.## Where files go {#files}diff --git a/webapp/docs/troubleshooting.md b/webapp/docs/troubleshooting.mdindex 420069d..dde2fdd 100644--- a/webapp/docs/troubleshooting.md+++ b/webapp/docs/troubleshooting.md@@ -39,6 +39,18 @@ If you updated and the panel still behaves like the old version, it is still run*"the macOS GPU watchdog killed a Metal command buffer"* — macOS itself stopped a GPU task that ran too long. It is a driver-level kill, not a Phosphene bug report. Phosphene retries the prompt encoding at a shorter length for the rest of the session. If it keeps happening, the message links to the GitHub issue where chip, macOS version and the crash log help most.+## A character training run failed {#training-failed}++*"training exited with code 1"* — the trainer stopped before finishing. Check the **Logs** tab for the actual reason: an out-of-memory kill (switch to a Mac with more RAM, or a smaller preset if one exists), a missing LTX-2.3 training download (the Train tab's own preflight card offers it), or a caption-encode timeout on a very long caption. Training under 24 GB always fails — that Mac cannot run it.++## The panel says it's offline {#offline}++*"Phosphene offline"*, and pressing **Generate** does nothing — the panel process isn't answering. Nothing you were typing is lost: the prompt stays as you left it, and the page reconnects and picks the queue back up on its own once the panel is running again. Start it from Pinokio's Phosphene sidebar if it doesn't come back within a few seconds.++## The queue paused itself {#queue-paused}++*"Queue paused: the last N renders failed the same way"* — after three renders in a row fail with the same problem, Phosphene stops burning through the rest of the queue on something a retry can't fix. Fix the cause the message names, then press **Resume**; or **Clear queue** to drop the rest and start over.+## The queue after a restart {#queue-restart}Restarting the panel resumes the queue: a queue that was paused when the panel stopped starts again on its own, and the log says so.diff --git a/webapp/docs/video.md b/webapp/docs/video.mdindex f660c32..338bb62 100644--- a/webapp/docs/video.md+++ b/webapp/docs/video.md@@ -76,6 +76,14 @@ On the fast qualities, a **Speed** row offers **Tuned** or **Fast draft** — aWith a trained character selected the chips become **Q8 Draft** (704×384), **Q8 Pro** (1024×576, *best identity*) and, on LTX-2.5, High and High · 720p. Trained faces hold best on Q8 Pro.+### Sliding windows on LTX {#ltx-windows}++For a clip longer than one pass, **Advanced → Long clips → Windows** renders it as a sequence: one first pass, then one Extend per later window, each continuing the kept tail of the one before. This needs the High add-on (the Q8 model) and a Mac that supports Extend.++**Per-window prompts.** Window 1 is always the main prompt above — there is no separate box for it. Every later window gets its own labelled, timed box ("Window 2 · 0:05–0:09"), built from the real render schedule; a box left blank holds the previous moment. Write the next beat of the action in each one, led by the movement (LTX renders whatever a prompt names first). **Invariants** — what must not change between windows (who is in frame, the light, the lens, the place) — go in the field below the boxes and are re-injected into every later window automatically.++This is the LTX equivalent of H3's [per-window prompts](#windows) — same idea (one prompt per pass so the action doesn't repeat), different engine and a different box layout, since the number of windows and their real timing come from LTX's own window planner rather than a fixed 5-second grid.+## Quality and Length on Hailuo H3 {#h3-quality}| Quality | Size | Notes |@@ -99,7 +107,7 @@ A 10 s or 15 s H3 clip asks every 5-second window for the same prompt, which can### H3 first frame and orientation {#h3-image}-Image mode works on H3 — the picture is the first frame. Under **Customize**, **Orientation** turns the tier's canvas **Portrait** at the same cost.+Image mode works on H3 — the picture is the first frame. The **Orientation** row (top-level, next to the size chips) turns the tier's canvas **Portrait** at the same cost.## Engines side by side {#engines}@@ -118,20 +126,22 @@ Image mode works on H3 — the picture is the first frame. Under **Customize**,After the render, the clip can be resized without cropping.-**On Hailuo H3** (under Customize → **Upscale**):+**On Hailuo H3** (under **After the render** → **Upscale**):- **Native** — as rendered.- **720p fit** / **1080p fit** — scaled to fill the frame. A canvas close to 16:9 (H3 Draft and Standard, LTX Standard) loses a few pixels at the edges instead of getting black bars; one far from it (square, portrait into landscape) is still padded. 720p fit is the default.Below the sizes, **Also run Upscale & Face Fix after the draft** is optional and off by default. When it is ticked, the draft ships as rendered and a second job re-renders it at twice the size with LTX-2.5, keeping the face and the sound; the fixed clip lands next to the draft. It needs the 0.3 GB Upscale adapter, downloaded from the Models window, and takes about the draft's time again.-**On LTX** (under Customize → **Export**): **Native** (default), **720p fit**, or **2×**. When it is not Native, **Method** chooses **Fast** (instant) or **Sharp** (a sharper upscaler, +30–90 s).+**On LTX** (under **After the render** → **Export**): **720p fit** (default), **Native**, or **2×**. When it is not Native, **Method** chooses **Fast** (instant) or **Sharp** (a sharper upscaler, +30–90 s).-Any finished clip can also go through [Upscale & Face Fix](#docs/remix/upscale-face-fix) later — one click under the player.+Any finished clip can also go through [Upscale & Face Fix](#docs/remix/upscale-face-fix) later — one click over the player, in its action overlay.## More controls {#more}- **Seed** — `-1` is random; reuse a seed to get the same take with a changed prompt.- **LoRAs** — the add-ons picker. See [LoRAs](#docs/loras).-- **Orientation** (LTX) — 16:9 or 9:16.-- **Customize** — width × height, duration and frames, and **Open file when done**.+- **Orientation** (LTX) — 16:9, 9:16, 1:1 or 4:5.+- **Advanced** — width × height, duration and frames.+- **After the render** — Export/Upscale, and **Open file when done**.- **⊞ Batch** — paste many prompts and queue them all.+- **Hide** (the eye icon on the player toolbar) — removes a clip from the gallery, with an **Undo** in the toast. The **Hidden (N)** chip in the Outputs filter row shows everything hidden, so a clip hidden by mistake is one click away.diff --git a/webapp/index.html b/webapp/index.htmlindex 6acb453..51ca40c 100644--- a/webapp/index.html+++ b/webapp/index.html@@ -52,21 +52,24 @@<symbol id="ph-scissors" viewBox="0 0 256 256"><circle cx="76" cy="68" r="28" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="76" cy="188" r="28" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96.9" y1="86.6" x2="200" y2="200" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96.9" y1="169.4" x2="200" y2="56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-gear-six" viewBox="0 0 256 256"><circle cx="128" cy="128" r="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M130.05,206.11c-1.34,0-2.69,0-4,0L94,224a104.61,104.61,0,0,1-34.11-19.2l-.12-36c-.71-1.12-1.38-2.25-2-3.41L25.9,147.24a99.15,99.15,0,0,1,0-38.46l31.84-18.1c.65-1.15,1.32-2.29,2-3.41l.16-36A104.58,104.58,0,0,1,94,32l32,17.89c1.34,0,2.69,0,4,0L162,32a104.61,104.61,0,0,1,34.11,19.2l.12,36c.71,1.12,1.38,2.25,2,3.41l31.85,18.14a99.15,99.15,0,0,1,0,38.46l-31.84,18.1c-.65,1.15-1.32,2.29-2,3.41l-.16,36A104.58,104.58,0,0,1,162,224Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-image" viewBox="0 0 256 256"><rect x="32" y="48" width="192" height="160" rx="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="156" cy="100" r="12"/><path d="M147.31,164,173,138.34a8,8,0,0,1,11.31,0L224,178.06" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M32,168.69l54.34-54.35a8,8,0,0,1,11.32,0L191.31,208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>-<symbol id="ph-info-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z"/></symbol>+<symbol id="ph-info-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z" fill="currentColor"/></symbol><symbol id="ph-info" viewBox="0 0 256 256"><circle cx="128" cy="128" r="96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="120 120 128 120 128 172 136 172" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="126" cy="84" r="10" fill="currentColor"/></symbol><symbol id="ph-magnifying-glass" viewBox="0 0 256 256"><circle cx="112" cy="112" r="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="168.57" y1="168.57" x2="224" y2="224" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-book-open" viewBox="0 0 256 256"><path d="M128,88a32,32,0,0,1,32-32h72V200H160a32,32,0,0,0-32,32" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M24,200H96a32,32,0,0,1,32,32V88A32,32,0,0,0,96,56H24Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>-<symbol id="ph-pause-fill" viewBox="0 0 256 256"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></symbol>+<symbol id="ph-pause-fill" viewBox="0 0 256 256"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z" fill="currentColor"/></symbol><symbol id="ph-pencil-simple" viewBox="0 0 256 256"><path d="M92.69,216H48a8,8,0,0,1-8-8V163.31a8,8,0,0,1,2.34-5.65L165.66,34.34a8,8,0,0,1,11.31,0L221.66,79a8,8,0,0,1,0,11.31L98.34,213.66A8,8,0,0,1,92.69,216Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="136" y1="64" x2="192" y2="120" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>-<symbol id="ph-play-fill" viewBox="0 0 256 256"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></symbol>-<symbol id="ph-sparkle-fill" viewBox="0 0 256 256"><path d="M208,144a15.78,15.78,0,0,1-10.42,14.94L146,178l-19,51.62a15.92,15.92,0,0,1-29.88,0L78,178l-51.62-19a15.92,15.92,0,0,1,0-29.88L78,110l19-51.62a15.92,15.92,0,0,1,29.88,0L146,110l51.62,19A15.78,15.78,0,0,1,208,144ZM152,48h16V64a8,8,0,0,0,16,0V48h16a8,8,0,0,0,0-16H184V16a8,8,0,0,0-16,0V32H152a8,8,0,0,0,0,16Zm88,32h-8V72a8,8,0,0,0-16,0v8h-8a8,8,0,0,0,0,16h8v8a8,8,0,0,0,16,0V96h8a8,8,0,0,0,0-16Z"/></symbol>+<!-- FILM-43: "Duplicate this storyboard" — two overlapping rounded+ rectangles, same currentColor-stroke idiom as every other ph- icon here. -->+<symbol id="ph-copy" viewBox="0 0 256 256"><rect x="88" y="88" width="128" height="128" rx="12" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M168,88V56a8,8,0,0,0-8-8H56a8,8,0,0,0-8,8V160a8,8,0,0,0,8,8H88" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>+<symbol id="ph-play-fill" viewBox="0 0 256 256"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z" fill="currentColor"/></symbol>+<symbol id="ph-sparkle-fill" viewBox="0 0 256 256"><path d="M208,144a15.78,15.78,0,0,1-10.42,14.94L146,178l-19,51.62a15.92,15.92,0,0,1-29.88,0L78,178l-51.62-19a15.92,15.92,0,0,1,0-29.88L78,110l19-51.62a15.92,15.92,0,0,1,29.88,0L146,110l51.62,19A15.78,15.78,0,0,1,208,144ZM152,48h16V64a8,8,0,0,0,16,0V48h16a8,8,0,0,0,0-16H184V16a8,8,0,0,0-16,0V32H152a8,8,0,0,0,0,16Zm88,32h-8V72a8,8,0,0,0-16,0v8h-8a8,8,0,0,0,0,16h8v8a8,8,0,0,0,16,0V96h8a8,8,0,0,0,0-16Z" fill="currentColor"/></symbol><symbol id="ph-target" viewBox="0 0 256 256"><line x1="128" y1="128" x2="224" y2="32" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M195.88,60.12a95.88,95.88,0,1,0,18.77,26.49" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M161.94,94.06a48,48,0,1,0,14,31.2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-trash-simple" viewBox="0 0 256 256"><line x1="216" y1="56" x2="40" y2="56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="88" y1="24" x2="168" y2="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M200,56V208a8,8,0,0,1-8,8H64a8,8,0,0,1-8-8V56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>-<symbol id="ph-warning-fill" viewBox="0 0 256 256"><path d="M236.8,188.09,149.35,36.22h0a24.76,24.76,0,0,0-42.7,0L19.2,188.09a23.51,23.51,0,0,0,0,23.72A24.35,24.35,0,0,0,40.55,224h174.9a24.35,24.35,0,0,0,21.33-12.19A23.51,23.51,0,0,0,236.8,188.09ZM120,104a8,8,0,0,1,16,0v40a8,8,0,0,1-16,0Zm8,88a12,12,0,1,1,12-12A12,12,0,0,1,128,192Z"/></symbol>+<symbol id="ph-warning-fill" viewBox="0 0 256 256"><path d="M236.8,188.09,149.35,36.22h0a24.76,24.76,0,0,0-42.7,0L19.2,188.09a23.51,23.51,0,0,0,0,23.72A24.35,24.35,0,0,0,40.55,224h174.9a24.35,24.35,0,0,0,21.33-12.19A23.51,23.51,0,0,0,236.8,188.09ZM120,104a8,8,0,0,1,16,0v40a8,8,0,0,1-16,0Zm8,88a12,12,0,1,1,12-12A12,12,0,0,1,128,192Z" fill="currentColor"/></symbol><symbol id="ph-x" viewBox="0 0 256 256"><line x1="200" y1="56" x2="56" y2="200" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="200" y1="200" x2="56" y2="56" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-x-bold" viewBox="0 0 256 256"><line x1="200" y1="56" x2="56" y2="200" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/><line x1="200" y1="200" x2="56" y2="56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/></symbol><symbol id="ph-x-circle" viewBox="0 0 256 256"><line x1="160" y1="96" x2="96" y2="160" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96" y1="96" x2="160" y2="160" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="128" cy="128" r="96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>-<symbol id="ph-x-circle-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm37.66,130.34a8,8,0,0,1-11.32,11.32L128,139.31l-26.34,26.35a8,8,0,0,1-11.32-11.32L116.69,128,90.34,101.66a8,8,0,0,1,11.32-11.32L128,116.69l26.34-26.35a8,8,0,0,1,11.32,11.32L139.31,128Z"/></symbol>+<symbol id="ph-x-circle-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm37.66,130.34a8,8,0,0,1-11.32,11.32L128,139.31l-26.34,26.35a8,8,0,0,1-11.32-11.32L116.69,128,90.34,101.66a8,8,0,0,1,11.32-11.32L128,116.69l26.34-26.35a8,8,0,0,1,11.32,11.32L139.31,128Z" fill="currentColor"/></symbol><!-- File-kind icons referenced dynamically by agentAttachIcon(); thetree-shake regex doesn't see runtime string concatenation. --><symbol id="ph-paperclip" viewBox="0 0 256 256"><path d="M160,80,76.69,164.69a16,16,0,0,0,22.63,22.62L198.63,86.63a32,32,0,0,0-45.26-45.26L54.06,142.06a48,48,0,0,0,67.88,67.88L204,128" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>@@ -193,7 +196,10 @@<div id="healthPop" hidden role="dialog" aria-label="System health detail"><div class="hc-row" data-pill="tierPill"><span class="hc-label">Tier</span></div><div class="hc-row" data-pill="memPill"><span class="hc-label">Memory</span></div>- <div class="hc-row" data-pill="helperPill"><span class="hc-label">Helper</span></div>+ <!-- SYS-19: "Helper" is the internal subprocess name (mlx_warm_helper.py);+ from a creator's chair this row answers "can I render right now",+ which "Engine" says plainly. -->+ <div class="hc-row" data-pill="helperPill"><span class="hc-label">Engine</span></div><div class="hc-row" data-pill="modelsPill"><span class="hc-label">Models</span></div><div class="hc-row" data-pill="comfyPill"><span class="hc-label">ComfyUI</span></div><div class="hc-row" data-pill="queuePill"><span class="hc-label">Queue</span></div>@@ -202,7 +208,7 @@<span id="tierPill" class="pill" style="cursor:pointer" onclick="openTierModal()" title="Click to see what this Mac can do">click for system info</span><span id="memPill" class="pill">memory…</span><span id="comfyPill" class="pill" style="display:none">comfy…</span>- <span id="helperPill" class="pill">helper…</span>+ <span id="helperPill" class="pill">engine…</span><!-- Models pill: shows roll-up status (X / Y models ready) and click-opensa modal with per-repo download buttons. Color reflects readiness:pill-good = all models present, pill-warn = base ready but Q8 missing,@@ -231,7 +237,11 @@pre-filled GitHub issue (URL-built client-side, no auth). Sits beforethe settings cog so it's where the user looks first when somethingfeels off. -->- <button id="bugBtn" class="icon-btn bug-btn" onclick="openBugModal()" title="Report a bug — opens GitHub issue with environment pre-filled">+ <!-- SYS-25: icon-only buttons had `title` (hover/focus tooltip, set+ lazily by tips.js) but no `aria-label`, so a screen reader announced+ them as unlabeled until tips.js happened to fire. Static labels+ here are read immediately, every time. -->+ <button id="bugBtn" class="icon-btn bug-btn" onclick="openBugModal()" aria-label="Report a bug" title="Report a bug — opens GitHub issue with environment pre-filled"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2l1.88 1.88"></path><path d="M14.12 3.88L16 2"></path>@@ -249,7 +259,7 @@<!-- Settings cog: opens the modal that lets users pick output codecpresets (Standard / Video production / Web / Custom). Sits between theruntime pills and Stop Comfy so it's findable but not loud. -->- <button id="settingsBtn" class="icon-btn" onclick="openSettingsModal()" title="Output settings — codec, file size">+ <button id="settingsBtn" class="icon-btn" onclick="openSettingsModal()" aria-label="Settings" title="Settings — models, rendering, output, accounts"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>@@ -276,11 +286,11 @@prompt: no badge, no pulse, no counter. --><a class="icon-btn star-link" id="starLink"href="https://github.com/mrbizarro/phosphene" target="_blank" rel="noopener"- title="Star Phosphene on GitHub — it is how people find it">+ aria-label="Star Phosphene on GitHub" title="Star Phosphene on GitHub — it is how people find it"><svg class="ph" aria-hidden="true"><use href="#ph-star"/></svg></a><a class="phosphene-x-link" href="https://x.com/PhospheneAI" target="_blank" rel="noopener"- title="Follow @PhospheneAI on X — the official Phosphene account">+ aria-label="Follow @PhospheneAI on X" title="Follow @PhospheneAI on X — the official Phosphene account"><svg class="ph" aria-hidden="true"><use href="#ph-x-brand"/></svg></a><a class="creator-link" href="https://x.com/AIBizarrothe" target="_blank" rel="noopener" title="Follow Mr. Bizarro on X (the panel's creator)">@@ -299,26 +309,31 @@(pick a trained character + scene + ship), Train (train newcharacter LoRAs). Default = manual; the choice persists inlocalStorage so the user lands on the same tab next session. -->- <nav class="workflow-tabs" id="workflowTabs">- <button data-workflow="manual" class="active"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-film-strip"/></svg>Video</button>+ <!-- SYS-25, accessibility: this was a plain row of <button>s — 0+ role=tablist, 0 role=tab, 0 aria-selected anywhere on the page.+ A screen reader had no way to know this was a tab strip, which+ tab was active, or how many there were. workflowSwitch()+ (editor.js) keeps aria-selected in sync with .active. -->+ <nav class="workflow-tabs" id="workflowTabs" role="tablist" aria-label="Workflow">+ <button data-workflow="manual" class="active" role="tab" aria-selected="true"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-film-strip"/></svg>Video</button><!-- One Shot is its own door (2026-09-08): one continuous shot of 30 s – 2 min,with its own composer and its own API (POST /oneshot). It was a mode chipon the video form; a shot that never cuts is a different thing to makethan a clip, and it gets the tab. -->- <button data-workflow="oneshot"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-target"/></svg>One Shot</button>- <button data-workflow="studio"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-image"/></svg>Images</button>+ <button data-workflow="oneshot" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-target"/></svg>One Shot</button>+ <button data-workflow="studio" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-image"/></svg>Images</button><!-- Storyboard sits next to the video surfaces; Audio and Train are thetwo "go elsewhere and come back" tabs. No NEW badge on purpose —with no film in progress the panel must look exactly as it didyesterday, plus one calm word. The count span is filled only whilea storyboard render is actually in flight. -->- <button data-workflow="storyboard"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-film-slate"/></svg>Storyboard<span class="new-badge sb-live" id="sbTabCount" hidden></span></button>+ <button data-workflow="storyboard" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-film-slate"/></svg>Storyboard<span class="new-badge sb-live" id="sbTabCount" hidden></span></button><!-- The Editor is a PLACE, not a room inside the Storyboard. It openswith no board, on clips from any engine, and it stays open whileyou go and look at something else. -->- <button data-workflow="editor"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-scissors"/></svg>Editor</button>- <button data-workflow="audio"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-music-notes"/></svg>Audio<span class="new-badge">NEW</span></button>- <button data-workflow="train"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-user-plus"/></svg>Train Character</button>+ <button data-workflow="editor" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-scissors"/></svg>Editor</button>+ <button data-workflow="audio" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-music-notes"/></svg>Audio<span class="new-badge">NEW</span></button>+ <button data-workflow="train" role="tab" aria-selected="false"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-user-plus"/></svg>Train Character</button></nav><!-- The original manual form is unchanged; it sits below in the DOMand is shown/hidden by JS as the workflow tab toggles. -->@@ -346,6 +361,18 @@<a class="models-inline-link" onclick="openModelsModal()">Manage all models →</a></div>+ <!-- SYS-16 (priority item): "no first-run path" -- a fresh 8 GB Mac and+ a 64 GB Studio saw the same empty prompt and placeholder, no example,+ no sample output. Shown when BOOT.first_run is true (server-computed+ from the SAME flag render_completed's first_render prop uses — "has+ this install ever finished a render"), hidden the moment poll() sees+ the first done history entry (renderFirstRunCard, boot.js), or on+ manual dismiss (persisted in panel_settings, same one-shot shape as+ the models-card dismissal). Lives OUTSIDE #genForm for the same+ reason modelsInline does: visible across the video-form <-> Studio+ swap is irrelevant here (Studio isn't the first thing to try), so it+ is hidden there in JS instead. -->+<!-- Mode bar — segmented chip strip. Lifted OUT of #genForm so itstays visible when the user switches to Image Studio (which hides#genForm). Without this, once a user clicks Studio they had no@@ -354,7 +381,14 @@FormData picks it up. The element keeps id=modeGroup and eachchip keeps data-mode + .pill-btn (alongside .mode-chip) so theexisting setMode() click wiring keeps working unchanged. -->- <div class="mode-bar pill-group" id="modeGroup">+ <!-- SYS-25: tab semantics finished here via a MutationObserver+ (main.js, _wireModeGroupTabSemantics) rather than editing each of+ the ~6 places that toggle .active on these chips (boot.js,+ characters.js, engines.js, settings.js -- multiple packages'+ territory in this same mega-ship pass) — role=tab ++ aria-selected stay correct no matter which call site changes+ .active, with zero changes to that shared toggle logic. -->+ <div class="mode-bar pill-group" id="modeGroup" role="tablist" aria-label="Mode"><button type="button" class="mode-chip pill-btn" data-mode="t2v">Text<span class="mc-sub sub">prompt → video</span></button><!-- Character intent — Codex C+ 2026-05-17. Promoted from a chipstrip inside T2V to a first-class mode pill so the cascade@@ -363,11 +397,24 @@toggle inside another mode. Q8-only — hidden on cap_tier="q4". --><button type="button" class="mode-chip pill-btn" data-mode="character">Character<span class="mc-sub sub">trained face + voice</span></button><button type="button" class="mode-chip pill-btn" data-mode="i2v">Image<span class="mc-sub sub">image + prompt</span></button>- <button type="button" class="mode-chip pill-btn" data-mode="keyframe">FFLF<span class="mc-sub sub">first + last</span></button>+ <!-- VA-33: renamed from "FFLF" — creator words, and distinct from the+ in-form "FFLF / Multi-Keyframe" toggle these chips duplicate+ (that toggle stays: it's the only way to change the keyframe+ COUNT once inside the section, not just enter it). -->+ <button type="button" class="mode-chip pill-btn" data-mode="keyframe" title="First-frame / last-frame interpolation (FFLF)">Start & end frame<span class="mc-sub sub">first + last</span></button><!-- Multi-keyframe shares backend mode="keyframe"; the form dropdownchooses any total anchor count from 3–8. --><button type="button" class="mode-chip pill-btn" data-mode="keyframe" data-kf-default="multi">Keyframes<span class="mc-sub sub">3–8 frames</span></button><button type="button" class="mode-chip pill-btn" data-mode="extend">Extend<span class="mc-sub sub">continue a clip</span></button>+ <!-- VA-01: lip-sync's only entrance used to be Audio tab → Music video+ → a folded "One shot (audio → video)" row that shared its name+ with the unrelated One Shot tab — nothing on the Video mode bar+ ever said "lip-sync", "talking" or "dub". This chip does not set+ a #genForm mode (data-mode intentionally absent); the click+ delegate below special-cases data-lipsync and calls+ openLipSyncEntry(), which jumps to the Audio tab's one-shot form+ (its own submit path — audioStudioGenerate, mode=a2v). -->+ <button type="button" class="mode-chip pill-btn" data-lipsync="1" title="Audio → Video — a picture (optional) and a stretch of audio become one clip whose mouth follows the track.">Lip-sync<span class="mc-sub sub">picture + your audio → it talks / sings</span></button><!-- Remix — the IC-LoRA reference tools (Ingredients / Control / Colorize)grouped under ONE pill so the mode bar stays uncluttered. All threerun on Q4 distilled (unlike FFLF/Extend/Character, which are Q8-only@@ -421,6 +468,23 @@</div><form id="genForm">+ <!-- SYS-16's first-run card lives INSIDE #genForm (4.17 integration):+ the sticky Generate footer can only stick within its own form, so a+ card above the form pushed the form's top down far enough that at+ 1366x768 / 1280x800 Generate sat under the Now pane on a first run. -->+ <div id="firstRunCard" class="first-run-card" style="display:none">+ <button type="button" class="first-run-dismiss" id="firstRunDismiss"+ title="Hide this card" aria-label="Hide this card"+ onclick="dismissFirstRunCard()"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>+ <div class="ttl">Make your first clip</div>+ <div class="sub">One click renders a starter clip at Balanced, the size this Mac handles best<span id="firstRunEta"></span>.</div>+ <div class="first-run-prompts" id="firstRunPrompts">+ <button type="button" class="first-run-prompt-btn" onclick="useFirstRunPrompt(this)" data-first-run-prompt="A lit candle on a windowsill at night, flame flickering gently · soft crackle, quiet room tone">A candle flickering at night</button>+ <button type="button" class="first-run-prompt-btn" onclick="useFirstRunPrompt(this)" data-first-run-prompt="Rain falling on a café window, blurred city lights beyond the glass · steady rain, distant traffic hum">Rain on a café window</button>+ <button type="button" class="first-run-prompt-btn" onclick="useFirstRunPrompt(this)" data-first-run-prompt="A cat stretching on a sunlit wooden floor, dust motes drifting in the light · quiet purring, a floorboard creak">A cat stretching in sunlight</button>+ </div>+ <a href="#" class="first-run-sample-link" onclick="downloadSampleCharacter(); return false;">Or get the sample character (Bizarro) →</a>+ </div><input type="hidden" name="preset_label" id="preset_label" value=""><input type="hidden" name="mode" id="mode" value="t2v"><input type="hidden" name="quality" id="quality" value="balanced">@@ -540,10 +604,21 @@<div class="hint">PNG / JPG / WEBP — auto cover-crop to model size</div></div><img class="picker-preview" id="picker_preview_image" alt="" style="display:none">+ <!-- VC-29/H3-01: the crop overlay this Mac will actually+ apply before the render — filled in by+ refreshPickerCropOverlays() (queue.js). Empty/hidden+ until an image is loaded AND a crop would actually+ happen. -->+ <div class="crop-overlay" id="picker_crop_image" hidden></div><button type="button" class="picker-clear" id="picker_clear_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button></div><input type="file" id="picker_file_image" accept="image/*" style="display:none"><input type="hidden" name="image" id="image" value="">+ <!-- Where the crop-preview overlay was set: 0..1 along+ whichever axis the cover-crop cuts. 0.5 = centre (the old,+ still default, behaviour). -->+ <input type="hidden" name="image_crop_focus" id="image_crop_focus" value="0.5">+ <div class="crop-overlay-controls" id="picker_crop_controls_image" hidden></div><div class="picker-recent" id="picker_recent_image_wrap" style="display:none"><div class="picker-recent-label">Recent uploads · click to use</div><div class="picker-recent-strip" id="picker_recent_image"></div>@@ -583,7 +658,7 @@<span class="kf-toggle-label">Keyframe mode</span><div class="kf-toggle-group pill-group" role="group"><button type="button" class="kf-toggle-chip pill-btn active" data-kf-mode="2" onclick="setKeyframeMode(2)">FFLF <span class="kf-sub">start → end</span></button>- <button type="button" class="kf-toggle-chip pill-btn" data-kf-mode="multi" onclick="setKeyframeMode(parseInt(document.getElementById('keyframe_count')?.value || '6', 10))">Multi-Keyframe <span class="kf-sub">3–8 frames</span></button>+ <button type="button" class="kf-toggle-chip pill-btn" data-kf-mode="multi" onclick="setKeyframeMode(parseInt(document.getElementById('keyframe_count')?.value || '3', 10))">Multi-Keyframe <span class="kf-sub">3–8 frames</span></button></div></div>@@ -610,10 +685,10 @@<div class="kf-count-row" id="kfCountRow" style="display:none"><label class="lbl" for="keyframe_count">Keyframes</label><select id="keyframe_count" name="keyframe_count" onchange="setKeyframeMode(parseInt(this.value, 10))">- <option value="3">3 keyframes</option>+ <option value="3" selected>3 keyframes</option><option value="4">4 keyframes</option><option value="5">5 keyframes</option>- <option value="6" selected>6 keyframes</option>+ <option value="6">6 keyframes</option><option value="7">7 keyframes</option><option value="8">8 keyframes</option></select>@@ -648,7 +723,7 @@</div></div>- <div class="hint" id="keyframeHint" style="margin-top:8px">Keyframe mode needs Q8 (auto-selects High quality). FFLF anchors the first and last frames; multi-keyframe mode locks every intermediate beat at its At(s) time.</div>+ <div class="hint" id="keyframeHint" style="margin-top:8px">Keyframe mode needs Q8 — it always renders the Q8 two-stage pass, whatever the Quality pill says. FFLF anchors the first and last frames; multi-keyframe mode locks every intermediate beat at its At(s) time.</div></div><!-- Extend — source-video select + extend-by + direction +@@ -656,6 +731,12 @@prompt sits below the source picker, mirroring the I2V flow. --><div class="mode-only" id="extendSection"><h2>Source video</h2>+ <!-- VA-13: the clamp used to be a log line nobody saw until the+ 6-16 min render finished softer than the clip it extended.+ extendClampNote is filled by refreshExtendClampNote() (from+ BOOT.tier.extend_max_dim) on boot and on every mode switch+ into Extend, so it's said BEFORE Generate every time. -->+ <div class="hint" id="extendClampNote" style="margin-bottom:6px"></div><select id="extendSrcSelect" onchange="document.getElementById('video_path').value=this.value"></select><input name="video_path" id="video_path" placeholder="/path/to/source.mp4" style="margin-top:6px"><div class="row" style="margin-top:8px">@@ -670,7 +751,7 @@value=2 is valid. --><input id="extend_seconds" type="number" value="2" min="0.5" max="10" step="0.5"><input type="hidden" name="extend_frames" id="extend_frames" value="6">- <div class="hint" id="extendDurationHint" style="margin-top:4px">≈ 2.0 s of new content (6 latent frames × 8 video frames at 24 fps)</div>+ <div class="hint" id="extendDurationHint" style="margin-top:4px" title="6 latent frames × 8 video frames at 24 fps">Adds 2.0 s</div></div><div><label class="lbl">Direction</label>@@ -689,21 +770,36 @@visually clear both intents live in the Q8 family withoutforcing the implementation onto the HQ sampler. --><label class="lbl" style="margin-top:10px">Quality</label>+ <!-- VA-12: the "N steps · ~M min" text below is the pre-JS+ fallback only — applyExtendPillPrices() (characters.js)+ overwrites both spans from the server's real, clamped-canvas+ price the moment BOOT is available, and again on every mode+ switch. Static fallback values must still be the REAL+ defaults (8 steps, not the old 12 this pill used to submit —+ see setExtendMode). --><div class="pill-group cols-2 quality-strip" id="extendModeGroup"><button type="button" class="pill-btn pill-quality active" data-extend-mode="fast"><span class="ql-name">Q8 Draft</span>- <span class="q-spec ql-spec sub">12 steps · 64 GB safe</span>- <span class="ql-tier">Q8 extend · ~16 min</span>+ <span class="q-spec ql-spec sub">8 steps · 64 GB safe</span>+ <span class="ql-tier">Q8 extend · pricing…</span></button>- <button type="button" class="pill-btn pill-quality" data-extend-mode="quality">+ <button type="button" class="pill-btn pill-quality" data-extend-mode="quality" hidden><span class="ql-name">Q8 Pro</span><span class="q-spec ql-spec sub">30 steps · 96+ GB</span>- <span class="ql-tier">Q8 extend · ~38 min · reference</span>+ <span class="ql-tier">Q8 extend · pricing…</span></button></div>- <input type="hidden" name="extend_steps" id="extend_steps" value="12">+ <input type="hidden" name="extend_steps" id="extend_steps" value="8"><input type="hidden" name="extend_cfg" id="extend_cfg" value="1.0">- <div class="hint">Each latent ≈ 8 frames (~0.33s). Q8 Pro runs the upstream Lightricks defaults but pushes 1280×704 into swap on 64 GB Macs (~2 hr/render). Stick with Q8 Draft unless you've got more RAM.</div>+ <div class="hint">Each latent ≈ 8 frames (~0.33s). Q8 Pro runs the upstream Lightricks defaults but pushes 1280×704 into swap below the Roomy tier — it only appears there. Stick with Q8 Draft unless you've got more RAM.</div>+ <!-- VA-13: Extend clamps to this Mac's tier cap and hands back+ whatever it renders at, softer than the source it extended+ into. This queues the fix behind it instead of leaving the+ user to notice and do it by hand. -->+ <label class="check" style="margin-top:8px">+ <input type="checkbox" name="extend_face_fix_after" id="extendFaceFixAfter" value="1">+ Also run Upscale & Face Fix after+ </label></div><!-- Colorize (restore) — source-video picker, cloned from the@@ -844,9 +940,68 @@announces "this is where you compose"). Audio-cue placeholderis the only nudge users get to describe the soundscape;documented in the LTX 2.3 paper but unobvious. -->+ <!-- SYS-25: had no label at all (placeholder only) — a screen+ reader announces a placeholder-only textarea as unlabeled. --><textarea name="prompt" id="prompt" class="composer-prompt"+ oninput="updateLangHint()" aria-label="Describe your shot"placeholder="Describe the scene AND the sound — e.g. wizard in a forest clearing, fireflies spiraling up · low whispered chant, ember crackle, distant owl. Audio is generated jointly with video; without sound cues the model outputs near-silent ambient."></textarea>+ <!-- VC-13: a language hint — LTX itself was trained on English+ prompts, and nothing told a non-English typist that. Hidden+ until updateLangHint() sees a non-Latin script (CJK, Hangul,+ Cyrillic, Arabic, Hebrew, Thai — see prompt_looks_non_latin()+ server-side); European Latin-script languages don't trigger+ it (unreliable to tell apart from English by character range+ alone). The toggle feeds Enhance's `translate` form field. -->+ <div class="lang-hint" id="langHint" hidden data-ltx-only>+ <span>LTX generates from English prompts. Enhance can translate this one for you.</span>+ <label class="lang-hint-toggle">+ <input type="checkbox" id="translateToEnglish" checked>+ Translate to English+ </label>+ </div>++ <!-- H3-07: H3's dialogue-tag prompt format has no help in the Video+ tab at all — a line written as prose quotes (`She says: "..."`)+ leaves H3's voice switched off with no error, and the fix+ (docs/H3_ENGINE.md "Dialogue on H3") is unobvious: the words go+ in `<d>[English] …</d>` and nowhere else, at most ~8 words per+ 5 s window, and the sentence must stop the mouth in the same+ breath ("his jaw ceases speaking motion and his mouth settles+ closed"). Structure inserts the three-field skeleton the+ Storyboard planner already writes; + Line inserts one dialogue+ line with the tag, a speaker id and the mouth-stop clause place-+ holder; the counter and the quote warning read the live prompt+ text on every keystroke (h3SyncPromptHelper, queue.js). -->+ <div class="h3-prompt-helper" id="h3PromptHelper" data-h3-only hidden>+ <button type="button" class="ghost-btn" id="h3StructureBtn"+ onclick="h3InsertPromptStructure()"+ title="Insert the three-field skeleton H3 prompts are trained on: integrated_multimodal_description / overall_soundscape / non_diegetic_music.">+ Structure+ </button>+ <button type="button" class="ghost-btn" id="h3AddLineBtn"+ onclick="h3InsertDialogueLine()"+ title="Insert one dialogue line: the <d>…</d> tag, a speaker id, and a mouth-stop clause so the model doesn't keep the mouth moving on nothing.">+ + Line+ </button>+ <select id="h3DialogueLang" title="Language the next inserted line is tagged with" style="max-width:120px">+ <option value="English" selected>English</option>+ <option value="Spanish">Spanish</option>+ <option value="French">French</option>+ <option value="German">German</option>+ <option value="Japanese">Japanese</option>+ <option value="Mandarin Chinese">Mandarin</option>+ <option value="Korean">Korean</option>+ <option value="Portuguese">Portuguese</option>+ </select>+ <span class="ct-spacer"></span>+ <span class="h3-prompt-helper-words" id="h3DialogueWordCount" hidden></span>+ <span class="h3-prompt-helper-warn" id="h3QuoteWarning" hidden+ title="Prose quotes are not spoken — H3 only voices text inside a <d>…</d> tag.">+ <svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>Quoted speech outside <d>…</d> won't be spoken+ </span>+ </div>+<!-- Tools strip — Enhance + HDR + No-music + Avoid disclosure.All inline so they read as part of composing the prompt.Avoid is now a toggle-disclosure (collapsed by default) — it's@@ -859,7 +1014,13 @@and the three labelled fields, and a rewrite strips every one ofthem (H3_PROMPTING_GUIDE §4.1, minimax-prompting SKILL.md). H3prompts go to the encoder verbatim. -->- <button type="button" class="ghost-btn" id="enhanceBtn" data-ltx-only onclick="enhancePrompt()" title="Use Gemma to rewrite your prompt in the style LTX 2.3 was trained on"><svg class="ph" aria-hidden="true" style="margin-right:6px"><use href="#ph-sparkle-fill"/></svg>Enhance</button>+ <!-- SYS-21: tooltip said "LTX 2.3" while the default/active engine+ has been LTX 2.5 since v4.0. -->+ <!-- VC-16: the title used to hardcode "LTX 2.3" — the panel has+ served 2.5 as the default generation since v4.0.0. Left+ generation-neutral here; main.js sets the precise "2.3" or+ "2.5" from BOOT.ltx.generation at boot. -->+ <button type="button" class="ghost-btn" id="enhanceBtn" data-ltx-only onclick="enhancePrompt()" title="Use Gemma to rewrite your prompt in the style LTX was trained on"><svg class="ph" aria-hidden="true" style="margin-right:6px"><use href="#ph-sparkle-fill"/></svg>Enhance</button><!-- Avoid is data-ltx-only because H3 HAS NO NEGATIVE PROMPT. It isguidance-distilled: no CFG, no unconditional branch, one forwardper step, and every official ComfyUI template ships zero@@ -942,6 +1103,31 @@<span id="noVoiceLabel">No voice</span></label></div>++ <!-- VC-16: Enhance's result, inline — replaces the old native+ confirm() (no edit, no diff, no undo). Two states, one panel:+ "review" (the fresh enhanced text, Accept / Keep mine) and+ "applied" (Accept was clicked — Undo reverts the textarea to+ the original, in case ⌘Z inside the textarea itself doesn't+ reach back far enough). Filled/shown by enhancePrompt(). -->+ <div class="enhance-panel" id="enhancePanel" hidden>+ <div class="enhance-panel-body" id="enhancePanelReview">+ <div class="enhance-panel-col">+ <div class="enhance-panel-label">Original</div>+ <div class="enhance-panel-text" id="enhanceOriginalText"></div>+ </div>+ <div class="enhance-panel-col">+ <div class="enhance-panel-label">Enhanced</div>+ <div class="enhance-panel-text" id="enhanceEnhancedText"></div>+ </div>+ </div>+ <div class="enhance-panel-actions">+ <button type="button" class="primary" id="enhanceAcceptBtn" onclick="acceptEnhance()">Accept</button>+ <button type="button" class="ghost-btn" id="enhanceKeepBtn" onclick="keepMineEnhance()">Keep mine</button>+ <button type="button" class="ghost-btn" id="enhanceUndoBtn" onclick="undoEnhance()" hidden>Undo</button>+ <span class="enhance-panel-note" id="enhancePanelNote"></span>+ </div>+ </div></div><!-- Avoid (negative prompt) — collapsed by default; toggled by the@@ -953,6 +1139,17 @@<span>Avoid</span><span class="avoid-hint">things the model should NOT generate — applies on High, Extend, first-last-frame and audio-to-video; Quick, Balanced and Standard run without guidance and ignore it</span></label>+ <!-- VC-15: the hint above SAYS Balanced ignores this box, but nothing+ on the box itself showed it — a typed Avoid line just silently+ did nothing on the default quality. updateIgnoredAvoidNote()+ (queue.js, called from updateDerived) dims the textarea and+ shows this note whenever the CURRENT mode+quality won't read+ negative_prompt at all; "Use High" jumps straight to the+ quality that will. -->+ <div class="avoid-ignored-note" id="avoidIgnoredNote" hidden>+ Ignored at <span id="avoidIgnoredQuality">this quality</span> —+ <a href="#" onclick="setQuality('high'); return false;">Use High</a>+ </div><textarea class="avoid-textarea" name="negative_prompt" id="negative_prompt" placeholder="blurry hands, distorted fingers, extra fingers, smeared face, warped text"></textarea></div>@@ -1118,17 +1315,20 @@folded in here (Fast replaces it). Rendered by renderH3Turbo();writes #h3_tristep. --><div class="h3-speed" id="h3SpeedRow" data-h3-only hidden>+ <!-- H3-40: this used to read "Fast = 3 steps · Best = full+ steps" — the mechanism, not the trade-off a user is+ actually choosing between. --><div class="qs-label"><span class="qs-name">Speed</span>- <span class="qs-meta">Fast = 3 steps · Best = full steps</span>+ <span class="qs-meta">Fast: ~4× quicker, a touch softer · Best: sharpest faces, much slower</span></div><div class="pill-group cols-2 h3-speed-group" id="h3SpeedGroup"><button type="button" class="pill-btn" data-h3-speed="fast"- title="3 steps — about 4× faster, great for drafts and most shots.">+ title="About 4× faster than Best, a touch softer on fine detail — great for drafts and most shots."><span>⚡ Fast</span><span class="sub" id="h3SpeedFastSub"></span></button><button type="button" class="pill-btn" data-h3-speed="best"- title="Best: this shape's full sampler — the slower, most careful render.">+ title="This shape's full sampler — sharpest faces and detail, the slower, most careful render."><span>✦ Best</span><span class="sub" id="h3SpeedBestSub"></span></button></div>@@ -1163,7 +1363,19 @@</div><div><div class="qs-label">- <span class="qs-name" id="qualityLabelName">Quality</span>+ <span style="display:flex;align-items:baseline;gap:8px;min-width:0">+ <span class="qs-name" id="qualityLabelName">Quality</span>+ <!-- VC-34: the Tier dialog ("What this Mac can do" — every+ mode's size/eta ceiling on THIS Mac) used to have one+ door: Health pill → the Tier row, which #tierPill's own+ CSS keeps out of sight until that popover is opened.+ Docs already send people with memory questions there;+ this puts a second, obvious door right where the+ decision actually happens — picking a quality chip. -->+ <a href="#" class="tier-quick-link" id="qualityTierLink"+ onclick="openTierModal(); return false;"+ title="See what this Mac can do at every quality">On this Mac: <span id="qualityTierLinkLabel">—</span></a>+ </span><span class="qs-meta" id="qualityMeta"></span></div><!-- Compact 4-col strip. Each chip carries name + a single spec@@ -1327,13 +1539,26 @@container that setQuality() hides when quality=quick. --><div class="mode-only show" id="aspectRow" data-ltx-only style="display:flex;align-items:center;gap:10px;margin:6px 0 8px 0;padding:0 2px;"><span style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.4px;font-weight:600;flex:0 0 auto;">Orientation</span>- <div class="pill-group" id="aspectGroup" style="display:flex;gap:4px;flex:0 0 auto;">+ <div class="pill-group" id="aspectGroup" style="display:flex;gap:4px;flex:0 0 auto;flex-wrap:wrap;"><button type="button" class="pill-btn active" data-aspect="landscape" title="Landscape 16:9" style="padding:4px 10px;font-size:12px;display:inline-flex;gap:6px;align-items:center;"><svg class="ph orient-icon" aria-hidden="true" style="width:14px;height:14px;transform:rotate(90deg);"><use href="#ph-device-mobile"/></svg><span>16:9</span></button><button type="button" class="pill-btn" data-aspect="vertical" title="Vertical 9:16" style="padding:4px 10px;font-size:12px;display:inline-flex;gap:6px;align-items:center;"><svg class="ph orient-icon" aria-hidden="true" style="width:14px;height:14px;"><use href="#ph-device-mobile"/></svg><span>9:16</span></button>+ <!-- VC-39: social creators need 1:1 and 4:5, not just the+ two video-shaped presets above. Fixed 768×768 /+ 768×960 cells, exact under this Mac's cap (see aspect_presets_for_this_mac server-side) — same wiring+ as the two pills above, no new JS needed. -->+ <button type="button" class="pill-btn" data-aspect="square" title="Square 1:1" style="padding:4px 10px;font-size:12px;display:inline-flex;gap:6px;align-items:center;">+ <svg class="ph orient-icon" aria-hidden="true" style="width:14px;height:14px;"><use href="#ph-device-mobile"/></svg><span>1:1</span>+ </button>+ <button type="button" class="pill-btn" data-aspect="portrait_4_5" title="Portrait 4:5" style="padding:4px 10px;font-size:12px;display:inline-flex;gap:6px;align-items:center;">+ <svg class="ph orient-icon" aria-hidden="true" style="width:14px;height:14px;"><use href="#ph-device-mobile"/></svg><span>4:5</span>+ </button>+ <!-- No dedicated square/portrait glyph in the sprite (grepped+ the whole sheet) — reusing ph-device-mobile like 16:9/9:16+ do rather than adding a new SVG symbol for a P3 chip. --></div><input type="hidden" name="aspect" id="aspect" value="landscape"></div>@@ -1365,7 +1590,7 @@<div class="mini-fields"><div class="mf-cell"><span class="mf-label">Seed <span class="mf-hint">-1 = random</span></span>- <input name="seed" id="seed" value="-1" title="-1 picks a fresh random seed per render. Any integer locks the seed for repeatable output.">+ <input name="seed" id="seed" value="-1" oninput="_syncSeedLockChip()" title="-1 picks a fresh random seed per render. Any integer locks the seed for repeatable output."></div></div></div>@@ -1375,6 +1600,16 @@#h3TierNote. Empty and hidden when the combination has nothingto warn about, which is most of them. --><div class="engine-hint" id="ltxTierNote" hidden></div>+ <!-- H3-14: the selected chip's own description (cell.blurb — the+ SAME text the chip's hover tooltip already carries) used to be+ hover-only, so a laptop trackpad or touch screen never saw it,+ and a stale/contradictory blurb (Native naming a "Turbo" the UI+ replaced; two "10s" chips each claiming to be "the safe one")+ was hard to catch because nobody but a hover-happy reviewer+ ever read it. Now shown as a visible line, written in user+ terms — what THIS shape costs and trades, not a developer's+ measurement note. -->+ <div class="engine-hint" id="h3TierBlurb" data-h3-only hidden></div><!-- Honest artefact notes for the selected combination. Rendered fromthe cell's `notes` list (server-side), so a Draft 10 s clip istold BOTH that 0.25 MP doesn't resolve faces and that one prompt@@ -1436,7 +1671,7 @@event.stopPropagation() keeps clicks from toggling the<details> open/closed state. --><span class="loras-header-actions">- <button type="button" class="loras-icon-btn"+ <button type="button" class="loras-icon-btn" id="lorasRescanBtn"title="Rescan mlx_models/loras/ for new files"onclick="event.stopPropagation(); event.preventDefault(); refreshLoras()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg></button><input type="file" id="h3LoraImportFile" accept=".safetensors,application/octet-stream" hidden@@ -1456,6 +1691,11 @@hidden when they switch engine in Image Studio. --><div class="lora-mode-banner hint" id="loraModeBanner"style="margin: 0 0 6px 0; font-size: 11px;"></div>+ <!-- H3-08: combined strength across every ACTIVE LoRA for the+ current engine. Only shown with 2+ active — one LoRA has+ nothing to stack against. Filled by renderLorasList(). -->+ <div class="hint" id="lorasStrengthTotal" hidden+ style="margin: 0 0 6px 0; font-size: 11px;"></div><!-- Filter/search box. Shows up only when 5+ LoRAs areinstalled; below that it's just visual noise. Filters byname AND trigger words (case-insensitive substring). -->@@ -1573,11 +1813,14 @@and the API are unchanged); a checkbox because it is anextra job, not a size. --><div class="cz-note" id="h3ExportNote" hidden></div>+ <!-- H3-26: shown whenever H3.upscale_modes allows ltx_x2, which+ is not Draft-only — the copy used to say "the draft"+ unconditionally, wrong on Standard/High. --><label class="check h3-facefix-after" id="h3FaceFixAfterRow"- title="Queues a second job right after the draft: the draft at twice the size with LTX-2.5 detail, the face and the sound kept. The draft itself stays as rendered, next to it. Needs the 0.3 GB Upscale adapter (Settings → Models).">+ title="Queues a second job right after this one: the same clip at twice the size with LTX-2.5 detail, the face and the sound kept. This render itself stays as rendered, next to it. Needs the 0.3 GB Upscale adapter (Settings → Models)."><input type="checkbox" id="h3FaceFixAfter" onchange="setH3FaceFixAfter(this.checked)">- <span>Also run <b>Upscale & Face Fix</b> after the draft- <span class="cz-label-hint" id="h3FaceFixEta">optional · 2× · face and sound kept · about the draft's time again</span></span>+ <span>Also run <b>Upscale & Face Fix</b> after this render+ <span class="cz-label-hint" id="h3FaceFixEta">optional · 2× · face and sound kept · about the same time again</span></span></label></div><!-- Export upscale — target dims after render. "720p fit"@@ -1839,17 +2082,24 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><button type="button" class="pill-btn" data-temporal="windows"><span>Windows</span><span class="sub">experimental · picture drifts across passes · needs Q8</span></button></div><!-- SLIDING WINDOWS: one prompt per window, the H3 chain's- contract brought to LTX. The first line is the shot; every- later line is the next beat, led by the movement; a blank- line holds the previous moment. The invariants are what- must not change between passes and are re-injected into- every window. -->+ contract brought to LTX. Window 1 is always the main+ prompt above (ltx_windows.window_prompts: a blank line 0+ means "use it") — VA-18: this used to be a free-text+ textarea whose PLACEHOLDER read "(first window uses the+ prompt above)⏎he turns to the window…", inviting a user+ to type their first beat on the first real line, which+ silently became line 0 and REPLACED the main prompt.+ There is now no control that can set window 1's line at+ all — one labelled, timed box per LATER window instead,+ built by renderWindowsSlots() from the real schedule+ (/ltx/windows_plan). Every later box is the next beat, led+ by the movement; a blank box holds the previous moment.+ The invariants are what must not change between passes+ and are re-injected into every window. --><div class="cz-control" id="windowsRow" hidden><div class="cz-label">Per-window prompts- <span class="cz-label-hint" id="windowsHint">one line per window · blank holds</span></div>- <textarea id="window_prompts_text" class="sb-textarea" rows="3" spellcheck="false"- oninput="windowPromptsInput()"- placeholder="(first window uses the prompt above) he turns to the window and the light catches his face "></textarea>+ <span class="cz-label-hint" id="windowsHint">window 1 is the prompt above · one box per later window</span></div>+ <div id="windowsDynamicSlots"></div><input type="hidden" name="window_prompts" id="window_prompts" value=""><input type="text" name="window_invariants" id="window_invariants" class="sb-input"placeholder="what must not change between windows — one man, a grey room, soft window light">@@ -1867,14 +2117,33 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><option value="i2v_clean_audio">Use external audio file (mux it onto LTX video)</option></select><div class="mode-only" id="audioSection" style="margin-top:8px">- <label class="lbl">Audio file path</label>- <input name="audio" id="audio" placeholder="/path/to/your/track.wav">+ <label class="lbl">Audio file</label>+ <!-- VA-20: was a raw path text box — the only non-picker file+ input on the video form, and the one place a pasted+ path could go stale silently. Same drop/click pattern as+ the Lip-sync tab's audio slot; wired by i2vAudioInit()+ in queue.js. -->+ <div class="studio-ref-slot" id="i2vAudioSlot" data-slot="audio"+ style="aspect-ratio:auto;min-height:72px;cursor:pointer;">+ <span class="ref-tag">Audio</span>+ <div class="hint" id="i2vAudioSlotHint" style="padding:16px 12px;text-align:center;color:var(--muted);font-size:12px;">+ Drop a WAV / MP3 / M4A / FLAC here, or click to pick a file.+ </div>+ </div>+ <input type="file" id="i2vAudioFileInput" accept=".wav,.mp3,.m4a,.flac,audio/*" style="display:none">+ <input type="hidden" name="audio" id="audio" value="">+ <!-- The mux warning: this audio replaces LTX's own generated+ sound AFTER the video renders, so a mouth that happens+ to move does not move to THIS file. Only lip-sync+ (audio-conditioned generation) can make that true. -->+ <div class="hint" style="margin-top:6px;color:var(--warn,#c98a2b)">+ The mouth will not follow this file — the video is generated first, and this audio replaces its sound afterward. To make a face talk or sing to your audio, use+ <a href="#" onclick="event.preventDefault();openLipSyncEntry();">Lip-sync</a> instead.+ </div></div></div></div></details>-- <div class="derived" id="derived"></div></div><!-- Comfy-kill toggle. Hidden in DOM by default; shown only when the@@ -1898,9 +2167,21 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div class="queue-strip"><button type="button" class="qchip" onclick="openBatch()" title="Queue many prompts, or several takes of this one"><svg class="ph" aria-hidden="true"><use href="#ph-film-strip"/></svg>Batch</button><button type="button" class="qchip" id="pauseBtn" onclick="togglePause()" title="Pause / resume the render queue"><svg class="ph" aria-hidden="true"><use href="#ph-pause-fill"/></svg>Pause queue</button>- <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true"><use href="#ph-x"/></svg>Clear</button>+ <button type="button" class="qchip" data-role="clear-queue-btn" onclick="requestClearQueue()" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true"><use href="#ph-x"/></svg><span class="clear-queue-label">Clear</span></button>+ <!-- VC-38: the prompt/settings draft autosaves to this browser as you+ type (see draftAutosaveInstall in queue.js) and survives a reload+ or the restart every Update asks for. This is the way back to a+ blank form on purpose, distinct from Clear queue above. -->+ <button type="button" class="qchip" id="clearFormBtn" onclick="clearDraftForm()" title="Reset the prompt, Avoid and seed, and forget the saved draft">Clear form</button><span class="qchip-spacer"></span>- <span class="qchip-derived" id="derivedFooter"></span>+ <!-- SYS-22: at 1280-1440px (and worse below) the Shot Setup+ chips (Quality/Length) render below the sticky footer,+ reachable only by scrolling — "5.00s · 1024x576" here was+ plain text with no way back up to change it without+ scrolling past the footer first. Now a button that jumps+ there directly; the derived summary text itself is+ unchanged (queue.js's own comment on that design stands). -->+ <button type="button" class="qchip-derived" id="derivedFooter" onclick="scrollToShotSetup()" title="Jump to Quality / Length"></button></div><!-- The after-render Upscale & Face Fix, beside Generate (same state asthe checkbox under Upscale: h3_upscale = "ltx_x2"). The footer line@@ -1911,9 +2192,44 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><span>Also run <b>Upscale & Face Fix</b><span class="cz-label-hint" id="h3FaceFixFooterEta"></span></span></label>+ <!-- SYS-32: the circuit breaker paused the queue and explained why+ ONLY in a log line (Logs tab) -- the visible UI was "queue N ·+ paused" plus a bare Resume button. This surfaces the same+ reason where the person is actually looking. Populated by+ poll() from /status.paused_reason. -->+ <div class="breaker-notice" id="breakerNotice" hidden>+ <svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>+ <span id="breakerNoticeText"></span>+ <!-- SYS-33: errors rarely linked to Docs even where a section+ already existed for them. -->+ <a href="#" class="phos-toast-action" onclick="openDocs('troubleshooting','queue-paused'); return false;">Learn more</a>+ <button type="button" class="ghost-btn" onclick="requestClearQueue()">Clear queue</button>+ <button type="button" class="primary-btn" onclick="api('/queue/resume','POST').then(poll)">Resume</button>+ </div>+ <!-- VC-03: Load Params restores the exact seed but used to say so+ only in the collapsed Shot setup summary — Generate then quietly+ reproduced the same clip. This chip appears whenever the seed+ field holds a real (non-random) value, wherever it came from,+ and ✕ is the one-click way back to a fresh roll. -->+ <div class="seed-lock-chip" id="seedLockChip" hidden+ title="This render will reuse this exact seed — click ✕ for a fresh one">+ <span id="seedLockValue"></span>+ <button type="button" class="seed-lock-clear" onclick="clearSeedLock()" aria-label="Use a new seed instead">✕</button>+ </div>+ <!-- VC-26: "click a row to load it into the form and Update job" —+ editing a QUEUED job in place, its position unchanged. Shown by+ editQueuedJob(); Update posts the current form back onto that+ job's id (/queue/update), Cancel just hides the banner. -->+ <div class="queue-edit-banner" id="queueEditBanner" hidden>+ <span>Editing queued job — changes replace it in place, its position stays put.</span>+ <div class="queue-edit-banner-actions">+ <button type="button" class="primary" onclick="updateQueuedJob()">Update job</button>+ <button type="button" class="ghost-btn" onclick="cancelEditingQueuedJob()">Cancel</button>+ </div>+ </div><div class="actions"><button type="submit" class="primary" id="genBtn">Generate</button>- <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>+ <button type="button" class="danger js-stop-btn" disabled data-role="stop-btn" onclick="requestStop()" title="Stop the current render">Stop</button></div></div></form>@@ -1942,8 +2258,16 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div class="composer-card"><div class="composer-refs"><div class="show">- <h2>Reference image(s) — for image-to-image (Reference Edit)- <span class="h2-hint">Drop a photo to edit/transform it · 2-3 subjects: Qwen Edit (reliable) · HiDream Dev (fragile)</span>+ <!-- SYS-14: this header claimed the Images tab was FOR+ image-to-image only, in engine-jargon ("Reference Edit"),+ which buries "make a still from words, then animate it" --+ the standard creator workflow the Animate button (a+ protected "delightful thing") exists to serve. The drop+ zone itself still leads (that's the more common path+ here), but the hint now says text-only is a real option+ too, in plain words. -->+ <h2>Make or change a picture+ <span class="h2-hint">Drop a photo to edit it, or leave the slots empty and describe one in words below · Ideogram 4 makes pictures from text alone</span></h2><div class="studio-ref-grid" id="imgStudioRefs"><div class="studio-ref-slot" data-slot="0">@@ -2209,7 +2533,14 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea></div><div class="studio-engine-row"><select id="imgStudioEngine" onchange="if(typeof ideoSyncVisibility==='function')ideoSyncVisibility();imgStudioUpdateValidity();imgStudioRefreshEngineStatus();imgStudioUpdateEstimate();imgStudioUpdateRefWarning();if(typeof renderLorasList==='function')renderLorasList()">- <option value="auto">Auto (use Settings)</option>+ <!-- SYS-13: "Auto (use Settings)" named nothing -- on a+ Compact Mac where every other engine gets disabled (SYS-13),+ this unnamed option was the ONLY one left, and a user had+ no way to know what it actually was or how big the first+ download would be. It resolves to image_engine.py's own+ default (mflux_model = "Runpod/FLUX.2-klein-4B-mflux-4bit"),+ named here directly. -->+ <option value="auto">Auto — FLUX.2 [klein] 4B (fits every Mac · ~4.3 GB first download)</option><option value="qwen_edit_lightning_inline" selected>Reference Edit — Fast (image-to-image, Lightning 4-step, ~1:20, default, multi-ref)</option><option value="qwen_edit_inline">Reference Edit — Standard (image-to-image, 8-step Q6, ~2:05, no LoRA)</option><option value="qwen_edit_high_inline">Reference Edit — Quality (image-to-image, 40-step Q8 + CFG, ~3:50, final renders)</option>@@ -2278,14 +2609,14 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div class="queue-strip"><button type="button" class="qchip" onclick="openBatch()" title="Queue many prompts, or several takes of this one"><svg class="ph" aria-hidden="true"><use href="#ph-film-strip"/></svg>Batch</button><button type="button" class="qchip" id="pauseBtnStudio" onclick="togglePause()" title="Pause / resume the render queue"><svg class="ph" aria-hidden="true"><use href="#ph-pause-fill"/></svg>Pause queue</button>- <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true"><use href="#ph-x"/></svg>Clear</button>+ <button type="button" class="qchip" data-role="clear-queue-btn" onclick="requestClearQueue()" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true"><use href="#ph-x"/></svg><span class="clear-queue-label">Clear</span></button><span class="qchip-spacer"></span></div><div class="actions"><button class="primary" id="imgStudioGenBtn" onclick="imgStudioGenerate()"><span id="imgStudioGenBtnLabel">Generate</span></button>- <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>+ <button type="button" class="danger js-stop-btn" disabled data-role="stop-btn" onclick="requestStop()" title="Stop the current render">Stop</button></div></div>@@ -2401,19 +2732,18 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea></div></div>- <!-- Reference audio (optional) — drop a clip and the character- lip-syncs to it via i2v_clean_audio. Image-to-video was- considered and dropped 2026-05-16 (not needed for the- Characters surface). -->- <div class="characters-adv-row">- <label class="characters-adv-label">Reference audio <span class="characters-adv-hint">(optional — character lip-syncs to this clip)</span></label>- <div class="characters-adv-control">- <input type="file" id="charactersAudioFile" accept="audio/wav,audio/mpeg,audio/mp4,audio/x-m4a,.wav,.mp3,.m4a,.flac" style="display:none" onchange="charactersHandleAudioUpload(event)">- <button type="button" class="characters-adv-pick-btn" onclick="document.getElementById('charactersAudioFile').click()">Pick audio…</button>- <span class="characters-adv-fname" id="charactersAudioFname">none</span>- <button type="button" class="characters-adv-clear" id="charactersAudioClear" hidden onclick="charactersClearAudio()">×</button>- </div>- </div>+ <!-- VA-37: the "Reference audio — character lip-syncs to this+ clip" row lived here, on the dead #charactersSection pane+ (workflowSwitch maps 'characters' to 'manual' — this whole+ section is unreachable; see the "dead HTML; hide defensively"+ comment in editor.js's workflowSwitch). Even reachable, it+ promised lip-sync it could not deliver: an audio file with no+ image made mode t2v (the audio was silently dropped), and+ with an image it became i2v_clean_audio — a mux, not+ audio-conditioned generation. Removed rather than fixed in+ place; the real path is Lip-sync on the Video tab (VA-01),+ and /characters/<id>/generate now refuses an audio-only+ request instead of silently ignoring it (routes_characters.py). --><!-- LoRA picker portal — the Manual tab's #lorasDetails pickermoves in here when the Characters tab is the active mode.@@ -2435,6 +2765,26 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div class="mode-only train-pane" id="trainSection">+ <!-- SYS-03: gate at the ENTRY, before a Mac under TRAIN_MIN_RAM_GB can+ prepare a whole dataset and see the 41 GB download offer only to+ be refused at Start. Populated by trainApplyRamGate() (characters.js),+ called from trainInit() on every tab-open. Hidden by default;+ when shown, every other direct child of #trainSection is hidden+ by the same function (a general RAM banner is not enough — the+ reviewer found the tab still walked users through captioning and+ 41 GB of downloads before the refusal). -->+ <div class="train-gate-card" id="trainGateCard" hidden>+ <svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>+ <div class="train-gate-text">+ <div class="train-gate-title" id="trainGateTitle">Training a character needs more memory</div>+ <div class="train-gate-body" id="trainGateBody"></div>+ <div class="train-gate-actions">+ <button type="button" class="primary-btn" onclick="downloadSampleCharacter()">Get the sample character (Bizarro)</button>+ <button type="button" class="ghost-btn" onclick="openCivitaiModal(); if (typeof civitaiSetKind === 'function') setTimeout(() => civitaiSetKind('character'), 0);">Browse community characters</button>+ </div>+ </div>+ </div>+<!-- Preflight model check — hidden by default; populated bytrainCheckPreflight() if any required model file is missing(today: transformer-dev.safetensors which isn't in default install). -->@@ -2569,20 +2919,27 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><!-- ============== DATASET CARD ============== --><div class="composer-card train-card"><h2>Dataset- <span class="h2-hint" id="trainDatasetHint">15-50 stills · drop your character into the box</span>+ <!-- SYS-36: this said "15-50" while TRAIN_MAX_IMAGES has been 500+ since the "friendly-default-misread-as-hard-rule" fix (see+ that comment in mlx_ltx_panel.py) — a static header+ contradicting the live counter the moment JS updates it+ (trainUpdateCounter, characters.js). 20-50 is the genuine+ sweet spot; 500 is a technical ceiling, not a target, so it+ isn't asserted here either. -->+ <span class="h2-hint" id="trainDatasetHint">15 minimum, 20–50 is the sweet spot · drop your character into the box</span></h2><div class="train-drop" id="trainDrop"><div class="train-drop-empty" id="trainDropEmpty"><div class="picker-icon"><svg class="ph"><use href="#ph-image"/></svg></div>- <div class="picker-cta">Drop 15-50 images <em>+ optional matching <code>.txt</code> captions</em> here, or <strong>click to browse</strong></div>+ <div class="picker-cta">Drop images <em>+ optional matching <code>.txt</code> captions</em> here, or <strong>click to browse</strong> — 15 minimum, 20–50 is the sweet spot</div><div class="hint">PNG / JPG / WEBP for images, <code>.txt</code> for captions (same filename stem). Each preview shows the 1:1 center-crop the trainer will see.</div></div><div class="train-thumbs" id="trainThumbs" hidden></div><input type="file" id="trainFileInput" accept="image/png,image/jpeg,image/webp,text/plain,.png,.jpg,.jpeg,.webp,.txt" multiple style="display:none"></div><div class="train-counter-row">- <span class="train-counter" id="trainCounter">0 / 50 images</span>- <span class="train-counter-hint" id="trainCounterHint">need at least 15 to train</span>+ <span class="train-counter" id="trainCounter">0 images</span>+ <span class="train-counter-hint" id="trainCounterHint">15 minimum · 20–50 is the sweet spot</span><span class="train-caption-counter" id="trainCaptionCounter" hidden>0 captioned</span><span class="qchip-spacer"></span><button type="button" class="qchip" id="trainClearAllBtn" onclick="trainClearAll()" hidden><svg class="ph" aria-hidden="true"><use href="#ph-x"/></svg>Clear all</button>@@ -2790,6 +3147,13 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><input type="file" id="trainVoiceFileInput" accept="audio/wav,audio/mpeg,audio/mp3,audio/mp4,audio/x-m4a,audio/flac,.wav,.mp3,.m4a,.flac" style="display:none"></div>+ <!-- SYS-10c: a voice dropped before any training image produced+ "nothing on the voice card" — the only feedback was #trainStatus,+ a status line that lives at the top of the tab, far from this+ card, and carries no styling of its own. This puts the same+ message right where the person just acted. -->+ <div class="train-voice-inline-error" id="trainVoiceInlineError" hidden></div>+<div class="train-voice-controls"><label class="train-voice-toggle" id="trainVoiceToggleWrap"><input type="checkbox" id="trainVoiceToggle" checked disabled onchange="trainVoiceToggleChanged()">@@ -2843,12 +3207,12 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div class="form-action-footer" id="formActionFooterTrain"><div class="queue-strip"><button type="button" class="qchip" id="pauseBtnTrain" onclick="togglePause()" title="Pause / resume the queue"><svg class="ph" aria-hidden="true"><use href="#ph-pause-fill"/></svg>Pause queue</button>- <button type="button" class="qchip" onclick="api('/queue/clear','POST').then(poll)" title="Clear all queued jobs"><svg class="ph" aria-hidden="true"><use href="#ph-x"/></svg>Clear</button>+ <button type="button" class="qchip" data-role="clear-queue-btn" onclick="requestClearQueue()" title="Clear all queued jobs (running job continues)"><svg class="ph" aria-hidden="true"><use href="#ph-x"/></svg><span class="clear-queue-label">Clear</span></button><span class="qchip-spacer"></span></div><div class="actions"><button type="button" class="primary" id="trainStartBtn" onclick="trainStart()" disabled>Train Character</button>- <button type="button" class="danger" onclick="api('/stop','POST').then(poll)">Stop</button>+ <button type="button" class="danger js-stop-btn" disabled data-role="stop-btn" onclick="requestStop()" title="Stop the current render">Stop</button></div></div>@@ -2964,6 +3328,15 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><option value="4">4 bars</option></select></div>+ <!-- FILM-44: this box writes a beat-synced shot list from a plain+ concept. Casting a Singer against pictures — the common+ "music video" ask — is the Audio tab's Music Video pane+ (drop the song, drop pictures, tag who sings), which a+ creator starting HERE would otherwise never find. -->+ <div class="cz-label-hint sb-track-signpost">+ Casting a singer with pictures? Try+ <a href="#" onclick="event.preventDefault();sbGoToMusicVideo()">the Music Video planner</a>.+ </div></div><div class="cz-control" id="sbStyleRow">@@ -3003,6 +3376,16 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div class="cz-meta" id="sbLocMeta">no locations — every shot invents its own</div></div>+ <!-- FILM-14 (item 4): the same fix as locations, one axis over — a cut+ jumps visibly when each shot re-invents its own lighting. Written+ ONCE and injected at render time into every shot not yet rendered,+ this line survives a re-plan the same way a location does. -->+ <div class="cz-control" id="sbLightRow">+ <div class="cz-label">Light <span class="cz-label-hint">one line — goes on every shot not yet rendered</span></div>+ <input type="text" id="sbLight" class="sb-input"+ placeholder="warm practical lamps, single source, deep shadows">+ </div>+<details class="customize-section" id="sbMustSection"><summary class="cz-summary"><span class="cz-chevron"><svg class="ph" aria-hidden="true"><use href="#ph-caret-down"/></svg></span>@@ -3028,7 +3411,16 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea>character's sheet when it has one) is made first, in seconds; theclip then starts from it. --><label class="check sb-auto" title="Before each shot renders, an image of its first frame is made (from the character's sheet when the shot has one) and the clip starts from that still. LTX shots only; the still shows on the shot card with a New still button.">- <input type="checkbox" id="sbAnchorStills"> Start each shot from a still+ <input type="checkbox" id="sbAnchorStills" onchange="sbStillsFirstSync()"> Start each shot from a still+ </label>+ <!-- FILM-46: STILLS FIRST. The still decides the composition, but the+ render went straight from still to video with no way to look at+ the still first — so the composition was only ever seen after+ the (expensive) video minutes were spent. This holds the render+ for approval once each still lands. Implies "start from a+ still" — a still to approve has to exist. -->+ <label class="check sb-auto" title="After a shot's still lands, the render stops there and waits for you to Approve it (or ask for a new one) before it spends the video minutes. Turns on "Start each shot from a still" too.">+ <input type="checkbox" id="sbStillsFirst" onchange="sbStillsFirstSync()"> Stills first — approve each still before it renders</label><!-- LONG WINDOWS. A shot longer than one LTX window renders as a chainof windows instead of being cut to fit. -->@@ -3150,8 +3542,8 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div class="pill-group cols-2" data-os-toggle="light" role="group" aria-label="Lock the light"><button type="button" class="pill-btn active" data-os-value="on"><span>On</span><span class="sub">same light, every part</span></button><button type="button" class="pill-btn" data-os-value="off"><span>Off</span><span class="sub">beats as written</span></button></div></div><div class="os-toggle">- <div class="qs-label h3-axis-label"><span class="qs-name">Redo a part that drifts</span><span class="qs-meta">a part whose light changes is rendered once more</span></div>- <div class="pill-group cols-2" data-os-toggle="retake" role="group" aria-label="Redo a part that drifts"><button type="button" class="pill-btn active" data-os-value="on"><span>On</span><span class="sub">once more, at most</span></button><button type="button" class="pill-btn" data-os-value="off"><span>Off</span><span class="sub">keep the first pass</span></button></div>+ <div class="qs-label h3-axis-label"><span class="qs-name">Redo a part that drifts / doesn't sync</span><span class="qs-meta">light-change or lip-sync misses each get rendered again, fresh seed</span></div>+ <div class="pill-group cols-2" data-os-toggle="retake" role="group" aria-label="Redo a part that drifts or doesn't sync"><button type="button" class="pill-btn active" data-os-value="on"><span>On</span><span class="sub">up to a few times, at most</span></button><button type="button" class="pill-btn" data-os-value="off"><span>Off</span><span class="sub">keep the first pass</span></button></div></div><div class="os-toggle"><div class="qs-label h3-axis-label"><span class="qs-name">Hand off where the line ends</span><span class="qs-meta">for dialogue: the next part starts while the mouth still moves</span></div>@@ -3172,7 +3564,7 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><div class="queue-strip"><span class="qchip-derived" id="osSummary"></span></div><div class="actions"><button type="button" class="primary" id="osGenBtn">Generate</button>- <button type="button" class="danger" onclick="api('/stop','POST').then(poll)">Stop</button>+ <button type="button" class="danger js-stop-btn" disabled data-role="stop-btn" onclick="requestStop()" title="Stop the current render">Stop</button></div></div>@@ -3402,7 +3794,7 @@ The last line"></textarea><div class="queue-strip"><span class="qchip-derived" id="musicEstimate" title="Estimated for a song that runs to Max length, from M4 Max timings (a 3-minute song took about 3 minutes on Final) scaled for this chip. Most songs end sooner; the first song after install also loads the models."></span></div><div class="actions"><button type="button" class="primary" id="musicGenBtn" onclick="musicGenerate()">Compose</button>- <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>+ <button type="button" class="danger js-stop-btn" disabled data-role="stop-btn" onclick="requestStop()" title="Stop the current render">Stop</button></div><div class="hint" id="musicStatus" role="status"></div><div class="music-credit" id="musicHint">Generated with YuE2 by Multimodal Art Projection · MLX port by vanch007</div>@@ -3478,6 +3870,12 @@ The last line"></textarea><span id="mvStatus" class="hint" role="status"></span></div>+ <!-- FILM-12: shown only when the beat/vocal reader found no singing at+ all despite a Singer picture being cast — one chip per detected+ phrase, Vocal/Instrumental toggle, so the user marks the sung+ parts instead of the plan silently going all-B-roll. -->+ <div class="mv-sections" id="mvSections" hidden></div>+<div class="form-action-footer" id="mvFooter"><div class="queue-strip"><span class="qchip-spacer"></span>@@ -3491,8 +3889,12 @@ The last line"></textarea><details class="cz-section" id="mvOneShotDetails"><summary class="cz-summary">- <span class="cz-title">One shot (audio → video)</span>- <span class="cz-sum">one clip, driven by one stretch of audio</span>+ <!-- VA-01: renamed from "One shot (audio → video)" — that name+ collided with the top-level One Shot tab (a different,+ unrelated multi-part composer). The Lip-sync chip in the+ Video mode bar opens this same section. -->+ <span class="cz-title">Lip-sync (one clip, one audio track)</span>+ <span class="cz-sum">a picture and a stretch of audio → one clip whose mouth follows the track</span></summary><div class="cz-body"><div class="composer-card">@@ -3533,10 +3935,19 @@ The last line"></textarea><div class="hint">PNG / JPG / WEBP — anchors frame 0 of the audio-driven clip</div></div><img class="picker-preview" id="picker_preview_a2v_image" alt="" style="display:none">+ <!-- VA-02: same crop-preview overlay as I2V/H3's picker —+ A2V's free-form Width/Height mean a picked photo can+ still get cover-cropped even after snapA2VSizeToImage+ matches its aspect (e.g. the user edits the fields+ afterward), so the overlay and its drag position+ apply here too. -->+ <div class="crop-overlay" id="picker_crop_a2v_image" hidden></div><button type="button" class="picker-clear" id="picker_clear_a2v_image" title="Clear" style="display:none"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button></div><input type="file" id="picker_file_a2v_image" accept="image/*" style="display:none"><input type="hidden" name="a2v_image" id="a2v_image" value="">+ <input type="hidden" id="a2v_image_crop_focus" value="0.5">+ <div class="crop-overlay-controls" id="picker_crop_controls_a2v_image" hidden></div><div class="picker-recent" id="picker_recent_a2v_image_wrap" style="display:none"><div class="picker-recent-label">Recent uploads · click to use</div><div class="picker-recent-strip" id="picker_recent_a2v_image"></div>@@ -3545,15 +3956,38 @@ The last line"></textarea><div class="hint" style="margin-top:6px">Leave empty for pure Audio → Video. Add an image to open the clip on that frame (e.g. a portrait for a talking-head shot).</div>+ <!-- Open-mouth anchor check (2026-09-22 anchor lesson): a+ strength-1.0 frame-0 anchor with the mouth already open+ freezes the performance open-mouthed for the whole clip.+ Populated by audioStudioMouthCheck() on every a2v_image+ pick (queue.js's pickerSetImage calls it). -->+ <div class="hint" id="audioStudioMouthWarn" style="margin-top:6px;display:none;color:var(--warn,#c98a2b)"></div>+ <!-- VA-04: LoRAs picked on the Video tab ride into this render+ with nothing on screen to say so — a face LoRA left over+ from a character render quietly changed identity on a+ lip-sync shot. This is the visibility line; the real+ picker still lives on the Video tab (workflowSwitch below+ opens it). Populated by audioStudioRenderLoraNote(). -->+ <div class="hint" id="audioStudioLorasNote" style="margin-top:6px;display:none"></div></div></div>+ <!-- VA-05: placeholder rewritten from a stillness-friendly scene+ description ("shallow depth of field, natural skin pores") to+ a PERFORMANCE prompt — direction the mouth, not the set. --><textarea id="audioStudioPrompt" class="composer-prompt" rows="4"- placeholder="A photoreal medium close-up of a woman speaking to camera, soft daylight, shallow depth of field, natural skin pores"></textarea>+ oninput="audioStudioPromptCheck()"+ placeholder="A woman sings to camera, eyebrows lifting on the high notes, breathing between lines, one hand drifting up"></textarea><div class="composer-tools"><button type="button" class="ghost-btn" id="audioStudioEnhanceBtn" onclick="audioStudioEnhancePrompt()" title="Use Gemma to rewrite your prompt"><svg class="ph" aria-hidden="true" style="margin-right:6px"><use href="#ph-sparkle-fill"/></svg>Enhance</button><span class="ct-spacer"></span>+ <span class="hint">Keep it under ~40 words and describe the performance — a sync sentence is appended automatically.</span></div>+ <!-- VA-05 (client half): live stillness check. The server ALWAYS+ strips these words and appends the sync contract before a+ render (a2v_prompt in run_job_inner), so this is purely a+ heads-up + one-click fix, not the safety net itself. -->+ <div class="hint" id="audioStudioPromptWarn" style="margin-top:6px;display:none;color:var(--warn,#c98a2b)"></div></div><div class="studio-status-row" style="margin: 6px 0 -4px;">@@ -3585,14 +4019,26 @@ The last line"></textarea>so every A2V render used the first N seconds of the file and theonly workaround was trimming the audio beforehand (#46). --><div class="mf-cell">- <span class="mf-label">Audio start</span>+ <span class="mf-label">Start at</span><input type="number" id="audioStudioStart" value="0" min="0" step="0.5"+ oninput="audioStudioDurationChanged()"title="Seconds into the audio file where the clip starts reading. 0 = from the beginning."></div></div><div class="hint" style="margin-top:4px">- Audio start is an offset into the file you loaded — set it to 30 to drive the clip from 0:30 onward.+ Start at is an offset into the file you loaded — set it to 30 to drive the clip from 0:30 onward.</div>+ <!-- VA-21: the server has taken audio_stem_auto since the vocal+ stem seam landed — drums/bass/guitar reach the mouth as+ hedged, constant motion; a separated vocal doubled how much+ a measured clip's mouth moved. The manual form never+ exposed a control for it. Default ON: a song is the common+ case this helps, and it degrades to the full mix (with a+ log note) rather than failing when demucs isn't installed. -->+ <label class="mf-cell" style="margin-top:8px;display:flex;align-items:center;gap:8px;cursor:pointer;">+ <input type="checkbox" id="audioStudioStemAuto" checked style="width:auto;margin:0;">+ <span>Listen to the voice only <span class="hint" style="font-weight:normal">(separates the singer from the band before the model listens — the finished clip still plays the full mix; adds ~1-2 min once per song, falls back to the full mix if unavailable)</span></span>+ </label><div class="mf-cell" style="margin-top:8px"><span class="mf-label">Duration</span><div class="range-strip">@@ -3629,7 +4075,7 @@ The last line"></textarea></div><div class="hint" style="margin-top:8px" id="audioStudioHint">- Audio → Video uses audio conditioning during generation (not post-hoc mux). Some seeds may not work properly — retry if the mouth doesn't move.+ Audio → Video uses audio conditioning during generation (not post-hoc mux). If the mouth doesn't move: (1) start on a closed-mouth, face-forward picture — an open-mouth anchor tends to freeze open (the panel warns when it detects one); (2) remove "static" / "holds still" / "motionless" language from the prompt — a stillness word freezes the whole scene, mouth included; (3) for a song, try the vocal-only option so the model listens to the voice instead of the full mix.</div><div class="form-action-footer" id="audioStudioFooter">@@ -3638,8 +4084,20 @@ The last line"></textarea><span class="qchip-derived" id="audioStudioEstimate"></span></div><div class="actions">+ <!-- VA-07: Draft renders the first ~3s of the chosen window at+ the SAME settings (seed resolved and locked into the Seed+ field above) — about 3 min to answer "does this picture and+ prompt move the mouth?" instead of the full 10-25.+ Generate (Final) reuses that seed at the full duration the+ slider still shows. -->+ <button type="button" class="ghost-btn" id="audioStudioDraftBtn" onclick="audioStudioGenerate({draft:true})" title="Render the first ~3 seconds only, at the same settings — check the mouth before committing to the full clip.">Draft (~3s)</button><button type="button" class="primary" id="audioStudioGenBtn" onclick="audioStudioGenerate()">Generate</button>- <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>+ <!-- VA-30: Stop also breaks the "Split into clips" loop before it+ queues its next part — a plain /stop kills the current+ render but the client-side loop would otherwise queue the+ next one regardless. requestStop (VC-05) keeps its confirm and+ calls onStop only when the user actually stops. -->+ <button type="button" class="danger js-stop-btn" disabled data-role="stop-btn" onclick="requestStop({onStop: audioStudioSplitCancel})" title="Stop the current render">Stop</button></div></div></div>@@ -3678,17 +4136,25 @@ The last line"></textarea><button type="button" class="ghost-btn" id="edPoolRefreshBtn"onclick="edPoolRefresh(true)" title="Re-read the clips on disk">Refresh</button></header>+ <!-- 4.17: the five sources used to be five pill buttons in one+ non-wrapping row (FILM-37); in the ~260 px pool they clipped into+ each other at 1280-1440 px ("s Sequer ır sequer…"). One labelled+ select fits every width and still names every source in full. --><div class="ed-pool-tabs" id="edPoolTabs">- <button type="button" class="pill-btn active" data-src="film">This __SEQCAP__</button>- <button type="button" class="pill-btn" data-src="other">Other __SEQS__</button>- <button type="button" class="pill-btn" data-src="gallery">Generations</button>- <!-- IMAGES. The gallery has always held them — the image queue drops- every render into panel_uploads/library/manual — and until a clip- could be a STILL there was nothing a timeline could do with one. -->- <button type="button" class="pill-btn" data-src="images">Images</button>- <!-- SOUND. Laugh tracks, stings, beds: this film's audio/ folder and- every sound file in the outputs, for the audio tracks. -->- <button type="button" class="pill-btn" data-src="sound">Sound</button>+ <label class="ed-pool-src-label" for="edPoolSrcSelect">Show</label>+ <select id="edPoolSrcSelect" class="ed-pool-src" onchange="edPoolSrc(this.value)"+ aria-label="Which clips the media pool shows">+ <option value="film" data-src="film" selected>This __SEQCAP__</option>+ <option value="other" data-src="other">Other __SEQS__</option>+ <option value="gallery" data-src="gallery">Generations</option>+ <!-- IMAGES. The gallery has always held them — the image queue drops+ every render into panel_uploads/library/manual — and until a clip+ could be a STILL there was nothing a timeline could do with one. -->+ <option value="images" data-src="images">Images</option>+ <!-- SOUND. Laugh tracks, stings, beds: this film's audio/ folder and+ every sound file in the outputs, for the audio tracks. -->+ <option value="sound" data-src="sound">Sound</option>+ </select></div><!-- BLACK IS NOT SOMETHING YOU PICK FROM A LIST. It has no file, so ithas no row; it is made, with a length, which is its only property. -->@@ -3857,12 +4323,16 @@ The last line"></textarea>working (loadParamsBtn.disabled, animateBtn.style.display,useAsExtendBtn.style.display all still apply). --><div class="player-overlay-actions" id="playerOverlayActions" style="display:none">- <!-- Draft → Finish (Hailuo H3) — "same length, HIGHER QUALITY".+ <!-- Draft → Finish — "same length, HIGHER QUALITY". One slot, BOTH+ engines (VC-18/37): _syncFinishAffordance() (queue.js) re-points+ this button's onclick/select's onchange to the H3 or LTX+ implementation depending on the selected clip's o.engine, and+ hides the whole control for anything neither engine can finish.Hidden for every clip that has no canvas above the one it was- rendered on (and for every non-H3 clip). It used to be gated on a- `draft` flag, which under fixed tiers meant a Standard 10 s clip- could never be committed to High; with Quality and Length as- independent axes the offer is coherent on any rung but the top.+ rendered on. It used to be gated on a `draft` flag, which under+ fixed tiers meant a Standard 10 s clip could never be committed+ to High; with Quality and Length as independent axes the offer+ is coherent on any rung but the top.Leads the cluster because on a draft it IS the action.Wired exactly like Params/Extend: read the clip's sidecar,restore it into #genForm, submit through the one submit path —@@ -3884,6 +4354,17 @@ The last line"></textarea>title="Pick the quality to finish at — the length stays this clip's"onchange="h3FinishSetTier(this.value)"></select></div>+ <!-- NEW TAKE (VC-03) — "I like this, give me another" in one click:+ same recipe, fresh seed, queued at once. Leads Params because+ it's the more common gesture; Params is for editing before a+ re-roll, this is for not editing at all. Shortcut: R. -->+ <button id="newTakeBtn" class="po-act" type="button"+ onclick="newTakeActive()" title="Queue another take — same prompt, size, quality and LoRAs, a fresh seed" disabled>+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <path d="M8 3 A5 5 0 1 1 3.5 5.5 M3.5 2 V5.5 H7" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>+ </svg>+ <span class="po-act-label">New take</span>+ </button><button id="loadParamsBtn" class="po-act" type="button"onclick="loadParams()" title="Load this clip's render params back into the form" disabled><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">@@ -3898,6 +4379,49 @@ The last line"></textarea></svg><span class="po-act-label">Extend</span></button>+ <!-- VA-36 / "Continue the song": on a lip-sync (a2v) clip, Extend+ regenerates LTX's own joint audio over the new frames — a+ singing shot would "continue" with invented gibberish instead+ of the next stretch of the actual song. This button replaces+ Extend for a2v clips only (queue.js's player-render code+ toggles which of the two shows). It opens the next lip-sync+ job anchored on THIS clip's most-closed-mouth frame near its+ end (see /a2v/continue_song), with Start at moved forward to+ match — not a literal "continue the video", a new render. -->+ <button id="continueSongBtn" class="po-act" type="button" style="display:none"+ onclick="continueSongFromClip(activePath)" title="Start the next lip-sync clip where this one's song leaves off — anchored on this clip's most-closed-mouth frame near the end.">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <path d="M3 8 L13 8 M9 4 L13 8 L9 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ <circle cx="4" cy="12.5" r="1" fill="currentColor"/>+ </svg>+ <span class="po-act-label">Continue the song</span>+ </button>+ <!-- VA-26: "Retake a moment" — regenerate one interior stretch of+ this clip while the rest is preserved. The engine's own+ RetakePipeline (Extend's backend) exposed as a player action+ for the first time; opens a small form (retakeModal) rather+ than a scrubber drag-select, which this session didn't build. -->+ <!-- VA-38: a Windows chain that failed partway used to leave only+ hidden working files behind. This clip IS the visible,+ labelled partial join (see _publish_windows_partial); the+ button hands it to Extend as the source for the rest —+ reusing Extend's already-proven path rather than a byte-exact+ re-entry into the original chain plan. -->+ <button id="windowsContinueBtn" class="po-act" type="button" style="display:none"+ onclick="windowsContinueFromPartial(activePath)" title="This clip is what finished before the Windows chain failed. Continue it as an Extend.">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <path d="M3 8 L13 8 M9 4 L13 8 L9 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ </svg>+ <span class="po-act-label" id="windowsContinueLabel">Continue from here</span>+ </button>+ <button id="retakeBtn" class="po-act" type="button" style="display:none"+ onclick="openRetakeModal(activePath)" title="Regenerate one stretch of this clip; everything outside it is kept.">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <path d="M3 3 v4 h4 M13 13 v-4 h-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M3.5 9.5 a5.5 5.5 0 0 0 9.5 3.3 M12.5 6.5 a5.5 5.5 0 0 0 -9.5 -3.3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>+ </svg>+ <span class="po-act-label">Retake a moment</span>+ </button><!-- Upscale & Face Fix — ONE CLICK queues the face-safe 2× of thisclip (a new file lands next to it). The ⋯ half opens the fulllane (Remix → Upscale & Face Fix) for presets and the prompt.@@ -3920,6 +4444,45 @@ The last line"></textarea></svg></button></div>+ <!-- VC-18/37: secondary clip actions that don't earn a permanent icon+ slot — Sharp export (re-run the ANE upscaler on a clip already+ liked, no re-render), Use last frame (seed a fresh i2v roll from+ where this take ended), Open in Editor, Reveal in Finder. One+ popover, video-only (CSS/JS hide it for stills and audio). -->+ <div class="kebab-wrap" id="playerMoreWrap">+ <button id="playerMoreBtn" class="po-act" type="button"+ onclick="kebabToggle('playerMorePop')" aria-haspopup="true"+ title="More actions for this clip">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <circle cx="3" cy="8" r="1.4" fill="currentColor"/>+ <circle cx="8" cy="8" r="1.4" fill="currentColor"/>+ <circle cx="13" cy="8" r="1.4" fill="currentColor"/>+ </svg>+ <span class="po-act-label">More</span>+ </button>+ <div class="kebab-pop" id="playerMorePop" role="menu">+ <button type="button" role="menuitem" onclick="kebabToggle('playerMorePop',false);sharpExportActive()"+ title="Re-run the Neural-Engine sharpen (PiperSR) on this clip — a new, crisper file lands next to it">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M8 2 L9.6 6.4 L14 8 L9.6 9.6 L8 14 L6.4 9.6 L2 8 L6.4 6.4 Z" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round" fill="none"/></svg>+ Sharp export+ </button>+ <button type="button" role="menuitem" onclick="kebabToggle('playerMorePop',false);useLastFrameActive()"+ title="Extract this clip's last frame and start a fresh i2v render from there">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><rect x="2.5" y="3" width="11" height="10" rx="1.3" stroke="currentColor" stroke-width="1.2"/><path d="M2.5 10 L6 7 L9 9.5 L13.5 5.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>+ Use last frame+ </button>+ <button type="button" role="menuitem" onclick="kebabToggle('playerMorePop',false);openActiveInEditor()"+ title="Add this clip to a film and open it in the Editor">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M3 12 L4 9 L11 2 L14 5 L7 12 L4 13 Z" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/></svg>+ Open in Editor+ </button>+ <button type="button" role="menuitem" onclick="kebabToggle('playerMorePop',false);revealActive()"+ title="Show this file in Finder">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M2 5 a1 1 0 0 1 1-1 h3 l1.2 1.6 H13 a1 1 0 0 1 1 1 V12 a1 1 0 0 1-1 1 H3 a1 1 0 0 1-1-1 Z" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/></svg>+ Reveal in Finder+ </button>+ </div>+ </div><!-- Pull a good accident from the Video tab into a film. Hidden untilat least one board exists on disk — nothing about Storyboard showsup in the rest of the panel until there is a film to show it for. -->@@ -3965,10 +4528,11 @@ The last line"></textarea><span class="po-act-label">Expand</span></button><button class="po-act po-act-danger" type="button"- onclick="hideActive()" title="Hide this output from the gallery">+ onclick="hideActive()" title="Hide this output from the gallery — it stays on disk, and there's an Undo right after, plus a Hidden view to bring it back later"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M2 8 C 4 4, 12 4, 14 8 C 12 12, 4 12, 2 8 Z M5 5 L11 11" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>+ <span class="po-act-label">Hide</span></button></div><!-- This chip appears only when a clip is being watched while another@@ -3976,6 +4540,15 @@ The last line"></textarea>playing clip out from under the viewer. --><button type="button" class="live-return-chip" id="liveReturnChip" hiddenonclick="returnToLiveRender()">LIVE · return to render</button>+ <!-- VA-17 / H3-11: a One Shot that stopped or failed mid-chain keeps its+ finished parts un-hidden and one of them (the last) carries the+ resume manifest. Shown only for that specific card, over the player+ so it's impossible to miss on the clip it applies to. -->+ <div class="one-shot-recovery-bar" id="oneShotRecoveryBar" hidden>+ <span id="oneShotRecoveryText"></span>+ <button type="button" class="ghost-btn" data-action="take-join-partial">Join what's done</button>+ <button type="button" class="primary" data-action="take-resume">Resume</button>+ </div><!-- Full-size live state. It reads the same progress object as #nowCardand adds no polling. Hidden whenever the finished-output player isvisible, so it cannot repeat the old overlay-over-playback mistake. -->@@ -4002,6 +4575,11 @@ The last line"></textarea></button><div class="expand-stage" id="expandStage"></div><div class="expand-meta" id="expandMeta"></div>+ <!-- VC-18/37: the same clip actions as the toolbar's "More" menu,+ rendered flat (no popover needed — there's already room) since+ the lightbox is the expanded, full-attention view. Filled by+ openExpandLightbox() for video only. -->+ <div class="expand-actions" id="expandActions"></div></div><!-- ============== MUSIC STUDIO — the Song card =====================Under the player, for songs only. The song is the unit: its words,@@ -4084,6 +4662,13 @@ The last line"></textarea><header class="carousel-head"><h3>Storyboards</h3><span class="ch-spacer"></span>+ <!-- FILM-43: search + Recent-first was the whole ask — the list+ was title-only, sorted by when a board was FIRST created+ (not touched since), with no way to find one on a Mac with+ more than a screenful. -->+ <input type="search" class="sb-board-search" id="sbBoardSearch"+ placeholder="Find a film…" aria-label="Search storyboards"+ oninput="sbFilterBoardList(this.value)"></header><ul class="row-list sb-boardlist" id="sbBoardList"></ul></div>@@ -4122,7 +4707,7 @@ The last line"></textarea><span class="sb-plan-status" id="sbPlanStatus">Draft plan · not rendered</span><div class="stage-mode-toggle" id="sbStageToggle" role="group" aria-label="Stage view" hidden><button type="button" class="smt-btn active" data-sb-stage="list" onclick="sbSetStage('list')">Shot list</button>- <button type="button" class="smt-btn" data-sb-stage="player" onclick="sbSetStage('player')">Player</button>+ <button type="button" class="smt-btn" data-sb-stage="player" onclick="sbPlayBoard()">Player</button></div><!-- "All storyboards" used to sit here. It lives on the rail now,with the rest of the navigation, so there is one place to look@@ -4184,6 +4769,17 @@ The last line"></textarea></details><div class="sb-errors" id="sbErrors" hidden></div>+ <!-- FILM-46: "N stills ready — Approve all" when Stills first is on+ and at least one still is waiting; painted by sbRenderPlan(). -->+ <div class="sb-stills-banner" id="sbStillsBanner" hidden></div>+ <!-- FILM-41: a 75-shot board is a 54,540px scroll of full cards with+ no overview. Grid is a dense contact sheet (thumbnail, number,+ length, status, K/R/C) for finding a shot fast; clicking one+ switches back to List scrolled to it. -->+ <div class="sb-shotview-toggle" id="sbShotViewToggle" role="group" aria-label="Shot list view" hidden>+ <button type="button" class="smt-btn active" data-sb-view="list" onclick="sbSetShotView('list')">List</button>+ <button type="button" class="smt-btn" data-sb-view="grid" onclick="sbSetShotView('grid')">Grid</button>+ </div><ol class="sb-shots" id="sbShots"></ol><div class="sb-addrow"><button type="button" class="ghost-btn" onclick="sbAddShot()">+ Add a shot</button></div>@@ -4204,8 +4800,16 @@ The last line"></textarea><button type="button" class="ghost-btn" id="sbExportBtn" onclick="sbExport()" hidden>Export</button><button type="button" class="ghost-btn" id="sbRewriteBtn" onclick="sbRewrite()" hidden>Rewrite</button><button type="button" class="ghost-btn" id="sbResumeBtn" onclick="sbRenderRemaining()" hidden>Render remaining</button>+ <!-- FILM-47: Finish needed KEEP pressed on every shot by hand — 52+ presses for a 52-shot board. -->+ <button type="button" class="ghost-btn" id="sbKeepAllBtn" onclick="sbKeepAllUngraded()" hidden+ title="Marks every rendered, ungraded shot KEEP — the same as pressing K on each one.">Keep all ungraded</button><button type="button" class="primary" id="sbFinishBtn" onclick="sbFinish()">Finish keepers</button></div>+ <!-- FILM-47: a finished film could silently mix draft- and+ delivery-size clips — any shot never marked KEEP stays at draft+ size forever. Painted by sbRenderTally() when that is true. -->+ <div class="sb-mixed-res-warn" id="sbMixedResWarn" hidden></div><div class="sb-export-note" id="sbExportNote" hidden>Export writes a folder with every kept shot, a shot list, and <strong>one playable film</strong>. If you have cut this film in the Editor, that film IS your cut — same clips, same trims, same soundtrack, same filename the Editor's own Render writes. Otherwise it is the shots joined in order, mixed sizes normalised to the largest. The clips in the gallery are never touched.</div></div>@@ -4372,6 +4976,11 @@ The last line"></textarea>onclick="sbePopToggle('sbeRenderMenu', 'sbeRenderMore')"aria-haspopup="menu" title="Export, and what the render will do">▾</button></span>+ <!-- FILM-24: the render used to end by throwing the user out of the+ Editor onto the Film screen. It stays here now; this chip is+ where "the last thing I rendered" lives instead — replaced by+ the next render, gone (hidden) until the first one. -->+ <span class="sbe-render-chip" id="sbeRenderChip" hidden></span><button type="button" class="ghost-btn sbe-kebab" id="sbeMoreBtn"onclick="sbePopToggle('sbeMoreMenu', 'sbeMoreBtn')"aria-haspopup="menu" title="Drafts, soundtrack, media pool, auto-edit, storyboard, close">⋯</button>@@ -4416,6 +5025,30 @@ The last line"></textarea>title="Coarse grain, 16 mm territory. Added after the size, so a 4K delivery gets 4K grain.">Heavy grain</button></span><span class="sbe-deliver-cap">Finish is on the delivery only — the preview and the export stay clean</span>+ <span class="sbe-pop-note">Film look <span class="cz-label-hint">a whole-film grade, on top of any per-clip grade — saved with the __SEQ__</span></span>+ <span class="pill-group cols-3 sbe-deliver" id="sbeFilmLook">+ <button type="button" class="pill-btn active" data-look="none" onclick="sbeSetFilmLook('none')"+ title="No whole-film grade — every clip keeps only its own colour.">None</button>+ <button type="button" class="pill-btn" data-look="neutral" onclick="sbeSetFilmLook('neutral')"+ title="A light, even correction across every shot.">Neutral</button>+ <button type="button" class="pill-btn" data-look="warm_tungsten" onclick="sbeSetFilmLook('warm_tungsten')"+ title="Warm and slightly saturated — one consistent tungsten-lit feel across the whole film.">Warm tungsten</button>+ </span>+ <span class="sbe-pop-note">Sequence aspect <span class="cz-label-hint">also saved with the __SEQ__ — crops to fit, never stretches</span></span>+ <span class="pill-group cols-3 sbe-deliver" id="sbeSeqAspect">+ <button type="button" class="pill-btn active" data-aspect="16:9" onclick="sbeSetSeqAspect('16:9')"+ title="Widescreen — the film's native shape.">16:9</button>+ <button type="button" class="pill-btn" data-aspect="9:16" onclick="sbeSetSeqAspect('9:16')"+ title="Vertical — Reels, Shorts, Stories. Centre-cropped from the widescreen frame.">9:16</button>+ <button type="button" class="pill-btn" data-aspect="1:1" onclick="sbeSetSeqAspect('1:1')"+ title="Square — the classic feed post. Centre-cropped from the widescreen frame.">1:1</button>+ </span>+ <label class="check sbe-deliver-loudnorm"+ title="Levels the delivered mix to -14 LUFS integrated, the loudness streaming platforms (YouTube, Instagram, TikTok) normalize to anyway. Off by default — a mix already graded by ear isn't retargeted without being asked.">+ <input type="checkbox" id="sbeDeliverLoudnorm"+ onchange="sbeDeliverToggleLoudnorm(this.checked)">+ <span>Normalize to −14 LUFS</span>+ </label><span class="sbe-pop-sep"></span><button type="button" class="ghost-btn" id="sbeNleBtn" onclick="sbeExportNle()"title="A folder with an FCP7 XML (Premiere + Resolve), an After Effects script, and hardlinked media. Audio comes out as stems, not the ducked mix.">Export for Premiere / Resolve / AE</button>@@ -4437,6 +5070,10 @@ The last line"></textarea>title="This __SEQ__'s shots, other __SEQS__' clips, and everything in your generations.">Media pool</button><button type="button" class="ghost-btn" id="sbeAutoBtn" onclick="sbeAuto()"title="Re-cuts the __SEQ__ from scratch. Throws away this arrangement.">Auto-edit…</button>+ <button type="button" class="ghost-btn" id="sbeAlignBtn" onclick="sbeAutoAlign()"+ title="Checks every singing shot's mouth against the song, CPU only, no render. Proposes a slip per shot — nothing moves until you accept.">Auto-align lip-sync…</button>+ <button type="button" class="ghost-btn" id="sbeMatchBtn" onclick="sbeMatchColourOpen()"+ title="Samples one frame per clip and proposes a colour correction toward a hero clip (select one first) or the film's median. Nothing changes until you press Apply.">Match colour across the film…</button><span class="sbe-pop-sep"></span><button type="button" class="ghost-btn" id="sbeBoardBtn" onclick="sbeGoToBoard()"title="Open this __SEQ__'s shot list in the Storyboard tab" hidden>Storyboard</button>@@ -4634,6 +5271,15 @@ The last line"></textarea>the day Retake shipped and the element did not exist, so a finishedretake could never be put on the timeline. --><div class="sbe-relink sbe-retakes" id="sbeRetakes" hidden></div>+ <!-- FILM-15: a moved or trashed file used to show a black preview with+ no explanation and export a shorter, out-of-sync film with a+ "Rendered N clips" success toast over the top of it. Painted by+ sbePaintOffline from `SBE.offline` (server-computed, _sbe_payload).+ Render is blocked while this is up — see sbeRenderFilm. -->+ <div class="sbe-relink sbe-offline" id="sbeOffline" hidden>+ <span id="sbeOfflineText"></span>+ <span class="sbe-relink-why">Render is blocked until every clip is back online.</span>+ </div><!-- ============== THE TWO MONITORS =========================@@ -4731,7 +5377,10 @@ The last line"></textarea>onclick="SBE.muted ? sbeUnmuteFromRefusal() : sbeSetMute(true)" title="Sound on — click to mute the preview" data-shortcut="editor.mute"aria-label="Mute the preview"><svg class="sbe-cbar-i"><use href="#ic-sound" id="sbeMuteUse"/></svg></button>- <span class="sbe-time" id="sbeTime">0:00.00 <span>/ 0:00.00</span></span>+ <span class="sbe-time" id="sbeTime" role="button" tabindex="0"+ onclick="sbeToggleTimeMode()"+ onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();sbeToggleTimeMode();}"+ title="Minutes:seconds. Click for a frame timecode.">0:00.00 <span>/ 0:00.00</span></span><span class="sbe-mon-clip" id="sbeProgClip"></span><span class="sbe-mon-name" id="sbeProgName"></span><button type="button" class="sbe-chipbtn" id="sbeUnplacedBtn" hidden@@ -4857,6 +5506,8 @@ The last line"></textarea><span class="sbe-cbar-sep"></span><button type="button" class="sbe-cbar-btn" id="sbeCbFaceFix" onclick="sbeFaceFixSel()" aria-label="Face Fix ×2"><svg class="sbe-cbar-i"><use href="#ic-facefix"/></svg><b>Face Fix ×2</b></button>+ <button type="button" class="sbe-cbar-btn" id="sbeCbRetake" onclick="sbeRetakeSel()" aria-label="Retake">+ <svg class="sbe-cbar-i"><use href="#ic-history"/></svg><b>Retake</b></button><!-- OVERFLOW, NOT A DRAWER. Whatever the row cannot fit at this widthmoves into it, in reverse priority order, and moves back out whenthe pane is widened. At the Editor's normal width it is not even@@ -4919,7 +5570,7 @@ The last line"></textarea>painted by sbePaintHeads; the keys come from the one SHORTCUTStable (editor.soundLanes). --><div class="sbe-gh sbe-gh-aud">- <span class="sbe-gh-tag"><i>A1</i><b>Clip sound A</b>+ <span class="sbe-gh-tag"><i>A1a</i><b>Clip sound A</b><button type="button" class="sbe-gh-more sbe-asize" id="sbeAudioSize"onclick="sbeSoundModeToggle()" aria-expanded="false"title="Make the sound lanes small — A1, A2 and every audio track become thin strips so the picture gets the height. They come back the moment you touch a sound.">▾</button>@@ -4931,7 +5582,7 @@ The last line"></textarea>this head carries the one click that does the same to a timelinecut before there were two. --><div class="sbe-gh sbe-gh-aud sbe-gh-audb">- <span class="sbe-gh-tag"><i>A1</i><b>Clip sound B</b></span>+ <span class="sbe-gh-tag"><i>A1b</i><b>Clip sound B</b></span><button type="button" class="ghost-btn sbe-gh-alt" id="sbeAltLanes"onclick="sbeAlternateSel()"title="Alternate sound lanes — lays every clip's sound A, B, A, B… in film order, so neighbouring shots sit on different lanes and can overlap and crossfade. Nothing moves in time; one Undo puts it back.">Alternate A/B</button>@@ -5096,12 +5747,14 @@ The last line"></textarea>onclick="openOutputsFolder()"><svg class="ph" aria-hidden="true"><use href="#ph-folder-simple"/></svg></button>- <!-- Visible/Hidden segmented control was removed: the Hide- functionality was confusing in practice and we replaced it- with a one-click per-card Delete + an in-place "Open folder"- reveal here. The element is left out entirely so the seg-vh- class loses its only consumer too (CSS still defines it for- other segs). -->+ <!-- VC-04: the eye icon on the player still hides a clip with no way+ back other than this. Shown only once something is hidden+ (hidden_count > 0), so it costs nothing on the common path where+ nobody has hidden anything. Toggling re-polls filterMode='hidden',+ which /status and the carousel title already understood before+ this control existed (they just had nothing pointed at them). -->+ <button type="button" class="ghost-btn" id="hiddenFilterToggle"+ style="display:none" onclick="toggleHiddenFilter()">Hidden</button></div><div class="carousel" id="carousel"></div><!-- MUSIC STUDIO — the player bar. Sticks to the bottom of the outputs@@ -5253,15 +5906,71 @@ The last line"></textarea><button class="ghost-btn" onclick="closeSettingsModal()">Close</button></div><div class="models-hint">- Pick how rendered clips are encoded. Settings are saved to- <code>panel_settings.json</code> and apply to every new render.+ Models, rendering, output format, accounts and privacy. Saved to+ <code>panel_settings.json</code> and applied to every new render.Files already in the gallery are not re-encoded.</div>+ <!-- SYS-28: reordered 2026-09-29 to match how people actually reach+ for these, not the order the code was written in. Was: Models,+ Output format, Memory/speed, Model files, Storage, API tokens,+ Spicy, Appearance, Completion alerts, Analytics, Custom — the+ modal opened on codec presets (SYS-28's own complaint) and split+ Storage from the Models section it exists to explain. Now:+ Models & storage (what's on disk) -> Rendering (live preview,+ H3 model, and Output format + its Custom detail, all about what+ a render produces) -> Accounts (tokens) -> Privacy (Spicy ++ Anonymous analytics, grouped — both are "what leaves/shows on+ this machine") -> Appearance -> Completion alerts. -->+ <!-- Models — a real destination for every "Settings → Models" pointer in+ the app's own error and banner copy (SYS-08: 16 of those pointers led+ nowhere, because this section didn't exist). Opens the existing+ Models modal rather than duplicating its content here. --><div class="settings-section">- <h3>Output format</h3>- <div class="preset-grid" id="settingsPresets">- <!-- populated by openSettingsModal() from /settings -->+ <h3>Models</h3>+ <div class="hint" style="margin-bottom:8px">+ What's downloaded, what else this Mac can run, and repairing a file+ that downloaded incomplete.+ </div>+ <div class="settings-row">+ <button type="button" class="primary-btn" onclick="closeSettingsModal(); openModelsModal();">Open Models</button>+ </div>+ </div>++ <!-- Storage. Directly after its only disk-facing sibling on purpose: one+ section says WHAT IS INSTALLED, the next says WHAT CAN GO.++ It renders NOTHING — including its own <h3> — when there is nothing to+ reclaim, so a single-generation install never sees it. That is rule 5:+ a user who never opens a pack sees no new chrome at all.++ .models-list / .models-foot are reused wholesale, so a Storage row and+ a Models row look like siblings because they are. -->+ <div class="settings-section" id="settingsStorageSection" style="display:none">+ <h3>Storage</h3>+ <div class="hint" style="margin-bottom:8px">+ Weights on this disk that this build does not render with by default —+ and, where one is listed, what you would lose by removing it. Removing+ frees the space immediately; re-installing later is a fresh download of+ the size shown. Nothing here is deleted without asking.+ </div>+ <ul class="models-list" id="storageList"></ul>+ <div class="models-foot" id="storageFoot"></div>+ </div>++ <div class="settings-section">+ <h3>Model files</h3>+ <div class="hint" style="margin-bottom:8px">+ Verify every installed model weight against the official checksums on+ Hugging Face. A file that's the right size but the wrong content — an+ interrupted, mirrored, or stale download — decodes to garbled / "mosaic"+ video. This catches it and offers a one-click re-download. Takes 1–2+ minutes (it hashes every file).+ </div>+ <div class="settings-row">+ <button type="button" class="primary-btn" id="deepVerifyBtn"+ onclick="startDeepVerify()">Verify model files (checksum)</button>+ <span class="hint" id="deepVerifyStatus" style="margin-left:10px"></span></div></div>@@ -5279,6 +5988,16 @@ The last line"></textarea><option value="off">Off</option></select></div>+ <!-- SYS-28: the select above used to read as "On" whenever the SAVED+ preference was on, even when the 22 MB decoder (TAE) is missing+ from disk and every render is silently preview-less — the same gap+ the Now card's `preview_state.reason === 'missing_decoder'` branch+ (preview.js) already covers on the main screen. Settings had no+ equivalent, so a user who only ever opens Settings never learns+ why the toggle "does nothing." BOOT.ltx.preview_state is server-+ computed (mlx_ltx_panel.py, live_preview_state()) — this just+ surfaces it here too, with the same one-click fix. -->+ <div class="hint" id="settingsLivePreviewNote" style="margin-top:6px" hidden></div><!-- H3 DiT. The setting has been honoured by `h3_dit_choice()` andvalidated by the settings handler since it was added, and its owndocstring says "`h3_dit` in Settings" — but no control was ever@@ -5312,40 +6031,37 @@ The last line"></textarea></div><div class="settings-section">- <h3>Model files</h3>- <div class="hint" style="margin-bottom:8px">- Verify every installed model weight against the official checksums on- Hugging Face. A file that's the right size but the wrong content — an- interrupted, mirrored, or stale download — decodes to garbled / "mosaic"- video. This catches it and offers a one-click re-download. Takes 1–2- minutes (it hashes every file).- </div>- <div class="settings-row">- <button type="button" class="primary-btn" id="deepVerifyBtn"- onclick="startDeepVerify()">Verify model files (checksum)</button>- <span class="hint" id="deepVerifyStatus" style="margin-left:10px"></span>+ <h3>Output format</h3>+ <div class="preset-grid" id="settingsPresets">+ <!-- populated by openSettingsModal() from /settings --></div></div>- <!-- Storage. Directly after its only disk-facing sibling on purpose: one- section says WHAT IS INSTALLED, the next says WHAT CAN GO.-- It renders NOTHING — including its own <h3> — when there is nothing to- reclaim, so a single-generation install never sees it. That is rule 5:- a user who never opens a pack sees no new chrome at all.-- .models-list / .models-foot are reused wholesale, so a Storage row and- a Models row look like siblings because they are. -->- <div class="settings-section" id="settingsStorageSection" style="display:none">- <h3>Storage</h3>- <div class="hint" style="margin-bottom:8px">- Weights on this disk that this build does not render with by default —- and, where one is listed, what you would lose by removing it. Removing- frees the space immediately; re-installing later is a fresh download of- the size shown. Nothing here is deleted without asking.+ <div class="settings-section" id="settingsCustomSection" style="display:none">+ <h3>Custom (advanced)</h3>+ <div class="settings-row" style="margin-bottom:10px">+ <label>pix_fmt</label>+ <select id="settingsPixFmt" style="flex:1">+ <option value="yuv420p">yuv420p — web standard, broad support</option>+ <option value="yuv422p">yuv422p — pro, more chroma than 420p</option>+ <option value="yuv444p">yuv444p — full chroma, no subsampling</option>+ <option value="yuv420p10le">yuv420p10le — 10-bit, HDR-ready</option>+ <option value="yuv422p10le">yuv422p10le — 10-bit pro</option>+ <option value="yuv444p10le">yuv444p10le — 10-bit, full chroma</option>+ </select>+ </div>+ <div class="settings-row">+ <label>CRF</label>+ <input type="range" id="settingsCrfRange" min="0" max="30" step="1"+ style="flex:1; width:auto" oninput="document.getElementById('settingsCrfNum').value = this.value">+ <input type="number" id="settingsCrfNum" min="0" max="30" step="1"+ style="width:60px"+ oninput="document.getElementById('settingsCrfRange').value = this.value">+ </div>+ <div class="hint" style="margin-top:6px">+ 0 = mathematically lossless · 18 = visually lossless ·+ 23 = web default · 28+ = lossy</div>- <ul class="models-list" id="storageList"></ul>- <div class="models-foot" id="storageFoot"></div></div><div class="settings-section">@@ -5400,7 +6116,16 @@ The last line"></textarea>onclick="clearToken('hf')" style="display:none">clear</button></div><div class="hint" id="hfTestResult">- Required for gated LoRAs (Lightricks HDR + Control LoRAs).+ <!-- SYS-28: this used to say "HDR + Control LoRAs" needed a token,+ which contradicted the Models modal — the Control mode's own+ Union-Control IC-LoRA is Lightricks' one OFFICIAL UN-GATED+ weight (see CURATED_LORAS["union-control"], mlx_ltx_panel.py:+ "Un-gated official weight — no HF token needed"), downloaded+ token-less at install time. Only HDR and Motion Track Control+ are actually gated (CURATED_LORAS["hdr"|"motion-track"]). -->+ Required for gated LoRAs (Lightricks HDR + Motion Track Control).+ The Control mode's Union-Control weight is official and un-gated —+ no token needed for that one.Get one at <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noopener">huggingface.co/settings/tokens</a>— read access is enough.</div>@@ -5431,41 +6156,6 @@ The last line"></textarea><div class="hint" id="spicyHint" style="margin-top:8px; display:none"></div></div>- <!-- Appearance. Three answers — dark, light, follow the system — kept- in this browser and applied before the first paint from main.js.- Same row shape as the switches below. -->- <div class="settings-section">- <h3>Appearance</h3>- <div class="hint" style="margin-bottom:10px">The panel's palette. "System" follows the Mac's own light or dark setting and switches live. Saved in this browser only.</div>- <div class="pill-group cols-3" id="appearanceGroup">- <button type="button" class="pill-btn active" data-appearance="dark" onclick="setAppearance('dark')">Dark</button>- <button type="button" class="pill-btn" data-appearance="light" onclick="setAppearance('light')">Light</button>- <button type="button" class="pill-btn" data-appearance="system" onclick="setAppearance('system')">System</button>- </div>- </div>-- <!-- Completion alerts. A chime in the tab when a render finishes or- fails, and a browser notification when the tab is in the- background — once the person has allowed them. Same row shape as- the analytics switch below. -->- <div class="settings-section">- <h3>Completion alerts</h3>- <div class="hint" style="margin-bottom:10px" id="notifyHint"></div>- <div class="spicy-row">- <span class="spicy-state on" id="notifyStateBadge">ON</span>- <button type="button" class="ghost-btn" id="notifyAllowBtn" hidden- onclick="askNotifyPermission()">Allow browser alerts</button>- <button type="button" class="ghost-btn" id="notifyPushBtn" hidden- onclick="pushToggle()">Alert me here even when the tab is closed</button>- <button type="button" class="ghost-btn" id="notifyPushTestBtn" hidden- onclick="pushTest()">Send a test</button>- <button type="button" class="ghost-btn" id="notifyToggleBtn"- onclick="toggleNotify()" style="margin-left:auto">- Turn off- </button>- </div>- </div>-<!-- Anonymous usage analytics. Default ON, one click to turn off, andthe copy below is the whole truth about what leaves the machine —if this list and docs/ANALYTICS.md ever disagree, the code is the@@ -5561,30 +6251,38 @@ The last line"></textarea></details></div>- <div class="settings-section" id="settingsCustomSection" style="display:none">- <h3>Custom (advanced)</h3>- <div class="settings-row" style="margin-bottom:10px">- <label>pix_fmt</label>- <select id="settingsPixFmt" style="flex:1">- <option value="yuv420p">yuv420p — web standard, broad support</option>- <option value="yuv422p">yuv422p — pro, more chroma than 420p</option>- <option value="yuv444p">yuv444p — full chroma, no subsampling</option>- <option value="yuv420p10le">yuv420p10le — 10-bit, HDR-ready</option>- <option value="yuv422p10le">yuv422p10le — 10-bit pro</option>- <option value="yuv444p10le">yuv444p10le — 10-bit, full chroma</option>- </select>- </div>- <div class="settings-row">- <label>CRF</label>- <input type="range" id="settingsCrfRange" min="0" max="30" step="1"- style="flex:1; width:auto" oninput="document.getElementById('settingsCrfNum').value = this.value">- <input type="number" id="settingsCrfNum" min="0" max="30" step="1"- style="width:60px"- oninput="document.getElementById('settingsCrfRange').value = this.value">+ <!-- Appearance. Three answers — dark, light, follow the system — kept+ in this browser and applied before the first paint from main.js.+ Same row shape as the switches below. -->+ <div class="settings-section">+ <h3>Appearance</h3>+ <div class="hint" style="margin-bottom:10px">The panel's palette. "System" follows the Mac's own light or dark setting and switches live. Saved in this browser only.</div>+ <div class="pill-group cols-3" id="appearanceGroup">+ <button type="button" class="pill-btn active" data-appearance="dark" onclick="setAppearance('dark')">Dark</button>+ <button type="button" class="pill-btn" data-appearance="light" onclick="setAppearance('light')">Light</button>+ <button type="button" class="pill-btn" data-appearance="system" onclick="setAppearance('system')">System</button></div>- <div class="hint" style="margin-top:6px">- 0 = mathematically lossless · 18 = visually lossless ·- 23 = web default · 28+ = lossy+ </div>++ <!-- Completion alerts. A chime in the tab when a render finishes or+ fails, and a browser notification when the tab is in the+ background — once the person has allowed them. Same row shape as+ the analytics switch below. -->+ <div class="settings-section">+ <h3>Completion alerts</h3>+ <div class="hint" style="margin-bottom:10px" id="notifyHint"></div>+ <div class="spicy-row">+ <span class="spicy-state on" id="notifyStateBadge">ON</span>+ <button type="button" class="ghost-btn" id="notifyAllowBtn" hidden+ onclick="askNotifyPermission()">Allow browser alerts</button>+ <button type="button" class="ghost-btn" id="notifyPushBtn" hidden+ onclick="pushToggle()">Alert me here even when the tab is closed</button>+ <button type="button" class="ghost-btn" id="notifyPushTestBtn" hidden+ onclick="pushTest()">Send a test</button>+ <button type="button" class="ghost-btn" id="notifyToggleBtn"+ onclick="toggleNotify()" style="margin-left:auto">+ Turn off+ </button></div></div>@@ -5610,10 +6308,12 @@ The last line"></textarea></div><div class="models-hint" id="tierModalBlurb"></div><ul class="models-list" id="tierCapsList"></ul>- <div class="models-foot">- Set <code>LTX_TIER_OVERRIDE=base|standard|high|pro</code> in the env to- force a tier (useful for testing what other users see).- </div>+ <!-- VC-23: this footer used to tell every user to "Set+ LTX_TIER_OVERRIDE=base|standard|high|pro in the env" — a+ developer testing instruction with nothing to do with what this+ dialog is for (showing what THIS Mac can render). That note+ already lives where developers look for it: CLAUDE.md §19,+ "Force a different hardware tier for testing". --></div></div>@@ -5683,6 +6383,54 @@ The last line"></textarea>mode/quality, frames + dimensions, LoRAs used (with name + strength),elapsed time, queue id, model. Plus copy-buttons for prompt + seedso users can easily re-use them. -->+<!-- ============== RETAKE A MOMENT (VA-26) ==============+ "Fix just the bad two seconds" instead of re-rendering the whole clip —+ the engine's own RetakePipeline (Extend's backend) exposed as a player+ action for the first time. Regenerates one interior stretch while the+ rest of the clip is preserved untouched. NEEDS RENDER CHECK: see+ ledger_lipsync.txt — this UI + its /queue/add mode=retake job spec are+ wired and guarded, but the seconds-to-latent-frame math and the actual+ pipeline call have not been proven against a real GPU render yet. -->+<div id="retakeModal" class="models-modal" style="display:none"+ role="dialog" aria-modal="true" aria-labelledby="retakeModalTitle"+ onclick="if(event.target===this) closeRetakeModal()">+ <div class="models-card" style="width: min(560px, 96vw)">+ <div class="models-head">+ <h2 id="retakeModalTitle">Retake a moment</h2>+ <button class="ghost-btn" onclick="closeRetakeModal()">Close</button>+ </div>+ <div class="models-hint">+ Regenerates one stretch of this clip and keeps the picture outside it as it was. The new stretch uses the same Q8 dev transformer as Extend — a real render, at that lane's speed, not instant.+ </div>+ <div class="hint" id="retakeClampNote" hidden></div>+ <div style="padding:12px 0; display:flex; flex-direction:column; gap:10px">+ <div class="mini-fields">+ <div class="mf-cell">+ <span class="mf-label">From (s)</span>+ <input type="number" id="retakeStart" value="0" min="0" step="0.5">+ </div>+ <div class="mf-cell">+ <span class="mf-label">To (s)</span>+ <input type="number" id="retakeEnd" value="1" min="0.5" step="0.5">+ </div>+ </div>+ <label style="display:flex; flex-direction:column; gap:4px; font-size:12px; color:var(--muted)">+ What should happen in that stretch (optional — leave blank to reuse this clip's own prompt)+ <textarea id="retakePrompt" rows="3" style="padding:6px 9px; font-size:13px; background:rgba(140,160,220,0.04); border:1px solid var(--ph-border-soft); border-radius:6px; color:var(--text); font-family:inherit"></textarea>+ </label>+ <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;">+ <input type="checkbox" id="retakeKeepSound" checked style="width:auto;margin:0;">+ <span>Keep the original sound in this stretch <span class="hint" style="font-weight:normal">(uncheck to let the audio regenerate too)</span></span>+ </label>+ <div class="hint" id="retakeStatus"></div>+ </div>+ <div class="actions" style="display:flex;gap:8px;justify-content:flex-end;">+ <button type="button" class="ghost-btn" onclick="closeRetakeModal()">Cancel</button>+ <button type="button" class="primary" id="retakeSubmitBtn" onclick="submitRetake()">Retake this stretch</button>+ </div>+ </div>+</div>+<div id="outputInfoModal" class="models-modal" style="display:none"role="dialog" aria-modal="true" aria-labelledby="outputInfoTitle"onclick="if(event.target===this) closeOutputInfoModal()">@@ -5728,11 +6476,22 @@ The last line"></textarea>style="padding:8px 10px; font-size:12px; background:rgba(140,160,220,0.04); border:1px solid var(--ph-border-soft); border-radius:6px; color:var(--text); font-family:ui-monospace,SFMono-Regular,Menlo,monospace; line-height:1.45; resize:vertical">Loading environment…</textarea></label><label id="bugCrashRow" style="display:none; align-items:center; gap:8px; font-size:12px; color:var(--muted)">- <input id="bugCrashCheck" type="checkbox" checked>+ <!-- SYS-12: off by default. This zips real crash logs into a public+ GitHub issue; that should be an opt-in per report, not a+ pre-ticked box next to a "Submit" the user might click fast. -->+ <input id="bugCrashCheck" type="checkbox"><span id="bugCrashLabel">Include latest crash reports (zips up to 5 .ips files)</span></label>- <div id="bugSubmitRow" style="display:flex; gap:8px; justify-content:flex-end; align-items:center">+ <!-- SYS-40: "Report a bug" assumed a GitHub account and English. Not+ everyone has either — a Copy button lets someone paste the same+ scrubbed diagnostics anywhere (a forum post, a DM, a translated+ message), and the X link is somewhere non-English creators+ already are. -->+ <div id="bugSubmitRow" style="display:flex; gap:8px; justify-content:flex-end; align-items:center; flex-wrap:wrap"><span id="bugStatus" style="flex:1; font-size:12px; color:var(--muted)"></span>+ <a href="https://x.com/PhospheneAI" target="_blank" rel="noopener"+ style="font-size:11.5px; color:var(--muted)">No GitHub? Reach out on X →</a>+ <button class="ghost-btn" onclick="copyBugDiagnostics()">Copy diagnostics</button><button class="ghost-btn" onclick="closeBugModal()">Cancel</button><button id="bugSubmitBtn" class="primary-btn" onclick="submitBugReport()">Open GitHub issue</button></div>@@ -5903,6 +6662,28 @@ The last line"></textarea></div></div>+<!-- FILM-14: "Match colour across the film". A server route samples one+ mid-frame per clip and proposes a per-clip correction toward a hero+ clip or the film's median — nothing on disk changes until Apply, and+ the strength slider scales every proposal at once, previewed as a+ count rather than a render. -->+<div class="modal-bg" id="sbeMatchModal" onclick="if(event.target===this)sbeMatchClose()">+ <div class="modal">+ <h3>Match colour across the film</h3>+ <div class="hint" id="sbeMatchWhere">Reading one frame from every clip…</div>+ <div class="cz-control" style="margin-top:12px">+ <div class="cz-label">Strength <span class="cz-label-hint" id="sbeMatchStrengthHint">100%</span></div>+ <input type="range" id="sbeMatchStrength" min="0" max="100" step="5" value="100"+ oninput="sbeMatchStrengthPreview(this.value)">+ </div>+ <div class="hint" style="margin-top:6px">Exposure, warmth and tint only — reused from the same maths the film's own seam smoothing uses. Contrast and saturation stay whatever each clip's own grade already says.</div>+ <div class="modal-actions">+ <button class="small" onclick="sbeMatchClose()">Cancel</button>+ <button class="small primary" style="padding:6px 14px" id="sbeMatchGo" onclick="sbeMatchApply()" disabled>Apply</button>+ </div>+ </div>+</div>+<!-- The raw planner reply, for a bug report. Never shown by default. --><div class="modal-bg" id="sbRawModal" onclick="if(event.target===this)document.getElementById('sbRawModal').classList.remove('show')"><div class="modal">diff --git a/webapp/js/boot.js b/webapp/js/boot.jsindex 5f18775..fe9f24f 100644--- a/webapp/js/boot.js+++ b/webapp/js/boot.js@@ -15,11 +15,7 @@ globalThis.PIPERSR_UPSCALE_ENABLED = !!BOOT.pipersr_upscale_enabled;// (useful for low-RAM-user testing on Mr Bizarro's M4 Max).window.PHOSPHENE_CAP_TIER = (BOOT.cap_tier || 'q8');-// Apply tier-aware time estimates to the Quality pill subtitles. The HTML-// ships with the Comfortable-tier (M4 Studio 64 GB) numbers as defaults;-// users on Compact / Roomy / Studio tiers see realistic estimates instead-// of the optimistic baseline. Runs once on boot, plus when the tier modal-// reports new info (rare — tier is fixed for a given Mac).+// Apply tier-aware time estimates to the Quality pill subtitles.function applyTierTimes() {// NO-OP for the LTX strip since v4.0, deliberately, and kept as a named// function because the tier modal still calls it.@@ -29,11 +25,11 @@ function applyTierTimes() {// canvas and the frame count. Two writers for one span is how a chip ends up// claiming "1024×576 · about 8 min" for a render the table prices at ~2 min.//- // The tier-aware estimate is not lost: BOOT.quality_times is a RAM-tier- // figure, and the tier table's own model is anchored on renders measured on- // this class of machine. When a per-tier coefficient is wanted it belongs in- // ltx_estimate_minutes(), server-side, where one number serves the chip, the- // Length meta and the queue card at once.+ // The tier-aware estimate is not lost: every LTX chip reads BOOT.ltx.tiers+ // (ltx_tiers_payload(), server-side), which is chip-AND-RAM-aware per+ // VC-01 — a strictly better number than a RAM-tier-only figure ever was.+ // BOOT.quality_times (a RAM-tier-only table, now retired — VC-12/SYS-20)+ // is gone; the Tier modal reads the same honest source via honest_tier_times().return;}@@ -79,8 +75,8 @@ function setKeyframeMode(n) {const hint = document.getElementById('keyframeHint');if (hint) {hint.textContent = n >= 3- ? `${n} Keyframes needs Q8 (auto-selects High quality). Intermediate beats are locked at their At(s) times below.`- : 'FFLF needs Q8 (auto-selects High quality). The model interpolates between the first and last frames.';+ ? `${n} Keyframes needs Q8 — it always renders the Q8 two-stage pass, whatever the Quality pill says. Intermediate beats are locked at their At(s) times below.`+ : 'FFLF needs Q8 — it always renders the Q8 two-stage pass, whatever the Quality pill says. The model interpolates between the first and last frames.';}if (currentMode === 'keyframe') {document.querySelectorAll('#modeGroup .pill-btn').forEach(b => {@@ -320,6 +316,11 @@ function filteredMainOutputs() {if (mainOutputsFilter === 'photos') all = all.filter(o => outputKind(o) === 'image');else if (mainOutputsFilter === 'audio') all = all.filter(o => outputKind(o) === 'audio');else if (mainOutputsFilter !== 'all') all = all.filter(o => outputKind(o) === 'video');+ // VC-04: when the Hidden view is on, /status was asked with+ // include_hidden=1 (queue.js poll()), which returns hidden AND visible+ // outputs mixed — this is the other half of that filter, narrowing to+ // just the hidden ones instead of showing everything twice-over.+ all = (filterMode === 'hidden') ? all.filter(o => o.hidden) : all.filter(o => !o.hidden);return applyOutputsQuery(all);}@@ -539,9 +540,19 @@ function _autoMainOutputsFilterForMode(mode) {//// A clip that predates the field has no `model` and falls back to BOOT.model// silently — the old behaviour, for the only case where it was ever right.+// H3-34: an H3 clip's raw model path (.../mlx_models/hailuo-h3/deepbeep-+// pruned-bf16/models/h3-dit-q8/...) fell through the same slice-off-the-+// last-two-segments logic LTX paths use, which reads a quantization-pack+// folder name, not an engine — so the credit read a bare "models/h3-dit-+// q8" with no indication it names H3 at all. Recognize the H3 tree+// explicitly and say the engine.function _modelCreditLabel(raw) {const m = String(raw || '');if (!m) return '';+ if (/\/hailuo-h3\//.test(m) || /\bh3-dit-(q8|bf16)\b/.test(m)) {+ return /\bh3-dit-q8\b|\/models\/h3-dit-q8\//.test(m) || /deepbeep-pruned-q8/.test(m)+ ? 'Hailuo H3 · compact (Q8)' : 'Hailuo H3 · full (bf16)';+ }let label = m;const idx = m.indexOf('mlx_models/');if (idx >= 0) label = m.slice(idx + 'mlx_models/'.length);@@ -552,10 +563,19 @@ function updateModelCredit(path) {const el = document.getElementById('modelTag');if (!el) return;let raw = '';+ let entry = null;try {const p = path || (typeof activePath !== 'undefined' ? activePath : '');- const entry = (typeof currentOutputs !== 'undefined' && currentOutputs || []).find(o => o && o.path === p);- if (entry && entry.kind === 'audio' && entry.engine === 'music') {+ entry = (typeof currentOutputs !== 'undefined' && currentOutputs || []).find(o => o && o.path === p);+ // VC-20: a song is only "what's active" while the Audio tab itself is+ // showing it. Browsing to Outputs -> Audio from the Video tab is a+ // FILTER on the gallery, not a switch of what Generate will render —+ // the credit chip stayed pinned to the last song's "YuE2 · MLX by+ // vanch007" even though the LTX form on the left was still the one+ // about to run. Off that tab, ignore the clip's own engine entirely+ // and fall through to the form's own model (BOOT.model below).+ const onAudioTab = document.body.dataset.workflow === 'audio';+ if (entry && entry.kind === 'audio' && entry.engine === 'music' && onAudioTab) {// The slot is a short chip beside the Now/Queue tabs: the full credit// lives in the tooltip and on the Compose form.el.textContent = 'YuE2 · MLX by vanch007';@@ -563,11 +583,43 @@ function updateModelCredit(path) {el.href = 'https://github.com/vanch007/mlx-Yue';return;}- if (entry && entry.model) raw = entry.model;+ // A song browsed from another tab credits the form's engine, not the+ // song (VC-20) — so it must not count as "a selected clip" for the+ // H3-34 active-engine fallback below either.+ if (entry && entry.kind === 'audio' && entry.engine === 'music') entry = null;+ if (entry && entry.model) {+ raw = entry.model;+ }} catch (e) {}- el.textContent = _modelCreditLabel(raw || BOOT.model);- el.title = 'MLX port by @dgrauet';- el.href = 'https://github.com/dgrauet/ltx-2-mlx';+ // H3-34: with no clip selected (or one that predates the `model` field),+ // this fell back to BOOT.model unconditionally — a server-rendered+ // snapshot from page load that is ALWAYS the LTX pack, regardless of+ // engine. On H3 that showed "ltx-2.5-mlx-q4" while the form was set up to+ // render on H3 entirely. Fall back to whichever engine is actually active.+ if (!raw && !entry && document.body.dataset.engine === 'h3') {+ const kind = (typeof H3 !== 'undefined' && H3.dit_choice && H3.dit_choice.kind) || 'bf16';+ el.textContent = kind === 'q8' ? 'Hailuo H3 · compact (Q8)' : 'Hailuo H3 · full (bf16)';+ el.title = `Current engine: ${el.textContent} — MiniMax H3 (FL2VA)`;+ el.href = 'https://github.com/mrbizarro/minimax-h3-mlx';+ return;+ }+ const label = _modelCreditLabel(raw || BOOT.model);+ el.textContent = label;+ const isH3Label = label.indexOf('Hailuo H3') === 0;+ const credit = isH3Label ? 'MiniMax H3 (FL2VA)' : 'MLX port by @dgrauet';+ // SYS-39: this label follows the SELECTED clip (deliberately — see the+ // comment above; it used to credit the currently-loaded engine and+ // mis-attributed every older-generation clip). Without any hint of+ // that, selecting an old output and watching the tag change reads as+ // "the engine changed", which it hasn't. The tooltip says what it+ // actually is; `raw` set means "this clip", the fallback means "no clip+ // selected yet".+ el.title = raw+ ? `This clip was rendered with ${label} — ${credit}`+ : `Current engine: ${label} — ${credit}`;+ el.href = isH3Label+ ? 'https://github.com/mrbizarro/minimax-h3-mlx'+ : 'https://github.com/dgrauet/ltx-2-mlx';}updateModelCredit();// `audio` is still a free-text input (advanced section); `image` is now a@@ -596,6 +648,11 @@ function toggleAvoidRow(forceOpen) {if (wantOpen && ta) {try { ta.focus(); } catch (e) {}}+ // VC-15: the collapsed label also needs "(off at Balanced)" appended+ // when guidance is ignored at the current mode/quality — recomputed+ // here (not just from updateDerived's poll) so opening/closing the row+ // updates it immediately rather than waiting a beat.+ if (typeof updateAvoidIgnoredState === 'function') { try { updateAvoidIgnoredState(); } catch (e) {} }}// Auto-open the Avoid row if it has content (e.g. loaded from a sidecar// via loadParams). Run once at boot AND after loadParams sets values.@@ -684,6 +741,19 @@ function setMode(mode) {mode = 't2v';}currentMode = mode;+ // VA-23: Train / Character / Image (Studio) all return early below, before+ // the fall-through video-mode branch's own remixSubGroup show/hide logic+ // (the `_inRemix` block further down) ever runs. Remix → Upscale & Face+ // Fix → Character used to leave the Remix tool panel on screen with+ // "Upscale & Face Fix" still lit, as if Character renders would be+ // upscaled or face-fixed too. Hide it unconditionally here; the+ // fall-through branch re-shows it when the new mode actually is a Remix+ // tool (REMIX_MODES.indexOf(mode) !== -1).+ const _remixBarEarly = document.getElementById('remixSubGroup');+ if (_remixBarEarly && mode !== 'remix'+ && (typeof REMIX_MODES === 'undefined' || REMIX_MODES.indexOf(mode) === -1)) {+ _remixBarEarly.style.display = 'none';+ }// HDR vs Character mutual exclusion — reflect mode change in pill state.// Runs in a microtask so the rest of setMode finishes setting UI bits// first (character chip strip visibility, etc.).@@ -860,6 +930,10 @@ function setMode(mode) {updateAccelAvailability();updateTemporalAvailability();updateDerived();+ if (mode === 'extend' && typeof applyExtendPillPrices === 'function') {+ applyExtendPillPrices();+ }+ if (typeof updateShotSetupSummary === 'function') { try { updateShotSetupSummary(); } catch (e) {} }// Ingredients (multi-reference) — lazily wire the multi-image picker + load// the recent-uploads strip on first entry. Idempotent (guarded by __wired).if (mode === 'ingredients') {diff --git a/webapp/js/characters.js b/webapp/js/characters.jsindex 773de99..0d1f2fa 100644--- a/webapp/js/characters.js+++ b/webapp/js/characters.js@@ -485,6 +485,23 @@ function closeMusicInstallCard() {document.getElementById('musicInstallModal').hidden = true;}+// VA-01: the Video mode bar's entry point into lip-sync. The chip lives in+// #modeGroup for discoverability (it was three levels deep: Audio tab →+// Music video → a folded "One shot (audio → video)" row sharing a name with+// the unrelated One Shot tab) but the form it opens is still the Audio tab's+// one-shot composer — that form has its own submit path+// (audioStudioGenerate → mode=a2v), so this jumps rather than switching+// #genForm's mode.+function openLipSyncEntry() {+ audioModeSet('drive');+ if (typeof workflowSwitch === 'function') workflowSwitch('audio');+ const det = document.getElementById('mvOneShotDetails');+ if (det) det.open = true;+ requestAnimationFrame(() => {+ if (det) det.scrollIntoView({ block: 'start', behavior: 'smooth' });+ });+}+function audioStudioInit() {if (musicComposeActive()) setMainOutputsFilter('audio');// The Drive-video pane is the Music video pane now (music.js owns it; the@@ -498,6 +515,11 @@ function audioStudioInit() {// already dragged is left exactly where they put it.const _acsEl = document.getElementById('audioConditioningScale');if (!_acsEl || _acsEl.dataset.auto) audioConditioningScaleReset();+ audioStudioRenderLoraNote();+ audioStudioApplyTierClamp();+ // VA-06: seed the price on every visit (not just after a slider drag) so+ // the estimate is on screen before Generate is ever pressed.+ if (typeof audioStudioDurationChanged === 'function') audioStudioDurationChanged();if (AUDIO_STUDIO.wired) return;AUDIO_STUDIO.wired = true;const audioSlot = document.getElementById('audioStudioAudioSlot');@@ -529,6 +551,30 @@ function audioStudioInit() {audioStudioRenderSlots();}+// VA-04: LoRAs the Video tab's picker has active ride into every a2v render+// (audioStudioGenerate forwards _activeLoras below) with nothing on screen+// to say so. A face LoRA left over from an earlier character render quietly+// changes identity on a lip-sync shot with no way to see, remove, or+// deliberately reproduce it. This is the visibility line — the picker+// itself stays on the Video tab; "change" jumps there and opens it.+function audioStudioRenderLoraNote() {+ const el = document.getElementById('audioStudioLorasNote');+ if (!el) return;+ const active = (typeof _activeLoras !== 'undefined' && Array.isArray(_activeLoras)) ? _activeLoras : [];+ if (!active.length) {+ el.style.display = 'none';+ el.innerHTML = '';+ return;+ }+ const names = active.map(l => escapeHtml(l.name || String(l.path || '').split('/').pop())).join(', ');+ el.style.display = '';+ el.innerHTML = (active.length === 1 ? '1 LoRA' : active.length + ' LoRAs')+ + ' from the Video tab will be applied here too: <b>' + names + '</b> — '+ + '<a href="#" onclick="event.preventDefault();workflowSwitch(\'manual\');'+ + 'var d=document.getElementById(\'lorasDetails\');if(d)d.open=true;'+ + 'd&&d.scrollIntoView({block:\'start\'});">change</a>';+}+async function audioStudioUploadAudio(file) {const status = document.getElementById('audioStudioStatus');if (status) status.textContent = 'Uploading audio…';@@ -544,6 +590,21 @@ async function audioStudioUploadAudio(file) {AUDIO_STUDIO.audioName = file.name;AUDIO_STUDIO.audioDuration = (data.duration_sec != null) ? Number(data.duration_sec) : null;audioStudioRenderSlots();+ // Default the window to the file, not a fixed 7 s (VA-03): a fresh+ // upload should default Duration to the whole clip (capped at the+ // slider's own 30 s ceiling) so the common case — one short line —+ // needs no manual trimming to avoid rendering silence.+ if (AUDIO_STUDIO.audioDuration != null) {+ const slider = document.getElementById('audioStudioDuration');+ if (slider) {+ // floor(len + 0.25): a 12.9 s file defaults to 13 s (0.1 s of tail,+ // under the silent-tail threshold below), a 12.6 s file to 12 s —+ // never a whole extra second of silence (4.17.0 render check).+ const target = Math.max(1, Math.min(30, Math.floor(AUDIO_STUDIO.audioDuration + 0.25)));+ slider.value = String(target);+ }+ }+ audioStudioDurationChanged();if (status) status.textContent = '';} catch (e) {if (status) status.textContent = 'Audio upload failed: ' + (e.message || 'unknown');@@ -556,6 +617,42 @@ async function audioStudioUploadAudio(file) {// handle upload and clear, and the hidden input #a2v_image carries the// path that audioStudioGenerate() reads.+// Open-mouth anchor check (build item 3 of the "Keyframe + lip-sync"+// section, report_video-advanced.txt). The 2026-09-22 anchor lesson: a+// strength-1.0 frame-0 anchor cut from an open-mouth still freezes the+// performance open-mouthed for the whole clip — "mouth open, doesn't move,+// doesn't sing" was the owner's exact report. Called from queue.js's+// pickerSetImage() whenever the a2v_image picker gets a new (or cleared)+// path; a crop preview belongs on the SAME picker tile (VA-02, the+// size-faces package) — this only owns the openness verdict line under it.+function audioStudioMouthCheck(path) {+ const warn = document.getElementById('audioStudioMouthWarn');+ if (!warn) return;+ if (!path) { warn.style.display = 'none'; warn.innerHTML = ''; return; }+ warn.style.display = '';+ warn.style.color = '';+ warn.textContent = 'Checking the mouth in this picture…';+ fetch('/a2v/mouth_check', { method: 'POST', body: new URLSearchParams({ image: path }) })+ .then(r => r.json())+ .then(res => {+ // A picker change while the request was in flight — don't overwrite+ // a newer check's result with a stale one.+ const current = (document.getElementById('a2v_image') || {}).value;+ if (current !== path) return;+ if (!res.ok || !res.measured) { warn.style.display = 'none'; warn.innerHTML = ''; return; }+ if (res.open) {+ warn.style.color = 'var(--warn,#c98a2b)';+ warn.innerHTML = 'This picture’s mouth looks open — lip-sync tends to '+ + 'freeze on an open-mouth start frame. A closed-mouth, face-forward '+ + 'picture works better.';+ } else {+ warn.style.display = 'none';+ warn.innerHTML = '';+ }+ })+ .catch(() => { warn.style.display = 'none'; warn.innerHTML = ''; });+}+function audioStudioClearAudio() {AUDIO_STUDIO.audioPath = null;AUDIO_STUDIO.audioName = null;@@ -644,6 +741,63 @@ function _a2vFramesForSeconds(sec) {const target = Math.max(1, Math.round(sec * 24));return ((target - 1 + 7) >> 3 << 3) + 1; // round up to 8k+1}+// VA-06: A2V showed no time estimate before a 10-25 minute render — the+// #audioStudioEstimate span existed in the markup and nothing wrote to it.+// Priced server-side (GET /a2v/estimate -> ltx_a2v_estimate_minutes), from+// the lane that actually runs (Q8 two-stage vs Q4 distilled) and the real+// clamped canvas, the same way the Video tab and One Shot already price a+// render before Generate. Debounced + sequence-guarded (osEstimate's+// pattern in oneshot.js) since duration is a drag slider that fires on+// every tick.+let _a2vEstimateSeq = 0;+let _a2vEstimateTimer = null;+function a2vUpdateEstimate(frames, w, h) {+ const el = document.getElementById('audioStudioEstimate');+ if (!el) return;+ el.textContent = 'pricing…';+ clearTimeout(_a2vEstimateTimer);+ const seq = ++_a2vEstimateSeq;+ _a2vEstimateTimer = setTimeout(async () => {+ try {+ const r = await fetch(`/a2v/estimate?frames=${frames}&width=${w}&height=${h}`);+ const d = await r.json();+ if (seq !== _a2vEstimateSeq) return;+ if (!d.ok) { el.textContent = ''; return; }+ const pack = d.pack === 'q8' ? 'Q8' : 'Q4';+ el.textContent = `${d.width}×${d.height} · ${pack} · about ${String(d.eta).replace(/^~\s*/, '')} on this Mac`;+ } catch (e) {+ if (seq === _a2vEstimateSeq) el.textContent = '';+ }+ }, 150);+}+// VA-35: on Compact tier (t2v_max_dim, e.g. 768) the A2V form used to show+// and price the size the user typed (e.g. 1024×576) while the server+// silently clamped to the tier cap at render time — the canvas warning+// below was then computed on the wrong number too. Runs once per Audio-tab+// visit: sets the Width/Height inputs' max attribute and pulls down any+// value that already exceeds it (same proportional-fit shape as the+// server's ltx_fit_canvas), so what's on screen is what will render.+function audioStudioApplyTierClamp() {+ const cap = ((BOOT || {}).tier || {}).t2v_max_dim || 0;+ if (!cap) return;+ const wEl = document.getElementById('audioStudioWidth');+ const hEl = document.getElementById('audioStudioHeight');+ if (!wEl || !hEl) return;+ wEl.max = String(cap);+ hEl.max = String(cap);+ const w = parseInt(wEl.value || '1024', 10);+ const h = parseInt(hEl.value || '576', 10);+ if (Math.max(w, h) > cap) {+ const scale = cap / Math.max(w, h);+ wEl.value = String(Math.max(32, Math.round((w * scale) / 32) * 32));+ hEl.value = String(Math.max(32, Math.round((h * scale) / 32) * 32));+ if (typeof phosToast === 'function') {+ phosToast(`This Mac renders Audio → Video up to ${cap} px on the longer side — size adjusted to fit.`,+ { kind: 'info' });+ }+ }+}+function audioStudioDurationChanged(val) {const slider = document.getElementById('audioStudioDuration');// Called with no argument from the Width/Height inputs, so the canvas and@@ -652,26 +806,70 @@ function audioStudioDurationChanged(val) {: (slider ? slider.value : '7')) || '7', 10);const out = document.getElementById('audioStudioDurationVal');if (out) out.textContent = sec + ' s';- const warn = document.getElementById('audioStudioDurationWarn');- if (!warn) return;const frames = _a2vFramesForSeconds(sec);const w = parseInt((document.getElementById('audioStudioWidth') || {}).value || '1024', 10);const h = parseInt((document.getElementById('audioStudioHeight') || {}).value || '576', 10);+ if (typeof a2vUpdateEstimate === 'function') a2vUpdateEstimate(frames, w, h);+ const warn = document.getElementById('audioStudioDurationWarn');+ if (!warn) return;const area = (w > 0 && h > 0) ? w * h : 1024 * 576;+ // THE WINDOW VS THE FILE (VA-03). Duration and Audio start used to be+ // free-floating numbers with no idea how long the uploaded file actually+ // is — a 4 s vocal silently rendered 7 s, 43% of it silence, which is+ // exactly where a lip-sync mouth freezes. Now that /upload returns+ // duration_sec, warn (start+duration past the end) or refuse outright+ // (start already past the end — nothing would play at all).+ const startEl = document.getElementById('audioStudioStart');+ const startSec = Math.max(0, parseFloat((startEl && startEl.value) || '0') || 0);+ if (AUDIO_STUDIO.audioDuration != null) {+ const fileLen = AUDIO_STUDIO.audioDuration;+ if (startSec >= fileLen) {+ warn.style.display = '';+ warn.innerHTML = '<b>Start at</b> (' + startSec.toFixed(1) + ' s) is past '+ + 'the end of this file (' + fileLen.toFixed(1) + ' s long) — this would '+ + 'render a fully silent clip. Pick a start under ' + fileLen.toFixed(1) + ' s.';+ return;+ }+ }// A MEMORY LIMIT COMES FIRST. On a Compact-tier Mac the panel refuses an// a2v render past BOOT.a2v_max_frames (see a2v_max_frames() server-side):// a 30 s clip on an 8 GB Mac died in the GPU watchdog instead. Say so here,// before Generate, with the same number the worker refuses on.+ // 4.17.0 render check: this used to sit AFTER the silent-tail note, so a+ // 12.9 s song defaulted to 13 s on a 32 GB Mac showed "the last 0.1 s+ // renders against silence" and never the cap or its Split link — the one+ // action that renders the song on that Mac. A refusal outranks a nuance.const a2vCap = (BOOT && BOOT.a2v_max_frames) || 0;if (a2vCap && frames > a2vCap) {const capSec = Math.round((a2vCap - 1) / 24);warn.style.display = '';+ // VA-30: was a manual-chore instruction only ("set Start at to 0, N,+ // 2N... and join them in the Editor"). "Split into clips" queues the+ // whole song as a sequence, each part after the first anchored on the+ // previous part's own most-closed-mouth frame (the "Continue the song"+ // primitive, build item 2) — no jump cuts at the joins, no hand math.warn.innerHTML = 'This Mac renders Audio → Video up to <b>' + capSec+ ' s</b> per clip — longer ones outgrow its memory and are refused. '- + 'Render the song as ' + capSec + ' s clips (set <b>Start at</b> to 0, '- + capSec + ', ' + (2 * capSec) + ' …) and join them in the Editor.';+ + '<a href="#" onclick="event.preventDefault();audioStudioSplitIntoClips(' + capSec + ');">'+ + 'Split into ' + capSec + ' s clips</a> — queues the whole song as a '+ + 'sequence, each part starting where the last one’s mouth closed, '+ + 'no jump cuts at the joins. One at a time; this Mac’s own a2v speed '+ + 'applies per part, so a long song is a long wait, not a fast one.';return;}+ if (AUDIO_STUDIO.audioDuration != null) {+ const fileLen = AUDIO_STUDIO.audioDuration;+ // Under a quarter second of tail is the rounding of a whole-second+ // slider, not a clip that "renders against silence".+ if (startSec + sec > fileLen + 0.25) {+ const silentTail = (startSec + sec - fileLen).toFixed(1);+ warn.style.display = '';+ warn.innerHTML = 'The last <b>' + silentTail + ' s</b> of this clip render '+ + 'against silence (the file ends at ' + fileLen.toFixed(1) + ' s) — the '+ + 'mouth will stop there. Shorten Duration or move Start at earlier.';+ return;+ }+ }// THE CANVAS IS THE LEVER, NOT THE LENGTH. Below the knee the reports run// clean to 721 frames, so there is nothing to say; above it they give out// around frame 450 whatever the length asked for.@@ -695,6 +893,45 @@ function audioStudioDurationChanged(val) {}}+// VA-05 (client half): "this freezes the mouth — Fix" for the lip-sync+// prompt box. Debounced (400ms) so it doesn't fire a request per keystroke.+// The server-side pass (storyboard.a2v_prompt in run_job_inner) is the real+// safety net and runs unconditionally on every a2v render; this is purely a+// before-you-render heads-up.+let _a2vPromptCheckTimer = null;+function audioStudioPromptCheck() {+ clearTimeout(_a2vPromptCheckTimer);+ _a2vPromptCheckTimer = setTimeout(_audioStudioPromptCheckNow, 400);+}+async function _audioStudioPromptCheckNow() {+ const ta = document.getElementById('audioStudioPrompt');+ const warn = document.getElementById('audioStudioPromptWarn');+ if (!ta || !warn) return;+ const text = ta.value;+ if (!text.trim()) { warn.style.display = 'none'; warn.innerHTML = ''; return; }+ try {+ const r = await fetch('/a2v/prompt_check', { method: 'POST', body: new URLSearchParams({ prompt: text }) });+ const res = await r.json();+ if (!res.ok || !res.problems || !res.problems.length) {+ warn.style.display = 'none';+ warn.innerHTML = '';+ return;+ }+ const phrases = res.problems.map(p => '"' + escapeHtml(p) + '"').join(', ');+ warn.style.display = '';+ warn.innerHTML = 'This freezes the mouth: ' + phrases+ + ' — audio-driven clips read stillness language as "nothing moves, '+ + 'including the lips." <a href="#" onclick="event.preventDefault();audioStudioPromptApplyFix(' + JSON.stringify(res.cleaned) + ');">Fix</a>';+ } catch (e) { /* best-effort — the server-side pass is the real gate */ }+}+function audioStudioPromptApplyFix(cleaned) {+ const ta = document.getElementById('audioStudioPrompt');+ if (!ta) return;+ ta.value = cleaned;+ const warn = document.getElementById('audioStudioPromptWarn');+ if (warn) { warn.style.display = 'none'; warn.innerHTML = ''; }+}+async function audioStudioEnhancePrompt() {const ta = document.getElementById('audioStudioPrompt');const original = ta.value.trim();@@ -702,9 +939,16 @@ async function audioStudioEnhancePrompt() {const btn = document.getElementById('audioStudioEnhanceBtn');const originalLabel = btn.innerHTML;btn.disabled = true;- btn.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-sparkle-fill"/></svg>Loading Gemma\u2026 (~15s)';+ // VC-23: same plain-English swap as queue.js's enhancePrompt().+ btn.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-sparkle-fill"/></svg>Loading the prompt helper\u2026 (~15s)';try {- const r = await fetch('/prompt/enhance', { method: 'POST', body: new URLSearchParams({ prompt: original, mode: 't2v' }) });+ // VA-24: was mode 't2v' — that Gemma system prompt asks for "describe+ // the scene AND the sound", which competes with the actual conditioning+ // audio, and readily writes stillness phrasing ("a static shot") that+ // freezes the mouth. mode 'a2v' (routes_queue.py) borrows the i2v system+ // prompt instead and runs the result through the same stillness-cleanup+ // + word-cap every other a2v prompt goes through.+ const r = await fetch('/prompt/enhance', { method: 'POST', body: new URLSearchParams({ prompt: original, mode: 'a2v' }) });const res = await r.json();if (res.error) { alert('Enhance failed: ' + res.error); return; }if (confirm('Original:\n' + res.original + '\n\nEnhanced:\n' + res.enhanced + '\n\nReplace your prompt with the enhanced version?'))@@ -736,17 +980,21 @@ function audioConditioningScaleReset() {const el = document.getElementById('audioConditioningScale');if (!el) return;el.dataset.auto = '1';+ const isQ4 = window.PHOSPHENE_CAP_TIER === 'q4';+ // VA-19: on Q8, 1.0 is exactly "audio guidance off" and below 1.0 inverts+ // the term — a user dragging the thumb "down a bit" from Auto's 3.0 could+ // land in that dead zone with no warning. Q8's floor moves up to 1.5 so+ // the slider itself cannot reach the off point; Q4 has no such trap.+ el.min = isQ4 ? '0.5' : '1.5';el.value = String(a2vLaneAudioScale());const out = document.getElementById('audioConditioningScaleVal');if (out) out.textContent = 'Auto';const hint = document.getElementById('audioConditioningScaleHint');if (hint) {- hint.textContent = 'Auto is ' + a2vLaneAudioScale().toFixed(1)- + ' on this Mac (' + (window.PHOSPHENE_CAP_TIER === 'q4' ? 'Q4' : 'Q8')- + ' pipeline) — the engine\'s own setting. Higher = stronger audio '- + 'adhesion, lower visual flexibility.'- + (window.PHOSPHENE_CAP_TIER === 'q4' ? ''- : ' On this lane 1.0 switches audio guidance off.');+ hint.textContent = 'How hard the mouth follows the audio. Auto is best '+ + 'for most clips — it picks the right value for this Mac\'s render '+ + 'lane (' + (isQ4 ? 'Q4' : 'Q8') + '). Drag right for tighter sync, '+ + 'left for more visual freedom.';}}@@ -768,7 +1016,22 @@ function a2vLoadParams(p) {audioModeSet('drive');if (typeof workflowSwitch === 'function') workflowSwitch('audio');const det = document.getElementById('mvOneShotDetails');- if (det) det.open = true;+ if (det) {+ det.open = true;+ // VA-10: opening the details left the restored form below the fold —+ // the data landed correctly, the user just never scrolled down far+ // enough to see it. Scroll it into view and give it the same brief+ // pulse the Params flash uses elsewhere (.flash / phos-tab-flash).+ // setTimeout(…, 0), not requestAnimationFrame: the JS test harness+ // (scripts/extract_panel_js.py) runs this in plain node, which has no+ // rAF. Either defers past the details' own reflow from `open = true`+ // just above, which is all this needs.+ setTimeout(() => {+ try { det.scrollIntoView({ block: 'start', behavior: 'smooth' }); } catch (e) { try { det.scrollIntoView(); } catch (e2) {} }+ det.classList.add('flash');+ setTimeout(() => det.classList.remove('flash'), 1200);+ }, 0);+ }audioStudioRenderSlots();const setVal = (id, v) => {const el = document.getElementById(id);@@ -790,6 +1053,10 @@ function a2vLoadParams(p) {}if (typeof pickerSetImage === 'function') {pickerSetImage('a2v_image', p.image ? String(p.image) : '', { snapAspect: false });+ // The lip-sync picture's saved crop framing (VA-02), not the last one's.+ if (typeof _setCropFocus === 'function' && typeof _cropFocusFromParams === 'function') {+ _setCropFocus('a2v_image', _cropFocusFromParams(p));+ }}const acs = p.audio_conditioning_scale;const acsEl = document.getElementById('audioConditioningScale');@@ -806,12 +1073,224 @@ function a2vLoadParams(p) {} else {audioConditioningScaleReset();}+ // LIPSYNC-10: "Listen to the voice only" as the clip was made — Generate+ // and Continue the song submit this checkbox. Same accepted values as the+ // server's a2v_conditioning_audio(); an explicit vocal stem (a music-video+ // shot) also means the model listened to the voice alone. A sidecar+ // without the field predates the control and rendered the full mix.+ const stemEl = document.getElementById('audioStudioStemAuto');+ if (stemEl) {+ const autoOn = ['1', 'true', 'on', 'yes'].includes(String(p.audio_stem_auto ?? '').trim().toLowerCase());+ stemEl.checked = autoOn || !!String(p.audio_stem || '').trim();+ }+ audioStudioRenderLoraNote();+}++// VA-07: Draft · Final. Draft renders the first ~3s of the CHOSEN window at+// full settings — same seed, same image, same audio start, same prompt —+// so "does this picture and prompt move the mouth?" costs about 3 min+// instead of the full 10-25. Final is the same recipe at the full duration+// the Duration slider still shows (Draft does not touch it). The pairing+// is seed-locked: Draft resolves a random seed (-1) to a concrete number+// and writes it back into the Seed field, so Final — pressed after —+// reproduces the same take, just longer, rather than drawing a new one.+// VA-30: "Split into N clips" — queues the WHOLE song as a sequence of a2v+// jobs on a Compact-tier Mac (a2v_max_frames cap), one at a time, each part+// after the first anchored on the previous part's own most-closed-mouth+// frame (the "Continue the song" primitive above — /a2v/continue_song) so+// the joins don't show a mid-syllable jump. This is a real client-side+// orchestration loop, not a server job: it takes as long as N a2v renders+// take (each 10-25 min on this Mac's own a2v speed), and the tab has to+// stay open for it. NEEDS RENDER CHECK (see ledger_lipsync.txt): the+// single-clip a2v path and /a2v/continue_song are both already exercised+// elsewhere; the multi-part CHAIN — does part 2's anchor really read back+// cleanly after part 1 is on disk, N times in a row — has not been proven+// against a real render.+let _a2vSplitCancel = false;+// LIPSYNC-7: one split chain at a time. AUDIO_STUDIO.busy only covers a single+// submit; a second Split (or a double-activated link) used to start a second+// chain that queued duplicate parts and reset the first one's cancel flag.+let _a2vSplitRunning = false;+function audioStudioSplitCancel() { _a2vSplitCancel = true; }+async function _waitForJob(jobId, onProgress) {+ const started = Date.now();+ const timeoutMs = 40 * 60 * 1000; // generous over the measured 10-25 min a2v ceiling+ while (Date.now() - started < timeoutMs) {+ if (_a2vSplitCancel) return { status: 'cancelled' };+ try {+ const r = await fetch('/status');+ const s = await r.json();+ const all = [].concat(s.current ? [s.current] : [], s.queue || [], s.history || []);+ const job = all.find(j => j && j.id === jobId);+ if (job) {+ if (job.status === 'done') return { status: 'done', output_path: job.output_path };+ if (job.status === 'failed' || job.status === 'error') return { status: job.status, error: job.error };+ if (job.status === 'stopped' || job.status === 'cancelled') return { status: job.status };+ if (onProgress) onProgress(job.status === 'running' ? 'rendering…' : 'queued…');+ }+ } catch (e) { /* transient network hiccup — keep polling */ }+ await new Promise(res => setTimeout(res, 4000));+ }+ return null; // timed out+}+async function audioStudioSplitIntoClips(capSec) {+ if (_a2vSplitRunning) {+ if (typeof phosToast === 'function') {+ phosToast('A split is already running — Stop it first, or wait for it to finish.', { kind: 'warning' });+ }+ return;+ }+ if (AUDIO_STUDIO.busy) { alert('Wait for the current render to finish first.'); return; }+ const totalDur = AUDIO_STUDIO.audioDuration;+ if (!totalDur) {+ alert('This file’s length is not known yet — wait for the upload to finish, or re-drop it.');+ return;+ }+ const startEl = document.getElementById('audioStudioStart');+ const fromSec = Math.max(0, parseFloat((startEl && startEl.value) || '0') || 0);+ const remaining = totalDur - fromSec;+ if (remaining <= 0) { alert('Start at is already past the end of this file.'); return; }+ const n = Math.max(1, Math.ceil(remaining / capSec));+ if (!confirm('Queue ' + n + ' clips of up to ' + capSec + 's each, one at a time — '+ + 'this Mac’s own a2v speed applies per part, so this can take a while. Continue?')) return;+ // Taken BEFORE the first await and released in finally — a second call+ // returns above without touching this chain's cancel flag.+ _a2vSplitRunning = true;+ _a2vSplitCancel = false;+ try {+ await _a2vSplitChain(capSec, totalDur, fromSec, n);+ } finally {+ _a2vSplitRunning = false;+ }+}+async function _a2vSplitChain(capSec, totalDur, fromSec, n) {+ const status = document.getElementById('audioStudioStatus');+ const w = Math.max(32, Math.round(parseInt(document.getElementById('audioStudioWidth').value || '1024', 10) / 32) * 32);+ const h = Math.max(32, Math.round(parseInt(document.getElementById('audioStudioHeight').value || '576', 10) / 32) * 32);+ const prompt = (document.getElementById('audioStudioPrompt').value || '').trim() || 'A performer sings to camera.';+ const a2vImageEl = document.getElementById('a2v_image');+ let imagePath = (a2vImageEl && a2vImageEl.value) || '';+ // LIPSYNC-6: the same request settings Generate sends. The picked+ // picture's crop position applies to the FIRST part only — later parts+ // anchor on a frame of the previous clip, already at the output size.+ const focusEl = document.getElementById('a2v_image_crop_focus');+ let cropFocus = imagePath ? ((focusEl && focusEl.value) || '0.5') : '';+ const lorasJson = (typeof _activeLoras !== 'undefined' && Array.isArray(_activeLoras) && _activeLoras.length)+ ? JSON.stringify(_activeLoras.map(l => ({ path: l.path, strength: l.strength })))+ : '';+ const acsEl = document.getElementById('audioConditioningScale');+ const audioConditioningScale = (acsEl && !acsEl.dataset.auto) ? parseFloat(acsEl.value) : null;+ const stemAutoEl = document.getElementById('audioStudioStemAuto');+ const stemAuto = !!(stemAutoEl && stemAutoEl.checked);+ // LIPSYNC-4: each closed-mouth anchor sits a little before its part's end,+ // so the parts overlap and the song needs MORE parts than the first+ // estimate. Loop until the rendered audio reaches the end of the file; `n`+ // is re-estimated as it goes. A non-advancing anchor falls back to the+ // plain cut, and a hard ceiling stops any runaway.+ const EPS = 0.05;+ const maxParts = 2 * n + 2;+ let nextStart = fromSec;+ let done = 0;+ while (nextStart < totalDur - EPS) {+ const i = done;+ n = Math.max(n, i + Math.ceil((totalDur - nextStart - EPS) / capSec));+ if (_a2vSplitCancel) { if (status) status.textContent = 'Split stopped after part ' + i + ' of ' + n + '.'; return; }+ if (i >= maxParts) break;+ const partDur = Math.min(capSec, totalDur - nextStart);+ const frames = _a2vFramesForSeconds(partDur);+ if (status) status.textContent = 'Queueing part ' + (i + 1) + ' of ' + n + ' ('+ + nextStart.toFixed(1) + 's–' + (nextStart + partDur).toFixed(1) + 's)…';+ const fd = new URLSearchParams();+ fd.set('mode', 'a2v');+ fd.set('prompt', prompt);+ fd.set('audio', AUDIO_STUDIO.audioPath);+ if (imagePath) {+ fd.set('image', imagePath);+ if (cropFocus) fd.set('image_crop_focus', cropFocus);+ }+ fd.set('width', String(w));+ fd.set('height', String(h));+ fd.set('frames', String(frames));+ fd.set('seed', '-1');+ if (audioConditioningScale !== null && !Number.isNaN(audioConditioningScale)) {+ fd.set('audio_conditioning_scale', String(audioConditioningScale));+ }+ fd.set('audio_start_time', String(nextStart));+ if (stemAuto) fd.set('audio_stem_auto', 'on');+ fd.set('quality', 'high');+ fd.set('accel', 'off');+ fd.set('enhance', 'off');+ if (lorasJson) fd.set('loras', lorasJson);+ fd.set('preset_label', 'Split ' + (i + 1) + '/' + n);+ let jobId;+ try {+ const r = await fetch('/queue/add', { method: 'POST', body: fd });+ const res = await r.json().catch(() => ({}));+ if (!r.ok || res.error) throw new Error(res.error || ('HTTP ' + r.status));+ jobId = res.id;+ } catch (e) {+ const msg = 'Part ' + (i + 1) + ' failed to queue: ' + (e.message || e)+ + ' — ' + i + ' clip(s) already rendered are safe in Outputs.';+ if (status) status.textContent = msg;+ if (typeof phosToast === 'function') phosToast(msg, { kind: 'danger', duration: 8000 });+ return;+ }+ const result = await _waitForJob(jobId, (msg) => {+ if (status) status.textContent = 'Part ' + (i + 1) + ' of ' + n + ': ' + msg;+ });+ if (!result || result.status !== 'done' || !result.output_path) {+ const msg = 'Part ' + (i + 1) + ' did not finish (' + ((result && result.error) || result?.status || 'timed out')+ + ') — ' + i + ' clip(s) already rendered are safe in Outputs.';+ if (status) status.textContent = msg;+ if (typeof phosToast === 'function') phosToast(msg, { kind: 'danger', duration: 8000 });+ return;+ }+ done = i + 1;+ const partEnd = nextStart + partDur;+ if (partEnd < totalDur - EPS) {+ // Anchor the NEXT part on THIS part's own closed-mouth frame — the+ // same primitive "Continue the song" uses — instead of a naive fixed+ // cut, so the joins don't show a mid-syllable jump. Falls back to the+ // naive cut (still correct, just un-anchored) if the probe fails or+ // the anchor would not move the song forward.+ let anchored = false;+ try {+ const cr = await fetch('/a2v/continue_song', { method: 'POST', body: new URLSearchParams({ clip: result.output_path }) });+ const cres = await cr.json();+ const at = Number(cres && cres.audio_start_time);+ if (cres && cres.ok && cres.anchor_image && Number.isFinite(at)+ && at > nextStart + EPS && at <= partEnd + EPS) {+ imagePath = cres.anchor_image;+ cropFocus = '';+ nextStart = at;+ anchored = true;+ }+ } catch (e) { /* fall through to the plain cut */ }+ if (!anchored) nextStart = partEnd;+ } else {+ nextStart = partEnd;+ }+ if (typeof poll === 'function') poll();+ }+ if (nextStart < totalDur - EPS) {+ const msg = 'Split stopped after ' + done + ' clips at ' + nextStart.toFixed(1)+ + 's — the rest of the song was not queued. The clips made are safe in Outputs.';+ if (status) status.textContent = msg;+ if (typeof phosToast === 'function') phosToast(msg, { kind: 'danger', duration: 8000 });+ return;+ }+ if (status) status.textContent = 'Split into ' + done + ' clips done — join them in the Editor.';+ if (typeof phosToast === 'function') {+ phosToast('Split into ' + done + ' clips finished — join them in the Editor.', { kind: 'success' });+ }}-async function audioStudioGenerate() {+async function audioStudioGenerate(opts) {+ opts = opts || {};+ const draft = !!opts.draft;if (AUDIO_STUDIO.busy) return;const status = document.getElementById('audioStudioStatus');- const btn = document.getElementById('audioStudioGenBtn');+ const btn = document.getElementById(draft ? 'audioStudioDraftBtn' : 'audioStudioGenBtn');const prompt = (document.getElementById('audioStudioPrompt').value || '').trim();if (!AUDIO_STUDIO.audioPath) {if (status) status.textContent = 'Audio file is required.';@@ -825,10 +1304,20 @@ async function audioStudioGenerate() {// (LTX latent grid requirement).const w = Math.max(32, Math.round(parseInt(document.getElementById('audioStudioWidth').value || '1024', 10) / 32) * 32);const h = Math.max(32, Math.round(parseInt(document.getElementById('audioStudioHeight').value || '576', 10) / 32) * 32);- // Duration from slider → frames at 8k+1 cadence the model expects.+ // Duration from slider → frames at 8k+1 cadence the model expects. Draft+ // clamps the SUBMITTED frame count only — the slider itself is left+ // alone, so it still shows the length Final will use.const dur = parseInt(document.getElementById('audioStudioDuration').value || '7', 10);- const frames = _a2vFramesForSeconds(dur);- const seed = parseInt(document.getElementById('audioStudioSeed').value || '-1', 10);+ const frames = _a2vFramesForSeconds(draft ? Math.min(3, dur) : dur);+ const seedEl = document.getElementById('audioStudioSeed');+ let seed = parseInt((seedEl && seedEl.value) || '-1', 10);+ if (draft && (!Number.isFinite(seed) || seed < 0)) {+ // Resolve -1 to a concrete seed NOW, client-side, and write it back —+ // Final needs to see the same number Draft is about to render with,+ // and the server would otherwise draw its own random seed per job.+ seed = Math.floor(Math.random() * 2147483647);+ if (seedEl) seedEl.value = String(seed);+ }// Auto = do not send the field at all; see audioConditioningScaleChanged.const acsEl = document.getElementById('audioConditioningScale');const audioConditioningScale = (acsEl && !acsEl.dataset.auto)@@ -838,6 +1327,14 @@ async function audioStudioGenerate() {// a negative start would be silently swallowed by load_audio.const audioStartEl = document.getElementById('audioStudioStart');const audioStart = Math.max(0, parseFloat((audioStartEl && audioStartEl.value) || '0') || 0);+ // VA-03: a start past the end of the known file renders pure silence —+ // refuse it the same way the missing-audio / missing-prompt checks do,+ // rather than spend 10-25 minutes finding out.+ if (AUDIO_STUDIO.audioDuration != null && audioStart >= AUDIO_STUDIO.audioDuration) {+ if (status) status.textContent = 'Start at (' + audioStart.toFixed(1)+ + ' s) is past the end of this file (' + AUDIO_STUDIO.audioDuration.toFixed(1) + ' s).';+ return;+ }AUDIO_STUDIO.busy = true;if (btn) btn.disabled = true;@@ -852,7 +1349,12 @@ async function audioStudioGenerate() {fd.set('mode', 'a2v');fd.set('prompt', prompt);fd.set('audio', AUDIO_STUDIO.audioPath);- if (a2vImagePath) fd.set('image', a2vImagePath);+ if (a2vImagePath) {+ fd.set('image', a2vImagePath);+ // VA-02: the crop-preview overlay's drag position for this picker.+ const focusEl = document.getElementById('a2v_image_crop_focus');+ fd.set('image_crop_focus', (focusEl && focusEl.value) || '0.5');+ }fd.set('width', String(w));fd.set('height', String(h));fd.set('frames', String(frames));@@ -861,6 +1363,9 @@ async function audioStudioGenerate() {fd.set('audio_conditioning_scale', String(audioConditioningScale));}fd.set('audio_start_time', String(audioStart));+ // VA-21: vocal-stem seam, exposed on the manual form for the first time.+ const stemAutoEl = document.getElementById('audioStudioStemAuto');+ if (stemAutoEl && stemAutoEl.checked) fd.set('audio_stem_auto', 'on');fd.set('quality', 'high'); // A2V is always pipeline-class (Q8 dev or Q4 distilled)// No accel, no enhance — A2V uses A2VidPipelineTwoStage's own walks.fd.set('accel', 'off');@@ -870,14 +1375,21 @@ async function audioStudioGenerate() {const slim = _activeLoras.map(l => ({ path: l.path, strength: l.strength }));fd.set('loras', JSON.stringify(slim));}+ fd.set('preset_label', (draft ? 'Draft' : (prompt.slice(0, 40) || 'Lip-sync')));const r = await fetch('/queue/add', { method: 'POST', body: fd });if (!r.ok) {const txt = await r.text();throw new Error('HTTP ' + r.status + ' ' + txt);}- if (status) status.textContent = 'Submitted. Watch Now / Recent.';+ if (status) {+ status.textContent = draft+ ? 'Draft queued (~3s, same seed) — check the mouth, then Generate the full clip.'+ : 'Submitted. Watch Now / Recent.';+ }if (typeof phosToast === 'function') {- phosToast('Queued Audio → Video clip · watch Now', { kind: 'success' });+ phosToast(draft+ ? 'Draft queued · ~3s at this seed — watch Now, then Generate for the full clip'+ : 'Queued Audio → Video clip · watch Now', { kind: 'success' });}const nowTab = document.querySelector('.tabs button[data-tab="now"]');if (nowTab) {@@ -1045,11 +1557,20 @@ function trainUpdatePresetNote() {'and no preset on this machine can reach it. Expect a weak adapter and treat the result as a look rather than an identity — that is the hardware, not your photos.';return;}+ // SYS-15: this used to lead with raw delta_rms numbers (lab jargon a+ // creator can't act on) while they were still picking a preset. Outcome+ // language up front; the measurement stays available for anyone who+ // wants it (or is filing a bug report) behind a details disclosure,+ // same pattern as the Now-card's own "Details for troubleshooting".el.innerHTML ='<strong>High is the only recipe ever graded on a face.</strong> ' +- 'Measured with <code>lora_compat.py</code>, rank-32 adapters that carry an identity sit at 5.4e-04 to 1.6e-03 delta_rms; ' +- 'Quick\'s rank 8 has measured 1.54e-04 and 1.98e-04 on real datasets, at or under the 2.0e-04 floor no working adapter has been below. ' +- 'Pick Quick for a fast look or a style, not for a person.';+ 'Pick Quick for a fast look or a style, not for a person — it has not ' ++ 'held an identity in any measured run. ' ++ '<details class="h3-diag"><summary>Measured numbers</summary>' ++ '<p>Measured with <code>lora_compat.py</code>: rank-32 (High) adapters ' ++ 'that carry an identity sit at 5.4e-04 to 1.6e-03 delta_rms. Quick\'s ' ++ 'rank 8 has measured 1.54e-04 and 1.98e-04 on real datasets — at or ' ++ 'under the 2.0e-04 floor no working adapter has been below.</p></details>';}function trainDisableSelectAbove(selectId, maxValue) {@@ -1819,7 +2340,45 @@ async function charactersLoadParams(p) {const TRAIN_MIN = Number(BOOT.train_min_images || 15);const TRAIN_MAX = Number(BOOT.train_max_images || 50);+// SYS-03: on a Mac under TRAIN_MIN_RAM_GB, /train/start has always+// refused (409) -- but only AFTER a user drops a whole dataset, captions+// it, and downloads 41 GB of LTX-2.3 weights the preflight card offers+// unconditionally. Gate the whole tab at the entry instead: every direct+// child of #trainSection except the gate card itself is hidden, and+// Generate never reaches the 41 GB offer or the dataset dropzone.+// Returns true when gated (caller should skip the rest of trainInit).+function trainApplyRamGate() {+ const card = document.getElementById('trainGateCard');+ const section = document.getElementById('trainSection');+ if (!card || !section) return false;+ const tier = (LAST_STATUS && LAST_STATUS.tier) || {};+ const ram = typeof tier.ram_gb === 'number' ? tier.ram_gb : null;+ const minRam = typeof tier.train_min_ram_gb === 'number' ? tier.train_min_ram_gb : 24;+ const gated = ram !== null && ram > 0 && ram < minRam;+ card.hidden = !gated;+ // Codex UI-7: this used to set every other child's `hidden` to `gated`+ // — on every /status poll — which overwrote+ // visibility the children own themselves: Style training hides the Voice+ // card, and the next poll un-hid it. The gate is a class on the section+ // now (panel.css hides every child but the gate card); no child's own+ // `hidden` is touched.+ section.classList.toggle('train-ram-gated', gated);+ if (gated) {+ document.getElementById('trainGateTitle').textContent =+ `Training a character needs a Mac with ${minRam} GB or more`;+ document.getElementById('trainGateBody').textContent =+ `This one has ${ram} GB — the trainer runs out of memory before it `+ + `finishes on this Mac, every time. You can still use characters: `+ + `try the sample character below, or a community-trained one.`;+ }+ return gated;+}+function trainInit() {+ // SYS-03: check the RAM gate before anything else runs — a gated Mac+ // never wires the drop zone, never renders presets, never shows the+ // 41 GB download offer.+ if (trainApplyRamGate()) return;// Idempotent — safe to call on every setMode('train') without re-binding// the drop zone. Triggers a list refresh too so the user sees the LoRAs// they trained in earlier sessions.@@ -1948,10 +2507,22 @@ async function trainCheckPreflight() {return;}box.style.display = 'block';+ // SYS-04: this used to disclose the cost piecemeal, one Download+ // button per row, with the actual total (41 GB across these two+ // downloads, on a build that already has everything else) never+ // stated anywhere. One combined total + one "Download all" that+ // runs them in sequence (the download lane is a singleton — only+ // one hf pull runs at a time, so this awaits each before starting+ // the next rather than firing them together).+ const totalGb = missing.reduce((sum, m) => sum + (Number(m.size_gb) || 0), 0);+ const q8ExtraNote = (LAST_STATUS && LAST_STATUS.q8_available)+ ? ''+ : ` Using a trained character afterward needs the separate 30 GB `+ + `Q8 pack too — that one's offered from Character mode when you get there.`;box.innerHTML = `<div class="train-preflight-card"><div class="train-preflight-title">- <svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>Required model${missing.length > 1 ? 's' : ''} not downloaded+ <svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>Get ready to train: ~${totalGb.toFixed(1)} GB (LTX-2.3 training weights)</div><div class="train-preflight-list">${missing.map(m => `@@ -1964,24 +2535,60 @@ async function trainCheckPreflight() {</div>`).join('')}</div>+ <div class="train-preflight-actions">+ <button type="button" class="btn btn-primary" id="trainInstallAllBtn">Download all (~${totalGb.toFixed(1)} GB)</button>+ </div><div class="train-preflight-foot">Phosphene installs only what it renders with. Training runs againstLTX-2.3 and needs its own weights, so they are downloaded on demandrather than shipped to everyone. Each download is resumable, and- nothing above is needed to render.+ nothing above is needed to render.${q8ExtraNote}</div></div>`;+ // Codex UI-4: the handler was an inline onclick="trainInstallAll([...])"+ // whose JSON's double quotes closed the double-quoted attribute, leaving+ // `trainInstallAll([` — a syntax error, so "Download all" did nothing.+ // Bound here instead, with the key list as a real array.+ const allKeys = missing.map(m => m.key);+ const allBtn = box.querySelector('#trainInstallAllBtn');+ if (allBtn) allBtn.onclick = () => trainInstallAll(allKeys);} catch (e) {box.style.display = 'none';}}-async function trainInstall(key) {+// SYS-04: "Download all" — runs the missing items through the SAME+// singleton download lane trainInstall() already uses, one at a time+// (only one hf pull can be active, so firing them concurrently would+// just 409 on the second). Each step awaits the preflight actually+// reporting that key ready before starting the next.+async function trainInstallAll(keys) {+ const btn = document.getElementById('trainInstallAllBtn');+ for (const key of keys) {+ if (btn) { btn.disabled = true; btn.textContent = 'Downloading…'; }+ await trainInstallAndWait(key);+ }+ trainCheckPreflight();+}++function trainInstallAndWait(key) {+ return new Promise((resolve) => {+ trainInstall(key, resolve);+ });+}++async function trainInstall(key, onDone) {// The panel parses POST bodies with parse_qs (urlencoded ONLY); a FormData// body serializes as multipart and reads back empty, so /train/install saw// key='' and returned "unknown install key" (reported by @cocktailpeanut,// 2026-06-04). Send urlencoded like every other POST in this panel.+ //+ // `onDone` (SYS-04, added for trainInstallAll's sequential "Download+ // all"): called once this KEY is ready, or once, on failure, so a+ // multi-item sequence never hangs waiting for a download that never+ // started. Optional — the plain single-button Download path ignores it.+ const finish = () => { if (typeof onDone === 'function') onDone(); };try {const r = await fetch('/train/install', {method: 'POST',@@ -1991,23 +2598,28 @@ async function trainInstall(key) {const data = await r.json();if (!data.ok) {alert('Download failed: ' + (data.error || r.status));+ finish();return;}// Progress streams to STATUS log. Re-poll preflight every 5s; banner- // self-hides when the file lands.+ // self-hides when the file lands. Watches THIS key specifically (not+ // "everything missing is now ready") so a sequential multi-download+ // resolves after each step instead of only after the last one.const watch = setInterval(async () => {try {const r2 = await fetch('/train/preflight');const d2 = await r2.json();- const stillMissing = (d2.required || []).filter(m => !m.ready).length;- if (stillMissing === 0) {+ const row = (d2.required || []).find(m => m.key === key);+ if (!row || row.ready) {clearInterval(watch);trainCheckPreflight();+ finish();}} catch (e) { /* ignore */ }}, 5000);} catch (e) {alert('Download request failed: ' + e.message);+ finish();}}@@ -2180,13 +2792,28 @@ async function trainUploadFiles(fileList) {// either type into the same zone — image_001.png + image_001.txt is the// intended workflow.const all = Array.from(fileList);+ // SYS-02: HEIC/HEIF/AVIF (macOS Photos/AirDrop's default hand-off) used+ // to fail BOTH tests here and get silently dropped from the selection —+ // no toast, no row in the grid, nothing. The server now converts them to+ // JPEG on upload (normalize_ingested_image_bytes); this filter just has+ // to stop throwing them away before they get there.const imgs = all.filter(f =>- /^image\/(png|jpe?g|webp)$/.test(f.type) ||- /\.(png|jpe?g|webp)$/i.test(f.name));+ /^image\/(png|jpe?g|webp|heic|heif|avif)$/.test(f.type) ||+ /\.(png|jpe?g|webp|heic|heif|avif)$/i.test(f.name));const caps = all.filter(f =>/\.txt$/i.test(f.name) || /^text\/plain$/.test(f.type));+ // SYS-10b: files that are neither an accepted image type nor a caption+ // used to just vanish from the drop with zero message. They're now named+ // in the persistent end-of-batch summary below instead of silently+ // dropped. (HEIC is accepted above since SYS-02 — the server converts it.)+ const rejected = all.filter(f => !imgs.includes(f) && !caps.includes(f))+ .map(f => `${f.name} (unsupported format)`);if (!imgs.length && !caps.length) {- if (status) status.textContent = 'No supported files in that selection (need PNG / JPG / WEBP / TXT).';+ if (status) {+ status.textContent = rejected.length+ ? `No supported files in that selection. Skipped: ${rejected.join(', ')}`+ : 'No supported files in that selection (need PNG / JPG / WEBP / HEIC / TXT).';+ }return;}const total = imgs.length + caps.length;@@ -2194,6 +2821,12 @@ async function trainUploadFiles(fileList) {let done = 0;let capThinWarnings = [];+ // Per-file failures (413 too-large, server error, network) used to only+ // ever live in status.textContent for the instant before the NEXT file's+ // "Uploaded N / total…" overwrote it — so a failure on file 2 of 6 was+ // invisible by the time file 3 finished. Collected here and folded into+ // the persistent end-of-batch summary instead.+ let failed = [];// ----- IMAGES (optimistic placeholders so the grid lights up immediately) -----for (let i = 0; i < imgs.length; i++) {@@ -2221,7 +2854,9 @@ async function trainUploadFiles(fileList) {const j = await r.json();if (!r.ok || !j.ok) {TRAIN.images.splice(placeholderIdx, 1);- if (status) status.textContent = 'Upload error: ' + (j.error || r.status);+ const reason = j.error || `HTTP ${r.status}`;+ failed.push(`${f.name} (${reason})`);+ if (status) status.textContent = 'Upload error: ' + reason;trainRenderThumbs();continue;}@@ -2241,7 +2876,9 @@ async function trainUploadFiles(fileList) {if (status) status.textContent = `Uploaded ${done} / ${total}…`;} catch (e) {TRAIN.images.splice(placeholderIdx, 1);- if (status) status.textContent = 'Upload failed: ' + (e.message || 'unknown');+ const reason = e.message || 'unknown';+ failed.push(`${f.name} (${reason})`);+ if (status) status.textContent = 'Upload failed: ' + reason;trainRenderThumbs();}}@@ -2256,7 +2893,9 @@ async function trainUploadFiles(fileList) {const r = await fetch('/train/upload', { method: 'POST', body: fd });const j = await r.json();if (!r.ok || !j.ok) {- if (status) status.textContent = 'Caption upload error: ' + (j.error || r.status);+ const reason = j.error || `HTTP ${r.status}`;+ failed.push(`${f.name} (${reason})`);+ if (status) status.textContent = 'Caption upload error: ' + reason;continue;}TRAIN.jobId = j.job_id;@@ -2266,7 +2905,9 @@ async function trainUploadFiles(fileList) {done += 1;if (status) status.textContent = `Uploaded ${done} / ${total}…`;} catch (e) {- if (status) status.textContent = 'Caption upload failed: ' + (e.message || 'unknown');+ const reason = e.message || 'unknown';+ failed.push(`${f.name} (${reason})`);+ if (status) status.textContent = 'Caption upload failed: ' + reason;}}if (caps.length) {@@ -2285,7 +2926,13 @@ async function trainUploadFiles(fileList) {if (capThinWarnings.length) {bits.push(`thin captions: ${capThinWarnings.slice(0, 3).join(', ')}${capThinWarnings.length > 3 ? '…' : ''}`);}+ const skipped = rejected.concat(failed);+ if (skipped.length) {+ bits.push(`${skipped.length} file${skipped.length === 1 ? '' : 's'} skipped: `+ + `${skipped.slice(0, 3).join(', ')}${skipped.length > 3 ? '…' : ''}`);+ }status.textContent = bits.join(' · ');+ status.classList.toggle('train-status-warn', skipped.length > 0);}trainUpdateEstimate();trainUpdateButtonState();@@ -2346,13 +2993,19 @@ function trainUpdateCounter() {if (!counter) return;const n = TRAIN.images.length;const captioned = TRAIN.images.filter(x => x.captioned).length;- counter.textContent = `${n} / ${TRAIN_MAX} images`;+ // SYS-36: this used to be "N / 500 images" -- TRAIN_MAX (500) is a+ // technical ceiling (mlx_ltx_panel.py's own comment calls the earlier+ // 50 "a friendly-default-misread-as-hard-rule"), not a target, so it+ // reads as a goal nobody should aim for. The sweet spot (20-50) is+ // what's worth stating; the hard ceiling only matters once someone is+ // actually near it.+ counter.textContent = `${n} image${n === 1 ? '' : 's'}`;counter.classList.toggle('ok', n >= TRAIN_MIN);counter.classList.toggle('short', n > 0 && n < TRAIN_MIN);if (hint) {- if (n === 0) hint.textContent = `need at least ${TRAIN_MIN} to train`;+ if (n === 0) hint.textContent = `${TRAIN_MIN} minimum · 20–50 is the sweet spot`;else if (n < TRAIN_MIN) hint.textContent = `need ${TRAIN_MIN - n} more`;- else if (n < TRAIN_MAX) hint.textContent = `ready · up to ${TRAIN_MAX - n} more if you want variety`;+ else if (n < TRAIN_MAX) hint.textContent = `ready · 20–50 is the sweet spot, more helps variety`;else hint.textContent = `at the ${TRAIN_MAX}-image limit`;}if (capChip) {@@ -2482,7 +3135,7 @@ async function trainAutoCaption() {if (label) label.textContent = 'Captioning…';if (prog) prog.hidden = false;if (fill) fill.style.width = '0%';- if (status) status.textContent = `Loading Gemma 3 (~3s)…`;+ if (status) status.textContent = `Loading the prompt helper (~3s)…`;const fd = new FormData();fd.set('train_job_id', TRAIN.jobId);fd.set('trigger', trig);@@ -2798,26 +3451,38 @@ function trainWireVoice() {trainRenderVoice();}+function _trainVoiceInlineError(msg) {+ const el = document.getElementById('trainVoiceInlineError');+ if (!el) return;+ if (msg) { el.textContent = msg; el.hidden = false; }+ else { el.hidden = true; el.textContent = ''; }+}+async function trainVoiceUpload(file) {if (!file) return;const status = document.getElementById('trainStatus');+ _trainVoiceInlineError(null);// The voice endpoint requires a dataset (job_id) — the user must drop- // at least one image first. Guard with a friendly message.+ // at least one image first. Guard with a friendly message, shown BOTH+ // on the card itself (SYS-10c) and on the shared status line.if (!TRAIN.jobId) {- if (status) status.textContent =- 'Upload at least one training image before adding a voice clip.';+ const msg = 'Upload at least one training image first — the voice clip attaches to that dataset.';+ if (status) status.textContent = msg;+ _trainVoiceInlineError(msg);return;}// Quick client-side extension + size check (server re-validates).const ext = (file.name.match(/\.[^.]+$/) || [''])[0].toLowerCase();if (!['.wav', '.mp3', '.m4a', '.flac'].includes(ext)) {- if (status) status.textContent =- `Unsupported audio type ${ext} — use WAV / MP3 / M4A / FLAC.`;+ const msg = `Unsupported audio type ${ext} — use WAV / MP3 / M4A / FLAC.`;+ if (status) status.textContent = msg;+ _trainVoiceInlineError(msg);return;}if (file.size > 50 * 1024 * 1024) {- if (status) status.textContent =- `Voice clip too large (${(file.size / 1024 / 1024).toFixed(1)} MB) — max 50 MB.`;+ const msg = `Voice clip too large (${(file.size / 1024 / 1024).toFixed(1)} MB) — max 50 MB.`;+ if (status) status.textContent = msg;+ _trainVoiceInlineError(msg);return;}try {@@ -2827,8 +3492,9 @@ async function trainVoiceUpload(file) {const r = await fetch('/train/upload-voice', { method: 'POST', body: fd });const j = await r.json();if (!r.ok || !j.ok) {- if (status) status.textContent =- 'Voice upload failed: ' + (j.error || r.status);+ const msg = 'Voice upload failed: ' + (j.error || r.status);+ if (status) status.textContent = msg;+ _trainVoiceInlineError(msg);return;}// Build a local object URL for the audio preview so we can play@@ -3050,6 +3716,36 @@ function trainFmtAge(ms) {return `${d}d ago`;}+// SYS-35: called from queue.js's notifyJobsDone the moment a mode='train'+// job finishes. /train/list is the same source trainRefreshLoraList()+// already renders from, so the newest entry by created_at IS the character+// that just finished — reused rather than trusting anything off the job+// dict itself, whose output shape for training differs from a render job's.+async function _trainAnnounceReady(job) {+ try {+ const r = await fetch('/train/list');+ const j = await r.json();+ const items = (j.loras || []);+ if (!items.length) return;+ const newest = items.reduce((a, b) =>+ (Number(b.created_at) || 0) > (Number(a.created_at) || 0) ? b : a);+ if (!newest || !newest.path || !newest.trigger) return;+ const el = phosToast(`Your character "${newest.trigger}" is ready.`,+ { kind: 'success', duration: 0 });+ if (!el) return;+ const a = document.createElement('a');+ a.href = '#';+ a.className = 'phos-toast-action';+ a.textContent = 'Make a clip with it';+ a.onclick = (ev) => {+ ev.preventDefault();+ el.remove();+ trainUseInVideo(newest.path, newest.trigger, 't2v');+ };+ el.appendChild(a);+ } catch (e) { /* best-effort */ }+}+function trainUseInVideo(loraPath, trigger, targetMode) {// Switch the panel into the requested video mode + pre-fill the LoRA// picker by emitting an "add" against the unified picker's state. The@@ -3130,9 +3826,19 @@ function setQuality(q) {// aspect choice. Quick is 4:3 only — landscape orientation only.const preset = QUALITY_PRESETS[q];const aspect = document.getElementById('aspect').value || 'landscape';- const vertical = (aspect === 'vertical' && q !== 'quick');- document.getElementById('width').value = vertical ? preset.h : preset.w;- document.getElementById('height').value = vertical ? preset.w : preset.h;+ if (q === 'quick') {+ document.getElementById('width').value = preset.w;+ document.getElementById('height').value = preset.h;+ } else {+ // VC-39: square (1:1) and 4:5 are fixed cells, shared with applyAspect+ // via _aspectDims so the two never disagree about what a pick renders.+ const dims = (typeof _aspectDims === 'function')+ ? _aspectDims(aspect, q)+ : { w: (aspect === 'vertical' ? preset.h : preset.w),+ h: (aspect === 'vertical' ? preset.w : preset.h) };+ document.getElementById('width').value = dims.w;+ document.getElementById('height').value = dims.h;+ }setUpscale(preset.upscale || 'off');// Hide the Aspect row when Quick is active (only 4:3 supported); show// it for Standard/High where 16:9 vs 9:16 is a real choice.@@ -3203,25 +3909,110 @@ function setTemporalMode(t) {updateDerived();}-// One line per window on screen, a JSON array on the wire — the same shape-// the H3 chain posts, so a curl and the form agree. The hint counts the-// windows the current length needs (ltx_windows: 121-frame windows, 112 new-// frames each) so the box says how many lines mean something.+// VA-18: one LABELLED, TIMED box per LATER window, a JSON array on the wire+// (same shape the H3 chain posts) whose index 0 is ALWAYS blank — window 1+// is always the main prompt above (ltx_windows.window_prompts' own+// contract), and there is now no UI control that can override it. This+// replaces a free-text textarea whose placeholder read "(first window uses+// the prompt above)⏎he turns to the window…" — the first REAL line typed+// there became index 0 and silently replaced the main prompt.+//+// Real per-window time ranges come from /ltx/windows_plan+// (ltx_windows.plan_windows, a pure function — same numbers the engine's+// own chain will use), not a client-side re-derivation that could drift+// from the server's rounding.+let _windowsPlanCache = { frames: null, plan: null };+let _windowsPlanFetching = null;function windowPromptsInput() {- const ta = document.getElementById('window_prompts_text');+ const out = document.getElementById('window_prompts');+ const wrap = document.getElementById('windowsDynamicSlots');+ if (!out || !wrap) return;+ // Only fetch/render while Windows mode is actually selected — this runs+ // on every updateDerived() call (every frames/duration/width/height+ // edit, in every mode), so a mode guard keeps it from hitting the+ // endpoint on unrelated keystrokes.+ const tmode = (document.getElementById('temporal_mode') || {}).value;+ if (tmode !== 'windows') return;+ const f = parseInt(document.getElementById('frames')?.value || '121', 10) || 121;+ if (_windowsPlanCache.frames === f && _windowsPlanCache.plan) {+ _renderWindowsSlotsFromPlan(_windowsPlanCache.plan);+ return;+ }+ if (_windowsPlanFetching === f) return; // already in flight for this length+ _windowsPlanFetching = f;+ fetch('/ltx/windows_plan?frames=' + f).then(r => r.json()).then(plan => {+ if (_windowsPlanFetching === f) _windowsPlanFetching = null;+ if (!plan || !plan.ok) return;+ // LIPSYNC-9: a plan for a length the form no longer shows is stale — two+ // quick length changes can answer out of order, and the older, shorter+ // plan used to redraw the boxes (dropping later windows' typed text) and+ // take the cache slot from the current one.+ const nowFrames = parseInt(document.getElementById('frames')?.value || '121', 10) || 121;+ const nowMode = (document.getElementById('temporal_mode') || {}).value;+ if (nowFrames !== f || nowMode !== 'windows') return;+ _windowsPlanCache = { frames: f, plan };+ _renderWindowsSlotsFromPlan(plan);+ }).catch(() => { if (_windowsPlanFetching === f) _windowsPlanFetching = null; });+}+function _fmtMinSec(sec) {+ sec = Math.max(0, Number(sec) || 0);+ const m = Math.floor(sec / 60), s = Math.floor(sec % 60);+ return m + ':' + String(s).padStart(2, '0');+}+function _renderWindowsSlotsFromPlan(plan) {+ const wrap = document.getElementById('windowsDynamicSlots');const out = document.getElementById('window_prompts');const hint = document.getElementById('windowsHint');- if (!ta || !out) return;- const lines = String(ta.value || '').split('\n').map(s => s.trim());- while (lines.length && !lines[lines.length - 1]) lines.pop();- out.value = lines.length ? JSON.stringify(lines) : '';+ if (!wrap || !out) return;+ const n = plan.count || 1;if (hint) {- const f = parseInt(document.getElementById('frames')?.value || '121', 10) || 121;- const n = f <= 121 ? 1 : 1 + Math.ceil((f - 121) / 112);hint.textContent = n <= 1? 'this length fits one window — pick a longer clip'- : n + ' windows · one line per window · blank holds the last moment';+ : n + ' windows · window 1 is the prompt above · blank holds the last moment';+ }+ if (n <= 1) {+ wrap.innerHTML = '<div class="hint">This length renders in one pass — no per-window prompts needed.</div>';+ out.value = '';+ return;}+ // Preserve already-typed text for a window index that survives a+ // duration change (20s -> 15s keeps windows 2-3's lines) — UNLESS a Load+ // Params restore is pending, which wins (it is a deliberate reopen of a+ // specific clip's exact recipe, not an in-progress edit).+ const previous = {};+ wrap.querySelectorAll('textarea[data-window-index]').forEach(t => {+ previous[t.dataset.windowIndex] = t.value;+ });+ const restore = (typeof window !== 'undefined') ? window._pendingWindowPromptsRestore : null;+ if (typeof window !== 'undefined') window._pendingWindowPromptsRestore = null; // consume once+ const rows = (plan.windows || []).slice(1); // window 0 has no box — it's the main prompt+ wrap.innerHTML = rows.map(w => {+ const label = 'Window ' + (w.index + 1) + ' · ' + _fmtMinSec(w.start_sec) + '–' + _fmtMinSec(w.end_sec);+ return '<div class="mf-cell" style="margin-top:6px">'+ + '<span class="mf-label">' + escapeHtml(label) + '</span>'+ + '<textarea class="sb-textarea" rows="2" data-window-index="' + w.index + '" '+ + 'oninput="_windowsSlotChanged()" placeholder="the next beat, led by the movement — blank holds the previous moment"></textarea>'+ + '</div>';+ }).join('');+ rows.forEach(w => {+ const el = wrap.querySelector('textarea[data-window-index="' + w.index + '"]');+ if (!el) return;+ const fromRestore = Array.isArray(restore) ? restore[w.index] : undefined;+ el.value = (fromRestore !== undefined && fromRestore !== null)+ ? fromRestore : (previous[String(w.index)] || '');+ });+ _windowsSlotChanged();+}+function _windowsSlotChanged() {+ const wrap = document.getElementById('windowsDynamicSlots');+ const out = document.getElementById('window_prompts');+ if (!wrap || !out) return;+ const boxes = Array.from(wrap.querySelectorAll('textarea[data-window-index]'))+ .sort((a, b) => Number(a.dataset.windowIndex) - Number(b.dataset.windowIndex));+ // Index 0 is ALWAYS blank — window 1 is the main prompt, by construction.+ const lines = [''].concat(boxes.map(b => b.value.trim()));+ while (lines.length && !lines[lines.length - 1]) lines.pop();+ out.value = lines.length ? JSON.stringify(lines) : '';}function setUpscale(u) {const v = ['off', 'fit_720p', 'x2'].includes(u) ? u : 'off';@@ -3323,6 +4114,47 @@ function updateShotSetupSummary() {let eta = '';try { eta = h3CellEta(cell); } catch (_) {}if (eta) parts.push(eta);+ // H3-08: the closed section named quality/length/speed/eta but never+ // said whether any LoRA was going to influence the render at all —+ // the LoRA panel is its own disclosure, further down, easy to miss.+ // Lane lookup mirrors _serializeLoras()'s _laneOf (loras.js): the+ // active entry itself carries no reliable lane, _knownUserLoras does.+ try {+ const laneOf = (p) => {+ const u = Array.isArray(_knownUserLoras)+ ? _knownUserLoras.find(x => x.path === p) : null;+ return (u && u.lane) || 'ltx';+ };+ const n = (Array.isArray(_activeLoras) ? _activeLoras : [])+ .filter(a => a && laneOf(a.path) === 'h3').length;+ if (n > 0) parts.push(n + (n === 1 ? ' LoRA' : ' LoRAs'));+ } catch (_) {}+ } else if (currentMode === 'keyframe' || currentMode === 'extend') {+ // VA-11 / VA-12: these two modes run a pipeline the Quality strip's+ // selected cell does NOT describe (keyframe is always Q8 two-stage at+ // this Mac's clamp; extend runs its own step count) — read the real,+ // server-computed price instead of ltxCellFor's cell.+ const tier = (typeof BOOT !== 'undefined' && BOOT.tier) || {};+ let card = null, pending = false;+ if (currentMode === 'keyframe') {+ // EST-7: priced for the duration and canvas the form holds, not 5 s.+ const kp = (typeof keyframePriceFor === 'function')+ ? keyframePriceFor() : { card: tier.keyframe_price, pending: false };+ card = kp.card; pending = kp.pending;+ parts.push('Q8 two-stage');+ } else {+ const proOn = (document.getElementById('extend_steps') || {}).value === '30';+ card = proOn ? tier.extend_price_pro : tier.extend_price_draft;+ parts.push(proOn ? 'Q8 Pro' : 'Q8 Draft');+ }+ if (card && pending) {+ parts.push('pricing…');+ } else if (card) {+ parts.push(`${card.width}×${card.height}`);+ parts.push(card.eta);+ } else {+ parts.push('needs more memory than this Mac has');+ }} else {let cell = null;try { cell = ltxCellFor(ltxCurrentQuality(), ltxCurrentLength()); } catch (_) {}@@ -3352,8 +4184,26 @@ function updateFinishSummary() {const parts = [];if (document.body.dataset.engine === 'h3') {const up = (document.getElementById('h3_upscale') || {}).value || 'off';- if (up === 'fit_720p') parts.push('720p export');- else if (up === 'fit_1080p') parts.push('1080p export');+ // H3-38: bare "720p export" on a Draft cell (640×384, a 1.875× lanczos+ // stretch) reads as "this shipped at 720p detail" — it didn't, the+ // source canvas decided the detail and this pass only fills the frame.+ // Say the upscale explicitly whenever the source is below the 720p+ // long side; a cell that's already there (High · 720p) keeps the plain+ // label because nothing is being stretched.+ let cell = null;+ try { cell = (typeof h3CurrentCell === 'function') ? h3CurrentCell() : null; } catch (_) {}+ const upscaling720 = cell && Math.max(cell.width, cell.height) < 1280;+ const upscaling1080 = cell && Math.max(cell.width, cell.height) < 1920;+ if (up === 'fit_720p') {+ parts.push(upscaling720+ ? `720p export (upscaled from ${cell.width}×${cell.height}, not added detail)`+ : '720p export');+ }+ else if (up === 'fit_1080p') {+ parts.push(upscaling1080+ ? `1080p export (upscaled from ${cell.width}×${cell.height}, not added detail)`+ : '1080p export');+ }else if (up === 'ltx_x2') parts.push('native + Upscale & Face Fix after');else parts.push('native export');} else {@@ -3417,12 +4267,50 @@ function setExtendMode(m) {// Fast = no-CFG path, fits in 64 GB at 1280×704. Quality = upstream// defaults, requires headroom. Both are exposed on the form via hidden// inputs; this just flips the values + active pill.- const steps = m === 'quality' ? 30 : 12;+ //+ // VA-12: Draft used to send 12 steps here — 50% slower than the+ // validated default (owner ruling 2026-05-21, mlx_ltx_panel.py's extend+ // branch: "steps cut from 12 -> 8"). The server has defaulted to 8 for a+ // while; this client value was silently overriding it back up to 12 on+ // every Draft render.+ const steps = m === 'quality' ? 30 : 8;const cfg = m === 'quality' ? 3.0 : 1.0;document.getElementById('extend_steps').value = String(steps);document.getElementById('extend_cfg').value = String(cfg);document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b =>b.classList.toggle('active', b.dataset.extendMode === m));+ if (typeof updateDerivedForClampedMode === 'function') updateDerivedForClampedMode('extend');+ if (typeof updateShotSetupSummary === 'function') { try { updateShotSetupSummary(); } catch (e) {} }+}++// VA-12: rewrite the Extend pill subtitles from the server's real,+// clamped-canvas price instead of the hardcoded "12 steps · ~16 min" /+// "30 steps · ~38 min" HTML — and hide Q8 Pro below the tier where it+// pushes the render into swap (the pill's own hint already warned about+// this; now the pill itself doesn't offer it there).+function applyExtendPillPrices() {+ const tier = (typeof BOOT !== 'undefined' && BOOT.tier) || {};+ const group = document.getElementById('extendModeGroup');+ if (!group) return;+ const draftBtn = group.querySelector('[data-extend-mode="fast"]');+ const proBtn = group.querySelector('[data-extend-mode="quality"]');+ const fill = (btn, card, stepsLabel) => {+ if (!btn || !card) return;+ const spec = btn.querySelector('.ql-spec');+ const tierEl = btn.querySelector('.ql-tier');+ if (spec) spec.textContent = `${stepsLabel} · ${card.width}×${card.height} safe`;+ if (tierEl) tierEl.textContent = `${card.pipeline_note} · ${card.eta}`;+ };+ fill(draftBtn, tier.extend_price_draft, '8 steps');+ fill(proBtn, tier.extend_price_pro, '30 steps');+ // Pro pushes the render past what Comfortable/Compact tiers can hold+ // resident (the hint text already said so) — hide it below "high" rather+ // than let it look like an equally-safe option.+ if (proBtn) {+ const proSafe = tier.key === 'high' || tier.key === 'pro';+ proBtn.hidden = !proSafe;+ if (!proSafe && proBtn.classList.contains('active')) setExtendMode('fast');+ }}function updatePromptPlaceholder() {@@ -3448,10 +4336,14 @@ function updatePromptPlaceholder() {// mode. The click handler chooses the 2- or 3-frame UI after setMode()// restores the shared keyframe screen.document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.onclick = () => {+ // Lip-sync (VA-01) isn't a #genForm mode — it's a jump to the Audio tab's+ // audio-driven form, which submits through its own path+ // (audioStudioGenerate). Keep it out of setMode()'s dispatch entirely.+ if (b.dataset.lipsync) { openLipSyncEntry(); return; }setMode(b.dataset.mode);if (b.dataset.mode === 'keyframe') {const def = b.dataset.kfDefault || '2';- const fallback = parseInt(document.getElementById('keyframe_count')?.value || '6', 10);+ const fallback = parseInt(document.getElementById('keyframe_count')?.value || '3', 10);setKeyframeMode(def === 'multi' ? fallback : parseInt(def, 10));}});@@ -3529,21 +4421,34 @@ Object.assign(globalThis, {musicLoraPicks, musicLoraRender, musicLoraToggled, musicLoraSummaryText,musicLoraInstallCard, musicLoraInstall, musicFetchCard,windowPromptsInput,+ // VA-18: _windowsSlotChanged is an inline onclick/oninput target on the+ // generated per-window textareas.+ _windowsSlotChanged,audioStudioInit, audioStudioDurationChanged, audioStudioEnhancePrompt, audioStudioGenerate,audioConditioningScaleChanged, audioConditioningScaleReset, a2vLoadParams,trainRecommendedPreset, trainUpdatePresetButtons, trainUpdatePresetNote, downloadSampleCharacter,charactersInit, charactersRenderChips, charactersOpenCompose, charactersBackToGrid,charactersHandleAudioUpload, charactersClearAudio, charactersUpdateStrengthDisplay, charactersSyncStrengthControls,charactersGenerate, charactersEscapeHtml, charactersEscapeAttr, _restoreCharacterStrengths,- charactersLoadParams, trainInit, trainGuidanceDismiss, trainCheckPreflight,+ charactersLoadParams, trainInit, trainApplyRamGate, trainGuidanceDismiss, trainCheckPreflight,trainSuggestTrigger, trainClearAll, trainAutoCaption, trainStart,trainVoiceRemove, trainVoiceToggleChanged, trainRefreshLoraList, trainRenderVerdictBanner,+ _trainAnnounceReady,setQuality, _qualityUsesHq, setAccel, setTemporalMode,setUpscale, setUpscaleMethod, updateAccelAvailability, updateTemporalAvailability,setAspect, updateCustomizeSummary, updatePromptPlaceholder,updateShotSetupSummary, updateFinishSummary, updateAdvancedSummary,+ setExtendMode, applyExtendPillPrices,// inline-handler targets: generated markup resolves these through the// global scope (the v4.9.0 regression, PR #69)- audioStudioClearAudio, charactersPickChip, trainInstall, trainRemoveImage,+ audioStudioClearAudio, charactersPickChip, trainInstall, trainInstallAll, trainRemoveImage,trainUseInVideo,+ // VA-01 / VA-04 / VA-20: openLipSyncEntry is an inline onclick target from+ // both the mode-bar chip's delegate (same file, would work unpublished)+ // and the mux-warning link in index.html (a different module's markup —+ // needs the global). audioStudioRenderLoraNote's own onclick lives in the+ // string it builds, so it needs the global too.+ openLipSyncEntry, audioStudioRenderLoraNote,+ audioStudioPromptCheck, audioStudioPromptApplyFix, audioStudioMouthCheck,+ audioStudioSplitIntoClips, audioStudioSplitCancel,});diff --git a/webapp/js/editor.js b/webapp/js/editor.jsindex 93f5ac7..59da4ad 100644--- a/webapp/js/editor.js+++ b/webapp/js/editor.js@@ -196,7 +196,7 @@ function sbeStripGain(y, top, H) {window.SBE = {open: false, id: '', title: '',edit: null, clips: [], audio: null, beats: null,- peaks: null, peaksFor: '', unplaced: [], pool: [], relink: [], prepare: {},+ peaks: null, peaksFor: '', unplaced: [], pool: [], relink: [], offline: [], prepare: {},onMissing: null,proxyUrl: '', revision: 0, dirty: false, saving: false, conflict: 0,// THE SAVE'S OWN BOOKKEEPING. `savePending` is the save that arrived while@@ -251,7 +251,8 @@ window.SBE = {// The soundtrack's own drag. Separate from `drag` because the two lanes are// separate objects and a pointer is only ever on one of them.musicDrag: null, audioDrag: null,- music: '', musicEl: null, musicOk: true, rendering: false, muteToasted: false,+ music: '', musicEl: null, musicOk: true, rendering: false, renderJob: '',+ renderPollTimer: null, muteToasted: false,// `dropAt` is where the insertion line is painted while something is being// dragged onto the track — null when nothing is. `lastTs` is the wall clock// the transport falls back on for the clips that carry no <video> to read a@@ -2782,6 +2783,94 @@ function sbeTrim(clips, id, edge, filmTime, opts) {return { clips: clips, ok: true };}+// FILM-03: SLIP. Every cut on a music video is butt-joined, so the only way+// to fix a mouth that is off the words is to change WHICH SECONDS OF THE+// TAKE play in a slot that does not move. A trim changes the slot's length;+// a slip does not touch it at all — `start` and `end` move together by the+// same source-second delta, `film_start`/`film_end` are untouched, and the+// move is clamped so the window never runs off the source. Because the slot+// is unchanged, the neighbours, the gaps and any linked/unlinked sound need+// no carry — nothing about the film's TIMING moved, only what is shown in it.+function sbeSlip(clips, id, deltaSrcSeconds) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const len = sbeNum(c.end) - sbeNum(c.start);+ if (len <= 0) return { clips: clips, ok: false, why: 'edge' };+ const srcDur = sbeNum(c.duration, 0) || Infinity;+ let start = sbeNum(c.start) + sbeNum(deltaSrcSeconds);+ start = Math.max(0, Math.min(srcDur - len, start));+ const applied = sbeRound(start - sbeNum(c.start));+ if (Math.abs(applied) < 1e-9) {+ return { clips: clips, ok: false,+ why: (deltaSrcSeconds < 0 ? 'Already at the start of the take — nothing to give.'+ : 'Already at the end of the take — nothing to give.') };+ }+ c.start = sbeRound(sbeNum(c.start) + applied);+ c.end = sbeRound(sbeNum(c.end) + applied);+ c.source = 'human';+ return { clips: clips, ok: true, applied: applied };+}++// One frame (⇧ for ten) at a time — the keyboard half of slip, the same+// shape as `sbeNudge` one function up. ⌥, and ⌥. so the plain arrows stay+// the playhead's and ⌥←/→ stays the whole-clip nudge.+function sbeSlipNudge(dir, big) {+ const id = SBE.sel;+ if (!id) return;+ const c = sbeById(SBE.clips, id);+ if (!c || sbeKind(c) !== 'video') return;+ const d = ((big ? 10 : 1) * (dir < 0 ? -1 : 1)) / sbeFps() * sbeSpeed(c);+ const ok = sbeMutate(cs => sbeSlip(cs, id, d));+ if (ok) {+ phosToast('Slipped ' + (d > 0 ? '+' : '') + Math.round(d * sbeFps() / sbeSpeed(c)) + ' f.',+ { duration: 2000 });+ }+}++// FILM-03: ROLL. The cut between two shots is one point in the film; a roll+// moves that point without moving anything else — the shot before gets+// longer by exactly what the shot after gets shorter, the total length of+// the pair (and the whole film) does not change, and neither picture's OWN+// trim moves at its far end. Only legal on a SHARED cut — `prev.film_end ===+// next.film_start`, i.e. no hole between them — which is the one place a+// plain trim's "grow into the gap" rule has no room to work with (the gap is+// zero), and exactly the case Premiere's roll tool exists for.+function sbeRollEdit(clips, prevId, nextId, deltaFilmSeconds) {+ const prev = sbeById(clips, prevId);+ const next = sbeById(clips, nextId);+ if (!prev || !next) return { clips: clips, ok: false, why: 'gone' };+ if (prev.locked || next.locked) return { clips: clips, ok: false, why: 'locked' };+ if (Math.abs(sbeNum(prev.film_end) - sbeNum(next.film_start)) > 1e-6) {+ return { clips: clips, ok: false, why: 'Those two shots do not share a cut.' };+ }+ const spPrev = sbeSpeed(prev), spNext = sbeSpeed(next);+ let d = sbeNum(deltaFilmSeconds);+ // Neither side may shrink past the minimum clip length, and neither may+ // grow past what its OWN take has left at that end.+ const prevLen = sbeNum(prev.film_end) - sbeNum(prev.film_start);+ const nextLen = sbeNum(next.film_end) - sbeNum(next.film_start);+ const prevRoom = sbeNum(prev.duration, 0) ? (sbeNum(prev.duration) - sbeNum(prev.end)) / spPrev : Infinity;+ const nextRoom = sbeNum(next.start) / spNext;+ const hi = Math.min(prevRoom, nextLen - SBE_MIN_CLIP);+ const lo = Math.max(-nextRoom, -(prevLen - SBE_MIN_CLIP));+ d = sbeRound(Math.max(lo, Math.min(hi, d)));+ if (Math.abs(d) < 1e-9) {+ return { clips: clips, ok: false,+ why: (deltaFilmSeconds < 0 ? 'The shot before is already as short as it can be.'+ : 'The shot after is already as short as it can be.') };+ }+ // Only the SOURCE windows move by hand; `_gap` before each clip is+ // untouched (next's stays 0 — still no hole), so `sbeLayout` derives both+ // new positions from the new lengths and the cut lands exactly at the+ // moved point, same as it was a single boundary all along.+ prev.end = sbeRound(sbeNum(prev.end) + d * spPrev);+ next.start = sbeRound(sbeNum(next.start) + d * spNext);+ prev.source = 'human'; next.source = 'human';+ sbeLayout(clips);+ return { clips: clips, ok: true, applied: d };+}+// DUPLICATE: the same shot again, right after itself, with everything it// carries — window, speed, fades, grade, mute — and its sound LINKED: a// copied J-cut strip would sit under the original's seconds, which is the@@ -2908,6 +2997,167 @@ function sbeNewId() {(Date.now() % 65536).toString(16);}+// ---------------------------------------------------------------------------+// FILM-58: COPY / PASTE — clips, or attributes onto a selection.+// ---------------------------------------------------------------------------+// What a "paste attributes" carries: everything about HOW a shot is shown,+// nothing about what it IS or where it sits.+const SBE_PASTE_ATTR_FIELDS = ['adjust', 'frame', 'fx', 'speed'];++function sbeClipboardCopy(clips, ids) {+ const items = (ids || []).map(id => sbeById(clips, id)).filter(Boolean)+ .map(c => JSON.parse(JSON.stringify(c)));+ items.sort((a, b) => sbeNum(a.film_start) - sbeNum(b.film_start));+ return items;+}++// PASTE ATTRIBUTES, from the one clip copied, onto every clip in `ids` —+// grade, frame, fades and speed; never the path, the window or the slot.+function sbeClipboardPasteAttrs(clips, ids, source) {+ if (!source) return { clips: clips, ok: false, why: 'nothing copied' };+ let out = clips.slice();+ let touched = 0;+ for (const id of ids || []) {+ const i = out.findIndex(c => String(c.id) === String(id));+ if (i < 0) continue;+ const c = out[i];+ if (c.locked || sbeKind(c) === 'slug') continue;+ const b = Object.assign({}, c);+ for (const f of SBE_PASTE_ATTR_FIELDS) {+ // EDITOR-5 (Codex 4.17.0): SPEED IS TIMING, NOT A LOOK. Copied as a+ // field it changed the clock while the window and the slot stayed put+ // — a 5 s window at 2x in a 5 s slot, which Save and the backup+ // refused (clip_length_mismatch). It goes through the one speed+ // operation below, which re-lays the film; a still has no clock.+ if (f === 'speed') continue;+ if (source[f] !== undefined) b[f] = JSON.parse(JSON.stringify(source[f])); else delete b[f];+ }+ out[i] = b;+ if (sbeKind(b) === 'video' && sbeKind(source) === 'video') {+ const r = sbeSetSpeed(out, b.id, sbeSpeed(source));+ if (r.ok) out = r.clips;+ }+ touched++;+ }+ return { clips: out, ok: touched > 0, why: touched ? '' : 'nothing to paste onto' };+}++// PASTE CLIPS, inserted at a film time in copied order — each a new clip+// (new id), carrying the source's own look (grade/frame/fx/speed) with it,+// the same "insert, ripple everything after" `sbeInsertAt` already does.+function sbeClipboardPasteClips(clips, items, at) {+ let cs = clips;+ let want = Math.max(0, sbeNum(at));+ const added = [];+ for (const src of items || []) {+ const kind = sbeKind(src);+ const filmLen = Math.max(SBE_MIN_CLIP,+ (sbeNum(src.end, 0) - sbeNum(src.start, 0)) / (sbeSpeed(src) || 1));+ const item = { path: src.path, proxy: src.proxy || null, kind: kind,+ duration_s: filmLen, title: src.title || '', n: src.n };+ const r = sbeInsertAt(cs, item, want);+ if (!r.ok) continue;+ cs = r.clips;+ const c = sbeById(cs, r.added.id);+ if (c) {+ if (src.adjust) c.adjust = JSON.parse(JSON.stringify(src.adjust));+ if (src.frame) c.frame = JSON.parse(JSON.stringify(src.frame));+ if (src.fx) c.fx = JSON.parse(JSON.stringify(src.fx));+ if (src.speed !== undefined) c.speed = src.speed;+ if (kind === 'video') {+ const sp = sbeSpeed(c);+ c.start = sbeRound(sbeNum(src.start, 0));+ c.end = sbeRound(sbeNum(src.start, 0) + filmLen * sp);+ c.duration = src.duration || null;+ }+ }+ added.push(r.added.id);+ want += filmLen;+ }+ return { clips: cs, ok: added.length > 0, added: added,+ why: added.length ? '' : 'nothing could be pasted' };+}++function sbeClipCopy() {+ const ids = sbeSelIds();+ if (!ids.length) { phosToast('Select a clip first.', {}); return; }+ SBE.clipboard = sbeClipboardCopy(SBE.clips, ids);+ phosToast((SBE.clipboard.length === 1 ? 'Clip copied.' : SBE.clipboard.length + ' clips copied.'),+ { duration: 2500 });+}+// ONE COMMAND, TWO MEANINGS — the same split Premiere spreads across Paste+// and Paste Attributes: with something selected, ⌘V pastes the copied+// clip's LOOK onto it (grade, frame, fades, speed); with nothing selected,+// or more than one clip copied, it pastes the clip(s) themselves at the+// playhead. Both are named in the toast, so which one just happened is+// never a guess.+function sbeClipPaste() {+ if (!SBE.open || !SBE.id) return;+ const clip = SBE.clipboard || [];+ if (!clip.length) { phosToast('Nothing copied yet — ⌘C a clip first.', {}); return; }+ const selIds = sbeSelIds();+ if (clip.length === 1 && selIds.length >= 1) {+ const ok = sbeMutate(cs => sbeClipboardPasteAttrs(cs, selIds, clip[0]));+ if (ok) {+ phosToast('Grade, frame, fades and speed pasted onto ' + selIds.length+ + (selIds.length === 1 ? ' clip.' : ' clips.'), { kind: 'success', duration: 4000 });+ }+ return;+ }+ const ok = sbeMutate(cs => sbeClipboardPasteClips(cs, clip, SBE.playhead));+ if (ok) {+ phosToast((clip.length === 1 ? 'Clip' : clip.length + ' clips') + ' pasted at '+ + sbeFmtTime(SBE.playhead) + '.', { kind: 'success', duration: 4000 });+ }+}++// ---------------------------------------------------------------------------+// FILM-58: SEQUENCE ASPECT — 16:9 / 9:16 / 1:1, a whole-film choice the same+// shape Film look is: stored in `edit.settings`, so it reaches the render+// AND stays true for whoever opens the __SEQ__ next.+// ---------------------------------------------------------------------------+const SBE_SEQ_ASPECTS = { '16:9': 16 / 9, '9:16': 9 / 16, '1:1': 1 };+function sbeSeqAspect() {+ const key = ((SBE.edit || {}).settings || {}).aspect;+ return (key && SBE_SEQ_ASPECTS[key]) ? key : '16:9';+}+function sbeSetSeqAspect(key) {+ if (!SBE.open || !SBE.id) return;+ if (!SBE_SEQ_ASPECTS[key]) return;+ SBE.edit = SBE.edit || {};+ SBE.edit.settings = Object.assign({}, SBE.edit.settings || {}, { aspect: key });+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaintChrome();+ sbeQueueSave();+}++// ---------------------------------------------------------------------------+// FILM-58: MARKERS — beat and lyric cues, on their own lane on the ruler.+// A marker names a SECOND, not a clip; it survives every re-cut, re-take+// and reorder untouched, which is the point — a beat the Director cut to+// stays where the beat is even after the shot at that second changes three+// times. `kind` is `beat` | `lyric` | `note`, all painted the same way and+// told apart by colour and the tooltip.+// ---------------------------------------------------------------------------+function sbeMarkerAdd(markers, at, kind, label) {+ const m = { id: sbeNewId(), at: Math.max(0, sbeRound(sbeNum(at))),+ kind: (kind || 'note'), label: String(label || '') };+ return (markers || []).concat([m]).sort((a, b) => sbeNum(a.at) - sbeNum(b.at));+}+function sbeMarkerRemove(markers, id) {+ return (markers || []).filter(m => String(m.id) !== String(id));+}+function sbeMarkerSetLabel(markers, id, label) {+ return (markers || []).map(m => String(m.id) === String(id)+ ? Object.assign({}, m, { label: String(label || '') }) : m);+}+function sbeMarkerSetKind(markers, id, kind) {+ const k = (kind === 'beat' || kind === 'lyric') ? kind : 'note';+ return (markers || []).map(m => String(m.id) === String(id)+ ? Object.assign({}, m, { kind: k }) : m);+}+// A clip the board has rendered but the timeline has never seen. `slot` is// where the person who ordered it wanted it — carried on the board by// edit/generate — so a shot generated for a hole lands in that hole rather than@@ -2952,6 +3202,72 @@ function sbePlaceUnplaced(clips, item, filmStart) {return { clips: out, ok: true, added: c };}+// FILM-08: REPLACE. "Place" and pool "+" always APPEND — swapping one shot+// in a 52-shot music video meant pushing every later shot off the beat, or+// doing an overwrite by hand. Replace is the other half: the SLOT does not+// move (film_start/film_end, so nothing else on the film shifts), and+// neither do the things that belong to the slot rather than the take —+// adjustments, frame, fx, transitions, lock. Only the source changes: path,+// proxy and the in/out window, its in-point clamped to whatever the new take+// actually has. A take too short to fill the slot is refused (EDITOR-4).+function sbeReplaceClip(clips, id, item) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const filmLen = Math.max(SBE_MIN_CLIP, sbeNum(c.film_end) - sbeNum(c.film_start));+ const i = clips.indexOf(c);+ // A STILL HAS NO SOURCE WINDOW OF ITS OWN — it holds for its slot, at 1x,+ // the way the server derives it (normalise_edit). The kind follows the+ // new source: a picture swapped in for a video used to stay `kind: video`+ // and play a .png through a <video> element.+ if (item.kind === 'still') {+ const st = Object.assign({}, c, {+ kind: 'still', path: item.path, proxy: item.proxy || null,+ duration: null, start: 0, end: sbeRound(filmLen),+ n: (item.n !== undefined ? item.n : c.n),+ title: item.title || c.title, source: 'human',+ });+ delete st.speed;+ const outS = clips.slice();+ outS[i] = st;+ return { clips: outS, ok: true, replaced: st };+ }+ const sp = sbeSpeed(c);+ const need = filmLen * sp;+ const srcDur = sbeNum(item.duration_s, 0) || need;+ // EDITOR-4 (Codex 4.17.0): A TAKE SHORTER THAN THE SLOT CANNOT FILL IT.+ // This used to clamp `end` to the take and keep the slot, answering ok:+ // a 4 s take in a 5 s slot — a `clip_length_mismatch` document that+ // blocked Save, the crash backup and Render until it was undone. The slot+ // is the promise Replace makes (nothing else on the film moves), so a+ // take that cannot keep it is refused, with the numbers.+ if (srcDur + 0.001 < need) {+ const f = v => (Math.round(v * 10) / 10).toFixed(1) + 's';+ return { clips: clips, ok: false,+ why: 'That take is ' + f(srcDur) + ' long and this slot needs ' ++ f(need) + (Math.abs(sp - 1) > 1e-9 ? ' at ' + sp + 'x' : '') ++ '. Trim the clip to ' + f(srcDur / sp) + ' or less first, ' ++ 'or pick a longer take.' };+ }+ // Keep the OLD in-point where it can — a replace that keeps its manual+ // offset is more often right than one that silently resets to zero — and+ // clamp it back if the new take is too short to honour it.+ let start = Math.max(0, sbeNum(c.start, 0));+ if (start + need > srcDur) start = Math.max(0, srcDur - need);+ const end = start + need;+ const b = Object.assign({}, c, {+ kind: 'video',+ path: item.path, proxy: item.proxy || null,+ duration: srcDur || null,+ start: sbeRound(start), end: sbeRound(end),+ n: (item.n !== undefined ? item.n : c.n),+ title: item.title || c.title, source: 'human',+ });+ const out = clips.slice();+ out[i] = b;+ return { clips: out, ok: true, replaced: b };+}+// ---------------------------------------------------------------------------// THE THREE KINDS// ---------------------------------------------------------------------------@@ -2985,6 +3301,75 @@ function sbeBrightnessCss(b) {return Math.max(0, sbeRound(1 + 2 * sbeNum(b)));}+// FILM-14: the 5-slider grade — exposure, contrast, saturation, temp, tint —+// a sibling of legacy `brightness` under the same `adjust`, mirroring+// `clip_grade()` in storyboard_editor.py exactly (same ranges, same+// neutral defaults) so the Inspector shows what the render will do.+const SBE_GRADE_EXPOSURE_MAX = 0.5;+const SBE_GRADE_CONTRAST_MIN = 0.5, SBE_GRADE_CONTRAST_MAX = 1.8;+const SBE_GRADE_SATURATION_MIN = 0.0, SBE_GRADE_SATURATION_MAX = 2.5;+const SBE_GRADE_TEMP_TINT_MAX = 1.0;+const SBE_GRADE_FIELDS = {+ exposure: [-SBE_GRADE_EXPOSURE_MAX, SBE_GRADE_EXPOSURE_MAX, 0],+ contrast: [SBE_GRADE_CONTRAST_MIN, SBE_GRADE_CONTRAST_MAX, 1],+ saturation: [SBE_GRADE_SATURATION_MIN, SBE_GRADE_SATURATION_MAX, 1],+ temp: [-SBE_GRADE_TEMP_TINT_MAX, SBE_GRADE_TEMP_TINT_MAX, 0],+ tint: [-SBE_GRADE_TEMP_TINT_MAX, SBE_GRADE_TEMP_TINT_MAX, 0],+};+function sbeGrade(c) {+ const a = (c && c.adjust) || {};+ const out = {};+ for (const key of Object.keys(SBE_GRADE_FIELDS)) {+ const [lo, hi, def] = SBE_GRADE_FIELDS[key];+ out[key] = sbeRound(Math.max(lo, Math.min(hi, sbeNum(a[key], def))));+ }+ return out;+}+function sbeGradeIsNeutral(c) {+ const g = sbeGrade(c);+ for (const key of Object.keys(SBE_GRADE_FIELDS)) {+ if (Math.abs(g[key] - SBE_GRADE_FIELDS[key][2]) >= 1e-9) return false;+ }+ return true;+}+// One field, one clip — the mirror of `sbeSetBrightness`, and neutral is+// absent on the way back to the model too: a slider dragged to its default+// must leave no dead key in `adjust`, the same rule the server enforces on+// save (`normalise_edit`).+function sbeSetGrade(clips, id, field, v) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const lim = SBE_GRADE_FIELDS[field];+ if (!lim) return { clips: clips, ok: false, why: 'unknown field' };+ const [lo, hi, def] = lim;+ const val = sbeRound(Math.max(lo, Math.min(hi, sbeNum(v))));+ const adj = Object.assign({}, c.adjust || {});+ if (Math.abs(val - def) < 1e-9) delete adj[field]; else adj[field] = val;+ c.adjust = Object.keys(adj).length ? adj : undefined;+ return { clips: clips, ok: true };+}+// COPY GRADE → SELECTION. One clip's five numbers, stamped onto every other+// selected clip, as one undo step — the same shape `sbeAlternateSel` and+// every other "apply this arrangement to the selection" verb here uses.+function sbeCopyGrade(clips, fromId, toIds) {+ const src = sbeById(clips, fromId);+ if (!src) return { clips: clips, ok: false, why: 'gone' };+ const g = sbeGrade(src);+ let touched = 0;+ for (const id of toIds || []) {+ if (String(id) === String(fromId)) continue;+ const c = sbeById(clips, id);+ if (!c || c.locked || sbeKind(c) === 'slug') continue;+ for (const key of Object.keys(SBE_GRADE_FIELDS)) {+ const r = sbeSetGrade(clips, id, key, g[key]);+ if (!r.ok) continue;+ }+ touched++;+ }+ return { clips: clips, ok: touched > 0, why: touched ? '' : 'nothing to copy it onto' };+}+// FRAMING — the mirror of `clip_frame()`: zoom 1–3 and the anchor as// fractions, clamped, neutral when absent. A slug has nothing to reframe.const SBE_FRAME_ZOOM_MAX = 3.0;@@ -3125,9 +3510,22 @@ function sbeCleanClip(c) {out.duration = null;if (kind === 'slug') { out.path = null; out.proxy = null; }}+ // THE GRADE TRAVELS WITH THE CLIP (4.17.0 render check). This used to+ // rebuild `adjust` as brightness alone, so FILM-14's exposure / contrast /+ // saturation / temp / tint — every per-clip grade and every Match colour —+ // lived on screen and was dropped by the next Save: the render, the backup+ // and the NLE exports never saw it. Neutral stays absent, as the server+ // writes it (validate_edit checks each key's own range).+ const adj = {};const b = sbeBright(out);- if (Math.abs(b) < 1e-6) delete out.adjust;- else out.adjust = { brightness: sbeRound(b) };+ if (Math.abs(b) >= 1e-6) adj.brightness = sbeRound(b);+ if (kind !== 'slug') {+ const g = sbeGrade(c);+ for (const key of Object.keys(SBE_GRADE_FIELDS)) {+ if (Math.abs(g[key] - SBE_GRADE_FIELDS[key][2]) >= 1e-9) adj[key] = g[key];+ }+ }+ if (Object.keys(adj).length) out.adjust = adj; else delete out.adjust;// 1x is the absence of the field, the same way the server writes it.const sp = sbeSpeed(c);if (kind !== 'video' || Math.abs(sp - 1) < 1e-9) delete out.speed;@@ -3156,6 +3554,10 @@ function sbeSaveBody(state) {// did and the backup's digest cannot differ from the save's over `[]`.const tracks = (typeof sbeTsClean === 'function') ? sbeTsClean(state.tracks || []) : [];if (tracks.length) edit.audio_tracks = tracks; else delete edit.audio_tracks;+ // FILM-58: MARKERS, and no key when there are none — the server's absent+ // key, the same rule the audio tracks just above follow.+ const markers = (state.markers || []).map(m => Object.assign({}, m));+ if (markers.length) edit.markers = markers; else delete edit.markers;edit.board_id = state.id;const body = { id: state.id, edit: edit };if (state.expect !== null && state.expect !== undefined) body.expect_revision = state.expect;@@ -3203,6 +3605,37 @@ function sbeFmtTime(t) {return m + ':' + (s < 10 ? '0' : '') + s.toFixed(2);}+// FILM-52: HH:MM:SS:FF. Hundredths of a second are the wrong unit for+// lip-sync work — the nudge already counts in frames (sbeNudge ±1/±10) and+// the owner does too — so a frame timecode is what the transport reads back+// in, once somebody asks for it.+function sbeFmtTC(t, fps) {+ const f = Math.max(1, Math.round(sbeNum(fps, 24)) || 24);+ t = Math.max(0, sbeNum(t));+ let frames = Math.round(t * f);+ const ff = frames % f;+ let secs = Math.floor(frames / f);+ const ss = secs % 60;+ secs = Math.floor(secs / 60);+ const mm = secs % 60;+ const hh = Math.floor(secs / 60);+ const p2 = (n) => (n < 10 ? '0' : '') + n;+ return p2(hh) + ':' + p2(mm) + ':' + p2(ss) + ':' + p2(ff);+}++// The toggle, remembered per browser the same way a retake dismissal is+// (sbeRetakeDismissed): read on paint, written on click, nothing round-trips+// through the server because it changes nothing about the document.+function sbeTimeMode() {+ try { return localStorage.getItem('phos_editor_tcmode') === 'frames' ? 'frames' : 'seconds'; }+ catch (e) { return 'seconds'; }+}+function sbeToggleTimeMode() {+ try { localStorage.setItem('phos_editor_tcmode', sbeTimeMode() === 'frames' ? 'seconds' : 'frames'); }+ catch (e) {}+ sbePaintHead();+}+// ---------------------------------------------------------------------------// PAN AND ZOOM — the two sliders, as arithmetic// ---------------------------------------------------------------------------@@ -3494,15 +3927,37 @@ function sbeSoundModeSet(on, opts) {if (!quiet) sbePaint();}+// FILM-57: A TOAST THAT DESCRIBES THE SCREEN OUTLIVES THE SCREEN. Picture+// mode / Sound mode / side-panels-hidden are not news the user still needs+// once they have switched to Storyboard or another tab — "Picture mode —+// the picture takes the height…" turning up over a shot list describes a+// screen that is not there. phosToast (queue.js) is a shared, global stack+// with no notion of which tab asked for a message, and rightly so — most of+// this file's 100+ toasts (a save failed, a take landed, a render finished)+// are exactly as true after a tab switch as before it. Only the handful that+// describe the CURRENT ON-SCREEN LAYOUT are wrong once you have left, so+// only those go through here: tagged, and swept on the one signal this file+// already has for "the user is leaving" (sbeSuspend, called from+// workflowSwitch whenever the active tab stops being 'editor').+function sbeViewToast(message, opts) {+ if (typeof phosToast !== 'function') return null;+ const el = phosToast(message, opts);+ if (el && el.dataset) el.dataset.sbeViewToast = '1';+ return el;+}+function sbeSweepViewToasts() {+ if (typeof document !== 'object' || !document || !document.querySelectorAll) return;+ document.querySelectorAll('.phos-toast[data-sbe-view-toast="1"]')+ .forEach(el => { try { el.remove(); } catch (e) {} });+}+function sbeSoundModeToggle() {const on = !sbeSoundMode();sbeSoundModeSet(on);- if (typeof phosToast === 'function') {- phosToast(on- ? 'Sound mode — every sound lane at full height, the picture small. ⇧A or the ⌁ button brings the picture back.'- : 'Picture mode — the picture takes the height, the sound lanes are thin. Click a sound to select it; ⇧A for sound mode.',- { duration: 4000 });- }+ sbeViewToast(on+ ? 'Sound mode — every sound lane at full height, the picture small. ⇧A or the ⌁ button brings the picture back.'+ : 'Picture mode — the picture takes the height, the sound lanes are thin. Click a sound to select it; ⇧A for sound mode.',+ { duration: 4000 });}// THE VIEW GROUP'S OWN STATE, painted in one place: Source, Inspector, Sound@@ -3626,9 +4081,9 @@ function sbePanelsToggle() {const hidden = !(document.body && document.body.classList.contains('ed-focus'));sbePanelsApply(hidden);sbePaint();- if (typeof phosToast === 'function' && hidden) {- phosToast('Side panels hidden — the media pool and the queue are out of the way. ` (or Panels in the View group) brings them back.',- { duration: 4000 });+ if (hidden) {+ sbeViewToast('Side panels hidden — the media pool and the queue are out of the way. ` (or Panels in the View group) brings them back.',+ { duration: 4000 });}}@@ -3737,6 +4192,16 @@ function edOpenBoard(id) {function sbeOpen(id, opts) {const want = String(id || SBE.id || edDoc() || '');if (!want) { edShowPicker(); return; }+ // FILM-16: OPENING THE FILM THAT IS ALREADY OPEN IS NOT A LOAD. Falling+ // through below calls `sbeLoad()` NON-QUIET, which always adopts the+ // server's last SAVED document over whatever is on screen — so "Open in+ // Editor" on the film you are already cutting (the rail's step 3, or+ // coming back from Storyboard to check a prompt) silently discarded every+ // edit since the last Save. sbeResume() is exactly the right verb for+ // re-entering a document that is already open: it shows the screen,+ // restarts the clock, and re-reads QUIETLY — which, unlike this path,+ // protects unsaved work (sbeLoad's `quiet` branch, sbeAdoptMeta).+ if (SBE.open && SBE.id === want) { sbeResume(); return; }if (SBE.open && SBE.id && SBE.id !== want) sbeCloseDoc({ quiet: true });SBE.open = true;SBE.id = want;@@ -3768,7 +4233,16 @@ function sbeSuspend() {if (!SBE.open) return;sbeStop();sbeSrcStop(); // both screens, or the left one plays on in a tab nobody is looking at- if (SBE.dirty && !SBE.conflict) sbeSave(true);+ // FILM-57: any toast describing THIS screen leaves with it.+ sbeSweepViewToasts();+ // FILM-29: NOT A SAVE. Switching tabs is not the user pressing Save — it is+ // exactly the "autosave to edit.json" the owner refused, wearing the name+ // of a different button (sbeCloseDoc already got this right; this call+ // sat right next to it writing the real document instead). The backup lane+ // is what a leave-without-saving is for; it never touches edit.json or the+ // revision, and the recovery chip on the way back offers it like any other+ // snapshot.+ if (SBE.dirty && !SBE.conflict) sbeBackup(true);if (SBE.timer) { clearInterval(SBE.timer); SBE.timer = null; }window.removeEventListener('resize', sbePaint);}@@ -3811,6 +4285,7 @@ function sbeCloseDoc(opts) {SBE.open = false;SBE.id = '';SBE.clips = [];+ SBE.markers = []; // EDITOR-1: a closed film's markers leave with itSBE.undo.length = 0; SBE.redo.length = 0;// The soundtrack field belongs to the document that just closed (SB5-11).SBE.musicFor = '';@@ -3853,7 +4328,14 @@ async function sbeFilmsToggle() {let boards;try {const r = await (await fetch('/storyboard/list')).json();- boards = ((r && r.boards) || []).filter(b => (b.clips || 0) > 0 || b.id === SBE.id);+ // FILM-43: `b.clips` counts board SHOTS with an output file — right+ // for "X of Y rendered", wrong for "does this film have something to+ // edit". A film cut from Video-tab or imported clips has a timeline+ // and no shots of its own, so filtering on `clips > 0` alone dropped+ // it from this list even though "No other __SEQ__ has clips yet" was+ // never true for it. `has_timeline` is edit.json's own existence.+ boards = ((r && r.boards) || [])+ .filter(b => (b.clips || 0) > 0 || b.has_timeline || b.id === SBE.id);} catch (e) {note.textContent = 'The panel did not answer — try again.';return;@@ -3941,6 +4423,7 @@ function sbeAdoptMeta(r) {SBE.unplaced = r.unplaced || [];SBE.pool = r.clips || [];SBE.relink = r.relink || [];+ SBE.offline = r.offline || [];SBE.sections = r.sections || SBE.sections || [];SBE.prepare = r.prepare || {};const px = {};@@ -3951,6 +4434,7 @@ function sbeAdoptMeta(r) {if (c && c.path && px[c.path]) c.proxy = px[c.path];}sbePaintRelink();+ sbePaintOffline();if (ED.src === 'film') edPoolRefresh();sbeFetchPeaks();sbePaint();@@ -3973,6 +4457,7 @@ function sbeAdopt(r, quiet) {SBE.unplaced = r.unplaced || [];SBE.pool = r.clips || [];SBE.relink = r.relink || [];+ SBE.offline = r.offline || [];SBE.sections = r.sections || [];SBE.prepare = r.prepare || {};if (r.drafts) SBE.drafts = r.drafts;@@ -3982,6 +4467,9 @@ function sbeAdopt(r, quiet) {SBE.overlays = (SBE.edit.overlays || []).map(o => Object.assign({}, o));SBE.transitions = (SBE.edit.transitions || []).map(t => Object.assign({}, t));SBE.tracks = sbeTsCopy(SBE.edit.audio_tracks || []);+ // EDITOR-1: THE MARKERS ARE THE DOCUMENT'S TOO. They were never read back,+ // so a reopened film showed none and the previous film's stayed on screen.+ SBE.markers = (SBE.edit.markers || []).map(m => Object.assign({}, m));SBE.tsSet = []; SBE.tsDrag = null; SBE.tsDrop = null; SBE.selLane = '';SBE.ovSel = '';SBE.txSel = '';@@ -4024,9 +4512,34 @@ function sbeAdopt(r, quiet) {sbePaintDraft();sbePaintRecovery();sbePaintRelink();+ sbePaintOffline();sbeDeliverPaint();+ if (typeof sbeRenderChipFor === 'function') sbeRenderChipFor(SBE.id);if (ED.src === 'film') edPoolRefresh();sbeFetchPeaks();+ // FILM-57: THE PLAYHEAD IS THE FILM'S, NOT THE TAB'S. It used to survive a+ // switch to a different film, so a short film opened after a long one+ // could land PAST ITS OWN END — black, on open, with nothing playing and+ // no obvious reason why. A genuine open (never a quiet re-read, which+ // must not move anything the user is looking at) starts at the top, like+ // opening a file anywhere else does.+ if (!quiet) SBE.playhead = 0;+ // FILM-57: UNDO SURVIVES A RELOAD, when it is safe to trust — see+ // sbeRestoreUndoIfFresh's own comment on the fingerprint check. A genuine+ // open is the one moment the just-adopted content is known and can be+ // compared; a quiet re-read must not touch the stack any more than it+ // touches anything else the user is looking at.+ if (!quiet) sbeRestoreUndoIfFresh();+ // FILM-39: OPEN LONG FILMS AT FIT. The default zoom showed about 10s of a+ // 2:52 film with no sign there was more — the rest was a scroll nobody was+ // told about. Only on a genuine OPEN (never a quiet re-read, which must+ // not touch the view the user already set), and only when the film would+ // not fit at the current zoom — a short film is unaffected, since "fit"+ // would mean zooming IN, which nobody asked for.+ if (!quiet) {+ const fit = sbeZoomMin();+ if (fit < SBE.pps) SBE.pps = fit;+ }sbePaint();// Land on a picture, not on black. A timeline that opens dark reads as// broken for the second and a half before the first click.@@ -4097,26 +4610,45 @@ function sbePaintProtected() {if (!el) return;if (!SBE.open || !SBE.id) { el.hidden = true; return; }const age = SBE.backedUpAt ? Math.round((Date.now() - SBE.backedUpAt) / 1000) : null;- // COLD IS "THERE IS UNSAVED WORK AND THE NET HAS NOT CAUGHT THIS TAB", and- // it is deliberately the SAME threshold the watchdog alarms on, so the chip- // and the banner can never disagree. Stated against `backedUpAt` rather than- // against `dirtyAt`: the outage this exists for froze `dirtyAt` in the past- // while `backedUpAt` stayed ahead of it, and every test written in terms of- // that pair read "protected" for seven hours. How long ago the net actually- // caught this tab cannot be faked by a stuck flag.- const cold = SBE.dirty && (!SBE.backedUpAt- || (Date.now() - SBE.backedUpAt) > SBE_SAVE_GRACE_MS);+ // FILM-38: COLD NOW MEANS EXACTLY WHAT THE WATCHDOG (sbeTick) MEANS BY+ // IT — the oldest unwritten change is older than the grace AND nothing has+ // backed it up since. The comment here used to CLAIM the two could never+ // disagree while actually comparing only against `backedUpAt`, which is+ // cold the instant `dirty` becomes true and `backedUpAt` is not yet set —+ // i.e. on every normal first edit, before the (now near-immediate, see+ // FILM-06) snapshot has had even one network round trip to land. A single+ // brightness change put a red "NOT PROTECTED" in the header on the very+ // next paint. The real alarm was never that impatient; the chip should not+ // have been either. `dirtyAt` freezing during the old stale-session outage+ // is what the comment was guarding against — that outage is closed (see+ // docs/EDITOR_SAVE_MODEL.md §5), and the watchdog itself has used `dirtyAt`+ // safely this whole time.+ const cold = SBE.dirty && !!SBE.dirtyAt+ && (Date.now() - SBE.dirtyAt) > SBE_SAVE_GRACE_MS+ && (SBE.backedUpAt || 0) < SBE.dirtyAt;let text;- if (age === null) text = SBE.dirty ? 'not backed up yet' : '';+ if (age === null) text = SBE.dirty ? 'backing up…' : '';else if (age < 60) text = 'protected ' + age + 's ago';else text = 'protected ' + Math.round(age / 60) + 'm ago';- if (cold) text = 'NOT PROTECTED — ' + text;+ if (cold) text = 'NOT PROTECTED — ' + (age === null ? 'not backed up yet' : text);// A SECOND EDITOR IS INFORMATION, NEVER A REASON TO STOP. It used to be the// reason this tab stopped writing entirely.if (SBE.otherEditor) text = (text ? text + ' · ' : '') + 'also open elsewhere';- el.textContent = text;- el.hidden = !text;+ // FILM-37: the routine case ("protected 4s ago") used to sit in the header+ // as its own always-visible chip, permanently spending width next to the+ // title/draft-chip/state text — the four of them together are what+ // truncated "saved · rev7" down to "saved · r" at 1366-1440px, well above+ // the breakpoint that was supposed to fold the state text first. An+ // ALARM (cold, or another tab open) earns that width, because it is the+ // one thing in the header that is actionable; the routine case does not,+ // so it moves into the status pill's own tooltip instead — still one+ // click of hovering away, never fully gone.+ const alarm = cold || SBE.otherEditor;+ el.textContent = alarm ? text : '';+ el.hidden = !alarm;el.classList.toggle('is-cold', !!cold);+ const pill = sbeEl('sbeState');+ if (pill) pill.title = text || '';}function sbeSetState(text, kind) {@@ -4168,6 +4700,10 @@ function sbeSnapshot(audio) {// THE AUDIO TRACKS ARE THE ARRANGEMENT TOO — a strip placed and undone// must leave with the undo, not stay behind on its lane.tracks: SBE.tracks || [],+ // FILM-58: MARKERS ARE PART OF THE ARRANGEMENT TOO — a beat cue dropped+ // and undone leaves with the undo, the same rule every other lane here+ // already follows.+ markers: SBE.markers || [],audio: (audio === undefined)? (SBE.audio || (SBE.edit && SBE.edit.audio) || null) : audio,});@@ -4183,6 +4719,7 @@ function sbeRestore(json) {if (s.overlays !== undefined) SBE.overlays = s.overlays || [];if (s.transitions !== undefined) SBE.transitions = s.transitions || [];if (s.tracks !== undefined) SBE.tracks = s.tracks || [];+ if (s.markers !== undefined) SBE.markers = s.markers || [];SBE.edit = SBE.edit || {};// ...and a restore never COMMITS a discovered track into the document. The// arrangement owns a soundtrack only once somebody has placed it (see@@ -4215,6 +4752,27 @@ function sbeOvMutate(fn) {return res;}+// Markers get their own tiny mutate, the same shape `sbeOvMutate` uses for+// the overlay lane — one undo step, one save, no clip in the mix.+function sbeMarkerMutate(fn) {+ const before = sbeSnapshot();+ SBE.markers = fn(SBE.markers || []);+ SBE.undo.push(before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+ return true;+}+function sbeMarkerAtPlayhead() {+ if (!SBE.open || !SBE.id) return;+ sbeMarkerMutate(ms => sbeMarkerAdd(ms, SBE.playhead, 'note', ''));+ phosToast('Marker at ' + sbeFmtTime(SBE.playhead) + '. Right-click it to remove.',+ { duration: 3000 });+}+function sbeOvAddAt(item, at) {const res = sbeOvMutate(os => sbeOvAdd(os, item, at));if (!res) return null;@@ -4498,6 +5056,54 @@ function sbeCloseGapAt(t) {});}+// FILM-27's "Close them": every hole, closed. `sbeCloseGapAt` re-reads+// `sbeHoles` itself, so the SOONEST remaining hole is always at its+// currently-correct position — closing one shifts every later hole earlier,+// and re-reading rather than working off a stale list is what keeps this+// from closing the wrong seconds on the second pass. `guard` is a render+// giving up rather than looping forever if a locked clip blocks progress.+function sbeCloseAllGaps() {+ let closed = 0;+ for (let guard = 0; guard < 500; guard++) {+ const holes = sbeHoles(SBE.clips) || [];+ if (!holes.length) break;+ const h = holes[0];+ if (!sbeCloseGapAt((sbeNum(h.film_start) + sbeNum(h.film_end)) / 2)) break;+ closed++;+ }+ if (closed) {+ phosToast(closed + ' hole' + (closed === 1 ? '' : 's') + ' closed.',+ { kind: 'success', duration: 4000 });+ }+}++// The render's hole warning — non-blocking, because a hole stopped being+// something a render could get wrong the moment the assembler started+// padding it with black instead of closing it. "Fill" opens Generate a+// shot on the soonest hole; "Close them" ripples every hole shut instead.+function sbeNoticeHoles(holes) {+ if (!holes || !holes.length) return;+ const total = holes.reduce((a, g) => a + sbeNum(g.duration), 0);+ const t = phosToast(holes.length + ' hole' + (holes.length === 1 ? '' : 's') ++ ' (' + total.toFixed(1) + 's) will play as black.',+ { duration: 9000 });+ if (!t) return;+ const first = holes[0];+ const fill = document.createElement('a');+ fill.href = '#'; fill.className = 'phos-toast-action'; fill.textContent = 'Fill';+ fill.onclick = (ev) => {+ ev.preventDefault();+ if (typeof sbeGenOpen === 'function') {+ sbeGenOpen(sbeNum(first.film_start), sbeNum(first.duration));+ }+ };+ const close = document.createElement('a');+ close.href = '#'; close.className = 'phos-toast-action'; close.textContent = 'Close them';+ close.onclick = (ev) => { ev.preventDefault(); sbeCloseAllGaps(); };+ t.appendChild(fill);+ t.appendChild(close);+}+// One frame at a time, on whatever is selected. Every NLE has this and this// one did not: the arrow keys moved the PLAYHEAD and there was no gesture at// all for "a hair later", short of dragging at a zoom high enough to see a@@ -4521,6 +5127,87 @@ function sbeNudge(dir, big) {sbeMutate(cs => sbeMoveGroup(cs, ids, d));}+// FILM-57: UNDO SURVIVES A RELOAD — FOR EXACTLY THE STATE IT WAS BUILT+// AGAINST. The stack (SBE.undo/SBE.redo) is in-memory only; a reload starts+// both empty, which is correct behaviour it just cannot tell apart from "the+// history is gone." What makes restoring it safe is not the film's id alone+// — a reload always re-adopts the last SAVED document, so if the user had+// unsaved edits sitting only in this tab, the screen coming back is NOT the+// screen the stack was built for, and an undo stack pointing at states the+// current arrangement never passed through is worse than no undo at all+// (`sbeUndo` would restore a clip arrangement with no relationship to what+// is on screen). So the persisted entry carries a FINGERPRINT of the exact+// content it was saved beside, and is only ever adopted when that fingerprint+// matches what just came back from the server — the one case where "the+// stack's current position IS the screen" is actually true. Session-scoped+// (sessionStorage, not localStorage) on purpose: this is "did I just reload+// this tab", not "remember my edits across a browser restart three days+// later" — the crash-backup lane already owns that promise, separately.+const SBE_UNDO_STORE_PREFIX = 'phos_sbe_undo_';+let _sbeUndoLastFingerprint = '';++function sbeUndoStoreKey(id) { return SBE_UNDO_STORE_PREFIX + String(id || ''); }++// Exactly the content an undo/redo entry would need to line up with — the+// same fields sbeSnapshot() carries, so "the fingerprint matches" and "we are+// at the position the stack thinks we are" are the same question.+function sbeUndoFingerprint() {+ return JSON.stringify({ clips: SBE.clips, overlays: SBE.overlays,+ tracks: SBE.tracks, transitions: SBE.transitions,+ markers: SBE.markers });+}++// Called from the tick, not from every push site — cheap (one fingerprint+// compare) when nothing changed since the last write, and it catches every+// mutation path (sbeMutate and the handful of call sites that push the+// stack directly) without touching any of them.+function sbePersistUndo() {+ if (!SBE.open || !SBE.id) return;+ // The dedup key is the CONTENT fingerprint plus the two stack depths, not+ // the fingerprint alone — a Restore or Keep-version can empty the stacks+ // without the current clips changing at all, and that transition is+ // exactly the one this lane must not miss (an emptied stack has to clear+ // its stored entry, or a later reload would resurrect undo history that+ // no longer applies).+ let mark;+ try {+ const fp = sbeUndoFingerprint();+ mark = fp + '\u0000' + SBE.undo.length + '\u0000' + SBE.redo.length;+ if (mark === _sbeUndoLastFingerprint) return;+ const key = sbeUndoStoreKey(SBE.id);+ if (!SBE.undo.length && !SBE.redo.length) {+ sessionStorage.removeItem(key);+ } else {+ sessionStorage.setItem(key, JSON.stringify({+ fp, undo: SBE.undo.slice(-SBE_UNDO_MAX), redo: SBE.redo.slice(-SBE_UNDO_MAX) }));+ }+ _sbeUndoLastFingerprint = mark;+ } catch (e) {+ // Quota, private browsing, storage disabled — undo simply does not+ // survive a reload this session. Never a reason to break editing.+ }+}++// Called once, right after a genuine (non-quiet) adopt — the one moment a+// freshly-loaded document's content is known and can be compared.+function sbeRestoreUndoIfFresh() {+ if (!SBE.open || !SBE.id) return;+ try {+ const raw = sessionStorage.getItem(sbeUndoStoreKey(SBE.id));+ if (!raw) return;+ const entry = JSON.parse(raw);+ const fp = sbeUndoFingerprint();+ if (!entry || entry.fp !== fp) return; // the screen moved on since this was written+ if (Array.isArray(entry.undo)) SBE.undo = entry.undo.slice(-SBE_UNDO_MAX);+ if (Array.isArray(entry.redo)) SBE.redo = entry.redo.slice(-SBE_UNDO_MAX);+ // Matches sbePersistUndo's own dedup key — restoring the stack is not a+ // change the very next tick needs to write straight back out.+ _sbeUndoLastFingerprint = fp + '\u0000' + SBE.undo.length + '\u0000' + SBE.redo.length;+ } catch (e) {+ // A corrupt or inaccessible entry starts the film clean — same as today.+ }+}+function sbeMutate(fn) {const before = sbeSnapshot();const res = fn(SBE.clips);@@ -4585,8 +5272,16 @@ function sbeQueueSave() {// alarm it exists to raise could never fire. Nothing may be allowed to// return from this function without first recording that there is unwritten// work and when it appeared.+ const firstEditSinceClean = !SBE.dirtyAt;if (!SBE.dirtyAt) SBE.dirtyAt = Date.now();if (SBE.saveTimer) clearTimeout(SBE.saveTimer);+ // FILM-06: THE FIRST EDIT OFF A CLEAN STATE IS THE ONE A QUICK RELOAD MOST+ // OFTEN CATCHES — a reload inside the 1.4s debounce window used to leave a+ // single change with no backup at all, silently. Nothing about the debounce+ // helps here: it exists to stop a keystroke storm from writing on every+ // keystroke, and the first keystroke off clean is never part of a storm+ // yet. Write it now; the debounce still coalesces everything after it.+ if (firstEditSinceClean) { sbeBackup(); return; }SBE.saveTimer = setTimeout(() => { SBE.saveTimer = null; sbeBackup(); }, 1400);}@@ -4610,19 +5305,41 @@ async function sbeBackup(quiet) {// snapshot, pruned), so a new snapshot cannot eat an old one and there is// nothing left to guard. See docs/EDITOR_SAVE_MODEL.md §2.if (SBE.saveTimer) { clearTimeout(SBE.saveTimer); SBE.saveTimer = null; }+ const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,+ overlays: SBE.overlays, tracks: SBE.tracks,+ transitions: SBE.transitions,+ markers: SBE.markers,+ expect: null });+ // WHICH DRAFT THIS WAS COMPOSED FROM. The server files the backup under+ // the draft that is active when the write LANDS, and this one is+ // debounced — so without the name in the body, a backup of the draft you+ // just left is offered back as the unsaved work of the one you opened.+ body.draft = SBE.activeDraft || '';+ body.session = SBE.session;+ // FILM-57: A BACKUP OF NOTHING NEW IS NOT A BACKUP. The watchdog above+ // re-arms sbeQueueSave on every tick the document is dirty, not-saving and+ // not-already-timered — by design ("re-queueing is free"), so nothing+ // unsaved is ever one dropped timer away from unprotected. What it could+ // not know is that the timer it just armed fires against content already+ // sitting in the last snapshot: the server dedups by digest (storyboard_+ // editor.py's `write_backup`, "an identical snapshot is not a snapshot")+ // so no new FILE was ever written by the loop, but the ROUND TRIP — a+ // fetch, `claim_session`, a digest compare — fired every 1.4s regardless,+ // measured at the reported "every 1.5 to 3 s forever" while the document+ // sat dirty and untouched. This is the same fingerprint the server already+ // keys its own dedup on, kept locally so the common case never leaves the+ // tab at all. `quiet` (the suspend/close paths) still checks it — sending+ // an identical body on close would be exactly the same pointless write,+ // just once instead of in a loop.+ // sbeSaveBody already folds clips/overlays/transitions/audio_tracks INTO+ // `body.edit` (there is no separate top-level field for any of them) —+ // so `body.edit`'s own JSON is the complete, deterministic content this+ // backup would carry.+ const sig = SBE.id + '\u0000' + body.draft + '\u0000' + JSON.stringify(body.edit);+ if (SBE.backedUpAt && SBE.lastBackupSig === sig) return true;SBE.backingUp = true;let r;try {- const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,- overlays: SBE.overlays, tracks: SBE.tracks,- transitions: SBE.transitions,- expect: null });- // WHICH DRAFT THIS WAS COMPOSED FROM. The server files the backup under- // the draft that is active when the write LANDS, and this one is- // debounced — so without the name in the body, a backup of the draft you- // just left is offered back as the unsaved work of the one you opened.- body.draft = SBE.activeDraft || '';- body.session = SBE.session;const res = await fetch('/storyboard/edit/backup', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body) });@@ -4633,6 +5350,7 @@ async function sbeBackup(quiet) {SBE.backingUp = false;}if (r && r.ok) {+ SBE.lastBackupSig = sig;SBE.backedUpAt = Date.now();// Somebody else is editing this film too. Worth saying; never worth// stopping for.@@ -4660,6 +5378,35 @@ async function sbeBackup(quiet) {return false;}+// THE LAST CHANCE — FILM-06. A reload, a closed tab, ⌘R or Pinokio's own+// panel restart give the 1.4s debounce in sbeQueueSave no time to land, and+// until now nothing ever told the browser to wait for it. `beforeunload`+// cannot await a fetch — the page is torn down before it would resolve — so+// the one thing that still leaves WITH the request is+// `navigator.sendBeacon`, which the browser guarantees to deliver even past+// unload. Same door as the debounced backup (`/storyboard/edit/backup`),+// same body `sbeSaveBody` already builds for it: this is not a new lane,+// only a synchronous trigger on the one that exists.+function sbeBeaconBackup() {+ if (!SBE.open || !SBE.id || !SBE.dirty || SBE.conflict) return;+ if (typeof navigator === 'undefined' || !navigator.sendBeacon) return;+ try {+ const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,+ overlays: SBE.overlays, tracks: SBE.tracks,+ transitions: SBE.transitions,+ markers: SBE.markers, expect: null });+ body.draft = SBE.activeDraft || '';+ body.session = SBE.session;+ const blob = new Blob([JSON.stringify(body)], { type: 'application/json' });+ navigator.sendBeacon('/storyboard/edit/backup', blob);+ } catch (e) { /* best effort — the tab is already on its way out */ }+}+window.addEventListener('beforeunload', sbeBeaconBackup);+// Safari and iOS fire `pagehide`, not `beforeunload`, on a real tab close —+// belt and braces, and `sbeBeaconBackup` is a no-op the second time either+// fires first and nothing is dirty any more.+window.addEventListener('pagehide', sbeBeaconBackup);+// THE OUTER HALF OF SAVING, AND IT EXISTS BECAUSE OF A REAL LOSS. The owner// cut for twenty minutes and nothing reached the disk: edit.json sat frozen// while he kept working, and the only thing on screen that knew was a small@@ -4754,6 +5501,7 @@ async function sbeSaveInner(quiet, force) {const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,overlays: SBE.overlays, tracks: SBE.tracks,transitions: SBE.transitions,+ markers: SBE.markers,expect: force ? null : SBE.revision });// WHAT THIS REQUEST CARRIES, AND FOR WHICH DOCUMENT. The answer comes back// later, and by then the user may have trimmed a clip or opened another@@ -4791,7 +5539,8 @@ async function sbeSaveInner(quiet, force) {// fields to fall out of date.const now = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,overlays: SBE.overlays, tracks: SBE.tracks,- transitions: SBE.transitions, expect: null });+ transitions: SBE.transitions,+ markers: SBE.markers, expect: null });const moved = JSON.stringify(now.edit) !== sentDoc;// Adopt the server's copy of the document, but NOT its clip array — the// user may have moved something in the milliseconds the save was in@@ -4799,6 +5548,12 @@ async function sbeSaveInner(quiet, force) {// If the document itself moved, keep ALL of it and take only the number.SBE.edit = moved ? Object.assign({}, SBE.edit, { revision: rev }): Object.assign({}, r.edit || {}, { clips: SBE.edit.clips || [] });+ // EDITOR-11 (Codex 4.17.0): ...BUT ITS TIMINGS, WHEN NOTHING MOVED. Save+ // heals sub-frame clip lengths (FILM-51) and cascades the positions after+ // them, so the document on disk can differ from the one sent. Keeping+ // the sent clips marked a cut "saved" that the preview played one way+ // and the render another until a reload.+ if (!moved) sbeAdoptSavedTimings(((r.edit || {}).clips) || []);SBE.revision = rev;SBE.unplaced = r.unplaced || [];SBE.prepare = r.prepare || SBE.prepare;@@ -4865,6 +5620,42 @@ async function sbeSaveInner(quiet, force) {return false;}+// EDITOR-11: take the saved document's clip TIMINGS onto the clips on+// screen — start/end, the slot, a split sound's placement — and nothing else+// (selection, proxies and the undo stack stay). Only when the saved clips are+// the same clips; a different set is not a heal and is left alone.+function sbeAdoptSavedTimings(saved) {+ if (!Array.isArray(saved) || !saved.length || saved.length !== (SBE.clips || []).length) {+ return false;+ }+ const byId = {};+ for (const x of saved) if (x && x.id !== undefined) byId[String(x.id)] = x;+ if (SBE.clips.some(c => !byId[String(c.id)])) return false;+ let changed = false;+ const out = SBE.clips.map(c => {+ const x = byId[String(c.id)];+ const next = {};+ for (const k of ['start', 'end', 'film_start', 'film_end']) {+ if (x[k] !== undefined && x[k] !== null && Math.abs(sbeNum(x[k]) - sbeNum(c[k])) > 1e-9) {+ next[k] = sbeNum(x[k]);+ }+ }+ const xa = x.audio, ca = c.audio;+ if (xa && ca && xa.film_start !== undefined && xa.film_start !== null+ && Math.abs(sbeNum(xa.film_start) - sbeNum(ca.film_start)) > 1e-9) {+ next.audio = Object.assign({}, ca, { film_start: sbeNum(xa.film_start) });+ }+ if (!Object.keys(next).length) return c;+ changed = true;+ return Object.assign({}, c, next);+ });+ if (!changed) return false;+ for (const c of out) { delete c._pin; }+ SBE.clips = sbeAdoptGaps(out);+ sbeLayout(SBE.clips);+ return true;+}+function sbeRenderErrors(errors) {const box = sbeEl('sbeErrors');if (!errors || !errors.length) {@@ -5227,8 +6018,8 @@ function sbeDraftRename(slug, was) {}// The verb the drafts rewrite dropped. It names the save ALREADY ON DISK —-// no revision bump, no write to edit.json, nothing about the timeline-// changes, which is exactly why it is safe to press at any moment.+// no revision bump, no write to edit.json beyond one already needed to make+// the label true, nothing else about the timeline changes.async function sbeKeepVersion() {const box = sbeEl('sbeVersName');const label = String((box && box.value) || '').trim();@@ -5238,6 +6029,30 @@ async function sbeKeepVersion() {if (box && box.focus) { try { box.focus(); } catch (e) {} }return;}+ // FILM-30: NAME WHAT'S ON SCREEN, NOT WHAT'S ON DISK. `/storyboard/edit/+ // version` archives a copy of edit.json exactly as it stands — it has no+ // idea the editor is showing something newer. Without this, "Keep this+ // version" against a dirty timeline silently named the PREVIOUS save while+ // reading, to the user, as if it had captured what was in front of them.+ // Same rule the render, the export and Relink already follow: an action+ // that reads the file on disk saves first, or says why it could not.+ // EDITOR-10 (Codex 4.17.0): ...AND NEVER DURING A CONFLICT. The save+ // above was skipped whenever another tab was ahead, so Keep went straight+ // to the server and named the arrangement ON DISK — the other tab's —+ // while telling this tab its own had been kept. Until the conflict is+ // settled there is no save of what is on this screen to name.+ if (SBE.conflict) {+ phosToast('Another tab saved this timeline after you opened it, so what is ' ++ 'on disk is not what is on your screen. Choose Load theirs or ' ++ 'Keep mine first, then name the version.',+ { kind: 'danger', duration: 9000 });+ return;+ }+ if (SBE.dirty && !(await sbeSave(true))) {+ phosToast('Your current arrangement could not be saved, so it could not ' ++ 'be named. Fix the save first.', { kind: 'danger', duration: 8000 });+ return;+ }const fd = new URLSearchParams();fd.set('id', SBE.id);fd.set('label', label);@@ -5392,9 +6207,13 @@ function sbePaintRecovery() {// counts and then declared that nothing had changed — a question about a// difference it could not name, over a document that had loaded correctly.// This says when, and how big, and leaves the decision where versions live.+ // FILM-54: `b.diff` (from `edit_diff_summary`, the server side of+ // `edit_digest`) says WHAT — "1 clip changed: 02 brightness +0.30" — so+ // the two counts matching is no longer the only thing on screen.sbeEl('sbeRecoverWhat').textContent ='from ' + sbeAgo(b.at) + ' · ' + sbeNum(b.clips, 0) + ' clips · ' +- sbeFmtTime(b.duration) + ' — your saved draft is untouched.';+ sbeFmtTime(b.duration) + (b.diff ? ' · ' + b.diff : '') ++ ' — your saved draft is untouched.';sbePaintNotices();}@@ -5430,13 +6249,26 @@ async function sbeRestoreVersion(file) {const fd = new URLSearchParams();fd.set('id', SBE.id);fd.set('file', file);+ // FILM-23: A CONFLICT IS A REASON TO STOP, NOT A REASON TO SKIP THE SAVE+ // AND CARRY ON. `!SBE.conflict` below used to be only a term inside the+ // save guard — with a conflict set, that term made the whole condition+ // false, so the save was skipped silently AND the restore proceeded,+ // installing the server's copy over an arrangement the user had not been+ // offered any way to keep. Face Fix already refuses outright; this now+ // matches it.+ if (SBE.conflict) {+ phosToast('This film was changed in another tab — resolve that first; ' ++ 'restoring now would replace the arrangement on screen with ' ++ 'no way back to it.', { kind: 'danger', duration: 8000 });+ return;+ }// The arrangement on screen is about to be replaced, so it goes to disk// first — the server archives what it overwrites, and an unsaved drag would// otherwise be the one thing in this feature that history could not keep.// Checked, for the same reason `sbeDraftOp` checks its backup: if the save// 409s or errors the server archives the OLD document, restore overwrites,// and the work goes with the undo stack that could have brought it back.- if (SBE.dirty && !SBE.conflict && !(await sbeSave(true))) {+ if (SBE.dirty && !(await sbeSave(true))) {phosToast('Your current arrangement could not be saved, so restoring ' +'would lose it. Fix the save first.',{ kind: 'danger', duration: 8000 });@@ -5747,6 +6579,24 @@ function sbeTlGrabKey(ev) {sbeTlPrefWrite(SBE.tlH);}+// FILM-58: one small flag per marker, on the ruler. Click jumps the+// playhead to it, right-click removes it — see the listeners in edInit.+function sbeMarkerBands(markers, span) {+ let out = '';+ for (const m of markers || []) {+ const at = sbeNum(m.at);+ if (at < -1e-6 || at > span + 1e-6) continue;+ const kind = (m && (m.kind === 'beat' || m.kind === 'lyric')) ? m.kind : 'note';+ const word = kind === 'beat' ? 'Beat' : kind === 'lyric' ? 'Lyric' : 'Marker';+ out += '<span class="sbe-marker is-' + kind + '" data-marker="' + escapeHtml(m.id)+ + '" data-at="' + at.toFixed(4) + '" '+ + 'style="left:' + sbePx(at).toFixed(1) + 'px" '+ + 'title="' + escapeHtml((m.label ? m.label + ' · ' : '') + word + ' · '+ + sbeFmtTime(at) + ' — click to jump, right-click to remove') + '"></span>';+ }+ return out;+}+function sbePaintRuler(span, width) {const r = sbeEl('sbeRuler');const steps = [0.5, 1, 2, 5, 10, 15, 30, 60, 120];@@ -5770,6 +6620,7 @@ function sbePaintRuler(span, width) {// through the same music window the bed and the beat grid use, so a// trimmed or slid soundtrack moves its sections with it.html += sbeSectionBands(SBE.sections, SBE.audio, SBE.peaks ? SBE.peaks.duration : 0, span);+ html += sbeMarkerBands(SBE.markers, span);r.innerHTML = html;r.style.width = width + 'px';if (r.classList) r.classList.toggle('has-sections', !!(SBE.sections && SBE.sections.length));@@ -6341,7 +7192,26 @@ function sbePaintTrack() {const bright = sbeBright(c);const bad = SBE.errors.byId && SBE.errors.byId[c.id];const sp = sbeSpeed(c);- const flag = c.locked ? 'lock'+ // FILM-15: OFFLINE OUTRANKS EVERY OTHER FLAG — a moved or trashed file+ // is the one thing on this clip that stops it playing at all, so it is+ // the one thing a glance at the track has to say first (only a live+ // slip/roll HUD, FILM-03, which exists just for the length of a drag,+ // sits above it).+ const offline = sbeClipOffline(c);+ // FILM-03: "slip +3 f" ON THE CLIP WHILE IT MOVES — the one place a+ // number can answer "how far did I just move the picture inside its+ // slot", which a slip or a roll drag has no other way to show (the slot+ // itself does not move, so there is no gap or overlap to read it from).+ let dragHud = '';+ if (SBE.drag && SBE.drag.moved && SBE.slipHud !== undefined+ && ((SBE.drag.mode === 'slip' && SBE.drag.id === c.id)+ || (SBE.drag.mode === 'roll' && SBE.drag.roll+ && (SBE.drag.roll.prevId === c.id || SBE.drag.roll.nextId === c.id)))) {+ const f = Math.round(SBE.slipHud * sbeFps());+ dragHud = 'slip ' + (f >= 0 ? '+' : '') + f + ' f';+ }+ const flag = dragHud ? dragHud : offline ? 'offline'+ : (c.locked ? 'lock': (Math.abs(sp - 1) >= 1e-6 ? sp.toFixed(2).replace(/\.?0+$/, '') + 'x': (Math.abs(bright) >= 1e-6? (bright > 0 ? '+' : '') + bright.toFixed(2)@@ -6349,7 +7219,7 @@ function sbePaintTrack() {// none and a slug has no file at all, so flagging either as// un-scrubbable would be advice to run a Prepare that would do// nothing.- : (kind === 'video' && !c.proxy ? 'slow' : '')));+ : (kind === 'video' && !c.proxy ? 'slow' : ''))));const cls = 'sbe-clip is-' + kind + (selMap[String(c.id)] ? ' is-sel' : '')+ ((selN > 1 && String(c.id) === String(SBE.sel)) ? ' is-primary' : '')+ (c.id === SBE.curId ? ' is-playing' : '')@@ -6357,6 +7227,7 @@ function sbePaintTrack() {+ (Math.abs(bright) >= 1e-6 ? ' is-graded' : '')+ (Math.abs(sp - 1) >= 1e-6 ? ' is-retimed' : '')+ (!sbeFramingIsNeutral(c) ? ' is-framed' : '')+ + (offline ? ' is-offline' : '')+ (flag ? ' has-flag' : '');// A still and a slug have no source window to report — their only number// is the hold, and printing "0.00→3.00" of a clock they do not have reads@@ -6372,20 +7243,44 @@ function sbePaintTrack() {// The still paints its own picture behind its name. One <img> per still on// the track, which is the same budget the pool already spends per row and// nothing like the media-element cap a <video> would eat.+ // FILM-39: A VIDEO CLIP NOW CARRIES ONE TOO — a cached first-frame JPEG+ // from its proxy (never the original: a clip with no proxy is exactly the+ // one flagged SLOW for the same reason, no fast seek, and asking ffmpeg to+ // open the source for a poster would be the slow decode Prepare exists to+ // avoid). Offline media gets no poster request at all — the file it would+ // ask for is already known not to answer, so this is not one more 404 on+ // top of the ones Relink already explains.const thumb = (kind === 'still' && c.path)? '<img class="sbe-cl-thumb" alt="" src="/image?w=240&path=' +encodeURIComponent(c.path) + '">'+ : (kind === 'video' && c.proxy && !offline)+ ? '<img class="sbe-cl-thumb" alt="" loading="lazy" src="/storyboard/edit/poster?id='+ + encodeURIComponent(SBE.id) + '&name='+ + encodeURIComponent(String(c.proxy).split('/').pop()) + '&w=240">': '';html += '<div class="' + cls + '" data-id="' + escapeHtml(c.id) + '" '+ 'data-kind="' + escapeHtml(kind) + '" '+ 'data-source="' + escapeHtml(c.source || 'auto') + '" '- + 'title="' + escapeHtml(label + (bad ? '\n' + bad[0].message : '')) + '" '+ + 'title="' + escapeHtml(label+ + (offline ? '\nMedia offline — ' + (c.path || '') ++ '. Relink to point at the file that has it now.' : '')+ + (bad ? '\n' + bad[0].message : '')) + '" '+ 'style="left:' + sbePx(c.film_start).toFixed(1) + 'px;width:' + w.toFixed(1) + 'px">'+ thumb+ '<div class="sbe-cl-name">' + escapeHtml(sbeNiceName(label)) + '</div>'+ (w > 96 ? '<div class="sbe-cl-meta">' + escapeHtml(meta) + '</div>' : '')- + (flag ? '<div class="sbe-cl-flag">' + escapeHtml(flag) + '</div>' : '')+ // FILM-39: "SLOW" was jargon with no tooltip and no action — it+ // means "no proxy yet, so scrubbing decodes from the source GOP".+ // A nested title on the flag itself (the innermost one a browser+ // shows on hover) explains it in the same words Prepare uses,+ // without touching the clip's own drag/select handling.+ // 4.17: the flag is also the fix — a click runs Prepare+ // (sbeOnTrackDown routes it before any drag/select handling).+ + (flag === 'slow'+ ? '<div class="sbe-cl-flag sbe-slow-flag" role="button" title="Slow to scrub until Prepare builds a proxy — click to run Prepare.">⧖</div>'+ : (flag ? '<div class="sbe-cl-flag">' + escapeHtml(flag) + '</div>' : ''))+ sbeSyncBadge(c)+ + (w > 60 ? sbeSongSyncBadge(c) : '')+ sbeFadeMarks(c)+ '<div class="sbe-grip l"></div><div class="sbe-grip r"></div>'// THE TWO CORNER HANDLES, IN A BAND INSET FROM BOTH GRIPS. The@@ -6474,6 +7369,80 @@ function sbeSyncBadge(c) {+ escapeHtml(sbeDriftLabel(d)) + '</div>';}+// FILM-05: "SYNC TO SONG". A singing shot is conditioned on one fixed+// stretch of the track (`audio_start_time`); the position it BELONGS at is+// that second plus however much its own head has been trimmed+// (`audio_start_time + start`), and the app never compared that against+// where the shot actually sits. Measured on the owner's cut: 16 of 19 a2v+// clips sat 4 to 9 frames off — his own hand corrections, recorded nowhere.+function sbeSongSyncOffset(c, shot) {+ if (!c || sbeKind(c) !== 'video' || !shot) return null;+ if (String(shot.mode || '').toLowerCase() !== 'a2v') return null;+ const ast = shot.audio_start_time;+ if (ast === null || ast === undefined) return null;+ const expected = sbeNum(ast) + sbeNum(c.start, 0);+ return sbeRound(sbeNum(c.film_start) - expected);+}++// FILM-05 item 4: AUTO-LOCK AGAINST MOVES THAT BREAK SONG SYNC. A trim or a+// roll leaves the offset above untouched — the film side and the source+// side of the mapping move together, by construction (a head trim moves the+// slot WITH the in-point; see sbeTrim) — but a plain MOVE, a multi-select+// MOVE or a REORDER slides only the slot: `film_start` changes, `start`+// does not, and the offset breaks silently with no gesture to catch it.+// This is the exact silent failure FILM-05 exists to surface, so a clip+// conditioned on the song refuses those three gestures outright. Slip stays+// open — it is the sanctioned way to correct the offset (`sbeSnapToSong`,+// FILM-03's own gesture) — and so does trim/roll, neither of which can move+// the offset. Editor-side only: the board's own lock is FILM-21's, a+// different surface entirely.+function sbeSongLocked(c) {+ if (!c) return false;+ const shot = sbeShotForClip(c);+ if (!shot || String(shot.mode || '').toLowerCase() !== 'a2v') return false;+ const ast = shot.audio_start_time;+ return ast !== null && ast !== undefined;+}++// The readout: "♪ +0.19 s vs song". Absent when the offset is under half a+// frame — a clip dead on its mark has nothing to say, the same rule+// `sbeSyncBadge` follows for the J/L-cut flag.+function sbeSongSyncBadge(c) {+ if (sbeKind(c) !== 'video') return '';+ const shot = sbeShotForClip(c);+ const off = sbeSongSyncOffset(c, shot);+ if (off === null || Math.abs(off) < 0.5 / sbeFps()) return '';+ const s = (off > 0 ? '+' : '') + off.toFixed(2) + ' s';+ return '<div class="sbe-songsync" data-songsync="' + escapeHtml(c.id) + '" '+ + 'title="' + escapeHtml('This shot sits ' + s + ' vs the song it was conditioned on '+ + '(' + (off > 0 ? 'late' : 'early') + '). Click to snap it back — a slip, the slot stays put.')+ + '">♪ ' + escapeHtml(s) + '</div>';+}++// ONE CLICK, AND IT USES SLIP: the slot (film_start/film_end) does not+// move — only which seconds of the take play in it, exactly the FILM-03+// gesture, applied by the number FILM-05 measures instead of by hand.+function sbeSnapToSong(id) {+ const c = sbeById(SBE.clips, id);+ if (!c) return;+ const shot = sbeShotForClip(c);+ const off = sbeSongSyncOffset(c, shot);+ if (off === null || Math.abs(off) < 1e-6) return;+ // offset = film_start - (audio_start_time + start), so zeroing it means+ // start_new = film_start - audio_start_time = start + offset: the delta+ // IS the offset, not its negation — a slot that sits LATE (offset > 0)+ // needs LATER source content too, so `start` moves forward by the same+ // amount the slot is ahead by.+ const ok = sbeMutate(cs => sbeSlip(cs, id, off));+ if (ok) {+ const df = Math.round(off * sbeFps());+ phosToast('Snapped to the song — ' + (df >= 0 ? '+' : '') + df + ' f.',+ { kind: 'success', duration: 4000 });+ } else {+ phosToast('Could not snap it — the take does not have that much head or tail left.', {});+ }+}+// THE SOUND, UNDER THE PICTURE THAT MADE IT. One strip per video clip,// directly beneath its block: linked ones are dim and inert, unlinked ones// carry the same grips a clip does.@@ -7076,6 +8045,9 @@ async function sbeTsAddSoundPath(path, tid, at) {phosToast('Open a __SEQ__ first — a sound belongs to a timeline.', {});return false;}+ // FILM-32: same as edPoolAdd — the import this awaits can outlast the+ // film that asked for it.+ const wantId = SBE.id;const fd = new URLSearchParams();fd.set('id', SBE.id);fd.set('path', String(path || ''));@@ -7083,6 +8055,7 @@ async function sbeTsAddSoundPath(path, tid, at) {try {r = await (await fetch('/storyboard/edit/add-sound', { method: 'POST', body: fd })).json();} catch (e) { r = { ok: false, error: String(e) }; }+ if (SBE.id !== wantId) return false;if (!r || !r.ok) {phosToast((r && r.error) || 'That sound could not be added.', { kind: 'danger' });return false;@@ -8650,8 +9623,13 @@ function sbePaintHead() {sbeCbarPlayhead();const t = sbeEl('sbeTime');if (t) {- t.innerHTML = escapeHtml(sbeFmtTime(SBE.playhead)) +- ' <span>/ ' + escapeHtml(sbeFmtTime(sbeFilmDuration(SBE.clips))) + '</span>';+ const frames = sbeTimeMode() === 'frames';+ const fmt = frames ? (x) => sbeFmtTC(x, sbeFps()) : sbeFmtTime;+ t.innerHTML = escapeHtml(fmt(SBE.playhead)) ++ ' <span>/ ' + escapeHtml(fmt(sbeFilmDuration(SBE.clips))) + '</span>';+ t.title = frames+ ? 'HH:MM:SS:FF at ' + sbeFps() + ' fps. Click for seconds.'+ : 'Minutes:seconds. Click for a frame timecode.';}}@@ -9075,6 +10053,31 @@ function sbeCbarModel() {+ 'keeping the face and the sound. It runs in the queue; when it '+ 'lands, a line above the timeline offers to swap it in — same '+ 'cut, same in and out points. The original file is not changed.' },+ // FILM-53: Retake was reachable only from the Inspector's Advanced+ // block — rare, but not THAT rare, and a right-click was the more+ // natural reach for it. Same verb, same dialog; now on the clip bar and+ // in the menu too.+ { id: 'sbeCbRetake', act: 'sbeRetakeSel()', label: 'Retake',+ why: !n ? noSel+ : (many ? 'Pick one clip — each retake is its own render.'+ : (!vid || !sbeShotForClip(c) ? 'Only a clip that came from a storyboard shot '+ + 'can be retaken — it has no prompt to start from.'+ : '')),+ title: 'Renders a new take of this shot — same character, a new seed, the prompt to edit. '+ + 'When it lands you choose whether it replaces this clip.' },+ // FILM-08: "Replace with…" picks the newest rendered alternate for the+ // SAME hole this clip sits in — not any alternate anywhere, which would+ // need a picker this menu has no room for; the unplaced list's own+ // "Swap in" button is that picker.+ { id: 'sbeCbReplace', act: 'sbeReplaceSelWithAlt()', label: 'Replace with…',+ why: !n ? noSel+ : (many ? 'Pick one clip.'+ : (!vid ? 'Only a video clip can be replaced.'+ : (!sbeAltForClip(c) ? 'No rendered alternate for this shot is waiting — drag '+ + 'one from the media pool, or ⌥-drop it onto this clip.'+ : ''))),+ title: 'Swaps in the newest rendered alternate for this shot. Keeps the slot, the trim, '+ + 'adjustments and transitions — only the picture changes.' },];// The one readout that makes the rest of the row legible.// A SOUND IS NAMED AS A SOUND, so "Duplicate" beside it reads as copying@@ -9694,7 +10697,7 @@ function sbePaintInspector() {// `adjust.brightness` on disk, because a label is not worth a data// migration — and it is PRESENTED here, beside the fades, because this is// where a person looks for it.- sect('Effects', adjust + fadeRow('in', e.fade_in) + fadeRow('out', e.fade_out)+ sect('Effects', adjust + sbeGradeRows(c) + fadeRow('in', e.fade_in) + fadeRow('out', e.fade_out)+ ((kind !== 'slug') ? (() => {const fr = sbeFraming(c);const on = !sbeFramingIsNeutral(c);@@ -9774,6 +10777,79 @@ function sbeBrightCommit(v) {sbeQueueSave();}+// FILM-14: the 5-slider grade's row markup, matching the existing brightness+// slider's shape exactly — a slug has no colour to grade.+function sbeGradeRows(c) {+ if (!c || sbeKind(c) === 'slug') return '';+ const g = sbeGrade(c);+ const row = (label, field, step, fmt) => {+ const [lo, hi] = SBE_GRADE_FIELDS[field];+ return '<span class="sbe-fade-row"><label for="sbeGrade' + field + '">' + label + '</label>'+ + '<input type="range" id="sbeGrade' + field + '" min="' + lo + '" max="' + hi + '" step="' + step + '" '+ + 'value="' + g[field] + '" oninput="sbeGradePreview(\'' + field + '\', this.value)" '+ + 'onchange="sbeGradeCommit(\'' + field + '\', this.value)" onmouseup="sbeBlurControl()" '+ + 'title="Approximate on screen, exact in the render.">'+ + '<span class="sbe-adj-val" id="sbeGrade' + field + 'Val">' + fmt(g[field]) + '</span></span>';+ };+ const notNeutral = !sbeGradeIsNeutral(c);+ return row('Exposure', 'exposure', '0.01', (v) => (v > 0 ? '+' : '') + v.toFixed(2))+ + row('Contrast', 'contrast', '0.01', (v) => v.toFixed(2) + 'x')+ + row('Saturation', 'saturation', '0.01', (v) => v.toFixed(2) + 'x')+ + row('Temp', 'temp', '0.01', (v) => (v > 0 ? '+' : '') + v.toFixed(2))+ + row('Tint', 'tint', '0.01', (v) => (v > 0 ? '+' : '') + v.toFixed(2))+ + (notNeutral+ ? '<span class="sbe-fade-row"><button type="button" class="ghost-btn" '+ + 'onclick="sbeGradeResetSel()">Reset grade</button>'+ + (sbeSelCount() > 1+ ? '<button type="button" class="ghost-btn" onclick="sbeCopyGradeSel()" '+ + 'title="Copies this clip\'s five grade numbers onto every other selected clip. '+ + 'One Undo puts them all back.">Copy grade → selection</button>'+ : '') + '</span>'+ : '');+}++// oninput paints the CSS preview only; onchange (drag end) is the edit —+// the same split every slider in this inspector makes.+function sbeGradePreview(field, v) {+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) return;+ const [lo, hi] = SBE_GRADE_FIELDS[field];+ const val = sbeRound(Math.max(lo, Math.min(hi, sbeNum(v))));+ const out = sbeEl('sbeGrade' + field + 'Val');+ if (out) {+ out.textContent = (field === 'contrast' || field === 'saturation')+ ? val.toFixed(2) + 'x' : (val > 0 ? '+' : '') + val.toFixed(2);+ }+ const preview = Object.assign({}, c, { adjust: Object.assign({}, c.adjust || {}, { [field]: val }) });+ sbeApplyPreviewGrade(preview, sbeFraming(c));+}+function sbeGradeCommit(field, v) {+ if (!SBE.sel) return;+ const ok = sbeMutate(cs => sbeSetGrade(cs, SBE.sel, field, v));+ if (!ok) { sbePaintInspector(); return; }+}+function sbeGradeResetSel() {+ if (!SBE.sel) return;+ const ok = sbeMutateEach([SBE.sel], (cs, id) => {+ let res = { clips: cs, ok: true };+ for (const key of Object.keys(SBE_GRADE_FIELDS)) {+ res = sbeSetGrade(res.clips, id, key, SBE_GRADE_FIELDS[key][2]);+ if (!res.ok) return res;+ }+ return res;+ });+ if (ok) phosToast('Grade reset.', { duration: 3000 });+}+function sbeCopyGradeSel() {+ const ids = sbeSelIds();+ if (!SBE.sel || ids.length < 2) return;+ const ok = sbeMutate(cs => sbeCopyGrade(cs, SBE.sel, ids));+ if (ok) {+ phosToast('Grade copied to ' + (ids.length - 1) + ' clip(s). One Undo puts them all back.',+ { kind: 'success', duration: 5000 });+ }+}+// A CONTROL THAT KEEPS FOCUS EATS THE SPACE BAR — the next press re-clicks// it instead of toggling play. Every inspector commit hands focus back.function sbeBlurControl() {@@ -9830,6 +10906,31 @@ function sbeApplyPreviewFilter(b, frame) {sbeApplyPreviewFraming(frame);}+// FILM-14: exposure/contrast/saturation preview cleanly onto CSS's own+// brightness()/contrast()/saturate() — unlike ffmpeg's ADDITIVE brightness,+// CSS contrast()/saturate() are ALREADY 1.0-centred multipliers, the exact+// semantics eq=contrast/eq=saturation use, so these two need no+// approximation at all. temp/tint have no CSS equivalent and are not+// previewed on the stage; the render is exact regardless, same as the+// brightness mismatch this function's sibling already documents.+function sbeGradeCss(c) {+ const g = sbeGrade(c);+ const total = sbeBright(c) + g.exposure;+ const parts = [];+ if (Math.abs(total) >= 1e-6) parts.push('brightness(' + sbeBrightnessCss(total) + ')');+ if (Math.abs(g.contrast - 1) >= 1e-6) parts.push('contrast(' + g.contrast.toFixed(3) + ')');+ if (Math.abs(g.saturation - 1) >= 1e-6) parts.push('saturate(' + g.saturation.toFixed(3) + ')');+ return parts.join(' ');+}+function sbeApplyPreviewGrade(c, frame) {+ const css = sbeGradeCss(c);+ const v = sbeEl('sbeVideo');+ const i = sbeEl('sbeStill');+ if (v) v.style.filter = css;+ if (i) i.style.filter = css;+ sbeApplyPreviewFraming(frame);+}+// THE REFRAME ON THE STAGE: the layer scaled about the anchor. Approximate// — the stage letterboxes with object-fit, so a picture that is not 16:9// scales about a point slightly off the source's own fraction — and the@@ -9901,6 +11002,22 @@ function sbePaintChrome() {save.classList.toggle('ghost-btn', !(SBE.dirty && !SBE.saving));}sbePlayGlyph('sbePlayBtn', 'sbePlayUse', SBE.playing);+ // FILM-14: FILM LOOK — the active pill follows the saved document, not a+ // client-remembered preference like Deliver's format/size/finish, because+ // the look is part of the film itself and has to agree with what a+ // teammate opening the same __SEQ__ sees.+ const lookWrap = sbeEl('sbeFilmLook');+ if (lookWrap) {+ const look = ((SBE.edit || {}).settings || {}).film_look || 'none';+ lookWrap.querySelectorAll('.pill-btn').forEach(+ b => b.classList.toggle('active', (b.dataset.look || 'none') === look));+ }+ const aspectWrap = sbeEl('sbeSeqAspect');+ if (aspectWrap) {+ const aspect = sbeSeqAspect();+ aspectWrap.querySelectorAll('.pill-btn').forEach(+ b => b.classList.toggle('active', b.dataset.aspect === aspect));+ }sbePaintPanels();// The zoom slider is a VIEW of SBE.pps, not a second copy of it: the − / +// buttons, alt + wheel and a resize all move the handle by coming through@@ -9949,12 +11066,27 @@ function sbePaintChrome() {? sbeNum(u.slot.film_start) : sbeFilmDuration(SBE.clips);// The timecode is the same on every row, so it belongs on the button's// title rather than repeated thirteen times down a 230px column.+ // FILM-08: a "Swap in" offer when this take was rendered for a hole a+ // clip is already sitting in — an alternate (P1_s2, P2_s1…) of a shot+ // that already has SOMETHING on the timeline, not a hole waiting to be+ // filled. Matched by slot, not by `n`: the alternates are separate+ // shots the planner made for the same position, so `n` differs.+ const target = (u.slot && u.slot.film_start !== undefined)+ ? (SBE.clips || []).find(x => Math.abs(sbeNum(x.film_start) - sbeNum(u.slot.film_start)) < 0.05)+ : null;+ const swap = (target && !target.locked)+ ? '<button type="button" class="ghost-btn" onclick="sbeSwapIn(' + i + ')" ' ++ 'title="Replaces shot ' + escapeHtml(String(target.n !== undefined && target.n !== null ? target.n : '')) ++ ' on the timeline with this take. Same slot, same trim, adjustments and transitions kept.">' ++ 'Swap in for shot ' + escapeHtml(String(target.n !== undefined && target.n !== null ? target.n : '?')) ++ '</button>'+ : '';return '<span class="sbe-chip" title="' +escapeHtml((u.title || ('shot ' + u.n)) + ' — would land at ' +sbeFmtTime(at)) + '">' +'<b>' + escapeHtml(sbeNiceName(u.title || ('shot ' + u.n))) + '</b>' +'<span>' + escapeHtml(u.duration_s ? sbeNum(u.duration_s).toFixed(1) + 's' : (u.pass || '')) + '</span>' +- '<button type="button" class="ghost-btn" onclick="sbePlace(' + i + ')">Place</button></span>';+ '<button type="button" class="ghost-btn" onclick="sbePlace(' + i + ')">Place</button>' + swap + '</span>';}).join('');}// prepare@@ -10015,9 +11147,25 @@ function sbeSnapEnabled(ev) {function sbeOnTrackDown(ev) {const track = sbeEl('sbeTrack');+ SBE.slipHud = undefined;// Same as the lane: the flag is a button, not part of the block.const badge = ev.target.closest('.sbe-sync');if (badge) { ev.preventDefault(); sbeResyncSel(badge.dataset.sync); return; }+ // FILM-05: the song-sync flag — a different button, a different fix.+ const songBadge = ev.target.closest('.sbe-songsync');+ if (songBadge) { ev.preventDefault(); sbeSnapToSong(songBadge.dataset.songsync); return; }+ // FILM-39: the SLOW flag names its own fix, so clicking it runs that fix —+ // Prepare, which builds the proxies — instead of starting a drag.+ const slowFlag = ev.target.closest('.sbe-slow-flag');+ if (slowFlag) {+ ev.preventDefault();+ if (SBE.prepare && SBE.prepare.state === 'running') {+ phosToast('Prepare is already running — smooth scrubbing arrives when it finishes.', {});+ } else {+ sbePrepare();+ }+ return;+ }const gap = ev.target.closest('.sbe-gap');if (gap) {sbeGenOpen(sbeNum(gap.dataset.gapStart), sbeNum(gap.dataset.gapDur));@@ -10133,9 +11281,49 @@ function sbeOnTrackDown(ev) {// trim is one clip's edge whatever else is selected, and a reorder chooses// one clip's neighbour.const many = sbeSelCount() > 1 && sbeSelHas(id);- const mode = grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL')+ // FILM-03: ⌥⌘-DRAG THE BODY IS SLIP. Neither modifier means anything on a+ // body drag today (⌘ alone is ripple, which a bare body-move already+ // reads), so the combination is free, and it is the same chord After+ // Effects and Resolve both already use for it.+ const wantSlip = !grip && ev.altKey && (ev.metaKey || ev.ctrlKey);+ // ⌥-DRAG AN EDGE IS ROLL, but only where there is a cut to roll: the other+ // side of THIS edge has to be a different clip with no gap between them.+ // Anywhere else (the film's own head or tail, or a real hole) alt on an+ // edge falls back to an ordinary trim — there is nothing for it to share.+ let rollWith = null;+ if (grip && ev.altKey && !ev.shiftKey && !ev.metaKey && !ev.ctrlKey) {+ const i = SBE.clips.indexOf(c);+ if (grip.classList.contains('r')) {+ const nb = SBE.clips[i + 1];+ if (nb && !nb.locked && Math.abs(sbeNum(nb.film_start) - sbeNum(c.film_end)) < 1e-6) {+ rollWith = { prevId: c.id, nextId: nb.id };+ }+ } else {+ const nb = SBE.clips[i - 1];+ if (nb && !nb.locked && Math.abs(sbeNum(nb.film_end) - sbeNum(c.film_start)) < 1e-6) {+ rollWith = { prevId: nb.id, nextId: c.id };+ }+ }+ }+ const mode = rollWith ? 'roll'+ : wantSlip ? 'slip'+ : grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL'): ((ev.shiftKey && ev.altKey) ? 'reorder': (many ? 'movemany' : 'move'));+ // FILM-05 item 4: a clip conditioned on the song refuses move/movemany/+ // reorder — see sbeSongLocked. Trim, roll and slip are untouched by this+ // check (none of them can move the offset; slip is how you fix it).+ if (mode === 'move' || mode === 'movemany' || mode === 'reorder') {+ const ids = (mode === 'movemany') ? sbeSelIds() : [id];+ const lockedId = ids.find(i => sbeSongLocked(sbeById(SBE.clips, i)));+ if (lockedId) {+ phosToast('That shot is conditioned on the song, so moving or reordering '+ + 'it is blocked — it would throw off the sync. Use the ♪ badge '+ + '(Snap to song) or slip it instead, or unlink its sound first.',+ { duration: 8000 });+ return;+ }+ }// ⌘ / CTRL IS RIPPLE: the gesture also slides everything after the clip,// the way it did before 2026-09-05. Read again on every move so it can be// pressed or released mid-drag, as in Premiere.@@ -10143,6 +11331,8 @@ function sbeOnTrackDown(ev) {fs0: sbeNum(c.film_start), fe0: sbeNum(c.film_end), moved: false,ripple: !!(ev.metaKey || ev.ctrlKey),ids: (mode === 'movemany') ? sbeSelIds() : null,+ s0: sbeNum(c.start), sp: sbeSpeed(c),+ roll: rollWith,toggle: toggle, collapse: collapse,before: JSON.stringify(SBE.clips) };if (mode === 'move' || mode === 'movemany') {@@ -10184,6 +11374,16 @@ function sbeOnTrackMove(ev) {// pulling the drop index onto a beat would mean nothing.const r = sbeReorderTo(SBE.clips, d.id, Math.max(0, d.t0 + dt));if (r.ok) SBE.clips = r.clips;+ } else if (d.mode === 'slip') {+ // FILM-03. No snap: a slip does not choose a TIME either, it chooses+ // which seconds of the take fill a slot that is not moving.+ SBE.clips = JSON.parse(d.before);+ const r = sbeSlip(SBE.clips, d.id, dt * d.sp);+ if (r.ok) { SBE.clips = r.clips; SBE.slipHud = r.applied; }+ } else if (d.mode === 'roll') {+ SBE.clips = JSON.parse(d.before);+ const r = sbeRollEdit(SBE.clips, d.roll.prevId, d.roll.nextId, dt);+ if (r.ok) { SBE.clips = r.clips; SBE.slipHud = r.applied; }} else {// A SHOT DRAGGED UP ONTO THE SOURCE MONITOR loads there and the track// stays exactly as it was — the block springs back while it is over it.@@ -10394,7 +11594,7 @@ async function sbeShowFrameAt(t) {return;}const kind = sbeKind(c);- sbeApplyPreviewFilter(sbeBright(c), sbeFraming(c));+ sbeApplyPreviewGrade(c, sbeFraming(c));if (kind === 'slug') {// NO FILE, SO NOTHING TO LOAD. Both layers off leaves the stage's own// black, which is the frame the render will write — the one case where the@@ -10562,6 +11762,11 @@ function sbePaintSource() {const mon = sbeEl('sbeSrcMon');if (mon) mon.hidden = !sbeSrcShown();const row = SBE.source;+ // FILM-37: collapsed to a rail while nothing is loaded — see the CSS+ // comment on .sbe-mon-src.is-empty for why. `!row` is the exact same test+ // the rest of this function already uses to decide "nothing loaded", so+ // the collapse can never show one answer while the bar says another.+ if (mon && mon.classList) mon.classList.toggle('is-empty', !row);const name = sbeEl('sbeSrcName');const add = sbeEl('sbeSrcAddBtn');const play = sbeEl('sbeSrcPlayBtn');@@ -10619,10 +11824,21 @@ function sbeSetMusicMode(v) {if (el) el.value = mode;if (SBE.audio) {if (String(SBE.audio.mode || 'under') === mode) return;- SBE.audio.mode = mode;- SBE.dirty = true;- sbeSetState('unsaved changes', 'dirty');- sbeQueueSave();+ // FILM-33: THROUGH THE ONE WRITER, LIKE EVERY OTHER SOUNDTRACK GESTURE.+ // This used to mutate `SBE.audio.mode` in place. A clean save replaces+ // `SBE.edit` with a FRESH object built from the server's answer+ // (`SBE.edit = Object.assign({}, r.edit || {}, ...)`) but never touches+ // `SBE.audio` — so after the first save the two silently point at+ // different objects, and every mode change after that mutates the+ // orphaned one. `sbeSaveBody` reads `SBE.edit.audio`, so the change was+ // real on screen and never reached the file: "Replace" (the music-video+ // mode) reopened as "Under", the clips' own audio back beneath the song.+ // `sbeSetAudio` writes both references to the same new object;+ // `sbeMusicCommit` gives the change undo and the queued backup every+ // other soundtrack edit already gets.+ const beforeJson = JSON.stringify(SBE.audio);+ sbeSetAudio(Object.assign({}, SBE.audio, { mode: mode }));+ sbeMusicCommit(beforeJson);}// Only `replace` needs saying: it is the one that destroys something.const warn = sbeEl('sbeMusicWarn');@@ -10650,9 +11866,8 @@ window.ED = { src: 'film', rows: [], films: [], film: '', loading: false,function edPoolSrc(name) {ED.src = name;- const tabs = document.getElementById('edPoolTabs');- if (tabs) tabs.querySelectorAll('.pill-btn').forEach(b =>- b.classList.toggle('active', b.dataset.src === name));+ const sel = document.getElementById('edPoolSrcSelect');+ if (sel && sel.value !== name) sel.value = name;const pick = document.getElementById('edPoolFilm');if (pick) pick.hidden = (name !== 'other');// Upload belongs to the source that shows what was uploaded.@@ -10696,8 +11911,8 @@ async function edPoolUpload(files) {if (ED.src !== 'images') edPoolSrc('images'); else await edPoolRefresh(true);if (done) {phosToast(done + (done === 1 ? ' file is' : ' files are') +- ' in the pool — press + to put it at the end, or drag it onto '- + 'the track.',+ ' in the pool — press + to put it at the playhead, or drag it '+ + 'onto the track.',{ kind: 'success', duration: 5000 });}for (const msg of bad) phosToast(msg, { kind: 'danger', duration: 7000 });@@ -10818,6 +12033,10 @@ async function edPoolLoadFilms() {function edPoolPickFilm(id) { ED.film = id; ED.limit = 60; edPoolRefresh(); }+// FILM-40: the one way past the pool's 60-row cap. Repaints only — the rows+// are already fetched, this just stops slicing them.+function edPoolShowAll() { ED.limit = Infinity; edPoolPaint(); }+async function edPoolLoadFilmShots(id) {if (!id) return [];let r;@@ -10862,7 +12081,14 @@ function edPoolPaint() {? (ED.films && ED.films.length? 'That __SEQ__ has no rendered clips yet.': 'No other __SEQS__ yet. Every __SEQ__ you make shows up here to borrow clips from.')- : 'This __SEQ__ has no rendered clips yet. Render its shots in Storyboard, or take one from another source above.') + '</span>';+ // FILM-40: THIS EMPTY STATE CONTRADICTED THE TIMELINE IT SAT NEXT+ // TO. "No rendered clips yet" is about the BOARD (this pool's own+ // source, the shots it rendered) — a film cut from imported or+ // Video-tab clips can have plenty on the timeline and nothing here+ // to borrow FROM, which is a different, true sentence.+ : ((SBE.clips || []).length+ ? 'Nothing left to add from this __SEQ__’s own shots — every clip on the timeline came from somewhere else.'+ : 'This __SEQ__ has no rendered clips yet. Render its shots in Storyboard, or take one from another source above.')) + '</span>';if (note) note.textContent = '';return;}@@ -10903,9 +12129,16 @@ function edPoolPaint() {? '<button type="button" class="ed-pool-add" ' +'title="Put this sound on an audio track at the playhead" ' +'onclick="event.stopPropagation();edPoolSound(' + i + ')">+</button>'+ // FILM-40: "+" USED TO MEAN "put this at the end", always — so a clip+ // swapped in mid-cut meant a click here and then a drag all the way+ // back to where you actually were. It inserts at the playhead now+ // (a ripple, like a drop does), which is where you were just looking;+ // ⌥+click keeps the old "append at the end" for the one time that is+ // actually what somebody wants.: '<button type="button" class="ed-pool-add" ' +- 'title="Put this clip at the end of the __SEQ__" ' +- 'onclick="event.stopPropagation();edPoolAdd(' + i + ')">+</button>') ++ 'title="Put this clip at the playhead (⌥ for the end of the __SEQ__)" ' ++ 'onclick="event.stopPropagation();edPoolAdd(' + i ++ ', event.altKey ? undefined : SBE.playhead)">+</button>') +// A VIDEO CAN GIVE ITS SOUND ALONE — onto an audio track, at the playhead,// with no picture.((!r.kind || r.kind === 'video')@@ -10932,10 +12165,15 @@ function edPoolPaint() {sbePaintSource();}if (note) {- note.textContent = rows.length > show.length- ? (show.length + ' of ' + rows.length + ' shown.')- : (rows.length + ' clip' + (rows.length === 1 ? '' : 's') +- ' · click one to watch it, + to put it at the end, or drag it onto the track.');+ // FILM-40: "60 of 75 shown." used to be the whole sentence — a cap with+ // no way past it. One link past the cap that raises it to "everything",+ // the same shape the search filter's own note already uses elsewhere.+ note.innerHTML = rows.length > show.length+ ? (show.length + ' of ' + rows.length + ' shown. ' ++ '<a href="#" onclick="event.preventDefault();edPoolShowAll();">Show all ' ++ rows.length + '</a>')+ : escapeHtml(rows.length + ' clip' + (rows.length === 1 ? '' : 's') ++ ' · click one to watch it, + to put it at the playhead, or drag it onto the track.');}}@@ -10974,7 +12212,7 @@ function edPoolObserve(list) {// THE VERB. A clip joins the timeline, gets its proxy built before it lands,// and the user does not move: adding to a cut is not a reason to leave it.-async function edPoolAdd(i, dropAt) {+async function edPoolAdd(i, dropAt, overwriteId) {const list = document.getElementById('edPoolList');const row = ((list || {})._rows || [])[i];if (!row) return;@@ -10999,6 +12237,12 @@ async function edPoolAdd(i, dropAt) {? ('reading ' + (row.title || 'that image') + '…'): ('building the proxy for ' + (row.title || 'that clip') + '…');}+ // FILM-32: WHICH FILM THIS WAS FOR. The proxy build below is the slow+ // part — real footage, sometimes several seconds — and nothing stopped+ // the user from switching films while it ran. The clip landed in+ // whichever film happened to be open when the AWAIT returned, not the+ // one it was dropped onto.+ const wantId = SBE.id;const fd = new URLSearchParams();fd.set('id', SBE.id);if (isStill) { fd.set('kind', 'still'); fd.set('path', row.path); }@@ -11008,6 +12252,14 @@ async function edPoolAdd(i, dropAt) {let r;try { r = await (await fetch('/storyboard/edit/add-clip', { method: 'POST', body: fd })).json(); }catch (e) { r = { ok: false, error: String(e) }; }+ if (SBE.id !== wantId) {+ // Too late to land it here, and wrong to land it where the user is now.+ // The build already happened server-side and the clip sits in the pool+ // (and, if `wantId`'s edit is reopened, in its "unplaced" list) — a+ // quiet re-read of the CURRENT film covers the note this leaves blank.+ if (note) note.textContent = '';+ return;+ }if (!r.ok) {if (note) note.textContent = '';phosToast(r.error || 'That clip could not be added.', { kind: 'danger' });@@ -11021,12 +12273,14 @@ async function edPoolAdd(i, dropAt) {: (c.duration_s || row.duration_s || null)),title: c.title || row.title || '', n: c.n,};- // A CLICK LANDS AT THE END; A DROP LANDS WHERE IT WAS DROPPED. The first- // cannot move anybody's cuts, which is why it is still the default verb; the- // second was ASKED for, and a drop that ignored where the pointer was would- // be a drag with no meaning.+ // A CLICK LANDS AT THE END; A DROP LANDS WHERE IT WAS DROPPED; A ⌥-DROP ON+ // A CLIP REPLACES IT. The first cannot move anybody's cuts, which is why+ // it is still the default verb; the second was ASKED for, and a drop that+ // ignored where the pointer was would be a drag with no meaning; the+ // third (FILM-08) never ripples anything — the slot is not touched.let at;const ok = sbeMutate(cs => {+ if (overwriteId) { at = (sbeById(cs, overwriteId) || {}).film_start; return sbeReplaceClip(cs, overwriteId, item); }if (dropAt === undefined || dropAt === null) {at = sbeFilmDuration(cs);return sbePlaceUnplaced(cs, item, at);@@ -11035,10 +12289,15 @@ async function edPoolAdd(i, dropAt) {return sbeInsertAt(cs, item, at);});if (!ok) { if (note) note.textContent = ''; return; }- await sbeSave(true);+ // FILM-29: `sbeMutate` above already marked this dirty and queued the+ // crash backup (immediately, on a clean timeline — see sbeQueueSave). A+ // manual save here was a second, silent write to edit.json the user never+ // pressed Save for. `sbeLoad(true)` below already refuses to clobber a+ // dirty document (see sbeAdoptMeta), so nothing needs the write to land+ // first.if (note) note.textContent = '';- phosToast('Added at ' + sbeFmtTime(at) +- (isStill ? ' · still' : ' · proxy ready.'),+ phosToast(overwriteId ? 'Replaced the clip at ' + sbeFmtTime(sbeNum(at)) + '. Same cut, same timings.'+ : ('Added at ' + sbeFmtTime(at) + (isStill ? ' · still' : ' · proxy ready.')),{ kind: 'success', duration: 4000 });// The board may have gained a shot (an import), and the payload's `unplaced`// and `clips` are now stale. Re-read quietly; nothing on screen moves.@@ -11162,6 +12421,14 @@ function edPoolDragMove(ev) {track.classList.toggle('is-dropping', !!over);SBE.dropAt = over ? edPoolDropTime(ev, track) : null;SBE.tsDrop = (onTracks && d.row.kind !== 'still') ? onTracks : null;+ // FILM-08: ⌥-DROP IS OVERWRITE. Dropped square over a clip's own picture+ // with ⌥ held, it REPLACES that clip instead of inserting and rippling —+ // the modifier "Place" and a plain drop never had, so a swap always meant+ // pushing every later shot off the beat by hand.+ SBE.dropOverwriteId = (over && ev.altKey && d.row.kind !== 'sound')+ ? (sbeClipAt(SBE.clips, sbeTimeFromEvent(ev, track)) || {}).id || null+ : null;+ track.classList.toggle('is-overwriting', !!SBE.dropOverwriteId);sbePaintTrack();sbePaintTracks();}@@ -11192,9 +12459,11 @@ async function edPoolDragEnd(ev) {if (!d) return;if (d.ghost) d.ghost.remove();const track = sbeEl('sbeTrack');- if (track) track.classList.remove('is-dropping');+ if (track) { track.classList.remove('is-dropping'); track.classList.remove('is-overwriting'); }const at = SBE.dropAt;SBE.dropAt = null;+ const overwriteId = SBE.dropOverwriteId;+ SBE.dropOverwriteId = null;const tsDrop = SBE.tsDrop;SBE.tsDrop = null;sbeSrcDropHover(null, false);@@ -11211,6 +12480,7 @@ async function edPoolDragEnd(ev) {if (d.toSrc) { edPoolPreview(d.index); return; }if (tsDrop) { await edPoolSound(d.index, tsDrop.tid, tsDrop.at); return; }if (at === null || at === undefined) return; // dropped in open space+ if (overwriteId) { await edPoolAdd(d.index, at, overwriteId); return; }await edPoolAdd(d.index, at);}@@ -11231,11 +12501,41 @@ function edAddSlug() {kind: 'slug', title: 'black', duration_s: secs,}, at));if (!ok) return;- sbeSave(true);+ // FILM-29: same as edPoolAdd — sbeMutate already queued the crash backup.+ // No extra silent write to edit.json.phosToast(secs.toFixed(1) + 's of black at ' + sbeFmtTime(at) + '.',{ kind: 'success', duration: 3500 });}+// ---------------------------------------------------------------------------+// OFFLINE MEDIA — FILM-15. A moved or trashed file, named rather than found+// out about from a black preview and a shorter, out-of-sync export.+// ---------------------------------------------------------------------------+// `SBE.offline` is a list of clip ids (see `_sbe_payload`) — a stat, not an+// ffprobe, so it is cheap enough for every read. A file that exists but will+// not decode reaches the assembler's own check instead, which pads it with+// black rather than shortening the film (`_sb_timeline_segments`).+function sbeClipOffline(c) {+ if (!c || !c.path) return false;+ const off = SBE.offline || [];+ return off.indexOf(String(c.id)) >= 0 || off.indexOf(String(c.path)) >= 0;+}++function sbePaintOffline() {+ const bar = sbeEl('sbeOffline');+ if (!bar) return;+ const ids = SBE.offline || [];+ bar.hidden = !ids.length;+ if (!ids.length) return;+ const names = (SBE.clips || [])+ .filter(c => sbeClipOffline(c))+ .map(c => sbeNiceName(c.title || String(c.path || '').split('/').pop()));+ sbeEl('sbeOfflineText').textContent =+ ids.length + (ids.length === 1 ? ' clip is' : ' clips are') ++ ' offline' + (names.length ? ' — ' + names.slice(0, 4).join(', ') ++ (names.length > 4 ? ', …' : '') : '') + '.';+}+// ---------------------------------------------------------------------------// RELINK — draft → delivery// ---------------------------------------------------------------------------@@ -11299,7 +12599,16 @@ function sbeRetakeKeep(id, to) {sbePaintRelink();}async function sbeRetakeUse(id, to) {- if (SBE.dirty && !SBE.conflict && !(await sbeSave(true))) {+ // FILM-23: see sbeRestoreVersion — a conflict must refuse outright, not+ // silently skip the save and swap the take in over an arrangement the+ // server has never seen.+ if (SBE.conflict) {+ phosToast('This film was changed in another tab — resolve that first; ' ++ 'the swap works on the saved file.',+ { kind: 'danger', duration: 8000 });+ return;+ }+ if (SBE.dirty && !(await sbeSave(true))) {phosToast('Your arrangement could not be saved, and the swap works on the saved file — fix the save first.',{ kind: 'danger', duration: 8000 });return;@@ -11411,11 +12720,21 @@ async function sbeRefreshOffers() {async function sbeRelink() {const btn = sbeEl('sbeRelinkBtn');if (btn) btn.disabled = true;+ // FILM-23: see sbeRestoreVersion — a conflict must refuse outright, not+ // silently skip the save and relink over an arrangement the server has+ // never seen.+ if (SBE.conflict) {+ if (btn) btn.disabled = false;+ phosToast('This film was changed in another tab — resolve that first; ' ++ 'relinking works on the saved file.',+ { kind: 'danger', duration: 8000 });+ return;+ }// Save first: the server rewrites the file on disk, and an unsaved// arrangement would be rewritten out from under itself. CHECKED — a save// that did not land means the server is holding an older cut, and relinking// that one writes it back over what is on screen.- if (SBE.dirty && !SBE.conflict && !(await sbeSave(true))) {+ if (SBE.dirty && !(await sbeSave(true))) {if (btn) btn.disabled = false;phosToast('Your arrangement could not be saved, and relinking works on ' +'the saved file — fix the save first.',@@ -11523,7 +12842,7 @@ function sbeUnmuteFromRefusal() {async function sbeEnter(c, at) {const v = sbeEl('sbeVideo');const img = sbeEl('sbeStill');- sbeApplyPreviewFilter(sbeBright(c), sbeFraming(c));+ sbeApplyPreviewGrade(c, sbeFraming(c));const kind = sbeKind(c);if (kind === 'video') {if (img) img.classList.remove('is-on');@@ -11580,7 +12899,7 @@ async function sbePlay() {try { await v.play(); } catch (e2) {}}}- sbeApplyPreviewFilter(sbeBright(c), sbeFraming(c));+ sbeApplyPreviewGrade(c, sbeFraming(c));} else {await sbeEnter(c);}@@ -11630,8 +12949,35 @@ async function sbeFrame() {sbePaintTrack();}} else if (c) {- SBE.playhead = sbeNum(c.film_start) + Math.max(0, v.currentTime - sbeNum(c.start)) / sbeSpeed(c);- if (v.currentTime >= sbeNum(c.end) - 1e-3 || v.ended) {+ // FILM-04: IN REPLACE MODE THE SONG DRIVES THE PLAYHEAD; the picture+ // chases it with `playbackRate` rather than a seek. A seek is what gave+ // the preview its 6-frame tolerance (SBE_STRIP_SLIP's sibling, the 0.25s+ // in sbeMusicSync) — larger than most of the owner's real corrections+ // (0.15 to 0.39s), so the tool could not show the drift it exists to fix.+ const songT = sbeMusicMaster() ? sbeSongPlayhead() : null;+ if (songT !== null) {+ SBE.playhead = songT;+ const wantV = sbeNum(c.start) + Math.max(0, songT - sbeNum(c.film_start)) * sbeSpeed(c);+ const drift = wantV - v.currentTime;+ const oneFrame = 1 / sbeFps();+ try {+ if (Math.abs(drift) >= 0.5) {+ // Bigger than a rate ramp should ever have to close (a scrub, a+ // stall, the clip that just loaded) — a seek is honest here.+ v.currentTime = wantV;+ v.playbackRate = sbeSpeed(c);+ } else if (Math.abs(drift) > oneFrame) {+ v.playbackRate = sbeSpeed(c) * (drift > 0 ? 1.02 : 0.98);+ } else {+ v.playbackRate = sbeSpeed(c);+ }+ } catch (e) {}+ } else {+ SBE.playhead = sbeNum(c.film_start) + Math.max(0, v.currentTime - sbeNum(c.start)) / sbeSpeed(c);+ }+ const cutNow = (songT !== null) ? SBE.playhead >= sbeNum(c.film_end) - 1e-3+ : (v.currentTime >= sbeNum(c.end) - 1e-3 || v.ended);+ if (cutNow) {const next = SBE.clips[SBE.clips.indexOf(c) + 1];if (!next) { sbeStop(); sbePaintHead(); return; }SBE.playing = false; // hold the loop across the cut@@ -11703,6 +13049,32 @@ function sbeMusicAt(t) {if (w.film_end !== null && t >= w.film_end) return null; // out alreadyreturn Math.max(0, w.head + (t - w.film_start));}++// FILM-04: THE SONG IS THE MASTER CLOCK in Replace mode. Every picture on a+// music video is conditioned on a fixed stretch of the song+// (`audio_start_time`), so the song's own position is the ground truth for+// where every clip's mouth SHOULD be — and it is the one clock in this page+// a browser does not stall, seek or decode-jitter the way a <video> can.+// Only while there is a song actually playing under everything: a board+// with no soundtrack, or the "Under" mode where clips keep their own sound,+// has no such ground truth and the picture stays the clock it always was.+function sbeMusicMaster() {+ return !!(SBE.audio && SBE.audio.mode === 'replace' && SBE.musicOk+ && SBE.musicEl && !SBE.musicEl.paused);+}+// The inverse of `sbeMusicAt`: the film second the song's own `currentTime`+// implies. Null before the song's window starts or after it ends, the same+// two cases `sbeMusicAt` refuses — those are the only moments the picture+// is still the better clock (a black head, a bed that has run out).+function sbeSongPlayhead() {+ const a = SBE.musicEl;+ if (!a) return null;+ const w = sbeMusicWindow(SBE.audio, SBE.peaks ? SBE.peaks.duration : 0);+ const t = w.film_start + (a.currentTime - w.head);+ if (t < w.film_start - 1e-3) return null;+ if (w.film_end !== null && t >= w.film_end) return null;+ return Math.max(0, t);+}function sbeMusicPlay() {const a = SBE.musicEl;if (!a || !SBE.musicOk) return;@@ -12148,6 +13520,59 @@ function sbePlace(i) {}}+// FILM-08: the newest unplaced take rendered for the SAME slot a clip sits+// in — the thing "Replace with…" on the clip bar / context menu offers+// without a picker. Last match wins: `unplaced` lists in the order the+// server built it (render order), so the last one sharing this slot is the+// most recent alternate.+function sbeAltForClip(c) {+ if (!c) return null;+ let best = null;+ for (const u of (SBE.unplaced || [])) {+ if (u.slot && u.slot.film_start !== undefined+ && Math.abs(sbeNum(u.slot.film_start) - sbeNum(c.film_start)) < 0.05) {+ best = u;+ }+ }+ return best;+}++function sbeReplaceSelWithAlt() {+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) return;+ const u = sbeAltForClip(c);+ if (!u) { phosToast('No rendered alternate for this shot is waiting.', {}); return; }+ const item = { path: u.path, proxy: u.proxy || null, duration_s: u.duration_s, n: u.n, title: u.title };+ const ok = sbeMutate(cs => sbeReplaceClip(cs, c.id, item));+ if (ok) {+ SBE.unplaced = (SBE.unplaced || []).filter(x => x !== u);+ phosToast('Replaced with the rendered alternate. Same cut, same timings.',+ { kind: 'success', duration: 5000 });+ sbePaint();+ }+}++// FILM-08: swap an unplaced alternate into the clip already sitting in the+// hole it was rendered for. Same slot, same trim (clamped), adjustments,+// frame and transitions — only the source changes. Unlike Place, this never+// ripples anything: the film stays exactly as long as it was.+function sbeSwapIn(i) {+ const u = (SBE.unplaced || [])[i];+ if (!u || !u.slot || u.slot.film_start === undefined) return;+ const target = (SBE.clips || []).find(+ x => Math.abs(sbeNum(x.film_start) - sbeNum(u.slot.film_start)) < 0.05);+ if (!target) { phosToast('That slot is empty now — use Place instead.', {}); return; }+ const item = { path: u.path, proxy: u.proxy || null,+ duration_s: u.duration_s, n: u.n, title: u.title };+ const ok = sbeMutate(cs => sbeReplaceClip(cs, target.id, item));+ if (ok) {+ SBE.unplaced = SBE.unplaced.filter((_, k) => k !== i);+ phosToast('Swapped in for shot ' + (target.n !== undefined && target.n !== null ? target.n : '')+ + '. Same cut, same timings.', { kind: 'success', duration: 5000 });+ sbePaint();+ }+}+// ---------------------------------------------------------------------------// PREPARE / AUTO / GENERATE / RENDER// ---------------------------------------------------------------------------@@ -12191,6 +13616,185 @@ async function sbeAuto() {phosToast('Re-cut · ' + (r.edit.clips || []).length + ' clips.', { kind: 'success' });}+// EDITOR-13 (Codex 4.17.0): THE ARRANGEMENT AN ANALYSIS MEASURES. Match+// colour and Auto-align used to read the last SAVE, then apply to the clip on+// screen with the same id — a replaced or trimmed clip got a correction+// measured on its old file or window, and a clip added since was never+// measured. The request now carries what is on screen (the save's own+// serialisation), and each clip's fingerprint is kept so a proposal only+// lands on the clip it was measured on. `place`: where it sits on the film+// matters too (Auto-align reads the song under it; Match colour does not).+function sbeAnalysisFp(c, place) {+ if (!c) return '';+ const f = [String(c.path || ''), sbeRound(c.start), sbeRound(c.end), sbeSpeed(c)];+ if (place) f.push(sbeRound(c.film_start), sbeRound(c.film_end));+ return JSON.stringify(f);+}+function sbeAnalysisSnapshot(fd, place) {+ const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,+ overlays: SBE.overlays, tracks: SBE.tracks,+ transitions: SBE.transitions, markers: SBE.markers,+ expect: null });+ fd.set('edit', JSON.stringify(body.edit));+ const fp = {};+ for (const c of (SBE.clips || [])) fp[String(c.id)] = sbeAnalysisFp(c, place);+ return fp;+}+function sbeAnalysisFresh(id, fp, place) {+ const c = sbeById(SBE.clips, id);+ return !!c && fp[String(id)] !== undefined && sbeAnalysisFp(c, place) === fp[String(id)];+}++// FILM-05: "AUTO-ALIGN LIP-SYNC". A few seconds of CPU per shot, no render —+// the scorer's own best-lag search, run against the song for every singing+// shot on the film, and proposed rather than applied: one toast names how+// many are off by more than a frame, and Accept applies every proposal as+// ONE undo step (`sbeMutateEach`), same shape as every batch verb here.+async function sbeAutoAlign() {+ if (!SBE.open || !SBE.id) return;+ const btn = sbeEl('sbeAlignBtn');+ if (btn) btn.disabled = true;+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ // EDITOR-13: MEASURE WHAT IS ON SCREEN, and remember exactly what that+ // was, so a proposal can only land on the clip it was measured on.+ const fp = sbeAnalysisSnapshot(fd, true);+ let r;+ try { r = await (await fetch('/storyboard/edit/auto-align', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (btn) btn.disabled = false;+ if (!r || !r.ok) { phosToast((r && r.error) || 'Auto-align could not run.', { kind: 'danger' }); return; }+ const props = (r.proposals || []).filter(p => sbeAnalysisFresh(p.id, fp, true));+ // EDITOR-9: A SHOT THAT COULD NOT BE MEASURED IS NOT A SHOT IN SYNC. No+ // face held, or too little voice or mouth motion to compare — said, and+ // never folded into "already matches".+ const skipped = (r.skipped || []).length;+ const unmeasured = skipped+ ? (skipped + (skipped === 1 ? ' singing shot' : ' singing shots') + ' could not be ' ++ 'measured (no face held, or too little voice to compare) and ' ++ (skipped === 1 ? 'was' : 'were') + ' left alone.')+ : '';+ if (!props.length) {+ if (skipped) {+ phosToast(unmeasured + (sbeNum(r.checked, 0)+ ? ' The rest already match the song within a frame.' : ''),+ { icon: 'ph-info', duration: 8000 });+ } else if (!sbeNum(r.checked, 0)) {+ phosToast('There are no singing (lip-sync) shots on this film to align.',+ { duration: 5000 });+ } else {+ phosToast('Every singing shot already matches the song within a frame.',+ { kind: 'success', duration: 5000 });+ }+ return;+ }+ const deltas = {};+ const ids = [];+ for (const p of props) { deltas[p.id] = sbeNum(p.delta_sec); ids.push(p.id); }+ const el = phosToast(props.length + (props.length === 1 ? ' shot is' : ' shots are')+ + ' off the song by more than a frame.'+ + (unmeasured ? ' ' + unmeasured : ''),+ { icon: 'ph-info', duration: 20000 });+ if (!el) return;+ const a = document.createElement('a');+ a.href = '#';+ a.className = 'phos-toast-action';+ a.textContent = 'Accept all (' + ids.length + ')';+ a.onclick = (ev) => {+ ev.preventDefault();+ el.remove();+ // A shot trimmed, slipped, moved or replaced since it was measured is+ // not the shot the number is about — it is left alone, and said.+ const live = ids.filter(id => sbeAnalysisFresh(id, fp, true));+ const stale = ids.length - live.length;+ if (!live.length) {+ phosToast('Those shots changed after they were measured — run Auto-align again.',+ { duration: 6000 });+ return;+ }+ const ok = sbeMutateEach(live, (cs, id) => sbeSlip(cs, id, deltas[id]));+ if (ok) {+ phosToast('Snapped ' + live.length + ' shot(s) to the song. One Undo puts them all back.'+ + (stale ? ' ' + stale + ' changed after they were measured and were left alone.' : ''),+ { kind: 'success', duration: 6000 });+ }+ };+ el.appendChild(a);+}++// FILM-14: "Match colour across the film". Proposals at full (100%)+// strength are fetched once on open; the slider only SCALES them (cheap,+// no round trip per drag) until Apply writes the scaled values as one+// undo step. The hero is the one selected clip if exactly one is+// selected when the dialog opens, else the server's own median.+let _sbeMatchProposals = [];+let _sbeMatchFp = {};+async function sbeMatchColourOpen() {+ if (!SBE.open || !SBE.id) return;+ sbeEl('sbeMatchModal').classList.add('show');+ sbeEl('sbeMatchGo').disabled = true;+ sbeEl('sbeMatchStrength').value = 100;+ sbeEl('sbeMatchStrengthHint').textContent = '100%';+ sbeEl('sbeMatchWhere').textContent = 'Reading one frame from every clip…';+ const heroId = (sbeSelCount() === 1) ? SBE.sel : '';+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ if (heroId) fd.set('ref', heroId);+ _sbeMatchFp = sbeAnalysisSnapshot(fd, false);+ let r;+ try { r = await (await fetch('/storyboard/edit/match-colour', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ sbeEl('sbeMatchWhere').textContent = (r && r.error) || 'Could not read the film.';+ return;+ }+ _sbeMatchProposals = (r.proposals || []).filter(p => sbeAnalysisFresh(p.id, _sbeMatchFp, false));+ const hero = heroId ? sbeNiceName((sbeById(SBE.clips, heroId) || {}).title || 'this clip')+ : "the film's median";+ sbeEl('sbeMatchWhere').textContent = _sbeMatchProposals.length+ ? (_sbeMatchProposals.length + ' of ' + (r.proposals || []).length + (heroId ? '' : ' other')+ + ' clip(s) differ from ' + hero + ' by more than a touch.')+ : ('Every clip already matches ' + hero + '.');+ sbeEl('sbeMatchGo').disabled = !_sbeMatchProposals.length;+}+function sbeMatchClose() { sbeEl('sbeMatchModal').classList.remove('show'); }+function sbeMatchStrengthPreview(v) {+ sbeEl('sbeMatchStrengthHint').textContent = Math.round(sbeNum(v)) + '%';+}+function sbeMatchApply() {+ if (!_sbeMatchProposals.length) return;+ const k = Math.max(0, Math.min(100, sbeNum(sbeEl('sbeMatchStrength').value, 100))) / 100;+ // EDITOR-13: only onto the picture that was sampled.+ const ids = _sbeMatchProposals.map(p => p.id)+ .filter(id => sbeAnalysisFresh(id, _sbeMatchFp, false));+ const stale = _sbeMatchProposals.length - ids.length;+ if (!ids.length) {+ sbeMatchClose();+ phosToast('Those clips changed after they were sampled — open Match colour again.',+ { duration: 6000 });+ return;+ }+ const byId = {};+ for (const p of _sbeMatchProposals) byId[p.id] = p;+ const ok = sbeMutateEach(ids, (cs, id) => {+ const p = byId[id];+ let res = { clips: cs, ok: true };+ for (const field of ['exposure', 'temp', 'tint']) {+ res = sbeSetGrade(res.clips, id, field,+ sbeGrade(sbeById(res.clips, id))[field] + sbeNum(p[field], 0) * k);+ if (!res.ok) return res;+ }+ return res;+ });+ sbeMatchClose();+ if (ok) {+ phosToast('Colour matched on ' + ids.length + ' clip(s) at ' + Math.round(k * 100)+ + '%. One Undo puts them all back.'+ + (stale ? ' ' + stale + ' changed after they were sampled and were left alone.' : ''),+ { kind: 'success', duration: 6000 });+ }+}+let _sbeGenAt = 0;// THE SHOT A CLIP CAME FROM, from the pool the payload already carries.// By path — a clip on the timeline is a file, and the pool row for that@@ -12206,20 +13810,54 @@ function sbeShotForClip(c) {// the new take comes back offered against THIS clip rather than as a loose// shot under the timeline.let _sbeRetakeOf = '';+// FILM-35: THE CLIP'S OWN PATH, sent alongside its id. The server used to+// resolve `retake_of` by loading the SAVED edit.json and looking the clip id+// up in it — so a clip split, duplicated or added since the last manual Save+// (the normal state of a timeline, under the save model) did not exist there+// yet, and the retake refused with "that clip is not on this timeline any+// more" while it sat selected on screen. The path is everything the server+// actually needs (it matches the source shot by `draft_output`/+// `final_output`), and the client already has it without asking anyone.+let _sbeRetakePath = '';function sbeRetakeSel() {const c = sbeById(SBE.clips, SBE.sel);const shot = c ? sbeShotForClip(c) : null;if (!c || !shot) { phosToast('Only a clip that came from a shot can be retaken.', {}); return; }const len = Math.max(0.5, sbeNum(shot.duration_s, 0) || (sbeLen(c) * sbeSpeed(c) + 1));- sbeGenOpen(sbeNum(c.film_start), len, { retakeOf: c.id, prompt: shot.prompt || '',- name: shot.title || String(c.path).split('/').pop() });+ sbeGenOpen(sbeNum(c.film_start), len, { retakeOf: c.id, retakePath: c.path,+ prompt: shot.prompt || '',+ name: shot.title || String(c.path).split('/').pop(),+ summary: sbeRetakeSummary(shot) });+}++// FILM-53: WHAT WILL ACTUALLY RENDER, before the person queues it. The+// dialog used to say only "LENGTH 7.7" and Draft/Delivery — nothing about+// which mode, which engine, which stretch of the song a singing shot is+// conditioned on, or the cost. "LTX a2v · song 0:09-0:16.6 · new seed ·+// ~14 min", built from the same fields the render itself reads+// (mode/audio_start_time) and the same per-shot cost model the board's own+// estimate uses (est_min, from `shot_render_secs` on the server).+function sbeRetakeSummary(shot) {+ const mode = String(shot.mode || '').toLowerCase();+ const bits = [mode === 'a2v' ? 'LTX a2v' : 'LTX'];+ if (mode === 'a2v' && shot.audio) {+ const t0 = sbeNum(shot.audio_start_time, 0);+ const t1 = t0 + sbeNum(shot.duration_s, 0);+ bits.push('song ' + sbeFmtTime(t0) + '-' + sbeFmtTime(t1));+ }+ bits.push('new seed');+ const est = (shot.est_min || {}).draft;+ if (est) bits.push('~' + (est < 1 ? '<1' : Math.round(est)) + ' min (draft)');+ return bits.join(' · ');}function sbeGenOpen(filmStart, duration, opts) {_sbeGenAt = sbeNum(filmStart);_sbeRetakeOf = (opts && opts.retakeOf) || '';+ _sbeRetakePath = (opts && opts.retakePath) || '';sbeEl('sbeGenWhere').textContent = _sbeRetakeOf- ? ('A new take of ' + (opts.name || 'this clip') + ': the same shot and character, a new ' ++ ? (((opts && opts.summary) ? opts.summary + ' — ' : '')+ + 'A new take of ' + (opts.name || 'this clip') + ': the same shot and character, a new ' +'seed, the prompt below to edit. When it lands, a line above the timeline offers it ' +'against this clip — Use it, or keep the old one.'): ('Nothing plays between ' + sbeFmtTime(filmStart) + ' and ' +@@ -12256,6 +13894,7 @@ async function sbeGenSubmit() {fd.set('duration', String(sbeNum(sbeEl('sbeGenDuration').value, 5)));fd.set('film_start', String(_sbeGenAt));if (_sbeRetakeOf) fd.set('retake_of', _sbeRetakeOf);+ if (_sbeRetakePath) fd.set('retake_path', _sbeRetakePath);const on = document.querySelector('#sbeGenPass .pill-btn.active');fd.set('pass', (on && on.dataset.pass) || 'draft');let r;@@ -12288,14 +13927,38 @@ function sbeDeliverGet() {try { d = JSON.parse(localStorage.getItem('phos_deliver') || '{}') || {}; } catch (e) { d = {}; }return { format: SBE_DELIVER_FORMATS.indexOf(d.format) >= 0 ? d.format : 'h264',size: SBE_DELIVER_SIZES.indexOf(d.size) >= 0 ? d.size : 'native',- finish: SBE_DELIVER_FINISH.indexOf(d.finish) >= 0 ? d.finish : 'none' };+ finish: SBE_DELIVER_FINISH.indexOf(d.finish) >= 0 ? d.finish : 'none',+ // FILM-28: off by default — a mix graded by ear is not something+ // a render should quietly retarget without being asked.+ loudnorm: !!d.loudnorm };+}+// FILM-14: unlike Deliver's format/size/finish (a client preference posted+// with each render), the Film look rides IN THE DOCUMENT — `edit.settings`,+// which `sbeSaveBody` already carries through untouched — so it reaches the+// film render AND the NLE export (both read `edit.json` off disk) and+// stays true for whoever opens this __SEQ__ next.+function sbeSetFilmLook(value) {+ if (!SBE.open || !SBE.id) return;+ SBE.edit = SBE.edit || {};+ SBE.edit.settings = Object.assign({}, SBE.edit.settings || {}, { film_look: value || 'none' });+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaintChrome();+ sbeQueueSave();}+function sbeDeliverPick(key, value) {const d = sbeDeliverGet();d[key] = value;try { localStorage.setItem('phos_deliver', JSON.stringify(d)); } catch (e) {}sbeDeliverPaint();}+function sbeDeliverToggleLoudnorm(on) {+ const d = sbeDeliverGet();+ d.loudnorm = !!on;+ try { localStorage.setItem('phos_deliver', JSON.stringify(d)); } catch (e) {}+ sbeDeliverPaint();+}function sbeDeliverPaint() {const d = sbeDeliverGet();document.querySelectorAll('#sbeDeliverFormat .pill-btn').forEach(b =>@@ -12304,15 +13967,19 @@ function sbeDeliverPaint() {b.classList.toggle('active', b.dataset.size === d.size));document.querySelectorAll('#sbeDeliverFinish .pill-btn').forEach(b =>b.classList.toggle('active', b.dataset.finish === d.finish));+ const lnBox = sbeEl('sbeDeliverLoudnorm');+ if (lnBox && lnBox.checked !== d.loudnorm) lnBox.checked = d.loudnorm;const btn = sbeEl('sbeRenderBtn');if (btn && !SBE.rendering) {const short = ({ h264: '', hevc: 'HEVC', prores: 'ProRes' })[d.format];const size = d.size === 'native' ? '' : (d.size === '2160p' ? '4K' : '1080p');const fin = d.finish === 'none' ? '' : (d.finish === 'heavy_grain' ? 'heavy grain' : 'grain');- const tag = [short, size, fin].filter(Boolean).join(' ');+ const ln = d.loudnorm ? '-14 LUFS' : '';+ const tag = [short, size, fin, ln].filter(Boolean).join(' ');btn.textContent = tag ? ('Render · ' + tag) : 'Render';btn.title = 'Assemble the film as ' + ({ h264: 'H.264', hevc: 'HEVC', prores: 'ProRes 422 HQ' })[d.format]+ (d.size === 'native' ? ', as cut' : (d.size === '2160p' ? ' at 4K' : ' at 1080p'))+ + (d.loudnorm ? ', normalized to -14 LUFS' : '')+ '. Change it under the arrow.';}}@@ -12328,17 +13995,36 @@ async function sbeRenderFilm() {'first.', { kind: 'danger', duration: 8000 });return;}- const holes = sbeHoles(SBE.clips);- if (holes.length && !confirm(- holes.length + ' hole(s) totalling ' +- holes.reduce((a, g) => a + g.duration, 0).toFixed(2) + 's are still empty.\n\n' +- 'The assembler CONCATENATES — a hole closes and everything after it slides ' +- 'earlier, off the beat it was cut to.\n\nRender anyway?')) return;+ // FILM-15: OFFLINE MEDIA BLOCKS THE RENDER, WITH THE LIST. Unlike a hole+ // (FILM-27, below) an offline clip is not something the assembler can make+ // honest on its own — it CAN pad the slot with black, but a film that+ // quietly went silent-black where a real shot used to be is the exact+ // "Rendered N clips" surprise this finding started from. Refuse here,+ // named, before spending an encode on it.+ if ((SBE.offline || []).length) {+ sbePaintOffline();+ const names = (SBE.clips || []).filter(c => sbeClipOffline(c))+ .map(c => sbeNiceName(c.title || String(c.path || '').split('/').pop()));+ phosToast((SBE.offline.length === 1 ? '1 clip is' : SBE.offline.length + ' clips are') ++ ' offline' + (names.length ? ' — ' + names.slice(0, 4).join(', ') ++ (names.length > 4 ? ', …' : '') : '') ++ '. Relink or replace them before rendering.',+ { kind: 'danger', duration: 9000 });+ return;+ }+ // FILM-27: HOLES ARE NO LONGER DESTRUCTIVE. The assembler now pads every+ // gap with black at its exact length instead of closing it and sliding+ // everything after it — so the browser's own blocking "are you sure"+ // dialog was the wrong weight for "this will show some black", in the+ // one styled surface this app owns least. It warns in-app instead, and+ // does not block: "Fill" opens Generate a shot on the first hole, "Close+ // them" ripples every hole shut for whoever would rather have that.+ sbeNoticeHoles(sbeHoles(SBE.clips));const btn = sbeEl('sbeRenderBtn');const prev = btn.textContent;SBE.rendering = true;btn.disabled = true;- btn.textContent = 'Assembling…';+ btn.textContent = 'Starting…';sbeEl('sbeRenderNote').textContent ='One ffmpeg pass over ' + SBE.clips.length + ' clips. This takes as long as an encode takes.';const fd = new URLSearchParams();@@ -12349,34 +14035,186 @@ async function sbeRenderFilm() {fd.set('format', dl.format);fd.set('size', dl.size);fd.set('finish', dl.finish);+ if (dl.loudnorm) fd.set('loudnorm', 'on');+ // FILM-28: A JOB, NOT A BLOCKED REQUEST. The route used to hold the whole+ // fetch open until ffmpeg finished — no progress, and closing the tab (or+ // just impatience) had no way to say "stop". `edit/render/start` answers+ // with a job id the moment the render is queued; sbeRenderPoll below is+ // what actually watches it land.+ let started;+ try {+ started = await (await fetch('/storyboard/edit/render/start',+ { method: 'POST', body: fd })).json();+ } catch (e) { started = { ok: false, error: String(e) }; }+ if (!started.ok) {+ SBE.rendering = false;+ btn.disabled = false;+ btn.textContent = prev;+ sbeEl('sbeRenderNote').textContent = '';+ phosToast(started.error || 'The render could not be started.',+ { kind: 'danger', duration: 8000 });+ return;+ }+ SBE.renderJob = started.job;+ btn.textContent = 'Assembling…';+ // EDITOR-12: THE FILM THIS RENDER IS OF, kept with the job — by the time+ // it lands the Editor may be showing another film.+ sbeRenderPoll(started.job, btn, prev, SBE.id, SBE.title || '');+}++// The job started above, watched to a finish. A fresh fetch every 1.2s+// rather than one held-open connection — the same reasoning `sbeTick`+// already uses for the save watchdog: a dropped poll costs nothing and+// re-arms on its own, where a held-open request either times out silently+// or, on some proxies, never notices the server went away at all.+async function sbeRenderPoll(job, btn, prev, boardId, boardTitle) {let r;- try { r = await (await fetch('/storyboard/edit/render', { method: 'POST', body: fd })).json(); }+ try { r = await (await fetch('/storyboard/edit/render/status?job=' ++ encodeURIComponent(job))).json(); }catch (e) { r = { ok: false, error: String(e) }; }- SBE.rendering = false;- btn.disabled = false;- btn.textContent = prev;+ if (SBE.renderJob !== job) return; // superseded — a newer poll owns the UI nowif (!r.ok) {+ sbeRenderSettle(btn, prev);+ sbeEl('sbeRenderNote').textContent = '';+ phosToast(r.error || 'Lost track of the render.', { kind: 'danger', duration: 8000 });+ return;+ }+ if (r.state === 'running') {+ sbeEl('sbeRenderNote').innerHTML =+ 'Rendering — ' + Math.round(sbeNum(r.elapsed_sec)) + 's so far. '+ + '<a href="#" class="phos-toast-action" onclick="sbeRenderCancel();return false;">Cancel</a>';+ SBE.renderPollTimer = setTimeout(() => sbeRenderPoll(job, btn, prev, boardId, boardTitle), 1200);+ return;+ }+ sbeRenderSettle(btn, prev);+ if (r.state === 'canceled') {+ sbeEl('sbeRenderNote').textContent = '';+ phosToast('Render canceled.', { duration: 4000 });+ return;+ }+ if (r.state !== 'done' || !r.result || !r.result.ok) {sbeEl('sbeRenderNote').textContent = '';- phosToast(r.error || 'The film could not be assembled.', { kind: 'danger', duration: 8000 });+ phosToast((r.result && r.result.error) || r.error ||+ 'The film could not be assembled.', { kind: 'danger', duration: 8000 });return;}- sbeEl('sbeRenderNote').textContent = (r.gaps_note || '') +- ' Wrote ' + Math.round(sbeNum(r.duration)) + 's to ' + (r.path || '').split('/').pop();- phosToast('Rendered ' + r.clips + ' clips · ' + Math.round(sbeNum(r.duration)) + 's' ++ sbeRenderFinish(r.result, boardId, boardTitle);+}++function sbeRenderSettle(btn, prev) {+ SBE.rendering = false;+ SBE.renderJob = '';+ if (SBE.renderPollTimer) { clearTimeout(SBE.renderPollTimer); SBE.renderPollTimer = null; }+ btn.disabled = false;+ btn.textContent = prev;+}++function sbeRenderCancel() {+ const job = SBE.renderJob;+ if (!job) return;+ sbeEl('sbeRenderNote').textContent = 'Canceling…';+ const fd = new URLSearchParams();+ fd.set('job', job);+ fetch('/storyboard/edit/render/cancel', { method: 'POST', body: fd }).catch(() => {});+}++// The success tail — unchanged from before the job split, just no longer+// inline in sbeRenderFilm: it is reached from sbeRenderPoll the moment the+// job's own status answers "done".+function sbeRenderFinish(r, boardId, boardTitle) {+ // EDITOR-12 (Codex 4.17.0): EVERYTHING HERE IS ABOUT THE FILM THAT WAS+ // RENDERED, not the one open now. It used to read SBE.id at completion, so+ // switching films mid-render gave film B film A's "Last render" chip, and+ // Open / Show in Finder looked for A's file inside B.+ const id = boardId || SBE.id;+ const here = (id === SBE.id);+ if (here) {+ sbeEl('sbeRenderNote').textContent = (r.gaps_note || '') ++ ' Wrote ' + Math.round(sbeNum(r.duration)) + 's to ' + (r.path || '').split('/').pop();+ }+ // FILM-24: THE RENDER STAYS ON THE TIMELINE. This used to end by switching+ // to Storyboard and opening the Film screen — which, combined with the+ // tab-entry race (FILM-02), sometimes landed on a DIFFERENT film's Film+ // screen while a "Rendered N clips" toast sat over it. Rendering to check+ // a cut is the normal loop, not a reason to leave the cut: the film is+ // ready where the user already is, one click from either place they might+ // want it.+ const focus = (r.path || '').split('/').pop();+ SBE.lastRenders = SBE.lastRenders || {};+ SBE.lastRenders[id] = { focus: focus, r: r };+ if (here) sbePaintRenderChip(id, focus, r);+ const toastEl = phosToast((here ? 'Film ready' : '"' + (boardTitle || 'The other film') + '" is ready')+ + ' · ' + Math.round(sbeNum(r.duration)) + 's' +(r.deliver && r.deliver.label ? ' · ' + r.deliver.label : '') +(r.deliver && r.deliver.format === 'prores'? ' — a ProRes .mov: it opens in an NLE or QuickTime, not in this preview' : '') +(r.gaps_note ? ' — ' + r.gaps_note : ''),{ kind: 'success', duration: (r.gaps_note || (r.deliver && r.deliver.format === 'prores')) ? 11000 : 6000 });- // The render ENDS ON THE FILM. Before this the timeline wrote an mp4 into- // mlx_outputs/storyboards/, printed one line of grey text under the button,- // and left the user looking at the timeline wondering where the film went.- // The Editor's document is not necessarily the storyboard's open board any- // more, so the board is opened before the film screen is asked for it.- const focus = (r.path || '').split('/').pop();+ if (toastEl) {+ const open = document.createElement('a');+ open.href = '#'; open.className = 'phos-toast-action'; open.textContent = 'Open';+ open.onclick = (ev) => { ev.preventDefault(); sbeOpenFilmScreen(id, focus); };+ const reveal = document.createElement('a');+ reveal.href = '#'; reveal.className = 'phos-toast-action'; reveal.textContent = 'Show in Finder';+ reveal.onclick = (ev) => { ev.preventDefault(); sbeRevealRender(id, focus); };+ toastEl.appendChild(open);+ toastEl.appendChild(reveal);+ }+}++// FILM-24's two actions, shared by the toast and the chip that outlives it.+// "Open" is exactly what the render used to do on its own: switch to+// Storyboard and land on this film's Film screen, focused on the file that+// just came out. Now it is something the user asks for instead of something+// that happens to them.+async function sbeOpenFilmScreen(id, focus) {if (typeof workflowSwitch === 'function') workflowSwitch('storyboard');- if (SBE.id !== SB.id && typeof sbOpen === 'function') await sbOpen(SBE.id);- sbFilmOpen({ focus: focus });+ if (id !== SB.id && typeof sbOpen === 'function') await sbOpen(id);+ if (typeof sbFilmOpen === 'function') sbFilmOpen({ focus: focus });+}++async function sbeRevealRender(id, focus) {+ const fd = new URLSearchParams();+ fd.set('id', id);+ if (focus) fd.set('name', focus);+ try { await fetch('/storyboard/reveal', { method: 'POST', body: fd }); }+ catch (e) {}+}++// THE LAST RENDER, next to the button that made it — so leaving the toast to+// vanish (or leaving the tab and coming back) does not cost the one thing+// most people actually want after a render: to look at it. Replaced by the+// next render; there is only ever one.+function sbePaintRenderChip(id, focus, r) {+ const chip = sbeEl('sbeRenderChip');+ if (!chip) return;+ chip.innerHTML = '';+ chip.hidden = false;+ if (chip.dataset) chip.dataset.board = String(id || '');+ const label = document.createElement('span');+ label.className = 'sbe-render-chip-label';+ label.textContent = 'Last render · ' + Math.round(sbeNum(r.duration)) + 's';+ chip.appendChild(label);+ const open = document.createElement('button');+ open.type = 'button'; open.textContent = 'Open';+ open.onclick = () => sbeOpenFilmScreen(id, focus);+ chip.appendChild(open);+ const reveal = document.createElement('button');+ reveal.type = 'button'; reveal.textContent = 'Show in Finder';+ reveal.onclick = () => sbeRevealRender(id, focus);+ chip.appendChild(reveal);+}++// EDITOR-12: THE CHIP BELONGS TO A FILM. Opening another film shows that+// film's last render (this session), or none — never the previous film's.+function sbeRenderChipFor(id) {+ const chip = sbeEl('sbeRenderChip');+ if (!chip) return;+ const last = (SBE.lastRenders || {})[id];+ if (last) { sbePaintRenderChip(id, last.focus, last.r); return; }+ chip.innerHTML = '';+ chip.hidden = true;+ if (chip.dataset) chip.dataset.board = '';}// ---------------------------------------------------------------------------@@ -12462,6 +14300,9 @@ async function sbeTick() {' seconds — press Save to store them');}}+ // FILM-57: the undo stack rides the same clock. Cheap when nothing has+ // changed since the last write — see sbePersistUndo's own comment.+ sbePersistUndo();const job = SBE.prepare || {};if (job.state === 'running') {try {@@ -12503,7 +14344,14 @@ async function sbeTick() {} finally { SBE.fixBusy = false; }}}- if (SBE.awaitingClip && !SBE.dirty && !SBE.drag && !SBE.saving) {+ // FILM-35: POLL WHILE DIRTY TOO. Under the save model, unsaved is the+ // NORMAL state of a timeline someone is actively cutting — so gating this+ // on `!SBE.dirty` meant the "new take landed" notice almost never fired+ // for the person it exists for. The quiet re-read just below is already+ // safe here: it never adopts the arrangement while dirty (sbeAdoptMeta),+ // it only refreshes facts around it — proxies, `unplaced`, relink offers —+ // which is exactly what this poll needs and nothing this poll could break.+ if (SBE.awaitingClip && !SBE.drag && !SBE.saving) {const before = (SBE.unplaced || []).length;await sbeLoad(true);if ((SBE.unplaced || []).length > before) {@@ -12518,7 +14366,36 @@ async function sbeTick() {document.addEventListener('keydown', (ev) => {if (!SBE.open || document.body.dataset.workflow !== 'editor') return;const t = ev.target;- if (t && /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName || '')) return;+ const inField = t && /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName || '');+ // FILM-36: A CHORD CANNOT BE A CHARACTER. ⌘S/⌘Z/⌘⇧Z/⌘E never insert+ // text into any field — the OS reserves them — so the field guard below+ // does not need to hide the app's OWN meaning for them, and hiding it was+ // the bug: dragging the Brightness or Zoom slider leaves focus on a range+ // input, and the next ⌘S either did nothing or (unblocked by+ // preventDefault) opened the browser's own "Save Page As". These four are+ // the ones the model doc and the render key already document, so they are+ // the ones let through — not every chord, which would also steal a text+ // field's own ⌘A/⌘Z (select-all, undo-my-typing) out from under it.+ if (inField && (ev.metaKey || ev.ctrlKey) && !ev.altKey) {+ if (ev.key === 's' || ev.key === 'S') { ev.preventDefault(); sbeSaveNow(); return; }+ if (ev.key === 'z' || ev.key === 'Z') {+ ev.preventDefault();+ ev.shiftKey ? sbeRedo() : sbeUndo();+ return;+ }+ if ((ev.key === 'e' || ev.key === 'E') && !ev.shiftKey) {+ ev.preventDefault(); sbeRenderFilm(); return;+ }+ }+ // SPACE ON A RANGE OR CHECKBOX is the one plain (unmodified) key worth+ // the same exemption: neither control uses it to enter TEXT, so play/pause+ // is not competing with anything the field itself would have done with it+ // — unlike a text input, where Space has to keep typing a space.+ if (inField && ev.key === ' '+ && (t.type === 'range' || t.type === 'checkbox')) {+ ev.preventDefault(); sbeTogglePlay(); return;+ }+ if (inField) return;if (document.querySelector('.modal-bg.show')) return;const step = 1 / sbeFps();if (ev.key === ' ') { ev.preventDefault(); sbeTogglePlay(); return; }@@ -12532,6 +14409,17 @@ document.addEventListener('keydown', (ev) => {sbeNudge(ev.key === 'ArrowLeft' ? -1 : 1, ev.shiftKey);return;}+ // FILM-03: SLIP, one frame (⇧ for ten) at a time. ⌥←/→ moves the whole clip+ // (nudge, above); ⌥, and ⌥. change which seconds of the TAKE play in the+ // same slot — the gesture a butt-joined lip-sync cut actually needs, since+ // there is no neighbour to nudge into. `.code` alongside `.key`: alt+ // remaps the character on some layouts, the same reason `` ` `` is read+ // both ways below.+ if (ev.altKey && (ev.key === ',' || ev.code === 'Comma' || ev.key === '.' || ev.code === 'Period')) {+ ev.preventDefault();+ sbeSlipNudge((ev.key === ',' || ev.code === 'Comma') ? -1 : 1, ev.shiftKey);+ return;+ }if (ev.key === 'ArrowLeft') { ev.preventDefault(); sbeStop(); sbeSeek(SBE.playhead - (ev.shiftKey ? step * 10 : step)); return; }if (ev.key === 'ArrowRight') { ev.preventDefault(); sbeStop(); sbeSeek(SBE.playhead + (ev.shiftKey ? step * 10 : step)); return; }// ↑ ↓ JUMP BETWEEN CUTS — where Premiere, Final Cut and Resolve all put@@ -12628,11 +14516,26 @@ document.addEventListener('keydown', (ev) => {ev.shiftKey ? sbeRedo() : sbeUndo();return;}- if ((ev.key === 'm' || ev.key === 'M') && !ev.metaKey && !ev.ctrlKey && !ev.altKey) {+ // FILM-58: M is MARKER, the letter every NLE this timeline aliases+ // itself to (Premiere, Final Cut, Resolve) already gives it — mute moved+ // to ⇧M, the same displacement `editor.ripple` already uses for its own+ // delete key.+ if (ev.key === 'm' && !ev.metaKey && !ev.ctrlKey && !ev.altKey) {+ ev.preventDefault();+ sbeMarkerAtPlayhead();+ return;+ }+ if (ev.key === 'M' && !ev.metaKey && !ev.ctrlKey && !ev.altKey) {ev.preventDefault();SBE.muted ? sbeUnmuteFromRefusal() : sbeSetMute(true);return;}+ if ((ev.metaKey || ev.ctrlKey) && !ev.shiftKey && !ev.altKey && (ev.key === 'c' || ev.key === 'C')) {+ ev.preventDefault(); sbeClipCopy(); return;+ }+ if ((ev.metaKey || ev.ctrlKey) && !ev.shiftKey && !ev.altKey && (ev.key === 'v' || ev.key === 'V')) {+ ev.preventDefault(); sbeClipPaste(); return;+ }if (ev.key === 'Escape') {ev.preventDefault();// The panel first: Escape means "close the thing on top", and closing the@@ -12793,6 +14696,11 @@ document.addEventListener('click', (ev) => {const el = document.getElementById(id);if (!el) continue;el.addEventListener('pointerdown', (ev) => {+ // FILM-58: a marker is a button on the ruler, not part of the scrub+ // surface — the same rule the sync flag and the fade handle already+ // follow on the track itself.+ const mk = ev.target.closest && ev.target.closest('.sbe-marker');+ if (mk && id === 'sbeRuler') { ev.preventDefault(); sbeSeek(sbeNum(mk.dataset.at)); return; }sbeStop();el.setPointerCapture && el.setPointerCapture(ev.pointerId);el.dataset.scrub = '1';@@ -12812,11 +14720,25 @@ document.addEventListener('click', (ev) => {el.addEventListener('pointerup', end);el.addEventListener('pointercancel', end);}- const tabs = document.getElementById('edPoolTabs');- if (tabs) {- tabs.addEventListener('click', (ev) => {- const b = ev.target.closest('.pill-btn');- if (b) edPoolSrc(b.dataset.src);+ const ruler = document.getElementById('sbeRuler');+ if (ruler) {+ ruler.addEventListener('contextmenu', (ev) => {+ const mk = ev.target.closest && ev.target.closest('.sbe-marker');+ if (!mk) return;+ ev.preventDefault();+ sbeMarkerMutate(ms => sbeMarkerRemove(ms, mk.dataset.marker));+ });+ // Double-click CYCLES THE KIND — note -> beat -> lyric -> note — the+ // gesture that needs no new keybinding and no menu for the two extra+ // colours "beat and lyric cues" asks for.+ ruler.addEventListener('dblclick', (ev) => {+ const mk = ev.target.closest && ev.target.closest('.sbe-marker');+ if (!mk) return;+ ev.preventDefault();+ const next = { note: 'beat', beat: 'lyric', lyric: 'note' };+ const cur = mk.classList.contains('is-beat') ? 'beat'+ : mk.classList.contains('is-lyric') ? 'lyric' : 'note';+ sbeMarkerMutate(ms => sbeMarkerSetKind(ms, mk.dataset.marker, next[cur]));});}const pass = document.getElementById('sbeGenPass');@@ -12839,7 +14761,12 @@ function workflowSwitch(name) {if (name === 'characters') name = 'manual';// Q4 tier uses the distilled A2V pipeline (no Q8 dev required).document.querySelectorAll('#workflowTabs button[data-workflow]')- .forEach(b => b.classList.toggle('active', b.dataset.workflow === name));+ .forEach(b => {+ const on = b.dataset.workflow === name;+ b.classList.toggle('active', on);+ // SYS-25: keep aria-selected in step with the visible .active state.+ b.setAttribute('aria-selected', on ? 'true' : 'false');+ });const manual = document.getElementById('genForm');const studio = document.getElementById('studioSection');const train = document.getElementById('trainSection');@@ -12981,7 +14908,7 @@ Object.assign(globalThis, {sbeSpeed, sbeSetSpeed, sbeSpeedCommit,sbeOvText, sbeHexColour, sbeRgba, sbeOvTextCommit, sbeOvTextPreview, edAddTitle,sbeSectionBands, sbeShotForClip, sbeRetakeSel, sbeRetakeDismissed,- sbeDeliverGet, sbeDeliverPick, sbeDeliverPaint, sbeDuplicate, sbeDuplicateSel,+ sbeDeliverGet, sbeDeliverPick, sbeDeliverPaint, sbeDeliverToggleLoudnorm, sbeDuplicate, sbeDuplicateSel,sbeFraming, sbeFramingIsNeutral, sbeSetFraming, sbeApplyPreviewFraming, sbeFramingPreview,sbeFramingCommit, sbeFramingReset,sbeRetakeKeep, sbeRetakeUse, sbeFaceFixSel, sbeFaceFixSwap,@@ -13004,7 +14931,7 @@ Object.assign(globalThis, {sbeLoad, sbeAdopt, sbeFetchPeaks, sbeMusicEditPath,sbePaintProtected, sbeSetState, sbeSnapshot, sbeRestore,sbeOvMutate, sbeOvAddAt, sbeOvSetPath, sbeMutate,- sbeUndo, sbeRedo, sbeQueueSave, sbeBackup,+ sbeUndo, sbeRedo, sbeQueueSave, sbeBackup, sbeBeaconBackup,sbeSave, sbeSaveAlarm, sbeSaveAlarmClear, sbeSaveInner,sbeRenderErrors, sbeErrsToggle, sbeTakeTheirs, sbeForceSave,sbeSaveNow, sbeAgo, sbeVersionLine, sbeVersionsEl,@@ -13033,16 +14960,16 @@ Object.assign(globalThis, {sbeShowFrameAt, sbeSrcUrl, edPoolPreview, sbeSrcPlay,sbeSrcStop, sbeSrcToggle, sbeSrcAdd, sbePaintSource,sbeMusicMode, sbeSetMusicMode, edPoolSrc, edPoolUpload,- edPoolUploadRow, edPoolRefresh, edPoolLoadFilms, edPoolPickFilm,+ edPoolUploadRow, edPoolRefresh, edPoolLoadFilms, edPoolPickFilm, edPoolShowAll,edPoolLoadFilmShots, edPoolPaint, edPoolObserve, edPoolAdd,edPoolDragStart, edPoolDragMove, edPoolDragEnd, edAddSlug,- sbePaintRelink, sbeRelink, edPoolFocus, sbeTogglePlay,+ sbePaintRelink, sbeRelink, sbeClipOffline, sbePaintOffline, edPoolFocus, sbeTogglePlay,sbeSetMute, sbeUnmuteFromRefusal, sbePlay, sbeStop,sbeFrame, sbeMusicPlay, sbeMusicSync, sbeStripSync,sbeStripStop, sbeZoomMin, sbeZoomTo, sbeZoom,sbeZoomSlide, sbeZoomFit, sbeJumpCut, sbeToggleSnap, sbeKeyHint,sbeOnTlWheel, sbePrepare, sbePrepareCancel,- sbeAuto, sbeGenClose, sbeGenSubmit, sbeRenderFilm,+ sbeAuto, sbeGenClose, sbeGenSubmit, sbeRenderFilm, sbeRenderCancel,sbeExportNle, sbeTick, workflowSwitch,// inline-handler targets: generated markup resolves these through the// global scope (the v4.9.0 regression, PR #69)@@ -13057,6 +14984,7 @@ Object.assign(globalThis, {sbeSelNormalise, sbeSelIds, sbeSelCount, sbeSelMap, sbeSelHas, sbeSelClips,sbeSelectOne, sbeSelectToggle, sbeSelectRange, sbeSelectAll, sbeSelectNone,sbeMutateEach, sbeGroupLimits, sbeMoveGroup, sbeCloseGapAt, sbeNudge,+ sbeCloseAllGaps, sbeNoticeHoles,sbeCbarModel, sbePaintCbar, sbeCbarFit, sbeCbarStamp,sbeSplitWhy, sbeCbarPlayhead,sbeCtxOpen, sbeReorderSel, sbeSplitHere, sbeGenOpen,@@ -13092,4 +15020,20 @@ Object.assign(globalThis, {sbeInspectRead, sbeInspectSet, sbeInspectToggle, sbeSrcMonToggle, sbeSrcClose,sbeFullscreen, sbePanelsRead, sbePanelsApply, sbePanelsToggle, sbePaintPanels,sbeProgInfo, sbePlayGlyph, sbeTlPrefKey,+ // FILM package (2026-09-29 mega review): slip/roll, takes and replace,+ // the frame timecode toggle, colour and the retake summary.+ sbeFmtTC, sbeTimeMode, sbeToggleTimeMode, sbeSlip, sbeSlipNudge, sbeRollEdit,+ sbeReplaceClip, sbeSwapIn, sbeAltForClip, sbeReplaceSelWithAlt, sbeRetakeSummary,+ sbeMusicMaster, sbeSongPlayhead, sbeSongSyncOffset, sbeSongSyncBadge, sbeSnapToSong,+ sbeAutoAlign,+ // FILM-14: the grade — model, preview, commit, copy-to-selection.+ sbeGrade, sbeGradeIsNeutral, sbeSetGrade, sbeCopyGrade, sbeGradeRows,+ sbeGradePreview, sbeGradeCommit, sbeGradeResetSel, sbeCopyGradeSel,+ sbeGradeCss, sbeApplyPreviewGrade, sbeSetFilmLook,+ sbeMatchColourOpen, sbeMatchClose, sbeMatchStrengthPreview, sbeMatchApply,+ // FILM-58: markers, copy/paste, sequence aspect.+ sbeMarkerAdd, sbeMarkerRemove, sbeMarkerSetLabel, sbeMarkerSetKind,+ sbeMarkerMutate, sbeMarkerAtPlayhead, sbeMarkerBands,+ sbeClipCopy, sbeClipPaste, sbeClipboardCopy, sbeClipboardPasteAttrs, sbeClipboardPasteClips,+ sbeSetSeqAspect, sbeSeqAspect,});diff --git a/webapp/js/engines.js b/webapp/js/engines.jsindex df493a4..ccde719 100644--- a/webapp/js/engines.js+++ b/webapp/js/engines.js@@ -395,7 +395,11 @@ function _h3TriStepMin(cell) {}function _h3TriStepEta(cell) {if (!cell || cell.tristep_min == null) return '';- return (_h3IsI2V() && cell.tristep_eta_i2v) ? cell.tristep_eta_i2v : cell.tristep_eta;+ if (_h3IsI2V()) return cell.tristep_eta_i2v || cell.tristep_eta;+ // Owner ruling (2026-09-29): real fleet range for Fast, where enough of+ // it exists (fleet_range_fast, priced separately from Best — H3's speed+ // split is a real difference in wall time, unlike LTX's mode axis).+ return cell.fleet_range_fast ? cell.fleet_range_fast.eta_range : cell.tristep_eta;}// "~9 min" → "9 min": a tilde at this size reads as a minus (the owner read@@ -421,8 +425,21 @@ function h3CellEtaMin(cell, opts) {}return cell.eta_min;}+// The provenance line for a cell's tooltip, matching whichever speed is+// actually showing — mirrors ltxCellEtaBasis's contract.+function h3CellEtaBasis(cell, opts) {+ if (!cell) return '';+ opts = opts || {};+ const fast = (opts.fast != null) ? opts.fast : h3TriStepOn(cell);+ const fr = fast ? cell.fleet_range_fast : cell.fleet_range;+ return fr ? fr.basis : 'estimated — few renders on this Mac class yet';+}function h3FmtEtaMin(m) {- return '~' + Math.max(1, Math.round(m)) + ' min' + (m >= 25 ? ' · batch' : '');+ // H3-37: "· batch" on a 25+ min chip was unexplained, and reads as the+ // unrelated Batch feature (queueing several renders) rather than what it+ // meant here — this single render is long enough to start and walk away+ // from. Say that plainly instead of a one-word label with two meanings.+ return '~' + Math.max(1, Math.round(m)) + ' min' + (m >= 25 ? ' · long, start and walk away' : '');}// The eta STRING for a cell under the current speed; the server's own string// wherever it priced that state (that is where a MEASURED wall clock lives).@@ -433,7 +450,13 @@ function h3CellEta(cell, opts) {if (fast && cell.tristep_min != null) return _h3TriStepEta(cell);if (opts.turbo) return cell.turbo_eta;const ov = (document.getElementById('h3_steps') || {}).value || 'auto';- if (ov === 'auto' || !/^\d+$/.test(ov)) return cell.eta;+ if (ov === 'auto' || !/^\d+$/.test(ov)) {+ // Owner ruling (2026-09-29): Best's own real fleet range, same idea as+ // Fast's above — never for i2v, which the server prices separately and+ // this fleet cell (mode "t2v") does not cover.+ if (!_h3IsI2V() && cell.fleet_range) return cell.fleet_range.eta_range;+ return cell.eta;+ }return h3FmtEtaMin(h3CellEtaMin(cell, { fast: false }));}// Second line of each half of the switch.@@ -498,12 +521,20 @@ function renderH3Turbo() {if (bestSub) bestSub.textContent = h3SpeedSub('best');if (fastBtn) {fastBtn.classList.toggle('needs-download', !tri.available);+ // H3-13: distinct from needs-download (the adapter isn't installed) —+ // this cell has no Fast path at all (Native, the single-pass 10s), same+ // dashed/dimmed treatment so the chip itself says "not really available+ // here" instead of only a sub-label most people skim past.+ const cellOnlyBest = tri.available && cell && cell.tristep_min == null;+ fastBtn.classList.toggle('cell-only-best', cellOnlyBest);fastBtn.title = !tri.supported? 'Fast needs a newer H3 runner — run "Update Hailuo H3 runner" in the Pinokio sidebar (weights stay).': !tri.downloaded? '3 steps — about 4× faster, great for drafts and most shots. One click installs the '+ '180 MB adapter (' + (tri.license || 'MiniMax H3 Community License') + ').'- : '3 steps — about 4× faster, great for drafts and most shots.';+ : cellOnlyBest+ ? (cell.label || 'This shape') + ' has no Fast pass yet — it always renders on Best.'+ : '3 steps — about 4× faster, great for drafts and most shots.';}_h3SyncSamplerTitles();_h3ApplySpeed();@@ -525,14 +556,21 @@ function _h3ApplySpeed() {if (triIn) triIn.value = fastOn ? '1' : '0';const tbIn = document.getElementById('h3_turbo');if (tbIn) tbIn.value = '0';- // The lit half is the PREFERENCE (what you chose); the note says when this- // shape can't honour it.- const lit = (pref === 'fast' && tri.available) ? 'fast' : 'best';+ // H3-13: the lit half used to be the PREFERENCE alone (pref === 'fast' &&+ // tri.available), so Native and the single-pass 10s — cells with no Fast+ // path at all (cell.tristep_min == null) — kept the Fast pill pink while+ // the render that actually queued ran Best, 8-25x slower. fastOn already+ // folds in per-cell availability (h3TriStepOn), so light whichever half+ // is really about to render; the note below still explains why.+ const lit = fastOn ? 'fast' : 'best';document.querySelectorAll('#h3SpeedGroup [data-h3-speed]').forEach(b =>b.classList.toggle('active', b.dataset.h3Speed === lit));const note = document.getElementById('h3SpeedNote');if (note) {- const bestOnly = lit === 'fast' && cell && cell.tristep_min == null;+ // Independent of `lit`: this is "you prefer Fast, but this shape can+ // only run Best", which is exactly the case where the pill and the+ // note used to disagree.+ const bestOnly = pref === 'fast' && cell && cell.tristep_min == null;note.textContent = bestOnly? cell.label + ' renders on Best — Fast is not validated at this shape yet.': '';@@ -546,7 +584,16 @@ function _h3ApplySpeed() {if (stIn && stIn.value !== 'auto' && typeof setH3Steps === 'function') {try { setH3Steps('auto'); } catch (e) {}}- if (s) s.value = tri.steps || 4;+ // H3-25: this used to mirror the adapter's own SIGMA-POINT count+ // (tri.steps, falling back to the literal 4) into the shared #steps+ // field that the derived line reads — but the Speed row says+ // "Fast = 3 steps", counting FORWARDS, not sigma points. Same render,+ // two different numbers on screen. cell.tristep_forwards is what+ // actually runs (windows * H3_TRISTEP_FORWARDS, server-side); a+ // sigma-point count minus one is the fallback only when a cell+ // hasn't loaded yet.+ if (s) s.value = (cell && cell.tristep_forwards != null)+ ? cell.tristep_forwards : (tri.steps ? tri.steps - 1 : 3);} else if (s && cell) {const ov = (stIn || {}).value || 'auto';s.value = (ov !== 'auto' && /^\d+$/.test(ov)) ? parseInt(ov, 10) : cell.steps;@@ -580,6 +627,23 @@ function h3SpeedOfParams(p) {p = p || {};return (p.h3_tristep || p.h3_turbo) ? 'fast' : 'best';}+// H3-04: "Fast" / "Best", for any place that shows a submitted or running+// H3 job's params — the Now card, a queue row, the info modal. One+// function so all three read the same label from the same field.+function h3JobSpeedLabel(p) {+ if (!p || p.engine !== 'h3') return '';+ return h3SpeedOfParams(p) === 'fast' ? 'Fast' : 'Best';+}+// "Hailuo H3 · Standard 10s" — the shape a submitted H3 job asked for,+// looked up from its own h3_tier (never re-derived from the CURRENT form+// state, which may have moved on to a different shot by the time this job+// is showing in the queue or the Now card).+function h3JobShapeLabel(p) {+ if (!p || p.engine !== 'h3') return '';+ const cell = h3TierByKey(p.h3_tier || '');+ const shape = cell ? `${cell.quality_label} ${cell.length_label}` : (p.h3_tier || '');+ return ['Hailuo H3', shape].filter(Boolean).join(' · ');+}// The Fast half: select it when ready; otherwise the one click that makes it// ready (install the adapter, or say which update is needed).@@ -594,23 +658,43 @@ async function h3SpeedClick(which) {return;}if (tri.installing) { toast('The Fast adapter is already installing — watch the log.', 'ok'); return; }- if (!confirm('Install Fast (3 steps)?\n\n'- + '180 MB adapter into the H3 models folder, from '- + (tri.repo || 'Kijai/MiniMax-H3_comfy') + ' (a conversion of '- + (tri.source_repo || 'TaoLiveAIGC/TaoMate-H3') + ').\n'- + 'License: ' + (tri.license || 'MiniMax H3 Community License')- + ' — the same terms as H3 itself.\n\n'- + 'Progress streams to the log. Fast switches on by itself when it lands.')) return;- try {- const r = await fetch('/h3/tristep/install', { method: 'POST' });- const j = await r.json().catch(() => ({}));- if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status));- _h3SetSpeedPref('fast');- toast(j.already_installed ? 'Fast is already installed.'- : 'Installing Fast (180 MB) — watch the log. It switches on by itself when it lands.', 'ok');- } catch (e) {- toast('Fast install: ' + (e.message || 'failed'), 'danger');- }+ // H3-27: a native confirm() blocks the tab and reads as a browser dialog,+ // not the panel's own UI (the same rule Stop's confirmation follows).+ // Replace it with the panel's existing "toast + action link" confirm+ // pattern (used for the engine-offer nudge, install prompts elsewhere) —+ // one informative toast, one explicit click to proceed, nothing blocking.+ // Also: when Fast can't install right now (or before the user commits),+ // mention Turbo if it's ALREADY installed — a real quicker-than-Best+ // option this click used to leave unmentioned entirely.+ const turbo = h3TurboState();+ const turboHint = (turbo && turbo.available)+ ? ' Turbo (already installed) is a quicker option too — pick it from this same switch after Best.'+ : '';+ const el = phosToast(+ 'Install Fast — 180 MB adapter from ' + (tri.repo || 'Kijai/MiniMax-H3_comfy')+ + ' (a conversion of ' + (tri.source_repo || 'TaoLiveAIGC/TaoMate-H3') + '). License: '+ + (tri.license || 'MiniMax H3 Community License') + ', same terms as H3 itself.' + turboHint,+ { icon: 'ph-download-simple', duration: 12000 });+ if (!el) return;+ const a = document.createElement('a');+ a.href = '#';+ a.className = 'phos-toast-action';+ a.textContent = 'Install Fast';+ a.onclick = async (ev) => {+ ev.preventDefault();+ el.remove();+ try {+ const r = await fetch('/h3/tristep/install', { method: 'POST' });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status));+ _h3SetSpeedPref('fast');+ toast(j.already_installed ? 'Fast is already installed.'+ : 'Installing Fast (180 MB) — watch the log. It switches on by itself when it lands.', 'ok');+ } catch (e) {+ toast('Fast install: ' + (e.message || 'failed'), 'danger');+ }+ };+ el.appendChild(a);}document.querySelectorAll('#h3SpeedGroup [data-h3-speed]').forEach(b => {b.onclick = () => h3SpeedClick(b.dataset.h3Speed);@@ -651,8 +735,12 @@ function h3EstimateLine() {if (cell.facefix_min == null) return txt;m += cell.facefix_min;}- const r = m < 10 ? Math.round(m * 2) / 2 : Math.round(m);- return txt + ' ≈ ' + r + ' min';+ // H3-24: this used to round to the nearest HALF minute below 10 min+ // (Math.round(m * 2) / 2, e.g. "6.5") while the chip and the Shot setup+ // summary round the SAME cell to the nearest whole minute (h3FmtEtaMin /+ // the server's own _fmt_eta) — one cell, three different numbers on+ // screen at once. One formatter now, everywhere.+ return txt + ' ≈ ' + h3FmtEtaMin(m).replace(/^~/, '').replace(/ · batch$/, '');}// Adapter-slot pills. Bound at parse time like the Turbo / Steps groups —@@ -732,12 +820,22 @@ function _engineMenuEl() {return m;}-function closeEngineMenu() {+// H3-17: the menu is portaled to <body> (it has to be — the header is+// overflow:hidden and would slice it) which is exactly what breaks Tab+// order: a portaled element sits at the END of the DOM regardless of where+// its trigger lives, so Tab from the trigger jumped clear over it to+// whatever else the header holds (the health chip). closeEngineMenu() used+// to only hide the menu, never give focus back anywhere, so a keyboard user+// who opened it with Enter/Space had no idea where focus went next.+function closeEngineMenu(opts) {window._engineMenuOpen = false;const m = document.getElementById('engineMenu');if (m) m.hidden = true;const t = document.querySelector('#engineSwitch .eng-trigger');- if (t) t.setAttribute('aria-expanded', 'false');+ if (t) {+ t.setAttribute('aria-expanded', 'false');+ if (!opts || opts.returnFocus !== false) t.focus();+ }}function toggleEngineMenu() {@@ -752,17 +850,41 @@ function toggleEngineMenu() {m.hidden = false;window._engineMenuOpen = true;trig.setAttribute('aria-expanded', 'true');+ // Move focus INTO the menu (the active engine's row, or the first row) —+ // a keyboard user who just opened this had no other way to reach it,+ // since Tab from the trigger skips clear over the portaled menu.+ const opts = Array.from(m.querySelectorAll('.eng-opt'));+ const target = opts.find(o => o.classList.contains('active')) || opts[0];+ if (target) target.focus();}document.addEventListener('click', (ev) => {if (!window._engineMenuOpen) return;if (ev.target.closest('#engineMenu') || ev.target.closest('#engineSwitch')) return;- closeEngineMenu();+ closeEngineMenu({ returnFocus: false });}, true);document.addEventListener('keydown', (ev) => {- if (ev.key === 'Escape' && window._engineMenuOpen) closeEngineMenu();+ if (!window._engineMenuOpen) return;+ if (ev.key === 'Escape') { closeEngineMenu(); return; }+ // Arrow Up/Down move focus between rows; Home/End jump to the ends. Enter+ // and Space already work — they're plain <button> elements, so the+ // browser fires their onclick natively when focused.+ if (ev.key !== 'ArrowDown' && ev.key !== 'ArrowUp'+ && ev.key !== 'Home' && ev.key !== 'End') return;+ const m = document.getElementById('engineMenu');+ if (!m) return;+ const opts = Array.from(m.querySelectorAll('.eng-opt'));+ if (!opts.length) return;+ ev.preventDefault();+ const cur = opts.indexOf(document.activeElement);+ let next;+ if (ev.key === 'Home') next = 0;+ else if (ev.key === 'End') next = opts.length - 1;+ else if (ev.key === 'ArrowDown') next = cur < 0 ? 0 : (cur + 1) % opts.length;+ else next = cur < 0 ? opts.length - 1 : (cur - 1 + opts.length) % opts.length;+ opts[next].focus();});-window.addEventListener('resize', closeEngineMenu);+window.addEventListener('resize', () => closeEngineMenu({ returnFocus: false }));function renderEngineSwitch() {const box = document.getElementById('engineSwitch');@@ -804,7 +926,14 @@ function renderEngineSwitch() {let badge = '', badgeClass = '';if (st.announced) { badge = 'soon'; }else if (offer) {- badge = st.repairable ? 'repair' : (e.install_size || '').replace(/^~/, '');+ // H3-05: "repairable" also covers the missing_q8_dit case (weights on+ // disk, only the local compact build is missing) — Pinokio's sidebar+ // shows ONLY a Build entry there, no Repair entry (pinokio.js), so a+ // "repair" badge sent the user looking for a button that doesn't+ // exist. venv/runner actually broken is the real repair case.+ badge = (st.repairable && st.reason === 'missing_q8_dit') ? 'build'+ : st.repairable ? 'repair'+ : (e.install_size || '').replace(/^~/, '');badgeClass = ' offer';} else if (st.available && !modeOk) { badge = (e.serves_label || '').toLowerCase().replace(' and ', ' · '); }// Inert = real but unreachable RIGHT NOW. Distinct from needs-install,@@ -856,12 +985,20 @@ function _engineTooltip(e, st, modeOk) {if (!e.builtin && !st.capable) {// The floor is the LOWEST lane's, served by the panel. This read// `st.min_ram_gb || 64` — the bf16 number, or a literal 64 that no floor- // in this codebase has ever been — on a machine whose real bar is 46.- return name + ' — needs ' + (st.ram_floor_gb || st.min_ram_gb || 46)+ // in this codebase has ever been — then `|| 46`, a number no floor in+ // this codebase has ever been either (H3-28). The real bar is+ // H3_MIN_RAM_GB_Q8 = 36 (mlx_ltx_panel.py); both server fields should+ // always be present, so this is a last-resort fallback only.+ return name + ' — needs ' + (st.ram_floor_gb || st.min_ram_gb || 36)+ ' GB unified memory';}if (!e.builtin && !st.available) {- return st.repairable+ // H3-05: "repairable" also covers missing_q8_dit (every weight present,+ // only the local compact build is missing) — a genuinely different fix+ // than "repair", with its own Pinokio menu entry (Build, not Repair).+ return (st.repairable && st.reason === 'missing_q8_dit')+ ? name + ' — needs its compact engine built; your weights are already on disk. Click for the one-click fix.'+ : st.repairable? name + ' — needs repair; your weights are still on disk. Click for the one-click fix.': name + ' — available to install (' + (e.install_size || '')+ '). Click to see what it does.';@@ -935,7 +1072,17 @@ const TIER_ENGINES = {// what the quality chip prints. It is the current cell's frames, never a// fixed number — a chip that said "73f" while rendering 121 would be the// same class of lie as the engine label this release is fixing.- qualitySpec: (item, cell) => `${item.canvas} · ${cell ? cell.frames : '—'}f`,+ // VC-28: show the size that actually lands in Outputs, not just the+ // render canvas — Balanced's default fit_720p export means a 1024×576+ // render delivers a 1280×720 file, the same gap VC-19 closed for the+ // info modal. item.delivered_canvas comes from the server+ // (ltx_tiers_payload -> compute_upscale_plan); equals item.canvas+ // whenever nothing is exported, so this is a no-op everywhere else.+ qualitySpec: (item, cell) => {+ const canvas = (item.delivered_canvas && item.delivered_canvas !== item.canvas)+ ? `${item.canvas} → ${item.delivered_canvas}` : item.canvas;+ return `${canvas} · ${cell ? cell.frames : '—'}f`;+ },lengthSpec: (item, cell) => (cell ? `${cell.frames}f` : `${item.frames}f`),eta: (cell) => ltxCellEta(cell),// A cell whose weights are not on disk is an INSTALL OFFER, not a choice.@@ -985,8 +1132,15 @@ function _tierChipHtml(engine, kind, item, cell, active) {const foot = !ok ? 'unavailable': needsInstall ? E.installLabel(cell): E.eta(cell);+ // Owner ruling (2026-09-29): the tooltip says WHERE the time on the chip+ // comes from — "based on 523 renders on Macs like yours" vs "estimated —+ // few renders on this Mac class yet" — right where a user is already+ // looking to decide whether to trust it.+ const basisFn = kind === 'quality' && !needsInstall+ ? (engine === 'h3' ? h3CellEtaBasis : ltxCellEtaBasis) : null;+ const basis = (ok && basisFn) ? basisFn(cell) : '';const title = ok- ? ((cell && cell.blurb) || item.blurb || '')+ ? ([(cell && cell.blurb) || item.blurb || '', basis].filter(Boolean).join(' — ')): (cell && cell.unavailable_reason) || 'Not available on this install.';const attr = (kind === 'quality') ? (E.qAttr || `${engine}-quality`): (E.lAttr || `${engine}-length`);@@ -1087,7 +1241,19 @@ function renderTierAxes(engine) {}}// The shipped name, kept so every H3 call site is unchanged.-function renderH3Axes() { return renderTierAxes('h3'); }+// H3-12: the Landscape/Portrait sub-labels ("Landscape 640x384") were only+// ever refreshed from setH3Orientation itself — every OTHER thing that+// changes the resolved cell's canvas (setH3Quality, setH3Length, setH3Tier,+// Load Params, a Fallback redirect) left them stale, showing a size that+// belonged to the PREVIOUS quality/length pick. renderH3Axes() is the one+// function every one of those already calls to repaint the strips, so+// syncing the subs here — instead of chasing each call site individually —+// fixes the whole class at once.+function renderH3Axes() {+ const result = renderTierAxes('h3');+ if (typeof _h3SyncOrientationSubs === 'function') { try { _h3SyncOrientationSubs(); } catch (e) {} }+ return result;+}// ---- LTX's side of the shared axis machinery --------------------------------// The mirror of h3CellFor / h3CurrentQuality / h3CellEta, and nothing more. The@@ -1150,13 +1316,33 @@ function ltxCellEta(cell) {// Chips must not advertise the tuned wall clock while the Fast draft// schedule is armed — the same lie the H3 Turbo repaint exists to kill.// fast_eta exists only on cells that can run the preset (server-stamped),- // so HQ cells keep their own number untouched.+ // so HQ cells keep their own number untouched. Fast draft has no fleet+ // range of its own yet, so this branch keeps the point estimate.if (cell.fast_eta && typeof schedPresetActive === 'function'&& schedPresetActive()) {return cell.fast_eta + ' · fast draft';}- const tail = (cell.pack === 'q8' && cell.pipeline === 'hq') ? ' · Q8 HQ' : '';- return (cell.eta || '') + tail;+ // VC-23: "Q8 HQ" names the internal quantization + pipeline, not+ // anything a user asked for — "High detail" says what it delivers.+ const tail = (cell.pack === 'q8' && cell.pipeline === 'hq') ? ' · High detail' : '';+ // Owner ruling (2026-09-29): show the fleet's own p25-p75 RANGE ("~12-18+ // min") wherever real fleet data exists, instead of a single point+ // number — cell.fleet_range is server-computed (fleet_calibrated_range,+ // mlx_ltx_panel.py) from real installs' own wall clocks, this Mac's+ // chip/RAM class first, falling back through chip-family and fleet-wide+ // levels. Without fleet data, VC-28's modelled band (cell.eta_range:+ // +/-10% on a measured cell, skewed upward on a modelled one) still reads+ // more honestly than a single point; the bare point estimate is last.+ const fr = cell.fleet_range;+ return (fr ? fr.eta_range : (cell.eta_range || cell.eta || '')) + tail;+}+// The provenance line for a cell's tooltip — "based on 523 renders on Macs+// like yours" / "estimated -- few renders on this Mac class yet". Kept+// separate from ltxCellEta so a caller that only wants the number (the+// Batch total, a queue-row label) doesn't have to strip a sentence back off.+function ltxCellEtaBasis(cell) {+ if (!cell) return '';+ return cell.fleet_range ? cell.fleet_range.basis : 'estimated — few renders on this Mac class yet';}// Are this cell's weights on disk? A RUNTIME question — the tier table is built// at import time and cannot know. `offered` answers "can this Mac's RAM serve@@ -1349,6 +1535,15 @@ function _h3ApplyShape(qualityKey, lengthKey, opts) {noteEl.textContent = n;noteEl.hidden = !n;}+ // H3-14: the same blurb the chip's own title= tooltip carries, surfaced as+ // a visible line so it isn't hover-only (unreachable on trackpad-averse+ // and touch use, and easy for a stale sentence to hide in for months).+ const blurbEl = document.getElementById('h3TierBlurb');+ if (blurbEl) {+ const b = cell.blurb || '';+ blurbEl.textContent = b;+ blurbEl.hidden = !b;+ }// The export line is per (canvas × target): switching quality changes whether// this canvas exports clean or padded, so it has to be re-read here too._h3SyncExportNote();@@ -1540,6 +1735,122 @@ function setH3Tier(key) {_h3ApplyShape(tier.quality, tier.length, { fallback: true });}+// ---- H3-07: the Video-tab prompt helper -------------------------------------+// H3 speaks only what sits inside a <d>[Language] …</d> tag, written into the+// three-field form (integrated_multimodal_description / overall_soundscape /+// non_diegetic_music) — docs/H3_ENGINE.md "Dialogue on H3". None of that was+// discoverable from the Video tab: a line written as prose quotes left H3's+// voice switched off with no error. These three functions are the whole+// control; the format itself is unchanged — this only helps someone write it.++const H3_PROMPT_FIELD_MARKER = 'integrated_multimodal_description:';++// Structure: wrap whatever is already typed as the first field's content+// (so nothing is thrown away) and append the other two, empty and labelled.+// A prompt that already looks structured is left alone — this is an insert,+// not a reformat.+function h3InsertPromptStructure() {+ const ta = document.getElementById('prompt');+ if (!ta) return;+ const cur = ta.value || '';+ if (cur.includes(H3_PROMPT_FIELD_MARKER)) {+ if (typeof phosToast === 'function') {+ phosToast('Already structured — the three fields are there.', { kind: 'ok' });+ }+ ta.focus();+ return;+ }+ const body = cur.trim()+ ? cur.trim()+ : '[Shot 1] Who is on screen, two or three anchors (build, clothes), '+ + 'where they are and the light. What happens, described plainly.';+ ta.value = `${H3_PROMPT_FIELD_MARKER} ${body}\n\n`+ + `overall_soundscape: ambience and sound effects in the scene.\n\n`+ + `non_diegetic_music: N/A`;+ ta.dispatchEvent(new Event('input', { bubbles: true }));+ ta.focus();+}++// + Line: insert one dialogue line at the cursor (or the end) — the tag, a+// speaker id, and the mouth-stop clause the model needs in the SAME+// sentence or it keeps the mouth moving on nothing (docs/H3_ENGINE.md).+// Selects the placeholder words inside the tag so typing replaces them.+function h3InsertDialogueLine() {+ const ta = document.getElementById('prompt');+ if (!ta) return;+ const lang = (document.getElementById('h3DialogueLang') || {}).value || 'English';+ const start = (typeof ta.selectionStart === 'number') ? ta.selectionStart : ta.value.length;+ const end = (typeof ta.selectionEnd === 'number') ? ta.selectionEnd : start;+ const before = ta.value.slice(0, start);+ const after = ta.value.slice(end);+ const needsLeadingSpace = before && !/[\s\n]$/.test(before);+ const speaker = 'NAME (S1) says: ';+ const line = `${needsLeadingSpace ? ' ' : ''}${speaker}<d>[${lang}] line here</d> `+ + `Exactly as the line ends, NAME's mouth settles closed.`;+ ta.value = before + line + after;+ // Select "line here" so typing the actual words is one keystroke away.+ // Numeric, always: `before && …` is '' at position 0, and '' + 1 + … used to+ // concatenate into a string offset that selected nothing (Codex H3-9).+ const selStart = before.length + (needsLeadingSpace ? 1 : 0) + speaker.length+ + `<d>[${lang}] `.length;+ const selEnd = selStart + 'line here'.length;+ ta.focus();+ try { ta.setSelectionRange(selStart, selEnd); } catch (e) {}+ ta.dispatchEvent(new Event('input', { bubbles: true }));+}++// Every <d>[Lang] …</d> tag's word count against this shape's budget+// (H3.speech_words_per_sec — the SAME number storyboard's own validator+// uses, so the two can't disagree), and a warning when prose quotes appear+// with no tag at all — the exact silent-failure this control exists for.+function h3SyncPromptHelper() {+ const ta = document.getElementById('prompt');+ const countEl = document.getElementById('h3DialogueWordCount');+ const warnEl = document.getElementById('h3QuoteWarning');+ if (!ta) return;+ const text = ta.value || '';+ const tagRe = /<d>\s*(?:\[[^\]]*\]\s*)?([^<]*)<\/d>/gi;+ let m, words = 0, tagCount = 0;+ while ((m = tagRe.exec(text))) {+ tagCount++;+ words += (m[1].trim().match(/\S+/g) || []).length;+ }+ if (countEl) {+ if (tagCount) {+ const cell = (typeof h3CurrentCell === 'function') ? h3CurrentCell() : null;+ const windows = Math.max(1, (cell && cell.chain_windows) || 1);+ const perWindowSec = (cell && cell.seconds) ? (cell.seconds / windows) : 5;+ const rate = (H3 && H3.speech_words_per_sec) || 2.4;+ // ONE window's speaking time, however many tags share it: splitting the+ // same words into more tags used to raise the allowance (Codex H3-8).+ // The main prompt's dialogue is window 1's; later windows have boxes.+ const budget = Math.max(1, Math.round(perWindowSec * rate));+ countEl.hidden = false;+ countEl.textContent = `${words}/${budget} dialogue words`;+ countEl.classList.toggle('over-budget', words > budget);+ } else {+ countEl.hidden = true;+ }+ }+ if (warnEl) {+ // A "-marked quote whose position falls outside every <d>…</d> span.+ const tagSpans = [];+ tagRe.lastIndex = 0;+ while ((m = tagRe.exec(text))) tagSpans.push([m.index, m.index + m[0].length]);+ const quoteRe = /["“”]/g;+ let hasStrayQuote = false;+ let q;+ while ((q = quoteRe.exec(text))) {+ if (!tagSpans.some(([s, e]) => q.index >= s && q.index < e)) { hasStrayQuote = true; break; }+ }+ warnEl.hidden = !hasStrayQuote;+ }+}+document.getElementById('prompt') && document.getElementById('prompt')+ .addEventListener('input', () => {+ if (document.body.dataset.engine === 'h3') { try { h3SyncPromptHelper(); } catch (e) {} }+ });+// ---- published to the page --------------------------------------------------// Inline handlers in the markup and the other files resolve these through@@ -1550,6 +1861,7 @@ Object.assign(globalThis, {setH3Upscale, setH3FaceFixAfter, setH3Orientation, setH3Steps, h3TurboPillSub,renderH3Turbo, setH3Turbo, syncModeStripToEngine, renderEngineSwitch,setH3Speed, h3SpeedOfParams, h3EstimateLine, setH3TriStep, h3TriStepOn, h3TriStepState,+ h3JobSpeedLabel, h3JobShapeLabel, ltxCellEtaBasis, h3CellEtaBasis,// Published for the Shot setup summary (characters.js): a closed section has// to price the shape it is hiding, and it must do it with the SAME numbers// the chips print — never a second cost model in a second module.@@ -1563,4 +1875,5 @@ Object.assign(globalThis, {ltxCurrentLength, ltxCurrentCell, ltxCellEta, ltxCellNeedsInstall,ltxCellInstallLabel, _ltxApplyShape, setH3Quality, _h3ApplyShape,renderH3WindowPrompts, toggleH3WindowHelp, setH3ChainPrompts, setH3Tier,+ h3InsertPromptStructure, h3InsertDialogueLine, h3SyncPromptHelper,});diff --git a/webapp/js/health.js b/webapp/js/health.jsindex 427dbcd..c4fb91f 100644--- a/webapp/js/health.js+++ b/webapp/js/health.js@@ -78,9 +78,12 @@ function renderVersionPill() {pill.classList.add('pill-restart');pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-arrow-clockwise-bold"/></svg>Restart Phosphene';const v = s.pull_pulled_to_version || s.pull_pulled_to_short || 'the new code';+ // SYS-29: the non-full-update case now self-restarts on click+ // (panelRestart(), same as the stale-process case below) instead of+ // asking for a manual Stop -> Start.pill.title = s.pull_requires_full_update? `Pulled ${v}. This update touched dependencies — use Pinokio's Update button (not just Stop+Start).`- : `Pulled ${v}. Click Stop → Start in Pinokio to apply.`;+ : `Pulled ${v}. Click to restart and apply it.`;return;}// Same restart affordance for a checkout that advanced UNDER this@@ -174,14 +177,20 @@ window._bcHandled = Object.create(null);function _phModalShow(opts) {const wrap = document.getElementById('phModalWrap');if (!wrap || window._phModalOpen) return false;+ // `tone` generalizes the old broadcast-only styling: 'broadcast' (cyan,+ // maintainer notes) or 'danger' (red, a destructive confirm — Stop+ // mid-render and friends). opts.broadcast still works for callers that+ // predate this.+ const tone = opts.tone || (opts.broadcast ? 'broadcast' : '');+ const toneClass = tone ? 'is-' + tone : '';document.getElementById('phModalKicker').textContent = opts.kicker || '';- document.getElementById('phModalKicker').className = opts.broadcast ? 'is-broadcast' : '';+ document.getElementById('phModalKicker').className = toneClass;document.getElementById('phModalTitle').textContent = opts.title || '';document.getElementById('phModalBody').textContent = opts.body || '';const prim = document.getElementById('phModalPrimary');const sec = document.getElementById('phModalSecondary');prim.textContent = opts.primaryLabel || 'OK';- prim.className = opts.broadcast ? 'is-broadcast' : '';+ prim.className = toneClass;prim.onclick = () => { _phModalClose(); if (opts.onPrimary) opts.onPrimary(); };if (opts.secondaryLabel) {sec.hidden = false;@@ -190,6 +199,12 @@ function _phModalShow(opts) {} else {sec.hidden = true;}+ // A confirm the user dismisses with Escape or a click outside must count+ // as "no" (onCancel), never silently vanish leaving the caller thinking+ // its onPrimary/onSecondary will still fire.+ wrap.onclick = (ev) => {+ if (ev.target === wrap) { _phModalClose(); if (opts.onCancel) opts.onCancel(); }+ };wrap.hidden = false;window._phModalOpen = true;return true;@@ -312,12 +327,42 @@ function _ubRestartState(newVersion, requiresFullUpdate) {const go = document.getElementById('ubUpdate');const later = document.getElementById('ubLater');if (title) title.textContent = `Updated to ${newVersion} — restart to finish`;- if (sub) {- sub.textContent = requiresFullUpdate- ? 'This update touched Python dependencies, so use Pinokio\u2019s Update button (not just Stop and Start) so they reinstall.'- : 'Click Stop, then Start in Pinokio. Your queue and settings are preserved.';+ // SYS-29: this used to hide `go` and tell the user to go click Stop+ // then Start in Pinokio themselves -- a second, manual mechanism+ // sitting right next to panelRestart() (the one-click, 409-guarded+ // self-restart this same file already uses for the stale-process+ // case). No reason the banner's Update needed a human to finish what+ // it started: when the pull didn't touch dependencies, the SAME+ // button now finishes the job by calling panelRestart() directly.+ // When it DID touch dependencies, a self-restart genuinely can't+ // reinstall them (that needs Pinokio's own Update, which reinstalls+ // the venv) -- that's the one case still asking for a manual step,+ // and it says exactly why.+ if (requiresFullUpdate) {+ if (sub) sub.textContent = 'This update touched Python dependencies, so use Pinokio\u2019s Update button (not just Stop and Start) so they reinstall.';+ if (go) go.hidden = true;+ } else {+ if (sub) sub.textContent = 'Your queue and settings are preserved across the restart.';+ if (go) {+ go.hidden = false;+ go.disabled = false;+ go.textContent = 'Restart now';+ go.onclick = async () => {+ _uiEvent('update_prompt', {action: 'banner_restart'});+ go.disabled = true;+ go.textContent = 'Restarting\u2026';+ // Codex UI-10: a refused restart (409 while a render runs) or a+ // failed one used to leave this button disabled on "Restarting…"+ // for good. panelRestart() says whether a restart is under way;+ // when it isn't, the same button is usable again.+ const started = await panelRestart();+ if (!started) {+ go.disabled = false;+ go.textContent = 'Restart now';+ }+ };+ }}- if (go) { go.hidden = true; }if (later) { later.textContent = 'Dismiss'; }el.classList.add('ub-done');return true;@@ -459,7 +504,15 @@ function updateHealthChip() {// Name the thing that is wrong. "Attention" tells the user to go looking.const bad = [models, helper, mem].find(el => _hcSeverity(el) === worst);face.textContent = clean(bad) || 'needs attention';- face.dataset.short = 'attention';+ // VC-32: this used to be the bare word "attention" below 1400px — no+ // indication of WHAT needs it, on a chip whose whole job is a one-glance+ // read. Name the row instead ("models"/"helper"/"memory"), same as the+ // full-width text does; only fall back to the old word if none of the+ // three pills is even findable (shouldn't happen, but the chip must+ // never render nothing).+ const badLabel = bad === models ? 'models' : bad === helper ? 'helper'+ : bad === mem ? 'memory' : 'attention';+ face.dataset.short = badLabel;} else {face.textContent = clean(mem) || 'all good';// The narrow-header face (review 2026-09-02): below 1400px the chip@@ -497,6 +550,9 @@ document.addEventListener('keydown', (ev) => {window.addEventListener('resize', closeHealthPop);// One click — does the right thing for the current state. Magic button.+// Returns false when no restart happened (refused, failed, or the panel did+// not come back) so a caller's own button can be re-armed (UI-10); on success+// the page reloads.async function panelRestart() {const pill = document.getElementById('versionPill');const say = (t) => { if (pill) pill.textContent = t; };@@ -505,9 +561,9 @@ async function panelRestart() {const d = await r.json().catch(() => ({}));if (r.status === 409) {phosToast(d.error || 'A render is running — stop it first.', 'warn');- return;+ return false;}- if (!d.ok) { phosToast(d.error || 'Restart failed.', 'error'); return; }+ if (!d.ok) { phosToast(d.error || 'Restart failed.', 'error'); return false; }} catch (e) {// The process may have exec'd before the response reached us. That is a// SUCCESSFUL restart, not a failure — fall through to polling.@@ -520,20 +576,26 @@ async function panelRestart() {await new Promise(r => setTimeout(r, 700));try {const r = await fetch('/version', {cache: 'no-store'});- if (r.ok) { location.reload(); return; }+ if (r.ok) { location.reload(); return true; }} catch (e) { /* still down */ }}phosToast('Panel did not come back within 60s — start it from Pinokio.', 'error');+ return false;}async function versionPillClick() {if (_versionRestartPending) {- // Educational click: tell the user what's needed.const s = _versionState || {};- const tip = s.pull_requires_full_update- ? "Pulled. Because this update touched Python deps / patches, use Pinokio's Update button (it reinstalls + reapplies patches). After that click Start."- : "Pulled. Click Stop, then Start in Pinokio to apply (your queue and settings are preserved).";- alert(tip);+ if (s.pull_requires_full_update) {+ // Genuinely can't self-restart into this one -- dependencies /+ // patches changed, and only Pinokio's own Update reinstalls those.+ alert("Pulled. Because this update touched Python deps / patches, use Pinokio's Update button (it reinstalls + reapplies patches). After that click Start.");+ return;+ }+ // SYS-29: same fix as the update banner's button -- finish the update+ // the pill already started instead of telling the user to go click+ // Stop then Start themselves.+ await panelRestart();return;}if ((_versionState || {}).stale_process) {@@ -807,4 +869,13 @@ setInterval(refreshVersionPill, 5 * 60 * 1000);// the global scope; everything NOT listed here is private to this module.Object.assign(globalThis, {renderVersionPill, updateHealthChip, versionPillClick, _uiEvent,+ // SYS-19: closeHealthPop wasn't published -- openTierModal (settings.js)+ // and openModelsModal (preview.js) need it so clicking a health-popover+ // row closes the popover before its modal opens on top of it.+ closeHealthPop,+ // The update/broadcast pop-up is the panel's only real dialog component+ // (kicker/title/body/two buttons, one at a time via _phModalOpen) — VC-35's+ // fix is "one in-app confirm/undo component", not a second modal shape, so+ // Stop's confirm-with-cost (queue.js) reuses this rather than inventing one.+ _phModalShow, _phModalClose,});diff --git a/webapp/js/loras.js b/webapp/js/loras.jsindex 8fb0e2b..eb08a9b 100644--- a/webapp/js/loras.js+++ b/webapp/js/loras.js@@ -142,10 +142,21 @@ function _syncLoraPickerForEngine() {if (typeof renderH3LoraSlot === 'function') { try { renderH3LoraSlot(); } catch (_) {} }}+// H3-10: import results used to be native alert()s for every outcome — the+// file-type guard, success, AND failure — which blocks the whole tab and+// reads as a browser error rather than the panel's own UI. A file trained+// for LTX (diffusers/PEFT layout, the file people most often try here by+// mistake) got the raw "PEFT's alpha/rank" engineering explanation with no+// pointer to what to do about it. Toasts now carry every outcome, and the+// diffusers-layout refusal gets its own plain-language line.+function _h3ImportIsLtxLora(message) {+ return /diffusers layout/i.test(String(message || ''));+}async function importH3Lora(file) {if (!file) return;if (!/\.safetensors$/i.test(file.name || '')) {- alert('Choose a .safetensors Hailuo H3 LoRA file.');+ phosToast('Choose a .safetensors Hailuo H3 LoRA file.',+ { icon: 'ph-warning-fill', duration: 4000 });return;}const btn = document.getElementById('h3LoraImportBtn');@@ -174,9 +185,22 @@ async function importH3Lora(file) {const strength = (typeof data.recommended_strength === 'number'&& Math.abs(data.recommended_strength - 1) > 1e-6)? ` Recommended strength ${Number(data.recommended_strength.toFixed(4))}.` : '';- alert(`Imported ${data.filename} (${pairs}).${converted}${strength}`);+ phosToast(`Imported ${data.filename} (${pairs}).${converted}${strength}`,+ { kind: 'success', duration: 6000 });} catch (e) {- alert(`H3 LoRA import failed: ${e.message || e}`);+ const msg = e.message || String(e);+ if (_h3ImportIsLtxLora(msg)) {+ // Name what the user actually did wrong, not the engineering reason+ // for the refusal — "PEFT's alpha/rank is not in the file" answers a+ // question nobody but us asked.+ phosToast("This looks like an LTX LoRA, not an H3 one — its layout "+ + "only exists in LTX/diffusers exports. Move the file into "+ + "mlx_models/loras/ to use it on LTX instead; it can't run "+ + "on H3.", { icon: 'ph-warning-fill', kind: 'danger', duration: 9000 });+ } else {+ phosToast(`H3 LoRA import failed: ${msg}`,+ { icon: 'ph-warning-fill', kind: 'danger', duration: 9000 });+ }} finally {if (btn) { btn.disabled = false; btn.innerHTML = original || 'Import'; }}@@ -321,12 +345,17 @@ function addLoraToActive(entry) {}renderLorasList();_serializeLoras();+ // H3-08: the closed Shot-setup summary names the active LoRA count — it+ // has to hear about every activation, not just the ones that happen to+ // route through a full form re-render.+ if (typeof updateCustomizeSummary === 'function') { try { updateCustomizeSummary(); } catch (e) {} }}function removeLoraFromActive(path) {_activeLoras = _activeLoras.filter(l => l.path !== path);renderLorasList();_serializeLoras();+ if (typeof updateCustomizeSummary === 'function') { try { updateCustomizeSummary(); } catch (e) {} }}function setLoraStrength(path, strength) {@@ -707,6 +736,14 @@ function renderLorasList() {// wins — the empty state below tells the user where to install// image LoRAs from instead.}+ // H3-09: the header summary used to count allRows.length here — every+ // LoRA in BOTH libraries, LTX and H3 combined — so an H3 install with 4+ // H3-compatible adapters and 16 LTX ones read "20 installed". Capture the+ // MODE-FILTERED count now, before the text search narrows `rows` further,+ // so the summary can say what's actually usable on the active engine.+ const modeFilteredCount = rows.length;+ const modeFilteredActiveRows = rows.filter(r => r.active);+ const modeFilteredActive = modeFilteredActiveRows.length;// Surface the filter input only when 5+ LoRAs (post-mode-filter)// remain; below that it's just visual noise.if (filterRow) filterRow.style.display = (rows.length >= 5) ? '' : 'none';@@ -736,19 +773,63 @@ function renderLorasList() {if (banner) {let bannerHtml = `Library filter: <strong>${escapeHtml(_loraFilterLabel(modeTag))}</strong>`;if (hiddenCount > 0) {- bannerHtml += ` · <a href="#" style="color:var(--muted)" onclick="event.preventDefault(); window._loraShowOtherModes = true; renderLorasList()">Show ${hiddenCount} from other modes</a>`;+ // H3-09: on H3 specifically, name what's hidden and say WHY it won't+ // help — "other modes" reads as "somewhere in this app", not "16 LTX+ // LoRAs, a different engine's library, that can never load here".+ const hiddenLabel = (modeTag === 'video:h3')+ ? `${hiddenCount} LTX LoRAs (won't load on H3)`+ : `${hiddenCount} from other modes`;+ bannerHtml += ` · <a href="#" style="color:var(--muted)" onclick="event.preventDefault(); window._loraShowOtherModes = true; renderLorasList()">Show ${hiddenLabel}</a>`;} else if (showOtherModes) {bannerHtml += ` · <a href="#" style="color:var(--muted)" onclick="event.preventDefault(); window._loraShowOtherModes = false; renderLorasList()">Hide other modes</a>`;}banner.innerHTML = bannerHtml;}- // Update header summary.+ // Update header summary. H3-09: counts are MODE-FILTERED (see+ // modeFilteredCount above), not allRows.length — a mixed LTX+H3 library+ // must not print a combined total under either engine's picker. H3 gets+ // its own wording ("N H3 LoRAs") rather than the generic "N installed",+ // since "installed" invited exactly the "20 installed" misreading.const summary = document.getElementById('lorasSummaryCount');if (summary) {- const total = allRows.length;- const active = allRows.filter(r => r.active).length;- summary.textContent = `${total} installed · ${active} active${q ? ` · ${rows.length} match` : ''}`;+ const unit = (modeTag === 'video:h3') ? 'H3 LoRAs' : 'installed';+ summary.textContent = `${modeFilteredCount} ${unit} · ${modeFilteredActive} active`+ + (q ? ` · ${rows.length} match` : '');+ }+ // H3-09: the Rescan button's tooltip named mlx_models/loras/ unconditionally+ // — the LTX folder, wrong for the H3 picker, which watches its own+ // directory (_lorasDirs.h3, filled by refreshLoras() from /loras).+ const rescanBtn = document.getElementById('lorasRescanBtn');+ if (rescanBtn) {+ const dir = (modeTag === 'video:h3')+ ? (_lorasDirs.h3 || "the Hailuo H3 pack's loras/ folder")+ : (_lorasDirs.ltx || 'mlx_models/loras/');+ rescanBtn.title = `Rescan ${dir} for new files`;+ }+ // H3-08: no total-strength warning ever showed for stacked H3 LoRAs — the+ // "keep total near 1.5" advice only rendered inside the single-adapter+ // slot row (renderH3LoraSlot), which is hidden on every runner that+ // stacks (today's default), so three LoRAs at 1.0 each (a real total of+ // 3.0) warned about nothing (shots_h3/h64_lora_three_active.png).+ const totalEl = document.getElementById('lorasStrengthTotal');+ if (totalEl) {+ if (modeFilteredActive >= 2) {+ const total = modeFilteredActiveRows.reduce(+ (sum, r) => sum + Math.abs(Number(r.strength) || 0), 0);+ const level = total > 2.5 ? 'high' : total > 1.5 ? 'mid' : 'ok';+ const color = level === 'high' ? 'var(--danger,#f85149)'+ : level === 'mid' ? 'var(--warn,#e8b341)' : 'var(--muted)';+ const stackNote = (modeTag === 'video:h3')+ ? ' — H3 stacks every active LoRA into one render'+ : '';+ totalEl.hidden = false;+ totalEl.style.color = color;+ totalEl.textContent = `Combined strength: ${total.toFixed(2)}${stackNote}`+ + (level !== 'ok' ? ' — keep the total near 1.5 for a clean result.' : '.');+ } else {+ totalEl.hidden = true;+ }}if (rows.length === 0) {@@ -805,6 +886,16 @@ function renderLorasList() {// modeTag is the active engine compat tag (e.g. "image:qwen") — used to// render the per-chip warning when an ACTIVE LoRA doesn't fit the// current engine, and a `?` indicator for unclassified LoRAs.+// Stable per-path id for a LoRA row's ⋯ popover (VC-42) — a simple string+// hash, not cryptographic, just enough that two different paths in the+// same render pass get two different DOM ids.+function _loraRowKebabId(path) {+ let h = 0;+ const s = String(path || '');+ for (let i = 0; i < s.length; i++) { h = (h * 31 + s.charCodeAt(i)) | 0; }+ return 'loraMore' + (h >>> 0);+}+function loraRowHtml(r, modeTag) {const pathHtml = escapeHtml(r.path);const pathAttr = JSON.stringify(r.path).replace(/"/g, '"');@@ -832,6 +923,15 @@ function loraRowHtml(r, modeTag) {if (r.layout_ok === false) {familyBadges.push(`<span class="badge" style="background:rgba(248,81,73,0.15);color:var(--danger,#f85149)" title="${escapeHtml(r.layout_reason || 'This LoRA is in a key layout the H3 runner cannot read.')}"><svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg></span>`);}+ // H3-33: a real H3 LoRA can carry "LTX 2.3" in its OWN display name — the+ // string comes from wherever it was downloaded (e.g. a CivitAI listing+ // title written before the file was adapted for H3) and the panel has no+ // business silently rewriting a user's LoRA name. Add a small, honest+ // lane badge instead, only where the name could actually mislead —+ // an H3-lane row whose name mentions LTX.+ if (r.lane === 'h3' && /\bltx\b/i.test(r.name || '')) {+ familyBadges.push(`<span class="badge" title="This is an H3 LoRA — its own display name mentions LTX, but it lives in the H3 library and only loads on H3.">H3</span>`);+ }// Trigger summary line under the name (when not expanded). Truncated.const trigs = r.trigger_words || [];const trigSummary = trigs.length@@ -857,8 +957,26 @@ function loraRowHtml(r, modeTag) {corner.push(`<a class="lora-icon-btn" href="${escapeHtml(r.civitai_url)}" target="_blank" rel="noopener" title="Open on CivitAI" onclick="event.stopPropagation()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-square-out"/></svg></a>`);}if (r.kind === 'user' || r.kind === 'trained') {- corner.push(`<button class="lora-icon-btn danger" type="button" title="Delete from disk"- onclick="event.stopPropagation(); deleteLora(${pathAttr}, ${nameAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`);+ // VC-42: a bare danger X sat right next to Rename/Download in the same+ // icon row — one fat-finger away from a permanent delete. Moved behind+ // a ⋯ menu so it takes two deliberate clicks (open the menu, then the+ // item) before the existing confirm() even shows. kebabToggle/.kebab-pop+ // are the shared popover component (also used by the clip toolbar's+ // "More" menu) — id is derived from the path so every row's popover is+ // independently addressable.+ const kid = _loraRowKebabId(r.path);+ corner.push(`<div class="kebab-wrap" onclick="event.stopPropagation()">+ <button class="lora-icon-btn" type="button" title="More" aria-haspopup="true"+ onclick="kebabToggle('${kid}')">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <circle cx="3" cy="8" r="1.4" fill="currentColor"/><circle cx="8" cy="8" r="1.4" fill="currentColor"/><circle cx="13" cy="8" r="1.4" fill="currentColor"/>+ </svg>+ </button>+ <div class="kebab-pop" id="${kid}" role="menu">+ <button type="button" role="menuitem" class="danger"+ onclick="kebabToggle('${kid}', false); deleteLora(${pathAttr}, ${nameAttr})">Delete from disk</button>+ </div>+ </div>`);} else {corner.push(`<button class="lora-icon-btn" type="button" title="Remove from active set"onclick="event.stopPropagation(); removeLoraFromActive(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`);diff --git a/webapp/js/main.js b/webapp/js/main.jsindex 7313b3e..ec241e5 100644--- a/webapp/js/main.js+++ b/webapp/js/main.js@@ -7,8 +7,46 @@// every module has evaluated — which 'last module tag' provides. Any// future 'call this once at startup' line belongs HERE, not at the top// level of a feature module.+// SYS-25: finishes the mode-bar tab semantics the workflow-tabs nav+// already has (SYS-25 partial, this pass). role=tab on every chip, and a+// MutationObserver keeps aria-selected in step with the existing .active+// class toggle -- WITHOUT touching the ~6 places that set .active+// (boot.js's setMode/applyTierGates, characters.js's renderCharacterStrip,+// engines.js's setEngine, settings.js's tier-gate pass), several of which+// are other packages' territory in this same mega-ship pass. A screen+// reader had no way to know this was a tab strip or which mode was active.+function _wireModeGroupTabSemantics() {+ const group = document.getElementById('modeGroup');+ if (!group) return;+ const sync = (btn) => btn.setAttribute('aria-selected', btn.classList.contains('active') ? 'true' : 'false');+ group.querySelectorAll('.mode-chip').forEach(btn => {+ btn.setAttribute('role', 'tab');+ sync(btn);+ });+ new MutationObserver((muts) => {+ muts.forEach(m => { if (m.target.classList.contains('mode-chip')) sync(m.target); });+ }).observe(group, { attributes: true, attributeFilter: ['class'], subtree: true });+}+// ====== Init ======musicInit();+_wireModeGroupTabSemantics();+// VC-34: the Tier quick-link next to the Quality label. Tier is fixed at+// boot (RAM doesn't change at runtime), so this is a one-time read of the+// bootstrap payload — no reason to wait for the first /status poll.+(() => {+ const el = document.getElementById('qualityTierLinkLabel');+ if (el && BOOT.tier && BOOT.tier.label) el.textContent = BOOT.tier.label;+})();+// VC-16: the Enhance tooltip hardcoded "LTX 2.3 was trained on" — this+// panel has served LTX 2.5 as the default generation since v4.0.0. Also+// fixed at boot: the active generation doesn't change without a restart.+(() => {+ const btn = document.getElementById('enhanceBtn');+ if (!btn) return;+ const gen = ((BOOT.ltx || {}).generation === 'ltx23') ? '2.3' : '2.5';+ btn.title = `Use Gemma to rewrite your prompt in the style LTX ${gen} was trained on`;+})();// Skip poll when the tab is backgrounded — at 1.5s cadence with a fan-// spinning render in the background, every saved request matters. Pinokio// users park the panel in a tab and switch to other apps for the 5–20 min@@ -24,7 +62,7 @@ document.addEventListener('visibilitychange', () => { if (!document.hidden) poll// click that landed mid-rewrite could be lost. A single delegated// listener on document survives every rewrite + costs nothing.document.addEventListener('click', (e) => {- const btn = e.target.closest('[data-action="retry"], [data-action="dismiss"], [data-action="stop-early"], [data-action="resume"]');+ const btn = e.target.closest('[data-action="retry"], [data-action="retry-smaller"], [data-action="dismiss"], [data-action="stop-early"], [data-action="resume"]');if (!btn) return;e.stopPropagation();e.preventDefault();@@ -38,17 +76,40 @@ document.addEventListener('click', (e) => {if (!id) return;if (btn.dataset.action === 'retry') {if (typeof retryJob === 'function') retryJob(id);+ } else if (btn.dataset.action === 'retry-smaller') {+ // SYS-07 / VC-08: "Retry smaller" for the GPU-watchdog / OOM failure+ // classes — re-queues one quality rung down at a scaled canvas + roughly+ // half the length, instead of the identical job that just died.+ if (typeof retryJob === 'function') retryJob(id, { smaller: true });} else {window._dismissedFailureId = id;if (typeof poll === 'function') poll();}});+// VA-17 / H3-11 — the One Shot recovery bar's two buttons. Delegated for+// the same reason as the block above: poll() can repaint the bar (or hide+// it) between a click landing and its handler running.+document.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-action="take-resume"], [data-action="take-join-partial"]');+ if (!btn) return;+ e.preventDefault();+ const bar = document.getElementById('oneShotRecoveryBar');+ const path = bar ? bar.dataset.path : '';+ if (!path) return;+ if (btn.dataset.action === 'take-resume' && typeof takeResumeFromPath === 'function') {+ takeResumeFromPath(path);+ } else if (btn.dataset.action === 'take-join-partial' && typeof takeJoinPartialFromPath === 'function') {+ takeJoinPartialFromPath(path);+ }+});+poll();setMode('t2v');setAspect('landscape'); // sets aspect first so the default preset orients correctlysetQuality('balanced'); // bundles quality + dims; respects current aspectapplyTierTimes(); // no-op for LTX since v4.0 — the tier table owns those subtitles+if (typeof applyExtendPillPrices === 'function') applyExtendPillPrices(); // VA-12renderCharacterStrip(); // the generation-scoped character quality ladder// Engine picker — re-apply the last-used engine after the boot sequence above// has settled the mode. setEngine() re-runs every gate (capable / installed /@@ -63,6 +124,13 @@ renderCharacterStrip(); // the generation-scoped character quality laddeupdateCustomizeSummary();updateDerived();+// VC-38: restore a saved draft AFTER the hardcoded t2v/landscape/balanced+// defaults above so it can actually override them, BEFORE anything else+// below touches the form. Autosave wiring runs regardless of whether a+// draft existed to restore — the point is that the NEXT reload has one.+if (typeof restoreDraftOnBoot === 'function') { try { restoreDraftOnBoot(); } catch (e) {} }+if (typeof draftAutosaveInstall === 'function') { try { draftAutosaveInstall(); } catch (e) {} }+// Wire the picker components (I2V image + FFLF start/end) and seed the// "Recent uploads" strip. The strip is shared across all three pickers,// so dropping a new image in one slot makes it instantly clickable indiff --git a/webapp/js/music.js b/webapp/js/music.jsindex b71f1e3..d4ec165 100644--- a/webapp/js/music.js+++ b/webapp/js/music.js@@ -22,7 +22,14 @@ function _say(msg) { const el = _el('songStatus'); if (el) el.textContent = msgasync function songCardRender(o) {const card = _el('songCard');if (!card) return;- const isSong = o && o.kind === 'audio' && o.engine === 'music';+ // VC-20: the Song card (New take / Re-roll the sound / Cover it / Sheet+ // music...) is Music Studio's own surface. selectOutput() runs this for+ // EVERY selection, including a song reached by filtering the Video tab's+ // own gallery to Audio — which used to fill the Video tab's player pane+ // with the Music tab's controls. Only the Audio tab itself gets the full+ // card; everywhere else a song is just another gallery entry.+ const onAudioTab = document.body.dataset.workflow === 'audio';+ const isSong = o && o.kind === 'audio' && o.engine === 'music' && onAudioTab;card.hidden = !isSong;// THE PREVIOUS SONG IS GONE THE MOMENT ANOTHER IS PICKED (M6-02). SONG// used to keep the last song until the new one's score arrived, so an@@ -68,7 +75,16 @@ async function songCardRender(o) {}function _songNameFromFile(name) {- return String(name || '').replace(/\.wav$/i, '').replace(/^music_\d{8}_\d{6}_/, '').replace(/_/g, ' ');+ // FILM-43: only .wav was stripped here, so a dropped .mp3/.m4a/.flac (or+ // a raw upload, which used file.name directly and skipped this function+ // entirely) kept its extension as the board's title forever ("song40.wav").+ // 4.17: also the upload route's millisecond prefix ("1790123456789_…"),+ // which a raw upload's path carries. Server mirror: routes_music.py+ // _board_title_from_song.+ return String(name || '').split('/').pop()+ .replace(/\.(wav|mp3|m4a|flac|aac|ogg|opus|aiff?)$/i, '')+ .replace(/^\d{10,}_/, '')+ .replace(/^music_\d{8}_\d{6}_/, '').replace(/_/g, ' ').trim();}// The gallery block carries `loras: [{name, strength}]`; /music/score answers@@ -254,6 +270,16 @@ function musicOpenSong(path) {if (typeof selectOutput === 'function') selectOutput(path);}+// VC-20: the "Open in Audio tab" link on a song reached from another tab's+// filtered gallery (e.g. Video -> Outputs -> Audio). Switches workflow+// FIRST so songCardRender()/selectOutput()'s onAudioTab check sees the+// audio tab already active and renders the full Music Studio surface,+// then selects the song there.+function openSongInAudioTab(path) {+ if (typeof workflowSwitch === 'function') workflowSwitch('audio');+ if (typeof selectOutput === 'function') selectOutput(path);+}+// ---- the score editor ------------------------------------------------------function musicScoreEditToggle(on) {@@ -742,6 +768,7 @@ function _watchScoreJob(id) {Object.assign(globalThis, {songCardRender, musicVariation, musicRestyleFromSong, musicCoverFromSong, musicOpenSong,+ openSongInAudioTab,musicSongAction,musicScoreEditToggle, musicScorePreview, musicRenderEditedScore, musicScoreCopy,musicTaskSet, musicTaskPick, musicWriteLyrics, musicTranscribe,@@ -1048,6 +1075,43 @@ const MV = { song: null, songName: '', songSeconds: null, cast: [], busy: false,function mvSay(msg) { const el = _el('mvStatus'); if (el) el.textContent = msg || ''; }+// 4.17: THE BRIEF SURVIVES A RELOAD. The song, the pictures and their roles+// (and the board they last planned) used to live only in this object, so a+// reload — or the restart every Update asks for — emptied the pane and the+// user re-uploaded every picture. A per-browser draft (localStorage, same+// shape as the Video tab's VC-38 draft), written on every change, read once+// on the first mvInit. Every access is guarded: blocked storage degrades to+// "no draft", never to a broken pane.+const MV_DRAFT_KEY = 'phos_mv_draft_v1';+let _mvDraftRestored = false;+function mvSaveDraft() {+ try {+ const d = { song: MV.song, songName: MV.songName, songSeconds: MV.songSeconds,+ boardId: MV.boardId,+ cast: MV.cast.map(c => ({ path: c.path, name: c.name,+ role: c.role || '', prompt: c.prompt || '' })) };+ if (!d.song && !d.cast.length) localStorage.removeItem(MV_DRAFT_KEY);+ else localStorage.setItem(MV_DRAFT_KEY, JSON.stringify(d));+ } catch (e) { /* private window / blocked storage: no draft */ }+}+function mvRestoreDraft() {+ if (_mvDraftRestored) return;+ _mvDraftRestored = true;+ if (MV.song || MV.cast.length) return; // never over live work+ let d = null;+ try { d = JSON.parse(localStorage.getItem(MV_DRAFT_KEY) || 'null'); } catch (e) { d = null; }+ if (!d || typeof d !== 'object') return;+ MV.song = (typeof d.song === 'string' && d.song) ? d.song : null;+ MV.songName = String(d.songName || '');+ MV.songSeconds = (d.songSeconds != null && isFinite(Number(d.songSeconds))) ? Number(d.songSeconds) : null;+ MV.boardId = String(d.boardId || '');+ MV.cast = Array.isArray(d.cast)+ ? d.cast.filter(c => c && typeof c.path === 'string' && c.path)+ .map(c => ({ path: c.path, name: String(c.name || ''),+ role: String(c.role || ''), prompt: String(c.prompt || '') }))+ : [];+}+function mvInit() {const drop = _el('mvImagesDrop');const file = _el('mvImagesFile');@@ -1076,6 +1140,7 @@ function mvInit() {});song.addEventListener('change', () => { if (song.files[0]) mvUploadSong(song.files[0]); });}+ mvRestoreDraft();mvRenderSong();mvRenderCast();mvFillLibrary();@@ -1087,8 +1152,15 @@ function mvInit() {function mvFillLibrary() {const sel = _el('mvSongLibrary');if (!sel) return;+ // FILM-44: this used to list only songs COMPOSED in-app (engine ===+ // 'music') — any audio the user already had (dropped into uploads,+ // rendered somewhere else, a client's raw track) never appeared, so+ // "pick one from the library" was a lie unless you had written it here+ // first. Every audio file the gallery knows about is a candidate now;+ // a composed song still leads with its real title, an uploaded file+ // with its (extension-stripped) filename.const songs = (typeof currentOutputs !== 'undefined' && currentOutputs || [])- .filter(o => o && o.kind === 'audio' && o.engine === 'music');+ .filter(o => o && o.kind === 'audio');const keep = sel.value;sel.innerHTML = songs.length? '<option value="">Pick one…</option>' + songs.map(o => {@@ -1096,7 +1168,7 @@ function mvFillLibrary() {const label = m.title || _songNameFromFile(o.name) || o.name;return `<option value="${_esc(o.path)}">${_esc(label)}</option>`;}).join('')- : '<option value="">Nothing composed yet</option>';+ : '<option value="">No audio in outputs or uploads yet</option>';if (keep && songs.some(o => o.path === keep)) sel.value = keep;}@@ -1105,7 +1177,7 @@ function mvPickFromLibrary(path) {const o = (typeof currentOutputs !== 'undefined' && currentOutputs || []).find(x => x && x.path === path);MV.song = path;- MV.songName = (o && ((o.music || {}).title || _songNameFromFile(o.name))) || path.split('/').pop();+ MV.songName = (o && ((o.music || {}).title || _songNameFromFile(o.name))) || _songNameFromFile(path);MV.songSeconds = (o && (o.clip_sec != null ? Number(o.clip_sec) : null));mvRenderSong();mvSay('');@@ -1120,7 +1192,7 @@ async function mvUploadSong(file) {const data = await r.json();if (!r.ok || data.error) throw new Error(data.error || ('HTTP ' + r.status));MV.song = data.path;- MV.songName = file.name;+ MV.songName = _songNameFromFile(file.name);MV.songSeconds = (data.duration_sec != null) ? Number(data.duration_sec) : null;const sel = _el('mvSongLibrary'); if (sel) sel.value = '';mvRenderSong();@@ -1132,11 +1204,16 @@ async function mvUploadSong(file) {function mvClearSong() {MV.song = null; MV.songName = ''; MV.songSeconds = null;+ // FILM-43: a cleared song is a genuinely new session — the next Plan+ // must mint its own board, not silently overwrite whatever this pane+ // planned before.+ MV.boardId = '';const sel = _el('mvSongLibrary'); if (sel) sel.value = '';mvRenderSong();}function mvRenderSong() {+ mvSaveDraft();const slot = _el('mvSongSlot');if (!slot) return;if (!MV.song) {@@ -1169,9 +1246,14 @@ async function mvAddPictures(files) {if (!r.ok || data.error) throw new Error(data.error || ('HTTP ' + r.status));// The FIRST picture is the singer unless the user says otherwise: a cast// with no face plans as B-roll only, and arriving at that by default- // would read as the feature not working.+ // would read as the feature not working. FILM-12: every picture AFTER+ // that used to default to Room with no evidence at all — a photo of a+ // guitar or a piano silently mislabelled "the wide, the lights, the+ // audience" and rendered with that prompt. There is no vision check+ // here, so guessing wrong is worse than asking: left unset, and+ // mvPlan() refuses to plan until every picture has a role.MV.cast.push({ path: data.path, name: f.name,- role: MV.cast.length === 0 ? 'singer' : 'room', prompt: '' });+ role: MV.cast.length === 0 ? 'singer' : '', prompt: '' });} catch (e) {mvSay(`Could not add ${f.name}: ` + (e.message || e));mvRenderCast();@@ -1190,6 +1272,7 @@ function mvSetRole(i, role) {function mvSetPrompt(i, text) {if (MV.cast[i]) MV.cast[i].prompt = String(text || '');+ mvSaveDraft();}function mvRemovePicture(i) {@@ -1204,10 +1287,11 @@ const MV_ROLES = [];function mvRenderCast() {+ mvSaveDraft();const box = _el('mvCast');if (!box) return;box.innerHTML = MV.cast.map((im, i) => `- <div class="mv-pic">+ <div class="mv-pic${im.role ? '' : ' needs-role'}"><img class="mv-pic-thumb" src="/image?path=${encodeURIComponent(im.path)}&w=160" alt=""><div class="mv-pic-body"><div class="mv-pic-name" title="${_esc(im.path)}">${_esc(im.name || im.path.split('/').pop())}</div>@@ -1216,6 +1300,7 @@ function mvRenderCast() {<button type="button" class="pill-btn${im.role === key ? ' active' : ''}"data-i="${i}" data-role="${key}" title="${_esc(tip)}">${label}</button>`).join('')}</div>+ ${im.role ? '' : '<div class="hint mv-pic-warn">Pick a role — nothing is guessed for you.</div>'}<input type="text" class="mv-pic-prompt" data-i="${i}"placeholder="Optional — what happens in this shot"value="${_esc(im.prompt || '')}">@@ -1241,10 +1326,41 @@ function mvRenderCast() {}}+// FILM-12: the classifier can plan a real vocal track as all-instrumental —+// "0 singing shots" with a Singer picture cast. The server refuses that one+// case (409, no_vocal_detected) instead of silently shipping it, and hands+// back the phrases it looked at so the user can mark which ones are sung.+// `MV.pendingSections` holds that list, editable, between the refusal and a+// deliberate re-submit — either "Plan with these sections" or "Plan as+// B-roll only" (which just sets plan_anyway and bypasses the check).+Object.assign(MV, { pendingSections: null });+async function mvPlan() {if (MV.busy) return;if (!MV.song) { mvSay('Pick a song first.'); return; }if (!MV.cast.length) { mvSay('Drop at least one picture.'); return; }+ // FILM-12: a picture with no role picked is one nobody has told the+ // planner what to do with — mvAddPictures() no longer guesses "Room" for+ // it, so pressing Plan on an unlabelled cast asks instead of misfiring.+ if (MV.cast.some(c => !c.role)) {+ mvSay('Pick a role for every picture — Singer, Instrument or Room.');+ mvRenderCast();+ return;+ }+ await _mvPlanRequest({});+}++async function mvPlanWithSections() {+ if (!MV.pendingSections) return;+ await _mvPlanRequest({ sections: MV.pendingSections });+}++async function mvPlanAnyway() {+ await _mvPlanRequest({ planAnyway: true });+}++async function _mvPlanRequest(opts) {+ if (MV.busy) return;const btn = _el('mvPlanBtn');MV.busy = true;if (btn) { btn.disabled = true; btn.textContent = 'Reading the song…'; }@@ -1256,10 +1372,28 @@ async function mvPlan() {path: c.path, role: c.role, prompt: c.prompt || '' }))));fd.set('style', (_el('mvStyle') || {}).value || '');fd.set('title', MV.songName || 'Music video');+ if (opts.sections) fd.set('sections', JSON.stringify(opts.sections));+ if (opts.planAnyway) fd.set('plan_anyway', '1');+ // FILM-43: re-planning inside the SAME session (marking sections,+ // adjusting the cast, pressing Plan again) updates the board this pane+ // already made instead of minting an identically-named duplicate of+ // it. Cleared by mvClearSong() so a genuinely new song still gets its+ // own board.+ if (MV.boardId) fd.set('board_id', MV.boardId);const r = await fetch('/music/video/plan', { method: 'POST', body: fd });const data = await r.json();+ if (data && data.no_vocal_detected) {+ MV.pendingSections = data.sections || [];+ mvRenderSections();+ mvSay(data.error || 'I heard no singing in this track — mark the sung parts below.');+ return;+ }+ // BOARD-1: the board is rendering — the plan was refused, nothing changed.+ if (data && data.busy) { mvSay(data.error); return; }if (!r.ok || data.error) throw new Error(data.error || ('HTTP ' + r.status));+ mvSectionsHide();MV.boardId = data.board_id;+ mvSaveDraft();mvSay(data.summary + (data.notes && data.notes.length ? ' — ' + data.notes.join(' ') : ''));const chip = _el('mvSummary'); if (chip) chip.textContent = data.summary;if (typeof phosToast === 'function') phosToast(data.summary, { kind: 'success' });@@ -1275,8 +1409,54 @@ async function mvPlan() {}}+function mvSectionsHide() {+ MV.pendingSections = null;+ const box = _el('mvSections');+ if (box) { box.hidden = true; box.innerHTML = ''; }+}++function _mvClock(sec) {+ const s = Math.max(0, Math.round(Number(sec) || 0));+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;+}++// One chip per phrase the classifier looked at. Click toggles vocal <->+// instrumental; the edited list is exactly what gets sent back as `sections`+// on "Plan with these sections", which skips the classifier entirely+// (given_sections() takes the caller's word for it).+function mvRenderSections() {+ const box = _el('mvSections');+ if (!box || !MV.pendingSections) return;+ box.hidden = false;+ box.innerHTML = '<div class="hint" style="margin-bottom:6px;">'+ + 'Click a phrase to mark it sung or instrumental, then plan again:</div>'+ + '<div class="mv-section-chips">'+ + MV.pendingSections.map((s, i) => {+ const vocal = String(s.kind || '').toLowerCase() === 'vocal';+ return `<button type="button" class="pill-btn mv-section-chip${vocal ? ' active' : ''}" data-i="${i}"+ title="${_esc(s.name || '')}: ${_mvClock(s.start)}–${_mvClock(s.end)}">+ ${_mvClock(s.start)}–${_mvClock(s.end)} · ${vocal ? 'Sung' : 'Instrumental'}+ </button>`;+ }).join('')+ + '</div>'+ + '<div class="actions" style="margin-top:8px;">'+ + '<button type="button" class="primary" onclick="mvPlanWithSections()">Plan with these sections</button>'+ + '<button type="button" onclick="mvPlanAnyway()">Plan as B-roll only</button>'+ + '</div>';+ box.querySelectorAll('.mv-section-chip').forEach(b =>+ b.addEventListener('click', () => mvToggleSection(+b.dataset.i)));+}++function mvToggleSection(i) {+ const s = MV.pendingSections && MV.pendingSections[i];+ if (!s) return;+ s.kind = String(s.kind || '').toLowerCase() === 'vocal' ? 'instrumental' : 'vocal';+ mvRenderSections();+}+Object.assign(globalThis, {renderSongList, songHero, songCoverStyle, musicMenuOpen, musicMenuClose,musicBarShow, musicBarToggle, musicBarTogglePlay, musicBarStep, musicBarSeek, musicBarInit,- mvInit, mvPlan, mvPickFromLibrary, mvClearSong, mvFillLibrary,+ mvInit, mvPlan, mvPlanWithSections, mvPlanAnyway, mvToggleSection,+ mvPickFromLibrary, mvClearSong, mvFillLibrary,});diff --git a/webapp/js/oneshot.js b/webapp/js/oneshot.jsindex 98d0f81..f8f6b17 100644--- a/webapp/js/oneshot.js+++ b/webapp/js/oneshot.js@@ -10,9 +10,29 @@//// Publish block at the bottom: what the page and the other modules call.+// VA-15: 60 s (~28 min at 6 parts) used to be the default a first-time user+// hit on typing a paragraph and pressing Generate, with no price shown+// anywhere near the button. 30 s (3 parts, ~15 min) is the owner's own+// sample length (ltx_oneshot_aliens...) and about half the commitment.+const OS_SECONDS_LS_KEY = 'phos_oneshot_seconds';+function _osStoredSeconds() {+ try {+ const v = parseInt(localStorage.getItem(OS_SECONDS_LS_KEY) || '', 10);+ return OS_SECONDS.includes(v) ? v : 30;+ } catch (e) { return 30; }+}+// The browser's remembered length, applied ONCE per page — on first wire, or+// earlier when Load Params opens a saved take first (LIPSYNC-8: osWire used to+// apply it AFTER oneshotOpenFromParams had restored the take's own length, so+// a 90 s take reopened on first visit came back as 30 s).+function _osApplyStoredPrefs() {+ if (OS.prefsApplied) return;+ OS.prefsApplied = true;+ OS.seconds = _osStoredSeconds();+}const OS = {engine: 'ltx',- seconds: 60,+ seconds: 30,quality: { ltx: 'balanced', h3: 'standard', character: 'pro' },character: '',image: '',@@ -26,7 +46,9 @@ const OS = {statusTimer: null,estimateSeq: 0,wired: false,+ prefsApplied: false, // _osApplyStoredPrefs ran (stored length never overrides a restored take)lastSubmitted: null,+ lastEta: '', // VA-15: bare "N min" from the last /oneshot/estimate, for the footer};const OS_SECONDS = [30, 45, 60, 90, 120];@@ -274,8 +296,13 @@ function osRenderSummary() {const who = (OS.engine === 'ltx' && OS.character)? (((OS.options || {}).characters || []).find(c => c.id === OS.character) || {}).name || OS.character: '';+ // VA-15: the price used to live only in the composer card above (#osEstimate),+ // out of sight once the user scrolls to Generate. The footer next to the+ // button now carries it too, so nobody commits to a render without seeing+ // the time right beside the button that starts it.+ const priceBit = OS.lastEta ? ` · about ${OS.lastEta}` : '';el.innerHTML = `<strong>${osLengthLabel(OS.seconds)}</strong> · ${osPartsText(OS.seconds)}`- + ` · ${OS.engine === 'h3' ? 'Hailuo H3' : 'LTX 2.5'}${who ? ` · ${osEsc(who)}` : ''}`;+ + ` · ${OS.engine === 'h3' ? 'Hailuo H3' : 'LTX 2.5'}${who ? ` · ${osEsc(who)}` : ''}${priceBit}`;}function osRenderAll() {osRenderEngine(); osRenderLengths(); osRenderQualities(); osRenderCharacters();@@ -300,6 +327,7 @@ function osSetSeconds(s) {s = parseInt(s, 10);if (!OS_SECONDS.includes(s)) return;OS.seconds = s;+ try { localStorage.setItem(OS_SECONDS_LS_KEY, String(s)); } catch (e) {}osRenderLengths(); osRenderBeats(); osBeatsInput(); osRenderSummary(); osEstimate();}function osSetQuality(q) {@@ -320,6 +348,9 @@ function osToggle(name, value) {else if (name === 'retake') OS.retake = value === 'off' ? 'off' : 'on';else if (name === 'handoff') { OS.handoff = value === 'speech' ? 'speech' : 'last'; OS.handoffTouched = true; }osRenderToggles();+ // Retake changes whether the "up to ~X if parts are redone" ceiling shows+ // at all — the price shown must follow the switch, not the last fetch.+ if (name === 'retake') { osEstimate(); }}function osSplitPrompt() {const prompt = String((osEl('osPrompt') || {}).value || '');@@ -359,9 +390,20 @@ async function osEstimate() {const d = await r.json();if (seq !== OS.estimateSeq) return;if (!d.ok) { el.textContent = d.error || ''; return; }+ const bareEta = d.eta ? String(d.eta).replace(/^~\s*/, '').split(' · ')[0] : '';+ OS.lastEta = bareEta;+ // VA-16: the base price only ever showed the best case. Each part can+ // ALSO get one light-drift retake and, if it's spoken, up to+ // TAKE_LIPSYNC_RETAKES lip-sync retakes — up to ~4x the base render in+ // the worst case. eta_worst is a mechanism-derived CEILING (not a+ // measured rate), labeled "up to" so it reads as a bound, not a promise.+ const worstBit = (OS.retake === 'on' && d.eta_worst)+ ? ` · up to ${String(d.eta_worst).replace(/^~\s*/, '')} if parts are redone`+ : '';el.textContent = `${osLengthLabel(d.seconds)} · ${osPartsText(d.seconds)}`- + (d.eta ? ` · about ${String(d.eta).replace(/^~\s*/, '').split(' · ')[0]} on this Mac` : '')- + (OS.retake === 'on' ? ' · a part that drifts is rendered once more' : '');+ + (bareEta ? ` · about ${bareEta} on this Mac` : '') + worstBit+ + (OS.retake === 'on' ? ' · a part that drifts or doesn’t sync is rendered again' : '');+ osRenderSummary();} catch (e) {if (seq === OS.estimateSeq) el.textContent = '';}@@ -511,10 +553,11 @@ function oneshotTabLeave() {// document is rebuilt from the take block, and the tab opens on it.function oneshotOpenFromParams(p) {p = p || {};+ _osApplyStoredPrefs();const take = p.take || {};OS.engine = (take.engine || p.engine) === 'h3' ? 'h3' : 'ltx';- const s = parseInt(take.seconds || p.take_seconds || 60, 10);- OS.seconds = OS_SECONDS.includes(s) ? s : 60;+ const s = parseInt(take.seconds || p.take_seconds || 30, 10);+ OS.seconds = OS_SECONDS.includes(s) ? s : 30;OS.character = String(p.character_id || '');OS.image = String(p.image || '');OS.light = take.light_lock === '' ? 'off' : 'on';@@ -528,7 +571,17 @@ function oneshotOpenFromParams(p) {const beats = (take.beats || take.beat_prompts || []);OS.beats = Array.isArray(beats) ? beats.map(b => String(b || '').replace(/\s+Continuity:.*$/, '')) : [];const cam = osEl('osCamera'); if (cam) cam.value = String(take.camera || '');- const seed = osEl('osSeed'); if (seed) seed.value = (p.seed && String(p.seed) !== '-1') ? String(p.seed) : '';+ // VA-28: a random parent seed (-1) drew a fresh random seed per part, and+ // none of them were recorded anywhere — reopening a random-seed take left+ // Seed blank (still random) even though the take's own sidecar now names+ // exactly which seed rendered part 1 (take.parts_meta, run_take_job_inner).+ const seed = osEl('osSeed');+ if (seed) {+ const partsMeta = Array.isArray(take.parts_meta) ? take.parts_meta : [];+ const firstPartSeed = partsMeta[0] && partsMeta[0].seed_used;+ seed.value = (p.seed && String(p.seed) !== '-1') ? String(p.seed)+ : (firstPartSeed != null ? String(firstPartSeed) : '');+ }const label = osEl('osLabel'); if (label) label.value = String(p.preset_label || '');const nm = osEl('osNoMusic'); if (nm) nm.checked = String(p.no_music || '') === 'on';if (typeof workflowSwitch === 'function') workflowSwitch('oneshot');@@ -539,6 +592,10 @@ function oneshotOpenFromParams(p) {function osWire() {if (OS.wired) return;OS.wired = true;+ // VA-15: remember the last length this browser used, once, on first wire —+ // a manual osSetSeconds() later in the same session is never overridden,+ // and neither is a take Load Params restored before the first wire.+ _osApplyStoredPrefs();document.querySelectorAll('#osEngineGroup [data-os-engine]').forEach(b => b.onclick = () => osSetEngine(b.dataset.osEngine));document.querySelectorAll('[data-os-toggle]').forEach(group => {group.querySelectorAll('[data-os-value]').forEach(b => b.onclick = () => osToggle(group.dataset.osToggle, b.dataset.osValue));diff --git a/webapp/js/preview.js b/webapp/js/preview.jsindex d8cf648..dafb18f 100644--- a/webapp/js/preview.js+++ b/webapp/js/preview.js@@ -1740,6 +1740,10 @@ document.addEventListener('DOMContentLoaded', () => {// ⊘ missing (red) — nothing on disk// ↻ downloading (blue, anim) — hf is currently fetching this repofunction openModelsModal() {+ // SYS-19: the health popover's Models row opens this modal too (the+ // real #modelsPill element is relocated into the popover by+ // _hcRelocate) -- same under-the-popover overlap as the Tier modal.+ if (typeof closeHealthPop === 'function') closeHealthPop();document.getElementById('modelsModal').style.display = 'flex';refreshModelsModal();}@@ -1756,7 +1760,23 @@ async function refreshModelsModal({ silent = false } = {}) {if (!silent) hint.textContent = 'Failed to load models. Panel might be restarting — try again.';return;}- const repos = data.repos || [];+ // SYS-17: the modal listed repos in registry order, which put the+ // PREVIOUS-generation LTX-2.3 Q4 first (red border, unmet) and the+ // engine this build actually renders with (LTX-2.5 base) 8th. Sorted+ // client-side into the groups the fix asked for: installed/required+ // for the active generation, then this generation's add-ons, then+ // previous-generation rows last (still shown -- training needs them --+ // just not leading with the one thing that reads as broken on a+ // perfectly healthy install).+ const repos = (data.repos || []).slice().sort((a, b) => {+ const rank = (r) => {+ if (!r.active) return 3; // previous generation+ if (r.kind !== 'optional' && r.complete) return 0; // required, installed+ if (r.complete) return 1; // optional, installed+ return 2; // this generation, not yet fetched+ };+ return rank(a) - rank(b);+ });const active = data.active_download;hint.innerHTML = data.hf_available? `Each row shows what's on disk. Click <b>Download</b> to fetch the missing files; progress streams to the log at the bottom of the page. Everything is resumable and checksum-verified.`@@ -1817,13 +1837,24 @@ async function refreshModelsModal({ silent = false } = {}) {: r.kind === 'optional'? `<span style="color:var(--muted)">optional</span>`: `<span style="color:var(--success,#3fb950)">required</span>`;+ // SYS-42: this row used to lead with "dgrauet/ltx-2.3-mlx-q4 ->+ // mlx_models/ltx-2.3-mlx-q4" — a repo id and a filesystem path, always+ // visible, ahead of the one thing a non-engineer can act on (what this+ // pack unlocks, how big it is, whether it's here). The report's own fix:+ // "one line per pack ... Put the path and repo behind 'Details'." The+ // outcome line now leads; repo_id/local_dir move into a closed+ // <details> that opens the same info for anyone who does want it+ // (debugging a mis-pointed LTX_Q8_LOCAL, filing an issue, etc).return `<li class="${cls}"><span class="icon">${icon}</span><div class="meta"><span class="ttl">${escapeHtml(r.name)} · ${kindBadge}</span>- <span class="sub">${escapeHtml(r.repo_id)} → ${escapeHtml(r.local_dir)}</span><span class="sub">${statusText}${r.blurb ? ' · ' + escapeHtml(r.blurb) : ''}</span>+ <details class="model-row-details">+ <summary>Details</summary>+ <span class="sub">${escapeHtml(r.repo_id)} → ${escapeHtml(r.local_dir)}</span>+ </details></div>${btnHtml}</li>`;diff --git a/webapp/js/queue.js b/webapp/js/queue.jsindex 0c44114..4e51b0d 100644--- a/webapp/js/queue.js+++ b/webapp/js/queue.js@@ -172,6 +172,11 @@ function h3FinishFieldsFromSidecar(p, tierKey) {// verbatim; on t2v it is deliberately empty — H3 ignores it and leaving a// stale path in the picker would misrepresent what was queued.image: (mode === 'i2v' && typeof p.image === 'string') ? p.image : '',+ // The crop framing is part of the recipe (VC-29/H3-01): a face kept by a+ // Top or dragged crop in the draft must be kept in the finish too. Older+ // sidecars predate it — they rendered centred.+ // (Inline, not _cropFocusFromParams: this function stays pure/self-contained.)+ image_crop_focus: ((v) => (isFinite(v) && v >= 0 && v <= 1) ? v : 0.5)(parseFloat(p.image_crop_focus)),};if (mode === 'i2v' && !fields.image) return null;return fields;@@ -204,12 +209,31 @@ function _syncH3FinishAffordance(o) {// its own "·" ("High · 10s"), which is flattened to "High 10s" so the one dot// left separates the shape from its cost.const name = String(target.label).replace(/\s*·\s*/g, ' ').trim();- if (label) label.textContent = `Finish at ${name} · ${target.eta}`;- if (btn) {- btn.title = `Re-render this ${srcTier.quality_label} clip at `- + `${target.label} (${target.spec}, ${target.eta}) — same `- + `${target.length_label} length, same prompt, same seed, same `- + `first frame`;+ // H3-21: this offered "Finish at Standard 5s · ~6 min" on a Mac without H3+ // at all — the tier/target math above is pure client-side registry lookup,+ // no install check anywhere in it. Clicking only raised a toast AFTER the+ // fact ("Finish needs the Hailuo H3 engine"). Say it up front and route+ // the click at the install card instead of a doomed render attempt.+ const h3NotHere = !(H3 && H3.available);+ if (h3NotHere) {+ if (label) label.textContent = 'Finish · needs Hailuo H3';+ if (btn) {+ btn.title = `Finishing this clip needs the Hailuo H3 engine, which `+ + `isn't installed on this Mac. Click for how to set it up.`;+ btn.onclick = (ev) => { ev.preventDefault(); openH3InstallCard(); };+ }+ } else {+ if (label) label.textContent = `Finish at ${name} · ${target.eta}`;+ if (btn) {+ btn.title = `Re-render this ${srcTier.quality_label} clip at `+ + `${target.label} (${target.spec}, ${target.eta}) — same `+ + `${target.length_label} length, same prompt, same seed, same `+ + `first frame`;+ // Restore the normal handler — a prior sync on a different clip (or+ // before H3 finished installing) may have pointed this at the install+ // card instead.+ btn.onclick = () => h3FinishActive();+ }}if (sel) {const opts = h3FinishTargets(srcTier)@@ -303,6 +327,7 @@ async function h3FinishActive() {} else {document.getElementById('image').value = fields.image;}+ if (typeof _setCropFocus === 'function') _setCropFocus('image', fields.image_crop_focus);}if (fields.h3_upscale && typeof setH3Upscale === 'function') setH3Upscale(fields.h3_upscale);// The source's adapters, not whatever the picker holds now (an empty list@@ -329,6 +354,7 @@ async function h3FinishActive() {// Seed after the shape for the same reason it comes last in loadParams:// nothing downstream may quietly re-randomise it.document.getElementById('seed').value = fields.seed;+ if (typeof _syncSeedLockChip === 'function') { try { _syncSeedLockChip(); } catch (e) {} }if (typeof updateCustomizeSummary === 'function') { try { updateCustomizeSummary(); } catch (e) {} }if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }const formPane = document.querySelector('aside.form-pane');@@ -351,6 +377,301 @@ async function h3FinishActive() {form.requestSubmit();}+// ============================================================================+// LTX Draft → Finish (VC-18/37) — the mirror of H3's Finish above, built on+// LTX's own two-axis table (BOOT.ltx.qualities/lengths/tiers, VC-28) instead+// of H3's tier keys. Same instinct, same "SAME LENGTH, HIGHER QUALITY"+// contract, same Load-Params-then-submit mechanism — deliberately NOT a+// generic engine-agnostic abstraction over both: H3's shape carries concepts+// (chain_prompts, orientation, a separate lora_scale_v convention, tristep)+// that don't exist on LTX, and forcing a shared function would either drop+// fields silently or grow a pile of H3-only branches inside what looks like+// one LTX-neutral function. Two short, honest functions beat one long,+// engine-guessing one — same trade the tier-chip factory already made+// differently (there, the per-cell SHAPE really is uniform enough to share).+//+// Scope: t2v/i2v only, matching H3's own Finish restriction (line ~126+// above) — Extend and Keyframe don't carry a "same length, higher quality"+// concept the way a fixed-duration T2V/I2V render does.++function ltxTierByKeyExact(key) {+ if (!key) return null;+ return ((BOOT.ltx || {}).tiers || []).find(t => t.key === key) || null;+}++// The length KEY for a raw frame count — the mirror of ltxCurrentLength()'s+// own lookup, applied to a clip's OWN sidecar frame count instead of the+// live form. null for an off-axis (custom) duration: Finish has nothing to+// offer there, same as it has nothing to offer a length H3's table doesn't+// carry.+function _ltxLengthKeyForFrames(frames) {+ const f = parseInt(String(frames == null ? '' : frames), 10);+ if (!Number.isFinite(f)) return null;+ const hit = ((BOOT.ltx || {}).lengths || []).find(l => Number(l.frames) === f);+ return hit ? hit.key : null;+}++// The cells a clip can be finished at: same length, every quality above the+// one it was rendered at, offered and available on this install.+function ltxFinishTargets(srcCell) {+ if (!srcCell) return [];+ const order = ((BOOT.ltx || {}).qualities || []).map(q => q.key);+ const from = order.indexOf(srcCell.quality);+ if (from < 0) return [];+ return order.slice(from + 1)+ .map(q => ltxCellFor(q, srcCell.length))+ .filter(c => c && c.available !== false);+}++function ltxFinishTierKey(srcCell) {+ const targets = ltxFinishTargets(srcCell);+ if (!targets.length) return null;+ let saved = null;+ try { saved = localStorage.getItem('phos_ltx_finish_quality'); } catch (e) {}+ const hit = saved && targets.find(t => t.quality === saved);+ return (hit || targets[0]).key;+}++function ltxFinishSetTier(key) {+ const cell = ltxTierByKeyExact(key);+ if (!cell) return;+ try { localStorage.setItem('phos_ltx_finish_quality', cell.quality); } catch (e) {}+ _syncFinishAffordance(findOutputByPath(activePath));+}++// PURE — same contract as h3FinishFieldsFromSidecar: given a completed LTX+// render's sidecar params and the tier to finish at, the exact #genForm+// field→value map that reproduces the clip at the new quality, or null when+// the sidecar isn't a finishable LTX t2v/i2v draft.+function ltxFinishFieldsFromSidecar(p, tierKey) {+ if (!p || typeof p !== 'object') return null;+ if (p.engine && p.engine !== 'ltx') return null;+ if (!tierKey) return null;+ const target = ltxTierByKeyExact(tierKey);+ if (!target) return null;+ // Codex UI-2: only a plain t2v/i2v draft has a "same shot, more detail"+ // re-render. Every other mode (keyframe, extend, a2v, i2v_clean_audio,+ // remix...) used to fall through to 't2v' here, so Finish on a Keyframe+ // clip queued a text-to-video that threw its keyframe images away.+ // No recorded mode = an old t2v sidecar.+ if (p.mode && p.mode !== 't2v' && p.mode !== 'i2v') return null;+ const mode = (p.mode === 'i2v') ? 'i2v' : 't2v';+ // Codex UI-3: the source's orientation is part of the recipe. Finish used+ // whatever the FORM's aspect was (a landscape clip finished as portrait when+ // the form was left on Portrait). Read it off the clip's own canvas.+ const sw = Number(p.width) || 0, sh = Number(p.height) || 0;+ const aspect = !(sw > 0 && sh > 0) ? ''+ : (sw === sh) ? 'square'+ : (sh > sw) ? ((Math.abs(sw / sh - 0.8) < 0.02) ? 'portrait_4_5' : 'vertical')+ : 'landscape';+ // Same seed contract as H3's Finish and Manual's own loadParams: the+ // RESOLVED seed_used, never '-1' (which would hand the finish render a+ // fresh roll of the dice instead of the same shot at more detail).+ const seedRaw = (p.seed_used != null && String(p.seed_used) !== ''+ && String(p.seed_used) !== '-1')+ ? p.seed_used+ : p.seed;+ const seed = (seedRaw == null || String(seedRaw) === '') ? '-1' : String(seedRaw);+ const fields = {+ mode, engine: 'ltx',+ quality: target.quality,+ length: target.length,+ width: target.width, height: target.height, frames: target.frames,+ prompt: String(p.prompt || ''),+ negative_prompt: String(p.negative_prompt || ''),+ seed,+ // The export pass and the speed dial are part of the recipe: a draft+ // judged with turbo, or with a 720p fit export, should be finished with+ // the same choices — a Finish that silently dropped them would be a+ // different recipe as well as a different canvas.+ upscale: (typeof p.upscale === 'string' && p.upscale) ? p.upscale : '',+ upscale_method: (typeof p.upscale_method === 'string' && p.upscale_method) ? p.upscale_method : '',+ aspect,+ accel: (typeof p.accel === 'string' && p.accel) ? p.accel : 'off',+ image: (mode === 'i2v' && typeof p.image === 'string') ? p.image : '',+ // The crop framing is part of the recipe (VC-29/H3-01): a face kept by a+ // Top or dragged crop in the draft must be kept in the finish too. Older+ // sidecars predate it — they rendered centred.+ // (Inline, not _cropFocusFromParams: this function stays pure/self-contained.)+ image_crop_focus: ((v) => (isFinite(v) && v >= 0 && v <= 1) ? v : 0.5)(parseFloat(p.image_crop_focus)),+ loras: Array.isArray(p.loras)+ ? p.loras.filter(l => l && l.path)+ .map(l => ({ path: String(l.path),+ strength: (typeof l.strength === 'number') ? l.strength : 1.0 }))+ : [],+ };+ if (mode === 'i2v' && !fields.image) return null;+ return fields;+}++// Show/hide + re-label the shared Finish control for an LTX clip. Mirrors+// _syncH3FinishAffordance exactly — same wrap/label/button/select ids, one+// toolbar slot shared by both engines (dispatched by _syncFinishAffordance+// below), because "commit this draft at higher quality" is one user concept+// regardless of which engine rendered the draft.+function _syncLtxFinishAffordance(o) {+ const wrap = document.getElementById('h3FinishWrap');+ if (!wrap) return false;+ const label = document.getElementById('h3FinishLabel');+ const btn = document.getElementById('h3FinishBtn');+ const sel = document.getElementById('h3FinishTier');+ const lengthKey = o ? _ltxLengthKeyForFrames(o.frames) : null;+ const srcTier = (o && o.engine === 'ltx' && lengthKey && _ltxFinishableMode(o.mode))+ ? ltxCellFor(o.quality, lengthKey) : null;+ const targetKey = srcTier ? ltxFinishTierKey(srcTier) : null;+ const target = targetKey ? ltxTierByKeyExact(targetKey) : null;+ if (!srcTier || !target) return false;+ wrap.style.display = '';+ const name = String(target.label).replace(/\s*·\s*/g, ' ').trim();+ if (label) label.textContent = `Finish at ${name} · ${target.eta}`;+ if (btn) {+ btn.title = `Re-render this ${srcTier.quality_label} clip at `+ + `${target.label} (${target.delivered_spec || target.spec}, ${target.eta}) — same `+ + `${target.length_label} length, same prompt, same seed`;+ btn.onclick = ltxFinishActive;+ }+ if (sel) {+ const opts = ltxFinishTargets(srcTier)+ .map(t => `<option value="${escapeHtml(t.key)}"${t.key === target.key ? ' selected' : ''}>`+ + `${escapeHtml(t.label)} · ${escapeHtml(t.eta)}</option>`)+ .join('');+ if (sel.dataset.built !== opts) {+ sel.innerHTML = opts;+ sel.dataset.built = opts;+ }+ sel.value = target.key;+ sel.onchange = () => ltxFinishSetTier(sel.value);+ }+ return true;+}++// UI-2: the modes LTX Finish can re-render (see ltxFinishFieldsFromSidecar).+// An output with no recorded mode is an old t2v clip.+function _ltxFinishableMode(mode) {+ return !mode || mode === 't2v' || mode === 'i2v';+}++// One toolbar slot, two engines. Tries H3 first (unchanged), then LTX; a+// clip that is neither hides the control. `btn.onclick`/`sel.onchange` are+// re-pointed by whichever branch matches so the SAME button always commits+// whatever is currently labelled on it — never a stale handler left over+// from the previously selected clip's engine.+function _syncFinishAffordance(o) {+ if (o && o.engine === 'h3') {+ const btn = document.getElementById('h3FinishBtn');+ const sel = document.getElementById('h3FinishTier');+ if (btn) btn.onclick = h3FinishActive;+ if (sel) sel.onchange = () => h3FinishSetTier(sel.value);+ _syncH3FinishAffordance(o);+ return;+ }+ if (_syncLtxFinishAffordance(o)) return;+ const wrap = document.getElementById('h3FinishWrap');+ if (wrap) wrap.style.display = 'none';+}++// Commit the selected LTX clip at a higher quality — the mirror of+// h3FinishActive, restoring through the same Load-Params-then-submit path.+async function ltxFinishActive() {+ if (!activePath) return;+ const o = findOutputByPath(activePath);+ const lengthKey = o ? _ltxLengthKeyForFrames(o.frames) : null;+ const srcTier = (o && o.engine === 'ltx' && lengthKey && _ltxFinishableMode(o.mode))+ ? ltxCellFor(o.quality, lengthKey) : null;+ if (!srcTier) return; // button shouldn't be visible+ const targetKey = ltxFinishTierKey(srcTier);+ const target = targetKey ? ltxTierByKeyExact(targetKey) : null;+ if (!target) return;++ let p = null;+ try {+ const r = await fetch('/sidecar?path=' + encodeURIComponent(activePath));+ if (!r.ok) throw new Error('no sidecar (older output?)');+ const data = await r.json();+ p = data && data.params;+ } catch (e) {+ if (typeof phosToast === 'function') {+ phosToast('Finish: ' + (e.message || 'failed to read sidecar'), { kind: 'danger' });+ }+ return;+ }+ const fields = ltxFinishFieldsFromSidecar(p, target.key);+ if (!fields) {+ if (typeof phosToast === 'function') {+ phosToast('Finish: this clip\'s sidecar is missing what the re-render needs.',+ { kind: 'danger' });+ }+ return;+ }++ if (typeof workflowSwitch === 'function') { try { workflowSwitch('manual'); } catch (e) {} }+ setMode(fields.mode);+ if (fields.mode === 'i2v') {+ const i2vSel = document.getElementById('i2vMode');+ if (i2vSel) i2vSel.value = 'i2v';+ document.getElementById('mode').value = 'i2v';+ }+ // setMode() re-applies the persisted engine via _syncEngineForMode(), so+ // LTX has to be forced AFTER it — same ordering reason h3FinishActive+ // forces 'h3' after setMode() above.+ const engine = (typeof setEngine === 'function') ? setEngine('ltx') : 'ltx';+ if (engine !== 'ltx') {+ const note = (document.getElementById('engineRowNote') || {}).textContent || '';+ if (typeof phosToast === 'function') {+ phosToast('Finish needs the LTX engine. ' + note, { kind: 'danger' });+ }+ return;+ }+ document.getElementById('prompt').value = fields.prompt;+ document.getElementById('negative_prompt').value = fields.negative_prompt;+ if (typeof syncAvoidRowFromValue === 'function') { try { syncAvoidRowFromValue(); } catch (e) {} }+ if (fields.image) {+ if (typeof pickerSetImage === 'function') {+ pickerSetImage('image', fields.image, { snapAspect: false });+ } else {+ document.getElementById('image').value = fields.image;+ }+ if (typeof _setCropFocus === 'function') _setCropFocus('image', fields.image_crop_focus);+ }+ // Adapters before the shape, same ordering h3FinishActive uses.+ _restoreLoraPicker(fields.loras);+ const accelEl = document.getElementById('accel');+ if (accelEl) accelEl.value = fields.accel;+ // UI-3: the source's orientation BEFORE the shape — setQuality() (called by+ // _ltxApplyShape) derives width/height from the form's #aspect.+ if (fields.aspect && typeof setAspect === 'function') setAspect(fields.aspect);+ // Shape LAST of the LTX controls — _ltxApplyShape is the one place the+ // form's LTX shape is written, so anything geometry-related set after it+ // would be fighting the source of truth. Quality AND length together,+ // not setLtxQuality() alone: that reads the form's CURRENT length, which+ // may not be this clip's.+ if (typeof _ltxApplyShape === 'function') _ltxApplyShape(target.quality, target.length);+ // UI-3: the export row AFTER the shape — setQuality() re-arms the target+ // preset's own upscale default, which silently dropped the clip's export+ // (a 720p-exported draft finished with export off). Method rides along.+ if (fields.upscale && typeof setUpscale === 'function') setUpscale(fields.upscale);+ if (fields.upscale_method && typeof setUpscaleMethod === 'function') setUpscaleMethod(fields.upscale_method);+ document.getElementById('seed').value = fields.seed;+ if (typeof _syncSeedLockChip === 'function') { try { _syncSeedLockChip(); } catch (e) {} }+ if (typeof updateCustomizeSummary === 'function') { try { updateCustomizeSummary(); } catch (e) {} }+ if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }+ const formPane = document.querySelector('aside.form-pane');+ if (formPane) formPane.scrollTop = 0;++ const form = document.getElementById('genForm');+ if (!form || typeof form.requestSubmit !== 'function') {+ if (typeof phosToast === 'function') {+ phosToast('Finish: form not ready — press Generate.', { kind: 'danger' });+ }+ return;+ }+ if (typeof phosToast === 'function') {+ phosToast(`Finishing at ${target.label} · ${target.eta} · seed ${fields.seed}`,+ { kind: 'success' });+ }+ form.requestSubmit();+}+// Modes H3 can serve. Thin wrapper over the registry so the H3-specific code// below (and anything else that grew to call this) keeps working unchanged.function _h3ServesMode(mode) {@@ -378,7 +699,7 @@ function setEngine(engine, opts) {target = fallback.id;// The lowest lane's floor, not the bf16 one and not a literal 64.reason = e.label + ' needs '- + (st.ram_floor_gb || st.min_ram_gb || 46) + ' GB unified memory.';+ + (st.ram_floor_gb || st.min_ram_gb || 36) + ' GB unified memory.';} else if (!st.available) {target = fallback.id;// Distinguish "you never installed this" from "you DID install this and@@ -528,6 +849,32 @@ function _syncEnginePromptTools() {|| pill.getAttribute('data-title-ltx');if (t) pill.title = t;}+ // H3-07: #h3PromptHelper isn't registered as any engine's `strip`/`hint`+ // (the generic ENGINES.forEach toggle in setEngine), so it needs its own+ // switch here — the one place both engines' prompt-tool state already+ // gets reconciled on every engine change.+ const helper = document.getElementById('h3PromptHelper');+ if (helper) helper.hidden = (eng !== 'h3');+ const promptEl = document.getElementById('prompt');+ if (promptEl) {+ // H3-07: the placeholder was LTX's audio-cue example unconditionally —+ // no hint anywhere that H3 needs a structured field + a <d>…</d> tag to+ // get spoken dialogue at all.+ promptEl.placeholder = (eng === 'h3')+ ? 'integrated_multimodal_description: [Shot 1] Who/what, the setting, '+ + 'what happens. A line of dialogue goes ONLY inside a tag: '+ + 'GEORGE says: <d>[English] I thought it was ashwagandha!</d> then '+ + 'his mouth settles closed. Click Structure or + Line above to '+ + 'insert the skeleton.\n\noverall_soundscape: ambience, sound '+ + 'effects.\n\nnon_diegetic_music: N/A or a description.'+ : 'Describe the scene AND the sound — e.g. wizard in a forest '+ + 'clearing, fireflies spiraling up · low whispered chant, ember '+ + 'crackle, distant owl. Audio is generated jointly with video; '+ + 'without sound cues the model outputs near-silent ambient.';+ }+ if (eng === 'h3' && typeof h3SyncPromptHelper === 'function') {+ try { h3SyncPromptHelper(); } catch (e) {}+ }}function currentEngine() {@@ -590,12 +937,14 @@ function updateH3Availability(s) {}if (changed) {setEngine(currentEngine(), { persist: false });- // The Finish button's label and its picker are both derived from H3.tiers,- // so a pack install/repair that changes the offered tiers has to re-label- // the currently-selected clip's affordance too — otherwise it keeps- // advertising a tier this install just stopped (or started) offering.- if (typeof _syncH3FinishAffordance === 'function') {- try { _syncH3FinishAffordance(findOutputByPath(activePath)); } catch (e) {}+ // The Finish button's label and its picker are both derived from the+ // engine's own tier table, so a pack install/repair that changes the+ // offered tiers has to re-label the currently-selected clip's+ // affordance too — otherwise it keeps advertising a tier this install+ // just stopped (or started) offering. Dispatches to whichever engine+ // rendered the selected clip (VC-18/37).+ if (typeof _syncFinishAffordance === 'function') {+ try { _syncFinishAffordance(findOutputByPath(activePath)); } catch (e) {}}}}@@ -653,10 +1002,26 @@ function openH3InstallCard(source) {+ 'Re-cloning it takes about a minute.': 'What broke: ' + (_missing[0] || 'a component the probe lists below')+ '.';+ // H3-05: "repairable" covers two different real situations and they+ // need two different CTAs. missing_q8_dit means every weight is present+ // and only the local compact build is missing — pinokio.js shows ONLY a+ // Build entry for that state, no Repair entry at all, so telling the+ // user to click "Repair Hailuo H3" sent them looking for a button that+ // doesn't exist (the exact 48 GB rescue scenario recent releases tried+ // to fix). venv/runner actually broken is the real repair case.+ const needsBuildOnly = H3.reason === 'missing_q8_dit';+ const fixMenuText = needsBuildOnly+ ? 'Build Hailuo H3 compact engine (weights kept — no re-download)'+ : 'Repair Hailuo H3 (weights kept — no re-download)';+ const fixBlurb = needsBuildOnly+ ? `<b>Hailuo H3 is installed — it just needs its compact engine built.</b>+ Your weights (~75 GB) are already on disk; the build downloads+ nothing.`+ : `<b>Hailuo H3 is installed — it just needs repairing.</b> Your weights+ (~75 GB) are still on disk and are <em>not</em> re-downloaded.`;const intro = H3.repairable ? `<p style="margin:0 0 10px">- <b>Hailuo H3 is installed — it just needs repairing.</b> Your weights- (~75 GB) are still on disk and are <em>not</em> re-downloaded.+ ${fixBlurb}</p><p style="margin:0 0 10px;color:var(--muted)">${diagnosis}@@ -666,18 +1031,18 @@ function openH3InstallCard(source) {</p><p style="margin:0 0 10px">Fix it from Pinokio: open the <b>Phosphene</b> entry in the Pinokio- sidebar and click <b>“Repair Hailuo H3”</b> (it appears in place of the- install entry). The step is idempotent — it skips every weight already- on disk. The panel picks the engine back up within a couple of seconds,- no restart.+ sidebar and click <b>“${escapeHtml(fixMenuText)}”</b> (it appears in+ place of the install entry). The step is idempotent — it skips every+ weight already on disk. The panel picks the engine back up within a+ couple of seconds, no restart.</p>` : `<p style="margin:0 0 10px"><b>Hailuo H3 is Phosphene's second video engine</b>, a peer of LTXrather than an add-on to it: one prompt in, video <em>and</em> synceddialogue <em>and</em> sound out, in a single pass. It runs fullylocally and sits beside LTX in the engine switcher — installing it- changes nothing about your existing renders, and either engine can- drive any render you start.+ changes nothing about your existing renders. H3 covers Text and+ Image; LTX still covers every other mode.</p><p style="margin:0 0 10px;color:var(--muted)">${escapeHtml(H3.size_note || '')}@@ -703,6 +1068,15 @@ function openH3InstallCard(source) {<summary>Details for troubleshooting</summary><p>Currently missing: ${escapeHtml(missing.join('; '))}</p></details>` : ''}`;+ // H3-39: the title was a static "Hailuo H3 · 75 GB" in the markup,+ // unconditionally — including the build-only and repair cases, where+ // nothing downloads. Say what this click actually costs.+ const title = document.getElementById('h3InstallTitle');+ if (title) {+ title.textContent = needsBuildOnly ? 'Build the compact engine · ~5 min, no download'+ : H3.repairable ? 'Repair Hailuo H3 · no download'+ : 'Hailuo H3 · 75 GB';+ }}if (m) m.style.display = 'flex';_h3CardSeen = true;@@ -740,8 +1114,14 @@ function _h3NudgeEngineOffer() {// inside a 480px cap, so a sentence that runs long is not a long toast, it// is a truncated one — "…install it from the Phosphene entry i…" was the// first draft, and it clipped exactly where the instruction lived.- const el = phosToast('Hailuo H3 · 75 GB — install from the Pinokio sidebar.',- { icon: 'ph-info', duration: 5000 });+ // H3-39: same "· 75 GB" default the modal title had, wrong whenever this is+ // a build-only or repair nudge — nothing downloads in either case.+ const nudgeMsg = (H3.reason === 'missing_q8_dit')+ ? 'Hailuo H3 · build the compact engine, no download — from the Pinokio sidebar.'+ : H3.repairable+ ? 'Hailuo H3 · repair, no download — from the Pinokio sidebar.'+ : 'Hailuo H3 · 75 GB — install from the Pinokio sidebar.';+ const el = phosToast(nudgeMsg, { icon: 'ph-info', duration: 5000 });if (!el) return;const a = document.createElement('a');a.href = '#';@@ -764,7 +1144,9 @@ async function enhancePrompt() {// an inline ph-sparkle-fill SVG that textContent would strip.const originalLabel = btn.innerHTML;btn.disabled = true;- btn.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-sparkle-fill"/></svg>Loading Gemma… (~15s on cold start)';+ // VC-23: "Gemma" is the internal model name and means nothing to most+ // users — "the prompt helper" says what it DOES instead.+ btn.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-sparkle-fill"/></svg>Loading the prompt helper… (~15s on cold start)';let res;try {// Collect trigger tokens to preserve case-exact through enhance.@@ -788,6 +1170,10 @@ async function enhancePrompt() {if (charIdEl && charIdEl.value) preserveTokens.push(charIdEl.value);const fd = new URLSearchParams({ prompt: original, mode });if (preserveTokens.length) fd.set('preserve_tokens', JSON.stringify(preserveTokens));+ // VC-13: the language-hint toggle, when it's showing (a non-Latin+ // prompt). Absent/checked = translate (unchanged default behaviour).+ const translateEl = document.getElementById('translateToEnglish');+ fd.set('translate', (!translateEl || translateEl.checked) ? '1' : '0');const r = await fetch('/prompt/enhance', { method: 'POST', body: fd });res = await r.json();} catch (e) {@@ -796,15 +1182,75 @@ async function enhancePrompt() {return;}btn.disabled = false; btn.innerHTML = originalLabel;- if (res.error) { alert('Enhance failed: ' + res.error); return; }- // Show diff in a confirm so the user can decide whether to accept.- const accept = confirm(- `Original:\n${res.original}\n\nEnhanced:\n${res.enhanced}\n\nReplace your prompt with the enhanced version?`- );- if (accept) {- ta.value = res.enhanced;- ta.dispatchEvent(new Event('input', { bubbles: true }));+ if (res.error) {+ // VC-16: a GPU-busy refusal (409) names what's rendering instead of a+ // flat "a render is using the GPU" — show it inline, not a blocking+ // alert(), so it reads the same register as everything else in this+ // panel and doesn't demand a click to dismiss.+ phosToast(res.error, { kind: 'danger', duration: 8000 });+ return;}+ showEnhancePanel(res.original, res.enhanced, !!res.translated);+}++// VC-13: a light, reliable "not Latin script" signal — mirrors+// prompt_looks_non_latin() server-side exactly (same ranges), so the hint+// and the toggle it feeds never disagree with what Enhance itself checks.+function promptLooksNonLatin(text) {+ return /[-ヿ㐀-䶿一-鿿가-Ѐ-ӿ-ۿ--]/.test(text || '');+}+function updateLangHint() {+ const ta = document.getElementById('prompt');+ const hint = document.getElementById('langHint');+ if (!ta || !hint) return;+ hint.hidden = !promptLooksNonLatin(ta.value);+}++// VC-16: the inline Enhance result — Accept / Undo / Keep mine, replacing+// the old native confirm() (no edit, no diff, no undo, and it broke ⌘Z by+// overwriting the textarea programmatically). Two states in one panel:+// "review" shows the fresh result; "applied" (after Accept) offers Undo.+function showEnhancePanel(original, enhanced, translated) {+ const panel = document.getElementById('enhancePanel');+ if (!panel) return;+ panel.dataset.original = original;+ panel.dataset.enhanced = enhanced;+ // VC-13: "Enhance states that it translated" — set once, up front, not+ // buried behind Accept, so it's visible while still reviewing.+ panel.dataset.translated = translated ? '1' : '';+ document.getElementById('enhanceOriginalText').textContent = original;+ document.getElementById('enhanceEnhancedText').textContent = enhanced;+ document.getElementById('enhanceAcceptBtn').hidden = false;+ document.getElementById('enhanceKeepBtn').hidden = false;+ document.getElementById('enhanceUndoBtn').hidden = true;+ document.getElementById('enhancePanelNote').textContent = translated ? 'Translated to English.' : '';+ panel.hidden = false;+}+function _setPromptValue(text) {+ const ta = document.getElementById('prompt');+ if (!ta) return;+ ta.value = text;+ ta.dispatchEvent(new Event('input', { bubbles: true }));+}+function acceptEnhance() {+ const panel = document.getElementById('enhancePanel');+ if (!panel || panel.hidden) return;+ _setPromptValue(panel.dataset.enhanced || '');+ document.getElementById('enhanceAcceptBtn').hidden = true;+ document.getElementById('enhanceKeepBtn').hidden = true;+ document.getElementById('enhanceUndoBtn').hidden = false;+ document.getElementById('enhancePanelNote').textContent =+ (panel.dataset.translated ? 'Translated to English. ' : '') + 'Applied.';+}+function undoEnhance() {+ const panel = document.getElementById('enhancePanel');+ if (!panel || panel.hidden) return;+ _setPromptValue(panel.dataset.original || '');+ panel.hidden = true;+}+function keepMineEnhance() {+ const panel = document.getElementById('enhancePanel');+ if (panel) panel.hidden = true;}// Extend duration: user types seconds, we convert to latent frames behind@@ -822,9 +1268,20 @@ function syncExtendDuration() {const latents = Math.max(1, Math.ceil(seconds * 24 / 8));const actualSec = (latents * 8 / 24);hidden.value = String(latents);- hint.textContent = `≈ ${actualSec.toFixed(2)} s of new content (${latents} latent frames × 8 video frames at 24 fps)`;+ // VC-23: "6 latent frames × 8 video frames at 24 fps" is the panel's own+ // math, not something a user needs to read to understand "this adds+ // about 2 seconds" — kept as a tooltip for anyone who does want it.+ hint.textContent = `Adds ${actualSec.toFixed(2)} s`;+ hint.title = `${latents} latent frames × 8 video frames at 24 fps`;+ // VC-25: the sticky footer's derived line has its own Extend-aware branch+ // (updateDerived()) that reads this same #extend_seconds/#extend_direction+ // pair — refresh it here too, or it keeps showing whatever it last said+ // (the wrong job's T2V geometry, or a stale Extend seconds value) until+ // something ELSE happens to call updateDerived().+ if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }}document.getElementById('extend_seconds').addEventListener('input', syncExtendDuration);+document.getElementById('extend_direction').addEventListener('change', syncExtendDuration);syncExtendDuration(); // initialize on loaddocument.getElementById('i2vMode').addEventListener('change', () => {document.getElementById('audioSection').classList.toggle('show', document.getElementById('i2vMode').value === 'i2v_clean_audio');@@ -834,19 +1291,99 @@ document.getElementById('i2vMode').addEventListener('change', () => {updateDerived();});+// VC-39: 1:1 and 4:5 are their own measured cells (ASPECTS.square /+// ASPECTS.portrait_4_5), fixed regardless of the quality tier — unlike+// landscape/vertical, which are a rotation of whatever canvas the CURRENT+// quality preset already renders at (Balanced 1024×576, Standard 1280×704,+// ...). Shared by applyAspect (here) and setQuality (characters.js) so the+// two can't drift into disagreeing about what a given (aspect, quality)+// pair renders at — published below.+function _aspectDims(aspectKey, qualityKey) {+ const fixed = ASPECTS[aspectKey];+ if (fixed && (aspectKey === 'square' || aspectKey === 'portrait_4_5')) {+ return { w: fixed.w, h: fixed.h };+ }+ const preset = QUALITY_PRESETS[qualityKey] || QUALITY_PRESETS['standard'];+ const vertical = (aspectKey === 'vertical' && qualityKey !== 'quick');+ return vertical ? { w: preset.h, h: preset.w } : { w: preset.w, h: preset.h };+}+// VA-20: the I2V "external audio" (mux) slot — was a raw path text box, the+// only non-picker file input on the video form. This is deliberately a+// smaller drop/click zone than the full .picker component (no recent-uploads+// strip, no image preview machinery — none of that applies to audio), but+// the same interaction shape as the Lip-sync tab's audio slot.+function i2vAudioRenderSlot(path) {+ const hint = document.getElementById('i2vAudioSlotHint');+ if (!hint) return;+ if (path) {+ const name = String(path).split('/').pop();+ hint.innerHTML = '<svg class="ph" aria-hidden="true" style="width:16px;height:16px;vertical-align:-3px;margin-right:6px;"><use href="#ph-music-notes"/></svg>'+ + escapeHtml(name)+ + '<div class="hint" style="margin-top:4px"><a href="#" onclick="event.stopPropagation();event.preventDefault();i2vAudioSet(\'\');">Remove</a></div>';+ } else {+ hint.textContent = 'Drop a WAV / MP3 / M4A / FLAC here, or click to pick a file.';+ }+}+function i2vAudioSet(path) {+ const el = document.getElementById('audio');+ if (el) el.value = path || '';+ i2vAudioRenderSlot(path);+ updateDerived();+}+async function i2vAudioUpload(file) {+ if (!file) return;+ const hint = document.getElementById('i2vAudioSlotHint');+ if (hint) hint.textContent = `Uploading ${file.name}…`;+ try {+ const fd = new FormData();+ fd.append('audio', file);+ const r = await fetch('/upload', { method: 'POST', body: fd });+ const data = await r.json();+ if (!data.ok) throw new Error(data.error || 'upload failed');+ i2vAudioSet(data.path);+ } catch (e) {+ i2vAudioRenderSlot(document.getElementById('audio')?.value || '');+ if (typeof phosToast === 'function') {+ phosToast('Audio upload failed: ' + (e.message || e), { kind: 'danger' });+ } else {+ alert('Audio upload failed: ' + (e.message || e));+ }+ }+}+(function wireI2vAudioSlot() {+ const slot = document.getElementById('i2vAudioSlot');+ const input = document.getElementById('i2vAudioFileInput');+ if (!slot || !input) return;+ slot.addEventListener('click', () => input.click());+ slot.addEventListener('dragover', (e) => { e.preventDefault(); slot.classList.add('drop-active'); });+ slot.addEventListener('dragleave', () => slot.classList.remove('drop-active'));+ slot.addEventListener('drop', (e) => {+ e.preventDefault();+ slot.classList.remove('drop-active');+ if (e.dataTransfer?.files?.[0]) i2vAudioUpload(e.dataTransfer.files[0]);+ });+ input.addEventListener('change', () => {+ if (input.files?.[0]) i2vAudioUpload(input.files[0]);+ });+ // boot.js runs before this module and already set #audio.value to+ // BOOT.default_audio — pick that up so the slot doesn't show an empty+ // state for a field that already has a value.+ i2vAudioRenderSlot(document.getElementById('audio')?.value || '');+})();+function applyAspect(key) {if (!ASPECTS[key]) return;document.getElementById('aspect').value = key;// Aspect controls dimensions only when the active preset has a choice- // (Standard / High at 1280×704 vs 704×1280). Quick is fixed 4:3 and- // ignores the aspect picker (the row is hidden in that state, so this- // path normally won't fire — defensive in case of programmatic calls).+ // (Standard / High at 1280×704 vs 704×1280, or the fixed 1:1 / 4:5+ // cells). Quick is fixed 4:3 and ignores the aspect picker (the row is+ // hidden in that state, so this path normally won't fire — defensive in+ // case of programmatic calls).const q = document.getElementById('quality').value;if (q === 'quick') return;- const preset = QUALITY_PRESETS[q] || QUALITY_PRESETS['standard'];- const vertical = (key === 'vertical');- document.getElementById('width').value = vertical ? preset.h : preset.w;- document.getElementById('height').value = vertical ? preset.w : preset.h;+ const dims = _aspectDims(key, q);+ document.getElementById('width').value = dims.w;+ document.getElementById('height').value = dims.h;updateCustomizeSummary();updateDerived();}@@ -895,12 +1432,144 @@ function snapFramesTo8kPlus1() {}}+// VC-15: the Avoid box takes input on every quality, but the distilled Q4+// lane (Quick/Balanced/Standard T2V+I2V) has no unconditional branch to run+// it against — the box's own hint said so in 10px grey text, but nothing on+// the box ITSELF, or on its collapsed toggle, showed it. Reads the same+// registry facts as everything else that draws this line (_qualityUsesHq),+// so "does Avoid work right now" can never disagree with the quality chips.+function avoidIsIgnored() {+ const mode = (document.getElementById('mode') || {}).value || 't2v';+ if (currentMode === 'extend' || currentMode === 'keyframe' || mode === 'a2v') return false;+ if (mode !== 't2v' && mode !== 'i2v' && mode !== 'i2v_clean_audio') return false;+ const quality = (document.getElementById('quality') || {}).value || 'balanced';+ return typeof _qualityUsesHq === 'function' ? !_qualityUsesHq(quality) : false;+}+function updateAvoidIgnoredState() {+ const note = document.getElementById('avoidIgnoredNote');+ const ta = document.getElementById('negative_prompt');+ const qLabel = document.getElementById('avoidIgnoredQuality');+ const lbl = document.getElementById('avoidToggleLabel');+ const row = document.getElementById('avoidRow');+ if (!note || !ta) return;+ const ignored = avoidIsIgnored();+ note.hidden = !ignored;+ ta.classList.toggle('is-ignored', ignored);+ if (qLabel) {+ let cell = (typeof ltxCurrentCell === 'function') ? ltxCurrentCell() : null;+ qLabel.textContent = (cell && cell.quality_label) || 'this quality';+ }+ if (lbl && row) {+ const open = row.classList.contains('show');+ lbl.textContent = open ? 'Avoid −'+ : (ignored ? `Avoid + (off at ${(qLabel && qLabel.textContent) || 'this quality'})` : 'Avoid +');+ }+}+let _h3DerivedMode = null;+// VA-11 / VA-12: keyframe and extend each run a DIFFERENT pipeline than+// whatever the Quality strip's w/h/steps form fields say — keyframe always+// renders Q8 two-stage at this Mac's clamped canvas, extend runs its own+// step count at its own clamp. Pricing those off the raw form fields (what+// updateDerived did for every other mode) is exactly the bug: the summary+// showed the Quality pill's number for a render that was never going to be+// that size, that quality, or that fast. Both prices are computed+// server-side (ltx_mode_price_card, BOOT.tier / /status tier) and read here+// verbatim — the browser prices nothing of its own (Structure Law §6).+// 4.17 Codex EST-7: BOOT's keyframe card is priced at 5 s on the default+// canvas. The shape the form actually holds (duration, aspect) is priced by+// GET /keyframe/estimate — debounced, sequence-guarded, cached per shape —+// and both readers (this footer and the Shot setup summary) repaint when+// it lands. Returns {card, pending}: card is null only when keyframe isn't+// available on this Mac; pending means the eta is still being priced.+const _kfPriceCache = {};+let _kfPriceSeq = 0;+let _kfPriceTimer = null;+function keyframePriceFor() {+ const tier = (typeof BOOT !== 'undefined' && BOOT.tier) || {};+ const base = tier.keyframe_price || null;+ if (!base) return { card: null, pending: false };+ const num = (id) => parseInt((document.getElementById(id) || {}).value || 0, 10) || 0;+ const frames = num('frames'), w = num('width'), h = num('height');+ const key = `${frames}|${w}|${h}`;+ if (_kfPriceCache[key]) return { card: _kfPriceCache[key], pending: false };+ clearTimeout(_kfPriceTimer);+ const seq = ++_kfPriceSeq;+ _kfPriceTimer = setTimeout(async () => {+ try {+ const r = await fetch(`/keyframe/estimate?frames=${frames}&width=${w}&height=${h}`);+ const d = await r.json();+ if (!d || !d.ok) return;+ _kfPriceCache[key] = d;+ if (seq !== _kfPriceSeq) return;+ const modeEl = document.getElementById('mode');+ if (modeEl && modeEl.value === 'keyframe') updateDerivedForClampedMode('keyframe');+ if (typeof updateShotSetupSummary === 'function') { try { updateShotSetupSummary(); } catch (e) {} }+ } catch (e) { /* the pending line stays; the next change retries */ }+ }, 150);+ return { card: base, pending: true };+}+function updateDerivedForClampedMode(mode) {+ const tier = (typeof BOOT !== 'undefined' && BOOT.tier) || {};+ const derivedFooter = document.getElementById('derivedFooter');+ let card = null, line = '';+ if (mode === 'keyframe') {+ const kp = keyframePriceFor();+ card = kp.card;+ line = card+ ? (kp.pending+ ? `${escapeHtml(card.pipeline_note)} · pricing…`+ : `${escapeHtml(card.pipeline_note)} · <strong>${card.width}×${card.height}</strong> · ${escapeHtml(card.eta)}`)+ : 'Needs more memory than this Mac has for keyframe (FFLF) rendering.';+ if (kp.pending) card = null; // the canvas below is not known yet either+ } else if (mode === 'extend') {+ const proOn = (document.getElementById('extend_steps') || {}).value === '30';+ card = proOn ? tier.extend_price_pro : tier.extend_price_draft;+ // VC-25: the seconds actually being added (rounded up to the+ // 8-video-frame latent grid, same arithmetic as syncExtendDuration())+ // and the direction — never the T2V width/height/frames fields, which+ // describe a shot Extend isn't building. VA-12: the canvas is this+ // Mac's Extend clamp and the ETA is priced server-side per latent count.+ const secEl = document.getElementById('extend_seconds');+ const dirEl = document.getElementById('extend_direction');+ const sec = secEl ? (parseFloat(secEl.value) || 0) : 0;+ const latents = Math.max(1, Math.ceil(sec * 24 / 8));+ const actualSec = (latents * 8 / 24).toFixed(1);+ const dir = (dirEl && dirEl.value === 'before') ? 'before' : 'after';+ const eta = card ? ((card.eta_by_latents || {})[String(latents)] || card.eta) : '';+ line = card+ ? `<strong>+${actualSec}s ${dir} · Q8</strong> · ≤${Math.max(card.width, card.height)} px · ${escapeHtml(eta)}`+ : 'Needs more memory than this Mac has for Extend.';+ }+ if (derivedFooter) derivedFooter.innerHTML = line;+ const qualityMeta = document.getElementById('qualityMeta');+ if (qualityMeta && card) qualityMeta.textContent = `${card.width}×${card.height}`;+}function updateDerived() {// The per-window hint counts windows for the CURRENT length, so it has to// move when the length does, not only when the pill is clicked.if (typeof windowPromptsInput === 'function') { try { windowPromptsInput(); } catch (e) {} }+ // VA-13: the Extend clamp note has to repaint on every mode switch (BOOT+ // data doesn't change, but the note is only relevant — and only in the+ // DOM's visible path — while Extend is the active mode).+ if (typeof refreshExtendClampNote === 'function') { try { refreshExtendClampNote(); } catch (e) {} }+ // VC-29/H3-01/VA-02: the crop-preview overlay tracks whatever the render+ // canvas currently is (#width/#height for 'image' — LTX or H3, since both+ // engines mirror their resolved canvas into those same fields — and A2V's+ // own width/height for 'a2v_image'), so it has to repaint on every change+ // that could move that canvas: quality/length/orientation pills, custom+ // W×H edits, and a fresh image pick. Routing through here (updateDerived+ // is already the one function all of those call) is the single point+ // that covers every trigger without threading a new hook to each one.+ if (typeof refreshPickerCropOverlays === 'function') { try { refreshPickerCropOverlays(); } catch (e) {} }const mode = document.getElementById('mode').value;+ // VA-11/12: keyframe and extend price a pipeline the Quality strip does+ // not describe, so their summary comes from the server's price card+ // (updateDerivedForClampedMode) — but that must not RETURN from here:+ // everything below the footer (which form sections show for this mode,+ // the keyframe slots, the frames gate) still has to run, or switching to+ // Extend / Keyframe would leave the previous mode's sections on screen.+ const clampedMode = (mode === 'keyframe' || currentMode === 'extend');const w = parseInt(document.getElementById('width').value || 0);const h = parseInt(document.getElementById('height').value || 0);const f = parseInt(document.getElementById('frames').value || 0);@@ -931,7 +1600,17 @@ function updateDerived() {temporalText = ` · LTX ${sourceFrames}f @ 12fps → ${FPS}fps`;}- document.getElementById('derived').innerHTML = `Duration <strong>${dur}s</strong> @ ${FPS}fps${temporalText} · ${finalRes} · Steps ${document.getElementById('steps').value}${accelText}`;+ // VC-27: this used to ALSO write the identical numbers into a standalone+ // "Duration ... · ... · Steps ..." box (#derived) that sat unconditionally+ // between the Advanced disclosure and the sticky footer — a plain+ // Balanced 5s render showed the same duration/resolution three times at+ // once (the collapsed Shot-setup summary, this box, and the footer line+ // below). #derived carried no information the footer's own line didn't+ // already have, and unlike the two `<summary>` texts it was never a+ // disclosure's collapsed-state indicator (nothing lived inside a+ // `<details>` to reveal), so there was nothing to preserve by keeping it.+ // Dropped outright; see the enhanced footer line below, which is now the+ // one place this information lives.// Compact derived line in the sticky action footer — same info, tighter// typography. Lets the user see what they're about to render WITHOUT@@ -939,13 +1618,42 @@ function updateDerived() {// summary style (just dimensions + duration; full details stay in the// expanded Customize body).const derivedFooter = document.getElementById('derivedFooter');- if (derivedFooter) {+ if (clampedMode) {+ updateDerivedForClampedMode(currentMode === 'extend' ? 'extend' : 'keyframe');+ } else if (derivedFooter) {const onH3 = typeof currentEngine === 'function' && currentEngine() === 'h3'&& typeof h3EstimateLine === 'function';// H3: the speed, the shape, the optional Face Fix, and what it all costs.const h3Line = onH3 ? h3EstimateLine() : '';+ // VC-27: "one live summary line directly above Generate, including the+ // ETA" — the footer line is that one line now. T2V/I2V read the same+ // quality cell the chip strip renders from (ltxCurrentCell / ltxCellEta,+ // engines.js), so the label and the ETA can never disagree with what+ // the chips themselves show. Scoped to t2v/i2v on purpose: every other+ // mode (Restore, Control, Ingredients, Upscale...) doesn't sit on the+ // quality ladder the same way, and keeps the plain dimensions+duration+ // line it always had.+ const ltxLine = (!onH3+ && (currentMode === 't2v' || currentMode === 'i2v')+ && typeof ltxCurrentCell === 'function')+ ? (() => {+ const cell = ltxCurrentCell();+ if (!cell || !cell.quality_label) return null;+ let deliveredRes = `${w}×${h}`;+ if (upscale === 'fit_720p') {+ deliveredRes = (w >= h) ? '1280×720' : '720×1280';+ } else if (upscale === 'x2') {+ deliveredRes = `${w * 2}×${h * 2}`;+ }+ const eta = (typeof ltxCellEta === 'function') ? ltxCellEta(cell) : '';+ return `${cell.quality_label} · ${dur}s · ${deliveredRes}`+ + (eta ? ` · ${eta}` : '');+ })()+ : null;derivedFooter.innerHTML = h3Line? `<strong>${escapeHtml(h3Line)}</strong> · ${dur}s`+ : ltxLine+ ? `<strong>${escapeHtml(ltxLine)}</strong>`: `<strong>${dur}s</strong> · ${finalRes}${temporalText}${accelText}`;// The Fast estimate depends on the mode (Image mode encodes a keyframe),// so a mode switch re-prices the H3 cards.@@ -958,7 +1666,7 @@ function updateDerived() {// Also update the Quality strip's right-side meta line (e.g. "5s · 1024×576")// so the Quality picker block reads as a self-contained summary.const qualityMeta = document.getElementById('qualityMeta');- if (qualityMeta) {+ if (qualityMeta && !clampedMode) {const qBare = `${w}×${h}`;qualityMeta.textContent = `${dur}s · ${qBare}`;}@@ -1063,11 +1771,43 @@ function updateDerived() {const dimsRow = document.getElementById('dimsRow');if (dimsRow) dimsRow.style.display = '';+ if (typeof updateAvoidIgnoredState === 'function') { try { updateAvoidIgnoredState(); } catch (e) {} }+// Image previews are now part of the picker component itself — the// preview <img> + clear button live inside .picker-drop and are toggled// by pickerSetImage(). No per-mode preview management here anymore;// the old imagePreview / startImagePreview / endImagePreview elements// are gone.+ _updateKeyframeFramesGate();+}++// VA-25: FFLF/Keyframes needs both a start and an end frame, and used to say+// so only in a native alert() AFTER Generate was clicked (Generate stayed+// enabled the whole time). Same inline-reason pattern as stage.js's+// invalidReason and the Q8/pack-blocked gates just above updateDerived() —+// disable the button and explain why in its title, rather than let the user+// find out after the click. Runs on every updateDerived() (which already+// fires on every picker change via pickerSetImage → updateDerived()).+const _KF_FRAMES_REASON = 'Pick both a start frame and an end frame before generating.';+function _updateKeyframeFramesGate() {+ const genBtn = document.getElementById('genBtn');+ if (!genBtn) return;+ if (currentMode !== 'keyframe') {+ if (genBtn.disabled && genBtn.title === _KF_FRAMES_REASON) {+ genBtn.disabled = false;+ genBtn.title = '';+ }+ return;+ }+ const startImg = (document.getElementById('start_image')?.value || '').trim();+ const endImg = (document.getElementById('end_image')?.value || '').trim();+ if (!startImg || !endImg) {+ genBtn.disabled = true;+ genBtn.title = _KF_FRAMES_REASON;+ } else if (genBtn.disabled && genBtn.title === _KF_FRAMES_REASON) {+ genBtn.disabled = false;+ genBtn.title = '';+ }}['width','height','frames','duration'].forEach(id => {@@ -1113,14 +1853,83 @@ document.getElementById('keyframe_mid_seconds')?.addEventListener('input', () =>// via pickerSetImage(), which already calls updateDerived(). No per-input// listeners needed.+// VA-13: say Extend's hardware clamp BEFORE Generate, not only in the log+// once the 6-16 min render has already finished softer than the source. The+// number is BOOT.tier.extend_max_dim — the same one run_job_inner enforces+// (tier_max_dim("extend")) — so the two can never disagree.+function refreshExtendClampNote() {+ const el = document.getElementById('extendClampNote');+ if (!el) return;+ if (currentMode !== 'extend') { el.hidden = true; return; }+ const tier = (BOOT && BOOT.tier) || {};+ const cap = Number(tier.extend_max_dim || 0);+ if (!cap) {+ // 0 = unclamped on this Mac's tier (Roomy carries its own 1024 cap —+ // still worth a line; Studio is the only truly uncapped one).+ el.hidden = true;+ return;+ }+ el.hidden = false;+ el.textContent = `On this Mac (${tier.label || 'this tier'}), Extend renders `+ + `at up to ${cap}px on the longer side — a bigger source clip is `+ + `downscaled to fit before the new frames are added.`;+}+// Auto-snap the aspect picker based on an image's actual dimensions.// Avoids the 16:9-source-cropped-to-9:16-strip footgun.+//+// H3-01: H3's Image mode shares this SAME picker (key='image') and used to+// carry no orientation signal from the picture at all — a 900x1600 portrait+// upload left H3's own Orientation row on whatever it was last (often+// "Landscape", the default), so the server centre-cropped a portrait photo+// onto a landscape canvas and kept the torso, not the face. Both engines'+// orientation state are driven from the same probed aspect now, so a picked+// image always sets the right one for whichever engine is active.function snapAspectToImage(path) {const probe = new Image();probe.onload = () => {const r = probe.naturalWidth / probe.naturalHeight;const target = r >= 1 ? 'landscape' : 'vertical';if (document.getElementById('aspect').value !== target) setAspect(target);+ if (currentEngine() === 'h3' && typeof setH3Orientation === 'function') {+ setH3Orientation(r >= 1 ? 'landscape' : 'portrait');+ }+ };+ probe.src = '/image?path=' + encodeURIComponent(path);+}++// VA-02: A2V kept its own free-form Width/Height fields fixed at whatever+// the user last typed (default 1024x576) no matter what picture was+// dropped in — so a 9:16 phone selfie, the single most common A2V input,+// rendered at 1024x576 and the vendored encoder's hardcoded centre crop+// kept the forehead and lost the mouth and chin (the report's own overlay:+// 24b-a2v-portrait-vs-frame0.png). Snaps toward the picture's aspect while+// keeping roughly the SAME render cost (area held constant, so this isn't+// also silently making the job bigger or slower) — the same spirit as+// snapAspectToImage's flip, just over free-form fields instead of a preset+// pair. Snapped to 32px (the field's own step) like audioStudioGenerate()+// already does at submit time.+function snapA2VSizeToImage(path) {+ const wEl = document.getElementById('audioStudioWidth');+ const hEl = document.getElementById('audioStudioHeight');+ if (!wEl || !hEl) return;+ const probe = new Image();+ probe.onload = () => {+ const r = probe.naturalWidth / probe.naturalHeight;+ if (!(r > 0) || !isFinite(r)) return;+ const area = Math.max(1, parseInt(wEl.value || '1024', 10))+ * Math.max(1, parseInt(hEl.value || '576', 10));+ let newH = Math.sqrt(area / r);+ let newW = area / newH;+ const snap32 = (v) => Math.max(256, Math.min(1920, Math.round(v / 32) * 32));+ wEl.value = String(snap32(newW));+ hEl.value = String(snap32(newH));+ if (typeof audioStudioDurationChanged === 'function') {+ try { audioStudioDurationChanged(); } catch (e) {}+ }+ if (typeof refreshPickerCropOverlays === 'function') {+ try { refreshPickerCropOverlays(); } catch (e) {}+ }};probe.src = '/image?path=' + encodeURIComponent(path);}@@ -1204,12 +2013,21 @@ function pickerSetImage(key, path, opts = {}) {}// FFLF anchors framing on the start frame; I2V anchors on its single// image. End frame doesn't drive aspect (would override the start- // frame). a2v_image lives in the Audio→Video tab which has its own- // width/height inputs — calling snapAspectToImage would change the- // GLOBAL #aspect selector, not the A2V one, so skip it for a2v_image- // to avoid silently mutating an unrelated mode.+ // frame). a2v_image lives in the Audio→Video tab, which has its own+ // free-form width/height fields rather than the global #aspect+ // selector (VA-02: snapA2VSizeToImage sets THOSE instead, so this+ // still can't reach an unrelated mode's state).if ((key === 'image' || key === 'start_image') && opts.snapAspect !== false) {snapAspectToImage(path);+ } else if (key === 'a2v_image' && opts.snapAspect !== false) {+ snapA2VSizeToImage(path);+ }+ // Open-mouth anchor check (build item 3, "Keyframe + lip-sync"): only+ // the lip-sync picture matters here — FFLF/Keyframe anchors are a+ // different contract (VA-02/size-faces owns the crop preview on this+ // same tile; this only adds the openness verdict line under it).+ if (key === 'a2v_image' && typeof audioStudioMouthCheck === 'function') {+ audioStudioMouthCheck(path);}} else {// Drop the handler with the pick, or a later `removeAttribute('src')`@@ -1223,6 +2041,9 @@ function pickerSetImage(key, path, opts = {}) {if (els.recentStrip) {els.recentStrip.querySelectorAll('img').forEach(img => img.classList.remove('selected'));}+ if (key === 'a2v_image' && typeof audioStudioMouthCheck === 'function') {+ audioStudioMouthCheck('');+ }}updateDerived();}@@ -1257,9 +2078,12 @@ async function pickerUploadFile(key, file) {function pickerWire(key) {const els = pickerEls(key);if (!els.drop) return;- // Click → file dialog. Skip when the click came from the clear button.+ // Click → file dialog. Skip when the click came from the clear button —+ // or from the crop preview (4.17 Codex EST-8): the overlay lives INSIDE+ // this tile, so the click that ends a crop drag bubbled here and opened+ // the file chooser on top of the framing the user had just set.els.drop.addEventListener('click', (e) => {- if (e.target.closest('.picker-clear')) return;+ if (e.target.closest('.picker-clear, .crop-overlay, .crop-overlay-controls')) return;els.file.click();});els.file.addEventListener('change', () => {@@ -1279,8 +2103,214 @@ function pickerWire(key) {const f = e.dataTransfer.files && e.dataTransfer.files[0];if (f) pickerUploadFile(key, f);});+ // VC-29/H3-01/VA-02: naturalWidth/Height (needed for the crop-preview+ // overlay's math) aren't available until the <img> actually decodes —+ // updateDerived() alone can fire before that, so also refresh on load.+ if (_pickerCropSupported(key)) {+ els.preview.addEventListener('load', () => _renderCropOverlay(key));+ }+}++// ====== Crop-preview overlay (VC-29 / H3-01 / VA-02) ========================+// "Faces survive every crop": the server cover-crops a reference image onto+// whatever canvas the render will use, and until this landed it always+// centred that crop with no way to see it coming — a portrait photo lost its+// mouth or its head with no warning, discovered only after a 3-25 minute+// render. This draws the crop the SERVER will actually apply (same math as+// _cover_crop_image in mlx_ltx_panel.py — kept in sync deliberately, see the+// comment on that function) directly on the reference thumbnail, warns when+// more than a quarter of the picture is going to be cut, and lets the user+// drag the kept window to a centre / top / bottom (or left / right)+// position before ever pressing Generate. The chosen position is sent as+// `image_crop_focus` (0..1) and consumed server-side by+// _job_crop_focus()/_cover_crop_image().+//+// Two pickers support it today — 'image' (T2V/I2V AND H3's Image mode+// share this one picker) and 'a2v_image' (Audio → Video's reference slot).+// Both keep the ONE crop bug class fixed the same way rather than each+// growing its own bespoke overlay.+const CROP_OVERLAY_KEYS = ['image', 'a2v_image'];+function _pickerCropSupported(key) { return CROP_OVERLAY_KEYS.indexOf(key) !== -1; }++// The canvas THIS render will actually use, for whichever engine/mode reads+// this picker. 'image' is shared by LTX (T2V/I2V) and H3 — both mirror+// their resolved canvas into the same #width/#height fields (H3 via+// _h3ApplyShape), so one read covers both. 'a2v_image' reads A2V's own+// free-form fields. Returns null when the canvas isn't known yet (or is+// zero — an empty/loading form), meaning "don't draw an overlay".+function _pickerCropTargetCanvas(key) {+ let w, h;+ if (key === 'a2v_image') {+ w = parseInt((document.getElementById('audioStudioWidth') || {}).value || '0', 10);+ h = parseInt((document.getElementById('audioStudioHeight') || {}).value || '0', 10);+ } else {+ w = parseInt((document.getElementById('width') || {}).value || '0', 10);+ h = parseInt((document.getElementById('height') || {}).value || '0', 10);+ }+ if (!(w > 0) || !(h > 0)) return null;+ return { w, h };+}++function _pickerCropFocusEl(key) {+ return document.getElementById(key === 'a2v_image' ? 'a2v_image_crop_focus' : 'image_crop_focus');+}++// Re-render every supported picker's overlay. Called from updateDerived()+// (the one function every relevant state change already routes through:+// quality/length/orientation pills, custom W×H edits, a fresh image pick)+// so no caller has to remember to refresh this on its own.+function refreshPickerCropOverlays() {+ CROP_OVERLAY_KEYS.forEach(k => { try { _renderCropOverlay(k); } catch (e) {} });+}++// Geometry: a line-for-line mirror of _cover_crop_image's max-scale cover+// crop. Returns null when there's effectively no crop (aspect already+// matches, or dims aren't known yet).+function _cropGeometry(key) {+ const els = pickerEls(key);+ if (!els.hidden || !els.hidden.value || !els.preview) return null;+ const nw = els.preview.naturalWidth, nh = els.preview.naturalHeight;+ if (!(nw > 0) || !(nh > 0)) return null;+ const target = _pickerCropTargetCanvas(key);+ if (!target) return null;+ const scale = Math.max(target.w / nw, target.h / nh);+ const scaledW = nw * scale, scaledH = nh * scale;+ // The window, as a FRACTION of the natural (rendered) image — this is+ // what "percent of the picture the crop keeps" means, and it's the same+ // fraction whether measured in natural or scaled-cover pixels.+ const fracW = Math.min(1, target.w / scaledW);+ const fracH = Math.min(1, target.h / scaledH);+ const axis = fracW < fracH ? 'x' : (fracH < fracW ? 'y' : null);+ const cutFraction = axis === 'x' ? (1 - fracW) : axis === 'y' ? (1 - fracH) : 0;+ return { axis, fracW, fracH, cutFraction };+}++function _cropQuickButtonsHtml(axis) {+ const labels = axis === 'x'+ ? [['0', 'Left'], ['0.5', 'Center'], ['1', 'Right']]+ : [['0', 'Top'], ['0.5', 'Center'], ['1', 'Bottom']];+ return labels.map(([v, l]) =>+ `<button type="button" class="crop-quick-btn" data-crop-focus="${v}">${l}</button>`).join('');+}++function _renderCropOverlay(key) {+ const els = pickerEls(key);+ const overlay = document.getElementById(`picker_crop_${key}`);+ const controls = document.getElementById(`picker_crop_controls_${key}`);+ if (!overlay) return;+ const geo = _cropGeometry(key);+ if (!geo || !geo.axis || geo.cutFraction < 0.01) {+ // No meaningful crop (aspect already matches, or nothing picked/known+ // yet) — nothing to warn about and nothing to drag.+ overlay.hidden = true;+ overlay.innerHTML = '';+ if (controls) { controls.hidden = true; controls.innerHTML = ''; }+ return;+ }+ // `.picker-preview` is `max-width:100%;max-height:240px`, so at most+ // aspect ratios it does NOT fill `.picker-drop` (which stretches to the+ // full composer width) — it's letterboxed and centred. The overlay is a+ // SIBLING of the <img>, not its child, so it has to be placed over the+ // image's own rendered box in pixels rather than assuming inset:0 covers+ // it; percentages inside the overlay then map correctly onto the actual+ // photo regardless of how much empty space surrounds it.+ if (els.drop && els.preview) {+ const dropRect = els.drop.getBoundingClientRect();+ const imgRect = els.preview.getBoundingClientRect();+ overlay.style.left = Math.round(imgRect.left - dropRect.left) + 'px';+ overlay.style.top = Math.round(imgRect.top - dropRect.top) + 'px';+ overlay.style.width = Math.round(imgRect.width) + 'px';+ overlay.style.height = Math.round(imgRect.height) + 'px';+ }+ const focusEl = _pickerCropFocusEl(key);+ const focus = Math.min(1, Math.max(0, parseFloat((focusEl && focusEl.value) || '0.5')));+ const axis = geo.axis;+ const frac = axis === 'x' ? geo.fracW : geo.fracH;+ const startPct = (focus * (1 - frac) * 100).toFixed(2);+ const sizePct = (frac * 100).toFixed(2);+ const warn = geo.cutFraction > 0.25;+ const maskStyle = axis === 'x'+ ? `left:0;top:0;width:${startPct}%;height:100%`+ : `left:0;top:0;width:100%;height:${startPct}%`;+ const maskStyle2 = axis === 'x'+ ? `right:0;top:0;width:${(100 - parseFloat(startPct) - parseFloat(sizePct)).toFixed(2)}%;height:100%`+ : `right:0;bottom:0;width:100%;height:${(100 - parseFloat(startPct) - parseFloat(sizePct)).toFixed(2)}%`;+ const winStyle = axis === 'x'+ ? `left:${startPct}%;top:0;width:${sizePct}%;height:100%`+ : `left:0;top:${startPct}%;width:100%;height:${sizePct}%`;+ overlay.hidden = false;+ overlay.className = 'crop-overlay crop-axis-' + axis + (warn ? ' crop-overlay-warn' : '');+ overlay.innerHTML = `+ <div class="crop-mask" style="${maskStyle}"></div>+ <div class="crop-mask" style="${maskStyle2}"></div>+ <div class="crop-window" style="${winStyle}"></div>+ ${warn ? `<div class="crop-warn">Crops out ${Math.round(geo.cutFraction * 100)}% of the photo</div>` : ''}+ `;+ _wireCropDrag(overlay, key, axis);+ if (controls) {+ controls.hidden = false;+ controls.innerHTML = _cropQuickButtonsHtml(axis);+ controls.querySelectorAll('.crop-quick-btn').forEach(b => {+ b.classList.toggle('active', Math.abs(parseFloat(b.dataset.cropFocus) - focus) < 0.01);+ b.onclick = (e) => { e.stopPropagation(); _setCropFocus(key, parseFloat(b.dataset.cropFocus)); };+ });+ }+}++// A sidecar's crop framing (0 = top/left … 1 = bottom/right), 0.5 for any+// render made before the crop preview existed — they were all centred.+function _cropFocusFromParams(p) {+ const v = parseFloat(p && p.image_crop_focus);+ return (isFinite(v) && v >= 0 && v <= 1) ? v : 0.5;+}++function _setCropFocus(key, focus) {+ const focusEl = _pickerCropFocusEl(key);+ if (focusEl) focusEl.value = String(Math.min(1, Math.max(0, focus)));+ _renderCropOverlay(key);+}++// Drag the crop window along whichever axis is actually being cropped.+// Pointer Events cover mouse + touch + pen in one listener set; capture+// keeps the drag tracking even if the pointer leaves the overlay's bounds+// mid-gesture (a fast drag near the edge of a small thumbnail otherwise+// drops the gesture).+function _wireCropDrag(overlay, key, axis) {+ const onMove = (e) => {+ const rect = overlay.getBoundingClientRect();+ const dim = axis === 'x' ? rect.width : rect.height;+ if (!(dim > 0)) return;+ const pos = axis === 'x' ? (e.clientX - rect.left) : (e.clientY - rect.top);+ // The window's CENTRE follows the pointer; invert to the focus fraction+ // the server uses (0 = window at the leading edge, 1 = trailing edge).+ const geo = _cropGeometry(key);+ if (!geo) return;+ const frac = axis === 'x' ? geo.fracW : geo.fracH;+ const centerFrac = Math.min(1, Math.max(0, pos / dim));+ const denom = Math.max(0.0001, 1 - frac);+ const focus = (centerFrac - frac / 2) / denom;+ _setCropFocus(key, focus);+ };+ overlay.onpointerdown = (e) => {+ e.preventDefault();+ try { overlay.setPointerCapture(e.pointerId); } catch (err) {}+ onMove(e);+ overlay.onpointermove = onMove;+ };+ overlay.onpointerup = overlay.onpointercancel = () => { overlay.onpointermove = null; };}+// The overlay is positioned in PIXELS against the image's rendered box+// (see _renderCropOverlay), so a window resize — or the composer column+// reflowing at a narrower pane width — leaves it pointing at the wrong+// rectangle until something else happens to call updateDerived(). Debounced+// so a drag-resize doesn't thrash layout reads every frame.+let _cropOverlayResizeTimer = null;+window.addEventListener('resize', () => {+ clearTimeout(_cropOverlayResizeTimer);+ _cropOverlayResizeTimer = setTimeout(refreshPickerCropOverlays, 120);+});+globalThis._uploadsCache = []; // last fetched list, kept module-level so all// three pickers render the same source data.async function refreshUploadsStrip() {@@ -1493,6 +2523,15 @@ function fmtMemTitle(m) {return [`${used} of ${tot} GB in use`, pr, sw].filter(Boolean).join(' · ');}function fmtMin(s) { if (!s || s < 0) return '—'; const m = Math.floor(s/60); const sec = Math.round(s%60); return m > 0 ? `${m}m ${sec}s` : `${sec}s`; }+// VC-26: compact "~N min" for a queue row/badge — same "~" convention the+// server's own _fmt_eta uses for the tier chips, so a queue row and the+// chip it was submitted from never read as two different formatting+// styles for the same kind of number.+function fmtEtaCompact(sec) {+ if (!sec || sec <= 0) return '';+ const m = Math.round(sec / 60);+ return m < 1 ? '~1 min' : `~${m} min`;+}function snippet(s, n = 70) { if (!s) return ''; s = s.replace(/\s+/g,' ').trim(); return s.length > n ? s.slice(0, n-1)+'…' : s; }function escapeHtml(s) { if (!s) return ''; return s.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }@@ -1537,9 +2576,14 @@ async function api(path, method = 'GET', body = null) {// Prefer the SERVER'S sentence. /models/remove's three refusals are// carefully written ("That's the model this build renders with.") and// throwing a bare status turned every one of them into "…: 400".- let msg = '';- try { msg = ((await r.json()) || {}).error || ''; } catch (e) {}- throw new Error(msg || `${path}: ${r.status}`);+ let msg = '', code = '';+ try { const b = (await r.json()) || {}; msg = b.error || ''; code = b.code || ''; } catch (e) {}+ const err = new Error(msg || `${path}: ${r.status}`);+ // A refusal the SERVER wrote (EST-10) — callers tell it apart from an+ // unreachable panel by these, and act on `code` (pack_missing -> Models).+ err.status = r.status;+ err.code = code;+ throw err;}return r.status === 409 ? { error: 'busy' } : r.json().catch(() => ({}));}@@ -1559,7 +2603,38 @@ globalThis._POLL_FAILS = 0;// read it can recover the message after the fact. Cheap insurance.window._panelBannerLog = window._panelBannerLog || [];+// SYS-10a: clicking Generate while the panel is offline used to do nothing+// visible — an uncaught `Failed to fetch` in the console, no toast, and the+// Now card kept reading "Idle" forever. Mirrors applyPackIncompleteGate's+// shape (disable genBtn, one-line reason in #engineRowNote, own dataset flag+// so it can't collide with the pack-incomplete gate's own note/clear).+function _applyOfflineGate(offline) {+ const genBtn = document.getElementById('genBtn');+ const note = document.getElementById('engineRowNote');+ if (!genBtn) return;+ if (offline) {+ genBtn.disabled = true;+ genBtn.title = "Phosphene can't reach its own server right now — restart it from Pinokio.";+ genBtn.dataset.offlineBlocked = '1';+ if (note) {+ note.innerHTML = escapeHtml(+ "Phosphene is offline — restart it from Pinokio before rendering.");+ note.hidden = false;+ note.dataset.offlineNote = '1';+ }+ } else if (genBtn.dataset.offlineBlocked === '1') {+ genBtn.disabled = false;+ genBtn.removeAttribute('title');+ delete genBtn.dataset.offlineBlocked;+ if (note && note.dataset.offlineNote === '1') {+ note.hidden = true; note.innerHTML = '';+ delete note.dataset.offlineNote;+ }+ }+}+function _setOfflineBanner(visible, msg) {+ _applyOfflineGate(visible);let bar = document.getElementById('panelOfflineBanner');if (visible) {const text = msg || "uploads, chat & renders are paused";@@ -1567,8 +2642,14 @@ function _setOfflineBanner(visible, msg) {bar = document.createElement('div');bar.id = 'panelOfflineBanner';bar.className = 'panel-offline-banner';+ // SYS-10a: this used to be an <img src="/assets/favicon-64.png">, but+ // the whole POINT of this banner is that the server can't be reached+ // -- so the image request failed too and users saw a broken-image+ // glyph instead of an icon. The `ph-warning-fill` symbol is already+ // inlined in the page's own SVG sprite (index.html <head>), so it+ // renders with no network round trip.bar.innerHTML =- '<span class="icon"><img src="/assets/favicon-64.png" alt=""></span>' ++ '<span class="icon"><svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg></span>' +'<span class="label">Phosphene offline</span>' +'<span class="text"></span>' +'<span class="hint">restart from Pinokio</span>';@@ -1755,17 +2836,53 @@ async function repairModel(key) {// memory-pressured Macs: the helper subprocess gets killed by the OS for using// too much RAM and we never get an event back. Tell the user how to recover// instead of leaving them with the engine wording.-function friendlyJobError(raw) {+// H3-22: strip an absolute local path out of a user-facing hint. The backend+// deliberately carries "metrics at /Users/.../state/....json" in the RAW+// error — that string is what the log and a bug report quote — but a path+// under the user's home directory (often their real name, on macOS) has no+// business in a toast/card the user reads on screen. Keep it in the log+// (`raw` is unredacted there); only the display copy gets this.+function _redactLocalPaths(text) {+ return String(text || '').replace(/\((?:see the log above; )?metrics at [^)]+\)/gi, '')+ .replace(/\/Users\/[^\s)]+/g, '(see Logs)')+ .replace(/\s{2,}/g, ' ').trim();+}+function friendlyJobError(raw, engine) {raw = raw || 'unknown error';if (/music engine isn't installed|YuE2 needs about|YuE2 weights.*repair/i.test(raw)) {return { friendly: 'Stopped before generating — the music engine is not ready.',hint: 'Install or repair it from the Phosphene sidebar in Pinokio. Everything else in the panel is unaffected.' };}const rawLower = String(raw).toLowerCase();+ // SYS-07: these two are the #1 and #3 fleet failures (54 + 23 installs in+ // 30 days) and the message used to ask for a crashlog/bug report instead+ // of saying what to change. Rewritten action-first, per the fix: a+ // headline naming what happened, a "Try:" line with the levers that+ // actually work, and the crashlog ask demoted to Details (SYS-07 asks+ // for the offer of a smaller retry too — `smaller: true` flags the Now+ // card to add a "Retry smaller" action next to plain Retry).+ // H3-22: the advice must fit the engine — H3 has no Quick tier, and+ // "Retry smaller" steps an LTX quality/canvas/frame count an H3 job does+ // not use, so it is offered on LTX only.+ const onH3 = engine === 'h3';if (rawLower.includes('sigkill')) {- return { friendly: 'Helper killed by the OS — out of memory (jetsam).',- hint: 'Close memory-heavy apps (Chrome, Slack, iOS Simulator) and try again, ' +- 'or switch Quality to Quick (about half the RAM).' };+ // VC-08/VC-23: say it in plain terms (no "Helper", no "jetsam" up+ // front — that lives in Details); the card's own "Retry smaller" button+ // is the actionable step on LTX (SYS-07, H3-22 above).+ return {+ friendly: 'Your Mac ran out of memory.',+ hint: onH3+ ? 'Close other apps (Chrome, Slack, iOS Simulator) and retry, or '+ + 'try Fast, a shorter length, or Draft (all use less memory).'+ : 'Retry smaller usually fits — or close memory-heavy apps (Chrome, '+ + 'Slack, iOS Simulator) and retry as is, or switch Quality to Quick '+ + '(about half the RAM).',+ ...(onH3 ? {} : { smaller: true }),+ details: 'jetsam (the macOS memory killer) ended the render; returncode -9. '+ + 'If this keeps happening on the lightest setting, this Mac may be '+ + 'too tight on RAM for this mode.',+ docsAnchor: 'memory',+ };}if (rawLower.includes('sigsegv') || rawLower.includes('sigbus')) {return { friendly: 'Helper crashed at the native level (MLX/Metal fault).',@@ -1773,6 +2890,28 @@ function friendlyJobError(raw) {'on github.com/mrbizarro/phosphene/issues so we can fix it.' };}if (rawLower.includes('sigabrt')) {+ // The watchdog signature (kIOGPUCommandBufferCallbackErrorTimeout) is+ // the specific, common case on M1/M2-class GPUs; anything else that+ // aborts at the C level still gets the crashlog ask, just demoted.+ const isWatchdog = rawLower.includes('gpu watchdog') || rawLower.includes('gpu timeout')+ || rawLower.includes('commandbuffercallbackerrortimeout');+ if (isWatchdog) {+ return {+ friendly: 'macOS stopped the render — this Mac ran out of GPU time.',+ hint: (onH3 ? 'Try: Fast or a shorter length' : 'Try: Quick or a 3 s clip')+ + ' · close other apps using the GPU '+ + '(browser video, games, another AI app) · restart the Mac if it '+ + 'keeps happening.',+ ...(onH3 ? {} : { smaller: true }),+ details: 'The macOS GPU watchdog killed a Metal command buffer that ran '+ + 'too long (kIOGPUCommandBufferCallbackErrorTimeout), seen on '+ + 'M1/M2-class GPUs. If it keeps happening on Quick at 3 s, please '+ + 'open an issue with your chip + macOS version and the crashlog at '+ + '~/Library/Logs/DiagnosticReports/python3.11_*.ips to '+ + 'github.com/mrbizarro/phosphene/issues/44.',+ docsAnchor: 'gpu-watchdog',+ };+ }return { friendly: 'Helper hit a C-level assertion and aborted.',hint: 'Share the crashlog at ~/Library/Logs/DiagnosticReports/python3.11_*.crash ' +'on github.com/mrbizarro/phosphene/issues.' };@@ -1783,6 +2922,19 @@ function friendlyJobError(raw) {hint: 'Check the log for the last "step:*" breadcrumb (tells us which ' +'phase died). If memory-pressured, close other apps and retry.' };}+ // SYS-31: the generic "training exited with code N" case (no known+ // signature to name a more specific cause for — the watchdog/OOM/canvas+ // cases above it already have their own specific RuntimeError text+ // server-side). Points at the Logs tab and the new troubleshooting+ // section rather than leaving "see Logs for stack trace" to stand alone.+ if (/training (exited|aborted)/i.test(raw)) {+ return {+ friendly: 'Training stopped before finishing.',+ hint: raw.replace(/^training /i, '').replace(/^\w/, c => c.toUpperCase())+ + ' Check the Logs tab (bottom pane) for the trainer\'s own error.',+ docsAnchor: 'training-failed',+ };+ }// Layer 2. Layer 1 (applyPackIncompleteGate) should have stopped this before// the render started; this fires when it could not — a file removed while the// job sat in the queue, or a surface that reaches make_job without the form.@@ -1795,13 +2947,43 @@ function friendlyJobError(raw) {friendly: 'Stopped before rendering — the model weights are incomplete.',hint: (m ? 'Missing: ' + m[1].trim() + '. ' : '')+ 'Rendering with a file missing produces garbled "mosaic" video rather '- + 'than an error, so Phosphene stops instead. Settings → Models → Resume.',+ + 'than an error, so Phosphene stops instead.',+ // SYS-11: a plain Retry here re-queues the identical job, which fails+ // instantly the same way — the fix is finishing the download, not+ // trying again. `action: 'models'` swaps the Now-card's Retry button+ // for one that actually does that.+ action: 'models',};}- if (rawLower.includes('q8') || rawLower.includes('keyframe')) {+ // VC-24: this used to check the lowercased text for the two bare+ // substrings "q8" and "keyframe" — a traceback or file path for ANY+ // error on the High/Extend/Keyframe lanes routinely contains one of+ // them (`ltx-2.5-mlx-q8/…` in a path, `keyframe_pipeline.py` in a+ // stack frame), so an unrelated OOM or shape error on those lanes was+ // reported as "This mode needs the Q8 model" — sending a user who+ // already has Q8 installed to re-download it. Every REAL "needs Q8"+ // refusal (make_job's RenderRefused for Extend / Keyframe / High) says+ // one of two things verbatim, so match those instead of a bare+ // substring: "(the Q8 model)" when the pack isn't downloaded, or+ // "… hardware tier —" when the Mac can't run it at all.+ if (/\(the q8 model\)|hardware tier\s*—/i.test(raw)) {return { friendly: 'This mode needs the Q8 model.', hint: raw };}- return { friendly: 'Job failed.', hint: raw };+ // H3-22: neither "H3 render timed out — no output for 20 minutes" nor+ // "H3 render exited with code N" matches any branch above (no signal, no+ // "helper exited from"), so both fell to the generic fallback below — the+ // exit-code one WITH its raw metrics_path (an absolute local path, often+ // containing the user's real name on macOS) shown verbatim on screen.+ if (/h3 render (timed out|exited with code)/i.test(raw)) {+ return {+ friendly: rawLower.includes('timed out')+ ? 'H3 stopped — no progress for 20 minutes.'+ : 'H3 render failed.',+ hint: _redactLocalPaths(raw) ||+ 'Try Fast, a shorter length, or Draft; quit Chrome/Slack if memory is tight.',+ };+ }+ return { friendly: 'Job failed.', hint: _redactLocalPaths(raw) || raw };}// ---- Completion alerts ------------------------------------------------------@@ -1822,6 +3004,15 @@ function notifyJobsDone(s) {for (const j of hist) {if (!j || !j.id || !now.has(j.id) || _doneSeen.has(j.id)) continue;if (on) notifyOneJob(j);+ // SYS-35: a finished training run had no bridge back to Video — the+ // only pointer was a link at the bottom of the Train tab (which a+ // user watching the Now card for their training to finish would+ // never be looking at). Announce it right where the completion+ // itself is already detected.+ if (j.status === 'done' && j.params && j.params.mode === 'train'+ && typeof _trainAnnounceReady === 'function') {+ _trainAnnounceReady(j);+ }}_doneSeen = now;}@@ -1912,14 +3103,22 @@ async function poll() {const memPill = document.getElementById('memPill');memPill.innerHTML = `<span class="dot"></span>${fmtMem(m)}`;memPill.title = fmtMemTitle(m);- // 2026-05-20: color the badge by real pressure, not by sticky swap.- // Same reason fmtMem dropped swap from the visible label — swap is- // a high-water mark that only decreases on reboot, so keying the- // danger/warn colors off it kept the badge red long after pressure- // had fully recovered.+ // SYS-19: this used to color by pressure_pct (active+wired+compressed /+ // total) — a USED ratio. macOS routinely sits at 75-90% "used" by that+ // measure while completely idle (it fills RAM with reclaimable cache on+ // purpose), so on an 8-16 GB Mac the chip read amber/red almost all day,+ // including during every healthy render. Colors by pressure_level now+ // (kern.memorystatus_vm_pressure_level — the same signal macOS itself+ // uses to decide whether to reclaim/compress/jetsam-kill: 1 normal, 2+ // warning, 3 critical), and a render in progress downgrades a mere+ // "warning" to the good color — elevated pressure while actively+ // rendering is the expected state, not a problem; level 3 (critical,+ // real jetsam risk) still shows regardless, render or not.+ const rendering = !!(s.running && s.current);+ const lvl = Number(m.pressure_level || 1);let memCls = 'pill-good';- if (m.pressure_pct > 90) memCls = 'pill-danger';- else if (m.pressure_pct > 75) memCls = 'pill-warn';+ if (lvl >= 3) memCls = 'pill-danger';+ else if (lvl === 2 && !rendering) memCls = 'pill-warn';memPill.className = 'pill ' + memCls;// The chip DERIVES from the pills, so it must refresh after the colour// classes land — calling it before memCls kept the chip one poll stale.@@ -1948,19 +3147,23 @@ async function poll() {if (comfyToggle) comfyToggle.checked = false;}- // Helper+ // Engine (the "helper" subprocess — mlx_warm_helper.py — from a+ // creator's chair this row just answers "can I render right now").+ // SYS-19: was "helper warm"/"helper idle" -- internal-process language,+ // and "idle" reads as a problem when it's actually the normal+ // after-timeout state.const hp = document.getElementById('helperPill');if (s.helper && s.helper.alive) {- hp.innerHTML = `<span class="dot"></span>helper warm`;+ hp.innerHTML = `<span class="dot"></span>engine ready`;hp.className = 'pill pill-good';- hp.title = 'Helper subprocess is loaded with pipelines and ready.';+ hp.title = 'The render engine is loaded and ready.';} else {// Helper auto-respawns on the next job (see WarmHelper._ensure). "Cold"// is normal after the idle timeout, not an error — first job after a// cold start eats a ~30s pipeline-load cost.- hp.innerHTML = `<span class="dot"></span>helper idle`;+ hp.innerHTML = `<span class="dot"></span>engine resting`;hp.className = 'pill';- hp.title = 'Helper is idle (auto-exited after the idle timeout). The next queued job will respawn it; expect a one-time ~30s pipeline-load delay.';+ hp.title = 'The render engine unloaded after being idle — normal, not a problem. The next render reloads it, a one-time ~30s delay.';}// Tier pill — what this Mac's RAM tier allows. Click to open the@@ -1984,10 +3187,10 @@ async function poll() {// Models pill — roll-up status: base ready / Q8 ready, plus active download.// Renders as one of:- // "models ↓ Q4 12%" while a download streams (live progress, last hf line)- // "models 3/3" all on disk- // "models 2/3" base ready, Q8 missing → warn color- // "models 0/3" base incomplete → bad color+ // "models ↓ Q4 12%" while a download streams (live progress, last hf line)+ // "models ✓" everything relevant is on disk+ // "models ✓ (1 optional not installed)" base + Q8 core ready, an extra isn't+ // "models 0/3" base incomplete → bad color, still a raw countconst mp = document.getElementById('modelsPill');const dl = s.download && s.download.active ? s.download : null;if (dl) {@@ -1996,18 +3199,31 @@ async function poll() {mp.className = 'pill pill-running';mp.title = `Downloading ${dl.repo_id} — ${dl.last_line || 'starting…'}`;} else {- // Per-repo ready/total counts, matches what the modal shows (3 rows by- // default: Q4 + Gemma + Q8). base_available is a roll-up bool that- // honors the HF-id env-var short-circuit; we use it for the color- // hint, not the count itself.+ // Per-repo ready/total counts, scoped server-side (VC-32) to repos that+ // are actually relevant to THIS generation — never another generation's+ // base pack, so a complete 2.5 install can't read "models 4/12" just+ // because 2.3's own trio and four IC-LoRA extras sit in the same+ // manifest. base_available is a roll-up bool that honors the HF-id+ // env-var short-circuit; we use it for the color hint, not the count.const baseOk = s.base_available;const q8Ok = s.q8_available;const ready = s.repos_ready ?? 0;const total = s.repos_total ?? 0;- mp.innerHTML = `<span class="dot"></span>models ${ready}/${total}`;+ // SYS-19 / VC-32: "models 3/12" read as "25% ready" even on a+ // perfectly healthy install — the denominator counts every OPTIONAL+ // add-on too. Plain outcome instead; the fraction survives in the+ // tooltip for anyone who wants it.+ // (VC-32's phrasing: the raw fraction survives only in the one case it+ // is the right shape — the base itself is incomplete.)+ const missingOptional = Math.max(0, total - ready);+ mp.innerHTML = (baseOk && missingOptional === 0)+ ? `<span class="dot"></span>models ✓`+ : baseOk+ ? `<span class="dot"></span>models ✓ (${missingOptional} optional not installed)`+ : `<span class="dot"></span>models ${ready}/${total}`;mp.className = 'pill ' + (!baseOk ? 'pill-warn' : (q8Ok ? 'pill-good' : ''));mp.title = !baseOk- ? 'Base models incomplete — click to download'+ ? `Base models incomplete (${ready}/${total} on disk) — click to download`: (q8Ok ? 'All models on disk' : 'Q8 not installed (optional — needed for High quality + FFLF)');}// If the modal is open, refresh its rows on each poll so progress updates.@@ -2025,6 +3241,16 @@ async function poll() {if (typeof applyPackIncompleteGate === 'function') {try { applyPackIncompleteGate(s); } catch (e) {}}+ // SYS-03: also re-checked every poll (not just on tab-open) so a Train+ // tab opened before the first /status response resolves still gates+ // itself the moment RAM data arrives, and so the gate applies even if+ // trainInit() hasn't run yet in this session.+ if (typeof trainApplyRamGate === 'function') {+ try { trainApplyRamGate(); } catch (e) {}+ }+ if (typeof applyFirstRunCard === 'function') {+ try { applyFirstRunCard(s); } catch (e) {}+ }// Queue pill + tab badge. Animate the bottom-pane Queue badge with// a brief scale-up "pop" when the count goes up — draws the eye to@@ -2037,7 +3263,12 @@ async function poll() {const qb = document.getElementById('queueBadge');const prevQueueLen = window._lastQueueLen ?? 0;if (s.queue.length) {- qb.textContent = s.queue.length;+ // VC-26: "a queue total in the tab badge ('10 · 27 min')". s.eta_sec is+ // the server's own sum of each row's priced/averaged ETA — never+ // recomputed client-side, so this can't drift from the per-row numbers.+ const etaTxt = fmtEtaCompact(s.eta_sec);+ qb.textContent = etaTxt ? `${s.queue.length} · ${etaTxt.replace('~', '')}` : String(s.queue.length);+ qb.title = etaTxt ? `${s.queue.length} queued, about ${etaTxt} total` : `${s.queue.length} queued`;qb.style.display = '';if (s.queue.length > prevQueueLen) {qb.classList.remove('bump');@@ -2053,6 +3284,23 @@ async function poll() {}window._lastQueueLen = s.queue.length;+ // SYS-10d / SYS-37: Stop was red and clickable at all times, including+ // while nothing was running or queued — clicking it then was a silent+ // no-op (`/stop` with nothing to stop). Disable every Stop button (six+ // copies, one per tab) whenever there is nothing for it to do.+ // Integration note: VC-05 (safety) disables Stop on the same poll via+ // [data-role="stop-btn"]; both classes sit on the same six buttons, so the+ // rule lives here once. requestStop() needs a CURRENT job — a queue that is+ // only waiting (paused, or between jobs) has nothing for Stop to stop;+ // Clear queue is its control.+ const stopActive = !!(s.running && s.current);+ document.querySelectorAll('.js-stop-btn').forEach(btn => {+ btn.disabled = !stopActive;+ btn.title = stopActive+ ? (s.queue.length ? `Stop the current render (${s.queue.length} more queued)` : 'Stop the current render')+ : 'Nothing is rendering';+ });+// Job pillconst jp = document.getElementById('jobPill');if (s.running && s.current) {@@ -2067,6 +3315,22 @@ async function poll() {}document.getElementById('pauseBtn').textContent = s.paused ? 'Resume queue' : 'Pause queue';+ _syncDestructiveQueueButtons(s);+ _syncHiddenFilterToggle(s);++ // SYS-32: show the breaker's reason (if any) right above Generate. A+ // manual Pause has no "cause" (paused_reason is null then) and gets no+ // notice — only the breaker's automatic pause does.+ const breakerNotice = document.getElementById('breakerNotice');+ if (breakerNotice) {+ if (s.paused && s.paused_reason) {+ document.getElementById('breakerNoticeText').textContent =+ `Queue paused: ${s.paused_reason}. Fix the cause, then Resume.`;+ breakerNotice.hidden = false;+ } else {+ breakerNotice.hidden = true;+ }+ }// Q8 / High enable.//@@ -2219,11 +3483,43 @@ async function poll() {const shape = [cur.width && cur.height ? `${cur.width}×${cur.height}` : null,(cur.frames != null && cur.frames !== '') ? `${cur.frames}f` : null].filter(Boolean).join(' · ');+ // H3-04: Fast/Best used to be invisible the moment Generate was+ // pressed — the Now card showed mode/shape/time only. prog.h3_speed is+ // the server's own record of what this render is ACTUALLY running+ // (set from the render loop itself, not guessed from a form field that+ // could be stale); h3JobShapeLabel/h3JobSpeedLabel fall back to the+ // submitted params when prog hasn't reported yet (the load phase's+ // very first tick).+ const isH3 = cur.engine === 'h3';+ const h3Speed = isH3+ ? ((prog && prog.h3_speed) ? (prog.h3_speed === 'fast' ? 'Fast' : 'Best')+ : (typeof h3JobSpeedLabel === 'function' ? h3JobSpeedLabel(cur) : ''))+ : '';+ const h3Shape = isH3 && typeof h3JobShapeLabel === 'function' ? h3JobShapeLabel(cur) : '';const baseMeta = (cur.mode === 'image')? `image · ${cur.aspect || '?'} · n=${cur.n || '?'} · ${cur.engine_override || 'auto'} · ${timing}`- : [cur.mode, shape, timing].filter(Boolean).join(' · ');- nowCard.querySelector('.meta').innerHTML = phaseLabel- ? `${baseMeta}<br><span style="color:var(--muted)">${escapeHtml(phaseLabel)}</span>`+ : isH3+ ? [h3Shape, h3Speed, timing].filter(Boolean).join(' · ')+ : [cur.mode, shape, timing].filter(Boolean).join(' · ');+ // The pace warning (server-computed: measured per-step vs. this+ // shape's own model, H3-04) rides under phaseLabel the same way a+ // phase note already does, so it never competes with the timing line+ // for space and never needs its own layout slot.+ const paceNote = (prog && prog.h3_pace_warning) || '';+ // VC-02(c): a clamp is a fact about the render that just started, not a+ // detail that only shows up in the log. generation_clamp_notes carries+ // it on the job's own params — surface it here so a smaller-than-picked+ // canvas is said WHILE it's rendering, not discovered after the wait.+ const clampNotes = Array.isArray(cur.generation_clamp_notes) ? cur.generation_clamp_notes : [];+ const underline = [+ phaseLabel ? `<span style="color:var(--muted)">${escapeHtml(phaseLabel)}</span>` : '',+ paceNote ? `<span style="color:var(--danger, #f85149)">${escapeHtml(paceNote)}</span>` : '',+ clampNotes.length+ ? `<span class="now-clamp-note" title="${escapeHtml(clampNotes.join('; '))}">⚠ ${escapeHtml(clampNotes[0])}</span>`+ : '',+ ].filter(Boolean).join('<br>');+ nowCard.querySelector('.meta').innerHTML = underline+ ? `${baseMeta}<br>${underline}`: baseMeta;livePreviewData = normalizeLivePreview(s, prog);renderNowPreview(s, prog, livePreviewData);@@ -2252,27 +3548,61 @@ async function poll() {// killed by the OS for using too much RAM and we never get an// event back. Tell the user how to recover instead of leaving them// with the engine wording.- const { friendly, hint } = friendlyJobError(last.error || 'unknown error');+ const { friendly, hint, smaller, details, action, docsAnchor } = friendlyJobError(last.error || 'unknown error',+ last.params && last.params.engine);nowCard.querySelector('.ttl').innerHTML =`<span style="color: var(--danger, #f85149)"><svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>${escapeHtml(friendly)}</span>`;+ // SYS-07: `details` (crashlog / bug-report ask) goes behind a <details>+ // disclosure instead of inline, so the actionable "Try:" hint isn't+ // buried under a paragraph most people can't act on. Same pattern as+ // the H3 install card's own "Details for troubleshooting" (queue.js+ // _h3InstallCardContent). `details` is a fixed string we compose+ // ourselves (never user/engine-supplied), so it's safe unescaped.nowCard.querySelector('.meta').innerHTML =`<span style="color: var(--muted)">${escapeHtml(snippet(last.params.label || last.params.prompt, 80))}</span>` +` <span style="color: var(--muted)">· ${escapeHtml(last.params.mode)} · ${last.params.width}×${last.params.height}</span>` +- `<br><span style="color: var(--text)">${escapeHtml(hint)}</span>`;- // Action row: Retry (re-submit same params via /queue/retry) +- // Dismiss (mark this id as handled so the next idle poll clears- // the card). Both buttons live in a stable sibling element of- // .ttl so the click handlers survive every poll-driven rewrite.- // A single delegated listener on document (installed once at- // boot) catches the clicks via data-action so we never lose them- // to an inline-handler race.+ `<br><span style="color: var(--text)">${escapeHtml(hint)}</span>` ++ // SYS-33: errors rarely linked to Docs even where a section already+ // existed. docsAnchor names one of troubleshooting.md's own anchors.+ (details ? `<details class="h3-diag"><summary>Details for troubleshooting</summary><p>${details}` ++ (docsAnchor ? ` <a href="#" onclick="openDocs('troubleshooting','${docsAnchor}');return false;">Learn more →</a>` : '') ++ `</p></details>` : '');+ // Action row: Retry (re-submit same params via /queue/retry), plus+ // Retry smaller for failure classes a same-size retry can't fix+ // (SYS-07: GPU watchdog timeout, OOM jetsam) + Dismiss. All three+ // live in a stable sibling element of .ttl so the click handlers+ // survive every poll-driven rewrite. A single delegated listener on+ // document (installed once at boot) catches the clicks via+ // data-action so we never lose them to an inline-handler race.if (actionsEl) {actionsEl.dataset.jobId = String(last.id);+ // SYS-07 x VC-08: the one-click action on an OOM / GPU-watchdog card+ // used to be "Retry" of the exact same size and length — the one+ // guaranteed to fail again after another 10+ minutes. friendlyJobError+ // flags `smaller` for those classes (LTX only — H3-22); the card then+ // offers BOTH: "Retry smaller" first (server-side: one quality rung+ // down, a grid-snapped 0.75x canvas and about half the length — the+ // canvas is what actually frees memory, a quality step alone keeps+ // the stored width/height) and "Retry as is" for the user who wants+ // to try unchanged (a closed Chrome tab, a swap install).actionsEl.innerHTML =- `<button type="button" class="now-card-retry" data-action="retry" ` +- `title="Re-submit this job with the same params">` +- `<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise"/></svg>` +- `<span>Retry</span></button>` ++ (action === 'models'+ ? `<button type="button" class="now-card-retry" onclick="openModelsModal()" ` ++ `title="A retry can't fix a missing file — finish the download instead">` ++ `<svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg>` ++ `<span>Open Models</span></button>`+ : smaller+ ? `<button type="button" class="now-card-retry" data-action="retry-smaller" ` ++ `title="Try again smaller — one quality rung down, a smaller canvas and about half the length">` ++ `<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise"/></svg>` ++ `<span>Retry smaller</span></button>` ++ `<button type="button" class="now-card-retry" data-action="retry" ` ++ `title="Re-submit this job with the same params, unchanged">` ++ `<span>Retry as is</span></button>`+ : `<button type="button" class="now-card-retry" data-action="retry" ` ++ `title="Re-submit this job with the same params">` ++ `<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise"/></svg>` ++ `<span>Retry</span></button>`) +`<button type="button" class="now-card-dismiss" data-action="dismiss" ` +`title="Dismiss this failure" aria-label="Dismiss this failure">` +`<svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>`;@@ -2367,6 +3697,12 @@ async function poll() {// A One Shot is named as one: the t2v/i2v underneath is how it is// rendered, not what was asked for.const _take = j.params.take && j.params.take.seconds;+ // H3-04: a queued H3 job used to show only "t2v · 768x448 · 73f" —+ // no shape name, no Fast/Best. Fast prices at a fraction of Best on+ // the identical cell, so it's the single biggest lever on how long+ // this row will actually take.+ const h3Tag = (j.params.engine === 'h3' && typeof h3JobSpeedLabel === 'function')+ ? h3JobSpeedLabel(j.params) : '';const params = j.params.engine === 'music'? `YuE2 · ${j.params.music_quality} · max ${j.params.music_max_seconds}s`: (j.params.mode === 'image')@@ -2375,7 +3711,16 @@ async function poll() {? `${FACE_FIX_NAME} · 2×`: _take? `One Shot · ${_take} s · ${j.params.width}×${j.params.height}`+ : h3Tag+ ? `${(typeof h3JobShapeLabel === 'function' && h3JobShapeLabel(j.params)) || 'Hailuo H3'} · ${h3Tag}`: `${j.params.mode} · ${j.params.width}×${j.params.height} · ${j.params.frames}f`;+ // VC-02(c): "1024×512" in the row above with no explanation is exactly+ // the report — the number that governs memory safety was never shown+ // anywhere a user would see it before the render finished. A clamped+ // job's own params carry WHY, so print it right next to the size.+ const clampNotes = Array.isArray(j.params.generation_clamp_notes) ? j.params.generation_clamp_notes : [];+ const clampBadge = clampNotes.length+ ? ` <span class="clamp-note" title="${escapeHtml(clampNotes.join('; '))}">⚠ clamped</span>` : '';// Which film this job is a shot of. A pure function of immutable params,// so the qSig memoisation above needs no change.const sb = /^sb:([^#]+)#(\d+)$/.exec(j.params.session_tag || '');@@ -2387,13 +3732,36 @@ async function poll() {? `<span class="sb-rowtags"><span class="badge sb-badge" title="${escapeHtml(j.params.label || '')}">S${sb[2].padStart(2,'0')}/${sbTotal}</span>`+ sbEngineChip(j.params.engine || 'ltx') + `</span>`: '';+ // VC-26: an ETA per row, from the same priced number the badge total+ // sums (routes_queue.py stamps job.eta_sec on every queue item).+ const etaTxt = fmtEtaCompact(j.eta_sec);+ const etaChip = etaTxt ? `<span class="q-eta">${etaTxt}</span>` : '';+ // Reorder: plain up/down, hidden at the list's own boundaries so a+ // click can never be a silent no-op. `stopPropagation` keeps a+ // reorder click from also firing the row's edit-on-click below.+ // ph-arrow-up is the only up/down glyph in the sprite; the down+ // button reuses it rotated 180deg (.q-reorder-down in panel.css)+ // rather than adding a near-duplicate symbol.+ const upBtn = i > 0+ ? `<button title="Move up" onclick="event.stopPropagation();reorderQueuedJob('${j.id}','up')"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-up"/></svg></button>`+ : '';+ const downBtn = i < s.queue.length - 1+ ? `<button title="Move down" class="q-reorder-down" onclick="event.stopPropagation();reorderQueuedJob('${j.id}','down')"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-up"/></svg></button>`+ : '';+ // Edit is scoped to the plain video modes editQueuedJob() actually+ // knows how to restore into #genForm (see its own comment) — a+ // batch/One-Shot/image/music/upscale row stays view-only rather than+ // silently mis-restoring into the wrong tab.+ const editable = !j.params.take && j.params.engine !== 'music'+ && !['image', 'train', 'upscale', 'sharp_export'].includes(j.params.mode);return `- <li>+ <li${editable ? ` class="q-row-editable" onclick="editQueuedJob('${j.id}')" title="Click to edit this queued job"` : ''}><span class="pos">#${i+1}</span><span class="ttl" title="${escapeHtml(j.params.prompt)}">${escapeHtml(j.params.label || snippet(j.params.prompt, 60))}</span>${sbBadge}- <span class="params">${params}</span>- <button title="Remove" onclick="removeJob('${j.id}')"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>+ <span class="params">${params}${clampBadge}${etaChip}</span>+ <span class="q-reorder">${upBtn}${downBtn}</span>+ <button title="Remove" onclick="event.stopPropagation();removeJob('${j.id}')"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button></li>`;}).join('');window._lastQueueSig = qSig;@@ -2422,7 +3790,7 @@ async function poll() {// here would abort the whole poll (outputs, version, banners). Guard, never// return, exactly like the queue memo above.const hSig = filterPhotos + '|' + filtered.slice(0, 20)- .map(j => j.id + '|' + j.status + '|' + (j.output_path || '')).join(';');+ .map(j => j.id + '|' + j.status + '|' + (j.output_path || '') + '|' + (j.warning || '')).join(';');if (window._lastHistorySig !== hSig) {window._lastHistorySig = hSig;if (!filtered.length) {@@ -2647,6 +4015,99 @@ async function poll() {// Scoped to the SELECTED tier on purpose. A T2V user on Balanced is not nagged// about weights High would need — the existing #engineRowNote contract is "the// one-line reason a gate fired", not a standing inventory.+// SYS-16: "Make your first clip" -- shown when BOOT.first_run (server-+// computed: has this install ever finished a render), hidden the moment+// a render actually finishes in this session (not just at next page load)+// or on manual dismiss. Re-checked every poll, same pattern as+// applyPackIncompleteGate/trainApplyRamGate above.+function applyFirstRunCard(s) {+ const card = document.getElementById('firstRunCard');+ if (!card || !BOOT.first_run) { if (card) card.style.display = 'none'; return; }+ const dismissed = !!(s.settings && s.settings.first_run_card_dismissed);+ const everFinished = (s.history || []).some(j => j && j.status === 'done');+ // BOOT.first_run reads analytics_first_render_reported, which is only+ // ever set with analytics ON — an install with analytics off that has+ // rendered hundreds of clips would still be greeted as brand new. A+ // gallery with anything in it is not a first run.+ const hasOutputs = (s.outputs || []).length > 0;+ const show = !(dismissed || everFinished || hasOutputs);+ card.style.display = show ? '' : 'none';+ const etaEl = document.getElementById('firstRunEta');+ if (show && etaEl && !etaEl.textContent) {+ const eta = _firstRunEta();+ if (eta) etaEl.textContent = ` — about ${String(eta).replace(/^~\s*/, '')} on this Mac`;+ }+}++async function dismissFirstRunCard() {+ try {+ const fd = new URLSearchParams();+ fd.set('first_run_card_dismissed', 'true');+ await fetch('/settings', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: fd,+ });+ } catch (e) { /* best effort — UI still hides locally */ }+ const card = document.getElementById('firstRunCard');+ if (card) card.style.display = 'none';+ if (LAST_STATUS && LAST_STATUS.settings) {+ LAST_STATUS.settings.first_run_card_dismissed = true;+ }+}++// Loads one of the three starter prompts and queues it directly, at this+// Mac's safe default (Balanced — the server-side hardware clamp still+// applies on a Compact-tier Mac, same as any other Balanced render).+function useFirstRunPrompt(btn) {+ const text = btn && btn.dataset && btn.dataset.firstRunPrompt;+ if (!text) return;+ try { setMode('t2v'); } catch (e) {}+ try { setQuality('balanced'); } catch (e) {}+ const p = document.getElementById('prompt');+ if (p) p.value = text;+ dismissFirstRunCard();+ const form = document.getElementById('genForm');+ if (form && typeof form.requestSubmit === 'function') {+ form.requestSubmit();+ } else if (form) {+ form.dispatchEvent(new Event('submit', { cancelable: true }));+ }+}++// SYS-22: jumps the form-pane to Quality/Length -- at 1280-1440px (worse+// below) that section renders underneath the sticky footer, reachable+// only by scrolling past it first, which most people never discover.+// Called from the footer's own derived-summary button (index.html).+function scrollToShotSetup() {+ const onH3 = typeof currentEngine === 'function' && currentEngine() === 'h3';+ const target = document.getElementById(onH3 ? 'h3QualityGroup' : 'qualityGroup');+ const pane = document.querySelector('.form-pane');+ if (!target || !pane) return;+ // Quality/Length lives inside a <details class="shot-setup"> disclosure+ // that starts CLOSED -- scrollIntoView on content inside a closed+ // <details> is a silent no-op (nothing is actually laid out to scroll+ // to), which is what made this jump button do nothing on first try.+ const details = target.closest('details');+ const wasClosed = details && !details.open;+ if (wasClosed) details.open = true;+ // Opening <details> changes layout asynchronously from the browser's+ // point of view -- scrollIntoView called in the same tick used the+ // PRE-open geometry and landed short. One rAF is enough for the reflow+ // to settle (confirmed live: 0 rAF = old position, 1 rAF = correct).+ const doScroll = () => {+ // 'auto' (instant), not 'smooth': verified live that 'smooth' can+ // silently fail to complete right after a <details> open changes+ // layout in the same gesture -- 'auto' reliably lands, and the+ // highlight below still gives the eye something to follow.+ target.scrollIntoView({ behavior: 'auto', block: 'center' });+ target.classList.add('shot-setup-jump-highlight');+ setTimeout(() => target.classList.remove('shot-setup-jump-highlight'), 1200);+ };+ if (wasClosed) requestAnimationFrame(() => requestAnimationFrame(doScroll));+ else doScroll();+}+function applyPackIncompleteGate(s) {const note = document.getElementById('engineRowNote');const genBtn = document.getElementById('genBtn');@@ -2665,6 +4126,34 @@ function applyPackIncompleteGate(s) {}};if (engine !== 'ltx') { clear(); return; }+ // VC-10: the base pack (the Q4 distilled transformer + its text encoder)+ // is what EVERY LTX render needs, no matter which quality/pack the form+ // is pointed at — this used to be considered "already a hard block in+ // the models card above" (updateModelsCard's red "Base models needed"+ // card), but that card only ever offered a Download button; it never+ // touched #genBtn. Clicking Generate still queued the job, which then+ // burned 15-25 minutes producing "mosaic" garbage (the server-side+ // refusal — ltx_pack_preflight("q4", ...) in run_job_inner — only fires+ // mid-render, after Gemma has already loaded). Check this FIRST, ahead+ // of the q8-specific logic below, since a missing base pack blocks+ // every quality, not one tier.+ if (!s.base_available) {+ const missing = s.base_missing || [];+ const names = missing.map(f => String(f).split('/').pop());+ const shown = names.slice(0, 2).join(', ') + (names.length > 2 ? ' …' : '');+ const n = missing.length || 1;+ note.innerHTML = escapeHtml(+ `Finish the model download first (${n} file${n === 1 ? '' : 's'}`+ + (shown ? ` — ${shown}` : '') + ').')+ + ` <a href="#" onclick="openModelsModal();return false;">Open Models →</a>`;+ note.hidden = false;+ note.dataset.packNote = '1';+ genBtn.disabled = true;+ genBtn.title = "The base model weights aren't all downloaded yet — "+ + 'open Settings → Models to finish.';+ genBtn.dataset.packBlocked = '1';+ return;+ }let cell = (typeof ltxCurrentCell === 'function') ? ltxCurrentCell() : null;const charId = (document.getElementById('characterIdInput') || {}).value || '';const charChip = charId@@ -2681,9 +4170,8 @@ function applyPackIncompleteGate(s) {// #quality directly.const pack = (cell && cell.pack)|| (_qualityUsesHq((document.getElementById('quality') || {}).value) ? 'q8' : 'q4');- // Only the q8 lane can be half-installed in a way the user can act on: an- // incomplete BASE pack is already a hard block in the models card above, and- // duplicating it here would give the same fact two voices.+ // Base incompleteness is handled above, unconditionally (VC-10) — from+ // here on this function only has the q8-specific case left to check.if (pack !== 'q8') { clear(); return; }const missing = [].concat(s.q8_missing || [],@@ -2780,15 +4268,23 @@ document.addEventListener('DOMContentLoaded', () => {// reference image and the same prompt. Does NOT auto-submit; the user// keeps the chance to tweak prompt/seed/quality before clicking// Generate. Reversible (changing the image picker resets it).-async function retryJob(jobId) {+async function retryJob(jobId, opts) {// Re-submit a failed/cancelled job by its id. Server side endpoint- // /queue/retry takes the original job's id, copies its params verbatim- // into a fresh queue entry, and returns the new id. Toast on success- // (the Now/Queue pane will pick the new entry up on the next poll).+ // /queue/retry takes the original job's id, copies its params into a+ // fresh queue entry, and returns the new id. Toast on success (the+ // Now/Queue pane will pick the new entry up on the next poll).+ // opts.smaller (SYS-07) asks the server to step quality down one rung+ // and shrink the canvas + roughly halve the length instead of copying+ // the failed job's size verbatim; opts.overrides (VC-08) applies a small+ // allowlisted set of params (quality, frames) — API callers only now.if (!jobId) return;try {const fd = new URLSearchParams();fd.set('id', jobId);+ if (opts && opts.smaller) fd.set('smaller', '1');+ if (opts && opts.overrides && Object.keys(opts.overrides).length) {+ fd.set('overrides', JSON.stringify(opts.overrides));+ }const r = await fetch('/queue/retry', { method: 'POST', body: fd });let data = {};try { data = await r.json(); } catch (e) { /* keep empty */ }@@ -3006,6 +4502,68 @@ function _songCardName(o) {: m.cover ? 'cover' : '';return `${escapeHtml(title)}${chip ? ` <span class="song-badge">${chip}</span>` : ''}`;}++// VC-36: the card's primary line — a filename ("integrated_multimodal_d…")+// tells nobody anything; a prompt does. Songs keep their own naming+// (_songCardName reads the title Music Studio gave it); everything else+// prefers the server's prompt snippet (list_outputs' `prompt` field, VC-36),+// falling back to the filename only when there isn't one (an older render,+// or a file with no sidecar).+function _cardTitleText(o) {+ if (o && o.music) return _songCardName(o);+ const p = (o && o.prompt || '').trim();+ if (!p) return escapeHtml(o.name);+ const words = p.split(/\s+/);+ const head = words.slice(0, 8).join(' ');+ return escapeHtml(head) + (words.length > 8 ? '…' : '');+}++// VC-36: the "Balanced · 1280×720" / "t2v · 1280×720" chip row — quality+// and delivered size for an LTX clip, tier label and spec for an H3 one.+// Reads only fields already in the /status payload (o.quality/o.frames,+// VC-18/37's lift; o.h3_tier, already lifted) plus BOOT/H3's own tables —+// no extra request per card.+// Codex UI-9: /poster answers `immutable, max-age=7d` (right for a given+// source), but its URL carried only the path — so a clip replaced at the same+// path kept its OLD thumbnail in the browser for up to a week while playback+// showed the new one. The URL now carries the source's version: the same+// mtime stamp the server puts on o.url (`&v=`) plus the byte size, i.e. the+// same (mtime, size) the server's own poster cache is keyed on.+function _posterVersionQuery(o) {+ const m = String((o && o.url) || '').match(/[?&]v=([^&]+)/);+ const mb = o ? Number(o.size_mb) : NaN;+ const parts = [];+ if (m) parts.push(m[1]);+ if (isFinite(mb) && mb > 0) parts.push(String(Math.round(mb * 1048576)));+ return parts.length ? '&v=' + encodeURIComponent(parts.join('-')) : '';+}++// Codex UI-8 / EST-12: the size is the FILE's (list_outputs reads it from the+// mp4 header), never the quality preset's or H3 tier's default canvas — those+// labelled a square, portrait, native-export or Sharp-exported clip with the+// preset's landscape delivery size. Unknown dimensions print no size at all.+function _cardModeSizeChip(o) {+ const bits = [];+ if (o && o.mode) bits.push(o.mode);+ const w = o ? Number(o.width) : 0, h = o ? Number(o.height) : 0;+ if (w > 0 && h > 0) bits.push(`${w}×${h}`);+ return bits.join(' · ');+}+// The default tier's own priced cell (VC-28 stamps exactly one "is_default"+// entry) — the ETA SYS-16's "Make your first clip" card quotes, reused rather+// than re-derived so the card can never disagree with the Quality chips.+// (4.17: VC-41's separate empty-gallery card was folded into SYS-16's — one+// first-run card, in the form, with this Mac's price on it.)+function _firstRunEta() {+ try {+ const tiers = ((BOOT.ltx || {}).tiers) || [];+ const cell = tiers.find(t => t.is_default) || tiers.find(t => t.key === 'balanced_5s');+ if (!cell) return '';+ const fr = cell.fleet_range;+ return (fr && fr.eta_range) || cell.eta_range || cell.eta || '';+ } catch (e) { return ''; }+}+function renderCarousel() {const el = document.getElementById('carousel');const visible = filteredMainOutputs();@@ -3025,7 +4583,18 @@ function renderCarousel() {: mainOutputsFilter === 'audio' ? 'No audio outputs yet — write a song in Audio → Compose.': mainOutputsFilter === 'videos' ? 'No video outputs yet.': 'No outputs in this view yet.';- el.innerHTML = `<div class="empty-msg">${msg}</div>`;+ // VC-40: this used to be a plain glowing blue dot (.empty-msg::before)+ // - no motion, but blue + glow + alone above the text reads as a+ // stuck spinner, especially on a first boot with nothing else on+ // screen to contradict it. A real icon, picked for the view the user+ // is actually looking at, reads as "empty" instead of "loading".+ const icon = q ? 'ph-magnifying-glass'+ : mainOutputsFilter === 'photos' ? 'ph-image'+ : mainOutputsFilter === 'audio' ? 'ph-music-notes'+ : 'ph-film-strip';+ el.innerHTML = `<div class="empty-msg">`+ + `<svg class="ph empty-msg-icon" aria-hidden="true"><use href="#${icon}"/></svg>`+ + `<div>${msg}</div></div>`;fitStagePlayer();return;}@@ -3049,41 +4618,25 @@ function renderCarousel() {const pathAttr = JSON.stringify(o.path).replace(/"/g, '"');const isPhoto = outputKind(o) === 'image';const isAudio = outputKind(o) === 'audio';- // Thumbnail markup branches on kind. Videos use <video> with a- // mid-clip seek (2.5s — LTX clips are 5s at 24fps and the first- // half-second is often a dark fade-in, so seeking to the middle- // gets a representative frame). Photos use <img> directly with+ // Thumbnail markup branches on kind. Photos use <img> directly with// the same /image?path=… cache-bust URL the server stamped.//- // PERF: with the auto-fetch landing 658+ entries into the carousel,- // `preload="metadata"` on every <video> stalled the page — each- // metadata fetch downloads the moov atom + enough bytes to render- // the t=2.5 poster frame (~hundreds of KB), and 586 of those- // saturate the browser's 6-connection limit. The user's click-to-- // play request then queues behind ~580 thumbnail fetches and looks- // "stuck."- //- // Fix: ship the <video> with `data-src` instead of `src`. An- // IntersectionObserver (wired below renderCarousel) promotes- // `data-src` to `src` only when the card is within the viewport's- // ~2-screen-tall preload margin. Off-screen cards stay completely- // dormant. <img> already has loading="lazy" so it's fine; we keep- // the existing markup for photos.+ // VC-31/36: video cards used to BE a live <video preload="metadata">+ // seeked to 2.5s — with a large library the first paint was black+ // cards while each clip's moov atom downloaded (hundreds of KB per+ // card, 586 of them saturating the browser's 6-connection limit; a+ // click-to-play then queued behind ~580 thumbnail fetches and looked+ // "stuck"). Now a plain <img> pointed at /poster?path=… — one cached+ // ffmpeg-extracted JPEG frame per clip (_ensure_video_poster,+ // generated once on first request, served from disk after that).+ // loading="lazy" alone now does the deferred-fetch job the old+ // data-src + IntersectionObserver dance existed for — no observer to+ // wire up or clean up.const thumbHtml = isAudio? `<span class="music-card-note" aria-hidden="true">♪</span><audio class="train-voice-audio music-card-player" controls preload="metadata" src="${escapeHtml(o.url)}" onclick="event.stopPropagation()"></audio>`: isPhoto? `<img class="car-thumb" src="${_thumbUrl(o.url, 480)}" alt="${escapeHtml(o.name)}" loading="lazy">`- // Hover-scrub: on enter, jump to 0 and play silently at 0.6×;- // on leave, pause + snap back to the static 2.5s preview frame.- // The play() promise can reject during a fast scrub (browser- // says "play interrupted by pause") — swallow it.- // src is deferred — the IntersectionObserver below promotes- // data-src → src when the card scrolls into view. preload stays- // metadata so once src is set, the t=2.5 poster frame renders- // without the user having to hover.- : `<video data-src="${o.url}#t=2.5" preload="metadata" muted playsinline- onmouseenter="if (!this.src && this.dataset.src) this.src = this.dataset.src; this.currentTime=0; this.playbackRate=0.6; this.play().catch(()=>{})"- onmouseleave="this.pause(); this.currentTime=2.5; this.playbackRate=1"></video>`;+ : `<img class="car-thumb" src="/poster?path=${encodeURIComponent(o.path)}${_posterVersionQuery(o)}" alt="${escapeHtml(o.name)}" loading="lazy">`;// Per-card actions (revealed on hover) — kept deliberately minimal:// * Photos get a small "Animate" chip (turns the still into i2v).// * Everything gets a delete (×) chip.@@ -3111,9 +4664,16 @@ function renderCarousel() {: '';// Upscale & Face Fix lives on the big player only (owner 2026-09-17: on the// thumbnails it was clutter).+ // Codex UI-5: the card's Enter/Space handler answers only for the CARD+ // itself (target === currentTarget). Keydown bubbles, so without that+ // guard Enter on a focused Info/Trash/Animate button — or Space on the+ // audio card's own controls — selected the card and preventDefault()+ // cancelled the button's own activation.return `<div class="car-card${o.path === activePath ? ' active' : ''}"- data-path="${escapeHtml(o.path)}" onclick="selectOutput(${pathAttr})">+ data-path="${escapeHtml(o.path)}" onclick="selectOutput(${pathAttr})"+ role="button" tabindex="0" aria-label="${escapeHtml(o.name)} — select"+ onkeydown="if(event.target===event.currentTarget&&(event.key==='Enter'||event.key===' ')){event.preventDefault();selectOutput(${pathAttr});}"><div class="car-thumb-wrap">${thumbHtml}${o.has_sidecar@@ -3129,11 +4689,12 @@ function renderCarousel() {</div></div><div class="info">- <div class="name" title="${escapeHtml(o.name)}">${_songCardName(o)}</div>+ <div class="name" title="${escapeHtml(o.prompt || o.name)}">${_cardTitleText(o)}</div><div class="sub" title="Render time · file size">${o.sb ? `<span class="badge sb-badge" title="Shot ${o.sb.n} of a storyboard — click to open it"onclick="event.stopPropagation(); sbOpenFromClip('${escapeHtml(o.sb.id)}')">S${String(o.sb.n).padStart(2,'0')}</span> · ` : ''}${_outputDurationLabel(o)} · ${o.size_mb.toFixed(1)} MB</div>+ ${(() => { const chip = _cardModeSizeChip(o); return chip ? `<div class="card-chip-row">${escapeHtml(chip)}</div>` : ''; })()}</div></div>`;}).join('');@@ -3150,31 +4711,9 @@ function renderCarousel() {</button></div>`);}- // Lazy-load the just-rendered video thumbnails. <img> entries already- // have native loading="lazy" but <video> has no equivalent, so we- // observe each carousel card and promote `data-src` → `src` only when- // it crosses into a 2-screen-tall preload margin. Without this, all- // 586 videos start downloading their poster-frame bytes at once when- // _showingAllOutputs is true, and the user's click-to-play stalls- // behind the queue. The observer is single-shot per card (unobserve- // after promotion) and uses a shared instance reset on each render- // so previously-observed nodes (now detached) get GC'd.- if (window._carThumbObserver) {- try { window._carThumbObserver.disconnect(); } catch (_e) {}- }- window._carThumbObserver = new IntersectionObserver((entries, obs) => {- for (const e of entries) {- if (!e.isIntersecting) continue;- const v = e.target.querySelector('video[data-src]');- if (v && !v.src) v.src = v.dataset.src;- obs.unobserve(e.target);- }- }, { root: el, rootMargin: '200% 0px 200% 0px', threshold: 0 });- el.querySelectorAll('.car-card').forEach(c => {- if (c.querySelector('video[data-src]:not([src])')) {- window._carThumbObserver.observe(c);- }- });+ // VC-31: video thumbnails are plain <img loading="lazy"> now (see+ // thumbHtml above) — the IntersectionObserver + data-src promotion this+ // block used to do for live <video> elements has nothing left to do.fitStagePlayer();}@@ -3453,7 +4992,13 @@ function selectOutput(path, options) {// clears for anything else. Runs for every selection so a click from a// song to a clip never leaves the previous song's score on screen.if (typeof songCardRender === 'function') songCardRender(o);- if (isAudio && o && o.engine === 'music' && typeof songHero === 'function') {+ // VC-20: the full Music-Studio player (cover art, score, New take / Cover+ // it / ...) is that tab's own surface. Reaching a song by filtering the+ // VIDEO tab's own gallery to Audio is browsing, not switching studios —+ // it used to transplant the whole Music player into the LTX tab's pane.+ // Same content, one extra affordance to actually get to the real thing.+ const onAudioTab = document.body.dataset.workflow === 'audio';+ if (isAudio && o && o.engine === 'music' && onAudioTab && typeof songHero === 'function') {// A song is not a black rectangle with a stock control in it: the// surface shows the cover, the title and the style; playback is the// bar's, which stays put while you browse.@@ -3464,7 +5009,13 @@ function selectOutput(path, options) {const _sf = wrap.closest('.player-surface');if (_sf) _sf.setAttribute('data-song', '');} else if (isAudio) {- wrap.innerHTML = `<audio class="train-voice-audio" controls preload="metadata"${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></audio>`;+ const pathAttr = JSON.stringify(path).replace(/"/g, '"');+ const openLink = (o && o.engine === 'music')+ ? `<button type="button" class="ghost-btn player-audio-open" onclick="openSongInAudioTab(${pathAttr})">Open in Audio tab</button>`+ : '';+ wrap.innerHTML = `<div class="player-audio-inline">`+ + `<audio class="train-voice-audio" controls preload="metadata"${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></audio>`+ + openLink + `</div>`;} else if (isPhoto) {wrap.innerHTML = `<img src="${escapeHtml(playerSrc)}" alt="${o ? escapeHtml(o.name) : ''}">`;} else if (liveBackdrop) {@@ -3543,10 +5094,24 @@ function selectOutput(path, options) {const rel = o ? _relTimeFromMtime(o.mtime) : '';const sizeLbl = o ? `${o.size_mb.toFixed(1)} MB` : '';const kindLbl = isPhoto ? 'Photo' : isAudio ? 'Audio' : 'Video';+ // VA-14: the lip-sync verdict chip, a2v clips only, only when scored.+ // Same thresholds + wording as One Shot's per-part verdict (oneshot.js+ // osVerdict) so the two surfaces read as one feature. "rough check" is+ // load-bearing copy — this is a hint, never a gate, and never a reason+ // to auto-delete anything.+ let lipsyncChip = '';+ if (o && o.mode === 'a2v' && o.lipsync_score !== null && o.lipsync_score !== undefined) {+ const n = Number(o.lipsync_score);+ const sign = n >= 0 ? '+' : '';+ const verdict = n >= 0.25 ? { cls: 'po-ls-ok', text: `mouth follows the voice (${sign}${n.toFixed(2)})` }+ : n >= 0.2 ? { cls: 'po-ls-mid', text: `borderline (${sign}${n.toFixed(2)})` }+ : { cls: 'po-ls-bad', text: `weak — try another seed (${sign}${n.toFixed(2)})` };+ lipsyncChip = `<span class="po-dot"></span><span class="${verdict.cls}" title="Lip-sync verdict — a rough check (mouth aperture vs. the audio), not a gate.">${escapeHtml(verdict.text)}</span>`;+ }document.getElementById('playerOverlayMeta').innerHTML = o? `<span>${kindLbl}</span><span class="po-dot"></span>` +`<span>${escapeHtml(rel)}</span><span class="po-dot"></span>` +- `<span>${sizeLbl}</span>`+ `<span>${sizeLbl}</span>${lipsyncChip}`: '';}if (overlayActions) overlayActions.style.display = '';@@ -3554,6 +5119,25 @@ function selectOutput(path, options) {// Load params is video-only — image sidecars use the library@1 schema// which doesn't carry the i2v/t2v form fields the loader expects.document.getElementById('loadParamsBtn').disabled = !(o && o.has_sidecar) || isPhoto || isAudio;+ // New Take (VC-03) replays a sidecar too, so the same video-with-sidecar+ // gate applies. Works on a One Shot clip too — the endpoint re-runs the+ // whole take with a fresh seed (routes_queue.py post_queue_newtake).+ const newTakeBtnEl = document.getElementById('newTakeBtn');+ if (newTakeBtnEl) newTakeBtnEl.disabled = !(o && o.has_sidecar) || isPhoto || isAudio;+ // VA-17 / H3-11: the recovery bar for a One Shot that stopped or failed+ // mid-chain. `o.one_shot_unfinished` is stamped server-side (list_outputs)+ // from the manifest run_take_job_inner's except clause writes on the last+ // kept part — see mlx_ltx_panel.py.+ const recBar = document.getElementById('oneShotRecoveryBar');+ if (recBar) {+ const show = !!(o && o.one_shot_unfinished);+ recBar.hidden = !show;+ if (show) {+ recBar.dataset.path = o.path;+ const txt = document.getElementById('oneShotRecoveryText');+ if (txt) txt.textContent = 'This One Shot stopped early — the parts already rendered are kept.';+ }+ }// Action button row: swap "Use as Extend" for "Animate" on photo// entries (Extend is video-only, but the still can be the seed for// an i2v render).@@ -3574,19 +5158,41 @@ function selectOutput(path, options) {// /status payload as o.engine) — not the form's current engine, which is// about the next render and says nothing about this clip.const outIsH3 = !!(o && o.engine === 'h3');- if (useExtBtn) useExtBtn.style.display = (isPhoto || isAudio || outIsH3) ? 'none' : '';+ // VA-36: on an a2v (lip-sync) clip, Extend continues with LTX's OWN+ // regenerated audio, not the song this clip was conditioned on — a+ // singing shot would "continue" with invented gibberish. Swap Extend for+ // "Continue the song" there instead (see /a2v/continue_song).+ const outIsA2v = !!(o && o.mode === 'a2v');+ if (useExtBtn) useExtBtn.style.display = (isPhoto || isAudio || outIsH3 || outIsA2v) ? 'none' : '';+ const continueSongBtn = document.getElementById('continueSongBtn');+ if (continueSongBtn) continueSongBtn.style.display = (outIsA2v && !isPhoto && !isAudio) ? '' : 'none';+ // VA-26: Retake is video-only, engine-agnostic (any finished clip, H3+ // included in principle — the pipeline call is LTX-only today, same+ // constraint Extend already has, so scope it the same way Extend is+ // scoped: not on H3 clips, not on photos/audio).+ const retakeBtn = document.getElementById('retakeBtn');+ if (retakeBtn) retakeBtn.style.display = (isPhoto || isAudio || outIsH3) ? 'none' : '';+ // VA-38: shown only on a published Windows-partial (windows_partial set+ // by _publish_windows_partial on a chain failure).+ const windowsContinueBtn = document.getElementById('windowsContinueBtn');+ if (windowsContinueBtn) {+ const wp = o && o.windows_partial;+ windowsContinueBtn.style.display = wp ? '' : 'none';+ const lbl = document.getElementById('windowsContinueLabel');+ if (lbl && wp) lbl.textContent = 'Continue (' + wp.completed + ' of ' + wp.total + ' done)';+ }// Upscale & Face Fix is video-only but engine-agnostic: an H3 draft is// exactly the clip it was built for.const useUpBtn = document.getElementById('faceFixWrap');// …and never on a clip that is already an upscale (owner 2026-09-17).if (useUpBtn) useUpBtn.style.display = (isPhoto || isAudio || isUpscaledPath(o && o.path)) ? 'none' : '';if (animBtn) animBtn.style.display = isPhoto ? '' : 'none';- // "Finish at …" — for a completed H3 render that has a higher canvas to be- // committed at. Decided from o.engine / o.h3_tier (both sidecar-derived,- // already in the /status payload and resolved server-side through the legacy- // alias map), so no extra request rides the selection path.- if (typeof _syncH3FinishAffordance === 'function') {- try { _syncH3FinishAffordance(isPhoto ? null : o); } catch (e) {}+ // "Finish at …" — for a completed H3 or LTX render that has a higher+ // canvas to be committed at (VC-18/37). Decided from o.engine plus either+ // o.h3_tier or o.quality/o.frames — all sidecar-derived, already in the+ // /status payload — so no extra request rides the selection path.+ if (typeof _syncFinishAffordance === 'function') {+ try { _syncFinishAffordance(isPhoto ? null : o); } catch (e) {}}}@@ -3615,6 +5221,17 @@ function openExpandLightbox() {const sizeLbl = `${o.size_mb.toFixed(1)} MB`;meta.textContent = `${o.name} · ${sizeLbl}`;}+ // VC-18/37: same clip actions as the toolbar's More menu, video-only —+ // a still or a song has no Sharp export / last frame / etc to offer.+ const actions = document.getElementById('expandActions');+ if (actions) {+ actions.innerHTML = (!isPhoto && !isAudio) ? `+ <button type="button" class="ghost-btn" onclick="sharpExportActive()">Sharp export</button>+ <button type="button" class="ghost-btn" onclick="useLastFrameActive()">Use last frame</button>+ <button type="button" class="ghost-btn" onclick="openActiveInEditor()">Open in Editor</button>+ <button type="button" class="ghost-btn" onclick="revealActive()">Reveal in Finder</button>+ ` : '';+ }lb.style.display = 'flex';}@@ -3672,34 +5289,86 @@ function closeExpandLightbox() {// Toast helper — non-blocking confirmation pattern, stacks at the// bottom-center of the viewport. Use for delete confirmation, "moved// to Trash" feedback, save success, etc. Auto-dismisses after-// `duration` ms (default 3 s). Pass `kind: "success" | "danger"` to-// tint the border + icon.+// `duration` ms (default 4 s; pass `duration: 0` to keep it up until the+// person closes it — every toast gets a close control, see below). Pass+// `kind: "success" | "warning" | "danger"` to tint the border + icon.+//+// SYS-09: this used to accept only an options OBJECT, but three call+// sites in health.js called `phosToast(message, 'warn')` /+// `phosToast(message, 'error')` — a bare string. `opts.kind` on a string+// is silently `undefined` (no throw), so those three failures rendered+// as neutral "info" toasts and vanished in 3 s with no color, no icon,+// no way to tell they were errors. Accepting the string shorthand here,+// and normalizing the two aliases those call sites actually used ('warn'+// -> 'warning', 'error' -> 'danger'), fixes them without having to catch+// every future caller that reaches for the shorter form.function phosToast(message, opts) {+ if (typeof opts === 'string') opts = { kind: opts };opts = opts || {};+ const kindAliases = { warn: 'warning', err: 'danger', error: 'danger' };+ const kind = kindAliases[opts.kind] || opts.kind;const c = document.getElementById('phosToast');if (!c) return null;+ const msg = String(message);+ const duration = (opts.duration === 0) ? 0 : (opts.duration || 4000);+ const arm = (el) => {+ if (el._toastTimer) clearTimeout(el._toastTimer);+ if (duration <= 0) return;+ el._toastTimer = setTimeout(() => {+ if (!el.isConnected) return;+ el.classList.add('is-leaving');+ el.addEventListener('animationend', () => el.remove(), { once: true });+ }, duration);+ };+ // FILM-03: A REFUSAL REPEATED IS NOT A NEW MESSAGE. Holding ⌥→ against a+ // clip already hard against its neighbour fired the same "nothing to+ // give" toast once per keypress and covered the timeline in identical+ // copies (shots_film/13_after_nudge.png). The same text still on screen+ // gets a ×N counter and a fresh dismiss timer instead of a new stack —+ // only while it is still THIS message; a different one still stacks.+ const dupe = Array.prototype.find.call(c.children, (el) =>+ el.classList && el.classList.contains('phos-toast')+ && !el.classList.contains('is-leaving') && el.dataset.msg === msg);+ if (dupe) {+ const n = (parseInt(dupe.dataset.count || '1', 10) || 1) + 1;+ dupe.dataset.count = String(n);+ let cnt = dupe.querySelector('.phos-toast-count');+ if (!cnt) {+ cnt = document.createElement('span');+ cnt.className = 'phos-toast-count';+ dupe.appendChild(cnt);+ }+ cnt.textContent = '×' + n;+ arm(dupe);+ return dupe;+ }const el = document.createElement('div');el.className = 'phos-toast';- if (opts.kind === 'success' || opts.kind === 'danger') {- el.classList.add('phos-toast-' + opts.kind);+ el.dataset.msg = msg;+ el.dataset.count = '1';+ if (kind === 'success' || kind === 'warning' || kind === 'danger') {+ el.classList.add('phos-toast-' + kind);}const icon = opts.icon- || (opts.kind === 'success' ? 'ph-check-bold'- : opts.kind === 'danger' ? 'ph-x-circle'+ || (kind === 'success' ? 'ph-check-bold'+ : kind === 'danger' ? 'ph-x-circle'+ : kind === 'warning' ? 'ph-warning-fill': 'ph-info');el.innerHTML =`<svg class="ph" aria-hidden="true"><use href="#${icon}"/></svg>` +- `<span class="phos-toast-msg"></span>`;- el.querySelector('.phos-toast-msg').textContent = String(message);+ `<span class="phos-toast-msg"></span>` ++ `<button type="button" class="phos-toast-close" aria-label="Dismiss">×</button>`;+ el.querySelector('.phos-toast-msg').textContent = msg;+ // SYS-09: every toast can be closed by hand; FILM-03's arm() owns the+ // auto-dismiss timer so a de-duplicated repeat can re-arm it.+ el.querySelector('.phos-toast-close').onclick = () => {+ if (el._toastTimer) clearTimeout(el._toastTimer);+ if (!el.isConnected) return;+ el.classList.add('is-leaving');+ el.addEventListener('animationend', () => el.remove(), { once: true });+ };c.appendChild(el);- const duration = (opts.duration === 0) ? 0 : (opts.duration || 3000);- if (duration > 0) {- setTimeout(() => {- if (!el.isConnected) return;- el.classList.add('is-leaving');- el.addEventListener('animationend', () => el.remove(), { once: true });- }, duration);- }+ arm(el);return el;}@@ -3729,8 +5398,27 @@ async function animateActive() {}}-async function hide(path) { await fetch('/output/hide?path='+encodeURIComponent(path),{method:'POST'}); outputsCacheMutated([path]); currentOutputs = []; poll(); }-async function unhide(path) { await fetch('/output/show?path='+encodeURIComponent(path),{method:'POST'}); outputsCacheMutated([]); currentOutputs = []; poll(); }+// VC-04: Hide used to be a silent one-way door — no toast, no undo, no way+// back short of a raw /output/show curl. It stays reversible on disk either+// way (the file never moves), but the UI now says so and gives Undo right+// where the click happened, plus a "Hidden" toggle in the Outputs filters+// (see setHiddenFilter) for anyone who dismissed the toast.+async function hide(path) {+ await fetch('/output/hide?path='+encodeURIComponent(path),{method:'POST'});+ outputsCacheMutated([path]); currentOutputs = []; poll();+ const name = String(path).split('/').pop();+ const el = phosToast('Hidden · ' + name, { kind: 'success', duration: 7000 });+ if (el) {+ const a = document.createElement('a');+ a.href = '#'; a.className = 'phos-toast-action'; a.textContent = 'Undo';+ a.onclick = (ev) => { ev.preventDefault(); el.remove(); unhide(path); };+ el.appendChild(a);+ }+}+async function unhide(path) {+ await fetch('/output/show?path='+encodeURIComponent(path),{method:'POST'});+ outputsCacheMutated([]); currentOutputs = []; poll();+}async function deleteOutput(path) {// Per-card × button. Moves the media (and any sibling sidecar JSON)@@ -3788,6 +5476,10 @@ async function openOutputsFolder() {function hideActive() { if (activePath) hide(activePath); }function useAsExtendSourcePath(path) {+ // VA-09: Extend switched the mode but not the tab, so pressing it from+ // Audio/One Shot/Images set mode=extend behind a hidden #genForm (0 px+ // tall) — same root cause as VA-08's Load Params, same fix.+ if (typeof workflowSwitch === 'function') { try { workflowSwitch('manual'); } catch (e) {} }setMode('extend');document.getElementById('video_path').value = path;document.getElementById('extendSrcSelect').value = path;@@ -3795,6 +5487,180 @@ function useAsExtendSourcePath(path) {document.querySelector('aside.form-pane').scrollTop = 0;}function useAsExtendSource() { if (!activePath) return alert('Pick an output first.'); useAsExtendSourcePath(activePath); }++// VA-38: hands a published Windows-partial to Extend as its source. Not a+// byte-exact resume of the original chain's plan (that would need the+// failure-path exception handler to thread window index / tail state back+// out through the job dict, which this session did not build) — a+// pragmatic equivalent built on Extend's own already-proven path: the+// partial clip IS the finished prefix, Extend continues it.+function windowsContinueFromPartial(path) {+ if (!path) { alert('Pick an output first.'); return; }+ useAsExtendSourcePath(path);+ if (typeof phosToast === 'function') {+ phosToast('This clip is what finished before the Windows chain stopped — '+ + 'Extend continues it. The prompt below is the ORIGINAL clip’s; edit it '+ + 'for what should happen next.', { duration: 7000 });+ }+}++// "Continue the song" (VA-36 / build item 2, report_video-advanced.txt).+// Opens the NEXT lip-sync clip anchored on THIS one's most-closed-mouth+// frame near its end (never the literal last frame — a2v's own last frame+// is usually mid-syllable), with Start at moved forward to where that frame+// sits in the song. This is a new render, not a video-level "continue" —+// Extend's job (regenerate joint LTX audio over new frames) is exactly+// wrong here, which is why it's swapped out for a2v clips.+async function continueSongFromClip(path) {+ if (!path) { alert('Pick an output first.'); return; }+ try {+ // Restore the source clip's own recipe first (audio file, prompt,+ // canvas, strength, LoRAs) — loadParams() reads the CURRENTLY SELECTED+ // output's sidecar, so this only applies when the clip being continued+ // is the one on screen (true from the player button; a defensive no-op+ // otherwise rather than restoring the wrong clip's params).+ if (activePath === path) await loadParams();+ const r = await fetch('/a2v/continue_song', { method: 'POST', body: new URLSearchParams({ clip: path }) });+ const res = await r.json();+ if (!res.ok) {+ const msg = res.error || 'Could not continue the song';+ if (typeof phosToast === 'function') phosToast(msg, { kind: 'danger', duration: 6000 });+ else alert(msg);+ return;+ }+ audioModeSet('drive');+ if (typeof workflowSwitch === 'function') workflowSwitch('audio');+ const det = document.getElementById('mvOneShotDetails');+ if (det) det.open = true;+ // Override with the CONTINUATION: anchor on the closed-mouth frame,+ // Start at moved to where it sits in the song.+ pickerSetImage('a2v_image', res.anchor_image, { snapAspect: false });+ const startEl = document.getElementById('audioStudioStart');+ if (startEl) {+ startEl.value = String(res.audio_start_time);+ if (typeof audioStudioDurationChanged === 'function') audioStudioDurationChanged();+ }+ requestAnimationFrame(() => {+ if (det) det.scrollIntoView({ block: 'start', behavior: 'smooth' });+ });+ if (typeof phosToast === 'function') {+ phosToast('Continuing from ' + res.audio_start_time.toFixed(1)+ + 's, anchored on the last closed-mouth frame.', { kind: 'success' });+ }+ } catch (e) {+ const msg = 'Continue the song failed: ' + (e.message || e);+ if (typeof phosToast === 'function') phosToast(msg, { kind: 'danger' });+ else alert(msg);+ }+}++// "Retake a moment" (VA-26). Regenerates one interior stretch of a finished+// clip via the engine's RetakePipeline (Extend's own backend), while the+// rest of the clip is preserved. A player action, not a full Extend-style+// mode switch — the form lives in its own small modal (retakeModal) rather+// than taking over #genForm, since this is a one-shot fix on an existing+// clip, not a new render recipe to keep tweaking.+let _retakeSourcePath = null;+// 4.17.0 render check: Retake shares Extend's size cap (tier_max_dim+// ("extend")), so on a capped Mac a 720x1280 clip came back 416x768 while the+// modal promised everything outside the stretch "kept exactly as it was".+// Say the cap before the render, the way refreshExtendClampNote does for+// Extend. PURE (tier in, text out) so it is tested by executing it.+function retakeClampNoteText(tier) {+ const t = tier || {};+ const cap = Number(t.extend_max_dim || 0);+ if (!cap) return '';+ return `On this Mac (${t.label || 'this tier'}), Retake works at up to ${cap}px `+ + `on the longer side: a bigger clip is downscaled first, so the new clip `+ + `can come out smaller than this one. The original stays as it is.`;+}+function openRetakeModal(path) {+ if (!path) { alert('Pick a clip first.'); return; }+ _retakeSourcePath = path;+ const modal = document.getElementById('retakeModal');+ const status = document.getElementById('retakeStatus');+ const promptEl = document.getElementById('retakePrompt');+ const startEl = document.getElementById('retakeStart');+ const endEl = document.getElementById('retakeEnd');+ if (status) status.textContent = '';+ const clampEl = document.getElementById('retakeClampNote');+ if (clampEl) {+ const note = retakeClampNoteText((typeof BOOT !== 'undefined' && BOOT && BOOT.tier) || {});+ clampEl.textContent = note;+ clampEl.hidden = !note;+ }+ if (promptEl) promptEl.value = '';+ if (startEl) startEl.value = '0';+ if (endEl) endEl.value = '1';+ // Best-effort prefill of the clip's own prompt (so "leave blank to reuse+ // this clip's own prompt" has something visible to confirm) and its+ // duration (so From/To default inside the real clip length rather than+ // an arbitrary 0-1s guess).+ fetch('/sidecar?path=' + encodeURIComponent(path)).then(r => r.ok ? r.json() : null).then(data => {+ if (!data || _retakeSourcePath !== path) return;+ const p = data.params || {};+ if (promptEl && !promptEl.value) promptEl.placeholder = String(p.prompt || data.prompt || '').slice(0, 200);+ const o = (typeof findOutputByPath === 'function') ? findOutputByPath(path) : null;+ if (o && o.clip_sec && endEl) endEl.value = String(Math.min(o.clip_sec, 2).toFixed(1));+ if (o && o.clip_sec) { startEl.max = String(o.clip_sec); endEl.max = String(o.clip_sec); }+ }).catch(() => {});+ if (modal) modal.style.display = 'flex';+}+function closeRetakeModal() {+ const modal = document.getElementById('retakeModal');+ if (modal) modal.style.display = 'none';+ _retakeSourcePath = null;+}+async function submitRetake() {+ if (!_retakeSourcePath) { closeRetakeModal(); return; }+ const status = document.getElementById('retakeStatus');+ const btn = document.getElementById('retakeSubmitBtn');+ const start = parseFloat((document.getElementById('retakeStart') || {}).value || '0') || 0;+ const end = parseFloat((document.getElementById('retakeEnd') || {}).value || '0') || 0;+ if (end <= start) {+ if (status) status.textContent = 'End must be after start.';+ return;+ }+ const promptEl = document.getElementById('retakePrompt');+ let prompt = (promptEl && promptEl.value.trim()) || '';+ if (!prompt) {+ // Fall back to the source clip's own prompt — the server also defaults+ // p["prompt"] from the form, but make_job's own fallback is the generic+ // "A cinematic atmospheric scene", which is wrong here; read the+ // source's real prompt from its sidecar placeholder we filled in above.+ prompt = (promptEl && promptEl.placeholder) || '';+ }+ const keepSoundEl = document.getElementById('retakeKeepSound');+ const keepSound = !keepSoundEl || keepSoundEl.checked;+ if (btn) btn.disabled = true;+ if (status) status.textContent = 'Queueing…';+ try {+ const fd = new URLSearchParams();+ fd.set('mode', 'retake');+ fd.set('video_path', _retakeSourcePath);+ fd.set('prompt', prompt);+ fd.set('retake_start_sec', String(start));+ fd.set('retake_end_sec', String(end));+ if (!keepSound) fd.set('retake_audio_action', 'regenerate');+ fd.set('preset_label', 'Retake ' + start.toFixed(1) + 's-' + end.toFixed(1) + 's');+ const r = await fetch('/queue/add', { method: 'POST', body: fd });+ const res = await r.json().catch(() => ({}));+ if (!r.ok || res.error) throw new Error(res.error || ('HTTP ' + r.status));+ if (typeof phosToast === 'function') {+ phosToast('Retake queued (' + start.toFixed(1) + 's–' + end.toFixed(1)+ + 's) — lands next to the original, watch Now', { kind: 'success' });+ }+ closeRetakeModal();+ if (typeof poll === 'function') poll();+ } catch (e) {+ const msg = 'Retake failed: ' + (e.message || e);+ if (status) status.textContent = msg;+ if (typeof phosToast === 'function') phosToast(msg, { kind: 'danger', duration: 6000 });+ } finally {+ if (btn) btn.disabled = false;+ }+}+// UPSCALE & FACE FIX — the one-click clip action. The server builds the job// (the face-safe recipe, the clip's own prompt and seed) so the player, the// Outputs cards, the history rows and the Editor queue exactly the same thing.@@ -3825,11 +5691,16 @@ async function faceFixClip(path, opts) {return r;}if (opts.btnId) { try { _flashActionDone(opts.btnId, 'Queued'); } catch (e) {} }+ // VA-22: was untruncated prose that clipped at 1440px and never said the+ // size — the real number the server just computed (no eta shown: one+ // measurement at 1024×576 exists, not a lane table, so a guessed time+ // would be exactly the kind of promise this review is about).+ const sizeNote = (r.target_w && r.target_h) ? (' · ' + r.target_w + '×' + r.target_h) : '';phosToast(r.duplicate- ? (FACE_FIX_NAME + (r.running ? ' is already rendering for ' : ' is already waiting in the queue for ')+ ? (FACE_FIX_NAME + (r.running ? ' is already rendering for ' : ' is already queued for ')+ name + '.')- : (opts.doneHint || (FACE_FIX_NAME + ' queued for ' + name- + ' — the fixed clip (2× size, same face, same sound) lands next to it in Outputs.')),+ : (opts.doneHint || (FACE_FIX_NAME + ' queued' + sizeNote+ + ' — lands next to the original.')),{ kind: 'success', duration: 6000 });try { poll(); } catch (e) {}return r;@@ -3838,10 +5709,395 @@ function faceFixActive() {if (!activePath) return phosToast('Pick a clip in Outputs first.', {});return faceFixClip(activePath, { btnId: 'faceFixBtn' });}++// ---- VC-18/37: the clip toolbar's "More" menu ------------------------------+// Sharp export, Use last frame, Open in Editor, Reveal in Finder — four+// actions that don't earn a permanent icon slot next to Params/Extend/+// Upscale, so they live in one small popover instead (kebabToggle below).+// Each function works from an explicit path so the SAME code drives the+// toolbar button (activePath) and the lightbox's row (openExpandLightbox+// wires them with the path of whatever is currently expanded).++async function queueSharpExport(path) {+ if (!path) { phosToast('Pick a clip first.', {}); return null; }+ const fd = new URLSearchParams();+ fd.set('path', path);+ let r;+ try { r = await (await fetch('/queue/sharp_export', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ const name = String(path).split('/').pop();+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'Sharp export could not be queued.',+ { kind: 'danger', duration: 9000 });+ return r;+ }+ phosToast(r.duplicate+ ? ('Sharp export is already queued for ' + name + '.')+ : ('Sharp export queued for ' + name + ' — a sharper file lands next to it in Outputs.'),+ { kind: 'success', duration: 6000 });+ try { poll(); } catch (e) {}+ return r;+}+function sharpExportActive() {+ if (!activePath) return phosToast('Pick a clip in Outputs first.', {});+ return queueSharpExport(activePath);+}++async function useLastFramePath(path) {+ if (!path) { phosToast('Pick a clip first.', {}); return; }+ phosToast('Grabbing the last frame…', { duration: 2500 });+ const fd = new URLSearchParams();+ fd.set('path', path);+ let r;+ try { r = await (await fetch('/output/last_frame', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'Could not grab the last frame.', { kind: 'danger', duration: 9000 });+ return;+ }+ // Same seam Animate-from-photo uses: leave Studio workflows, switch to+ // i2v, drop the frame into the image picker so its preview updates too.+ if (typeof workflowSwitch === 'function') workflowSwitch('manual');+ setMode('i2v');+ if (typeof pickerSetImage === 'function') {+ pickerSetImage('image', r.path, { snapAspect: false });+ } else {+ document.getElementById('image').value = r.path;+ }+ const formPane = document.querySelector('aside.form-pane');+ if (formPane) formPane.scrollTop = 0;+ if (typeof updateDerived === 'function') updateDerived();+ phosToast('Last frame loaded as the i2v reference — ready for a fresh take.', { kind: 'success' });+}+function useLastFrameActive() {+ if (!activePath) return phosToast('Pick a clip in Outputs first.', {});+ return useLastFramePath(activePath);+}++async function revealClipInFinder(path) {+ if (!path) { phosToast('Pick a clip first.', {}); return; }+ const fd = new URLSearchParams();+ fd.set('path', path);+ let r;+ try { r = await (await fetch('/output/reveal', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) phosToast((r && r.error) || 'Could not open Finder.', { kind: 'danger' });+}+function revealActive() {+ if (!activePath) return phosToast('Pick a clip in Outputs first.', {});+ return revealClipInFinder(activePath);+}++async function openClipInEditor(path) {+ if (!path) { phosToast('Pick a clip first.', {}); return; }+ if (!(typeof SB !== 'undefined' && SB.boards && SB.boards.length)) {+ phosToast('Create a film in Storyboard first — then a clip can join it in the Editor.', {});+ return;+ }+ const id = (SB.boards[0] || {}).id;+ const fd = new URLSearchParams();+ fd.set('id', id); fd.set('path', path);+ let r;+ try { r = await (await fetch('/storyboard/add-shot', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) { phosToast((r && r.error) || 'Could not add the clip.', { kind: 'danger' }); return; }+ phosToast('Added to "' + (r.title || 'the film') + '" — opening the Editor.', { kind: 'success' });+ if (typeof edOpenBoard === 'function') edOpenBoard(id);+}+function openActiveInEditor() { return openClipInEditor(activePath); }++// Generic kebab/popover controller — shared by the player's More menu and+// the LoRA row's ⋯ menu (VC-42). id === the .kebab-pop element's id.+// Closing on an outside click and on Escape is wired once, module-load time.+function kebabToggle(id, forceOpen) {+ const pop = document.getElementById(id);+ if (!pop) return;+ const willOpen = typeof forceOpen === 'boolean' ? forceOpen : !pop.classList.contains('open');+ document.querySelectorAll('.kebab-pop.open').forEach(p => { if (p !== pop) p.classList.remove('open'); });+ pop.classList.toggle('open', willOpen);+}+(function _wireKebabOutsideClick() {+ document.addEventListener('click', (ev) => {+ if (ev.target.closest && ev.target.closest('.kebab-wrap')) return;+ document.querySelectorAll('.kebab-pop.open').forEach(p => p.classList.remove('open'));+ });+ document.addEventListener('keydown', (ev) => {+ if (ev.key === 'Escape') document.querySelectorAll('.kebab-pop.open').forEach(p => p.classList.remove('open'));+ });+})();++// NEW TAKE (VC-03) — "I like this, give me another": same recipe, a fresh+// seed, queued at once. Sourced from the clip's own sidecar server-side+// (/queue/newtake), so it works on anything still in the gallery, not only+// a recent job. Published on globalThis so the board's own New Take+// (FILM-22) can call this instead of re-deriving "same recipe, new seed" a+// second time — one seed helper, shared.+async function newTakeFromPath(path, opts) {+ opts = opts || {};+ if (!path) { phosToast('Pick a clip first.', {}); return null; }+ const fd = new URLSearchParams();+ fd.set('path', path);+ let r;+ try { r = await (await fetch('/queue/newtake', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ const name = String(path).split('/').pop();+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'New take could not be queued.',+ { kind: 'danger', duration: 7000 });+ return r;+ }+ if (opts.btnId) { try { _flashActionDone(opts.btnId, 'Queued'); } catch (e) {} }+ const etaMin = (typeof r.eta_sec === 'number' && r.eta_sec > 0)+ ? Math.max(1, Math.round(r.eta_sec / 60)) : null;+ phosToast('New take queued for ' + name+ + (etaMin ? (' · about ' + etaMin + ' min, same as last time') : ''),+ { kind: 'success', duration: 6000 });+ try { poll(); } catch (e) {}+ return r;+}+function newTakeActive() {+ if (!activePath) return phosToast('Pick a clip in Outputs first.', {});+ return newTakeFromPath(activePath, { btnId: 'newTakeBtn' });+}++// ---- destructive queue controls (VC-05, VC-06, VC-35, H3-11) --------------+//+// Stop and Clear used to be armed at all times, right next to Generate, with+// no cost shown and no way back — the exact shape VC-35 calls out ("Trash+// asks, Hide/Stop/Clear don't"). This is the one place both are wired: idle+// disables Stop, real elapsed time gates whether it asks first, and a+// chained One Shot gets the option to keep what already finished instead of+// an all-or-nothing kill. Runs every poll() cycle — cheap DOM writes, no+// network of its own.+// VC-04: the reopened way back for anything hidden from the player. Flips+// filterMode (boot.js) between 'visible' and 'hidden' and re-polls so+// /status fetches with include_hidden=1 — the same plumbing the old+// Visible/Hidden segmented control drove, left in place when that control+// was removed.+function toggleHiddenFilter() {+ filterMode = (filterMode === 'hidden') ? 'visible' : 'hidden';+ try { renderCarousel(); } catch (e) {}+ poll();+}+function _syncHiddenFilterToggle(s) {+ const btn = document.getElementById('hiddenFilterToggle');+ if (!btn) return;+ const n = (s && s.hidden_count) || 0;+ btn.style.display = (n > 0 || filterMode === 'hidden') ? '' : 'none';+ btn.classList.toggle('active', filterMode === 'hidden');+ btn.textContent = filterMode === 'hidden' ? 'Showing hidden — back to Outputs' : `Hidden (${n})`;+ btn.title = filterMode === 'hidden'+ ? 'Show the regular gallery again'+ : `${n} output${n === 1 ? '' : 's'} hidden from the gallery — click to see and restore them`;+}++// VC-03: the seed-locked chip. Shows whenever #seed holds a real (locked)+// value instead of -1/random, wherever it came from (Load Params, typing+// one in by hand, a saved draft restored on reload — VC-38). ✕ is the one+// click back to a fresh roll on the next Generate.+function _syncSeedLockChip() {+ const chip = document.getElementById('seedLockChip');+ const valEl = document.getElementById('seedLockValue');+ const seedEl = document.getElementById('seed');+ if (!chip || !valEl || !seedEl) return;+ const raw = String(seedEl.value || '').trim();+ const locked = raw !== '' && raw !== '-1';+ chip.hidden = !locked;+ if (locked) valEl.textContent = 'seed ' + raw;+}+function clearSeedLock() {+ const seedEl = document.getElementById('seed');+ if (!seedEl) return;+ seedEl.value = '-1';+ _syncSeedLockChip();+ if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }+}++function _syncDestructiveQueueButtons(s) {+ // Stop's enabled state + title are set once, in poll() (SYS-10d/VC-05 —+ // the `.js-stop-btn` block), on the same buttons this used to reach via+ // [data-role="stop-btn"]; two writers on one poll made the title flicker.+ const queued = (s && s.queue) || [];+ document.querySelectorAll('[data-role="clear-queue-btn"]').forEach(btn => {+ btn.disabled = queued.length === 0;+ const label = btn.querySelector('.clear-queue-label');+ const text = queued.length ? `Clear queue (${queued.length})` : 'Clear queue';+ if (label) label.textContent = text; else btn.title = text;+ btn.title = queued.length+ ? `Remove ${queued.length} waiting render${queued.length === 1 ? '' : 's'} — the running one continues. Undo brings them right back.`+ : 'Nothing waiting in the queue';+ });+}++// See _syncDestructiveQueueButtons for why Stop is disabled when idle. Once+// something is rendering: a chained One Shot always offers the safer+// "finish this part, then stop" choice alongside a hard stop; an ordinary+// render under 2 minutes old stops at once (too little is at stake to make+// the user click twice), past that it asks and says what is lost.+function requestStop(opts) {+ // opts.onStop: a caller-side loop to break when the user actually stops+ // (confirmed, not cancelled) — the Lip-sync "Split into clips" chain (VA-30)+ // queues its next part client-side and must not outlive a Stop.+ const onStop = (opts && typeof opts.onStop === 'function') ? opts.onStop : null;+ const cur = LAST_STATUS && LAST_STATUS.current;+ if (!cur) { if (onStop) onStop(); return; }+ const cp = cur.params || {};+ const isTake = !!cp.take;+ const progress = cur.progress || {};+ // H3-11's other half: a plain chained H3 render (10/15 s+, no One Shot+ // wrapper) is still ONE job with several windows — window/window_total are+ // already live in cur.progress (the Now-card ETA reads the same fields).+ // (4.17: offered only when the H3 runner can keep finished windows on a+ // stop — BOOT.tier.h3_stop_after_window; today's runner writes its one+ // output after the last window, so a mid-chain stop keeps nothing.)+ const isH3Chain = !isTake && String(cp.engine || '').toLowerCase() === 'h3'+ && Number(progress.window_total || 1) > 1+ && !!(typeof BOOT !== 'undefined' && (BOOT.tier || {}).h3_stop_after_window);+ const startedTs = Number(cur.started_ts) || 0;+ const now = Number((LAST_STATUS && LAST_STATUS.server_now) || (Date.now() / 1000));+ const elapsedMin = startedTs ? Math.max(0, (now - startedTs) / 60) : 0;+ const promptSnippet = (typeof snippet === 'function') ? snippet(cp.prompt || '', 60) : (cp.prompt || '').slice(0, 60);+ const hasDialog = typeof _phModalShow === 'function';++ // 4.17 Codex SAFETY-3: both stops name the job this dialog describes. A+ // confirmation left open while that job finished used to stop whatever+ // started next; the server now refuses a stale id (409) and nothing stops.+ const jobQ = cur.id ? ('?id=' + encodeURIComponent(cur.id)) : '';+ const doHardStop = () => {+ if (onStop) onStop();+ api('/stop' + jobQ, 'POST').then(d => {+ if (d && d.error) phosToast('That render already finished — nothing was stopped.', { kind: 'info' });+ poll();+ }).catch(e => { phosToast((e && e.message) || 'Could not stop.', { kind: 'danger' }); poll(); });+ };+ const doStopAfterPart = (label) => {+ if (onStop) onStop();+ fetch('/stop/after_part' + jobQ, { method: 'POST' }).then(r => r.json()).then(d => {+ phosToast(d && d.ok+ ? `Stopping after this ${label} — keeping everything already rendered.`+ : ((d && d.error) || `Could not stop after this ${label}.`),+ { kind: d && d.ok ? 'success' : 'danger', duration: 6000 });+ poll();+ }).catch(() => phosToast(`Could not stop after this ${label}.`, { kind: 'danger' }));+ };++ if ((isTake || isH3Chain) && hasDialog) {+ const tp = isTake ? (cur.take_progress || {}) : progress;+ const done = isTake ? (tp.part || 0) : Math.max(0, Number(progress.window || 1) - 1);+ const total = isTake ? (tp.parts || (cp.take.parts && cp.take.parts.length) || 0)+ : Number(progress.window_total || 0);+ const unit = isTake ? 'part' : 'window';+ _phModalShow({+ tone: 'danger', kicker: isTake ? 'Stop this One Shot?' : 'Stop this chained render?',+ title: promptSnippet ? `Stop "${promptSnippet}"?` : 'Stop this render?',+ body: (done > 0 ? `${unit === 'part' ? 'Part' : 'Window'} ${done} of ${total || '?'} is finishing. `+ : `The first ${unit} is still rendering. `)+ + `Stop after this ${unit} keeps everything already rendered`+ + (isTake ? ' and joins it into a shorter clip. ' : ' as a shorter clip. ')+ + `Stop now throws away the ${unit} in progress too`+ + (isH3Chain ? ' — and this engine may not be able to save anything at all mid-window.' : '.'),+ primaryLabel: `Stop after this ${unit}`, onPrimary: () => doStopAfterPart(unit),+ secondaryLabel: `Stop now (loses this ${unit})`, onSecondary: doHardStop,+ });+ return;+ }+ if (elapsedMin < 2) { doHardStop(); return; }+ if (hasDialog) {+ const mins = Math.max(1, Math.round(elapsedMin));+ _phModalShow({+ tone: 'danger', kicker: 'Stop this render?',+ title: promptSnippet ? `Stop "${promptSnippet}"?` : 'Stop this render?',+ body: `About ${mins} min of work will be lost, and the next render reloads the model from scratch.`,+ primaryLabel: 'Stop', onPrimary: doHardStop,+ secondaryLabel: 'Keep rendering',+ });+ return;+ }+ doHardStop(); // no dialog available — fail open rather than do nothing+}++// VC-06: Clear still empties the queue in one click (the label now says how+// many, and it's disabled at zero), with Undo instead of asking first.+// 4.17 Codex SAFETY-8/9/10: Undo restores what the SERVER removed — the+// token /queue/clear returns — not this page's last poll. The poll could be+// a second stale (a job the worker already started came back as a duplicate;+// one another tab added was lost), and the old replay minted new ids, which+// cut storyboard shots off from their restored jobs.+function requestClearQueue() {+ const queued = (LAST_STATUS && LAST_STATUS.queue) || [];+ if (!queued.length) return;+ api('/queue/clear', 'POST').then((d) => {+ poll();+ const n = Number((d && d.cleared) || 0);+ const token = d && d.undo_token;+ if (!n) return;+ const el = phosToast(`Cleared ${n} queued render${n === 1 ? '' : 's'} (the running one continues)`,+ { kind: 'success', duration: 8000 });+ if (!el || !token) return;+ const a = document.createElement('a');+ a.href = '#'; a.className = 'phos-toast-action'; a.textContent = 'Undo';+ a.onclick = async (ev) => {+ ev.preventDefault(); el.remove();+ try {+ const r = await fetch('/queue/restore', {+ method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token }),+ });+ const d = await r.json().catch(() => ({}));+ if (!r.ok || !d.ok) throw new Error((d && d.error) || ('HTTP ' + r.status));+ const restored = (typeof d.restored === 'number') ? d.restored : n;+ phosToast(`Restored ${restored} render${restored === 1 ? '' : 's'}`, { kind: 'success' });+ } catch (e) {+ phosToast('Could not restore the queue: ' + (e.message || e), { kind: 'danger', duration: 7000 });+ }+ poll();+ };+ el.appendChild(a);+ });+}++// VA-17 / H3-11: the two ways back for a One Shot that stopped or failed+// mid-chain, driven from the recovery bar's `data-path` (main.js's+// delegated click handler reads it and calls these). "Resume" picks the+// take back up from the next part; "Join what's done" publishes exactly+// what finished as a shorter clip — never a false "the whole thing failed"+// with no clip to show for it.+async function takeResumeFromPath(path) {+ if (!path) return;+ const fd = new URLSearchParams(); fd.set('path', path);+ let r;+ try { r = await (await fetch('/take/resume', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'Could not resume this One Shot.', { kind: 'danger', duration: 7000 });+ return;+ }+ phosToast(`Resuming from part ${(r.resumed_from_part || 0) + 1} of ${r.total_parts || '?'}`,+ { kind: 'success', duration: 6000 });+ poll();+}+async function takeJoinPartialFromPath(path) {+ if (!path) return;+ const fd = new URLSearchParams(); fd.set('path', path);+ let r;+ try { r = await (await fetch('/take/join_partial', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'Could not join what finished.', { kind: 'danger', duration: 7000 });+ return;+ }+ phosToast(`Joined ${r.parts_joined} part${r.parts_joined === 1 ? '' : 's'} into one clip.`,+ { kind: 'success', duration: 6000 });+ currentOutputs = []; outputsCacheMutated([]); poll();+}+// The full lane (Remix → Upscale & Face Fix): presets, source picker, prompt.// Same hand-off shape as Extend: switch to the Remix tool, point the picker// at this clip, scroll the form to the top.function useAsUpscaleSourcePath(path) {+ // VA-09: same fix as Extend above — switch tabs before the mode change,+ // not after (or never).+ if (typeof workflowSwitch === 'function') { try { workflowSwitch('manual'); } catch (e) {} }setMode('upscale');const inp = document.getElementById('upscale_source_path');if (inp) inp.value = path;@@ -3903,11 +6159,29 @@ function _restoreLoraPicker(list, scaleV) {}}-async function loadParams() {- if (!activePath) return;- const r = await fetch('/sidecar?path='+encodeURIComponent(activePath));- if (!r.ok) return;- const data = await r.json();+// VC-03: what Load Params most recently restored into the Video form, for+// the Generate-time duplicate check below. null until the first Load Params+// of the session; stays set until the next one (a second Generate press on+// an untouched form should still warn).+let _loadedRecipeSnapshot = null;++async function loadParams(recipe) {+ // 4.17 Codex SAFETY-4: `recipe` ({params}) applies a QUEUED job's recipe+ // with no sidecar fetch — editQueuedJob() restores through this one+ // complete path (engine, H3 tier/speed/window prompts, LTX windows,+ // steps, export method, keyframes, character, LoRAs) instead of its own+ // short field list, which left the rest of the form as it was and let+ // "Update job" turn an H3 job into an LTX one.+ const _queueEdit = !!(recipe && recipe.params);+ let data;+ if (_queueEdit) {+ data = recipe;+ } else {+ if (!activePath) return;+ const r = await fetch('/sidecar?path='+encodeURIComponent(activePath));+ if (!r.ok) return;+ data = await r.json();+ }const p = data.params;// Image-Studio sidecars (Ideogram 4 etc.) carry a TOP-LEVEL prompt that is a// structured caption JSON, not the video params shape below — the p.mode@@ -3962,7 +6236,7 @@ async function loadParams() {// compose state instead of dumping the user into Manual. The sidecar// carries the source flag + the original compose chips verbatim// (character_id, framing, duration, prompt_body, quality_choice).- if (p && p.source === 'characters' && p.character_id) {+ if (p && p.source === 'characters' && p.character_id && !_queueEdit) {try {await charactersLoadParams(p);return;@@ -3992,7 +6266,17 @@ async function loadParams() {oneshotOpenFromParams(p);return;}- else if (p.mode === 'upscale') {+ // VA-08: everything below here fills #genForm on the Video tab — upscale,+ // extend, keyframe, i2v, character, t2v. Every branch ABOVE this point+ // already switches to its own tab (Images, One Shot, Audio, Characters);+ // nothing BELOW it did, so pressing Params from Audio/One Shot/Images left+ // the form filled in behind a tab the user was still looking at, at 0+ // height. Switch first, then scroll the pane to the top so the restored+ // recipe is what's on screen, not whatever scroll position was left over.+ if (typeof workflowSwitch === 'function') { try { workflowSwitch('manual'); } catch (e) {} }+ const _lpPane = document.querySelector('aside.form-pane');+ if (_lpPane) _lpPane.scrollTop = 0;+ if (p.mode === 'upscale') {// Upscale & Face Fix reopens in its own lane on the same source clip with// the EXACT recipe that ran. A pill lights only when it names that recipe;// old sidecars (keep_shot only) match the pill with that strength.@@ -4022,6 +6306,8 @@ async function loadParams() {}const sd = (p.seed_used != null) ? p.seed_used : p.seed;if (sd != null && sd !== '') document.getElementById('seed').value = sd;++ if (typeof _syncSeedLockChip === 'function') { try { _syncSeedLockChip(); } catch (e) {} }_flashActionDone('loadParamsBtn', 'Loaded');return;}@@ -4062,15 +6348,20 @@ async function loadParams() {// dropped its per-window prompts and invariants — the next Generate asked// for the whole length in one pass. The window text is always written, so// a native clip clears whatever an earlier windowed one left in the box.- const _winText = document.getElementById('window_prompts_text');+ // VA-18: the per-window text now lives in dynamically rendered boxes+ // (windowsDynamicSlots), built from an async /ltx/windows_plan fetch —+ // there is no synchronous textarea to write into any more. Stash the+ // restored array; _renderWindowsSlotsFromPlan consumes it (once) the+ // next time it builds the boxes, which setTemporalMode('windows') below+ // triggers once temporal_mode is actually 'windows' (windowPromptsInput+ // itself is a no-op until then — see its own mode guard).const _winInv = document.getElementById('window_invariants');const _windowed = p.long_mode === 'windows';- if (_winText) {- _winText.value = (_windowed && Array.isArray(p.window_prompts))- ? p.window_prompts.map(x => String(x || '')).join('\n') : '';+ if (typeof window !== 'undefined') {+ window._pendingWindowPromptsRestore = (_windowed && Array.isArray(p.window_prompts))+ ? p.window_prompts.map(x => String(x || '')) : null;}if (_winInv) _winInv.value = _windowed ? String(p.window_invariants || '') : '';- if (typeof windowPromptsInput === 'function') windowPromptsInput();if (_windowed) setTemporalMode('windows');else if (p.temporal_mode) setTemporalMode(p.temporal_mode);if (p.upscale) setUpscale(p.upscale);@@ -4093,6 +6384,7 @@ async function loadParams() {: p.seed;if (seedToRestore != null) {document.getElementById('seed').value = seedToRestore;+ if (typeof _syncSeedLockChip === 'function') { try { _syncSeedLockChip(); } catch (e) {} }}// Image / keyframes go through pickerSetImage so the preview tile// and recent-strip selection state update along with the hidden input.@@ -4142,10 +6434,14 @@ async function loadParams() {}}}- if (p.image) pickerSetImage('image', p.image, { snapAspect: false });+ if (p.image) {+ pickerSetImage('image', p.image, { snapAspect: false });+ // The saved crop framing, not whatever the form last had (Codex H3-3).+ _setCropFocus('image', _cropFocusFromParams(p));+ }if (restoredStartImage) pickerSetImage('start_image', restoredStartImage, { snapAspect: false });if (restoredEndImage) pickerSetImage('end_image', restoredEndImage, { snapAspect: false });- if (p.audio) document.getElementById('audio').value = p.audio;+ if (p.audio) i2vAudioSet(p.audio);// Extend-specific: restore the WHOLE request, not just the source path.// Duration, direction, sampler depth and CFG were all saved to the sidecar// and never read back — a Load Params + Generate on an Extend silently@@ -4291,10 +6587,26 @@ async function loadParams() {// after the tier so the tier can't clobber the seed we just loaded.const _seedBefore = (document.getElementById('seed') || {}).value;const _eng = String((p && p.engine) || (data && data.engine) || 'ltx').toLowerCase();+ // H3-21: setEngine() refuses to hand back an engine the machine can't+ // serve (same gate h3FinishActive() checks) and silently lands on the+ // fallback instead — so loading an H3 clip's params on a Mac without H3+ // used to swap to LTX with no explanation: the image mode, aspect and+ // dims all changed under the user's H3-format prompt, and nothing said+ // why. Read what setEngine() actually landed on and tell the user when+ // it disagrees with what the clip was made with.+ let _engLanded = _eng;if (typeof setEngine === 'function' && typeof engineById === 'function' && engineById(_eng)) {- try { setEngine(_eng, { persist: false }); } catch (e) {}+ try { _engLanded = setEngine(_eng, { persist: false }) || _eng; } catch (e) {}+ }+ if (_eng === 'h3' && _engLanded !== 'h3') {+ if (typeof phosToast === 'function') {+ const note = (document.getElementById('engineRowNote') || {}).textContent || '';+ phosToast('This clip was made with Hailuo H3. ' + (note+ || 'H3 isn\'t available on this Mac, so it loaded into LTX instead — the prompt is H3-format and the shape won\'t match.'),+ { kind: 'danger', duration: 8000 });+ }}- if (_eng === 'h3') {+ if (_engLanded === 'h3') {if (typeof setH3Upscale === 'function' && p.h3_upscale) {try { setH3Upscale(p.h3_upscale); } catch (e) {}}@@ -4354,6 +6666,19 @@ async function loadParams() {updateCustomizeSummary();updateDerived();+ if (_queueEdit) return; // a queued job is not a clip: no duplicate guard, no flash+ // VC-03's third half: if Generate is pressed with nothing changed from+ // what Load Params just restored, it would render the identical clip a+ // second time. Snapshot what got loaded so the submit handler can compare+ // against it — see _duplicateOfLoadedRecipe / genForm's submit listener.+ _loadedRecipeSnapshot = {+ path: activePath, name: (activePath || '').split('/').pop(),+ prompt: p.prompt || '', seed: String(seedToRestore != null ? seedToRestore : ''),+ width: String(p.width || ''), height: String(p.height || ''),+ quality: p.quality || '',+ loras: (Array.isArray(p.loras) ? p.loras : [])+ .map(l => (l && l.path) + '@' + (l && l.strength)).sort().join(','),+ };// Say it out loud. This whole function ran silently before — the form// changed somewhere off-screen and the click read as a dead button._flashActionDone('loadParamsBtn', 'Loaded');@@ -4516,8 +6841,28 @@ function renderOutputInfoBody(path, data) {// Compose the dimensions + duration into a single "Format" line — fewer// grid rows, easier to scan. We separate technical metadata (Format,// Frames) from generation parameters (Mode, Quality, Seed, Steps).+ //+ // VC-19: this used to be p.width x p.height alone — the RENDER canvas,+ // not the file actually delivered to disk. Balanced's default 720p-fit+ // export (or any upscale) changes the two, so a 1024x576 render that+ // fit-exported to 1280x720 reported "Format 1024 x 576" for a file that+ // opens at 1280x720. /sidecar now probes the real file (routes_files.py)+ // and attaches actual_width/actual_height; when those disagree with the+ // render params, say both, delivered first (the number that matters to+ // whoever's about to use the file) with the render size as context.const formatBits = [];- if (p.width && p.height) formatBits.push(`${p.width} × ${p.height}`);+ const _upscaleNote = { fit_720p: '720p fit', x2: '×2 upscale' }[p.upscale];+ if (data.actual_width && data.actual_height) {+ if (p.width && p.height+ && (data.actual_width !== p.width || data.actual_height !== p.height)) {+ formatBits.push(`Delivered ${data.actual_width} × ${data.actual_height} `+ + `(rendered ${p.width} × ${p.height}${_upscaleNote ? ', ' + _upscaleNote : ''})`);+ } else {+ formatBits.push(`${data.actual_width} × ${data.actual_height}`);+ }+ } else if (p.width && p.height) {+ formatBits.push(`${p.width} × ${p.height}`);+ }if (data.video_duration_sec != null) formatBits.push(`${data.video_duration_sec.toFixed(2)} s @ ${data.fps || 24} fps`);let html = '';@@ -4598,10 +6943,15 @@ function renderOutputInfoBody(path, data) {const applied = tinfo && tinfo.applied && tinfo.applied.applied;genRows.push(`<dt>Turbo</dt><dd>on · ${escapeHtml(String(p.steps || 4))}-step `+ `distill LoRA${applied ? ' · ' + escapeHtml(String(applied)) + ' modules applied' : ''}</dd>`);- } else if (Number(p.h3_steps || 0) > 0) {- // Steps only earns a row when the user pinned a depth — the tier default- // is already implied by the tier row.- genRows.push(`<dt>Steps</dt><dd>${escapeHtml(String(p.steps || p.h3_steps))} · tier default overridden</dd>`);+ } else {+ // H3-04: a Best clip fell through with NO Speed row at all — only+ // Fast (tristep) and the retired Turbo earned one, so "what speed+ // was this rendered at" was answerable for some clips and not+ // others. Best earns the same row every other speed gets.+ genRows.push(`<dt>Speed</dt><dd>Best · this shape's full sampler`+ + (Number(p.h3_steps || 0) > 0+ ? ` · ${escapeHtml(String(p.steps || p.h3_steps))} steps · tier default overridden`+ : '') + '</dd>');}} else {genRows.push(`<dt>Quality</dt><dd>${escapeHtml((p.quality || 'standard').replace(/^./, c => c.toUpperCase()))}</dd>`);@@ -4759,6 +7109,75 @@ function renderOutputInfoBody(path, data) {}async function removeJob(id) { await fetch('/queue/remove?id='+encodeURIComponent(id),{method:'POST'}); poll(); }++// VC-26: reorder — plain up/down (the review's own alternative to drag).+async function reorderQueuedJob(id, direction) {+ const fd = new URLSearchParams();+ fd.set('id', id); fd.set('direction', direction);+ let r;+ try { r = await (await fetch('/queue/reorder', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) { phosToast((r && r.error) || 'Could not reorder the queue.', { kind: 'danger' }); return; }+ try { poll(); } catch (e) {}+}++// VC-26: "Click a row to load it into the form and Update job." Restores+// the plain video modes (t2v/i2v/i2v_clean_audio/extend/keyframe) from the+// job's OWN params, already in memory via LAST_STATUS — there is no+// rendered file yet for a queued job, so they go through loadParams(recipe)+// rather than its sidecar fetch. Anything editQueuedJob's own row-template+// gate (`editable` in the queue render above) didn't already exclude gets+// a graceful refusal here too, belt and braces.+let _editingQueuedJobId = null;+const _EDITABLE_QUEUE_MODES = ['t2v', 'i2v', 'i2v_clean_audio', 'extend', 'keyframe'];+async function editQueuedJob(jobId) {+ const job = ((typeof LAST_STATUS !== 'undefined' && LAST_STATUS && LAST_STATUS.queue) || [])+ .find(j => j.id === jobId);+ if (!job) { phosToast('That job is no longer queued.', {}); return; }+ const p = job.params || {};+ if (p.take || p.engine === 'music' || !_EDITABLE_QUEUE_MODES.includes(p.mode)) {+ phosToast('This job type can’t be edited inline yet — remove it and queue a new one.', {});+ return;+ }+ // SAFETY-4: the WHOLE recipe, through Load Params' own setters (engine+ // first, then its surface) — see loadParams(recipe). "Update job" posts+ // the full form, so anything not restored here would be replaced by+ // whatever the form happened to hold.+ _editingQueuedJobId = null;+ try {+ await loadParams({ params: Object.assign({}, p), engine: p.engine });+ } catch (e) {+ phosToast('Could not load that job into the form: ' + ((e && e.message) || e), { kind: 'danger' });+ return;+ }+ _editingQueuedJobId = jobId;+ const banner = document.getElementById('queueEditBanner');+ if (banner) banner.hidden = false;+ const formPane = document.querySelector('aside.form-pane');+ if (formPane) formPane.scrollTop = 0;+ phosToast('Editing queued job — change fields, then Update job.', { duration: 4000 });+}+function cancelEditingQueuedJob() {+ _editingQueuedJobId = null;+ const banner = document.getElementById('queueEditBanner');+ if (banner) banner.hidden = true;+}+async function updateQueuedJob() {+ if (!_editingQueuedJobId) return;+ const form = document.getElementById('genForm');+ const fd = new FormData(form);+ fd.set('id', _editingQueuedJobId);+ let r;+ try { r = await (await fetch('/queue/update', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'Could not update the job.', { kind: 'danger', duration: 7000 });+ return;+ }+ phosToast('Queued job updated.', { kind: 'success' });+ cancelEditingQueuedJob();+ try { poll(); } catch (e) {}+}async function togglePause() {const s = await (await fetch('/status')).json();await api(s.paused ? '/queue/resume' : '/queue/pause', 'POST');@@ -4980,6 +7399,61 @@ async function queueBatch() {sync();})();+// VC-03: "if prompt + seed + size + quality + LoRAs equal an existing+// output's sidecar, ask." Scoped to the clip Load Params most recently+// restored (_loadedRecipeSnapshot) rather than scanning the whole gallery —+// that covers the actual repro (Params, then Generate with nothing+// changed) at the cost of a full-outputs comparison, which would mean a+// server round trip on every keystroke-adjacent Generate click for a+// gallery that can run into the thousands.+function _duplicateOfLoadedRecipe() {+ const snap = _loadedRecipeSnapshot;+ if (!snap) return null;+ const seedEl = document.getElementById('seed');+ const seed = seedEl ? String(seedEl.value || '') : '';+ if (!seed || seed === '-1') return null; // a random-seed render is never "the same clip"+ const promptEl = document.getElementById('prompt');+ const prompt = promptEl ? (promptEl.value || '') : '';+ const widthEl = document.getElementById('width');+ const heightEl = document.getElementById('height');+ const qualityEl = document.getElementById('quality');+ const loras = (typeof _activeLoras !== 'undefined' && Array.isArray(_activeLoras) ? _activeLoras : [])+ .map(l => (l && l.path) + '@' + (l && l.strength)).sort().join(',');+ const same = prompt === snap.prompt && seed === snap.seed+ && String((widthEl && widthEl.value) || '') === snap.width+ && String((heightEl && heightEl.value) || '') === snap.height+ && String((qualityEl && qualityEl.value) || '') === snap.quality+ && loras === snap.loras;+ return same ? snap : null;+}++// A submit-button click's default action IS submitting the form — cancel+// that (not the form's 'submit' handler below, which is too late to swap in+// an async dialog cleanly) and let the dialog's own choice decide whether to+// call requestSubmit(), which fires 'submit' directly and does not re-run+// this click listener.+(function () {+ const btn = document.getElementById('genBtn');+ const form = document.getElementById('genForm');+ if (!btn || !form) return;+ btn.addEventListener('click', (ev) => {+ const dup = _duplicateOfLoadedRecipe();+ if (!dup || typeof _phModalShow !== 'function') return;+ ev.preventDefault();+ _phModalShow({+ tone: 'danger', kicker: 'Same clip again?',+ title: `This will render the same clip as ${dup.name}`,+ body: 'The prompt, seed, size, quality and LoRAs all match. Render a new '+ + 'take uses the same recipe with a fresh seed; Generate anyway repeats '+ + 'this exact clip.',+ primaryLabel: 'Render a new take',+ onPrimary: () => newTakeFromPath(dup.path, { btnId: 'genBtn' }),+ secondaryLabel: 'Generate anyway',+ onSecondary: () => { try { form.requestSubmit(); } catch (e) { form.submit(); } },+ });+ });+})();+// ====== Form submit ======//// "No music" toggle: appends a clear audio constraint to the prompt@@ -4994,6 +7468,19 @@ document.getElementById('genForm').addEventListener('submit', async e => {e.preventDefault();const fd = new FormData(e.target);+ // VC-15: a non-empty Avoid box on a quality that ignores it (distilled+ // Quick/Balanced/Standard) submits fine and produces exactly the clip the+ // "forbidden" content still appears in — the render isn't wrong, the+ // expectation set by the box was. One toast, not a block: the user may+ // know exactly what they're doing (leftover text from a High render, say)+ // and Generate must not gain a second confirmation step for that.+ if ((fd.get('negative_prompt') || '').toString().trim()+ && typeof avoidIsIgnored === 'function' && avoidIsIgnored()+ && typeof phosToast === 'function') {+ phosToast('Avoid is ignored at this quality — it will not affect this render.',+ { kind: 'warn', duration: 6000 });+ }+// ---- engine payload scrub ------------------------------------------------// The fold rules hide an LTX-only control on H3; they do not empty the hidden// input behind it, and FormData reads the input. So a user who picks a@@ -5322,6 +7809,29 @@ document.getElementById('genForm').addEventListener('submit', async e => {}}await api('/queue/add','POST',fd);+ } catch (e) {+ // 4.17 Codex EST-10: the server REFUSED this render and said why (an+ // Extend asking for a Face Fix follow-up this Mac can't run). That is+ // not "offline" — show its sentence, and for a missing download offer+ // the place to get it, before anything renders.+ if (e && e.status) {+ const shown = (e.code === 'pack_missing' && typeof _phModalShow === 'function'+ && typeof openModelsModal === 'function')+ && _phModalShow({ kicker: 'Needs a download', title: 'Not queued',+ body: e.message, primaryLabel: 'Open Models',+ onPrimary: () => openModelsModal(), secondaryLabel: 'Not now' });+ if (!shown) phosToast(e.message, { kind: 'danger', duration: 0 });+ return;+ }+ // SYS-10a: this used to be uncaught. If the panel is offline (server+ // unreachable, Pinokio stopped, a crash) `api()`'s underlying fetch+ // throws "Failed to fetch" here, and with no catch it surfaced as+ // nothing a user could see — Generate just silently did nothing, no+ // toast, Now still said Idle. The prompt is never lost (the form isn't+ // cleared on failure), so this is safe to just say and let them retry.+ phosToast("Couldn't reach Phosphene — it may be offline or restarting. "+ + 'Your prompt is still here; try again once it reconnects.',+ { kind: 'danger', duration: 0 });} finally {// Re-enable on the next event-loop tick so the button visibly// bounces rather than feeling "stuck on click". poll() refreshes@@ -5332,28 +7842,200 @@ document.getElementById('genForm').addEventListener('submit', async e => {});+// ---- Video form draft autosave (VC-38) -------------------------------------+//+// A reload, or the restart every Pinokio Update asks for, used to wipe the+// prompt and every setting — reload.py's own finding: `after reload prompt=+// ''`. Autosaves the Video tab's form to this browser's localStorage (never+// sent anywhere) so either one comes back to what was there before, not a+// blank form. Every access is try/catch'd — a private window, blocked site+// data, or a bad JSON blob degrades to "no draft" rather than a thrown error+// that would take the rest of boot down with it.+const DRAFT_LS_KEY = 'phos_video_draft_v1';++function _draftSnapshot() {+ const val = (id) => { const el = document.getElementById(id); return el ? el.value : undefined; };+ return {+ v: 1,+ mode: val('mode'),+ quality: val('quality'),+ prompt: val('prompt'),+ negative_prompt: val('negative_prompt'),+ seed: val('seed'),+ width: val('width'),+ height: val('height'),+ frames: val('frames'),+ duration: val('duration'),+ // 4.17 Codex SAFETY-13: the mode's own inputs. The draft restored an+ // Image/Keyframe/Extend mode with its source slots empty, so Generate+ // failed until the user rebuilt the inputs the toast said were restored.+ i2v_mode: val('i2vMode'),+ image: val('image'),+ audio: val('audio'),+ video_path: val('video_path'),+ start_image: val('start_image'),+ end_image: val('end_image'),+ loras: (typeof _activeLoras !== 'undefined' && Array.isArray(_activeLoras))+ ? _activeLoras.map(l => ({ path: l.path, strength: l.strength })) : [],+ };+}+// SAFETY-13: a source path from a draft may be gone since; images validate+// in the picker itself (pickerSetImage's /image 404 check), audio and the+// Extend source ask /file/exists and are cleared out loud, never kept dead.+async function _draftDropIfMissing(path, stillSet, clear, what) {+ let d = null;+ try { d = await (await fetch('/file/exists?path=' + encodeURIComponent(path))).json(); }+ catch (e) { return; }+ if (!d || d.exists !== false || !stillSet()) return;+ clear();+ const name = String(path).split('/').pop();+ phosToast(`${name} from your draft is no longer on disk — pick the ${what} again.`, { kind: 'warning' });+}+function saveDraftNow() {+ try {+ const snap = _draftSnapshot();+ // An empty prompt with nothing else interesting isn't worth a write —+ // avoids overwriting a real saved draft with the blank state the form+ // is in for the first second or two of every fresh boot.+ if (!snap.prompt && !snap.negative_prompt && (!snap.loras || !snap.loras.length)) return;+ localStorage.setItem(DRAFT_LS_KEY, JSON.stringify(snap));+ } catch (e) { /* private window / storage blocked — draft just doesn't persist */ }+}+let _draftSaveTimer = null;+function _draftSaveDebounced() {+ if (_draftSaveTimer) clearTimeout(_draftSaveTimer);+ _draftSaveTimer = setTimeout(saveDraftNow, 500);+}+function restoreDraftOnBoot() {+ // Only on a genuinely fresh form — never stomps a clip already loaded via+ // a deep link, an agent-driven Load Params, or anything else that ran+ // before this (boot order keeps this call early, but "never" is cheaper+ // to guarantee than "usually").+ const promptEl = document.getElementById('prompt');+ if (!promptEl || promptEl.value || (typeof activePath !== 'undefined' && activePath)) return;+ let snap = null;+ try {+ const raw = localStorage.getItem(DRAFT_LS_KEY);+ if (raw) snap = JSON.parse(raw);+ } catch (e) { snap = null; }+ if (!snap || (!snap.prompt && !snap.negative_prompt)) return;+ try {+ const videoModes = ['t2v', 'i2v', 'i2v_clean_audio', 'extend', 'keyframe', 'character'];+ if (snap.mode && videoModes.includes(snap.mode) && typeof setMode === 'function') {+ setMode(snap.mode === 'i2v_clean_audio' ? 'i2v' : snap.mode);+ // The With-your-audio sub-mode rides the same field Load Params sets.+ const sub = snap.mode === 'i2v_clean_audio' ? 'i2v_clean_audio' : snap.i2v_mode;+ if ((snap.mode === 'i2v' || snap.mode === 'i2v_clean_audio')+ && (sub === 'i2v' || sub === 'i2v_clean_audio')) {+ const im = document.getElementById('i2vMode'); if (im) im.value = sub;+ const m = document.getElementById('mode'); if (m) m.value = sub;+ }+ }+ if (snap.quality && typeof setQuality === 'function') setQuality(snap.quality);+ const setVal = (id, v) => { const el = document.getElementById(id); if (el && v !== undefined && v !== '') el.value = v; };+ setVal('width', snap.width); setVal('height', snap.height);+ setVal('frames', snap.frames); setVal('duration', snap.duration);+ setVal('prompt', snap.prompt); setVal('negative_prompt', snap.negative_prompt);+ setVal('seed', snap.seed);+ // SAFETY-13: the source inputs, AFTER the dims (no aspect snap — the+ // saved width/height already are what the user had).+ if (typeof pickerSetImage === 'function') {+ for (const key of ['image', 'start_image', 'end_image']) {+ if (snap[key]) pickerSetImage(key, snap[key], { snapAspect: false });+ }+ }+ if (snap.audio && typeof i2vAudioSet === 'function') {+ i2vAudioSet(snap.audio);+ _draftDropIfMissing(snap.audio,+ () => (document.getElementById('audio') || {}).value === snap.audio,+ () => i2vAudioSet(''), 'audio');+ }+ if (snap.video_path) {+ setVal('video_path', snap.video_path);+ setVal('extendSrcSelect', snap.video_path);+ _draftDropIfMissing(snap.video_path,+ () => (document.getElementById('video_path') || {}).value === snap.video_path,+ () => { const v = document.getElementById('video_path'); if (v) v.value = '';+ const sel = document.getElementById('extendSrcSelect'); if (sel) sel.value = '';+ if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} } },+ 'clip to extend');+ }+ if (Array.isArray(snap.loras) && snap.loras.length && typeof _restoreLoraPicker === 'function') {+ _restoreLoraPicker(snap.loras);+ }+ if (typeof syncAvoidRowFromValue === 'function') { try { syncAvoidRowFromValue(); } catch (e) {} }+ if (typeof _syncSeedLockChip === 'function') { try { _syncSeedLockChip(); } catch (e) {} }+ if (typeof updateCustomizeSummary === 'function') { try { updateCustomizeSummary(); } catch (e) {} }+ if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }+ phosToast('Restored your draft prompt and settings from last time.', { kind: 'success', duration: 5000 });+ } catch (e) { /* a half-applied restore is still better than a thrown boot */ }+}+function clearDraftForm() {+ const setVal = (id, v) => { const el = document.getElementById(id); if (el) el.value = v; };+ setVal('prompt', ''); setVal('negative_prompt', ''); setVal('seed', '-1');+ if (typeof syncAvoidRowFromValue === 'function') { try { syncAvoidRowFromValue(); } catch (e) {} }+ if (typeof _syncSeedLockChip === 'function') { try { _syncSeedLockChip(); } catch (e) {} }+ if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }+ try { localStorage.removeItem(DRAFT_LS_KEY); } catch (e) {}+ phosToast('Form cleared.', {});+}+function draftAutosaveInstall() {+ const form = document.getElementById('genForm');+ if (!form) return;+ form.addEventListener('input', _draftSaveDebounced);+ form.addEventListener('change', _draftSaveDebounced);+ // Catches mode/quality/LoRA changes made by clicking a pill rather than+ // typing — those don't fire on #genForm's own input/change, and hunting+ // down every pill's click handler to hook individually is exactly the+ // fragile coupling a plain interval avoids.+ setInterval(saveDraftNow, 4000);+ window.addEventListener('beforeunload', saveDraftNow);+}+// ---- published to the page --------------------------------------------------// Inline handlers in the markup and the other files resolve these through// the global scope; everything NOT listed here is private to this module.Object.assign(globalThis, {notifyJobsDone, notifyOneJob, playDoneChime,h3FinishSetTier, h3FinishActive, setEngine, _syncEnginePromptTools,+ ltxFinishSetTier, ltxFinishActive, _syncFinishAffordance,+ ltxFinishTargets, ltxFinishTierKey, ltxFinishFieldsFromSidecar, ltxTierByKeyExact,currentEngine, _syncEngineForMode, openH3InstallCard, closeH3InstallCard,- enhancePrompt, applyAspect, applyQuality, updateDerived,+ enhancePrompt, applyAspect, applyQuality, updateDerived, updateDerivedForClampedMode, keyframePriceFor,+ _aspectDims, refreshPickerCropOverlays, refreshExtendClampNote, _setCropFocus, _cropFocusFromParams,pickerSetImage, pickerUploadFile, pickerWire, refreshUploadsStrip,refreshIngredientRecent, ingredientPickerWire, fmtMin, snippet,escapeHtml, api, _setOfflineBanner, startDeepVerify,+ applyFirstRunCard, dismissFirstRunCard, useFirstRunPrompt, scrollToShotSetup,friendlyJobError, poll, applyPackIncompleteGate, setRecentFilter,+ avoidIsIgnored, updateAvoidIgnoredState,retryJob, renderCarousel, findOutputByPath, stageMayAutoSelectOutput,setStageAspect, clearStageAspect, fitStagePlayer, initStagePlayerFit,selectOutput, openExpandLightbox, closeExpandLightbox, phosToast,- animateActive, hide, openOutputsFolder, hideActive,+ animateActive, hide, unhide, openOutputsFolder, hideActive,useAsExtendSource, useAsUpscaleSource, useAsUpscaleSourcePath, setUpscalePreset,faceFixClip, faceFixActive, isUpscaledPath, loadParams, _flashActionDone, closeOutputInfoModal,+ queueSharpExport, sharpExportActive, useLastFramePath, useLastFrameActive,+ revealClipInFinder, revealActive, openClipInEditor, openActiveInEditor, kebabToggle,+ reorderQueuedJob, editQueuedJob, cancelEditingQueuedJob, updateQueuedJob, fmtEtaCompact,+ showEnhancePanel, acceptEnhance, undoEnhance, keepMineEnhance,+ updateLangHint, promptLooksNonLatin,+ newTakeFromPath, newTakeActive, requestStop, requestClearQueue, toggleHiddenFilter,+ _syncSeedLockChip, clearSeedLock,+ clearDraftForm, draftAutosaveInstall, restoreDraftOnBoot, saveDraftNow,+ takeResumeFromPath, takeJoinPartialFromPath,togglePause, openBatch, closeBatch, queueBatch,setBatchMode, setBatchTakes, updateBatchSummary, batchPrompts, batchMainPrompt,// inline-handler targets: generated markup resolves these through the// global scope (the v4.9.0 regression, PR #69)_copyToClipboard, animateFromPhoto, deleteOutput, openOutputInfoModal,remakeInQuality, remakeQualityEngine, removeJob, repairModel,+ // VA-20: the mux audio slot's own "Remove" link.+ i2vAudioSet, i2vAudioRenderSlot,+ // "Continue the song" — the player button's inline onclick target.+ continueSongFromClip,+ // "Retake a moment" (VA-26) — the player button + modal's inline onclick targets.+ openRetakeModal, closeRetakeModal, submitRetake,+ // "Continue from here" (VA-38) — the player button's inline onclick target.+ windowsContinueFromPartial,});diff --git a/webapp/js/settings.js b/webapp/js/settings.jsindex d9f9f5b..8100167 100644--- a/webapp/js/settings.js+++ b/webapp/js/settings.js@@ -28,6 +28,27 @@ function updateModelsCard(s) {card.classList.remove('state-missing', 'state-warn', 'state-downloading', 'dismissible');progress.style.display = 'none';+ // ----- A Pinokio-side H3 build/install is running RIGHT NOW --------------+ // H3-19: install/build only ever runs as a Pinokio script — there is no+ // real in-panel trigger for the ~75 GB clone+venv+download (unlike the+ // small Fast/Turbo adapter installs, which DO run in-process). But the+ // worker already reads scripts/pinokio/h3_build_q8.sh's lock file to HOLD+ // the render queue while that script runs (_external_build_hold,+ // mlx_ltx_panel.py) — it just never told the UI why. Surface it as its+ // own precedence-topping state: not an in-panel installer, but an+ // in-panel PROGRESS SIGNAL, so a user who started the build from the+ // Pinokio sidebar doesn't have to keep that tab open to know it's working.+ const extBuild = s.h3 && s.h3.external_build;+ if (extBuild && extBuild.active) {+ card.style.display = '';+ card.classList.add('state-downloading');+ icon.textContent = '↓';+ title.textContent = `Building ${extBuild.what || 'an H3 engine'} in Pinokio`;+ sub.textContent = 'Running in the Pinokio sidebar — Generate resumes here automatically when it finishes. No need to keep that tab open.';+ actions.innerHTML = '';+ return;+ }+// ----- Active download takes precedence over everything ------------------if (dl) {card.style.display = '';@@ -52,16 +73,30 @@ function updateModelsCard(s) {card.classList.add('state-missing');icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>';title.textContent = 'Base models needed before you can render';- const missing = (s.base_missing || []).length;+ const missingList = s.base_missing || [];+ const missing = missingList.length;// REGISTRY-DRIVEN, for the ACTIVE generation. `base_missing` is already// version-scoped, so offering `q4` here downloaded 2.3's base to fix a// broken 2.5 install: 20 GB spent, still broken.const P = ((BOOT.ltx || {}).packs) || {};const pBase = P.base, pEnc = P.encoder;- sub.innerHTML = `${escapeHtml(pBase ? pBase.name : 'The base model')} (~${escapeHtml(pBase ? pBase.size : '?')})`- + ` and ${escapeHtml(pEnc ? pEnc.name : 'its text encoder')} (~${escapeHtml(pEnc ? pEnc.size : '?')})`- + ` are required. Click below — downloads resume if interrupted.${- missing ? ` <span style="color:var(--muted)">(${missing} files left)</span>` : ''+ // SYS-11: this used to say "X AND Y are required" unconditionally,+ // even when only one pack (say, just the base transformer) was+ // actually missing a file and the other (Gemma) was fully present —+ // a half-installed 16 GB install saw "LTX-2.5 base and Gemma 4 are+ // required" with Gemma 4 sitting right there on disk. Name only the+ // pack(s) whose local_dir actually shows up in base_missing.+ const packNeeded = (p) => !p || !p.local_dir+ || missingList.some(f => String(f).includes(p.local_dir));+ const needBase = packNeeded(pBase), needEnc = packNeeded(pEnc);+ const parts = [];+ if (needBase) parts.push(`${escapeHtml(pBase ? pBase.name : 'The base model')} (~${escapeHtml(pBase ? pBase.size : '?')})`);+ if (needEnc) parts.push(`${escapeHtml(pEnc ? pEnc.name : 'its text encoder')} (~${escapeHtml(pEnc ? pEnc.size : '?')})`);+ sub.innerHTML = (parts.join(' and ') || 'A required model')+ + ` ${parts.length > 1 ? 'are' : 'is'} required. Click below — downloads resume if interrupted.${+ // VC-10: was always "(N files left)" — grammatically wrong for the+ // single-file case the review actually hit ("1 files left").+ missing ? ` <span style="color:var(--muted)">(${missing} file${missing === 1 ? '' : 's'} left)</span>` : ''}`;// A mirrored pack does not need `hf` at all — the same per-row question the// Models modal already asks, answered from the same registry field.@@ -152,17 +187,31 @@ function updateModelsCard(s) {// low-RAM engine isn't built yet" misread as "your Mac is not enough" beside// a size note that said 64 GB (X, 2026-09-24).if (h3s.needs_q8_dit) {+ // H3-20: this branch never added 'dismissible' (the × only renders on+ // that class — panel.css `.models-inline.dismissible .models-inline-+ // dismiss`), so the banner was permanent on every 36-59 GB Mac. It also+ // never checked `dismissed`, so a user who did dismiss it (nothing else+ // sets the flag differently) would have kept seeing it anyway. And the+ // body repeated the title almost verbatim: the title said "Hailuo H3+ // runs on this Mac..." and h3s.ram_note (the FULL server sentence, built+ // for the install-card modal) starts with "Hailuo H3 runs on this Mac —+ // on its reduced-RAM lane..." — two sentences that opened the same way,+ // wrapping to ~270px at 1440x900 and pushing Generate under the Now+ // card. One short line here; the full explanation lives one click away+ // in the install card, which already reads h3s.ram_note itself.+ if (dismissed) { card.style.display = 'none'; return; }const built = (h3s.reason === 'missing_q8_dit');card.style.display = '';+ card.classList.add('dismissible');if (built) card.classList.add('state-warn');icon.innerHTML = built? '<svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>': '<svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg>';- title.textContent = built- ? 'Hailuo H3 runs on this Mac — its low-RAM engine isn’t built yet'- : 'Hailuo H3 runs on this Mac — on its compact Q8 engine';- sub.textContent = h3s.ram_note || '';- actions.innerHTML = `<button onclick="openH3InstallCard()">${built ? 'How to enable H3' : 'How to install H3'}</button>`;+ title.textContent = 'Hailuo H3 can run on this Mac';+ sub.textContent = built+ ? 'Its compact engine just needs building — no download.'+ : 'Needs its compact (Q8) engine, built during install.';+ actions.innerHTML = `<button onclick="openH3InstallCard()">Set up H3 →</button>`;return;}if (h3s.capable && !h3s.available && h3s.repairable) {@@ -207,13 +256,19 @@ function updateModelsCard(s) {card.style.display = '';card.classList.add('dismissible');icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-check-bold"/></svg>';+ // SYS-17: "Models ready · 3/12" read as "25% ready" -- the denominator+ // counts every optional add-on, most of which nobody needs. Also+ // dropped the inline "Manage models ->" link here: the card's own+ // static "Manage all models ->" footer link (index.html) said the+ // identical thing right below, so both showed together every time+ // this state rendered.const ready = s.repos_ready ?? 0;const total = s.repos_total ?? 0;- title.textContent = `Models ready · ${ready}/${total}`;- const partialNote = (q8Ok && baseOk) ? '' : ` · ${total - ready} optional missing`;- sub.innerHTML =- `All installed weights detected${partialNote}. ` +- `<a style="color:var(--accent-bright,#7e98ff); cursor:pointer; text-decoration:underline" onclick="openModelsModal()">Manage models →</a>`;+ const addons = Math.max(0, total - ready);+ title.textContent = addons > 0+ ? `Ready to render ✓ · ${addons} add-on${addons === 1 ? '' : 's'} available`+ : 'Ready to render ✓';+ sub.textContent = 'All the weights this Mac renders with are installed.';actions.innerHTML = '';}@@ -292,6 +347,9 @@ document.addEventListener('click', (e) => {// ====== Tier modal ======function openTierModal() {+ // SYS-19: the health popover's Tier row opened this modal UNDERNEATH the+ // still-open popover. Close it first.+ if (typeof closeHealthPop === 'function') closeHealthPop();const modal = document.getElementById('tierModal');modal.style.display = 'flex';// Defensive: show "loading" state immediately so the modal never appears@@ -447,11 +505,14 @@ ${tail}\`\`\``;// Crash-report checkbox only when there's something to bundle.+ // SYS-12: default OFF, per report (was pre-ticked). Zipping a crash log+ // into a public GitHub issue should be something the reporter chooses+ // each time, not a box that was already checked when they opened this.if ((c.crashCount || 0) > 0) {crashRow.style.display = 'flex';crashLabel.textContent =`Include latest crash reports (zips up to 5 of ${c.crashCount} .ips files)`;- document.getElementById('bugCrashCheck').checked = true;+ document.getElementById('bugCrashCheck').checked = false;} else {crashRow.style.display = 'none';}@@ -470,6 +531,21 @@ ${tail}function closeBugModal() {document.getElementById('bugModal').style.display = 'none';}+// SYS-40: for anyone without a GitHub account (or more comfortable+// reporting somewhere else in their own language) — copies the exact+// title + description GitHub would have received, already scrubbed+// server-side the same way (see get_panel_bug_context).+async function copyBugDiagnostics() {+ const statusEl = document.getElementById('bugStatus');+ const title = document.getElementById('bugTitle').value.trim() || '[bug] (untitled)';+ const body = document.getElementById('bugBody').value;+ try {+ await navigator.clipboard.writeText(title + '\n\n' + body);+ if (statusEl) statusEl.textContent = 'Copied — paste it anywhere (a forum post, a DM, a translated message).';+ } catch (e) {+ if (statusEl) statusEl.textContent = 'Could not copy — select the text above manually.';+ }+}async function submitBugReport() {const submitBtn = document.getElementById('bugSubmitBtn');const statusEl = document.getElementById('bugStatus');@@ -675,6 +751,21 @@ async function openSettingsModal() {if (lpSelect) {lpSelect.value = (cur.live_preview === 'off') ? 'off' : 'on';}+ // SYS-28: the select can read "On" while the 22 MB decoder isn't on disk —+ // BOOT.ltx.preview_state names that case (`reason === 'missing_decoder'`)+ // the same way the Now card's preview area already does (preview.js).+ const lpNote = document.getElementById('settingsLivePreviewNote');+ if (lpNote) {+ const ps = ((BOOT.ltx || {}).preview_state) || {};+ if (ps.reason === 'missing_decoder') {+ lpNote.hidden = false;+ lpNote.innerHTML = 'Live preview: needs a 22 MB add-on — ' ++ '<a href="#" onclick="closeSettingsModal();openModelsModal();return false;">Get it</a>';+ } else {+ lpNote.hidden = true;+ lpNote.textContent = '';+ }+ }// H3 model. Hidden entirely when H3 is not installed — an install that// cannot render H3 has no use for a control that only changes how it does.const ditRow = document.getElementById('settingsH3DitRow');@@ -1361,7 +1452,7 @@ Object.assign(globalThis, {appearanceGet, applyAppearance, setAppearance,renderNotifyState, toggleNotify, askNotifyPermission,updateModelsCard, dismissModelsCard, applyTierGates, openTierModal,- closeTierModal, openBugModal, closeBugModal, submitBugReport,+ closeTierModal, openBugModal, closeBugModal, submitBugReport, copyBugDiagnostics,openSettingsModal, toggleAnalytics, saveAnalyticsKey, clearAnalyticsKey,toggleSpicyMode, onTokenInput, toggleTokenVisibility, testToken,clearToken, closeSettingsModal, applySettings, _applyHdrPillAvailability,diff --git a/webapp/js/shortcuts.js b/webapp/js/shortcuts.jsindex ebb2e59..5d290da 100644--- a/webapp/js/shortcuts.js+++ b/webapp/js/shortcuts.js@@ -70,8 +70,8 @@ const SHORTCUTS = [// ---- typing a prompt --------------------------------------------------------{ id: 'prompt.generate', scope: 'prompt', combos: ['mod+enter'], typing: true,- owner: 'shortcuts.js (Video, Images) · oneshot.js (One Shot)',- label: 'Generate — from the Video prompt, the Images prompt or the One Shot prompt. Same as pressing the Generate button, so it queues a render.',+ owner: 'shortcuts.js (Video, Images, Lip-sync) · oneshot.js (One Shot)',+ label: 'Generate — from the Video prompt, the Images prompt, the Lip-sync prompt or the One Shot prompt. Same as pressing the Generate button, so it queues a render.',run: (ev) => shortcutGenerateFrom(ev.target) },{ id: 'oneshot.beats', scope: 'prompt', combos: ['enter', 'backspace'], owner: 'oneshot.js',label: 'In One Shot beats: ⏎ goes to the next beat · ⌫ in an empty beat goes back one' },@@ -87,6 +87,9 @@ const SHORTCUTS = [{ id: 'outputs.trash', scope: 'outputs', combos: ['mod+backspace'], owner: 'shortcuts.js',label: 'Move the selected output to the Trash — asks first, like the trash button on the card',run: () => shortcutTrashOutput() },+ { id: 'outputs.newtake', scope: 'outputs', combos: ['r'], owner: 'shortcuts.js',+ label: 'New take — queue another render of the selected output, same recipe, a fresh seed (VC-03)',+ run: () => shortcutNewTake() },// ---- the Editor: keys ---------------------------------------------------------// `calls` is the function the Editor's own keydown handler runs for these@@ -104,6 +107,10 @@ const SHORTCUTS = [{ id: 'editor.nudge', scope: 'editor', combos: ['alt+arrowleft', 'alt+arrowright'],hidden: ['alt+shift+arrowleft', 'alt+shift+arrowright'], owner: 'editor.js',calls: 'sbeNudge', label: 'Nudge the selected clips one frame earlier / later · add ⇧ for ten' },+ { id: 'editor.slip', scope: 'editor', combos: ['alt+comma', 'alt+period'],+ hidden: ['alt+shift+comma', 'alt+shift+period'], owner: 'editor.js',+ calls: 'sbeSlipNudge',+ label: 'Slip the selected clip one frame — changes what plays, not when (⌥⌘-drag the clip body for the same thing by eye) · add ⇧ for ten' },{ id: 'editor.split', scope: 'editor', combos: ['s', 'mod+k', 'mod+b'], owner: 'editor.js',calls: 'sbeSplitHere', label: 'Split the shot under the playhead — or, with sounds on an audio track selected, those sounds (S, or ⌘K as in Premiere, ⌘B as in Final Cut and Resolve)' },{ id: 'editor.lift', scope: 'editor', combos: ['backspace'], hidden: ['delete'], owner: 'editor.js',@@ -134,9 +141,21 @@ const SHORTCUTS = [calls: 'sbeZoomFit', label: 'Fit the whole sequence in the window' },{ id: 'editor.snap', scope: 'editor', combos: ['n'], owner: 'editor.js',calls: 'sbeToggleSnap', label: 'Snap to beat on / off' },- { id: 'editor.mute', scope: 'editor', combos: ['m'], owner: 'editor.js',+ // FILM-58: M is MARKER in every NLE this timeline aliases itself to+ // (Premiere, Final Cut, Resolve) — the preview mute that used to own it+ // moved to ⇧M, the same displacement pattern editor.ripple already uses+ // for its own delete key.+ { id: 'editor.marker', scope: 'editor', combos: ['m'], owner: 'editor.js',+ calls: 'sbeMarkerAtPlayhead',+ label: 'Add a marker at the playhead (Premiere\'s, Final Cut\'s and Resolve\'s M)' },+ { id: 'editor.mute', scope: 'editor', combos: ['shift+m'], owner: 'editor.js',calls: ['sbeSetMute', 'sbeUnmuteFromRefusal'],label: 'Mute / unmute the preview — the film itself is not changed' },+ { id: 'editor.copy', scope: 'editor', combos: ['mod+c'], owner: 'editor.js',+ calls: 'sbeClipCopy', label: 'Copy the selected clip(s)' },+ { id: 'editor.paste', scope: 'editor', combos: ['mod+v'], owner: 'editor.js',+ calls: 'sbeClipPaste',+ label: 'Paste — onto one selected clip, pastes its grade, frame, fades and speed; otherwise pastes new clips at the playhead' },// THE SPLIT. Sound mode is the one thing that changes it: the sound lanes// at full height and the picture small, or back. The ⌁ button on the tool// row and the ▾ on the A1 head are the same control.@@ -218,7 +237,7 @@ const _SC_KEYNAMES = {space: ' ', enter: 'enter', escape: 'escape', backspace: 'backspace', delete: 'delete',arrowleft: 'arrowleft', arrowright: 'arrowright', arrowup: 'arrowup', arrowdown: 'arrowdown',home: 'home', end: 'end', plus: '+', minus: '-', equals: '=', underscore: '_',- backslash: '\\', backquote: '`', comma: ',', tab: 'tab', slash: '/',+ backslash: '\\', backquote: '`', comma: ',', period: '.', tab: 'tab', slash: '/',};// Keys whose character already needs Shift on a US layout: their combos do not// say shift, and matching ignores it.@@ -419,6 +438,20 @@ function shortcutGenerateFrom(t) {imgStudioGenerate();return;}+ // VA-34: Lip-sync's prompt box had no Cmd+Enter — shortcuts.js listed+ // Video and Images, oneshot.js has its own listener for One Shot, and+ // A2V (audioStudioGenerate, its own submit path outside #genForm) had+ // neither.+ if (id === 'audioStudioPrompt') {+ const btn = document.getElementById('audioStudioGenBtn');+ if (!btn || typeof audioStudioGenerate !== 'function') return false;+ if (btn.disabled) {+ if (typeof phosToast === 'function') phosToast(btn.title || 'Generate is not available right now.', { duration: 5000 });+ return;+ }+ audioStudioGenerate();+ return;+ }return false; // One Shot's prompt has its own listener (oneshot.js)}@@ -453,6 +486,14 @@ function shortcutTrashOutput() {deleteOutput(activePath); // confirms before it moves anything}+function shortcutNewTake() {+ if (shortcutTopModal() || !_scOnOutputsTab()) return false;+ if (typeof activePath === 'undefined' || !activePath || typeof newTakeActive !== 'function') return false;+ const btn = document.getElementById('newTakeBtn');+ if (btn && btn.disabled) return false;+ newTakeActive();+}+document.addEventListener('keydown', (ev) => {if (ev.defaultPrevented || ev.isComposing) return;const typing = shortcutTyping(ev.target);diff --git a/webapp/js/stage.js b/webapp/js/stage.jsindex da65539..7db61f3 100644--- a/webapp/js/stage.js+++ b/webapp/js/stage.js@@ -44,7 +44,11 @@ function imgStudioUpdateValidity() {invalidReason = 'This engine needs a ' + engInfo.mac_gb_needed + ' GB Mac — this one has '+ (_IMG_HOST_RAM_GB || '?') + ' GB. Auto (the 4B FLUX engine) fits here.';} else if (needsRefs && refsCount === 0) {- invalidReason = 'Pick at least 1 reference image (drop a file into one of the 3 slots above) — Qwen-Image-Edit composes against an image, it cannot run text-only. Use the Lightning preset only after picking a ref.';+ // SYS-14: "Pick a reference image" was the whole message -- for+ // someone who came here to make a FIRST picture from words (no photo+ // to drop yet), that's a dead end with no next step. Names the+ // engine that actually does this.+ invalidReason = 'This engine composes against a photo — drop one into a slot above, or switch Engine (below) to "Ideogram 4" to make a picture from words alone.';}// Non-blocking notice (does NOT disable Generate): Ideogram is text-only,// so a loaded reference is silently dropped unless the reference bridge is@@ -58,6 +62,28 @@ function imgStudioUpdateValidity() {&& !(typeof ideoState === 'object' && ideoState.refBridge)) {softNotice = 'Heads up: Ideogram is text-only, so your reference image will be IGNORED. Turn on "Use reference" above to have Ideogram redraw it from a description, or switch to a Reference Edit engine for a faithful copy.';}+ // SYS-13: `image_ram` is the #1 refusal (78 installs/30d) and the+ // FREE-memory branch specifically fires at RENDER time, after the job+ // waited in the queue -- the fits_mac check above already prevents+ // submitting an engine that can NEVER fit this Mac, but not a heavier+ // engine that fits in principle while other apps are currently holding+ // the RAM it needs. ram_need_gb (image/engine_status, the same number+ // the server's own preflight compares) vs. the live memory poll gives+ // the same warning BEFORE queueing instead of after. Soft on purpose+ // (matches the fix note: a 24 GB engine on a 48 GB Mac should warn, not+ // hard-refuse -- memory frees up, and the server still does the+ // authoritative check right before it actually loads the model).+ if (!invalidReason && !softNotice && engInfo && engInfo.fits_mac !== false+ && typeof engInfo.ram_need_gb === 'number'+ && typeof LAST_STATUS === 'object' && LAST_STATUS && LAST_STATUS.memory) {+ const mem = LAST_STATUS.memory;+ const freeGb = Math.max(0, (Number(mem.total_gb) || 0) - (Number(mem.used_gb) || 0));+ if (freeGb < engInfo.ram_need_gb) {+ softNotice = `Heads up: this engine typically needs ~${engInfo.ram_need_gb.toFixed(0)} GB free, `+ + `and only ~${freeGb.toFixed(1)} GB is free right now. It may still work — Phosphene frees `+ + `the idle video engine first — but closing other apps (browsers, another render) first is safer.`;+ }+ }// Don't override the busy state — imgStudioGenerate manages disabled// during in-flight gens.if (!IMG_STUDIO.busy) {diff --git a/webapp/js/storyboard.js b/webapp/js/storyboard.jsindex 5cf5904..6ac7cb2 100644--- a/webapp/js/storyboard.js+++ b/webapp/js/storyboard.js@@ -39,6 +39,14 @@ globalThis.SB = {filmShort: '',filmOpen: '', // the film being played, by nameboardsSig: '', // last painted board-row signature (see sbPollHook)+ // FILM-41: 'list' (the full editable cards) | 'grid' (a dense contact+ // sheet). Session-scoped like stageMode — a working preference, not a+ // setting to hunt down and undo.+ shotView: (function () {+ try { return sessionStorage.getItem('phos.sb.shotView') || 'list'; }+ catch (e) { return 'list'; }+ })(),+ playlist: null, // {paths, idx, boardId} — see sbPlayBoard()};const SB_BOOT = (typeof BOOT !== 'undefined' && BOOT.storyboard) ? BOOT.storyboard : {};@@ -188,6 +196,17 @@ function sbInit() {sbRenderFinalQualities();const help = sbEl('sbRamHelpNote');if (help && !help.textContent) help.textContent = SB_BOOT.ram_help || '';+ // FILM-56: this line sits right next to the Plan button, before a shot+ // count even exists to scale by — so it gets the RAM half of the fix+ // (the modal's own copy, once planning is running, adds the shot-count+ // half via _sbPlanningTimeCopy). Said once, at boot, from the same+ // ram_status the modal reads.+ const ramLine = sbEl('sbRamLine');+ const ramStatus = SB_BOOT.ram_status || {};+ if (ramLine && !ramStatus.ok && ramStatus.message) {+ const span = ramLine.querySelector('span');+ if (span) span.textContent = ramStatus.message;+ }// Draft restore — a restart must not eat what someone typed.try {const draft = localStorage.getItem('phos_sb_draft');@@ -215,7 +234,20 @@ function sbInit() {// Restore the last board the user was on, same idiom as phos_workflow.let last = '';try { last = localStorage.getItem('phos_sb_open') || ''; } catch (e) {}+ // FILM-02: sbInit() runs on every tab entry, including the entries a+ // caller makes ON PURPOSE to land on a SPECIFIC board — Plan the video,+ // a finished render, the gallery's "open this film" badge. Every one of+ // those calls workflowSwitch('storyboard') (which runs sbInit) and THEN+ // sbOpen(theBoardItMeans) — synchronously, before any await, so SB.id is+ // already the caller's target the instant sbOpen runs. But this restore+ // is async too: if /storyboard/list is still in flight when that happens,+ // this .then() used to fire anyway and call sbOpen(last) — overwriting+ // the caller's board with whatever tab was open last time. Snapshot the+ // id this restore started with; if it's different by the time the list+ // comes back, someone already moved on and this restore has nothing to do.+ const sbInitId = SB.id;sbRefreshBoards().then(() => {+ if (SB.id !== sbInitId) return;if (last && SB.boards.some(b => b.id === last)) sbOpen(last);else if (SB.boards.length) sbShow('list');else sbShow('empty');@@ -349,15 +381,22 @@ function sbParseLocations(text) {((text || '').split('\n')).forEach(line => {const raw = line.trim();if (!raw) return;- const at = raw.indexOf(':');+ // FILM-45: a Japanese location line uses the full-width colon (":")+ // rather than the ASCII one — checked first so it wins when both a+ // name and a ":" appear (mirrors the server's own fallback order).+ let at = raw.indexOf(':');+ if (at <= 0) { const fw = raw.indexOf(':'); if (fw > 0) at = fw; }// No colon = the whole line is the description and the name is derived.// Refusing the line instead would lose what somebody just typed.const name = (at > 0 ? raw.slice(0, at) : raw.split(/[,.]/)[0]).trim().slice(0, 60);const desc = (at > 0 ? raw.slice(at + 1) : raw).trim();if (!name || !desc) return;- let id = name.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 40);+ // Unicode-aware: \p{L}/\p{N} keep any script's letters/digits, not just+ // a-z0-9, so a Japanese location name gets its own id instead of every+ // one collapsing to loc1/loc2/loc3 with no distinguishing text.+ let id = name.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '_').replace(/^_+|_+$/g, '').slice(0, 40);if (!id) id = 'loc' + (out.length + 1);- if (!/^[a-z0-9]/.test(id)) id = 'l' + id;+ if (!/^[\p{L}\p{N}]/u.test(id)) id = 'l' + id;while (seen[id]) id = id.replace(/\d*$/, m => String((parseInt(m || '1', 10) || 1) + 1));seen[id] = 1;out.push({ id: id, name: name, description: desc });@@ -380,6 +419,10 @@ let _sbShots = 12;// ONE SHOT is the fifth answer on the Shots row: a film that is one shot,// planned as beats. `_sbTake` is 0 (off) or the shot's length in seconds.let _sbTake = 0;+// FILM-56: the shot count the planner is actually running on, captured at+// submit time so the "About a minute" copy can scale with it instead of+// quoting the same line for a 4-shot board and a 20-shot one.+let _sbPlanShotsSubmitted = 12;function sbSetShots(n, persist) {const take = (n === 'take');if (take) { if (!_sbTake) _sbTake = 60; }@@ -415,6 +458,18 @@ function sbToggleSwitchHelp() {btn.setAttribute('aria-expanded', open ? 'false' : 'true');note.hidden = open;}+// FILM-46: "Stills first" implies "start each shot from a still" — a still+// to approve has to exist. Checking Stills first force-checks and locks+// Anchor stills; unchecking Anchor stills (when it was carrying Stills+// first) turns Stills first back off, since approving a still that will+// never be made makes no sense.+function sbStillsFirstSync() {+ const first = sbEl('sbStillsFirst');+ const anchor = sbEl('sbAnchorStills');+ if (!first || !anchor) return;+ if (first.checked) { anchor.checked = true; anchor.disabled = true; }+ else { anchor.disabled = false; }+}// The long-shot switch needs the Q8 pack (the chain runs on the dev// transformer). Say so on the switch, from the status the panel already has,// rather than at render time per shot.@@ -442,6 +497,43 @@ async function sbRestill(n) {sbLoad(SB.id, true);}+// FILM-22: "Edit & re-render" on a done card. No planner call — the shot's+// current clip is archived (never deleted) and the shot goes back to+// pending with a fresh seed, so it's an ordinary renderable shot again: the+// prompt unlocks, and the next Render (or Retry) picks it up like any other.+async function sbNewTake(n) {+ const fd = new FormData();+ fd.set('id', SB.id); fd.set('n', String(n));+ let r;+ try { r = await (await fetch('/storyboard/new-take', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) { phosToast(r.error || 'Could not start a new take.', { kind: 'danger', duration: 6000 }); return; }+ phosToast(`Shot ${n} is ready to edit and re-render — the old clip is kept.`, { duration: 6000 });+ sbLoad(SB.id, true);+}++// FILM-46: "Stills first" approve step — no render is queued by this call,+// it only releases the hold the render thread put on the shot; the next+// Render/Retry picks it up.+async function sbApproveStill(n) {+ const fd = new FormData();+ fd.set('id', SB.id); fd.set('n', String(n));+ let r;+ try { r = await (await fetch('/storyboard/approve-still', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) { phosToast(r.error || 'Could not approve that still.', { kind: 'danger', duration: 6000 }); return; }+ sbLoad(SB.id, true);+}+async function sbApproveAllStills() {+ const fd = new FormData(); fd.set('id', SB.id);+ let r;+ try { r = await (await fetch('/storyboard/approve-all-stills', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) { phosToast(r.error || 'Could not approve those stills.', { kind: 'danger', duration: 6000 }); return; }+ if (r.approved) phosToast(`Approved ${r.approved} still${r.approved === 1 ? '' : 's'}.`, { kind: 'success' });+ sbLoad(SB.id, true);+}+function sbToggleRamHelp() {const btn = sbEl('sbRamHelpBtn'), note = sbEl('sbRamHelpNote');if (!btn || !note) return;@@ -632,6 +724,15 @@ function sbEngineSnapWarning(mode) {async function sbPlan() {const concept = (sbEl('sbConcept') || {}).value || '';if (!concept.trim()) { phosToast('Write a couple of sentences about the film first.'); return; }+ // FILM-56: the planner's own memory footprint used to OOM on an 8-16 GB+ // Mac after several minutes' wait, with nothing said before it started.+ // The server already knows whether this Mac clears its floor — say so+ // now, once, rather than let the timeout say it later.+ const ramStatus = SB_BOOT.ram_status || {};+ if (!ramStatus.ok && ramStatus.message) {+ phosToast(ramStatus.message, { duration: 8000 });+ }+ _sbPlanShotsSubmitted = sbShotsValue() || 12;const btn = sbEl('sbPlanBtn');if (btn) { btn.dataset.busy = '1'; btn.disabled = true; btn.textContent = 'Planning…'; }const fd = new URLSearchParams();@@ -642,6 +743,7 @@ async function sbPlan() {fd.set('must', (sbEl('sbMust') || {}).value || '');fd.set('locations', (sbEl('sbLocations') || {}).value || '');fd.set('wardrobe', (sbEl('sbWardrobe') || {}).value || '');+ fd.set('light', (sbEl('sbLight') || {}).value || '');fd.set('engine', _sbEngineMode);if (_sbCastId) fd.set('character_id', _sbCastId);// The director's two fields travel whenever the row exists, so clearing@@ -653,6 +755,7 @@ async function sbPlan() {}if (sbEl('sbAuto')) fd.set('auto', sbEl('sbAuto').checked ? '1' : '0');if (sbEl('sbAnchorStills')) fd.set('anchor_stills', sbEl('sbAnchorStills').checked ? '1' : '0');+ if (sbEl('sbStillsFirst')) fd.set('stills_first', sbEl('sbStillsFirst').checked ? '1' : '0');if (sbEl('sbLongWindows')) fd.set('long_windows', sbEl('sbLongWindows').checked ? '1' : '0');let r;try {@@ -673,6 +776,16 @@ async function sbPlan() {sbSetPlanningStage('load');sbLoad(SB.id);}+// FILM-44: this Soundtrack box is the "Director" — an LLM writes a+// beat-synced shot list from a plain concept, and the track is a raw file+// path. The Audio tab's Music Video pane is a different, more capable+// entrance for the common case (cast a Singer + B-roll pictures against a+// song, with a real drop-zone and a library) and a creator typing a+// concept here would never find it. This is the one signpost between them.+function sbGoToMusicVideo() {+ if (typeof workflowSwitch === 'function') workflowSwitch('audio');+ if (typeof audioModeSet === 'function') audioModeSet('drive');+}// THE SHOTS CHIPS STAND DOWN WHEN A TRACK IS ON THE BRIEF — the grid decides// the count — and the line under the field says what will happen instead.function sbTrackInput() {@@ -705,12 +818,32 @@ async function sbCancelPlan() {sbLoad(SB.id);}+// FILM-56: "About a minute" was said for every board regardless of shot+// count, while the server's own timeout is 900s (15 minutes) — a large+// board that genuinely takes several minutes read as stuck against a+// promise of one. Scales with the shot count actually submitted, and+// folds in the low-RAM notice (see SB_BOOT.ram_status) so a Mac already+// flagged as likely to run out keeps saying so through every stage, not+// just in the one-off toast `sbPlan()` shows at submit time.+function _sbPlanningTimeCopy() {+ const n = _sbPlanShotsSubmitted || 12;+ const base = n <= 4 ? 'About a minute'+ : n <= 12 ? 'A few minutes for ' + n + ' shots'+ : 'Several minutes for ' + n + ' shots';+ const ramStatus = SB_BOOT.ram_status || {};+ if (!ramStatus.ok) {+ return base + '. This Mac is short on memory for the planner — it can '+ + 'fail instead of finishing. Nothing renders yet.';+ }+ return base + '. Nothing renders yet.';+}+function sbSetPlanningStage(stage) {const map = {- load: ['Loading the planner', 'About a minute. Nothing renders yet.'],+ load: ['Loading the planner', _sbPlanningTimeCopy()],grid: ['Reading the beat', 'Finding the downbeats the shots will cut on.'],- write: ['Writing the plan', 'About a minute. Nothing renders yet.'],- check: ['Checking the plan', 'About a minute. Nothing renders yet.'],+ write: ['Writing the plan', _sbPlanningTimeCopy()],+ check: ['Checking the plan', _sbPlanningTimeCopy()],repair: ['Fixing the plan', 'It came back slightly malformed. One retry.'],unload: ['Giving the memory back', 'The renderer gets it now.'],};@@ -918,6 +1051,11 @@ async function sbLoad(id, quiet) {try {r = await (await fetch('/storyboard/get?id=' + encodeURIComponent(id))).json();} catch (e) { return; }+ // FILM-02/FILM-19: another sbOpen — a caller elsewhere, the 2s poll, the+ // gallery's "open this film" badge — may have moved SB.id on while this+ // fetch was in flight. Adopting this reply now would silently repaint (and+ // let a later save write) a DIFFERENT film than the one now on screen.+ if (id !== SB.id) return;if (!r || !r.ok) {if (!quiet) phosToast('That storyboard is gone.', { kind: 'danger' });sbBackToList();@@ -1085,42 +1223,59 @@ function sbRenderPlan(r) {const shots = b.shots || [];const title = sbEl('sbTitle');if (title && document.activeElement !== title) title.value = b.title || '';- // The three brief switches read back from the board, so reopening a film- // shows how it is being made — not whatever the last brief had ticked.- for (const [id, key] of [['sbAuto', 'auto'], ['sbAnchorStills', 'anchor_stills'], ['sbLongWindows', 'long_windows']]) {+ // The brief switches read back from the board, so reopening a film shows+ // how it is being made — not whatever the last brief had ticked.+ for (const [id, key] of [['sbAuto', 'auto'], ['sbAnchorStills', 'anchor_stills'],+ ['sbStillsFirst', 'stills_first'], ['sbLongWindows', 'long_windows']]) {const el = sbEl(id);if (el && key in b) el.checked = !!b[key];}- if ('take_seconds' in b) {- if (b.take_seconds) { sbSetShots('take', false); sbSetTake(b.take_seconds); }- else sbSetShots(b.shots_target || _sbShots, false);- }+ sbStillsFirstSync();+ // 4.17: the brief's Length (shot count / One-take seconds) and Engine are+ // the NEW-film form — the next "Plan" reads them. Opening a board used to+ // copy that board's shot count into them, so planning a new film after+ // browsing an old one silently inherited its length. The open board's own+ // size is on its plan screen; Re-plan / Try again read the board itself+ // (b.shots_target, b.engine_mode), never these controls.sbSyncBriefGates();// --- summary ---- // Per PASS, not per `status`: during delivery, `status === 'done'` still- // reads true from the draft that already landed.- const outKey = r.pass === 'final' ? 'final_output' : 'draft_output';- const done = shots.filter(s => s[outKey]).length;+ // FILM-42: ONE model, both passes counted honestly, so this line can+ // never again contradict the rail's own "N of M rendered" (which counts+ // ANY clip, `final_output || draft_output`). The old version counted only+ // the CURRENT pass's output key and then labelled the final branch+ // "Finished" unconditionally — so a board whose delivery pass had not+ // even started yet (0 delivered) read "Finished · 0 shots" right next to+ // a rail that correctly said every draft had rendered.+ const draftDone = shots.filter(s => s.draft_output).length;+ const finalDone = shots.filter(s => s.final_output).length;const failed = shots.filter(s => s.status === 'failed').length;const rendering = !!r.rendering;let status;if (r.pass === 'final') {- // "Delivery rendering · 4 of 4" is a sentence about a thread that hasn't- // released its slot yet, not about the film. Once every shot has its- // delivery clip the film is finished, whatever the dispatcher is doing.- status = (rendering && done < shots.length)- ? `Delivery rendering · ${done} of ${shots.length}`- : `Finished · ${done} shot${done === 1 ? '' : 's'}`;+ if (rendering && finalDone < shots.length) {+ // "Delivery rendering · 4 of 4" is a sentence about a thread that+ // hasn't released its slot yet, not about the film.+ status = `Delivery rendering · ${finalDone} of ${shots.length}`;+ } else if (shots.length && finalDone >= shots.length) {+ status = `Finished · ${finalDone} shot${finalDone === 1 ? '' : 's'}`;+ } else if (finalDone) {+ status = `Delivery · ${finalDone} of ${shots.length}`;+ } else {+ // The drafts are what finished — that is WHY the pass moved to+ // final — but delivery itself has not started. "Finished" would+ // claim a pass that never ran.+ status = 'Drafts done · ready for delivery';+ }} else if (rendering) {- status = `Drafts rendering · ${done} of ${shots.length}`;- } else if (done && done + failed >= shots.length) {- status = failed ? `Drafts done · ${done} of ${shots.length}, ${failed} failed`- : `Drafts done · ${done} of ${shots.length}`;- } else if (done) {+ status = `Drafts rendering · ${draftDone} of ${shots.length}`;+ } else if (draftDone && draftDone + failed >= shots.length) {+ status = failed ? `Drafts done · ${draftDone} of ${shots.length}, ${failed} failed`+ : `Drafts done · ${draftDone} of ${shots.length}`;+ } else if (draftDone) {// Partway through and NOT running — stopped, or a single shot retried.// "Drafts rendering" here would be a sentence that isn't true.- status = `Drafts · ${done} of ${shots.length}`;+ status = `Drafts · ${draftDone} of ${shots.length}`;} else {status = 'Draft plan · not rendered';}@@ -1197,6 +1352,21 @@ function sbRenderPlan(r) {errBox.hidden = !boardErrs.length;errBox.innerHTML = boardErrs.map(sbErrRow).join('');+ // FILM-46: "Stills first" — how many are waiting for a look, in one place,+ // with a bulk Approve so a 20-shot board isn't 20 individual clicks.+ const stillsBanner = sbEl('sbStillsBanner');+ if (stillsBanner) {+ const waiting = b.stills_first+ ? shots.filter(s => s.still && !s.still_approved && s.still_source !== 'user').length+ : 0;+ stillsBanner.hidden = !waiting;+ if (waiting) {+ stillsBanner.innerHTML =+ `<span>${waiting} still${waiting === 1 ? '' : 's'} ready for approval.</span>` ++ `<button type="button" class="ghost-btn" onclick="sbApproveAllStills()">Approve all</button>`;+ }+ }+// --- shot cards ---// Rebuilding the list under a cursor is what makes editing impossible, so a// repaint that arrives mid-word repaints everything EXCEPT the cards. The@@ -1210,8 +1380,15 @@ function sbRenderPlan(r) {// visibly. Cheap, too: the string is built either way, the compare is the// only new work.const box = sbEl('sbShots');+ box.classList.toggle('sb-shots-grid', SB.shotView === 'grid');+ const viewTog = sbEl('sbShotViewToggle');+ // FILM-41: a handful of shots is already fully visible as a list; the+ // grid earns its place on a board long enough to need finding a shot fast.+ if (viewTog) viewTog.hidden = shots.length < 12;if (!sbTypingInShots() && !sbSelectOpen()) {- const html = shots.map(s => sbShotCard(s, r, errs)).join('');+ const html = SB.shotView === 'grid'+ ? shots.map(sbShotGridTile).join('')+ : shots.map(s => sbShotCard(s, r, errs)).join('');if (html !== _sbShotsHtml || box.childElementCount !== shots.length) {box.innerHTML = html;_sbShotsHtml = html;@@ -1270,6 +1447,48 @@ function sbAutoGrowPrompts(one) {});}+// FILM-41: List/Grid toggle for the shot list itself (separate from the+// Shot-list/Player stage toggle above — this decides how the SHOT LIST is+// laid out, not what the stage pane shows).+function sbSetShotView(mode) {+ SB.shotView = mode;+ try { sessionStorage.setItem('phos.sb.shotView', mode); } catch (e) {}+ const tog = sbEl('sbShotViewToggle');+ if (tog) tog.querySelectorAll('.smt-btn').forEach(b =>+ b.classList.toggle('active', b.dataset.sbView === mode));+ const box = sbEl('sbShots');+ if (box) box.classList.toggle('sb-shots-grid', mode === 'grid');+ _sbShotsHtml = ''; // force a repaint under the new layout+ if (SB.payload) sbRenderPlan(SB.payload);+}+// Clicking a tile is the "detail" step: back to the full editable card,+// scrolled to it — no second surface to keep in sync with the real one.+function sbGridTileOpen(n) {+ sbSetShotView('list');+ requestAnimationFrame(() => sbScrollToShot(n));+}+function sbShotGridTile(s) {+ const n = s.n;+ const clip = s.final_output || s.draft_output;+ const dur = Number(s.duration_s || 0);+ const gradeDot = s.grade+ ? `<span class="sb-grid-grade sb-grid-grade-${escapeHtml(s.grade)}">${{ keep: 'K', reroll: 'R', cut: 'C' }[s.grade] || ''}</span>`+ : '';+ const thumb = clip+ ? `<video class="sb-grid-thumb" preload="metadata" muted playsinline src="/file?path=${encodeURIComponent(clip)}"></video>`+ : `<div class="sb-grid-thumb sb-grid-thumb-empty" aria-hidden="true"></div>`;+ return `<li class="sb-grid-tile" data-n="${n}" onclick="sbGridTileOpen(${n})" role="button" tabindex="0"+ title="${escapeHtml((s.title || s.prompt || '').slice(0, 140))}">+ ${thumb}+ <div class="sb-grid-meta">+ <span class="sb-grid-n">${String(n).padStart(2, '0')}</span>+ <span class="sb-grid-dur">${dur ? dur.toFixed(1) + 's' : ''}</span>+ <span class="sb-grid-status sb-grid-status-${escapeHtml(s.status || 'pending')}">${escapeHtml(s.status || 'pending')}</span>+ ${gradeDot}+ </div>+ </li>`;+}+function sbErrRow(e) {const copy = SB_ERR_COPY[e.code];const html = !copy ? escapeHtml(e.message)@@ -1287,6 +1506,14 @@ function sbShotCard(s, r, errs) {const est = (r.per_shot_est || {})[String(n)];const chars = r.characters || [];const locked = (s.status === 'rendering' || s.status === 'queued' || s.status === 'done');+ // FILM-21: a singing (a2v) shot on a music-video board was rendered+ // against ONE EXACT stretch of the song — its film_start/film_end and+ // its audio linkage are facts about the track, not creative choices.+ // Reorder, a duration change, the Text/Character toggle or a Rewrite can+ // each knock it (and every later singing shot) off its own words, so all+ // four are locked here rather than fixed after the fact.+ const mv = s.music_video || null;+ const singingLocked = s.mode === 'a2v' && mv && mv.kind === 'singing';// The chip says what will ACTUALLY render, not what the plan wrote. With no// H3 pack the server forces every shot to LTX at enqueue, so a pink Hailuo// chip on a machine that has no Hailuo would be the UI contradicting itself.@@ -1353,22 +1580,53 @@ function sbShotCard(s, r, errs) {}durOpts += `<option value="${_cur}" selected>${escapeHtml(label)}</option>`;}- const passLabel = r.pass === 'final' ? 'Delivery' : 'Draft';+ // FILM-42: this used to be ONE label for the whole board, read off+ // `r.pass` (whichever pass is currently active) — so a shot that had+ // already delivered was badged "Draft" the moment ANY other shot on the+ // board still needed its delivery pass, and vice versa. Each shot is+ // judged on its OWN clip now: the real pixel size ffprobe measured when+ // the clip landed (`output_dims`), compared against the board's own+ // Delivery canvas — never a guess from whichever pass queued it.+ const finalPol = ((r.board || {}).policy || {}).final || {};+ const finalMax = Math.max(Number(finalPol.width) || 0, Number(finalPol.height) || 0);+ let passLabel;+ if (Array.isArray(s.output_dims) && finalMax) {+ const shotMax = Math.max(Number(s.output_dims[0]) || 0, Number(s.output_dims[1]) || 0);+ passLabel = shotMax >= finalMax ? 'Delivery' : 'Draft';+ } else {+ // No measured size yet (an older clip from before this fix) — fall+ // back to which file this card is actually showing.+ passLabel = s.final_output ? 'Delivery' : 'Draft';+ }const seedSet = (s.seed != null && s.seed !== -1);// ANCHOR STILL. The image the shot starts from, when the board anchors// shots; a failed still says so and the shot renders unanchored.const stillPending = !s.still && !s.still_error && s.still_job_id && s.still_job_id !== 'skipped';+ // FILM-11: a user-uploaded still (a music-video cast photo) is never+ // regenerated — "New still" on it would silently delete the user's own+ // picture. The button becomes an honest "Re-render" that keeps the photo+ // and just renders a fresh take (new seed) from it.+ const userStill = s.still_source === 'user';+ // FILM-46: "Stills first" holds the render at the still until the user+ // approves it — this is the approve/decline UI for that pause. Never+ // shown for a user photo: there is nothing generated to approve.+ const awaitingApproval = !!((r.board || {}).stills_first) && !userStill+ && !s.still_approved;const stillBlock = s.still ? `- <div class="sb-still" title="The still this shot starts from">+ <div class="sb-still${awaitingApproval ? ' sb-still-awaiting' : ''}" title="${userStill ? 'The photo this shot starts from' : 'The still this shot starts from'}"><a href="/image?path=${encodeURIComponent(s.still)}" target="_blank" rel="noopener" title="Open the still"><img src="/image?w=480&path=${encodeURIComponent(s.still)}" alt="Anchor still for shot ${n}" loading="lazy"></a>- <span class="sb-still-tag">starts from this still</span>- <button type="button" class="sb-err-fix sb-still-redo" data-act="restill" title="Make a new still and render this shot from it">New still</button>+ <span class="sb-still-tag">${awaitingApproval ? 'approve this still before it renders' : userStill ? 'starts from your photo' : 'starts from this still'}</span>+ ${awaitingApproval ? `+ <button type="button" class="sb-err-fix sb-still-approve" data-act="approve-still" title="Render the video from this still">Approve</button>` : ''}+ <button type="button" class="sb-err-fix sb-still-redo" data-act="restill"+ title="${userStill ? 'Render a new take from this photo (new seed) — your photo is kept' : 'Make a new still and render this shot from it'}">${userStill ? 'Re-render (new seed)' : 'New still'}</button></div>` : stillPending ? `<div class="sb-still is-pending"><span class="sb-still-spin" aria-hidden="true"></span><span class="sb-still-tag">making the still…</span></div>`- : (s.still_error ? `<div class="sb-still sb-still-failed" title="${escapeHtml(s.still_error)}"><span class="sb-still-tag">no still — rendered unanchored</span>- <button type="button" class="sb-err-fix sb-still-redo" data-act="restill" title="Try the still again">Try again</button></div>` : '');+ : (s.still_error ? `<div class="sb-still sb-still-failed" title="${escapeHtml(s.still_error)}"><span class="sb-still-tag">${awaitingApproval ? 'the still could not be made — held until you choose' : 'no still — rendered unanchored'}</span>+ <button type="button" class="sb-err-fix sb-still-redo" data-act="restill" title="Try the still again">Try again</button>${awaitingApproval ? `+ <button type="button" class="sb-err-fix sb-still-approve" data-act="approve-still" title="Render the video without a still to start from">Render without a still</button>` : ''}</div>` : '');const outBlock = stale ? `<div class="sb-shot-out car-card is-stale"><div class="car-thumb-wrap" onclick="selectOutput('${escapeHtml(stale)}')">@@ -1389,7 +1647,8 @@ function sbShotCard(s, r, errs) {<span class="sub">${s.final_output ? 'delivery' : 'draft'}</span></div><div class="sb-grade" role="group" aria-label="Grade shot ${n}"><button type="button" class="sb-grade-btn ${s.grade === 'keep' ? 'active' : ''}" data-act="grade" data-g="keep" aria-pressed="${s.grade === 'keep'}">KEEP</button>- <button type="button" class="sb-grade-btn ${s.grade === 'reroll' ? 'active' : ''}" data-act="grade" data-g="reroll" aria-pressed="${s.grade === 'reroll'}">RE-ROLL</button>+ <button type="button" class="sb-grade-btn ${s.grade === 'reroll' ? 'active' : ''}" data-act="grade" data-g="reroll" aria-pressed="${s.grade === 'reroll'}"+ ${singingLocked ? 'disabled title="Locked to the song — Rewrite would drop its audio and its place in the song."' : ''}>RE-ROLL</button><button type="button" class="sb-grade-btn ${s.grade === 'cut' ? 'active' : ''}" data-act="grade" data-g="cut" aria-pressed="${s.grade === 'cut'}">CUT</button></div><textarea class="sb-note" rows="2" data-act="note" ${s.grade === 'reroll' ? '' : 'hidden'}@@ -1397,39 +1656,49 @@ function sbShotCard(s, r, errs) {</div>` : '';const failBlock = (s.status === 'failed') ? (() => {- const fe = friendlyJobError(s.error || '');+ const fe = friendlyJobError(s.error || '', s.engine);return `<div class="sb-shot-err"><div class="sb-err-row"><span class="sb-err-dot"></span><span><b>Shot ${n} failed.</b> ${escapeHtml(fe.friendly)} — ${escapeHtml(fe.hint)}</span><button type="button" class="sb-err-fix" data-act="retry">Retry this shot</button><button type="button" class="sb-err-fix" data-act="cut">Cut it</button></div></div>`;})() : '';+ const singingChip = singingLocked+ ? `<span class="sb-chip sb-chip-singing" title="Singing shots are locked to the song — mode, length and order can't change here.">+ Singing${mv.section ? ' · ' + escapeHtml(mv.section) : ''} · ${sbFmtClock(mv.film_start || 0)}+ </span>` : '';+return `<li class="sb-shot ${mine.length ? 'has-error' : ''} ${locked ? 'is-locked' : ''}"- data-n="${n}" draggable="${locked ? 'false' : 'true'}" tabindex="0">+ data-n="${n}" draggable="${locked || singingLocked ? 'false' : 'true'}" tabindex="0"><div class="sb-shot-head"><span class="sb-shot-n">${String(n).padStart(2, '0')}</span>+ ${singingLocked ? singingChip : `<div class="sb-seg" role="group" aria-label="Shot type"><button type="button" class="sb-seg-btn ${isChar ? '' : 'active'}" data-act="mode" data-mode="text" ${locked ? 'disabled' : ''}>Text</button><button type="button" class="sb-seg-btn ${isChar ? 'active' : ''}" data-act="mode" data-mode="character"${locked || noCast ? 'disabled' : ''} ${noCast ? 'title="No trained characters on this Mac yet — train one in the Train tab."' : ''}>Character</button>- </div>+ </div>`}<select class="sb-select sb-shot-char" data-act="char" aria-label="Who's in this shot" ${locked ? 'disabled' : ''} ${noCast ? 'hidden' : ''}>${opts}</select>- <select class="sb-select sb-shot-dur" data-act="dur" aria-label="Length" ${locked ? 'disabled' : ''}>${durOpts}</select>+ <select class="sb-select sb-shot-dur" data-act="dur" aria-label="Length" ${locked || singingLocked ? 'disabled' : ''} ${singingLocked ? 'title="Locked to the song — its length is the words it sings."' : ''}>${durOpts}</select>${sbEngineChip(engine)}${isChar && /<d>\s*(?!<\/\s*d\s*>)\S/i.test(s.prompt || '')? `<span class="sb-chip sb-chip-voice" title="This shot has spoken lines, so the character's voice loads.">voice</span>`: ''}- <span class="sb-chip sb-chip-pass" data-act="pass" title="Quality is set for the whole film — click to change it">${passLabel}</span>+ <span class="sb-chip sb-chip-pass" data-act="pass" title="${Array.isArray(s.output_dims) ? `Rendered at ${s.output_dims[0]}×${s.output_dims[1]} — ` : ''}Quality is set for the whole film — click to change it">${passLabel}</span><span class="sb-shot-est">${sbShotEst(est)}</span><span class="sb-shot-spacer"></span><span class="sb-seedwrap" hidden><input type="number" class="sb-seed" data-act="seed" value="${seedSet ? s.seed : ''}"aria-label="Seed for shot ${n}" ${locked ? 'disabled' : ''}></span>- <button type="button" class="sb-icon" data-act="up" title="Move up" aria-label="Move shot ${n} up" ${n === 1 || locked ? 'disabled' : ''}>↑</button>- <button type="button" class="sb-icon" data-act="down" title="Move down" aria-label="Move shot ${n} down" ${n === shots.length || locked ? 'disabled' : ''}>↓</button>+ <button type="button" class="sb-icon" data-act="up" title="${singingLocked ? "Locked to the song — reordering it would move its mouth off the words." : 'Move up'}" aria-label="Move shot ${n} up" ${n === 1 || locked || singingLocked ? 'disabled' : ''}>↑</button>+ <button type="button" class="sb-icon" data-act="down" title="${singingLocked ? "Locked to the song — reordering it would move its mouth off the words." : 'Move down'}" aria-label="Move shot ${n} down" ${n === shots.length || locked || singingLocked ? 'disabled' : ''}>↓</button><button type="button" class="sb-icon ${seedSet ? 'is-set' : ''}" data-act="seedtoggle"title="${seedSet ? `Seed ${s.seed} — same number, same roll of the dice. Fix it so the delivery render matches the draft you approved.` : 'Seed — same number, same roll of the dice. Fix it so the delivery render matches the draft you approved.'}"aria-label="Seed for shot ${n}">🎲</button>+ ${s.status === 'done' ? `+ <button type="button" class="sb-icon" data-act="newtake"+ title="Edit & re-render — unlocks the prompt and renders a new take with a fresh seed. The old clip is kept, not deleted. No planner call, so it works even while other shots are queued."+ aria-label="New take of shot ${n}">↻</button>` : ''}<button type="button" class="sb-icon sb-icon-danger" data-act="del" title="${locked ? "This one's already rendering." : 'Delete this shot'}" aria-label="Delete shot ${n}" ${locked && s.status !== 'done' ? 'disabled' : ''}>✕</button><span class="sb-grip" title="Drag to reorder" aria-hidden="true">⠿</span></div>@@ -1467,6 +1736,33 @@ function sbRenderTally(shots, r) {fin.textContent = keep ? `Finish ${keep} keeper${keep === 1 ? '' : 's'}` : 'Finish keepers';fin.disabled = !keep;fin.title = keep ? '' : 'Mark at least one shot KEEP first.';+ // FILM-47: "Keep all ungraded" — only offered when there is something it+ // would actually do (a rendered, un-skipped shot with no grade yet).+ const keepAllBtn = sbEl('sbKeepAllBtn');+ if (keepAllBtn) {+ const ungradedWithClip = shots.filter(s => (s.draft_output || s.final_output)+ && s.status !== 'skipped' && !s.grade).length;+ keepAllBtn.hidden = !ungradedWithClip;+ keepAllBtn.textContent = `Keep all ungraded (${ungradedWithClip})`;+ }+ // FILM-47: a finished export/timeline mixes whatever resolution each+ // shot's own clip happens to be at — a shot delivered at the Delivery+ // canvas next to one still sitting at Draft size, silently. Flag it+ // before Finish rather than after the film is cut.+ const mixWarn = sbEl('sbMixedResWarn');+ if (mixWarn) {+ const withClip = shots.filter(s => s.draft_output || s.final_output);+ const sizes = new Set(withClip+ .filter(s => Array.isArray(s.output_dims))+ .map(s => s.output_dims.join('x')));+ if (sizes.size > 1) {+ mixWarn.hidden = false;+ mixWarn.textContent = `This film mixes ${sizes.size} clip sizes (${[...sizes].join(', ')}) — `+ + 'some shots are still at draft size. Finish keepers (or KEEP them) before rendering the film.';+ } else {+ mixWarn.hidden = true;+ }+ }const canExport = shots.some(s => s.final_output);sbEl('sbExportBtn').hidden = !canExport;sbEl('sbExportNote').hidden = !canExport;@@ -1508,20 +1804,53 @@ function sbRenderRunBar(r) {: `${done} of ${shots.length} done`);let sub = '';if (active) sub = (tag.still ? 'making the still · ' : '') + `S${String(active.n).padStart(2, '0')} · ${snippet(active.prompt, 40)}`;- // The remaining time is a SERVER number. /status.eta_sec is the sum of- // per-job ETAs and is trustworthy when every queued job is this film's.+ // FILM-49: "Time left" used to count only the CURRENT BATCH. The film+ // dispatcher submits one bucket at a time (_sb_render_thread: "Submit+ // the film ONE BUCKET AT A TIME"), so /status.eta_sec — the sum of+ // per-job ETAs for what is queued RIGHT NOW — only ever covers that one+ // bucket. `allMine` is true for nearly the whole render (nothing else+ // typically shares the queue with a film), so the shallow bucket total+ // was what actually displayed: "12m left" with hours still to go once+ // the ~19-min singing shots in later buckets were counted.+ //+ // The number now combines BOTH sources: the server's own eta_sec for+ // whatever is genuinely queued (accurate wall-clock — a job's OWN+ // remaining_sec extrapolation lives inside it) plus the film's own+ // per-shot estimate for every shot that has not been queued AT ALL yet,+ // from the same cost model the summary cell prices the film with.+ //+ // 4.17 Codex EST-6: three separate sums, each only of THIS film's work —+ // the shot rendering now (its own remaining_sec), this film's queued rows+ // (each row's own eta_sec, which /status stamps per job), and the shots+ // not queued at all yet. The old version dropped the current shot+ // entirely and used the WHOLE queue's total only while every queued job+ // was this film's — one unrelated job queued made the film's queued work+ // vanish from its own estimate.const q = (LAST_STATUS && LAST_STATUS.queue) || [];- const allMine = q.length && q.every(j => { const t = _sbTagOf(j); return t && t.id === SB.id; });- if (allMine && LAST_STATUS.eta_sec) sub += ` · ${sbFmtWall(LAST_STATUS.eta_sec)} left`;- else {- // THE FILM'S OWN NUMBER when the queue's is not ours to read: the sum- // of the per-shot estimates for what this pass has not landed yet,- // from the same cost model the summary cell prices the film with.- const per = r.per_shot_est || {};- const left = shots.filter(s => !s[outKey] && s.status !== 'skipped')- .reduce((a, s) => a + (Number(per[String(s.n)]) || 0), 0);- if (left > 0) sub += ` · ${sbFmtWall(left)} left`;+ const per = r.per_shot_est || {};+ const shotEst = t => (t && !t.still) ? (Number(per[String(t.n)]) || 0) : 0;+ const accounted = new Set();+ let queuedPortion = 0;+ q.forEach(j => {+ const t = _sbTagOf(j);+ if (!t || t.id !== SB.id) return;+ if (!t.still) accounted.add(t.n); // a still ahead of its shot is not the shot+ const eta = Number(j.eta_sec);+ queuedPortion += (Number.isFinite(eta) && eta >= 0) ? eta : shotEst(t);+ });+ const curTag = cur ? _sbTagOf(cur) : null;+ let currentPortion = 0;+ if (curTag && curTag.id === SB.id) {+ if (!curTag.still) accounted.add(curTag.n);+ const rem = Number(((cur || {}).progress || {}).remaining_sec);+ currentPortion = (((cur || {}).progress || {}).remaining_sec != null && Number.isFinite(rem))+ ? Math.max(0, rem) : shotEst(curTag);}+ const notYetQueued = shots+ .filter(s => !s[outKey] && s.status !== 'skipped' && !accounted.has(s.n))+ .reduce((a, s) => a + (Number(per[String(s.n)]) || 0), 0);+ const left = currentPortion + queuedPortion + notYetQueued;+ if (left > 0) sub += ` · ${sbFmtWall(left)} left`;sbEl('sbRunSub').textContent = sub;sbEl('sbPauseBtn').textContent = paused ? 'Resume' : 'Pause';sbEl('sbRunDots').innerHTML = shots.map(s => {@@ -1551,6 +1880,48 @@ function sbScrollToShot(n) {const el = document.querySelector(`.sb-shot[data-n="${n}"]`);if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });}+// FILM-41: "Player" used to just reveal the shared stage pane, which still+// held whatever the Video tab had last selected — a board with nothing+// rendered showed an unrelated clip, and a rendered board showed one+// arbitrary shot, never the film in order. This plays THIS board's own+// shots, oldest to last, as one ordered playlist; each clip's `ended` event+// advances to the next. The shared player element is rebuilt from scratch+// by selectOutput() on every call, so the listener is re-attached each time+// rather than assumed to survive.+function sbPlaylistPaths() {+ const shots = (((SB.payload || {}).board) || {}).shots || [];+ return shots.filter(s => s.status !== 'skipped')+ .slice().sort((a, b) => (a.n || 0) - (b.n || 0))+ .map(s => s.final_output || s.draft_output)+ .filter(Boolean);+}+function sbPlayBoard() {+ const paths = sbPlaylistPaths();+ if (!paths.length) {+ if (typeof phosToast === 'function') phosToast('Nothing on this board has rendered yet.');+ return;+ }+ SB.playlist = { paths, idx: 0, boardId: SB.id };+ sbSetStage('player');+ sbPlaylistPlay(0);+}+function sbPlaylistPlay(idx) {+ const pl = SB.playlist;+ if (!pl || idx >= pl.paths.length) { SB.playlist = null; return; }+ pl.idx = idx;+ if (typeof selectOutput === 'function') selectOutput(pl.paths[idx], { autoplay: true });+ const v = document.querySelector('#playerWrap video');+ if (v) {+ v.addEventListener('ended', () => {+ // The user may have clicked away to a different clip (or a different+ // board) while this one played — only advance if this playlist is+ // still the thing actually on screen.+ if (SB.playlist !== pl || SB.id !== pl.boardId || activePath !== pl.paths[pl.idx]) return;+ sbPlaylistPlay(pl.idx + 1);+ }, { once: true });+ }+}+function sbOpenShotClip(n) {const s = (((SB.payload || {}).board) || {}).shots.find(x => x.n === n);const clip = s && (s.final_output || s.draft_output);@@ -1605,12 +1976,14 @@ async function sbFlushSave() {const board = ((SB.payload || {}).board);if (!board) return;SB.saveInFlight = true;+ const bid = SB.id;try {const r = await (await fetch('/storyboard/save', {method: 'POST', headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ id: SB.id, board: board }),+ body: JSON.stringify({ id: bid, board: board }),})).json();- if (r && r.ok) {+ // BOARD-2: a reply for a board that is no longer open never repaints.+ if (r && r.ok && bid === SB.id) {SB.payload = r;if (sbAdoptLiveEdits(r)) SB.saveAgain = true;sbRenderPlan(r);@@ -1699,6 +2072,8 @@ function sbShotAction(n, act, el, ev) {case 'note': s.note = el.value; sbGrade(n, s.grade, el.value); return;case 'retry': sbRenderPass(SB.payload.pass || 'draft', [n]); return;case 'restill': sbRestill(n); return;+ case 'newtake': sbNewTake(n); return;+ case 'approve-still': sbApproveStill(n); return;case 'cut': sbGrade(n, 'cut', s.note || ''); return;default: return;}@@ -1740,13 +2115,21 @@ function sbTitleSave() {}async function sbGrade(n, grade, note) {+ const bid = SB.id;const fd = new URLSearchParams();- fd.set('id', SB.id); fd.set('n', String(n));+ fd.set('id', bid); fd.set('n', String(n));+ // BOARD-2: the shot's identity rides along, so the server refuses a grade+ // aimed at a shot number that now belongs to a different shot.+ let shot = null;+ try { shot = sbShotById(n); } catch (e) {}+ if (shot && shot.uid) fd.set('uid', shot.uid);if (grade) fd.set('grade', grade);fd.set('note', note || '');try {const r = await (await fetch('/storyboard/grade', { method: 'POST', body: fd })).json();+ if (bid !== SB.id) return;if (r && r.ok) { SB.payload = r; sbRenderPlan(r); }+ else if (r && r.error) phosToast(r.error, { kind: 'warning' });} catch (e) {}}@@ -1838,15 +2221,37 @@ async function sbFinish() {catch (e) {}const pol = (((SB.payload || {}).board) || {}).policy || {};const f = pol.final || {};+ // FILM-47: "you get the take you approved — bigger" was never true — the+ // same seed and prompt at a different pipeline/canvas gives a DIFFERENT+ // clip on these engines, not the approved one scaled up. Said honestly.if (!confirm(`Finish ${keep.length} shot${keep.length === 1 ? '' : 's'}?\n\n` +`Delivery pass, ${f.width}×${f.height}, ${(f.quality || '').replace(/^./, c => c.toUpperCase())}. ` +`${sbFmtWall(est.total_secs).replace(/^about /, 'About ')} on this Mac.\n` +- "Each shot re-renders at its draft's seed, so you get the take you approved — bigger.\n" ++ 'Each shot renders a NEW take at delivery size — same prompt, same seed, ' ++ 'but not pixel-identical to the draft you approved.\n' +'The drafts stay in your gallery.')) return;sbRenderPass('final', keep);}+// FILM-47: a 52-shot board needed 52 individual KEEP presses before Finish+// could do anything — this is the one-click version for "everything I+// haven't graded is fine, keep it". One request, one save server-side —+// N separate grade calls would each load-mutate-save the whole board and+// could race each other (the same class of bug as FILM-19/20).+async function sbKeepAllUngraded() {+ const bid = SB.id;+ const fd = new URLSearchParams(); fd.set('id', bid);+ let r;+ try { r = await (await fetch('/storyboard/keep-all-ungraded', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ // BOARD-2: board A's reply must not paint A's shots under board B's id —+ // the next grade would then change B's shot with A's number.+ if (bid !== SB.id) return;+ if (!r.ok) { phosToast(r.error || 'Could not keep those shots.', { kind: 'danger', duration: 6000 }); return; }+ if (r.kept) { SB.payload = r; sbRenderPlan(r); phosToast(`Kept ${r.kept} ungraded shot${r.kept === 1 ? '' : 's'}.`, { kind: 'success' }); }+}+async function sbRewrite() {const shots = (((SB.payload || {}).board) || {}).shots || [];const ns = shots.filter(s => s.grade === 'reroll').map(s => s.n);@@ -1888,9 +2293,18 @@ async function sbExport() {btn.dataset.busy = '1';btn.disabled = true;btn.textContent = 'Assembling…';- const fd = new URLSearchParams(); fd.set('id', SB.id);+ // FILM-48: Export posted only `id` — with no edit.json yet (the Editor+ // was never opened), the server had no song to lay under the film and+ // silently concatenated each clip's OWN audio instead. A music-video+ // board already has a dedicated route that knows where its song is+ // (/music/video/film, same _sb_export underneath, music_mode=replace)+ // — route there instead of guessing the song path here.+ const isMusicVideo = !!sbMusicVideoBlock();+ const url = isMusicVideo ? '/music/video/film' : '/storyboard/export';+ const fd = new URLSearchParams();+ fd.set(isMusicVideo ? 'board_id' : 'id', SB.id);let r;- try { r = await (await fetch('/storyboard/export', { method: 'POST', body: fd })).json(); }+ try { r = await (await fetch(url, { method: 'POST', body: fd })).json(); }catch (e) { r = { ok: false, error: String(e) }; }finally { btn.dataset.busy = ''; btn.disabled = false; btn.textContent = prev; }if (!r.ok) { phosToast(r.error || 'Export failed.', { kind: 'danger' }); return; }@@ -2002,9 +2416,14 @@ function sbFilmPaint() {<div class="sb-empty-icon"><svg width="56" height="56" viewBox="0 0 256 256" aria-hidden="true"><use href="#ph-film-slate"/></svg></div><div class="sb-empty-title">No film yet.</div><div class="sb-empty-sub">${clips- ? 'Arrange the ' + clips + ' clip' + (clips === 1 ? '' : 's') + ' you have on the timeline and render. The finished film lands in <code>' + escapeHtml(SB.filmShort || 'mlx_outputs/storyboards/') + '</code> and appears here.'+ // FILM-42: this used to say "the N clips you have ON THE+ // TIMELINE" — a claim about the Editor's arrangement this+ // screen has no way to check (it only knows how many shots+ // RENDERED). Said honestly: how many are ready to arrange, not+ // how many already are.+ ? clips + ' shot' + (clips === 1 ? ' has' : 's have') + ' rendered. Open the timeline, arrange them and render the film. The finished film lands in <code>' + escapeHtml(SB.filmShort || 'mlx_outputs/storyboards/') + '</code> and appears here.': 'Render some shots first — a film is the shots, joined. Nothing to arrange yet.'}</div>- ${clips ? '<div class="sb-film-actions"><button type="button" class="primary" onclick="sbGo(\'arrange\')">Open the timeline</button></div>' : ''}+ ${clips ? '<div class="sb-film-actions"><button type="button" class="primary" onclick="sbGo(\'edit\')">Open the timeline</button></div>' : ''}</div>`;return;}@@ -2097,23 +2516,147 @@ function sbRowAction(b) {}return '';}-function sbRenderBoardLists() {- const rows = SB.boards.map(b => `+// FILM-43: filters the FULL board list (search box above it) client-side —+// there are never more than a few dozen boards, and a round-trip for this+// would just be latency with no benefit.+let _sbBoardFilter = '';+function sbFilterBoardList(q) {+ _sbBoardFilter = String(q || '').trim().toLowerCase();+ sbRenderBoardLists();+}+// 4.17: DELETE LIVES BEHIND ⋯. A bare × sat at the end of every board row —+// in the rail too, where the rows are 230 px wide — one slip away from+// deleting a plan. It is now a menu item (the shared .kebab-wrap/.kebab-pop+// component the LoRA rows and the clip toolbar use), and the confirm is the+// panel's own dialog, not the browser's.+function sbBoardRowMenu(b, where) {+ const kid = 'sbk-' + where + '-' + String(b.id).replace(/[^A-Za-z0-9_-]/g, '_');+ const idAttr = escapeHtml(JSON.stringify(String(b.id)));+ const titleAttr = escapeHtml(JSON.stringify(String(b.title || '')));+ return `<div class="kebab-wrap sb-board-menu" onclick="event.stopPropagation()">+ <button type="button" title="More" aria-haspopup="true" aria-label="More actions for this film"+ onclick="kebabToggle('${kid}')">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <circle cx="3" cy="8" r="1.4" fill="currentColor"/><circle cx="8" cy="8" r="1.4" fill="currentColor"/><circle cx="13" cy="8" r="1.4" fill="currentColor"/>+ </svg>+ </button>+ <div class="kebab-pop" id="${kid}" role="menu">+ <button type="button" role="menuitem" class="danger"+ onclick="kebabToggle('${kid}', false); sbDeleteBoard(${idAttr}, ${titleAttr})">Delete this storyboard…</button>+ </div>+ </div>`;+}+// The FULL board-list screen's row: thumbnail, date, rename, duplicate.+function sbBoardRow(b) {+ const thumb = b.thumb+ ? `<video class="sb-board-thumb" preload="metadata" muted playsinline src="/file?path=${encodeURIComponent(b.thumb)}"></video>`+ : `<span class="sb-board-thumb sb-board-thumb-empty" aria-hidden="true"></span>`;+ const when = sbFmtAgo(b.updated_at || b.created_at);+ return `+ <li data-id="${escapeHtml(b.id)}" class="${b.running || b.planning ? 'is-live' : ''}"+ onclick="sbOpen('${escapeHtml(b.id)}')">+ ${thumb}+ <span class="ttl" data-role="title">${escapeHtml(b.title || 'Untitled film')}</span>+ <span class="params">${b.shots} shots · ${b.done} rendered${when ? ' · ' + escapeHtml(when) : ''}</span>+ <span class="badge">${escapeHtml(sbBoardChip(b))}</span>+ ${sbRowAction(b)}+ <button title="Rename" onclick="event.stopPropagation();sbRenameBoardStart(this)"><svg class="ph" aria-hidden="true"><use href="#ph-pencil-simple"/></svg></button>+ <button title="Duplicate this storyboard" onclick="event.stopPropagation();sbDuplicateBoard('${escapeHtml(b.id)}')"><svg class="ph" aria-hidden="true"><use href="#ph-copy"/></svg></button>+ ${sbBoardRowMenu(b, 'full')}+ </li>`;+}+// The rail's quick-switch copy — deliberately unchanged: ~230px has no room+// for a thumbnail or three action buttons, and it is a jump list, not the+// place search/rename/duplicate belong.+function sbBoardRowMini(b) {+ return `<li data-id="${escapeHtml(b.id)}" class="${b.running || b.planning ? 'is-live' : ''}"onclick="sbOpen('${escapeHtml(b.id)}')"><span class="ttl">${escapeHtml(b.title || 'Untitled film')}</span><span class="params">${b.shots} shots · ${b.done} rendered</span><span class="badge">${escapeHtml(sbBoardChip(b))}</span>${sbRowAction(b)}- <button title="Delete this storyboard" onclick="event.stopPropagation();sbDeleteBoard('${escapeHtml(b.id)}','${escapeHtml((b.title || '').replace(/'/g, ''))}')"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button>- </li>`).join('');+ ${sbBoardRowMenu(b, 'mini')}+ </li>`;+}+function sbRenderBoardLists() {+ const boards = _sbBoardFilter+ ? SB.boards.filter(b => (b.title || 'Untitled film').toLowerCase().includes(_sbBoardFilter))+ : SB.boards;const full = sbEl('sbBoardList');- if (full) full.innerHTML = rows || '<li class="empty-state"><span></span><span>No storyboards yet</span><span></span><span></span></li>';+ if (full) {+ full.innerHTML = boards.map(sbBoardRow).join('') || (_sbBoardFilter+ ? '<li class="empty-state"><span></span><span>No film matches that search</span><span></span><span></span></li>'+ : '<li class="empty-state"><span></span><span>No storyboards yet</span><span></span><span></span></li>');+ }const mini = sbEl('sbBoardListMini');- if (mini) mini.innerHTML = rows;+ // The rail's mini list never filters — it's a quick-switch, not a search+ // result — so it always shows every board regardless of the box above.+ if (mini) mini.innerHTML = SB.boards.map(sbBoardRowMini).join('');+}+// Turns a row's title into an inline text input; Enter/blur saves through+// the ordinary board-save route (title is one of the fields it already+// accepts), Escape cancels. No native prompt() — the panel's own idiom.+function sbRenameBoardStart(btn) {+ const li = btn.closest('li');+ if (!li) return;+ const id = li.dataset.id;+ const ttl = li.querySelector('[data-role="title"]');+ if (!ttl || ttl.querySelector('input')) return;+ const current = ttl.textContent;+ const input = document.createElement('input');+ input.type = 'text'; input.value = current; input.className = 'sb-board-rename';+ input.addEventListener('click', (e) => e.stopPropagation());+ const commit = () => {+ const next = input.value.trim();+ ttl.textContent = next || current;+ if (next && next !== current) sbRenameBoard(id, next);+ };+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); input.blur(); }+ else if (e.key === 'Escape') { ttl.textContent = current; input.remove(); }+ });+ input.addEventListener('blur', commit, { once: true });+ ttl.textContent = '';+ ttl.appendChild(input);+ input.focus(); input.select();}-async function sbDeleteBoard(id, title) {- if (!confirm(`Delete "${title || 'this storyboard'}"?\n\nDeletes the plan. The clips it already rendered stay in mlx_outputs/.`)) return;+async function sbRenameBoard(id, title) {+ let r;+ try {+ r = await (await fetch('/storyboard/save', {+ method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ id, board: { id, title } }),+ })).json();+ } catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) { phosToast(r.error || 'Could not rename that film.', { kind: 'danger' }); return; }+ if (SB.id === id && SB.payload) { SB.payload.board.title = title; sbRenderPlan(SB.payload); }+ sbRefreshBoards();+}+async function sbDuplicateBoard(id) {+ const fd = new URLSearchParams(); fd.set('id', id);+ let r;+ try { r = await (await fetch('/storyboard/duplicate', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) { phosToast(r.error || 'Could not duplicate that film.', { kind: 'danger' }); return; }+ phosToast(`Duplicated as "${r.title}".`, { kind: 'success' });+ await sbRefreshBoards();+}+function sbDeleteBoard(id, title) {+ const body = 'Deletes the plan. The clips it already rendered stay in your outputs.';+ const go = () => { sbDeleteBoardNow(id); };+ if (typeof _phModalShow === 'function' && _phModalShow({+ tone: 'danger', kicker: 'Delete storyboard',+ title: `Delete "${title || 'this storyboard'}"?`, body,+ primaryLabel: 'Delete', onPrimary: go,+ secondaryLabel: 'Keep it' })) {+ return;+ }+ // The panel's dialog is busy with something else (one at a time) — the+ // browser's confirm is the fallback, never "no confirm at all".+ if (confirm(`Delete "${title || 'this storyboard'}"?\n\n${body}`)) go();+}+async function sbDeleteBoardNow(id) {const fd = new URLSearchParams(); fd.set('id', id);const r = await (await fetch('/storyboard/delete', { method: 'POST', body: fd })).json();if (!r.ok) { phosToast(r.error || 'Could not delete.', { kind: 'danger' }); return; }@@ -2123,17 +2666,40 @@ async function sbDeleteBoard(id, title) {}// ---- shared state: pull a normal generation INTO a film ---------------------+// FILM-26: the select used to open already showing its FIRST real film+// selected — so a user who wanted exactly that film clicked it, nothing+// fired (`onchange` never fires when the value does not change), and the+// button looked broken. A leading placeholder option means every real+// choice is a CHANGE, so onchange always fires; `showPicker()` also opens+// the native list immediately instead of leaving a revealed-but-closed+// 20px control the user has to find and click a second time.async function sbAddActiveToBoard(chosen) {if (!activePath) return;const sel = sbEl('sbAddSelect');if (!chosen && SB.boards.length > 1 && sel && sel.style.display === 'none') {- sel.innerHTML = SB.boards.map(b =>- `<option value="${escapeHtml(b.id)}">${escapeHtml(b.title || 'Untitled film')}</option>`).join('')- + '<option value="new">— new storyboard —</option>';+ // Last-used first: the film you were just cutting is the one you most+ // likely mean to add this clip to.+ let last = '';+ try { last = localStorage.getItem('phos_sb_open') || ''; } catch (e) {}+ const boards = last ? SB.boards.slice().sort(+ (a, b) => (b.id === last) - (a.id === last)) : SB.boards;+ sel.innerHTML = '<option value="" disabled selected>Add to which film?</option>'+ + boards.map(b =>+ `<option value="${escapeHtml(b.id)}">${escapeHtml(b.title || 'Untitled film')}</option>`).join('')+ + '<option value="new">— new film —</option>';sel.style.display = '';+ if (typeof sel.showPicker === 'function') { try { sel.showPicker(); } catch (e) {} }+ else { try { sel.focus(); } catch (e) {} }return;}- const id = chosen || (SB.boards.length === 1 ? SB.boards[0].id : (SB.boards[0] || {}).id) || 'new';+ if (!chosen && SB.boards.length <= 1) {+ // Nothing to choose between — the old fallback silently picked+ // SB.boards[0] even when `chosen` was empty and boards.length was 0,+ // which sent id="" straight to add-shot as if a real film existed.+ chosen = (SB.boards[0] || {}).id || 'new';+ }+ if (!chosen) return; // the placeholder option, or a stray call+ const id = chosen;if (sel) sel.style.display = 'none';const fd = new URLSearchParams();fd.set('id', id); fd.set('path', activePath);@@ -2360,8 +2926,9 @@ document.addEventListener('dragend', () => {// the global scope; everything NOT listed here is private to this module.Object.assign(globalThis, {sbSetTake,- sbToggleSwitchHelp, sbSyncBriefGates, sbRestill,- sbTrackInput,+ sbToggleSwitchHelp, sbSyncBriefGates, sbRestill, sbNewTake, sbStillsFirstSync,+ sbApproveAllStills, sbKeepAllUngraded,+ sbTrackInput, sbGoToMusicVideo,sbEl, sbFmtClock, sbFmtBytes, sbFmtAgo,sbFilmKind, sbFilmPick, sbRenderFinalQualities, sbInit,sbTeardown, sbConceptInput, sbMustInput, sbLocInput,@@ -2370,7 +2937,7 @@ Object.assign(globalThis, {sbReplan, sbTryAgain, sbShowRaw, sbOpen,sbOpenAt, sbBackToList, sbRailModel, sbRailPaint,sbGo, sbLoad, sbShow, sbSyncStage,- sbSetStage, sbRenderPlan, sbRenderRemaining, sbAddShot,+ sbSetStage, sbPlayBoard, sbSetShotView, sbGridTileOpen, sbRenderPlan, sbRenderRemaining, sbAddShot,sbTitleSave, sbRenderDrafts, sbFinish, sbRewrite,sbStopShot, sbStopFilm, sbExport, sbFilmOpen,sbMusicVideoBlock, sbFilmWithTheSong,@@ -2380,4 +2947,5 @@ Object.assign(globalThis, {// global scope (the v4.9.0 regression, PR #69)sbDeleteBoard, sbFilmReveal, sbFilmSelect, sbFixError,sbOpenShotClip, sbPickCast, sbScrollToShot,+ sbFilterBoardList, sbRenameBoardStart, sbDuplicateBoard,});diff --git a/webapp/style/panel.css b/webapp/style/panel.cssindex 9ec925d..36999f9 100644--- a/webapp/style/panel.css+++ b/webapp/style/panel.css@@ -28,7 +28,17 @@which is why rows in the rail and the drafts panel came out a pixeloff each other. Anything new picks a rung; nothing declares its own. */--ctl-h: 32px; --ctl-h-sm: 28px; --ctl-h-lg: 36px;- --fs-2xs: 10px; --fs-xs: 11px; --fs-sm: 12px; --fs-md: 13px;+ /* SYS-24: --fs-2xs was 10px — one rung below the 11px floor an+ accessibility pass set as the minimum for any text carrying+ information (report_system.txt: 36 of 120 visible text nodes were+ under 11px, 18 under 10px, and panel.css itself had 105 literal+ sub-11px font-size declarations, since floored to 11px directly —+ see the sweep below). Raising the token to match --fs-xs, rather+ than hunting the 48 call sites that reference it, keeps the+ five-rung type scale's names intact (nothing renamed --fs-2xs to+ --fs-xs) while guaranteeing every current AND future user of the+ token clears the floor. */+ --fs-2xs: 11px; --fs-xs: 11px; --fs-sm: 12px; --fs-md: 13px;--fs-lg: 15px;--t-fast: 120ms cubic-bezier(.2,.8,.2,1);--t-base: 180ms cubic-bezier(.2,.8,.2,1);@@ -70,9 +80,26 @@html[data-theme="light"] .sbe-ov { color: #4c1d95; }html[data-theme="light"] .sbe-ruler u { color: rgba(20,26,46,0.75); background: rgba(20,26,46,0.10); }html[data-theme="light"] .sbe-track.is-dropping { background: rgba(20,26,46,0.04); }+ html[data-theme="light"] .sbe-track.is-overwriting { background: rgba(180, 95, 6, 0.08); }* { box-sizing: border-box; }html, body { margin: 0; height: 100%; }+ /* [hidden] must always win. Without this, any component rule that sets+ `display` on the same element (.toggle-pill, .loras-browse-btn, and+ whatever comes next) silently outranks the UA's built-in `[hidden] {+ display: none }` — the element's `.hidden` property still reads true,+ but it renders anyway. That shipped a "No voice" pill that stayed on+ screen while wired off (a wasted render) and an "Import" button that+ opened the wrong engine's LoRA importer (VC-07). Fixing this one+ selector, instead of patching every offending component with its own+ `[hidden] { display: none !important }` override (see the many+ examples below — that's the whack-a-mole this replaces), closes the+ whole class: any element hidden via the `hidden` attribute is gone,+ full stop, no matter what other CSS targets it. See+ test_hidden_wins.py for the gate that walks every `[hidden]` element+ at boot and asserts its computed display is none. */+ [hidden] { display: none !important; }+/* Phase 0 a11y floor —(a) Visible focus ring on every interactive element when reachedvia keyboard (mouse-click clears via :focus-visible). Today's@@ -133,7 +160,7 @@background: rgba(240,185,64,0.18);color: var(--warning, #f0b940);border: 1px solid rgba(240,185,64,0.55);- font-size: 10px; font-weight: 700;+ font-size: 11px; font-weight: 700;letter-spacing: 0.12em;cursor: help;}@@ -208,9 +235,11 @@filter: grayscale(0.45) brightness(0.85);animation: pulse 2s ease-in-out infinite;}- .panel-offline-banner .icon img {+ .panel-offline-banner .icon img,+ .panel-offline-banner .icon svg {width: 100%; height: 100%;display: block;+ color: #ffd9d6;}.panel-offline-banner .label {font-weight: 600;@@ -269,6 +298,10 @@text-transform: uppercase; color: #f0b940; margin-bottom: 8px;}#phModalKicker.is-broadcast { color: #5eeaff; }+ /* Destructive confirms (Stop mid-render, etc. — VC-05/VC-35) share this+ dialog with a red kicker/primary instead of a second modal built for+ the occasion. */+ #phModalKicker.is-danger { color: var(--danger, #f85149); }#phModal h2 {margin: 0 0 10px; font-size: 17px; color: var(--ink, #e8eaf0);line-height: 1.35;@@ -286,6 +319,7 @@font-weight: 650; cursor: pointer;}#phModalPrimary.is-broadcast { background: #5eeaff; color: #06222a; }+ #phModalPrimary.is-danger { background: var(--danger, #f85149); color: #2a0a08; }#phModalPrimary:hover { filter: brightness(1.08); }#phModalSecondary {background: transparent; color: var(--ink-500, #98a0b3);@@ -345,6 +379,22 @@font-variant-numeric: tabular-nums;}#healthChip:hover { background: rgba(255,255,255,.07); }+ /* VC-32: at widths just above the 1400px breakpoint below (a real+ laptop width — 1440x900), #healthCluster's own `overflow: hidden`+ (min-width:0; flex-shrink:1, so the cluster shrinks rather than+ wrapping the header) was doing the clipping, mid-character, with no+ ellipsis: ".hc-face" is a flex item and flex items default to+ `min-width: auto`, which refuses to shrink below its own text's+ natural width — so the ANCESTOR's raw pixel clip was the only thing+ that ever fired, "43/64 G" instead of "43/64 GB · 68%" with no sign+ anything was cut. Letting the face itself shrink and ellipsize means+ there's always a visible "…" instead of a silently truncated number,+ at any width, not only below the JS breakpoint. */+ #healthChip { min-width: 0; }+ #healthChip .hc-face {+ min-width: 0; overflow: hidden; text-overflow: ellipsis;+ display: inline-block; max-width: 22ch; vertical-align: bottom;+ }/* Narrow header (Pinokio's window is ~1300px): the chip's full readout("15/64 GB · 23%") was clipped mid-number by the cluster'soverflow:hidden — the compaction rule above still targeted the@@ -353,8 +403,14 @@@media (max-width: 1400px) {#healthChip .hc-face { font-size: 0; }#healthChip .hc-face::after { content: attr(data-short); font-size: 11.5px; }- #versionPill .vp-detail { display: none; }}+ /* SYS-38: the branch + short SHA + commit date ("HEAD · 70665d3+ (2026-09-28)") is developer build detail — useful for self-+ diagnosing a stale dev/beta build, which is exactly why+ renderVersionPill() (health.js) also puts the same SHA in the+ pill's title/tooltip. It doesn't need to sit in the always-visible+ header text at any width; this used to hide it only below 1400px. */+ #versionPill .vp-detail { display: none; }.hc-dot {width: 7px; height: 7px; border-radius: 50%; flex: 0 0 auto;background: #5fbf8f; box-shadow: 0 0 0 3px rgba(95,191,143,.15);@@ -451,13 +507,41 @@this, the Enhance button stretches full-width and forces theNo-music pill to wrap to a second line. Tactile surface (item#13 from the polish audit) — pre-this commit they read as- outlined stickers. */+ outlined stickers.+ display:inline-flex (base, not a per-context patch) — VC-17. A+ plain <button> is UA-default inline-block; inside ANY flex/grid+ ancestor (.composer-tools, .row-actions, header rows, …) the CSS+ Display spec blockifies it, so getComputedStyle reports `block`.+ A block button plus a block icon (`button > .ph { display: block }`+ below) means the icon and the label stack on separate lines instead+ of sitting side by side — measured on #enhanceBtn: a 70x30 box+ with 37px of content spilling out of it. Every ghost-btn that+ happened to sit under `.row-actions`/`.sb-film-actions`/etc. was+ individually patched to `inline-flex` already (grep the rest of+ this file); putting it on the base rule instead covers every+ ghost-btn, including ones inside a flex ancestor nobody has+ patched yet (#enhanceBtn's own parent, .composer-tools, was one). */width: auto;+ display: inline-flex; align-items: center; gap: 6px; white-space: nowrap;background: var(--panel-2);border: 1px solid var(--border); color: var(--text);padding: 5px 10px; border-radius: var(--r-xs); font-size: 11px; cursor: pointer;transition: background var(--t-base), border-color var(--t-base), color var(--t-base);}+ /* SYS-21: same "ghost-btn is display:block, icon lands on its own+ line" issue .sb-film-actions .ghost-btn already works around+ elsewhere in this file — #enhanceBtn never got the fix, so its+ icon+label wrapped to 37px tall inside a 30px button on every width. */+ #enhanceBtn {+ display: inline-flex; align-items: center; gap: 6px;+ }+ /* Engaged state — e.g. the Hidden outputs toggle (VC-04) while it's+ showing the hidden set instead of the regular gallery. */+ .ghost-btn.active {+ background: var(--accent-dim);+ border-color: var(--accent);+ color: var(--accent-bright);+ }.ghost-btn:hover {background: var(--bg-2);border-color: var(--accent);@@ -483,6 +567,15 @@.toggle-pill input[type="checkbox"] {position: absolute; opacity: 0; pointer-events: none; width: 0; height: 0;}+ /* SYS-25: the checkbox above is visually a 0x0 box, so a keyboard Tab+ landed a focus ring on nothing visible — a sighted keyboard user+ (or anyone tabbing through, not just screen-reader users) lost+ track of where focus was. :focus-within puts the ring on the whole+ visible pill instead of the invisible input inside it. */+ .toggle-pill:focus-within {+ outline: 2px solid var(--accent-bright, #7e98ff);+ outline-offset: 2px;+ }.toggle-pill .toggle-dot {width: 8px; height: 8px; border-radius: 50%;background: var(--border-strong); border: 1px solid transparent;@@ -522,7 +615,7 @@box-shadow: 0 0 0 2px var(--accent, #5a7cff), 0 0 0 3px var(--bg, #0d1017);}.creator-link .x-icon {- font-size: 10px; opacity: 0.6; margin-left: -2px;+ font-size: 11px; opacity: 0.6; margin-left: -2px;letter-spacing: 0.05em;}@@ -560,11 +653,20 @@background: rgba(90,124,255,0.07);animation: keyframes-modeldl 1.6s ease-in-out infinite;}+ /* SYS-11: `auto` on the actions column let a long button label+ ("Download LTX-2.5 base (20.74 GB)") claim as much width as it+ needed, squeezing the text column to ~130px and wrapping a two-line+ sentence to nine. The actions column now sits on its own row+ instead of competing with the text for horizontal space. */.models-inline-body {display: grid;- grid-template-columns: 28px 1fr auto;- gap: 12px; align-items: center;+ grid-template-columns: 28px 1fr;+ grid-template-areas: "icon text" "actions actions";+ gap: 8px 12px; align-items: start;}+ .models-inline-icon { grid-area: icon; }+ .models-inline-text { grid-area: text; }+ .models-inline-actions { grid-area: actions; }.models-inline-icon { font-size: 22px; line-height: 1; text-align: center; }.models-inline-text { min-width: 0; }.models-inline-text .ttl { font-weight: 600; font-size: 13px; color: var(--fg, #d8e0ee); }@@ -580,7 +682,7 @@}.models-inline-progress .last {font-family: ui-monospace, SFMono-Regular, Menlo, monospace;- font-size: 10px; color: var(--muted); margin-top: 4px;+ font-size: 11px; color: var(--muted); margin-top: 4px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}.models-inline-actions button {@@ -595,6 +697,44 @@background: transparent; color: var(--muted);border: 1px solid var(--border, #2a3140); font-weight: 500;}+ /* SYS-16: first-run card, same card language as .models-inline+ (border-radius, padding, dismiss ×) so it reads as a sibling. */+ .first-run-card {+ border-radius: 10px; padding: 14px 16px;+ margin-bottom: 14px; position: relative;+ border: 1.5px solid var(--accent, #2f81f7);+ background: rgba(47, 129, 247, 0.06);+ }+ .first-run-card .ttl { font-weight: 600; font-size: 13px; color: var(--fg, #d8e0ee); margin-bottom: 4px; }+ .first-run-card .sub { font-size: 11.5px; color: var(--muted); margin-bottom: 12px; }+ .first-run-dismiss {+ position: absolute; top: 6px; right: 8px;+ width: 22px; height: 22px; border-radius: 4px;+ background: transparent; border: 1px solid transparent;+ color: var(--muted); cursor: pointer; padding: 0;+ display: inline-flex; align-items: center; justify-content: center;+ }+ .first-run-dismiss:hover { color: var(--text); border-color: var(--border); }+ .first-run-dismiss .ph { width: 14px; height: 14px; }+ .first-run-prompts {+ display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px;+ }+ .first-run-prompt-btn {+ /* Chips, not full-width rows: the global button rule (width 100%)+ stacked three 42 px rows here, and at 1366x768 / 1280x800 the card+ pushed the prompt and Generate below the fold on a first run. */+ width: auto; flex: 0 1 auto;+ padding: 7px 12px; border-radius: 999px;+ background: var(--panel-2, #1d2752); border: 1px solid var(--border);+ color: var(--text); font-size: 12px; cursor: pointer;+ transition: border-color 120ms ease, background 120ms ease;+ }+ .first-run-prompt-btn:hover { border-color: var(--accent); background: var(--accent-dim); }+ .first-run-sample-link {+ display: inline-block; font-size: 11.5px;+ color: var(--accent-bright, #58a6ff); text-decoration: underline;+ }+ .first-run-sample-link:visited { color: var(--accent-bright, #58a6ff); }.models-inline-link {display: block; margin-top: 10px;font-size: 11px; color: var(--muted); text-align: right;@@ -877,6 +1017,64 @@#sbStageToggle .smt-btn:hover { color: var(--text); }#sbStageToggle .smt-btn.active { background: var(--accent); color: #fff; }+ /* FILM-41: List/Grid toggle for the shot list, and the grid (contact+ sheet) itself. Same segmented-pill idiom as #sbStageToggle above —+ one rule set, shared look. */+ .sb-shotview-toggle {+ display: inline-flex; gap: 4px; padding: 3px; margin-bottom: 8px;+ background: var(--bg-2); border: 1px solid var(--border);+ border-radius: 10px; width: fit-content;+ }+ .sb-shotview-toggle[hidden] { display: none !important; }+ .sb-shotview-toggle .smt-btn {+ appearance: none; border: 0; background: transparent;+ color: var(--muted); font: inherit; font-size: 12px; font-weight: 600;+ padding: 4px 12px; border-radius: 7px; cursor: pointer;+ transition: background var(--t-fast), color var(--t-fast);+ white-space: nowrap; width: auto;+ }+ .sb-shotview-toggle .smt-btn:hover { color: var(--text); }+ .sb-shotview-toggle .smt-btn.active { background: var(--accent); color: #fff; }++ .sb-shots.sb-shots-grid {+ display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: 10px; list-style: none; padding: 0; margin: 0;+ }+ .sb-grid-tile {+ display: flex; flex-direction: column; gap: 0;+ border: 1px solid var(--border); border-radius: var(--r-sm);+ background: var(--panel-2); overflow: hidden; cursor: pointer;+ transition: border-color var(--t-fast);+ }+ .sb-grid-tile:hover { border-color: var(--border-strong); }+ .sb-grid-thumb {+ width: 100%; aspect-ratio: 16 / 9; object-fit: cover;+ background: var(--bg-2); display: block;+ }+ .sb-grid-thumb-empty { display: flex; }+ .sb-grid-meta {+ display: flex; align-items: center; gap: 6px; padding: 5px 7px;+ font-size: 11px; color: var(--muted);+ font-family: var(--ph-font-mono, ui-monospace, Menlo, monospace);+ }+ .sb-grid-n { color: var(--text); font-weight: 700; }+ .sb-grid-dur { flex: 0 0 auto; }+ .sb-grid-status {+ flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis;+ white-space: nowrap; text-align: right;+ }+ .sb-grid-status-done { color: var(--accent-bright, var(--accent)); }+ .sb-grid-status-failed { color: var(--danger); }+ .sb-grid-status-rendering, .sb-grid-status-queued { color: var(--text); }+ .sb-grid-grade {+ flex: 0 0 auto; width: 16px; height: 16px; border-radius: 50%;+ display: inline-flex; align-items: center; justify-content: center;+ font-size: 11px; font-weight: 800; color: #fff;+ }+ .sb-grid-grade-keep { background: var(--accent-bright, var(--accent)); }+ .sb-grid-grade-reroll { background: #c9862a; }+ .sb-grid-grade-cut { background: var(--danger); }+.sb-summary {position: sticky; top: 0; z-index: 3;display: flex; align-items: stretch; gap: 8px; flex-wrap: wrap;@@ -895,7 +1093,7 @@font-size: 13px; font-weight: 600; color: var(--text);white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}- .sb-sum-cell span { font-size: 10.5px; color: var(--muted); line-height: 1.4; }+ .sb-sum-cell span { font-size: 11px; color: var(--muted); line-height: 1.4; }.sb-sum-cell.is-warn { border-color: rgba(210,153,34,0.45); }.sb-sum-cell.is-warn b { color: var(--warning); }.sb-runstrip { flex: 1 1 100%; display: flex; gap: 4px; }@@ -905,12 +1103,12 @@padding: 5px 9px; min-width: 0;background: var(--panel-2); border: 1px solid var(--border);border-radius: var(--r-sm);- font-size: 10.5px; color: var(--muted); cursor: default;+ font-size: 11px; color: var(--muted); cursor: default;}.sb-runseg:hover { border-color: var(--border-strong); }.sb-runseg-load {text-transform: uppercase; letter-spacing: 0.07em; font-weight: 700;- font-size: 8.5px; color: var(--accent-bright);+ font-size: 11px; color: var(--accent-bright);padding: 1px 5px; border-radius: var(--r-pill);background: var(--accent-dim); flex: 0 0 auto;}@@ -982,7 +1180,7 @@max-width: 150px;}.sb-chip {- font-size: 9px; font-weight: 700; letter-spacing: 0.07em;+ font-size: 11px; font-weight: 700; letter-spacing: 0.07em;text-transform: uppercase; padding: 2px 7px;border-radius: var(--r-pill);border: 1px solid var(--border); color: var(--muted);@@ -1043,8 +1241,16 @@chip: silence is the honest default and a chip for it would be noise onevery other card. */.sb-chip-voice { cursor: default; }+ /* FILM-21: replaces the Text/Character toggle on a singing shot — read+ only, on purpose. The shot's mode, length and place in the film are+ facts about the song, not a choice made per card. */+ .sb-chip-singing {+ cursor: default; color: var(--eng-accent, var(--accent-bright));+ border-color: var(--eng-soft, var(--accent)); background: var(--eng-dim, var(--accent-dim));+ text-transform: none; letter-spacing: 0.02em; font-weight: 600;+ }.sb-shot-est {- font-size: 10.5px; color: var(--muted); flex: 0 0 auto;+ font-size: 11px; color: var(--muted); flex: 0 0 auto;font-family: var(--ph-font-mono, ui-monospace, Menlo, monospace);}.sb-shot-spacer { flex: 1 1 auto; }@@ -1092,7 +1298,7 @@}.sb-err-fix {width: auto; flex: 0 0 auto; margin-left: 4px;- padding: 2px 8px; font-size: 10.5px;+ padding: 2px 8px; font-size: 11px;background: var(--panel-2); border: 1px solid var(--border);border-radius: var(--r-sm); color: var(--text); cursor: pointer;}@@ -1118,7 +1324,7 @@.sb-shot-out .info .sub { color: var(--muted); margin-left: auto; flex: 0 0 auto; }.sb-shot-out.is-stale { opacity: 0.5; }.sb-stale-tag {- font-size: 9px; text-transform: uppercase; letter-spacing: 0.07em;+ font-size: 11px; text-transform: uppercase; letter-spacing: 0.07em;color: var(--warning); font-weight: 700;}.sb-grade { display: flex; gap: 4px; padding: 0 8px 7px; }@@ -1175,6 +1381,14 @@padding: 0 0 10px;}.sb-export-note[hidden] { display: none !important; }+ /* FILM-47: mixed-resolution warning before Finish/Export. */+ .sb-mixed-res-warn {+ font-size: 11.5px; line-height: 1.5; color: var(--warning);+ background: color-mix(in srgb, var(--warning) 12%, transparent);+ border: 1px solid var(--warning);+ border-radius: var(--r-sm, 8px); padding: 7px 10px; margin: 4px 0 8px;+ }+ .sb-mixed-res-warn[hidden] { display: none !important; }/* ---- run bar ---------------------------------------------------- */.sb-runbar {@@ -1221,11 +1435,36 @@collapsed to nothing — at 1000px the rows read "7 shots · 0… PLAN ONLYEdit ×" with no film name anywhere on screen. minmax(0,1fr) on the titleand a shrinkable, ellipsised `.params` puts the name back. */- .sb-boardlist li {+ /* FILM-43: the FULL list (#sbBoardList) gained a thumbnail and two more+ actions (rename, duplicate) beside delete — the mini rail copy+ (#sbBoardListMini, rendered from sbBoardRowMini) is untouched and+ keeps the narrower 5-column rule below it. */+ #sbBoardList.sb-boardlist li {+ grid-template-columns: 48px minmax(0, 1fr) auto auto max-content auto auto auto !important;+ align-items: center; gap: 8px;+ cursor: pointer;+ }+ #sbBoardListMini.sb-boardlist li {grid-template-columns: minmax(0, 1fr) auto auto max-content auto !important;cursor: pointer;}.sb-boardlist li .ttl { min-width: 0; overflow: hidden; text-overflow: ellipsis; }+ .sb-board-thumb {+ width: 48px; height: 27px; object-fit: cover; border-radius: var(--r-xs);+ background: var(--bg-2); border: 1px solid var(--border); display: block;+ }+ .sb-board-thumb-empty { display: block; }+ .sb-board-rename {+ width: 100%; font: inherit; font-size: inherit; color: inherit;+ background: var(--bg-2); border: 1px solid var(--accent);+ border-radius: var(--r-xs); padding: 1px 5px;+ }+ .sb-board-search {+ min-width: 160px; font-size: 12px; padding: 5px 10px;+ border-radius: var(--r-pill); border: 1px solid var(--border);+ background: var(--bg-2); color: var(--text);+ }+ .sb-board-search:focus { outline: none; border-color: var(--accent); box-shadow: var(--ring); }/* The sidebar copy of the same list is ~230 px wide, and one line cannothold a film's name, a shot count, a state badge, a chip and a deletebutton. The name is what lost: at 1000 px the rows read "DRAFTS DONE@@ -1242,7 +1481,16 @@row-gap: 5px; padding: 6px 9px;}#sbBoardListMini li .ttl { grid-area: 1 / 1 / 2 / 2; }- #sbBoardListMini li > button:last-child { grid-area: 1 / 2 / 2 / 3; }+ #sbBoardListMini li > button:last-child,+ #sbBoardListMini li > .sb-board-menu { grid-area: 1 / 2 / 2 / 3; }+ /* 4.17: the row's delete moved into a ⋯ menu (sbBoardRowMenu). The+ `.row-list li button` rule sizes every button in a row to 22x22 —+ the menu's own items must win that back. */+ .sb-boardlist li .sb-board-menu .kebab-pop { z-index: 30; }+ .sb-boardlist li .sb-board-menu .kebab-pop button {+ width: 100%; height: auto; padding: 7px 10px; border: none;+ color: #ff8b80; font-size: 12.5px;+ }#sbBoardListMini li .badge {grid-area: 2 / 1 / 3 / 3; justify-self: start;max-width: 52%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;@@ -1287,10 +1535,10 @@grid-template-columns: auto 1fr auto auto auto;}.sb-rowtags { display: inline-flex; align-items: center; gap: 5px; }- .sb-rowtags .sb-chip-engine { font-size: 8.5px; padding: 1px 6px; }+ .sb-rowtags .sb-chip-engine { font-size: 11px; padding: 1px 6px; }.sb-rowtags .sb-chip-engine .ph { width: 9px; height: 9px; }.car-card .sb-badge {- font-size: 8.5px; letter-spacing: 0.07em; text-transform: uppercase;+ font-size: 11px; letter-spacing: 0.07em; text-transform: uppercase;font-weight: 700; padding: 1px 6px; border-radius: var(--r-pill);cursor: pointer;}@@ -1352,11 +1600,11 @@cursor: pointer; white-space: nowrap; font-family: inherit;}.sb-rail-step .sb-rail-n {- font-size: 9.5px; font-weight: 700; letter-spacing: 0.04em;+ font-size: 11px; font-weight: 700; letter-spacing: 0.04em;color: var(--muted); opacity: 0.75;}.sb-rail-step .sb-rail-sub {- font-size: 10.5px; font-weight: 500; color: var(--muted); opacity: 0.85;+ font-size: 11px; font-weight: 500; color: var(--muted); opacity: 0.85;}.sb-rail-step:hover { color: var(--text); background: var(--panel-2); }.sb-rail-step.is-done { color: var(--text); }@@ -1406,7 +1654,7 @@padding: 2px 7px;}.sb-film-kind {- font-size: 9px; font-weight: 700; letter-spacing: 0.07em;+ font-size: 11px; font-weight: 700; letter-spacing: 0.07em;text-transform: uppercase; padding: 2px 7px;border-radius: var(--r-pill);color: var(--accent-bright); background: var(--accent-dim);@@ -1544,11 +1792,23 @@#edSectionTab { flex-direction: column; min-height: 0; gap: 8px; padding-bottom: 14px; }.ed-pool-head { margin: 0; }.ed-pool-head h3 { margin: 0; }- .ed-pool-tabs { display: flex; gap: 6px; flex-wrap: wrap; }- /* Four sources in a ~200px column. `flex: 1 1 auto` laid them out three- and one, which reads as the fourth being an afterthought rather than a- peer. A 40% basis wraps them two and two. */- .ed-pool-tabs .pill-btn { flex: 1 1 40%; width: auto; }+ /* FILM-37: five sources (This __SEQCAP__ / Other __SEQS__ / Generations /+ Images / Sound) at a 40% flex-basis wrapped into up to three rows —+ measured 1.5 rows at 1366x768 — which ate vertical space the pool's+ own list needed. One row, always: each tab shares the row equally and+ ellipsises its label rather than wrapping the row itself. */+ .ed-pool-tabs { display: flex; gap: 8px; flex-wrap: nowrap; align-items: center; }+ .ed-pool-src-label {+ flex: 0 0 auto; font-size: var(--fs-xs); font-weight: 600;+ letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted);+ }+ .ed-pool-tabs .ed-pool-src {+ flex: 1 1 auto; min-width: 0; width: auto;+ font-size: 12px; padding: 6px 8px;+ background: var(--bg-2); color: var(--text);+ border: 1px solid var(--border); border-radius: var(--r-sm);+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }.ed-pool-film, .ed-pool-search { width: 100%; }.ed-pool-film[hidden] { display: none !important; }.ed-pool-list {@@ -1616,6 +1876,9 @@}.sbe-relink[hidden] { display: none !important; }.sbe-relink .sbe-relink-why { color: var(--muted); font-size: var(--fs-xs); }+ /* FILM-15: offline is a harder stop than "a finished version exists" —+ it blocks Render — so it borrows the danger colour the alarm uses. */+ .sbe-relink.sbe-offline { border-color: var(--danger); }.ed-pick {display: flex; flex-direction: column; gap: 6px;margin-top: 14px; width: 100%; max-width: 460px;@@ -1675,6 +1938,22 @@width: auto; padding-inline: 8px; margin-left: 1px;}.sbe-kebab { width: auto; padding-inline: 9px; letter-spacing: 0.06em; }+ /* FILM-24 — the last render, next to the button that made it. Plain text+ plus two inline actions, the same visual weight as the draft chip+ beside it: this is a fact about the film, not another button. */+ .sbe-render-chip {+ display: inline-flex; align-items: center; gap: 8px;+ font-size: var(--fs-2xs); color: var(--muted); white-space: nowrap;+ max-width: 220px; overflow: hidden;+ }+ .sbe-render-chip[hidden] { display: none !important; }+ .sbe-render-chip-label { overflow: hidden; text-overflow: ellipsis; }+ .sbe-render-chip button {+ background: none; border: none; padding: 0; margin: 0;+ font: inherit; font-weight: 600; color: var(--accent-bright);+ cursor: pointer; white-space: nowrap;+ }+ .sbe-render-chip button:hover { text-decoration: underline; }/* ---- the popover, four times ------------------------------------FIXED, so an open menu is not part of the column's height and cannotpush the workspace around — the rule the notice surface set. */@@ -1769,7 +2048,7 @@.sbe-trk-mute {flex: 0 0 auto; width: 18px; height: 16px; padding: 0; line-height: 1;border: 1px solid var(--border); border-radius: var(--r-xs);- background: var(--panel); color: var(--muted); font-size: 9px; font-weight: 700;+ background: var(--panel); color: var(--muted); font-size: 11px; font-weight: 700;cursor: pointer;}.sbe-trk-mute.is-on { background: var(--warning); border-color: var(--warning); color: #14101c; }@@ -1781,13 +2060,13 @@width: auto; height: 18px; padding: 0 6px; font-size: var(--fs-2xs);white-space: nowrap; min-width: 0; overflow: hidden; text-overflow: ellipsis;}- .sbe-gh-add .sbe-gh-more { margin-left: auto; font-size: 10px; }+ .sbe-gh-add .sbe-gh-more { margin-left: auto; font-size: 11px; }.sbe-gh-tag {display: flex; align-items: center; gap: 5px; min-width: 0;font-size: var(--fs-2xs); color: var(--text); font-weight: 600;}.sbe-gh-tag i {- font-style: normal; font-size: 9px; letter-spacing: 0.04em;+ font-style: normal; font-size: 11px; letter-spacing: 0.04em;color: var(--muted); border: 1px solid var(--border);border-radius: 3px; padding: 1px 3px; flex: 0 0 auto;}@@ -1801,7 +2080,7 @@margin-left: auto; flex: 0 0 auto; width: 18px; height: 16px;border: 1px solid var(--border); border-radius: var(--r-xs);background: var(--panel); color: var(--muted); cursor: pointer;- font-size: 9px; line-height: 1; padding: 0;+ font-size: 11px; line-height: 1; padding: 0;}.sbe-gh-more:hover { border-color: var(--accent); color: var(--text); }.sbe-gh-mode {@@ -1845,7 +2124,7 @@ticked while doing nothing would be the silent guard this editor keepspaying for. */.sbe-mix-note {- font-size: 9px; line-height: 1.25; color: var(--warn, #d29922);+ font-size: 11px; line-height: 1.25; color: var(--warn, #d29922);overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}.sbe-gh-mus.is-duck-off .sbe-mix-duck { opacity: 0.55; }@@ -2102,6 +2381,24 @@Source picture came out 499x315 — not 16:9. Stated widths, no shrink;the bars ellipsise inside them. */.sbe-monitors > .sbe-mon-src { flex: 0 0 auto; width: calc(var(--sbe-src-h) * 16 / 9); }+ /* FILM-37: EMPTY IS NOT A PICTURE. "Nothing loaded" used to sit in the+ full 16:9 box regardless — about a third of the row, permanently, on+ every open of the Editor, even for someone who never uses Source at+ all. Collapsed to a rail wide enough for its own label and the drop+ icon, and nothing else: the play/add/close buttons and the empty-+ state's own sentence have no job to do until something is loaded, so+ they are the parts that go. `sbePaintSource` (editor.js) sets this+ class from the one place that already knows whether a row is loaded —+ `!SBE.source` — so it can never disagree with what the bar itself+ says ("Nothing loaded"). */+ .sbe-monitors > .sbe-mon-src.is-empty { width: 64px; }+ .sbe-mon-src.is-empty .sbe-mon-bar > :not(.sbe-mon-label) { display: none; }+ .sbe-mon-src.is-empty .sbe-mon-label {+ writing-mode: vertical-rl; text-orientation: mixed; flex: 1 1 auto;+ justify-content: center; display: flex; align-items: center;+ }+ .sbe-mon-src.is-empty .sbe-src-empty b,+ .sbe-mon-src.is-empty .sbe-src-empty span { display: none; }.sbe-monitors > .sbe-mon-prog { flex: 0 0 auto; width: calc(var(--sbe-prog-h) * 16 / 9); max-width: 100%; }.sbe-mon-src .sbe-stage, .sbe-mon-prog .sbe-stage { width: 100%; }/* THE DROP TARGET. Lit while a clip is dragged over it. */@@ -2150,6 +2447,35 @@/* A clipped list has to READ as clipped. */scrollbar-color: var(--border) transparent; scrollbar-width: thin;}+ /* FILM-37: BELOW 1600px THE INSPECTOR IS A DRAWER, NOT A COLUMN. In the+ normal flex row above it shared width with the monitors and the+ timeline through `--sbe-rail-w` (a number sbeFitMonitors computes,+ elsewhere) — at 1366-1440px that number measured about 210px, and the+ "2x" speed control clipped inside it. `position: fixed` takes the+ rail OUT of that row's width budget entirely — sbeFitMonitors can go+ on computing whatever it likes for `--sbe-rail-w`, unread here — and+ floats it over the picture instead, at a width wide enough to read+ every control in it: 320px, the same "wide enough for real controls"+ judgment the versions panel above already made at 400px. It still+ toggles on the exact same `hidden` attribute sbeInspectSet already+ flips — opening the drawer costs the picture no width at all now,+ where it used to cost up to a third of it. Portalled in intent, not+ in DOM: unlike the versions panel this does not need to survive an+ ancestor's `overflow`, since it sits directly under `.sbe-monitors`'+ row with nothing clipping between them.+ Above 1600px there is room for both without squeezing anything past+ readable, so the rail goes back to being an ordinary column — this+ rule undoes itself outside the media query, nothing else has to. */+ @media (max-width: 1599px) {+ .sbe-rail {+ position: fixed; top: 64px; right: 12px; bottom: 12px;+ width: 320px; max-width: calc(100vw - 24px);+ height: auto; z-index: 60;+ background: var(--panel); border: 1px solid var(--border-strong);+ border-radius: var(--r-md); box-shadow: var(--shadow-2);+ padding: 10px;+ }+ }/* ---- the stage: ONE <video> per monitor. Double-buffering measured nobenefit once proxies are all-intra, and two elements on one stream istwo decoders for nothing. ---- */@@ -2303,7 +2629,7 @@`.quality-strip` and the One Shot panel already paid for. */.sbe-cbar-btn[hidden], .sbe-cbar-sep[hidden] { display: none !important; }.sbe-cbar-more { margin-left: 2px; }- .sbe-cbar-more .sbe-car { font-size: 9px; opacity: 0.75; }+ .sbe-cbar-more .sbe-car { font-size: 11px; opacity: 0.75; }/* THE OVERFLOW PANEL holds the very same buttons, so they have to stopbeing a row and become a list once they are in it. */.sbe-cbar-pop { min-width: 170px; }@@ -2397,6 +2723,8 @@.sbe-time {font-variant-numeric: tabular-nums; font-size: var(--fs-sm); color: var(--text);min-width: 104px;+ /* FILM-52: it is a toggle now (seconds vs frame timecode) — say so. */+ cursor: pointer;}.sbe-time span { color: var(--muted); }.sbe-approx {@@ -2509,7 +2837,7 @@.sbe-ruler u {position: absolute; top: 1px; height: 12px; text-decoration: none;border-radius: 3px; overflow: hidden; white-space: nowrap;- font-size: 9px; line-height: 12px; letter-spacing: 0.08em; text-transform: uppercase;+ font-size: 11px; line-height: 12px; letter-spacing: 0.08em; text-transform: uppercase;font-weight: 700; color: rgba(255,255,255,0.85); padding: 0 5px; pointer-events: auto;background: rgba(255,255,255,0.12); box-shadow: inset 0 0 0 1px rgba(255,255,255,0.08);}@@ -2526,6 +2854,18 @@position: absolute; top: 3px; font-weight: 500;transform: translateX(3px); font-variant-numeric: tabular-nums;}+ /* FILM-58: MARKERS — a small flag at the ruler's bottom edge, the same+ silhouette Premiere/Resolve/Final Cut all use, so it reads as "marker"+ on sight. Coloured by kind: beat cyan, lyric violet, a plain note grey. */+ .sbe-marker {+ position: absolute; bottom: 0; width: 8px; height: 8px;+ transform: translateX(-1px); cursor: pointer; z-index: 4; pointer-events: auto;+ clip-path: polygon(0 0, 100% 0, 100% 60%, 50% 100%, 0 60%);+ background: var(--muted);+ }+ .sbe-marker.is-beat { background: #4fd6e8; }+ .sbe-marker.is-lyric { background: #b98bff; }+ .sbe-marker:hover { filter: brightness(1.25); }/* The soundtrack lane lives UNDER the picture now, so the rule thatseparates it from the track is its own top border — the track's wasremoved for the same reason, or the ruler's bottom edge would have been@@ -3161,6 +3501,16 @@background: var(--success);}.sbe-clip.is-bad { border-color: var(--danger); box-shadow: 0 0 0 1px var(--danger); }+ /* FILM-15: the red hatch — a moved or trashed file, at a glance, without+ opening the Inspector. Same weight as .is-bad's border; the hatch is+ what says WHY rather than just that something is wrong. */+ .sbe-clip.is-offline {+ border-color: var(--danger); box-shadow: 0 0 0 1px var(--danger);+ background-image: repeating-linear-gradient(135deg,+ rgba(248,81,73,0.18), rgba(248,81,73,0.18) 6px,+ transparent 6px, transparent 12px);+ }+ .sbe-clip.is-offline .sbe-cl-flag { background: var(--danger); color: #fff; }.sbe-clip.is-drag { opacity: 0.8; cursor: grabbing; z-index: 20; }.sbe-clip.is-locked { cursor: not-allowed; }.sbe-clip .sbe-cl-name {@@ -3196,6 +3546,18 @@object-fit: cover; opacity: 0.38; z-index: 0; pointer-events: none;}.sbe-clip .sbe-cl-name, .sbe-clip .sbe-cl-meta { position: relative; z-index: 1; }+ /* FILM-05: "sync to song" — bottom-left, clear of the name/flag/sync+ cluster at the top and the grips/fades at the sides. A button, the+ same as the drift flag: one click is Snap to song. */+ .sbe-songsync {+ position: absolute; left: 4px; bottom: 4px; z-index: 8;+ padding: 0 5px; border-radius: var(--r-xs);+ background: var(--accent); color: #fff; cursor: pointer;+ font-size: var(--fs-2xs); font-weight: 700; line-height: 15px;+ font-variant-numeric: tabular-nums; letter-spacing: 0.02em;+ border: 1px solid rgba(0,0,0,0.25); pointer-events: auto;+ }+ .sbe-songsync:hover { filter: brightness(1.12); }.sbe-clip.is-slug {background: #000; border-color: var(--border-strong);}@@ -3210,6 +3572,8 @@box-shadow: 0 0 6px var(--accent);}.sbe-track.is-dropping { background: rgba(255,255,255,0.035); }+ /* FILM-08: ⌥-drop overwrites a clip instead of inserting one. */+ .sbe-track.is-overwriting { background: rgba(248, 176, 81, 0.08); }.sbe-grip {position: absolute; top: 0; bottom: 0; width: var(--sbe-grip-w, 9px);z-index: 6;@@ -3626,13 +3990,13 @@/* ===== FORM ===== */h2 {- font-size: 10px; margin: 14px 0 8px; color: var(--muted);+ font-size: 11px; margin: 14px 0 8px; color: var(--muted);text-transform: uppercase; letter-spacing: 0.1em; font-weight: 600;}h2:first-child { margin-top: 0; }label.lbl {display: block; margin: 10px 0 4px; color: var(--muted);- font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 600;+ font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 600;}input, textarea, select, button {width: 100%; padding: 8px 11px; font: inherit; color: inherit;@@ -3681,7 +4045,7 @@color: var(--accent-bright); font-weight: 600;}.pill-btn .ico { font-size: 16px; line-height: 1; }- .pill-btn .sub { font-size: 10px; color: var(--muted); margin-top: 1px; }+ .pill-btn .sub { font-size: 11px; color: var(--muted); margin-top: 1px; }/* Tiny amber chip flagging a feature as not-yet-fully-validated.Inline alongside the label, doesn't push the layout — same idiomas a "NEW" or "BETA" tag. Used on the Style train-type pill in@@ -3690,7 +4054,7 @@display: inline-block;padding: 1px 6px;margin-left: 6px;- font-size: 9px;+ font-size: 11px;font-weight: 600;letter-spacing: 0.06em;text-transform: uppercase;@@ -3747,7 +4111,7 @@position: absolute; left: 0; right: 0; bottom: 0;background: linear-gradient(to top, rgba(0,0,0,0.85), rgba(0,0,0,0));color: white; padding: 16px 6px 4px;- font-size: 10px; line-height: 1.2;+ font-size: 11px; line-height: 1.2;pointer-events: none;}@@ -3769,7 +4133,7 @@app from the video form even though the comment claimed theymirrored it. */.studio-pane h2 .h2-hint {- font-size: 10px;+ font-size: 11px;letter-spacing: 0;color: var(--muted);text-transform: none;@@ -3921,7 +4285,7 @@top: 6px; left: 6px;padding: 2px 6px;border-radius: 4px;- font-size: 9.5px;+ font-size: 11px;font-family: var(--ph-font-mono);letter-spacing: 0.06em;text-transform: uppercase;@@ -4165,7 +4529,7 @@.ideo-box-text.st-serif { font-weight: 600; font-family: Georgia,"Times New Roman",serif; }.ideo-box-obj-label {position: absolute; left: 0; top: 0; padding: 1px 5px;- font-size: 9px; font-family: var(--ph-font-mono); letter-spacing: .04em;+ font-size: 11px; font-family: var(--ph-font-mono); letter-spacing: .04em;color: var(--muted); background: rgba(10,15,36,0.7); border-bottom-right-radius: 3px;pointer-events: none; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}@@ -4265,7 +4629,7 @@body[data-workflow="studio"].ideo-canvas-on .ideo-insp-grid { grid-template-columns: 1fr; }.ideo-stage-note {- font-size: 10.5px; color: var(--muted); margin: 6px 2px 0; line-height: 1.45;+ font-size: 11px; color: var(--muted); margin: 6px 2px 0; line-height: 1.45;}/* Inspector */@@ -4278,7 +4642,7 @@.ideo-insp-row:last-child { margin-bottom: 0; }.ideo-insp-row .mf-label,.ideo-insp-cell .mf-label {- display: block; font-size: 10.5px; color: var(--muted);+ display: block; font-size: 11px; color: var(--muted);text-transform: uppercase; letter-spacing: .04em; margin-bottom: 4px;}.ideo-inspector input[type="text"] {@@ -4315,12 +4679,12 @@border-radius: var(--r-sm); background: transparent; cursor: pointer;}.ideo-insp-actions { display: flex; align-items: center; gap: 8px; margin-top: 10px; }- .ideo-insp-bbox { font-size: 10px; font-family: var(--ph-font-mono); color: var(--muted); }+ .ideo-insp-bbox { font-size: 11px; font-family: var(--ph-font-mono); color: var(--muted); }.ideo-danger:hover { border-color: var(--danger) !important; color: var(--danger) !important; }/* Render / Quality / palette / raw controls */.ideo-controls { display: grid; grid-template-columns: 1.4fr 1fr; gap: 11px; margin-top: 11px; }- .ideo-ctrl-cell .mf-label { display: block; font-size: 10.5px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; margin-bottom: 5px; }+ .ideo-ctrl-cell .mf-label { display: block; font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; margin-bottom: 5px; }.ideo-ctrl-cell .pill-group { margin-bottom: 0; }.ideo-ctrl-cell select {width: 100%; padding: 8px 9px; font-size: 13px;@@ -4337,15 +4701,15 @@}.ideo-details > summary::-webkit-details-marker { display: none; }.ideo-details > summary::before {- content: "▸"; color: var(--muted); font-size: 10px; transition: transform var(--t-fast);+ content: "▸"; color: var(--muted); font-size: 11px; transition: transform var(--t-fast);}.ideo-details[open] > summary::before { transform: rotate(90deg); }- .ideo-summary-meta { font-size: 10.5px; color: var(--muted); font-weight: 400; }+ .ideo-summary-meta { font-size: 11px; color: var(--muted); font-weight: 400; }.ideo-palette-body, .ideo-raw-body { padding: 0 11px 11px; }.ideo-help { font-size: 11px; color: var(--muted); margin: 2px 0 8px; line-height: 1.45; }.ideo-palette-add { display: flex; align-items: center; gap: 8px; margin-top: 9px; }.ideo-validity-chip {- font-size: 10px; font-family: var(--ph-font-mono); padding: 1px 7px;+ font-size: 11px; font-family: var(--ph-font-mono); padding: 1px 7px;border-radius: var(--r-pill); border: 1px solid var(--border);color: var(--muted); background: var(--bg-2);}@@ -4549,7 +4913,7 @@display: inline-flex;align-items: center;gap: 4px;- font-size: 10.5px;+ font-size: 11px;letter-spacing: 0.02em;padding: 2px 7px;border-radius: 4px;@@ -4723,7 +5087,7 @@gap: 5px;}.characters-group-label {- font-size: 10.5px;+ font-size: 11px;font-weight: 600;letter-spacing: 0.08em;text-transform: uppercase;@@ -4817,7 +5181,7 @@padding: 12px 14px;}.characters-preview-label {- font-size: 10.5px;+ font-size: 11px;font-weight: 600;letter-spacing: 0.1em;text-transform: uppercase;@@ -4923,7 +5287,7 @@============================================================ */.train-pane.show { display: block; }.train-pane h2 .h2-hint {- font-size: 10px;+ font-size: 11px;letter-spacing: 0;color: var(--muted);text-transform: none;@@ -4976,6 +5340,32 @@padding: 6px 14px;font-size: 13px;}+ .train-preflight-actions { margin: 4px 0 12px; }+ .train-preflight-actions .btn {+ padding: 8px 16px; font-size: 13px; font-weight: 600;+ }+ /* SYS-03: the Train tab's whole-tab RAM gate.+ Caught live: same [hidden]-losing-to-a-class-display-rule bug as+ .breaker-notice below — a bare `display: flex` here beat the UA+ [hidden] rule, so this card showed even on a Mac with plenty of+ RAM (trainGateCard.hidden = true, computed display still "flex").+ Same established fix pattern as [data-spicy-only][hidden]. */+ .train-gate-card[hidden] { display: none !important; }+ /* Codex UI-7: the gate hides the rest of the tab by CLASS, so the+ children keep their own `hidden` state (the Voice card under Style). */+ #trainSection.train-ram-gated > :not(#trainGateCard) { display: none !important; }+ .train-gate-card {+ display: flex; gap: 12px; align-items: flex-start;+ background: rgba(255, 168, 0, 0.06);+ border: 1px solid rgba(255, 168, 0, 0.35);+ border-radius: 10px;+ padding: 16px 18px;+ margin-bottom: 12px;+ }+ .train-gate-card .ph { width: 20px; height: 20px; flex-shrink: 0; color: #ffb84a; margin-top: 2px; }+ .train-gate-title { font-weight: 600; font-size: 14px; color: #e6e6ea; margin-bottom: 6px; }+ .train-gate-body { color: #aab; font-size: 12.5px; line-height: 1.5; margin-bottom: 12px; }+ .train-gate-actions { display: flex; gap: 8px; flex-wrap: wrap; }.train-preflight-foot {margin-top: 12px;color: #888;@@ -5023,7 +5413,7 @@}.train-guidance[open] summary::after { transform: rotate(-135deg); }.train-guidance-eyebrow {- font-size: 10.5px;+ font-size: 11px;font-weight: 600;letter-spacing: 0.08em;text-transform: uppercase;@@ -5154,7 +5544,7 @@.train-thumb .train-thumb-num {position: absolute;left: 4px; bottom: 4px;- font-size: 9.5px;+ font-size: 11px;font-family: var(--ph-font-mono);background: rgba(0, 0, 0, 0.55);color: var(--text);@@ -5228,7 +5618,7 @@.train-thumb .train-thumb-cap {position: absolute;right: 4px; bottom: 4px;- font-size: 9px;+ font-size: 11px;font-family: var(--ph-font-mono);padding: 1px 5px;border-radius: 4px;@@ -5294,7 +5684,7 @@details.train-caption-hint > summary::-webkit-details-marker { display: none; }details.train-caption-hint .train-caption-hint-eyebrow {color: var(--muted);- font-size: 10.5px;+ font-size: 11px;margin-left: auto;letter-spacing: 0.4px;}@@ -5401,7 +5791,7 @@grid-template-columns: repeat(3, 1fr);}.train-pane .pill-btn .sub {- font-size: 10.5px;+ font-size: 11px;letter-spacing: 0;font-family: var(--ph-font-mono);}@@ -5435,7 +5825,7 @@display: inline-flex; align-items: center;margin-left: 6px;padding: 1px 6px;- font-size: 9.5px; font-weight: 600;+ font-size: 11px; font-weight: 600;font-family: var(--ph-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);letter-spacing: 0.04em;text-transform: none;@@ -5469,7 +5859,7 @@color: var(--muted);text-transform: uppercase;letter-spacing: 0.06em;- font-size: 10px;+ font-size: 11px;}.train-est-value {font-family: var(--ph-font-mono);@@ -5556,6 +5946,14 @@height: 32px;filter: invert(0.86) hue-rotate(180deg);}+ /* VC-20: the Video tab's compact inline audio player — one <audio>+ element plus an optional way over to the real Music Studio surface,+ instead of transplanting that tab's whole player+card into this one. */+ .player-audio-inline {+ width: 100%; padding: 24px 16px;+ display: flex; flex-direction: column; align-items: stretch; gap: 10px;+ }+ .player-audio-open { align-self: center; }.train-voice-controls {display: flex;flex-direction: column;@@ -5587,9 +5985,28 @@border-radius: 0;appearance: auto;-webkit-appearance: auto;+ /* SYS-10c: a checked+disabled checkbox (the pre-upload "will enable+ once you add a clip" state) rendered as an empty grey box — the+ default UA disabled-opacity plus a dark surface left the checkmark+ with too little contrast to read as checked. accent-color fixes+ the fill; the raised floor on :disabled keeps the mark visible. */+ accent-color: var(--accent, #4f8cff);+ }+ .train-voice-toggle input[type="checkbox"]:disabled {+ cursor: not-allowed;+ opacity: 0.85;}- .train-voice-toggle input[type="checkbox"]:disabled { cursor: not-allowed; }.train-voice-toggle-label { color: var(--text); white-space: nowrap; }+ .train-voice-inline-error {+ color: #d29922;+ font-size: 11.5px;+ line-height: 1.4;+ margin-top: 6px;+ padding: 6px 10px;+ background: rgba(210, 153, 34, 0.08);+ border: 1px solid rgba(210, 153, 34, 0.3);+ border-radius: 6px;+ }.train-voice-toggle-hint {color: var(--muted);font-size: 11px;@@ -5632,12 +6049,12 @@white-space: nowrap;}.train-lora-row .tl-trigger {- font-size: 10.5px;+ font-size: 11px;color: var(--accent);font-family: var(--ph-font-mono);}.train-lora-row .tl-size {- font-size: 10.5px;+ font-size: 11px;color: var(--muted);font-family: var(--ph-font-mono);}@@ -5679,7 +6096,7 @@.train-lora-verdict {margin-left: 6px;padding: 0 5px;- font-size: 9px; font-weight: 700; letter-spacing: 0.06em;+ font-size: 11px; font-weight: 700; letter-spacing: 0.06em;font-family: var(--ph-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);color: var(--warning);border: 1px solid rgba(210, 153, 34, 0.48);@@ -5730,14 +6147,14 @@color: inherit; /* picks up muted/active colour from .pill-btn */}.pill-quality .ql-spec {- font-size: 10.5px;+ font-size: 11px;color: var(--text);opacity: 0.85;font-family: ui-monospace, SFMono-Regular, Menlo, monospace;letter-spacing: 0;}.pill-quality .ql-tier {- font-size: 9.5px;+ font-size: 11px;color: var(--muted);letter-spacing: 0.04em;text-transform: uppercase;@@ -5800,6 +6217,11 @@one stays clickable so it can explain the pending release asset. */.pill-btn.needs-download { opacity: .62; border-style: dashed; }.pill-btn.needs-download:hover { opacity: .9; }+ /* H3-13: a shape with no Fast pass at all (Native, single-pass 10s) —+ same dashed/dimmed grammar as needs-download, but it can never resolve+ by installing anything, only by picking a different shape. */+ .pill-btn.cell-only-best { opacity: .62; border-style: dashed; }+ .pill-btn.cell-only-best:hover { opacity: .9; }/* H3 Speed switch (⚡ Fast | ✦ Best), above the Quality cards. */.h3-speed { margin: 0 0 10px; }.h3-speed .h3-speed-group .pill-btn { display: flex; flex-direction: column; align-items: center; gap: 2px; }@@ -5884,12 +6306,19 @@font-weight: 400;letter-spacing: 0;text-transform: none;- font-size: 10.5px;+ font-size: 11px;color: var(--muted);opacity: 0.85;}.cz-control .row { gap: 8px; }+ /* FILM-44: the signpost from Storyboard's raw Soundtrack box to the+ Audio tab's real Music Video planner. */+ .sb-track-signpost {+ font-size: 11px; color: var(--muted); margin-top: 6px;+ }+ .sb-track-signpost a { color: var(--accent-bright, var(--accent)); }+/* Mode-specific blocks (image/audio/extend sections) */.mode-only { display: none; }.mode-only.show { display: block; }@@ -5906,7 +6335,7 @@background: rgba(255,255,255,0.02);}.kf-toggle-label {- font-size: 10px;+ font-size: 11px;font-weight: 600;text-transform: uppercase;letter-spacing: 0.5px;@@ -5919,7 +6348,7 @@}.kf-sub {display: block;- font-size: 9px;+ font-size: 11px;font-weight: 400;opacity: 0.6;line-height: 1.1;@@ -5939,13 +6368,19 @@.row3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }.check { display: flex; align-items: center; gap: 8px; margin: 10px 0; cursor: pointer; color: var(--text); font-size: 12px; }.check input { width: auto; margin: 0; }- .hint { color: var(--muted); font-size: 10px; margin-top: 4px; }- .derived {- margin-top: 8px; padding: 9px 11px; border-radius: 6px;- background: var(--panel-2); border: 1px solid var(--border);- font-size: 12px; color: var(--muted);+ .hint { color: var(--muted); font-size: 11px; margin-top: 4px; }+ /* SYS-24: this is a same-page href="#" link, so after the first click+ it's :visited — and unstyled :visited defaults to the browser's own+ dull purple/dark-blue, which read as "dark blue on navy, nearly+ invisible" against this panel's dark background. Explicit color for+ both states fixes it (and stops it silently darkening after use). */+ .train-go-video-link,+ .train-go-video-link:visited {+ color: var(--accent-bright, #58a6ff);+ text-decoration: underline;+ font-weight: 600;}- .derived strong { color: var(--accent-bright); font-weight: 600; }+ .train-go-video-link:hover { color: var(--text); }.warn-banner {background: rgba(210,153,34,0.08); border: 1px solid rgba(210,153,34,0.4);color: var(--warning); padding: 8px 11px; border-radius: 6px; margin: 8px 0;@@ -5959,11 +6394,25 @@}button.primary:hover { background: var(--accent-bright); border-color: var(--accent-bright); }button.primary:disabled { opacity: 0.55; cursor: not-allowed; }+ /* SYS-24: white-on-#2f81f7 measures 3.75:1 -- below the 4.5:1 AA floor+ for normal text (Generate's 14px/600 weight doesn't reach WCAG's+ "large text" exemption). This is the single most-clicked button in+ the app; scoped to #genBtn rather than every button.primary so it+ doesn't ripple into surfaces this measurement wasn't about. */+ #genBtn { background: #1f6feb; border-color: #1f6feb; }+ /* Darker on hover, not lighter — the usual "brighten on hover" pattern+ (button.primary:hover above) moves toward --accent-bright, which+ measures WORSE (3.84:1) than the resting state. */+ #genBtn:hover:not(:disabled) { background: #1a5fd0; border-color: #1a5fd0; }button.danger {color: var(--danger); border-color: rgba(248,81,73,0.4); background: transparent;padding: 11px; font-weight: 600; cursor: pointer;}- button.danger:hover { background: rgba(248,81,73,0.1); }+ button.danger:hover:not(:disabled) { background: rgba(248,81,73,0.1); }+ /* SYS-10d / SYS-37: Stop had no disabled look at all — armed-red at+ every moment including idle, so there was no visual cue that+ clicking it right now would do nothing. */+ button.danger:disabled { opacity: 0.4; cursor: not-allowed; }.actions { display: grid; grid-template-columns: 2fr 1fr; gap: 8px; margin-top: 14px; }button.small {width: auto; padding: 6px 10px; font-size: 11px;@@ -6033,7 +6482,7 @@box-shadow: var(--shadow-1);}.mode-bar .mode-chip .mc-sub {- font-size: 9.5px;+ font-size: 11px;font-weight: 500;color: var(--muted);letter-spacing: 0.02em;@@ -6142,6 +6591,75 @@color: var(--muted); opacity: 0.85;flex: 1 1 220px; min-width: 0;}+ /* H3-07: the prompt helper toolbar (Structure / + Line / language /+ word-budget / quote warning). Same flex-row grammar as+ .composer-tools, its own row so the two never compete for space when+ both are visible at once (H3's ct-hint sits in composer-tools below+ this). */+ .h3-prompt-helper {+ margin-top: 8px;+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap;+ }+ .h3-prompt-helper .ct-spacer { flex: 1 1 auto; }+ .h3-prompt-helper select#h3DialogueLang {+ font-size: 12px; padding: 4px 6px;+ background: var(--panel-2, var(--panel)); color: var(--text);+ border: 1px solid var(--border); border-radius: 6px;+ }+ .h3-prompt-helper-words {+ font-size: 11px; color: var(--muted); white-space: nowrap;+ }+ .h3-prompt-helper-words.over-budget {+ color: var(--warn, #e8b341); font-weight: 600;+ }+ .h3-prompt-helper-warn {+ display: inline-flex; align-items: center; gap: 5px;+ font-size: 11px; color: var(--warn, #e8b341);+ white-space: nowrap;+ }+ .h3-prompt-helper-warn .ph { width: 13px; height: 13px; }++ /* VC-13: the language hint — shown once a non-Latin-script prompt is+ typed (updateLangHint()). Between the textarea and the tools strip,+ reads as a caption rather than a warning. */+ .lang-hint {+ display: flex; align-items: center; gap: 12px; flex-wrap: wrap;+ margin-top: 6px; padding: 6px 10px;+ font-size: 11px; color: var(--muted);+ background: var(--accent-dim); border: 1px solid var(--accent);+ border-radius: var(--r-sm);+ }+ .lang-hint-toggle {+ display: flex; align-items: center; gap: 5px;+ color: var(--text); font-weight: 500; white-space: nowrap;+ cursor: pointer;+ }+ /* VC-16: Enhance's inline result — replaces the old native confirm(). */+ .enhance-panel {+ margin-top: 10px; padding: 10px;+ border: 1px solid var(--border); border-radius: var(--r-sm);+ background: var(--panel-2);+ }+ .enhance-panel-body {+ display: grid; grid-template-columns: 1fr 1fr; gap: 10px;+ }+ @media (max-width: 520px) {+ .enhance-panel-body { grid-template-columns: 1fr; }+ }+ .enhance-panel-label {+ font-size: 11px; font-weight: 600; text-transform: uppercase;+ letter-spacing: 0.08em; color: var(--muted); margin-bottom: 4px;+ }+ .enhance-panel-text {+ font-size: 12px; line-height: 1.45; color: var(--text);+ max-height: 160px; overflow-y: auto; white-space: pre-wrap;+ }+ .enhance-panel-actions {+ display: flex; align-items: center; gap: 8px; margin-top: 10px;+ }+ .enhance-panel-note {+ font-size: 11px; color: var(--muted);+ }/* Avoid disclosure — collapsed by default. When opened, thetextarea sits outside the composer-card (in its own panel below)so the prompt stays clean. */@@ -6153,22 +6671,42 @@.avoid-row .avoid-label {display: flex; align-items: center; gap: 8px;margin: 0 0 5px 2px;- font-size: 10.5px; font-weight: 600;+ font-size: 11px; font-weight: 600;color: var(--muted);text-transform: uppercase; letter-spacing: 0.08em;}.avoid-row .avoid-label .avoid-hint {- font-weight: 400; font-size: 10px;+ font-weight: 400; font-size: 11px;letter-spacing: 0; text-transform: none;color: var(--muted); opacity: 0.7;}+ /* VC-15: shown instead of leaving a typed Avoid line silently ignored on+ Quick/Balanced/Standard. Sits between the label and the textarea, which+ itself dims (avoid-textarea.is-ignored below) so the whole control+ reads as "off", not just the note. */+ .avoid-ignored-note {+ font-size: 11px; color: var(--warning);+ margin: 0 0 6px 2px;+ }+ .avoid-ignored-note a {+ color: var(--accent-bright); text-decoration: none;+ }+ .avoid-ignored-note a:hover { text-decoration: underline; }+ .avoid-textarea.is-ignored {+ opacity: 0.55;+ }/* Tiny icon-style toggle inside the composer tools row. Same idiom as.toggle-pill but icon-first so it stays compact. */.ct-link {width: auto;padding: 4px 9px;background: transparent;- border: 1px solid transparent;+ /* SYS-21: was a fully transparent border, so "Avoid +" read as plain+ text next to the always-bordered "No music"/"No voice" pills right+ beside it — one interactive control looked disabled or decorative.+ A faint resting border matches those without competing visually+ once it's active (.ct-link.active below takes over). */+ border: 1px solid var(--border);color: var(--muted);font-size: 11px; font-weight: 500;border-radius: var(--r-xs);@@ -6187,7 +6725,7 @@.composer-card h2,.customize-section h2,.composer-refs h2 {- font-size: 10px;+ font-size: 11px;margin: 0 0 6px;color: var(--muted);text-transform: uppercase;@@ -6209,7 +6747,7 @@margin-bottom: 6px;}.quick-settings .qs-label .qs-name {- font-size: 10px; font-weight: 600;+ font-size: 11px; font-weight: 600;color: var(--muted);text-transform: uppercase; letter-spacing: 0.08em;}@@ -6218,6 +6756,16 @@color: var(--muted);font-family: ui-monospace, SFMono-Regular, Menlo, monospace;}+ /* VC-34: a second, visible door into the Tier dialog, right where a+ quality choice actually gets made. */+ .tier-quick-link {+ font-size: 11px; font-weight: 500;+ color: var(--muted); text-decoration: none;+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;+ border-bottom: 1px dotted var(--border-strong);+ }+ .tier-quick-link:hover { color: var(--accent-bright); border-color: var(--accent-bright); }+ .tier-quick-link span { color: var(--text); font-weight: 600; }/* Compact quality strip — looks like the mode bar but tighter, 4 cols.Each chip carries a name on top of an optional secondary spec. */.quality-strip {@@ -6321,7 +6869,7 @@font-weight: 700;}.quality-strip .q-chip .q-spec {- font-size: 9.5px; font-weight: 500;+ font-size: 11px; font-weight: 500;color: inherit; opacity: 0.7;font-family: ui-monospace, SFMono-Regular, Menlo, monospace;letter-spacing: 0;@@ -6345,7 +6893,7 @@display: flex; flex-direction: column; gap: 4px;}.mini-fields .mf-label {- font-size: 10px; font-weight: 600;+ font-size: 11px; font-weight: 600;color: var(--muted);text-transform: uppercase; letter-spacing: 0.08em;display: inline-flex; align-items: baseline; gap: 6px;@@ -6354,7 +6902,7 @@constraint inline (e.g. "8k+1", "-1 = random") instead ofhiding it in a title= tooltip the user might never hover. */.mini-fields .mf-label .mf-hint {- font-size: 9.5px; font-weight: 500;+ font-size: 11px; font-weight: 500;color: var(--muted);opacity: 0.7;text-transform: none; letter-spacing: 0.02em;@@ -6424,6 +6972,34 @@gap: 8px;margin: 0;}+ /* VC-03 — the seed-locked chip. Sits between the queue strip and+ Generate/Stop so it reads as "this is what Generate will do", not a+ buried form field. The [hidden] rule has to come first and the flex+ display has to be scoped to :not([hidden]) — an unconditional+ `display:flex` here would beat the `hidden` attribute at equal+ specificity (the exact bug VC-07 found elsewhere in this file). */+ .seed-lock-chip[hidden] { display: none; }+ .seed-lock-chip:not([hidden]) {+ display: flex; align-items: center; gap: 6px;+ margin-bottom: 8px;+ padding: 5px 10px;+ background: rgba(240, 185, 64, 0.08);+ border: 1px solid rgba(240, 185, 64, 0.35);+ border-radius: var(--r-pill);+ font-size: 11px;+ color: var(--text);+ width: fit-content;+ }+ .seed-lock-chip::before {+ content: '🔒';+ font-size: 11px;+ }+ .seed-lock-clear {+ width: auto; padding: 0 4px;+ background: transparent; border: 0; color: var(--muted);+ cursor: pointer; font-size: 12px; line-height: 1;+ }+ .seed-lock-clear:hover { color: var(--danger, #f85149); }.form-action-footer .actions .primary {padding: 12px 14px;font-size: 14px; font-weight: 600;@@ -6461,12 +7037,31 @@background: rgba(47,129,247,0.06);}.form-action-footer .queue-strip .qchip-spacer { flex: 1 1 auto; }+ /* SYS-22: now a <button> (was a <span>) so it can jump to Shot Setup;+ resets the global `button { width:100%; background; border }` rule+ so it still reads as plain inline text, not a form control, with+ just a hover/focus cue to signal it's clickable. */.form-action-footer .queue-strip .qchip-derived {- font-size: 10.5px;+ width: auto;+ font-size: 11px;color: var(--muted);font-family: ui-monospace, SFMono-Regular, Menlo, monospace;padding: 4px 0;+ background: transparent;+ border: none;+ cursor: pointer;+ border-radius: var(--r-xs);}+ .form-action-footer .queue-strip .qchip-derived:hover,+ .form-action-footer .queue-strip .qchip-derived:focus-visible {+ color: var(--text);+ text-decoration: underline;+ }+ @keyframes shot-setup-jump-flash {+ 0%, 100% { box-shadow: none; }+ 30% { box-shadow: 0 0 0 3px var(--accent, #2f81f7); }+ }+ .shot-setup-jump-highlight { animation: shot-setup-jump-flash 1.2s ease-out; border-radius: 8px; }.form-action-footer .queue-strip .qchip-derived strong {color: var(--accent-bright); font-weight: 600;}@@ -6772,7 +7367,12 @@font-family: ui-monospace, SFMono-Regular, Menlo, monospace;display: inline-flex; gap: 6px;align-items: center;+ /* 4.17.0 render check: on a portrait clip the player is ~290px wide and+ each span wrapped INSIDE itself ("22 / min / ago", the lip-sync+ verdict over three lines). Wrap between the items, never inside one. */+ flex-wrap: wrap; row-gap: 2px;}+ .po-meta > span:not(.po-dot) { white-space: nowrap; }.po-meta .po-dot {width: 3px; height: 3px; border-radius: 50%;background: rgba(255,255,255,0.35);@@ -6856,6 +7456,46 @@border-color: rgba(248,81,73,0.35);}+ /* ---- Generic kebab / "More ▾" menu (VC-18/37, VC-42) ------------------+ One small popover component, reused for the clip toolbar's secondary+ actions (Sharp export, Use last frame, Open in Editor, Reveal in+ Finder) AND the LoRA row's ⋯ menu — same shape, two call sites, no+ need for two implementations. */+ .kebab-wrap { position: relative; display: inline-flex; }+ .kebab-pop {+ position: absolute; top: 100%; right: 0; margin-top: 4px;+ min-width: 190px; padding: 4px;+ background: var(--panel-2, #171a20);+ border: 1px solid rgba(255,255,255,0.12);+ border-radius: var(--r-sm);+ box-shadow: 0 10px 28px rgba(0,0,0,0.45);+ z-index: 60;+ display: none;+ }+ .kebab-pop.open { display: block; }+ .kebab-pop button {+ display: flex; align-items: center; gap: 8px;+ width: 100%; padding: 7px 10px;+ background: none; border: none; border-radius: 6px;+ color: inherit; font-size: 12.5px; text-align: left;+ cursor: pointer;+ }+ .kebab-pop button:hover { background: rgba(255,255,255,0.08); }+ .kebab-pop button.danger { color: #ff8b80; }+ .kebab-pop button.danger:hover { background: rgba(248,81,73,0.18); }+ .kebab-pop button svg { opacity: 0.85; flex: none; }+ .kebab-pop hr {+ border: none; border-top: 1px solid rgba(255,255,255,0.08); margin: 4px 2px;+ }++ /* Lightbox's own action row — same buttons, laid out under the meta line+ instead of in the main toolbar (the lightbox has no #playerOverlayActions+ of its own). Hidden for stills/audio where none of the actions apply. */+ .expand-actions {+ display: flex; gap: 8px; margin-top: 6px; flex-wrap: wrap;+ }+ .expand-actions:empty { display: none; }+/* ---- "Finish at …" split control (H3 draft outputs only) -------------Shown by _syncH3FinishAffordance() when the selected clip has a canvasabove the one it was rendered on. Two parts sharing one shell: the button@@ -6987,7 +7627,7 @@border-radius: var(--r-pill);border: 1px solid rgba(255,255,255,.24);background: rgba(8,14,35,.62);- font-size: 10.5px; font-weight: 750; letter-spacing: .1em;+ font-size: 11px; font-weight: 750; letter-spacing: .1em;box-shadow: 0 0 18px rgba(248,81,73,.14);}.live-stage-badge::before {@@ -7053,6 +7693,26 @@.live-return-chip.is-done::before {background: var(--ok, #2fbf71); box-shadow: 0 0 0 3px rgba(47,191,113,.14);}+ /* VA-17 / H3-11 — the recovery bar for a One Shot that stopped or failed+ partway. Bottom-anchored like the live-return chip, but full-width and+ two-button so "keep what's finished" reads as the headline, not a+ footnote. [hidden] declared first, same VC-07-shaped trap as the seed+ chip above. */+ .one-shot-recovery-bar[hidden] { display: none; }+ .one-shot-recovery-bar:not([hidden]) {+ position: absolute; left: 12px; right: 12px; bottom: 12px; z-index: 6;+ display: flex; align-items: center; gap: 10px;+ padding: 10px 14px;+ border-radius: var(--r-md, 10px);+ border: 1px solid rgba(240, 185, 64, 0.4);+ background: rgba(20, 16, 5, 0.82);+ backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);+ box-shadow: 0 8px 24px rgba(0,0,0,.4);+ }+ .one-shot-recovery-bar #oneShotRecoveryText {+ flex: 1 1 auto; min-width: 0; color: #f4e3b0; font-size: 12px;+ }+ .one-shot-recovery-bar button { width: auto; flex: 0 0 auto; }.live-return-chip:hover {border-color: rgba(88,166,255,.78);background: rgba(10,20,46,.9);@@ -7245,7 +7905,8 @@border-top-left-radius: inherit;border-top-right-radius: inherit;}- .car-card video,+ /* VC-31: cards were live <video> elements; now img.car-thumb covers+ both photos and the poster JPEG a video card gets. */.car-card img.car-thumb {width: 100%; aspect-ratio: 16/9; object-fit: cover;background: black; display: block;@@ -7281,7 +7942,7 @@flex: 1;width: auto;padding: 4px 6px;- font-size: 10.5px;+ font-size: 11px;font-weight: 500;background: rgba(255,255,255,0.10);border: 1px solid rgba(255,255,255,0.18);@@ -7493,7 +8154,7 @@the gallery without hovering each card), denser typography. */.car-card .info {padding: 7px 9px 8px;- font-size: 10.5px;+ font-size: 11px;display: flex; flex-direction: column; gap: 2px;}.car-card .name {@@ -7505,7 +8166,15 @@.car-card .sub {color: var(--muted);font-family: ui-monospace, SFMono-Regular, Menlo, monospace;- font-size: 10px;+ font-size: 11px;+ }+ /* VC-36: quality/mode + size chip — "Balanced · 1280×720", the third+ line VC-36 asked for beside the prompt snippet and render time. */+ .car-card .card-chip-row {+ color: var(--accent-bright, #58a6ff);+ font-size: 11px; font-weight: 600;+ letter-spacing: 0.02em;+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}/* Legacy .row-btns (still rendered by renderCarousel) is hidden infavour of .card-chrome — but kept structurally so any external@@ -7515,21 +8184,22 @@display: none;}.empty-msg {+ display: flex; flex-direction: column; align-items: center; gap: 10px;color: var(--muted); font-size: 13px;padding: 28px 16px;text-align: center; width: 100%;grid-column: 1 / -1;}- .empty-msg::before {- content: '';- display: block;+ /* VC-40: was a plain glowing blue dot (no motion, but blue + glow ++ alone above "No outputs yet" reads as a stuck spinner). Replaced+ with a real icon chosen per view (queue.js renderCarousel) so it+ reads as empty, not loading. */+ .empty-msg-icon {width: 28px; height: 28px;- margin: 0 auto 10px;- border-radius: 50%;- background: var(--accent-dim);- box-shadow: 0 0 12px rgba(47,129,247,0.18);+ color: var(--muted); opacity: 0.55;}+/* ===== BOTTOM TABBED PANE — REDESIGN Y2.001 =====Reads as one cohesive footer rather than a bolted-on strip.Live-dot in the leading slot communicates worker status at a@@ -7617,7 +8287,7 @@color: #fff;padding: 1px 6px;border-radius: var(--r-pill);- font-size: 10px; font-weight: 700;+ font-size: 11px; font-weight: 700;min-width: 18px;text-align: center;letter-spacing: 0;@@ -7678,6 +8348,17 @@now carried only by the muted .ttl color + the live-dot turningoff, not by dimming the whole surface. */.now-card.idle .ttl { color: var(--muted); font-weight: 500; }+ /* H3-32: an idle card showed a 0% progress bar and full padding for+ nothing there is to progress — pure decoration eating space the Shot+ setup column needs at 1280-1440px. Collapses the DECORATIVE parts+ only (padding, the empty bar); "Idle" and "No job running" stay+ exactly as visible as before — nothing informative is hidden, which+ is the distinction the 2026-05-12 "remove collapse button" ruling+ drew (that one hid active-job progress and the queue; this state has+ neither to hide). */+ .now-card.idle { padding: 8px 14px; }+ .now-card.idle .progress-bar { display: none; }+ .now-card.idle .meta { margin-top: 2px; }.now-card.failed {border-color: rgba(248,81,73,0.55);background: rgba(248,81,73,0.06);@@ -7701,6 +8382,13 @@.now-card.stopped .meta {padding-right: 140px;}+ /* VC-02(c): the render in progress may be smaller than the chip promised+ — say so on the card that's on screen for the whole wait, not only in+ a log line nobody is tailing. */+ .now-card .meta .now-clamp-note {+ color: var(--warning);+ font-size: 11px;+ }/* ---- the live-preview slot -------------------------------------------A fixed 16:9 box, always the same size once a render starts, so thethumbnail's ARRIVAL causes no reflow. The card becomes a two-column@@ -7842,7 +8530,7 @@so it reads as actionable distinct from neutral chrome. */.retry-btn {padding: 2px 9px;- font-size: 10px;+ font-size: 11px;background: rgba(255, 168, 0, 0.08);border: 1px solid rgba(255, 168, 0, 0.45);color: #ffb84a;@@ -7880,7 +8568,7 @@color: var(--muted);font-weight: 600;font-family: ui-monospace, SFMono-Regular, Menlo, monospace;- font-size: 10.5px;+ font-size: 11px;min-width: 26px;}.row-list li .ttl, .row-list li .params {@@ -7891,7 +8579,7 @@font-weight: 500;}.row-list li .params {- color: var(--muted); font-size: 10.5px;+ color: var(--muted); font-size: 11px;font-family: ui-monospace, SFMono-Regular, Menlo, monospace;}.row-list li .err-inline {@@ -7904,9 +8592,17 @@color: var(--warning);font-weight: 500;}+ /* VC-02(c): the hardware-clamp note used to reach only the log. This is+ the one place in the Queue row it can sit without fighting the+ monospace params string it decorates. */+ .row-list li .params .clamp-note {+ color: var(--warning);+ font-family: inherit;+ font-weight: 500;+ }/* Status badge — solid pill, color-coded. */.row-list li .badge {- font-size: 9px;+ font-size: 11px;text-transform: uppercase;letter-spacing: 0.08em;padding: 2px 7px;@@ -7947,6 +8643,47 @@}.row-actions { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; }+ /* VC-26: queue reorder + per-row ETA + click-to-edit. Every queue row+ now carries a 5th grid cell (the reorder buttons); scoped to+ #queueList so the shared History-list rows (.row-list too) are+ byte-identical, matching the same one-extra-column idiom+ `.row-list li:has(.sb-rowtags)` above already uses for the film+ badge — queue rows just need it unconditionally, not only when a+ film tag is present. */+ #queueList li {+ grid-template-columns: auto 1fr auto auto auto;+ }+ #queueList li:has(.sb-rowtags) {+ grid-template-columns: auto 1fr auto auto auto auto;+ }+ .q-eta {+ color: var(--muted); margin-left: 6px; white-space: nowrap;+ }+ .q-reorder { display: inline-flex; gap: 1px; }+ .q-reorder button {+ width: 18px; height: 18px;+ }+ /* Reorder is not destructive — the shared .row-list button hover (red,+ meant for Remove) would read as a warning on a harmless move. */+ .q-reorder button:hover {+ color: var(--accent-bright);+ background: var(--accent-dim);+ border-color: var(--accent);+ }+ .q-reorder button svg { width: 11px; height: 11px; }+ .q-reorder-down svg { transform: rotate(180deg); }+ .q-row-editable { cursor: pointer; }+ .q-row-editable:hover {+ border-color: var(--accent);+ }+ .queue-edit-banner {+ display: flex; align-items: center; justify-content: space-between;+ gap: 10px; padding: 8px 12px; margin-bottom: 8px;+ background: var(--accent-dim); border: 1px solid var(--accent);+ border-radius: var(--r-sm); font-size: 11.5px; color: var(--text);+ }+ .queue-edit-banner-actions { display: flex; gap: 6px; flex: none; }+/* Recent-tab type filter — chip strip matching the stage-outputsfilter so all three filter rows in the app share one language. */.row-list-filter {@@ -8071,6 +8808,61 @@background: rgba(0,0,0,0.55); border-radius: 8px;color: var(--fg, #d8e0ee); font-size: 12px;}+ /* ---- Crop-preview overlay (VC-29 / H3-01 / VA-02) -------------------+ Positioned in PIXELS by JS against the <img>'s own rendered box+ (queue.js _renderCropOverlay) — not inset:0 — because .picker-preview+ is letterboxed inside .picker-drop at most aspect ratios. Everything+ INSIDE the overlay is then plain percentages of that box. */+ .crop-overlay {+ position: absolute;+ touch-action: none;+ z-index: 2;+ border-radius: 8px;+ overflow: hidden;+ }+ .crop-overlay.crop-axis-y { cursor: ns-resize; }+ .crop-overlay.crop-axis-x { cursor: ew-resize; }+ .crop-mask {+ position: absolute;+ background: rgba(0,0,0,0.55);+ pointer-events: none;+ }+ .crop-window {+ position: absolute;+ border: 2px solid var(--accent-bright, #7e98ff);+ box-shadow: 0 0 0 1px rgba(0,0,0,0.4);+ pointer-events: none;+ }+ .crop-overlay-warn .crop-window { border-color: var(--warning, #d29922); }+ .crop-warn {+ position: absolute;+ left: 50%; bottom: 6px; transform: translateX(-50%);+ background: rgba(0,0,0,0.72);+ color: var(--warning, #d29922);+ font-size: 11px; font-weight: 600;+ padding: 3px 8px; border-radius: 999px;+ white-space: nowrap;+ pointer-events: none;+ }+ .crop-overlay-controls {+ display: flex; gap: 6px; margin-top: 6px;+ }+ .crop-quick-btn {+ flex: 1;+ font-size: 11px;+ padding: 4px 6px;+ border-radius: 6px;+ border: 1px solid var(--border, #2a3140);+ background: rgba(255,255,255,0.03);+ color: var(--muted);+ cursor: pointer;+ }+ .crop-quick-btn:hover { border-color: var(--accent, #5a7cff); color: var(--fg, #d8e0ee); }+ .crop-quick-btn.active {+ border-color: var(--accent-bright, #7e98ff);+ color: var(--fg, #d8e0ee);+ background: rgba(90,124,255,0.12);+ }.picker-recent { margin-top: 8px; }.picker-recent-label {font-size: 11px; color: var(--muted); margin-bottom: 4px;@@ -8314,7 +9106,7 @@min-width: 0;}.lora-row .lora-name .badge {- display: inline-block; font-size: 9px; font-weight: 600;+ display: inline-block; font-size: 11px; font-weight: 600;letter-spacing: 0.04em; text-transform: uppercase;padding: 1px 5px; border-radius: 999px; margin-left: 6px;border: 1px solid var(--accent); color: var(--accent-bright);@@ -8329,7 +9121,7 @@background: rgba(89, 200, 130, 0.10);}.lora-row .lora-name-meta {- font-size: 10px; color: var(--muted); margin-top: 1px;+ font-size: 11px; color: var(--muted); margin-top: 1px;font-family: ui-monospace, SFMono-Regular, Menlo, monospace;overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}@@ -8387,7 +9179,7 @@padding-top: 7px;}.lora-row .lora-strength-row label {- font-size: 10px; text-transform: uppercase; letter-spacing: 0.04em;+ font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em;color: var(--muted); width: 52px; flex: none;}/* Slider needs the same chrome reset as .range-strip — the generic@@ -8420,7 +9212,7 @@}.lora-row .trigger-chip {font-family: ui-monospace, SFMono-Regular, Menlo, monospace;- font-size: 10px; padding: 2px 7px; border-radius: 999px;+ font-size: 11px; padding: 2px 7px; border-radius: 999px;background: rgba(255,255,255,0.04);border: 1px solid var(--border); color: var(--text);cursor: pointer; user-select: none;@@ -8546,7 +9338,7 @@background: linear-gradient(135deg, #5b6cd1 0%, #8a4fc8 100%);}.chars-avatar-chip .chars-avatar-name {- font-size: 10.5px; font-weight: 500;+ font-size: 11px; font-weight: 500;color: var(--muted);line-height: 1.1;max-width: 56px;@@ -8597,7 +9389,7 @@.chars-strip-active .chars-inline-strength {margin-left: auto;display: inline-flex; align-items: center; gap: 6px;- font-size: 10px; color: var(--muted);+ font-size: 11px; color: var(--muted);}.chars-strip-active .chars-inline-strength input[type="range"] {width: 96px;@@ -8618,7 +9410,7 @@border: 1px solid var(--ph-border-soft);border-radius: 4px;padding: 1px 6px;- font-size: 10px; font-family: var(--ph-font-mono);+ font-size: 11px; font-family: var(--ph-font-mono);color: var(--muted); cursor: pointer;white-space: nowrap;}@@ -8639,7 +9431,7 @@}.chars-strip-active .chars-split-line {display: flex; align-items: center; gap: 6px;- font-size: 10px; color: var(--muted);+ font-size: 11px; color: var(--muted);}.chars-strip-active .chars-split-line > span:first-child {min-width: 34px;@@ -8926,7 +9718,7 @@}.chars-chip .chars-trigger {font-family: ui-monospace, SFMono-Regular, Menlo, monospace;- font-size: 10px; color: var(--muted);+ font-size: 11px; color: var(--muted);line-height: 1.2;margin-top: 1px;}@@ -8935,7 +9727,7 @@margin-left: 4px;}.chars-chip .chars-badge {- font-size: 9px; font-weight: 600; letter-spacing: 0.04em;+ font-size: 11px; font-weight: 600; letter-spacing: 0.04em;text-transform: uppercase;padding: 1px 5px; border-radius: 999px;border: 1px solid currentColor;@@ -8958,7 +9750,7 @@}.chars-strength-row.show { display: flex; }.chars-strength-row label {- font-size: 10px; text-transform: uppercase; letter-spacing: 0.04em;+ font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em;color: var(--muted); width: 70px; flex: none;}.chars-strength-row input[type="range"] {@@ -9019,11 +9811,11 @@display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;}.civitai-card .meta {- font-size: 10px; color: var(--muted);+ font-size: 11px; color: var(--muted);display: flex; gap: 10px; flex-wrap: wrap;}.civitai-card .nsfw-badge {- display: inline-block; font-size: 9px; font-weight: 700;+ display: inline-block; font-size: 11px; font-weight: 700;letter-spacing: 0.05em; padding: 1px 6px; border-radius: 999px;background: rgba(248,81,73,0.15); border: 1px solid var(--danger, #f85149);color: var(--danger, #f85149);@@ -9131,7 +9923,7 @@}.preset-card .preset-spec {font-family: ui-monospace, SFMono-Regular, Menlo, monospace;- font-size: 10px; color: var(--accent-bright);+ font-size: 11px; color: var(--accent-bright);margin-top: 4px; letter-spacing: 0.02em;}.settings-section { margin-top: 14px; }@@ -9193,7 +9985,7 @@margin-bottom: 4px;}.token-row .token-status {- font-size: 10px; font-weight: 600;+ font-size: 11px; font-weight: 600;padding: 1px 7px; border-radius: 999px;border: 1px solid var(--border); color: var(--muted);letter-spacing: 0.05em; text-transform: uppercase;@@ -9231,6 +10023,31 @@.settings-status { color: var(--muted); font-size: 11px; flex: 1; align-self: center; }.settings-status.ok { color: var(--success, #3fb950); }.settings-status.err { color: var(--danger, #f85149); }+ /* SYS-32: the circuit-breaker pause reason, shown above Generate.+ Caught live (browser check, not just source review): a bare class+ rule with `display: flex` beats the UA stylesheet's `[hidden] {+ display: none }` at equal specificity, whichever is LATER in the+ cascade — so breakerNotice.hidden = true left it visibly flex'd+ anyway. This is the exact bug class the review's own VC-07/H3-02+ findings are about ("CSS lets hidden controls show"), and this+ codebase already has the fix pattern one rule away+ ([data-spicy-only][hidden] { display: none !important; }) —+ applied the same way here. */+ .breaker-notice[hidden] { display: none !important; }+ .breaker-notice {+ display: flex; align-items: center; gap: 8px;+ margin: 0 0 10px; padding: 8px 12px;+ background: rgba(210, 153, 34, 0.1);+ border: 1px solid rgba(210, 153, 34, 0.4);+ border-radius: 8px;+ font-size: 12px; color: #f0d78c;+ }+ .breaker-notice .ph { width: 15px; height: 15px; flex-shrink: 0; color: #d29922; }+ .breaker-notice span#breakerNoticeText { flex: 1; min-width: 0; line-height: 1.4; }+ .breaker-notice button { flex-shrink: 0; }+ /* SYS-10b: #trainStatus had no rule at all -- a summary naming skipped+ or failed files read identically to routine "N images ready" text. */+ #trainStatus.train-status-warn { color: #d29922; }button.primary-btn {width: auto;background: var(--accent); color: white; border: 1px solid var(--accent);@@ -9282,9 +10099,9 @@}.phos-toast {pointer-events: auto;- display: inline-flex; align-items: center; gap: 10px;- min-width: 260px; max-width: 480px;- padding: 10px 16px;+ display: flex; align-items: flex-start; gap: 10px;+ min-width: 260px; max-width: 560px;+ padding: 10px 12px 10px 16px;background: rgba(20, 26, 50, 0.94);border: 1px solid var(--border-strong);border-radius: 10px;@@ -9296,15 +10113,38 @@animation: phos-toast-in 200ms cubic-bezier(.2,.8,.2,1);}.phos-toast.is-leaving { animation: phos-toast-out 180ms ease-in forwards; }- .phos-toast .ph { width: 16px; height: 16px; flex-shrink: 0; opacity: 0.85; }+ .phos-toast .ph { width: 16px; height: 16px; flex-shrink: 0; opacity: 0.85; margin-top: 2px; }+ /* SYS-09: a single-line, ellipsis-truncated toast hid the actionable+ part of longer messages (20+ literals over 70 chars were clipped).+ Wrap up to 3 lines instead of cutting the text — a toast that grows+ one line taller is still fully readable; a toast that eats its own+ words is not. */.phos-toast .phos-toast-msg {flex: 1; min-width: 0;- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ overflow: hidden; white-space: normal; line-height: 1.4;+ display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical;+ }+ .phos-toast .phos-toast-close {+ /* Always the last item, after FILM-03's ×N repeat counter. */+ order: 99;+ flex-shrink: 0; align-self: flex-start;+ background: none; border: none; color: var(--muted);+ font-size: 16px; line-height: 1; padding: 2px 4px; margin: -2px -4px 0 0;+ cursor: pointer;}+ .phos-toast .phos-toast-close:hover { color: var(--text); }.phos-toast.phos-toast-success { border-color: rgba(63, 185, 80, 0.45); }.phos-toast.phos-toast-success .ph { color: var(--success); opacity: 1; }+ .phos-toast.phos-toast-warning { border-color: rgba(210, 153, 34, 0.5); }+ .phos-toast.phos-toast-warning .ph { color: #d29922; opacity: 1; }.phos-toast.phos-toast-danger { border-color: rgba(248, 81, 73, 0.45); }.phos-toast.phos-toast-danger .ph { color: var(--danger); opacity: 1; }+ /* FILM-03: a repeated refusal bumps this instead of stacking a copy. */+ .phos-toast .phos-toast-count {+ flex: 0 0 auto; font-variant-numeric: tabular-nums; font-size: 11px;+ color: var(--muted); background: rgba(255, 255, 255, 0.08);+ border-radius: 999px; padding: 1px 7px;+ }/* Models modal — opened by the header `models` pill. Layered on topof everything; the form/log keep working underneath while a@@ -9338,7 +10178,19 @@.models-list li .icon { font-size: 18px; line-height: 1; text-align: center; }.models-list li .meta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }.models-list li .meta .ttl { font-weight: 500; font-size: 13px; }- .models-list li .meta .sub { font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ /* SYS-17: this truncated with an ellipsis, so a row's key fact (e.g.+ "Needed to TRAIN a character...") was routinely the part cut off. */+ .models-list li .meta .sub { font-size: 11px; color: var(--muted); white-space: normal; line-height: 1.4; }+ /* SYS-42: the repo id + local path moved behind this disclosure so the+ row's one visible line is the outcome (what it unlocks / size /+ ready), not `dgrauet/ltx-2.3-mlx-q4 -> mlx_models/ltx-2.3-mlx-q4`. */+ .models-list li .model-row-details { margin-top: 2px; }+ .models-list li .model-row-details summary {+ font-size: 11px; color: var(--accent-bright); cursor: pointer;+ list-style: none; width: fit-content;+ }+ .models-list li .model-row-details summary::-webkit-details-marker { display: none; }+ .models-list li .model-row-details[open] summary { margin-bottom: 2px; }.models-list li .progress {font-size: 11px; color: var(--muted); margin-top: 4px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace;max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;@@ -9758,7 +10610,7 @@body > header .eng-seg.inert:hover { background: transparent; color: var(--muted); }body > header .eng-badge {font-family: var(--ph-font-mono);- font-size: 9.5px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase;+ font-size: 11px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase;padding: 2px 6px; border-radius: 5px; margin-left: -2px;color: var(--muted);background: rgba(140, 160, 220, 0.08);@@ -9769,7 +10621,7 @@is derived from the ACTIVE model version, so it reads 2.5 here and 2.3for a user pinned back with LTX_MODEL_VERSION=ltx23. */body > header .eng-seg-gen {- font-size: 10px; font-weight: 600; letter-spacing: .3px;+ font-size: 11px; font-weight: 600; letter-spacing: .3px;color: var(--muted); margin-left: 5px; font-family: var(--ph-font-mono);}/* An offer (download / repair) is worth the engine's own colour; a plain@@ -10048,7 +10900,7 @@max-width: calc(100% - 36px);}.workflow-tabs button {- /* Override the global `button { width: 100% }` rule. Without+ /* Override the global button rule (width 100%) rule. Withoutwidth:auto each tab stretches to fill the form-pane width, soManual + Agentic Flows + Train all rendered at ~306px each andthe latter two overflowed the visible nav pill off-screen —@@ -10091,7 +10943,7 @@.workflow-tabs .new-badge {margin-left: 6px;padding: 1px 5px;- font-size: 9px; font-weight: 600;+ font-size: 11px; font-weight: 600;font-family: var(--ph-font-mono);letter-spacing: 0.06em;background: rgba(47, 129, 247, 0.12);@@ -10107,9 +10959,18 @@top-left corner, set by their own margin above. */.form-pane > #genForm { padding: 0 18px; }.form-pane > #modelsInline { margin: 0 18px 14px; }+ /* SYS-23: .form-pane's own padding was zeroed out (below) and moved+ onto individual direct children -- #genForm (Video) got it back,+ but #studioSection (Images) and #trainSection (Train) never did,+ so their ENGINE/ASPECT/CANDIDATES/SEED fields and the Train sticky+ bar rendered flush against the pane's left edge at x=0. Same fix+ for #firstRunCard (new this pass) so it doesn't join the list. */+ .form-pane > #studioSection { padding: 0 18px; }+ .form-pane > #trainSection { padding: 0 18px; }+ #genForm > #firstRunCard { margin: 0 18px 14px; }/* h2 section labels — mono uppercase, Linear's signature. */#genForm h2 {- font-size: 10.5px;+ font-size: 11px;font-family: var(--ph-font-mono);letter-spacing: 0.08em;color: var(--ph-text-faint);@@ -10160,7 +11021,7 @@border: none;}.pill-btn .sub {- font-size: 10.5px;+ font-size: 11px;font-family: var(--ph-font-mono);color: var(--ph-text-faint);letter-spacing: 0;@@ -10196,7 +11057,7 @@content: 'RECOMMENDED';position: absolute;top: 9px; right: 10px;- font-size: 9px;+ font-size: 11px;font-family: var(--ph-font-mono);font-weight: 600;padding: 2px 6px;@@ -10222,7 +11083,7 @@color: var(--muted);}.pill-quality .ql-tier {- font-size: 9.5px;+ font-size: 11px;font-family: var(--ph-font-mono);color: var(--ph-text-faint);margin-top: 6px;@@ -10461,13 +11322,13 @@.h3-winlist .h3-win-label {display: flex; align-items: baseline; gap: 6px;margin: 0 0 4px 2px;- font-size: 10px; font-weight: 600;+ font-size: 11px; font-weight: 600;letter-spacing: 0.08em; text-transform: uppercase;color: var(--muted);}.h3-winlist .h3-win-span {font-weight: 400; letter-spacing: 0; text-transform: none;- font-size: 10px; opacity: 0.7;+ font-size: 11px; opacity: 0.7;}/* Two lines is the right size for a beat: enough to see the whole line,small enough that three of them don't push Speed off the screen. */@@ -10480,7 +11341,7 @@width: 15px; height: 15px; flex: 0 0 auto;padding: 0; line-height: 1;display: inline-flex; align-items: center; justify-content: center;- font-size: 10px; font-weight: 700;+ font-size: 11px; font-weight: 700;border-radius: 50%;border: 1px solid var(--border);background: transparent; color: var(--muted);@@ -10511,7 +11372,7 @@.sb-still { position: relative; margin: 6px 0 4px; border-radius: 8px; overflow: hidden;background: var(--bg-2, #111); border: 1px solid var(--border); }.sb-still img { display: block; width: 100%; max-height: 120px; object-fit: cover; cursor: zoom-in; }-.sb-still-tag { position: absolute; left: 6px; bottom: 6px; font-size: 10px; letter-spacing: .04em;+.sb-still-tag { position: absolute; left: 6px; bottom: 6px; font-size: 11px; letter-spacing: .04em;text-transform: uppercase; padding: 2px 6px; border-radius: 999px; background: rgba(0,0,0,.6); color: #fff; }.sb-still-failed { padding: 8px; }.sb-still-failed .sb-still-tag { position: static; background: color-mix(in srgb, var(--warning) 18%, transparent); color: var(--warning); }@@ -10522,12 +11383,34 @@.lora-guide { margin: 8px 0 2px; padding: 8px 10px; border-radius: 8px; background: var(--bg-2, #111);border: 1px solid var(--border); font-size: var(--fs-sm, 12px); line-height: 1.45; color: var(--muted); }.lora-guide-actions { display: flex; gap: 8px; align-items: center; margin-top: 6px; }+/* H3-33: flex's default min-width:auto let this button shrink below its own+ text width whenever the sibling hint span wanted more room, wrapping+ "Write a guide" onto three lines. Keep the button at its natural single-+ line size and let the descriptive span (already the flexible one) give+ ground instead. */+.lora-guide-actions .ghost-btn { flex-shrink: 0; white-space: nowrap; }.sb-still.is-pending { padding: 10px 8px; display: flex; align-items: center; gap: 8px; }.sb-still.is-pending .sb-still-tag { position: static; background: color-mix(in srgb, var(--accent) 18%, transparent); color: var(--accent-bright, var(--accent)); }.sb-still-spin { width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--border); border-top-color: var(--accent); animation: sbStillSpin 1s linear infinite; }@keyframes sbStillSpin { to { transform: rotate(360deg); } }.sb-still-redo { position: absolute; right: 6px; top: 6px; }+/* FILM-46: "Stills first" approve step. The Approve button takes the+ top-right corner New still normally has; New still moves down a row so+ the two never overlap. */+.sb-still-awaiting .sb-still-approve { position: absolute; right: 6px; top: 6px; }+.sb-still-awaiting .sb-still-redo { position: absolute; right: 6px; top: 32px; }+.sb-still-awaiting .sb-still-tag {+ background: color-mix(in srgb, var(--accent) 25%, transparent);+ color: var(--accent-bright, var(--accent));+}+.sb-stills-banner {+ display: flex; align-items: center; justify-content: space-between; gap: 10px;+ margin: 8px 0; padding: 8px 12px; border-radius: var(--r-sm, 8px);+ background: color-mix(in srgb, var(--accent) 12%, transparent);+ border: 1px solid var(--accent); font-size: 12.5px;+}+.sb-stills-banner[hidden] { display: none !important; }.sb-flag { display: inline-flex; align-items: center; gap: 4px; font-size: var(--fs-sm, 12px); padding: 2px 8px; border-radius: 999px;background: color-mix(in srgb, var(--accent) 14%, transparent); color: var(--accent-bright, var(--accent)); margin-left: 6px; }.ghost-btn.small { padding: 3px 9px; font-size: var(--fs-sm, 12px); }@@ -10631,7 +11514,7 @@ body[data-workflow="oneshot"] #trainSection,body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }/* The label row, as the quick-settings cards draw it: name left, meta right. */.os-card .qs-label { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 6px; min-width: 0; }-.os-card .qs-label .qs-name { flex: 0 0 auto; font-size: 10px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; white-space: nowrap; }+.os-card .qs-label .qs-name { flex: 0 0 auto; font-size: 11px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; white-space: nowrap; }.os-card .qs-label .qs-meta { min-width: 0; font-size: 11px; color: var(--muted); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; text-align: right; white-space: normal; }#oneshotSectionTab { display: grid; gap: 10px; min-width: 0; max-width: 100%; }/* The same side padding the video form gets, so the cards and the sticky@@ -10688,6 +11571,13 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }.os-part.mid { color: #d29922; border-color: rgba(210, 153, 34, 0.5); }.os-part.bad { color: #f85149; border-color: rgba(248, 81, 73, 0.5); }.os-part.quiet { color: var(--muted); }+/* VA-14: the player overlay's lip-sync verdict chip, same colours as the+ One Shot part pills above (osVerdict) so both surfaces read as one+ feature — plain text here (no pill/border) since it sits inline in+ playerOverlayMeta next to the kind/time/size spans. */+.po-ls-ok { color: #3fb950; }+.po-ls-mid { color: #d29922; }+.po-ls-bad { color: #f85149; }.os-log { margin: 0; white-space: pre-wrap; font-family: var(--ph-font-mono); font-size: 11px; line-height: 1.4; color: var(--muted); max-height: 9em; overflow: auto; }/* ======================================================================@@ -10948,7 +11838,7 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }color: #dfe6f7; background: rgba(255,255,255,0.08);border: 1px solid rgba(255,255,255,0.14); border-bottom-width: 2px; border-radius: 4px;}-.phos-tip-keys .phos-tip-or { color: #8b95b2; font-size: 10.5px; align-self: center; }+.phos-tip-keys .phos-tip-or { color: #8b95b2; font-size: 11px; align-self: center; }.phos-tip-body { color: #b9c3dc; margin-top: 2px; white-space: pre-line; }.phos-tip-head + .phos-tip-body:empty { display: none; }@media (prefers-reduced-motion: reduce) {@@ -11001,6 +11891,17 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }the .mode-only.show `display: block` and stack the label above the pills.State the row shape here so the class, not an inline style, owns it. */.cz-body > #aspectRow.mode-only.show { display: flex !important; align-items: center; gap: 10px; margin: 0; }+/* H3-02: #aspectRow is LTX's own Orientation row (marked data-ltx-only), and+ _engine_css() already generates a fold rule for it —+ `body:not([data-engine="ltx"]) [data-ltx-only] {display:none!important}`+ — but that rule's specificity (0,2,1) loses to the ID+class rule directly+ above (1,3,0), needed so setQuality()'s cleared inline style doesn't+ collapse the row to `.mode-only`'s plain `display:block`. Net effect: the+ row kept showing on H3, where it does nothing (H3 has its OWN Orientation+ control) and, once a portrait image auto-set H3's row, visibly disagreed+ with it. State the fold at the SAME specificity tier (an ID selector) so+ it always wins regardless of source order. */+body:not([data-engine="ltx"]) .cz-body > #aspectRow.mode-only.show { display: none !important; }/* The Quality/Length axis block (the unnamed wrapper around the strips). */.cz-body > div > .qs-label:first-child { margin-top: 0; }@@ -11107,7 +12008,7 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }#batchDetails #batchSeedsHint {margin-top: 6px;font-family: var(--ph-font-mono);- font-size: 10.5px;+ font-size: 11px;color: var(--ph-text-faint);}@@ -11133,7 +12034,7 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }display: block;margin-top: 2px;font-family: var(--ph-font-mono);- font-size: 10.5px;+ font-size: 11px;color: var(--ph-text-faint);text-transform: none;letter-spacing: 0;@@ -11602,6 +12503,10 @@ label > .ph:first-child:not(:only-child),background: var(--bg-2); color: var(--text);}.mv-pic-prompt:focus { outline: none; border-color: var(--accent); box-shadow: var(--ring); }+/* FILM-12: no role is guessed past the first picture (Singer) — a picture+ with no role chosen yet is flagged, not silently planned as Room. */+.mv-pic.needs-role { border-color: var(--accent); }+.mv-pic-warn { color: var(--accent); margin-top: 2px; }.mv-pic-x {width: 24px; height: 24px; display: grid; place-items: center;border: 1px solid var(--border); border-radius: var(--r-xs);@@ -11611,6 +12516,24 @@ label > .ph:first-child:not(:only-child),.mv-pic-x:hover { color: var(--danger); border-color: var(--danger); }.mv-pic-x .ph { width: 12px; height: 12px; }+/* VA-10: the same brief pulse `.tabs button.flash` uses (phos-tab-flash,+ defined once near the tab strip), reused here so a2vLoadParams' scroll+ lands somewhere that visibly says "this is what changed", not just a+ silent jump. */+#mvOneShotDetails.flash { animation: phos-tab-flash 1.1s ease-out; border-radius: var(--r-md, 8px); }++/* FILM-12: the "I heard no singing" review strip. One chip per phrase the+ classifier looked at; click to mark it sung. Reuses .pill-btn so it needs+ no new active-state rule, just the wrap and a tighter gap than the role+ picker (there can be a dozen of these on a real song). */+.mv-sections {+ margin: 10px 0; padding: 10px;+ border: 1px solid var(--border); border-radius: var(--r-sm);+ background: var(--panel-2);+}+.mv-section-chips { display: flex; flex-wrap: wrap; gap: 6px; }+.mv-section-chip { font-size: var(--fs-xs); padding: 4px 8px; }+/* A footer INSIDE a disclosure is not the pane's bottom bar. `.form-action-footer`is written to break out of the form-pane's own padding and stick to itsbottom edge; One shot now lives inside a `<details>` halfway down the Music@@ -11623,3 +12546,7 @@ label > .ph:first-child:not(:only-child),background: none;backdrop-filter: none; -webkit-backdrop-filter: none;}++/* FILM-39 (4.17): the SLOW flag on a clip is a button — click runs Prepare. */+.sbe-slow-flag { cursor: pointer; pointer-events: auto; }+.sbe-slow-flag:hover { color: var(--accent-bright, var(--accent)); }