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.15.0): Hailuo H3 goes Fast — a finished HD clip in five minutes

mrbizarrof1b2441f47bd
diff --git a/README.md b/README.md
index 02c8bf4..fea591f 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@
</p>
-> **Current release: v4.14.3.** **Songs work on every install** — the music engine refused to start under Pinokio's environment, so the first song failed on most Macs; it writes songs now. **Pasted file paths just work**: a path copied out of Finder or dragged into Terminal (quotes, `Macintosh HD`, escaped spaces, `file://`) is accepted everywhere you can paste one. A render no longer dies on a stray character in a tool's output, and when the render helper can't start, the message names the cause and what to do. **v4.14.2 — Outputs and Recent have an Audio filter** next to Videos and Photos, so your songs are one click away (thanks @cocktailpeanut). **v4.14.1 — Compose is always in Audio**: install YuE2 from right there with one click (no more hunting in the Pinokio sidebar), and H3 renders that some community LoRAs turned black now work or fail with a clear message. **v4.14.0 — Songs, faces and sound**: **Audio → Compose** writes whole songs with vocals from your lyrics and a style (YuE2 by Multimodal Art Projection, MLX port by vanch007; about real time on an M4 Max, 11 GB). **Upscale & Face Fix** sharpens faces and doubles the size of any clip in one click, from the player, Outputs, the queue or the Editor. The Editor gets **sound tracks**: A3, A4 and more, a Sound pool, and clip sound on two lanes so neighbouring shots can crossfade. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
+> **Current release: v4.15.0.** **Hailuo H3 has a Speed switch.** **Fast** runs a 3-step adapter, **Best** runs the full schedule — with **Upscale & Face Fix** after it, a finished HD clip is about **5 minutes** on an M4 Max (Draft 2.8 min + 2.5 min, 1280×768) instead of half an hour. **Room tone** puts one generated ambience bed under a whole film so cuts stop clicking. **The Editor stops rearranging itself**: Sound is a mode you choose, panels open when you ask, the Source monitor is a drop target again. **The render form is four closed sections** — Shot setup, LoRAs, After the render, Advanced — each printing what it hides (`Draft · 3s · Fast · ~2 min`), and **Batch is a section**: paste many prompts, or ask for N takes of one, each with its own seed. Fixed: a film with music over it no longer comes out with silent shots, and a crashed engine names the line of code. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
## Overview
diff --git a/ROADMAP.md b/ROADMAP.md
index 78f4246..2862ccd 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -320,6 +320,52 @@ side watchdog SIGKILLs hung helper). Quality-level work still open:
hang is now invisible; the artifact still requires the Q8/Q4
TI2VidTwoStages route above.
+### `[ ]` Long films that hold together — continuity the panel writes, not the user
+
+H3 renders about 15 s at a time, so anything longer is a chain of shots, and
+what breaks first is not the picture — it is CONTINUITY. Today a user keeps a
+long film coherent by hand: re-stating wardrobe in every chained window,
+re-naming who is in frame, and hoping the shot text they cannot see says what
+they think it says. Three concrete pieces, in order:
+
+- **Name-scoped character sheets.** A character already carries a trigger, a
+ face LoRA and a voice; let it also carry a sheet line (pronoun, age,
+ wardrobe, two physical anchors). Every shot is then given the entries for
+ ONLY the people its beat names — nobody else, so a two-hander does not drag
+ a third character's wardrobe into frame. This is our own law
+ ("wardrobe drifts before faces do") moved out of the user's hands.
+- **Show the shot text, and the balance.** The storyboard path composes what
+ each shot is actually sent and never shows it. Surface it per shot, and warn
+ when the panel's own injected continuity outweighs the user's words — on a
+ short beat an injected clause set can be most of the prompt, which is why a
+ beat sometimes "does not render what I wrote".
+- **A line that reaches the model verbatim.** One marker inside a beat whose
+ text nothing reads, scopes, reorders or drops.
+
+Prior art, read for the method and NOT copied (its licence forbids
+redistribution): the ComfyUI node `Smite79/MiniMax-H3-Longvideos`, which chains
+shots exactly this way and reports that balance every run. Its settings match
+ours already (cfg 1.0, shift 12/3, res_multistep + simple, 1 MP, 6-8 steps on a
+distill adapter = our Fast). Its one finding we did not have: **ambience must be
+mixed, never prompted** — an open audio branch on a joint model invents a voice
+for the face to lip-sync to. That is the silent-mouthing failure we have hit,
+and it is the argument for Room tone being a track and not a prompt line.
+
+### `[ ]` Evaluate the FL2VA + Ref2VA hybrid checkpoints
+
+`smhfacct/Minimax-H3-fl2va-ref2va-hybrid-models` merges the first/last-frame
+branch with the reference branch (four int8 merges, block depths 15/20/25/30 of
+49). One checkpoint that takes BOTH a first frame and reference inputs would
+unlock two things already asked for: H3 first+last frame (#83), and the native
+character-voice route — Ref2VA is the branch that accepts an audio timbre
+reference, which is the honest way to get a character's trained voice into an
+H3 render instead of converting it afterwards.
+
+Not a drop-in: int8 safetensors in the ComfyUI layout (our runner loads its own
+Q8 pack), CUDA-oriented, and a merge always costs something. The test is a
+matched A/B against our Q8 pack on likeness, motion and lip-sync — the same
+canvas, the same seeds, the same prompts — before any of it is offered.
+
## Mid term
### `[ ]` In-panel "Report bug" button
diff --git a/VERSION b/VERSION
index 453b50f..5c517bf 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.14.3
+4.15.0
diff --git a/conftest.py b/conftest.py
new file mode 100644
index 0000000..9d0953e
--- /dev/null
+++ b/conftest.py
@@ -0,0 +1,41 @@
+"""NO TEST MAY TOUCH THE PANEL SOMEBODY IS USING.
+
+2026-09-18: a full-suite run on this machine wrote
+`analytics_query_key = "phx_secret_from_the_other_panel"` and
+`civitai_api_key = "civ_from_the_other_panel"` into the LIVE
+`state/panel_settings.json` — destroying the owner's real PostHog and CivitAI
+keys — and `analytics_last_version = "9.9.9"` along with them. The test that
+did it (`test_settings_merge.py`) sets `LTX_STATE_DIR` to a temp dir at import
+time and is correct on its own: run alone it is airtight. But STATE_DIR is
+resolved ONCE, when `mlx_ltx_panel` is first imported, so in a whole-suite run
+any earlier test module that imported the panel had already fixed it to the
+real `state/` — and every "temp dir" assignment after that was decoration.
+The same trap explains `state/usage-log.jsonl.bak-fixtures` (an earlier
+session's rescue) and the suite's order-dependent failures.
+
+A conftest is imported before any test module, so this is the one place the
+sandbox can be set up in time. Everything a test could write — state, outputs,
+uploads — is pointed at a per-run temp tree unless the caller set it
+deliberately. `test_state_sandbox.py` holds the line.
+"""
+from __future__ import annotations
+
+import os
+import tempfile
+from pathlib import Path
+
+#: One tree per pytest run; the OS reaps it.
+SANDBOX = Path(tempfile.mkdtemp(prefix="phos-test-sandbox-"))
+
+for _var, _sub in (("LTX_STATE_DIR", "state"),
+ ("LTX_OUTPUT_DIR", "mlx_outputs"),
+ ("LTX_UPLOADS_DIR", "panel_uploads")):
+ if not (os.environ.get(_var) or "").strip():
+ _dir = SANDBOX / _sub
+ _dir.mkdir(parents=True, exist_ok=True)
+ os.environ[_var] = str(_dir)
+
+# A test run also has no business reporting to PostHog or phoning home for a
+# version check; both were already set per-file, inconsistently.
+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")
+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 307c263..bf77b71 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -45,6 +45,8 @@ ltx_windows.py ← PURE: the sliding-window schedule and per-window
storyboard_editor.py ← the Editor's document model: clips, overlays
(cards and titles), transitions, the mix — every
accessor the preview, render and export share
+room_tone.py ← PURE numpy: the Editor's room-tone beds (film-derived
+ or preset ambience, periodic loop, BS.1770 level)
panel_assets/
└── stats.html ← the /stats dashboard (predates webapp/; same
served-from-disk idea)
diff --git a/docs/EDITOR_TOOLBAR.md b/docs/EDITOR_TOOLBAR.md
index bfedf05..3ece0d7 100644
--- a/docs/EDITOR_TOOLBAR.md
+++ b/docs/EDITOR_TOOLBAR.md
@@ -36,6 +36,19 @@ The test that applies to anything new is not "is this related to a clip" but
**how many times an hour**. Rare, slow, or dialogue-opening stays in the rail
(Retake is the example: it starts a render).
+## 2026-09-17: icons, one row, and the panels
+
+The bar is icons only now — "the menu doesn't need to have the words on each
+one… just when you hover over it, you see an explanation" — every tooltip
+leads with the name, then the consequence, then the key (`sbePaintCbar`), and
+the words come back in the More menu and the right-click menu, where a list
+reads better than a row. The transport (play, mute, time) moved under the
+Program monitor, so the bar and the timeline's own controls (Sound mode, Snap,
+zoom, ⓘ, Keys) share ONE row, `.sbe-toolrow`, with the grab below it. The
+inspector is a panel you open (☰ / ⌘I / double-click a clip), not a fixture.
+The sound lanes no longer size themselves: Sound mode (⇧A) is the switch. See
+`webapp/docs/editor.md` §layout and §compact.
+
## Where it is
A row of its own, between the monitors and the transport, directly above the
@@ -187,6 +200,45 @@ first, with no modifier guard. The one chord every person on a Mac presses to
make their work safe cut their film in half. Gated now in
`TheEverydayGesturesThatWereMissing`.
+## 2026-09-17 (round 2): fast tooltips, the Source monitor back, real icons
+
+Owner, after using the redesign: "the tooltips on the buttons are too slow",
+"you have two empty dark spaces on the sides [of the Program monitor] … a place
+where you can drag the clips and see them … is actually necessary", "the icons
+are not very clear, are really weird, and maybe deformed", and the panel
+toggles are "a good idea but it's not clear".
+
+* **Icons.** The sprite was bare `<g>`s on a 24-unit grid used from `<svg>`s
+ with no viewBox, so a 15px box drew only the top-left 15 units of each glyph
+ — that was the deformation. Every glyph is now a `<symbol viewBox="0 0 256
+ 256">` in Phosphor's geometry (the set the rest of the panel uses): scissors
+ for split, a clip lifted out of its gap for lift, a gap closing for ripple
+ delete, Phosphor's copy / link / arrows-clockwise / speaker / speaker-slash /
+ lock / lock-open / corners-out / keyboard, a trash can with a waveform for
+ delete sound, a level line with an × for clear points, a smiley with a
+ sparkle for Face Fix, a waveform for Sound mode, sidebars for Inspector and
+ Panels, a split screen with a play mark for Source. 18px, stroke 22/256
+ (≈1.5px), set once on `.sbe-cbar-i`. The preview's mute is an icon too.
+* **View group.** Source · Inspector · Sound · Panels · Full screen are one
+ labelled segmented control in the header (`#sbeView`). Pressed = the panel is
+ showing (`aria-pressed`, accent fill); `sbeViewTip` writes a tooltip that
+ says what a click will show or hide, and the key. Labels fold below a
+ 1360px window unless the side panels are hidden.
+* **Tooltips** (`webapp/js/tips.js`). One shared element: 150 ms after the
+ pointer settles, immediately while sliding along a row (400 ms warm window),
+ on keyboard focus-visible, flipped above / clamped 8px inside the window, no
+ transition under reduced motion. Name · body · keycaps (from `data-shortcut`
+ or a trailing "(⌘I)"). The painters keep writing `title`; a button in scope
+ has it moved to `data-tip` on hover/focus and by a MutationObserver on every
+ rewrite, so the OS tooltip never shows. Scope: the Editor's icon buttons,
+ header buttons, chips, and the player's `.po-act` pills.
+* **Source monitor** is on screen by default (`phos_sbe_src`, hide with Source
+ or ×). Each monitor column is exactly its picture's width, so neither is
+ squeezed out of 16:9. It is a drop target: a pool row (`edPoolDragMove` /
+ `edPoolDragEnd`) or a shot dragged from the track (`sbeOnTrackMove` /
+ `sbeOnTrackUp`, the track restored from the snapshot, no undo step) loads
+ there; `sbeSrcDropHover` lights it.
+
## Deliberately not built
* **Copy / paste clips.** `Duplicate` covers "again, right here"; a clipboard
diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.md
index 8d16ea0..380b900 100644
--- a/docs/H3_ENGINE.md
+++ b/docs/H3_ENGINE.md
@@ -220,6 +220,62 @@ no raw-file fetch: it records the exact release-asset publication TODO and must
gain a digest-checked fetch only after the repacked asset and its output digest
exist.
+### Speed: ⚡ Fast | ✦ Best — TaoMate's 3-step adapter (2026-09-17)
+
+ONE switch above the Quality cards. **Fast** renders with TaoLiveAIGC's
+TaoMate-H3 3-step adapter on its own sigma ladder; **Best** is each shape's own
+sampler, unchanged (Draft/Standard 8 forwards, High 15, Native as tuned) and the
+only place the Steps override shows. Fast is the default once its adapter is
+installed; the choice is remembered per browser (`phos_h3_speed`). The cards'
+estimates follow the switch and the mode (T2V/I2V). Fast runs on **Draft,
+Standard and High** (5 s windows, chained too); **Native** and the dense 10 s
+single pass are not validated on 3 steps and always render Best — the switch
+says so under itself when one of them is picked.
+
+| Cell (5 s, M4 Max, char + style LoRA) | Best | Fast |
+|---|---:|---:|
+| Draft 640×384 | 6.9 min (8 fwd, full decode) | **3.0 min** I2V (panel, cold cache: 3.4) |
+| Standard 768×448 | ~9 min (8 fwd) | **4.8** I2V · **4.9** T2V |
+| High 1024×576 | 35.1 min (15 fwd) | **9.0** I2V · **8.4** T2V |
+
+- **Recipe.** TaoMate distils H3 onto points `(0, 16, 33, 49)` of the shifted
+ 50-point sigma grid (video σ `[1, .96117, .85333, 0]`, audio σ
+ `[1, .86087, .59259, 0]`) — **3 forwards**. Runner spelling:
+ `--steps 4 --sigma-subset 50:0,16,33,49 --lora <adapter>:1.0` (`--steps 4`
+ alone would re-space a 4-point grid the adapter never saw). Needs a runner
+ with `--sigma-subset` (minimax-h3-mlx `codex/h3-engine-v2` from `ccf532b`)
+ and stacking `--lora`; on an older runner the Fast half says "update H3
+ runner". Stacks with character/style LoRAs (adapter first; 416 wrapped,
+ 0 unaccounted on the validation render). Full VAE decode, never TAE.
+- **Install.** Not installed → the Fast half reads **Install (180 MB)**; one
+ click (confirm names the license) runs `POST /h3/tristep/install`: Kijai's
+ rank-resized conversion
+ `turbo-lora/minimax_h3_taomate_3step_lora_avg_rank_19_bf16.safetensors`
+ (alpha == rank, ~87 % of the full delta) from `Kijai/MiniMax-H3_comfy` @
+ `098f8c4…`, resumable (HTTP Range on the `.partial`), exact size + sha256
+ `de9663d9…` before the rename. Never re-hosted. License: MiniMax H3
+ Community License (same as H3). A full-rank runner-layout copy
+ `taomate_h3_3step_ourlayout.safetensors` in the same folder wins. The
+ official release is T2AV only; I2V is unofficial (owner-approved look).
+- **Turbo is folded in.** The old Standard | Turbo row is gone: Fast replaces
+ it (faster, and the owner's pick), and two speed controls or two adapters on
+ one render is what the switch removes. The form posts `h3_turbo=0`; the
+ server still honours `h3_turbo` from the API (Storyboard, One Shot, curl)
+ wherever Fast does not run, and drops it when Fast does. A Turbo clip's Load
+ Params / Finish maps to Fast.
+- **Job field** `h3_tristep`: `1` Fast, `0` Best, absent = default (Fast where
+ offered and installed, unless a Steps pin asks for a depth). make_job and
+ `run_h3_job_inner` both refuse it off Draft/Standard/High and never stack it
+ with Turbo.
+- **Upscale & Face Fix** sits beside Generate (same state as the checkbox under
+ Upscale); the footer line prices the pair from the cell, e.g.
+ `Draft · Fast + Face Fix ≈ 5.5 min`. Face Fix receipts: 640×384 → 2.5 min,
+ 1024×576 → ~9 min; 768×448 ~4 min is interpolated.
+- **Provenance.** Sidecar `params.h3_tristep`, and `h3.tristep` = file,
+ version, repo, revision, sha256, source repo, license, steps, forwards,
+ sigma subset, decode; plus `h3.schedule` (the sigmas the runner ran) and
+ `h3.lora_accounting`. The ⓘ modal prints a Speed row.
+
### Chained windows (v3.4.1)
Window *N*'s **last decoded frame** becomes window *N+1*'s first-frame keyframe
diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.md
index 7f4202e..5dd785e 100644
--- a/docs/RELEASE_CHECKLIST.md
+++ b/docs/RELEASE_CHECKLIST.md
@@ -8,6 +8,17 @@ have shipped broken (gated model needing a token, mflux not bundled, the missing
upscaler "mosaic", the scary pip dependency block) were invisible on a warm dev
box and only showed up from zero.
+> **Before any release, read the `phosphene-release` skill**
+> (`~/.claude/skills/phosphene-release/SKILL.md`). This file owns the **gates**;
+> that one owns the **environment** — what Pinokio injects into every app it
+> launches, where `uv`/python/ffmpeg/git come from when Pinokio starts the app
+> versus when a human does, and the "launch it the way Pinokio launches it" gate.
+> It exists because v4.14.0 shipped music broken for nearly every user: Pinokio's
+> kernel exports `PYTORCH_ENABLE_MPS_FALLBACK=1` and YuE2 refuses to construct
+> with it set, while our hand-started panel never had it. **From zero is not
+> enough on its own** — a clean room started by hand has the same wrong
+> environment this dev box does.
+
Run these BEFORE promoting `dev`/`beta` → public `main`. All must pass.
## 0. The mechanical gates, in one command
diff --git a/docs/STATE.md b/docs/STATE.md
index 4e633b5..45f7b73 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,5 +1,51 @@
# Phosphene — project state, history, open work
+> **🧹 2026-09-18 — The render form is four closed sections (UNRELEASED, dev; waits for owner use).**
+> Owner: "The H3 layout is kind of a bit too much … you have a pill for speed, quality, length, and all that. That
+> should be inside one section that you can compress and decompress, like we have LoRAs and Customize, because it is
+> very messy like that. I don't think it is easy to navigate between the options … it should be closed by default …
+> Think about what you can separate and what should be grouped together."
+> **What was open on every H3 render:** five labelled pill rows stacked down the form — Speed, Quality, Length, Steps,
+> Orientation — plus a Seed field, the engine's standing note, the cell note and an OPEN LoRA picker. Four of those
+> five rows are one decision each and none of them changes between renders.
+> **Now:** the form keeps four things visible — engine (header), mode (bar), the composer (reference + prompt) and
+> Generate (footer). Everything else is a `<details>` that ships CLOSED, in the same `.customize-section` /
+> `.cz-summary` chrome LoRAs and Customize already used (no second disclosure widget):
+> **Shot setup** (`#shotSetupDetails`, accented in the active engine's colour) = the shape — Speed (H3 Fast|Best,
+> LTX Tuned|Fast draft), Quality, Length, Steps, Adapter slot, Orientation (both engines' rows in one slot), Seed;
+> **LoRAs** (now closed too — it shipped open, so an empty list and its four-line empty state were the tallest thing
+> on the form for anyone who owns no LoRAs; Browse CivitAI and Import H3 LoRA open it themselves);
+> **After the render** (`#finishDetails`) = what happens to the file — H3 Upscale + "also run Upscale & Face Fix",
+> LTX Export + Method, open when done. None of it changes a pixel the model produced;
+> **Advanced** (`#customizeDetails`, was "Customize") = the overrides — width × height, duration/frames, STG,
+> long clips + per-window prompts, external I2V audio, accel.
+> **Each summary prints what its own section hides**, so a closed section still says what will render:
+> `Shot setup · High · 10s · 9:16 · Best · 16 steps · ~67 min · batch`. `updateCustomizeSummary()` keeps its name and
+> its 23 call sites and fans out to `updateShotSetupSummary` / `updateFinishSummary` / `updateAdvancedSummary`; the
+> H3 eta comes from the engine module's own `h3CellEta` (published for this) and the LTX one from `ltxCellEta`, so a
+> summary can never disagree with the chips inside it. `setH3Upscale` / `setH3Orientation` / `#seed` now refresh it —
+> the export target was stale in the old Customize line for the same reason and it mattered less there.
+> **Two things stay OUTSIDE the disclosures on purpose:** `#ltxTierNote` / `#h3TierNote` / `#engineRowNote` (a warning
+> about the render you are about to queue must not be foldable), and the per-window prompt list, which moved UP to sit
+> with the prompt — it is prompt content, one line per 5 s window, and inside a closed section a user who had just
+> chosen a 15 s length would never find it.
+> **Nothing was dropped, renamed or re-defaulted.** Every row only changed parent: same ids, same `data-*` hooks, same
+> handlers, same hidden inputs, same defaults. Proved on the live panel: `FormData(#genForm)` has the identical 59
+> keys before and after, on both engines, and every control still resolves inside `#genForm`.
+> **Also fixed while in there:** a stray `</div>` that closed `.quick-settings` early (Orientation and Seed were
+> siblings of the form, so the block's own label styles never reached them) — `webapp/index.html` now parses with no
+> unmatched tags, and a test keeps it that way. The tier strips and the chip rows are auto-fit tracks instead of fixed
+> column counts (measured 90 px floor): H3's four canvases stay one row across at the pane's real 386 px content box,
+> LTX's five wrap 4 + 1 instead of squeezing, and a dragged-in pane gives ground a column at a time instead of
+> clipping the last chip. The LoRAs header wraps instead of hanging "Check for updates" off the edge.
+> Tests: `test_render_form_sections.py` (26) — the four sections and their closed default, which control is in which
+> section, the Speed→Quality order, every form field name still present, the H3 fields still read server-side, the
+> notes not foldable, the summary fan-out, the markup balance. Full suite 2687 passed / 6 failed, and those six are
+> the known order-dependent `test_room_tone.py` / `test_routes.py` / `test_uploads.py` failures that pass when run
+> alone (unchanged by this work). Screenshots (before + after, dark, retina):
+> `~/AI/projects/phosphene/notes/h3-layout/`. **NOTE: `webapp/index.html` is read once at import
+> (`mlx_ltx_panel.py:33956`), so markup edits need a panel restart; CSS and JS are served from disk.**
+
> **🩹 2026-09-17 — v4.14.3 released (public, tag `v4.14.3`): "songs that start, paths that paste".**
> A fleet read (PostHog, last 48 h) rather than a report: four real-user failures, fixed and shipped the same day.
> **1. YuE2 failed for nearly everyone.** Pinokio's shell exports `PYTORCH_ENABLE_MPS_FALLBACK=1` into every app it
@@ -64,7 +110,133 @@
> in `<home>/api/phosphene.git` + install's LTX steps, no music engine, empty HF_HOME, PATH without uv, booted :8441 → 4.14.1
> not dirty, music `not_installed`; Compose → card → Install ran clone, pin `9253ed1`, venv (3.12.13, mlx 0.32.2), frozen sync
> and started the weight download; Stop left no process or guard. Not run: a full 10.5 GB download, any render, Codex (owner).
-> **Local dev checkout (8199's) is behind beta** by `ee5827b` + the merge — ff it at the next panel restart (new JS needs the new routes).
+> **Shipped:** public main `d8a7ca4` (FF from `fbc777c`), tag `v4.14.1`, release https://github.com/mrbizarro/Phosphene/releases/tag/v4.14.1 ;
+> merged back into dev. **Pinokio post: NOT made** (owner replies to peanut himself). **Local dev checkout (8199's) is behind beta** —
+> ff it at the next panel restart (new JS needs the new routes).
+
+> **🔊 2026-09-17 — Room tone: a generated ambience bed under the whole film, and no clicks at cuts (UNRELEASED, beta; waits for owner use).**
+> Owner: "for auto videos … the cuts are very rough in terms of sound … if it was all over the timeline as an ambient
+> sound, not something really subtle … generated for the video each time." Design: PM hub `notes/room-tone/DESIGN.md`.
+> **Model:** a room-tone bed is an ordinary audio track tagged `room_tone: {variant, seed, level, ref_lufs}` with ONE locked
+> strip 0 → film end, so preview, render mix and NLE export already carry it (no new mix path). `level` (LUFS) is the label,
+> the track `gain` = `room_tone.level_gain(level, ref_lufs)` is what plays. `storyboard_editor.room_tone_{meta,track,
+> new_track,fit}`; validate/normalise know the tag. **Generator** `room_tone.py` (numpy only, CPU, ~0.25 s preset / ~1.2 s
+> film): magnitude × random phase → one inverse FFT over a 40 s grid, so the loop is periodic by construction (hum on exact
+> bins, LFO/crickets/rain ticks in whole cycles); BS.1770 loudness computed from the spectrum (agrees with ffmpeg ebur128 within
+> 0.1–0.3 LU); written at −18 LUFS, peak ≤ −1 dBFS; file length rounded up to 30 s; deterministic name
+> `<film>/audio/room_tone/rt_<variant>_<seed>_<digest>_<secs>s.wav` (+ .json facts), so a repeat pick reuses it. **From this
+> film** = per-clip quiet windows (≤ p25, ≤ −30 dBFS, > −80, 2 windows from anything 10 dB louder) → unit-power spectra →
+> per-bin median; < 1.5 s of quiet → Quiet room + a stated reason. 13 presets (Quiet room … Plane cabin, VHS tape). New take =
+> seed + 1. YuE2/H3 audio rejected (minutes of GPU for a spectrum's job).
+> **UI:** media pool → Sound → **Room tone** card (variant picker, Level −45…−18 LUFS default −27, Add room tone → Rebuild /
+> Use this sound / New take / Remove, "Add room tone to automatic cuts"); ♪ menu on the track gutter → **Room tone…**
+> (`edRtOpen`). The Sound tab hides Add black / Add title and got its own empty sentence. `sbeRtFollow` (in `sbePaint`,
+> `SBE.rtLen` guard so a load never dirties) refits the untouched bed when the film length changes — part of that edit, not its
+> own undo step; a film that outgrew the file gets a longer bed in the background (`sbeRtGrow`, 900 ms debounce).
+> **Routes:** `GET/POST /storyboard/edit/room-tone` (POST takes the on-screen `clips` JSON + `film_len`). **Setting**
+> `room_tone_auto` (default on). **Auto cuts:** `_sbe_auto_edit` → `_sbe_room_tone_auto` (first Editor open, Re-cut,
+> Storyboard auto film) lays a "From this film" bed at −27; strict (no preset hiss when the clips have no quiet sound) and
+> skipped for a music-video cut (`audio.mode` replace). One Shot makes one take, not a cut — no bed.
+> **De-click:** `SB_DECLICK_S = 0.012` → `_sb_declick_term` on every clip-sound segment (both lanes), timeline render only
+> (`_sbe_render_edit` passes it; every other `_sb_assemble_film` caller builds the old graph).
+> **Measured** (scratch panel :8473 on APFS copies; DIVORCE v2 stretch 14.5–45.7 s, 7 cuts, before = no bed, no de-click):
+> mean floor step across a cut **13.0 → 2.7 dB**, worst 25.8 → 12.3 dB (that cut enters a clip whose own floor is −19 dBFS),
+> quietest 10 ms near a cut **−90.4 → −35.5 dBFS**, 10 ms frames under −50 dBFS within ±150 ms of cuts **116 → 0**, integrated
+> −12.8 → −13.0 LUFS. Listen: PM hub `notes/room-tone/divorce_{before,after}.{mp4,wav}`; every variant `variants/*.m4a`.
+> Browser (own headless Chrome): add 0.26 s (DIVORCE) / 1.0 s (Saint Feld, lands on A7 under its 4 tracks), ripple delete →
+> bed 101.40 → 96.23 s, undo → back, New take, swap to VHS tape keeps lane id, grow 120 → 150 s file after +30 s of black,
+> save clean, 0 console errors; auto-edit in-process on both films lays A3 at −27. Screens PM hub `notes/room-tone/*.png`.
+> **Tests:** `test_room_tone.py` 67 (loop seam, tiling, loudness vs ebur128 + BS.1770 sine, peaks, stereo, takes, film shape
+> from quiet not lines, median, fallback, make_bed length/reuse/strict, model/validate/fit, de-click graph on/off/split, a real
+> two-clip render measured, auto-cut on/off/music video/no quiet, setting, routes, client mirror in node, card/docs). Editor +
+> audio suites + geometry 1477 passed, lint clean. Not run: Codex (owner), full release_gates. **Live 8199 needs a restart**
+> (Python: routes, generator, auto cuts, de-click); until then its cached index.html has no card and the new JS is inert.
+
+> **⚡ 2026-09-17 — H3 Speed switch: ⚡ Fast (TaoMate 3-step adapter) | ✦ Best (UNRELEASED, beta; headline of the next release — waits for owner use).**
+> Owner: "3-step render plus 2.5 upscale … it works … a much better option for a draft", then "works well for image-to-video
+> too" → Fast at Standard/High as well, as ONE control ("finally fast generations"). Evidence: PM hub
+> `notes/h3-review/tristep-draft/` (640×384 I2V, bizarro 1.0 + vh5tape 0.8, seed 52010: 8-forward draft 6.9 min vs 3-step
+> 3.0; 768×448 4.8; Face Fix 1 step → 1280×768 ~2.5) and `notes/h3-review/comfy-vae-tristep/REPORT.md` (High I2V gym 9.0 vs
+> 35.1 at 15 forwards; T2V 8.4). Design: `docs/H3_ENGINE.md` → "Speed: ⚡ Fast | ✦ Best".
+> **Runner:** `--sigma-subset N:i,j,…` + `--vae-dtype` (default float32, bit-identical) on minimax-h3-mlx
+> `codex/h3-engine-v2` = `6bbed80` + tests `ccf532b` (`tests/test_sigma_subset.py`). **Fork branch NOT pushed yet** —
+> users get it via "Update Hailuo H3 runner" once it is; until then their Fast half says "update H3 runner". The owner's
+> beta panel runs `codex/live-preview` (`1d2e200` + `39ac145`, tree-identical), carried over by a 3-way merge-file that kept
+> that worktree's uncommitted Sep 10 `generate_staged.py` diff hunk-for-hunk.
+> **UI:** one two-half switch above the Quality cards (`#h3SpeedRow`; `renderH3Turbo()` paints it; `_h3ApplySpeed()` is the
+> one writer of `#h3_tristep` / `#h3_turbo` / `steps`); the cards and the footer re-price for the speed and the mode
+> (T2V/I2V); Fast is the default once installed (`phos_h3_speed`); the Fast half reads "Install (180 MB)" when the adapter
+> is missing and one click installs it; the Steps row shows only under Best; the old Standard | Turbo row is removed (Fast
+> replaces Turbo — the form posts `h3_turbo=0`, the server keeps API Turbo wherever Fast doesn't run); Upscale & Face Fix
+> checkbox beside Generate, footer "Draft · Fast + Face Fix ≈ 5.5 min". Native and the dense 10 s: Best only, one-line note.
+> Load Params / Finish restore the clip's speed (`h3SpeedOfParams`; a Turbo clip → Fast).
+> **Server:** job field `h3_tristep` (1/0/absent = default) in the make_job allowlist; `h3_cell_takes_tristep` (Draft + lab
+> preview, Standard, High; never dense/Native); never stacked with Turbo (make_job and `run_h3_job_inner`); a Steps pin
+> without an explicit 1 keeps Best; Fast = `--steps 4 --sigma-subset 50:0,16,33,49 --lora <adapter>:1.0` ahead of the user's
+> LoRAs, full VAE decode (never TAE). Cells carry `tristep_min/eta/measured` (+ `_i2v`), `tristep_forwards`,
+> `tristep_default`, `facefix_min` (receipts: draft i2v 3.0; standard 4.8 i2v / 4.9 t2v; high 9.0 / 8.4; Face Fix 2.5 /
+> ~4 interpolated / 9). Storyboard prices Fast cells at Fast. **Adapter:** Kijai's
+> `minimax_h3_taomate_3step_lora_avg_rank_19_bf16.safetensors` (182 MB, alpha == rank, ~87 % of the 2.48 GB official
+> delta: median B·A relative error 13 %) from `Kijai/MiniMax-H3_comfy` @ `098f8c4`, sha256 `de9663d9…`, into
+> `<H3 models>/turbo-lora/` via `POST /h3/tristep/install` (resumable Range fetch, size + digest, atomic rename). A
+> full-rank `taomate_h3_3step_ourlayout.safetensors` there wins. Never re-hosted. **Provenance:** `params.h3_tristep`,
+> `h3.tristep` (file, version, repo, revision, sha256, source repo, license, ladder, decode), `h3.schedule`,
+> `h3.lora_accounting`; ⓘ modal Speed row.
+> **Validated:** one real panel-queue render (first commit, `52d1ff8`) — DIVORCE v01, I2V draft 640×384/124f, seed 52010,
+> bizarrotrn_h3 1.0 + vh5tape 0.8: `mlx_outputs/tristep_validation_divorce_v01_h3.mp4` in **205 s** (denoise 139 s = 3 ×
+> ~46 s; text encode 13 s on a cold cache; VAE 44 s), schedule [1, .9612, .8533, 0] / [1, .8609, .5926, 0], 416 wrapped / 0
+> unaccounted, 124 frames + 5.167 s audio, max −1.3 dB; the chained Face Fix → 1280×768 in **171 s** (124 frames). Frame 70
+> matches the owner-approved full-rank clip (PM hub `tristep-draft/panel_validation_cmp70.png`). Real HF resume verified
+> (170 MB partial → 206 → digest OK); the real install ran through the route. The switch was clicked through on scratch :8471
+> (Draft/Standard/High/Native, T2V↔I2V re-pricing, Install state, Face Fix footer). Tests: `test_h3_tristep_draft.py`
+> (45); release_gates --fast 100/0/2. Not run: Codex (owner), from-zero install, a Native Fast render.
+
+> **🎛 2026-09-17 — Editor round 2: fast tooltips, Source monitor back as a drop target, real icons, a View group (UNRELEASED, beta; waits for owner use).**
+> Owner after using 32c9add: tooltips "too slow"; "two empty dark spaces" beside the Program monitor → bring back the Source
+> monitor "where you can drag the clips and see them"; icons "not very clear … deformed"; the panel toggles "not clear".
+> **Icons:** the cause of "deformed" — the sprite was bare `<g>`s on a 24-unit grid used from `<svg>`s with no viewBox, so a
+> 15px box drew the top-left 15 units. Now 24 `<symbol viewBox="0 0 256 256">` in Phosphor geometry (scissors, lift-out-of-gap,
+> gap-closing ripple, copy, link/unlink, arrows-clockwise, speaker/speaker-slash, trash+waveform, level line ×, lock/lock-open,
+> smiley+sparkle, waveform, sidebars, split-screen+play, corners-out, keyboard, clock), 18px, stroke 22/256 on `.sbe-cbar-i`;
+> the preview mute is an icon (`#sbeMuteUse`). **View group** (`#sbeView`, header): Source · Inspector · Sound · Panels · Full
+> screen, labelled (icons-only below a 1360px window unless panels are hidden), pressed = showing, `sbeViewTip` writes what a
+> click shows/hides + key. The toggles left the Program strip and the tool row. **Tooltips:** new `webapp/js/tips.js` — one
+> element, 150 ms delay (measured 0.16–0.17 s in headless Chrome), instant when sliding along a row (400 ms warm), focus-visible,
+> flipped/clamped 8px in the window, reduced-motion aware; painters still write `title`, which is moved to `data-tip` on
+> hover/focus and by a MutationObserver (no native tooltip; aria-label kept/filled). Scope: Editor icon/header buttons, chips,
+> `.po-act`. **Source monitor** on by default (`phos_sbe_src`; Source or × hides), each monitor column exactly its picture's
+> width (the old layout squeezed Source to 499×315, not 16:9), empty state "Drop a clip here to preview"; drop target for pool
+> rows (`edPoolDragMove/End`) and shots dragged off the track (`sbeOnTrackMove/Up`: track restored from the snapshot, no undo,
+> not dirty), `sbeSrcDropHover` lights it. **Measured** (scratch panel :8461 on an APFS clone of Saint Feld): Program stays
+> **681×383** at 1920×992 with Source **681×383** beside it; at 1512×945 Program **597×336** + Source **560×315**, row 1170/1182px.
+> Three-up (Inspector open) 681/492/380 and 567/379/212. Geometry gate now also asserts Source shown, both boxes 16:9, 5 View
+> buttons. Tests: `RoundTwoTipsSourceIcons` (8), audio_compact/face_fix/docs updated; editor suites + geometry 1083 passed,
+> lint clean. Not run: Codex (owner), full release_gates. Screens: PM hub `notes/editor-redesign/round2_*.png`.
+
+> **🎛 2026-09-17 — Editor layout redesign: Sound mode, panels on demand, icons (UNRELEASED, beta; waits for owner use).**
+> Owner, after cutting *Saint Feld*: the sound lanes resizing themselves is "really weird… really bad", the picture is small,
+> the clip name sits on the picture, the inspector is "open like this all the time", the clip bar is wordy, rows are wasted.
+> Design (PM hub `notes/editor-redesign/DESIGN.md`, before/after PNGs + `*_measure.json` beside it): **nothing resizes itself**.
+> **Sound mode** (⇧A · the ⌁ Sound button on the tool row · the ▾ on the A1 head; `sbeSoundModeSet` is the one writer,
+> `phos_sbe_mode` per browser) replaces the self-sizing lanes of e588b52/c48e3c8 — picture mode = thin lanes, big picture;
+> sound mode = full lanes, timeline at the roof, picture at its 120px floor; each mode keeps its own handle height
+> (`phos_sbe_tl_h` / `phos_sbe_tl_h_sound`). A thin lane selects on one click, is sound mode on a double-click. **Source
+> monitor** is a guest (`#sbeSrcMon` hidden until a pool row is clicked or ◫ pressed; × closes it). **Inspector** is a
+> collapsible rail (☰ under the picture, ⌘I, double-click a clip; `phos_sbe_inspect`); "rendered, not placed" is a count chip
+> under the picture while it is closed. `sbeMonitorFit(width, budget, {src, rail})` sizes one, two or three across. The
+> **clip name** moved off the picture to the strip under it (`#sbeProgClip`); the badge carries only the no-proxy warning, on
+> hover. **Transport** (▶/⏸, 🔊, time) sits under the Program monitor; the old transport row is gone — the **tool row** is the
+> icon-only clip bar (labels in tooltips, in More and the right-click menu) plus Sound · Snap · zoom · ⓘ · ⌨ Keys, with the
+> grab below it (`.sbe-toolrow`). **Full screen** (⛶ / F, Fullscreen API on `#sbeStage`). **Panels** (▯ in the header / `):
+> hides the app's left column (`body.ed-focus`, `phos_sbe_panels`). The **snapshot** offer is a header chip (`#sbeRecoverChip`),
+> not a row. Registry: `editor.soundLanes` → `editor.soundMode`; new `editor.inspector` ⌘I, `editor.fullscreen` F,
+> `editor.panels` `. Measured (headless Chrome, the owner's film, fresh browser): Program monitor **412×232 → 681×383** at a
+> 1920×992 window, **329×185 → 597×336** at 1512×945; the header+notice+transport rows 49+31+34 → 49+0+28. Sound mode: 213×120
+> picture, 545px timeline. Tests: `test_audio_compact.py` rewritten as the Sound-mode contract (nothing may move the split but
+> the switch); `test_storyboard_editor_ui.py` harness stubs `mode: 'sound'` and probes picture mode's own ends (166/246);
+> `scripts/measure_editor_layout.py` holds the lanes open via `sbeSoundModeSet`. Green: editor suites 1052 passed, geometry
+> gate 12 passed (browser run), lint clean. Not run: Codex (owner: skip). Live 8199 was NOT restarted (it caches index.html at
+> boot, so it still serves the old HTML until its next restart); verified on a scratch panel :8437 over an APFS clone of the film.
> **🎵 2026-09-17 — v4.14.0 released (public, tag `v4.14.0`): "Songs, faces and sound".**
> Owner's order: "Let's make a release because I think there are too many things to release at the moment." No further
@@ -81,6 +253,17 @@
> dev then merges that snapshot (tree-identical), so `git log dev..origin/main` is empty.
> **Credit:** YuE2 by Multimodal Art Projection (m-a-p), CC BY-NC 4.0 + individual-creator permission; MLX port by vanch007
> (Apache-2.0). CivitAI search fix #82 by @Viktorminator.
+> **Shipped:** public main `fbc777c` (FF from `e1d500e`, parent = v4.13.2, tree == dev `3cf4662`), tag `v4.14.0`, release
+> https://github.com/mrbizarro/Phosphene/releases/tag/v4.14.0 ; dev/beta = `3cf4662` + tree-identical merge of `fbc777c`.
+> Leak check: 54 paths, all this release's (YuE2 pack + licences, face fix, editor sound, docs); public `dev` untouched.
+> **Gates:** full `release_gates.sh` 100 PASS / 0 FAIL / 0 SKIP in the release worktree, MLX forced to CPU (sitecustomize).
+> **Clean room:** fresh clone of `3cf4662`, fresh ltx-2-mlx clone → `ltx_checkout.sh` (ltx25.7 `bf419b6`) + `ltx_venv.sh` +
+> install's uv steps + codec patch; music path `music_preflight/clone/checkout` (pin `9253ed1`) `/venv` (3.12.13) `/sync`,
+> `music_fetch.py --check` = 1 (no weights, expected); H3 path `h3_preflight` + clone + `h3_checkout.sh` (`11b90a0`) + deps OK.
+> No weights, empty HF_HOME/state/outputs, analytics host blackholed. Booted on :8414 → `/version` 4.14.0 not dirty, UI 200,
+> integrity OK, `music` runner_ok/venv_ok with reason `missing_weights`, `h3` root resolved with only weights missing, no
+> tracebacks; stopped by PID, removed. **Not run:** any render, update-path gate, real 10.5 GB YuE2 download, Codex (owner).
+> **Pinokio post: NOT posted** — draft PM hub `launch/10_release_4140.md` (media post + X thread; covers 4.13.1/4.13.2 too).
> **🧑‍🎨 2026-09-17 — "Upscale ×2 / LTX Upscale" is now Upscale & Face Fix, and a one-click clip action (UNRELEASED, beta; waits for owner use).**
> Owner: the upscaler "that fixes the faces has the wrong name … should be optional and something you can do to an existing clip."
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 2e06410..1240620 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -869,6 +869,11 @@ def _settings_defaults() -> dict:
# allowed them. On by default because a render is minutes long and
# nobody watches a progress bar for eleven of them; one click off.
"notify_done": True,
+ # Room tone on automatic cuts: the auto-editor lays a bed made from the
+ # film's own quiet sound under every cut it invents, so cuts do not
+ # drop to silence. On by default (owner, 2026-09-17); one switch off,
+ # in the Editor's Room tone card.
+ "room_tone_auto": True,
# Memory/speed policy. Defaults to Auto so 5 s clips keep the fast
# full-decode path while long/high-pressure renders stay protected.
# Live preview. On by default: it costs ~0.2 % of the render,
@@ -999,9 +1004,16 @@ def _load_settings() -> dict:
return _settings_defaults()
-def _save_settings(settings: dict) -> None:
+def _save_settings(settings: dict, *, _target: "Path | None" = None) -> None:
"""Atomic write so a Pinokio kill mid-write can't leave a half-file.
+ REFUSES to write an installed panel's own `state/panel_settings.json` from
+ inside a test process (2026-09-18: a whole-suite run replaced the owner's
+ PostHog and CivitAI keys with test fixtures, because STATE_DIR had already
+ been resolved to the real `state/` by an earlier test module's import).
+ `conftest.py` sandboxes the paths; this is the refusal that does not depend
+ on the paths being right.
+
M3: matches the same O_EXCL temp + fsync + replace + explicit
chmod 0o600 shape used by `atomic_write_text` (defined later in this
module) and `agent/runtime.py:save_session`. Inlined rather than
@@ -1013,8 +1025,20 @@ def _save_settings(settings: dict) -> None:
security-review.md §M3.
"""
import os as _os
- tmp = SETTINGS_FILE.with_name(
- f".{SETTINGS_FILE.name}.{_os.getpid()}.{threading.get_ident()}."
+ dest = Path(_target) if _target is not None else SETTINGS_FILE
+ if _os.environ.get("PYTEST_CURRENT_TEST"):
+ installed = Path(__file__).resolve().parent / "state" / "panel_settings.json"
+ try:
+ same = dest.resolve() == installed.resolve()
+ except OSError:
+ same = str(dest) == str(installed)
+ if same:
+ raise RuntimeError(
+ "refusing to write an installed panel's settings from a test "
+ f"({dest}) — set LTX_STATE_DIR to a temp dir (conftest.py does "
+ "this for the suite)")
+ tmp = dest.with_name(
+ f".{dest.name}.{_os.getpid()}.{threading.get_ident()}."
f"{time.time_ns()}.tmp"
)
fd = _os.open(
@@ -1031,9 +1055,9 @@ def _save_settings(settings: dict) -> None:
_os.chmod(tmp, 0o600)
except OSError:
pass
- _os.replace(tmp, SETTINGS_FILE)
+ _os.replace(tmp, dest)
try:
- _os.chmod(SETTINGS_FILE, 0o600)
+ _os.chmod(dest, 0o600)
except OSError:
pass
except Exception:
@@ -1141,6 +1165,13 @@ def _validate_settings_patch(patch: dict) -> tuple[dict, str | None]:
else:
out["notify_done"] = str(v).strip().lower() in ("1", "true", "yes", "on")
+ if "room_tone_auto" in patch:
+ v = patch["room_tone_auto"]
+ if isinstance(v, bool):
+ out["room_tone_auto"] = v
+ else:
+ out["room_tone_auto"] = str(v).strip().lower() in ("1", "true", "yes", "on")
+
if "live_preview" in patch:
# Two states, and anything unrecognised is refused rather than
@@ -1291,6 +1322,7 @@ def get_settings_public() -> dict:
"spicy_mode": bool(s.get("spicy_mode", False)),
"live_preview": str(s.get("live_preview", "on")),
"notify_done": bool(s.get("notify_done", True)),
+ "room_tone_auto": bool(s.get("room_tone_auto", True)),
# Push: can the panel send at all, and how many browsers listen.
"push_available": push_available(),
"push_subscriptions": len(_push_subs()),
@@ -7973,6 +8005,85 @@ def h3_turbo_note(paths: dict | None = None) -> str:
return H3_TURBO_NOTE
return H3_TURBO_NOTE_V4 if (resolved or {}).get("version") == "v4-600-EMA" else H3_TURBO_NOTE
+
+# ---- TriStep: TaoMate-H3's 3-step adapter ("Fast" on the Speed switch) ----------
+# TaoLiveAIGC/TaoMate-H3 (Alibaba TaoLive, 2026-09-07) distils H3 onto FOUR
+# points of the shifted 50-point sigma grid — (0, 16, 33, 49), video
+# σ [1, .96117, .85333, 0], audio σ [1, .86087, .59259, 0] — so it runs THREE
+# forwards. That is `--steps 4 --sigma-subset 50:0,16,33,49` on the runner, NOT
+# `--steps 4` alone (which re-spaces a 4-point grid the adapter never saw).
+#
+# Owner ruling 2026-09-17, after a Bizarro I2V draft (640×384, character 1.0 +
+# vh5tape 0.8, seed 52010) at 3 forwards vs the 8-forward draft: "3-step render
+# plus 2.5 upscale … it works … a much better option for a draft."
+# Measured on the M4 Max: 8-forward draft 6.9 min vs TriStep 3.0 min, then
+# Upscale & Face Fix (1 refine step) → 1280×768 in ~2.5 min.
+#
+# The same evening he asked for it at higher quality too, and for ONE control:
+# the H3 composer's Speed switch, ⚡ Fast | ✦ Best. Fast = this adapter on
+# Draft 640×384 (3.0 min for 5 s), Standard 768×448 (4.8) and High 1024×576
+# (8.4 T2V / 9.0 I2V, vs ~35 min at 15 forwards), T2V and I2V; the DEFAULT on
+# all three once installed. Best = each shape's own sampler, unchanged. Native
+# and the dense 10 s single pass are not validated on 3 steps and always
+# render Best. The official release is T2AV only; I2V is unofficial, and its
+# look is owner-approved. Fast replaces Turbo in the UI (never stacked).
+#
+# THE FILE. The official adapter is 2.48 GB (rank 128, PEFT `lora_a`/`lora_b`
+# keys). Kijai's rank-resized conversion (avg rank 19, bf16, alpha == rank on
+# every module, bare runner keys under `diffusion_model.`) is 182 MB and keeps
+# ~87 % of the delta (median relative error of B·A 13 %, measured module by
+# module against the full adapter). It is fetched from its author's repo at a
+# pinned revision and digest — never re-hosted. The license is the MiniMax H3
+# Community License, the same as H3's own weights. A full-rank runner-layout
+# copy (`lora_a`→`lora_A.weight`, values untouched) is accepted FIRST when
+# someone put one there; the managed download is the small file.
+H3_TRISTEP_REPO = "Kijai/MiniMax-H3_comfy"
+H3_TRISTEP_REVISION = "098f8c48fccead9a93191c166ca31a130659d3bd"
+H3_TRISTEP_FILE = "minimax_h3_taomate_3step_lora_avg_rank_19_bf16.safetensors"
+H3_TRISTEP_URL = ("https://huggingface.co/" + H3_TRISTEP_REPO + "/resolve/"
+ + H3_TRISTEP_REVISION + "/loras/" + H3_TRISTEP_FILE)
+H3_TRISTEP_SHA256 = "de9663d974a884b477556748239c6f28239f7ca1825be270f98f023ff5dab6a7"
+H3_TRISTEP_BYTES = 181697688
+H3_TRISTEP_FULL_FILE = "taomate_h3_3step_ourlayout.safetensors"
+H3_TRISTEP_SOURCE_REPO = "TaoLiveAIGC/TaoMate-H3"
+H3_TRISTEP_LICENSE = "MiniMax H3 Community License"
+# (filename, version label, size floor) — resolved in this order.
+H3_TRISTEP_CANDIDATES = (
+ (H3_TRISTEP_FULL_FILE, "r128-full", 2 * 1024 ** 3),
+ (H3_TRISTEP_FILE, "r19-kijai", 150 * 1024 * 1024),
+)
+H3_TRISTEP_STEPS = 4 # sigma POINTS → 3 forwards
+H3_TRISTEP_FORWARDS = H3_TRISTEP_STEPS - 1
+H3_TRISTEP_SIGMA_SUBSET = "50:0,16,33,49"
+H3_TRISTEP_DOWNLOAD_GB = 0.2
+H3_TRISTEP_LABEL = "Fast"
+H3_TRISTEP_NOTE = ("Fast: 3 steps — about 4× faster, great for drafts and most "
+ "shots (TaoMate's 3-step adapter on the same H3 model). "
+ "Turbo is never stacked on it.")
+# Canvases that offer it, and the ones where it is the default once installed.
+H3_TRISTEP_QUALITIES = ("draft", "preview", "standard", "high")
+H3_TRISTEP_DEFAULT_QUALITIES = H3_TRISTEP_QUALITIES
+# End-to-end wall clocks for TriStep cells, M4 Max, keyed (quality, length).
+# Keyed (quality, length, mode). All with the character + vh5tape LoRAs on top
+# and the full VAE decode (notes/h3-review/tristep-draft/run.out and
+# notes/h3-review/comfy-vae-tristep/REPORT.md):
+# draft i2v 640×384 v01 3.0 min (panel queue, cold cache: 3.4)
+# standard 768×448 v01 i2v 4.8 · t2v 4.9
+# high 1024×576 gym i2v 9.0 · walk/v01 t2v 8.4
+H3_TRISTEP_MEASURED_ETA: dict[tuple[str, str, str], tuple[float, str]] = {
+ ("draft", "5s", "i2v"): (3.0, "~3 min"),
+ ("standard", "5s", "i2v"): (4.8, "~5 min"),
+ ("standard", "5s", "t2v"): (4.9, "~5 min"),
+ ("high", "5s", "i2v"): (9.0, "~9 min"),
+ ("high", "5s", "t2v"): (8.4, "~8 min"),
+}
+# Upscale & Face Fix (1 refine step from the clip, ×2) after a 5 s render, by
+# source canvas. 640×384 → 1280×768 measured 2.5–2.8 min; 1024×576 measured
+# 8.2–9.9 min (panel history, 2026-09-16/17); 768×448 is interpolated between
+# them on output pixels (~4 min, not measured). Other lengths scale by frames.
+FACE_FIX_DRAFT_5S_MIN = 2.5
+FACE_FIX_5S_MIN = {"draft": 2.5, "preview": 2.0, "standard": 4.0, "high": 9.0}
+
# ============================================================================
# H3 RENDER SHAPE — two independent axes, priced by one measured cost model
# ============================================================================
@@ -8693,6 +8804,31 @@ def _build_h3_tiers() -> dict[str, dict]:
if hit and int(hit[2]) == H3_TURBO_FORWARDS:
turbo_min, turbo_measured = hit[0] * hw, True
turbo_eta = hit[1] if hw == 1.0 else _fmt_eta(turbo_min)
+ # TriStep prices only the cells that offer it (h3_cell_takes_tristep).
+ tristep = {}
+ if q["key"] in H3_TRISTEP_QUALITIES and not ln["dense"]:
+ tri_min = min(eta_min, h3_estimate_minutes(
+ w, h, window_frames, windows, H3_TRISTEP_FORWARDS))
+ tristep = {
+ "tristep_default": q["key"] in H3_TRISTEP_DEFAULT_QUALITIES,
+ "tristep_forwards": windows * H3_TRISTEP_FORWARDS,
+ }
+ # T2V and I2V priced separately where a receipt says they differ;
+ # the model (no mode term) covers the rest.
+ for mode_key, suffix in (("t2v", ""), ("i2v", "_i2v")):
+ m_min, m_eta, m_meas = tri_min, _fmt_eta(tri_min), False
+ hit = H3_TRISTEP_MEASURED_ETA.get((q["key"], ln["key"], mode_key))
+ if hit:
+ m_min, m_meas = hit[0] * hw, True
+ m_eta = hit[1] if hw == 1.0 else _fmt_eta(m_min)
+ tristep["tristep_min" + suffix] = round(m_min, 2)
+ tristep["tristep_eta" + suffix] = m_eta
+ tristep["tristep_measured" + suffix] = m_meas
+ # The Upscale & Face Fix pass, priced beside the render so the
+ # 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)
spec = f"{w}×{h} · {frames}f"
if windows > 1:
spec += f" · {windows}×5s"
@@ -8740,6 +8876,7 @@ def _build_h3_tiers() -> dict[str, dict]:
"draft": bool(q["draft"]),
"dense": bool(ln["dense"]),
"offered": bool(q["offered"] and ln["offered"]),
+ **tristep,
}
return tiers
@@ -10617,6 +10754,221 @@ def h3_turbo_status() -> dict:
}
+# ---- TriStep (the Draft sampler) — resolver, argv, status, fetch ------------
+def h3_cell_takes_tristep(cell: dict) -> bool:
+ """Draft, Standard or High at a 5 s-window length (single or chained).
+ Native and the dense single-pass 10 s keep their own samplers: neither has
+ been looked at on 3 steps, and a 243-frame window is far past the chunks
+ TaoMate was distilled on."""
+ return (cell.get("quality") in H3_TRISTEP_QUALITIES
+ and not bool(cell.get("dense")))
+
+
+def h3_cell_tristep_default(cell: dict) -> bool:
+ """Where Fast is the DEFAULT once installed (every canvas that offers it)."""
+ return h3_cell_takes_tristep(cell) and cell.get("quality") in H3_TRISTEP_DEFAULT_QUALITIES
+
+
+def h3_supports_sigma_subset() -> bool:
+ """Whether the INSTALLED runner takes `--sigma-subset` (the TaoMate ladder).
+ TriStep also rides as one more `--lora` beside the user's, so it needs the
+ stacking runner too — every runner with `--sigma-subset` has it."""
+ return h3_supports_lora_stack() and _h3_runner_has_flag("--sigma-subset")
+
+
+def h3_tristep_paths() -> dict:
+ """The TriStep adapter that would run: the full-rank copy if someone put
+ one there, else the managed 182 MB download. Exact allowlist, no glob."""
+ directory = _h3_turbo_dir()
+ for filename, version, floor in H3_TRISTEP_CANDIDATES:
+ candidate = directory / filename
+ if _h3_real_file(candidate, floor):
+ return {"dir": directory, "lora": candidate, "version": version,
+ "files_ok": True, "missing": []}
+ return {"dir": directory, "lora": None, "version": None, "files_ok": False,
+ "missing": [f"adapter ({H3_TRISTEP_FILE}, "
+ f"~{H3_TRISTEP_DOWNLOAD_GB} GB)"]}
+
+
+def h3_tristep_argv(paths: dict | None = None) -> list[str]:
+ """The runner argv fragment: the TaoMate ladder and the adapter at 1.0.
+ `--steps` is stamped by the caller (H3_TRISTEP_STEPS) like every tier's."""
+ resolved = paths or h3_tristep_paths()
+ if not resolved.get("files_ok") or resolved.get("lora") is None:
+ raise RuntimeError("H3 fast 3-step adapter is not available")
+ return ["--sigma-subset", H3_TRISTEP_SIGMA_SUBSET,
+ "--lora", f"{resolved['lora']}:1.0"]
+
+
+_h3_tristep_dl_lock = threading.Lock()
+_h3_tristep_dl_state: dict = {"status": "idle", "mb": 0, "total_mb": 0,
+ "error": None}
+
+
+def _set_h3_tristep_dl(**kw) -> None:
+ with _h3_tristep_dl_lock:
+ _h3_tristep_dl_state.clear()
+ _h3_tristep_dl_state.update(kw)
+
+
+def h3_tristep_status() -> dict:
+ """/status + BOOT block for the Draft sampler. Same three answers as
+ Turbo's: can the runner take it, is the file here, so is it offered."""
+ supported = h3_supports_sigma_subset()
+ paths = h3_tristep_paths()
+ downloaded = bool(paths["files_ok"])
+ return {
+ "available": bool(supported and downloaded),
+ "supported": supported,
+ "downloaded": downloaded,
+ "reason": ("runner_too_old" if not supported
+ else "not_downloaded" if not downloaded else "ok"),
+ "steps": H3_TRISTEP_STEPS,
+ "forwards": H3_TRISTEP_FORWARDS,
+ "sigma_subset": H3_TRISTEP_SIGMA_SUBSET,
+ "download_gb": H3_TRISTEP_DOWNLOAD_GB,
+ "repo": H3_TRISTEP_REPO,
+ "source_repo": H3_TRISTEP_SOURCE_REPO,
+ "license": H3_TRISTEP_LICENSE,
+ "adapter": str(paths["lora"]) if paths["lora"] else None,
+ "adapter_version": paths["version"],
+ "install_available": bool(supported),
+ "installing": _h3_tristep_dl_state.get("status") == "downloading",
+ "download": dict(_h3_tristep_dl_state),
+ "dir": str(paths["dir"]),
+ "missing": paths["missing"],
+ "note": H3_TRISTEP_NOTE,
+ "label": H3_TRISTEP_LABEL,
+ }
+
+
+def _h3_tristep_download_bg(target_dir, push_log, asset: dict | None = None,
+ opener=None) -> None:
+ """Fetch the pinned TriStep adapter into the H3 pack, RESUMABLY.
+
+ A `.partial` left by an interrupted fetch is continued with an HTTP Range
+ request (its bytes are re-hashed first); a server that ignores the Range
+ gets a fresh start. Exact size + sha256 before the atomic rename, so a
+ killed download never leaves a file h3_tristep_paths() would resolve."""
+ import contextlib
+ import hashlib
+ import urllib.request
+ asset = asset or {"file": H3_TRISTEP_FILE, "url": H3_TRISTEP_URL,
+ "sha256": H3_TRISTEP_SHA256, "bytes": H3_TRISTEP_BYTES}
+ opener = opener or urllib.request.urlopen
+ total = int(asset["bytes"])
+ total_mb = total // (1 << 20)
+ target_dir = Path(target_dir)
+ target = target_dir / asset["file"]
+ tmp = target.with_name(target.name + ".partial")
+ try:
+ target_dir.mkdir(parents=True, exist_ok=True)
+ if _h3_real_file(target, 1) and target.stat().st_size == total:
+ _set_h3_tristep_dl(status="done", mb=total_mb, total_mb=total_mb,
+ error=None)
+ return
+ h = hashlib.sha256()
+ have = 0
+ if tmp.is_file():
+ have = tmp.stat().st_size
+ if have > total:
+ tmp.unlink()
+ have = 0
+ else:
+ with open(tmp, "rb") as fh:
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
+ h.update(chunk)
+ headers = {"User-Agent": "Phosphene"}
+ if have:
+ headers["Range"] = f"bytes={have}-"
+ push_log(f"[h3:tristep] resuming {asset['file']} at "
+ f"{have // (1 << 20)} / {total_mb} MB…")
+ else:
+ push_log(f"[h3:tristep] downloading {asset['file']} (~{total_mb} MB, "
+ f"{H3_TRISTEP_REPO} @ {H3_TRISTEP_REVISION[:7]}, "
+ f"{H3_TRISTEP_LICENSE})…")
+ written = have
+ last_log = 0.0
+ # A .partial that is already whole (killed between the last byte and
+ # the rename) needs no request at all — a Range past the end is a 416.
+ with (opener(urllib.request.Request(asset["url"], headers=headers),
+ timeout=60) if have < total else contextlib.nullcontext()) as resp:
+ status = int(getattr(resp, "status", 200) or 200)
+ mode = "ab"
+ if resp is not None and have and status != 206:
+ # The server sent the whole file: start over, never append it.
+ push_log("[h3:tristep] server ignored the resume — restarting")
+ h = hashlib.sha256()
+ written = 0
+ mode = "wb"
+ with open(tmp, mode) as fh:
+ while resp is not None:
+ chunk = resp.read(1 << 20)
+ if not chunk:
+ break
+ fh.write(chunk)
+ h.update(chunk)
+ written += len(chunk)
+ now = time.time()
+ if now - last_log > 2.5:
+ _set_h3_tristep_dl(status="downloading",
+ mb=written // (1 << 20),
+ total_mb=total_mb, error=None)
+ push_log(f"[h3:tristep] {written // (1 << 20)} / "
+ f"{total_mb} MB")
+ last_log = now
+ if written != total:
+ raise RuntimeError(f"size mismatch: got {written}, expected {total}"
+ " — press the pill again to resume")
+ if h.hexdigest() != asset["sha256"]:
+ tmp.unlink()
+ raise RuntimeError("checksum mismatch (download corrupt) — please retry")
+ tmp.replace(target)
+ push_log(f"[h3:tristep] adapter installed → {target}")
+ _set_h3_tristep_dl(status="done", mb=total_mb, total_mb=total_mb,
+ error=None)
+ except Exception as e: # noqa: BLE001
+ # The .partial stays (unless it was corrupt): the next press resumes.
+ _set_h3_tristep_dl(status="error", mb=0, total_mb=total_mb,
+ error=str(e)[:200])
+ push_log(f"[h3:tristep] FAILED: {e}")
+
+
+def _h3_install_tristep(push_log, download_fn=None) -> dict:
+ """On-demand fetch of the Draft sampler's adapter (one at a time)."""
+ paths = h3_paths()
+ if paths["missing"]:
+ return {"ok": False,
+ "error": "Fast (3 steps) is an add-on to the Hailuo H3 "
+ "pack, and H3 isn't fully installed yet: "
+ + "; ".join(paths["missing"])}
+ if not h3_supports_sigma_subset():
+ return {"ok": False,
+ "error": "This Hailuo H3 runner predates Fast (3 steps) "
+ "(no --sigma-subset). Run 'Update Hailuo H3 runner' "
+ "from the Phosphene sidebar in Pinokio — your weights "
+ "stay."}
+ resolved = h3_tristep_paths()
+ target = resolved["dir"]
+ if resolved["files_ok"]:
+ return {"ok": True, "started": False, "already_installed": True,
+ "dir": str(target)}
+ with _h3_tristep_dl_lock:
+ if _h3_tristep_dl_state.get("status") == "downloading":
+ return {"ok": False,
+ "error": "a Fast (3-step) adapter download is already active"}
+ _h3_tristep_dl_state.clear()
+ _h3_tristep_dl_state.update(status="downloading", mb=0,
+ total_mb=H3_TRISTEP_BYTES // (1 << 20),
+ error=None)
+ fn = download_fn or _h3_tristep_download_bg
+ threading.Thread(target=fn, args=(target, push_log), daemon=True,
+ name="h3-tristep-download").start()
+ return {"ok": True, "started": True, "dir": str(target),
+ "asset": H3_TRISTEP_URL, "sha256": H3_TRISTEP_SHA256,
+ "bytes": H3_TRISTEP_BYTES, "license": H3_TRISTEP_LICENSE}
+
+
# ============================================================================
# H3 USER LoRAs — CivitAI adapters for the MiniMax H3 lane
# ============================================================================
@@ -12109,7 +12461,10 @@ def _h3_export_notes(w: int, h: int) -> dict[str, str]:
_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 "
f"{_tw}×{_th} with LTX-2.5 detail, keeps the face and the sound, and "
- "lands beside the draft. About the draft's time again."
+ "lands beside the draft. "
+ + (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.")
+ ("" if _adapter_ok else
" Needs the 0.3 GB Upscale adapter first — Settings → Models."))
continue
@@ -12299,6 +12654,19 @@ def h3_status() -> dict:
"pack — install H3 first.",
"dir": str(_h3_turbo_dir()), "missing": [],
"note": H3_TURBO_NOTE, "label": "Turbo"}),
+ # Speed switch "Fast" (TaoMate 3-step adapter). Same three-cause shape as Turbo.
+ "tristep": (h3_tristep_status() if available else
+ {"available": False, "supported": False, "downloaded": False,
+ "reason": "h3_" + paths["reason"],
+ "steps": H3_TRISTEP_STEPS, "forwards": H3_TRISTEP_FORWARDS,
+ "sigma_subset": H3_TRISTEP_SIGMA_SUBSET,
+ "download_gb": H3_TRISTEP_DOWNLOAD_GB,
+ "repo": H3_TRISTEP_REPO, "source_repo": H3_TRISTEP_SOURCE_REPO,
+ "license": H3_TRISTEP_LICENSE, "adapter": None,
+ "adapter_version": None, "install_available": False,
+ "installing": False, "download": {}, "dir": str(_h3_turbo_dir()),
+ "missing": [], "note": H3_TRISTEP_NOTE,
+ "label": H3_TRISTEP_LABEL}),
# User LoRAs — the CivitAI lane. A separate block from `turbo` for the
# same reason turbo is separate from `first_frame`: "you can't pick a
# LoRA" has three unrelated causes (H3 absent / runner predates --lora
@@ -12813,6 +13181,32 @@ def music_child_env(base: dict | None = None) -> dict:
return env
+#: Vars the TRAINERS must not inherit. Both are PyTorch switches Pinokio's
+#: kernel exports into every app it launches; lora_lab is MLX end to end
+#: (`import mlx.core` in train_character / train_audio / preprocess_*), so they
+#: mean nothing to it and they are exactly the accident that killed music in
+#: 4.14.0. `Malloc*` goes for the reason image_engine strips it: macOS dev
+#: tooling exports empty MallocStackLogging vars and every child then prints a
+#: warning it cannot act on.
+TRAINER_ENV_STRIP = ("PYTORCH_ENABLE_MPS_FALLBACK", "PYTORCH_MPS_FAST_MATH")
+
+
+def trainer_child_env(base: dict | None = None) -> dict:
+ """The env a LoRA trainer child gets — decided here, not inherited whole.
+
+ The release checklist named the two `{**os.environ}` spreads in this file
+ (the character trainer and the audio trainer) as the last raw ones, and the
+ rule they broke is the one that cost 4.14.0 its music: never hand an engine
+ the shell's environment and hope. PYTHONPATH is deliberately left alone —
+ `scripts/lora_lab_run.sh` sets it for the child, and Pinokio deletes it on
+ the way in anyway.
+ """
+ env = {k: v for k, v in (base if base is not None else os.environ).items()
+ if k not in TRAINER_ENV_STRIP and not k.startswith("Malloc")}
+ env["PYTHONUNBUFFERED"] = "1"
+ return env
+
+
def music_progress(line: str, previous: dict | None = None) -> dict | None:
"""Decode the runner's flushed protocol; percentages describe stages."""
m = re.match(r"^\[music\] (stage|plan|song|synth|decode|done|error)\s*(.*)$", line.strip())
@@ -14712,9 +15106,39 @@ def _usage_fleet_report() -> dict | None:
}
+def _usage_attach_local(report: dict) -> dict:
+ """Ride this machine's own totals along with whatever we return.
+
+ Owner, 2026-09-18: "when I ask you for total renders, I mean total renders
+ from the fleet too… one of the first windows I want to see is total renders
+ for all the fleet." The dashboard used to show ONE number called
+ "Total renders" whose meaning silently changed with whether a query key was
+ configured — the fleet's total, or this Mac's. Two numbers, both labelled,
+ always: the fleet answers "how much is this app used", the machine answers
+ "how much have I used it", and neither can be mistaken for the other.
+ """
+ try:
+ local = _usage_local_report()
+ except Exception:
+ return report
+ report["machine"] = {
+ "total_renders": (local.get("tiles") or {}).get("total_renders"),
+ "renders_7d": (local.get("tiles") or {}).get("renders_7d"),
+ "error_rate_pct": (local.get("tiles") or {}).get("error_rate_pct"),
+ "first_day": (((local.get("growth") or {}).get("installs_by_day") or [{}])[0]
+ or {}).get("date"),
+ }
+ return report
+
+
def _usage_report(force: bool = False) -> dict:
"""What GET /stats/usage returns. Fleet when a query key is configured
- and the 6 h cache is stale; otherwise the cache; otherwise local."""
+ and the 6 h cache is stale; otherwise the cache; otherwise local.
+
+ Either way the payload carries `machine` (this Mac) AND says whether the
+ fleet half is available — `fleet_blocked` is "no_key" or "query_failed",
+ so the dashboard can show the fleet tile as unknown with a remedy instead
+ of quietly substituting a local number under a fleet label."""
with _USAGE_FLEET_LOCK:
if _analytics_query_key():
if not force:
@@ -14723,7 +15147,8 @@ def _usage_report(force: bool = False) -> dict:
if (time.time() - float(cached.get("_fetched_at") or 0)
< USAGE_FLEET_TTL_SEC):
cached["cached"] = True
- return cached
+ cached["fleet_blocked"] = ""
+ return _usage_attach_local(cached)
except (OSError, ValueError, json.JSONDecodeError):
pass
fleet = None
@@ -14733,18 +15158,22 @@ def _usage_report(force: bool = False) -> dict:
fleet = None
if fleet:
fleet["_fetched_at"] = time.time()
+ fleet["fleet_blocked"] = ""
try:
_ensure_state_dir()
atomic_write_text(USAGE_FLEET_CACHE,
json.dumps(fleet, indent=2))
except Exception:
pass
- return fleet
+ return _usage_attach_local(fleet)
local = _usage_local_report()
+ local["fleet_blocked"] = "query_failed"
local["warning"] = ("PostHog query failed - showing this machine "
"only. Check the personal API key in Settings.")
- return local
- return _usage_local_report()
+ return _usage_attach_local(local)
+ local = _usage_local_report()
+ local["fleet_blocked"] = "no_key"
+ return _usage_attach_local(local)
def _scale_dims_to_max(width: int, height: int, max_dim: int,
@@ -15972,7 +16401,9 @@ class WarmHelper:
# single most-reported failure in the fleet (85 events, 7 installs in
# a week) and names no cause, no remedy and nothing to search for.
# These are the lines that do.
- self._boot_tail: collections.deque = collections.deque(maxlen=14)
+ # Wide enough that a traceback's frames survive an argument dump
+ # printed under the exception (see failure_frame).
+ self._boot_tail: collections.deque = collections.deque(maxlen=40)
def _ensure(self) -> None:
with self.lock:
@@ -17900,6 +18331,14 @@ def _sb_h3_cost(quality_key: str, length_key: str):
except Exception:
turbo = False
minutes = cell.get("turbo_min") if turbo else cell.get("eta_min")
+ # A Draft/Standard/High cell renders Fast when it is installed
+ # (make_job's default), whatever Turbo says.
+ if cell.get("tristep_min") and cell.get("tristep_default"): # Fast by default
+ try:
+ if h3_tristep_status().get("available"):
+ minutes = cell["tristep_min"]
+ except Exception:
+ pass
return float(minutes) * 60.0 if minutes else None
except Exception:
return None
@@ -20300,6 +20739,25 @@ def _sb_music_head(music: dict | None, n_inputs: int) -> str:
return head
+# THE DE-CLICK. A hard butt join between two clips' sound is a step in the
+# waveform, and a step is a click. 12 ms is under a frame (41.7 ms at 24 fps),
+# far too short to hear as a fade, and long enough to round the step off. It
+# is a RENDER-ONLY safety term, like the limiter: the browser preview sets an
+# element's volume per frame and cannot ramp inside 12 ms, and an NLE applies
+# its own. Owner, 2026-09-17: "the cuts are very rough in terms of sound".
+SB_DECLICK_S = 0.012
+
+
+def _sb_declick_term(d: float, length: float) -> str:
+ """`,afade=in…,afade=out…` for a sound `length` seconds long, or "" when
+ the de-click is off or the sound is too short to carry two fades."""
+ d = float(d or 0.0)
+ if d <= 0 or float(length) < 4 * d:
+ return ""
+ return (f",afade=t=in:d={d:g},"
+ f"afade=t=out:st={float(length) - d:.6f}:d={d:g}")
+
+
def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
rate: int, pix_fmt: str,
cuts: dict | None = None,
@@ -20309,9 +20767,15 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
segments: list[dict] | None = None,
scale_to: int = 0, grain: int = 0,
sound_strips: list | None = None,
- sound_base: int = 0) -> tuple[str, str]:
+ sound_base: int = 0,
+ declick: float = 0.0) -> tuple[str, str]:
"""The concat FILTER graph for a mixed-geometry cut → (graph, video_label).
+ `declick` (seconds, 0 = off) fades the head and the tail of every clip's
+ sound by that much, so a butt join between two clips cannot click. The
+ timeline render passes `SB_DECLICK_S`; every other caller builds the graph
+ it always did.
+
`sound_strips` are the audio TRACKS' strips (A3, A4, …), from
`storyboard_editor.track_render_strips`, and `sound_base` the ffmpeg input
index of the first of them (one `-i` per row, in order). Each is trimmed to
@@ -20485,6 +20949,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
f"asetpts=PTS-STARTPTS,{tempo}aresample={rate},"
f"aformat=sample_fmts=fltp:channel_layouts=stereo,"
f"apad,atrim=0:{L['len']:.6f},asetpts=PTS-STARTPTS"
+ f"{_sb_declick_term(declick, L['len'])}"
f"{vtail}[a{idx}]")
pads.append(f"[v{idx}]")
continue
@@ -20498,6 +20963,7 @@ def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,
f"{ahead}aresample={rate},"
f"aformat=sample_fmts=fltp:channel_layouts=stereo,"
f"apad,atrim=0:{dur},asetpts=PTS-STARTPTS"
+ f"{_sb_declick_term(declick, float(dur))}"
f"{vtail}[a{idx}]")
else:
# A still and a slug are silent by construction; a silent clip is
@@ -20925,7 +21391,8 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,
music_mode: str = "replace",
music_gain: list | None = None,
deliver: dict | None = None,
- sound_strips: list | None = None) -> dict:
+ sound_strips: list | None = None,
+ declick: float = 0.0) -> dict:
"""Concatenate the exported shots into ONE playable film.
`sound_strips` (from `storyboard_editor.track_render_strips`) are the audio
@@ -21092,7 +21559,8 @@ def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,
overlay_base=overlay_base,
scale_to=scale_to, grain=dl["grain"],
sound_strips=strip_rows,
- sound_base=overlay_base + len(ov_inputs))
+ sound_base=overlay_base + len(ov_inputs),
+ declick=declick)
cmd = [str(FFMPEG), "-y"]
if segments is not None:
@@ -21319,11 +21787,19 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,
push(f"[timeline] rendering {len(cuts)} clip(s) → {name}"
+ (f" ({kinds.get('still', 0)} still, {kinds.get('slug', 0)} black)"
if (kinds.get("still") or kinds.get("slug")) else ""))
- # `under` keeps the clips' own audio and ducks the bed beneath it. It is
- # the right default for anything with a voice in it, but `replace` stays
- # the default HERE because a beat-cut music video wants the track and
- # nothing else, and that is what this path has always done.
- mmode = str(music_mode or audio.get("mode") or "replace").lower()
+ # `under` keeps the clips' own audio and ducks the bed beneath it;
+ # `replace` throws every clip's sound away and plays the bed alone.
+ #
+ # The DEFAULT IS `under`, and it was `replace` until 2026-09-18: Saint
+ # Feld (13 shots of dialogue, a 20 s bed) rendered with 21 seconds of
+ # DIGITAL SILENCE in it — every shot whose sound was not also a strip on
+ # a lane came out mute, because the bed replaced it and the bed is 20 s
+ # long. Meanwhile the Editor's own selector reads "under the clips"
+ # (editor.js: `sbeSetMusicMode(... || 'under')`) and only posts
+ # `music_mode` when there IS a soundtrack — so the screen said one thing
+ # and this function did another. A music video loses nothing by the
+ # change: ducking a bed under silent clips plays the bed.
+ mmode = str(music_mode or audio.get("mode") or "under").lower()
# `timeline=` rather than `clips=` + `plan=`: the cut list is the film now,
# kinds and all. A slug has no path, so it could never have appeared in the
# `clips` argument, and a still's `-i` needs `-loop 1 -t` in front of it —
@@ -21338,7 +21814,7 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,
music_end=win["end"], music_delay=win["delay"], music_mode=mmode,
music_gain=sedit.bed_render_gain(edit),
overlays=sedit.overlay_items(edit),
- deliver=dl, sound_strips=strips or None)
+ deliver=dl, sound_strips=strips or None, declick=SB_DECLICK_S)
film["gaps"] = gaps
if gaps:
# An honest limitation, disclosed rather than discovered: this
@@ -21350,6 +21826,9 @@ def _sbe_render_edit(board: dict, edit: dict, *, music=None,
f"concatenation — the film is that much shorter than the "
f"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.
+ film["music_mode"] = mmode
return film
@@ -22193,6 +22672,81 @@ def _sbe_add_sound(board: dict, path: str) -> dict:
"imported": imported}
+def _sbe_room_tone_dir(board: dict) -> Path:
+ """Where the film's room-tone beds live: `<film>/audio/room_tone/`. Under
+ OUTPUT so the preview can play them, and one level below `audio/` so the
+ Sound pool (which lists `audio/` itself) is not filled with takes."""
+ return _sbe_sound_dir(board) / "room_tone"
+
+
+def _sbe_room_tone(board: dict, *, variant: str = "film", seed: int = 1,
+ film_len: float = 0.0, clips: list | None = None,
+ strict: bool = False) -> dict:
+ """Make (or reuse) a room-tone bed for this film → `room_tone.make_bed`'s
+ facts plus `ok`. `clips` are `[{path, start, end}]` in source seconds —
+ the timeline the user is looking at, which may be ahead of the saved one.
+ Only files that exist are read. CPU and about a second; no GPU, no queue."""
+ import room_tone as rt # noqa: PLC0415
+ if variant not in rt.variant_ids():
+ return {"ok": False, "status": 400, "error": f"unknown room tone: {variant}"}
+ rows = []
+ for c in clips or []:
+ if not isinstance(c, dict):
+ continue
+ pth = str(c.get("path") or "")
+ try:
+ st = max(0.0, float(c.get("start") or 0.0))
+ en = float(c.get("end") or 0.0)
+ except (TypeError, ValueError):
+ continue
+ if pth and en > st and Path(pth).is_file():
+ rows.append({"path": pth, "start": st, "end": en})
+ t0 = time.time()
+ facts = rt.make_bed(_sbe_room_tone_dir(board), variant=variant, seed=seed,
+ film_len=film_len, clips=rows, strict=strict)
+ if not facts.get("path"):
+ return {"ok": False, "status": 422, **facts,
+ "error": f"no room tone from this film: {facts.get('fallback')}"}
+ if not facts.get("reused"):
+ push(f"[timeline] room tone: {facts['label']} (take {facts['seed']}, "
+ f"{facts['duration']:g} s) in {time.time() - t0:.1f} s"
+ + (f" — {facts['fallback']}, so a preset stands in"
+ if facts.get("fallback") else ""))
+ return {"ok": True, **facts}
+
+
+def _sbe_room_tone_auto(board: dict, edit: dict, sedit) -> None:
+ """Lay a "From this film" bed under an automatic cut, when the setting is
+ on. Mutates `edit`. Best-effort: a bed that cannot be made is a log line,
+ never a failed cut."""
+ if not bool(get_settings().get("room_tone_auto", True)):
+ return
+ if sedit.room_tone_track(edit) or not (edit.get("clips") or []):
+ return
+ # A MUSIC VIDEO IS LEFT ALONE: a soundtrack in `replace` mode throws the
+ # clips' own sound away, so there are no cuts in the sound to smooth and a
+ # bed would only be hiss under the song.
+ aud = edit.get("audio") or {}
+ if aud.get("path") and str(aud.get("mode") or "replace").lower() == "replace":
+ return
+ clips = [{"path": c.get("path"), "start": c.get("start"), "end": c.get("end")}
+ for c in edit.get("clips") or []
+ if isinstance(c, dict) and sedit.clip_kind(c) == "video"]
+ film_len = sedit.edit_duration(edit)
+ try:
+ import room_tone as rt # noqa: PLC0415
+ facts = _sbe_room_tone(board, variant="film", seed=1,
+ film_len=film_len, clips=clips, strict=True)
+ if not facts.get("ok"):
+ push(f"[timeline] no automatic room tone: {facts.get('error')}")
+ return
+ track = sedit.room_tone_new_track(facts, film_len, level=rt.DEFAULT_LEVEL)
+ except Exception as exc: # noqa: BLE001
+ push(f"[timeline] room tone skipped: {type(exc).__name__}: {exc}")
+ return
+ edit["audio_tracks"] = list(edit.get("audio_tracks") or []) + [track]
+
+
def _sbe_proxy_now(board_dir: Path, paths: list[str], sedit) -> dict:
"""Build proxies for EXACTLY these paths, and prune nothing.
@@ -22275,13 +22829,16 @@ def _sbe_auto_edit(board: dict, *, music: str | None = None,
audio = {"path": str(music), "offset": 0.0,
"peaks": "peaks.json" if peaks else None,
"duration": dur}
- return sedit.edit_from_plan(
+ edit = sedit.edit_from_plan(
plan, board_id=board["id"], audio=audio, beats=beats,
proxies=_sbe_proxy_map(bdir, clips, sedit),
labels={c["path"]: f"S{(c.get('n') or 0):02d} · {c['title']}"
for c in clips},
settings={"target_seconds": target_seconds, "min_shot": min_shot,
"max_shot": max_shot})
+ # ROOM TONE UNDER EVERY CUT THE MACHINE MAKES (setting `room_tone_auto`).
+ _sbe_room_tone_auto(board, edit, sedit)
+ return edit
def _sbe_relinks(board: dict, edit: dict) -> list[dict]:
@@ -22728,6 +23285,36 @@ def failure_line(tail) -> str:
return lines[-1]
+#: `File "<path>", line N, in <func>` — one Python traceback frame.
+_TB_FRAME_RX = re.compile(r'^\s*File "([^"]+)", line (\d+), in (\S+)')
+
+
+def failure_frame(tail) -> str:
+ """`file.py:LINE in func` for the deepest frame in a traceback tail.
+
+ The exception sentence alone is not a diagnosis. Fleet 2026-09-18: two
+ `standard_15s` I2V renders on 4.14.3 died with
+ `TypeError: repeat(): incompatible function arguments` and nothing else —
+ and `repeat` appears in exactly one place in the engine, which is not
+ enough to tell a live-preview decode from a VAE upsample. The frame is
+ what turns that into a line of code. Basename only: a user's folder names
+ are theirs, and the file is ours.
+ """
+ frame = ""
+ for line in [str(t) for t in tail if str(t or "").strip()]:
+ m = _TB_FRAME_RX.match(line)
+ if m:
+ frame = f"{Path(m.group(1)).name}:{m.group(2)} in {m.group(3)}"
+ return frame
+
+
+def failure_where(tail) -> str:
+ """`failure_line` plus the frame that raised it, when there is one."""
+ cause = failure_line(tail)
+ frame = failure_frame(tail)
+ return f"{cause} (at {frame})" if cause and frame else cause
+
+
def _helper_start_failure(ready: dict | None, tail) -> str:
"""The sentence the user gets when the render helper never comes up.
@@ -22738,7 +23325,7 @@ def _helper_start_failure(ready: dict | None, tail) -> str:
`helper failed to start: {'event': 'exit', 'reason': 'python_normal_exit'}`
— which means "it printed a traceback and exited" and told nobody that.
"""
- cause = failure_line(tail)
+ cause = failure_where(tail)
event = (ready or {}).get("event") if isinstance(ready, dict) else None
if ready is None:
what = "it never reported ready"
@@ -23279,6 +23866,15 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# or a curl must never reach the worker asking for an adapter this install
# doesn't have).
_h3_turbo = (f("h3_turbo", "") or "").strip().lower() in ("1", "true", "on", "yes")
+ # Speed switch: "1" = Fast (TaoMate 3-step adapter), "0" = Best (the
+ # shape's own sampler), absent/"auto" = the default: Fast on Draft,
+ # Standard and High when installed, unless a Steps pin says which sampler
+ # depth this render wants. Resolved against the FINAL cell below.
+ _h3_tristep_raw = (f("h3_tristep", "") or "").strip().lower()
+ _h3_tristep_want = (True if _h3_tristep_raw in ("1", "true", "on", "yes")
+ else False if _h3_tristep_raw in ("0", "false", "off", "no")
+ else None)
+ _h3_tristep = False
# Which of the runner's ONE adapter slots this render spends. H3's
# `--lora` is a single path (`default=None`, not `action="append"` — see
# scripts/generate_staged.py), so a user LoRA and Turbo are mutually
@@ -23339,6 +23935,39 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
+ "; ".join(_turbo["missing"]) + ")."
) + f" Rendering at this shape's own {H3_TIERS[_h3_tier]['steps']} steps.")
_h3_turbo = False
+ # Fast. The default on Draft/Standard/High; never on Native or the
+ # dense pass; only when installed; never together with Turbo (two
+ # step-distillation adapters on one render is a recipe nobody
+ # validated) — Fast wins when both arrive, and says so. A Steps pin
+ # keeps Best unless the form explicitly asked for Fast.
+ if _h3_tristep_want is not False and h3_available():
+ _tcell = H3_TIERS[_h3_tier]
+ if not h3_cell_takes_tristep(_tcell):
+ if _h3_tristep_want:
+ push("Fast (3 steps) runs on Draft, Standard and High "
+ f"(5 s windows) — rendering {_tcell['label']} at Best.")
+ elif not _h3_tristep_want and not h3_cell_tristep_default(_tcell):
+ pass # a canvas where Fast is not the default
+ elif _h3_tristep_want or not _h3_steps:
+ _tri = h3_tristep_status()
+ if _tri["available"]:
+ _h3_tristep = True
+ elif _h3_tristep_want:
+ push("Fast (3 steps) requested but " + (
+ "this H3 runner has no --sigma-subset — update the H3 "
+ "runner." if not _tri["supported"] else
+ "its adapter isn't downloaded ("
+ + "; ".join(_tri["missing"]) + ").")
+ + " Rendering at Best.")
+ if _h3_tristep:
+ if _h3_turbo:
+ push("Fast (3 steps): Turbo is not stacked on the 3-step "
+ "adapter — Turbo is off for this render.")
+ _h3_turbo = False
+ if _h3_steps:
+ push(f"Fast runs {H3_TRISTEP_FORWARDS} forwards on "
+ f"its own ladder — ignoring the {_h3_steps}-step override.")
+ _h3_steps = 0
# Per-window prompts, matched to the cell that will ACTUALLY render.
# Normalising after the fallback above is the whole point: a 15 s
# request that degraded to 5 s has one window, and three prompts on a
@@ -23469,6 +24098,10 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# this dict — leaving `h3_turbo` out of here is how the control
# would look wired, pass validation, and silently render at 9.
"h3_turbo": _h3_turbo,
+ # Speed switch: Fast (TaoMate adapter + its sigma ladder) or not,
+ # resolved above. SAME allowlist trap: leave it out and the switch
+ # silently renders Best.
+ "h3_tristep": _h3_tristep,
# Which of H3's ONE adapter slots this render spends: "turbo"
# (default) or "user". SAME allowlist trap as every key in this
# dict — leave `h3_lora_slot` out and the Turbo-vs-LoRA control
@@ -23693,6 +24326,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# both ride the SAME path the tier default does (nothing downstream
# branches on WHY the count is what it is).
job["params"]["steps"] = int(
+ H3_TRISTEP_STEPS if _h3_tristep else
h3_turbo_steps() if _h3_turbo else (_h3_steps or _tier_cfg["steps"]))
job["params"]["h3_chain_windows"] = int(_tier_cfg.get("chain_windows") or 1)
job["params"]["h3_window_frames"] = int(
@@ -24833,7 +25467,7 @@ def run_train_job_inner(job: dict) -> None:
# be PLACED (#61): the caption encode is the phase that dies on some
# chips, and the only one worth relaunching — see _train_encode_retry.
_train_phase = "start"
- _train_env = {**os.environ}
+ _train_env = trainer_child_env()
_encode_retried = False
try:
while True:
@@ -25236,7 +25870,7 @@ def run_train_job_inner(job: dict) -> None:
stderr=subprocess.STDOUT,
text=True, errors="replace",
bufsize=1,
- env={**os.environ},
+ env=trainer_child_env(),
# Same reasoning as the face trainer above — own pgid so
# /stop can SIGTERM the whole audio tree at once.
start_new_session=True,
@@ -26068,6 +26702,37 @@ def run_h3_job_inner(job: dict) -> None:
turbo_paths = h3_turbo_paths()
steps = h3_turbo_steps(turbo_paths)
+ # ---- Speed "Fast": TaoMate 3-step adapter + its sigma ladder ----------
+ # make_job resolved it; re-check here for the same reason as Turbo (a
+ # queued job outlives the file), and keep the two adapters exclusive even
+ # for a hand-edited queue entry.
+ tristep = bool(p.get("h3_tristep"))
+ tristep_paths: dict = {}
+ if tristep and not h3_cell_takes_tristep(tier):
+ tristep = False
+ p["h3_tristep"] = False
+ push(f"[h3] Fast (3 steps) runs on Draft, Standard and High — "
+ f"{tier['label']} renders at Best.")
+ if tristep:
+ if turbo:
+ turbo = False
+ p["h3_turbo"] = False
+ turbo_paths = {}
+ push("[h3] Turbo is not stacked on Fast (3 steps) — Turbo off.")
+ if not h3_supports_sigma_subset():
+ raise RuntimeError(
+ "Fast (3 steps) needs `--sigma-subset`: "
+ + _h3_runner_behind("--sigma-subset", paths["runner"],
+ "Or pick Best under Speed."))
+ tristep_paths = h3_tristep_paths()
+ if not tristep_paths["files_ok"]:
+ raise RuntimeError(
+ "Fast's 3-step adapter isn't on disk: "
+ + "; ".join(tristep_paths["missing"])
+ + f". Expected under {tristep_paths['dir']} — pick Best under "
+ f"Speed, or click Fast to install it (180 MB).")
+ steps = H3_TRISTEP_STEPS
+
# First-frame conditioning (Image mode). The flag landed on the runner
# after the first public branch, so probe the INSTALLED script rather than
# assuming; an older pack renders Text fine and must fail here with a
@@ -26261,7 +26926,9 @@ def run_h3_job_inner(job: dict) -> None:
# delivery render can silently pick up a draft decoder.
tae_used = False
_tae = None
- if tier.get("draft") and h3_supports_tae_draft():
+ # NOT on a Fast draft: its owner-approved look is the full VAE
+ # decode, and it is the clip an Upscale & Face Fix pass starts from.
+ if tier.get("draft") and not tristep and h3_supports_tae_draft():
_tae = h3_tae_checkpoint()
if _tae is not None:
cmd += ["--draft-decode", "tae", "--tae-checkpoint", str(_tae)]
@@ -26293,6 +26960,11 @@ def run_h3_job_inner(job: dict) -> None:
# CLI still requires PATH:SCALE; 1.0 means "as repacked". Never pass
# the raw v0.1 file here — its missing alpha/rank fold renders noise.
cmd += h3_turbo_argv(turbo_paths)
+ if tristep:
+ # The adapter first, then the user's stack — each `--lora` is one more
+ # delta on the same base layers (416 wrapped, 0 unaccounted measured
+ # with a character + a style LoRA on top).
+ cmd += h3_tristep_argv(tristep_paths)
if user_lora is not None and (not turbo or h3_supports_lora_stack()):
# The SAME flag Turbo rides. On a stacking runner every `--lora` is one
# more adapter on the same base layers, Turbo first; on the single-slot
@@ -26315,6 +26987,8 @@ def run_h3_job_inner(job: dict) -> None:
f"{steps} sigma points ({steps - 1} forwards) · seed {seed}"
+ (" · Q8 DiT (low-RAM)" if _dit_kind == "q8" else "")
+ (" · Turbo (4-step distill LoRA)" if turbo else "")
+ + (f" · Fast, 3 steps (TaoMate adapter {tristep_paths['version']}, "
+ f"σ subset {H3_TRISTEP_SIGMA_SUBSET})" if tristep else "")
+ (f" · LoRA {user_lora.name} @ {user_lora_strength:g}"
if (user_lora is not None and not turbo) else "")
+ (" · fast draft decode (TAE)" if tae_used else "")
@@ -26452,7 +27126,11 @@ def run_h3_job_inner(job: dict) -> None:
# see and users rarely paste). Traceback tails are what we want.
# Deep enough to hold a whole Python traceback's tail: the line that
# names the exception can sit several lines above the last one.
- _h3_tail: collections.deque = collections.deque(maxlen=14)
+ # 40, not 14: nanobind prints its whole accepted-signature block
+ # under the exception, which pushed every `File "...", line N`
+ # frame out of the window — so the fleet got an exception with no
+ # line of code behind it (4.14.3 `repeat()` I2V crashes).
+ _h3_tail: collections.deque = collections.deque(maxlen=40)
for raw in _h3_lines():
line = raw.rstrip("\n")
if not line.strip():
@@ -26598,7 +27276,7 @@ def run_h3_job_inner(job: dict) -> None:
raise RuntimeError(
f"H3 helper exited from {_sig} ({_hint}) — see the log "
f"above (metrics at {metrics_path}).")
- _last = failure_line(_h3_tail)
+ _last = failure_where(_h3_tail)
raise RuntimeError(
f"H3 render exited with code {rc}"
+ (f" — last line: {_last[:220]}" if _last else "")
@@ -26728,6 +27406,8 @@ def run_h3_job_inner(job: dict) -> None:
# Turbo") rather than an absence the reader has to guess about —
# this is what Load Params, Draft → Finish and the ⓘ modal read.
"h3_turbo": turbo,
+ # Same rule for the fast 3-step sampler (False = the shape's own).
+ "h3_tristep": tristep,
"width": width, "height": height, "frames": frames, "steps": steps,
"seed_used": seed,
# The user's OWN reference, not the canvas crop made from it: the
@@ -26796,6 +27476,28 @@ def run_h3_job_inner(job: dict) -> None:
"accounting": (metrics.get("lora_accounting")
or metrics.get("w1_lora_accounting"))}
if turbo else None),
+ # The fast 3-step sampler's provenance: which file, where it came from,
+ # under what license, and the schedule the runner actually ran.
+ "tristep": ({"lora": str(tristep_paths["lora"]),
+ "adapter_version": tristep_paths["version"],
+ "repo": H3_TRISTEP_REPO,
+ "revision": H3_TRISTEP_REVISION,
+ "sha256": (H3_TRISTEP_SHA256
+ if tristep_paths["version"] == "r19-kijai"
+ else None),
+ "source_repo": H3_TRISTEP_SOURCE_REPO,
+ "license": H3_TRISTEP_LICENSE,
+ "scale": 1.0,
+ "steps": steps,
+ "forwards": H3_TRISTEP_FORWARDS,
+ "sigma_subset": H3_TRISTEP_SIGMA_SUBSET,
+ "decode": "full"}
+ if tristep else None),
+ # The sigma ladder each window ran (runner's own record).
+ "schedule": (metrics.get("schedule") or metrics.get("w1_schedule")),
+ # Every adapter the runner wrapped, and the must-be-zero count.
+ "lora_accounting": (metrics.get("lora_accounting")
+ or metrics.get("w1_lora_accounting")),
"chain_windows": chain_windows,
"window_frames": window_frames,
# The RESOLVED shot list — blanks already filled from the main
diff --git a/panel/routes_image.py b/panel/routes_image.py
index f86cafa..372ec48 100644
--- a/panel/routes_image.py
+++ b/panel/routes_image.py
@@ -429,6 +429,18 @@ def post_h3_turbo_install(h, path, qs, ctype) -> None:
h._json(result, 202)
+# ====== Hailuo H3 Draft · fast 3-step — fetch TaoMate's 3-step adapter
+# (Kijai's 182 MB conversion, pinned revision + sha256, resumable).
+@post("/h3/tristep/install")
+def post_h3_tristep_install(h, path, qs, ctype) -> None:
+ P.h3_status_invalidate()
+ result = P._h3_install_tristep(P.push)
+ if not result.get("ok"):
+ h._json(result, 409 if "active" in result.get("error", "") else 400)
+ return
+ h._json(result, 202)
+
+
# Image-engine config (pluggable: mock | bfl).
@post("/agent/image/config")
def post_agent_image_config(h, path, qs, ctype) -> None:
diff --git a/panel/routes_storyboard.py b/panel/routes_storyboard.py
index ec75876..df81ec1 100644
--- a/panel/routes_storyboard.py
+++ b/panel/routes_storyboard.py
@@ -155,6 +155,59 @@ def post_storyboard_edit_add_sound(h, path, qs, ctype) -> None:
200 if out.get("ok") else int(out.get("status") or 400))
+# ====== Room tone — a generated bed under the whole film ============
+# The picker's rows and the numbers the Room tone card needs. Read-only.
+@get("/storyboard/edit/room-tone")
+def get_storyboard_edit_room_tone(h, parsed) -> None:
+ import room_tone as rt # noqa: PLC0415
+ h._json({"ok": True, "variants": rt.variants(),
+ "default_variant": rt.DEFAULT_VARIANT,
+ "default_level": rt.DEFAULT_LEVEL,
+ "level_min": rt.LEVEL_MIN, "level_max": rt.LEVEL_MAX,
+ "ref_lufs": rt.REF_LUFS,
+ "auto": bool(P.get_settings().get("room_tone_auto", True))})
+
+
+# Make (or reuse) one bed. The client sends the timeline it is showing —
+# `clips` as JSON `[{path, start, end}]` and `film_len` — because a room tone
+# "from this film" must be made from the cut on screen, saved or not. The
+# track itself is placed by the client, like every other sound.
+@post("/storyboard/edit/room-tone")
+def post_storyboard_edit_room_tone(h, path, qs, ctype) -> None:
+ import json as _json # noqa: PLC0415
+ _rb = h._read_form_body()
+ if _rb is None:
+ return
+ _body, form = _rb
+
+ def f(name: str) -> str:
+ v = form.get(name) or [""]
+ return str(v[0] if isinstance(v, list) else v).strip()
+
+ try:
+ board = P.storyboard.load_storyboard(P.STATE_DIR, f("id"))
+ except Exception as exc: # noqa: BLE001
+ h._json({"ok": False, "error": str(exc)}, 404)
+ return
+ try:
+ clips = _json.loads(f("clips") or "[]")
+ if not isinstance(clips, list):
+ raise ValueError("clips must be a list")
+ seed = int(f("seed") or 1)
+ film_len = float(f("film_len") or 0.0)
+ except (ValueError, TypeError) as exc:
+ h._json({"ok": False, "error": f"bad room tone request: {exc}"}, 400)
+ return
+ try:
+ out = P._sbe_room_tone(board, variant=f("variant") or "film", seed=seed,
+ film_len=film_len, clips=clips)
+ except Exception as exc: # noqa: BLE001
+ out = {"ok": False, "status": 500,
+ "error": f"could not make the room tone: {exc}"}
+ h._json({k: v for k, v in out.items() if k != "status"},
+ 200 if out.get("ok") else int(out.get("status") or 400))
+
+
# ====== Storyboard — plan a film, then shoot it ====================
# Sits with the /queue/* cluster on purpose: every one of these routes
# ends up going through the SAME make_job -> STATE["queue"] contract
diff --git a/panel_assets/stats.html b/panel_assets/stats.html
index ccefbf0..73a8c7c 100644
--- a/panel_assets/stats.html
+++ b/panel_assets/stats.html
@@ -298,6 +298,15 @@
-webkit-text-fill-color: transparent;
color: transparent;
}
+ /* A hero that cannot be answered must not look like a zero, and must not
+ wear the brand gradient as if it were a result: muted, plain, and its
+ caption carries the remedy rather than a unit. */
+ .kpi.is-hero.is-unknown .value {
+ background: none;
+ -webkit-text-fill-color: initial;
+ color: var(--muted, #8b93a7);
+ }
+ .kpi.is-unknown .delta { color: var(--warn, #d29922); }
.kpi .deltas {
display: flex; gap: 10px; flex-wrap: wrap;
margin-top: 8px;
@@ -900,50 +909,6 @@
<!-- ============================================================
RIGHT NOW — KPI strip with sparklines + health pulse.
============================================================ -->
- <section class="card" id="sec-now">
- <div class="section-head">
- <h2>Right now <span class="h2-sub">snapshot from latest fetch</span></h2>
- </div>
- <div class="kpi-grid" id="kpi-grid" aria-busy="true" aria-label="Current repository stats">
- <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
- <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
- <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
- <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
- <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
- <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
- </div>
- </section>
-
- <!-- ============================================================
- NEEDS ATTENTION — live board of the actual open issues + PRs.
- Populated from the latest snapshot's `open_items` array (added
- by scripts/fetch_repo_stats.py). Hidden entirely if the fetcher
- predates the field (older snapshot) so old data degrades cleanly.
- ============================================================ -->
- <section class="card" id="sec-attention" hidden>
- <div class="section-head">
- <h2>Needs attention <span class="h2-sub">open issues &amp; pull requests · newest first</span></h2>
- <a class="icon-btn" id="attention-repo-link"
- href="https://github.com/mrbizarro/phosphene/issues"
- target="_blank" rel="noopener"
- title="Open the issues + PRs on GitHub">
- <span class="ico">↗</span> on GitHub
- </a>
- </div>
- <div class="board">
- <div class="board-col">
- <h3>Open issues <span class="count-pill" id="attn-issues-count">0</span></h3>
- <ul class="board-list" id="attn-issues-list"></ul>
- <div class="board-more" id="attn-issues-more" hidden></div>
- </div>
- <div class="board-col">
- <h3>Open PRs <span class="count-pill" id="attn-prs-count">0</span></h3>
- <ul class="board-list" id="attn-prs-list"></ul>
- <div class="board-more" id="attn-prs-more" hidden></div>
- </div>
- </div>
- </section>
-
<!-- ============================================================
USAGE — anonymous panel telemetry. Independent of /stats/data:
it reads /stats/usage, which always answers (local aggregates
@@ -1015,7 +980,51 @@
<!-- ============================================================
FUNNEL — Views → Clones → Stars → Forks.
============================================================ -->
- <section class="card" id="sec-funnel">
+ <section class="card" id="sec-now">
+ <div class="section-head">
+ <h2>Right now <span class="h2-sub">snapshot from latest fetch</span></h2>
+ </div>
+ <div class="kpi-grid" id="kpi-grid" aria-busy="true" aria-label="Current repository stats">
+ <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ </div>
+ </section>
+
+ <!-- ============================================================
+ NEEDS ATTENTION — live board of the actual open issues + PRs.
+ Populated from the latest snapshot's `open_items` array (added
+ by scripts/fetch_repo_stats.py). Hidden entirely if the fetcher
+ predates the field (older snapshot) so old data degrades cleanly.
+ ============================================================ -->
+ <section class="card" id="sec-attention" hidden>
+ <div class="section-head">
+ <h2>Needs attention <span class="h2-sub">open issues &amp; pull requests · newest first</span></h2>
+ <a class="icon-btn" id="attention-repo-link"
+ href="https://github.com/mrbizarro/phosphene/issues"
+ target="_blank" rel="noopener"
+ title="Open the issues + PRs on GitHub">
+ <span class="ico">↗</span> on GitHub
+ </a>
+ </div>
+ <div class="board">
+ <div class="board-col">
+ <h3>Open issues <span class="count-pill" id="attn-issues-count">0</span></h3>
+ <ul class="board-list" id="attn-issues-list"></ul>
+ <div class="board-more" id="attn-issues-more" hidden></div>
+ </div>
+ <div class="board-col">
+ <h3>Open PRs <span class="count-pill" id="attn-prs-count">0</span></h3>
+ <ul class="board-list" id="attn-prs-list"></ul>
+ <div class="board-more" id="attn-prs-more" hidden></div>
+ </div>
+ </div>
+ </section>
+
+<section class="card" id="sec-funnel">
<div class="section-head">
<h2>Discovery funnel <span class="h2-sub">how the repo converts pageviews to commitment</span></h2>
</div>
@@ -2606,15 +2615,36 @@
// as "since the app existed".
const firstDay = (((u.growth || {}).installs_by_day || [])[0] || {}).date;
const since = firstDay ? 'since ' + firstDay : 'all time';
+ // THE FLEET IS THE HEADLINE (owner, 2026-09-18: "when I ask you for total
+ // renders, I mean total renders from the fleet too… one of the first
+ // windows I want to see is total renders for all the fleet"). One tile
+ // used to be called "Total renders" and mean the fleet's total or THIS
+ // MAC's depending on whether a query key happened to be configured — a
+ // number whose meaning moved under the same label. Now the hero is always
+ // the fleet, it reads "—" with a remedy when the fleet cannot be reached,
+ // and this machine's own total is its own tile that never pretends to be
+ // anything else.
+ const m = u.machine || {};
+ const blocked = String(u.fleet_blocked || '');
+ const fleetSub = blocked === 'no_key'
+ ? 'add a PostHog read key in Settings'
+ : (blocked ? 'PostHog query failed — check the key in Settings'
+ : 'completed · all installs · ' + since);
const tiles = [
- { label: 'Total renders', value: fmt(t.total_renders),
- sub: isFleet ? 'completed · all installs · ' + since : 'completed · this machine · ' + since, hero: true },
+ { label: 'Total renders · fleet', value: isFleet ? fmt(t.total_renders) : '—',
+ sub: fleetSub, hero: true, warn: !isFleet },
+ { label: 'Total renders · this Mac',
+ value: fmt(isFleet ? m.total_renders : t.total_renders),
+ sub: 'completed' + (m.first_day || (!isFleet && firstDay)
+ ? ' · since ' + (m.first_day || firstDay) : '') },
{ label: isFleet ? 'Total installs' : 'Installs',
- value: fmt(t.total_installs), sub: isFleet ? 'ever booted · ' + since : 'this machine' },
+ value: isFleet ? fmt(t.total_installs) : '—',
+ sub: isFleet ? 'ever booted · ' + since : fleetSub },
{ label: isFleet ? 'Weekly active installs' : 'Active this week',
value: fmt(t.weekly_active_installs),
sub: isFleet ? 'unique installs · 7d' : 'this machine · 7d' },
- { label: 'Renders', value: fmt(t.renders_7d), sub: 'completed + failed · 14d' },
+ { label: 'Renders', value: fmt(t.renders_7d),
+ sub: 'completed + failed · 14d · ' + (isFleet ? 'all installs' : 'this machine') },
{ label: 'H3 share', value: fmtPct(t.h3_share_pct), sub: 'of renders · 14d' },
{ label: 'Error rate', value: fmtPct(t.error_rate_pct), sub: 'failed renders · 14d' },
{ label: 'Refused', value: fmt(t.refusals_7d), sub: 'declined on purpose · 7d' },
@@ -2622,7 +2652,7 @@
const grid = $('#usage-tiles');
if (grid) {
grid.innerHTML = tiles.map(k => `
- <div class="kpi${k.hero ? ' is-hero' : ''}">
+ <div class="kpi${k.hero ? ' is-hero' : ''}${k.warn ? ' is-unknown' : ''}">
<div class="label">${escapeHtml(k.label)}</div>
<div class="value">${k.value}</div>
<div class="delta">${escapeHtml(k.sub)}</div>
diff --git a/room_tone.py b/room_tone.py
new file mode 100644
index 0000000..89ae22f
--- /dev/null
+++ b/room_tone.py
@@ -0,0 +1,578 @@
+#!/usr/bin/env python3
+"""Room tone — a generated ambience bed that runs under a whole film.
+
+THE OWNER'S CASE (2026-09-17): "the cuts are very rough in terms of sound, and
+it's really annoying. If it was all over the timeline as an ambient sound, not
+something really subtle … it could be generated for the video each time."
+
+Measured on DIVORCE v2: the clips' own noise floors run from −23 to −68 dBFS,
+so a cut can drop the room by 26 dB in one frame. A continuous bed under the
+whole timeline hides that step, the way every film mixer lays room tone.
+
+WHAT THIS FILE DOES — numpy only, CPU, about a second:
+
+ * **From this film** (`film`): decode each timeline clip's window, keep its
+ quietest analysis windows (the room tone and tape hiss between lines),
+ average their spectra per clip, take the per-bin MEDIAN across clips. That
+ is the film's own ambience shape. Too little quiet → the "Quiet room"
+ preset, and the result says so.
+ * **Presets**: spectral tilt + resonant bands + hum harmonics + slow movement
+ (+ crickets / rain ticks), one parameter row each.
+ * **A new seed is a new take**, so there are as many versions as clicks.
+
+HOW IT STAYS SEAMLESS: the loop is built in the frequency domain — a magnitude
+per FFT bin times a random phase, then ONE inverse FFT over a `LOOP_S` grid. A
+signal made that way is periodic with exactly that period, so tiling it has no
+seam. Everything layered on top (hum on exact bins, the movement LFO, the
+cricket pulses, the rain ticks) completes whole cycles over the same grid.
+
+HOW LOUD: loudness is BS.1770 (K-weighted mean square, −0.691 offset), computed
+from the loop's own spectrum, which is exact for a periodic signal. The file is
+written at `REF_LUFS` (peak capped at −1 dBFS; if that cap bites, the real
+reference is returned) and the level the user picks becomes the TRACK FADER,
+`level_gain(level, ref)`. So a level change is instant and is the very number
+the render applies. Gating is not modelled: the bed moves by a few dB at most,
+and BS.1770's −70 LUFS / −10 LU gates never close on it.
+
+Run the CLI: python3 room_tone.py --variant film --clip a.mp4 --seconds 30 out.wav
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import os
+import shutil
+import subprocess
+import sys
+import wave
+from pathlib import Path
+
+import numpy as np
+
+SR = 48000
+LOOP_S = 40 # the periodic grid, seconds (bins are 1/40 Hz)
+REF_LUFS = -18.0 # what the file is written at
+PEAK_CAP = 10 ** (-1.0 / 20) # −1 dBFS
+DEFAULT_LEVEL = -27.0 # "not something really subtle"
+LEVEL_MIN, LEVEL_MAX = -45.0, -18.0
+DEFAULT_VARIANT = "film"
+FALLBACK_VARIANT = "quiet_room"
+MIN_QUIET_S = 1.5 # less usable quiet than this → fallback
+BED_STEP_S = 30 # file length is rounded up to this
+BED_MAX_S = 1800
+STEREO_CORR = 0.35 # shared share of the two channels' power
+WIN = 4096 # analysis window (85 ms)
+HOP = 2048
+
+# ---------------------------------------------------------------------------
+# THE PRESETS
+# ---------------------------------------------------------------------------
+# tilt: dB per octave around 1 kHz · hp/lp: 12 dB/oct corners · bands:
+# (centre Hz, dB, width in octaves) · hum: (Hz, dB relative to the broadband
+# RMS) · move: slow level movement, ± dB · lfo: which whole cycles over the
+# loop the movement is made of · extra: a texture layer.
+_PRESETS: list[dict] = [
+ {"id": "quiet_room", "label": "Quiet room",
+ "blurb": "A still interior — soft air, a faint mains hum.",
+ "tilt": -4.5, "hp": 40, "lp": 9000, "bands": [(120, 4, 0.8)],
+ "hum": [(50, -20)], "move": 1.0},
+ {"id": "living_room", "label": "Living room",
+ "blurb": "Warmer, a fridge somewhere in the flat.",
+ "tilt": -5.0, "hp": 30, "lp": 7000, "bands": [(90, 6, 0.7), (300, 2, 1.0)],
+ "hum": [(50, -18), (100, -24)], "move": 1.5},
+ {"id": "office", "label": "Office",
+ "blurb": "Air conditioning, fluorescent hum.",
+ "tilt": -3.0, "hp": 40, "lp": 12000, "bands": [(200, 5, 1.2), (1500, 2, 1.0)],
+ "hum": [(60, -20), (120, -22), (180, -28)], "move": 1.0},
+ {"id": "tv_studio", "label": "TV studio",
+ "blurb": "A big treated room — air handling, a bright top.",
+ "tilt": -2.5, "hp": 30, "lp": 14000, "bands": [(80, 5, 0.8), (2500, 3, 1.2)],
+ "hum": [(60, -24)], "move": 0.8},
+ {"id": "kitchen", "label": "Kitchen",
+ "blurb": "A fridge compressor and a hard room.",
+ "tilt": -4.0, "hp": 40, "lp": 10000, "bands": [(250, 3, 1.0), (1800, 2, 0.8)],
+ "hum": [(100, -10), (200, -16), (300, -22), (400, -26)], "move": 1.2},
+ {"id": "car", "label": "Car interior",
+ "blurb": "Road rumble, engine drone, moving.",
+ "tilt": -8.0, "hp": 20, "lp": 5000,
+ "bands": [(45, 10, 0.8), (110, 6, 0.8), (1000, 3, 1.5)],
+ "hum": [(32, -16)], "move": 2.5, "lfo": (1, 3, 7, 19, 31, 43)},
+ {"id": "outdoor_day", "label": "Outdoors, day",
+ "blurb": "Wind in gusts, open air.",
+ "tilt": -6.0, "hp": 25, "lp": 16000, "bands": [(60, 6, 1.2), (3500, 4, 1.5)],
+ "move": 4.0, "lfo": (1, 2, 3, 5, 9, 14)},
+ {"id": "night_outside", "label": "Night outside",
+ "blurb": "Still night air and crickets.",
+ "tilt": -3.0, "hp": 60, "lp": 12000, "bands": [(200, 2, 1.0)],
+ "move": 1.0, "extra": {"kind": "crickets", "fc": 4700, "db": -4}},
+ {"id": "city_street", "label": "City street",
+ "blurb": "Distant traffic, a low city wash.",
+ "tilt": -5.0, "hp": 25, "lp": 11000, "bands": [(70, 8, 1.0), (500, 4, 1.2)],
+ "move": 3.5, "lfo": (1, 2, 4, 7, 11)},
+ {"id": "rain", "label": "Rain",
+ "blurb": "Steady rain on a window.",
+ "tilt": -1.5, "hp": 150, "lp": 16000, "bands": [(2500, 5, 1.5), (8000, 3, 1.0)],
+ "move": 1.5, "extra": {"kind": "ticks", "per_s": 90, "db": -9}},
+ {"id": "vhs_tape", "label": "VHS tape",
+ "blurb": "Tape hiss, mains hum and the line whine.",
+ "tilt": 0.5, "hp": 60, "lp": 13000, "bands": [(4000, 4, 1.5)],
+ "hum": [(60, -14), (180, -22), (15734, -30)], "move": 0.5},
+ {"id": "big_hall", "label": "Big hall",
+ "blurb": "A large dark space, low and wide.",
+ "tilt": -7.0, "hp": 25, "lp": 5000, "bands": [(100, 6, 1.2), (400, 3, 1.0)],
+ "move": 2.0},
+ {"id": "plane_cabin", "label": "Plane cabin",
+ "blurb": "The steady roar of a cabin in flight.",
+ "tilt": -4.0, "hp": 30, "lp": 9000, "bands": [(300, 8, 1.2), (120, 5, 0.7)],
+ "hum": [(400, -22)], "move": 0.6},
+]
+PRESETS = {p["id"]: p for p in _PRESETS}
+FILM_VARIANT = {"id": "film", "label": "From this film",
+ "blurb": "Made from the quiet moments of your own clips."}
+
+
+def variants() -> list[dict]:
+ """The picker's rows, film first: `[{id, label, blurb}]`."""
+ return [dict(FILM_VARIANT)] + [
+ {"id": p["id"], "label": p["label"], "blurb": p["blurb"]} for p in _PRESETS]
+
+
+def variant_ids() -> list[str]:
+ return [v["id"] for v in variants()]
+
+
+def variant_label(vid: str) -> str:
+ for v in variants():
+ if v["id"] == vid:
+ return v["label"]
+ return str(vid)
+
+
+def clamp_level(v, default: float = DEFAULT_LEVEL) -> float:
+ try:
+ x = float(v)
+ except (TypeError, ValueError):
+ return default
+ if x != x:
+ return default
+ return round(max(LEVEL_MIN, min(LEVEL_MAX, x)), 2)
+
+
+def level_gain(level: float, ref: float = REF_LUFS) -> float:
+ """The track fader that turns a file at `ref` LUFS into `level` LUFS.
+ Capped at 1 — a fader never boosts (the tracks' model is 0..1)."""
+ g = 10 ** ((clamp_level(level) - float(ref)) / 20.0)
+ return round(max(0.0, min(1.0, g)), 6)
+
+
+def gain_level(gain: float, ref: float = REF_LUFS) -> float:
+ """The inverse: what level a fader value plays a bed at."""
+ g = max(1e-6, float(gain))
+ return round(float(ref) + 20 * math.log10(g), 2)
+
+
+def bed_seconds(film_len: float) -> int:
+ """The file length for a film: rounded UP to `BED_STEP_S`, so trims and
+ small moves never need a new file."""
+ n = max(0.0, float(film_len or 0.0)) + 0.5
+ return int(min(BED_MAX_S, max(BED_STEP_S, math.ceil(n / BED_STEP_S) * BED_STEP_S)))
+
+
+# ---------------------------------------------------------------------------
+# LOUDNESS — BS.1770 K-weighting, in the frequency domain
+# ---------------------------------------------------------------------------
+_K_SHELF = ((1.53512485958697, -2.69169618940638, 1.19839281085285),
+ (1.0, -1.69065929318241, 0.73248077421585))
+_K_HP = ((1.0, -2.0, 1.0), (1.0, -1.99004745483398, 0.99007225036621))
+
+
+def _biquad_power(b, a, freqs, sr=SR):
+ z = np.exp(-1j * 2 * np.pi * np.asarray(freqs, dtype=np.float64) / sr)
+ num = b[0] + b[1] * z + b[2] * z * z
+ den = a[0] + a[1] * z + a[2] * z * z
+ return np.abs(num / den) ** 2
+
+
+def k_weight_power(freqs, sr: int = SR) -> np.ndarray:
+ """|H_K(f)|² at 48 kHz — the two BS.1770 stages."""
+ return (_biquad_power(*_K_SHELF, freqs, sr) * _biquad_power(*_K_HP, freqs, sr))
+
+
+def loudness_lufs(x: np.ndarray, sr: int = SR) -> float:
+ """Ungated BS.1770 loudness of `x` ((channels, n) or (n,)), exact for a
+ periodic signal and a close estimate for a steady one."""
+ x = np.atleast_2d(np.asarray(x, dtype=np.float64))
+ n = x.shape[1]
+ if n < 2:
+ return -120.0
+ freqs = np.fft.rfftfreq(n, 1.0 / sr)
+ kw = k_weight_power(freqs, sr)
+ kw[0] = 0.0
+ total = 0.0
+ for ch in x:
+ X = np.fft.rfft(ch)
+ p = np.abs(X) ** 2 * kw
+ # Parseval: mean(x²) = (|X0|² + 2Σ|Xk|²) / n², Nyquist counted once.
+ s = 2.0 * p[1:].sum()
+ if n % 2 == 0:
+ s -= p[-1]
+ total += s / (n * n)
+ if total <= 0:
+ return -120.0
+ return round(-0.691 + 10 * math.log10(total), 3)
+
+
+# ---------------------------------------------------------------------------
+# SPECTRA
+# ---------------------------------------------------------------------------
+def _db_shape(p: dict, freqs: np.ndarray) -> np.ndarray:
+ f = np.maximum(freqs, 1.0)
+ db = float(p.get("tilt", -3.0)) * np.log2(f / 1000.0)
+ for fc, g, bw in p.get("bands") or []:
+ db += g * np.exp(-0.5 * (np.log2(f / fc) / bw) ** 2)
+ hp, lp = float(p.get("hp", 20)), float(p.get("lp", 16000))
+ db += -10 * np.log10(1 + (hp / f) ** 4) # 2nd order, 12 dB/oct
+ db += -10 * np.log10(1 + (f / lp) ** 4)
+ return db
+
+
+def _phases(rng, n):
+ return np.exp(1j * rng.uniform(0, 2 * np.pi, n))
+
+
+def _lfo(rng, n: int, ks, depth_db: float) -> np.ndarray:
+ """Slow level movement: whole cycles over the loop, peak ±depth dB."""
+ if depth_db <= 0:
+ return np.ones(n, dtype=np.float64)
+ t = np.arange(n, dtype=np.float64) / n
+ m = np.zeros(n)
+ for k in ks:
+ m += np.sin(2 * np.pi * k * t + rng.uniform(0, 2 * np.pi)) / math.sqrt(k)
+ m /= max(1e-9, np.abs(m).max())
+ return 10 ** (depth_db * m / 20.0)
+
+
+def _texture(extra: dict, rng, n: int, freqs: np.ndarray) -> np.ndarray | None:
+ """Crickets or rain ticks, periodic over the loop. Unit RMS."""
+ kind = (extra or {}).get("kind")
+ t = np.arange(n, dtype=np.float64) / n
+ if kind == "crickets":
+ fc = float(extra.get("fc", 4700))
+ band = np.exp(-0.5 * (np.log2(np.maximum(freqs, 1) / fc) / 0.06) ** 2)
+ carrier = np.fft.irfft(band * _phases(rng, freqs.size), n=n)
+ pulse = (0.5 + 0.5 * np.sin(2 * np.pi * 16 * LOOP_S * t)) ** 6
+ gate = np.clip(np.sin(2 * np.pi * 29 * t + rng.uniform(0, 6.28))
+ + 0.4 * np.sin(2 * np.pi * 83 * t + rng.uniform(0, 6.28)), 0, None)
+ y = carrier * pulse * np.sqrt(gate)
+ elif kind == "ticks":
+ count = int(float(extra.get("per_s", 80)) * LOOP_S)
+ imp = np.zeros(n)
+ pos = rng.integers(0, n, count)
+ np.add.at(imp, pos, rng.uniform(0.2, 1.0, count) * rng.choice([-1, 1], count))
+ shape = np.exp(-0.5 * (np.log2(np.maximum(freqs, 1) / 5000.0) / 1.2) ** 2)
+ y = np.fft.irfft(np.fft.rfft(imp) * shape, n=n) # periodic convolution
+ else:
+ return None
+ r = np.sqrt(np.mean(y * y))
+ return y / r if r > 0 else None
+
+
+def _add_hum(ch: np.ndarray, hum, rng, phases: dict) -> None:
+ n = ch.size
+ rms = math.sqrt(float(np.mean(ch * ch))) or 1e-6
+ t = np.arange(n, dtype=np.float64) / SR
+ for f, rel in hum or []:
+ k = round(f * LOOP_S) # an exact bin → whole cycles
+ if k <= 0 or k >= n // 2:
+ continue
+ ph = phases.setdefault(f, rng.uniform(0, 2 * np.pi))
+ ch += (rms * 10 ** (rel / 20.0) * math.sqrt(2)
+ * np.sin(2 * np.pi * (k / LOOP_S) * t + ph))
+
+
+def _synth(db: np.ndarray, rng, p: dict) -> np.ndarray:
+ """Two channels of periodic noise with the magnitude `db` (per rfft bin of
+ a LOOP_S grid), partly correlated, then hum, texture and movement."""
+ n = LOOP_S * SR
+ freqs = np.fft.rfftfreq(n, 1.0 / SR)
+ mag = 10 ** (db / 20.0)
+ mag[0] = 0.0
+ shared = np.fft.irfft(mag * _phases(rng, freqs.size), n=n)
+ out = np.empty((2, n))
+ for c in range(2):
+ own = np.fft.irfft(mag * _phases(rng, freqs.size), n=n)
+ out[c] = math.sqrt(STEREO_CORR) * shared + math.sqrt(1 - STEREO_CORR) * own
+ tex = _texture(p.get("extra") or {}, rng, n, freqs)
+ hum_ph: dict = {}
+ for c in range(2):
+ rms = math.sqrt(float(np.mean(out[c] ** 2))) or 1e-6
+ out[c] /= rms
+ if tex is not None:
+ out[c] += 10 ** (float(p["extra"].get("db", -6)) / 20.0) * np.roll(tex, c * 997)
+ _add_hum(out[c], p.get("hum"), rng, hum_ph)
+ lfo = _lfo(rng, n, p.get("lfo") or (1, 2, 3, 5, 8, 13), float(p.get("move", 1.0)))
+ return out * lfo
+
+
+# ---------------------------------------------------------------------------
+# FROM THIS FILM
+# ---------------------------------------------------------------------------
+def _ffmpeg() -> str:
+ for c in (os.environ.get("PHOSPHENE_FFMPEG"), shutil.which("ffmpeg"),
+ "/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg"):
+ if c and Path(c).exists():
+ return c
+ return "ffmpeg"
+
+
+def decode_window(path, start: float, end: float, sr: int = SR) -> np.ndarray:
+ """Mono float32 of `path` between two SOURCE seconds; empty when the file
+ has no sound."""
+ dur = max(0.0, float(end) - float(start))
+ if dur <= 0:
+ return np.zeros(0, dtype=np.float32)
+ cmd = [_ffmpeg(), "-v", "error", "-nostdin", "-ss", f"{max(0.0, float(start)):.6f}",
+ "-i", str(path), "-t", f"{dur:.6f}", "-map", "0:a:0?", "-vn", "-ac", "1",
+ "-ar", str(sr), "-f", "s16le", "-acodec", "pcm_s16le", "-"]
+ try:
+ r = subprocess.run(cmd, capture_output=True, timeout=300)
+ except (OSError, subprocess.SubprocessError):
+ return np.zeros(0, dtype=np.float32)
+ if r.returncode != 0:
+ return np.zeros(0, dtype=np.float32)
+ pcm = np.frombuffer(r.stdout[: len(r.stdout) // 2 * 2], dtype="<i2")
+ return pcm.astype(np.float32) / 32768.0
+
+
+def quiet_spectrum(x: np.ndarray) -> tuple[np.ndarray | None, float]:
+ """The average power spectrum of one clip's quiet windows → (psd, seconds).
+
+ Quiet = at or under the clip's own 25th percentile, under −30 dBFS, over
+ −80 dBFS (digital silence carries no room), and at least two windows away
+ from anything 10 dB louder than that percentile (a line's breath and
+ reverb tail are not room tone)."""
+ x = np.asarray(x, dtype=np.float64)
+ if x.size < WIN * 4:
+ return None, 0.0
+ idx = np.arange(0, x.size - WIN + 1, HOP)
+ frames = np.stack([x[i:i + WIN] for i in idx])
+ db = 10 * np.log10(np.mean(frames ** 2, axis=1) + 1e-12)
+ p25 = float(np.percentile(db, 25))
+ keep = (db <= min(p25, -30.0)) & (db > -80.0)
+ loud = db > p25 + 10.0
+ near = loud.copy()
+ for s in (1, 2):
+ near[s:] |= loud[:-s]
+ near[:-s] |= loud[s:]
+ keep &= ~near
+ if keep.sum() < 4:
+ return None, 0.0
+ w = np.hanning(WIN)
+ spec = np.abs(np.fft.rfft(frames[keep] * w, axis=1)) ** 2
+ return spec.mean(axis=0), float(keep.sum() * HOP / SR)
+
+
+def film_shape(clips, decoder=None) -> dict:
+ """The film's ambience: `{db (per WIN bin, 0 dB = unit power), quiet_s,
+ clips_used}` or `{db: None, ...}` when nothing usable was found.
+
+ `clips` is `[{path, start, end}]` in SOURCE seconds. Every clip's spectrum
+ is normalised to unit power first (shape, not level), and the per-bin
+ MEDIAN across clips keeps one noisy shot from owning the film."""
+ dec = decoder or decode_window
+ shapes, quiet, used = [], 0.0, 0
+ seen = set()
+ for c in clips or []:
+ path = str((c or {}).get("path") or "")
+ if not path:
+ continue
+ key = (path, round(float(c.get("start") or 0), 3), round(float(c.get("end") or 0), 3))
+ if key in seen:
+ continue
+ seen.add(key)
+ try:
+ x = dec(path, float(c.get("start") or 0.0), float(c.get("end") or 0.0))
+ except Exception: # noqa: BLE001
+ continue
+ psd, secs = quiet_spectrum(x)
+ if psd is None:
+ continue
+ tot = psd[1:].sum()
+ if tot <= 0:
+ continue
+ shapes.append(10 * np.log10(psd / tot + 1e-20))
+ quiet += secs
+ used += 1
+ if not shapes:
+ return {"db": None, "quiet_s": 0.0, "clips_used": 0}
+ return {"db": np.median(np.stack(shapes), axis=0), "quiet_s": round(quiet, 2),
+ "clips_used": used}
+
+
+# ---------------------------------------------------------------------------
+# THE BED
+# ---------------------------------------------------------------------------
+def _seed_int(variant: str, seed) -> int:
+ h = hashlib.sha1(f"{variant}:{seed}".encode()).hexdigest()
+ return int(h[:12], 16)
+
+
+def build_loop(variant: str = DEFAULT_VARIANT, seed: int = 1, clips=None,
+ decoder=None) -> dict:
+ """One LOOP_S-second periodic loop at REF_LUFS → a dict with `loop`
+ ((2, n) float32), `ref_lufs`, `peak`, `variant` (the one actually used),
+ `fallback` (why, or ""), `quiet_s`, `clips_used`."""
+ rng = np.random.default_rng(_seed_int(variant, seed))
+ n = LOOP_S * SR
+ freqs = np.fft.rfftfreq(n, 1.0 / SR)
+ used, fallback, quiet, nclips = variant, "", 0.0, 0
+ if variant == "film":
+ shape = film_shape(clips, decoder)
+ quiet, nclips = shape["quiet_s"], shape["clips_used"]
+ if shape["db"] is None or quiet < MIN_QUIET_S:
+ used = FALLBACK_VARIANT
+ fallback = (f"only {quiet:.1f} s of quiet sound in the clips"
+ if nclips else "no clip with usable quiet sound")
+ else:
+ wf = np.fft.rfftfreq(WIN, 1.0 / SR)
+ db = np.interp(freqs, wf, shape["db"])
+ # Nothing below 20 Hz: a bed that moves the woofer is not room tone.
+ db += -10 * np.log10(1 + (20.0 / np.maximum(freqs, 1.0)) ** 4)
+ loop = _synth(db, rng, {"move": 1.0})
+ if used != "film":
+ p = PRESETS.get(used) or PRESETS[FALLBACK_VARIANT]
+ used = p["id"]
+ loop = _synth(_db_shape(p, freqs), rng, p)
+ lufs = loudness_lufs(loop)
+ g = 10 ** ((REF_LUFS - lufs) / 20.0)
+ peak = float(np.abs(loop).max()) * g
+ if peak > PEAK_CAP:
+ g *= PEAK_CAP / peak
+ peak = PEAK_CAP
+ loop = (loop * g).astype(np.float32)
+ ref = round(lufs + 20 * math.log10(g), 2)
+ return {"loop": loop, "ref_lufs": ref, "peak": round(peak, 4), "variant": used,
+ "fallback": fallback, "quiet_s": quiet, "clips_used": nclips}
+
+
+def tile(loop: np.ndarray, seconds: float) -> np.ndarray:
+ total = int(round(float(seconds) * SR))
+ reps = -(-total // loop.shape[1])
+ return np.tile(loop, (1, reps))[:, :total]
+
+
+def seam_jump(x: np.ndarray, at: int) -> tuple[float, float]:
+ """(|step| across sample `at`, 99.9th percentile of |step| elsewhere) —
+ a seam is audible when the first is far above the second."""
+ x = np.atleast_2d(x)
+ d = np.abs(np.diff(x, axis=1))
+ return float(d[:, at - 1].max()), float(np.percentile(d, 99.9))
+
+
+def write_wav(path, samples: np.ndarray, sr: int = SR) -> None:
+ x = np.clip(np.atleast_2d(samples), -1.0, 1.0)
+ pcm = (x.T * 32767.0).round().astype("<i2")
+ tmp = Path(str(path) + ".part")
+ with wave.open(str(tmp), "wb") as w:
+ w.setnchannels(x.shape[0])
+ w.setsampwidth(2)
+ w.setframerate(sr)
+ w.writeframes(pcm.tobytes())
+ os.replace(tmp, path)
+
+
+def clips_digest(clips) -> str:
+ rows = []
+ for c in clips or []:
+ p = str((c or {}).get("path") or "")
+ try:
+ m = int(Path(p).stat().st_mtime)
+ except OSError:
+ m = 0
+ rows.append([p, round(float(c.get("start") or 0), 3),
+ round(float(c.get("end") or 0), 3), m])
+ return hashlib.sha1(json.dumps(rows).encode()).hexdigest()[:8]
+
+
+def make_bed(dest_dir, *, variant: str = DEFAULT_VARIANT, seed: int = 1,
+ film_len: float = 0.0, clips=None, decoder=None,
+ strict: bool = False) -> dict:
+ """Write (or reuse) the bed file for a film → the facts the Editor needs:
+ `{path, duration, ref_lufs, variant, label, seed, fallback, quiet_s,
+ clips_used, reused}`. The name is a function of every input, so the same
+ pick reuses the same file and a different pick never overwrites one.
+
+ `strict` (the automatic cut's mode): a "From this film" bed that would
+ fall back to a preset is NOT written — `path` is "" and `fallback` says
+ why. A film of silent clips gets no hiss nobody asked for."""
+ if variant not in variant_ids():
+ raise ValueError(f"unknown room tone: {variant}")
+ seed = int(seed) if str(seed).lstrip("-").isdigit() else 1
+ secs = bed_seconds(film_len)
+ dest = Path(dest_dir)
+ dest.mkdir(parents=True, exist_ok=True)
+ tag = clips_digest(clips) if variant == "film" else "p"
+ stem = f"rt_{variant}_{seed}_{tag}_{secs}s"
+ wav, meta = dest / f"{stem}.wav", dest / f"{stem}.json"
+ if wav.is_file() and meta.is_file():
+ try:
+ facts = json.loads(meta.read_text(encoding="utf-8"))
+ # A cache hit is still subject to `strict`. The same film can be
+ # bedded by hand first ("From this film" falling back to a preset,
+ # which the manual path allows) and re-cut automatically later —
+ # and the automatic path refuses preset hiss over silent clips.
+ # Returning the cached fallback here handed the automatic cut the
+ # very file its own policy had just refused to make.
+ if strict and facts.get("fallback"):
+ return {"path": "", "duration": 0.0, "variant": variant,
+ "used": facts.get("used", variant),
+ "fallback": facts.get("fallback"),
+ "quiet_s": facts.get("quiet_s", 0.0),
+ "clips_used": facts.get("clips_used", 0),
+ "seed": seed, "reused": False}
+ facts.update(path=str(wav), reused=True)
+ return facts
+ except (OSError, ValueError):
+ pass
+ res = build_loop(variant, seed, clips=clips, decoder=decoder)
+ if strict and res["fallback"]:
+ return {"path": "", "duration": 0.0, "variant": variant, "used": res["variant"],
+ "fallback": res["fallback"], "quiet_s": res["quiet_s"],
+ "clips_used": res["clips_used"], "seed": seed, "reused": False}
+ write_wav(wav, tile(res["loop"], secs))
+ facts = {"path": str(wav), "duration": float(secs), "ref_lufs": res["ref_lufs"],
+ "peak": res["peak"], "variant": variant, "used": res["variant"],
+ "label": variant_label(res["variant"]), "seed": seed,
+ "fallback": res["fallback"], "quiet_s": res["quiet_s"],
+ "clips_used": res["clips_used"]}
+ meta.write_text(json.dumps(facts, indent=1), encoding="utf-8")
+ facts["reused"] = False
+ return facts
+
+
+def _main(argv) -> int:
+ import argparse
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ ap.add_argument("out")
+ ap.add_argument("--variant", default=DEFAULT_VARIANT, choices=variant_ids())
+ ap.add_argument("--seed", type=int, default=1)
+ ap.add_argument("--seconds", type=float, default=30)
+ ap.add_argument("--clip", action="append", default=[],
+ help="path[:start:end] (repeatable) for --variant film")
+ a = ap.parse_args(argv)
+ clips = []
+ for spec in a.clip:
+ parts = spec.rsplit(":", 2)
+ if len(parts) == 3:
+ clips.append({"path": parts[0], "start": float(parts[1]), "end": float(parts[2])})
+ else:
+ clips.append({"path": spec, "start": 0.0, "end": 1e6})
+ res = build_loop(a.variant, a.seed, clips=clips)
+ write_wav(a.out, tile(res["loop"], a.seconds))
+ print(json.dumps({k: v for k, v in res.items() if k != "loop"}))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(_main(sys.argv[1:]))
diff --git a/scripts/measure_editor_layout.py b/scripts/measure_editor_layout.py
index 9d26b42..154a997 100644
--- a/scripts/measure_editor_layout.py
+++ b/scripts/measure_editor_layout.py
@@ -697,6 +697,18 @@ JS_MEASURE = r"""
out.still_visible = on(still);
out.stage_layers_both_visible = on(video) && on(still);
+ // THE TWO MONITORS (round 2). The Source monitor is on screen by default
+ // and both pictures must be 16:9 — the first cut of this layout let the
+ // Program column's bar squeeze the Source picture to 499x315. The View
+ // group must hold its five buttons on the header's one row (header_rows).
+ const box = (e) => { if (!e || e.offsetParent === null) return null;
+ 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);
+ out.program_box = box(el('sbeStage'));
+ out.source_box = box(el('sbeSrcStage'));
+ out.view_buttons = document.querySelectorAll('#sbeView .sbe-vbtn').length;
+
// Put it back, so the next width does not start from a forced state.
try {
if (window.SBE) SBE.dirty = false;
@@ -719,12 +731,11 @@ JS_HANDLES = r"""
const out = { blocks: {}, errors: [] };
if (typeof sbeTlSet !== 'function') { out.errors.push('sbeTlSet missing'); return out; }
- // THE HANDLES THIS GATE MEASURES LIVE ON THE SOUND LANES, and those lanes now
- // make themselves small when nobody is working on sound — a grip inside an
- // 18px strip is not the control this gate is about, and the page would have
- // compacted underneath it a couple of seconds after it loaded. Hold them open
- // the way a user does with the ▾ on the A1 head, through the app's own writer.
- if (typeof sbeAudioPinSet === 'function') sbeAudioPinSet('open');
+ // THE HANDLES THIS GATE MEASURES LIVE ON THE SOUND LANES, which are thin
+ // strips in picture mode (the default) — a grip inside an 18px strip is not
+ // the control this gate is about. Sound mode, through the app's own writer,
+ // is how a user gets them at full height.
+ if (typeof sbeSoundModeSet === 'function') sbeSoundModeSet(true, { quiet: true });
sbeTlSet(%(tl)s);
if (typeof sbePaint === 'function') sbePaint();
await settle();
@@ -918,6 +929,18 @@ def check(width: int, m: dict) -> list[str]:
f"clientHeight {m.get('timeline_client_height')}, "
f"floor {m.get('timeline_floor_h')})")
+ 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")
+ if m.get("view_buttons") != 5:
+ bad.append(f"{w}: the View group has {m.get('view_buttons')} buttons, not 5")
+
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/storyboard_editor.py b/storyboard_editor.py
index bb8a1a8..b18ed20 100644
--- a/storyboard_editor.py
+++ b/storyboard_editor.py
@@ -88,6 +88,8 @@ __all__ = [
"track_label", "track_gain", "track_muted", "strip_gain", "strip_muted",
"strip_window", "track_strip_gain_points", "track_strip_gain_at",
"track_render_strips",
+ "ROOM_TONE_NAME", "ROOM_TONE_KEYS", "room_tone_meta", "room_tone_track",
+ "room_tone_new_track", "room_tone_fit",
"overlay_items", "overlay_kind", "OVERLAY_SUFFIXES",
"blocking_errors", "WARNING_CODES", "repair_audio_overlaps",
"edit_digest", "session_token_path", "claim_session", "current_session",
@@ -1356,6 +1358,97 @@ def track_render_strips(edit) -> list[dict]:
return out
+# ---------------------------------------------------------------------------
+# ROOM TONE — one tagged audio track under the whole film
+# ---------------------------------------------------------------------------
+# "If it was all over the timeline as an ambient sound, not something really
+# subtle." A room-tone bed IS an audio track — so the preview, the render mix
+# and the NLE export already play it, and there is no fourth mix path — with a
+# tag that says what made the file, so the Editor can offer Update / New take
+# and keep the strip as long as the film:
+#
+# track["room_tone"] = {"variant", "seed", "level", "ref_lufs"}
+#
+# `level` is what the user picked (LUFS); `ref_lufs` is what the FILE is at;
+# the track's `gain` is the fader between them (`room_tone.level_gain`). The
+# gain is the number the mix plays — `level` is only the label on it.
+ROOM_TONE_NAME = "Room tone"
+ROOM_TONE_KEYS = ("variant", "seed", "level", "ref_lufs")
+
+
+def room_tone_meta(track) -> dict | None:
+ """The tag, cleaned, or None for an ordinary track."""
+ rt = track.get("room_tone") if isinstance(track, dict) else None
+ if not isinstance(rt, dict):
+ return None
+ out = {"variant": str(rt.get("variant") or "film")[:40]}
+ try:
+ out["seed"] = int(rt.get("seed") or 1)
+ except (TypeError, ValueError):
+ out["seed"] = 1
+ for k, d in (("level", -27.0), ("ref_lufs", -18.0)):
+ v = rt.get(k)
+ out[k] = round(float(v), 2) if _is_num(v) else d
+ return out
+
+
+def room_tone_track(edit) -> tuple[int, dict] | None:
+ """(index, track) of the film's room-tone track, or None. The first wins."""
+ for i, t in enumerate(audio_tracks(edit)):
+ if room_tone_meta(t) is not None:
+ return i, t
+ return None
+
+
+def room_tone_new_track(facts: dict, film_len: float, *, level: float = -27.0,
+ track_id: str = "") -> dict:
+ """A room-tone track from `room_tone.make_bed`'s facts: one locked strip
+ from the film's first second to its last, the fader set for `level`."""
+ import room_tone as _rt # noqa: PLC0415
+ dur = float(facts.get("duration") or 0.0)
+ end = round(max(TRACK_STRIP_MIN, min(float(film_len or 0.0), dur)), 6)
+ ref = float(facts.get("ref_lufs") or _rt.REF_LUFS)
+ lvl = _rt.clamp_level(level)
+ t = {"id": track_id or ("trt" + _clip_id(str(facts.get("path")), 0.0, 0.0)[:8]),
+ "name": ROOM_TONE_NAME,
+ "room_tone": {"variant": str(facts.get("variant") or "film"),
+ "seed": int(facts.get("seed") or 1),
+ "level": lvl, "ref_lufs": round(ref, 2)},
+ "strips": [{"id": "srt" + _clip_id(str(facts.get("path")), 0.0, 0.0)[:8],
+ "path": str(facts.get("path") or ""), "start": 0.0,
+ "end": end, "film_start": 0.0, "duration": round(dur, 6),
+ "title": f"Room tone · {facts.get('label') or ''}".strip(" ·"),
+ "locked": True}]}
+ g = _rt.level_gain(lvl, ref)
+ if abs(g - 1.0) > 1e-9:
+ t["gain"] = g
+ return t
+
+
+def room_tone_fit(edit) -> bool:
+ """Keep an untouched room-tone strip as long as the film. Mutates `edit`.
+
+ Only the plain case is fitted — ONE strip starting at 0 — because a bed
+ somebody split or moved by hand is an arrangement, not a default. The file
+ bounds the fit; a film that outgrew it needs a longer bed (the Editor asks
+ for one). True when something changed."""
+ found = room_tone_track(edit)
+ if not found:
+ return False
+ strips = track_strips(found[1])
+ if len(strips) != 1 or abs(_f(strips[0].get("film_start"))) > 1e-6:
+ return False
+ s = strips[0]
+ want = edit_duration(edit)
+ st = _f(s.get("start"))
+ dur = _f(s.get("duration"), 0.0) or (want + st)
+ end = round(st + max(TRACK_STRIP_MIN, min(want, dur - st)), 6)
+ if abs(_f(s.get("end")) - end) <= 1e-6:
+ return False
+ s["end"] = end
+ return True
+
+
def _is_num(v) -> bool:
return (isinstance(v, (int, float)) and not isinstance(v, bool)
and v == v and v not in (float("inf"), float("-inf")))
@@ -1391,6 +1484,16 @@ def _validate_audio_tracks(edit, bad) -> None:
elif not 0.0 <= float(g) <= 1.0:
bad("audio_track_gain_range",
f"audio track {who}: gain must be between 0 and 1")
+ rtag = t.get("room_tone")
+ if rtag is not None:
+ if not isinstance(rtag, dict):
+ bad("audio_track_room_tone",
+ f"audio track {who}: room_tone must be an object or absent")
+ else:
+ for key in ("level", "ref_lufs"):
+ if rtag.get(key) is not None and not _is_num(rtag.get(key)):
+ bad("audio_track_room_tone",
+ f"audio track {who}: room_tone.{key} must be a number")
strips = t.get("strips")
if strips is None:
continue
@@ -1506,6 +1609,11 @@ def _normalise_audio_tracks(out: dict) -> None:
t2["gain"] = g
else:
t2.pop("gain", None)
+ rtag = room_tone_meta(t2)
+ if rtag is None:
+ t2.pop("room_tone", None)
+ else:
+ t2["room_tone"] = rtag
strips = []
for s in track_strips(t2):
s2 = {k: v for k, v in s.items() if not str(k).startswith("_")}
diff --git a/test_audio_compact.py b/test_audio_compact.py
index 0aa6c7e..ce63c8e 100644
--- a/test_audio_compact.py
+++ b/test_audio_compact.py
@@ -1,46 +1,45 @@
#!/usr/bin/env python3
-"""The sound lanes make themselves small — the contract, on screen and in code.
-
-The owner, editing a 13-shot film with clip sound on two lanes and four audio
-tracks: "the sound expands lower. The picture is so tiny, and it's a problem. I
-cannot see anything in the image, and I can also not push it down if I want to
-compact it. Think of some way that is really seamless and user-friendly to maybe
-compact all audio lanes when I am not working with them and make them little
-(because I want to see the image also as I'm working sometimes)."
-
-Three things had to be true for that, and each one is checked here:
-
- * THE AREA SIZES ITSELF. Every lane in the sound area — clip sound A and B,
- the soundtrack, and every A3+ track — has a second height, and one decision
- function says which one is on screen. It may not collapse mid-drag, during
- playback or under an open menu, which is the difference between "seamless"
- and "jumps".
- * THE FLOOR IS NOT A CONSTANT any more. It is the sum of the lane set that is
- on screen, so with the sound small the handle really does push the timeline
- down — the arithmetic lives in test_storyboard_editor_ui's probe; what is
- checked here is that sbeFitMonitors budgets the monitors against it.
- * IT IS A CONTROL, NOT A TRICK. A ▾ on the A1 head, a key in the one
- SHORTCUTS table, and the manual's own words — a behaviour that only
- happens to you is a bug report waiting to be filed.
+"""Picture mode and Sound mode — the contract, on screen and in code.
+
+The sound lanes used to size themselves: thin until you went near them, full
+height for as long as you were on sound, small again 2.4 s after you left. The
+owner, after cutting a film with it: "I don't like that the audio editing mode
+is automatic and moves the screens up. It's really weird… The automatic
+changing of the size of the timeline if you are going around with audio is
+really bad. I think a button is warranted where you can enter sound editing
+mode, and then you see the sound very big and the image very little."
+
+So the split has TWO STATES AND ONE SWITCH, and this file holds it to that:
+
+ * NOTHING MOVES BY ITSELF. No hover, click, selection, playback or timer
+ changes the split. The functions that did (sbeAudioWant, sbeAudioArm,
+ sbeAudioTouch, sbeAudioOver, sbeAudioBusy, the idle constant) are gone and
+ may not come back under any name; the pointer-over wiring is gone with
+ them.
+ * ONE SWITCH, THREE DOORS. sbeSoundModeSet is the only writer; ⇧A, the ⌁
+ Sound button on the tool row and the ▾ on the A1 head all call its toggle.
+ Each mode remembers its own timeline height, per browser, never in the
+ film.
+ * THE LANE TABLE STILL CARRIES A SECOND HEIGHT, and the floor and the roof
+ are still the sum of the lane set on screen — that arithmetic is what
+ makes picture mode give the height to the picture.
+ * A THIN LANE IS STILL A PICTURE, NOT A CONTROL: one click selects what was
+ clicked and nothing resizes; a double-click is sound mode.
"""
from __future__ import annotations
-import json
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
-
WEB = ROOT / "webapp"
+sys.path.insert(0, str(ROOT))
+from test_storyboard_editor_ui import extract_function # noqa: E402
-class TheSoundAreaSizesItself(unittest.TestCase):
-
+class TheSplitHasTwoStatesAndOneSwitch(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.js = (WEB / "js" / "editor.js").read_text(encoding="utf-8")
@@ -49,168 +48,150 @@ class TheSoundAreaSizesItself(unittest.TestCase):
cls.docs = (WEB / "docs" / "editor.md").read_text(encoding="utf-8")
cls.keys = (WEB / "js" / "shortcuts.js").read_text(encoding="utf-8")
- # ---- the lane table ---------------------------------------------------
+ # ---- the lane table and the two ends ------------------------------------
def test_every_lane_in_the_sound_area_has_a_second_height(self):
lanes = re.findall(
r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*(\d+), share: ([\d.]+)"
r"(, audio: true, small: (\d+))?", self.js)
by = {l[0]: l for l in lanes}
self.assertEqual(sorted(by), ["alane", "ov", "track", "wave"])
- # The two sound lanes, and only them: the picture and the overlay are
- # not the owner's complaint and must not shrink behind his back.
for key, small in (("alane", "18"), ("wave", "20")):
self.assertTrue(by[key][4], f"{key} has no small height")
self.assertEqual(by[key][5], small)
self.assertLess(int(small), int(by[key][1]))
for key in ("ov", "track"):
self.assertFalse(by[key][4], f"{key} is not part of the sound area")
- # A3, A4 … are drawn at the clip lane's height, so they follow it for
- # free — that is the whole reason four tracks cost what they cost.
self.assertIn("lanes.alane", extract_function("sbeTracksExtraH", self.js))
def test_the_floor_and_the_ceiling_are_the_lane_set_on_screen(self):
self.assertIn("globalThis.SBE_TL_MIN_H = sbeTlFloor(false);", self.js)
self.assertIn("globalThis.SBE_TL_MAX_H = sbeTlRoof(false);", self.js)
- # The monitors' budget: the floor, the ceiling and the extra lanes all
- # read the CURRENT size, which is how compacting reaches the picture.
fit = extract_function("sbeFitMonitors", self.js)
self.assertIn("sbeTlFloor()", fit)
self.assertIn("sbeTlRoof()", fit)
self.assertIn("avail - SBE_MON_MIN_H - extra", fit)
- # ...and the stacked page still bails out before any of it.
self.assertIn("(max-width: 900px)", fit)
self.assertIn("return;", fit[fit.index("(max-width: 900px)"):])
-
- def test_the_handle_can_ask_for_the_smaller_floor(self):
- for fn in ("sbeApplyTl", "sbeTlReset"):
- self.assertIn("sbeTlFloor()", extract_function(fn, self.js))
+ # "small" has exactly one input: the mode.
+ self.assertIn("function sbeAudioSmall() { return !sbeSoundMode(); }", self.js)
clamp = extract_function("sbeTlClamp", self.js)
self.assertIn("const floor = sbeTlFloor(small), roof = sbeTlRoof(small);", clamp)
- # Pull the edge up past what thin lanes can use and the sound comes
- # back — there is no other height in the box left to be asking for.
- self.assertIn("sbeAudioTouch({ open: true })", extract_function("sbeTlSet", self.js))
-
- # ---- when it happens --------------------------------------------------
- def test_it_never_collapses_in_the_middle_of_something(self):
- busy = extract_function("sbeAudioBusy", self.js)
- for held in ("SBE.audioDrag", "SBE.musicDrag", "SBE.tsDrag", "SBE.kfDrag",
- "SBE.tgSliding", "SBE.tlDrag", "SBE.playing", "SBE.aHover",
- "sbePopAnyOpen()", "SBE.selLane", "'@ts:'", "'@music'",
- "ED.src === 'sound'"):
- self.assertIn(held, busy, f"the lanes can collapse while {held}")
- want = extract_function("sbeAudioWant", self.js)
- self.assertIn("if (SBE.aPin === 'open') return false;", want)
- self.assertIn("if (SBE.aPin === 'small') return true;", want)
- self.assertIn("if (sbeAudioBusy()) return false;", want)
- self.assertIn("SBE_ASMALL_IDLE", want)
- # A couple of seconds: long enough that looking away is not a flicker.
- idle = int(re.search(r"const SBE_ASMALL_IDLE = (\d+);", self.js).group(1))
- self.assertGreaterEqual(idle, 1500)
- self.assertLessEqual(idle, 5000)
-
- def test_touching_sound_opens_it_at_once(self):
- touch = extract_function("sbeAudioTouch", self.js)
- self.assertIn("SBE.aTouch = Date.now();", touch)
- self.assertIn("if (SBE.aSmall && SBE.aPin !== 'small') sbeAudioSet(false);", touch)
- # The verbs aimed at sound say so, because none of them leaves a trace
- # in the selection the busy test reads.
+
+ # ---- nothing moves by itself -----------------------------------------------
+ def test_nothing_resizes_the_split_but_the_switch(self):
+ for gone in ("sbeAudioWant", "sbeAudioArm", "sbeAudioSync", "sbeAudioTouch",
+ "sbeAudioOver", "sbeAudioBusy", "sbeAudioPinToggle", "sbeAudioPinSet",
+ "sbeAudioSet", "sbeAudioSmallOnce", "SBE_ASMALL_IDLE",
+ "aTouch", "aHover", "aPin"):
+ self.assertNotIn(gone, self.js, f"{gone} is back — the split may move by itself again")
+ for wire in ("addEventListener('pointerenter', () => sbeAudio",
+ "addEventListener('pointerleave', () => sbeAudio",
+ "gutter.addEventListener('pointermove'"):
+ self.assertNotIn(wire, self.js, wire)
+ # The handle no longer "asks for the sound back" when dragged up.
+ self.assertNotIn("sbeAudioTouch", extract_function("sbeTlSet", self.js))
+ # A sound verb, a new track, a sound file, the Sound pool: none of them
+ # touch the split.
for fn in ("sbeToggleAudioLink", "sbeResyncSel", "sbeAlternateSel",
"sbeTrackAdd", "sbeTsAddSoundPath", "edPoolSrc"):
- self.assertIn("sbeAudioTouch({ open: true })",
- extract_function(fn, self.js), fn)
- # The pointer over a lane or a head opens it, which is how anybody
- # discovers that it opens at all.
- for wire in ("alane.addEventListener('pointerenter'",
- "lane.addEventListener('pointerenter'",
- "tlanes.addEventListener('pointerenter'",
- "gutter.addEventListener('pointermove'"):
- self.assertIn(wire, self.js)
- # ...and the idle is restarted by the one function every edit and
- # every selection already ends in.
- self.assertIn("sbeAudioArm();", extract_function("sbePaint", self.js))
-
- def test_a_small_lane_is_a_picture_and_one_click_opens_it(self):
- for fn in ("sbeOnAudioDown", "sbeOnMusicDown", "sbeOnTsDown"):
body = extract_function(fn, self.js)
- self.assertIn("if (sbeAudioSmall()) { sbeAudioOpenFrom(ev); return; }", body, fn)
- opener = extract_function("sbeAudioOpenFrom", self.js)
- # One gesture: the area opens AND what was clicked is selected.
- self.assertIn("sbeTsSelectOne(", opener)
- self.assertIn("sbeSelectOne(", opener)
- self.assertIn("'@music'", opener)
- self.assertIn("sbeAudioTouch({ open: true });", opener)
- # The waveform still has a height to be drawn at down there.
- self.assertIn("sbeAudioSmall() ? 8 : 14", extract_function("sbeStripH", self.js))
-
- def test_the_change_is_animated_and_the_drag_is_not(self):
- setter = extract_function("sbeAudioSet", self.js)
+ self.assertNotIn("sbeSoundModeSet", body, fn)
+ self.assertNotIn("sbeAudioTouch", body, fn)
+ # sbePaint does not arm a timer.
+ self.assertNotIn("sbeAudioArm", extract_function("sbePaint", self.js))
+
+ def test_the_one_writer_flips_the_class_and_swaps_the_height(self):
+ setter = extract_function("sbeSoundModeSet", self.js)
+ self.assertIn("SBE.mode = want ? 'sound' : 'picture';", setter)
+ self.assertIn("sbeModeWrite(SBE.mode);", setter)
+ self.assertIn("plan.classList.toggle('is-asmall', !want);", setter)
+ self.assertIn("plan.classList.toggle('is-sound', want);", setter)
+ self.assertIn("SBE.tlH = sbeTlPrefRead();", setter)
+ self.assertIn("sbeApplyTl(sbeTlClamp(SBE.tlH, SBE.tlMax));", setter)
+ # animated on a change, never on the open of a document, and the drawn
+ # waveforms are re-issued at the height they landed on
self.assertIn("classList.add('sbe-aanim')", setter)
- self.assertIn("classList.remove('sbe-aanim')", setter)
- # The waveforms are drawn, not styled: re-issued at the height they
- # landed on, exactly as the drag handle's own correction does it.
self.assertIn("SBE.laneAt = -1;", setter)
+ self.assertIn("opts.quiet", setter)
self.assertIn("transition: height 180ms", self.css)
- # ...and only while the class is on the body, so dragging the timeline's
- # edge — which moves the same numbers 60 times a second — stays instant.
- block = self.css[self.css.index("body.sbe-aanim .sbe-alane"):]
- self.assertLess(block.index("transition:"), block.index("}"))
-
- # ---- it is this browser's preference, never the film's -----------------
- def test_the_pin_lives_beside_the_timeline_height_and_not_in_the_document(self):
- self.assertIn("localStorage.getItem('phos_sbe_audio')", self.js)
- self.assertIn("localStorage.setItem('phos_sbe_audio'", self.js)
- # The save payload is the whole of what the server is told. A window's
- # shape in there would bump the film's revision — see sbeTlPrefRead.
+ # sbeSoundModeSet is the only thing that writes SBE.mode
+ self.assertEqual(self.js.count("SBE.mode = "), 1)
+
+ def test_each_mode_remembers_its_own_height_in_this_browser(self):
+ self.assertIn("function sbeTlPrefKey() { return sbeSoundMode() ? 'phos_sbe_tl_h_sound' : 'phos_sbe_tl_h'; }",
+ self.js)
+ read = extract_function("sbeTlPrefRead", self.js)
+ self.assertIn("localStorage.getItem(sbeTlPrefKey())", read)
+ # picture mode starts as low as it goes, sound mode as tall as it goes
+ self.assertIn("return small ? sbeTlFloor(true) : sbeTlRoof(false);", read)
+ self.assertIn("localStorage.setItem(sbeTlPrefKey()", extract_function("sbeTlPrefWrite", self.js))
+ self.assertIn("localStorage.getItem('phos_sbe_mode')", self.js)
+ self.assertIn("localStorage.setItem('phos_sbe_mode'", self.js)
save = extract_function("sbeSaveBody", self.js)
- for word in ("aPin", "aSmall", "phos_sbe_audio"):
+ for word in ("mode", "phos_sbe_mode", "inspect", "phos_sbe_inspect"):
self.assertNotIn(word, save)
self.assertNotIn("audio_small", self.js)
-
- # ---- and it is a control, not a trick ---------------------------------
- def test_the_control_is_on_the_head_of_the_area_it_acts_on(self):
+ # the document open restores the mode quietly, before anything is drawn
+ opened = extract_function("sbeOpen", self.js)
+ self.assertIn("sbeSoundModeSet(sbeModeRead() === 'sound', { quiet: true });", opened)
+
+ # ---- three doors, one switch --------------------------------------------------
+ def test_the_button_the_key_and_the_head_are_the_same_control(self):
+ self.assertIn('id="sbeSoundBtn" onclick="sbeSoundModeToggle()"', self.html)
+ self.assertIn('data-shortcut="editor.soundMode"', self.html)
self.assertIn('id="sbeAudioSize"', self.html)
- self.assertIn('onclick="sbeAudioPinToggle()"', self.html)
- self.assertIn('aria-expanded="true"', self.html)
- # On the A1 head — the top of the sound area, next to its name.
- head = self.html[self.html.index('class="sbe-gh sbe-gh-aud">'):]
- head = head[:head.index("</div>")]
- self.assertIn("sbeAudioSize", head)
- self.assertIn("<b>Clip sound A</b>", head)
- # Its glyph and its words are painted, so they cannot say "make them
- # small" while the lanes already are.
- heads = extract_function("sbePaintHeads", self.js)
- self.assertIn("sbeAudioSize", heads)
- self.assertIn("'▸' : '▾'", heads)
- self.assertIn("aria-expanded", heads)
- self.assertIn("shortcutHint('editor.soundLanes')", heads)
-
- def test_the_key_is_in_the_one_table(self):
- row = self.keys[self.keys.index("id: 'editor.soundLanes'"):]
+ head = self.html[self.html.index('id="sbeAudioSize"'):]
+ head = head[:head.index("</button>")]
+ self.assertIn('onclick="sbeSoundModeToggle()"', head)
+ row = self.keys[self.keys.index("id: 'editor.soundMode'"):]
row = row[:row.index("},")]
self.assertIn("combos: ['shift+a']", row)
- self.assertIn("calls: 'sbeAudioPinToggle'", row)
+ self.assertIn("calls: 'sbeSoundModeToggle'", row)
self.assertIn("scope: 'editor'", row)
- # The Editor's own handler answers it — test_docs_and_shortcuts drives
- # the real listener; here it is enough that the branch is there.
- self.assertIn("ev.preventDefault(); sbeAudioPinToggle(); return;", self.js)
-
- def test_the_manual_says_it_in_the_words_on_screen(self):
- self.assertIn("{#compact}", self.docs)
- for words in ("Sound lanes small", "Clip sound A", "[[sc:editor.soundLanes]]"):
- self.assertIn(words, self.docs)
- # The docs promise the two halves the code has to keep.
- self.assertIn("come back to full height the moment you are", self.docs)
- self.assertIn("remembered in this browser", self.docs)
+ self.assertIn("ev.preventDefault(); sbeSoundModeToggle(); return;", self.js)
+ self.assertNotIn("editor.soundLanes", self.keys)
+ self.assertNotIn("editor.soundLanes", self.js)
+ heads = extract_function("sbePaintHeads", self.js)
+ self.assertIn("shortcutHint('editor.soundMode')", heads)
+ self.assertIn("'▸' : '▾'", heads)
+ panels = extract_function("sbePaintPanels", self.js)
+ self.assertIn("sbeViewTip(sbeEl('sbeSoundBtn'), sbeSoundMode(), 'Sound mode',", panels)
+ self.assertIn("'editor.soundMode'", panels)
+ tip = extract_function("sbeViewTip", self.js)
+ self.assertIn("btn.setAttribute('aria-pressed', pressed ? 'true' : 'false');", tip)
+ # the button lives in the header's View group now, with the other panels
+ view = self.html[self.html.index('id="sbeView"'):]
+ view = view[:view.index("</span>\n")]
+ self.assertIn('id="sbeSoundBtn"', view)
+
+ # ---- a thin lane is a picture -----------------------------------------------------
+ def test_a_thin_lane_selects_on_one_click_and_is_sound_mode_on_two(self):
+ for fn in ("sbeOnAudioDown", "sbeOnMusicDown", "sbeOnTsDown"):
+ body = extract_function(fn, self.js)
+ self.assertIn("if (sbeAudioSmall()) { sbeAudioOpenFrom(ev); return; }", body, fn)
+ opener = extract_function("sbeAudioOpenFrom", self.js)
+ self.assertIn("sbeTsSelectOne(", opener)
+ self.assertIn("sbeSelectOne(", opener)
+ self.assertIn("'@music'", opener)
+ self.assertNotIn("sbeSoundModeSet", opener) # one click never resizes
+ for fn in ("sbeOnAudioDbl", "sbeOnMusicDbl", "sbeOnTsDbl"):
+ body = extract_function(fn, self.js)
+ self.assertIn("if (sbeAudioSmall()) { sbeSoundModeSet(true); return; }", body, fn)
+ self.assertIn("sbeAudioSmall() ? 8 : 14", extract_function("sbeStripH", self.js))
def test_the_stacked_page_keeps_its_controls(self):
- # Below the breakpoint the page is the scroller, sbeFitMonitors stands
- # down and the lanes are back on their CSS heights — so the class that
- # takes the grips away may not reach down there.
i = self.css.index("body.sbe-aanim .sbe-alane")
guard = self.css.rindex("@media (min-width: 901px) {", 0, i)
self.assertLess(guard, i)
self.assertLess(i, self.css.index(".is-asmall .sbe-grip"))
+ def test_the_manual_says_it_in_the_words_on_screen(self):
+ self.assertIn("{#compact}", self.docs)
+ for words in ("Sound mode", "Picture mode", "[[sc:editor.soundMode]]",
+ "Nothing changes the split by itself", "remembered in this browser"):
+ self.assertIn(words, self.docs)
+ self.assertNotIn("make themselves small", self.docs)
+
if __name__ == "__main__":
unittest.main()
diff --git a/test_audio_tracks.py b/test_audio_tracks.py
index 32e12b5..15152c2 100644
--- a/test_audio_tracks.py
+++ b/test_audio_tracks.py
@@ -316,6 +316,51 @@ class TheRenderGraph(unittest.TestCase):
self.assertIn("no sound file at /x/laugh.wav (audio track A3)", res["error"])
+class TheMixModeDefault(unittest.TestCase):
+ """A film with a bed over it must not come out with mute clips.
+
+ Saint Feld (2026-09-18): 13 shots of dialogue, a 20 s bed, and the
+ delivered film had 21 s of digital silence — every shot the bed did not
+ reach played nothing, because the default was `replace`. The Editor's own
+ selector has always read "under the clips".
+ """
+
+ def render(self, **kw):
+ cap = {}
+ doc = dict(_base())
+ info = {"w": 320, "h": 240, "duration": 6.0, "has_audio": True,
+ "sample_rate": 48000}
+ with tempfile.TemporaryDirectory() as d:
+ clip, bed = Path(d) / "a.mp4", Path(d) / "bed.m4a"
+ clip.write_bytes(b"x")
+ bed.write_bytes(b"x")
+ doc["clips"][0]["path"] = str(clip)
+ doc["audio"] = {"path": str(bed), "offset": 0.0, "duration": 20.0}
+ doc["audio"].update(kw.pop("audio", {}))
+ real_probe, real_assemble = panel._sb_probe_clip, panel._sb_assemble_film
+ panel._sb_probe_clip = lambda p: dict(info)
+ panel._sb_assemble_film = lambda *a, **k: cap.update(k) or {"ok": True}
+ try:
+ res = panel._sbe_render_edit(
+ {"id": "b", "title": "t", "created_at": 0}, doc, **kw)
+ finally:
+ panel._sb_probe_clip = real_probe
+ panel._sb_assemble_film = real_assemble
+ return cap, res
+
+ def test_the_default_keeps_the_clips_and_ducks_the_bed(self):
+ cap, res = self.render()
+ self.assertEqual(cap["music_mode"], "under")
+ self.assertEqual(res["music_mode"], "under")
+
+ def test_the_document_and_the_caller_can_still_ask_for_replace(self):
+ cap, res = self.render(audio={"mode": "replace"})
+ self.assertEqual(cap["music_mode"], "replace")
+ self.assertEqual(res["music_mode"], "replace")
+ cap, res = self.render(music_mode="replace")
+ self.assertEqual(cap["music_mode"], "replace")
+
+
class TheNleExport(unittest.TestCase):
def export(self, tracks):
d = Path(tempfile.mkdtemp(prefix="phos-nle-"))
diff --git a/test_docs_and_shortcuts.py b/test_docs_and_shortcuts.py
index baac318..8690088 100644
--- a/test_docs_and_shortcuts.py
+++ b/test_docs_and_shortcuts.py
@@ -127,6 +127,22 @@ class TheDocsShowTheTable(unittest.TestCase):
for m in re.finditer(r"(?:sbeKeyHint|shortcutHint)\('([\w.-]+)'\)", f.read_text(encoding="utf-8")):
self.assertIn(m.group(1), self.ids, f"{f.name}: {m.group(0)}")
+ def test_the_view_group_names_real_keys_in_its_tips_and_its_docs(self):
+ # sbeViewTip takes the registry id as its last argument, which the
+ # sbeKeyHint regex above cannot see — so the View group is checked here.
+ js = (WEB / "js" / "editor.js").read_text(encoding="utf-8")
+ fn = js[js.index("function sbePaintPanels()"):]
+ fn = fn[:fn.index("\n}\n")]
+ keys = re.findall(r"'(editor\.[\w]+)'\);", fn)
+ self.assertEqual(sorted(keys), ["editor.inspector", "editor.panels", "editor.soundMode"])
+ for k in keys:
+ self.assertIn(k, self.ids)
+ md = (DOCS / "editor.md").read_text(encoding="utf-8")
+ view = md[md.index("**View**"):md.index("**The timeline**") if "**The timeline**" in md else None]
+ for k in ("editor.inspector", "editor.soundMode", "editor.panels", "editor.fullscreen"):
+ self.assertIn(f"[[sc:{k}]]", view, k)
+ self.assertIn("Drop a clip here to preview", md)
+
def test_no_shortcut_claims_a_reserved_chord(self):
reserved = set(self.r["reserved"])
for c in ("mod+r", "mod+w", "mod+q", "mod+t", "mod+n", "mod+l", "mod+h", "mod+m",
@@ -145,7 +161,8 @@ class TheDocsShowTheTable(unittest.TestCase):
_KEY = {"space": " ", "escape": "Escape", "backspace": "Backspace", "delete": "Delete",
"arrowleft": "ArrowLeft", "arrowright": "ArrowRight", "arrowup": "ArrowUp",
"arrowdown": "ArrowDown", "home": "Home", "end": "End", "plus": "+", "minus": "-",
- "equals": "=", "underscore": "_", "backslash": "\\", "enter": "Enter"}
+ "equals": "=", "underscore": "_", "backslash": "\\", "enter": "Enter",
+ "backquote": "`"}
# State each row needs for its branch to be the one that answers.
_STATE = {
diff --git a/test_face_fix.py b/test_face_fix.py
index 1dfded8..d502fd9 100644
--- a/test_face_fix.py
+++ b/test_face_fix.py
@@ -337,12 +337,26 @@ class TestUI(unittest.TestCase):
self.assertNotIn(">LTX Upscale<", HTML)
self.assertIn("getElementById('faceFixWrap')", QJS)
- def test_card_and_history_buttons_post_to_the_route(self):
+ def test_face_fix_only_on_the_big_player(self):
+ # Owner 2026-09-17: no Face Fix on Outputs thumbnails or queue rows,
+ # and never on a clip that is already an upscale.
self.assertIn("fetch('/queue/facefix'", QJS)
- self.assertIn("card-action-facefix", QJS)
- self.assertIn("faceFixClip(${escapeHtml(JSON.stringify(o.path))})", QJS)
- self.assertIn("facefix-btn", QJS)
- self.assertRegex(QJS, r"faceFixClip, faceFixActive")
+ self.assertNotIn("card-action-facefix", QJS)
+ self.assertNotIn("facefix-btn", QJS)
+ self.assertRegex(QJS, r"faceFixClip, faceFixActive, isUpscaledPath")
+ self.assertIn("isUpscaledPath(o && o.path)", QJS)
+ self.assertIn("This clip is already upscaled.",
+ (Path(__file__).resolve().parent / "webapp/js/editor.js").read_text())
+
+ def test_is_upscaled_path_pattern(self):
+ import re
+ m = re.search(r"function isUpscaledPath\(p\) \{\n return /(.+)/i\.test", QJS)
+ self.assertTrue(m)
+ rx = re.compile(m.group(1).replace('\\\\', '\\'), re.I)
+ for yes in ("a_h3_8_x2_20260917_120000.mp4", "x2_faithful_nolaugh/s01.mp4", "v01_x2f.mp4", "v01_bizvoice.mp4"):
+ self.assertTrue(rx.search(yes), yes)
+ for no in ("for_the_target_video_at_0_h3_55.mp4", "shot_1_live_h3_21.mp4", "max2_take.mp4"):
+ self.assertFalse(rx.search(no), no)
def test_remix_lane_names_and_presets(self):
self.assertIn('data-remix="upscale"', HTML)
@@ -394,7 +408,7 @@ class TestUI(unittest.TestCase):
self.assertIn('id="sbeCbFaceFix" onclick="sbeFaceFixSel()"', HTML)
self.assertIn("<b>Face Fix ×2</b>", HTML)
self.assertIn("menuLabel: 'Upscale & Face Fix'", EDJS)
- self.assertIn('<g id="ic-facefix">', HTML)
+ self.assertIn('<symbol id="ic-facefix" viewBox="0 0 256 256">', HTML)
self.assertEqual(EDJS.count("id: 'sbeCbFaceFix'"), 2) # picture + sound models
fn = EDJS[EDJS.index("async function sbeFaceFixSel()"):]
fn = fn[:fn.index("\n}\n")]
diff --git a/test_h3_lora_file_import.py b/test_h3_lora_file_import.py
index 71cb63a..4dd2942 100644
--- a/test_h3_lora_file_import.py
+++ b/test_h3_lora_file_import.py
@@ -330,7 +330,11 @@ class TestH3LoraFileImport(unittest.TestCase):
+ "\n" + (ROOT / "webapp" / "index.html").read_text(encoding="utf-8"))
for _m in sorted((ROOT / "webapp" / "js").glob("*.js")):
panel += "\n" + _m.read_text(encoding="utf-8")
- self.assertIn("Import H3 LoRA", panel)
+ # The label itself is "Import" now (four buttons share one header row
+ # and the long labels wrapped it onto three lines); the control is
+ # identified by its id and the phrase lives in its tooltip.
+ self.assertIn("Import H3 LoRA", panel) # tooltip
+ self.assertIn('id="h3LoraImportBtn"', panel) # the control
self.assertIn("/h3/loras/import", panel)
diff --git a/test_h3_tristep_draft.py b/test_h3_tristep_draft.py
new file mode 100644
index 0000000..3d81dfe
--- /dev/null
+++ b/test_h3_tristep_draft.py
@@ -0,0 +1,634 @@
+#!/usr/bin/env python3
+"""Contract gate: the H3 Speed switch — ⚡ Fast (TaoMate-H3's 3-step adapter) | ✦ Best.
+
+Owner rulings 2026-09-17: the 3-step draft (+ Upscale & Face Fix) is "a much
+better option for a draft", it works for image-to-video at higher quality too,
+and it ships as ONE switch. So Draft, Standard and High render with the
+TaoMate adapter and its own sigma ladder (`--steps 4 --sigma-subset
+50:0,16,33,49`, 3 forwards) by default whenever the adapter is installed;
+Best (h3_tristep=0) is each shape's own sampler; Native and the dense single
+pass always render Best; Turbo is never stacked on Fast; the file is fetched
+from its author's repo at a pinned revision + digest, resumably.
+
+No model, no GPU, no network: the runner is intercepted at Popen and the
+download reads from an in-memory opener.
+"""
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import os
+import struct
+import sys
+import tempfile
+import threading
+import unittest
+import unittest.mock
+from contextlib import ExitStack
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+_TMP = Path(tempfile.mkdtemp(prefix="phos-h3-tristep-"))
+for _k, _d in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "out"),
+ ("LTX_UPLOADS_DIR", "uploads")):
+ (_TMP / _d).mkdir(parents=True, exist_ok=True)
+ os.environ[_k] = str(_TMP / _d)
+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))
+
+import mlx_ltx_panel as P # noqa: E402
+
+SUBSET = "50:0,16,33,49"
+
+
+def _safetensors(path: Path, tensors: dict) -> None:
+ header, blobs, off = {}, [], 0
+ for name, (shape, vals) in tensors.items():
+ raw = struct.pack(f"<{len(vals)}f", *vals)
+ header[name] = {"dtype": "F32", "shape": list(shape),
+ "data_offsets": [off, off + len(raw)]}
+ blobs.append(raw)
+ off += len(raw)
+ hb = json.dumps(header).encode()
+ hb += b" " * (-len(hb) % 8)
+ path.write_bytes(struct.pack("<Q", len(hb)) + hb + b"".join(blobs))
+
+
+class _Env(unittest.TestCase):
+ """A fake install: H3 present, a stacking runner with --sigma-subset, the
+ adapter directory in a temp dir, tiny size floors."""
+ runner_flags = ("--lora", "--sigma-subset", "--lora-adaln")
+ stack = True
+
+ def setUp(self):
+ self.st = ExitStack()
+ self.adir = Path(tempfile.mkdtemp(prefix="adapters-", dir=_TMP))
+ self.logs: list[str] = []
+ flags = self.runner_flags
+ for name, val in {
+ "h3_available": lambda: True,
+ "h3_supports_lora": lambda: True,
+ "h3_supports_lora_stack": lambda: self.stack,
+ "_h3_runner_has_flag": lambda flag: flag in flags,
+ "_h3_turbo_dir": lambda: self.adir,
+ "H3_TRISTEP_CANDIDATES": tuple((f, v, 1) for f, v, _ in P.H3_TRISTEP_CANDIDATES),
+ "H3_TURBO_LORA_MIN_BYTES": 1,
+ "push": self.logs.append}.items():
+ self.st.enter_context(unittest.mock.patch.object(P, name, val))
+ P._set_h3_tristep_dl(status="idle", mb=0, total_mb=0, error=None)
+
+ def tearDown(self):
+ self.st.close()
+ P._set_h3_tristep_dl(status="idle", mb=0, total_mb=0, error=None)
+
+ def install(self, filename=P.H3_TRISTEP_FILE) -> Path:
+ f = self.adir / filename
+ f.write_bytes(b"adapter fixture")
+ return f
+
+ def job(self, **form) -> dict:
+ base = {"mode": "t2v", "engine": "h3", "prompt": "a man lifts a dumbbell",
+ "h3_quality": "draft", "h3_length": "5s", "h3_turbo": "0"}
+ base.update(form)
+ return P.make_job({k: [v] for k, v in base.items()})
+
+
+class TestPins(unittest.TestCase):
+ def test_the_file_comes_from_its_author_at_a_pinned_revision(self):
+ self.assertEqual(P.H3_TRISTEP_REPO, "Kijai/MiniMax-H3_comfy")
+ self.assertRegex(P.H3_TRISTEP_REVISION, r"^[0-9a-f]{40}$")
+ self.assertIn("/resolve/" + P.H3_TRISTEP_REVISION + "/loras/", P.H3_TRISTEP_URL)
+ self.assertTrue(P.H3_TRISTEP_URL.startswith("https://huggingface.co/"))
+ self.assertTrue(P.H3_TRISTEP_URL.endswith(P.H3_TRISTEP_FILE))
+ self.assertRegex(P.H3_TRISTEP_SHA256, r"^[0-9a-f]{64}$")
+ self.assertEqual(P.H3_TRISTEP_BYTES, 181697688)
+ self.assertEqual(P.H3_TRISTEP_LICENSE, "MiniMax H3 Community License")
+ self.assertEqual(P.H3_TRISTEP_SOURCE_REPO, "TaoLiveAIGC/TaoMate-H3")
+
+ def test_the_ladder_is_taomates(self):
+ self.assertEqual(P.H3_TRISTEP_SIGMA_SUBSET, SUBSET)
+ self.assertEqual(P.H3_TRISTEP_STEPS, 4)
+ self.assertEqual(P.H3_TRISTEP_FORWARDS, 3)
+ idx = [int(i) for i in SUBSET.split(":")[1].split(",")]
+ self.assertEqual(len(idx), P.H3_TRISTEP_STEPS)
+
+ def test_the_local_copy_matches_the_pin_when_present(self):
+ # The install's own adapter folder (LTX_H3_MODELS decides where it is).
+ local = P._h3_turbo_dir() / P.H3_TRISTEP_FILE
+ if not local.is_file():
+ self.skipTest("adapter not installed on this machine")
+ self.assertEqual(local.stat().st_size, P.H3_TRISTEP_BYTES)
+ h = hashlib.sha256()
+ with open(local, "rb") as fh:
+ for chunk in iter(lambda: fh.read(1 << 22), b""):
+ h.update(chunk)
+ self.assertEqual(h.hexdigest(), P.H3_TRISTEP_SHA256)
+
+
+class TestResolverAndStatus(_Env):
+ def test_nothing_installed(self):
+ r = P.h3_tristep_paths()
+ self.assertFalse(r["files_ok"])
+ self.assertIn(P.H3_TRISTEP_FILE, r["missing"][0])
+ s = P.h3_tristep_status()
+ self.assertFalse(s["available"])
+ self.assertEqual(s["reason"], "not_downloaded")
+ self.assertTrue(s["install_available"])
+ with self.assertRaises(RuntimeError):
+ P.h3_tristep_argv(r)
+
+ def test_the_managed_file_resolves_and_emits_the_ladder(self):
+ f = self.install()
+ r = P.h3_tristep_paths()
+ self.assertEqual((r["lora"], r["version"]), (f, "r19-kijai"))
+ self.assertEqual(P.h3_tristep_argv(r),
+ ["--sigma-subset", SUBSET, "--lora", f"{f}:1.0"])
+ s = P.h3_tristep_status()
+ self.assertTrue(s["available"])
+ self.assertEqual(s["steps"], 4)
+ self.assertEqual(s["forwards"], 3)
+
+ def test_a_full_rank_copy_wins(self):
+ self.install()
+ full = self.install(P.H3_TRISTEP_FULL_FILE)
+ r = P.h3_tristep_paths()
+ self.assertEqual((r["lora"], r["version"]), (full, "r128-full"))
+
+ def test_turbo_never_resolves_the_tristep_file(self):
+ self.install()
+ self.assertFalse(P.h3_turbo_paths()["files_ok"])
+
+ def test_an_old_runner_hides_it(self):
+ self.install()
+ with unittest.mock.patch.object(P, "_h3_runner_has_flag", lambda flag: flag == "--lora"):
+ s = P.h3_tristep_status()
+ self.assertFalse(s["available"])
+ self.assertEqual(s["reason"], "runner_too_old")
+ self.assertFalse(s["install_available"])
+
+ def test_a_single_slot_runner_hides_it(self):
+ self.install()
+ with unittest.mock.patch.object(P, "h3_supports_lora_stack", lambda: False):
+ self.assertFalse(P.h3_tristep_status()["available"])
+
+
+class TestMakeJob(_Env):
+ def test_draft_defaults_to_three_steps_when_installed(self):
+ self.install()
+ p = self.job()["params"]
+ self.assertTrue(p["h3_tristep"])
+ self.assertEqual(p["steps"], 4)
+ self.assertFalse(p["h3_turbo"])
+
+ def test_every_draft_canvas_and_length(self):
+ self.install()
+ for key, cell in P.H3_TIERS.items():
+ if not cell["draft"] or cell["dense"]:
+ continue
+ with self.subTest(cell=key):
+ p = self.job(h3_quality=cell["quality"], h3_length=cell["length"],
+ h3_tier=key)["params"]
+ if p["h3_tier"] != key:
+ continue # a lab cell this install can't render
+ self.assertTrue(p["h3_tristep"])
+ self.assertEqual(p["steps"], 4)
+
+ def test_the_dense_single_pass_keeps_its_own_sampler(self):
+ self.install()
+ p = self.job(h3_length="10s_dense", h3_tier="draft_10s_dense", h3_tristep="1")["params"]
+ if p["h3_tier"] == "draft_10s_dense":
+ self.assertFalse(p["h3_tristep"])
+ self.assertEqual(p["steps"], 16)
+ self.assertNotIn("tristep_min", P.H3_TIERS["draft_10s_dense"])
+
+ def test_i2v_drafts_too(self):
+ self.install()
+ p = self.job(mode="i2v")["params"]
+ self.assertTrue(p["h3_tristep"])
+
+ def test_without_the_adapter_the_draft_is_unchanged(self):
+ p = self.job()["params"]
+ self.assertFalse(p["h3_tristep"])
+ self.assertEqual(p["steps"], P.H3_TIERS["draft_5s"]["steps"])
+
+ def test_asked_for_but_missing_says_so(self):
+ p = self.job(h3_tristep="1")["params"]
+ self.assertFalse(p["h3_tristep"])
+ self.assertTrue(any("Fast (3 steps) requested" in m for m in self.logs))
+
+ def test_the_eight_forward_draft_stays_reachable(self):
+ self.install()
+ p = self.job(h3_tristep="0")["params"]
+ self.assertFalse(p["h3_tristep"])
+ self.assertEqual(p["steps"], 9)
+ # A Steps pin with no explicit choice keeps the standard sampler too.
+ p = self.job(h3_steps="12")["params"]
+ self.assertFalse(p["h3_tristep"])
+ self.assertEqual(p["steps"], 12)
+
+ def test_explicit_three_step_wins_over_a_leftover_steps_pin(self):
+ self.install()
+ p = self.job(h3_tristep="1", h3_steps="12")["params"]
+ self.assertTrue(p["h3_tristep"])
+ self.assertEqual((p["steps"], p["h3_steps"]), (4, 0))
+
+ def test_standard_and_high_default_to_fast_and_best_is_one_field_away(self):
+ self.install()
+ for q in ("standard", "high"):
+ with self.subTest(quality=q):
+ p = self.job(h3_quality=q)["params"]
+ self.assertTrue(p["h3_tristep"])
+ self.assertEqual(p["steps"], 4)
+ p = self.job(h3_quality=q, h3_tristep="1", mode="i2v")["params"]
+ self.assertTrue(p["h3_tristep"])
+ p = self.job(h3_quality=q, h3_length="10s", h3_tristep="1")["params"]
+ self.assertTrue(p["h3_tristep"]) # chained 5 s windows
+ p = self.job(h3_quality=q, h3_tristep="0")["params"] # Best
+ self.assertFalse(p["h3_tristep"])
+ self.assertEqual(p["steps"], P.H3_TIERS[f"{q}_5s"]["steps"])
+
+ def test_never_on_native(self):
+ self.install()
+ p = self.job(h3_quality="native", h3_tristep="1")["params"]
+ self.assertFalse(p["h3_tristep"])
+ self.assertEqual(p["steps"], P.H3_TIERS["native_5s"]["steps"])
+ self.assertTrue(any("Draft, Standard and High" in m for m in self.logs))
+ self.assertFalse(self.job(h3_quality="native")["params"]["h3_tristep"])
+
+ def test_turbo_is_never_stacked_on_it(self):
+ self.install()
+ with unittest.mock.patch.object(P, "h3_turbo_status",
+ lambda: {"available": True, "supported": True,
+ "missing": []}):
+ p = self.job(h3_turbo="1")["params"]
+ self.assertTrue(p["h3_tristep"])
+ self.assertFalse(p["h3_turbo"])
+ self.assertEqual(p["steps"], 4)
+ self.assertTrue(any("Turbo is off" in m for m in self.logs))
+ # High too: Fast replaces Turbo; Best (h3_tristep=0) keeps an API
+ # caller's Turbo; Native keeps Turbo (Fast never runs there).
+ p = self.job(h3_turbo="1", h3_quality="high")["params"]
+ self.assertFalse(p["h3_turbo"])
+ self.assertTrue(p["h3_tristep"])
+ p = self.job(h3_turbo="1", h3_quality="high", h3_tristep="0")["params"]
+ self.assertTrue(p["h3_turbo"])
+ self.assertFalse(p["h3_tristep"])
+ p = self.job(h3_turbo="1", h3_quality="native")["params"]
+ self.assertTrue(p["h3_turbo"])
+ self.assertFalse(p["h3_tristep"])
+ # Picking Turbo on a Draft (h3_tristep=0) renders Turbo.
+ p = self.job(h3_turbo="1", h3_tristep="0")["params"]
+ self.assertTrue(p["h3_turbo"])
+ self.assertFalse(p["h3_tristep"])
+
+ def test_ltx_jobs_never_carry_it(self):
+ self.install()
+ p = P.make_job({"mode": ["t2v"], "engine": ["ltx"], "prompt": ["x"],
+ "h3_tristep": ["1"]})["params"]
+ self.assertFalse(p["h3_tristep"])
+
+
+class TestEstimates(unittest.TestCase):
+ def test_draft_cells_are_priced(self):
+ cell = P.H3_TIERS["draft_5s"]
+ self.assertEqual(cell["tristep_min_i2v"], 3.0)
+ self.assertEqual(cell["tristep_eta_i2v"], "~3 min")
+ self.assertTrue(cell["tristep_measured_i2v"])
+ # No T2V receipt at 640×384: the model prices it (and agrees).
+ self.assertFalse(cell["tristep_measured"])
+ self.assertEqual(cell["tristep_min"], round(P.h3_estimate_minutes(640, 384, 124, 1, 3), 2))
+ self.assertEqual(cell["tristep_eta"], "~3 min")
+ self.assertEqual(cell["tristep_forwards"], 3)
+ self.assertEqual(cell["facefix_min"], P.FACE_FIX_DRAFT_5S_MIN)
+ self.assertAlmostEqual(cell["tristep_min_i2v"] + cell["facefix_min"], 5.5)
+ self.assertLess(cell["tristep_min"], cell["eta_min"])
+ short = P.H3_TIERS["draft_3s"]
+ self.assertFalse(short["tristep_measured"])
+ self.assertLess(short["tristep_min"], short["eta_min"])
+ self.assertEqual(short["tristep_min"], round(P.h3_estimate_minutes(640, 384, 73, 1, 3), 2))
+ self.assertEqual(P.H3_TIERS["draft_10s"]["tristep_forwards"], 6)
+ self.assertTrue(cell["tristep_default"])
+
+ def test_standard_and_high_are_priced_from_their_receipts(self):
+ std, high = P.H3_TIERS["standard_5s"], P.H3_TIERS["high_5s"]
+ self.assertEqual((std["tristep_min"], std["tristep_eta"]), (4.9, "~5 min"))
+ self.assertEqual((std["tristep_min_i2v"], std["tristep_eta_i2v"]), (4.8, "~5 min"))
+ self.assertEqual((high["tristep_min"], high["tristep_eta"]), (8.4, "~8 min"))
+ self.assertEqual((high["tristep_min_i2v"], high["tristep_eta_i2v"]), (9.0, "~9 min"))
+ for c in (std, high):
+ self.assertTrue(c["tristep_measured"] and c["tristep_measured_i2v"])
+ self.assertTrue(c["tristep_default"])
+ self.assertEqual(std["facefix_min"], 4.0)
+ self.assertEqual(high["facefix_min"], 9.0)
+ self.assertLess(high["tristep_min_i2v"], high["eta_min"] / 3)
+ self.assertIn("tristep_min", P.H3_TIERS["high_15s"])
+ self.assertNotIn("tristep_min", P.H3_TIERS["native_5s"])
+ self.assertNotIn("tristep_min", P.H3_TIERS["high_10s_dense"])
+
+ def test_other_canvases_are_not(self):
+ for key, cell in P.H3_TIERS.items():
+ if P.h3_cell_takes_tristep(cell):
+ continue
+ with self.subTest(cell=key):
+ self.assertNotIn("tristep_min", cell)
+ self.assertNotIn("facefix_min", cell)
+
+ def test_the_face_fix_note_prices_the_draft(self):
+ 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"])
+
+ def test_storyboard_prices_a_draft_at_three_steps_when_installed(self):
+ with unittest.mock.patch.object(P, "h3_tristep_status", lambda: {"available": True}), \
+ unittest.mock.patch.object(P, "h3_turbo_status", lambda: {"available": False}):
+ self.assertEqual(P._sb_h3_cost("draft", "5s"),
+ P.H3_TIERS["draft_5s"]["tristep_min"] * 60.0)
+ self.assertEqual(P._sb_h3_cost("high", "5s"),
+ P.H3_TIERS["high_5s"]["tristep_min"] * 60.0)
+ self.assertEqual(P._sb_h3_cost("native", "5s"),
+ P.H3_TIERS["native_5s"]["eta_min"] * 60.0)
+ with unittest.mock.patch.object(P, "h3_tristep_status", lambda: {"available": False}), \
+ unittest.mock.patch.object(P, "h3_turbo_status", lambda: {"available": False}):
+ self.assertEqual(P._sb_h3_cost("draft", "5s"),
+ P.H3_TIERS["draft_5s"]["eta_min"] * 60.0)
+
+
+class TestRenderArgv(_Env):
+ """The runner argv, intercepted at Popen."""
+
+ def dispatch(self, params: dict) -> tuple[list[str], dict]:
+ seen = {}
+
+ class Intercept(Exception):
+ pass
+
+ def popen(cmd, **kw):
+ seen["cmd"] = cmd
+ raise Intercept()
+
+ job = {"id": "tri-1", "params": {
+ "engine": "h3", "mode": "t2v", "prompt": "a dancer", "seed": "7",
+ "h3_tier": "draft_5s", "h3_turbo": False, **params}}
+ paths = dict(missing=[], repairable=False, dit=_TMP / "dit", python=sys.executable,
+ runner=_TMP / "gen.py", compact_root=_TMP / "c", text_config=_TMP / "t")
+ ff = _TMP / "ffmpeg"
+ ff.write_text("")
+ with ExitStack() as st:
+ for name, val in {
+ "h3_paths": lambda: paths, "h3_capable": lambda: True,
+ "h3_lora_max_stack": lambda: 4,
+ "h3_dit_choice": lambda: ("bf16", None),
+ "output_codec_settings": lambda: {"crf": "18", "pix_fmt": "yuv420p"},
+ "h3_tae_checkpoint": lambda: _TMP / "tae.safetensors",
+ "FFMPEG": ff}.items():
+ st.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"):
+ st.enter_context(unittest.mock.patch.object(P, name, lambda: False))
+ st.enter_context(unittest.mock.patch.object(P, "h3_supports_tae_draft", lambda: True))
+ st.enter_context(unittest.mock.patch.object(P.HELPER, "is_alive", lambda: False))
+ st.enter_context(unittest.mock.patch.object(P.subprocess, "Popen", popen))
+ with self.assertRaises(Intercept):
+ P.run_h3_job_inner(job)
+ return seen["cmd"], job["params"]
+
+ @staticmethod
+ def loras(cmd):
+ return [cmd[i + 1] for i, a in enumerate(cmd) if a == "--lora"]
+
+ def test_three_step_argv(self):
+ f = self.install()
+ cmd, p = self.dispatch({"h3_tristep": True, "steps": 4})
+ self.assertEqual(cmd[cmd.index("--steps") + 1], "4")
+ self.assertEqual(cmd[cmd.index("--sigma-subset") + 1], SUBSET)
+ self.assertEqual(self.loras(cmd), [f"{f}:1.0"])
+ # Full VAE decode — the approved look, and what Face Fix starts from.
+ self.assertNotIn("--draft-decode", cmd)
+ self.assertTrue(any("Fast, 3 steps (TaoMate adapter" in m for m in self.logs))
+
+ def test_the_eight_forward_draft_argv_is_unchanged(self):
+ self.install()
+ cmd, _ = self.dispatch({"h3_tristep": False, "steps": 9})
+ self.assertEqual(cmd[cmd.index("--steps") + 1], "9")
+ self.assertNotIn("--sigma-subset", cmd)
+ self.assertEqual(self.loras(cmd), [])
+ self.assertIn("--draft-decode", cmd)
+
+ def test_a_hand_edited_job_never_stacks_turbo(self):
+ f = self.install()
+ (self.adir / P.H3_TURBO_V4_FILE).write_bytes(b"turbo fixture")
+ cmd, p = self.dispatch({"h3_tristep": True, "h3_turbo": True, "steps": 4})
+ self.assertEqual(self.loras(cmd), [f"{f}:1.0"])
+ self.assertFalse(p["h3_turbo"])
+ self.assertEqual(cmd[cmd.index("--steps") + 1], "4")
+
+ def test_high_i2v_takes_it_when_asked(self):
+ f = self.install()
+ img = _TMP / "frame.png"
+ from PIL import Image
+ Image.new("RGB", (1024, 576)).save(img)
+ with unittest.mock.patch.object(P, "h3_supports_first_frame", lambda: True):
+ cmd, p = self.dispatch({"h3_tier": "high_5s", "h3_tristep": True, "steps": 4,
+ "mode": "i2v", "image": str(img)})
+ self.assertEqual(cmd[cmd.index("--steps") + 1], "4")
+ self.assertEqual(cmd[cmd.index("--sigma-subset") + 1], SUBSET)
+ self.assertEqual(self.loras(cmd), [f"{f}:1.0"])
+ self.assertIn("--first-frame", cmd)
+ self.assertEqual(cmd[cmd.index("--width") + 1], "1024")
+
+ def test_native_drops_it(self):
+ self.install()
+ cmd, p = self.dispatch({"h3_tier": "native_5s", "h3_tristep": True, "steps": 9})
+ self.assertNotIn("--sigma-subset", cmd)
+ self.assertFalse(p["h3_tristep"])
+ self.assertEqual(cmd[cmd.index("--steps") + 1], "9")
+
+ def test_a_vanished_adapter_fails_with_the_remedy(self):
+ with self.assertRaises(RuntimeError) as ctx:
+ self.dispatch({"h3_tristep": True, "steps": 4})
+ self.assertIn("pick Best under Speed", str(ctx.exception))
+
+ def test_it_stacks_with_character_and_style_loras(self):
+ f = self.install()
+ ldir = Path(tempfile.mkdtemp(prefix="h3loras-", dir=_TMP))
+ users = []
+ for name in ("bizarro", "vhs"):
+ u = ldir / f"{name}.safetensors"
+ _safetensors(u, {"blocks.1.attn.qkv_proj.lora_A.weight": ((4, 3), [1.0] * 12),
+ "blocks.1.attn.qkv_proj.lora_B.weight": ((4, 4), [1.0] * 16)})
+ u.with_suffix(".json").write_text(json.dumps(
+ {"name": name, "kind": "import", "lora_layout": "bare",
+ "recommended_strength": 1.0}))
+ users.append(u)
+ import mlx.core as mx
+ mx.set_default_device(mx.cpu)
+ with unittest.mock.patch.object(P, "_h3_loras_dir", lambda: ldir):
+ P._H3_LORA_LAYOUT_CACHE.clear()
+ cmd, _ = self.dispatch({"h3_tristep": True, "steps": 4, "mode": "t2v",
+ "loras": [{"path": str(users[0]), "strength": 1.0},
+ {"path": str(users[1]), "strength": 0.8}]})
+ got = self.loras(cmd)
+ self.assertEqual(got[0], f"{f}:1.0") # the adapter first
+ self.assertEqual(len(got), 3)
+ self.assertEqual([float(s.rsplit(":", 1)[1]) for s in got[1:]], [1.0, 0.8])
+
+
+class _FakeResp(io.BytesIO):
+ def __init__(self, data: bytes, status: int):
+ super().__init__(data)
+ self.status = status
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ self.close()
+
+
+class TestDownload(unittest.TestCase):
+ PAYLOAD = bytes(range(256)) * 40 # 10,240 bytes
+
+ def setUp(self):
+ self.dir = Path(tempfile.mkdtemp(prefix="tri-dl-", dir=_TMP))
+ self.asset = {"file": "tri.safetensors", "url": "https://example.invalid/tri",
+ "sha256": hashlib.sha256(self.PAYLOAD).hexdigest(),
+ "bytes": len(self.PAYLOAD)}
+ self.requests: list[dict] = []
+ self.logs: list[str] = []
+
+ def opener(self, honour_range=True):
+ def _open(req, timeout=None):
+ rng = req.get_header("Range")
+ self.requests.append({"range": rng})
+ if rng and honour_range:
+ start = int(rng.split("=")[1].rstrip("-"))
+ return _FakeResp(self.PAYLOAD[start:], 206)
+ return _FakeResp(self.PAYLOAD, 200)
+ return _open
+
+ def run_dl(self, **kw):
+ P._h3_tristep_download_bg(self.dir, self.logs.append, asset=self.asset,
+ opener=kw.get("opener") or self.opener())
+
+ def test_fresh(self):
+ self.run_dl()
+ self.assertEqual((self.dir / "tri.safetensors").read_bytes(), self.PAYLOAD)
+ self.assertEqual(P._h3_tristep_dl_state["status"], "done")
+ self.assertIsNone(self.requests[0]["range"])
+
+ def test_resumes_a_partial(self):
+ (self.dir / "tri.safetensors.partial").write_bytes(self.PAYLOAD[:4000])
+ self.run_dl()
+ self.assertEqual(self.requests[0]["range"], "bytes=4000-")
+ self.assertEqual((self.dir / "tri.safetensors").read_bytes(), self.PAYLOAD)
+ self.assertFalse((self.dir / "tri.safetensors.partial").exists())
+
+ def test_a_server_that_ignores_range_restarts_cleanly(self):
+ (self.dir / "tri.safetensors.partial").write_bytes(self.PAYLOAD[:4000])
+ self.run_dl(opener=self.opener(honour_range=False))
+ self.assertEqual((self.dir / "tri.safetensors").read_bytes(), self.PAYLOAD)
+
+ def test_a_whole_partial_needs_no_request(self):
+ (self.dir / "tri.safetensors.partial").write_bytes(self.PAYLOAD)
+ self.run_dl()
+ self.assertEqual(self.requests, [])
+ self.assertTrue((self.dir / "tri.safetensors").is_file())
+
+ def test_a_corrupt_download_is_refused_and_dropped(self):
+ self.asset["sha256"] = "0" * 64
+ self.run_dl()
+ self.assertFalse((self.dir / "tri.safetensors").exists())
+ self.assertFalse((self.dir / "tri.safetensors.partial").exists())
+ self.assertEqual(P._h3_tristep_dl_state["status"], "error")
+ self.assertIn("checksum", P._h3_tristep_dl_state["error"])
+
+ def test_a_cut_download_keeps_its_partial_for_the_next_press(self):
+ def short(req, timeout=None):
+ return _FakeResp(self.PAYLOAD[:3000], 200)
+ self.run_dl(opener=short)
+ self.assertFalse((self.dir / "tri.safetensors").exists())
+ self.assertEqual((self.dir / "tri.safetensors.partial").stat().st_size, 3000)
+ self.assertEqual(P._h3_tristep_dl_state["status"], "error")
+ self.run_dl()
+ self.assertEqual((self.dir / "tri.safetensors").read_bytes(), self.PAYLOAD)
+
+
+class TestInstall(_Env):
+ def test_refuses_without_h3_or_with_an_old_runner(self):
+ with unittest.mock.patch.object(P, "h3_paths", lambda: {"missing": ["dit"]}):
+ r = P._h3_install_tristep(lambda _m: None, download_fn=lambda *a: None)
+ self.assertFalse(r["ok"])
+ self.assertIn("isn't fully installed", r["error"])
+ with unittest.mock.patch.object(P, "h3_paths", lambda: {"missing": []}), \
+ unittest.mock.patch.object(P, "_h3_runner_has_flag", lambda flag: flag == "--lora"):
+ r = P._h3_install_tristep(lambda _m: None, download_fn=lambda *a: None)
+ self.assertFalse(r["ok"])
+ self.assertIn("--sigma-subset", r["error"])
+
+ def test_starts_once_and_short_circuits_when_present(self):
+ gate, calls = threading.Event(), []
+
+ def blocked(target, push_log):
+ calls.append(target)
+ gate.wait(timeout=10)
+
+ with unittest.mock.patch.object(P, "h3_paths", lambda: {"missing": []}):
+ first = P._h3_install_tristep(lambda _m: None, download_fn=blocked)
+ second = P._h3_install_tristep(lambda _m: None, download_fn=blocked)
+ gate.set()
+ self.assertTrue(first["ok"] and first["started"])
+ self.assertEqual(first["sha256"], P.H3_TRISTEP_SHA256)
+ self.assertEqual(first["asset"], P.H3_TRISTEP_URL)
+ self.assertFalse(second["ok"])
+ self.assertIn("active", second["error"])
+ P._set_h3_tristep_dl(status="idle", mb=0, total_mb=0, error=None)
+ self.install()
+ third = P._h3_install_tristep(lambda _m: None, download_fn=blocked)
+ self.assertTrue(third["already_installed"])
+ self.assertFalse(third["started"])
+
+ def test_the_route_is_registered(self):
+ src = (ROOT / "panel" / "routes_image.py").read_text(encoding="utf-8")
+ self.assertIn('@post("/h3/tristep/install")', src)
+ self.assertIn("P._h3_install_tristep(P.push)", src)
+
+
+class TestUiContract(unittest.TestCase):
+ """The form posts the choice; the pill exists; the modal and Finish know it."""
+
+ def test_markup(self):
+ html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")
+ self.assertIn('name="h3_tristep" id="h3_tristep"', html)
+ # ONE switch, two halves, ABOVE the Quality cards; the old Turbo row is gone.
+ self.assertIn('data-h3-speed="fast"', html)
+ 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)
+ # 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"'))
+
+ def test_engines_js(self):
+ js = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")
+ for needle in ("function h3TriStepOn", "tristep_min_i2v", "/h3/tristep/install",
+ "phos_h3_speed", "Install (180 MB)", "facefix_min",
+ "function h3EstimateLine", "function setH3Speed",
+ "if (tbIn) tbIn.value = '0';"):
+ self.assertIn(needle, js)
+
+ def test_queue_js(self):
+ js = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")
+ self.assertIn("h3_speed: (p.h3_tristep || p.h3_turbo) ? 'fast' : 'best'", js)
+ self.assertIn("setH3Speed(h3SpeedOfParams(p))", js)
+ self.assertIn("h3EstimateLine()", js)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/test_music_engine.py b/test_music_engine.py
index 7ac6e14..e72b198 100644
--- a/test_music_engine.py
+++ b/test_music_engine.py
@@ -950,3 +950,33 @@ def test_the_panel_spawns_music_through_the_scrubbed_env():
body = src[src.index("def run_music_job_inner"):src.index("ENGINE_DEFAULT = ")]
assert "env=music_child_env()" in body
assert "env={**os.environ" not in body
+
+
+# ---- the trainers get the same treatment (2026-09-18) ------------------------
+#
+# The release checklist's §0 listed the two `{**os.environ}` spreads in
+# mlx_ltx_panel.py — the character trainer and the audio trainer — as the last
+# raw ones in the repo, with the note "fix the trainers before anything
+# MPS-sensitive lands in them". lora_lab is MLX end to end, so Pinokio's
+# PyTorch switches mean nothing to it and are pure inherited accident.
+
+def test_trainer_child_env_drops_the_pinokio_torch_vars_and_malloc_noise():
+ env = P.trainer_child_env({
+ "PATH": "/bin", "HF_HOME": "/hf", "PYTHONPATH": "/panel",
+ "PYTORCH_ENABLE_MPS_FALLBACK": "1", "PYTORCH_MPS_FAST_MATH": "1",
+ "MallocStackLogging": "", "MallocNanoZone": "0",
+ })
+ assert "PYTORCH_ENABLE_MPS_FALLBACK" not in env
+ assert "PYTORCH_MPS_FAST_MATH" not in env
+ assert not [k for k in env if k.startswith("Malloc")]
+ # ...and everything the trainer actually needs survives untouched.
+ assert env["PATH"] == "/bin" and env["HF_HOME"] == "/hf"
+ assert env["PYTHONPATH"] == "/panel" # scripts/lora_lab_run.sh owns it
+ assert env["PYTHONUNBUFFERED"] == "1"
+
+
+def test_no_trainer_spawns_the_raw_environment_any_more():
+ src = Path(P.__file__).read_text()
+ assert "env={**os.environ" not in src
+ assert "_train_env = trainer_child_env()" in src
+ assert src.count("env=trainer_child_env()") >= 1
diff --git a/test_pasted_paths.py b/test_pasted_paths.py
index 43d91d2..d5deaf3 100644
--- a/test_pasted_paths.py
+++ b/test_pasted_paths.py
@@ -140,9 +140,53 @@ def test_failure_line_falls_back_to_the_last_real_line():
def test_h3_failure_uses_it_and_keeps_a_deep_tail():
src = Path(P.__file__).read_text()
- assert "_last = failure_line(_h3_tail)" in src
- assert "collections.deque(maxlen=14)" in src[src.index("_h3_tail: collections.deque"):
- src.index("_h3_tail: collections.deque") + 120]
+ assert "_last = failure_where(_h3_tail)" in src
+ i = src.index("_h3_tail: collections.deque")
+ assert "collections.deque(maxlen=40)" in src[i:i + 120]
+
+
+# ---- and WHERE it came from --------------------------------------------------
+
+NANOBIND_TAIL = [
+ "step 8/8",
+ "Traceback (most recent call last):",
+ ' File "/Users/somebody/minimax-h3-mlx/scripts/generate_staged.py", line 1204, in main',
+ " frames = decode(latents)",
+ ' File "/Users/somebody/minimax-h3-mlx/minimax_h3_mlx/tiny_video_vae.py", line 42, in __call__',
+ " return mx.repeat(mx.repeat(x, 2, axis=2), 2, axis=3)",
+ "TypeError: repeat(): incompatible function arguments. The following argument types are supported:",
+ " 1. repeat(array: array, repeats: int, axis: int, *, stream = None) -> array",
+ " 2. repeat(array: array, repeats: int, *, stream = None) -> array",
+ "Invoked with types: mlx.core.array, float, kwargs = { axis: int }",
+]
+
+
+def test_failure_frame_names_the_deepest_frame_by_basename_only():
+ assert P.failure_frame(NANOBIND_TAIL) == "tiny_video_vae.py:42 in __call__"
+ # A user's folder names are theirs; only the file is ours to report.
+ assert "somebody" not in P.failure_frame(NANOBIND_TAIL)
+ assert P.failure_frame(["killed by the sandbox"]) == ""
+ assert P.failure_frame([]) == ""
+
+
+def test_failure_where_is_the_exception_and_the_frame():
+ msg = P.failure_where(NANOBIND_TAIL)
+ assert msg.startswith("TypeError: repeat(): incompatible function arguments")
+ assert msg.endswith("(at tiny_video_vae.py:42 in __call__)")
+ # No traceback: unchanged from failure_line, no empty parenthetical.
+ assert P.failure_where(["killed by the sandbox"]) == "killed by the sandbox"
+ assert P.failure_where([]) == ""
+
+
+def test_helper_start_failure_names_the_frame_too():
+ msg = P._helper_start_failure(
+ {"event": "exit"},
+ ["Traceback (most recent call last):",
+ ' File "/x/mlx_warm_helper.py", line 12, in <module>',
+ " import ltx_pipelines_mlx",
+ "ModuleNotFoundError: No module named 'ltx_pipelines_mlx'"])
+ assert "No module named 'ltx_pipelines_mlx'" in msg
+ assert "mlx_warm_helper.py:12 in <module>" in msg
def test_helper_start_failure_says_what_happened_and_what_to_do():
diff --git a/test_render_form_sections.py b/test_render_form_sections.py
new file mode 100644
index 0000000..68a0536
--- /dev/null
+++ b/test_render_form_sections.py
@@ -0,0 +1,477 @@
+#!/usr/bin/env python3
+"""The render form is three named, closed-by-default sections.
+
+Owner, 2026-09-18: "The H3 layout is kind of a bit too much. … you have a pill
+for speed, quality, length, and all that. That should be inside one section that
+you can compress and decompress, like we have LoRAs and Customize, because it is
+very messy like that. I don't think it is easy to navigate between the options …
+it should be closed by default. … Think about what you can separate and what
+should be grouped together."
+
+What this pins:
+ 1 the form keeps FOUR things in the open — engine (header), mode (bar), the
+ composer (reference + prompt), Generate (footer) — and everything else
+ lives in a disclosure that ships CLOSED: Shot setup, After the render,
+ Advanced, LoRAs. No `open` attribute on any of them.
+ 2 WHICH control is in WHICH section, by id. A control that drifts back out
+ to the top level, or into the wrong section, fails here.
+ 3 the order Speed → Quality inside Shot setup (test_h3_tristep_draft pins the
+ same thing from the other side, because Fast overrules Steps).
+ 4 nothing was dropped or renamed: every form field name the old layout posted
+ is still in the markup, and the H3 fields are still read by the panel (a
+ field that isn't in make_job's allowlist silently no-ops on /queue/add).
+ 5 the cell's honest notes (#ltxTierNote / #h3TierNote) stay OUTSIDE the
+ disclosures — a warning about the render you are about to queue must not
+ be foldable.
+ 6 the three summary lines exist and are written from one entry point, so a
+ closed section still says what it is hiding.
+ 7 the markup is balanced. The old form carried a stray `</div>` that closed
+ .quick-settings early, which is why Orientation and Seed were siblings of
+ the form rather than children of the block that styled them.
+"""
+from __future__ import annotations
+
+import re
+import unittest
+from html.parser import HTMLParser
+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")
+CJS = (ROOT / "webapp" / "js" / "characters.js").read_text(encoding="utf-8")
+LJS = (ROOT / "webapp" / "js" / "loras.js").read_text(encoding="utf-8")
+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")
+PANEL = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")
+
+FORM = HTML[HTML.index('<form id="genForm">'):HTML.index("</form>")]
+
+
+def block(details_id: str) -> str:
+ """The inner HTML of <details id=...>. None of the form's sections nest a
+ <details>, so the first close is the right one."""
+ start = HTML.index('<details id="%s"' % details_id)
+ return HTML[start:HTML.index("</details>", start)]
+
+
+SHOT = block("shotSetupDetails")
+FINISH = block("finishDetails")
+ADVANCED = block("customizeDetails")
+
+
+class SectionsAreClosedByDefault(unittest.TestCase):
+ def test_the_four_disclosures_exist_with_their_labels(self):
+ for did, title in (
+ ("shotSetupDetails", "Shot setup"),
+ ("finishDetails", "After the render"),
+ ("customizeDetails", "Advanced"),
+ ):
+ self.assertIn('<details id="%s"' % did, HTML)
+ self.assertIn('<span class="cz-title">%s</span>' % title, HTML)
+ self.assertIn('<details id="lorasDetails" class="loras-section">', HTML)
+
+ def test_none_of_them_ships_open(self):
+ for did in ("shotSetupDetails", "finishDetails", "customizeDetails",
+ "lorasDetails"):
+ tag = re.search(r"<details id=\"%s\"[^>]*>" % did, HTML)
+ self.assertIsNotNone(tag, did)
+ self.assertNotIn(" open", tag.group(0), did + " must ship closed")
+
+ def test_each_section_carries_a_summary_line(self):
+ for meta in ("shotSetupSummary", "finishSummary", "customizeSummary"):
+ self.assertIn('class="cz-meta" id="%s"' % meta, HTML)
+
+ def test_the_word_customize_is_gone_from_the_form(self):
+ # The grab-bag was split; the id survives for every caller, the label
+ # does not.
+ self.assertNotIn('<span class="cz-title">Customize</span>', HTML)
+
+
+class WhatIsInEachSection(unittest.TestCase):
+ def test_shot_setup_holds_the_shape(self):
+ for cid in (
+ 'id="h3SpeedRow"', # H3 Fast | Best
+ 'id="schedPresetRow"', # LTX Tuned | Fast draft
+ 'id="qualityLabelName"', # Quality label (both engines)
+ 'id="qualityGroup"', # LTX canvas
+ 'id="ltxAxes"', # LTX length
+ 'id="qualityGroupCharacter"',
+ 'id="h3TierGroup"', # H3 canvas + length
+ 'id="h3PrimaryControls"',
+ 'id="h3StepsRow"', # H3 steps
+ 'id="h3LoraSlotRow"', # the one adapter slot
+ 'id="aspectRow"', # LTX orientation
+ 'id="h3OrientationRow"', # H3 orientation
+ 'id="quickMetricsRow"', # seed
+ ):
+ self.assertIn(cid, SHOT, cid + " left Shot setup")
+
+ def test_speed_still_comes_before_quality(self):
+ self.assertLess(SHOT.index('id="h3SpeedRow"'),
+ SHOT.index('id="qualityLabelName"'))
+
+ def test_after_the_render_holds_what_happens_to_the_file(self):
+ for cid in ('id="h3ExportRow"', 'id="h3UpscaleGroup"',
+ 'id="h3FaceFixAfter"', 'id="upscaleGroup"',
+ 'id="upscaleMethodRow"', 'id="open_when_done"'):
+ self.assertIn(cid, FINISH, cid + " left After the render")
+
+ def test_advanced_holds_the_overrides(self):
+ for cid in ('id="dimsRow"', 'id="durationRow"', 'id="accelRow"',
+ 'id="stgRow"', 'id="temporalRow"', 'id="windowsRow"',
+ 'id="i2vAudioModeSection"'):
+ self.assertIn(cid, ADVANCED, cid + " left Advanced")
+
+ def test_the_sections_do_not_overlap(self):
+ for cid in ('id="dimsRow"', 'id="upscaleGroup"', 'id="open_when_done"'):
+ self.assertNotIn(cid, SHOT)
+ for cid in ('id="h3StepsRow"', 'id="quickMetricsRow"', 'id="dimsRow"'):
+ self.assertNotIn(cid, FINISH)
+ for cid in ('id="h3StepsRow"', 'id="h3ExportRow"', 'id="upscaleGroup"'):
+ self.assertNotIn(cid, ADVANCED)
+
+ def test_the_shot_list_sits_with_the_prompt_not_inside_a_section(self):
+ # Per-window prompts is prompt CONTENT (one line per 5 s window), and a
+ # user who has just chosen a 15 s length has to be able to see it.
+ self.assertNotIn('id="h3WindowPromptsRow"', SHOT)
+ self.assertLess(HTML.index('id="h3WindowPromptsRow"'),
+ HTML.index('<details id="shotSetupDetails"'))
+ self.assertLess(HTML.index('id="prompt" class="composer-prompt"'),
+ HTML.index('id="h3WindowPromptsRow"'))
+
+ def test_the_honest_notes_are_not_foldable(self):
+ for cid in ('id="ltxTierNote"', 'id="h3TierNote"', 'id="engineRowNote"'):
+ self.assertIn(cid, HTML)
+ for sec in (SHOT, FINISH, ADVANCED):
+ self.assertNotIn(cid, sec, cid + " must stay visible")
+
+
+class NothingWasDroppedOrRenamed(unittest.TestCase):
+ # Every field the form posted before the layout pass. The list is the point:
+ # a moved row that loses its hidden input posts nothing and fails silently.
+ FIELDS = (
+ "preset_label", "mode", "quality", "quality_choice", "ltx_length",
+ "accel", "temporal_mode", "upscale", "schedule_preset", "prompt",
+ "negative_prompt", "no_music", "no_voice", "hdr", "engine",
+ "h3_tier", "h3_quality", "h3_length", "h3_upscale", "h3_steps",
+ "h3_turbo", "h3_tristep", "h3_lora_slot", "h3_chain_prompts",
+ "h3_orientation", "aspect", "seed", "loras", "steps", "width",
+ "height", "frames", "stg_scale", "window_prompts",
+ "window_invariants", "upscale_method", "audio", "open_when_done",
+ "image", "i2v_reference_mode", "start_image", "end_image",
+ "keyframe_count", "character_id", "character_strength",
+ "character_voice_strength", "stop_comfy",
+ )
+
+ def test_every_field_is_still_in_the_form(self):
+ names = set(re.findall(r'name="([a-z0-9_]+)"', FORM))
+ for f in self.FIELDS:
+ self.assertIn(f, names, f + " is no longer posted by #genForm")
+
+ def test_the_h3_fields_are_still_read_by_the_panel(self):
+ # A form field that isn't in make_job's allowlist silently no-ops on
+ # /queue/add — the known trap. This is the cheap standing guard.
+ for f in ("h3_tier", "h3_quality", "h3_length", "h3_upscale",
+ "h3_steps", "h3_turbo", "h3_tristep", "h3_lora_slot",
+ "h3_chain_prompts", "h3_orientation"):
+ self.assertIn('"%s"' % f, PANEL, f + " is not read server-side")
+
+ def test_the_engine_fold_hooks_survived_the_move(self):
+ # The per-engine fold rules key off these attributes, not off position.
+ self.assertGreater(SHOT.count("data-h3-only"), 3)
+ self.assertGreater(SHOT.count("data-ltx-only"), 2)
+ self.assertIn("data-h3-only", FINISH)
+ self.assertIn("data-ltx-only", ADVANCED)
+
+
+class TheSummariesAreWrittenFromOnePlace(unittest.TestCase):
+ def test_the_three_writers_exist(self):
+ for fn in ("function updateShotSetupSummary",
+ "function updateFinishSummary",
+ "function updateAdvancedSummary"):
+ self.assertIn(fn, CJS)
+
+ def test_the_old_entry_point_fans_out(self):
+ # 23 call sites across five modules call updateCustomizeSummary after
+ # every state change; it keeps its name and updates all three.
+ body = CJS[CJS.index("function updateCustomizeSummary"):]
+ body = body[:body.index("\nfunction updateShotSetupSummary")]
+ for fn in ("updateShotSetupSummary()", "updateFinishSummary()",
+ "updateAdvancedSummary()"):
+ self.assertIn(fn, body)
+
+ def test_the_writers_are_exported(self):
+ self.assertIn("updateShotSetupSummary, updateFinishSummary, "
+ "updateAdvancedSummary,", CJS)
+
+ def test_a_closed_shot_setup_still_names_the_shape(self):
+ body = CJS[CJS.index("function updateShotSetupSummary"):
+ CJS.index("function updateFinishSummary")]
+ for needle in ("quality_label", "length_label", "h3TriStepOn",
+ "h3CellEta", "ltxCellEta", "seed "):
+ self.assertIn(needle, body)
+
+ def test_an_import_opens_the_closed_lora_picker(self):
+ self.assertIn("_det.open = true", LJS)
+
+ def test_every_control_in_a_closed_section_refreshes_its_summary(self):
+ # A closed section's line is the only thing the user sees, so each
+ # setter that changes what it says has to rewrite it. setH3Upscale and
+ # setH3Orientation did not (the export target was stale in the old
+ # Customize summary too), and #seed had no listener at all.
+ ejs = (ROOT / "webapp" / "js" / "engines.js").read_text()
+ for fn in ("function setH3Upscale", "function setH3Orientation",
+ "function setH3Steps"):
+ body = ejs[ejs.index(fn):]
+ body = body[:body.index("\n}\n") + 3]
+ self.assertIn("updateCustomizeSummary", body, fn + " leaves it stale")
+ qjs = (ROOT / "webapp" / "js" / "queue.js").read_text()
+ self.assertIn("document.getElementById('seed')?.addEventListener('input'",
+ qjs)
+
+
+class TheChromeIsStyled(unittest.TestCase):
+ def test_the_primary_section_is_marked_in_the_engine_colour(self):
+ self.assertIn('class="customize-section shot-setup"', HTML)
+ self.assertIn(".customize-section.shot-setup", CSS)
+ self.assertIn("--eng-accent", CSS.split(".customize-section.shot-setup")[1][:400])
+
+ def test_the_moved_rows_got_their_margins_rehomed(self):
+ for rule in (".cz-body .h3-speed", ".cz-body .eng-primary",
+ ".cz-body > #quickMetricsRow",
+ ".cz-body > #aspectRow.mode-only.show",
+ ".quick-settings > .engine-hint"):
+ self.assertIn(rule, CSS)
+
+ def test_the_chip_rows_answer_to_the_panes_width_not_the_windows(self):
+ # auto-fit tracks, so a dragged-in pane wraps the chips instead of
+ # squeezing them. Identical to the fixed grids at full width.
+ for rule in (".cz-body .quality-strip { grid-template-columns: "
+ "repeat(auto-fit, minmax(90px, 1fr)); }",
+ ".cz-body .pill-group.cols-4 { grid-template-columns: "
+ "repeat(auto-fit, minmax(62px, 1fr)); }",
+ ".quick-settings .qs-label { flex-wrap: wrap;"):
+ self.assertIn(rule, CSS)
+ self.assertIn("repeat(auto-fit, minmax(90px, 1fr))",
+ (ROOT / "webapp" / "js" / "engines.js").read_text())
+
+ def test_the_shot_list_block_got_its_own_chrome(self):
+ self.assertIn("#genForm > .h3-winprompts {", CSS)
+ self.assertIn(".cz-label .toggle-pill {", CSS)
+
+
+class _Balance(HTMLParser):
+ WATCH = ("div", "details", "form", "summary")
+
+ def __init__(self):
+ super().__init__(convert_charrefs=True)
+ self.stack: list[tuple[str, int]] = []
+ self.bad: list[tuple] = []
+
+ def handle_starttag(self, tag, attrs):
+ if tag in self.WATCH:
+ self.stack.append((tag, self.getpos()[0]))
+
+ def handle_endtag(self, tag):
+ if tag not in self.WATCH:
+ return
+ for i in range(len(self.stack) - 1, -1, -1):
+ if self.stack[i][0] == tag:
+ if i != len(self.stack) - 1:
+ self.bad.append(("crossed", tag, self.getpos()[0],
+ self.stack[-1]))
+ del self.stack[i:]
+ return
+ self.bad.append(("no open", tag, self.getpos()[0]))
+
+
+class TheMarkupIsBalanced(unittest.TestCase):
+ def test_no_stray_or_crossed_div(self):
+ p = _Balance()
+ p.feed(HTML)
+ self.assertEqual(p.bad, [], "unbalanced tags in webapp/index.html")
+ self.assertEqual(p.stack, [], "unclosed tags in webapp/index.html")
+
+ def test_orientation_and_seed_are_inside_the_quick_settings_block(self):
+ # They used to be siblings of the form: the stray </div> closed
+ # .quick-settings before them, so .quick-settings' own label styles
+ # never applied. Both now sit inside Shot setup, inside that block.
+ qs = HTML.index('<div class="quick-settings">')
+ self.assertLess(qs, HTML.index('<details id="shotSetupDetails"'))
+ self.assertIn('id="aspectRow"', SHOT)
+ self.assertIn('id="quickMetricsRow"', SHOT)
+
+
+class BatchIsASection(unittest.TestCase):
+ """Owner, 2026-09-18: "batch is kind of hidden, and it should probably be
+ re-taught in a way that is more user-friendly and also more highlighted. It
+ should be a section, actually, after the render and setup."
+
+ It was a 60-px pill in the queue strip opening a modal with one textarea and
+ the line "split prompts with --- on its own line".
+ """
+
+ def test_it_is_a_closed_section_after_after_the_render(self):
+ self.assertIn('<details id="batchDetails"', HTML)
+ self.assertNotIn('<details id="batchDetails" open', HTML)
+ self.assertLess(HTML.index('<details id="finishDetails"'),
+ HTML.index('<details id="batchDetails"'))
+ self.assertLess(HTML.index('<details id="batchDetails"'),
+ HTML.index('<details id="customizeDetails"'))
+
+ def test_the_modal_is_gone_and_the_pill_opens_the_section(self):
+ self.assertNotIn("batchModal", HTML)
+ self.assertNotIn("batchModal", QJS)
+ self.assertIn("getElementById('batchDetails')", QJS)
+
+ def test_both_modes_exist_and_seeds_mode_randomises(self):
+ batch = block("batchDetails")
+ self.assertIn('data-batch-mode="prompts"', batch)
+ self.assertIn('data-batch-mode="seeds"', batch)
+ # N takes of one prompt must not come back as N identical clips.
+ self.assertIn("fd.set('seed', '-1')", QJS)
+ # One function builds the list the count shows AND the jobs it posts.
+ self.assertIn("function batchPrompts()", QJS)
+
+ def test_the_section_says_how_many_jobs_before_you_commit(self):
+ self.assertIn('id="batchSummary"', HTML)
+ self.assertIn('id="batchCount"', HTML)
+ self.assertIn('id="batchTotal"', HTML)
+ self.assertIn("function updateBatchSummary", QJS)
+ # ...and it is refreshed from the same entry point as the others.
+ self.assertIn("updateBatchSummary()", CJS)
+
+
+class TheShipReviewFindings(unittest.TestCase):
+ """Codex ship review of 92e3033..bca2aa0, 2026-09-18 — the four findings
+ that live in this file's surfaces. Each one is a real user path, so each
+ one gets a line here that fails if it comes back."""
+
+ def test_takes_mode_refuses_a_prompt_that_contains_the_separator(self):
+ # /queue/batch splits `prompts` on a line of three dashes. Repeating a
+ # prompt that CONTAINS such a line turned 3 advertised takes into 6 jobs
+ # holding fragments. The list must come back empty instead.
+ self.assertIn("BATCH_SEP_RX", QJS)
+ i = QJS.index("function batchPrompts()")
+ body = QJS[i:i + 400]
+ self.assertIn("BATCH_SEP_RX.test(main)", body)
+ # ...and the refusal has to be said out loud, in both places a user looks.
+ self.assertIn("line of three dashes, which Batch uses", QJS)
+ self.assertIn("Batch uses that to", QJS)
+
+ def test_the_batch_row_listens_to_the_prompt_it_repeats(self):
+ # Queue stayed disabled while the user typed the very prompt it wanted.
+ i = QJS.index("// \"Same prompt, N takes\" reads #prompt")
+ body = QJS[i:i + 420]
+ self.assertIn("getElementById('prompt')", body)
+ self.assertIn("addEventListener('input'", body)
+ self.assertIn("updateBatchSummary", body)
+
+ def test_the_batch_estimate_helpers_are_published(self):
+ # Private, they threw on first call and the catch swallowed it, so an
+ # H3 batch showed no total at all (lint_webapp no-undef).
+ EJS = (ROOT / "webapp" / "js" / "engines.js").read_text(encoding="utf-8")
+ self.assertIn("h3CellEtaMin, h3FaceFixOn,", EJS)
+
+
+
+ """Owner, 2026-09-18, on After the render: "What is this? It's not good.
+ Normalize the design. The pills are okay. The rest is pretty okay, but it's
+ weird: the other stuff that is in there doesn't look related to the design
+ at all."
+
+ The cause was in the CSS, not the markup: the segmented trough was only ever
+ applied to `.pill-group.cols-2` and `.cols-4`, so the three-option Export
+ row had no container at all while the two-option METHOD row under it did.
+ """
+
+ def test_every_pill_group_count_gets_the_same_trough(self):
+ i = CSS.index(".pill-group.cols-2,")
+ rule = CSS[i:CSS.index("}", i)]
+ for cols in ("cols-2", "cols-3", "cols-4", "cols-5"):
+ self.assertIn(".pill-group." + cols, rule)
+ self.assertIn("background: rgba(140, 160, 220, 0.04)", rule)
+
+ def test_a_checkbox_row_wears_the_sections_chrome(self):
+ i = CSS.index("#genForm .cz-body .check {")
+ rule = CSS[i:CSS.index("}", i)]
+ self.assertIn("background: rgba(140, 160, 220, 0.04)", rule)
+ self.assertIn("border: 1px solid var(--ph-border-soft)", rule)
+
+ def test_the_export_note_sits_under_the_pills_it_explains(self):
+ finish = block("finishDetails")
+ self.assertLess(finish.index('id="h3ExportNote"'),
+ finish.index('id="h3FaceFixAfterRow"'))
+
+
+class OneControlScale(unittest.TestCase):
+ """Owner, 2026-09-18, with a screenshot of the LoRAs header: "all the
+ buttons are different. What the fuck? You need to really clean up the
+ visuals so it looks professional in general."
+
+ Measured in that row before the fix: the rescan icon 28 px, Browse CivitAI
+ 43 px (an inline-styled <svg> inflated its line box), Check for updates
+ 31 px; the footer chips 27 px at 11 px with a pill radius; the batch button
+ 35 px at 12.5 px. This pins the scale, not the look: heights and radii come
+ from one place, and no button carries its geometry inline.
+ """
+
+ SCALED = ("#genForm .loras-summary .loras-icon-btn",
+ "#genForm .loras-summary .loras-browse-btn",
+ "#genForm .batch-queue-btn",
+ ".form-action-footer .queue-strip .qchip")
+
+ def test_the_small_action_buttons_share_one_rule(self):
+ i = CSS.index("#genForm .loras-summary .loras-icon-btn,")
+ rule = CSS[i:CSS.index("}", i)]
+ for sel in self.SCALED:
+ self.assertIn(sel, rule)
+ self.assertIn("height: 30px", rule)
+ self.assertIn("border-radius: 6px", rule)
+ self.assertIn("font-size: 12px", rule)
+
+ def test_no_button_carries_its_geometry_inline(self):
+ # `style="margin-right:6px;vertical-align:-2px"` on nine icons was what
+ # made one button 12 px taller than its neighbour.
+ self.assertNotIn("vertical-align:-2px", HTML)
+
+ def test_one_filled_primary_per_header_row(self):
+ i = CSS.index("#genForm .loras-summary .loras-browse-btn:not(.is-ghost),")
+ rule = CSS[i:CSS.index("}", i)]
+ self.assertIn("background: var(--accent)", rule)
+ # ...and the others are the hairline
+ j = CSS.index("#genForm .loras-summary .loras-browse-btn.is-ghost,")
+ ghost = CSS[j:CSS.index("}", j)]
+ self.assertIn("background: transparent", ghost)
+
+ def test_generate_and_stop_are_one_pair(self):
+ i = CSS.index(".form-action-footer .actions .primary,")
+ self.assertIn("border-radius: 6px", CSS[i:CSS.index("}", i)])
+
+
+class AClosedSectionCostsOneRow(unittest.TestCase):
+ """A fold that is closed must cost a row, and an empty fold must not exist.
+
+ Measured on the live panel after the first pass: the closed LoRAs summary
+ still stood 252 px tall, because every button inside the render form is
+ full-width by default and the header's three buttons each took a line of
+ their own; and on H3 the Advanced row opened onto NOTHING, since every
+ control in it is an LTX override that H3 ignores.
+ """
+
+ def test_the_loras_header_buttons_keep_their_own_width(self):
+ self.assertIn(".loras-summary .loras-browse-btn { width: auto; flex: 0 0 auto; }", CSS)
+
+ def test_advanced_is_hidden_on_h3_not_labelled_empty(self):
+ i = CJS.index("function updateAdvancedSummary")
+ body = CJS[i:i + 1400]
+ self.assertIn("customizeDetails", body)
+ self.assertIn("adv.hidden = true", body)
+ self.assertIn("adv.hidden = false", body)
+ # The inputs stay in the DOM: hiding the container must not change what
+ # the form posts (verified live: 59 FormData keys on both engines).
+ self.assertNotIn("disabled = true", body)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_room_tone.py b/test_room_tone.py
new file mode 100644
index 0000000..26d3287
--- /dev/null
+++ b/test_room_tone.py
@@ -0,0 +1,898 @@
+#!/usr/bin/env python3
+"""Room tone — a generated ambience bed under the whole film.
+
+Owner, 2026-09-17: "the cuts are very rough in terms of sound … if it was all
+over the timeline as an ambient sound, not something really subtle." Locked
+here, against the real generator, the real model, the real filtergraph builder
+and the panel's real JavaScript (run in node):
+
+ * the bed: periodic loop (no seam when tiled), the loudness it claims is the
+ loudness ffmpeg's ebur128 measures, peaks under −1 dBFS, exact length,
+ two decorrelated channels, deterministic per (variant, seed);
+ * "From this film" learns from the QUIET windows of the clips, not from the
+ lines, and falls back to a preset — and says so — when there is no quiet;
+ * the model: a room-tone track validates, normalises with its tag, fits the
+ film's length (only when untouched, bounded by the file);
+ * the de-click: 12 ms fades on each clip-sound segment in the timeline
+ render, and nothing at all for every other caller;
+ * automatic cuts get a bed when the setting is on (and not under a music
+ video, and not when the clips have no quiet sound);
+ * the route, the setting, the client mirror and the Room tone card.
+
+Run: python3 -m unittest test_room_tone
+"""
+from __future__ import annotations
+
+import json
+import math
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+import numpy as np
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT))
+_SCRATCH = Path(tempfile.mkdtemp(prefix="phos-roomtone-"))
+for _k, _d in (("LTX_STATE_DIR", "state"), ("LTX_OUTPUT_DIR", "out"),
+ ("LTX_UPLOADS_DIR", "up")):
+ os.environ.setdefault(_k, str(_SCRATCH / _d))
+ Path(os.environ[_k]).mkdir(parents=True, exist_ok=True)
+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")
+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")
+
+import mlx_ltx_panel as panel # noqa: E402
+import room_tone as rt # noqa: E402
+import storyboard_editor as se # noqa: E402
+from panel.routes import GET_ROUTES, POST_ROUTES # noqa: E402
+from test_storyboard_editor_ui import (NODE, SHIM, extract_function, # noqa: E402
+ panel_source)
+
+FFMPEG = shutil.which("ffmpeg") or ("/opt/homebrew/bin/ffmpeg"
+ if Path("/opt/homebrew/bin/ffmpeg").exists() else None)
+N = rt.LOOP_S * rt.SR
+
+
+def _ebur128(path) -> float:
+ o = subprocess.run([FFMPEG, "-nostats", "-i", str(path), "-af", "ebur128",
+ "-f", "null", "-"], capture_output=True, text=True).stderr
+ return float(re.findall(r"I:\s+(-?[\d.]+) LUFS", o)[-1])
+
+
+# =============================================================================
+# 1. THE BED
+# =============================================================================
+class TheLoop(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.loops = {v: rt.build_loop(v, 7) for v in rt.variant_ids() if v != "film"}
+
+ def test_every_preset_is_on_the_list_the_picker_shows(self):
+ ids = rt.variant_ids()
+ self.assertEqual(ids[0], "film")
+ self.assertEqual(len(ids), len(set(ids)))
+ self.assertGreaterEqual(len(ids), 12) # "10 or 20 versions"
+ for v in rt.variants():
+ self.assertTrue(v["label"] and v["blurb"], v)
+
+ def test_the_loop_is_stereo_and_exactly_one_grid_long(self):
+ for v, r in self.loops.items():
+ self.assertEqual(r["loop"].shape, (2, N), v)
+ self.assertEqual(r["variant"], v)
+ self.assertEqual(r["fallback"], "")
+
+ def test_the_seam_is_no_louder_than_any_other_sample_step(self):
+ # Tiled three times, the step across each boundary is an ordinary step.
+ for v, r in self.loops.items():
+ x = rt.tile(r["loop"], rt.LOOP_S * 3)
+ for k in (1, 2):
+ jump, p999 = rt.seam_jump(x, k * N)
+ self.assertLessEqual(jump, p999, (v, k, jump, p999))
+
+ def test_tiling_repeats_the_loop_sample_for_sample(self):
+ r = self.loops["quiet_room"]
+ x = rt.tile(r["loop"], rt.LOOP_S * 2 + 1.5)
+ self.assertEqual(x.shape[1], int((rt.LOOP_S * 2 + 1.5) * rt.SR))
+ np.testing.assert_array_equal(x[:, N:2 * N], r["loop"])
+ np.testing.assert_array_equal(x[:, 2 * N:], r["loop"][:, :x.shape[1] - 2 * N])
+
+ def test_the_loudness_it_reports_is_the_loudness_it_has(self):
+ for v, r in self.loops.items():
+ self.assertAlmostEqual(rt.loudness_lufs(r["loop"]), r["ref_lufs"], delta=0.05, msg=v)
+ self.assertLessEqual(r["ref_lufs"], rt.REF_LUFS + 0.01, v)
+ # the cap may pull a peaky preset down a little, never a lot
+ self.assertGreater(r["ref_lufs"], rt.REF_LUFS - 3.0, v)
+
+ def test_no_sample_reaches_minus_one_dbfs(self):
+ for v, r in self.loops.items():
+ self.assertLessEqual(float(np.abs(r["loop"]).max()), rt.PEAK_CAP + 1e-6, v)
+
+ def test_the_two_channels_are_not_one_signal(self):
+ for v, r in self.loops.items():
+ c = float(np.corrcoef(r["loop"][0], r["loop"][1])[0, 1])
+ self.assertLess(c, 0.9, v)
+
+ def test_a_seed_is_a_take(self):
+ a = rt.build_loop("office", 1)["loop"]
+ b = rt.build_loop("office", 1)["loop"]
+ c = rt.build_loop("office", 2)["loop"]
+ np.testing.assert_array_equal(a, b)
+ self.assertGreater(float(np.abs(a - c).mean()), 1e-3)
+
+ def test_the_movement_stays_a_few_db(self):
+ # 0.5 s short-term levels of a moving preset never swing like a gate.
+ x = self.loops["outdoor_day"]["loop"][0]
+ blk = x[: N // 24000 * 24000].reshape(-1, 24000)
+ db = 10 * np.log10((blk ** 2).mean(1))
+ self.assertLess(float(db.max() - db.min()), 12.0)
+
+
+class TheLoudnessMeter(unittest.TestCase):
+ def test_a_997_hz_sine_reads_as_bs1770_says(self):
+ # BS.1770: a 0 dBFS 997 Hz sine in ONE channel reads −3.01 LKFS.
+ t = np.arange(rt.SR * 4) / rt.SR
+ x = np.zeros((2, t.size))
+ x[0] = 10 ** (-20 / 20) * np.sin(2 * np.pi * 997 * t)
+ self.assertAlmostEqual(rt.loudness_lufs(x), -23.01, delta=0.1)
+
+ def test_silence_is_the_floor(self):
+ self.assertEqual(rt.loudness_lufs(np.zeros((2, 1000))), -120.0)
+
+ @unittest.skipUnless(FFMPEG, "ffmpeg not on PATH")
+ def test_ffmpeg_agrees_on_the_written_file(self):
+ with tempfile.TemporaryDirectory() as d:
+ for v in ("film_fallback", "kitchen", "car", "vhs_tape"):
+ r = (rt.build_loop("film", 1, clips=[]) if v == "film_fallback"
+ else rt.build_loop(v, 3))
+ f = Path(d) / f"{v}.wav"
+ rt.write_wav(f, rt.tile(r["loop"], 60))
+ # ffmpeg gates 400 ms blocks and prints one decimal; a moving
+ # preset reads a few tenths apart from the ungated figure.
+ self.assertAlmostEqual(_ebur128(f), r["ref_lufs"], delta=0.5, msg=v)
+
+
+class TheLevel(unittest.TestCase):
+ def test_the_fader_turns_the_reference_into_the_level(self):
+ self.assertAlmostEqual(rt.level_gain(-27), 10 ** (-9 / 20), places=5)
+ self.assertEqual(rt.level_gain(-18), 1.0)
+ self.assertEqual(rt.level_gain(-10), 1.0) # clamped, never a boost
+ self.assertAlmostEqual(rt.level_gain(-27, -21), 10 ** (-6 / 20), places=5)
+ self.assertEqual(rt.level_gain(-20, -23.5), 1.0) # as loud as it goes
+
+ def test_level_and_gain_are_inverses(self):
+ for lvl in (-45, -33.5, -27, -24, -18):
+ self.assertAlmostEqual(rt.gain_level(rt.level_gain(lvl)), lvl, places=2)
+
+ def test_junk_is_the_default(self):
+ for junk in (None, "", "abc", float("nan")):
+ self.assertEqual(rt.clamp_level(junk), rt.DEFAULT_LEVEL)
+ self.assertEqual(rt.clamp_level(-99), rt.LEVEL_MIN)
+
+ def test_the_default_is_clearly_audible(self):
+ # "not something really subtle": between −30 and −24 LUFS
+ self.assertTrue(-30 <= rt.DEFAULT_LEVEL <= -24)
+
+ def test_the_file_is_rounded_up_so_trims_never_regenerate(self):
+ self.assertEqual(rt.bed_seconds(0), 30)
+ self.assertEqual(rt.bed_seconds(29.4), 30)
+ self.assertEqual(rt.bed_seconds(29.6), 60)
+ self.assertEqual(rt.bed_seconds(101.4), 120)
+ self.assertEqual(rt.bed_seconds(10 ** 6), rt.BED_MAX_S)
+
+
+# =============================================================================
+# 2. FROM THIS FILM
+# =============================================================================
+def _scene(seed, n_s=6.0, noise_db=-45.0, line_db=-12.0, lp=1200.0):
+ """A clip: lowpassed noise at `noise_db` (the room) with 3 kHz "lines" on
+ top every other second (the dialogue)."""
+ rng = np.random.default_rng(seed)
+ n = int(n_s * rt.SR)
+ f = np.fft.rfftfreq(n, 1 / rt.SR)
+ mag = 1 / (1 + (f / lp) ** 4)
+ room = np.fft.irfft(mag * np.exp(1j * rng.uniform(0, 6.28, f.size)), n=n)
+ room *= 10 ** (noise_db / 20) / np.sqrt(np.mean(room ** 2))
+ t = np.arange(n) / rt.SR
+ gate = ((t % 2.0) > 1.0).astype(float)
+ line = 10 ** (line_db / 20) * np.sqrt(2) * np.sin(2 * np.pi * 3000 * t) * gate
+ return (room + line).astype(np.float32)
+
+
+def _band_db(x, lo, hi):
+ X = np.abs(np.fft.rfft(x)) ** 2
+ f = np.fft.rfftfreq(x.size, 1 / rt.SR)
+ return 10 * np.log10(X[(f >= lo) & (f < hi)].mean() + 1e-30)
+
+
+class FromThisFilm(unittest.TestCase):
+ def test_the_bed_is_the_room_not_the_lines(self):
+ clips = {f"/c{i}.mp4": _scene(i) for i in range(3)}
+ dec = lambda p, s, e: clips[p][int(s * rt.SR):int(e * rt.SR)] # noqa: E731
+ r = rt.build_loop("film", 1, clips=[{"path": p, "start": 0, "end": 6}
+ for p in clips], decoder=dec)
+ self.assertEqual(r["variant"], "film")
+ self.assertEqual(r["fallback"], "")
+ self.assertEqual(r["clips_used"], 3)
+ self.assertGreater(r["quiet_s"], rt.MIN_QUIET_S)
+ x = r["loop"][0].astype(np.float64)
+ # the room lives under 1.2 kHz; the 3 kHz line must not be in the bed
+ low = _band_db(x, 200, 1000)
+ tone = _band_db(x, 2950, 3050)
+ self.assertGreater(low - tone, 20.0)
+
+ def test_the_median_keeps_one_odd_clip_from_owning_the_film(self):
+ clips = {"/a": _scene(1, lp=800), "/b": _scene(2, lp=800),
+ "/odd": _scene(3, lp=12000)}
+ dec = lambda p, s, e: clips[p] # noqa: E731
+ shape = rt.film_shape([{"path": p, "start": 0, "end": 6} for p in clips], dec)
+ f = np.fft.rfftfreq(rt.WIN, 1 / rt.SR)
+ hi = shape["db"][(f > 6000) & (f < 9000)].mean()
+ lo = shape["db"][(f > 200) & (f < 600)].mean()
+ self.assertGreater(lo - hi, 30.0)
+
+ def test_digital_silence_and_no_sound_fall_back_and_say_so(self):
+ silent = lambda p, s, e: np.zeros(int((e - s) * rt.SR), np.float32) # noqa: E731
+ r = rt.build_loop("film", 1, clips=[{"path": "/s", "start": 0, "end": 5}],
+ decoder=silent)
+ self.assertEqual(r["variant"], rt.FALLBACK_VARIANT)
+ self.assertIn("no clip", r["fallback"])
+ r = rt.build_loop("film", 1, clips=[])
+ self.assertEqual(r["variant"], rt.FALLBACK_VARIANT)
+ self.assertTrue(r["fallback"])
+
+ def test_a_decoder_that_fails_is_a_clip_skipped(self):
+ def boom(p, s, e):
+ raise RuntimeError("unreadable")
+ self.assertIsNone(rt.film_shape([{"path": "/x", "start": 0, "end": 2}], boom)["db"])
+
+ @unittest.skipUnless(FFMPEG, "ffmpeg not on PATH")
+ def test_a_real_clip_through_ffmpeg(self):
+ with tempfile.TemporaryDirectory() as d:
+ wav = Path(d) / "clip.wav"
+ x = _scene(5, n_s=8.0)
+ rt.write_wav(wav, np.stack([x, x]))
+ mp4 = Path(d) / "clip.mp4"
+ subprocess.run([FFMPEG, "-y", "-v", "error", "-f", "lavfi", "-i",
+ "color=c=black:s=64x64:d=8", "-i", str(wav), "-shortest",
+ "-c:v", "libx264", "-c:a", "aac", str(mp4)], check=True)
+ got = rt.decode_window(mp4, 1.0, 5.0)
+ self.assertAlmostEqual(got.size / rt.SR, 4.0, delta=0.05)
+ r = rt.build_loop("film", 1, clips=[{"path": str(mp4), "start": 0, "end": 8}])
+ self.assertEqual(r["variant"], "film")
+
+
+class MakeBed(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.dir = Path(self.tmp.name)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def test_the_file_is_as_long_as_it_says_and_reused_on_the_same_pick(self):
+ a = rt.make_bed(self.dir, variant="kitchen", seed=2, film_len=31.2)
+ self.assertFalse(a["reused"])
+ self.assertEqual(a["duration"], 60.0)
+ import wave
+ with wave.open(a["path"]) as w:
+ self.assertEqual((w.getnchannels(), w.getframerate(), w.getnframes()),
+ (2, rt.SR, 60 * rt.SR))
+ b = rt.make_bed(self.dir, variant="kitchen", seed=2, film_len=40)
+ self.assertTrue(b["reused"])
+ self.assertEqual(b["path"], a["path"])
+ self.assertEqual(b["ref_lufs"], a["ref_lufs"])
+ c = rt.make_bed(self.dir, variant="kitchen", seed=3, film_len=40)
+ self.assertNotEqual(c["path"], a["path"])
+ d = rt.make_bed(self.dir, variant="kitchen", seed=2, film_len=70)
+ self.assertNotEqual(d["path"], a["path"])
+ self.assertTrue(Path(a["path"]).is_file())
+
+ def test_a_longer_bed_starts_with_the_same_sound(self):
+ a = rt.make_bed(self.dir, variant="office", seed=4, film_len=10)
+ b = rt.make_bed(self.dir, variant="office", seed=4, film_len=50)
+ import wave
+ with wave.open(a["path"]) as w1, wave.open(b["path"]) as w2:
+ self.assertEqual(w1.readframes(rt.SR * 30), w2.readframes(rt.SR * 30))
+
+ def test_an_unknown_variant_is_refused(self):
+ with self.assertRaises(ValueError):
+ rt.make_bed(self.dir, variant="nope", film_len=5)
+
+ def test_strict_refuses_a_CACHED_fallback_too(self):
+ """Ship review 2026-09-18 (Codex, confirmed): the cache hit returned
+ before the `strict` check, so a bed the MANUAL path was allowed to make
+ from a preset could be handed straight back to the AUTOMATIC cut, whose
+ whole policy is that a film of silent clips gets no hiss nobody asked
+ for. Same film, same seed, same length — one path wrote it, the other
+ must still refuse it."""
+ loose = rt.make_bed(self.dir, variant="film", film_len=5, clips=[])
+ self.assertTrue(Path(loose["path"]).is_file()) # the manual bed exists
+ self.assertTrue(loose["fallback"]) # ...as a preset stand-in
+ strict = rt.make_bed(self.dir, variant="film", film_len=5, clips=[], strict=True)
+ self.assertEqual(strict["path"], "")
+ self.assertTrue(strict["fallback"])
+ self.assertFalse(strict["reused"])
+ # ...and the file the manual path made is still there, untouched.
+ self.assertTrue(Path(loose["path"]).is_file())
+
+ def test_strict_writes_nothing_when_the_film_has_no_quiet(self):
+ f = rt.make_bed(self.dir, variant="film", film_len=5, clips=[], strict=True)
+ self.assertEqual(f["path"], "")
+ self.assertTrue(f["fallback"])
+ self.assertEqual(list(self.dir.glob("*.wav")), [])
+ g = rt.make_bed(self.dir, variant="film", film_len=5, clips=[])
+ self.assertEqual(g["used"], rt.FALLBACK_VARIANT)
+ self.assertEqual(g["label"], "Quiet room")
+ self.assertTrue(Path(g["path"]).is_file())
+
+
+# =============================================================================
+# 3. THE MODEL
+# =============================================================================
+def _doc(film_len=12.0, tracks=None):
+ doc = {"version": se.EDIT_VERSION, "board_id": "b", "audio": None,
+ "clips": [{"id": "c1", "path": "/x/a.mp4", "start": 0.0, "end": film_len,
+ "film_start": 0.0, "film_end": film_len, "source": "auto"}]}
+ if tracks is not None:
+ doc["audio_tracks"] = tracks
+ return doc
+
+
+FACTS = {"path": "/f/audio/room_tone/rt_film_1_ab_30s.wav", "duration": 30.0,
+ "ref_lufs": -18.0, "variant": "film", "label": "From this film", "seed": 1}
+
+
+class TheModel(unittest.TestCase):
+ def test_a_room_tone_track_is_a_legal_track(self):
+ t = se.room_tone_new_track(FACTS, 12.0, level=-27)
+ self.assertEqual(t["name"], se.ROOM_TONE_NAME)
+ self.assertEqual(t["room_tone"], {"variant": "film", "seed": 1, "level": -27.0,
+ "ref_lufs": -18.0})
+ self.assertAlmostEqual(t["gain"], rt.level_gain(-27), places=6)
+ s = t["strips"][0]
+ self.assertEqual((s["start"], s["end"], s["film_start"], s["duration"]),
+ (0.0, 12.0, 0.0, 30.0))
+ self.assertTrue(s["locked"])
+ doc = _doc(tracks=[t])
+ self.assertEqual(se.blocking_errors(se.validate_edit(doc)), [])
+ norm = se.normalise_edit(doc)
+ self.assertEqual(norm["audio_tracks"][0]["room_tone"], t["room_tone"])
+ self.assertEqual(se.room_tone_track(norm)[0], 0)
+
+ def test_the_strip_never_runs_past_its_file(self):
+ t = se.room_tone_new_track(FACTS, 45.0)
+ self.assertEqual(t["strips"][0]["end"], 30.0)
+
+ def test_a_bed_at_its_reference_level_has_no_fader(self):
+ t = se.room_tone_new_track(FACTS, 12.0, level=-18)
+ self.assertNotIn("gain", t)
+
+ def test_the_render_mixes_it_at_the_fader(self):
+ doc = _doc(tracks=[se.room_tone_new_track(FACTS, 12.0, level=-30)])
+ rows = se.track_render_strips(doc)
+ self.assertEqual(len(rows), 1)
+ self.assertEqual((rows[0]["at"], rows[0]["len"]), (0.0, 12.0))
+ g = rt.level_gain(-30)
+ self.assertEqual(rows[0]["gain"], [[0.0, g], [12.0, g]])
+
+ def test_a_junk_tag_is_refused_or_dropped(self):
+ bad = dict(se.room_tone_new_track(FACTS, 12.0), room_tone="loud")
+ codes = [e["code"] for e in se.validate_edit(_doc(tracks=[bad]))]
+ self.assertIn("audio_track_room_tone", codes)
+ worse = dict(se.room_tone_new_track(FACTS, 12.0))
+ worse["room_tone"] = {"variant": "film", "level": "x"}
+ codes = [e["code"] for e in se.validate_edit(_doc(tracks=[worse]))]
+ self.assertIn("audio_track_room_tone", codes)
+ norm = se.normalise_edit(_doc(tracks=[dict(bad)]))
+ self.assertNotIn("room_tone", norm["audio_tracks"][0])
+ self.assertIsNone(se.room_tone_track(norm))
+
+ def test_an_ordinary_track_is_not_room_tone(self):
+ doc = _doc(tracks=[{"id": "t1", "strips": []}])
+ self.assertIsNone(se.room_tone_track(doc))
+ self.assertIsNone(se.room_tone_meta({"id": "t"}))
+
+ def test_the_bed_follows_the_film(self):
+ doc = _doc(8.0, tracks=[se.room_tone_new_track(FACTS, 12.0)])
+ self.assertTrue(se.room_tone_fit(doc))
+ self.assertEqual(doc["audio_tracks"][0]["strips"][0]["end"], 8.0)
+ self.assertFalse(se.room_tone_fit(doc))
+ doc["clips"][0]["end"] = doc["clips"][0]["film_end"] = 40.0
+ self.assertTrue(se.room_tone_fit(doc))
+ self.assertEqual(doc["audio_tracks"][0]["strips"][0]["end"], 30.0) # the file
+
+ def test_a_bed_cut_by_hand_is_left_alone(self):
+ t = se.room_tone_new_track(FACTS, 12.0)
+ s2 = dict(t["strips"][0], id="s2", start=6.0, end=12.0, film_start=6.0)
+ t["strips"][0]["end"] = 5.0
+ t["strips"].append(s2)
+ doc = _doc(8.0, tracks=[t])
+ self.assertFalse(se.room_tone_fit(doc))
+ moved = se.room_tone_new_track(FACTS, 12.0)
+ moved["strips"][0]["film_start"] = 1.0
+ self.assertFalse(se.room_tone_fit(_doc(8.0, tracks=[moved])))
+
+
+# =============================================================================
+# 4. THE RENDER — the de-click, and the bed in a real mix
+# =============================================================================
+class TheDeclick(unittest.TestCase):
+ def graph(self, **kw):
+ probes = [("/a.mp4", {"width": 640, "height": 360, "duration": 3.0,
+ "has_audio": True}),
+ ("/b.mp4", {"width": 640, "height": 360, "duration": 2.0,
+ "has_audio": True})]
+ return panel._sb_film_filtergraph(probes, 640, 360, 48000, "yuv420p", **kw)[0]
+
+ def test_off_by_default_so_every_other_caller_builds_the_old_graph(self):
+ self.assertNotIn("afade", self.graph())
+ self.assertEqual(self.graph(), self.graph(declick=0.0))
+
+ def test_on_every_clip_sound_gets_a_head_and_a_tail(self):
+ g = self.graph(declick=0.012)
+ self.assertEqual(g.count("afade=t=in:d=0.012"), 2)
+ self.assertIn("afade=t=out:st=2.988000:d=0.012", g)
+ self.assertIn("afade=t=out:st=1.988000:d=0.012", g)
+
+ def test_a_sound_too_short_for_two_fades_is_left_alone(self):
+ self.assertEqual(panel._sb_declick_term(0.012, 0.04), "")
+ self.assertEqual(panel._sb_declick_term(0.0, 5.0), "")
+
+ def test_the_split_lanes_get_it_too(self):
+ segs = [{"input": 0, "kind": "video", "info": {"has_audio": True, "duration": 3.0},
+ "window": {"start": 0.0, "end": 3.0},
+ "audio": {"start": 0.0, "end": 3.0, "film_start": 0.0}},
+ {"input": 1, "kind": "video", "info": {"has_audio": True, "duration": 3.0},
+ "window": {"start": 0.0, "end": 2.0}, "lane": 2}]
+ probes = [("/a.mp4", segs[0]["info"]), ("/b.mp4", segs[1]["info"])]
+ try:
+ g = panel._sb_film_filtergraph(probes, 640, 360, 48000, "yuv420p",
+ segments=segs, declick=0.012)[0]
+ except Exception as exc: # noqa: BLE001
+ self.skipTest(f"segment shape drifted: {exc}")
+ self.assertGreaterEqual(g.count("afade=t=in:d=0.012"), 2)
+
+ def test_the_timeline_render_asks_for_it(self):
+ seen = {}
+
+ def fake(*a, **kw):
+ seen.update(kw)
+ return {"ok": True, "path": "/x.mp4"}
+ board = {"id": "b", "title": "T", "created_at": 1_700_000_000}
+ doc = _doc(3.0)
+ with mock.patch.object(panel, "_sb_assemble_film", fake), \
+ mock.patch.object(panel, "push", lambda *a, **k: None):
+ panel._sbe_render_edit(board, doc)
+ self.assertEqual(seen.get("declick"), panel.SB_DECLICK_S)
+ self.assertTrue(0.010 <= panel.SB_DECLICK_S <= 0.020)
+
+
[email protected](FFMPEG, "ffmpeg not on PATH")
+class ARealMix(unittest.TestCase):
+ """Two clips — loud room, then digital silence — rendered by the real
+ assembler, with and without the bed: the silence after the cut is filled."""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.tmp = tempfile.TemporaryDirectory()
+ d = Path(cls.tmp.name)
+ run = lambda *a: subprocess.run([FFMPEG, "-y", "-v", "error", *a], check=True) # noqa: E731
+ cls.a, cls.b = d / "a.mp4", d / "b.mp4"
+ run("-f", "lavfi", "-i", "color=c=gray:s=160x90:d=3:r=24", "-f", "lavfi", "-i",
+ "anoisesrc=d=3:c=pink:a=0.05:r=48000", "-shortest", "-c:v", "libx264",
+ "-c:a", "aac", str(cls.a))
+ run("-f", "lavfi", "-i", "color=c=gray:s=160x90:d=3:r=24", "-f", "lavfi", "-i",
+ "anullsrc=r=48000:cl=stereo", "-t", "3", "-c:v", "libx264", "-c:a", "aac",
+ str(cls.b))
+ bed = rt.make_bed(d / "rt", variant="quiet_room", seed=1, film_len=6)
+ cls.board = {"id": "sb_rt_mix", "title": "Room tone mix", "created_at": 1_700_000_000}
+ clips = [{"id": "c1", "path": str(cls.a), "start": 0.0, "end": 3.0,
+ "film_start": 0.0, "film_end": 3.0, "source": "auto"},
+ {"id": "c2", "path": str(cls.b), "start": 0.0, "end": 3.0,
+ "film_start": 3.0, "film_end": 6.0, "source": "auto"}]
+ base = {"version": se.EDIT_VERSION, "board_id": "sb_rt_mix", "audio": None,
+ "clips": clips}
+ with_bed = dict(base, audio_tracks=[se.room_tone_new_track(bed, 6.0, level=-27)])
+ cls.out = {}
+ with mock.patch.object(panel, "OUTPUT", d / "out"), \
+ mock.patch.object(panel, "push", lambda *a, **k: None):
+ for name, doc in (("dry", base), ("bed", with_bed)):
+ film = panel._sbe_render_edit(cls.board, doc, out_name=f"{name}.mp4")
+ assert film.get("ok"), film
+ cls.out[name] = film["path"]
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.tmp.cleanup()
+
+ def level(self, path, start, dur):
+ r = subprocess.run([FFMPEG, "-v", "error", "-ss", str(start), "-t", str(dur),
+ "-i", str(path), "-map", "0:a:0", "-ac", "1", "-f", "f32le", "-"],
+ capture_output=True, check=True)
+ x = np.frombuffer(r.stdout, "<f4").astype(np.float64)
+ return 20 * math.log10(math.sqrt(float(np.mean(x * x))) + 1e-9)
+
+ def test_the_cut_no_longer_drops_to_silence(self):
+ self.assertLess(self.level(self.out["dry"], 3.5, 2.0), -70)
+ self.assertGreater(self.level(self.out["bed"], 3.5, 2.0), -40)
+
+ def test_the_bed_plays_at_its_level(self):
+ f = Path(self.out["bed"]).with_name("tail.wav")
+ subprocess.run([FFMPEG, "-y", "-v", "error", "-ss", "3.3", "-i", str(self.out["bed"]),
+ "-map", "0:a:0", str(f)], check=True)
+ self.assertAlmostEqual(_ebur128(f), -27.0, delta=1.0)
+
+
+# =============================================================================
+# 5. THE PANEL — automatic cuts, the setting, the route
+# =============================================================================
+class AutomaticCuts(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.board = {"id": "sb_rt_auto", "title": "Auto", "created_at": 1_700_000_000}
+ self.edit = _doc(12.0)
+ self.facts = dict(FACTS, ok=True)
+ self.calls = []
+
+ def fake(board, **kw):
+ self.calls.append(kw)
+ return dict(self.facts)
+ self.patches = [mock.patch.object(panel, "_sbe_room_tone", fake),
+ mock.patch.object(panel, "push", lambda *a, **k: None)]
+ for p in self.patches:
+ p.start()
+
+ def tearDown(self):
+ for p in reversed(self.patches):
+ p.stop()
+ self.tmp.cleanup()
+
+ def settings(self, on):
+ return mock.patch.object(panel, "get_settings", lambda: {"room_tone_auto": on})
+
+ def test_on_by_default_it_lays_a_bed_made_from_the_film(self):
+ with self.settings(True):
+ panel._sbe_room_tone_auto(self.board, self.edit, se)
+ found = se.room_tone_track(self.edit)
+ self.assertIsNotNone(found)
+ self.assertEqual(self.calls[0]["variant"], "film")
+ self.assertTrue(self.calls[0]["strict"])
+ self.assertEqual(self.calls[0]["clips"][0]["path"], "/x/a.mp4")
+ self.assertEqual(found[1]["room_tone"]["level"], rt.DEFAULT_LEVEL)
+ self.assertEqual(se.blocking_errors(se.validate_edit(self.edit)), [])
+ self.assertTrue(panel._settings_defaults()["room_tone_auto"])
+
+ def test_off_means_off(self):
+ with self.settings(False):
+ panel._sbe_room_tone_auto(self.board, self.edit, se)
+ self.assertIsNone(se.room_tone_track(self.edit))
+ self.assertEqual(self.calls, [])
+
+ def test_a_music_video_is_left_alone(self):
+ self.edit["audio"] = {"path": "/song.wav"}
+ with self.settings(True):
+ panel._sbe_room_tone_auto(self.board, self.edit, se)
+ self.assertIsNone(se.room_tone_track(self.edit))
+ self.edit["audio"]["mode"] = "under"
+ with self.settings(True):
+ panel._sbe_room_tone_auto(self.board, self.edit, se)
+ self.assertIsNotNone(se.room_tone_track(self.edit))
+
+ def test_no_quiet_no_bed_and_a_failure_is_not_a_failed_cut(self):
+ self.facts = {"ok": False, "error": "no room tone from this film"}
+ with self.settings(True):
+ panel._sbe_room_tone_auto(self.board, self.edit, se)
+ self.assertIsNone(se.room_tone_track(self.edit))
+
+ def boom(board, **kw):
+ raise RuntimeError("disk full")
+ with self.settings(True), mock.patch.object(panel, "_sbe_room_tone", boom):
+ panel._sbe_room_tone_auto(self.board, self.edit, se)
+ self.assertIsNone(se.room_tone_track(self.edit))
+
+ def test_a_film_that_has_one_keeps_it(self):
+ self.edit["audio_tracks"] = [se.room_tone_new_track(FACTS, 12.0, level=-33)]
+ with self.settings(True):
+ panel._sbe_room_tone_auto(self.board, self.edit, se)
+ self.assertEqual(len(self.edit["audio_tracks"]), 1)
+ self.assertEqual(self.calls, [])
+
+ def test_the_auto_editor_calls_it(self):
+ src = Path(panel.__file__).read_text(encoding="utf-8")
+ body = src[src.index("def _sbe_auto_edit("):src.index("def _sbe_relinks(")]
+ self.assertIn("_sbe_room_tone_auto(board, edit, sedit)", body)
+
+
+class TheSetting(unittest.TestCase):
+ def test_the_patch_is_validated_and_public(self):
+ for raw, want in (("1", True), ("0", False), (True, True), ("off", False)):
+ out, err = panel._validate_settings_patch({"room_tone_auto": raw}) \
+ if hasattr(panel, "_validate_settings_patch") else (None, None)
+ if out is None:
+ self.skipTest("settings validator renamed")
+ self.assertIsNone(err)
+ self.assertEqual(out["room_tone_auto"], want)
+ with mock.patch.object(panel, "get_settings", lambda: {"room_tone_auto": False}):
+ self.assertFalse(panel.get_settings_public()["room_tone_auto"])
+
+
+class TheRoute(unittest.TestCase):
+ class H:
+ def __init__(self, body=""):
+ 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)
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ root = Path(self.tmp.name)
+ self.patches = [mock.patch.object(panel, "STATE_DIR", root / "state"),
+ mock.patch.object(panel, "OUTPUT", root / "out"),
+ mock.patch.object(panel, "push", lambda *a, **k: None)]
+ for p in self.patches:
+ p.start()
+ (root / "state").mkdir()
+ board = {"schema": 1, "id": "sb_rt_route", "title": "Route", "created_at": 1_700_000_000,
+ "policy": panel.storyboard.default_policy(), "cast": [],
+ "engine_mode": "ltx", "shots": []}
+ panel.storyboard.save_storyboard(root / "state", board)
+ self.root = root
+
+ def tearDown(self):
+ for p in reversed(self.patches):
+ p.stop()
+ self.tmp.cleanup()
+
+ def post(self, **form):
+ from urllib.parse import urlencode
+ h = self.H(urlencode(form))
+ POST_ROUTES["/storyboard/edit/room-tone"](h, "/storyboard/edit/room-tone", {}, "")
+ return h.out
+
+ def test_both_routes_are_registered(self):
+ self.assertIn("/storyboard/edit/room-tone", GET_ROUTES)
+ self.assertIn("/storyboard/edit/room-tone", POST_ROUTES)
+
+ def test_the_picker_rows_and_the_numbers(self):
+ h = self.H()
+ GET_ROUTES["/storyboard/edit/room-tone"](h, None)
+ code, body = h.out
+ self.assertEqual(code, 200)
+ self.assertEqual([v["id"] for v in body["variants"]], rt.variant_ids())
+ self.assertEqual((body["default_level"], body["level_min"], body["level_max"],
+ body["ref_lufs"]),
+ (rt.DEFAULT_LEVEL, rt.LEVEL_MIN, rt.LEVEL_MAX, rt.REF_LUFS))
+ self.assertIn("auto", body)
+
+ def test_a_preset_bed_lands_in_the_films_audio_folder(self):
+ code, body = self.post(id="sb_rt_route", variant="tv_studio", seed="3",
+ film_len="12.5", clips="[]")
+ self.assertEqual(code, 200, body)
+ p = Path(body["path"])
+ self.assertTrue(p.is_file())
+ self.assertEqual(p.parent.name, "room_tone")
+ self.assertEqual(p.parent.parent.name, "audio")
+ self.assertTrue(p.is_relative_to(self.root / "out"))
+ self.assertEqual((body["duration"], body["seed"], body["label"]), (30.0, 3, "TV studio"))
+ # the Sound pool does not list the takes
+ board = panel.storyboard.load_storyboard(panel.STATE_DIR, "sb_rt_route")
+ self.assertEqual(panel._sbe_list_sounds(board), [])
+
+ def test_a_film_bed_with_nothing_to_hear_falls_back_openly(self):
+ code, body = self.post(id="sb_rt_route", variant="film", seed="1", film_len="5",
+ clips=json.dumps([{"path": "/no/such.mp4", "start": 0, "end": 5}]))
+ self.assertEqual(code, 200, body)
+ self.assertEqual(body["used"], rt.FALLBACK_VARIANT)
+ self.assertTrue(body["fallback"])
+
+ def test_bad_requests_are_refused(self):
+ self.assertEqual(self.post(id="nope", variant="film")[0], 404)
+ self.assertEqual(self.post(id="sb_rt_route", variant="loud")[0], 400)
+ self.assertEqual(self.post(id="sb_rt_route", variant="film", clips="{")[0], 400)
+ self.assertEqual(self.post(id="sb_rt_route", variant="film", seed="x")[0], 400)
+
+
+# =============================================================================
+# 6. THE CLIENT — the panel's real JavaScript, run in node
+# =============================================================================
+RT_FUNCTIONS = (
+ "sbeNum", "sbeRound", "sbeTsCopy", "sbeTrackLabel", "sbeKind",
+ "sbeFilmDuration", "sbeRtClampLevel", "sbeRtGain", "sbeRtBedSeconds",
+ "sbeRtFind", "sbeRtLevelOf", "sbeRtNewTrack", "sbeRtPlace", "sbeRtRemove",
+ "sbeRtSetLevel", "sbeRtFit", "sbeRtClips", "sbeRtFmtLevel",
+)
+
+
+def run_client(body: str) -> dict:
+ if NODE is None:
+ raise unittest.SkipTest("node not on PATH")
+ src = panel_source()
+ consts = "\n".join(m + ";" for m in re.findall(
+ r"^const (?:SBE_RT_\w+|SBE_TRACK_STRIP_MIN) = [^;]+", src, re.MULTILINE))
+ script = (SHIM + consts + "\n"
+ + "let __id = 0; function sbeNewId() { __id += 1; return 'k' + String(__id).padStart(12, '0'); }\n"
+ + "\n".join(extract_function(n, src) for n in RT_FUNCTIONS)
+ + "\nconst out = {};\n" + body
+ + "\nprocess.stdout.write(JSON.stringify(out));\n")
+ with tempfile.TemporaryDirectory() as d:
+ f = Path(d) / "harness.js"
+ f.write_text(script, encoding="utf-8")
+ r = subprocess.run([NODE, str(f)], capture_output=True, text=True, timeout=60)
+ if r.returncode != 0:
+ raise AssertionError("node harness failed:\n" + r.stderr[-3000:])
+ return json.loads(r.stdout)
+
+
[email protected](NODE, "node not on PATH")
+class TheClientMirror(unittest.TestCase):
+ def test_the_constants_are_the_generators(self):
+ src = panel_source()
+ for js, py in (("SBE_RT_DEFAULT_LEVEL", rt.DEFAULT_LEVEL),
+ ("SBE_RT_LEVEL_MIN", rt.LEVEL_MIN), ("SBE_RT_LEVEL_MAX", rt.LEVEL_MAX),
+ ("SBE_RT_REF", rt.REF_LUFS), ("SBE_RT_STEP", rt.BED_STEP_S),
+ ("SBE_RT_MAX", rt.BED_MAX_S)):
+ m = re.search(rf"^const {js} = (-?[\d.]+);", src, re.MULTILINE)
+ self.assertIsNotNone(m, js)
+ self.assertEqual(float(m.group(1)), float(py), js)
+ self.assertIn(f"const SBE_RT_NAME = '{se.ROOM_TONE_NAME}';", src)
+
+ def test_gain_and_file_length_agree_with_the_server(self):
+ levels = [-45, -40.5, -33, -27, -24, -18, -10, "", None, "x"]
+ refs = [-18, -21.3, None]
+ lens = [0, 12, 29.4, 29.6, 101.399, 5000]
+ out = run_client(f"out.g = {json.dumps(levels)}.map(l => {json.dumps(refs)}.map(r => sbeRtGain(l, r)));"
+ f"out.s = {json.dumps(lens)}.map(sbeRtBedSeconds);"
+ f"out.f = sbeRtFmtLevel(-27);")
+ for i, lvl in enumerate(levels):
+ for j, ref in enumerate(refs):
+ want = rt.level_gain(lvl, rt.REF_LUFS if ref is None else ref)
+ self.assertAlmostEqual(out["g"][i][j], want, places=5, msg=(lvl, ref))
+ self.assertEqual(out["s"], [rt.bed_seconds(n) for n in lens])
+ self.assertEqual(out["f"], "−27 LUFS")
+
+ def test_the_new_track_is_the_servers_track(self):
+ out = run_client(f"out.t = sbeRtNewTrack({json.dumps(FACTS)}, 12, -30, 'tA');"
+ f"out.long = sbeRtNewTrack({json.dumps(FACTS)}, 45, -18, '');")
+ want = se.room_tone_new_track(FACTS, 12.0, level=-30, track_id="tA")
+ t = out["t"]
+ self.assertEqual(t["id"], "tA")
+ self.assertEqual(t["room_tone"], want["room_tone"])
+ self.assertAlmostEqual(t["gain"], want["gain"], places=6)
+ for k in ("path", "start", "end", "film_start", "duration", "title", "locked"):
+ self.assertEqual(t["strips"][0][k], want["strips"][0][k], k)
+ self.assertEqual(out["long"]["strips"][0]["end"], 30)
+ self.assertNotIn("gain", out["long"])
+ doc = _doc(12.0, tracks=[t, out["long"]])
+ self.assertEqual(se.blocking_errors(se.validate_edit(doc)), [])
+
+ def test_place_replaces_in_the_same_lane_and_keeps_the_mute(self):
+ out = run_client(f"""
+const other = {{ id: 'o', name: 'Laughs', strips: [] }};
+const a = sbeRtNewTrack({json.dumps(FACTS)}, 12, -27, '');
+const first = sbeRtPlace([other], a).tracks;
+first[1].muted = true;
+const b = sbeRtNewTrack(Object.assign({{}}, {json.dumps(FACTS)}, {{ variant: 'office', seed: 2 }}), 12, -27, '');
+out.second = sbeRtPlace(first, b);
+out.first = first;
+out.removed = sbeRtRemove(out.second.tracks);
+out.none = sbeRtRemove([other]);
+out.level = sbeRtSetLevel(first, -18).tracks;
+out.level2 = sbeRtSetLevel(first, -36).tracks;
+""")
+ tr = out["second"]["tracks"]
+ self.assertEqual([t["id"] for t in tr], ["o", out["first"][1]["id"]])
+ self.assertEqual(tr[1]["room_tone"]["variant"], "office")
+ self.assertTrue(tr[1]["muted"])
+ # a LOCKED bed is still removed by its own Remove
+ self.assertEqual([t["id"] for t in out["removed"]["tracks"]], ["o"])
+ self.assertFalse(out["none"]["ok"])
+ self.assertNotIn("gain", out["level"][1])
+ self.assertEqual(out["level"][1]["room_tone"]["level"], -18)
+ self.assertAlmostEqual(out["level2"][1]["gain"], rt.level_gain(-36), places=6)
+
+ def test_fit_is_the_servers_fit(self):
+ cases = [(8.0, None), (40.0, None), (12.0, None), (0.0, None),
+ (8.0, "split"), (8.0, "moved")]
+ rows = []
+ for film_len, shape in cases:
+ t = se.room_tone_new_track(FACTS, 12.0)
+ if shape == "split":
+ t["strips"].append(dict(t["strips"][0], id="s2", film_start=12.0))
+ if shape == "moved":
+ t["strips"][0]["film_start"] = 1.0
+ rows.append((film_len, [t]))
+ out = run_client(f"out.r = {json.dumps(rows)}.map(([n, ts]) => sbeRtFit(ts, n));")
+ for (film_len, tracks), got in zip(rows, out["r"]):
+ doc = _doc(film_len, tracks=json.loads(json.dumps(tracks)))
+ if film_len == 0.0:
+ doc["clips"] = []
+ changed = se.room_tone_fit(doc)
+ self.assertEqual(got["changed"], changed, (film_len, got))
+ self.assertEqual(got["tracks"][0]["strips"][0]["end"],
+ doc["audio_tracks"][0]["strips"][0]["end"])
+ self.assertTrue(out["r"][1]["short"]) # 40 s film, 30 s file
+ self.assertFalse(out["r"][0]["short"])
+
+ def test_the_bed_listens_to_the_picture_clips_only(self):
+ out = run_client("out.c = sbeRtClips([{path: '/a.mp4', start: 1, end: 3},"
+ "{kind: 'slug', start: 0, end: 2}, {path: '/p.png', start: 0, end: 2},"
+ "{path: '/b.mov', start: 0.5, end: 4, kind: 'video'}]);")
+ self.assertEqual(out["c"], [{"path": "/a.mp4", "start": 1, "end": 3},
+ {"path": "/b.mov", "start": 0.5, "end": 4}])
+
+
+class TheCard(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")
+ cls.js = panel_source()
+ cls.css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")
+ cls.docs = (ROOT / "webapp" / "docs" / "editor.md").read_text(encoding="utf-8")
+
+ def test_the_card_has_its_controls(self):
+ card = self.html[self.html.index('id="edRoomTone"'):]
+ card = card[:card.index("</section>")]
+ for needle in ('id="edRtVariant"', 'id="edRtLevel"', 'min="-45"', 'max="-18"',
+ 'value="-27"', "edRtApply('apply')", "edRtApply('take')",
+ 'edRtRemove()', 'edRtAuto(this.checked)', 'Add room tone',
+ 'New take', 'Remove', 'Add room tone to automatic cuts'):
+ self.assertIn(needle, card, needle)
+ self.assertIn('id="edRoomTone" hidden ', self.html)
+
+ def test_no_element_id_shadows_a_function(self):
+ for fn in re.findall(r"^(?:async )?function (edRt\w+|sbeRt\w+)\(", self.js, re.MULTILINE):
+ self.assertNotIn(f'id="{fn}"', self.html, fn)
+
+ def test_the_sound_menu_is_a_second_door(self):
+ menu = self.html[self.html.index('id="sbeSoundMenu"'):]
+ menu = menu[:menu.index("</div>")]
+ self.assertIn("edRtOpen()", menu)
+ self.assertIn("Room tone…", menu)
+
+ def test_it_is_painted_and_followed(self):
+ paint = extract_function("sbePaint", self.js)
+ self.assertIn("sbeRtFollow();", paint)
+ self.assertLess(paint.index("sbeRtFollow();"), paint.index("sbePaintTracks();"))
+ self.assertIn("edRtPaint()", paint)
+ self.assertIn("SBE.rtLen = sbeFilmDuration(SBE.clips);", self.js)
+ self.assertIn("edRtLoad().then(edRtPaint)", extract_function("edPoolRefresh", self.js))
+ src = extract_function("edPoolSrc", self.js)
+ self.assertIn(".ed-pool-make", src)
+
+ def test_the_level_slider_is_one_undo_step(self):
+ commit = extract_function("edRtLevelCommit", self.js)
+ self.assertIn("sbeTsCommit(before)", commit)
+ self.assertIn("sbeSnapshot()", extract_function("edRtLevelSlide", self.js))
+
+ def test_a_grown_film_gets_a_longer_bed_in_the_background(self):
+ follow = extract_function("sbeRtFollow", self.js)
+ self.assertIn("setTimeout(sbeRtGrow", follow)
+ grow = extract_function("sbeRtGrow", self.js)
+ self.assertIn("sbeRtRequest(rt.variant, rt.seed, len)", grow)
+ self.assertNotIn("SBE.undo.push", grow)
+
+ def test_the_card_is_styled_on_the_tokens(self):
+ for sel in (".ed-rt {", ".ed-rt-head", ".ed-rt-level", ".ed-rt-acts",
+ ".ed-rt[hidden]", ".ed-pool-make[hidden]"):
+ self.assertIn(sel, self.css, sel)
+
+ def test_the_docs_say_it_in_the_users_words(self):
+ low = self.docs.lower()
+ for word in ("room tone", "background noise", "ambience", "new take",
+ "automatic cuts", "lufs", "click"):
+ self.assertIn(word, low, word)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_state_sandbox.py b/test_state_sandbox.py
new file mode 100644
index 0000000..411e6f2
--- /dev/null
+++ b/test_state_sandbox.py
@@ -0,0 +1,38 @@
+"""The suite must run in a sandbox, not in the owner's install.
+
+See `conftest.py`. This is the gate: if the panel's state, outputs or uploads
+ever resolve back to the checkout, a test can overwrite real settings, real
+renders and real uploads — which is exactly what happened on 2026-09-18.
+"""
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import conftest
+import mlx_ltx_panel as P
+
+
+def test_state_outputs_and_uploads_live_in_the_sandbox():
+ for name, path in (("STATE_DIR", P.STATE_DIR), ("OUTPUT", P.OUTPUT),
+ ("UPLOADS", P.UPLOADS)):
+ assert str(path).startswith(str(conftest.SANDBOX)), \
+ f"{name} is {path} — a test would write the real install"
+
+
+def test_the_settings_file_is_not_the_installs_own():
+ real = Path(P.__file__).resolve().parent / "state" / "panel_settings.json"
+ assert P.SETTINGS_FILE.resolve() != real.resolve()
+
+
+def test_a_write_to_a_real_installs_settings_is_refused():
+ """The belt to the sandbox's braces: even with a bad STATE_DIR, a test
+ process may not persist settings into somebody's install."""
+ assert os.environ.get("PYTEST_CURRENT_TEST")
+ real = Path(P.__file__).resolve().parent / "state" / "panel_settings.json"
+ try:
+ P._save_settings({"hijacked": True}, _target=real)
+ except RuntimeError as exc:
+ assert "test" in str(exc).lower()
+ else: # pragma: no cover
+ raise AssertionError("a test just wrote the real panel_settings.json")
diff --git a/test_storyboard_editor_ui.py b/test_storyboard_editor_ui.py
index c8c297d..94779fa 100644
--- a/test_storyboard_editor_ui.py
+++ b/test_storyboard_editor_ui.py
@@ -101,6 +101,7 @@ FUNCTIONS = (
# that is ON SCREEN, which is what lets the handle push a timeline with
# small sound lanes 114px lower than one with tall ones.
"sbeLaneBase", "sbeLaneCap", "sbeTlFloor", "sbeTlRoof", "sbeAudioSmall",
+ "sbeSoundMode", "sbeTlPrefKey",
# The level line's geometry, which three gestures now share instead of
# each carrying a copy of a 20px band.
"sbeStripY", "sbeStripGain", "sbeStripEditable", "sbeKeysLegend",
@@ -351,6 +352,10 @@ const SBE = {
// The timeline's height: the preference, what the window could give it, and
// the ceiling the monitors impose.
tlH: SBE_TL_MIN_H, tlNow: SBE_TL_MIN_H, tlMax: SBE_TL_MAX_H, tlDrag: null,
+ // SOUND MODE, so every lane is at its full height: the numbers below were
+ // written for the full lane set (floor 280, roof 638). Picture mode — the
+ // thin lanes — is probed where it is named (tlPref, test_audio_compact).
+ mode: 'sound',
};
// One fetch stub, scripted per case.
let FETCHES = [];
@@ -2038,8 +2043,9 @@ out.rulerFixed = [out.lanesAtFloor.ruler, out.lanesAtCeiling.ruler];
out.tlPref = (() => {
const seen = {};
STORE.clear();
+ SBE.mode = 'picture'; // the default on a real screen
seen.fresh = sbeTlPrefRead(); // nothing stored yet
- sbeTlPrefWrite(392);
+ sbeTlPrefWrite(200);
seen.stored = STORE.get('phos_sbe_tl_h');
seen.restored = sbeTlPrefRead(); // ...as a new tab would read it
STORE.set('phos_sbe_tl_h', '99999');
@@ -2047,7 +2053,18 @@ out.tlPref = (() => {
STORE.set('phos_sbe_tl_h', 'not-a-height');
seen.junk = sbeTlPrefRead();
seen.keys = [...STORE.keys()];
+ sbeTlPrefWrite(200); // a real number again, over the junk
+ // SOUND MODE HAS ITS OWN KEY AND ITS OWN ENDS: fresh is the roof of the
+ // full lanes, and what it stores never touches picture mode's number.
+ SBE.mode = 'sound';
+ seen.soundFresh = sbeTlPrefRead();
+ sbeTlPrefWrite(400);
+ seen.soundKeys = [...STORE.keys()].sort();
+ seen.soundRestored = sbeTlPrefRead();
+ SBE.mode = 'picture';
+ seen.pictureAfter = sbeTlPrefRead();
STORE.clear();
+ SBE.mode = 'sound'; // back to the harness's default
return seen;
})();
// AND IT IS NOT IN THE DOCUMENT. The save payload is the whole of what the
@@ -4284,7 +4301,14 @@ class OneNoticeSurface(unittest.TestCase):
# worked on. It is an invitation to go and look.
got = self.r["noticeQuietIsAlwaysAChip"]
self.assertEqual(got["folded"], ["sbeRecover"])
- self.assertFalse(got["wrapHidden"])
+ # ...and ALONE it is a chip in the HEADER (#sbeRecoverChip), not a row
+ # of its own under it: the row is hidden until the chip is clicked.
+ self.assertTrue(got["wrapHidden"])
+ self.assertIn('id="sbeRecoverChip"', self.src)
+ self.assertIn("onclick=\"sbeNoticeOpen('sbeRecover')\"", self.src)
+ paint = extract_function("sbePaintNotices", self.src)
+ self.assertIn("open[0] === 'sbeRecover'", paint)
+ self.assertIn("if (chipOnly) wrap.hidden = true;", paint)
self.assertIn('data-quiet="1"', self.src)
# ...and it points at the place versions live rather than acting.
el = self.src[self.src.index('id="sbeRecover"'):]
@@ -5218,12 +5242,18 @@ class TheTimelineIsResizable(unittest.TestCase):
# ---- where the preference lives -------------------------------------
def test_the_height_survives_a_reload_and_is_clamped_on_the_way_back(self):
p = self.r["tlPref"]
- self.assertEqual(p["fresh"], 280) # nothing stored → the floor
- self.assertEqual(p["stored"], "392")
- self.assertEqual(p["restored"], 392) # what the next tab reads
- self.assertEqual(p["absurd"], 638) # a stored screenful is capped
- self.assertEqual(p["junk"], 280) # ...and junk is the floor
+ # PICTURE MODE (the default): the thin lanes' own ends — floor 166,
+ # roof 246 — not the full-height 280 / 638, which are sound mode's.
+ self.assertEqual(p["fresh"], 166) # nothing stored → the floor
+ self.assertEqual(p["stored"], "200")
+ self.assertEqual(p["restored"], 200) # what the next tab reads
+ self.assertEqual(p["absurd"], 246) # a stored screenful is capped
+ self.assertEqual(p["junk"], 166) # ...and junk is the floor
self.assertEqual(p["keys"], ["phos_sbe_tl_h"])
+ self.assertEqual(p["soundFresh"], 638) # sound mode starts at the roof
+ self.assertEqual(p["soundKeys"], ["phos_sbe_tl_h", "phos_sbe_tl_h_sound"])
+ self.assertEqual(p["soundRestored"], 400)
+ self.assertEqual(p["pictureAfter"], 200) # untouched by sound mode's write
def test_the_height_is_a_view_preference_and_NOT_sequence_data(self):
# It is not in the save payload, so a drag cannot bump the document's
@@ -5231,8 +5261,9 @@ class TheTimelineIsResizable(unittest.TestCase):
# else's screen. localStorage is where every other view preference in
# this panel already lives.
self.assertEqual(self.r["tlIsNotInTheSave"], [-1, -1, -1])
- self.assertIn("localStorage.getItem('phos_sbe_tl_h')", self.src)
- self.assertIn("localStorage.setItem('phos_sbe_tl_h'", self.src)
+ self.assertIn("localStorage.getItem(sbeTlPrefKey())", self.src)
+ self.assertIn("localStorage.setItem(sbeTlPrefKey()", self.src)
+ self.assertIn("'phos_sbe_tl_h_sound' : 'phos_sbe_tl_h'", self.src)
# The server's document model has never heard of it.
model = (Path(__file__).resolve().parent
/ "storyboard_editor.py").read_text(encoding="utf-8")
@@ -5251,9 +5282,12 @@ class TheTimelineIsResizable(unittest.TestCase):
# below it: sbeFitMonitors budgets against every child of the column
# it can measure, so a grip with a height of its own would have been
# paid for out of the picture.
- transport = self.src[self.src.index('<div class="sbe-transport">'):]
- transport = transport[:transport.index("<div class=\"sbe-tl\"")]
- self.assertIn('id="sbeTlGrab"', transport)
+ # The grab hangs below the TOOL ROW (the clip bar and the timeline's
+ # own controls, one row) — the transport row it used to live in went
+ # under the Program monitor.
+ toolrow = self.src[self.src.index('<div class="sbe-toolrow" id="sbeToolRow">'):]
+ toolrow = toolrow[:toolrow.index("<div class=\"sbe-tl\"")]
+ self.assertIn('id="sbeTlGrab"', toolrow)
css = self.src[self.src.index(".sbe-tl-grab {"):]
css = css[:css.index(".sbe-tl-grab:focus-visible {")]
self.assertIn("position: absolute", css)
@@ -5743,7 +5777,7 @@ class TheHeaderIsOneRow(unittest.TestCase):
self.assertIn("classList.toggle('primary'", self.src)
# ...and every editor row that hosts buttons cancels the stretch.
for rule in (".sbe-head .ghost-btn, .sbe-head .primary {",
- ".sbe-transport .primary {",
+ ".sbe-toolrow .ghost-btn, .sbe-toolrow .primary {",
".sbe-recover .ghost-btn, .sbe-recover .primary {",
".sbe-vers-new .primary {"):
self.assertIn(rule, self.src, "%s is gone — the row it styled "
@@ -5755,15 +5789,14 @@ class TheHeaderIsOneRow(unittest.TestCase):
"button stretch" % rule)
def test_the_two_rows_the_calm_layout_added_cannot_wrap_either(self):
- # The transport is the other flex row that gained controls, and the
- # gutter is a fixed column beside a scroller. Measured at 1100px: the
- # transport is 34px and one row, the gutter 124px.
- t = self.src[self.src.index("\n .sbe-transport {"):]
+ # The tool row is the other flex row with controls on it, and the
+ # gutter is a fixed column beside a scroller. The tool row does NOT
+ # wrap: the clip bar inside it overflows into its More menu instead
+ # (see TheClipBar), so the row is 28px at every width.
+ t = self.src[self.src.index("\n .sbe-toolrow {"):]
t = t[:t.index("}")]
- self.assertIn("flex-wrap: wrap", t) # it MAY wrap: it is the row that
- # has somewhere to go — nothing below it is pinned to the viewport, and
- # sbeFitMonitors measures whatever height it ends up with. Stated here
- # so the difference from the header is a decision, not an oversight.
+ self.assertIn("display: flex", t)
+ self.assertNotIn("flex-wrap: wrap", t)
g = self.src[self.src.index("\n .sbe-gutter {"):]
g = g[:g.index("}")]
self.assertIn("flex: 0 0 124px", g)
@@ -5912,7 +5945,7 @@ class TheClipBar(unittest.TestCase):
cls.src = panel_source()
cls.html = panel_html_render()
cls.bar = cls.html[cls.html.index('id="sbeCbar"'):]
- cls.bar = cls.bar[:cls.bar.index('class="sbe-transport"')]
+ cls.bar = cls.bar[:cls.bar.index('id="sbeTlWrap"')]
# ---- the ten verbs ---------------------------------------------------
VERBS = (
@@ -5955,8 +5988,8 @@ class TheClipBar(unittest.TestCase):
# "we have an empty corner that we can use in the upper part of the
# timeline".
for a, b in (('id="sbeMonitors"', 'id="sbeCbar"'),
- ('id="sbeCbar"', 'class="sbe-transport"'),
- ('class="sbe-transport"', 'id="sbeTlWrap"')):
+ ('id="sbeCbar"', 'id="sbeTlGrab"'),
+ ('id="sbeTlGrab"', 'id="sbeTlWrap"')):
self.assertLess(self.html.index(a), self.html.index(b), (a, b))
def test_a_verb_that_cannot_fire_is_DISABLED_and_says_why(self):
@@ -6049,7 +6082,7 @@ class TheClipBar(unittest.TestCase):
# `flex-wrap: wrap` would answer a narrow pane with a second row, and
# a second row is height sbeFitMonitors then takes off the PICTURE.
css = self.src[self.src.index(" .sbe-cbar {"):]
- css = css[:css.index(".sbe-transport {")]
+ css = css[:css.index(".sbe-toolrow {")]
self.assertIn("flex-wrap: nowrap", css)
self.assertIn("overflow: hidden", css)
# ...and the fold is restated, because `display: inline-flex` on the
@@ -6315,7 +6348,7 @@ class TimelineMarkup(unittest.TestCase):
self.assertIn("c.proxy", fn)
self.assertIn("proxy_url", panel_source()[:0] + "proxy_url")
badge = extract_function("sbeShowFrameAt", self.src)
- self.assertIn("SOURCE (slow", badge)
+ self.assertIn("SOURCE — slow to seek", badge)
# The three below are SOURCE assertions, not behaviour, because the thing
# under test is CSS and there is no way to run CSS in node. They are here
@@ -6361,12 +6394,12 @@ class TimelineMarkup(unittest.TestCase):
# (the test above still counts exactly one video in it); the source is
# a second element with its own video, still, badge and empty state.
row = self.src[self.src.index('<div class="sbe-monitors" id="sbeMonitors">'):]
- row = row[:row.index('<div class="sbe-transport">')]
+ row = row[:row.index('<!-- ============== THE CLIP BAR')]
self.assertIn('id="sbeSrcVideo"', row)
self.assertIn('id="sbeSrcStill"', row)
self.assertIn('id="sbeSrcAddBtn"', row)
self.assertIn('id="sbeStage"', row) # the program
- self.assertIn("Click a clip to preview it.", row)
+ self.assertIn("Drop a clip here to preview", row)
# Two monitors, two videos — and no third one that nobody owns.
self.assertEqual(row.count("<video id="), 2)
# The source is a player, not a second editor: no track, no trim.
@@ -7264,6 +7297,147 @@ def run_oneshot_contract() -> dict:
path.unlink(missing_ok=True)
+class RoundTwoTipsSourceIcons(unittest.TestCase):
+ """Round 2 of the layout redesign (2026-09-17), the owner after using it:
+
+ "The tooltips on the buttons are too slow."
+ "You have two empty dark spaces on the sides … you can still add the
+ preview clip for a place where you can drag the clips and see them."
+ "The icons are not very clear, are really weird, and maybe deformed."
+ "The on/off toggles for the screen panels … it's not clear."
+ """
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")
+ cls.js = (ROOT / "webapp" / "js" / "editor.js").read_text(encoding="utf-8")
+ cls.tips = (ROOT / "webapp" / "js" / "tips.js").read_text(encoding="utf-8")
+ cls.css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")
+
+ # ---- icons ----------------------------------------------------------------
+ def test_every_editor_glyph_is_a_symbol_with_its_own_viewbox(self):
+ # THE DEFORMATION: bare <g>s drawn on a 24-unit grid, used from an <svg>
+ # with no viewBox, so a 15px box showed the top-left 15 units of each.
+ sprite = self.html[self.html.index('<svg class="sbe-icons"'):]
+ sprite = sprite[:sprite.index("</defs></svg>")]
+ self.assertNotIn("<g id=", sprite)
+ ids = re.findall(r'<symbol id="(ic-[\w-]+)" viewBox="0 0 256 256">', sprite)
+ self.assertEqual(len(ids), sprite.count("<symbol "))
+ used = set(re.findall(r'#(ic-[\w-]+)', self.html + self.js))
+ self.assertEqual(used - set(ids), set(), "an icon is used that the sprite does not define")
+ for want in ("ic-split", "ic-lift", "ic-ripple", "ic-dup", "ic-link", "ic-unlink",
+ "ic-mute", "ic-sound", "ic-lock", "ic-unlock", "ic-facefix", "ic-wave",
+ "ic-inspect", "ic-full", "ic-panels", "ic-source"):
+ self.assertIn(want, ids)
+ # scissors for split, the Phosphor geometry the panel already ships
+ split = sprite[sprite.index('id="ic-split"'):]
+ self.assertIn('<circle cx="76" cy="68" r="28"/>', split[:split.index("</symbol>")])
+
+ def test_the_stroke_is_set_once_in_symbol_units(self):
+ rule = self.css[self.css.index(" .sbe-cbar-i {"):]
+ rule = rule[:rule.index("}")]
+ self.assertIn("stroke-width: 22;", rule)
+ self.assertIn("#sbeCbar > .sbe-cbar-btn .sbe-cbar-i, .sbe-tbtn .sbe-cbar-i { width: 18px; height: 18px; }", self.css)
+ self.assertNotIn("'🔇' : '🔊'", self.js)
+ self.assertIn("SBE.muted ? '#ic-mute' : '#ic-sound'", extract_function("sbeSetMute", self.js))
+
+ # ---- the View group --------------------------------------------------------
+ def test_the_panel_toggles_are_one_labelled_group_in_the_header(self):
+ head = self.html[self.html.index('<header class="carousel-head sbe-head">'):]
+ head = head[:head.index("</header>")]
+ view = head[head.index('id="sbeView"'):]
+ view = view[:view.index(" </span>\n")]
+ for bid, label in (("sbeSrcBtn", "Source"), ("sbeInspectBtn", "Inspector"),
+ ("sbeSoundBtn", "Sound"), ("sbePanelsBtn", "Panels")):
+ btn = view[view.index('id="%s"' % bid):]
+ btn = btn[:btn.index("</button>")]
+ self.assertIn("aria-pressed=", btn, bid)
+ self.assertIn("<b>%s</b>" % label, btn, bid)
+ self.assertIn('id="sbeFullBtn"', view)
+ # nowhere else: not under the picture, not on the tool row
+ rest = self.html.replace(view, "")
+ for bid in ("sbeSrcBtn", "sbeInspectBtn", "sbeSoundBtn", "sbePanelsBtn", "sbeFullBtn"):
+ self.assertNotIn('id="%s"' % bid, rest, bid)
+
+ def test_pressed_means_the_panel_is_showing_and_the_tip_says_what_a_click_does(self):
+ fn = extract_function("sbePaintPanels", self.js)
+ self.assertIn("!(document.body && document.body.classList.contains('ed-focus')), 'Side panels'", fn)
+ self.assertIn("sbeSrcShown(), 'Source monitor'", fn)
+ self.assertIn("!!SBE.inspect, 'Inspector'", fn)
+ tip = extract_function("sbeViewTip", self.js)
+ self.assertIn("(pressed ? onText : offText) + sbeKeyHint(keyId)", tip)
+ self.assertIn('.sbe-vbtn[aria-pressed="true"]', self.css)
+
+ # ---- the Source monitor ------------------------------------------------------
+ def test_the_source_monitor_is_on_screen_unless_this_browser_hid_it(self):
+ self.assertIn('<div class="sbe-mon sbe-mon-src" id="sbeSrcMon">', self.html)
+ self.assertIn("srcOn: sbeSrcRead(),", self.js)
+ self.assertIn("return v !== 'hidden';", extract_function("sbeSrcRead", self.js))
+ self.assertIn("sbeSrcWrite(false);", extract_function("sbeSrcClose", self.js))
+ self.assertIn("sbeSrcWrite(true);", extract_function("sbeSrcMonToggle", self.js))
+ # both columns are exactly their picture's width, so neither is squeezed out of 16:9
+ self.assertIn(".sbe-monitors > .sbe-mon-src { flex: 0 0 auto; width: calc(var(--sbe-src-h) * 16 / 9); }", self.css)
+
+ def test_the_source_monitor_is_a_drop_target_for_the_pool_and_the_track(self):
+ self.assertIn("Drop a clip here to preview", self.html)
+ move = extract_function("edPoolDragMove", self.js)
+ self.assertIn("sbeSrcDropHover(ev, d.row.kind !== 'sound')", move)
+ end = extract_function("edPoolDragEnd", self.js)
+ self.assertIn("if (d.toSrc) { edPoolPreview(d.index); return; }", end)
+ self.assertLess(end.index("d.toSrc"), end.index("edPoolSound("))
+ tmove = extract_function("sbeOnTrackMove", self.js)
+ self.assertIn("d.toSrc = sbeSrcDropHover(ev, true);", tmove)
+ tup = extract_function("sbeOnTrackUp", self.js)
+ # the track is restored BEFORE anything else happens: a drop on the monitor is never an edit
+ self.assertIn("SBE.clips = JSON.parse(d.before);", tup[tup.index("if (d.toSrc)"):])
+ self.assertLess(tup.index("if (d.toSrc)"), tup.index("SBE.undo.push"))
+ load = extract_function("sbeSrcLoadClip", self.js)
+ self.assertIn("sbeKind(c) === 'slug'", load)
+ self.assertIn(".sbe-mon-src.is-drop-over .sbe-stage", self.css)
+
+ # ---- the tooltips ---------------------------------------------------------------
+ def test_one_fast_tooltip_replaces_the_native_one_on_icon_buttons(self):
+ self.assertIn("const TIP_DELAY_MS = 150;", self.tips)
+ for sel in ("'.sbe-ibtn'", "'.sbe-vbtn'", "'#sbeCbar .sbe-cbar-btn'", "'.po-act'"):
+ self.assertIn(sel, self.tips)
+ adopt = extract_function("tipAdopt", self.tips)
+ self.assertIn("el.removeAttribute('title');", adopt)
+ self.assertIn("setAttribute('aria-label'", adopt)
+ self.assertIn("attributeFilter: ['title']", self.tips)
+ self.assertIn("matches(':focus-visible')", self.tips)
+ self.assertIn("prefers-reduced-motion: reduce", self.css[self.css.index(".phos-tip {"):])
+ place = extract_function("tipPlace", self.tips)
+ self.assertIn("vw - TIP_MARGIN - w", place)
+ self.assertIn("r.top - TIP_GAP - h", place)
+ # warm: the next tip along a row is immediate
+ arm = extract_function("tipArm", self.tips)
+ self.assertIn("if (warm) { tipShow(target); return; }", arm)
+
+ def test_the_tooltip_splits_name_body_and_keys(self):
+ if not shutil.which("node"):
+ self.skipTest("node not installed")
+ # the whole module, on a stub page: it must load with nothing but listeners
+ code = """
+globalThis.document = { addEventListener() {}, documentElement: {} };
+globalThis.window = { addEventListener() {} };
+globalThis.shortcutHint = (id) => ({ 'editor.inspector': '⌘I', 'editor.split': 'S or ⌘K or ⌘B' })[id] || '';
+""" + self.tips + """
+const el = (sc) => ({ getAttribute: (k) => k === 'data-shortcut' ? sc : null });
+console.log(JSON.stringify([
+ tipSplit(el('editor.inspector'), 'Inspector — hidden. Click to show it. (⌘I)'),
+ tipSplit(el(null), 'Ripple delete\\nTakes the clip off. (⇧⌫)'),
+ tipSplit(el('editor.split'), 'Split\\nCuts at the playhead (S or ⌘K or ⌘B)'),
+ tipSplit(el(null), 'Undo'),
+]));
+"""
+ out = subprocess.run(["node", "-e", code], capture_output=True, text=True, check=True).stdout
+ a, b, c, d = json.loads(out)
+ self.assertEqual((a["name"], a["body"], a["keys"]), ("Inspector", "Hidden. Click to show it.", ["⌘I"]))
+ self.assertEqual((b["name"], b["body"], b["keys"]), ("Ripple delete", "Takes the clip off.", ["⇧⌫"]))
+ self.assertEqual(c["keys"], ["S", "⌘K", "⌘B"])
+ self.assertEqual((d["name"], d["body"], d["keys"]), ("Undo", "", []))
+
+
class OneShotIsATab(unittest.TestCase):
"""Its own door: a tab beside Video, its own composer, one document to
POST /oneshot, and the video form carries none of it any more."""
@@ -7387,3 +7561,27 @@ class OneShotIsATab(unittest.TestCase):
m = self.r["statusMine"]
self.assertIn("Queued, paused", m["title"]); self.assertIn("coast ride", m["title"])
self.assertIn("1 ahead of it", m["meta"]); self.assertIn("paused", m["meta"])
+
+
+class RoomToneShipReview(unittest.TestCase):
+ """Codex ship review 2026-09-18, two confirmed defects in the room-tone
+ apply path. Source assertions, because both are async UI paths."""
+
+ JS = (Path(__file__).resolve().parent / "webapp" / "js" / "editor.js").read_text(encoding="utf-8")
+
+ def test_the_bed_lands_on_the_timeline_that_asked_for_it(self):
+ # Open film B while A's bed is being made and the response used to
+ # replace B's bed with A's file.
+ i = self.JS.index("async function edRtApply")
+ body = self.JS[i:i + 3000]
+ self.assertIn("const askedFor = String(SBE.id", body)
+ self.assertIn("!== askedFor", body)
+ self.assertLess(body.index("const askedFor"), body.index("await sbeRtRequest"))
+
+ def test_a_rebuild_keeps_the_fader_the_user_set(self):
+ # `room_tone.level` is the level the bed was MADE with; the fader writes
+ # `track.gain`. Rebuilding from the metadata reset a bed pulled down to
+ # 10% back to 35% (+11 dB).
+ self.assertIn("function sbeRtLevelOfTrack", self.JS)
+ i = self.JS.index("async function edRtApply")
+ self.assertIn("sbeRtLevelOfTrack(cur.track)", self.JS[i:i + 2000])
diff --git a/test_usage_fleet_first.py b/test_usage_fleet_first.py
new file mode 100644
index 0000000..1201f2b
--- /dev/null
+++ b/test_usage_fleet_first.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+"""Total renders means THE FLEET, and the dashboard says which is which.
+
+Owner, 2026-09-18: "when I ask you for total renders, I mean total renders from
+the fleet too… one of the first windows I want to see is total renders for all
+the fleet."
+
+Before this, /stats had ONE tile called "Total renders" whose meaning changed
+with whether a PostHog read key happened to be configured: the fleet's total
+when it was, this Mac's when it wasn't, distinguishable only by a caption in
+10 px type. A number that changes meaning under a fixed label is not a number
+you can quote in a release post.
+"""
+from __future__ import annotations
+
+import os
+import tempfile
+import unittest
+from pathlib import Path
+
+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-usage-"))
+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"
+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"
+
+import mlx_ltx_panel as P # noqa: E402
+
+ROOT = Path(P.__file__).resolve().parent
+HTML = (ROOT / "panel_assets" / "stats.html").read_text(encoding="utf-8")
+
+
+class ThePayloadCarriesBoth(unittest.TestCase):
+ def test_a_report_without_a_key_says_why_the_fleet_is_missing(self):
+ real = P._analytics_query_key
+ P._analytics_query_key = lambda: ""
+ try:
+ rep = P._usage_report()
+ finally:
+ P._analytics_query_key = real
+ self.assertEqual(rep.get("source"), "local")
+ self.assertEqual(rep.get("fleet_blocked"), "no_key")
+ # ...and this machine's own numbers ride along, named as such.
+ self.assertIn("machine", rep)
+ self.assertIn("total_renders", rep["machine"])
+
+ def test_attach_local_never_overwrites_the_fleet_tiles(self):
+ fleet = {"ok": True, "source": "fleet", "tiles": {"total_renders": 12345}}
+ out = P._usage_attach_local(dict(fleet))
+ self.assertEqual(out["tiles"]["total_renders"], 12345)
+ self.assertIn("machine", out)
+ self.assertIsNot(out["machine"].get("total_renders"), 12345)
+
+
+class TheDashboardLeadsWithTheFleet(unittest.TestCase):
+ def test_usage_is_the_first_section_on_the_page(self):
+ first = HTML.index('id="sec-usage"')
+ for other in ('id="sec-now"', 'id="sec-attention"', 'id="sec-funnel"'):
+ self.assertLess(first, HTML.index(other), other + " comes before Usage")
+
+ def test_the_hero_tile_is_the_fleet_and_says_so(self):
+ i = HTML.index("const tiles = [")
+ block = HTML[i:i + 1600]
+ self.assertIn("'Total renders · fleet'", block)
+ self.assertIn("'Total renders · this Mac'", block)
+ # The hero is the fleet one.
+ self.assertLess(block.index("fleet'"), block.index("this Mac'"))
+ self.assertIn("hero: true", block[:block.index("this Mac'")])
+
+ def test_an_unreachable_fleet_shows_a_dash_and_a_remedy(self):
+ i = HTML.index("const tiles = [")
+ block = HTML[i:i + 1600]
+ # never a local number under the fleet label
+ self.assertIn("isFleet ? fmt(t.total_renders) : '—'", block)
+ self.assertIn("add a PostHog read key in Settings", HTML)
+ self.assertIn("PostHog query failed", HTML)
+ self.assertIn("is-unknown", HTML)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/webapp/docs/editor.md b/webapp/docs/editor.md
index a52b6fa..69c9208 100644
--- a/webapp/docs/editor.md
+++ b/webapp/docs/editor.md
@@ -11,11 +11,11 @@ The Editor is a timeline for the clips you make — from any engine, from a stor
## The layout {#layout}
-**The header** — the sequence's name, the draft chip, whether it is saved (*unsaved changes*, *saved · revision N*), **Undo**, **Redo**, **Save**, **Render** with its **▾**, and **⋯** (Drafts and versions, Media pool, Auto-edit, Storyboard, Close).
+**The header** — the sequence's name, the draft chip, whether it is saved (*unsaved changes*, *saved · revision N*), the **View** group (below), **Undo**, **Redo**, **Save**, **Render** with its **▾**, and **⋯** (Drafts and versions, Media pool, Auto-edit, Storyboard, Close).
**The media pool** (left) — **This Sequence**, **Other sequences**, **Generations**, **Images** and **Sound**. Click a row to watch it in the Source monitor; **+** puts it at the end of the sequence; drag it onto the track to insert it where you drop it. On **Sound**, **+** puts the sound on an audio track at the playhead; on a video row, **♪** puts only its sound there — see [Audio tracks](#docs/editor/tracks). **Add black** adds that many seconds of black at the end, **Add title** puts a title at the playhead, **Filter by name** searches ([[sc:search.focus]]).
-**The monitors** — **Source** plays what you clicked in the pool (**Add to timeline** places it). **Program** plays the timeline. Beside them, the inspector (below) and *Rendered but not on the timeline*, with **Place** for each clip that finished but was never put on the track.
+**The monitors** — **Source** on the left, **Program** on the right. **Program** plays the timeline. Under it, left to right: **▶** / **⏸**, the speaker (mutes the preview only), the time, and what is under the playhead (the clip's name, its trim, *source* if it has no proxy yet); a chip counts clips that finished rendering but are not on the timeline and opens the Inspector. **Source** plays a clip before you cut it in: click a clip in the pool, or **drag a clip onto it** — from the media pool or from the timeline (dragging a shot from the track onto the Source monitor loads it there and leaves the timeline exactly as it was). Until something is loaded it says *Drop a clip here to preview*. **Add to timeline** places the clip; **×** hides the monitor. The **Inspector** opens beside the monitors when you ask for it and holds the clip's properties (below) and *Rendered but not on the timeline*, with **Place** for each clip that finished but was never put on the track. Nothing on this screen resizes itself: the monitors and the panels change only when you press a toggle, and what you chose is remembered in this browser.
**The tracks**, top to bottom:
@@ -27,7 +27,17 @@ The Editor is a timeline for the clips you make — from any engine, from a stor
| **A2 Music** | the soundtrack |
| **A3, A4, …** | audio tracks — laugh tracks, stings, beds, any number of sounds; every track plays together |
-**The transport** — **Play**, 🔊 (mutes the preview only), the time, **Snap to beat**, zoom **−** / slider / **+**, the **i** (the preview is approximate at cuts; the render is exact) and **Keys**. Drag the timeline's top edge up for taller tracks; double-click it to reset. With the sound lanes small (below) the edge goes much further down, and the picture gets what it leaves.
+**The tool row** — directly above the tracks: the [clip bar](#docs/editor/clip-bar) on the left (icons; hover one for its name, what it does and its key), and on the right **Snap** (to the beat grid), zoom **−** / slider / **+**, the **i** (the preview is approximate at cuts; the render is exact — it turns amber when it has a note for you) and **Keys**. Drag the timeline's top edge (just below this row) up for taller tracks; double-click it to reset; each mode remembers its own height.
+
+**View** — the group of switches in the header decides what is on the screen. Each one is **highlighted while its panel is showing**; click to hide it, click again to bring it back:
+
+- **Source** — the Source monitor on the left.
+- **Inspector** ([[sc:editor.inspector]], or double-click a clip) — the properties panel on the right.
+- **Sound** ([[sc:editor.soundMode]]) — Sound mode: every sound lane at full height, the picture small. See [Picture mode and Sound mode](#docs/editor/compact).
+- **Panels** ([[sc:editor.panels]]) — the app's left column: the tabs, the media pool and the queue. Hide it to give the cut the whole window.
+- **Full screen** (the corners, [[sc:editor.fullscreen]]) — the Program monitor fills the screen; **Esc** or **F** brings it back.
+
+In a narrow window the group shows icons only. Every icon button in the Editor shows its name, what it does and its key a moment after you point at it (or tab to it).
## Selecting {#selecting}
@@ -47,9 +57,9 @@ The Editor is a timeline for the clips you make — from any engine, from a stor
## The clip bar {#clip-bar}
-The row of buttons directly above the tracks holds the actions you use all day. Left of them, the readout names what is selected (*3 clips selected*).
+The row of icons directly above the tracks holds the actions you use all day, in four groups: edit (**Split**, **Lift**, **Ripple delete**, **Duplicate**), sound (**Unlink / Link**, **Resync**, **Mute**, **Delete sound**, **Clear points**), **Lock**, and **Face Fix ×2**. Hover an icon for its name, what it does and its key. Left of them, the readout names what is selected (*3 clips selected*).
-Every button is always there. When it cannot act, it is greyed out and its tooltip says what would make it work.
+Every button is always there. When it cannot act, it is greyed out and its tooltip says what would make it work. When the pane is too narrow, the tail of the row moves into a **More** menu, with the names written out — as they are in the right-click menu.
| Button | What it does | Greyed out when |
|---|---|---|
@@ -69,7 +79,7 @@ When the pane is too narrow, the last buttons move into **More ▾**. **Right-cl
## The inspector (Advanced) {#inspector}
-The panel beside the monitors holds the **properties** of the selected clip — the settings you change occasionally. It has three sections:
+The panel beside the Program monitor holds the **properties** of the selected clip — the settings you change occasionally. It is closed until you open it: **Inspector** in the View group, [[sc:editor.inspector]], or a double-click on a clip; press again to close it. Whether it is open is remembered in this browser. It has three sections:
- **Clip** — **Speed**, 0.25× to 4× (**0.5x**, **1x**, **2x** buttons); the clip's slot on the film changes and everything after it moves. **Retake** renders a new take of a storyboard shot — see [Replace a shot with a retake](#docs/editor/job-retake).
- **Sound** — **Fade in** / **Fade out** in seconds, and **Add point at playhead** for the level line.
@@ -96,15 +106,13 @@ A **J-cut** starts the next shot's sound before its picture; an **L-cut** lets a
- Everything else works the same on both lanes: unlink, trim, J-cut and L-cut, fades, level points, Mute, Resync, Duplicate, snapping (a dragged edge also snaps to the other sounds' edges).
- The preview plays both lanes, the render mixes them under the same safety limiter as the music (and **Duck under dialogue** follows sound on either lane), and the export puts **Clip sound B** on its own audio track, right after the first.
-### Sound lanes small, so you can see the picture {#compact}
+### Picture mode and Sound mode {#compact}
-**A1**, **A2** and every audio track make themselves **small** — thin strips showing where each sound sits — while you are not working on sound, and come back to full height the moment you are. The picture and the monitors get the height they give up.
+The Editor has two layouts and one switch between them — **Sound** in the View group, [[sc:editor.soundMode]], or the **▾** on the **A1 Clip sound A** head; all three are the same control.
-- **They open by themselves** when you click, hover or drag any sound or its lane head, when a sound is selected, when you open **Sound** in the media pool, when you add a track or a sound file, and while the film is playing. They never shrink in the middle of a drag, during playback, or under an open menu.
-- **They make themselves small again** a couple of seconds after you leave the sound alone.
-- **A small lane is a picture, not a control**: the waveform shows where the sound is; the grips, the corner fades and the level line are not there. Moving the pointer onto the lanes is enough to open them, so by the time you click, the sound is at full height and behaves exactly as it always has.
-- **▾ on the A1 Clip sound A head** ([[sc:editor.soundLanes]]) pins it: press it once and the lanes stay small whatever you do; press it again (**▸**) and they stay at full height. Clicking a small lane hands the decision back to the automatic one. The choice is remembered in this browser, not in the film.
-- With them small, the timeline's top edge can be pushed much lower than before — the box is only as tall as what is in it.
+- **Picture mode** (the default) — the picture is big. **A1**, **A2** and every audio track are thin strips that show where each sound sits and what colour it is. A thin strip is a picture, not a control: click it to select it (the clip bar's sound verbs — mute, delete, unlink, resync, duplicate — all work on the selection), double-click it for sound mode. The timeline sits at the height you last dragged it to, as low as its thin lanes allow.
+- **Sound mode** — the sound is big and the picture is small. Every sound lane is at full height with its grips, corner fades, level line and points; the timeline takes the height and the Program monitor drops to its smallest size. Press the switch again for the picture.
+- **Nothing changes the split by itself.** No hover, click, selection, playback or timer moves a lane or a monitor — only the switch. Each mode remembers its own timeline height, and the mode itself is remembered in this browser, not in the film.
### When sound drifts: Resync {#resync}
@@ -143,6 +151,21 @@ Under **A2 Music** are the audio tracks — **A3**, **A4** and on. A track holds
- The inspector shows the selected sound's **Level**, **Fade in** / **Fade out** and **Add point at playhead**. The level you hear is the sound's level times its track's level.
- Everything plays in the preview, mixes into the render under the same safety limiter as the music, and exports: each audio track becomes its own audio track in Premiere / Resolve and its own layers in After Effects, with trims, levels, fades and mutes editable there.
+### Room tone {#room-tone}
+
+**Room tone** is background noise — room noise, atmos, an ambience bed — that runs under the whole sequence on its own audio track, so a cut never drops to silence or jumps from one room to another. It is made for the sequence each time, in about a second, on the CPU.
+
+- **Add it:** media pool → **Sound** → the **Room tone** card, or **♪** beside **+ Add audio track** → **Room tone…**. Pick a sound and press **Add room tone**. It lands on its own track (named *Room tone*), locked, from the first frame to the last.
+- **From this film** (the default) listens to the quiet moments of your own clips — the room between the lines, tape hiss, hum — and makes a continuous bed of that sound. When the clips have too little quiet sound it says so on the card and **Quiet room** stands in.
+- **Other sounds:** Quiet room, Living room, Office, TV studio, Kitchen, Car interior, Outdoors day, Night outside, City street, Rain, VHS tape, Big hall, Plane cabin.
+- **New take** makes another version of the same sound — a new one every click. **Use this sound** swaps to what the picker shows, at the same level. **Rebuild** makes it again from the sequence as it is now (after a re-cut). **Remove** takes it off (Undo brings it back).
+- **Level** is in LUFS: **−27** by default — clearly there, under dialogue that sits around −16. The track head's level slider is the same control in percent. Every change is one Undo step.
+- **It follows the sequence.** Trim, add or delete shots and the bed stays as long as the sequence; when the sequence outgrows the sound file, a longer one is made in the background. A bed you split or moved by hand is left alone — to dip it somewhere, unlock it (**Lock** on the clip bar) and add level points.
+- **Automatic cuts** — the Editor's first cut of a Storyboard, **Auto-edit…**, and Storyboard's automatic film — get a *From this film* room tone by default. Turn **Add room tone to automatic cuts** off on the card to stop it. A music-video cut (the song replaces the clips' sound) and clips with no quiet sound get none.
+- It plays in the preview, mixes into the render and exports as its own audio track, like any other track. The file lives in the sequence's `audio/room_tone/` folder.
+
+**No clicks at cuts.** The render also puts a 12 ms fade on the start and end of every clip's sound, so a hard cut between two sounds cannot click. It is too short to hear as a fade. The preview does not do this, and an exported project leaves it to your editor.
+
## Titles, cards and black {#titles}
- **Add title** (media pool) puts a 3-second title on **V2 Overlay** at the playhead. In the inspector: the text, **Size**, **Colour**, **Align**, **Across** / **Down** position and **Box behind**, plus fades. Drag it to move it, drag its edges to change its length; [[sc:editor.removeOverlay]] removes it.
@@ -187,7 +210,7 @@ A transition borrows extra picture from beyond each clip's trim, so the cut does
| **Size** | **As cut** · **1080p** · **4K** | only ever up, never a crop; 4K adds pixels, not detail |
| **Finish** | **Clean** · **Grain** · **Heavy grain** | on the delivered file only — the preview and the export stay clean |
-**Export for Premiere / Resolve / AE** (in the same menu) writes a folder with an FCP7 XML (for Premiere and Resolve), an After Effects script and the media, and shows it in Finder. Sound comes out as separate stems, not the mixed track — the clips' sound (lane A, then lane B as its own track when it is used), the music, and one audio track per **A3, A4, …**. Cuts, trims, speed, fades, mutes and reframing travel into the project as editable settings; titles do not, and transitions arrive as plain cuts.
+**Export for Premiere / Resolve / AE** (in the same menu) writes a folder with an FCP7 XML (for Premiere and Resolve), an After Effects script and the media, and shows it in Finder. Sound comes out as separate stems, not the mixed track — the clips' sound (lane A, then lane B as its own track when it is used), the music, and one audio track per **A3, A4, …** (room tone included). Cuts, trims, speed, fades, mutes and reframing travel into the project as editable settings; titles do not, and transitions arrive as plain cuts.
**Auto-edit…** (⋯) re-cuts the sequence from scratch and throws away this arrangement — it asks first.
@@ -226,6 +249,13 @@ For an L-cut, do the same with the **outgoing** shot and drag its strip's right
4. Play across the cut — both sounds play together while they overlap.
5. **Save**.
+### Smooth the sound between cuts {#job-room-tone}
+
+1. Media pool → **Sound**. The **Room tone** card is at the top.
+2. Leave **From this film** picked (or choose a room) and press **Add room tone**. A *Room tone* track appears under the other sounds, as long as the sequence.
+3. Play across a few cuts. Too loud or too quiet? Move **Level** (−27 LUFS is the default). Not the right texture? **New take**, or pick another sound and press **Use this sound**.
+4. **Save**.
+
### Replace a shot with a retake {#job-retake}
1. Select the shot. Retake works on shots that came from a storyboard.
diff --git a/webapp/index.html b/webapp/index.html
index 6af14d1..b566532 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -286,7 +286,7 @@
<a class="creator-link" href="https://x.com/AIBizarrothe" target="_blank" rel="noopener" title="Follow Mr. Bizarro on X (the panel's creator)">
<img src="/assets/bizarro-avatar.jpg" class="creator-avatar" alt="">
<span>by Bizarro</span>
- <span class="x-icon"><svg class="ph" aria-hidden="true" style="margin-right:3px;vertical-align:-2px"><use href="#ph-arrow-square-out"/></svg>X</span>
+ <span class="x-icon"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-square-out"/></svg>X</span>
</a>
</header>
@@ -956,11 +956,83 @@
<textarea class="avoid-textarea" name="negative_prompt" id="negative_prompt" placeholder="blurry hands, distorted fingers, extra fingers, smeared face, warped text"></textarea>
</div>
- <!-- ============== QUICK SETTINGS ==============
- Quality picker (compact 4-up segmented strip) + Duration +
- Frames + Seed in one dense block. Everything more advanced
- (aspect, dims, speed, long-clips, export, audio source,
- open-when-done) is folded into the Customize disclosure below. -->
+ <!-- ========== SHOT LIST · per-window prompts (chained lengths only) ====== -->
+ <!-- ========== PER-WINDOW PROMPTS (chained lengths only) ==========
+ The fix for the public report — @Wizard_1981, v3.6.0: "10s and
+ 15s just repeat immediately after 5 seconds." The frames were
+ never duplicated (a 10 s render was checked frame by frame; the
+ background progresses continuously across the seam). What
+ repeated was the ACTION, because a 10 s clip is two chained 5 s
+ windows and BOTH were handed the same prompt. A continuous action
+ ("he walks") carries on fine; a discrete one ("he raises his arm",
+ a line of dialogue) is performed once per window and reads as a
+ loop. Our own tier note has warned about this in words since
+ v3.4.1 — and the runner has taken `--chain-prompts` the whole
+ time. This is the control that reaches it.
+
+ DEFAULT IS UNCHANGED. Off (the default) posts nothing and every
+ window gets the main prompt, exactly as before. On reveals one
+ small textarea per window, seeded with the main prompt so the
+ user EDITS a shot list instead of facing blank boxes, and a box
+ left empty falls back to the main prompt server-side.
+
+ Visible only when the selected Length is chained, and it follows
+ the Length strip live — 10 s shows two boxes, 15 s shows three
+ (renderH3WindowPrompts, called from _h3ApplyShape). Hidden
+ entirely when the INSTALLED runner has no `--chain-prompts`: that
+ user keeps the honest warning on the cell instead of being sent
+ looking for a control they don't have.
+
+ Sits with the PROMPT, above the render controls (layout pass,
+ 2026-09-18). It is prompt content — one line per 5 s window — not
+ a render setting, and inside the collapsed Shot setup section a
+ user who had just chosen a 15 s length would never have found it.
+ Still hidden entirely unless the chosen Length chains windows. -->
+ <div class="cz-control h3-winprompts" id="h3WindowPromptsRow" data-h3-only hidden>
+ <div class="cz-label">
+ <span>Per-window prompts</span>
+ <!-- The `?`. The panel had no help idiom of its own — every
+ explanation lived in a title= tooltip, which is invisible on
+ a trackpad and unreachable on a touch screen. One round
+ button, one sentence revealed in place, text owned by Python
+ (H3_CHAIN_PROMPT_HELP) so it can't drift from the mechanism. -->
+ <button type="button" class="help-dot" id="h3WinHelpBtn"
+ aria-expanded="false" aria-controls="h3WinHelpNote"
+ title="What are windows?"
+ onclick="toggleH3WindowHelp()">?</button>
+ <span class="cz-label-hint" id="h3WinPromptsHint"></span>
+ <span class="h3-winprompts-spacer"></span>
+ <label class="toggle-pill" id="h3WinPromptsPill"
+ title="Give each 5 s window its own line. Off = one prompt for the whole clip.">
+ <input type="checkbox" id="h3WinPromptsToggle">
+ <span class="toggle-dot"></span>
+ <span>One line per window</span>
+ </label>
+ </div>
+ <div class="h3-winhelp" id="h3WinHelpNote" hidden></div>
+ <div class="h3-winlist" id="h3WinPromptsList" hidden></div>
+ </div>
+
+ <!-- ============== SHOT SETUP ==============
+ Owner, 2026-09-18: "The H3 layout is kind of a bit too much … you have
+ a pill for speed, quality, length, and all that. That should be inside
+ one section that you can compress and decompress, like we have LoRAs
+ and Customize, because it is very messy like that … it should be
+ closed by default."
+ What used to be five stacked pill rows, each with its own label —
+ Speed, Quality, Length, Steps, Orientation — plus a Seed field, all of
+ it open on every render, is now ONE disclosure holding all of them,
+ closed until you want it. The summary line carries the whole shape
+ (#shotSetupSummary, written by updateShotSetupSummary), so the closed
+ section still says what will render.
+ Nothing left the form and nothing was renamed: every id, every data-*
+ hook, every hidden input and every handler is the one it was. The
+ order inside is deliberate and tested — Speed BEFORE the Quality label
+ (test_h3_tristep_draft), then the two axis strips, then the knobs that
+ modify them, then orientation and seed.
+ The selected cell's honest notes (#ltxTierNote / #h3TierNote) stay
+ OUTSIDE it, visible: a warning about the render you are about to queue
+ must not be foldable. -->
<div class="quick-settings">
<!-- ============== ENGINE STATE ==============
The PICKER lives in the header now (#engineSwitch, rendered from
@@ -997,6 +1069,11 @@
<input type="hidden" name="h3_upscale" id="h3_upscale" value="fit_720p">
<input type="hidden" name="h3_steps" id="h3_steps" value="auto">
<input type="hidden" name="h3_turbo" id="h3_turbo" value="0">
+ <!-- Fast · 3-step (TaoMate's 3-step adapter + its sigma ladder). "1"
+ when the Fast · 3-step Speed pill is lit, "0" otherwise; make_job
+ re-resolves it (Draft/Standard/High only, never with Turbo). In
+ the make_job allowlist. -->
+ <input type="hidden" name="h3_tristep" id="h3_tristep" value="0">
<!-- Which of H3's ONE adapter slots this render spends. Its runner's
`--lora` takes a single path (default=None, not append), so Turbo
and a picked LoRA cannot both run and something has to choose.
@@ -1016,309 +1093,297 @@
listed there silently no-ops on /queue/add — the known trap). -->
<input type="hidden" name="h3_chain_prompts" id="h3_chain_prompts" value="">
<div class="engine-note" id="engineRowNote" hidden></div>
- <!-- The engine's standing note. Second sentence added with the player
- scoping (Part C): Extend is an LTX pipeline and is now hidden on
- an H3 clip, so the surface has to say where length actually comes
- from — the chained tiers, chosen BEFORE the render, not a post-hoc
- action on the result. Said here, next to the tier strip where the
- user can act on it, rather than as a tooltip on a button that no
- longer exists. -->
- <div class="engine-hint" id="h3Hint" hidden>
- Dialogue + sound are generated jointly — write them into the prompt.
- Length is chosen here, before the render: 10 s and 15 s chain 5 s
- windows at render time, so there is no Extend afterwards.
- </div>
- <div>
- <div class="qs-label">
- <span class="qs-name" id="qualityLabelName">Quality</span>
- <span class="qs-meta" id="qualityMeta"></span>
- </div>
- <!-- Compact 4-col strip. Each chip carries name + a single spec
- line. Same data-quality wiring as before so setQuality()
- keeps working unchanged. The .pill-btn class is preserved
- for the click handler that filters by it.
- When a character is selected in the Characters chip strip,
- selectManualCharacter() hides this strip and reveals the
- character-only strip below. Its Draft/Pro rows use q8 distilled,
- while its High rows use the real q8 HQ lane; no character chip
- ever falls through to the ordinary q4 quality strip. -->
- <!-- LTX's CANVAS axis. Rendered by renderTierAxes('ltx') from
- BOOT.ltx.qualities / .lengths / .tiers, exactly as H3's two
- strips are, so the server-side table is the single source of
- truth for geometry and every estimate.
-
- These four chips used to be static markup carrying hand-written
- subtitles ("Q4 · 5 min", "Q8 Pro · 7 min") kept up to date by two
- separate JS updaters — numbers no measurement on 2.5 supported.
- The table fills the third slot now, the way H3's already did, and
- both updaters are deleted.
-
- `data-quality` is UNCHANGED: five surfaces read it (the click
- handler, setQuality's active toggle, applyTierTimes, the
- trained-LoRA compatibility gate, the character-strip swap). -->
- <div class="quality-strip pill-group" id="qualityGroup" data-ltx-only></div>
- <!-- LTX's DURATION axis — the same second row H3 grew, for the same
- reason: a canvas and a length are independent choices and one
- strip cannot express both. Duration used to be a free numeric
- field whose value one lane silently rounded away. The field
- itself is not deleted (power users have shipped work with it);
- it lives in Customize and a value off the axis lights no chip. -->
- <div class="ltx-axes" id="ltxAxes" data-ltx-only>
- <div class="qs-label h3-axis-label">
- <span class="qs-name">Length</span>
- <span class="qs-meta" id="ltxLengthMeta"></span>
- </div>
- <div class="quality-strip pill-group" id="ltxLengthGroup"></div>
- </div>
- <!-- The selected cell's honest notes, joined — the mirror of
- #h3TierNote. Empty and hidden when the combination has nothing
- to warn about, which is most of them. -->
- <div class="engine-hint" id="ltxTierNote" hidden></div>
- <!-- Character-only quality strip — revealed by selectManualCharacter.
- Rendered entirely from BOOT.ltx.character so the Manual surface
- and Characters tab expose the same generation-specific tokens. -->
- <!-- data-ltx-only for a reason the `hidden` attribute can't cover:
- its visibility is owned by _applyCharacterQualityStripVisibility,
- which only ever asks "is a character selected?". With a character
- active, switching to H3 left this strip lit BESIDE the H3 tier
- strip — two primary strips, both claiming to set the render. The
- fold rule settles it declaratively, whatever the JS believes. -->
- <div class="quality-strip pill-group" id="qualityGroupCharacter" hidden data-ltx-only></div>
- <!-- Hailuo H3 render shape — TWO INDEPENDENT AXES, not one fixed tier
- menu. This shipped as six baked combinations (Draft 3s, HQ 3s,
- HQ 5s, Wide 5s, Long 10s, Long 15s) and the owner's report was
- exact: "somebody may want to run the HQ 5s version for 10s, and
- it's now not possible from the UI." The matrix was mostly empty —
- our best canvas, the only true 16:9, could only produce 5-second
- clips — and nothing technical said so. Chained windows keep memory
- flat per window, so every canvas reaches every length.
-
- So: Quality picks the CANVAS (Draft 640×384 · Standard 768×448
- · High 1024×576 · Native 1344×768, the model's own ceiling),
- Length picks the DURATION (3s · 5s · 10s · 15s), and they don't
- know about each other. Both strips reuse the LTX
- .quality-strip visual language (separate elements, so neither
- engine's chips can ever be half-lit) and both are rendered by
- renderH3Axes() from BOOT.h3.qualities / .lengths / .tiers — the
- server-side tables stay the single source of truth for geometry,
- steps and every estimate, so a change is one Python edit.
-
- The outer id is UNCHANGED (#h3TierGroup): the engine registry row
- names it as H3's `strip` and setEngine's generic surface-swap
- hides it by id. It is now a wrapper around the two strips rather
- than a strip itself. -->
- <div class="h3-axes" id="h3TierGroup" hidden>
- <div class="quality-strip pill-group" id="h3QualityGroup"></div>
- <div class="qs-label h3-axis-label" id="h3LengthLabel">
- <span class="qs-name">Length</span>
- <span class="qs-meta" id="h3LengthMeta"></span>
+ <details id="shotSetupDetails" class="customize-section shot-setup">
+ <summary class="cz-summary">
+ <span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
+ <span class="cz-title">Shot setup</span>
+ <span class="cz-meta" id="shotSetupSummary">quality · length · speed</span>
+ </summary>
+ <div class="cz-body">
+ <!-- The engine's standing note. Second sentence added with the player
+ scoping (Part C): Extend is an LTX pipeline and is now hidden on
+ an H3 clip, so the surface has to say where length actually comes
+ from — the chained tiers, chosen BEFORE the render, not a post-hoc
+ action on the result. Said here, next to the tier strip where the
+ user can act on it, rather than as a tooltip on a button that no
+ longer exists. -->
+ <div class="engine-hint" id="h3Hint" hidden>
+ Dialogue + sound are generated jointly — write them into the prompt.
+ Length is chosen here, before the render: 10 s and 15 s chain 5 s
+ windows at render time, so there is no Extend afterwards.
</div>
- <div class="quality-strip pill-group" id="h3LengthGroup"></div>
- </div>
- <!-- Honest artefact notes for the selected combination. Rendered from
- the cell's `notes` list (server-side), so a Draft 10 s clip is
- told BOTH that 0.25 MP doesn't resolve faces and that one prompt
- is asked of every 5 s window. The chained warning now fires at any
- quality, because chaining is now available at any quality. The
- chained sentence now POINTS AT the control below instead of only
- warning; h3_visible_tiers() swaps the old warning back in for a
- pack whose runner has no --chain-prompts. -->
- <div class="engine-hint" id="h3TierNote" data-h3-only hidden></div>
- </div>
-
- <!-- ========== PER-WINDOW PROMPTS (chained lengths only) ==========
- The fix for the public report — @Wizard_1981, v3.6.0: "10s and
- 15s just repeat immediately after 5 seconds." The frames were
- never duplicated (a 10 s render was checked frame by frame; the
- background progresses continuously across the seam). What
- repeated was the ACTION, because a 10 s clip is two chained 5 s
- windows and BOTH were handed the same prompt. A continuous action
- ("he walks") carries on fine; a discrete one ("he raises his arm",
- a line of dialogue) is performed once per window and reads as a
- loop. Our own tier note has warned about this in words since
- v3.4.1 — and the runner has taken `--chain-prompts` the whole
- time. This is the control that reaches it.
-
- DEFAULT IS UNCHANGED. Off (the default) posts nothing and every
- window gets the main prompt, exactly as before. On reveals one
- small textarea per window, seeded with the main prompt so the
- user EDITS a shot list instead of facing blank boxes, and a box
- left empty falls back to the main prompt server-side.
-
- Visible only when the selected Length is chained, and it follows
- the Length strip live — 10 s shows two boxes, 15 s shows three
- (renderH3WindowPrompts, called from _h3ApplyShape). Hidden
- entirely when the INSTALLED runner has no `--chain-prompts`: that
- user keeps the honest warning on the cell instead of being sent
- looking for a control they don't have.
-
- Sits between the Length strip and Speed on purpose — it only
- exists because of a Length the user just chose, and it is about
- WHAT renders, not how long it takes. -->
- <div class="cz-control h3-winprompts" id="h3WindowPromptsRow" data-h3-only hidden>
- <div class="cz-label">
- <span>Per-window prompts</span>
- <!-- The `?`. The panel had no help idiom of its own — every
- explanation lived in a title= tooltip, which is invisible on
- a trackpad and unreachable on a touch screen. One round
- button, one sentence revealed in place, text owned by Python
- (H3_CHAIN_PROMPT_HELP) so it can't drift from the mechanism. -->
- <button type="button" class="help-dot" id="h3WinHelpBtn"
- aria-expanded="false" aria-controls="h3WinHelpNote"
- title="What are windows?"
- onclick="toggleH3WindowHelp()">?</button>
- <span class="cz-label-hint" id="h3WinPromptsHint"></span>
- <span class="h3-winprompts-spacer"></span>
- <label class="toggle-pill" id="h3WinPromptsPill"
- title="Give each 5 s window its own line. Off = one prompt for the whole clip.">
- <input type="checkbox" id="h3WinPromptsToggle">
- <span class="toggle-dot"></span>
- <span>One line per window</span>
- </label>
+ <!-- H3 SPEED — one switch above the Quality cards: ⚡ Fast (TaoMate's
+ 3-step adapter, the default once installed) | ✦ Best (the shape's
+ full sampler). The cards below re-price live for it. Turbo is
+ folded in here (Fast replaces it). Rendered by renderH3Turbo();
+ writes #h3_tristep. -->
+ <div class="h3-speed" id="h3SpeedRow" data-h3-only hidden>
+ <div class="qs-label">
+ <span class="qs-name">Speed</span>
+ <span class="qs-meta">Fast = 3 steps · Best = full steps</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.">
+ <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.">
+ <span>✦ Best</span><span class="sub" id="h3SpeedBestSub"></span>
+ </button>
+ </div>
+ <div class="h3-turbo-note" id="h3SpeedNote" hidden></div>
</div>
- <div class="h3-winhelp" id="h3WinHelpNote" hidden></div>
- <div class="h3-winlist" id="h3WinPromptsList" hidden></div>
- </div>
-
- <!-- ========== H3 PRIMARY CONTROLS — Speed + Steps ==========
- These two shipped inside the Customize disclosure and the owner
- could not find Steps at all: "I see you removed the step options
- we had before, no?" He hadn't lost a control, he'd lost a
- control's VISIBILITY, and the diagnosis matters — the rule that
- put them there was "LTX keeps its secondary knobs in Customize,
- so H3 should too", applied without checking whether they are
- secondary on this engine. They are not. Quality picks the canvas
- and Length picks the duration; Turbo (4-step distill adapter) and
- Steps (9 → 20 sigma points) are what decide how long you wait,
- each worth about a 2× swing, and neither is implied by either
- axis. A control that changes wall clock by 2× does not belong
- behind a disclosure triangle.
- So they sit here, directly under the two strips they modify,
- in the same chip grammar as the rest of the form. Nothing else
- moved: same ids, same .cz-* classes, same handlers, same hidden
- inputs (#h3_turbo / #h3_steps, both in the make_job allowlist).
- .eng-primary is only a CSS hook — the active-pill accent rules
- were scoped to .cz-body, so leaving Customize would otherwise
- have cost these chips their engine colour. Order is deliberate:
- Speed first because Turbo OVERRULES Steps. -->
- <div class="eng-primary" id="h3PrimaryControls" data-h3-only>
- <!-- H3 Turbo — the 4-step distillation LoRA. Grouped with Steps
- because it is the same axis (how many denoise passes), and it
- WINS: with Turbo on the Steps pills go visibly dead and the
- sampler is pinned at 4. Rendered by renderH3Turbo() from
- BOOT.h3.turbo, so Python stays the single source of truth for
- availability, size and copy — including the tooltip's
- measured-vs-derived distinction. LightX2V v1.0 has a visual
- approval but no end-to-end timing receipt yet, so every Turbo
- figure honestly stays derived from the measured cost model.
- The whole control
- hides when the installed pack's runner has no --lora. -->
- <div class="cz-control" id="h3TurboRow" data-h3-only hidden>
+ <!-- Speed — the LTX-2.5 distilled lane's REAL speed control
+ (v4.0.5), replacing the dead one above. "Fast draft" selects
+ the engine's named `fast` schedule preset: 5+2 forwards vs
+ the tuned 8+2, ~13% faster, and it renders a DIFFERENT take
+ (same prompt + seed land on a different shot) — which is why
+ it sits next to draft affordances and never on a quality
+ slider. Visibility is SERVER-OWNED: the row shows only when
+ the current tier cell carries `fast_eta`, which the registry
+ stamps only on 2.5 distilled cells — the UI never parses a
+ version string. -->
+ <div id="schedPresetRow" class="cz-control" data-ltx-only hidden>
<div class="cz-label">Speed
- <span class="cz-label-hint">4-step distill adapter · overrules Steps</span>
+ <span class="cz-label-hint">draft schedule · changes the take</span>
</div>
- <div class="pill-group cols-2" id="h3TurboGroup">
- <button type="button" class="pill-btn active" data-h3-turbo="0"
- title="This shape's own sampler — its tuned sigma points per window.">
- <span>Standard</span><span class="sub" id="h3StdPillSub"></span>
+ <div class="pill-group cols-2" id="schedPresetGroup">
+ <button type="button" class="pill-btn active" data-sched-preset=""
+ title="The tuned schedule every graded 2.5 clip runs (8+2 forwards).">
+ <span>Tuned</span>
+ <span class="sub" id="schedTunedSub">default schedule</span>
</button>
- <button type="button" class="pill-btn" data-h3-turbo="1" id="h3TurboPill">
- <span>Turbo</span><span class="sub" id="h3TurboPillSub"></span>
+ <button type="button" class="pill-btn" data-sched-preset="fast"
+ title="The engine's fast draft schedule (5+2 forwards). Renders a DIFFERENT take — the same prompt and seed land on a different shot than Tuned, so use it to explore, then re-render keepers on Tuned.">
+ <span>Fast draft</span>
+ <span class="sub" id="schedFastSub">different take</span>
</button>
</div>
- <div class="h3-turbo-note" id="h3TurboNote" hidden></div>
</div>
+ <div>
+ <div class="qs-label">
+ <span class="qs-name" id="qualityLabelName">Quality</span>
+ <span class="qs-meta" id="qualityMeta"></span>
+ </div>
+ <!-- Compact 4-col strip. Each chip carries name + a single spec
+ line. Same data-quality wiring as before so setQuality()
+ keeps working unchanged. The .pill-btn class is preserved
+ for the click handler that filters by it.
+ When a character is selected in the Characters chip strip,
+ selectManualCharacter() hides this strip and reveals the
+ character-only strip below. Its Draft/Pro rows use q8 distilled,
+ while its High rows use the real q8 HQ lane; no character chip
+ ever falls through to the ordinary q4 quality strip. -->
+ <!-- LTX's CANVAS axis. Rendered by renderTierAxes('ltx') from
+ BOOT.ltx.qualities / .lengths / .tiers, exactly as H3's two
+ strips are, so the server-side table is the single source of
+ truth for geometry and every estimate.
+
+ These four chips used to be static markup carrying hand-written
+ subtitles ("Q4 · 5 min", "Q8 Pro · 7 min") kept up to date by two
+ separate JS updaters — numbers no measurement on 2.5 supported.
+ The table fills the third slot now, the way H3's already did, and
+ both updaters are deleted.
+
+ `data-quality` is UNCHANGED: five surfaces read it (the click
+ handler, setQuality's active toggle, applyTierTimes, the
+ trained-LoRA compatibility gate, the character-strip swap). -->
+ <div class="quality-strip pill-group" id="qualityGroup" data-ltx-only></div>
+ <!-- LTX's DURATION axis — the same second row H3 grew, for the same
+ reason: a canvas and a length are independent choices and one
+ strip cannot express both. Duration used to be a free numeric
+ field whose value one lane silently rounded away. The field
+ itself is not deleted (power users have shipped work with it);
+ it lives in Customize and a value off the axis lights no chip. -->
+ <div class="ltx-axes" id="ltxAxes" data-ltx-only>
+ <div class="qs-label h3-axis-label">
+ <span class="qs-name">Length</span>
+ <span class="qs-meta" id="ltxLengthMeta"></span>
+ </div>
+ <div class="quality-strip pill-group" id="ltxLengthGroup"></div>
+ </div>
+ <!-- Character-only quality strip — revealed by selectManualCharacter.
+ Rendered entirely from BOOT.ltx.character so the Manual surface
+ and Characters tab expose the same generation-specific tokens. -->
+ <!-- data-ltx-only for a reason the `hidden` attribute can't cover:
+ its visibility is owned by _applyCharacterQualityStripVisibility,
+ which only ever asks "is a character selected?". With a character
+ active, switching to H3 left this strip lit BESIDE the H3 tier
+ strip — two primary strips, both claiming to set the render. The
+ fold rule settles it declaratively, whatever the JS believes. -->
+ <div class="quality-strip pill-group" id="qualityGroupCharacter" hidden data-ltx-only></div>
+ <!-- Hailuo H3 render shape — TWO INDEPENDENT AXES, not one fixed tier
+ menu. This shipped as six baked combinations (Draft 3s, HQ 3s,
+ HQ 5s, Wide 5s, Long 10s, Long 15s) and the owner's report was
+ exact: "somebody may want to run the HQ 5s version for 10s, and
+ it's now not possible from the UI." The matrix was mostly empty —
+ our best canvas, the only true 16:9, could only produce 5-second
+ clips — and nothing technical said so. Chained windows keep memory
+ flat per window, so every canvas reaches every length.
+
+ So: Quality picks the CANVAS (Draft 640×384 · Standard 768×448
+ · High 1024×576 · Native 1344×768, the model's own ceiling),
+ Length picks the DURATION (3s · 5s · 10s · 15s), and they don't
+ know about each other. Both strips reuse the LTX
+ .quality-strip visual language (separate elements, so neither
+ engine's chips can ever be half-lit) and both are rendered by
+ renderH3Axes() from BOOT.h3.qualities / .lengths / .tiers — the
+ server-side tables stay the single source of truth for geometry,
+ steps and every estimate, so a change is one Python edit.
+
+ The outer id is UNCHANGED (#h3TierGroup): the engine registry row
+ names it as H3's `strip` and setEngine's generic surface-swap
+ hides it by id. It is now a wrapper around the two strips rather
+ than a strip itself. -->
+ <div class="h3-axes" id="h3TierGroup" hidden>
+ <div class="quality-strip pill-group" id="h3QualityGroup"></div>
+ <div class="qs-label h3-axis-label" id="h3LengthLabel">
+ <span class="qs-name">Length</span>
+ <span class="qs-meta" id="h3LengthMeta"></span>
+ </div>
+ <div class="quality-strip pill-group" id="h3LengthGroup"></div>
+ </div>
+ </div>
+
+ <!-- ========== H3 PRIMARY CONTROLS — Speed + Steps ==========
+ These two shipped inside the Customize disclosure and the owner
+ could not find Steps at all: "I see you removed the step options
+ we had before, no?" He hadn't lost a control, he'd lost a
+ control's VISIBILITY, and the diagnosis matters — the rule that
+ put them there was "LTX keeps its secondary knobs in Customize,
+ so H3 should too", applied without checking whether they are
+ secondary on this engine. They are not. Quality picks the canvas
+ and Length picks the duration; Turbo (4-step distill adapter) and
+ Steps (9 → 20 sigma points) are what decide how long you wait,
+ each worth about a 2× swing, and neither is implied by either
+ axis. A control that changes wall clock by 2× does not belong
+ behind a disclosure triangle.
+ So they sit here, directly under the two strips they modify,
+ in the same chip grammar as the rest of the form. Nothing else
+ moved: same ids, same .cz-* classes, same handlers, same hidden
+ inputs (#h3_turbo / #h3_steps, both in the make_job allowlist).
+ .eng-primary is only a CSS hook — the active-pill accent rules
+ were scoped to .cz-body, so leaving Customize would otherwise
+ have cost these chips their engine colour. Order is deliberate:
+ Speed first because Turbo OVERRULES Steps. -->
+ <div class="eng-primary" id="h3PrimaryControls" data-h3-only>
+ <!-- The Standard | Turbo Speed row that lived here is folded into
+ the Speed switch above the Quality cards (#h3SpeedRow): Fast
+ replaces Turbo, Best is the shape's own sampler. -->
+
+ <!-- Adapter slot. Appears ONLY when the conflict is real — Turbo
+ selected AND a LoRA picked — because H3's runner has exactly
+ one `--lora` and there is nothing to decide until both want
+ it. Rendered by renderH3LoraSlot() from BOOT.h3.loras so the
+ sentence explaining the constraint comes from Python, next to
+ the constant that encodes it. The alternative (silently
+ preferring one) is the failure this control exists to
+ prevent: a render that quietly ignored the LoRA you picked,
+ or quietly dropped the Turbo you asked for. -->
+ <div class="cz-control" id="h3LoraSlotRow" data-h3-only hidden>
+ <div class="cz-label">Adapter
+ <span class="cz-label-hint">one slot · Turbo or your LoRA</span>
+ </div>
+ <div class="pill-group cols-2" id="h3LoraSlotGroup">
+ <button type="button" class="pill-btn active" data-h3-lora-slot="turbo"
+ title="Spend the slot on Turbo. Your picked LoRA won't render — the job stops and says so rather than silently dropping it.">
+ <span>Turbo</span>
+ </button>
+ <button type="button" class="pill-btn" data-h3-lora-slot="user" id="h3LoraSlotUserPill">
+ <span>My LoRA</span><span class="sub" id="h3LoraSlotUserSub"></span>
+ </button>
+ </div>
+ <div class="h3-turbo-note" id="h3LoraSlotNote"></div>
+ </div>
- <!-- Adapter slot. Appears ONLY when the conflict is real — Turbo
- selected AND a LoRA picked — because H3's runner has exactly
- one `--lora` and there is nothing to decide until both want
- it. Rendered by renderH3LoraSlot() from BOOT.h3.loras so the
- sentence explaining the constraint comes from Python, next to
- the constant that encodes it. The alternative (silently
- preferring one) is the failure this control exists to
- prevent: a render that quietly ignored the LoRA you picked,
- or quietly dropped the Turbo you asked for. -->
- <div class="cz-control" id="h3LoraSlotRow" data-h3-only hidden>
- <div class="cz-label">Adapter
- <span class="cz-label-hint">one slot · Turbo or your LoRA</span>
+ <!-- H3 sampler depth. Cells bake 9 steps (8 forwards per window),
+ except High and dense 10 s, which bake 16 (15 forwards) — High
+ since the 2026-09-16 gym A/B; the official
+ reference recipe runs 20. Four honest pills beat an unbounded
+ numeric box, and the chips above re-price live when one is
+ pinned, so the multiplier does not have to live in a tooltip. -->
+ <div class="cz-control" id="h3StepsRow" data-h3-only>
+ <div class="cz-label">Steps
+ <span class="cz-label-hint">Auto = this shape's tuned count</span>
+ </div>
+ <div class="pill-group cols-4" id="h3StepsGroup">
+ <button type="button" class="pill-btn active" data-h3-steps="auto"
+ title="This shape's tuned count — the validated speed/quality point.">Auto</button>
+ <button type="button" class="pill-btn" data-h3-steps="12"
+ title="More refinement — ~1.4× the render time. The Quality and Length chips re-price when you pin it.">12</button>
+ <button type="button" class="pill-btn" data-h3-steps="16"
+ title="~1.9× the render time. The Quality and Length chips re-price when you pin it.">16</button>
+ <button type="button" class="pill-btn" data-h3-steps="20"
+ title="The official reference recipe — ~2.4× the render time.">20</button>
+ </div>
</div>
- <div class="pill-group cols-2" id="h3LoraSlotGroup">
- <button type="button" class="pill-btn active" data-h3-lora-slot="turbo"
- title="Spend the slot on Turbo. Your picked LoRA won't render — the job stops and says so rather than silently dropping it.">
- <span>Turbo</span>
+ </div>
+
+ <!-- ============== ORIENTATION (compact, top-level) ==============
+ Lifted out of the Customize accordion so users don't have to
+ dig for it. Compact 2-pill row reusing the same id="aspect"
+ hidden input + id="aspectGroup" click delegation + id="aspectRow"
+ 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;">
+ <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-h3-lora-slot="user" id="h3LoraSlotUserPill">
- <span>My LoRA</span><span class="sub" id="h3LoraSlotUserSub"></span>
+ <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>
</div>
- <div class="h3-turbo-note" id="h3LoraSlotNote"></div>
+ <input type="hidden" name="aspect" id="aspect" value="landscape">
</div>
-
- <!-- H3 sampler depth. Cells bake 9 steps (8 forwards per window),
- except High and dense 10 s, which bake 16 (15 forwards) — High
- since the 2026-09-16 gym A/B; the official
- reference recipe runs 20. Four honest pills beat an unbounded
- numeric box, and the chips above re-price live when one is
- pinned, so the multiplier does not have to live in a tooltip. -->
- <div class="cz-control" id="h3StepsRow" data-h3-only>
- <div class="cz-label">Steps
- <span class="cz-label-hint">Auto = this shape's tuned count</span>
+ <!-- H3 orientation. Every H3 canvas ships landscape, which made
+ vertical social formats unreachable on this engine. Portrait
+ is the SAME canvas rotated — identical pixel count, identical
+ packed rows, so the tier chip's measured estimate stays true
+ and no new cell is invented. Applied where make_job stamps the
+ cell's geometry; `h3_tier` (the wire format every sidecar
+ carries) is untouched. -->
+ <div class="cz-control" id="h3OrientationRow" data-h3-only>
+ <div class="cz-label">Orientation
+ <span class="cz-label-hint">portrait rotates the tier's canvas — same cost</span>
</div>
- <div class="pill-group cols-4" id="h3StepsGroup">
- <button type="button" class="pill-btn active" data-h3-steps="auto"
- title="This shape's tuned count — the validated speed/quality point.">Auto</button>
- <button type="button" class="pill-btn" data-h3-steps="12"
- title="More refinement — ~1.4× the render time. The Quality and Length chips re-price when you pin it.">12</button>
- <button type="button" class="pill-btn" data-h3-steps="16"
- title="~1.9× the render time. The Quality and Length chips re-price when you pin it.">16</button>
- <button type="button" class="pill-btn" data-h3-steps="20"
- title="The official reference recipe — ~2.4× the render time.">20</button>
+ <input type="hidden" name="h3_orientation" id="h3_orientation" value="landscape">
+ <div class="pill-group cols-2" id="h3OrientationGroup">
+ <button type="button" class="pill-btn active" data-h3-orientation="landscape"
+ title="The tier's canvas as trained and measured — e.g. 1024×576.">
+ <span>Landscape</span><span class="sub" id="h3OrientLandSub">16:9-ish</span>
+ </button>
+ <button type="button" class="pill-btn" data-h3-orientation="portrait"
+ title="The same canvas rotated for vertical/social — e.g. 576×1024. Same pixel budget, same wall clock.">
+ <span>Portrait</span><span class="sub" id="h3OrientPortSub">vertical / social</span>
+ </button>
</div>
</div>
- </div>
-
- <!-- Export used to sit here too, as a third flat pill row with
- hand-rolled inline styles and its note floating loose beneath
- it. It is now a .cz-control inside the SAME Customize disclosure
- LTX uses (grep h3ExportRow) — one information architecture, one
- chip grammar, one summary line, so the two engines read as one
- product. Export earns the demotion that Speed and Steps did not:
- it is an ffmpeg scale-and-pad pass AFTER the render, so it costs
- no wall clock and changes no pixel the model produced. The
- hidden inputs for all three live up in the engine-state block;
- every one is in the make_job allowlist, which is the only place
- they could silently die. -->
- <!-- The skip-step toggle (and its charSkipstepToggle legacy stub)
- is gone as of v4.0.5 — the control was dead at the engine
- boundary; see the HQ-speed removal note in Customize. -->
- </div>
-
- <!-- ============== ORIENTATION (compact, top-level) ==============
- Lifted out of the Customize accordion so users don't have to
- dig for it. Compact 2-pill row reusing the same id="aspect"
- hidden input + id="aspectGroup" click delegation + id="aspectRow"
- 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;">
- <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>
- </div>
- <input type="hidden" name="aspect" id="aspect" value="landscape">
- </div>
- <div class="mode-only show" id="quickMetricsRow">
- <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.">
+ <div class="mode-only show" id="quickMetricsRow">
+ <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.">
+ </div>
+ </div>
</div>
</div>
- </div>
+ </details>
+ <!-- The selected cell's honest notes, joined — the mirror of
+ #h3TierNote. Empty and hidden when the combination has nothing
+ to warn about, which is most of them. -->
+ <div class="engine-hint" id="ltxTierNote" hidden></div>
+ <!-- Honest artefact notes for the selected combination. Rendered from
+ the cell's `notes` list (server-side), so a Draft 10 s clip is
+ told BOTH that 0.25 MP doesn't resolve faces and that one prompt
+ is asked of every 5 s window. The chained warning now fires at any
+ quality, because chaining is now available at any quality. The
+ chained sentence now POINTS AT the control below instead of only
+ warning; h3_visible_tiers() swaps the old warning back in for a
+ pack whose runner has no --chain-prompts. -->
+ <div class="engine-hint" id="h3TierNote" data-h3-only hidden></div>
</div>
<!-- Characters picker MOVED to the top of the form (right after
@@ -1343,8 +1408,13 @@
Collapsible because most users won't touch it on a given
session, and inline because hiding it behind a modal makes
- it easy to forget. Default open so first-time users see what's
- inside without hunting for the disclosure triangle. -->
+ it easy to forget. CLOSED by default since the 2026-09-18 layout
+ pass — it shipped open, which meant an empty list and its
+ four-line "drop .safetensors files here" empty state were the
+ tallest thing on the form for every user who owns no LoRAs. The
+ summary still carries the state ("none active" / "2 active"), and
+ the paths that add one (Browse CivitAI, Import H3 LoRA) open the
+ section themselves. -->
<div class="form-divider"></div>
<!-- NOT `data-ltx-only` any more (2026-08-09): H3 takes LoRAs too, out
of its own library, so the picker is shared and its visibility is
@@ -1353,7 +1423,7 @@
"one engine" but not "any engine whose installed pack has --lora",
which is the actual condition. -->
<div id="loraPickerVideoSlot">
- <details id="lorasDetails" open class="loras-section">
+ <details id="lorasDetails" class="loras-section">
<summary class="loras-summary">
<span class="loras-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
<span class="loras-title">LoRAs</span>
@@ -1372,12 +1442,12 @@
<input type="file" id="h3LoraImportFile" accept=".safetensors,application/octet-stream" hidden
onchange="importH3Lora(this.files[0]); this.value = ''">
<button type="button" class="loras-browse-btn is-ghost" id="h3LoraImportBtn" hidden
- title="Import a .safetensors H3 LoRA you already have"
- onclick="event.stopPropagation(); event.preventDefault(); document.getElementById('h3LoraImportFile').click()"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-folder-simple"/></svg>Import H3 LoRA</button>
+ title="Import H3 LoRA — a .safetensors file you already have"
+ onclick="event.stopPropagation(); event.preventDefault(); document.getElementById('h3LoraImportFile').click()"><svg class="ph" aria-hidden="true"><use href="#ph-folder-simple"/></svg>Import</button>
<button type="button" class="loras-browse-btn"
- onclick="event.stopPropagation(); event.preventDefault(); openCivitaiModal()"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-magnifying-glass"/></svg>Browse CivitAI</button>
- <button type="button" class="loras-browse-btn is-ghost" id="loraUpdatesBtn" title="Ask CivitAI whether any installed LoRA has a newer version"
- onclick="event.stopPropagation(); event.preventDefault(); checkLoraUpdates()">Check for updates</button>
+ onclick="event.stopPropagation(); event.preventDefault(); openCivitaiModal()"><svg class="ph" aria-hidden="true"><use href="#ph-magnifying-glass"/></svg>Browse CivitAI</button>
+ <button type="button" class="loras-browse-btn is-ghost" id="loraUpdatesBtn" title="Check for updates — ask CivitAI whether any installed LoRA has a newer version"
+ onclick="event.stopPropagation(); event.preventDefault(); checkLoraUpdates()">Updates</button>
</span>
</summary>
<div class="loras-body" id="lorasBody">
@@ -1416,28 +1486,32 @@
<input type="hidden" name="steps" id="steps" value="8">
- <!-- ============== UNIFIED CUSTOMIZE DISCLOSURE ==============
- Folds together the old "Customize" (aspect, dims, speed,
- long-clips, export, method) and "Advanced" (audio source,
- open-when-done) into ONE collapsed disclosure. Power users
- open it; beginners ignore it. The summary line shows the
- effective state so power users can scan at a glance.
-
- Lives at form level (not mode-conditional) — its inner rows
- manage their own visibility (e.g. dimsRow stays visible in all flows now;
- i2vAudioModeSection only shows for I2V; method only shows
- when an upscale is active). The wrapping #sizingSection
- class kept for the mode-only show/hide that still toggles
- it for Extend (Extend supplies its own duration/etc). -->
+
+ <!-- ============== AFTER THE RENDER · ADVANCED ==============
+ One "Customize" grab-bag used to hold H3 orientation, both engines'
+ export pills, the upscale method, width × height, duration/frames, the
+ schedule preset, STG, long clips, the I2V audio source and "open file
+ when done" — ten unrelated decisions behind one word. Split by what the
+ user is DECIDING, not by which engine owns the feature:
+ · After the render — what happens to the file once the model is
+ done: the export size on either engine, how the upscale is done,
+ the optional Upscale & Face Fix job, open when done. None of it
+ changes a pixel the model produced.
+ · Advanced — the overrides that DO change the render and that most
+ users should never touch: raw canvas, raw frames, detail guidance,
+ long-clip strategy, external I2V audio.
+ Orientation and the LTX schedule preset left for Shot setup (they are
+ part of the shape). Everything else kept its id, its field name, its
+ handler and its default. #sizingSection still wraps both, so the
+ mode-only show/hide that folds this away for Extend keeps working. -->
<div class="mode-only" id="sizingSection">
- <details id="customizeDetails" class="customize-section">
+ <details id="finishDetails" class="customize-section">
<summary class="cz-summary">
<span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
- <span class="cz-title">Customize</span>
- <span class="cz-meta" id="customizeSummary">16:9 · default speed</span>
+ <span class="cz-title">After the render</span>
+ <span class="cz-meta" id="finishSummary">native export</span>
</summary>
<div class="cz-body">
-
<!-- ========== HAILUO H3 CONTROLS ==========
What is left of the H3 half of Customize is EXPORT, and only
export. Speed and Steps used to live here too, on the LTX-parity
@@ -1454,30 +1528,6 @@
control below it, folded away on any other engine by
data-h3-only (rule emitted from the ENGINES table). -->
- <!-- H3 orientation. Every H3 canvas ships landscape, which made
- vertical social formats unreachable on this engine. Portrait
- is the SAME canvas rotated — identical pixel count, identical
- packed rows, so the tier chip's measured estimate stays true
- and no new cell is invented. Applied where make_job stamps the
- cell's geometry; `h3_tier` (the wire format every sidecar
- carries) is untouched. -->
- <div class="cz-control" id="h3OrientationRow" data-h3-only>
- <div class="cz-label">Orientation
- <span class="cz-label-hint">portrait rotates the tier's canvas — same cost</span>
- </div>
- <input type="hidden" name="h3_orientation" id="h3_orientation" value="landscape">
- <div class="pill-group cols-2" id="h3OrientationGroup">
- <button type="button" class="pill-btn active" data-h3-orientation="landscape"
- title="The tier's canvas as trained and measured — e.g. 1024×576.">
- <span>Landscape</span><span class="sub" id="h3OrientLandSub">16:9-ish</span>
- </button>
- <button type="button" class="pill-btn" data-h3-orientation="portrait"
- title="The same canvas rotated for vertical/social — e.g. 576×1024. Same pixel budget, same wall clock.">
- <span>Portrait</span><span class="sub" id="h3OrientPortSub">vertical / social</span>
- </button>
- </div>
- </div>
-
<!-- H3 export canvas. Most tiers render 12:7 (768×448), which is
neither 720p nor 1080p; this runs the SAME lanczos-fit + pad +
libx264 pass an LTX render gets, keeping the native file on
@@ -1521,15 +1571,154 @@
it. Stored as h3_upscale = "ltx_x2" (sidecars, Load Params
and the API are unchanged); a checkbox because it is an
extra job, not a size. -->
- <label class="check h3-facefix-after" id="h3FaceFixAfterRow"
+ <div class="cz-note" id="h3ExportNote" hidden></div>
+ <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).">
<input type="checkbox" id="h3FaceFixAfter" onchange="setH3FaceFixAfter(this.checked)">
<span>Also run <b>Upscale &amp; Face Fix</b> after the draft
- <span class="cz-label-hint">optional · 2× · face and sound kept · about the draft's time again</span></span>
+ <span class="cz-label-hint" id="h3FaceFixEta">optional · 2× · face and sound kept · about the draft's time again</span></span>
</label>
- <div class="cz-note" id="h3ExportNote" hidden></div>
+ </div>
+ <!-- Export upscale — target dims after render. "720p fit"
+ preserves aspect ratio (no crop, no distortion). 2× doubles
+ each side. Native skips the upscale entirely. The "Method"
+ row below picks how the upscaling is done. -->
+ <div class="cz-control" data-ltx-only>
+ <div class="cz-label">Export
+ <span class="cz-label-hint">post-render, no crop</span>
+ </div>
+ <div class="pill-group cols-3" id="upscaleGroup">
+ <button type="button" class="pill-btn active" data-upscale="off"><span>Native</span><span class="sub">as generated</span></button>
+ <button type="button" class="pill-btn" data-upscale="fit_720p"><span>720p fit</span><span class="sub">scale + pad</span></button>
+ <button type="button" class="pill-btn" data-upscale="x2"><span>2×</span><span class="sub">same ratio</span></button>
+ </div>
+ </div>
+ <!-- Upscale method. Hidden when Export = Native. Fast = ffmpeg
+ Lanczos resize, no detail recovery, near-instant. Sharp =
+ PiperSR/CoreML 2× post-upscale on Apple Neural Engine, then
+ ffmpeg fit/export. The old LTX latent upscaler path remains
+ hidden behind LTX_ENABLE_MODEL_UPSCALE for lab archaeology. -->
+ <div class="cz-control" id="upscaleMethodRow" data-ltx-only style="display:none;">
+ <div class="cz-label">Method
+ <span class="cz-label-hint">how the upscale is done</span>
+ </div>
+ <div class="pill-group cols-2" id="upscaleMethodGroup">
+ <button type="button" class="pill-btn active" data-method="lanczos"><span>Fast</span><span class="sub">ffmpeg Lanczos · instant</span></button>
+ <button type="button" class="pill-btn" data-method="pipersr"><span>Sharp</span><span class="sub">PiperSR ANE · +30-90 s</span></button>
+ </div>
+ <input type="hidden" name="upscale_method" id="upscale_method" value="lanczos">
+ </div>
+ <!-- Open file when done — minor convenience. Was its own row
+ in the old Advanced disclosure; now folded inline. -->
+ <div class="cz-control">
+ <label class="check" style="margin:0">
+ <input type="checkbox" name="open_when_done" id="open_when_done"> Open file when done
+ </label>
+ </div>
+ <!-- Export used to sit here too, as a third flat pill row with
+ hand-rolled inline styles and its note floating loose beneath
+ it. It is now a .cz-control inside the SAME Customize disclosure
+ LTX uses (grep h3ExportRow) — one information architecture, one
+ chip grammar, one summary line, so the two engines read as one
+ product. Export earns the demotion that Speed and Steps did not:
+ it is an ffmpeg scale-and-pad pass AFTER the render, so it costs
+ no wall clock and changes no pixel the model produced. The
+ hidden inputs for all three live up in the engine-state block;
+ every one is in the make_job allowlist, which is the only place
+ they could silently die. -->
+ <!-- The skip-step toggle (and its charSkipstepToggle legacy stub)
+ is gone as of v4.0.5 — the control was dead at the engine
+ boundary; see the HQ-speed removal note in Customize. -->
+ </div>
+ </details>
+ <!-- ============== BATCH ==============
+ Owner, 2026-09-18: "batch is kind of hidden, and it should probably
+ be re-taught in a way that is more user-friendly and also more
+ highlighted. It should be a section, actually, after the render and
+ setup."
+
+ It was a 60-px pill in the queue strip that opened a modal holding
+ one textarea and the sentence "split prompts with --- on its own
+ line" — a power feature behind a door nobody opens, with a
+ convention nobody guesses. Now it is a row of the same stack, it
+ says how many jobs it is about to queue BEFORE you press anything,
+ and it offers the two things people actually batch:
+
+ Many prompts — the --- paste, with a live count and the first
+ line of each prompt listed back, so a paste that
+ split wrong is visible instead of discovered in
+ the queue.
+ Same prompt — N takes of what is in the prompt box, each with
+ its own random seed. This is what judging a
+ prompt needs, and doing it by hand meant pasting
+ the same paragraph N times.
+
+ Queue-all is inside the section, next to the count. The old pill
+ stays in the queue strip and now opens THIS, not a modal — one
+ door, two handles. -->
+ <details id="batchDetails" class="customize-section batch-section">
+ <summary class="cz-summary">
+ <span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
+ <span class="cz-title">Batch</span>
+ <span class="cz-meta" id="batchSummary">one render at a time</span>
+ </summary>
+ <div class="cz-body">
+ <div class="cz-label">What varies
+ <span class="cz-label-hint">one job per prompt, or one prompt many times</span>
+ </div>
+ <div class="pill-group cols-2" id="batchModeGroup">
+ <button type="button" class="pill-btn active" data-batch-mode="prompts"
+ onclick="setBatchMode('prompts')">Many prompts
+ <span class="sub">one job per prompt</span></button>
+ <button type="button" class="pill-btn" data-batch-mode="seeds"
+ onclick="setBatchMode('seeds')">Same prompt
+ <span class="sub">N takes, new seed each</span></button>
</div>
+ <div id="batchPromptsWrap">
+ <textarea class="batch" id="batchPrompts" rows="7"
+ oninput="updateBatchSummary()"
+ placeholder="Paste your prompts here, with a line containing only three dashes between them:
+
+A wizard lights a lantern in a dark forest. Audio: wind, a match striking.
+
+---
+
+The same wizard walks out of frame. Audio: footsteps on leaves."></textarea>
+ <div class="hint" id="batchCount">Nothing pasted yet.</div>
+ </div>
+
+ <div id="batchSeedsWrap" hidden>
+ <div class="cz-label">Takes
+ <span class="cz-label-hint" id="batchTakesNote"></span>
+ </div>
+ <div class="pill-group cols-5" id="batchTakesGroup">
+ <button type="button" class="pill-btn" data-batch-takes="2" onclick="setBatchTakes(2)">2</button>
+ <button type="button" class="pill-btn active" data-batch-takes="3" onclick="setBatchTakes(3)">3</button>
+ <button type="button" class="pill-btn" data-batch-takes="4" onclick="setBatchTakes(4)">4</button>
+ <button type="button" class="pill-btn" data-batch-takes="6" onclick="setBatchTakes(6)">6</button>
+ <button type="button" class="pill-btn" data-batch-takes="8" onclick="setBatchTakes(8)">8</button>
+ </div>
+ <div class="hint" id="batchSeedsHint">Every take uses the prompt above with a fresh random seed.</div>
+ </div>
+
+ <div class="batch-actions">
+ <span class="batch-total" id="batchTotal"></span>
+ <button type="button" class="batch-queue-btn" id="batchQueueBtn"
+ onclick="queueBatch()">Queue batch</button>
+ </div>
+ <div class="hint">Auto-open is forced off for a batch, and the queue
+ runs them one after another — you can keep working while it does.</div>
+ </div>
+ </details>
+
+ <details id="customizeDetails" class="customize-section">
+ <summary class="cz-summary">
+ <span class="cz-chevron" aria-hidden="true"><svg class="ph"><use href="#ph-caret-down-bold"/></svg></span>
+ <span class="cz-title">Advanced</span>
+ <span class="cz-meta" id="customizeSummary"></span>
+ </summary>
+ <div class="cz-body">
<!-- Width × height. Setting custom dimensions makes the form
leave the active preset (the Quality pill stays highlighted
but the Customize summary shows "custom" so the user knows
@@ -1558,7 +1747,6 @@
<div><input name="height" id="height" value="576" type="number" min="64" step="64" aria-label="Height"></div>
</div>
</div>
-
<!-- Duration / Frames — the power-user override, MOVED HERE in
v4.0 (spec §2.2). It used to sit in the primary form ~60 px
under the Length chips, which meant the panel showed a
@@ -1578,7 +1766,6 @@
<div><input name="frames" id="frames" value="121" type="number" min="1" aria-label="Frames" title="Must be 8k+1 (e.g., 121, 161, 201). Duration auto-syncs."></div>
</div>
</div>
-
<!-- 2026-05-17 (Codex C+ pass 5): the Speed (Boost/Turbo)
acceleration row used to live here. Killed from the public
surface — it's a Q4-distilled-pipeline-only knob; the Q8
@@ -1598,7 +1785,6 @@
<button type="button" class="pill-btn" data-accel="turbo">Turbo</button>
</div>
</div>
-
<!-- HQ speed (Fast/Exact) REMOVED in v4.0.5. The 2026-05-15
skip-step patch it described belongs to the pre-vendored
engine era: the pinned port's `generate_and_save` accepts
@@ -1610,35 +1796,6 @@
support exists (`MultiModalGuiderParams.skip_step`); if it is
ever wired for real, rebenchmark and bring the control back
with a measured number, not this one. -->
-
- <!-- Speed — the LTX-2.5 distilled lane's REAL speed control
- (v4.0.5), replacing the dead one above. "Fast draft" selects
- the engine's named `fast` schedule preset: 5+2 forwards vs
- the tuned 8+2, ~13% faster, and it renders a DIFFERENT take
- (same prompt + seed land on a different shot) — which is why
- it sits next to draft affordances and never on a quality
- slider. Visibility is SERVER-OWNED: the row shows only when
- the current tier cell carries `fast_eta`, which the registry
- stamps only on 2.5 distilled cells — the UI never parses a
- version string. -->
- <div id="schedPresetRow" class="cz-control" data-ltx-only hidden>
- <div class="cz-label">Speed
- <span class="cz-label-hint">draft schedule · changes the take</span>
- </div>
- <div class="pill-group cols-2" id="schedPresetGroup">
- <button type="button" class="pill-btn active" data-sched-preset=""
- title="The tuned schedule every graded 2.5 clip runs (8+2 forwards).">
- <span>Tuned</span>
- <span class="sub" id="schedTunedSub">default schedule</span>
- </button>
- <button type="button" class="pill-btn" data-sched-preset="fast"
- title="The engine's fast draft schedule (5+2 forwards). Renders a DIFFERENT take — the same prompt and seed land on a different shot than Tuned, so use it to explore, then re-render keepers on Tuned.">
- <span>Fast draft</span>
- <span class="sub" id="schedFastSub">different take</span>
- </button>
- </div>
- </div>
-
<!-- STG (Spatio-Temporal Guidance) — "detail guidance". The Q8 HQ
res_2s guider adds stg_scale·(cond - perturbed) to the
prediction (guiders.py MultiModalGuider.calculate), which
@@ -1663,7 +1820,6 @@
<span class="characters-strength-value" id="stgScaleValue">Off</span>
</div>
</div>
-
<!-- Long Clip Boost — asks LTX 2.3 to generate fewer semantic
frames at 12fps, then exports a normal 24fps file with
motion interpolation. This is explicit because dialogue,
@@ -1698,38 +1854,6 @@
placeholder="what must not change between windows — one man, a grey room, soft window light">
</div>
</div>
-
- <!-- Export upscale — target dims after render. "720p fit"
- preserves aspect ratio (no crop, no distortion). 2× doubles
- each side. Native skips the upscale entirely. The "Method"
- row below picks how the upscaling is done. -->
- <div class="cz-control" data-ltx-only>
- <div class="cz-label">Export
- <span class="cz-label-hint">post-render, no crop</span>
- </div>
- <div class="pill-group cols-3" id="upscaleGroup">
- <button type="button" class="pill-btn active" data-upscale="off"><span>Native</span><span class="sub">as generated</span></button>
- <button type="button" class="pill-btn" data-upscale="fit_720p"><span>720p fit</span><span class="sub">scale + pad</span></button>
- <button type="button" class="pill-btn" data-upscale="x2"><span>2×</span><span class="sub">same ratio</span></button>
- </div>
- </div>
-
- <!-- Upscale method. Hidden when Export = Native. Fast = ffmpeg
- Lanczos resize, no detail recovery, near-instant. Sharp =
- PiperSR/CoreML 2× post-upscale on Apple Neural Engine, then
- ffmpeg fit/export. The old LTX latent upscaler path remains
- hidden behind LTX_ENABLE_MODEL_UPSCALE for lab archaeology. -->
- <div class="cz-control" id="upscaleMethodRow" data-ltx-only style="display:none;">
- <div class="cz-label">Method
- <span class="cz-label-hint">how the upscale is done</span>
- </div>
- <div class="pill-group cols-2" id="upscaleMethodGroup">
- <button type="button" class="pill-btn active" data-method="lanczos"><span>Fast</span><span class="sub">ffmpeg Lanczos · instant</span></button>
- <button type="button" class="pill-btn" data-method="pipersr"><span>Sharp</span><span class="sub">PiperSR ANE · +30-90 s</span></button>
- </div>
- <input type="hidden" name="upscale_method" id="upscale_method" value="lanczos">
- </div>
-
<!-- Audio source (I2V only) — folded in from the old separate
Advanced disclosure. Picker auto-hides when the current
mode isn't I2V (see updateDerived's mode-aware visibility). -->
@@ -1746,14 +1870,6 @@
<input name="audio" id="audio" placeholder="/path/to/your/track.wav">
</div>
</div>
-
- <!-- Open file when done — minor convenience. Was its own row
- in the old Advanced disclosure; now folded inline. -->
- <div class="cz-control">
- <label class="check" style="margin:0">
- <input type="checkbox" name="open_when_done" id="open_when_done"> Open file when done
- </label>
- </div>
</div>
</details>
@@ -1779,12 +1895,21 @@
primary touch target. -->
<div class="form-action-footer" id="formActionFooter">
<div class="queue-strip">
- <button type="button" class="qchip" onclick="openBatch()" title="Paste many prompts at once and queue them">⊞ Batch</button>
- <button type="button" class="qchip" id="pauseBtn" onclick="togglePause()" title="Pause / resume the render queue"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><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" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
+ <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>
<span class="qchip-spacer"></span>
<span class="qchip-derived" id="derivedFooter"></span>
</div>
+ <!-- The after-render Upscale & Face Fix, beside Generate (same state as
+ the checkbox under Upscale: h3_upscale = "ltx_x2"). The footer line
+ to the right of the queue chips prices the pair. -->
+ <label class="check h3-facefix-after h3-facefix-footer" id="h3FaceFixFooterRow" data-h3-only hidden
+ title="Queues a second job right after this render: the clip at twice the size with LTX-2.5 detail, the face and the sound kept. The original stays as rendered, next to it. Needs the 0.3 GB Upscale adapter (Settings → Models).">
+ <input type="checkbox" id="h3FaceFixFooter" onchange="setH3FaceFixAfter(this.checked)">
+ <span>Also run <b>Upscale &amp; Face Fix</b>
+ <span class="cz-label-hint" id="h3FaceFixFooterEta"></span></span>
+ </label>
<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>
@@ -1897,10 +2022,10 @@
<!-- Toolbar -->
<div class="ideo-toolbar">
<button type="button" class="qchip" id="ideoInsertTextBtn" onclick="ideoInsertBox('text')" title="Add a text box (or drag on an empty area of the frame)">
- <svg class="ph" aria-hidden="true" style="margin-right:5px;vertical-align:-2px"><use href="#ph-pencil-simple"/></svg>Insert text
+ <svg class="ph" aria-hidden="true"><use href="#ph-pencil-simple"/></svg>Insert text
</button>
<button type="button" class="qchip" id="ideoInsertObjBtn" onclick="ideoInsertBox('obj')" title="Add an object region (something the model should draw)">
- <svg class="ph" aria-hidden="true" style="margin-right:5px;vertical-align:-2px"><use href="#ph-image"/></svg>Insert object
+ <svg class="ph" aria-hidden="true"><use href="#ph-image"/></svg>Insert object
</button>
<span class="qchip-spacer"></span>
<label class="ideo-toolbar-toggle" title="Snap boxes to thirds / center / other boxes">
@@ -1908,7 +2033,7 @@
<span>Snap</span>
</label>
<button type="button" class="qchip" id="ideoUndoBtn" onclick="ideoUndo()" title="Undo (Cmd/Ctrl+Z)" disabled>
- <svg class="ph" aria-hidden="true" style="margin-right:5px;vertical-align:-2px"><use href="#ph-arrow-clockwise" style="transform:scaleX(-1);transform-origin:center"/></svg>Undo
+ <svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise" style="transform:scaleX(-1);transform-origin:center"/></svg>Undo
</button>
<select id="ideoExamplePicker" class="ideo-example-picker" onchange="ideoLoadExample(this.value); this.value='';" title="Load an example layout">
<option value="">Examples…</option>
@@ -1933,7 +2058,7 @@
</div>
</div>
<div class="ideo-stage-note" id="ideoStageNote">
- <svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-info"/></svg>
+ <svg class="ph" aria-hidden="true"><use href="#ph-info"/></svg>
Placement preview — boxes show where words sit; Ideogram renders the final type, weight, and texture.
</div>
@@ -1989,7 +2114,7 @@
<span class="ideo-insp-bbox" id="ideoInspBbox" title="bbox [y_min, x_min, y_max, x_max], 0–1000 row-first">bbox …</span>
<span class="qchip-spacer"></span>
<button type="button" class="qchip ideo-danger" onclick="ideoDeleteSel()" title="Delete this box (Delete key)">
- <svg class="ph" aria-hidden="true" style="margin-right:5px;vertical-align:-2px"><use href="#ph-trash-simple"/></svg>Delete
+ <svg class="ph" aria-hidden="true"><use href="#ph-trash-simple"/></svg>Delete
</button>
</div>
</div>
@@ -2150,9 +2275,9 @@
pills, never the primary touch target. -->
<div class="form-action-footer" id="formActionFooterStudio">
<div class="queue-strip">
- <button type="button" class="qchip" onclick="openBatch()" title="Paste many prompts at once and queue them">⊞ Batch</button>
- <button type="button" class="qchip" id="pauseBtnStudio" onclick="togglePause()" title="Pause / resume the render queue"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><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" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
+ <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>
<span class="qchip-spacer"></span>
</div>
<div class="actions">
@@ -2459,7 +2584,7 @@
<span class="train-counter-hint" id="trainCounterHint">need at least 15 to train</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" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear all</button>
+ <button type="button" class="qchip" id="trainClearAllBtn" onclick="trainClearAll()" hidden><svg class="ph" aria-hidden="true"><use href="#ph-x"/></svg>Clear all</button>
</div>
<!-- ============== BULK BUNDLE DROP ============== -->
@@ -2479,7 +2604,7 @@
<!-- ============== CAPTION FORMAT HINT ============== -->
<details class="train-caption-hint" id="trainCaptionHint">
<summary>
- <svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-info-fill"/></svg>
+ <svg class="ph" aria-hidden="true"><use href="#ph-info-fill"/></svg>
Caption format
<span class="train-caption-hint-eyebrow">LTX <code>[VISUAL]:</code> / <code>[TEXT]:</code></span>
</summary>
@@ -2508,7 +2633,7 @@
<button type="button" id="trainAutoCaptionBtn"
class="train-autocaption-btn"
onclick="trainAutoCaption()" disabled>
- <svg class="ph" aria-hidden="true" style="margin-right:8px;vertical-align:-2px"><use href="#ph-sparkle-fill"/></svg>
+ <svg class="ph" aria-hidden="true"><use href="#ph-sparkle-fill"/></svg>
<span id="trainAutoCaptionLabel">Auto-caption with Gemma 3</span>
</button>
<span class="train-autocaption-hint" id="trainAutoCaptionHint">
@@ -2716,8 +2841,8 @@
<!-- Sticky action footer — same chrome as the video/studio forms. -->
<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" style="margin-right:6px;vertical-align:-2px"><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" style="margin-right:6px;vertical-align:-2px"><use href="#ph-x"/></svg>Clear</button>
+ <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>
<span class="qchip-spacer"></span>
</div>
<div class="actions">
@@ -3331,6 +3456,37 @@ The last line"></textarea>
onclick="edAddTitle()"
title="Text over the picture, on the overlay lane at the playhead. Type it in the inspector; it is drawn by the render.">Add title</button>
</div>
+ <!-- ROOM TONE. "The cuts are very rough in terms of sound." A bed under
+ the whole film, made for this film (or from a preset), on its own
+ audio track. Shown on the Sound tab only; painted by edRtPaint. -->
+ <section class="ed-rt" id="edRoomTone" hidden aria-labelledby="edRtTitle">
+ <div class="ed-rt-head">
+ <span class="ed-rt-title" id="edRtTitle">Room tone</span>
+ <span class="ed-rt-status" id="edRtStatus"></span>
+ </div>
+ <p class="ed-rt-sub">Background noise under the whole __SEQ__, so cuts never drop to silence.</p>
+ <select class="sb-input ed-rt-pick" id="edRtVariant" aria-label="Which room tone"
+ onchange="edRtPick()"></select>
+ <label class="ed-rt-level" title="How loud the bed plays, in LUFS. Dialogue sits around −16; −27 is clearly there without competing. The render applies exactly this.">
+ <span>Level</span>
+ <input type="range" id="edRtLevel" min="-45" max="-18" step="1" value="-27"
+ aria-label="Room tone level in LUFS"
+ oninput="edRtLevelSlide(this.value)" onchange="edRtLevelCommit(this.value)">
+ <output id="edRtLevelOut">−27 LUFS</output>
+ </label>
+ <div class="ed-rt-acts">
+ <button type="button" class="ghost-btn primary" id="edRtAdd" onclick="edRtApply('apply')">Add room tone</button>
+ <button type="button" class="ghost-btn" id="edRtTake" hidden onclick="edRtApply('take')"
+ title="Another version of the same sound — a new take every click">New take</button>
+ <button type="button" class="ghost-btn" id="edRtRemoveBtn" hidden onclick="edRtRemove()"
+ title="Take the room tone off this __SEQ__. Undo brings it back.">Remove</button>
+ </div>
+ <p class="ed-rt-note" id="edRtNote" hidden></p>
+ <label class="check ed-rt-auto" title="When the Editor cuts a __SEQ__ by itself (first open, Re-cut, Storyboard's automatic film) it lays a room tone made from the __SEQ__'s own clips.">
+ <input type="checkbox" id="edRtAutoBox" checked onchange="edRtAuto(this.checked)">
+ <span>Add room tone to automatic cuts</span>
+ </label>
+ </section>
<select class="sb-input ed-pool-film" id="edPoolFilm" hidden
onchange="edPoolPickFilm(this.value)"
aria-label="Which __SEQ__ to take clips from"></select>
@@ -3837,7 +3993,53 @@ The last line"></textarea>
AFTER losing something. This says it in the one place a person
already looks to find out whether their work is safe. -->
<span class="sbe-protected" id="sbeProtected" hidden></span>
+ <!-- THE SNAPSHOT, AS A CHIP. It used to be a whole row under the header
+ ("Unsaved snapshot · open") for as long as a backup existed, which
+ was most of the time. Now it is a chip in the status area; click
+ it and the full offer drops in below the header. -->
+ <button type="button" class="sbe-chipbtn sbe-snapchip" id="sbeRecoverChip" hidden
+ onclick="sbeNoticeOpen('sbeRecover')"
+ title="A snapshot of unsaved work exists — click to see it and open it from Drafts">
+ <svg class="sbe-cbar-i"><use href="#ic-history"/></svg><b>snapshot</b></button>
<span class="ch-spacer" style="flex:1 1 auto"></span>
+ <!-- VIEW — WHAT IS ON THE SCREEN, in one place. "The on/off toggles for
+ the screen panels are a good idea but it's not clear." They were
+ four icons in three rows (under the picture, on the tool row, in
+ this header); now they are one labelled group, each a toggle that
+ is FILLED while its panel is showing, and a tooltip that names what
+ appears or disappears and the key. Full screen is the one action in
+ the group, so it has no label and no pressed state. -->
+ <span class="sbe-view" id="sbeView" role="group" aria-label="View">
+ <button type="button" class="sbe-vbtn" id="sbeSrcBtn" onclick="sbeSrcMonToggle()"
+ aria-label="Source monitor" aria-pressed="false"
+ title="Source monitor — the left screen, where a clip from the media pool plays before it goes on the timeline">
+ <svg class="sbe-cbar-i"><use href="#ic-source"/></svg><b>Source</b></button>
+ <button type="button" class="sbe-vbtn" id="sbeInspectBtn" onclick="sbeInspectToggle()"
+ aria-label="Inspector" aria-pressed="false" data-shortcut="editor.inspector"
+ title="Inspector — the right-hand panel: speed, fades, brightness, zoom, transitions and titles for what is selected">
+ <svg class="sbe-cbar-i"><use href="#ic-inspect"/></svg><b>Inspector</b></button>
+ <!-- SOUND MODE. The one control that changes the split: the timeline
+ takes the height, every sound lane is at full height, the picture
+ is small. Off again is picture mode: lanes thin, picture big. It
+ replaced the lanes that sized themselves — "the automatic changing
+ of the size of the timeline if you are going around with audio is
+ really bad. A button is warranted." -->
+ <button type="button" class="sbe-vbtn" id="sbeSoundBtn" onclick="sbeSoundModeToggle()"
+ aria-label="Sound mode" aria-pressed="false" data-shortcut="editor.soundMode"
+ title="Sound mode — the sound lanes at full height and the picture small">
+ <svg class="sbe-cbar-i"><use href="#ic-wave"/></svg><b>Sound</b></button>
+ <!-- PANELS. Photoshop's Tab: the app's left column (tabs, media pool,
+ queue) out of the way, and back. ` on the keyboard. -->
+ <button type="button" class="sbe-vbtn" id="sbePanelsBtn" onclick="sbePanelsToggle()"
+ aria-label="Side panels" aria-pressed="true" data-shortcut="editor.panels"
+ title="Side panels — the app's left column: the tabs, the media pool and the queue">
+ <svg class="sbe-cbar-i"><use href="#ic-panels"/></svg><b>Panels</b></button>
+ <span class="sbe-vsep" aria-hidden="true"></span>
+ <button type="button" class="sbe-vbtn sbe-vbtn-act" id="sbeFullBtn" onclick="sbeFullscreen()"
+ aria-label="Full screen" data-shortcut="editor.fullscreen"
+ title="Full screen — the Program monitor fills the whole screen. Esc brings it back">
+ <svg class="sbe-cbar-i"><use href="#ic-full"/></svg></button>
+ </span>
<!-- One gesture, two directions: a segmented pair rather than two
free-standing buttons that happen to sit next to each other. -->
<span class="sbe-undogroup">
@@ -3968,6 +4170,11 @@ The last line"></textarea>
<button type="button" class="ghost-btn" onclick="sbeAddSoundFile()"
title=".wav, .m4a, .mp3, .aac — or a video, for its sound only">Add sound file</button>
</span>
+ <span class="sbe-pop-note">Or lay an ambience bed under the whole __SEQ__.</span>
+ <span class="sbe-pop-row">
+ <button type="button" class="ghost-btn" onclick="edRtOpen()"
+ title="Room tone — generated background noise under every cut, on its own track">Room tone…</button>
+ </span>
</div>
@@ -4129,29 +4336,41 @@ The last line"></textarea>
mute state of every element on this row, and only one of the two
ever plays. -->
<div class="sbe-monitors" id="sbeMonitors">
- <div class="sbe-mon sbe-mon-src">
+ <!-- SOURCE IS ON SCREEN BY DEFAULT again (round 2): "you have two empty
+ dark spaces on the sides [of the Program monitor], so probably you
+ can still add the preview clip for a place where you can drag the
+ clips and see them. I think that is actually necessary." It sits
+ in the width the Program monitor could not use — the row is
+ height-limited, so the Program monitor keeps its size. It is a DROP
+ TARGET: a pool row or a timeline clip dragged onto it loads there.
+ Source in the View group (or × on its bar) hides it, per browser
+ (phos_sbe_src). -->
+ <div class="sbe-mon sbe-mon-src" id="sbeSrcMon">
<div class="sbe-stage" id="sbeSrcStage">
<!-- Same opacity rule as the program monitor, for the same
WebKit reason: a display:none <video> is never loaded. -->
<video id="sbeSrcVideo" playsinline preload="auto"></video>
<img id="sbeSrcStill" class="sbe-still" alt="">
<div class="sbe-stage-badge" id="sbeSrcBadge" hidden></div>
- <div class="sbe-stage-empty" id="sbeSrcEmpty">Click a clip to preview it.</div>
+ <div class="sbe-stage-empty sbe-src-empty" id="sbeSrcEmpty">
+ <svg class="sbe-cbar-i" aria-hidden="true"><use href="#ic-source"/></svg>
+ <b>Drop a clip here to preview</b>
+ <span>Drag one from the media pool or the timeline — or click a clip in the pool.</span>
+ </div>
</div>
- <!-- ONE bar per monitor, and both the same height, because the row
- is as tall as the taller column and the budget maths in
- sbeFitMonitors reads its overhead off the program side. The
- label lives IN the bar rather than above the picture: two
- captions per column is 38px of a budget that is already the
- tightest thing on this screen. -->
<div class="sbe-mon-bar">
<span class="sbe-mon-label">Source</span>
- <button type="button" class="ghost-btn" id="sbeSrcPlayBtn"
- onclick="sbeSrcToggle()" disabled>Play</button>
+ <button type="button" class="ghost-btn sbe-ibtn" id="sbeSrcPlayBtn"
+ onclick="sbeSrcToggle()" disabled aria-label="Play the source" title="Play / pause the source">
+ <svg class="sbe-cbar-i"><use href="#ic-play" id="sbeSrcPlayUse"/></svg></button>
<span class="sbe-mon-name" id="sbeSrcName">Nothing loaded</span>
<button type="button" class="ghost-btn" id="sbeSrcAddBtn"
onclick="sbeSrcAdd()" disabled
title="Puts this clip at the end of the __SEQ__ — exactly what the + on its row does.">Add to timeline</button>
+ <button type="button" class="ghost-btn sbe-ibtn" id="sbeSrcCloseBtn"
+ onclick="sbeSrcClose()" aria-label="Hide the Source monitor"
+ title="Hide the Source monitor — Source in the View group brings it back">
+ <svg class="sbe-cbar-i"><use href="#ic-close"/></svg></button>
</div>
</div>
<div class="sbe-mon sbe-mon-prog">
@@ -4181,25 +4400,37 @@ The last line"></textarea>
<div class="sbe-stage-badge" id="sbeBadge">idle</div>
<div class="sbe-stage-empty" id="sbeStageEmpty" hidden></div>
</div>
- <div class="sbe-mon-bar">
- <span class="sbe-mon-label">Program</span>
+ <!-- THE STRIP UNDER THE PICTURE — where Premiere and Resolve keep the
+ transport, and where the clip's name now lives instead of on the
+ picture: "the name of the clip in the full screen is hiding a
+ part of what is visible". Left to right: play, mute, the time,
+ what is under the playhead, then the three panel toggles. -->
+ <div class="sbe-mon-bar sbe-mon-bar-prog">
+ <button type="button" class="ghost-btn sbe-ibtn" id="sbePlayBtn" onclick="sbeTogglePlay()"
+ title="Play / pause" data-shortcut="editor.play" aria-label="Play">
+ <svg class="sbe-cbar-i"><use href="#ic-play" id="sbePlayUse"/></svg></button>
+ <button type="button" class="ghost-btn sbe-ibtn sbe-mute" id="sbeMuteBtn"
+ 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-mon-clip" id="sbeProgClip"></span>
<span class="sbe-mon-name" id="sbeProgName"></span>
+ <button type="button" class="sbe-chipbtn" id="sbeUnplacedBtn" hidden
+ onclick="sbeInspectSet(true)"
+ title="Shots that finished rendering but are not on the timeline — open the panel to place them"></button>
</div>
</div>
- <!-- THE RAIL, and why it exists. Two 16:9 monitors need 2.96px of
- width for every px of height. Measured in this column, at
- 1440x900, there are 307px of height to spare and 1110px of width
- — the pair can span 886 of them. Something has to hold the other
- 224, and the choice is between black page background (the exact
- thing the owner circled) and the two panels that were sitting
- under the timeline eating 46px of the height that made the
- picture small in the first place. Resolve and Premiere both put
- the inspector beside the monitors; so does this. Its width is
- whatever the pair leaves — see sbeFitMonitors — clamped so it can
- be neither a slot nor a second sidebar. Below the stacking
- breakpoint it goes back to being a row. -->
- <div class="sbe-rail" id="sbeRail">
+ <!-- THE RAIL IS A PANEL, NOT A FIXTURE. Resolve and Premiere put the
+ inspector beside the monitors, and so does this — but they let
+ you close it, and until now this one was open for every minute
+ of every session: "It shouldn't be open like this all the time,
+ only when it's necessary." ☰ under the picture, ⌘I, or a double-
+ click on a clip opens it; the state is this browser's
+ (phos_sbe_inspect). Width is whatever the monitors leave — see
+ sbeMonitorFit — clamped so it is neither a slot nor a sidebar. -->
+ <div class="sbe-rail" id="sbeRail" hidden>
<div class="sbe-inspect" id="sbeInspect"></div>
<div class="sbe-unplaced" id="sbeUnplacedWrap" hidden>
<div class="sbe-unplaced-head">Rendered but not on the timeline</div>
@@ -4235,90 +4466,90 @@ The last line"></textarea>
for it to work — a control that vanishes teaches nothing, and the
inspector's habit of dropping a button it could not offer is
exactly why "delete sound" read as a feature that did not exist. -->
- <!-- THE ICON SPRITE. Defined once, referenced by <use>, stroked in
- currentColor so one rule themes every glyph and the disabled state
- dims the icon with its label. Geometric rather than pictorial: at
- 13px a drawing of a padlock is four grey pixels, and the label is
- doing the naming anyway. -->
+ <!-- THE ICON SPRITE. Phosphor's geometry (the set the rest of the panel
+ uses, 256-unit grid), one <symbol> per glyph WITH ITS viewBox — the
+ first version used bare <g>s, so a 15px <svg> showed the top-left
+ 15 units of a 24-unit drawing: "the icons are … deformed". Stroked in
+ currentColor at a width set once in .sbe-cbar-i. -->
<svg class="sbe-icons" aria-hidden="true" focusable="false"><defs>
- <g id="ic-split"><path d="M12 2v20"/><path d="M7 8 3.5 12 7 16"/><path d="M17 8l3.5 4-3.5 4"/></g>
- <g id="ic-lift"><path d="M3 20h18"/><path d="M12 3v11"/><path d="M7.5 7.5 12 3l4.5 4.5"/></g>
- <g id="ic-ripple"><path d="M3 20h18"/><path d="M20 9H7"/><path d="M11.5 4.5 7 9l4.5 4.5"/></g>
- <g id="ic-dup"><rect x="3" y="3" width="12" height="12" rx="2"/><path d="M9 21h10a2 2 0 0 0 2-2V9"/></g>
- <g id="ic-unlink"><path d="M9 7H6a5 5 0 0 0 0 10h3"/><path d="M15 7h3a5 5 0 0 1 0 10h-3"/><path d="M4 4l16 16"/></g>
- <g id="ic-link"><path d="M9 7H6a5 5 0 0 0 0 10h3"/><path d="M15 7h3a5 5 0 0 1 0 10h-3"/><path d="M8 12h8"/></g>
- <g id="ic-resync"><path d="M20 6v5h-5"/><path d="M20 11A8 8 0 0 0 5 8"/><path d="M4 18v-5h5"/><path d="M4 13a8 8 0 0 0 15 3"/></g>
- <g id="ic-mute"><path d="M4 9v6h3l5 4V5L7 9H4z"/><path d="M17 9l4 6"/><path d="M21 9l-4 6"/></g>
- <g id="ic-sound"><path d="M4 9v6h3l5 4V5L7 9H4z"/><path d="M16 9a4 4 0 0 1 0 6"/></g>
- <g id="ic-delsound"><path d="M4 9v6h3l5 4V5L7 9H4z"/><path d="M15 12h6"/></g>
- <g id="ic-points"><path d="M3 14h18"/><circle cx="8" cy="14" r="1.8"/><circle cx="15" cy="14" r="1.8"/><path d="M17 5l5 5"/><path d="M22 5l-5 5"/></g>
- <g id="ic-lock"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></g>
- <g id="ic-facefix"><path d="M4 20L20 4"/><path d="M13 4h7v7"/><path d="M4 13v7h7"/></g>
- <g id="ic-unlock"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.5-2"/></g>
+ <symbol id="ic-split" viewBox="0 0 256 256"><circle cx="76" cy="68" r="28"/><circle cx="76" cy="188" r="28"/><path d="M96.9 86.6 200 200M96.9 169.4 200 56"/></symbol>
+ <symbol id="ic-lift" viewBox="0 0 256 256"><rect x="20" y="168" width="60" height="56" rx="8"/><rect x="176" y="168" width="60" height="56" rx="8"/><rect x="104" y="168" width="48" height="56" rx="6" stroke-dasharray="20 16"/><path d="M128 136V36M88 76l40-40 40 40"/></symbol>
+ <symbol id="ic-ripple" viewBox="0 0 256 256"><rect x="20" y="168" width="72" height="56" rx="8"/><rect x="112" y="168" width="124" height="56" rx="8"/><path d="M224 88H116M156 48l-40 40 40 40M80 44v88"/></symbol>
+ <symbol id="ic-dup" viewBox="0 0 256 256"><path d="M168 168h48V40H88v48"/><rect x="40" y="88" width="128" height="128" rx="8"/></symbol>
+ <symbol id="ic-link" viewBox="0 0 256 256"><path d="M108 84H76a44 44 0 0 0 0 88h32M148 84h32a44 44 0 0 1 0 88h-32M88 128h80"/></symbol>
+ <symbol id="ic-unlink" viewBox="0 0 256 256"><path d="M96 84H68a44 44 0 0 0 0 88h28M160 84h28a44 44 0 0 1 0 88h-28M128 32v36M128 188v36"/></symbol>
+ <symbol id="ic-resync" viewBox="0 0 256 256"><path d="M176 104h48V56M224 104l-28.3-28.3a96 96 0 0 0-135.4-.5M80 152H32v48M32 152l28.3 28.3a96 96 0 0 0 135.4.5"/></symbol>
+ <symbol id="ic-mute" viewBox="0 0 256 256"><path d="M48 40l160 176M80 168H32a8 8 0 0 1-8-8V96a8 8 0 0 1 8-8h48l72-56v115M152 179v45l-57.6-44.8"/></symbol>
+ <symbol id="ic-sound" viewBox="0 0 256 256"><path d="M80 168H32a8 8 0 0 1-8-8V96a8 8 0 0 1 8-8h48l72-56v192ZM80 88v80M192 106.9a32 32 0 0 1 0 42.3M221.7 80a72 72 0 0 1 0 96"/></symbol>
+ <symbol id="ic-delsound" viewBox="0 0 256 256"><path d="M216 56H40M168 56V40a16 16 0 0 0-16-16h-48a16 16 0 0 0-16 16v16M200 56v152a8 8 0 0 1-8 8H64a8 8 0 0 1-8-8V56M100 124v40M128 100v88M156 124v40"/></symbol>
+ <symbol id="ic-points" viewBox="0 0 256 256"><path d="M24 200l64-56 72 32 72-64M180 28l40 40M220 28l-40 40"/><circle cx="88" cy="144" r="20" fill="currentColor" stroke="none"/><circle cx="160" cy="176" r="20" fill="currentColor" stroke="none"/></symbol>
+ <symbol id="ic-lock" viewBox="0 0 256 256"><rect x="40" y="88" width="176" height="128" rx="10"/><path d="M92 88V56a36 36 0 0 1 72 0v32"/><circle cx="128" cy="152" r="16" fill="currentColor" stroke="none"/></symbol>
+ <symbol id="ic-unlock" viewBox="0 0 256 256"><rect x="40" y="88" width="176" height="128" rx="10"/><path d="M92 88V56a36 36 0 0 1 69.1-14"/><circle cx="128" cy="152" r="16" fill="currentColor" stroke="none"/></symbol>
+ <symbol id="ic-facefix" viewBox="0 0 256 256"><circle cx="112" cy="144" r="84"/><circle cx="84" cy="128" r="13" fill="currentColor" stroke="none"/><circle cx="140" cy="128" r="13" fill="currentColor" stroke="none"/><path d="M76 170a44 44 0 0 0 72 0"/><path d="M208 12l10 30 30 10-30 10-10 30-10-30-30-10 30-10z" fill="currentColor" stroke="none"/></symbol>
+ <symbol id="ic-play" viewBox="0 0 256 256"><path d="M240 128a15.7 15.7 0 0 1-7.6 13.5L88.3 229.7a16 16 0 0 1-16.2.3A15.9 15.9 0 0 1 64 216.1V39.9a15.9 15.9 0 0 1 8.1-13.8 16 16 0 0 1 16.2.3l144.1 88.1A15.7 15.7 0 0 1 240 128Z" fill="currentColor" stroke="none"/></symbol>
+ <symbol id="ic-pause" viewBox="0 0 256 256"><rect x="48" y="32" width="64" height="192" rx="16" fill="currentColor" stroke="none"/><rect x="144" y="32" width="64" height="192" rx="16" fill="currentColor" stroke="none"/></symbol>
+ <symbol id="ic-close" viewBox="0 0 256 256"><path d="M200 56 56 200M200 200 56 56"/></symbol>
+ <symbol id="ic-source" viewBox="0 0 256 256"><rect x="16" y="48" width="224" height="160" rx="14"/><path d="M128 48v160"/><path d="M60 100v56l44-28z" fill="currentColor" stroke="none"/></symbol>
+ <symbol id="ic-inspect" viewBox="0 0 256 256"><rect x="16" y="48" width="224" height="160" rx="14"/><path d="M160 48v160M186 92h28M186 128h28M186 164h28"/></symbol>
+ <symbol id="ic-panels" viewBox="0 0 256 256"><rect x="16" y="48" width="224" height="160" rx="14"/><path d="M96 48v160"/><path d="M30 48h66v160H30a14 14 0 0 1-14-14V62a14 14 0 0 1 14-14z" fill="currentColor" stroke="none" opacity=".4"/></symbol>
+ <symbol id="ic-full" viewBox="0 0 256 256"><path d="M168 40h48v48M88 216H40v-48M216 168v48h-48M40 88V40h48"/></symbol>
+ <symbol id="ic-wave" viewBox="0 0 256 256"><path d="M28 112v32M68 80v96M108 36v184M148 68v120M188 96v64M228 116v24"/></symbol>
+ <symbol id="ic-keys" viewBox="0 0 256 256"><rect x="20" y="56" width="216" height="144" rx="12"/><path d="M60 98h12M100 98h12M140 98h12M180 98h16M60 130h12M100 130h56M180 130h16M76 162h104"/></symbol>
+ <symbol id="ic-history" viewBox="0 0 256 256"><path d="M128 80v48l40 24M72 104H32V64M67.6 192a88 88 0 1 0-1.8-126.2L32 104"/></symbol>
</defs></svg>
+ <!-- ONE ROW: the verbs, then the timeline's own controls, then the grab.
+ The verbs are ICONS — "the menu doesn't need to have the words on
+ each one … just when you hover over it, you see an explanation" —
+ and every tooltip carries the name, the consequence and the key.
+ The words come back in the More menu and the right-click menu, where
+ a list reads better than a row. The transport (play, mute, time)
+ moved under the Program monitor, which is where Premiere and Resolve
+ keep it, so this row and the old transport row are one row: 42px
+ back to the picture. `.sbe-toolrow` exists so the grab can hang
+ below a bar that clips its own overflow. -->
+ <div class="sbe-toolrow" id="sbeToolRow">
<div class="sbe-cbar" id="sbeCbar">
<!-- WHAT AM I ABOUT TO ACT ON. The bar's buttons are worth nothing
without it: "Ripple delete" over an unnamed selection is the one
- gesture nobody should have to guess at, and multi-select made the
- question real rather than rhetorical. -->
+ gesture nobody should have to guess at. -->
<span class="sbe-cbar-who" id="sbeCbarWho">Nothing selected</span>
<span class="sbe-cbar-sep"></span>
- <button type="button" class="sbe-cbar-btn" id="sbeCbSplit" onclick="sbeSplitHere()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbSplit" onclick="sbeSplitHere()" aria-label="Split">
<svg class="sbe-cbar-i"><use href="#ic-split"/></svg><b>Split</b></button>
- <button type="button" class="sbe-cbar-btn" id="sbeCbLift" onclick="sbeLiftSelected()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbLift" onclick="sbeLiftSelected()" aria-label="Lift">
<svg class="sbe-cbar-i"><use href="#ic-lift"/></svg><b>Lift</b></button>
- <button type="button" class="sbe-cbar-btn" id="sbeCbRipple" onclick="sbeRippleSelected()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbRipple" onclick="sbeRippleSelected()" aria-label="Ripple delete">
<svg class="sbe-cbar-i"><use href="#ic-ripple"/></svg><b>Ripple delete</b></button>
- <button type="button" class="sbe-cbar-btn" id="sbeCbDup" onclick="sbeDuplicateSel()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbDup" onclick="sbeDuplicateSel()" aria-label="Duplicate">
<svg class="sbe-cbar-i"><use href="#ic-dup"/></svg><b>Duplicate</b></button>
<span class="sbe-cbar-sep"></span>
- <!-- THE SOUND GROUP, and it is second because it is the one he named:
- "I find myself all the time un-syncing and syncing." Link and
- Resync sit side by side because the difference between them is
- the thing that is hard to hold in your head — one makes the pair
- permanent, the other only slides the sound back under its frame
- and leaves it free. -->
- <button type="button" class="sbe-cbar-btn" id="sbeCbLink" onclick="sbeToggleAudioLink()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbLink" onclick="sbeToggleAudioLink()" aria-label="Unlink sound">
<svg class="sbe-cbar-i"><use href="#ic-unlink" id="sbeCbLinkUse"/></svg><b>Unlink sound</b></button>
- <button type="button" class="sbe-cbar-btn" id="sbeCbResync" onclick="sbeResyncSel()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbResync" onclick="sbeResyncSel()" aria-label="Resync sound">
<svg class="sbe-cbar-i"><use href="#ic-resync"/></svg><b>Resync sound</b></button>
- <button type="button" class="sbe-cbar-btn" id="sbeCbMute" onclick="sbeToggleClipMute()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbMute" onclick="sbeToggleClipMute()" aria-label="Mute sound">
<svg class="sbe-cbar-i"><use href="#ic-mute" id="sbeCbMuteUse"/></svg><b>Mute sound</b></button>
- <button type="button" class="sbe-cbar-btn" id="sbeCbDelSound" onclick="sbeDeleteStripSel()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbDelSound" onclick="sbeDeleteStripSel()" aria-label="Delete sound">
<svg class="sbe-cbar-i"><use href="#ic-delsound"/></svg><b>Delete sound</b></button>
- <!-- THE "DELETE BUTTON FOR THE ANCHORS OF THE AUDIO". The dots on the
- yellow level line are the only anchors a person PLACES on a
- sound, and until now the only ways to take them off were a
- right-click on each one and a "Clear 4" button in the inspector
- that appeared and disappeared. -->
- <button type="button" class="sbe-cbar-btn" id="sbeCbPoints" onclick="sbeClearPoints()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbPoints" onclick="sbeClearPoints()" aria-label="Clear points">
<svg class="sbe-cbar-i"><use href="#ic-points"/></svg><b>Clear points</b></button>
<span class="sbe-cbar-sep"></span>
- <button type="button" class="sbe-cbar-btn" id="sbeCbLock" onclick="sbeToggleLock()">
+ <button type="button" class="sbe-cbar-btn" id="sbeCbLock" onclick="sbeToggleLock()" aria-label="Lock">
<svg class="sbe-cbar-i"><use href="#ic-lock" id="sbeCbLockUse"/></svg><b>Lock</b></button>
<span class="sbe-cbar-sep"></span>
- <!-- UPSCALE & FACE FIX on the selected clip: queues the face-safe 2×;
- the swap is offered on the relink line when it lands. -->
- <button type="button" class="sbe-cbar-btn" id="sbeCbFaceFix" onclick="sbeFaceFixSel()">
+ <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>
- <span class="ch-spacer" style="flex:1 1 auto"></span>
- <!-- OVERFLOW, NOT A DRAWER. It holds nothing of its own: whatever the
- row cannot fit at this width moves into it, in reverse priority
- order, and moves back out when the pane is widened. At the
- Editor's normal width it is not even rendered. -->
+ <!-- OVERFLOW, NOT A DRAWER. Whatever the row cannot fit at this width
+ moves into it, in reverse priority order, and moves back out when
+ the pane is widened. At the Editor's normal width it is not even
+ rendered. -->
<button type="button" class="sbe-cbar-btn sbe-cbar-more" id="sbeCbMoreBtn" hidden
onclick="sbePopToggle('sbeCbarMenu', 'sbeCbMoreBtn')"
aria-haspopup="menu" title="The verbs this pane is too narrow to show">More<span class="sbe-car">▾</span></button>
- </div>
-
- <div class="sbe-transport">
- <button type="button" class="ghost-btn" id="sbePlayBtn" onclick="sbeTogglePlay()" title="Play / pause" data-shortcut="editor.play">Play</button>
- <button type="button" class="ghost-btn sbe-mute" id="sbeMuteBtn"
- onclick="SBE.muted ? sbeUnmuteFromRefusal() : sbeSetMute(true)" title="Mute / unmute the preview" data-shortcut="editor.mute">🔊</button>
- <span class="sbe-time" id="sbeTime">0:00.00 <span>/ 0:00.00</span></span>
- <label class="check" style="margin:0;font-size:11px" data-shortcut="editor.snap"
+ <span class="ch-spacer" style="flex:1 1 auto"></span>
+ <label class="check sbe-snap" data-shortcut="editor.snap"
title="Clips you drag snap to the beat grid. ⌥ while dragging ignores it">
- <input type="checkbox" id="sbeSnapOn" checked onchange="sbePaint()"> Snap to beat
+ <input type="checkbox" id="sbeSnapOn" checked onchange="sbePaint()"> Snap
</label>
<!-- The two sliders an editor expects: the scrollbar on the track
below moves the view, this one changes the scale. All the way
@@ -4331,22 +4562,15 @@ The last line"></textarea>
oninput="sbeZoomSlide(this.value)">
<button type="button" class="ghost-btn" onclick="sbeZoom(1)" title="Zoom in" data-shortcut="editor.zoom">+</button>
</span>
- <!-- PROSE DEMOTED TO AN AFFORDANCE. Two lines of explanation sat
- across the middle of the transport for the life of the feature;
- it is true, it is worth saying once, and it is not worth 220px of
- the row every time. -->
<span class="sbe-info" id="sbeApprox" tabindex="0"
title="The preview is approximate: the browser lands within a few frames of each cut and freezes for about one there. The render is exact.">i</span>
- <span style="flex:1 1 auto"></span>
- <button type="button" class="ghost-btn" id="sbeKeysBtn"
+ <button type="button" class="sbe-tbtn" id="sbeKeysBtn"
onclick="sbePopToggle('sbeKeysPop', 'sbeKeysBtn')"
- aria-haspopup="menu" title="Every gesture this timeline answers to">Keys</button>
- <!-- THE TIMELINE'S TOP EDGE. It lives in the transport because the
- transport is the element directly above the seam and an absolute
- child costs the column nothing; what it drags is one number
- (SBE.tlH), and the monitors are sized off whatever is left. Up is
- more track, down is more picture, and neither element is resized
- directly — see sbeFitMonitors. -->
+ aria-haspopup="menu" aria-label="Keys" title="Every gesture this timeline answers to">
+ <svg class="sbe-cbar-i"><use href="#ic-keys"/></svg></button>
+ </div>
+ <!-- THE TIMELINE'S TOP EDGE, as a handle. Positioned over the 8px gap
+ below this row so it costs the column no height of its own. -->
<div class="sbe-tl-grab" id="sbeTlGrab" role="separator"
aria-orientation="horizontal"
aria-label="Resize the timeline — drag up for taller lanes"
@@ -4360,14 +4584,6 @@ The last line"></textarea>
onkeydown="sbeTlGrabKey(event)"></div>
</div>
- <!-- NAMED TRACKS. A timeline whose lanes are unlabelled asks you to
- infer which one is which from what happens to be on it, and the
- soundtrack's whole control row was a full-width strip at the top of
- the column, four inches from the lane it acts on. The gutter is
- 124px that says V2 / V1 / A1 / A2 and gives A2 the file it is
- playing, the way it sits under the clips, and a ▾ for the rest.
- Every head's height is the SAME variable its lane reads, so the two
- columns cannot drift apart. -->
<div class="sbe-tlwrap" id="sbeTlWrap">
<div class="sbe-gutter" id="sbeGutter">
<div class="sbe-gh sbe-gh-top"></div>
@@ -4387,7 +4603,7 @@ The last line"></textarea>
<div class="sbe-gh sbe-gh-aud">
<span class="sbe-gh-tag"><i>A1</i><b>Clip sound A</b>
<button type="button" class="sbe-gh-more sbe-asize" id="sbeAudioSize"
- onclick="sbeAudioPinToggle()" aria-expanded="true"
+ 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>
</span>
<span class="sbe-gh-sub" id="sbeHeadAud"></span>
@@ -4451,7 +4667,7 @@ The last line"></textarea>
<button type="button" class="sbe-gh-more" id="sbeSoundMore"
onclick="sbePopToggle('sbeSoundMenu', 'sbeSoundMore')"
aria-haspopup="menu"
- title="Add sound file… — put a sound from anywhere on this Mac onto an audio track at the playhead">♪</button>
+ title="Add sound file… or Room tone… — a sound from this Mac, or an ambience bed under the whole film">♪</button>
</div>
<div class="sbe-gh sbe-gh-foot"></div>
</div>
@@ -5279,26 +5495,6 @@ The last line"></textarea>
</div>
</div>
-<div class="modal-bg" id="batchModal" onclick="if(event.target===this)closeBatch()">
- <div class="modal">
- <h3>Batch paste — split prompts with <code>---</code> on its own line</h3>
- <textarea class="batch" id="batchPrompts" placeholder="First prompt here.
-
----
-
-Second prompt.
-
----
-
-Third prompt."></textarea>
- <div class="hint" style="margin-top:6px">Each chunk between <code>---</code> lines becomes a queued job using the current form settings. Auto-open is forced off for batches.</div>
- <div class="modal-actions">
- <button class="small" onclick="closeBatch()">Cancel</button>
- <button class="small primary" style="padding:6px 14px" onclick="queueBatch().then(closeBatch)">Queue all</button>
- </div>
- </div>
-</div>
-
<!-- Re-plan. The one storyboard surface that needs a modal, because it needs a
text field. Written HERE, at column 0, as a direct child of <body> and
present at boot on purpose: the global _phosModalScaffold IIFE registers
@@ -5377,6 +5573,7 @@ Third prompt."></textarea>
const BOOT = __BOOTSTRAP__;</script>
<script type="module" src="/webapp/js/boot.js"></script>
<script type="module" src="/webapp/js/shortcuts.js"></script>
+<script type="module" src="/webapp/js/tips.js"></script>
<script type="module" src="/webapp/js/docs.js"></script>
<script type="module" src="/webapp/js/stage.js"></script>
<script type="module" src="/webapp/js/characters.js"></script>
diff --git a/webapp/js/characters.js b/webapp/js/characters.js
index 41143e5..a656715 100644
--- a/webapp/js/characters.js
+++ b/webapp/js/characters.js
@@ -2889,73 +2889,139 @@ function setAspect(a) {
}
}
-// Compose the right-aligned line in the Customize summary. Reflects the
-// current effective state: aspect, custom-dims callout, speed setting.
+// ============ THE THREE DISCLOSURE SUMMARIES ============
+// The render form is three collapsed sections now (Shot setup · After the
+// render · Advanced), and a section you cannot see into still owes you its
+// state — that is the whole price of folding it away. So each summary prints
+// what ITS section is hiding, and nothing that belongs to another one:
+// Shot setup → the shape: quality, length, orientation, speed, steps,
+// a locked seed, and the live estimate for all of it.
+// After the render → what happens to the file afterwards.
+// Advanced → only the overrides that are OFF their default; a
+// default deserves no words, so it prints "defaults".
+// updateCustomizeSummary() keeps its name and stays the entry point (23 call
+// sites across five modules call it after every state change) and fans out.
function updateCustomizeSummary() {
- const el = document.getElementById('customizeSummary');
+ updateShotSetupSummary();
+ updateFinishSummary();
+ updateAdvancedSummary();
+ if (typeof updateBatchSummary === 'function') updateBatchSummary();
+}
+function updateShotSetupSummary() {
+ const el = document.getElementById('shotSetupSummary');
+ if (!el) return;
+ const parts = [];
+ if (document.body.dataset.engine === 'h3') {
+ let cell = null;
+ try { cell = h3CurrentCell(); } catch (_) {}
+ if (cell) {
+ parts.push(cell.quality_label || 'Hailuo H3');
+ if (cell.length_label) parts.push(cell.length_label);
+ } else {
+ parts.push('Hailuo H3');
+ }
+ if (((document.getElementById('h3_orientation') || {}).value) === 'portrait') {
+ parts.push('9:16');
+ }
+ let fast = false;
+ try { fast = h3TriStepOn(cell); } catch (_) {}
+ parts.push(fast ? 'Fast' : 'Best');
+ const st = (document.getElementById('h3_steps') || {}).value || 'auto';
+ if (st !== 'auto') parts.push(st + ' steps');
+ // Priced by the engine module's own helper, so the line can never
+ // disagree with the chips inside the section.
+ let eta = '';
+ try { eta = h3CellEta(cell); } catch (_) {}
+ if (eta) parts.push(eta);
+ } else {
+ let cell = null;
+ try { cell = ltxCellFor(ltxCurrentQuality(), ltxCurrentLength()); } catch (_) {}
+ const q = (document.getElementById('quality') || {}).value || 'standard';
+ parts.push((cell && cell.quality_label) || q);
+ // A custom duration lights no chip, so the summary says the frames rather
+ // than a length that isn't on the axis.
+ if (cell && cell.length_label) parts.push(cell.length_label);
+ else parts.push(((document.getElementById('frames') || {}).value || '?') + 'f');
+ if (q === 'quick') parts.push('10:7');
+ else parts.push(((document.getElementById('aspect') || {}).value === 'vertical') ? '9:16' : '16:9');
+ // ltxCellEta() already says "· fast draft" when that schedule is armed —
+ // which is exactly why the eta comes from it and not from cell.eta: a
+ // summary must not advertise the tuned wall clock for a draft render.
+ let eta = '';
+ try { eta = ltxCellEta(cell); } catch (_) {}
+ if (!eta && typeof schedPresetActive === 'function' && schedPresetActive()) eta = 'fast draft';
+ if (eta) parts.push(eta);
+ }
+ const seed = String((document.getElementById('seed') || {}).value || '-1').trim();
+ if (seed && seed !== '-1') parts.push('seed ' + seed);
+ el.textContent = parts.filter(Boolean).join(' · ');
+}
+function updateFinishSummary() {
+ const el = document.getElementById('finishSummary');
if (!el) return;
- // H3 renders on its own geometry and its own export control; every LTX knob
- // summarised below is folded away in that state, so summarising them would
- // describe a render that isn't happening.
+ const parts = [];
if (document.body.dataset.engine === 'h3') {
- const tier = h3CurrentCell();
const up = (document.getElementById('h3_upscale') || {}).value || 'off';
- const parts = [tier ? tier.spec : 'Hailuo H3'];
- // Turbo and Steps used to be summarised here. They moved onto the primary
- // surface (#h3PrimaryControls), and a disclosure summary exists to reveal
- // what the disclosure is HIDING — restating two chips the user can see two
- // inches above it makes the line longer and tells them nothing. What is
- // actually folded away on H3 is the export target, so that is what it says.
if (up === 'fit_720p') parts.push('720p export');
else if (up === 'fit_1080p') parts.push('1080p export');
- else if (up === 'ltx_x2') parts.push('native export + Upscale & Face Fix after');
+ else if (up === 'ltx_x2') parts.push('native + Upscale & Face Fix after');
+ else parts.push('native export');
+ } else {
+ const up = (document.getElementById('upscale') || {}).value || 'off';
+ const method = (document.getElementById('upscale_method') || {}).value || 'lanczos';
+ const tag = (method === 'pipersr' || method === 'model') ? ' sharp' : '';
+ if (up === 'fit_720p') parts.push('720p export' + tag);
+ else if (up === 'x2') parts.push('2× export' + tag);
else parts.push('native export');
- el.textContent = parts.join(' · ');
+ }
+ if ((document.getElementById('open_when_done') || {}).checked) parts.push('opens when done');
+ el.textContent = parts.join(' · ');
+}
+function updateAdvancedSummary() {
+ const el = document.getElementById('customizeSummary');
+ if (!el) return;
+ // H3 renders on the tier's own geometry and ignores every LTX override in
+ // this section (make_job neutralises them server-side), so summarising them
+ // would describe a render that isn't happening.
+ const adv = document.getElementById('customizeDetails');
+ if (document.body.dataset.engine === 'h3') {
+ // Every row in here is an LTX override that H3 ignores (make_job
+ // neutralises them server-side), so on H3 the section opened onto
+ // NOTHING — a row that says "Advanced · LTX only" and rewards a click
+ // with an empty box is exactly the clutter this redesign is removing.
+ // Hidden, not removed: the inputs stay in the form, so the posted
+ // FormData is byte-identical on both engines.
+ el.textContent = 'LTX only';
+ if (adv) { adv.open = false; adv.hidden = true; }
return;
}
- const q = document.getElementById('quality').value;
- const w = parseInt(document.getElementById('width').value || 0);
- const h = parseInt(document.getElementById('height').value || 0);
- const aspect = document.getElementById('aspect').value || 'landscape';
- const accel = document.getElementById('accel').value || 'off';
- const upscale = document.getElementById('upscale').value || 'off';
+ if (adv) adv.hidden = false;
const parts = [];
- // Aspect (Quick is fixed 4:3, no choice; Standard/High show landscape/vertical).
- if (q === 'quick') parts.push('10:7 · 640×448');
- else parts.push(aspect === 'vertical' ? '9:16' : '16:9');
- // Flag custom dims if they don't match the preset.
+ const q = (document.getElementById('quality') || {}).value || 'standard';
+ const w = parseInt((document.getElementById('width') || {}).value || 0, 10);
+ const h = parseInt((document.getElementById('height') || {}).value || 0, 10);
const preset = QUALITY_PRESETS[q] || QUALITY_PRESETS['standard'];
- const vertical = (aspect === 'vertical' && q !== 'quick');
- const expectedW = vertical ? preset.h : preset.w;
- const expectedH = vertical ? preset.w : preset.h;
- if (q !== 'quick' && (w !== expectedW || h !== expectedH)) {
- parts.push(`${w}×${h} custom`);
- }
- // Speed — say something ONLY when a non-default accel is set (an old
- // sidecar restore). "exact speed" used to print whenever accel was off,
- // while the separate HQ Speed control defaulted to Fast — the summary
- // could contradict the open panel. That control is gone (v4.0.5, dead at
- // the engine boundary), and a default deserves no words.
+ const vertical = (((document.getElementById('aspect') || {}).value) === 'vertical' && q !== 'quick');
+ if (q !== 'quick' && (w !== (vertical ? preset.h : preset.w) || h !== (vertical ? preset.w : preset.h))) {
+ parts.push(w + '×' + h + ' custom');
+ }
+ const accel = (document.getElementById('accel') || {}).value || 'off';
if (accel === 'boost' || accel === 'turbo') parts.push(accel);
- // The REAL speed control: the folded-away disclosure must name a
- // non-default schedule, because it changes the take, not just the clock.
- if (typeof schedPresetActive === 'function' && schedPresetActive()) {
- parts.push('fast draft · different take');
- }
- // Inspire changes what the reference DOES; the folded-away summary owes
- // that sentence as much as it owes the schedule.
- if (typeof i2vInspireActive === 'function' && i2vInspireActive()
- && currentMode === 'i2v') {
+ const stg = parseFloat((document.getElementById('stgScale') || {}).value || '0');
+ if (stg > 0) parts.push('STG ' + stg.toFixed(1));
+ const temporal = (document.getElementById('temporal_mode') || {}).value || 'native';
+ if (temporal === 'fps12_interp24') parts.push('12→24fps long clip');
+ else if (temporal === 'windows') parts.push('chained windows');
+ if (currentMode === 'i2v'
+ && ((document.getElementById('i2vMode') || {}).value === 'i2v_clean_audio')) {
+ parts.push('external audio');
+ }
+ // Inspire changes what the reference DOES; it lives in the composer, but the
+ // sentence is worth carrying where the rest of the deviations are listed.
+ if (typeof i2vInspireActive === 'function' && i2vInspireActive() && currentMode === 'i2v') {
parts.push('inspire · new shot from the image');
}
- if ((document.getElementById('temporal_mode')?.value || 'native') === 'fps12_interp24') {
- parts.push('12→24fps long clip');
- }
- const method = (document.getElementById('upscale_method')?.value || 'lanczos');
- const methodTag = method === 'pipersr' || method === 'model' ? ' sharp' : '';
- if (upscale === 'fit_720p') parts.push('720p export' + methodTag);
- else if (upscale === 'x2') parts.push('2× export' + methodTag);
- el.textContent = parts.join(' · ');
+ el.textContent = parts.length ? parts.join(' · ') : 'defaults';
}
function setExtendMode(m) {
// Fast = no-CFG path, fits in 64 GB at 1280×704. Quality = upstream
@@ -3079,6 +3145,7 @@ Object.assign(globalThis, {
setQuality, _qualityUsesHq, setAccel, setTemporalMode,
setUpscale, setUpscaleMethod, updateAccelAvailability, updateTemporalAvailability,
setAspect, updateCustomizeSummary, updatePromptPlaceholder,
+ updateShotSetupSummary, updateFinishSummary, updateAdvancedSummary,
// inline-handler targets: generated markup resolves these through the
// global scope (the v4.9.0 regression, PR #69)
audioStudioClearAudio, charactersPickChip, trainInstall, trainRemoveImage,
diff --git a/webapp/js/editor.js b/webapp/js/editor.js
index 61baef7..8999e1c 100644
--- a/webapp/js/editor.js
+++ b/webapp/js/editor.js
@@ -124,10 +124,6 @@ function sbeTlRoof(small) {
// remembered preference and the layout gate all stand on these.
globalThis.SBE_TL_MIN_H = sbeTlFloor(false);
globalThis.SBE_TL_MAX_H = sbeTlRoof(false);
-// How long the sound lanes wait, with nothing happening on sound, before they
-// make themselves small. Long enough that clicking off a strip to look at the
-// picture is not a flicker; short enough that it reads as the app noticing.
-const SBE_ASMALL_IDLE = 2400;
// How far one arrow key moves the edge, and one arrow key with Shift.
const SBE_TL_STEP = 12;
const SBE_TL_STEP_BIG = 40;
@@ -288,12 +284,11 @@ window.SBE = {
// the shot. `tgSliding` holds the heads still while a level slider moves.
tracks: [], tsSet: [], tsDrag: null, tsDrop: null, selLane: '',
tgBefore: null, tgSliding: false, tsGainBefore: null,
- // THE SOUND AREA'S SIZE. `aPin` is this browser's own answer ('auto' — thin
- // until you touch sound — or 'open' / 'small' pinned); `aSmall` is what is on
- // screen; `aTouch` when sound was last worked on; `aHover` whether the pointer
- // is on a lane or a head; `aTimer` the idle that makes them small and `aAnim`
- // the brief transition. See sbeAudioPinRead.
- aPin: sbeAudioPinRead(), aSmall: false, aTouch: 0, aHover: false,
+ // THE SPLIT AND THE PANELS, this browser's own: `mode` is 'picture' or
+ // 'sound' (see sbeSoundModeSet), `inspect` whether the rail is open, `srcOn`
+ // whether the Source monitor is on screen (ON unless this browser hid it —
+ // round 2: "the preview clip … is actually necessary").
+ mode: sbeModeRead(), inspect: sbeInspectRead(), srcOn: sbeSrcRead(),
aTimer: null, aAnim: null,
};
@@ -3302,26 +3297,37 @@ function sbeMonitorFit(width, budget, opts) {
const maxR = sbeNum(o.maxRatio, SBE_MON_RATIO_MAX);
const railMin = sbeNum(o.railMin, SBE_RAIL_MIN);
const railMax = sbeNum(o.railMax, SBE_RAIL_MAX);
+ // WHICH NEIGHBOURS ARE ON SCREEN. The Source monitor and the Inspector are
+ // both guests now (see sbeSrcMonToggle, sbeInspectSet); with neither, the
+ // Program monitor alone is width-limited by the column and nothing else,
+ // which is how the picture gets big. Defaults are both on, so every caller
+ // that predates the toggles still gets the three-up it was written for.
+ const withSrc = o.src !== false;
+ const withRail = o.rail !== false;
+ const rMin = withRail ? railMin : 0;
+ const rMax = withRail ? railMax : 0;
+ const gaps = (withSrc ? 1 : 0) + (withRail ? 1 : 0);
const A = 16 / 9;
- const total = Math.max(2 * minH * A + railMin + 2 * gap, sbeNum(width));
+ const total = Math.max(minH * A * (withSrc ? 1 + pref : 1) + rMin + gaps * gap, sbeNum(width));
const cap = Math.max(minH, sbeNum(budget));
// The most the pair may ever take, and the height at which 40/60 fills it.
- const pairMax = total - railMin - 2 * gap;
- const wide = (pairMax - gap) / (A * (1 + pref));
+ const pairMax = total - rMin - gaps * gap;
+ const wide = withSrc ? (pairMax - gap) / (A * (1 + pref)) : pairMax / A;
let h, r;
- if (wide <= cap) { h = wide; r = pref; }
+ if (wide <= cap) { h = wide; r = withSrc ? pref : 0; }
else {
h = cap;
// Widen the source only as far as the rail's own maximum allows: past
// that the rail stops being leftover and starts being a panel.
- const room = total - railMax - 2 * gap - gap;
- r = Math.max(pref, Math.min(maxR, room / (A * h) - 1));
+ const room = total - rMax - gaps * gap - (withSrc ? gap : 0);
+ r = withSrc ? Math.max(pref, Math.min(maxR, room / (A * h) - 1)) : 0;
}
const progW = h * A;
- const srcW = h * r * A;
- const rail = Math.max(railMin, Math.min(railMax, total - progW - srcW - 2 * gap));
- return { progH: h, progW: progW, srcH: h * r, srcW: srcW, ratio: r,
- rail: rail, gap: gap, total: progW + srcW + rail + 2 * gap };
+ const srcW = withSrc ? h * r * A : 0;
+ const rail = withRail
+ ? Math.max(rMin, Math.min(rMax, total - progW - srcW - gaps * gap)) : 0;
+ return { progH: h, progW: progW, srcH: withSrc ? h * r : 0, srcW: srcW, ratio: r,
+ rail: rail, gap: gap, total: progW + srcW + rail + gaps * gap };
}
// ---------------------------------------------------------------------------
@@ -3391,193 +3397,242 @@ function sbeLaneHeights(tlH, small) {
// snapshot lane for a number no renderer will ever read. localStorage is where
// every other view preference in this panel already lives — `sbeMuted`, the
// open document, the workflow tab.
+// ONE HEIGHT PER MODE. Picture mode starts at the floor of its (thin) lanes
+// and sound mode at the roof of its (full) lanes — "the sound very big and the
+// image very little" — and each keeps whatever the handle was last dragged to.
+function sbeTlPrefKey() { return sbeSoundMode() ? 'phos_sbe_tl_h_sound' : 'phos_sbe_tl_h'; }
function sbeTlPrefRead() {
let v = NaN;
- try { v = parseInt(localStorage.getItem('phos_sbe_tl_h') || '', 10); } catch (e) {}
- // Read and written against the FULL-height ends: the number the user dragged
- // is what he asked for with the sound open, and making the lanes small must
- // not quietly rewrite it to the smaller ceiling.
- return (v === v) ? sbeTlClamp(v, SBE_TL_MAX_H, false) : SBE_TL_MIN_H;
+ try { v = parseInt(localStorage.getItem(sbeTlPrefKey()) || '', 10); } catch (e) {}
+ const small = sbeAudioSmall();
+ if (v !== v) return small ? sbeTlFloor(true) : sbeTlRoof(false);
+ return sbeTlClamp(v, small ? sbeTlRoof(true) : SBE_TL_MAX_H, small);
}
function sbeTlPrefWrite(px) {
try {
- localStorage.setItem('phos_sbe_tl_h',
- String(sbeTlClamp(px, SBE_TL_MAX_H, false)));
+ localStorage.setItem(sbeTlPrefKey(), String(Math.round(sbeNum(px, sbeTlFloor()))));
} catch (e) {}
}
// ---------------------------------------------------------------------------
-// THE SOUND LANES MAKE THEMSELVES SMALL
+// PICTURE MODE AND SOUND MODE
// ---------------------------------------------------------------------------
-// "Think of some way that is really seamless and user-friendly to maybe
-// compact all audio lanes when I am not working with them and make them little
-// (because I want to see the image also as I'm working sometimes)."
+// "I don't like that the audio editing mode is automatic and moves the screens
+// up. It's really weird… The automatic changing of the size of the timeline if
+// you are going around with audio is really bad. I think a button is warranted
+// where you can enter sound editing mode, and then you see the sound very big
+// and the image very little."
//
-// So it is AUTOMATIC and it is also a button. Automatic is the default: the
-// sound area is thin until you go near it and full height for as long as you
-// are on it. The button (the ▾ on the A1 head, ⇧A) is for when you have an
-// opinion — it pins one answer, in THIS BROWSER, next to the timeline's height
-// and for the same reason: a window's shape is not the film's data. See the
-// comment above sbeTlPrefRead, which this follows exactly.
+// So the split has TWO STATES AND ONE SWITCH, and nothing else ever moves it.
+// Picture mode (the default): the sound lanes are thin strips, the timeline sits
+// at the height you last gave it, the picture takes the rest. Sound mode: every
+// sound lane at full height, the timeline as tall as the column allows, the
+// picture at its floor. The switch is the ⌁ button on the tool row, ⇧A, and the
+// ▾ on the A1 head — the same control three times. No hover, click, selection,
+// playback or timer changes it: the lanes that used to size themselves 2.4s
+// after the last touch were exactly the "weirdness" the owner named.
//
-// THREE STATES, ONE KEY: 'auto' (the default), 'open', 'small'.
-function sbeAudioPinRead() {
+// The choice is THIS BROWSER'S, next to the timeline height and for the same
+// reason (see sbeTlPrefRead): a window's shape is not the film's data.
+function sbeModeRead() {
let v = '';
- try { v = localStorage.getItem('phos_sbe_audio') || ''; } catch (e) {}
- return (v === 'open' || v === 'small') ? v : 'auto';
-}
-function sbeAudioPinWrite(v) {
- try { localStorage.setItem('phos_sbe_audio', String(v || 'auto')); } catch (e) {}
-}
-function sbeAudioPinSet(v) {
- const want = (v === 'open' || v === 'small') ? v : 'auto';
- SBE.aPin = want;
- sbeAudioPinWrite(want);
- sbeAudioSync();
-}
-
-// IS THE SOUND AREA SMALL RIGHT NOW? Every height function asks this, including
-// the one the timeline's own preference is read through — which runs inside
-// SBE's initialiser, before SBE exists. Hence the guard: this may not throw.
-function sbeAudioSmall() {
- try { return !!(SBE && SBE.aSmall); } catch (e) { return false; }
-}
-
-// IS SOMEBODY WORKING ON SOUND? Read off the state the audio gestures already
-// write, so no click path has to remember to announce itself: a selected strip,
-// a drag in progress, the pointer over a lane or a head, the Sound pool open,
-// a focused control in the sound heads. Playback and an open menu hold it open
-// too — a lane that collapsed mid-play or under an open menu would be the
-// "jumps" the request rules out.
-function sbeAudioBusy() {
- if (SBE.audioDrag || SBE.musicDrag || SBE.tsDrag || SBE.kfDrag || SBE.tgSliding) return true;
- if (SBE.tlDrag) return true;
- if (SBE.playing) return true;
- if (SBE.aHover) return true;
- if (typeof sbePopAnyOpen === 'function' && sbePopAnyOpen()) return true;
- const sel = String(SBE.sel || '');
- if (sel === '@music' || sel.indexOf('@ts:') === 0) return true;
- if (SBE.selLane) return true;
- if (typeof ED === 'object' && ED && ED.src === 'sound') return true;
- const f = (typeof document === 'object' && document) ? document.activeElement : null;
- if (f && f.closest && f.closest('.sbe-gh-aud, .sbe-gh-mus, .sbe-gh-trk, .sbe-gh-add')) return true;
- return false;
-}
-
-// What the area SHOULD be, right now. Pure decision, no DOM.
-function sbeAudioWant() {
- if (SBE.aPin === 'open') return false;
- if (SBE.aPin === 'small') return true;
- if (sbeAudioBusy()) return false;
- return (Date.now() - sbeNum(SBE.aTouch, 0)) >= SBE_ASMALL_IDLE;
+ try { v = localStorage.getItem('phos_sbe_mode') || ''; } catch (e) {}
+ return v === 'sound' ? 'sound' : 'picture';
}
-
-// ASK AGAIN LATER. One timer, always the only one, and it is only ever armed
-// while the area is OPEN and unpinned — the way back the other direction is a
-// touch, which is immediate.
-function sbeAudioArm() {
- if (SBE.aTimer) { clearTimeout(SBE.aTimer); SBE.aTimer = null; }
- if (!SBE.open || SBE.aPin !== 'auto' || SBE.aSmall) return;
- SBE.aTimer = setTimeout(() => { SBE.aTimer = null; sbeAudioSync(); }, SBE_ASMALL_IDLE);
+function sbeModeWrite(v) {
+ try { localStorage.setItem('phos_sbe_mode', v === 'sound' ? 'sound' : 'picture'); } catch (e) {}
}
-function sbeAudioSync() {
- const want = sbeAudioWant();
- if (want !== SBE.aSmall) { sbeAudioSet(want); return; }
- sbeAudioArm();
+// IS THE EDITOR IN SOUND MODE? Guarded because the height functions ask this
+// from inside SBE's own initialiser, before SBE exists — it may not throw.
+function sbeSoundMode() {
+ try { return !!(SBE && SBE.mode === 'sound'); } catch (e) { return false; }
}
+// The lane table's second height is on screen whenever we are NOT in sound
+// mode. Every height function reads this, and it has exactly one input.
+function sbeAudioSmall() { return !sbeSoundMode(); }
-// SOMEBODY IS ON SOUND. Opens the area at once (that half may never wait) and
-// restarts the idle. `opts.open` also releases a `small` pin, because the two
-// gestures that carry it — clicking a thin lane, dragging the edge up past what
-// thin lanes can use — are the user asking for the sound back in so many words.
-function sbeAudioTouch(opts) {
- SBE.aTouch = Date.now();
- if (opts && opts.open && SBE.aPin === 'small') {
- SBE.aPin = 'auto';
- sbeAudioPinWrite('auto');
- }
- if (SBE.aSmall && SBE.aPin !== 'small') sbeAudioSet(false);
- else sbeAudioArm();
-}
-
-// The pointer over a lane or a head is "working with it" for as long as it is
-// there — hovering a thin lane opens it, which is how you find out it opens.
-function sbeAudioOver(on) {
+// THE ONE WRITER of the mode. Nothing here resizes an element: it flips the
+// class the CSS reads, swaps in the mode's own remembered timeline height, and
+// sbeFitMonitors gives the difference to — or takes it from — the picture.
+function sbeSoundModeSet(on, opts) {
const want = !!on;
- if (SBE.aHover === want) return;
- SBE.aHover = want;
- if (want) sbeAudioTouch();
- else sbeAudioArm();
-}
-
-// THE ONE WRITER of the area's size. Nothing here resizes an element either:
-// it moves the same lane table the drag handle moves, and sbeFitMonitors gives
-// the difference to the picture.
-function sbeAudioSet(small) {
- const want = !!small;
- if (SBE.aSmall === want) return;
- SBE.aSmall = want;
+ const was = sbeSoundMode();
+ SBE.mode = want ? 'sound' : 'picture';
+ sbeModeWrite(SBE.mode);
const plan = sbeEl('sbTimeline');
- if (plan && plan.classList) plan.classList.toggle('is-asmall', want);
+ if (plan && plan.classList) {
+ plan.classList.toggle('is-asmall', !want);
+ plan.classList.toggle('is-sound', want);
+ }
// A HEIGHT THAT JUMPS READS AS A BUG, so the lanes and their heads carry a
// transition — but only while this class is on the body, so the drag handle,
- // which moves the same numbers sixty times a second, stays instant.
- if (typeof document === 'object' && document && document.body) {
+ // which moves the same numbers sixty times a second, stays instant. Not on
+ // the open of a document: there is nothing on screen yet to animate from.
+ const quiet = !!(opts && opts.quiet);
+ if (was !== want && !quiet && typeof document === 'object' && document && document.body) {
document.body.classList.add('sbe-aanim');
+ if (SBE.aAnim) clearTimeout(SBE.aAnim);
+ SBE.aAnim = setTimeout(() => {
+ SBE.aAnim = null;
+ if (document.body) document.body.classList.remove('sbe-aanim');
+ // THE WAVEFORMS ARE DRAWN, NOT STYLED: the soundtrack's canvas carries a
+ // backing store and every strip's waveform is emitted at its own height,
+ // so both are re-issued at the height they actually landed on.
+ SBE.laneAt = -1;
+ sbePaint();
+ }, 220);
}
- if (SBE.aAnim) clearTimeout(SBE.aAnim);
- SBE.aAnim = setTimeout(() => {
- SBE.aAnim = null;
- if (typeof document === 'object' && document && document.body) {
- document.body.classList.remove('sbe-aanim');
- }
- // THE WAVEFORMS ARE DRAWN, NOT STYLED: the soundtrack's canvas carries a
- // backing store and every strip's waveform is emitted at its own height, so
- // both have to be re-issued at the height they actually landed on. Same
- // reason sbeFitMonitors redraws them when the drag moves the number.
- SBE.laneAt = -1;
- sbePaint();
- }, 220);
+ // Each mode remembers its own height: the picture mode's handle position is
+ // not what you want the moment you go to sound, and vice versa.
+ SBE.tlH = sbeTlPrefRead();
sbeApplyTl(sbeTlClamp(SBE.tlH, SBE.tlMax));
- if (want) sbeAudioSmallOnce();
- sbePaint();
- sbeAudioArm();
-}
-
-// THE FIRST TIME IT HAPPENS BY ITSELF, IT SAYS SO. An area that shrinks with no
-// explanation is a bug the user reports; one sentence turns it into a feature
-// he knows the handle for. Once per browser, next to the other view preferences.
-function sbeAudioSmallOnce() {
- let seen = '';
- try { seen = localStorage.getItem('phos_sbe_audio_seen') || ''; } catch (e) {}
- if (seen) return;
- try { localStorage.setItem('phos_sbe_audio_seen', '1'); } catch (e) {}
- if (typeof phosToast !== 'function') return;
- phosToast('Sound lanes made small so the picture gets the height — touch any sound and they '
- + 'come straight back. The ▾ on the A1 head (⇧A) keeps them small, or open, for good.',
- { duration: 9000 });
-}
-
-// THE BUTTON. Two answers, and neither of them is "auto": auto is what you have
-// until you have an opinion, and clicking a thin lane hands it back.
-function sbeAudioPinToggle() {
- const want = sbeAudioSmall() ? 'open' : 'small';
- SBE.aPin = want;
- sbeAudioPinWrite(want);
- sbeAudioSet(want === 'small');
+ sbePaintPanels();
+ if (!quiet) sbePaint();
+}
+
+function sbeSoundModeToggle() {
+ const on = !sbeSoundMode();
+ sbeSoundModeSet(on);
if (typeof phosToast === 'function') {
- phosToast(want === 'small'
- ? 'Sound lanes small — A1, A2 and every audio track stay thin and the picture keeps the '
- + 'height. Click any sound to work on it; ⇧A brings them back for good.'
- : 'Sound lanes at full height — they stay open while you work. ⇧A, or the ▾ on the A1 '
- + 'head, makes them small again.', { duration: 6000 });
+ 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 });
+ }
+}
+
+// THE VIEW GROUP'S OWN STATE, painted in one place: Source, Inspector, Sound
+// and Panels in the header. PRESSED MEANS SHOWING — every one of the four is
+// filled while its panel is on screen, and its tooltip says what a click will
+// make appear or disappear. Cheap, so sbePaintChrome calls it on every paint.
+function sbeViewTip(btn, pressed, name, onText, offText, keyId) {
+ if (!btn || !btn.classList) return;
+ btn.classList.toggle('is-on', pressed);
+ btn.setAttribute('aria-pressed', pressed ? 'true' : 'false');
+ btn.title = name + ' — ' + (pressed ? onText : offText) + sbeKeyHint(keyId);
+}
+function sbePaintPanels() {
+ sbeViewTip(sbeEl('sbeSoundBtn'), sbeSoundMode(), 'Sound mode',
+ 'on: the sound lanes are at full height and the picture is small. Click for picture mode — thin lanes, big picture.',
+ 'off. Click to open every sound lane at full height; the picture gets small.',
+ 'editor.soundMode');
+ sbeViewTip(sbeEl('sbeInspectBtn'), !!SBE.inspect, 'Inspector',
+ 'showing on the right. Click to hide it; the monitors take the width.',
+ 'hidden. Click to show the right-hand panel: speed, fades, brightness, zoom, transitions and titles for what is selected.',
+ 'editor.inspector');
+ sbeViewTip(sbeEl('sbeSrcBtn'), sbeSrcShown(), 'Source monitor',
+ 'showing on the left. Click to hide it; the Program monitor stays the size it is.',
+ 'hidden. Click to show the left screen, where a clip from the media pool or the timeline plays before you cut it in.',
+ '');
+ sbeViewTip(sbeEl('sbePanelsBtn'),
+ !(document.body && document.body.classList.contains('ed-focus')), 'Side panels',
+ 'showing: the tabs, the media pool and the queue. Click to hide them and give the cut the whole window.',
+ 'hidden. Click to bring back the tabs, the media pool and the queue.',
+ 'editor.panels');
+}
+
+// ---- THE INSPECTOR IS A PANEL YOU OPEN ------------------------------------
+// "I'm not sure how useful it is to have the right-side thingy… It shouldn't be
+// open like this all the time, only when it's necessary." ☰ under the picture,
+// ⌘I, or a double-click on a clip. Remembered per browser, never in the film.
+function sbeInspectRead() {
+ let v = '';
+ try { v = localStorage.getItem('phos_sbe_inspect') || ''; } catch (e) {}
+ return v === 'open';
+}
+function sbeInspectSet(on) {
+ SBE.inspect = !!on;
+ try { localStorage.setItem('phos_sbe_inspect', SBE.inspect ? 'open' : 'closed'); } catch (e) {}
+ const rail = sbeEl('sbeRail');
+ if (rail) rail.hidden = !SBE.inspect;
+ sbePaintPanels();
+ sbePaint();
+}
+function sbeInspectToggle() { sbeInspectSet(!SBE.inspect); }
+
+// ---- THE SOURCE MONITOR IS A GUEST ----------------------------------------
+// On screen while a pool clip is loaded, or while it was asked for; gone the
+// rest of the time, and the Program monitor takes the width back.
+function sbeSrcRead() {
+ let v = '';
+ try { v = localStorage.getItem('phos_sbe_src') || ''; } catch (e) {}
+ return v !== 'hidden';
+}
+function sbeSrcWrite(on) {
+ try { localStorage.setItem('phos_sbe_src', on ? 'shown' : 'hidden'); } catch (e) {}
+}
+function sbeSrcShown() { return !!(SBE.source || SBE.srcOn); }
+function sbeSrcMonToggle() {
+ if (sbeSrcShown()) { sbeSrcClose(); return; }
+ SBE.srcOn = true;
+ sbeSrcWrite(true);
+ sbePaintSource();
+ sbePaintPanels();
+ sbePaint();
+}
+function sbeSrcClose() {
+ sbeSrcStop();
+ SBE.source = null;
+ SBE.srcIndex = -1;
+ SBE.srcOn = false;
+ sbeSrcWrite(false);
+ const v = sbeEl('sbeSrcVideo');
+ if (v) { try { v.pause(); } catch (e) {} v.classList.remove('is-on'); }
+ const img = sbeEl('sbeSrcStill');
+ if (img) img.classList.remove('is-on');
+ const list = document.getElementById('edPoolList');
+ if (list && list.querySelectorAll) {
+ for (const el of list.querySelectorAll('.is-source')) el.classList.remove('is-source');
}
+ sbePaintSource();
+ sbePaintPanels();
+ sbePaint();
}
-// ONE CLICK ON A THIN LANE OPENS THE AREA AND SELECTS WHAT WAS CLICKED, which
-// is the whole gesture: you point at the sound you want and it is there, full
-// height, selected, ready for the second click to edit it.
+// ---- FULL SCREEN ------------------------------------------------------------
+// "There should be an option to see the video in full screen on the actual
+// screen." The browser's own Fullscreen API on the Program monitor; Esc, or
+// the key again, brings it back. Space and the arrows keep working there
+// because the keydown handler is on the document, not the stage.
+function sbeFullscreen() {
+ const stage = sbeEl('sbeStage');
+ if (!stage) return;
+ try {
+ if (document.fullscreenElement) { document.exitFullscreen(); return; }
+ if (stage.requestFullscreen) stage.requestFullscreen();
+ else if (stage.webkitRequestFullscreen) stage.webkitRequestFullscreen();
+ } catch (e) {}
+}
+
+// ---- THE APP'S OWN PANELS -----------------------------------------------------
+// Photoshop's Tab: hide the left column (workflow tabs, media pool, queue) so
+// the cut has the window. ` on the keyboard, the ▯ button in the header.
+function sbePanelsRead() {
+ let v = '';
+ try { v = localStorage.getItem('phos_sbe_panels') || ''; } catch (e) {}
+ return v === 'hidden';
+}
+function sbePanelsApply(hidden) {
+ if (typeof document !== 'object' || !document || !document.body) return;
+ document.body.classList.toggle('ed-focus', !!hidden);
+ try { localStorage.setItem('phos_sbe_panels', hidden ? 'hidden' : 'shown'); } catch (e) {}
+ sbePaintPanels();
+}
+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 });
+ }
+}
+
+// ONE CLICK ON A THIN LANE SELECTS WHAT WAS CLICKED — and nothing moves. The
+// verbs on the tool row (mute, delete sound, unlink, resync, duplicate) all act
+// on the selection, so most of what you do to a sound never needs the lanes
+// open. A double-click on a thin lane is sound mode.
function sbeAudioOpenFrom(ev) {
const blk = (ev && ev.target && ev.target.closest)
? ev.target.closest('.sbe-tstrip, .sbe-aclip, .sbe-music-clip') : null;
@@ -3589,7 +3644,7 @@ function sbeAudioOpenFrom(ev) {
sbeSelectOne(blk.dataset.id);
SBE.selLane = blk.dataset.id; SBE.tsSet = [];
}
- sbeAudioTouch({ open: true });
+ sbePaint();
if (ev && ev.preventDefault) ev.preventDefault();
}
@@ -3690,6 +3745,12 @@ function sbeOpen(id, opts) {
? ((((SB.payload || {}).board) || {}).title || '') : '') || SBE.title || 'Editor';
sbeEl('sbeTitle').textContent = SBE.title;
edShow('doc');
+ // The split, the inspector and the app's panels come up the way this
+ // browser left them — and stay that way until a toggle is pressed.
+ sbeSoundModeSet(sbeModeRead() === 'sound', { quiet: true });
+ const rail = sbeEl('sbeRail');
+ if (rail) rail.hidden = !SBE.inspect;
+ sbePanelsApply(sbePanelsRead());
sbeSetState('loading…', '');
sbeLoad();
if (SBE.timer) clearInterval(SBE.timer);
@@ -3828,6 +3889,9 @@ function sbeAdopt(r, quiet) {
SBE.txSel = '';
SBE.clips = sbeAdoptGaps((SBE.edit.clips || []).map(c => Object.assign({}, c)));
sbeLayout(SBE.clips);
+ // A loaded bed is as the document says; only a length change from here on
+ // refits it (sbeRtFollow).
+ SBE.rtLen = sbeFilmDuration(SBE.clips);
SBE.dirty = false;
SBE.conflict = 0;
SBE.errors = {};
@@ -5105,6 +5169,16 @@ function sbePaintNotices() {
// the lead unless the user clicks it open.
const loud = open.filter(id => !((sbeEl(id).dataset || {}).quiet));
let lead = open.indexOf(SBE.noticeLead) >= 0 ? SBE.noticeLead : loud[0];
+ // A QUIET NOTICE ALONE IS A CHIP IN THE HEADER, not a row of its own: the
+ // snapshot offer took a whole row under the header for as long as a backup
+ // existed, which was most of the time. The row appears when the chip is
+ // clicked (sbeNoticeOpen makes it the lead) or when something loud joins it.
+ // Only the snapshot has a header chip; any other quiet notice alone (the
+ // keyed receipt) keeps the row, folded, as it always did.
+ const chip = sbeEl('sbeRecoverChip');
+ const chipOnly = !lead && open.length === 1 && open[0] === 'sbeRecover';
+ if (chip) chip.hidden = !chipOnly;
+ if (chipOnly) wrap.hidden = true;
for (const id of SBE_NOTICE_ORDER) {
const el = sbeEl(id);
if (!el || !el.classList) continue;
@@ -5271,9 +5345,12 @@ function sbePaint() {
// paint, not on the next scrub — the review caught a deleted title still
// painting over the picture.
sbeOvPaint();
+ // ROOM TONE FOLLOWS THE FILM'S LENGTH, before the lanes are drawn.
+ sbeRtFollow();
sbePaintTrack();
sbePaintAudioLane();
sbePaintTracks();
+ if (ED.src === 'sound') edRtPaint();
sbePaintHead();
sbePaintCbar();
sbePaintInspector();
@@ -5288,7 +5365,6 @@ function sbePaint() {
// EVERY EDIT AND EVERY SELECTION LANDS HERE, so this is where the sound
// area's idle is restarted — a click that deselected the last strip has to
// start the clock without every click path knowing that it did.
- sbeAudioArm();
// LAST, and after the inspector: the row's budget is what the column has
// left once everything else has been laid out, and the inspector is the
// one that changes height when a clip is selected.
@@ -5361,7 +5437,8 @@ function sbeFitMonitors() {
const want = sbeTlClamp(SBE.tlH, SBE.tlMax);
const budget = avail - want - extra;
const apply = (b) => {
- const fit = sbeMonitorFit(row.clientWidth, b);
+ const fit = sbeMonitorFit(row.clientWidth, b,
+ { src: sbeSrcShown(), rail: !!SBE.inspect });
row.style.setProperty('--sbe-prog-h', Math.round(fit.progH) + 'px');
row.style.setProperty('--sbe-src-h', Math.round(fit.srcH) + 'px');
row.style.setProperty('--sbe-rail-w', Math.round(fit.rail) + 'px');
@@ -5476,11 +5553,6 @@ function sbeTlGrabUp(ev) {
// sbeFitMonitors (last inside sbePaint) gives the monitors what is left and
// corrects tlNow for what the window could actually spare.
function sbeTlSet(px) {
- // PULLING THE EDGE UP PAST WHAT THIN LANES CAN USE IS "give me the sound
- // back": there is no other height left in the box to ask for.
- if (sbeAudioSmall() && sbeNum(px, 0) > sbeTlRoof(true) + 8) {
- sbeAudioTouch({ open: true });
- }
SBE.tlH = sbeTlClamp(px, SBE.tlMax);
sbeApplyTl(SBE.tlH);
sbePaint();
@@ -5974,6 +6046,7 @@ function sbeBedGhost(ev) {
// drag stays "move the music" — the gesture this lane already had — so the
// control case is opt-in and the simple case is untouched.
function sbeOnMusicDbl(ev) {
+ if (sbeAudioSmall()) { sbeSoundModeSet(true); return; }
const el = sbeEl('sbeMusicClip');
if (!el || el.hidden || !ev.target.closest('#sbeMusicClip')) return;
if (ev.target.closest('.sbe-kf') || ev.target.closest('.sbe-fade-h')) return;
@@ -6432,7 +6505,6 @@ function sbeTsCommit(before) {
}
function sbeTrackAdd() {
- sbeAudioTouch({ open: true });
if (!SBE.open) return;
if (sbeTsMutate(ts => sbeTsNewTrack(ts))) {
phosToast(sbeTrackLabel(SBE.tracks.length - 1) + ' added — drag a sound from the media '
@@ -6799,6 +6871,7 @@ function sbeTsGhost(ev) {
}
function sbeOnTsDbl(ev) {
+ if (sbeAudioSmall()) { sbeSoundModeSet(true); return; }
const at = sbeTsStripAt(ev);
if (!at || ev.target.closest('.sbe-kf')) return;
// SILENT WHEN A POINT IS ALREADY THERE — the first press of this very
@@ -6831,7 +6904,6 @@ function sbeOnTsMenu(ev) {
// server probes the file (and brings it into the film's audio/ folder when
// the preview could not play it where it is), the client places the strip.
async function sbeTsAddSoundPath(path, tid, at) {
- sbeAudioTouch({ open: true });
if (!SBE.open || !SBE.id) {
phosToast('Open a __SEQ__ first — a sound belongs to a timeline.', {});
return false;
@@ -6883,6 +6955,451 @@ async function sbeAddSoundFile() {
}
}
+// ---------------------------------------------------------------------------
+// ROOM TONE — a generated bed under the whole film
+// ---------------------------------------------------------------------------
+// "The cuts are very rough in terms of sound … if it was all over the timeline
+// as an ambient sound, not something really subtle." The client half of
+// `storyboard_editor.room_tone_*` and `room_tone.py`: a room-tone bed is an
+// ordinary audio track tagged `room_tone: {variant, seed, level, ref_lufs}`
+// with ONE locked strip from 0 to the film's end — so the preview, the render
+// and the export already play it. `level` is the label (LUFS); the track's
+// `gain` is the number the mix plays, `sbeRtGain(level, ref_lufs)`.
+const SBE_RT_NAME = 'Room tone';
+const SBE_RT_DEFAULT_LEVEL = -27; // mirrors room_tone.DEFAULT_LEVEL
+const SBE_RT_LEVEL_MIN = -45; // mirrors LEVEL_MIN / LEVEL_MAX
+const SBE_RT_LEVEL_MAX = -18;
+const SBE_RT_REF = -18; // mirrors REF_LUFS
+const SBE_RT_STEP = 30; // mirrors BED_STEP_S
+const SBE_RT_MAX = 1800; // mirrors BED_MAX_S
+
+function sbeRtClampLevel(v) {
+ const x = Number(v);
+ if (v === null || v === undefined || v === '' || !(x === x) || !isFinite(x)) {
+ return SBE_RT_DEFAULT_LEVEL;
+ }
+ return Math.round(Math.max(SBE_RT_LEVEL_MIN, Math.min(SBE_RT_LEVEL_MAX, x)) * 100) / 100;
+}
+
+// The fader for a level — the mirror of `room_tone.level_gain`. Never boosts.
+function sbeRtGain(level, ref) {
+ const r = (ref === null || ref === undefined || !isFinite(Number(ref)))
+ ? SBE_RT_REF : Number(ref);
+ const g = Math.pow(10, (sbeRtClampLevel(level) - r) / 20);
+ return sbeRound(Math.max(0, Math.min(1, g)));
+}
+
+// The file length for a film — the mirror of `room_tone.bed_seconds`.
+function sbeRtBedSeconds(filmLen) {
+ const n = Math.max(0, sbeNum(filmLen)) + 0.5;
+ return Math.min(SBE_RT_MAX, Math.max(SBE_RT_STEP, Math.ceil(n / SBE_RT_STEP) * SBE_RT_STEP));
+}
+
+// {track, ti} of the film's room-tone track — the first tagged one — or null.
+function sbeRtFind(tracks) {
+ const list = tracks || [];
+ for (let ti = 0; ti < list.length; ti++) {
+ const t = list[ti];
+ if (t && t.room_tone && typeof t.room_tone === 'object') return { track: t, ti: ti };
+ }
+ return null;
+}
+
+function sbeRtLevelOf(track) {
+ const rt = (track || {}).room_tone || {};
+ return sbeRtClampLevel(rt.level);
+}
+
+// The level a room-tone track is ACTUALLY playing at: its own fader, read back
+// through the same curve `sbeRtGain` writes. `room_tone.level` is only the
+// number the bed was MADE with — the fader moves independently, and a rebuild
+// that trusted the metadata reset the user's mix.
+function sbeRtLevelOfTrack(track) {
+ const tr = track || {};
+ const rt = tr.room_tone || {};
+ const stored = sbeRtClampLevel(rt.level);
+ const g = sbeNum(tr.gain, 1);
+ if (!isFinite(g) || g <= 0) return stored;
+ const ref = isFinite(Number(rt.ref_lufs)) && rt.ref_lufs !== null
+ ? Number(rt.ref_lufs) : SBE_RT_REF;
+ // Unchanged fader (within rounding) → keep the stored level verbatim, so a
+ // bed that was never touched rebuilds bit-identically.
+ if (Math.abs(g - sbeRtGain(stored, ref)) < 5e-4) return stored;
+ return sbeRtClampLevel(ref + 20 * Math.log10(g));
+}
+
+// A room-tone track from the server's facts — the mirror of
+// `room_tone_new_track`: one locked strip, 0 → the film's end (bounded by the
+// file), the fader set for `level`.
+function sbeRtNewTrack(facts, filmLen, level, tid) {
+ const f = facts || {};
+ const dur = sbeRound(sbeNum(f.duration));
+ const end = sbeRound(Math.max(SBE_TRACK_STRIP_MIN, Math.min(sbeNum(filmLen), dur)));
+ const ref = isFinite(Number(f.ref_lufs)) && f.ref_lufs !== null ? Number(f.ref_lufs) : SBE_RT_REF;
+ const lvl = sbeRtClampLevel(level);
+ const label = String(f.label || '');
+ const t = {
+ id: tid || ('t' + sbeNewId().slice(1)),
+ name: SBE_RT_NAME,
+ room_tone: { variant: String(f.variant || 'film'), seed: Math.round(sbeNum(f.seed, 1)) || 1,
+ level: lvl, ref_lufs: Math.round(ref * 100) / 100 },
+ strips: [{ id: sbeNewId(), path: String(f.path || ''), start: 0, end: end,
+ film_start: 0, duration: dur,
+ title: label ? SBE_RT_NAME + ' · ' + label : SBE_RT_NAME, locked: true }],
+ };
+ const g = sbeRtGain(lvl, ref);
+ if (Math.abs(g - 1) > 1e-9) t.gain = g;
+ return t;
+}
+
+// Put a room-tone track on the timeline: in the old one's lane (same id, same
+// mute) when there is one, else as a new track under the others.
+function sbeRtPlace(tracks, track) {
+ const out = sbeTsCopy(tracks);
+ const t = JSON.parse(JSON.stringify(track || {}));
+ const cur = sbeRtFind(out);
+ if (cur) {
+ t.id = cur.track.id;
+ if (cur.track.muted === true) t.muted = true;
+ out[cur.ti] = t;
+ } else {
+ out.push(t);
+ }
+ return { tracks: out, ok: true, added: t, track: t.id };
+}
+
+function sbeRtRemove(tracks) {
+ const cur = sbeRtFind(tracks);
+ if (!cur) return { tracks: tracks, ok: false, why: 'there is no room tone on this timeline' };
+ return { tracks: sbeTsCopy(tracks).filter((x, i) => i !== cur.ti), ok: true,
+ removed: cur.track };
+}
+
+// A new level: the label and the fader move together.
+function sbeRtSetLevel(tracks, level) {
+ const out = sbeTsCopy(tracks);
+ const cur = sbeRtFind(out);
+ if (!cur) return { tracks: tracks, ok: false, why: 'there is no room tone on this timeline' };
+ const lvl = sbeRtClampLevel(level);
+ cur.track.room_tone.level = lvl;
+ const g = sbeRtGain(lvl, cur.track.room_tone.ref_lufs);
+ if (Math.abs(g - 1) > 1e-9) cur.track.gain = g; else delete cur.track.gain;
+ return { tracks: out, ok: true };
+}
+
+// KEEP THE BED AS LONG AS THE FILM — the mirror of `room_tone_fit`. Only the
+// untouched case (one strip starting at 0) is fitted; a bed somebody split or
+// moved is an arrangement. `short` says the film outgrew the file.
+function sbeRtFit(tracks, filmLen) {
+ const cur = sbeRtFind(tracks);
+ if (!cur) return { tracks: tracks, changed: false, short: false };
+ const ss = cur.track.strips || [];
+ if (ss.length !== 1 || Math.abs(sbeNum(ss[0].film_start)) > 1e-6) {
+ return { tracks: tracks, changed: false, short: false };
+ }
+ const s = ss[0];
+ const want = Math.max(0, sbeNum(filmLen));
+ const st = sbeNum(s.start);
+ const dur = sbeNum(s.duration) || (want + st);
+ const end = sbeRound(st + Math.max(SBE_TRACK_STRIP_MIN, Math.min(want, dur - st)));
+ const short = want > dur - st + 1e-3;
+ if (Math.abs(sbeNum(s.end) - end) <= 1e-6) return { tracks: tracks, changed: false, short: short };
+ const out = sbeTsCopy(tracks);
+ out[cur.ti].strips[0].end = end;
+ return { tracks: out, changed: true, short: short };
+}
+
+// The picture clips a "From this film" bed listens to, in SOURCE seconds.
+function sbeRtClips(clips) {
+ return (clips || []).filter(c => c && c.path && sbeKind(c) === 'video')
+ .map(c => ({ path: c.path, start: sbeRound(c.start), end: sbeRound(c.end) }));
+}
+
+// ---- the card, and the requests behind it ---------------------------------
+async function sbeRtRequest(variant, seed, filmLen) {
+ const fd = new URLSearchParams();
+ fd.set('id', SBE.id);
+ fd.set('variant', variant);
+ fd.set('seed', String(seed));
+ fd.set('film_len', String(sbeRound(filmLen)));
+ fd.set('clips', JSON.stringify(sbeRtClips(SBE.clips)));
+ try {
+ return await (await fetch('/storyboard/edit/room-tone', { method: 'POST', body: fd })).json();
+ } catch (e) { return { ok: false, error: String(e) }; }
+}
+
+async function edRtLoad() {
+ if (ED.rtInfo) return ED.rtInfo;
+ try {
+ const r = await (await fetch('/storyboard/edit/room-tone')).json();
+ if (r && r.ok) ED.rtInfo = r;
+ } catch (e) { /* the card says it could not load */ }
+ return ED.rtInfo || null;
+}
+
+// The card on the Sound tab. Painted from the timeline: what is on, at what
+// level, and what the picker would change.
+function edRtPaint() {
+ const card = document.getElementById('edRoomTone');
+ if (!card) return;
+ card.hidden = (ED.src !== 'sound');
+ if (card.hidden) return;
+ const info = ED.rtInfo;
+ const pick = document.getElementById('edRtVariant');
+ const cur = (SBE.open ? sbeRtFind(SBE.tracks) : null);
+ const rt = cur ? cur.track.room_tone : null;
+ if (pick && info && pick.dataset.filled !== '1') {
+ pick.innerHTML = info.variants.map(v =>
+ '<option value="' + escapeHtml(v.id) + '" title="' + escapeHtml(v.blurb || '') + '">'
+ + escapeHtml(v.label) + '</option>').join('');
+ pick.dataset.filled = '1';
+ pick.value = (rt && rt.variant) || info.default_variant || 'film';
+ }
+ if (pick && rt && !ED.rtPicked) pick.value = rt.variant;
+ const level = cur ? sbeRtLevelOf(cur.track)
+ : sbeRtClampLevel(ED.rtLevel === undefined ? SBE_RT_DEFAULT_LEVEL : ED.rtLevel);
+ const slider = document.getElementById('edRtLevel');
+ if (slider && !ED.rtSliding) slider.value = String(level);
+ const out = document.getElementById('edRtLevelOut');
+ if (out) out.textContent = sbeRtFmtLevel(level);
+ const row = info ? (info.variants || []).find(v => pick && v.id === pick.value) : null;
+ if (pick) pick.title = row ? row.label + ' — ' + row.blurb : 'Which room tone';
+ const status = document.getElementById('edRtStatus');
+ const busy = !!ED.rtBusy;
+ if (status) {
+ let msg;
+ if (busy) msg = 'Making the room tone…';
+ else if (!SBE.open) msg = 'Open a __SEQ__ to lay room tone under it.';
+ else if (cur) {
+ const muted = cur.track.muted === true;
+ msg = sbeTrackLabel(cur.ti) + ' · ' + sbeRtVariantLabel(rt.variant) + ' · take '
+ + (rt.seed || 1) + (muted ? ' · muted' : '')
+ + ((cur.track.strips || []).length !== 1 ? ' · edited by hand' : '');
+ } else msg = 'Not on this __SEQ__ yet.';
+ status.textContent = msg;
+ status.classList.toggle('is-on', !!cur && !busy);
+ }
+ const note = document.getElementById('edRtNote');
+ if (note) {
+ const fb = ED.rtFallback || '';
+ note.textContent = fb;
+ note.hidden = !fb;
+ }
+ const add = document.getElementById('edRtAdd');
+ const take = document.getElementById('edRtTake');
+ const del = document.getElementById('edRtRemoveBtn');
+ const changed = !!(cur && pick && pick.value !== rt.variant);
+ if (add) {
+ add.textContent = cur ? (changed ? 'Use this sound' : 'Rebuild') : 'Add room tone';
+ add.disabled = busy || !SBE.open;
+ add.title = cur
+ ? (changed ? 'Swap the room tone for ' + (row ? row.label : 'this sound') + ', same level'
+ : 'Make the bed again from the timeline as it is now (after a re-cut)')
+ : 'Lay this sound under the whole __SEQ__ on its own audio track — cuts stop dropping to silence';
+ add.classList.toggle('primary', !cur || changed);
+ }
+ if (take) { take.hidden = !cur; take.disabled = busy; }
+ if (del) { del.hidden = !cur; del.disabled = busy; }
+ const auto = document.getElementById('edRtAutoBox');
+ if (auto && info) auto.checked = info.auto !== false;
+}
+
+function sbeRtFmtLevel(v) {
+ return String(sbeRtClampLevel(v).toFixed(0)).replace('-', '−') + ' LUFS';
+}
+
+function sbeRtVariantLabel(id) {
+ const rows = ((ED.rtInfo || {}).variants) || [];
+ const r = rows.find(v => v.id === id);
+ return r ? r.label : String(id || '');
+}
+
+// ♪ menu → "Room tone…": the Sound tab, with the card in view.
+async function edRtOpen() {
+ if (typeof sbePopCloseAll === 'function') sbePopCloseAll('');
+ if (document.body && document.body.classList.contains('ed-focus')
+ && typeof sbePanelsApply === 'function') sbePanelsApply(false);
+ if (ED.src !== 'sound') edPoolSrc('sound');
+ await edRtLoad();
+ edRtPaint();
+ const card = document.getElementById('edRoomTone');
+ if (card && card.scrollIntoView) card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ const pick = document.getElementById('edRtVariant');
+ if (pick) { try { pick.focus(); } catch (e) {} }
+}
+
+function edRtPick() { ED.rtPicked = true; edRtPaint(); }
+
+// Add / swap / rebuild (`kind` 'apply') or a new take ('take').
+async function edRtApply(kind) {
+ if (!SBE.open || !SBE.id) {
+ phosToast('Open a __SEQ__ first — room tone belongs to a timeline.', {});
+ return false;
+ }
+ if (ED.rtBusy) return false;
+ const filmLen = sbeFilmDuration(SBE.clips);
+ if (filmLen <= 0) {
+ phosToast('Put a clip on the timeline first — the room tone runs as long as the __SEQ__.', {});
+ return false;
+ }
+ await edRtLoad();
+ const cur = sbeRtFind(SBE.tracks);
+ const pick = document.getElementById('edRtVariant');
+ const variant = (pick && pick.value) || (cur && cur.track.room_tone.variant) || 'film';
+ let seed = 1;
+ if (cur) {
+ const was = Math.round(sbeNum(cur.track.room_tone.seed, 1)) || 1;
+ seed = kind === 'take' ? was + 1 : (cur.track.room_tone.variant === variant ? was : 1);
+ }
+ // THE FADER IS THE TRUTH, not the metadata. `room_tone.level` is written
+ // when the bed is made; dragging the track's fader afterwards writes
+ // `track.gain` and leaves that number stale. Rebuilding from the stale one
+ // threw the user's setting away — a bed pulled down to 10% came back at
+ // 35% (+11 dB) on a New take. Read the gain that is actually on the track
+ // and derive the level from it whenever the two disagree.
+ const level = cur ? sbeRtLevelOfTrack(cur.track)
+ : sbeRtClampLevel(ED.rtLevel === undefined ? SBE_RT_DEFAULT_LEVEL : ED.rtLevel);
+ // WHICH FILM ASKED. The request takes seconds; the user can open another
+ // __SEQ__ while it runs, and the response used to land on whatever was open
+ // when it came back — replacing THAT film's bed with this one's.
+ const askedFor = String(SBE.id || '');
+ ED.rtBusy = true;
+ edRtPaint();
+ const r = await sbeRtRequest(variant, seed, filmLen);
+ ED.rtBusy = false;
+ if (String(SBE.id || '') !== askedFor) {
+ edRtPaint();
+ phosToast('You opened another __SEQ__ while the room tone was being made, '
+ + 'so it was not placed.', { kind: 'warn', duration: 6000 });
+ return false;
+ }
+ if (!r || !r.ok) {
+ edRtPaint();
+ phosToast((r && r.error) || 'The room tone could not be made.', { kind: 'danger' });
+ return false;
+ }
+ // The timeline may have moved while the bed was being made.
+ const nowLen = sbeFilmDuration(SBE.clips);
+ const tr = sbeRtNewTrack(r, nowLen, level, cur ? cur.track.id : '');
+ const res = sbeTsMutate(ts => sbeRtPlace(ts, tr));
+ ED.rtPicked = false;
+ ED.rtFallback = r.fallback
+ ? ('Not enough quiet sound in these clips (' + r.fallback + ') — '
+ + (r.label || 'a preset') + ' stands in.')
+ : '';
+ SBE.rtLen = nowLen;
+ edRtPaint();
+ if (!res) return false;
+ const idx = (SBE.tracks || []).findIndex(t => String(t.id) === String(res.track));
+ phosToast(SBE_RT_NAME + ' on ' + sbeTrackLabel(idx) + ': ' + (r.label || variant)
+ + (kind === 'take' ? ', take ' + seed : '') + ', ' + sbeRtFmtLevel(level) + '.',
+ { kind: 'success', duration: 5000 });
+ return true;
+}
+
+function edRtRemove() {
+ if (!SBE.open) return;
+ if (sbeTsMutate(ts => sbeRtRemove(ts))) {
+ ED.rtFallback = '';
+ edRtPaint();
+ phosToast('Room tone removed — Undo brings it back.', { duration: 5000 });
+ }
+}
+
+// The level slider: live on input, one undo step on change (the rule every
+// slider here follows). With no room tone on yet it only sets what Add uses.
+function edRtLevelSlide(v) {
+ const out = document.getElementById('edRtLevelOut');
+ if (out) out.textContent = sbeRtFmtLevel(v);
+ ED.rtLevel = sbeRtClampLevel(v);
+ if (!SBE.open || !sbeRtFind(SBE.tracks)) return;
+ const r = sbeRtSetLevel(SBE.tracks, v);
+ if (!r.ok) return;
+ if (!ED.rtBefore) ED.rtBefore = sbeSnapshot();
+ ED.rtSliding = true;
+ SBE.tracks = r.tracks;
+ sbePaintTracks();
+ sbeStripSync();
+}
+
+function edRtLevelCommit(v) {
+ edRtLevelSlide(v);
+ ED.rtSliding = false;
+ const before = ED.rtBefore;
+ ED.rtBefore = null;
+ if (!before || JSON.stringify(JSON.parse(before).tracks || []) === JSON.stringify(SBE.tracks)) {
+ edRtPaint();
+ return;
+ }
+ sbeTsCommit(before);
+ edRtPaint();
+}
+
+// "Add room tone to automatic cuts" — a panel setting, not a film one.
+async function edRtAuto(on) {
+ const fd = new URLSearchParams();
+ fd.set('room_tone_auto', on ? '1' : '0');
+ try {
+ const r = await (await fetch('/settings', { method: 'POST', body: fd })).json();
+ if (r && r.ok === false) throw new Error(r.error || 'refused');
+ if (ED.rtInfo) ED.rtInfo.auto = !!on;
+ phosToast(on ? 'Automatic cuts get room tone from now on.'
+ : 'Automatic cuts come without room tone from now on.', { duration: 4000 });
+ } catch (e) {
+ phosToast('That setting could not be saved: ' + e, { kind: 'danger' });
+ }
+ edRtPaint();
+}
+
+// FOLLOW THE FILM. Called from sbePaint: when the film's length changed since
+// the last look, the untouched bed is refit — part of the edit that changed
+// the length, not an undo step of its own — and a film that outgrew the file
+// gets a longer bed, made in the background and swapped in.
+function sbeRtFollow() {
+ const cur = sbeRtFind(SBE.tracks);
+ const len = sbeFilmDuration(SBE.clips);
+ if (!cur) { SBE.rtLen = len; return; }
+ if (SBE.rtLen !== undefined && Math.abs(SBE.rtLen - len) < 1e-6) return;
+ SBE.rtLen = len;
+ const r = sbeRtFit(SBE.tracks, len);
+ if (r.changed) {
+ SBE.tracks = r.tracks;
+ SBE.dirty = true;
+ sbeQueueSave();
+ }
+ if (r.short && len > 0) {
+ if (SBE.rtGrowTimer) clearTimeout(SBE.rtGrowTimer);
+ SBE.rtGrowTimer = setTimeout(sbeRtGrow, 900);
+ }
+}
+
+async function sbeRtGrow() {
+ SBE.rtGrowTimer = null;
+ const cur = sbeRtFind(SBE.tracks);
+ if (!SBE.open || !cur || ED.rtBusy) return;
+ const len = sbeFilmDuration(SBE.clips);
+ if (!sbeRtFit(SBE.tracks, len).short) return;
+ const rt = cur.track.room_tone;
+ const id = SBE.id;
+ ED.rtBusy = true;
+ edRtPaint();
+ const r = await sbeRtRequest(rt.variant, rt.seed, len);
+ ED.rtBusy = false;
+ edRtPaint();
+ if (!r || !r.ok || SBE.id !== id) return;
+ const now = sbeRtFind(SBE.tracks);
+ if (!now || (now.track.strips || []).length !== 1) return;
+ const out = sbeTsCopy(SBE.tracks);
+ const s = out[now.ti].strips[0];
+ s.path = r.path;
+ s.duration = sbeRound(sbeNum(r.duration));
+ const fit = sbeRtFit(out, sbeFilmDuration(SBE.clips));
+ SBE.tracks = fit.tracks;
+ SBE.dirty = true;
+ sbePaint();
+ sbeQueueSave();
+}
+
// Where a pool row would land on the audio tracks: {tid, at}, or null.
function edPoolOverTracks(ev) {
const box = sbeEl('sbeTracks');
@@ -7543,6 +8060,7 @@ function sbeAudioFadeMarks(c, w) {
// stays "move the strip" — the gesture every lane on this timeline already
// uses — so the control case is opt-in and the simple case is untouched.
function sbeOnAudioDbl(ev) {
+ if (sbeAudioSmall()) { sbeSoundModeSet(true); return; }
const blk = ev.target.closest ? ev.target.closest('.sbe-aclip') : null;
if (!blk) return;
if (ev.target.closest('.sbe-kf') || ev.target.closest('.sbe-fade-h')) return;
@@ -7824,7 +8342,6 @@ function sbeAudioLaneAtY(y) {
// "ALTERNATE SOUND LANES" — the one click that re-lays an existing timeline's
// clip sound A, B, A… without moving a picture or a sound. One undo step.
function sbeAlternateSel() {
- sbeAudioTouch({ open: true });
sbePopCloseAll('');
const ok = sbeMutate(cs => sbeAlternateLanes(cs));
if (ok) {
@@ -7843,7 +8360,6 @@ function sbeSoundLaneSet(id, lane) {
}
function sbeToggleAudioLink() {
- sbeAudioTouch({ open: true });
const c = sbeById(SBE.clips, SBE.sel);
if (!c) return;
const w = sbeClipAudio(c);
@@ -7931,7 +8447,6 @@ function sbeToggleClipMute() {
// inspector. An explicit `id` is a click on one flag and means that strip
// alone; no id means the selection, which may be several.
function sbeResyncSel(id) {
- sbeAudioTouch({ open: true });
if (!id) {
const ids = sbeSelIds().filter(x => {
const c = sbeById(SBE.clips, x);
@@ -8068,14 +8583,13 @@ function sbePaintHeads() {
if (sz) {
const small = sbeAudioSmall();
const hint = (typeof shortcutHint === 'function')
- ? shortcutHint('editor.soundLanes') : '';
+ ? shortcutHint('editor.soundMode') : '';
sz.textContent = small ? '▸' : '▾';
sz.setAttribute('aria-expanded', small ? 'false' : 'true');
sz.title = (small
- ? 'Sound lanes are small. Click to put them back at full height and keep them there'
- + (SBE.aPin === 'small' ? '' : ' — or click any sound to open them while you work')
- : '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') + '.' + hint;
+ ? 'Sound mode — A1, A2 and every audio track at full height, the picture small'
+ : 'Picture mode — the sound lanes become thin strips and the picture gets the height')
+ + '.' + hint;
}
}
@@ -8291,10 +8805,10 @@ function sbeCbarModel() {
? 'The soundtrack on A2 is selected, not a shot — its file, mode and level '
+ 'are on the A2 head, and Duplicate copies it onto an audio track. ' + pick
: (!n && SBE.ovSel) ? 'A title or card is selected, not a shot '
- + '— its own controls are in the panel on the right, and '
+ + '— its own controls are in the Inspector (⌘I), and '
+ '⌫ removes it. ' + pick
: ((!n && SBE.txSel) ? 'A cut is selected, not a shot — set its '
- + 'transition in the panel on the right. ' + pick
+ + 'transition in the Inspector (⌘I). ' + pick
: pick);
const rows = [
{ id: 'sbeCbSplit', act: 'sbeSplitHere()', label: 'Split',
@@ -8387,7 +8901,8 @@ function sbeCbarModel() {
why: !n ? noSel
: (many ? 'Pick one clip — each fix is its own render.'
: (!vid ? 'Only a video clip can be upscaled — a still or a black '
- + 'slug has no frames to fix.' : '')),
+ + 'slug has no frames to fix.'
+ : (isUpscaledPath(c && c.path) ? 'This clip is already upscaled.' : ''))),
title: 'Upscale & Face Fix — renders this clip again at twice the size with LTX-2.5 detail, '
+ '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 '
@@ -8429,6 +8944,9 @@ function sbePaintCbar() {
if (lab && lab.textContent !== r.label) lab.textContent = r.label;
el.disabled = !!r.why;
el.title = r.why || r.title;
+ // ICONS ONLY on the row, so the tooltip leads with the name.
+ el.title = r.label + '\n' + el.title;
+ el.setAttribute('aria-label', r.label);
el.classList.toggle('is-on', !!r.on);
if (r.icon) {
const use = el.querySelector('use');
@@ -9191,6 +9709,15 @@ function sbeFramingReset() {
sbeApplyPreviewFraming(null);
}
+// A play button is a triangle, a pause button two bars — the words are in the
+// tooltip. One helper for both monitors so they cannot drift apart.
+function sbePlayGlyph(btnId, useId, playing) {
+ const use = sbeEl(useId);
+ if (use && use.setAttribute) use.setAttribute('href', playing ? '#ic-pause' : '#ic-play');
+ const btn = sbeEl(btnId);
+ if (btn && btn.setAttribute) btn.setAttribute('aria-label', playing ? 'Pause' : 'Play');
+}
+
function sbePaintChrome() {
const board = sbeEl('sbeBoardBtn');
if (board) board.hidden = !SBE.id;
@@ -9205,7 +9732,8 @@ function sbePaintChrome() {
save.classList.toggle('primary', !!SBE.dirty && !SBE.saving);
save.classList.toggle('ghost-btn', !(SBE.dirty && !SBE.saving));
}
- sbeEl('sbePlayBtn').textContent = SBE.playing ? 'Pause' : 'Play';
+ sbePlayGlyph('sbePlayBtn', 'sbePlayUse', SBE.playing);
+ 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
// here, so the control can never disagree with the track it is scaling.
@@ -9240,6 +9768,13 @@ function sbePaintChrome() {
const wrap = sbeEl('sbeUnplacedWrap');
const list = SBE.unplaced || [];
wrap.hidden = !list.length;
+ // With the rail closed the offer is a count on the bar under the picture;
+ // clicking it opens the rail, where Place lives.
+ const ub = sbeEl('sbeUnplacedBtn');
+ if (ub) {
+ ub.hidden = !list.length || !!SBE.inspect;
+ ub.textContent = list.length + ' rendered, not placed';
+ }
if (list.length) {
sbeEl('sbeUnplaced').innerHTML = list.map((u, i) => {
const at = (u.slot && u.slot.film_start !== undefined)
@@ -9482,6 +10017,12 @@ function sbeOnTrackMove(ev) {
const r = sbeReorderTo(SBE.clips, d.id, Math.max(0, d.t0 + dt));
if (r.ok) SBE.clips = r.clips;
} 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.
+ if (d.mode === 'move') {
+ d.toSrc = sbeSrcDropHover(ev, true);
+ if (d.toSrc) { SBE.clips = JSON.parse(d.before); sbePaint(); return; }
+ }
// A move or a trim always works from the SNAPSHOT: the model clamps at
// neighbours, and re-applying deltas to an already-clamped state would
// let a pointer that kept going drag the clip through the wall.
@@ -9537,6 +10078,16 @@ function sbeOnTrackUp(ev) {
if (!d) return;
document.querySelectorAll('.sbe-clip.is-drag').forEach(el => el.classList.remove('is-drag'));
const trk = sbeEl('sbeTrack'); if (trk) trk.classList.remove('is-ripple');
+ if (d.mode === 'move') sbeSrcDropHover(null, false);
+ if (d.toSrc) {
+ SBE.clips = JSON.parse(d.before);
+ const c = SBE.clips.find(x => String(x.id) === String(d.id));
+ sbePaint();
+ if (!sbeSrcLoadClip(c) && typeof phosToast === 'function') {
+ phosToast('Black has no picture to preview.', { duration: 3000 });
+ }
+ return;
+ }
// A CLICK, NOT A DRAG — so the two modifiers this gesture shares with the
// selection finally get to mean the selection. ⌘ could not be decided at
// pointerdown (the same chord is ripple-drag) and a plain click inside a
@@ -9671,7 +10222,7 @@ async function sbeShowFrameAt(t) {
if (!c) {
v.classList.remove('is-on');
if (img) img.classList.remove('is-on');
- sbeEl('sbeBadge').textContent = SBE.clips.length ? 'nothing plays here' : 'no clips';
+ sbeProgInfo(SBE.clips.length ? 'nothing plays here' : 'no clips', '');
return;
}
const kind = sbeKind(c);
@@ -9682,7 +10233,7 @@ async function sbeShowFrameAt(t) {
// preview is not an approximation at all.
v.classList.remove('is-on');
if (img) img.classList.remove('is-on');
- sbeEl('sbeBadge').textContent = 'black · ' + sbeLen(c).toFixed(2) + 's';
+ sbeProgInfo('black · ' + sbeLen(c).toFixed(2) + 's', '');
sbePaintTrack();
return;
}
@@ -9696,18 +10247,17 @@ async function sbeShowFrameAt(t) {
if (img.getAttribute('src') !== url) img.src = url;
img.classList.add('is-on');
}
- sbeEl('sbeBadge').textContent =
- (c.title || String(c.path || '').split('/').pop()) + ' · still · ' +
- sbeLen(c).toFixed(2) + 's';
+ sbeProgInfo((c.title || String(c.path || '').split('/').pop()) + ' · still · ' +
+ sbeLen(c).toFixed(2) + 's', '');
sbePaintTrack();
return;
}
if (img) img.classList.remove('is-on');
await sbeLoadInto(v, c, sbeNum(c.start) + (t - sbeNum(c.film_start)) * sbeSpeed(c));
v.classList.add('is-on');
- sbeEl('sbeBadge').textContent =
- (c.title || c.path.split('/').pop()) + ' · ' + sbeNum(c.start).toFixed(2) + '–' +
- sbeNum(c.end).toFixed(2) + ' · ' + (c.proxy ? 'proxy' : 'SOURCE (slow — run Prepare)');
+ sbeProgInfo((c.title || c.path.split('/').pop()) + ' · ' + sbeNum(c.start).toFixed(2) + '–' +
+ sbeNum(c.end).toFixed(2) + (c.proxy ? '' : ' · source'),
+ c.proxy ? '' : 'SOURCE — slow to seek. Run Prepare (A2 head ▾) for proxies.');
// A SCRUB SHOWS THE TRUE OPACITY at the second it landed on, which is the
// only way a fade can be judged without playing the whole clip.
sbeFadePaint(t);
@@ -9825,7 +10375,24 @@ function sbeSrcAdd() {
edPoolAdd(SBE.srcIndex);
}
+// WHAT IS UNDER THE PLAYHEAD, in the strip under the picture. The badge on the
+// picture used to carry this and hid the top of the frame — "the name of the
+// clip in the full screen is hiding a part of what is visible". It now carries
+// only a WARNING (a clip with no proxy), and only on hover.
+function sbeProgInfo(text, warn) {
+ const el = sbeEl('sbeProgClip');
+ if (el) { el.textContent = text || ''; el.title = text || ''; }
+ const badge = sbeEl('sbeBadge');
+ if (badge) {
+ badge.textContent = warn || '';
+ badge.hidden = !warn;
+ if (badge.classList) badge.classList.toggle('is-warn', !!warn);
+ }
+}
+
function sbePaintSource() {
+ const mon = sbeEl('sbeSrcMon');
+ if (mon) mon.hidden = !sbeSrcShown();
const row = SBE.source;
const name = sbeEl('sbeSrcName');
const add = sbeEl('sbeSrcAddBtn');
@@ -9836,7 +10403,7 @@ function sbePaintSource() {
if (!row) {
name.textContent = 'Nothing loaded';
if (add) add.disabled = true;
- if (play) { play.disabled = true; play.textContent = 'Play'; }
+ if (play) { play.disabled = true; sbePlayGlyph('sbeSrcPlayBtn', 'sbeSrcPlayUse', false); }
if (badge) badge.hidden = true;
if (empty) empty.hidden = false;
return;
@@ -9851,7 +10418,7 @@ function sbePaintSource() {
if (add) add.disabled = !(SBE.open && SBE.id) || SBE.srcIndex < 0;
if (play) {
play.disabled = (row.kind === 'still');
- play.textContent = SBE.srcPlaying ? 'Pause' : 'Play';
+ sbePlayGlyph('sbeSrcPlayBtn', 'sbeSrcPlayUse', SBE.srcPlaying);
}
if (empty) empty.hidden = true;
if (badge) {
@@ -9915,8 +10482,6 @@ window.ED = { src: 'film', rows: [], films: [], film: '', loading: false,
function edPoolSrc(name) {
ED.src = name;
- // Opening the Sound pool is somebody going to put a sound somewhere.
- if (name === 'sound') sbeAudioTouch({ open: true });
const tabs = document.getElementById('edPoolTabs');
if (tabs) tabs.querySelectorAll('.pill-btn').forEach(b =>
b.classList.toggle('active', b.dataset.src === name));
@@ -9925,6 +10490,9 @@ function edPoolSrc(name) {
// Upload belongs to the source that shows what was uploaded.
const up = document.getElementById('edPoolUploadBtn');
if (up) up.hidden = (name !== 'images');
+ // Black and titles are pictures; the Sound tab has the Room tone card there.
+ const make = document.querySelector('.ed-pool-make');
+ if (make) make.hidden = (name === 'sound');
ED.limit = 60;
edPoolRefresh();
}
@@ -10059,6 +10627,7 @@ async function edPoolRefresh(force) {
}
ED.loading = false;
edPoolPaint();
+ if (ED.src === 'sound') edRtLoad().then(edRtPaint); else edRtPaint();
}
async function edPoolLoadFilms() {
@@ -10119,6 +10688,8 @@ function edPoolPaint() {
? 'No generations yet. Render something in Video or Storyboard and it lands here.'
: ED.src === 'images'
? 'No images yet — press Upload to bring one in from this Mac, or make one in the Image studio.'
+ : ED.src === 'sound'
+ ? 'No sound files yet. ♪ on the track heads adds one from this Mac — or lay Room tone above.'
: ED.src === 'other'
? (ED.films && ED.films.length
? 'That __SEQ__ has no rendered clips yet.'
@@ -10306,6 +10877,59 @@ async function edPoolAdd(i, dropAt) {
sbeLoad(true);
}
+// ---------------------------------------------------------------------------
+// DROP ON THE SOURCE MONITOR — a pool row or a timeline clip, to watch it
+// ---------------------------------------------------------------------------
+// "a place where you can drag the clips and see them." Both drags are pointer
+// gestures (see below), so the monitor is a rectangle the pointer is over, not
+// an HTML5 drop zone. `ev` null clears the highlight. Returns whether the
+// pointer is over the monitor and the thing dragged can play there (a sound
+// has no picture, so it never can). A hidden monitor comes back for the drag:
+// `is-drop-ready` dashes its border while any clip is in the air.
+function sbeSrcDropHover(ev, playable) {
+ const mon = sbeEl('sbeSrcMon');
+ if (!mon || !mon.classList) return false;
+ if (!ev) {
+ mon.classList.remove('is-drop-ready', 'is-drop-over');
+ return false;
+ }
+ const stage = sbeEl('sbeSrcStage');
+ let over = false;
+ if (playable && !mon.hidden && stage && stage.getBoundingClientRect) {
+ const r = stage.getBoundingClientRect();
+ over = r.width > 0 && ev.clientX >= r.left && ev.clientX <= r.right &&
+ ev.clientY >= r.top && ev.clientY <= r.bottom;
+ }
+ mon.classList.toggle('is-drop-ready', !!playable && !over);
+ mon.classList.toggle('is-drop-over', over);
+ return over;
+}
+
+// A TIMELINE CLIP IN THE SOURCE MONITOR: the file it plays, as a pool row. The
+// pool index is looked up by path so "Add to timeline" works when the clip is
+// also in the pool, and is off (-1) when it is not.
+function sbeSrcLoadClip(c) {
+ if (!c || !c.path || sbeKind(c) === 'slug') return false;
+ const list = document.getElementById('edPoolList');
+ const rows = (list || {})._rows || [];
+ const i = rows.findIndex(r => r && r.path === c.path);
+ const row = i >= 0 ? rows[i] : {
+ kind: sbeKind(c) === 'still' ? 'still' : 'video', path: c.path,
+ title: c.title || sbeNiceName(String(c.path).split('/').pop()),
+ duration_s: sbeNum(c.duration, 0) || undefined,
+ };
+ SBE.source = row;
+ SBE.srcIndex = i;
+ if (list && list.querySelectorAll) {
+ list.querySelectorAll('.ed-pool-row').forEach((el, k) => el.classList.toggle('is-source', k === i));
+ }
+ sbeSrcLoad(row);
+ sbePaintSource();
+ sbePaintPanels();
+ sbePaint();
+ return true;
+}
+
// ---------------------------------------------------------------------------
// DRAG: a pool row onto the track
// ---------------------------------------------------------------------------
@@ -10352,7 +10976,17 @@ function edPoolDragMove(ev) {
}
d.ghost.style.left = (ev.clientX + 12) + 'px';
d.ghost.style.top = (ev.clientY + 12) + 'px';
+ // THE SOURCE MONITOR IS A TARGET TOO: over it, the drop loads the clip
+ // there instead of cutting it in, and nothing on the tracks lights up.
+ const toSrc = sbeSrcDropHover(ev, d.row.kind !== 'sound');
+ d.toSrc = toSrc;
const track = sbeEl('sbeTrack');
+ if (toSrc) {
+ if (track) track.classList.remove('is-dropping');
+ SBE.dropAt = null; SBE.tsDrop = null;
+ sbePaintTrack(); sbePaintTracks();
+ return;
+ }
// A SOUND lands on an audio track only; a VIDEO dropped on one gives its
// sound; anything dropped on the picture track is a clip, as before.
const onTracks = edPoolOverTracks(ev);
@@ -10395,6 +11029,7 @@ async function edPoolDragEnd(ev) {
SBE.dropAt = null;
const tsDrop = SBE.tsDrop;
SBE.tsDrop = null;
+ sbeSrcDropHover(null, false);
sbePaintTrack();
sbePaintTracks();
if (!d.moved) return; // a press that never travelled
@@ -10405,6 +11040,7 @@ async function edPoolDragEnd(ev) {
// a clip on the timeline, click another clip to preview it, and the source
// monitor does nothing until you click a second time.
ED.suppressClick = !!(d.el && ev.target && d.el.contains(ev.target));
+ 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
await edPoolAdd(d.index, at);
@@ -10677,15 +11313,21 @@ function sbeSetMute(on, note, remember) {
if (a) { a.muted = SBE.muted; }
const b = sbeEl('sbeMuteBtn');
if (b) {
- b.textContent = SBE.muted ? '🔇' : '🔊';
+ const use = sbeEl('sbeMuteUse');
+ if (use && use.setAttribute) use.setAttribute('href', SBE.muted ? '#ic-mute' : '#ic-sound');
+ b.setAttribute('aria-label', SBE.muted ? 'Unmute the preview' : 'Mute the preview');
b.classList.toggle('is-off', SBE.muted);
- b.title = note || (SBE.muted ? 'Sound off — click to unmute (M)' : 'Sound on (M)');
+ b.title = note || (SBE.muted ? 'Sound off — click to unmute the preview (M)'
+ : 'Sound on — click to mute the preview (M)');
}
if (note) {
const el = sbeEl('sbeApprox');
if (el && el.dataset.muteNoted !== '1') {
el.dataset.muteNoted = '1';
- el.textContent = note + ' ' + el.textContent;
+ // The (i) stays a 16px circle on the tool row: the note goes into its
+ // tooltip and the circle turns amber to say there is one.
+ el.title = note + ' ' + el.title;
+ if (el.classList) el.classList.add('is-noted');
}
if (typeof phosToast === 'function' && !SBE.muteToasted) {
SBE.muteToasted = true;
@@ -10874,8 +11516,9 @@ function sbeSyncMusic() {
const el = sbeEl('sbeApprox');
if (el && el.dataset.musicNoted !== '1') {
el.dataset.musicNoted = '1';
- el.textContent = el.textContent +
+ el.title = el.title +
' The soundtrack cannot be played from here (it lives outside mlx_outputs) — the waveform, the beat grid and the render still use it.';
+ if (el.classList) el.classList.add('is-noted');
}
});
SBE.musicEl = a;
@@ -11765,11 +12408,25 @@ document.addEventListener('keydown', (ev) => {
// they cannot be hit while reaching for L or R, and because the bare
// letters are worth keeping free for the J/K/L transport this timeline does
// not have yet.
- // ⇧A — THE SOUND AREA'S SIZE, on a key, because it is the one thing on this
- // screen you reach for with both hands already on the timeline.
+ // ⇧A — SOUND MODE, on a key, because it is the one thing on this screen you
+ // reach for with both hands already on the timeline.
if (ev.shiftKey && !ev.metaKey && !ev.ctrlKey && !ev.altKey
&& (ev.key === 'A' || ev.key === 'a')) {
- ev.preventDefault(); sbeAudioPinToggle(); return;
+ ev.preventDefault(); sbeSoundModeToggle(); return;
+ }
+ // ⌘I — the Inspector. F — the Program monitor full screen. ` — the app's
+ // own panels out of the way. All three are toggles and none moves anything
+ // else on the screen.
+ if ((ev.metaKey || ev.ctrlKey) && !ev.altKey && !ev.shiftKey
+ && (ev.key === 'i' || ev.key === 'I')) {
+ ev.preventDefault(); sbeInspectToggle(); return;
+ }
+ if (!ev.metaKey && !ev.ctrlKey && !ev.altKey && !ev.shiftKey && (ev.key === 'f' || ev.key === 'F')) {
+ ev.preventDefault(); sbeFullscreen(); return;
+ }
+ if (!ev.metaKey && !ev.ctrlKey && !ev.altKey && !ev.shiftKey
+ && (ev.key === '`' || ev.code === 'Backquote')) {
+ ev.preventDefault(); sbePanelsToggle(); return;
}
if (ev.shiftKey && !ev.metaKey && !ev.ctrlKey && (ev.key === 'L' || ev.key === 'l')) {
ev.preventDefault(); sbeToggleAudioLink(); return;
@@ -11859,6 +12516,13 @@ document.addEventListener('click', (ev) => {
if (!track) return;
sbeSetMute(SBE.muted); // the button must agree with the stored state on load
track.addEventListener('pointerdown', sbeOnTrackDown);
+ // Double-click a clip: the Inspector, the way Premiere opens a clip's
+ // properties. Cuts (the transition mark) and titles are on their own paths.
+ track.addEventListener('dblclick', (ev) => {
+ if (!ev.target.closest || !ev.target.closest('.sbe-clip')) return;
+ if (ev.target.closest('.sbe-grip, .sbe-tx')) return;
+ sbeInspectSet(true);
+ });
// THE SECOND PLACE EVERY EDITOR'S HAND GOES. Until now a right-click on the
// picture lane got the browser's own menu — Reload, Save image as — over a
// film somebody was cutting.
@@ -11916,8 +12580,6 @@ document.addEventListener('click', (ev) => {
lane.addEventListener('pointerup', sbeOnMusicUp);
lane.addEventListener('pointercancel', sbeOnMusicUp);
lane.addEventListener('dblclick', sbeOnMusicDbl);
- lane.addEventListener('pointerenter', () => sbeAudioOver(true));
- lane.addEventListener('pointerleave', () => sbeAudioOver(false));
// The ghost belongs to the pointer, so it goes when the pointer does.
lane.addEventListener('pointerleave', () => {
if (SBE.kfGhost && SBE.kfGhost.id === '@music') {
@@ -11929,17 +12591,8 @@ document.addEventListener('click', (ev) => {
// THE POINTER ON THE SOUND AREA OPENS IT, which is also how anybody finds
// out that it opens: the lanes answer before they are used. On the
// CONTAINERS, which outlive every repaint of the strips inside them.
- const gutter = document.getElementById('sbeGutter');
- if (gutter) {
- gutter.addEventListener('pointermove', (ev) => sbeAudioOver(
- !!(ev.target.closest
- && ev.target.closest('.sbe-gh-aud, .sbe-gh-mus, .sbe-gh-trk, .sbe-gh-add'))));
- gutter.addEventListener('pointerleave', () => sbeAudioOver(false));
- }
const alane = document.getElementById('sbeAudioLane');
if (alane) {
- alane.addEventListener('pointerenter', () => sbeAudioOver(true));
- alane.addEventListener('pointerleave', () => sbeAudioOver(false));
alane.addEventListener('pointerdown', (ev) => { sbeStop(); sbeOnAudioDown(ev); });
alane.addEventListener('dblclick', sbeOnAudioDbl);
alane.addEventListener('pointermove', sbeOnAudioMove);
@@ -11959,8 +12612,6 @@ document.addEventListener('click', (ev) => {
tlanes.addEventListener('pointerup', sbeOnTsUp);
tlanes.addEventListener('pointercancel', sbeOnTsUp);
tlanes.addEventListener('dblclick', sbeOnTsDbl);
- tlanes.addEventListener('pointerenter', () => sbeAudioOver(true));
- tlanes.addEventListener('pointerleave', () => sbeAudioOver(false));
tlanes.addEventListener('contextmenu', sbeOnTsMenu);
tlanes.addEventListener('pointerleave', () => {
if (SBE.kfGhost && String(SBE.kfGhost.id).indexOf('@ts:') === 0) {
@@ -12257,12 +12908,18 @@ Object.assign(globalThis, {
sbePaintTsInspector, sbeTsStripAt, sbeTsLaneAt, sbeTsEnvGain, sbeTsLevelClick,
sbeOnTsDown, sbeOnTsMove, sbeOnTsUp, sbeTsGhost, sbeOnTsDbl, sbeOnTsMenu,
sbeTsAddSoundPath, edPoolSound, sbeAddSoundFile, edPoolOverTracks,
+ sbeRtClampLevel, sbeRtGain, sbeRtBedSeconds, sbeRtFind, sbeRtLevelOf,
+ sbeRtNewTrack, sbeRtPlace, sbeRtRemove, sbeRtSetLevel, sbeRtFit, sbeRtClips,
+ sbeRtRequest, edRtLoad, edRtPaint, sbeRtFmtLevel, sbeRtVariantLabel, edRtOpen,
+ edRtPick, edRtApply, edRtRemove, edRtLevelSlide, edRtLevelCommit, edRtAuto,
+ sbeRtFollow, sbeRtGrow,
// THE TWO CLIP-SOUND LANES — the model (for the harnesses) and the verbs the
// head button and the right-click menu call.
sbeSoundLane, sbeLaneName, sbeSetSoundLane, sbeAlternateLanes, sbeLaneAfter, sbeLaneFit,
sbeExtraLanesH, sbeAudioLaneAtY, sbeAlternateSel, sbeSoundLaneSet,
- sbeLaneBase, sbeLaneCap, sbeTlFloor, sbeTlRoof, sbeAudioSmall, sbeAudioBusy,
- sbeAudioWant, sbeAudioSync, sbeAudioArm, sbeAudioSet, sbeAudioTouch,
- sbeAudioOver, sbeAudioOpenFrom, sbeAudioPinRead, sbeAudioPinWrite,
- sbeAudioPinSet, sbeAudioPinToggle, sbeAudioSmallOnce,
+ sbeLaneBase, sbeLaneCap, sbeTlFloor, sbeTlRoof, sbeAudioSmall,
+ sbeAudioOpenFrom, sbeModeRead, sbeSoundMode, sbeSoundModeSet, sbeSoundModeToggle,
+ sbeInspectRead, sbeInspectSet, sbeInspectToggle, sbeSrcMonToggle, sbeSrcClose,
+ sbeFullscreen, sbePanelsRead, sbePanelsApply, sbePanelsToggle, sbePaintPanels,
+ sbeProgInfo, sbePlayGlyph, sbeTlPrefKey,
});
diff --git a/webapp/js/engines.js b/webapp/js/engines.js
index 78da45b..df493a4 100644
--- a/webapp/js/engines.js
+++ b/webapp/js/engines.js
@@ -189,20 +189,10 @@ function h3CurrentCell() {
let savedSt = null;
try { savedSt = localStorage.getItem('phos_h3_steps'); } catch (e) {}
if (savedSt) st.value = h3NormalizeSteps(savedSt);
- // And Turbo — but only restore an ON state when this install can actually
- // serve it. A user who downloaded the adapter, deleted it and reloaded must
- // come back on Standard, not on a mode that would fail at queue time.
+ // Turbo is folded into the Speed switch (Fast | Best): the form never posts
+ // it. renderH3Turbo() writes #h3_tristep from the saved speed.
const tb = document.getElementById('h3_turbo');
- if (!tb) return;
- let savedTb = null;
- try { savedTb = localStorage.getItem('phos_h3_turbo'); } catch (e) {}
- // Turbo is the DEFAULT when the adapter is installed (owner's call): it is
- // ~half the wall clock and graded better at the mouth than the full-step
- // path, so the fast one should be the one you land on and Standard the one
- // you reach for. An explicit "0" is still honoured — only the ABSENCE of a
- // preference defaults on. Never defaults on when the adapter isn't there.
- const turboOk = !!(H3.turbo && H3.turbo.available);
- tb.value = (turboOk && savedTb !== '0') ? '1' : '0';
+ if (tb) tb.value = '0';
})();
// What the export pass will DO to the selected tier's canvas, in one line under
@@ -251,11 +241,19 @@ function setH3Upscale(mode) {
b.classList.toggle('active', b.dataset.h3Upscale === shown));
const box = document.getElementById('h3FaceFixAfter');
if (box) box.checked = fix;
+ const box2 = document.getElementById('h3FaceFixFooter');
+ if (box2) box2.checked = fix;
+ _h3SyncFaceFixEta();
const row = document.getElementById('h3FaceFixAfterRow');
if (row) row.hidden = allowed.indexOf('ltx_x2') === -1;
if (!fix) { try { localStorage.setItem('phos_h3_upscale', v); } catch (e) {} }
_h3SyncExportNote();
if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }
+ // The export target is what the "After the render" summary SAYS, and that
+ // section is closed by default — so the line has to be rewritten here or it
+ // keeps advertising 720p for a render that ships 1080p. (It was stale in the
+ // old Customize summary for the same reason, where it mattered less.)
+ if (typeof updateCustomizeSummary === 'function') { try { updateCustomizeSummary(); } catch (e) {} }
}
function setH3FaceFixAfter(on) {
if (on) { setH3Upscale('ltx_x2'); return; }
@@ -279,6 +277,8 @@ function setH3Orientation(v) {
try { localStorage.setItem('phos_h3_orientation', val); } catch (e) {}
_h3SyncOrientationSubs();
if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }
+ // Orientation is part of the shape the closed Shot setup summary prints.
+ if (typeof updateCustomizeSummary === 'function') { try { updateCustomizeSummary(); } catch (e) {} }
}
// Say the ACTUAL canvases the current cell would produce, both ways round.
function _h3SyncOrientationSubs() {
@@ -348,49 +348,70 @@ document.querySelectorAll('#h3StepsGroup [data-h3-steps]').forEach(b => {
b.onclick = () => setH3Steps(b.dataset.h3Steps);
});
-// ---- Turbo: the 4-step distillation LoRA ------------------------------------
-// A speed MODE, not a tier: same model, same geometry, fewer denoise passes.
-// Three states, and the UI has to say which one it is in:
-// runner has no --lora → the whole row is hidden (an old pack never learns
-// Turbo exists, exactly like chained tiers)
-// supported, not installed → dashed pill; click explains/fetches the asset
-// available → a normal pill, and picking it pins steps at 4
+// ---- Speed: ⚡ Fast | ✦ Best ------------------------------------------------
+// ONE switch above the Quality cards (owner, 2026-09-17: "finally fast
+// generations", and no messy UI):
+// ⚡ Fast — TaoMate's 3-step adapter on its own sigma ladder (3 forwards).
+// Draft, Standard and High, T2V and I2V. Needs the 180 MB adapter
+// and a runner with --sigma-subset; until then the Fast half says
+// what one click does (install / update the runner).
+// ✦ Best — the shape's own sampler, as before (Draft/Standard 8 forwards,
+// High 15, Native as tuned), and the Steps override.
+// Default Fast once installed; remembered per browser (phos_h3_speed).
+// Native and the dense 10 s single pass have not been validated on 3 steps,
+// so they always render Best and say so under the switch.
+//
+// TURBO IS FOLDED IN. The old Standard | Turbo row is gone: Fast is the faster
+// AND the owner-preferred recipe, and two speed controls — or two adapters on
+// one render — is the confusion this switch exists to remove. The UI posts
+// h3_turbo=0 always; the server still honours h3_turbo from the API (and
+// never stacks it with Fast). A Turbo clip's Load Params / Finish maps to Fast.
function h3TurboState() {
return (H3 && H3.turbo) || { available: false, supported: false, downloaded: false };
}
+function h3TriStepState() {
+ return (H3 && H3.tristep) || { available: false, supported: false, downloaded: false };
+}
+function h3SpeedPref() {
+ let v = null;
+ try { v = localStorage.getItem('phos_h3_speed'); } catch (e) {}
+ return v === 'best' ? 'best' : 'fast';
+}
+function _h3SetSpeedPref(v) {
+ try { localStorage.setItem('phos_h3_speed', v === 'best' ? 'best' : 'fast'); } catch (e) {}
+}
+function _h3IsI2V() {
+ return ((document.getElementById('mode') || {}).value || 't2v') === 'i2v';
+}
+// Would THIS cell render Fast, as things stand?
+function h3TriStepOn(cell) {
+ cell = cell || h3CurrentCell();
+ return !!(cell && cell.tristep_min != null
+ && h3TriStepState().available && h3SpeedPref() === 'fast');
+}
+function _h3TriStepMin(cell) {
+ if (!cell || cell.tristep_min == null) return null;
+ return (_h3IsI2V() && cell.tristep_min_i2v != null) ? cell.tristep_min_i2v : cell.tristep_min;
+}
+function _h3TriStepEta(cell) {
+ if (!cell || cell.tristep_min == null) return '';
+ return (_h3IsI2V() && cell.tristep_eta_i2v) ? cell.tristep_eta_i2v : cell.tristep_eta;
+}
-// The per-tier estimate comes from the server's tier table (turbo_eta), built
-// from that tier's own GEOMETRY — Turbo runs 3 forwards whatever the tier bakes
-// and the fixed per-window cost doesn't shrink, so there is no single ratio
-// that could be right for every tier (it is 0.45 on an 8-forward one and 0.59
-// on a 6-forward one). The retired adapter has end-to-end measurements in the
-// changelog, but LightX2V v1.0 does not yet; its active cells remain derived
-// rather than inheriting a measurement from different weights.
-// The pill's SECOND line, in the same grammar every other .pill-btn in
-// Customize uses (name on top, one spec line under it): the cost of turning it
-// on, or the cost of getting it at all.
-// Both Speed segments print an ABSOLUTE wall clock, in the same shape, so the
-// two are directly comparable. Two mistakes were baked into the old copy and
-// the owner hit both: the Standard segment described the sampler ("the tier's
-// own sampler") while Turbo quoted a number, so there was nothing to compare
-// against; and the number was rendered as "~4 min", whose tilde reads as a
-// MINUS at this size — he read "-4 min at this tier" as four minutes being
-// ADDED. No tildes here, and never a delta: just "8 min" vs "4 min".
+// "~9 min" → "9 min": a tilde at this size reads as a minus (the owner read
+// "-4 min" once). Estimates on the switch are plain.
function _h3EtaPlain(s) {
- // "~17-19 min" -> "17-19 min", "~4 min" -> "4 min", "~27 min · batch" kept.
return String(s || '').replace(/[~≈]/g, '').trim();
}
-// Minutes for a cell under the CURRENT sampler state. The server pre-computes
-// the two states that matter (the cell's own steps, and Turbo's 3 forwards) and
-// ships the two model outputs — per_forward_sec and fixed_sec — so a PINNED
-// Steps override can be priced in the browser through the same arithmetic
-// rather than through a second, drifting cost model.
+// Minutes for a cell under the CURRENT speed (or the one opts names). The
+// server ships every number (Best eta, Fast eta per mode, per-forward and
+// fixed seconds for a pinned Steps count); nothing here models anything.
function h3CellEtaMin(cell, opts) {
if (!cell) return 0;
opts = opts || {};
- const turbo = (opts.turbo != null) ? opts.turbo
- : ((document.getElementById('h3_turbo') || {}).value === '1');
- if (turbo) return cell.turbo_min;
+ const fast = (opts.fast != null) ? opts.fast : h3TriStepOn(cell);
+ if (fast && cell.tristep_min != null) return _h3TriStepMin(cell);
+ if (opts.turbo) return cell.turbo_min;
const ov = (opts.steps != null) ? String(opts.steps)
: ((document.getElementById('h3_steps') || {}).value || 'auto');
if (ov !== 'auto' && /^\d+$/.test(ov)) {
@@ -403,51 +424,48 @@ function h3CellEtaMin(cell, opts) {
function h3FmtEtaMin(m) {
return '~' + Math.max(1, Math.round(m)) + ' min' + (m >= 25 ? ' · batch' : '');
}
-// The eta STRING for a cell in the current state. Prefers the server's own
-// string whenever the state is one the server priced (default steps, or Turbo),
-// because that is where a MEASURED wall clock lives — "~8-9 min" on the one
-// Turbo run that has actually been rendered end to end is not a number this
-// function should be regenerating.
+// 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).
function h3CellEta(cell, opts) {
if (!cell) return '';
opts = opts || {};
- const turbo = (opts.turbo != null) ? opts.turbo
- : ((document.getElementById('h3_turbo') || {}).value === '1');
- if (turbo) return cell.turbo_eta;
+ const fast = (opts.fast != null) ? opts.fast : h3TriStepOn(cell);
+ 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;
- return h3FmtEtaMin(h3CellEtaMin(cell, { turbo: false }));
+ return h3FmtEtaMin(h3CellEtaMin(cell, { fast: false }));
}
+// Second line of each half of the switch.
function h3SpeedSub(which) {
const cell = h3CurrentCell();
- if (which === 'standard') {
- const eta = cell ? _h3EtaPlain(h3CellEta(cell, { turbo: false })) : '';
- return eta || 'this shape as tuned';
+ if (which === 'best') {
+ return _h3EtaPlain(h3CellEta(cell, { fast: false })) || 'full steps';
}
- const t = h3TurboState();
- if (!t.downloaded && !t.install_available) return 'adapter asset pending';
- if (!t.downloaded) return (t.download_gb || 2.0) + ' GB download';
- const eta = cell && cell.turbo_eta ? _h3EtaPlain(cell.turbo_eta) : '';
- return eta || '4-step adapter';
-}
-function h3TurboPillSub() {
- return h3SpeedSub('turbo');
-}
-// Kept for anything (and anyone) still reading the one-line form.
-function h3TurboPillLabel() {
- return 'Turbo · ' + h3TurboPillSub();
+ const tri = h3TriStepState();
+ if (!tri.supported) return 'update H3 runner';
+ if (!tri.downloaded) {
+ if (tri.installing) {
+ const d = tri.download || {};
+ return 'installing ' + (d.mb || 0) + ' / ' + (d.total_mb || 173) + ' MB';
+ }
+ return 'Install (180 MB)';
+ }
+ if (!cell || cell.tristep_min == null) return 'Best only here';
+ return _h3EtaPlain(_h3TriStepEta(cell)) || '3 steps';
}
+// Kept for callers of the pre-switch API.
+function h3TurboPillSub() { return h3SpeedSub('fast'); }
-// The sampler depth each shape runs is per CELL (High runs 16 sigma points,
-// Draft/Standard/Native 9, dense 10 s 16), so the Standard and Auto tooltips
-// read it from the cell rather than printing one number for every shape.
+// The sampler depth Best runs is per CELL (High 16 sigma points, Draft/
+// Standard/Native 9, dense 10 s 16), so the tooltips read it from the cell.
function _h3SyncSamplerTitles() {
const cell = h3CurrentCell();
const pts = (cell && cell.steps) || 9;
const fwd = Math.max(1, pts - 1);
- const std = document.querySelector('#h3TurboGroup [data-h3-turbo="0"]');
- if (std) std.title = "This shape's own sampler — " + pts + ' sigma points, '
- + fwd + ' forwards per window.';
+ const best = document.querySelector('#h3SpeedGroup [data-h3-speed="best"]');
+ if (best) best.title = "Best: this shape's full sampler — " + fwd + ' steps per window. '
+ + 'The slower, most careful render.';
const auto = document.querySelector('#h3StepsGroup [data-h3-steps="auto"]');
if (auto) auto.title = "This shape's tuned count — " + pts + ' sigma points ('
+ fwd + ' forwards per window) at this canvas.';
@@ -455,7 +473,7 @@ function _h3SyncSamplerTitles() {
document.querySelectorAll('#h3StepsGroup [data-h3-steps]').forEach(b => {
const n = b.dataset.h3Steps;
if (!/^\d+$/.test(n)) return;
- const k = h3CellEtaMin(cell, { turbo: false, steps: n }) / cell.eta_min;
+ const k = h3CellEtaMin(cell, { fast: false, steps: n }) / cell.eta_min;
const rel = Math.abs(k - 1) < 0.05 ? 'the same time as Auto at this shape'
: '~' + k.toFixed(1) + '× Auto\'s render time at this shape';
b.title = n + ' sigma points (' + (parseInt(n, 10) - 1) + ' forwards) — ' + rel
@@ -463,142 +481,180 @@ function _h3SyncSamplerTitles() {
});
}
+// Paint the switch for the current cell and apply it. Called from every place
+// that moves the shape, the steps, the mode or the install state.
function renderH3Turbo() {
- const row = document.getElementById('h3TurboRow');
- const pill = document.getElementById('h3TurboPill');
- const sub = document.getElementById('h3TurboPillSub');
+ const row = document.getElementById('h3SpeedRow');
const t = h3TurboState();
- if (row) row.hidden = !t.supported;
- if (!pill) return;
- if (sub) sub.textContent = h3SpeedSub('turbo');
- const stdSub = document.getElementById('h3StdPillSub');
- if (stdSub) stdSub.textContent = h3SpeedSub('standard');
- _h3SyncSamplerTitles();
- pill.classList.toggle('needs-download', !t.downloaded);
- // Two different kinds of number, and the tooltip must not blur them: the ONE
- // shape that has actually been rendered with the adapter end to end says so,
- // everything else says out loud that its figure is derived from geometry.
- const tier = h3CurrentCell();
- const basis = (tier && tier.turbo_measured)
- ? ' Measured end to end at this exact canvas and length — not derived.'
- : ' Estimated for this shape: Turbo runs ' + ((tier && tier.turbo_forwards) || 3)
- + ' forwards instead of ' + ((tier && tier.forwards) || 8)
- + ', over the same fixed load/decode time. Not measured at this canvas.';
- const fallbackNote = (t.downloaded && t.fallback && t.adapter_version)
- ? ' Running the ' + t.adapter_version + ' fallback adapter — the v1.0 '
- + 'download replaces it.'
- : '';
- pill.title = t.downloaded
- ? (t.note || '') + basis + fallbackNote
- : (t.install_available
- ? 'Downloads the LightX2V v1.0 runner-layout adapter (~'
- + (t.download_gb || 2.0) + ' GB) into the H3 pack.'
- : (t.install_note || 'The runner-layout adapter release asset is pending.'));
- // The pack could have gone away (or arrived) since boot without a reload.
- if (!t.available && (document.getElementById('h3_turbo') || {}).value === '1') {
- setH3Turbo(false);
- }
-}
-
-// Steps and Turbo are the same axis, so only one of them can be in charge.
-// Turbo is, and the pills go visibly dead rather than silently ignored — the
-// server drops the override too (make_job), this just stops it looking live.
-function _h3SyncStepsEnabled() {
- const on = (document.getElementById('h3_turbo') || {}).value === '1';
- const row = document.getElementById('h3StepsRow');
- document.querySelectorAll('#h3StepsGroup [data-h3-steps]').forEach(b => {
- b.disabled = on;
- b.classList.toggle('disabled', on);
- });
- if (row) {
- row.style.opacity = on ? '.5' : '';
- row.title = on ? ('Turbo pins the sampler at ' + (h3TurboState().steps || 7) + ' sigma points.') : '';
+ const tri = h3TriStepState();
+ // An old pack with no --lora at all can do neither; the switch hides, as
+ // Turbo's row always did.
+ if (row) row.hidden = !(t.supported || tri.supported);
+ const cell = h3CurrentCell();
+ const fastBtn = document.querySelector('#h3SpeedGroup [data-h3-speed="fast"]');
+ const bestSub = document.getElementById('h3SpeedBestSub');
+ const fastSub = document.getElementById('h3SpeedFastSub');
+ if (fastSub) fastSub.textContent = h3SpeedSub('fast');
+ if (bestSub) bestSub.textContent = h3SpeedSub('best');
+ if (fastBtn) {
+ fastBtn.classList.toggle('needs-download', !tri.available);
+ 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.';
}
+ _h3SyncSamplerTitles();
+ _h3ApplySpeed();
+ _h3SyncFaceFixEta();
}
-function setH3Turbo(on) {
- const t = h3TurboState();
- const v = (on && t.available) ? '1' : '0';
- const inp = document.getElementById('h3_turbo');
- if (inp) inp.value = v;
- document.querySelectorAll('#h3TurboGroup [data-h3-turbo]').forEach(b =>
- b.classList.toggle('active', b.dataset.h3Turbo === v));
- const note = document.getElementById('h3TurboNote');
- if (note) {
- note.hidden = (v !== '1');
- note.textContent = t.note || '';
- }
- if (v === '1') {
- // ORDER IS LOAD-BEARING, and it was wrong until Steps became a primary
- // control and the lie got visible: setH3Steps('auto') re-derives the
- // shared hidden `steps` from the TIER (9), so running it after the pin
- // overwrote the 4 and the derived line read "Steps 9" on a Turbo render.
- // Release the pill override first, THEN pin. make_job stamps
- // H3_TURBO_STEPS server-side either way — this only ever affected what the
- // form told the user it was about to do, which is the whole reason Speed
- // and Steps were moved out where the user can see them.
- if (typeof setH3Steps === 'function') { try { setH3Steps('auto'); } catch (e) {} }
+// ONE writer for what this render does: both hidden inputs, the lit half, the
+// Steps row, the note. Guarded: setH3Steps re-enters through renderH3Turbo.
+let _h3SpeedBusy = false;
+function _h3ApplySpeed() {
+ if (_h3SpeedBusy) return;
+ _h3SpeedBusy = true;
+ try {
+ const cell = h3CurrentCell();
+ const tri = h3TriStepState();
+ const pref = h3SpeedPref();
+ const fastOn = h3TriStepOn(cell);
+ const triIn = document.getElementById('h3_tristep');
+ 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';
+ 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;
+ note.textContent = bestOnly
+ ? cell.label + ' renders on Best — Fast is not validated at this shape yet.'
+ : '';
+ note.hidden = !bestOnly;
+ }
+ const stIn = document.getElementById('h3_steps');
const s = document.getElementById('steps');
- if (s) s.value = t.steps || 4;
+ if (fastOn) {
+ // Release a pinned Steps pill FIRST (it re-derives `steps` from the
+ // cell), THEN pin Fast's own count.
+ if (stIn && stIn.value !== 'auto' && typeof setH3Steps === 'function') {
+ try { setH3Steps('auto'); } catch (e) {}
+ }
+ if (s) s.value = tri.steps || 4;
+ } else if (s && cell) {
+ const ov = (stIn || {}).value || 'auto';
+ s.value = (ov !== 'auto' && /^\d+$/.test(ov)) ? parseInt(ov, 10) : cell.steps;
+ }
+ // Steps is a Best control: it only shows while Best is what renders.
+ const stepsRow = document.getElementById('h3StepsRow');
+ if (stepsRow) stepsRow.hidden = fastOn;
+ if (typeof renderH3LoraSlot === 'function') { try { renderH3LoraSlot(); } catch (e) {} }
+ } finally {
+ _h3SpeedBusy = false;
}
- _h3SyncStepsEnabled();
- // Turbo is one half of the single-adapter-slot conflict, so the Adapter row
- // appears / disappears with it.
- if (typeof renderH3LoraSlot === 'function') { try { renderH3LoraSlot(); } catch (e) {} }
- try { localStorage.setItem('phos_h3_turbo', v); } catch (e) {}
- // Turbo roughly halves every cell, so the chips have to re-price — a strip
- // still advertising the 9-step wall clock while Turbo is lit is the same lie
- // the Speed pill's absolute times were added to kill.
+}
+function _h3SpeedRepriced() {
if (typeof renderH3Axes === 'function') { try { renderH3Axes(); } catch (e) {} }
+ if (typeof renderH3Turbo === 'function') { try { renderH3Turbo(); } catch (e) {} }
if (typeof updateDerived === 'function') { try { updateDerived(); } catch (e) {} }
if (typeof updateCustomizeSummary === 'function') { try { updateCustomizeSummary(); } catch (e) {} }
}
-// One click, two behaviours, because the pill has two jobs: select Turbo when
-// it is ready, or fetch it when it isn't. Never both — a click that starts a
-// download must not also arm a render that has nothing to render with.
-async function h3TurboClick() {
- const t = h3TurboState();
- if (t.available) { setH3Turbo(true); return; }
- if (!t.supported) {
- if (typeof phosToast === 'function') {
- phosToast('This Hailuo H3 pack predates Turbo. Re-run "Install Hailuo H3" '
- + 'in the Pinokio sidebar to update the clone — your weights stay.',
- { kind: 'danger' });
- }
- return;
- }
- if (!t.install_available) {
- if (typeof phosToast === 'function') {
- phosToast(t.install_note || 'The H3 Turbo runner-layout adapter release asset is pending.',
- { kind: 'danger' });
- }
+// Set the speed ('fast' | 'best'). Remembered per browser.
+function setH3Speed(v) {
+ _h3SetSpeedPref(v === 'best' ? 'best' : 'fast');
+ _h3ApplySpeed();
+ _h3SpeedRepriced();
+}
+// Pre-switch API: Turbo on meant "the fast one".
+function setH3Turbo(on) { if (on) setH3Speed('fast'); else _h3ApplySpeed(); }
+function setH3TriStep(on) { setH3Speed(on ? 'fast' : 'best'); }
+// What a saved clip was made with, as this switch's value.
+function h3SpeedOfParams(p) {
+ p = p || {};
+ return (p.h3_tristep || p.h3_turbo) ? 'fast' : 'best';
+}
+
+// The Fast half: select it when ready; otherwise the one click that makes it
+// ready (install the adapter, or say which update is needed).
+async function h3SpeedClick(which) {
+ if (which !== 'fast') { setH3Speed('best'); return; }
+ const tri = h3TriStepState();
+ if (tri.available) { setH3Speed('fast'); return; }
+ const toast = (m, kind) => { if (typeof phosToast === 'function') phosToast(m, { kind }); };
+ if (!tri.supported) {
+ toast('Fast needs a newer Hailuo H3 runner. Run "Update Hailuo H3 runner" in the Pinokio '
+ + 'sidebar — your weights stay.', 'danger');
return;
}
- const gb = t.download_gb || 2.0;
- if (!confirm('Download the H3 Turbo adapter?\n\n'
- + '~' + gb + ' GB, into the H3 pack’s models folder.\n'
- + 'The LightX2V source adapter is Apache-2.0.\n\n'
- + 'Progress streams to the log at the bottom of the page.')) 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/turbo/install', { method: 'POST' });
+ 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));
- if (typeof phosToast === 'function') {
- phosToast('Turbo download started — watch the log. The pill turns on by '
- + 'itself when the adapter lands.', { kind: 'ok' });
- }
+ _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) {
- if (typeof phosToast === 'function') {
- phosToast('Turbo download: ' + (e.message || 'failed'), { kind: 'danger' });
- }
+ toast('Fast install: ' + (e.message || 'failed'), 'danger');
}
}
-
-document.querySelectorAll('#h3TurboGroup [data-h3-turbo]').forEach(b => {
- b.onclick = () => (b.dataset.h3Turbo === '1') ? h3TurboClick() : setH3Turbo(false);
+document.querySelectorAll('#h3SpeedGroup [data-h3-speed]').forEach(b => {
+ b.onclick = () => h3SpeedClick(b.dataset.h3Speed);
});
+// The Upscale & Face Fix pair, priced from the cell's own numbers: the
+// checkbox beside Generate and the estimate line in the footer.
+function h3FaceFixOn() {
+ return ((document.getElementById('h3_upscale') || {}).value) === 'ltx_x2';
+}
+function _h3SyncFaceFixEta() {
+ const cell = h3CurrentCell();
+ const allowed = (H3.upscale_modes || []).indexOf('ltx_x2') !== -1;
+ const row = document.getElementById('h3FaceFixFooterRow');
+ if (row) row.hidden = !allowed;
+ const eta = document.getElementById('h3FaceFixFooterEta');
+ if (eta) {
+ eta.textContent = (cell && cell.facefix_min != null)
+ ? '+' + (Math.round(cell.facefix_min * 2) / 2) + ' min · 2× · face and sound kept'
+ : '2× · face and sound kept';
+ }
+ const legacy = document.getElementById('h3FaceFixEta');
+ if (legacy) {
+ legacy.textContent = 'optional · 2× · face and sound kept'
+ + ((cell && cell.facefix_min != null)
+ ? ' · +' + (Math.round(cell.facefix_min * 2) / 2) + ' min' : " · about the render's time again");
+ }
+}
+// The footer line: "Draft · Fast ≈ 3 min" / "High · Best + Face Fix ≈ 44 min".
+function h3EstimateLine() {
+ const cell = h3CurrentCell();
+ if (!cell) return '';
+ const fast = h3TriStepOn(cell);
+ let m = h3CellEtaMin(cell);
+ let txt = cell.quality_label + ' · ' + (fast ? 'Fast' : 'Best');
+ if (h3FaceFixOn()) {
+ txt += ' + Face Fix';
+ 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';
+}
+
// Adapter-slot pills. Bound at parse time like the Turbo / Steps groups —
// the row itself is hidden until Turbo and a LoRA actually collide.
document.querySelectorAll('#h3LoraSlotGroup [data-h3-lora-slot]').forEach(b => {
@@ -959,13 +1015,28 @@ function renderTierAxes(engine) {
const curQ = E.currentQuality();
const curL = E.currentLength();
- qStrip.style.gridTemplateColumns = `repeat(${Math.max(1, qualities.length)}, 1fr)`;
+ // Both strips used to be fixed column counts, which squeezed and then
+ // CLIPPED: LTX ships five canvases (Quick · Balanced · Standard · High ·
+ // High 720p) whose specs wrapped to three lines in the pane's usual width,
+ // and H3's four ran off the right edge as soon as the window was dragged in.
+ // Auto-fit tracks answer to the strip's own width. The 90 px floor is
+ // measured, not guessed: the pane's content box is ~386 px, where four
+ // tracks + gaps fit and five do not — so H3's four canvases stay one row
+ // across (unchanged) and LTX's five wrap 4 + 1 instead of squeezing five
+ // into a row. Squeeze the pane and it gives ground a column at a time
+ // instead of clipping. An unfilled track collapses, so a 2-cell strip still
+ // stretches its two cells across the row.
+ qStrip.style.gridTemplateColumns = 'repeat(auto-fit, minmax(90px, 1fr))';
qStrip.innerHTML = qualities.map(q =>
_tierChipHtml(engine, 'quality', q, E.cellFor(q.key, curL), q.key === curQ)).join('');
// Past four lengths (the lab dense pass turns a fifth on) the chips would
- // squeeze; wrap to three per row and let the strip grow a line instead.
- lStrip.style.gridTemplateColumns =
- `repeat(${lengths.length > 4 ? 3 : Math.max(1, lengths.length)}, 1fr)`;
+ // squeeze; wrap to three per row and let the strip grow a line instead. The
+ // wider floor is what makes it three rather than four at the pane's usual
+ // width — same result the hard-coded 3 gave, and it keeps giving ground as
+ // the pane narrows instead of clipping.
+ lStrip.style.gridTemplateColumns = lengths.length > 4
+ ? 'repeat(auto-fit, minmax(118px, 1fr))'
+ : 'repeat(auto-fit, minmax(90px, 1fr))';
lStrip.innerHTML = lengths.map(l =>
_tierChipHtml(engine, 'length', l, E.cellFor(curQ, l.key), l.key === curL)).join('');
@@ -1478,6 +1549,16 @@ Object.assign(globalThis, {
h3ResolveTierKey, h3TierByKey, h3CellFor, h3CurrentCell,
setH3Upscale, setH3FaceFixAfter, setH3Orientation, setH3Steps, h3TurboPillSub,
renderH3Turbo, setH3Turbo, syncModeStripToEngine, renderEngineSwitch,
+ setH3Speed, h3SpeedOfParams, h3EstimateLine, setH3TriStep, h3TriStepOn, h3TriStepState,
+ // 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.
+ h3CellEta,
+ // ...and the two the Batch section needs to price N jobs: the MINUTES behind
+ // that string, and whether a Face Fix rides along. Private, they threw on
+ // first call and the catch swallowed it, so an H3 batch showed no total at
+ // all (lint_webapp: no-undef, queue.js:4579).
+ h3CellEtaMin, h3FaceFixOn,
renderTierAxes, renderH3Axes, ltxCellFor, ltxCurrentQuality,
ltxCurrentLength, ltxCurrentCell, ltxCellEta, ltxCellNeedsInstall,
ltxCellInstallLabel, _ltxApplyShape, setH3Quality, _h3ApplyShape,
diff --git a/webapp/js/loras.js b/webapp/js/loras.js
index f3501f9..9183306 100644
--- a/webapp/js/loras.js
+++ b/webapp/js/loras.js
@@ -161,6 +161,11 @@ async function importH3Lora(file) {
const data = await r.json();
if (!r.ok || !data.ok) throw new Error(data.error || `HTTP ${r.status}`);
await refreshLoras();
+ // The picker is closed by default since the 2026-09-18 layout pass, so the
+ // file that just landed has to be shown rather than filed away out of
+ // sight — the same thing the CivitAI install path does.
+ const _det = document.getElementById('lorasDetails');
+ if (_det) _det.open = true;
const pairs = `${data.pairs} module pair${data.pairs === 1 ? '' : 's'}`;
const converted = data.converted ? ' Key namespace converted safely.' : '';
// The H3 loader applies no alpha, so when a file's own scale isn't 1.0 the
@@ -173,7 +178,7 @@ async function importH3Lora(file) {
} catch (e) {
alert(`H3 LoRA import failed: ${e.message || e}`);
} finally {
- if (btn) { btn.disabled = false; btn.innerHTML = original || 'Import H3 LoRA'; }
+ if (btn) { btn.disabled = false; btn.innerHTML = original || 'Import'; }
}
}
@@ -774,7 +779,7 @@ function renderLorasList() {
<div class="hint" style="padding:14px 8px;text-align:center;line-height:1.6;">
<div style="margin-bottom:4px;color:var(--fg);"><strong>No Hailuo H3 LoRAs in your library.</strong></div>
<div>H3 has its own library — your LTX LoRAs can't load here, and H3's can't load on LTX.</div>
- <div style="margin-top:6px;">Already have one? <strong>Import H3 LoRA</strong> above takes a <code>.safetensors</code> file and checks it against your installed H3 transformer before it lands in the library.</div>
+ <div style="margin-top:6px;">Already have one? <strong>Import</strong> above takes a <code>.safetensors</code> file and checks it against your installed H3 transformer before it lands in the library.</div>
<div style="margin-top:6px;">Drop a converted H3 <code>.safetensors</code> with <code>lora_A</code> / <code>lora_B</code> tensors into <code>${escapeHtml(_lorasDirs.h3 || 'the H3 pack’s loras/ folder')}</code>, then press Rescan — same result, no size limit.</div>
<div style="margin-top:6px;">Or install one via <strong>Browse CivitAI</strong> above using the <strong>Hailuo H3</strong> CivitAI filter.</div>
</div>`;
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index 003b160..edc0786 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -156,7 +156,10 @@ function h3FinishFieldsFromSidecar(p, tierKey) {
// as a different canvas. setH3Turbo re-checks availability, so a sidecar
// from an install that has since lost the files lands on Standard, not on a
// mode that would fail at queue time.
- h3_turbo: !!p.h3_turbo,
+ // The Speed switch value the clip was made with (Fast = 3-step, or the
+ // retired Turbo; Best = the shape's full sampler). setH3Speed re-checks
+ // availability: a Fast clip on an install without the adapter lands on Best.
+ h3_speed: (p.h3_tristep || p.h3_turbo) ? 'fast' : 'best',
// The shot list carries over, and it is safe to: Finish means SAME LENGTH,
// higher quality, so the window count is identical by construction and
// entry i still means window i. Dropping it would silently finish a
@@ -307,7 +310,7 @@ async function h3FinishActive() {
if (typeof setH3Steps === 'function') setH3Steps(fields.h3_steps);
// Turbo before the shape: setH3Turbo forces the Steps pills back to 'auto',
// and setH3Tier below re-reads them when it stamps the resolved count.
- if (typeof setH3Turbo === 'function') setH3Turbo(!!fields.h3_turbo);
+ if (typeof setH3Speed === 'function' && fields.h3_speed) setH3Speed(fields.h3_speed);
// Shape LAST of the H3 controls: setH3Tier stamps width/height/frames/steps
// from the cell table, so anything geometry-related set after it would be
// fighting the source of truth. The LENGTH inside `fields.h3_tier` is the
@@ -432,8 +435,8 @@ function setEngine(engine, opts) {
setH3Upscale((document.getElementById('h3_upscale') || {}).value
|| H3.default_upscale || 'fit_720p');
setH3Steps((document.getElementById('h3_steps') || {}).value || 'auto');
+ // Paints the Speed switch and writes #h3_tristep / #h3_turbo from it.
renderH3Turbo();
- setH3Turbo((document.getElementById('h3_turbo') || {}).value === '1');
// After the shape, because the number of window boxes IS the shape.
renderH3WindowPrompts();
// LTX post-processing doesn't run on an H3 render (make_job neutralises
@@ -567,13 +570,22 @@ function updateH3Availability(s) {
// this turns the dashed pill live as soon as it lands.
|| (((next.turbo || {}).available) !== ((H3.turbo || {}).available))
|| (((next.turbo || {}).supported) !== ((H3.turbo || {}).supported))
+ // Same for the Draft's fast 3-step adapter.
+ || (((next.tristep || {}).available) !== ((H3.tristep || {}).available))
+ || (((next.tristep || {}).supported) !== ((H3.tristep || {}).supported))
|| ((next.tiers || []).length !== (H3.tiers || []).length);
// BOTH bindings, and they must stay the same object: the H3-specific code
// reads `H3` on nearly every line, the registry reads the probe map. A
// divergence here is a switcher showing "not installed" over a working
// engine (or worse, the reverse).
+ const _triDl = !!((next.tristep || {}).installing || (H3.tristep || {}).installing);
H3 = next;
window._ENGINE_PROBES.h3 = next;
+ // A running 3-step download prints its progress on the pill.
+ if (_triDl && !changed && typeof renderH3Turbo === 'function'
+ && typeof currentEngine === 'function' && currentEngine() === 'h3') {
+ try { renderH3Turbo(); } catch (e) {}
+ }
if (changed) {
setEngine(currentEngine(), { persist: false });
// The Finish button's label and its picker are both derived from H3.tiers,
@@ -869,6 +881,7 @@ function snapFramesTo8kPlus1() {
}
}
+let _h3DerivedMode = null;
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.
@@ -913,7 +926,20 @@ function updateDerived() {
// expanded Customize body).
const derivedFooter = document.getElementById('derivedFooter');
if (derivedFooter) {
- derivedFooter.innerHTML = `<strong>${dur}s</strong> · ${finalRes}${temporalText}${accelText}`;
+ 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() : '';
+ derivedFooter.innerHTML = h3Line
+ ? `<strong>${escapeHtml(h3Line)}</strong> · ${dur}s`
+ : `<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.
+ if (onH3 && _h3DerivedMode !== mode) {
+ _h3DerivedMode = mode;
+ if (typeof renderH3Axes === 'function') { try { renderH3Axes(); } catch (e) {} }
+ if (typeof renderH3Turbo === 'function') { try { renderH3Turbo(); } catch (e) {} }
+ }
}
// 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.
@@ -1053,6 +1079,11 @@ function updateDerived() {
el.addEventListener('input', () => { updateCustomizeSummary(); updateDerived(); repaintTiers(); });
}
});
+// A locked seed is part of the shape the closed Shot setup summary prints, and
+// the field has never had a listener of its own (nothing else read it live).
+document.getElementById('seed')?.addEventListener('input', () => {
+ if (typeof updateCustomizeSummary === 'function') updateCustomizeSummary();
+});
document.getElementById('keyframe_mid_seconds')?.addEventListener('input', () => {
window._kfMidTouched = true;
window._kfTimingTouched.mid = true;
@@ -2449,16 +2480,10 @@ async function poll() {
// sometimes "ran out of RAM, want to retry as-is."
const isRetryable = j.status === 'failed' || j.status === 'cancelled';
const _p = j.params || {};
- const canFaceFix = j.status === 'done' && j.output_path && _p.mode !== 'upscale'
- && _p.mode !== 'train' && /\.(mp4|mov|m4v|webm|mkv)$/i.test(String(j.output_path));
const actionHtml = isRetryable
? `<button class="retry-btn" type="button"
title="Re-submit this job with the same params"
onclick='retryJob(${JSON.stringify(j.id)})'>Retry</button>`
- : canFaceFix
- ? `<button class="retry-btn facefix-btn" type="button"
- title="Upscale &amp; Face Fix — queue a 2× re-render of this clip that keeps the face and the sound. The fixed clip lands next to it."
- onclick="faceFixClip(${escapeHtml(JSON.stringify(j.output_path))})">Face Fix</button>`
: '';
// Same film badge the queue rows carry, so a shot is identifiable
// wherever the bottom pane shows it.
@@ -3049,11 +3074,8 @@ function renderCarousel() {
title="Re-run this prompt + seed + refs at Quality (auto-submits)"
onclick="event.stopPropagation(); remakeInQuality(${remakeArgs})">✦ Quality</button>`
: '';
- // Upscale & Face Fix — one click, on video cards only.
- const faceFixChip = (isPhoto || isAudio) ? ''
- : `<button class="card-action card-action-facefix" type="button"
- title="Upscale &amp; Face Fix — queue a 2× re-render of this clip that keeps the face and the sound. The fixed clip lands next to it; this one is not changed."
- onclick="event.stopPropagation(); faceFixClip(${escapeHtml(JSON.stringify(o.path))})">Upscale &amp; Face Fix</button>`;
+ // Upscale & Face Fix lives on the big player only (owner 2026-09-17: on the
+ // thumbnails it was clutter).
return `
<div class="car-card${o.path === activePath ? ' active' : ''}"
data-path="${escapeHtml(o.path)}" onclick="selectOutput(${pathAttr})">
@@ -3067,7 +3089,6 @@ function renderCarousel() {
${remakeChip}
${animateChip}
${isAudio ? `<button class="card-action card-action-photo" type="button" title="Load this track into Audio → Video (does not auto-submit)" onclick="event.stopPropagation();useTrackInA2V(${pathAttr})">Drive video</button>` : ''}
- ${faceFixChip}
<button class="card-action card-action-danger" type="button" title="Move this file to the Trash — asks first"
onclick="event.stopPropagation(); deleteOutput(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-trash-simple"/></svg></button>
</div>
@@ -3364,7 +3385,8 @@ function selectOutput(path, options) {
// 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');
- if (useUpBtn) useUpBtn.style.display = (isPhoto || isAudio) ? 'none' : '';
+ // …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,
@@ -3585,6 +3607,12 @@ function useAsExtendSource() { if (!activePath) return alert('Pick an output fir
// overwritten. `opts.board` + `opts.clip` = ordered from an Editor clip, which
// makes the Editor offer the swap when it lands.
const FACE_FIX_NAME = 'Upscale & Face Fix';
+// A clip that already went through Upscale & Face Fix (or an older ×2 pass):
+// the lane names its outputs <stem>_x2_<stamp>.mp4; hand-made finals carry
+// _x2f / x2_faithful / _bizvoice (built from an ×2) in the path.
+function isUpscaledPath(p) {
+ return /(_x2(_|f|\.)|x2_faithful|x2_levelled|_bizvoice)/i.test(String(p || ''));
+}
async function faceFixClip(path, opts) {
opts = opts || {};
if (!path) { phosToast('Pick a clip first.', {}); return null; }
@@ -4026,8 +4054,9 @@ async function loadParams() {
if (typeof setH3Orientation === 'function') {
try { setH3Orientation(p.h3_orientation || 'landscape'); } catch (e) {}
}
- if (typeof setH3Turbo === 'function') {
- try { setH3Turbo(!!Number(p.h3_turbo || 0)); } catch (e) {}
+ // The Speed the clip was made with (Fast = 3-step or the retired Turbo).
+ if (typeof setH3Speed === 'function' && typeof h3SpeedOfParams === 'function') {
+ try { setH3Speed(h3SpeedOfParams(p)); } catch (e) {}
}
if (typeof setH3Steps === 'function') {
try { setH3Steps(Number(p.h3_steps || 0) > 0 ? String(p.h3_steps) : 'auto'); } catch (e) {}
@@ -4308,7 +4337,16 @@ function renderOutputInfoBody(path, data) {
}
// Turbo changed the sampler recipe, so it earns a row on every clip that
// used it — it is the difference between two otherwise identical renders.
- if (p.h3_turbo) {
+ if (p.h3_tristep) {
+ // The Draft sampler: which adapter file, and the ladder it ran.
+ const ti = (data && data.h3 && data.h3.tristep) || {};
+ const acc = (data && data.h3 && data.h3.lora_accounting) || null;
+ genRows.push(`<dt>Speed</dt><dd>Fast · 3-step · ${escapeHtml(String(ti.forwards || 3))} forwards`
+ + ` · TaoMate 3-step adapter${ti.adapter_version ? ' (' + escapeHtml(String(ti.adapter_version)) + ')' : ''}`
+ + ` · σ ${escapeHtml(String(ti.sigma_subset || '50:0,16,33,49'))}`
+ + (acc && acc.applied != null ? ' · ' + escapeHtml(String(acc.applied)) + ' modules wrapped' : '')
+ + '</dd>');
+ } else if (p.h3_turbo) {
const tinfo = (data && data.h3 && data.h3.turbo) || null;
const applied = tinfo && tinfo.applied && tinfo.applied.applied;
genRows.push(`<dt>Turbo</dt><dd>on · ${escapeHtml(String(p.steps || 4))}-step `
@@ -4482,14 +4520,191 @@ document.querySelectorAll('.tabs button[data-tab]').forEach(b => b.onclick = ()
});
// ====== Batch modal ======
-function openBatch() { document.getElementById('batchModal').classList.add('show'); }
-function closeBatch() { document.getElementById('batchModal').classList.remove('show'); }
+// ====== Batch — a section of the form, not a modal (2026-09-18) ======
+//
+// It was a pill in the queue strip opening a modal with one textarea and the
+// instruction "split prompts with --- on its own line". Two problems, both the
+// owner's words: hidden, and taught badly. Now it is a row of the same stack
+// as Shot setup and After the render, it counts the jobs before you commit
+// them, and it does the thing people were doing by hand — N takes of one
+// prompt, each with its own seed.
+//
+// Nothing about the enqueue contract changed: both modes post the current form
+// to /queue/batch with a `prompts` field split on `---`, which is the route
+// that has always built one job per chunk (and is all-or-nothing on refusal).
+let _batchMode = 'prompts';
+let _batchTakes = 3;
+
+function setBatchMode(mode) {
+ _batchMode = (mode === 'seeds') ? 'seeds' : 'prompts';
+ document.querySelectorAll('#batchModeGroup [data-batch-mode]').forEach(b => {
+ b.classList.toggle('active', b.dataset.batchMode === _batchMode);
+ });
+ const pw = document.getElementById('batchPromptsWrap');
+ const sw = document.getElementById('batchSeedsWrap');
+ if (pw) pw.hidden = _batchMode !== 'prompts';
+ if (sw) sw.hidden = _batchMode !== 'seeds';
+ updateBatchSummary();
+}
+
+function setBatchTakes(n) {
+ _batchTakes = Math.max(2, Math.min(8, parseInt(n, 10) || 3));
+ document.querySelectorAll('#batchTakesGroup [data-batch-takes]').forEach(b => {
+ b.classList.toggle('active', parseInt(b.dataset.batchTakes, 10) === _batchTakes);
+ });
+ updateBatchSummary();
+}
+
+// The prompts a Queue-all would actually send, in the order it would send
+// them. One function, so the count on screen and the jobs in the queue cannot
+// disagree — the old modal showed no count at all and a paste that failed to
+// split arrived as one enormous job.
+//: `/queue/batch` splits its `prompts` field on a line of exactly three
+//: dashes. In "many prompts" that IS the contract; in "N takes" it is a hazard,
+//: because the user's own prompt may contain such a line — and then three
+//: advertised takes arrive as six jobs holding fragments of one prompt.
+const BATCH_SEP_RX = /^\s*---\s*$/m;
+
+function batchMainPrompt() {
+ return ((document.getElementById('prompt') || {}).value || '').trim();
+}
+
+function batchPrompts() {
+ if (_batchMode === 'seeds') {
+ const main = batchMainPrompt();
+ if (!main || BATCH_SEP_RX.test(main)) return [];
+ return Array(_batchTakes).fill(main);
+ }
+ const raw = (document.getElementById('batchPrompts') || {}).value || '';
+ return raw.split(/^\s*---\s*$/m).map(c => c.trim()).filter(Boolean);
+}
+
+// Minutes for ONE render at the current settings, from the engine module's own
+// numbers (the server ships them). Unknown stays unknown — a batch total is
+// not a place to invent a cost model.
+function batchPerRenderMin() {
+ try {
+ if (document.body.dataset.engine === 'h3') {
+ const cell = h3CurrentCell();
+ if (!cell) return 0;
+ let m = h3CellEtaMin(cell);
+ if (typeof h3FaceFixOn === 'function' && h3FaceFixOn() && cell.facefix_min != null) {
+ m += cell.facefix_min;
+ }
+ return m || 0;
+ }
+ const cell = ltxCellFor(ltxCurrentQuality(), ltxCurrentLength());
+ return (cell && typeof cell.eta_min === 'number') ? cell.eta_min : 0;
+ } catch (_) { return 0; }
+}
+
+function _batchFmtTotal(n, per) {
+ const jobs = n + (n === 1 ? ' job' : ' jobs');
+ if (!per) return jobs;
+ const total = n * per;
+ const t = total < 60 ? Math.round(total) + ' min'
+ : (Math.round(total / 6) / 10) + ' h';
+ return jobs + ' · about ' + t + ' in all';
+}
+
+function updateBatchSummary() {
+ const list = batchPrompts();
+ const per = batchPerRenderMin();
+ const meta = document.getElementById('batchSummary');
+ const count = document.getElementById('batchCount');
+ const total = document.getElementById('batchTotal');
+ const btn = document.getElementById('batchQueueBtn');
+ const note = document.getElementById('batchTakesNote');
+ if (count) {
+ // The first line of each prompt, listed back: a paste that split on the
+ // wrong lines is then visible HERE instead of in the queue ten minutes
+ // later. Five is enough to see the shape of it.
+ count.textContent = list.length
+ ? list.length + (list.length === 1 ? ' prompt: ' : ' prompts: ')
+ + list.slice(0, 5).map(p => {
+ const first = p.split('\n').find(l => l.trim()) || '';
+ return '"' + first.trim().slice(0, 42) + (first.trim().length > 42 ? '…' : '') + '"';
+ }).join(' · ') + (list.length > 5 ? ' · …' : '')
+ : 'Nothing pasted yet. One line of three dashes between prompts.';
+ }
+ if (note) note.textContent = per ? ('each ~' + (per < 10 ? Math.round(per * 2) / 2 : Math.round(per)) + ' min') : '';
+ const seedsHint = document.getElementById('batchSeedsHint');
+ if (seedsHint) {
+ const main = batchMainPrompt();
+ seedsHint.textContent = !main
+ ? 'Write a prompt above — every take renders that prompt.'
+ : (BATCH_SEP_RX.test(main)
+ ? 'This prompt contains a line of three dashes, which Batch uses to '
+ + 'separate prompts. Remove it, or use Many prompts instead.'
+ : 'Every take uses the prompt above with a fresh random seed.');
+ }
+ if (total) total.textContent = list.length ? _batchFmtTotal(list.length, per) : '';
+ if (btn) {
+ btn.disabled = list.length < 2;
+ btn.textContent = list.length > 1 ? ('Queue ' + list.length + ' jobs') : 'Queue batch';
+ }
+ if (meta) {
+ meta.textContent = !list.length ? 'one render at a time'
+ : (_batchMode === 'seeds'
+ ? _batchTakes + ' takes of this prompt' + (per ? ' · ' + _batchFmtTotal(list.length, per).split('· ')[1] : '')
+ : _batchFmtTotal(list.length, per));
+ }
+}
+
+// "Same prompt, N takes" reads #prompt, so the section has to hear it change:
+// without this the Queue button stayed disabled while the user typed the very
+// prompt it was waiting for, and only woke up when some other control moved.
+document.addEventListener('DOMContentLoaded', () => {
+ const p = document.getElementById('prompt');
+ if (p) p.addEventListener('input', () => {
+ if (typeof updateBatchSummary === 'function') updateBatchSummary();
+ });
+});
+
+// The queue-strip pill and any shortcut land on the section now.
+function openBatch() {
+ const d = document.getElementById('batchDetails');
+ if (!d) return;
+ d.open = true;
+ d.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ const ta = document.getElementById('batchPrompts');
+ if (_batchMode === 'prompts' && ta) ta.focus();
+ updateBatchSummary();
+}
+function closeBatch() {
+ const d = document.getElementById('batchDetails');
+ if (d) d.open = false;
+}
+
async function queueBatch() {
+ const list = batchPrompts();
+ if (list.length < 2) {
+ alert(_batchMode !== 'seeds'
+ ? 'Paste at least two prompts, separated by a line of three dashes.'
+ : (BATCH_SEP_RX.test(batchMainPrompt())
+ ? 'Your prompt contains a line of three dashes. Batch uses that to '
+ + 'separate prompts, so it cannot repeat this one — remove the '
+ + 'dashes, or switch to Many prompts.'
+ : 'Write a prompt above first — a batch of takes renders that prompt.'));
+ return;
+ }
const fd = new FormData(document.getElementById('genForm'));
- fd.set('prompts', document.getElementById('batchPrompts').value);
- const r = await api('/queue/batch','POST',fd);
- if (r && r.error) { alert('Batch error: '+r.error); return; }
- if (r && r.added) { document.getElementById('batchPrompts').value = ''; poll(); }
+ fd.set('prompts', list.join('\n---\n'));
+ // Takes mode is N renders of ONE prompt, so the seed must be random per job
+ // or every take comes back identical. -1 is the panel's "random", resolved
+ // per job at render time and recorded as seed_used.
+ if (_batchMode === 'seeds') fd.set('seed', '-1');
+ const r = await api('/queue/batch', 'POST', fd);
+ if (r && r.error) { alert('Batch error: ' + r.error); return; }
+ if (r && r.added) {
+ if (_batchMode === 'prompts') {
+ const ta = document.getElementById('batchPrompts');
+ if (ta) ta.value = '';
+ }
+ updateBatchSummary();
+ closeBatch();
+ poll();
+ }
}
// ====== "No music" toggle pill ======
@@ -4881,8 +5096,9 @@ Object.assign(globalThis, {
selectOutput, openExpandLightbox, closeExpandLightbox, phosToast,
animateActive, hide, openOutputsFolder, hideActive,
useAsExtendSource, useAsUpscaleSource, useAsUpscaleSourcePath, setUpscalePreset,
- faceFixClip, faceFixActive, loadParams, _flashActionDone, closeOutputInfoModal,
+ faceFixClip, faceFixActive, isUpscaledPath, loadParams, _flashActionDone, closeOutputInfoModal,
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,
diff --git a/webapp/js/shortcuts.js b/webapp/js/shortcuts.js
index d8c9416..ebb2e59 100644
--- a/webapp/js/shortcuts.js
+++ b/webapp/js/shortcuts.js
@@ -137,11 +137,21 @@ const SHORTCUTS = [
{ id: 'editor.mute', scope: 'editor', combos: ['m'], owner: 'editor.js',
calls: ['sbeSetMute', 'sbeUnmuteFromRefusal'],
label: 'Mute / unmute the preview — the film itself is not changed' },
- // The sound area's size. It manages itself; this is the key for when you
- // want one answer to stick — the ▾ on the A1 head is the same control.
- { id: 'editor.soundLanes', scope: 'editor', combos: ['shift+a'], owner: 'editor.js',
- calls: 'sbeAudioPinToggle',
- label: 'Sound lanes small / full height — A1, A2 and the audio tracks (the ▾ on the A1 head does the same)' },
+ // 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.
+ { id: 'editor.soundMode', scope: 'editor', combos: ['shift+a'], owner: 'editor.js',
+ calls: 'sbeSoundModeToggle',
+ label: 'Sound mode on / off — the sound lanes at full height and the picture small (the ⌁ Sound button and the ▾ on the A1 head do the same)' },
+ { id: 'editor.inspector', scope: 'editor', combos: ['mod+i'], owner: 'editor.js',
+ calls: 'sbeInspectToggle',
+ label: 'Inspector open / close — speed, fades, brightness, zoom, transitions, titles (double-clicking a clip opens it too)' },
+ { id: 'editor.fullscreen', scope: 'editor', combos: ['f'], owner: 'editor.js',
+ calls: 'sbeFullscreen',
+ label: 'Program monitor full screen — F or Esc brings it back' },
+ { id: 'editor.panels', scope: 'editor', combos: ['backquote'], display: [['`']], owner: 'editor.js',
+ calls: 'sbePanelsToggle',
+ label: 'Hide / show the media pool and the queue, so the cut has the window (Photoshop\'s Tab)' },
{ id: 'editor.undo', scope: 'editor', combos: ['mod+z'], owner: 'editor.js',
calls: 'sbeUndo', label: 'Undo' },
{ id: 'editor.redo', scope: 'editor', combos: ['shift+mod+z'], owner: 'editor.js',
diff --git a/webapp/js/tips.js b/webapp/js/tips.js
new file mode 100644
index 0000000..c3173d1
--- /dev/null
+++ b/webapp/js/tips.js
@@ -0,0 +1,217 @@
+// webapp/js/tips.js — FAST TOOLTIPS for the panel's icon buttons.
+//
+// "The tooltips take too long … The tooltips on the buttons are too slow."
+// The browser's own `title` tooltip waits about a second and cannot be told to
+// hurry. This is one shared tooltip element instead:
+//
+// * 150 ms after the pointer settles on a button (TIP_DELAY_MS), and at once
+// while you slide along a row — a tip that was showing, or closed less
+// than TIP_WARM_MS ago, makes the next one immediate;
+// * name · what it does · the keys, the keys as keycaps. The name is the
+// title's first line, or the words before " — "; the keys come from the
+// element's data-shortcut (the one SHORTCUTS table) or a trailing "(⌘I)";
+// * placed below the element, flipped above when there is no room, and kept
+// 8px inside the window on every side;
+// * keyboard focus shows it too (focus-visible only, so a click does not);
+// * no transition under prefers-reduced-motion (the CSS owns that).
+//
+// NOTHING THAT WRITES A TITLE HAD TO CHANGE. The code that paints these
+// buttons keeps setting `title` (and the tests keep reading it). A button in
+// TIP_SCOPE has its title moved into data-tip the moment the pointer or the
+// focus reaches it, and a MutationObserver moves it again whenever a repaint
+// writes a new one — so the OS tooltip never gets its second, and the custom
+// one always shows the current text. aria-label is left alone; when a button
+// has no accessible name but its title, the name is copied to aria-label
+// before the title goes.
+
+const TIP_DELAY_MS = 150;
+const TIP_WARM_MS = 400;
+const TIP_GAP = 6;
+const TIP_MARGIN = 8;
+// The icon buttons: the Editor's strips, tool row, View group and header, the
+// player's action pills (.po-act), and anything that opts in with data-tip.
+const TIP_SCOPE = [
+ '.sbe-ibtn', '.sbe-tbtn', '.sbe-vbtn', '#sbeCbar .sbe-cbar-btn', '.sbe-chipbtn',
+ '.sbe-head .ghost-btn', '.sbe-head .primary', '.sbe-info', '.po-act', '[data-tip]',
+].join(', ');
+
+const TIP = { el: null, target: null, timer: 0, lastHide: 0, shown: false };
+
+function tipEl() {
+ if (TIP.el) return TIP.el;
+ const el = document.createElement('div');
+ el.className = 'phos-tip';
+ el.id = 'phosTip';
+ el.setAttribute('role', 'tooltip');
+ el.hidden = true;
+ document.body.appendChild(el);
+ TIP.el = el;
+ return el;
+}
+
+function tipEsc(s) {
+ return String(s).replace(/[&<>"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[ch]));
+}
+
+// Take the title off an element in scope and keep it as data-tip.
+function tipAdopt(el) {
+ if (!el || !el.getAttribute) return;
+ const t = el.getAttribute('title');
+ if (t === null) return;
+ if (!t) delete el.dataset.tip;
+ else {
+ el.dataset.tip = t;
+ const named = el.getAttribute('aria-label') || el.getAttribute('aria-labelledby')
+ || (el.textContent || '').trim();
+ if (!named) el.setAttribute('aria-label', tipSplit(el, t).name || t);
+ }
+ el.removeAttribute('title');
+}
+
+function tipScoped(node) {
+ if (!node || node.nodeType !== 1 || !node.closest) return null;
+ return node.closest(TIP_SCOPE);
+}
+
+// Keys: data-shortcut first (the registry is the truth), then a trailing
+// "(…)" that reads like keys. Returns [text-without-keys, [groups]].
+function tipKeys(el, text) {
+ let groups = [];
+ let body = text;
+ const id = el.getAttribute && el.getAttribute('data-shortcut');
+ const hint = (id && typeof shortcutHint === 'function') ? shortcutHint(id) : '';
+ const m = body.match(/\s*\(([^()]{1,28})\)\s*$/);
+ const looksLikeKeys = (s) => /[⌘⇧⌥⌃⌫⏎↑↓←→`]/.test(s) || /^[A-Za-z0-9+\-]$/.test(s.trim())
+ || /^([A-Za-z0-9+\-]|⌘\S+)( or ([A-Za-z0-9+\-]|⌘\S+))+$/.test(s.trim());
+ if (m && (m[1] === hint || looksLikeKeys(m[1]))) {
+ body = body.slice(0, m.index);
+ if (!hint) groups = m[1].split(/\s+or\s+/);
+ }
+ if (hint) groups = hint.split(/\s+or\s+/);
+ return [body, groups];
+}
+
+function tipSplit(el, raw) {
+ const [text, keys] = tipKeys(el, String(raw || '').trim());
+ let name = '', body = text;
+ const nl = text.indexOf('\n');
+ if (nl > 0 && nl <= 48) { name = text.slice(0, nl); body = text.slice(nl + 1); }
+ else {
+ const dash = text.indexOf(' — ');
+ if (dash > 0 && dash <= 40) { name = text.slice(0, dash); body = text.slice(dash + 3); }
+ else if (text.length <= 40) { name = text; body = ''; }
+ }
+ body = body.trim();
+ if (body) body = body.charAt(0).toUpperCase() + body.slice(1);
+ return { name: name.trim(), body: body, keys: keys };
+}
+
+function tipRender(target) {
+ const el = tipEl();
+ const raw = target.dataset.tip || '';
+ const s = tipSplit(target, raw);
+ const keys = s.keys.length
+ ? '<span class="phos-tip-keys">' + s.keys.map(k => '<kbd>' + tipEsc(k) + '</kbd>')
+ .join('<span class="phos-tip-or">or</span>') + '</span>'
+ : '';
+ el.innerHTML = (s.name || keys
+ ? '<div class="phos-tip-head">' + (s.name ? '<span class="phos-tip-name">' + tipEsc(s.name) + '</span>' : '') + keys + '</div>'
+ : '')
+ + (s.body ? '<div class="phos-tip-body">' + tipEsc(s.body) + '</div>' : '');
+}
+
+function tipPlace(target) {
+ const el = tipEl();
+ const r = target.getBoundingClientRect();
+ const vw = window.innerWidth, vh = window.innerHeight;
+ const w = el.offsetWidth, h = el.offsetHeight;
+ let top = r.bottom + TIP_GAP;
+ if (top + h > vh - TIP_MARGIN && r.top - TIP_GAP - h >= TIP_MARGIN) top = r.top - TIP_GAP - h;
+ top = Math.max(TIP_MARGIN, Math.min(vh - TIP_MARGIN - h, top));
+ let left = r.left + r.width / 2 - w / 2;
+ left = Math.max(TIP_MARGIN, Math.min(vw - TIP_MARGIN - w, left));
+ el.style.left = Math.round(left) + 'px';
+ el.style.top = Math.round(top) + 'px';
+}
+
+function tipShow(target) {
+ clearTimeout(TIP.timer);
+ if (!target.isConnected || !target.dataset.tip) { tipHide(); return; }
+ const el = tipEl();
+ const warm = TIP.shown || (performance.now() - TIP.lastHide < TIP_WARM_MS);
+ if (TIP.target && TIP.target !== target) TIP.target.removeAttribute('aria-describedby');
+ TIP.target = target;
+ tipRender(target);
+ el.hidden = false;
+ el.classList.toggle('is-warm', warm);
+ tipPlace(target);
+ target.setAttribute('aria-describedby', 'phosTip');
+ el.classList.add('is-shown');
+ TIP.shown = true;
+}
+
+function tipHide() {
+ clearTimeout(TIP.timer);
+ TIP.timer = 0;
+ if (TIP.target) TIP.target.removeAttribute('aria-describedby');
+ TIP.target = null;
+ if (!TIP.shown) return;
+ TIP.shown = false;
+ TIP.lastHide = performance.now();
+ const el = tipEl();
+ el.classList.remove('is-shown');
+ el.hidden = true;
+}
+
+function tipArm(target) {
+ tipAdopt(target);
+ if (!target.dataset.tip) { tipHide(); return; }
+ if (TIP.target && TIP.target !== target) TIP.target.removeAttribute('aria-describedby');
+ clearTimeout(TIP.timer);
+ const warm = TIP.shown || (performance.now() - TIP.lastHide < TIP_WARM_MS);
+ if (warm) { tipShow(target); return; }
+ TIP.target = target;
+ TIP.timer = setTimeout(() => tipShow(target), TIP_DELAY_MS);
+}
+
+// Pointer: `pointerover` reaches disabled buttons in current Chromium and
+// WebKit, and the disabled ones are where the tooltip says WHY.
+document.addEventListener('pointerover', (ev) => {
+ if (ev.pointerType === 'touch') return;
+ const t = tipScoped(ev.target);
+ if (t) { if (t !== TIP.target) tipArm(t); return; }
+ if (TIP.target) tipHide();
+}, true);
+document.addEventListener('pointerout', (ev) => {
+ const t = tipScoped(ev.target);
+ if (!t || t !== TIP.target) return;
+ if (ev.relatedTarget && t.contains(ev.relatedTarget)) return;
+ tipHide();
+}, true);
+document.addEventListener('pointerdown', () => tipHide(), true);
+document.addEventListener('scroll', () => { if (TIP.shown || TIP.timer) tipHide(); }, true);
+window.addEventListener('blur', () => tipHide());
+document.addEventListener('keydown', (ev) => { if (ev.key === 'Escape' && TIP.shown) tipHide(); }, true);
+document.addEventListener('focusin', (ev) => {
+ const t = tipScoped(ev.target);
+ if (!t || t !== ev.target) return;
+ let visible = false;
+ try { visible = t.matches(':focus-visible'); } catch (e) {}
+ if (visible) tipArm(t);
+});
+document.addEventListener('focusout', (ev) => { if (tipScoped(ev.target) === TIP.target) tipHide(); });
+
+// A repaint that writes a new title on a button in scope: adopt it at once,
+// and refresh the tip if it is the one on screen (a toggle that just flipped).
+if (typeof MutationObserver === 'function') {
+ new MutationObserver((muts) => {
+ for (const m of muts) {
+ const el = m.target;
+ if (!el.hasAttribute('title') || !el.matches || !el.matches(TIP_SCOPE)) continue;
+ tipAdopt(el);
+ if (el === TIP.target && TIP.shown) { tipRender(el); tipPlace(el); }
+ }
+ }).observe(document.documentElement, { attributes: true, attributeFilter: ['title'], subtree: true });
+}
+
+Object.assign(globalThis, { tipSplit, tipHide, TIP_DELAY_MS, TIP_SCOPE });
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index 41a4218..1d7b95d 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -1460,6 +1460,14 @@
/* Anything that cannot survive 300px scrolls. */
overflow-x: hidden;
}
+ /* PANELS HIDDEN (` or the ▯ in the header): the left column — workflow
+ tabs, media pool, queue — is gone and the cut has the window. Photoshop's
+ Tab. The state is this browser's (phos_sbe_panels). */
+ body.ed-focus[data-workflow="editor"] main.layout {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ body.ed-focus[data-workflow="editor"] main.layout > aside.form-pane { display: none; }
+ body.ed-focus[data-workflow="editor"] main.layout > .stage-pane { grid-column: 1 / 2; }
/* THE CUT SPANS BOTH ROWS, exactly as the base layout does for every
other workflow. This rule said `grid-row: 1 / 2` for two releases, so
row 2 — the bottomPane's own height, 170px measured at 1440x900 — was
@@ -1632,6 +1640,10 @@
screen; the kebab is a square. */
.sbe-draftchip { width: auto; gap: 6px; color: var(--muted); }
.sbe-draftchip #sbeDraftName { color: var(--text); font-weight: 600; }
+ /* The draft's name yields with the title now that the View group shares
+ the header: it ellipsises past 200px instead of taking the title's room. */
+ .sbe-head .ghost-btn.sbe-draftchip { flex: 0 1 auto; min-width: 0; max-width: 220px; }
+ .sbe-head .sbe-draftchip #sbeDraftName { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sbe-car { color: var(--muted); font-size: var(--fs-2xs); }
.sbe-split { display: inline-flex; }
.sbe-split > .primary:first-child {
@@ -1672,6 +1684,8 @@
font-size: var(--fs-2xs); font-style: italic; cursor: help;
}
.sbe-info:hover { color: var(--text); border-color: var(--accent); }
+ /* Amber when its tooltip carries a note (the preview is muted, the soundtrack cannot play here). */
+ .sbe-info.is-noted { color: var(--warn, #d9a441); border-color: var(--warn, #d9a441); }
/* ---- the lane gutter --------------------------------------------
Its heads read the SAME variables the lanes do, so the two columns
cannot drift apart at any height the handle is dragged to. The two
@@ -1904,6 +1918,40 @@
.sbe-head .sbe-draftchip #sbeDraftName { display: none; }
.sbe-head .sbe-draftchip { padding-inline: 8px; }
}
+ /* ---- VIEW: the panel toggles, one labelled group ------------------
+ A segmented control. OFF is quiet (muted glyph, no fill); ON is the
+ accent fill with the accent glyph, so "which panels are showing" reads
+ across the room. Labels fold below 1360px unless the side panels are
+ hidden (the header is then as wide as the window). */
+ .sbe-view {
+ display: inline-flex; align-items: center; gap: 2px; flex: 0 0 auto;
+ height: var(--ctl-h-sm); box-sizing: border-box; padding: 2px; margin-right: 6px;
+ background: var(--bg-2); border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ }
+ .sbe-vbtn {
+ width: auto; flex: 0 0 auto; display: inline-flex; align-items: center; gap: 6px;
+ height: 22px; padding: 0 8px 0 6px; margin: 0;
+ background: transparent; border: 1px solid transparent; border-radius: var(--r-xs);
+ color: var(--muted); font-size: var(--fs-xs); font-weight: 500; line-height: 1;
+ cursor: pointer; white-space: nowrap;
+ transition: background var(--t-fast), color var(--t-fast), border-color var(--t-fast);
+ }
+ .sbe-vbtn .sbe-cbar-i { width: 18px; height: 18px; }
+ .sbe-vbtn > b { font-weight: inherit; }
+ .sbe-vbtn:hover { color: var(--text); background: var(--panel-2); }
+ .sbe-vbtn:focus-visible { outline: none; box-shadow: var(--ring); }
+ .sbe-vbtn[aria-pressed="true"] {
+ background: var(--accent-dim); border-color: color-mix(in srgb, var(--accent) 60%, transparent);
+ color: var(--accent-bright);
+ }
+ .sbe-vbtn[aria-pressed="true"]:hover { color: #fff; }
+ .sbe-vbtn-act { padding: 0 3px; }
+ .sbe-vsep { width: 1px; height: 16px; margin: 0 3px; background: var(--border); flex: 0 0 auto; }
+ @media (max-width: 1359px) {
+ body:not(.ed-focus) .sbe-vbtn > b { display: none; }
+ body:not(.ed-focus) .sbe-vbtn { padding: 0 3px; }
+ }
.sbe-state {
font-size: var(--fs-xs); color: var(--muted); display: inline-flex;
align-items: center; gap: 6px; white-space: nowrap;
@@ -1977,12 +2025,76 @@
}
/* The two bars under the monitors and the transport share the header's
rung: they are the same rank of control and were 29px against 28. */
- .sbe-mon-bar .ghost-btn, .sbe-transport .ghost-btn,
- .sbe-transport .primary {
+ .sbe-mon-bar .ghost-btn, .sbe-mon-bar .primary,
+ .sbe-toolrow .ghost-btn, .sbe-toolrow .primary {
width: auto; flex: 0 0 auto; height: var(--ctl-h-sm);
padding-block: 0; padding-inline: 10px; font-size: var(--fs-xs);
}
+ /* THE STRIP UNDER THE PROGRAM MONITOR: transport on the left, what is
+ under the playhead in the middle, the panel toggles on the right. It
+ is the row Premiere and Resolve put there, and it is where the clip's
+ name went when it came off the picture. Fixed min-height, nowrap: the
+ budget in sbeFitMonitors reads this row's height as a constant. */
+ .sbe-mon-bar-prog { gap: 6px; }
+ .sbe-mon-bar-prog .sbe-time { flex: 0 0 auto; }
+ .sbe-mon-bar .sbe-mon-clip {
+ flex: 1 1 60px; min-width: 0; overflow: hidden; text-overflow: ellipsis;
+ white-space: nowrap; color: var(--text); font-size: var(--fs-xs);
+ margin-left: 2px;
+ }
+ .sbe-mon-bar-prog .sbe-mon-name { flex: 0 1 auto; }
+ /* ICON BUTTONS on the strips: a 28px square, the glyph in currentColor.
+ `is-on` is the pressed state of a toggle (Inspector open, Source on). */
+ .sbe-ibtn, .sbe-mon-bar .sbe-ibtn.ghost-btn, .sbe-toolrow .sbe-ibtn.ghost-btn {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 28px; min-width: 28px; padding-inline: 0; flex: 0 0 auto;
+ }
+ .sbe-ibtn .sbe-cbar-i { width: 18px; height: 18px; }
+ .sbe-ibtn.is-on { background: var(--accent-dim); border-color: var(--accent); color: var(--accent-bright); }
+ /* A COUNT CHIP (rendered-not-placed, the snapshot in the header): a pill
+ that is also a button. */
+ .sbe-chipbtn {
+ display: inline-flex; align-items: center; gap: 5px; flex: 0 0 auto;
+ width: auto; height: 22px; padding: 0 9px;
+ background: var(--panel-2); border: 1px solid var(--border);
+ border-radius: var(--r-pill); color: var(--muted);
+ font-size: var(--fs-2xs); line-height: 1; cursor: pointer;
+ white-space: nowrap;
+ }
+ .sbe-chipbtn:hover { border-color: var(--accent); color: var(--accent-bright); }
+ .sbe-chipbtn[hidden] { display: none !important; }
+ .sbe-chipbtn .sbe-cbar-i { width: 13px; height: 13px; }
+ .sbe-snapchip { color: var(--warn, #d9a441); border-color: color-mix(in srgb, var(--warn, #d9a441) 45%, var(--border)); }
+ /* THE MONITOR IN FULL SCREEN: the browser hands the stage the whole
+ screen; the ratio and the frame come off so the picture is the screen. */
+ .sbe-stage:fullscreen, .sbe-stage:-webkit-full-screen {
+ width: 100%; height: 100%; max-width: none; aspect-ratio: auto;
+ border: 0; border-radius: 0; box-shadow: none; background: #000;
+ }
+ /* Guests: the Source monitor and the rail are display:none while hidden,
+ whatever the flex rules above would otherwise give them. */
+ .sbe-mon-src[hidden], .sbe-rail[hidden] { display: none !important; }
.sbe-mon-src .sbe-stage { height: var(--sbe-src-h); }
+ /* EACH MONITOR COLUMN IS EXACTLY ITS PICTURE'S WIDTH. Left to content,
+ the Program column's bar (time, clip name, chip) asked for more than
+ the picture, the row shrank the Source column to pay for it, and the
+ 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); }
+ .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. */
+ .sbe-mon-src .sbe-stage { transition: border-color var(--t-fast), box-shadow var(--t-fast); }
+ .sbe-mon-src.is-drop-ready .sbe-stage { border-color: color-mix(in srgb, var(--accent) 55%, var(--border)); border-style: dashed; }
+ .sbe-mon-src.is-drop-over .sbe-stage {
+ border-color: var(--accent-bright); border-style: solid;
+ box-shadow: 0 0 0 3px var(--accent-dim), var(--shadow-1);
+ }
+ .sbe-src-empty { flex-direction: column; gap: 6px; }
+ .sbe-src-empty .sbe-cbar-i { width: 28px; height: 28px; stroke-width: 14; opacity: 0.55; }
+ .sbe-src-empty b { font-weight: 600; color: var(--text); font-size: var(--fs-sm); }
+ .sbe-src-empty span { font-size: var(--fs-xs); max-width: 260px; line-height: 1.4; }
+ .sbe-mon-src.is-drop-over .sbe-src-empty .sbe-cbar-i { opacity: 1; color: var(--accent-bright); }
/* The rail takes an EXPLICIT height, never `stretch`. A stretched flex
item still offers its content height as the line's hypothetical size,
so a long inspector would have grown the row and pushed the picture
@@ -2064,6 +2176,12 @@
object-fit: contain; opacity: 0; background: #000;
}
.sbe-stage img.sbe-still.is-on { opacity: 1; }
+ /* THE BADGE IS A WARNING, NOT A CAPTION. The clip's name is on the strip
+ under the picture (#sbeProgClip); this carries only "no proxy" and only
+ while the pointer is on the picture, so nothing sits on the frame. */
+ .sbe-stage-badge { opacity: 0; transition: opacity var(--t-fast); }
+ .sbe-stage:hover .sbe-stage-badge.is-warn, .sbe-stage:hover #sbeSrcBadge { opacity: 1; }
+ .sbe-stage-badge[hidden] { display: none !important; }
.sbe-stage-badge {
position: absolute; left: 8px; top: 8px; z-index: 3;
background: rgba(0,0,0,0.62); border: 1px solid var(--border);
@@ -2150,9 +2268,12 @@
background: var(--accent-dim); border-color: var(--accent);
color: var(--accent-bright);
}
+ /* THE GLYPHS ARE PHOSPHOR SYMBOLS on a 256-unit grid (the sprite in
+ index.html), so the stroke is in those units: 22 is 1.5px at 18px and
+ 1.2px at the 14px of a menu row — Phosphor's own regular weight is 16. */
.sbe-cbar-i {
- flex: 0 0 auto; width: 13px; height: 13px;
- fill: none; stroke: currentColor; stroke-width: 1.7;
+ flex: 0 0 auto; width: 14px; height: 14px; overflow: visible;
+ fill: none; stroke: currentColor; stroke-width: 22;
stroke-linecap: round; stroke-linejoin: round;
}
/* THE FOLD, RESTATED. `display: inline-flex` on the class beats the UA's
@@ -2185,10 +2306,35 @@
.sbe-cbar { flex-wrap: wrap; overflow: visible; }
}
- .sbe-transport {
- display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
- position: relative;
+ /* THE TOOL ROW: the clip bar plus the timeline's own controls, one row,
+ and the grab hanging below it. `position: relative` is for the grab;
+ the bar inside clips its own overflow (the More menu takes the rest),
+ so the grab cannot live inside the bar. */
+ .sbe-toolrow { position: relative; display: flex; min-width: 0; }
+ .sbe-toolrow > .sbe-cbar { flex: 1 1 auto; }
+ /* ICONS ONLY on the row: the label is in the tooltip (and in the More
+ and right-click menus, where the buttons are a list). 28px squares,
+ the glyph at 15px so it reads at arm's length. */
+ #sbeCbar > .sbe-cbar-btn > b { display: none; }
+ #sbeCbar > .sbe-cbar-btn, .sbe-tbtn {
+ width: 28px; min-width: 28px; padding: 0; justify-content: center;
+ }
+ #sbeCbar > .sbe-cbar-btn .sbe-cbar-i, .sbe-tbtn .sbe-cbar-i { width: 18px; height: 18px; }
+ #sbeCbar > .sbe-cbar-more { width: auto; min-width: 0; padding: 0 8px; }
+ .sbe-tbtn {
+ flex: 0 0 auto; display: inline-flex; align-items: center; gap: 5px;
+ height: var(--ctl-h-sm); background: var(--panel-2);
+ border: 1px solid var(--border); color: var(--text); border-radius: var(--r-xs);
+ font-size: var(--fs-xs); line-height: 1; cursor: pointer; white-space: nowrap;
+ transition: background var(--t-base), border-color var(--t-base), color var(--t-base);
}
+ .sbe-tbtn > b { display: none; }
+ .sbe-tbtn:hover { background: var(--bg-2); border-color: var(--accent); color: var(--accent-bright); }
+ .sbe-tbtn:focus-visible { outline: none; box-shadow: var(--ring); }
+ .sbe-snap { margin: 0; font-size: 11px; flex: 0 0 auto; white-space: nowrap; }
+ /* The row must never clip its last button: the slider is the one thing on it that can give. */
+ .sbe-toolrow .sbe-zoom input[type="range"] { width: 88px; }
+ .sbe-toolrow > .sbe-cbar { padding-right: 2px; }
/* ---- THE TIMELINE'S TOP EDGE, as a handle ------------------------
"It needs to allow you to drag the upper side of the timeline, which
will change the layout a little bit, enabling expansion in case you
@@ -3189,6 +3335,42 @@
font-variant-numeric: tabular-nums; color: var(--text);
min-width: 42px; text-align: right;
}
+ /* ---- ROOM TONE: the card on the pool's Sound tab ------------------ */
+ .ed-rt {
+ display: flex; flex-direction: column; gap: 6px; padding: 9px 10px; flex: 0 0 auto;
+ background: var(--panel-2); border: 1px solid var(--border);
+ border-radius: var(--r-md); box-shadow: var(--shadow-1);
+ }
+ .ed-rt[hidden] { display: none !important; }
+ .ed-rt-head { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
+ .ed-rt-title { font-size: var(--fs-md); font-weight: 600; color: var(--text); }
+ .ed-rt-status {
+ margin-left: auto; min-width: 0; overflow: hidden; text-overflow: ellipsis;
+ white-space: nowrap; color: var(--muted); font-size: var(--fs-xs);
+ font-variant-numeric: tabular-nums;
+ }
+ .ed-rt-status.is-on { color: var(--success); }
+ .ed-rt-sub, .ed-rt-note { margin: 0; color: var(--muted); font-size: var(--fs-xs); line-height: 1.4; }
+ .ed-rt-note[hidden] { display: none; }
+ .ed-rt-note { color: var(--warning); }
+ .ed-rt-pick { width: 100%; margin: 0; }
+ .ed-rt-level {
+ display: flex; align-items: center; gap: 8px; font-size: var(--fs-xs); color: var(--muted);
+ }
+ .ed-rt-level input[type=range] { flex: 1 1 auto; min-width: 0; margin: 0; accent-color: var(--accent); }
+ .ed-rt-level output {
+ flex: 0 0 auto; min-width: 62px; text-align: right; color: var(--text);
+ font-variant-numeric: tabular-nums; font-weight: 600;
+ }
+ .ed-rt-acts { display: flex; gap: 6px; flex-wrap: wrap; }
+ .ed-rt-acts .ghost-btn { flex: 1 1 auto; width: auto; height: var(--ctl-h-sm); }
+ .ed-rt-acts .ghost-btn.primary {
+ background: var(--accent); border-color: var(--accent); color: #fff;
+ }
+ .ed-rt-acts .ghost-btn.primary:hover:not(:disabled) { background: var(--accent-bright); }
+ .ed-rt-acts .ghost-btn[hidden] { display: none; }
+ .ed-rt-auto { font-size: var(--fs-xs); color: var(--muted); margin: 0; }
+ .ed-pool-make[hidden] { display: none !important; }
.ed-pool-make { display: flex; gap: 6px; align-items: center; }
.ed-pool-make .sb-input { width: 66px; flex: 0 0 auto; }
.ed-pool-make .ghost-btn { flex: 1 1 auto; }
@@ -5597,6 +5779,13 @@
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 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; }
+ .h3-speed .h3-turbo-note { margin-top: 6px; }
+ /* Upscale & Face Fix beside Generate. */
+ .form-action-footer .h3-facefix-footer { margin: 2px 0 8px; font-size: 12px; }
+ .form-action-footer .h3-facefix-footer .cz-label-hint { display: inline; margin-left: 6px; }
/* The honest one-liner under the Speed control. Shown only while Turbo is
on, so it describes the render being queued rather than advertising.
Shares .cz-note's metrics with the export note so the two sentences
@@ -7057,13 +7246,6 @@
/* Upscale & Face Fix on video cards: the only chip a video card has
besides Delete, so it takes the row. Ellipsis on a narrow card; the
title carries the whole sentence. */
- .car-card .card-chrome .card-action-facefix {
- flex: 1 1 auto;
- min-width: 0;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
.car-card .card-chrome .card-action-danger {
flex: 0 0 auto;
width: 28px;
@@ -9879,8 +10061,18 @@
/* Mode + Quality pickers as Linear's grouped panel: a subtle inset
container with hairline border, then 4 buttons inside. */
+ /* cols-3 and cols-5 joined this list on 2026-09-18. They had never been in
+ it, so a three- or five-option group rendered with NO container at all:
+ transparent background, no border, no padding, and only the selected pill
+ painted — which is why "After the render" read as three loose words with
+ one box around the middle one while the METHOD row (cols-2) right beneath
+ it sat in a proper segmented trough. Owner: "the other stuff that is in
+ there doesn't look related to the design at all." One rule, every group
+ count, same control. */
.pill-group.cols-2,
- .pill-group.cols-4 {
+ .pill-group.cols-3,
+ .pill-group.cols-4,
+ .pill-group.cols-5 {
gap: 6px;
padding: 3px;
background: rgba(140, 160, 220, 0.04);
@@ -10673,3 +10865,359 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }
.h3-facefix-after .cz-label-hint { display: block; margin-left: 0; }
#h3UpscaleGroup.is-overridden .pill-btn { opacity: 0.45; }
#h3UpscaleGroup.is-overridden .pill-btn[data-h3-upscale="off"] { opacity: 1; }
+
+/* ---- FAST TOOLTIPS (webapp/js/tips.js) ---------------------------------------
+ "The tooltips on the buttons are too slow." The OS tooltip waits ~1 s; this
+ one waits 150 ms, and none at all while you slide along a row of buttons.
+ One element for the whole page, position: fixed, never takes a click. */
+.phos-tip {
+ position: fixed; left: 0; top: 0; z-index: 10050; pointer-events: none;
+ max-width: 300px; padding: 7px 10px 8px;
+ background: rgba(10, 14, 32, 0.97); color: #eef2fb;
+ border: 1px solid rgba(160, 175, 230, 0.20); border-radius: 8px;
+ box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45), 0 1px 0 rgba(255,255,255,0.04) inset;
+ font-size: 12px; line-height: 1.4; letter-spacing: 0;
+ opacity: 0; transform: translateY(2px);
+ transition: opacity 90ms ease-out, transform 90ms ease-out;
+}
+.phos-tip.is-shown { opacity: 1; transform: none; }
+.phos-tip.is-warm { transition: none; }
+.phos-tip[hidden] { display: none !important; }
+.phos-tip-head { display: flex; align-items: center; gap: 8px; }
+.phos-tip-name { font-weight: 600; color: #fff; }
+.phos-tip-keys { margin-left: auto; display: inline-flex; gap: 3px; flex: 0 0 auto; padding-left: 10px; }
+.phos-tip-keys kbd {
+ font: 600 10.5px/1 var(--ph-font-mono, ui-monospace, Menlo, monospace);
+ padding: 3px 5px; min-width: 18px; text-align: center;
+ 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-body { color: #b9c3dc; margin-top: 2px; white-space: pre-line; }
+.phos-tip-head + .phos-tip-body:empty { display: none; }
+@media (prefers-reduced-motion: reduce) {
+ .phos-tip, .phos-tip.is-shown { transition: none; transform: none; }
+}
+
+/* ============================================================================
+ RENDER FORM · THE THREE SECTIONS (layout pass, 2026-09-18)
+ Owner: "you have a pill for speed, quality, length, and all that. That should
+ be inside one section that you can compress and decompress … it should be
+ closed by default … I don't think it is easy to navigate between the options."
+ The form keeps FOUR things in the open — engine (header), mode (bar), the
+ composer (reference + prompt) and Generate (sticky footer) — and folds the
+ rest into three named disclosures: Shot setup, After the render, Advanced.
+ Everything below is chrome for that: no control changed size, class or id,
+ the rows only changed parent, so these rules re-home the margins the rows
+ used to get from sitting loose in the form.
+ ========================================================================== */
+
+/* The primary section of the three. A 2 px accent edge in the ACTIVE ENGINE's
+ colour (the same --eng-* variable the chips use) so the one section a user
+ opens on most renders is the one the eye lands on, and so switching engine
+ is visible even with every section shut. */
+.customize-section.shot-setup {
+ border-color: var(--eng-soft, var(--accent, #8b7bff));
+ box-shadow: inset 2px 0 0 0 var(--eng-accent, var(--accent, #8b7bff));
+}
+.customize-section.shot-setup > summary .cz-title { color: var(--text); }
+/* The shape, right-aligned, in the summary: the closed section still says what
+ will render. Let it use the room it needs before it ellipsises. */
+.cz-summary .cz-meta {
+ min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ text-align: right;
+}
+/* Three boxes in a row need air between them, and the first one needs to clear
+ the composer. */
+.quick-settings > .customize-section { margin-top: 0; }
+#sizingSection > .customize-section + .customize-section { margin-top: 6px; }
+
+/* ---- rows that moved INTO a .cz-body keep their own spacing ---------------
+ Each of these had a margin tuned for standing loose in the form; inside the
+ flex column (gap: 14px) that margin doubles up. */
+.cz-body .h3-speed { margin: 0; }
+.cz-body > .engine-hint { margin: 0; }
+.cz-body .eng-primary { margin-top: 0; gap: 14px; }
+.cz-body > #quickMetricsRow { margin: 0; }
+.cz-body > #quickMetricsRow .mini-fields { grid-template-columns: minmax(0, 220px); }
+/* #aspectRow carries an inline display:flex that setQuality() clears when it
+ shows the row again (it writes style.display = ''), which used to drop it to
+ 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; }
+/* The Quality/Length axis block (the unnamed wrapper around the strips). */
+.cz-body > div > .qs-label:first-child { margin-top: 0; }
+
+/* ---- the notes that deliberately stay OUTSIDE the disclosure -------------
+ #ltxTierNote / #h3TierNote warn about the render you are about to queue, so
+ they must not be foldable. They used to hug the strip above them with a
+ negative top margin; now they follow a box. */
+.quick-settings > .engine-hint { margin: 8px 0 0 0; }
+.quick-settings > .engine-note { margin-bottom: 8px; }
+
+/* ---- a narrow form pane --------------------------------------------------
+ The panel is a three-column desktop layout and does not reflow for a phone,
+ but the form pane itself is narrow on a 13" screen and narrower again when
+ the window is dragged in — and four fixed columns of chips stop being
+ readable long before they stop fitting. These are auto-fit tracks, not media
+ queries, so the strips answer to the PANE's width rather than the window's:
+ four across in the pane's usual ~470 px, two when it is squeezed, one when
+ it is tiny. At full width the grids are identical to the fixed ones they
+ replace. */
+.cz-body .quality-strip { grid-template-columns: repeat(auto-fit, minmax(90px, 1fr)); }
+/* qs-label is name-left / meta-right with space-between and no wrap, so in a
+ squeezed pane "SPEED" and "Fast = 3 steps · Best = full steps" ran into each
+ other. Let the meta drop to its own line instead. */
+.quick-settings .qs-label { flex-wrap: wrap; column-gap: 10px; }
+.cz-body .pill-group.cols-4 { grid-template-columns: repeat(auto-fit, minmax(62px, 1fr)); }
+.cz-body .pill-group.cols-3 { grid-template-columns: repeat(auto-fit, minmax(94px, 1fr)); }
+.cz-body .pill-group.cols-2 { grid-template-columns: repeat(auto-fit, minmax(118px, 1fr)); }
+@media (max-width: 560px) {
+ .cz-summary { flex-wrap: wrap; row-gap: 2px; }
+ .cz-summary .cz-meta { margin-left: 22px; flex-basis: 100%; text-align: left; }
+ .cz-body { padding: 10px 10px 12px; }
+ .cz-body > #aspectRow.mode-only.show { flex-wrap: wrap; }
+}
+
+/* ---- the shot list, now a block of its own -------------------------------
+ #h3WindowPromptsRow left the render controls for the composer's side of the
+ form, where it has no .cz-body panel around it. Give it the same quiet
+ chrome the sections have so it reads as a block that belongs to the prompt,
+ and stop .cz-label's uppercase from shouting at the toggle inside it. */
+#genForm > .h3-winprompts {
+ margin: 10px 0 12px; padding: 10px 12px;
+ border: 1px solid var(--border); border-radius: 8px;
+ background: rgba(255,255,255,0.012);
+}
+.cz-label .toggle-pill {
+ text-transform: none; letter-spacing: 0; font-weight: 500;
+}
+#genForm > .h3-winprompts .cz-label { flex-wrap: wrap; row-gap: 6px; }
+#genForm > .h3-winprompts .cz-label > span:first-child { white-space: nowrap; }
+
+/* The LoRAs summary is the fourth section of the same stack now, and it was the
+ only one that could overflow: a chevron, a title, a count and FOUR action
+ buttons on one line, in a pane the user can drag down to 500 px. It printed
+ "27 installed" over two squeezed lines with "Check for updates" hanging off
+ the edge. Let the row wrap — the count stays on the title's line, the buttons
+ drop to their own right-aligned row — instead of shrinking the words. */
+.loras-summary { flex-wrap: wrap; row-gap: 8px; }
+.loras-summary .loras-title { flex: 0 0 auto; }
+.loras-summary .loras-meta { white-space: nowrap; }
+.loras-summary .loras-header-actions { margin-left: auto; flex-wrap: wrap; justify-content: flex-end; }
+/* ...and they must not each take the whole line. A width:100% rule upstream
+ (every button inside the render form is full-width by default) made the
+ three header buttons 407 px each, so a CLOSED LoRAs section still cost
+ 163 px of stacked blue buttons — the exact clutter the fold is for. Back to
+ their own widths: the row is ~380 px and sits on one line at panel width,
+ and still wraps instead of overflowing when the pane is dragged narrow. */
+.loras-summary .loras-browse-btn { width: auto; flex: 0 0 auto; }
+
+/* ---- Batch, as a section (2026-09-18) ----------------------------------
+ The count and the queue button share one row so the number you are about
+ to commit to is next to the button that commits it. The button is the
+ section's only primary; it greys out until there are at least two jobs,
+ because "Queue batch" on one prompt is just Generate with extra steps. */
+#batchDetails .batch {
+ width: 100%;
+ min-height: 132px;
+ resize: vertical;
+ font-size: 12.5px;
+ line-height: 1.5;
+}
+#batchDetails .batch-actions {
+ display: flex; align-items: center; gap: 10px;
+ justify-content: space-between;
+ margin: 10px 0 6px;
+}
+#batchDetails .batch-total {
+ font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12px; color: var(--accent-bright);
+}
+#batchDetails .batch-queue-btn {
+ width: auto; flex: 0 0 auto;
+ padding: 7px 16px;
+ border-radius: 6px;
+ border: 1px solid var(--accent);
+ background: var(--accent);
+ color: #fff;
+ font-size: 12.5px; font-weight: 600;
+ cursor: pointer;
+ transition: background 100ms, opacity 100ms;
+}
+#batchDetails .batch-queue-btn:hover:not(:disabled) { background: var(--accent-bright, #58a6ff); }
+#batchDetails .batch-queue-btn:disabled { opacity: 0.45; cursor: not-allowed; }
+#batchDetails #batchCount,
+#batchDetails #batchSeedsHint {
+ margin-top: 6px;
+ font-family: var(--ph-font-mono);
+ font-size: 10.5px;
+ color: var(--ph-text-faint);
+}
+
+/* ---- checkbox rows inside a section (2026-09-18) ----------------------
+ A bare `label.check` beside a segmented control looks like a different
+ application. Same trough, same hairline, same radius as the pill groups,
+ so an option that happens to be a switch still reads as one of the
+ section's controls — and its hint takes the mono/faint treatment the
+ pills' own .sub uses instead of body text at full contrast. */
+#genForm .cz-body .check {
+ margin: 8px 0 0;
+ padding: 8px 10px;
+ gap: 10px;
+ align-items: flex-start;
+ background: rgba(140, 160, 220, 0.04);
+ border: 1px solid var(--ph-border-soft);
+ border-radius: 8px;
+ font-size: 12px;
+}
+#genForm .cz-body .check:hover { border-color: var(--eng-soft, var(--accent)); }
+#genForm .cz-body .check input { margin-top: 1px; }
+#genForm .cz-body .check .cz-label-hint {
+ display: block;
+ margin-top: 2px;
+ font-family: var(--ph-font-mono);
+ font-size: 10.5px;
+ color: var(--ph-text-faint);
+ text-transform: none;
+ letter-spacing: 0;
+}
+/* The section's own note is a note, not a divider between two switches. */
+#genForm .cz-body .cz-note { margin: 8px 0 2px; }
+@media (max-width: 560px) {
+ .loras-summary { padding: 10px; }
+ .loras-summary .loras-header-actions { gap: 4px; }
+}
+
+
+/* ============ ONE CONTROL SCALE (2026-09-18) ==========================
+ Owner, with a screenshot of the LoRAs header: "all the buttons are
+ different. What the fuck? You need to really clean up the visuals so it looks
+ professional in general."
+
+ Measured in that one row before this rule: the rescan icon button 28 px tall,
+ "Browse CivitAI" 43 px (its inline-styled <svg> inflated the line box),
+ "Check for updates" 31 px; one line below, the queue chips 27 px with a pill
+ radius at 11 px text, a 35 px batch button at 12.5 px, and Generate at 46 px
+ / 13 px. Four heights, three radii and four type sizes inside a column
+ 500 px wide — which is exactly what "all the buttons are different" looks
+ like from the outside.
+
+ THE SCALE: 30 px tall, 6 px radius, 12 px/600 text, 10 px side padding,
+ 14 px icons with a 6 px gap, centred by flexbox rather than by line-height
+ (the inline vertical-align hacks existed to fight that line box). Icon-only
+ buttons are square at the same height. Generate keeps its own size: it is
+ the page's one big action and is meant to outrank everything here.
+
+ THE HIERARCHY, one per row: filled accent = the call to action
+ (Browse CivitAI, Queue batch); hairline = everything else; hover raises the
+ border to the engine accent. Nothing in a section header is filled twice. */
+#genForm .loras-summary .loras-icon-btn,
+#genForm .loras-summary .loras-browse-btn,
+#genForm .batch-queue-btn,
+.form-action-footer .queue-strip .qchip {
+ box-sizing: border-box;
+ height: 30px; min-height: 30px;
+ padding: 0 10px;
+ border-radius: 6px;
+ font-size: 12px; font-weight: 600; line-height: 1;
+ letter-spacing: 0;
+ display: inline-flex; align-items: center; justify-content: center; gap: 6px;
+ width: auto; flex: 0 0 auto;
+}
+#genForm .loras-summary .loras-icon-btn { width: 30px; padding: 0; }
+#genForm .loras-summary button .ph,
+.form-action-footer .queue-strip .qchip .ph {
+ width: 14px; height: 14px; margin: 0; flex: 0 0 auto;
+}
+/* Secondary: the hairline. One border colour, one text colour, one hover. */
+#genForm .loras-summary .loras-icon-btn,
+#genForm .loras-summary .loras-browse-btn.is-ghost,
+.form-action-footer .queue-strip .qchip {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--muted);
+}
+#genForm .loras-summary .loras-icon-btn:hover,
+#genForm .loras-summary .loras-browse-btn.is-ghost:hover,
+.form-action-footer .queue-strip .qchip:hover {
+ color: var(--text);
+ border-color: var(--eng-soft, var(--accent));
+ background: rgba(47, 129, 247, 0.06);
+}
+/* Primary: filled, and the only filled thing in its row. */
+#genForm .loras-summary .loras-browse-btn:not(.is-ghost),
+#genForm .batch-queue-btn {
+ background: var(--accent);
+ border: 1px solid var(--accent);
+ color: #fff;
+}
+#genForm .loras-summary .loras-browse-btn:not(.is-ghost):hover,
+#genForm .batch-queue-btn:hover:not(:disabled) {
+ background: var(--accent-bright, #58a6ff);
+ border-color: var(--accent-bright, #58a6ff);
+}
+
+/* ---- the same scale, applied to the strays ---------------------------------
+ An audit of every visible button on the page found seven radii (4, 5, 6, 7,
+ 8, 9, 10 px and full pills) and six type sizes (10.5 - 13 px) among controls
+ that do the same KIND of job. Families that genuinely differ keep their own
+ size — the tier chips are tall cards, the mode chips carry two lines,
+ Generate is the page's one big action, the dense card overlay actions stay
+ 24 px — but a small action button is now one thing everywhere:
+
+ small action button 30 px tall, 6 px radius, 12 px text
+ dense/inline action 24-28 px tall, 6 px radius
+ a row of filters stays a pill row (All / Videos / Photos / Audio):
+ pills read as "pick one of these", buttons read as
+ "do something", and that distinction is worth
+ keeping — it just has to be the ONLY exception.
+
+ Sizes only. No colour, no border, no hover behaviour is touched here. */
+.icon-btn, .open-folder-btn {
+ height: 30px; min-height: 30px;
+ border-radius: 6px;
+ font-size: 12px;
+ display: inline-flex; align-items: center; justify-content: center;
+}
+/* The header is its own family and should be: bigger, borderless, 34 px — a
+ title bar is not a form. It just has to be ONE family, so the engine picker
+ and the icon buttons beside it share a height and a radius instead of
+ 34/9 px next to 34/7 px. */
+body > header .icon-btn, .eng-trigger { border-radius: 8px; }
+.eng-trigger { height: 34px; min-height: 34px; }
+.icon-btn { width: 30px; padding: 0; }
+.ghost-btn { height: 30px; border-radius: 6px; font-size: 12px; }
+.lora-row .lora-icon-btn { width: 24px; height: 24px; border-radius: 6px; font-size: 12px; }
+.po-act { height: 28px; border-radius: 6px; }
+/* The segmented pair keeps its shared edge — a group, not two buttons. */
+.po-act:first-child { border-radius: 6px 0 0 6px; }
+.po-act:last-child { border-radius: 0 6px 6px 0; }
+.workflow-tabs button, .tabs button {
+ height: 28px; min-height: 28px;
+ border-radius: 6px;
+ font-size: 12px;
+}
+.stage-outputs-filter button { border-radius: 999px; font-size: 11.5px; height: 26px; }
+/* Generate and Stop are one pair and must not carry two radii (6 vs 10). */
+.form-action-footer .actions .primary,
+.form-action-footer .actions .danger { border-radius: 6px; }
+/* The last two: a header icon button that kept 7 px because its id carries
+ more weight than its class, and the Finder button in the carousel head at
+ 8 px among 6 px siblings. Every visible button on the page is now 6 px
+ (controls), 8 px (the header family and the two-line cards) or a pill (the
+ one filter row). */
+body > header #settingsBtn { border-radius: 8px; }
+.carousel-head .open-folder-btn { border-radius: 6px; }
+.eng-trigger { font-size: 12px; }
+/* 99px was a typo-grade stray next to 999px pills — same shape, different number. */
+#healthChip { border-radius: 999px; }
+/* ---- one icon, one gap ----------------------------------------------------
+ Icons inside buttons and labels carried their geometry inline, with the gap
+ written by hand at 3, 4, 5, 6 and 8 px in different places (and a
+ vertical-align hack to fight the line box). Same two values, once, in CSS —
+ families that need another size keep their own, more specific, rule. */
+button .ph, label .ph, .qchip .ph { width: 14px; height: 14px; }
+button > .ph:first-child:not(:only-child),
+label > .ph:first-child:not(:only-child),
+.qchip > .ph:first-child:not(:only-child) { margin-right: 6px; vertical-align: -2px; }