Skip to content

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

release(v4.16.2): the outputs list stays on screen; honest H3 times on 36-59 GB Macs

mrbizarrod2c09a159116
diff --git a/README.md b/README.md
index f636536..2c38c40 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@
</p>
-> **Current release: v4.16.1.** **No more black bars on a 720p or 1080p export.** Hailuo H3's Draft and Standard canvases (and LTX's Standard) are close to 16:9 but not exactly, and the export used to pad the difference with black: 40 px down each side of a Draft clip at 720p. Now the picture fills the frame and a few pixels are trimmed at the edges instead; canvases far from 16:9 (square, 4:3) still get bars. 4.16.0 brought the Music Studio and more than 70 fixes. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
+> **Current release: v4.16.2.** **The outputs list stays on screen, and Hailuo H3 times are honest on 48 GB Macs.** On a 1080p screen a square or wide clip used to make the preview so tall that the outputs list (and its delete buttons) went off the bottom; the preview now scales down so the outputs header and a full row of clips always stay visible. On a 36-59 GB Mac, H3's 10 s and 15 s estimates now include the reduced-memory engine's extra time (about a third longer than on 64 GB), and say why. 4.16.1 made 720p/1080p exports fill the frame; 4.16.0 brought the Music Studio and more than 70 fixes. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
## Overview
diff --git a/VERSION b/VERSION
index 27593c8..469f283 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.16.1
+4.16.2
diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.md
index e1ef830..fd672d6 100644
--- a/docs/H3_ENGINE.md
+++ b/docs/H3_ENGINE.md
@@ -49,6 +49,21 @@ system memory the user read while rendering, not an MLX-internal number:
Consistent with the Q8 lane's 25.63 GiB run peak plus macOS and the panel, and
with the 36 GB floor leaving headroom on a 48 GB Mac.
+**Time estimates on 36-59 GB (v4.16.2).** Every H3 receipt was measured on a
+64 GB M4 Max, and until 4.16.2 the estimate only scaled it by chip. A Pinokio
+user on an M4 Pro 48 GB was told ~17 min for a 15 s Draft and waited 40+. The
+fleet (60 days to 2026-09-26, 6,587 H3 renders, wall bucket over the model's
+own estimate, one median per install) puts the reduced-RAM lane at **1.32x**
+the >=60 GB lane on chained 10/15 s lengths (29 vs 117 installs) and **1.07x**
+on single windows (43 vs 170). `_h3_ram_factor()` carries those two numbers
+(`H3_LOWRAM_FACTOR_CHAIN` / `_SINGLE`) into every H3 estimate below 60 GB, and
+chained cells there show a note: about a third longer than 64 GB, quit other
+apps, swapping can take far longer. The mechanism is not measured
+(`render_completed` has no pressure field); memory pressure inside a budget
+that leaves the Mac max(6, RAM/8) GB is the likely one. Separately, Fast is a
+one-click 180 MB adapter: until it is installed, a "Draft" render runs the
+full 8-forward sampler, about twice the Fast time.
+
---
## How it plugs in
diff --git a/docs/STATE.md b/docs/STATE.md
index 2220696..ecea467 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,3 +1,5 @@
+> **🧭 2026-09-26 — v4.16.2: the outputs pane stays on screen; H3 estimates price the 36-59 GB lane.** Two Pinokio reports on the 4.15 post. **(1) @fuschichou, 1080p:** "videos that are square or more widescreen push down the outputs pane so far that it goes out of view" — reproduced headless: `.player-surface` was `width:100%` + `aspect-ratio`, so a square clip in the ~970 px stage column of a 1920×940 page (a maximised Pinokio on 1080p) was 970 px tall and the outputs header, cards and delete buttons sat below the viewport inside an `overflow:hidden` stage; 16:9 already lost the first card row at 1366×650 and 1280×720. **Fix:** `fitStagePlayer()` (queue.js) measures the height left once the Outputs pane has its header + chrome + one full card row (stage clientHeight − other visible rows − gaps − `wrap.offsetHeight − carousel.offsetHeight` − first card) and hands it to CSS as `--player-max-h`; the surface width is `min(100%, --player-max-h × --media-ar)` so the clip scales with its own shape. `setStageAspect()/clearStageAspect()` are now the one door for `--media-aspect` + the new numeric `--media-ar` + `data-orient` (queue.js selectOutput, preview.js live stage). Wired by `initStagePlayerFit()` from main.js (ResizeObserver on the stage, the pane, its header and the music bar; re-fit after every renderCarousel); stacked (≤900 px) layouts and surfaces with no gallery (storyboard, Ideogram canvas) drop the variable and keep the 100vh fallback. A player scaled well inside its column (≥ 2×200 px free) gets `data-fit="narrow"`, which moves the action cluster beside it like portrait clips always did. **Found on the way:** a still/clip whose load event fired after another output was picked stamped ITS shape on the surface (a square photo framed 16:9 after a fast click) — `apply()` now returns when the media is detached. 16:9 on 2560×1400 is unchanged (full column). **(2) @abandonedmuse, M4 Pro 48 GB:** 15 s Draft "supposed to be 18 min, so far 43". Fleet (PostHog HogQL, 60 days, 6,587 H3 render_completed): each render's wall bucket over the model's estimate for its cell/steps/chip, median per install then over installs — <60 GB chained 1.43 (29 installs) vs ≥60 GB 1.08 (117) = **1.32×**; single windows 1.21 (43) vs 1.13 (170) = **1.07×**; lower bucket edges give 1.27/1.07; M4 Pro chained 1.43 (15 inst, 48 GB) vs 1.03 (5, 64 GB). Every H3 receipt was a 64 GB M4 Max (bf16 lane); below 60 GB H3 runs the Q8 DiT in a budget that leaves the Mac max(6, RAM/8) GB. That class's own buckets: draft_15s Fast 15/15 in 20-30 min (panel said ~17), draft_15s Best 10/10 in 40-60 min. ~17 min is the Fast price; Fast is a separate one-click 180 MB adapter, and without it a render runs Best (~2x) — the release notes say so. **Fix:** `H3_LOWRAM_FACTOR_CHAIN = 1.3`, `H3_LOWRAM_FACTOR_SINGLE = 1.07` via `_h3_ram_factor()`/`_h3_speed_factor()` in `h3_estimate_minutes`, the receipts, and the per_forward_sec/fixed_sec the browser prices pinned steps from (Face Fix stays chip-only; a `PHOSPHENE_SPEED_FACTOR` override is total and disables it). M4 Pro 48 GB draft_15s now Fast ~22 / Best ~42 min. Chained cells on 36-59 GB carry `H3_TIER_LOWRAM_CHAIN_NOTE` (shown in #h3TierNote): about a third longer than 64 GB, the time includes it, quit other apps — swapping can take far longer. The swap mechanism is NOT measured (render_completed carries no pressure field); the note says "can", not "will". Also: the Editor geometry gate booted its panel with `PHOSPHENE_NO_TELEMETRY` (read by nothing) — it now sets `PHOSPHENE_ANALYTICS_DISABLED` + `PHOSPHENE_DISABLE_VERSION_CHECK`. **Tests:** `test_outputs_layout_geometry.py` + `scripts/measure_outputs_layout.py` (stdlib CDP, 7 viewports × 16:9/1:1/9:16/21:9 stills; 4.16.1 fails at all 7 for square and at 1366×650/1280×720 for 16:9), `test_h3_lowram_estimate.py` (fleet buckets for the reporter's class, 64 GB unchanged, JS repricing consistent, note present/absent). **Codex, one pass** (codex-cli 0.155.1, read-only): P2 a song (hero: 180 px cover + Play, no shape) could be squeezed to 180 px and clip its Play button — song surfaces keep the column width and get a height between 260 px and the old 16:9 (`data-song`); P3 a non-numeric `PHOSPHENE_SPEED_FACTOR` switched the RAM factor off while the chip table ignored it — only a number overrides both. **Clean-room pass** (fresh clone, install.js code steps under a Pinokio-8.2.0-shaped env: miniforge PATH, MPS fallback + fast-math, no SSH/SSL/PYTHONPATH; booted the start.js way on :8472, weights linked because nothing here touches them) found two more, fixed: the side action cluster sized to its gap so "Upscale & Face Fix" wrapped over three lines (now max-content, labels nowrap), and with a song selected the Song card (sheet music) pushed the list of songs off a 1920×940 page (the card scrolls in the stage column; the Outputs pane's floor is `--outputs-min-h` = header + one row). **Validation:** clean room `/version` 4.16.2 not dirty, no traceback; the outputs gate run from the clean-room tree 35/35; a real song (YuE2 Final, 53 s, with score) and a real 768×768 LTX clip rendered there (codec gate PASS, yuv420p + faststart) and both surfaces screenshotted at 1920×940; a second clean-room boot with a fake `sysctl` (hw.memsize 48 GiB, Apple M4 Pro) shows H3 Draft·15s as Fast ~22 / Best ~42 min with the RAM note under the chips. Update path: a clone of 4.16.1 from a local stand-in for public main, the candidate published there, update.js's four steps run as update.js runs them → rc 0 ×4, no `error:` line, VERSION 4.16.2, `/status` integrity OK. Gates (full): 147 PASS / 4 FAIL / 1 SKIP — the four are the environmental ones every release since 4.16.0 records (assert_registry 152/17 and assert_schedules 40/5 need packs + the bizarrotrn character, test_yue2_train_voice, scripts/test_pack_release no-mirror; the last two re-checked failing identically on the 4.16.1 tree); test_storyboard_editor_ui and test_editor_layout_geometry pass. Pinokio post: covers 4.15.2-4.16.2 (none of those had been announced).
+
> **🎞 2026-09-24 — v4.16.1: 720p/1080p exports fill the frame instead of padding black bars.** Same X user as 4.15.3 (M5 Pro 48 GB, on 4.15.3), after posting H3 numbers (Draft 3 s 37 GB 2m32s, Standard 36 GB 3m53s, High 39 GB 13m27s — recorded in docs/H3_ENGINE.md as field data): "Is it a bug that black bars appear on the left and right when the resolution is set to 720p?" (H3 Image→Video from a photo). **Cause:** not the reference fit — `_h3_fit_first_frame` already cover-crops the reference onto the tier canvas — but the export pass: `compute_upscale_plan` fitted any non-16:9 source INSIDE 1280×720 and padded. H3 Draft is 640×384 (5:3) → **40 px black each side**, Standard 768×448 (12:7) → 23 px; luma-scanned on two real exports in the owner's outputs (L=40/R=40 and L=22/R=26) and reproduced with a portrait and a 16:9 reference through the real `_h3_fit_first_frame` + both filtergraphs (4.16.0 bars, 4.16.1 none). LTX had the same shape on 1280×704 (8 px top/bottom); LTX i2v otherwise snaps its canvas to the image's orientation and Balanced is exact 16:9. The 2026-08-06 entry called the pillarbox "correct — no crop, no distortion"; for a file whose job is to be 720p it wasn't, and the app already crops rather than pads elsewhere (reference fit, Extend's downscale ≤31 px). **Fix:** `EXPORT_FILL_MAX_TRIM = 0.08` — a source within 8% of the target aspect is scaled to cover + centre-cropped (`scale=…:force_original_aspect_ratio=increase,crop=W:H`); plan gains `fill`, `trim_w`, `trim_h`. 5:3→720p trims 24 px top/bottom, 12:7 13 px, 1280×704 14 px left/right, Native 7:4→1080p 8 px. Square/4:3 keep bars. The Sharp (PiperSR) script carries the same constant (a test holds them equal) and now gets the source dims. Export notes, tier blurbs, the pill sub-labels ("scale to fill"), H3/LTX log lines and webapp/docs/video.md updated. No face detection ships with the base install (cv2 is not in a fresh venv), so the crop is centred; the trims are ≤ 3.4% per edge. One Codex pass (codex-cli 0.155.1, read-only): P2 — LTX `i2v_clean_audio` pads 1280×704→1280×720 at the mux BEFORE the export, so the fill cropped a frame that already had bars and the plan lied (fixed: the mux skips its pad when the export will fill; with export off the pad stays); P3 — "no crop" still promised in two Export hints and the clip-details rows (fixed: the rows read the sidecar plan — "filled, edges trimmed" / "bars added" / "no crop"). New `test_export_fill_no_bars.py` (12; the 10 original ones all fail on 4.16.0; one encodes a real 640×384 clip through both targets and checks the edge columns/rows are not black). Not changed: storyboard film assembly still pads mixed-aspect clips on purpose (`test_storyboard_assembly` pins "bars, never crop").
> **🎼 2026-09-24 — v4.16.0: the Music Studio line goes public, with the 4.16.0 review fixes.** Codex reviewed seven flows of beta `cdca462` (install, jobs, LTX, H3, storyboard/editor, music, UI): 69 findings, fixed on three branches (`fix416-jobs` 17, `fix416-editor` 25 incl. one extra editor bug, `fix416-install` 27 + the FP16 flag; JOB-05 = INST-07), each with a test that fails before its fix. Integrated as `int-4160` on beta `33dd394` (after the 4.15.4 merge-back). **Conflicts:** only the UI-01 pair (`panel/routes_files.py`, `test_image_route_scope.py`), resolved to the 4.15.4 version (wider raster allowlist, never svg) keeping fix416-install's trash (UI-05) change; mlx_ltx_panel.py, queue.js, characters.js and image_engine.py auto-merged. **One Codex pass on the combined diff** (gpt-6-astra, high, read-only): 2×P2, both fixed — Load Params on a pre-4.15.2 a2v clip restored the legacy float 1.0 as an explicit "1" (audio guidance off on Q8; now reopens as Auto, `test_review_416_ltx.py`), and an incomplete FLAT H3 weights tree (LTX_H3_MODELS) was skipped by Install/Repair forever (now `h3_fetch_weights` in `h3_roots.sh` stops with an `error:` naming the missing parts; install_h3.js dispatch 16 chars). **Fleet fix:** "The reference image can't be read (ModuleNotFoundError)" was a half-installed engine venv (panel cannot import PIL), not a bad picture — 6 H3 i2v failures, one 4.15.2 install; `h3_reference_image_error()` now gives ENGINE_ENV_REPAIR (venv_broken). **H3 FP16 decode ON by default** after the release A/B through the panel (High 5 s Turbo, seed 42, runner 7919020): decode 90.1 → 77.4 s, peak 10.7 → 9.5 GiB, no visible difference (RGB PSNR 42 dB through the h264 exports; mean |Δ| 1.4/255). **LTX-03 verified on the GPU:** FFLF (Q8 dev, 768×384/49f) and Q4 A2V (Compact tier, 512×256/49f) with Pixar_Toon attach 576/576 modules and change the clip (PSNR vs no-LoRA 30.3 / 25.4 dB); a repeat no-LoRA A2V is bit-identical (inf), so the LoRA cache key releases the adapter. **Tests:** full root pytest in one process = the same suite-order pollution as beta/main (route tests pass alone, fail after an earlier test rebinds panel globals; beta/main shows it on test_routes/test_uploads/test_room_tone, int adds test_trash_collisions/test_version_pull_route — all pass per file); `release_gates.sh --fast` int 143/4/2 vs beta/main 119/4/2 with the identical 4 environmental FAILs (assert_registry 152/17 and assert_schedules 40/5 need packs + the bizarrotrn character, test_yue2_train_voice needs yue2 weights, scripts/test_pack_release no-mirror case). PostHog: the 403 a fixer saw was an endpoint the query key has no scope for; HogQL queries with it return 200. **Skipped-by-fast gates run separately:** test_storyboard_editor_ui 466 passed; check_output_codec PASS on the FFLF render. **From zero:** fresh clone of the release commit + install.js code steps in a Pinokio-shaped env (miniforge PATH, MPS fallback + fast-math set, no SSL/SSH/PYTHONPATH), booted the start.js way → /version 4.16.0 not dirty, UI 200, no traceback, /image refuses the settings file, a render with no weights fails naming the missing pack. **Update path:** a 4.15.4 install cloned from a local stand-in for public main, then 4.16.0 published there and update.js run → fast-forward, 4 steps rc 0, no `error:` line, VERSION 4.16.0, /status integrity OK. **INST-03:** env replaced by an empty `uv venv --seed` (boot WARNs "has a Python but no packages"); Update again → post_update rebuilt it, `import ltx_core_mlx, ltx_pipelines_mlx, mlx, mlx_arsenal` OK, boot clean; Repair (install.js code steps) rebuilds it too. **Found on the way, NOT fixed (mirror, not code):** the weights-ltx25-v1 release asset `LICENSE-LTX-2.x-Community-License.md` was overwritten on 2026-09-06 by the ic_upscale_x2 publish (34545 B, sha a6622b0e…); q4_25/q8_25/hq_25/gemma4_25 manifests expect 30938 B (4e7dd26d…), so every mirror fetch of those packs ends "1 file FAILED" + a WARN, though every weight file verifies and the pack reads ready.
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 51dad76..f66a910 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -8736,6 +8736,74 @@ def _hw_chip_family() -> str:
+# THE REDUCED-RAM LANE IS SLOWER, AND MOST SLOWER ON CHAINED LENGTHS. Every
+# number above was measured on a 64 GB M4 Max, i.e. the bf16 lane. Below
+# H3_MIN_RAM_GB (60) H3 renders on the Q8 DiT inside a memory budget that
+# leaves the Mac max(6, RAM/8) GB (h3_memory_budget), and the fleet says that
+# costs time the chip factor does not see. Reported from Pinokio (2026-09-20,
+# M4 Pro 48 GB): a 15 s Draft priced "~17 min" ran 40+ min.
+#
+# FLEET, PostHog render_completed, engine=h3, 60 days to 2026-09-26, 6,587
+# renders. Each render's wall_sec_bucket over this model's own estimate for
+# its exact cell and steps at its chip's factor, one median per install (so a
+# heavy user cannot outvote the fleet), then the median over installs:
+#
+# <60 GB (Q8 lane) >=60 GB (bf16 lane) ratio
+# chained 10/15 s 1.43 (29 installs) 1.08 (117 installs) 1.32
+# single window 1.21 (43 installs) 1.13 (170 installs) 1.07
+#
+# Taking each bucket's LOWER edge instead of its geometric middle gives 1.27
+# and 1.07 - the bucket ladder moves both bands together, so the ratio holds.
+# Same chip, M4 Pro: chained 1.43 (15 installs, 48 GB) vs 1.03 (5, 64 GB).
+# The mechanism is not measured here (render_completed carries no swap or
+# pressure field); the likely one is memory - a chained clip holds the earlier
+# windows' frames and audio while the next window denoises, inside a budget
+# that leaves a 48 GB Mac ~6 GB for macOS and everything else, so the rest of
+# the Mac is pushed into compression and swap. The factors below price what the
+# fleet sees; H3_TIER_LOWRAM_CHAIN_NOTE tells the user why and what helps.
+H3_LOWRAM_FACTOR_CHAIN = 1.3
+H3_LOWRAM_FACTOR_SINGLE = 1.07
+H3_TIER_LOWRAM_CHAIN_NOTE = (
+ "On this {ram} GB Mac, H3 runs its reduced-memory engine, and 10-15 s "
+ "clips take about a third longer than on a 64 GB Mac - the time shown "
+ "includes that. Quit other apps while it renders: if macOS runs short of "
+ "memory it starts swapping, and the render can take far longer than shown.")
+
+
+def _h3_ram_factor(windows: int, ram_gb: float | None = None) -> float:
+ """How much slower than the bf16 lane a render of `windows` chained
+ windows runs on this Mac's H3 lane (1.0 at 60 GB and up). A
+ PHOSPHENE_SPEED_FACTOR override is a TOTAL factor for a Mac the tables
+ misjudge, so it replaces this as well as the chip factor."""
+ raw = (os.environ.get("PHOSPHENE_SPEED_FACTOR") or "").strip()
+ if raw:
+ # Only an override _hw_speed_factor would actually USE replaces this
+ # one; "auto" or a typo leaves both tables in force (Codex, 4.16.2).
+ 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 >= H3_MIN_RAM_GB:
+ return 1.0
+ return H3_LOWRAM_FACTOR_CHAIN if int(windows) > 1 else H3_LOWRAM_FACTOR_SINGLE
+
+
+def _h3_speed_factor(windows: int = 1) -> float:
+ """The ONE multiplier every H3 estimate carries: this Mac's chip, and the
+ lane its RAM puts H3 on."""
+ return _hw_speed_factor("h3") * _h3_ram_factor(windows)
+
+
+def h3_lowram_chain_note(windows: int, ram_gb: float | None = None) -> str:
+ """The sentence a chained cell owes a reduced-RAM Mac, or ''."""
+ ram = float(SYSTEM_RAM_GB if ram_gb is None else ram_gb)
+ if int(windows) <= 1 or ram <= 0 or ram >= H3_MIN_RAM_GB:
+ return ""
+ return H3_TIER_LOWRAM_CHAIN_NOTE.format(ram=int(round(ram)))
+
+
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
@@ -8747,7 +8815,7 @@ def h3_estimate_minutes(w: int, h: int, window_frames: int, windows: int,
rows = _h3_packed_rows(w, h, window_frames)
per_fwd = _h3_forward_seconds(rows)
fixed = _h3_fixed_seconds(w, h, window_frames)
- return (windows * max(0, int(forwards)) * per_fwd + windows * fixed) / 60.0 * _hw_speed_factor("h3")
+ return (windows * max(0, int(forwards)) * per_fwd + windows * fixed) / 60.0 * _h3_speed_factor(windows)
def _fmt_eta(minutes: float) -> str:
@@ -9010,7 +9078,9 @@ def _build_h3_tiers() -> dict[str, dict]:
# Receipts are M4 Max wall clocks. The model above already carries
# this Mac's factor, so a receipt must carry it too or an M4 Pro is
# promised the M4 Max number exactly where a measurement exists.
- hw = _hw_speed_factor("h3")
+ # It includes the reduced-RAM lane's factor (_h3_ram_factor), so a
+ # 48 GB Mac is not promised a 64 GB Mac's chained clip either.
+ hw = _h3_speed_factor(windows)
hit = H3_MEASURED_ETA.get((q["key"], ln["key"], False))
if hit and int(hit[2]) == win_fwd:
eta_min, eta_measured = hit[0] * hw, True
@@ -9044,13 +9114,16 @@ def _build_h3_tiers() -> dict[str, dict]:
# checkbox can say what both cost together.
ff = FACE_FIX_5S_MIN.get(q["key"])
if ff:
- tristep["facefix_min"] = round(ff * hw * frames / 124.0, 2)
+ # An LTX pass: the chip factor only, not H3's RAM lane.
+ tristep["facefix_min"] = round(
+ ff * _hw_speed_factor("h3") * frames / 124.0, 2)
spec = f"{w}×{h} · {frames}f"
if windows > 1:
spec += f" · {windows}×5s"
elif ln["dense"]:
spec += " · single pass"
- notes = [n for n in (q["note"], ln["note"]) if n]
+ notes = [n for n in (q["note"], ln["note"],
+ h3_lowram_chain_note(windows)) if n]
tiers[key] = {
"key": key,
# Same "<name> · <length>" grammar the fixed tiers printed, so
diff --git a/scripts/measure_editor_layout.py b/scripts/measure_editor_layout.py
index 154a997..5c932c5 100644
--- a/scripts/measure_editor_layout.py
+++ b/scripts/measure_editor_layout.py
@@ -425,8 +425,13 @@ def start_panel(work: Path, log: Path, verbose: bool) -> tuple[subprocess.Popen,
"LTX_OUTPUT_DIR": str(work / "outputs"),
"LTX_UPLOADS_DIR": str(work / "uploads"),
# Nothing here should phone home or open a window.
+ # PHOSPHENE_NO_TELEMETRY is read by nothing; the panel's real switches
+ # are the two below, and without them a hand-run gate booted a panel
+ # that reported an app_boot to the fleet under a fresh install id.
"LTX_NO_BROWSER": "1",
"PHOSPHENE_NO_TELEMETRY": "1",
+ "PHOSPHENE_ANALYTICS_DISABLED": "1",
+ "PHOSPHENE_DISABLE_VERSION_CHECK": "1",
})
fh = log.open("wb")
proc = subprocess.Popen(
diff --git a/scripts/measure_outputs_layout.py b/scripts/measure_outputs_layout.py
new file mode 100644
index 0000000..6ade7ee
--- /dev/null
+++ b/scripts/measure_outputs_layout.py
@@ -0,0 +1,452 @@
+#!/usr/bin/env python3.11
+"""A REAL browser geometry gate for the Video tab's player + Outputs pane.
+
+WHY THIS EXISTS. A Pinokio user on a 1080p monitor (@fuschichou, 2026-09-25):
+"video generations that are square or more widescreen push down the outputs
+pane so far that it goes out of view" - the only way back to the thumbnails
+(and their delete buttons) was to make Pinokio's window narrower. The player
+was sized from the column's WIDTH (`width:100%` + `aspect-ratio`), so a square
+clip in a 1300px column asked for a 1300px-tall player on a ~950px screen, and
+even a 16:9 clip left the gallery a sliver. Nothing in the suite could see it:
+the rule that breaks and the rule that fixes are both just strings in the
+stylesheet. Only a browser that has laid the page out can tell.
+
+So this boots the panel out of THIS tree against a throwaway state directory
+with four stills in its outputs folder (16:9, 1:1, 9:16 and 21:9 - written by
+hand as PNGs so the gate needs no ffmpeg and no codec), drives a headless
+Chrome over CDP (the websocket client and process helpers are the Editor
+gate's, `scripts/measure_editor_layout.py`, loaded by path so both stay
+stdlib-only), selects each still through the app's own `selectOutput`, and
+reads, at several real screen sizes:
+
+ outputs_visible the Outputs header (filters, search) and one whole row of
+ cards - thumbnail, name and the delete button - sit inside
+ the viewport and inside the stage column
+ player_fits the player ends above the Outputs pane (no overlap)
+ aspect_kept the player keeps the clip's shape (it is scaled, never
+ stretched, and never letterboxed into a wrong-shape box)
+ fills_on_large on a big screen a 16:9 clip still spans the whole column
+ (the fix must not shrink the player where there was room)
+
+Exit codes: 0 pass, 1 a measurement FAILED, 3 no browser (the unittest skips),
+4 the harness could not get far enough to measure - never reported as a pass.
+
+ ./ltx-2-mlx/env/bin/python3.11 scripts/measure_outputs_layout.py -v
+"""
+
+from __future__ import annotations
+
+import argparse
+import importlib.util
+import json
+import os
+import shutil
+import struct
+import sys
+import tempfile
+import time
+import wave
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+
+# The owner's live panel. Nothing here may ever bind it (the Editor gate's
+# free_port refuses the same set).
+FORBIDDEN_PORTS = {8199}
+
+# (width, height) of the page itself - i.e. the browser viewport, which inside
+# Pinokio is the screen minus the OS menu bar / taskbar and Pinokio's own
+# title + tab strip. 1920x940 is a maximised Pinokio on a 1080p monitor, the
+# reporter's screen; 1366x650 the same on a 768p laptop.
+VIEWPORTS = (
+ (1920, 1080),
+ (1920, 940),
+ (1680, 950),
+ (1440, 820),
+ (1366, 650),
+ (1280, 720),
+ (2560, 1400),
+)
+LARGE = (2560, 1400)
+
+# name -> (w, h) of the still written into outputs/
+MEDIA = {
+ "wide_16x9": (1280, 720),
+ "square_1x1": (768, 768),
+ "tall_9x16": (720, 1280),
+ "ultra_21x9": (1344, 576),
+}
+
+TOL = 1.0 # px
+ASPECT_TOL = 0.02 # 2 %
+
+
+def _load_editor_gate():
+ """The Editor gate's harness (CDP client, panel/Chrome boot, kill).
+
+ Loaded by file path, not imported as a package: both scripts must run on
+ a bare standard library, and `test_script_is_stdlib_only` holds each of
+ them to that.
+ """
+ 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
+
+
+def write_png(path: Path, w: int, h: int, rgb: tuple[int, int, int]) -> None:
+ """A flat-colour RGB PNG, standard library only."""
+ row = b"\x00" + bytes(rgb) * w
+ raw = row * h
+
+ def chunk(tag: bytes, data: bytes) -> bytes:
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ png = (b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw, 6))
+ + chunk(b"IEND", b""))
+ path.write_bytes(png)
+
+
+def seed_outputs(out_dir: Path) -> dict[str, str]:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ colours = [(40, 70, 140), (140, 60, 90), (50, 120, 80), (120, 110, 40)]
+ paths = {}
+ now = time.time()
+ for i, (name, (w, h)) in enumerate(MEDIA.items()):
+ p = out_dir / f"geom_{name}.png"
+ write_png(p, w, h, colours[i % len(colours)])
+ os.utime(p, (now - i, now - i))
+ paths[name] = str(p)
+ # A SONG: a Music Studio output shows a hero (cover, title, Play), not a
+ # picture, and has no shape of its own - the one case a shape-driven
+ # player can squeeze until its own button is clipped (Codex, 4.16.2).
+ # One second of silence plus the sidecar that makes it a song.
+ song = out_dir / "geom_song.wav"
+ with wave.open(str(song), "wb") as w:
+ w.setnchannels(1); w.setsampwidth(2); w.setframerate(8000)
+ w.writeframes(b"\x00\x00" * 8000)
+ # With a score, so the Song card draws sheet music and is TALL - the card
+ # is what pushed the list of songs off a 1080p screen.
+ abc = ("X:1\nT:Gate song\nM:4/4\nL:1/8\nQ:1/4=92\nK:D\n"
+ + "V:1 name=\"Vocal\"\n" + "|DEFG ABcd|efga bagf|" * 6 + "\n"
+ + "V:2 name=\"Ins\"\n" + "|D2F2 A2d2|e2g2 b2a2|" * 6 + "\n")
+ (out_dir / "geom_song.wav.json").write_text(json.dumps(
+ {"engine": "music", "title": "Gate song", "style": "a test tone",
+ "mode": "full", "score_abc": abc}), encoding="utf-8")
+ os.utime(song, (now - 50, now - 50))
+ paths["song"] = str(song)
+ # Enough extra cards that the gallery has more than one row to scroll.
+ for j in range(8):
+ p = out_dir / f"geom_extra_{j}.png"
+ write_png(p, 640, 360, (30 + j * 12, 40, 60))
+ os.utime(p, (now - 100 - j, now - 100 - j))
+ return paths
+
+
+# The Video tab opens its gallery on the Videos filter; the gate's media are
+# stills (no codec, no ffmpeg), so it looks at All - the same cards, the same
+# player, the same `--media-aspect` path a clip takes.
+JS_READY = """
+(() => {
+ if (typeof selectOutput !== 'function') return 'selectOutput missing';
+ if (typeof setMainOutputsFilter === 'function' && mainOutputsFilter !== 'all')
+ setMainOutputsFilter('all');
+ const cards = document.querySelectorAll('#carousel .car-card');
+ if (cards.length < 4) return 'only ' + cards.length + ' cards in the gallery';
+ return 'ok';
+})()
+"""
+
+# Select one still through the app's own door and wait for the surface to take
+# its shape, then read everything off the laid-out DOM.
+JS_MEASURE = r"""
+(async () => {
+ const path = %(path)s;
+ const want = %(ratio)s;
+ const raf = () => new Promise(r => requestAnimationFrame(() => r()));
+ const settle = async () => { await raf(); await raf(); await raf(); };
+ const num = v => Math.round(v * 100) / 100;
+ const box = e => { if (!e) return null; const r = e.getBoundingClientRect();
+ 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: [] };
+ const surface = document.querySelector('.stage-pane > .player-surface');
+ if (!surface) { out.missing.push('.player-surface'); return out; }
+ const shaped = () => {
+ const asp = surface.style.getPropertyValue('--media-aspect').trim();
+ if (!asp) return false;
+ const [a, b] = asp.split('/').map(s => parseFloat(s));
+ return !!(a && b && Math.abs(a / b - want) / want < 0.01);
+ };
+ // The page's own boot selection can land after ours; re-select until the
+ // surface carries THIS still's shape (a stale shape would be measured as a
+ // pass or a failure that has nothing to do with the layout).
+ const t0 = performance.now();
+ let tries = 0;
+ while (performance.now() - t0 < 10000) {
+ if (tries++ %% 20 === 0) selectOutput(path);
+ await settle();
+ if (shaped()) break;
+ }
+ out.shaped = shaped();
+ // two more frames for fitStagePlayer's rAF, then settle the layout
+ await settle(); await settle();
+ const stage = document.querySelector('main.layout > .stage-pane')
+ || document.querySelector('.stage-pane');
+ const wrap = document.querySelector('.stage-pane > .carousel-wrap');
+ const head = wrap && wrap.querySelector('.carousel-head');
+ const car = document.getElementById('carousel');
+ const card = car && car.querySelector('.car-card');
+ const del = card && card.querySelector('.card-action-danger');
+ const name = card && card.querySelector('.info');
+ const media = surface.querySelector('.player-wrap img, .player-wrap video');
+ if (!stage) out.missing.push('.stage-pane');
+ if (!wrap) out.missing.push('.carousel-wrap');
+ if (!head) out.missing.push('.carousel-head');
+ if (!card) out.missing.push('.car-card');
+ if (!del) out.missing.push('.card-action-danger');
+ if (!media) out.missing.push('player media');
+ out.aspect_prop = surface.style.getPropertyValue('--media-aspect').trim();
+ out.vw = innerWidth; out.vh = innerHeight;
+ out.stage = box(stage); out.surface = box(surface); out.wrap = box(wrap);
+ out.head = box(head); out.carousel = box(car); out.card = box(card);
+ out.del = box(del); out.name = box(name);
+ const acts = document.getElementById('playerOverlayActions');
+ out.actions = box(acts);
+ out.fit = surface.getAttribute('data-fit');
+ out.stage_inner_w = stage ? num(stage.clientWidth
+ - parseFloat(getComputedStyle(stage).paddingLeft)
+ - parseFloat(getComputedStyle(stage).paddingRight)) : null;
+ out.stacked = !!(stage && getComputedStyle(document.querySelector('main.layout'))
+ .gridTemplateColumns.trim().split(/\s+/).length < 2);
+ return out;
+})()
+"""
+
+
+JS_SONG = r"""
+(async () => {
+ const raf = () => new Promise(r => requestAnimationFrame(() => r()));
+ const settle = async () => { for (let i = 0; i < 4; i++) await raf(); };
+ const num = v => Math.round(v * 100) / 100;
+ const box = e => { if (!e) return null; const r = e.getBoundingClientRect();
+ 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');
+ const t0 = performance.now();
+ let tries = 0;
+ while (performance.now() - t0 < 10000) {
+ if (tries++ %% 20 === 0) selectOutput(%(path)s);
+ await settle();
+ if (surface.querySelector('.song-hero-play')) break;
+ }
+ await settle(); await settle();
+ // the card fetches the score; give it a moment to draw
+ const t1 = performance.now();
+ while (performance.now() - t1 < 4000) {
+ await settle();
+ if (document.querySelector('#songCard svg')) break;
+ }
+ await settle(); await settle();
+ const play = surface.querySelector('.song-hero-play');
+ const cover = surface.querySelector('.song-hero-cover');
+ const wrap = document.querySelector('.stage-pane > .carousel-wrap');
+ const head = wrap && wrap.querySelector('.carousel-head');
+ const first = document.getElementById('carousel').firstElementChild;
+ const stage = document.querySelector('.stage-pane');
+ return { vh: innerHeight, surface: box(surface), play: box(play),
+ cover: box(cover), song: surface.hasAttribute('data-song'),
+ card: box(document.getElementById('songCard')),
+ card_has_score: !!document.querySelector('#songCard svg'),
+ head: box(head), first: box(first), stage: box(stage) };
+})()
+"""
+
+
+def check_song(tag: str, m: dict) -> list[str]:
+ f: list[str] = []
+ s, p, c = m.get("surface"), m.get("play"), m.get("cover")
+ if not (s and p and c) or not m.get("song"):
+ return [f"{tag}: the song hero never came up ({m})"]
+ for label, b in (("Play button", p), ("cover", c)):
+ if b["y"] < s["y"] - TOL or b["b"] > s["b"] + TOL:
+ f.append(f"{tag}: the song hero's {label} ({b['y']}-{b['b']}) is "
+ f"clipped by the player ({s['y']}-{s['b']})")
+ if p["b"] > m["vh"] + TOL:
+ f.append(f"{tag}: the song's Play button is below the viewport")
+ # The list of songs stays reachable on the screens people have (the
+ # smallest two viewports cannot hold a hero, a card and a list at once;
+ # there the card and list scroll).
+ if m["vh"] >= 820:
+ floor = min(m["vh"], m["stage"]["b"])
+ for label, b in (("Outputs header", m.get("head")),
+ ("first output", m.get("first"))):
+ if not b or b["h"] <= 0:
+ f.append(f"{tag}: {label} not drawn")
+ elif b["b"] > floor + TOL:
+ f.append(f"{tag}: with a song selected the {label} ends at "
+ f"{b['b']}, below the visible floor {floor}")
+ return f
+
+
+def check(tag: str, want: float, m: dict, large: bool, name: str) -> list[str]:
+ f: list[str] = []
+ if m.get("missing"):
+ return [f"{tag}: could not find {m['missing']}"]
+ if not m.get("shaped"):
+ return [f"{tag}: the player never took the still's shape "
+ f"(--media-aspect {m.get('aspect_prop')!r})"]
+ vh = m["vh"]
+ stage, surf, wrap, head = m["stage"], m["surface"], m["wrap"], m["head"]
+ card, dele = m["card"], m["del"]
+ floor = min(vh, stage["b"])
+ # 1. the Outputs header and a whole first row of cards are on screen
+ for label, b in (("outputs header", head), ("first card", card),
+ ("its delete button", dele)):
+ if b["h"] <= 0:
+ f.append(f"{tag}: {label} has no height")
+ elif b["b"] > floor + TOL:
+ f.append(f"{tag}: {label} ends at {b['b']} - below the visible "
+ f"floor {floor} (viewport {vh})")
+ # 2. the player ends above the Outputs pane
+ if surf["b"] > wrap["y"] + TOL:
+ f.append(f"{tag}: the player (bottom {surf['b']}) runs into the "
+ f"Outputs pane (top {wrap['y']})")
+ if surf["r"] > stage["r"] + TOL or surf["x"] < stage["x"] - TOL:
+ f.append(f"{tag}: the player spills sideways out of the stage column")
+ # 3. the player keeps the clip's shape
+ got = surf["w"] / surf["h"] if surf["h"] else 0
+ if not got or abs(got - want) / want > ASPECT_TOL:
+ f.append(f"{tag}: player is {surf['w']}x{surf['h']} "
+ f"(ratio {got:.3f}), the clip is {want:.3f}")
+ # 3b. a cluster moved beside the picture stays inside the page
+ a = m.get("actions")
+ if m.get("fit") == "narrow" and a and a["w"] > 0 and a["r"] > m["vw"] + TOL:
+ f.append(f"{tag}: the action buttons beside the player run off the "
+ f"right edge ({a['r']} > {m['vw']})")
+ # 4. no shrink where there is room
+ if large and name == "wide_16x9":
+ if surf["w"] < m["stage_inner_w"] - 2:
+ f.append(f"{tag}: on a large screen the 16:9 player is "
+ f"{surf['w']}px in a {m['stage_inner_w']}px column - "
+ f"it should fill it")
+ return f
+
+
+def run(verbose: bool) -> tuple[dict, int]:
+ binary = G.find_browser() # raises NoBrowser -> exit 3
+ work = Path(tempfile.mkdtemp(prefix="phos-outputs-geom-"))
+ profile = work / "chrome"
+ profile.mkdir()
+ log = work / "panel.log"
+ panel = chrome = ws = None
+ try:
+ media = seed_outputs(work / "outputs")
+ 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")
+ w0, h0 = VIEWPORTS[0]
+ cdp.call("Emulation.setDeviceMetricsOverride",
+ {"width": w0, "height": h0, "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 gallery never filled: {why}")
+
+ results: dict[str, dict] = {}
+ failures: list[str] = []
+ for vw, vh in VIEWPORTS:
+ cdp.call("Emulation.setDeviceMetricsOverride",
+ {"width": vw, "height": vh, "deviceScaleFactor": 1,
+ "mobile": False})
+ for name, (mw, mh) in MEDIA.items():
+ tag = f"{vw}x{vh}/{name}"
+ want = mw / mh
+ m = cdp.evaluate(JS_MEASURE % {"path": json.dumps(media[name]),
+ "ratio": repr(want)},
+ await_promise=True, timeout=30.0)
+ if not isinstance(m, dict):
+ raise HarnessError(f"{tag}: the page returned {m!r}")
+ results[tag] = m
+ if m.get("stacked"):
+ continue # the <=900px one-column layout scrolls
+ fl = check(tag, want, m, (vw, vh) == LARGE, name)
+ failures.extend(fl)
+ if verbose:
+ s = m.get("surface") or {}
+ c = m.get("card") or {}
+ print(f"{tag:28s} player {s.get('w')}x{s.get('h')} "
+ f"card.bottom {c.get('b')} vh {vh} "
+ f"{'FAIL' if fl else 'ok'}", file=sys.stderr)
+ tag = f"{vw}x{vh}/song"
+ m = cdp.evaluate(JS_SONG % {"path": json.dumps(media["song"])},
+ await_promise=True, timeout=30.0)
+ if not isinstance(m, dict):
+ raise HarnessError(f"{tag}: the page returned {m!r}")
+ results[tag] = m
+ fl = check_song(tag, m)
+ failures.extend(fl)
+ if verbose:
+ s_ = m.get("surface") or {}
+ print(f"{tag:28s} player {s_.get('w')}x{s_.get('h')} "
+ f"{'FAIL' if fl else 'ok'}", file=sys.stderr)
+ return ({"ok": not failures, "results": results,
+ "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",
+ help="progress on stderr; stdout stays one JSON document")
+ 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, "results": {},
+ "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/test_h3_lowram_estimate.py b/test_h3_lowram_estimate.py
new file mode 100644
index 0000000..584038c
--- /dev/null
+++ b/test_h3_lowram_estimate.py
@@ -0,0 +1,150 @@
+"""H3 time estimates on a 36-59 GB Mac price the reduced-RAM lane.
+
+THE REPORT (Pinokio, 2026-09-20). M4 Pro, 48 GB, Hailuo H3, a 15 s Draft:
+the panel said about 18 minutes, the render took 43+. Two things were wrong
+with the number and both are pinned here:
+
+ 1. Every H3 estimate was measured on a 64 GB M4 Max (the bf16 lane) and only
+ scaled by CHIP. Below 60 GB H3 runs the Q8 DiT inside a tighter memory
+ budget, and the fleet (60 days, 6,587 H3 renders, one median per install)
+ shows chained 10/15 s clips there running 1.32x what the same chip is
+ priced at on a >=60 GB Mac, single windows 1.07x.
+ 2. The same fleet shows that user's install rendering its 15 s Draft at the
+ full 9-step sampler (Best, 40-60 min bucket) the day H3 was installed,
+ while ~17 min is the FAST (3-step) price - Fast needs its one-click
+ 180 MB adapter. Best on that Mac is now priced ~42 min, Fast ~22.
+
+The fleet buckets these assertions use are the ones that Mac's class actually
+landed in (M4 Pro 48 GB, 4.15/4.16): draft_15s Fast 15/15 renders in the
+20-30 min bucket, draft_15s Best 10/10 in 40-60.
+"""
+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-lowram-eta-"))
+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 H3 table as a given Mac would at import."""
+
+ def __init__(self, ram_gb: float, chip: str):
+ self.ram_gb, self.chip = ram_gb, chip
+
+ def __enter__(self):
+ self.saved = (P.SYSTEM_RAM_GB, P._HW_CHIP_FAMILY,
+ os.environ.pop("PHOSPHENE_SPEED_FACTOR", None))
+ P.SYSTEM_RAM_GB = self.ram_gb
+ P._HW_CHIP_FAMILY = self.chip
+ return P._build_h3_tiers()
+
+ def __exit__(self, *exc):
+ P.SYSTEM_RAM_GB, P._HW_CHIP_FAMILY, env = self.saved
+ if env is not None:
+ os.environ["PHOSPHENE_SPEED_FACTOR"] = env
+
+
+class ReducedRamLanePrice(unittest.TestCase):
+ def test_the_reporters_mac_lands_in_its_fleet_bucket(self):
+ with _Mac(48.0, "M4 Pro") as t:
+ c = t["draft_15s"]
+ # Fast: 15 of 15 fleet renders at 20-30 min. 4.16.1 said ~17.
+ self.assertGreaterEqual(c["tristep_min"], 20.0)
+ self.assertLess(c["tristep_min"], 30.0)
+ # Best: 10 of 10 at 40-60 min. 4.16.1 said ~32.
+ self.assertGreaterEqual(c["eta_min"], 40.0)
+ self.assertLess(c["eta_min"], 60.0)
+
+ def test_chained_cells_carry_the_chain_factor(self):
+ with _Mac(64.0, "M4 Pro") as t64:
+ base = {k: (c["eta_min"], c.get("tristep_min")) for k, c in t64.items()}
+ with _Mac(48.0, "M4 Pro") as t48:
+ for key, c in t48.items():
+ with self.subTest(cell=key):
+ k = (P.H3_LOWRAM_FACTOR_CHAIN if c["chain_windows"] > 1
+ else P.H3_LOWRAM_FACTOR_SINGLE)
+ self.assertAlmostEqual(c["eta_min"], base[key][0] * k, delta=0.02)
+ if base[key][1] is not None:
+ self.assertAlmostEqual(c["tristep_min"], base[key][1] * k,
+ delta=0.02)
+
+ def test_sixty_gb_and_up_is_unchanged(self):
+ """The bf16 lane is what every receipt was measured on."""
+ for ram in (60.0, 64.0, 128.0):
+ with _Mac(ram, "M4 Max") as t:
+ self.assertEqual(t["standard_15s"]["eta_min"], 26.6) # receipt
+ self.assertEqual(t["draft_3s"]["eta_min"], 3.0) # receipt
+ self.assertAlmostEqual(t["draft_15s"]["tristep_min"], 8.53, delta=0.01)
+
+ def test_browser_repricing_uses_the_same_factor(self):
+ """A pinned Steps count is priced in JS from per_forward_sec and
+ fixed_sec; at Auto that sum must equal the server's own model."""
+ with _Mac(48.0, "M4 Pro") as t:
+ for key in ("draft_15s", "standard_10s", "high_15s", "draft_5s"):
+ c = t[key]
+ if c["eta_measured"]:
+ continue
+ win = c["chain_windows"]
+ fwd = max(1, c["steps"] - 1)
+ js = (win * fwd * c["per_forward_sec"] + win * c["fixed_sec"]) / 60
+ with self.subTest(cell=key):
+ self.assertAlmostEqual(js, c["eta_min"], delta=0.05)
+
+ def test_explicit_speed_override_is_total(self):
+ os.environ["PHOSPHENE_SPEED_FACTOR"] = "2.0"
+ try:
+ self.assertEqual(P._h3_ram_factor(3, ram_gb=48.0), 1.0)
+ finally:
+ del os.environ["PHOSPHENE_SPEED_FACTOR"]
+ # An override the chip table would ignore must not switch this off.
+ os.environ["PHOSPHENE_SPEED_FACTOR"] = "auto"
+ try:
+ self.assertEqual(P._h3_ram_factor(3, ram_gb=48.0), P.H3_LOWRAM_FACTOR_CHAIN)
+ finally:
+ del os.environ["PHOSPHENE_SPEED_FACTOR"]
+ self.assertEqual(P._h3_ram_factor(3, ram_gb=48.0), P.H3_LOWRAM_FACTOR_CHAIN)
+ self.assertEqual(P._h3_ram_factor(1, ram_gb=48.0), P.H3_LOWRAM_FACTOR_SINGLE)
+ self.assertEqual(P._h3_ram_factor(3, ram_gb=64.0), 1.0)
+
+
+class HonestNote(unittest.TestCase):
+ def test_chained_lengths_say_why_and_what_helps(self):
+ with _Mac(48.0, "M4 Pro") as t:
+ for key in ("draft_10s", "draft_15s", "high_15s"):
+ with self.subTest(cell=key):
+ note = t[key]["note"]
+ self.assertIn("48 GB Mac", note)
+ self.assertIn("swap", note)
+ self.assertIn("includes that", note)
+ for key in ("draft_5s", "high_3s", "standard_10s_dense"):
+ with self.subTest(cell=key):
+ self.assertNotIn("reduced-memory", t[key]["note"])
+
+ def test_no_note_where_there_is_room(self):
+ with _Mac(64.0, "M4 Max") as t:
+ self.assertNotIn("reduced-memory", t["draft_15s"]["note"])
+
+ def test_the_legacy_chain_swap_keeps_the_ram_note(self):
+ """h3_visible_tiers swaps ONE note for its legacy text by value; the
+ RAM sentence is a separate entry and has to survive that."""
+ with _Mac(48.0, "M4 Pro") as t:
+ notes = t["draft_15s"]["notes"]
+ self.assertIn(P.H3_TIER_CHAIN_NOTE, notes)
+ self.assertEqual(sum("reduced-memory" in n for n in notes), 1)
+
+ def test_note_is_ascii_safe_for_copying(self):
+ self.assertTrue(P.H3_TIER_LOWRAM_CHAIN_NOTE.isascii())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_outputs_layout_geometry.py b/test_outputs_layout_geometry.py
new file mode 100644
index 0000000..3aa9398
--- /dev/null
+++ b/test_outputs_layout_geometry.py
@@ -0,0 +1,197 @@
+"""The Video tab's player and Outputs pane, measured in a real browser.
+
+WHAT THIS GUARDS. A Pinokio user on a 1080p monitor (2026-09-25): "video
+generations that are square or more widescreen push down the outputs pane so
+far that it goes out of view" - the gallery and its delete buttons could only
+be reached by making Pinokio's window narrower. The player took the column's
+full width and its height followed the clip's shape, so a square clip in a
+~1000 px column wanted a ~1000 px player on a ~940 px page. On 4.16.1 this
+gate fails at every one of its seven screen sizes for a square clip and at
+1366x650 / 1280x720 for a 16:9 one.
+
+`scripts/measure_outputs_layout.py` boots a panel from this tree against a
+throwaway state directory with four stills (16:9, 1:1, 9:16, 21:9), drives a
+headless Chrome over CDP with the Editor gate's standard-library websocket
+client, selects each still through `selectOutput`, and reads the laid-out DOM
+at seven viewports. This file runs it and asserts on the result.
+
+NO NEW DEPENDENCY, same rule as test_editor_layout_geometry.py: the script is
+standard library only, and on a machine with no browser the measurement SKIPS
+while the shape tests still run.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import re
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+SCRIPT = ROOT / "scripts" / "measure_outputs_layout.py"
+VENV_PY = ROOT / "ltx-2-mlx" / "env" / "bin" / "python3.11"
+NO_BROWSER_EXIT = 3
+
+
+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 ScriptShape(unittest.TestCase):
+ def test_script_parses(self):
+ compile(SCRIPT.read_text(encoding="utf-8"), str(SCRIPT), "exec")
+
+ def test_script_is_stdlib_only(self):
+ """A pip dependency here would ride into every Pinokio install."""
+ tree = ast.parse(SCRIPT.read_text(encoding="utf-8"), str(SCRIPT))
+ allowed = set(sys.stdlib_module_names) | {"__future__"}
+ seen: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ seen.update(a.name.split(".")[0] for a in node.names)
+ elif isinstance(node, ast.ImportFrom):
+ self.assertFalse(node.level, "relative import")
+ if node.module:
+ seen.add(node.module.split(".")[0])
+ self.assertEqual(sorted(seen - allowed), [])
+
+ 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}")
+
+ def test_measures_the_reporters_screen(self):
+ """1920 wide with Pinokio's chrome taken off 1080 is the report."""
+ src = SCRIPT.read_text(encoding="utf-8")
+ self.assertIn("(1920, 940)", src)
+ self.assertIn("(1366, 650)", src)
+ self.assertIn('"square_1x1"', src)
+
+
+class PlayerWiring(unittest.TestCase):
+ """The pieces the browser measurement depends on, read from the source so
+ a machine with no Chrome still notices one going missing."""
+
+ def test_css_width_follows_the_fitted_height(self):
+ css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")
+ self.assertRegex(css, r"\.player-surface \{[^}]*width: min\(100%, calc\("
+ r"var\(--player-max-h")
+ self.assertIn("var(--media-ar", css)
+
+ def test_every_shape_write_goes_through_the_helper(self):
+ """A write that sets --media-aspect without --media-ar would size a
+ square clip as 16:9 wide - the helper is the one door."""
+ for name in ("queue.js", "preview.js", "stage.js", "editor.js",
+ "storyboard.js", "music.js"):
+ src = (ROOT / "webapp" / "js" / name).read_text(encoding="utf-8")
+ code = "\n".join(l for l in src.splitlines()
+ if not l.lstrip().startswith("//"))
+ hits = code.count("setProperty('--media-aspect'")
+ if name == "queue.js":
+ self.assertEqual(hits, 1, "only setStageAspect may write it")
+ else:
+ self.assertEqual(hits, 0, f"{name} writes --media-aspect "
+ f"directly - use setStageAspect")
+
+ def test_a_late_load_cannot_restamp_the_shape(self):
+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")
+ i = src.index("const apply = () => {")
+ self.assertIn("if (!media.isConnected) return;", src[i:i + 600])
+
+ def test_fitter_is_started_once_at_boot(self):
+ main = (ROOT / "webapp" / "js" / "main.js").read_text(encoding="utf-8")
+ self.assertEqual(main.count("initStagePlayerFit();"), 1)
+
+
+class OutputsLayoutGeometry(unittest.TestCase):
+ 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=400)
+ except subprocess.TimeoutExpired:
+ cls.fail_why = "the outputs geometry gate did not finish in 400s"
+ 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_gate_reports_no_failures(self):
+ self.assertEqual(self.doc.get("failures") or [], [],
+ "the player/Outputs layout is wrong:\n "
+ + "\n ".join(self.doc.get("failures") or []))
+ self.assertTrue(self.doc.get("ok"))
+ self.assertEqual(self.returncode, 0)
+
+ def test_every_case_was_measured_side_by_side(self):
+ """28 picture cases, none in the stacked layout (which scrolls on
+ purpose), plus the song hero at every viewport."""
+ res = self.doc.get("results") or {}
+ songs = {t: m for t, m in res.items() if t.endswith("/song")}
+ pics = {t: m for t, m in res.items() if not t.endswith("/song")}
+ self.assertEqual(len(pics), 28, sorted(pics))
+ self.assertEqual(len(songs), 7, sorted(songs))
+ for tag, m in songs.items():
+ with self.subTest(case=tag):
+ self.assertTrue(m.get("song"), f"{tag}: no song hero")
+ self.assertGreaterEqual(m["surface"]["h"], 244,
+ f"{tag}: hero squeezed below its cover")
+ for tag, m in pics.items():
+ with self.subTest(case=tag):
+ self.assertFalse(m.get("stacked"), f"{tag} measured stacked")
+ self.assertTrue(m.get("shaped"), f"{tag} never took its shape")
+
+ def test_square_on_the_reporters_screen(self):
+ """The report itself: 1920x940, square clip, delete button reachable."""
+ m = (self.doc.get("results") or {}).get("1920x940/square_1x1")
+ self.assertIsNotNone(m)
+ self.assertLessEqual(m["del"]["b"], m["vh"])
+ self.assertLessEqual(m["surface"]["b"], m["wrap"]["y"] + 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_stage_live_preview.py b/test_stage_live_preview.py
index 4c41d52..26dfb26 100644
--- a/test_stage_live_preview.py
+++ b/test_stage_live_preview.py
@@ -122,6 +122,11 @@ FUNCTIONS = (
"returnToLiveRender",
"_renderLiveStageFrame",
"renderLiveStage",
+ # 4.16.2: the stage's shape goes through ONE door (queue.js), which also
+ # re-fits the player to leave the Outputs pane on screen. The fit itself is
+ # a layout measurement (test_outputs_layout_geometry.py); here it is a no-op.
+ "setStageAspect",
+ "clearStageAspect",
)
@@ -129,7 +134,8 @@ def run_contract() -> dict:
if NODE is None:
raise unittest.SkipTest("node not on PATH")
source = panel_source()
- script = DOM_SHIM + "\n".join(extract_function(name, source) for name in FUNCTIONS) + r"""
+ script = DOM_SHIM + "function fitStagePlayer() {}\n" + "\n".join(
+ extract_function(name, source) for name in FUNCTIONS) + r"""
const out = {};
activePath = null; _liveStageOwnsPlayer = true;
diff --git a/webapp/js/main.js b/webapp/js/main.js
index cab37ff..7313b3e 100644
--- a/webapp/js/main.js
+++ b/webapp/js/main.js
@@ -100,3 +100,6 @@ document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.addEventListene
// The appearance is applied at boot, before anyone looks — a stored "light"
// that arrived after the first paint would flash the dark palette first.
try { if (typeof applyAppearance === 'function') applyAppearance(); } catch (e) {}
+// The player scales to leave the Outputs pane a header and a row of cards on
+// every screen (queue.js, fitStagePlayer).
+initStagePlayerFit();
diff --git a/webapp/js/preview.js b/webapp/js/preview.js
index 61550f6..d8cf648 100644
--- a/webapp/js/preview.js
+++ b/webapp/js/preview.js
@@ -142,7 +142,7 @@ function _restoreSelectedOutputAfterLive() {
<div class="ps-empty-sub">Generate something on the left and the result lands here.</div>
</div>`;
const surface = wrap.closest('.player-surface');
- if (surface) { surface.removeAttribute('data-orient'); surface.style.removeProperty('--media-aspect'); }
+ if (surface) { surface.removeAttribute('data-song'); clearStageAspect(surface); }
}
function _handoffLiveStageToOutput(path) {
@@ -196,9 +196,7 @@ function _renderLiveStageFrame(s, preview) {
// small strip inside a landscape box).
const _lw = parseInt((cur.params || {}).width, 10) || 16;
const _lh = parseInt((cur.params || {}).height, 10) || 9;
- surface.style.setProperty('--media-aspect', `${_lw} / ${_lh}`);
- if (_lh > _lw) surface.setAttribute('data-orient', 'vertical');
- else surface.removeAttribute('data-orient');
+ setStageAspect(surface, _lw, _lh);
wrap.classList.remove('empty');
wrap.classList.add('live-stage');
wrap.dataset.liveJobId = String(cur.id);
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index d897bc7..0c44114 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -3015,6 +3015,7 @@ function renderCarousel() {
el.classList.toggle('song-list', mainOutputsFilter === 'audio');
if (mainOutputsFilter === 'audio' && visible.length && typeof renderSongList === 'function') {
renderSongList(el, visible);
+ fitStagePlayer();
return;
}
if (!visible.length) {
@@ -3025,6 +3026,7 @@ function renderCarousel() {
: mainOutputsFilter === 'videos' ? 'No video outputs yet.'
: 'No outputs in this view yet.';
el.innerHTML = `<div class="empty-msg">${msg}</div>`;
+ fitStagePlayer();
return;
}
// PERF: cap rendered DOM cards. The auto-fetch (d29de9c) started
@@ -3173,6 +3175,7 @@ function renderCarousel() {
window._carThumbObserver.observe(c);
}
});
+ fitStagePlayer();
}
// Relative-time helper for the player overlay meta line. Takes the
@@ -3237,6 +3240,146 @@ function _wireStageMutePersistence(video) {
function stageMayAutoSelectOutput() {
return !activePath && !window._liveStageOwnsPlayer;
}
+
+// ---- THE PLAYER NEVER PUSHES THE OUTPUTS OFF SCREEN -------------------------
+// Reported from a 1080p monitor (Pinokio, 2026-09-25): "video generations that
+// are square or more widescreen push down the outputs pane so far that it goes
+// out of view" - the thumbnails and their delete buttons were unreachable
+// until Pinokio's window was made narrower. The player was sized from the
+// column's WIDTH (`width:100%` + `aspect-ratio`), so a square clip in a
+// ~1000 px column asked for a ~1000 px-tall player on a ~940 px page, and the
+// stage pane (overflow:hidden) cut the gallery off below it.
+//
+// The rule now: the Outputs pane always keeps its header (filters, search) and
+// one whole row of cards; the player takes what is left and SCALES DOWN inside
+// it, keeping the clip's own shape. `fitStagePlayer` measures that height off
+// the laid-out page (stage pane minus every other visible row minus the pane's
+// own chrome and first card row) and hands it to CSS as `--player-max-h`; the
+// CSS turns it into a width through `--media-ar`, so nothing is stretched.
+// Where there was already room - a 16:9 clip on a big screen - the cap is
+// larger than the clip and nothing changes. Stacked (one-column, <=900 px)
+// layouts scroll, so the variable is removed there and the CSS fallback holds.
+// `test_outputs_layout_geometry.py` measures all of this in a real browser.
+const PLAYER_MIN_H = 180; // below this the player is a postage stamp
+// A song shows a hero, not a picture: a 180 px cover in 32 px of padding with
+// the title and a Play button beside it. It has no shape of its own, so its
+// surface keeps the column's width and gets a HEIGHT: never under what the
+// hero needs, never over the 16:9 it had before (Codex review, 4.16.2).
+const SONG_HERO_MIN_H = 260;
+const PLAYER_SIDE_ACTIONS_MIN = 200; // px of free column beside the player
+
+function setStageAspect(surface, w, h) {
+ if (!surface) return;
+ if (!(w > 0) || !(h > 0)) { clearStageAspect(surface); return; }
+ surface.style.setProperty('--media-aspect', `${w} / ${h}`);
+ surface.style.setProperty('--media-ar', String(Math.round((w / h) * 10000) / 10000));
+ surface.removeAttribute('data-song'); // media with a shape is not a song hero
+ if (h > w) surface.setAttribute('data-orient', 'vertical');
+ else surface.removeAttribute('data-orient');
+ fitStagePlayer();
+}
+function clearStageAspect(surface) {
+ if (!surface) return;
+ surface.removeAttribute('data-orient');
+ surface.style.removeProperty('--media-aspect');
+ surface.style.removeProperty('--media-ar');
+ fitStagePlayer();
+}
+
+let _stageFitRaf = 0;
+function fitStagePlayer() {
+ if (_stageFitRaf) return;
+ _stageFitRaf = requestAnimationFrame(() => { _stageFitRaf = 0; _fitStagePlayerNow(); });
+}
+function _fitStagePlayerNow() {
+ const surface = document.querySelector('.stage-pane > .player-surface');
+ if (!surface) return;
+ const stage = surface.parentElement;
+ const wrap = stage.querySelector(':scope > .carousel-wrap');
+ const car = document.getElementById('carousel');
+ const setVar = (v) => {
+ const cur = surface.style.getPropertyValue('--player-max-h');
+ if (v == null) { if (cur) surface.style.removeProperty('--player-max-h'); }
+ else if (cur !== v) surface.style.setProperty('--player-max-h', v);
+ };
+ const layout = stage.parentElement;
+ const stacked = !layout || getComputedStyle(layout).gridTemplateColumns
+ .trim().split(/\s+/).length < 2;
+ // Nothing to protect (storyboard, the Ideogram canvas, the Editor) or a
+ // layout that scrolls: hand the player back to the CSS fallback.
+ if (stacked || !wrap || !car || wrap.getClientRects().length === 0
+ || surface.getClientRects().length === 0) {
+ setVar(null);
+ stage.style.removeProperty('--outputs-min-h');
+ surface.removeAttribute('data-fit');
+ return;
+ }
+ const cs = getComputedStyle(stage);
+ const gap = parseFloat(cs.rowGap) || 0;
+ let avail = stage.clientHeight - (parseFloat(cs.paddingTop) || 0)
+ - (parseFloat(cs.paddingBottom) || 0);
+ let rows = 0;
+ for (const el of stage.children) {
+ if (!el.getClientRects().length) continue; // display:none / hidden
+ const s = getComputedStyle(el);
+ if (s.position === 'absolute' || s.position === 'fixed') continue;
+ rows += 1;
+ if (el === surface || el === wrap) continue;
+ // Priced at its CONTENT height: the song card is the one row that can
+ // scroll inside itself, so if this leaves too little it is the card that
+ // shrinks (CSS), never the gallery and never the hero below its minimum.
+ avail -= Math.max(el.offsetHeight, el.scrollHeight) + (parseFloat(s.marginTop) || 0)
+ + (parseFloat(s.marginBottom) || 0);
+ }
+ avail -= gap * Math.max(0, rows - 1);
+ // The Outputs pane's own chrome (padding, border, the header row, the song
+ // bar when it is up) is everything in it that is not the scrolling grid, so
+ // it is measured the same way whether the pane is squeezed or not.
+ const chrome = wrap.offsetHeight - car.offsetHeight;
+ const first = car.firstElementChild;
+ // +4: the active ring and the hover lift draw outside the card's box.
+ const row = first ? first.offsetHeight + 4 : 150;
+ // The same number is the pane's own floor, so a row that can shrink (the
+ // song card, which scrolls) gives way before the gallery does.
+ const reserve = Math.ceil(chrome + row);
+ if (stage.style.getPropertyValue('--outputs-min-h') !== reserve + 'px') {
+ stage.style.setProperty('--outputs-min-h', reserve + 'px');
+ }
+ let cap = Math.max(PLAYER_MIN_H, Math.floor(avail - chrome - row));
+ if (surface.hasAttribute('data-song')) {
+ const natural = Math.floor(surface.parentElement.clientWidth * 9 / 16);
+ cap = Math.min(natural, Math.max(SONG_HERO_MIN_H, cap));
+ }
+ setVar(cap + 'px');
+ // A player scaled well inside its column has room beside it: the action
+ // cluster moves there (as it always has for portrait clips) instead of
+ // crowding the picture.
+ requestAnimationFrame(() => {
+ const free = stage.clientWidth - surface.offsetWidth;
+ if (free >= PLAYER_SIDE_ACTIONS_MIN * 2) surface.setAttribute('data-fit', 'narrow');
+ else surface.removeAttribute('data-fit');
+ });
+}
+let _stageFitWired = false;
+function initStagePlayerFit() {
+ if (_stageFitWired) return;
+ _stageFitWired = true;
+ const surface = document.querySelector('.stage-pane > .player-surface');
+ const stage = surface && surface.parentElement;
+ if (!stage) return;
+ if ('ResizeObserver' in window) {
+ const ro = new ResizeObserver(() => fitStagePlayer());
+ ro.observe(stage);
+ const wrap = stage.querySelector(':scope > .carousel-wrap');
+ if (wrap) ro.observe(wrap);
+ const head = wrap && wrap.querySelector('.carousel-head');
+ if (head) ro.observe(head);
+ const bar = document.getElementById('musicBar');
+ if (bar) ro.observe(bar);
+ }
+ window.addEventListener('resize', fitStagePlayer);
+ fitStagePlayer();
+}
function selectOutput(path, options) {
options = options || {};
activePath = path;
@@ -3318,6 +3461,8 @@ function selectOutput(path, options) {
// score, the words, the family. Sound starts on a play button and
// nowhere else, and it keeps going while you browse other songs.
wrap.innerHTML = songHero(o);
+ 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>`;
} else if (isPhoto) {
@@ -3356,17 +3501,20 @@ function selectOutput(path, options) {
// to height-driven sizing rather than overflowing the stage.
const surface = wrap.closest('.player-surface');
if (surface) {
- surface.removeAttribute('data-orient');
- surface.style.removeProperty('--media-aspect');
+ if (!wrap.querySelector('.song-hero')) surface.removeAttribute('data-song');
+ clearStageAspect(surface);
const media = wrap.querySelector(isPhoto ? 'img' : 'video');
if (media) {
const apply = () => {
+ // A still/clip that finished loading AFTER another output was picked
+ // is detached by then; its late load event used to stamp ITS shape
+ // on the surface now showing something else (a square photo framed
+ // 16:9 after a quick click from a wide one).
+ if (!media.isConnected) return;
const w = isPhoto ? media.naturalWidth : media.videoWidth;
const h = isPhoto ? media.naturalHeight : media.videoHeight;
if (!w || !h) return;
- surface.style.setProperty('--media-aspect', `${w} / ${h}`);
- if (h > w) surface.setAttribute('data-orient', 'vertical');
- else surface.removeAttribute('data-orient');
+ setStageAspect(surface, w, h);
};
if (isPhoto) {
if (media.complete && media.naturalWidth) apply();
@@ -5197,6 +5345,7 @@ Object.assign(globalThis, {
escapeHtml, api, _setOfflineBanner, startDeepVerify,
friendlyJobError, poll, applyPackIncompleteGate, setRecentFilter,
retryJob, renderCarousel, findOutputByPath, stageMayAutoSelectOutput,
+ setStageAspect, clearStageAspect, fitStagePlayer, initStagePlayerFit,
selectOutput, openExpandLightbox, closeExpandLightbox, phosToast,
animateActive, hide, openOutputsFolder, hideActive,
useAsExtendSource, useAsUpscaleSource, useAsUpscaleSourcePath, setUpscalePreset,
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index 5698911..9ec925d 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -6596,10 +6596,19 @@
linear-gradient(160deg, #0d1430, #0a0f24);
background-size: 22px 22px, 100% 100%;
}
+ /* WIDTH COMES FROM THE HEIGHT IT MAY HAVE. `--player-max-h` is the
+ height left once the Outputs pane has its header and one whole row of
+ cards (fitStagePlayer in queue.js measures it), `--media-ar` the clip's
+ w/h as a number; so the surface is as wide as the column OR as wide as
+ that height allows at the clip's shape, whichever is smaller, and
+ `aspect-ratio` gives it the matching height. A square or wide clip on a
+ 1080p screen no longer pushes the gallery out of view (Pinokio report,
+ 2026-09-25); a 16:9 clip on a big screen is still full width. The
+ fallback cap applies when the fitter is not running (stacked layout). */
.player-surface {
position: relative;
flex: 0 0 auto;
- width: 100%;
+ width: min(100%, calc(var(--player-max-h, calc(100vh - 340px)) * var(--media-ar, 1.7778)));
aspect-ratio: var(--media-aspect, 16 / 9);
margin: 0 auto;
border-radius: var(--r-lg);
@@ -6609,6 +6618,13 @@
box-shadow: var(--shadow-2);
display: flex;
}
+ /* A song hero has no shape of its own: full column width, and the
+ HEIGHT fitStagePlayer picked (the hero's own minimum up to the 16:9 it
+ had before). Without the variable it falls back to 16:9. */
+ .player-surface[data-song] {
+ width: 100%;
+ height: var(--player-max-h, auto);
+ }
/* Vertical / portrait media: flip to height-driven sizing so the
surface stays inside the visible stage area instead of growing
past the carousel. Height budget is tighter than landscape — we
@@ -6617,9 +6633,9 @@
520px so a 4K monitor doesn't get a giant vertical strip either. */
.player-surface[data-orient="vertical"] {
width: auto;
- height: min(520px, calc(100vh - 380px));
+ height: min(520px, var(--player-max-h, calc(100vh - 380px)));
max-width: 100%;
- max-height: min(520px, calc(100vh - 380px));
+ max-height: min(520px, var(--player-max-h, calc(100vh - 380px)));
}
.player-wrap {
flex: 1 1 auto;
@@ -6902,9 +6918,15 @@
cluster can escape its bounds; the inner .player-wrap keeps its
own overflow:hidden so the video itself still clips cleanly to
the rounded corners. Landscape clips are unchanged. */
- .player-surface[data-orient="vertical"] {
+ /* data-fit="narrow" is the same move for ANY clip the player had to
+ scale well inside its column (a square clip on a 1080p screen): the
+ cluster would otherwise cover the picture it no longer has room beside.
+ fitStagePlayer sets it only when the column has the room. */
+ .player-surface[data-orient="vertical"],
+ .player-surface[data-fit="narrow"] {
overflow: visible;
}
+ .player-surface[data-fit="narrow"] .player-overlay-actions,
.player-surface[data-orient="vertical"] .player-overlay-actions {
top: 6px;
right: auto;
@@ -6914,10 +6936,24 @@
gap: 2px;
background: rgba(8, 14, 35, 0.42);
}
+ .player-surface[data-fit="narrow"] .po-act,
.player-surface[data-orient="vertical"] .po-act {
justify-content: flex-start;
padding: 6px 10px;
}
+ /* Beside the picture the cluster is a column of full labels: it sizes to
+ its longest one instead of to the gap it starts in, and a label never
+ wraps ("Upscale & Face Fix" broke over three lines, with the split
+ button's settings half stranded beside it). */
+ .player-surface[data-fit="narrow"] .player-overlay-actions,
+ .player-surface[data-orient="vertical"] .player-overlay-actions {
+ width: max-content;
+ }
+ .player-surface[data-fit="narrow"] .po-act-label,
+ .player-surface[data-orient="vertical"] .po-act-label {
+ white-space: nowrap;
+ }
+ .player-surface[data-fit="narrow"] .po-act.po-act-danger,
.player-surface[data-orient="vertical"] .po-act.po-act-danger {
margin-top: 4px;
padding-top: 8px;
@@ -7034,7 +7070,10 @@
become visible on tall viewports. */
.carousel-wrap {
flex: 1 1 auto;
- min-height: 200px;
+ /* --outputs-min-h is the pane's header plus one full row of cards,
+ measured by fitStagePlayer; everything else in the column gives way
+ before this does. */
+ min-height: max(200px, var(--outputs-min-h, 0px));
display: flex;
flex-direction: column;
padding: 12px 14px 14px;
@@ -11416,6 +11455,10 @@ label > .ph:first-child:not(:only-child),
/* The Song card: under the player, only for songs. */
.song-card { margin: 10px 0 0; padding: 12px 14px; border: 1px solid var(--border); border-radius: var(--r-lg);
background: var(--panel); box-shadow: var(--shadow-1); }
+/* In the stage column the card is the reader between the song hero and the
+ Outputs pane: it scrolls inside itself rather than pushing the list of
+ songs off the bottom of a 1080p screen (4.16.2). */
+.stage-pane > .song-card { flex: 0 1 auto; min-height: 120px; overflow-y: auto; }
.song-card[hidden] { display: none; }
.song-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.song-title { font-size: var(--fs-lg); font-weight: 650; letter-spacing: -0.01em; }