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.

v4.13.0 — the editor you already know

mrbizarrodfaf4db00a10
diff --git a/README.md b/README.md
index a8973a2..80da39d 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@
</p>
-> **Current release: v4.12.4.** **Ten fixes from the field**: the queue no longer stays "Worker paused" after a restart, the Avoid box stops pushing the avoided thing into the picture, Hailuo H3 renders on 48 GB Macs again when Settings said Full, long H3 renders with per-window prompts no longer fail on a cache error, a dub a moment shorter than its clip no longer crashes, FLUX.2 klein stops reporting a finished download as stuck, and training survives the macOS GPU watchdog on its retry. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
+> **Current release: v4.13.0.** **The editor you already know**: a clip bar above the tracks for the everyday cuts, select several clips and move them together, right-click menus, keys from Premiere and Final Cut, and **Docs built into the app** (the Docs button, or press ?). One Shot gets its own tab, and Storyboard scores spoken shots for lip-sync. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
## Overview
diff --git a/VERSION b/VERSION
index 23297c3..813b83b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.12.4
+4.13.0
diff --git a/docs/API.md b/docs/API.md
index df4ceeb..7e1975b 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -137,6 +137,45 @@ Submit multiple prompts as one batch.
## Status — poll job state
+### One Shot — its own door: `POST /oneshot` (2026-09-08)
+
+One Shot is a workflow tab and a first-class API. A script posts the same
+document the tab posts — one JSON object — and gets the queued job back:
+
+```bash
+curl -s -X POST http://127.0.0.1:8198/oneshot -H 'Content-Type: application/json' -d '{
+ "prompt": "A red vintage tram rolls through a rain-soaked Lisbon street at night; a woman with a yellow umbrella waits at the stop. The bell rings twice; rain on the roof.",
+ "seconds": 60,
+ "engine": "ltx",
+ "quality": "balanced",
+ "camera": "a slow, steady push in along the street",
+ "beats": ["the tram comes round the corner", "", "the woman steps to the kerb"],
+ "handoff": "last"
+}'
+# → {"ok": true, "id": "j-…", "plan": {"seconds": 60, "parts": 6, "beats": 12, "engine": "ltx", "handoff": "last", "minutes": 28.2, "eta": "~28 min"}}
+```
+
+| Field | Type | Default | Meaning |
+|---|---|---|---|
+| `prompt` | str | **required** | The whole shot, once: who, where, the time of day and the weather, the sound. With no beats it carries every five seconds. |
+| `seconds` | int | `60` | One of 30 / 45 / 60 / 90 / 120. Any other value is refused, never rounded (a 75 used to render as one clip). |
+| `engine` | `ltx` / `h3` | `ltx` | LTX renders 10 s parts (faces, voices, dialogue); H3 renders 15 s parts (motion, landscapes). H3 is refused when not installed. |
+| `quality` | str | engine default | LTX: `quick` / `balanced` / `standard` / `high`; with a character: `draft` / `pro` / `high` / `high_720p`; H3: `draft` / `standard` / `high` / `native`. |
+| `beats` | list or newline text | none | One line per five seconds. A blank line holds that moment; extra lines are dropped. Absent = the prompt is every beat. |
+| `camera` | str | `""` | One move for the whole shot, its direction and speed; carried into every part (`take_camera`). |
+| `image` | path | none | A start frame already on this Mac — upload first with `POST /upload` (field `image`) and pass the returned `path`. Makes the first part i2v. |
+| `character_id` | str | none | A trained character (LTX only). Defaults quality to `pro`, the export to 720p Sharp, and `handoff` to `speech`. `character_strength`, `voice_strength` optional. |
+| `handoff` | `last` / `speech` | `last` (`speech` with a character) | Where a part hands off: its last frame, or a talking frame with the last word carried over the next part (see the take contract below). |
+| `light_lock` / `retake` | on/off | `on` | The continuity sentence on every beat; one drift retake per part. |
+| `seed`, `label`, `no_music`, `turbo` (H3), `upscale`, `upscale_method` | | | As on `/queue/add`. |
+
+`GET /oneshot/options` — what this Mac can do: `seconds`, `engines.{ltx,h3}` (available, `part_seconds`, `qualities`), `character_qualities`, `characters` (id, name, trigger, has_voice), `planner`.
+`GET /oneshot/estimate?engine=&quality=&seconds=` — `parts`, `part_seconds`, `beats`, `minutes`, `eta`.
+`POST /oneshot/plan` `{prompt, seconds, engine}` — the Storyboard planner writes one beat per five seconds from the prompt (blocks 20–40 s): `{ok, beats:[…]}`.
+`GET /oneshot/status` — `current` (id, label, part, parts, `lipsync` per part, `drift`, handoff), `queued`, `recent`, and the take's own `log` lines.
+
+Under the hood every One Shot is the take contract below — `POST /oneshot` maps the document onto `make_job`'s form, so the tab, the API and `/queue/add` render exactly the same job.
+
### One take — `take_seconds` + `beats` on `POST /queue/add`
A clip longer than a single pass, on either engine. `take_seconds` is one of
@@ -523,7 +562,7 @@ Renders a multi-view turnaround sheet from the character's reference image (bund
```json
{
- "engine_override": "hidream_inline",
+ "engine_override": "qwen_edit_inline",
"views": ["front", "profile_left", "three_quarter"],
"wardrobe": "a red flight jacket",
"seed": -1
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ed583ef..307c263 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -33,6 +33,7 @@ webapp/ ← the frontend, as plain files served from disk
│ ├── health.js ← version pill, update pop-up/banner, health chip
│ ├── storyboard.js ← the Storyboard tab
│ ├── editor.js ← the timeline editor
+│ ├── oneshot.js ← the One Shot tab (its own composer; posts to /oneshot)
│ └── main.js ← the kickoff sequence — ALWAYS the last tag (see below)
└── style/
└── panel.css ← ALL panel CSS (slice 1, landed)
diff --git a/docs/EDITOR_EFFECTS_MODEL.md b/docs/EDITOR_EFFECTS_MODEL.md
index 5a0e877..3493416 100644
--- a/docs/EDITOR_EFFECTS_MODEL.md
+++ b/docs/EDITOR_EFFECTS_MODEL.md
@@ -64,6 +64,24 @@ The inspector presents brightness in the **Effects** section beside the fades,
because that is where a person looks for it. Presentation follows the model;
storage follows history.
+## The inspector is the PROPERTIES panel now (2026-09-12)
+
+The three sections below are unchanged, but the inspector no longer holds
+verbs. Lock, Duplicate, Lift, Ripple delete, Unlink/Link sound, Resync, Mute,
+Delete sound and Clear points moved to a **clip bar** above the tracks, because
+a cutter presses them hundreds of times a session and they were in a 212px rail
+in the corner, drawn identically to a brightness slider — and four of them were
+rendered conditionally, so they appeared and disappeared with the selection.
+
+> "We have some, but they are hidden inside that menu, the toggle menu on the
+> right. That is not a good use... You can leave it if the person wants to dig
+> into the options and then put advanced options there."
+
+The rule that decides where a new control goes is therefore **how many times an
+hour**, not what it is a property of: a verb goes on the bar, a property stays
+here, and rare-or-slow stays here too (Retake opens a render). The first
+section carries one line saying so. Full account: `docs/EDITOR_TOOLBAR.md`.
+
## The inspector has sections now
The inspector grew one control at a time and was a flat run of buttons with a
diff --git a/docs/EDITOR_TOOLBAR.md b/docs/EDITOR_TOOLBAR.md
new file mode 100644
index 0000000..bfedf05
--- /dev/null
+++ b/docs/EDITOR_TOOLBAR.md
@@ -0,0 +1,203 @@
+# The clip bar, and what is left in the inspector
+
+Status: **built**, 2026-09-12. Sibling to `docs/EDITOR_EFFECTS_MODEL.md` and
+`docs/EDITOR_SAVE_MODEL.md`.
+
+## The ruling
+
+> "It's really hard when you are using the editor of Phosphene to use the
+> basic tools you actually need to use all the time, for instance, unlink and
+> link audio... We have an empty corner that we can use in the upper part of
+> the timeline, like a button thingy. Of course, the buttons need to be really
+> clear about what they are for. I find myself all the time un-syncing and
+> syncing. Maybe some kind of delete button for the anchors of the audio.
+> Basic stuff that we are missing exists in a normal video editor, and they
+> should be there. We have some, but they are hidden inside that menu, the
+> toggle menu on the right. That is not a good use... You can leave it if the
+> person wants to dig into the options and then put advanced options there."
+
+And, the same day:
+
+> "You should be able to select, hit Shift, and select multiple clips and move
+> them together. It's very important."
+
+## The rule that decides where a control lives
+
+**A verb goes on the bar. A property stays in the inspector.**
+
+A cutter presses split, lift, ripple, unlink and resync hundreds of times in a
+session and sets a font size twice. Both were drawn identically, in the same
+212px rail, in the corner of the screen — and four of the verbs were rendered
+*conditionally*, so they appeared and disappeared as the selection changed.
+That is how "Delete sound" came to be invisible on every linked clip, which is
+almost every clip: it read as a feature that did not exist.
+
+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).
+
+## Where it is
+
+A row of its own, between the monitors and the transport, directly above the
+tracks — where Resolve and Final Cut both put it, and the corner the owner
+pointed at. It costs the column 28px plus its gap, which `sbeFitMonitors`
+measures like every other child; at 1600×1000 that is the picture going from
+620×349 to 594×334. That is the price, it is paid on purpose, and it is the
+one number to argue with if the bar is ever the wrong trade.
+
+## What is on it, in order
+
+Cut, then remove, then the sound, then the pin.
+
+| | verb | acts on | key |
+|---|---|---|---|
+| 1 | **Split** | the shot under the **playhead** — never the selection, as in every NLE | `S` |
+| 2 | **Lift** | the selection; leaves the hole (a black slug) | `⌫` |
+| 3 | **Ripple delete** | the selection; closes the gap | `⇧⌫` |
+| 4 | **Duplicate** | the selection; each copy lands behind its original | `D` |
+| 5 | **Unlink / Re-link / Link sound** | the selection | `⇧L` |
+| 6 | **Resync sound** | the selection's out-of-sync strips | `⇧R` |
+| 7 | **Mute / Unmute sound** | the selection | |
+| 8 | **Delete sound** | the selection; only once the halves are separate | |
+| 9 | **Clear points** | the selection's level anchors | |
+| 10 | **Lock / Unlock** | the selection | |
+
+Left of them is the one readout that makes the rest legible: the clip's name,
+or *"3 clips selected"*. Right of them is **More**, which holds nothing of its
+own — see *Overflow* below.
+
+### Three rules every button follows
+
+1. **It disables; it never disappears.** A disabled button's tooltip carries
+ the sentence that would make it work ("Unlink the sound first…", "Put the
+ playhead over a shot…"). A control that is not on screen teaches nothing.
+2. **The label says what you get, the tooltip says the consequence.** "Unlink
+ sound" / "Frees this clip's sound from the picture so you can slide it under
+ the shot before or after — the J-cut and the L-cut. The picture does not
+ move."
+3. **One table, three consumers.** `sbeCbarModel()` returns the row set; the
+ bar, the overflow panel and the right-click menu all read it. Three sets of
+ labels would be three chances for one of them to go on offering a verb the
+ model has stopped accepting.
+
+### Overflow, not wrap
+
+`flex-wrap` would answer a narrow pane with a second row, and a second row is
+height `sbeFitMonitors` takes off the picture. So `sbeCbarFit` measures the
+row and moves its tail into `#sbeCbarMenu`, last button first, until what is
+left fits; everything comes home when the pane is widened. There is exactly
+one copy of every control, and its position is stamped once (`data-ord`) so a
+button returns to where it came from. Measured once per width-and-label
+change, not once per painted frame — `sbePaint` runs on every frame of a drag.
+Below the 900px stacking breakpoint the page is the scroller, there is no
+column height to protect, and the bar is allowed to wrap.
+
+## What stayed in the inspector
+
+Everything that is a **property of the one selected clip**: transition kind and
+length, speed, picture fades, brightness, zoom and reframe, sound fades, the
+level line's "Add point at playhead", a title's text and styling — and Retake.
+Its first section now carries one line, *"Advanced — the everyday verbs are on
+the bar above the tracks"*, so a panel that used to be full of buttons does not
+read as a panel with buttons missing. With several clips selected it says so,
+and whose properties it is showing.
+
+The three section names — **Clip / Sound / Effects** — are unchanged. That is
+the model `docs/EDITOR_EFFECTS_MODEL.md` describes and the home the next effect
+lands in without a decision.
+
+## "The anchors of the audio"
+
+There are two things in this editor that could be called an anchor, and the
+honest answer covers both.
+
+* **The level points** — the dots on the yellow line inside a sound strip. They
+ are the only anchors a person *places* on a sound, so **Clear points** is the
+ delete button the owner asked for. Removing one is still a right-click or a
+ shift-click on the dot itself; the bar removes them all, across the whole
+ selection, and says how many went.
+* **The link point** — where a strip is pinned to its picture. It is not a
+ thing you delete, it is a state you change, and **Unlink sound** /
+ **Re-link sound** / **Resync sound** are that state. They sit adjacent on the
+ bar because the difference between the last two is the thing that is hard to
+ hold in your head: re-link makes the pair permanent at whatever offset it has,
+ resync only slides the sound back under its own frame and leaves it free.
+
+No new data model was invented for either.
+
+## Selecting several clips
+
+`SBE.sel` stays a single id and stays the **primary** — the one clip the
+inspector describes, the preview loads and the sound buttons read their state
+from. `SBE.selSet` is the full selection and always contains it.
+
+The invariant is repaired in **one place**, `sbeSelNormalise()` at the top of
+`sbePaint`, and not at every assignment. A lift, a duplicate, a resync and a
+dozen other paths write `SBE.sel = …` directly; a set maintained by hand at
+each of them is a set that is stale by the next feature. So pointing `SBE.sel`
+at a clip outside the set **collapses** the selection to that clip — which is
+the correct behaviour at every one of those call sites, and costs them nothing.
+
+### The gestures, and the two modifiers that were already taken
+
+| gesture | what it does |
+|---|---|
+| click | select this shot |
+| click inside a multiple selection | keeps the selection so the drag can move the block; collapses to this shot if the pointer never moves |
+| shift-click | the range, from the anchor |
+| ⌘-click | add or drop one — resolved on **pointerup**, because the same chord is ripple-drag while the pointer moves |
+| ⌘A / Esc / click empty track | all / none / none |
+| drag a selected shot | slides the whole block |
+| alt+shift-drag | reorder (it was shift alone; shift went to the range) |
+| alt+←/→ | nudge the selection one frame, ⇧ ten |
+
+Reorder also became **Move earlier / Move later** in the right-click menu,
+which is easier to find than the modifier it gave up.
+
+### The arithmetic
+
+A group move is one question per **boundary**. Slide a set by `d` and leave
+everything else put: the only gaps that change are those between a moving clip
+and a still one, and each changes by exactly ±d. So the legal range of `d` is
+closed-form — the intersection of "no gap goes negative" over every boundary,
+which is `sbeGroupLimits` — and it is the same clamp a single-clip move already
+applies at its two neighbours, written once for any number of clips. Relative
+spacing is preserved by construction, holes inside the selection included.
+
+**The sound comes too**, and this is the one place the rule differs from a
+single-clip drag. Dragging one picture deliberately leaves its strip behind —
+that is how a J-cut is made. Sliding a block is not that gesture: it means "put
+these four shots a second later", and a strip left behind would be a sync error
+nobody asked for. Carrying also preserves any J-cut already inside the
+selection, because every strip moves by the same `d`.
+
+A group verb is **one undo step** (`sbeMutateEach`), and a locked member does
+not abort the rest — refusing the whole gesture over one pinned shot would make
+a multiple selection unusable — but the ones left alone are named in a toast.
+A mixed selection **converges**: the primary decides, so pressing Lock over
+three shots where one is pinned ends with three pinned shots, which is what the
+button says.
+
+## The bug this pass found
+
+**⌘S split the shot under the playhead instead of saving.** It has been
+documented as the manual save since `docs/EDITOR_SAVE_MODEL.md` §1 was written
+— "`Save` (and ⌘S)" — and it never did it: the bare-`S` split took the key
+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`.
+
+## Deliberately not built
+
+* **Copy / paste clips.** `Duplicate` covers "again, right here"; a clipboard
+ that survives across drafts needs insert-at-playhead semantics the gap model
+ does not have yet.
+* **J / K / L transport.** `Space` and the arrows cover play and step. The
+ shuttle needs a playback-rate model the one-`<video>` stage does not have.
+* **Snapping to a cut or to the playhead.** Snap is the beat grid only. The
+ model already clamps at neighbours, so butt joins are automatic; snapping to
+ the playhead is a real want and a bigger change than this pass.
+* **Overwrite drop from the media pool.** A drop inserts with ripple
+ (`sbeInsertAt`), which is the safe half; overwrite needs a trim-on-drop rule.
+* **A verb on the bar for a title or a card.** The bar acts on clips; with an
+ overlay selected the readout says so and `⌫` and the inspector handle it.
diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.md
index 09d9198..0b3cd43 100644
--- a/docs/H3_ENGINE.md
+++ b/docs/H3_ENGINE.md
@@ -287,6 +287,68 @@ can never disagree with the ffmpeg command because it is generated from it.
---
+## Dialogue on H3 — the recipe (measured 2026-09-08)
+
+H3 speaks only what is written inside its dialogue tag. A line written as
+prose quotes — `She says: "You said Tuesday."` — leaves the voice switched
+off and the model guessing: a 10 s draft written that way transcribed (whisper
+large-v3-turbo) as *"You know, for when? Please, Jack, you're telling him…"*.
+The same engine, same canvas, with the line in the tag, transcribed the line
+word for word — at 640×384 draft and at 768×448 standard alike, so a draft is
+enough to judge whether a line comes out.
+
+One 5-second window, in the three-field form the Storyboard planner writes
+(`docs/PROMPTING.md` has the laws; this is the shape):
+
+```text
+integrated_multimodal_description: [Shot 1] Live-action, vintage 1990s
+multi-camera sitcom, a medium shot of GEORGE, <two or three anchors: build,
+glasses, jacket>, <where he is, the light>. The camera holds a static shot,
+the frame never moves - no pan, no push-in, no reframing. <What he does
+first, in silence.> Then George, with a nasal, agitated New York voice (S1),
+says: <d>[English] I thought it was ashwagandha!</d> Exactly as his voice
+stops, his jaw ceases speaking motion and his mouth settles closed, and a
+studio audience laughs. No text appears at any point.
+
+overall_soundscape: The room tone of a television studio, then a burst of
+studio-audience laughter right after the line.
+
+non_diegetic_music: N/A
+```
+
+The rules that were paid for:
+
+- **The words go in `<d>[English] …</d>` and nowhere else.** Speaker, voice
+ and delivery stay outside the tag; the speaker keeps one ID (`(S1)`) across
+ every shot. The panel and the runner pass the tag through untouched.
+- **At most about eight words per five seconds.** Speech runs ~2.4 words a
+ second and the mouth needs a second to settle (`storyboard.SPEECH_WORDS_PER_SEC`
+ is the same budget the board validator enforces). A twelve-word line spills
+ past the window.
+- **Stop the mouth in the same sentence** — "his jaw ceases speaking motion
+ and his mouth settles closed" — or the model keeps it moving on nothing.
+- **Voiceover has a fixed phrase.** `George (S1) says in an off-screen
+ voiceover: <d>[English] …</d> while his lips remain completely closed.`
+ Without the closing clause the on-screen mouth lip-syncs the narration.
+- **One face in frame while a line plays.** Every mouth in frame moves to
+ whatever voice plays. The other character's hands may enter the frame; the
+ reverse angle is its own shot.
+- **A laugh track is a soundscape event**, not dialogue: "then a burst of
+ studio-audience laughter right after the line" gave a clean line at
+ 0.5–2.5 s and laughter at 3–4.5 s at the same loudness; the identical prompt
+ without it is silent after the line.
+- **Music is instrumentation.** "A funky slap bass riff with a bright synth
+ pop, fast tempo, two bars, that ends before he speaks" plays as a sting under
+ the first second; "upbeat sitcom music" is a mood word and does nothing
+ predictable.
+
+A chained 10 s or 15 s clip carries one line per window through the
+per-window prompts (`h3_chain_prompts`); a board shot carries one line per
+5 s shot. The Saint Feld chapter (twelve 5 s draft shots, every line
+transcribed back word for word on the first take) is the reference render.
+
+---
+
## LoRAs
H3 takes community adapters through the same `--lora PATH[:SCALE]` flag Turbo
diff --git a/docs/PROMPTING.md b/docs/PROMPTING.md
index e8e66d0..6bb38f9 100644
--- a/docs/PROMPTING.md
+++ b/docs/PROMPTING.md
@@ -4,6 +4,7 @@ Copy this whole page into your own assistant (ChatGPT, Claude, Codex) and ask it
## One Shot (a clip longer than one pass)
+- **One Shot has its own tab** beside Video: the shot, a start frame, who is in it, length and quality, then the beats with a time gutter, one camera line and the continuity switches. A script posts the same document to `POST /oneshot` (docs/API.md).
- **You do not have to write beats.** Leave the box empty and the prompt carries the whole shot, sustained for every five seconds. Write beats when you want the shot to *go* somewhere: each line directs its own five seconds, a blank line holds the moment before it.
- **One beat = five seconds = one thing that happens.** Lead with the movement: what the subject does, what the camera does, what enters the frame.
- **A scene change gets a beat of its own.** Going through a door, into a room, onto a bridge: give it its own five seconds, and put the *approach* in the beat before it. A scene change hidden at the end of a busy beat is the one the model skips.
diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.md
index e88b84e..ee9c108 100644
--- a/docs/RELEASE_CHECKLIST.md
+++ b/docs/RELEASE_CHECKLIST.md
@@ -25,6 +25,12 @@ zero tests from them and prints a green "Ran 0 tests / OK" that asserts
nothing). It prints a PASS/FAIL/SKIP table and exits non-zero on any failure.
**A SKIP is not a PASS** — it means the gate could not run.
+**Key every public step on the runner's exit code, explicitly.** On 2026-09-08 a
+release chain written as `set -e; …; [ "$G" = "0" ]; git push …` ran straight
+through a red gate (one UI test) and 4.12.2 went out with a failing test in its
+tree. `set -e` is not a gate. Write `if [ "$G" != "0" ]; then exit 1; fi` right
+after the gate line, or chain every public step with `&&` from that test onward.
+
This does NOT replace the sections below. From-zero, the Ideogram eyeball, the
smoke renders, the weight mirror and the update-path gate all need a human and
a real machine.
diff --git a/docs/STATE.md b/docs/STATE.md
index 71d78b7..7b5e8eb 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,5 +1,48 @@
# Phosphene — project state, history, open work
+> **🚀 2026-09-13 — v4.13.0 ships: "the editor you already know".** Owner:
+> "ship everything". Promoted dev's whole tree (5a1675a) onto origin/main by
+> read-tree: the Editor clip bar + multi-select + right-click + gap audit
+> keys (ba48941), Docs inside the panel + one SHORTCUTS registry (eee5f89,
+> 8878285), Escape never closes the film (5a1675a), One Shot as its own tab
+> with its composer and API (44dd227, 0c3632b), Storyboard lip-sync scoring
+> and retake for spoken shots (712109d, e0a3dd7), board stills anchor H3
+> shots (457b2b8), located H3 shots composed in the description (bc9871e),
+> Image Quality chip engine guard (d68e598), Sharp export 1080p (6a4b3d8),
+> settings writes merge per key (b75fd0d). Gates --fast 86 pass (the banner
+> test fails until the banner is written); release copy clicked through on
+> a scratch panel: all seven tabs, Editor on a cloned 13-clip board with the
+> clip bar, Docs, One Shot composer, zero console errors. From-zero install
+> NOT re-run (6 GB free disk); the change set is panel code and webapp only.
+
+> **📖 2026-09-13 — Docs inside the panel, and one table for every shortcut.**
+> A **Docs** button beside the settings gear (and `?` anywhere) opens a
+> full-height manual over whatever you are doing: left nav, search that filters
+> headings as you type, deep links `#docs/<section>/<anchor>` that work from any
+> link in the panel. Fourteen pages — Getting started, Video, One Shot, Remix,
+> Images, Storyboard, Audio, Editor (the deep one: clip bar button by button,
+> sound, music, titles, transitions, save model, deliver, five step-by-step
+> jobs), Train Character, LoRAs, Settings, Keyboard shortcuts, Buttons and
+> icons, Troubleshooting. Written against the code; the words are the UI's.
+> Source is Markdown in `webapp/docs/*.md`, rendered by `webapp/js/docs.js`
+> (no build step, served by the panel's `/webapp/` route, offline).
+> **`webapp/js/shortcuts.js` is the one list of shortcuts**: the Docs page, the
+> Editor's Keys popover and every `data-shortcut` tooltip render from it, and
+> `test_docs_and_shortcuts.py` drives the Editor's REAL keydown handler with
+> every row's keys (both directions), checks every docs link lands on a heading,
+> and forbids browser/macOS-reserved chords. New keys: `?` Docs, `⇧1–⇧7` tabs
+> (Resolve's pages), `⌘F` the on-screen search box, `⌘⏎` Generate from the
+> Video / Images prompt (the button's own submit path, refused when the button
+> is), Space play/pause and `⌘⌫` Trash (asks) for the selected output; in the
+> Editor `↑ ↓` previous/next cut, `⌘K` / `⌘B` split, `N` snap, `⇧Z` fit, and
+> **Render moved from ⌘R (the browser's reload — a refresh queued a render) to
+> ⌘E**. Fixed on the way: the Retake offer (*New take is ready · Use it*) was
+> painted into `#sbeRetakes`, which never existed in the markup — a finished
+> retake could not be put on the timeline; Storyboard's K/R/C grade keys fired
+> on ⌘C / ⌘R; the Outputs F / arrow keys fired inside the Editor; the Save
+> tooltip claimed an autosave that is only a backup; two toasts pointed at the
+> inspector for buttons that moved to the clip bar.
+
> **🩹 2026-09-13 — v4.12.4 ships: the morning's issues and fleet read.**
> Promoted by cherry-pick onto origin/main: ca9b8e9 (#80 paused queue clears
> on boot, Now card carries Resume), 5e888ee (#81 Avoid no longer folded into
@@ -32,6 +75,66 @@
> (`…50s_q8pro_sync.mp4` beside the original). Promoted by cherry-pick
> (9e3bbc1) onto origin/main.
+> **🔍 2026-09-09 — Upscale ×2 on a real film: 86 s of EX ALTO through seventeen chunks.**
+> The mode renders one pass at twice the source, so a long clip is cut first:
+> the film scaled to 768×432 (its native detail level — the 720p delivery was
+> a lanczos enlargement of 768×448 H3 renders), padded to the 1+8k grid and
+> split into 121-frame chunks, one `mode=upscale` job each (Faithful: keep 1.0,
+> from the clip's own latent, 3 refine steps, Q8 fused, one seed). Measured:
+> **447–531 s per 5 s chunk at 1536×832, 129 min for 86 s.** Two things the
+> mode does not tell you: (1) `ltx_floor_canvas` floors to /64, so a 16:9
+> source lands on 1536×**832** and the reference is resized onto it — a 3.7 %
+> squash, undone with one lanczos pass at assembly; (2) butt-joined chunks
+> pop, because the invented texture re-rolls per chunk (seam frame step 20
+> against ~11.5 inside a chunk) — a 24-frame exposure match plus a four-frame
+> blend toward the source at each edge (.25/.5 | .5/.25) brings the seam to
+> 12.6, no warp (the chunks are cuts of one continuous clip). Faithfulness by
+> passage (SSIM against the 768 source): 0.93–0.97 on the slow half, 0.81–0.86
+> with dips to 0.71 on the fast city passes, where the adapter re-draws
+> motion-blurred buildings rather than resolving them. Deliverables in the
+> gallery: `ex_alto_v2_from_above_86s_{track,wind}_x2_1536.mp4`. A
+> chunked long-clip path inside the mode itself (split, refine, seam-match,
+> rejoin, one job) is the obvious product follow-up.
+
+> **📺 2026-09-08 — Saint Feld, one chapter: the planner, the board, the Editor and H3 dialogue, end to end.**
+> A one-minute sitcom chapter (twelve 5 s H3 draft shots at 640×384, no
+> Turbo, ~5.6 min each) planned through `POST /storyboard/plan` (H3 engine,
+> two locations, five views derived), the shots then replaced with a
+> hand-written script through `save`, rendered by the board's own `render`,
+> cut whole in the Editor with a text-overlay title and delivered at native
+> size: `mlx_outputs/saint_feld_the_ceremony_h3_draft_60s.mp4`, 61.5 s. **All
+> twelve lines transcribed back word for word on the first take** (whisper
+> large-v3-turbo), the laugh track after each line where the soundscape asked
+> for it, the slap-bass sting where `non_diegetic_music` named the
+> instrument. What made it work is in `docs/H3_ENGINE.md` → "Dialogue on
+> H3 — the recipe": the line inside `<d>[English] …</d>` (prose quotes render
+> babble — the earlier 10 s dialogue draft transcribed as *"You know, for
+> when? Please, Jack…"*), ≤8 words per 5 s, the mouth stopped in the same
+> sentence, the exact voiceover phrase, one face per shot. Two things found on
+> the way: (1) **`compose_shot_prompt` put a located H3 shot's framing, eyeline
+> and room AFTER `non_diegetic_music:`** — the room in the score on every
+> H3 board with geography; fixed in `bc9871e` (`split_h3_fields`, the
+> additions compose into the description; `test_storyboard.H3ThreeFieldsCompose`).
+> (2) the plan route's `notes` is the RE-PLAN feedback field and refuses a
+> fresh plan ("feedback needs the plan it refers to"); a first plan carries
+> its structure in `concept` / `must`. Levelled each shot with `loudnorm`
+> before the cut (one shot rendered ~12 dB under its neighbours) and cut from
+> the native 5:3 files, not the pillarboxed 720p exports. Draft only — the
+> owner's call whether to re-shoot at Standard/High or Upscale ×2.
+> **2026-09-10 follow-up — the jungle shots re-shot at the final pass from the
+> owner's own stills, through the new lip-sync gate.** The draft chapter's
+> spoken shots scored −0.06 … +0.33 on the panel's mouth-vs-voice meter at the
+> same recipe: sync is a per-shot roll, One Shot already retook under 0.20 and
+> the board never did (`712109d` adds the gate; `e0a3dd7` makes the kept take's
+> job id and seed travel with it — `_sb_reconcile` had repointed shot 9 at the
+> last retake). Two rounds of GENERATED stills for the jungle lost the face
+> (Reference Edit re-posing a wide shot, text-only drafts); four stills the
+> owner supplied, cut to 1024×576 with the face kept, set as `still` and
+> rendered as anchored i2v at H3 high (`457b2b8`, `h3_first_frame`) held it
+> in one pass: sync +0.31 / +0.46 first take, every line transcribed verbatim,
+> ~18 min a take. v5 is `mlx_outputs/saint_feld_the_ceremony_v5_60s.mp4`
+> (Sharp ×2 from the native takes, centre-cut to the film's 5:3, `loudnorm`).
+
> **🎙️ 2026-09-07, evening — the handoff is a J-cut, and audio-first is out.**
> Two questions from the owner. (1) *Can he keep talking through a cut?* Yes,
> when the next part is anchored on a frame where his mouth is mid-word:
@@ -205,6 +308,24 @@
> shitty on the faces" — and the two-character experiment (bizarrotrn +
> eltrumpo at one table, Q8 Pro, camera lock) is the first render on this code.
+> **🎬 2026-09-08 — One Shot is its own door (on dev).** Owner: "One shot should be
+> its own thing… highly optimized… even one prompt should work, and the user
+> should be able to tweak it; the API should make good use of it." A workflow
+> tab beside Video with its own composer (`webapp/js/oneshot.js`,
+> `#oneshotSectionTab`): engine, the shot, a start frame, who is in it (trained
+> characters), length and quality with the cost on this Mac, beats with a time
+> gutter (+ 'Split my prompt' and 'Write the beats for me' through the Storyboard
+> planner), one camera line, three continuity switches (light, drift retake,
+> speech handoff — on by itself when a character is picked), More (seed, label,
+> no music), Generate, and a part-by-part status strip with the lip-sync verdicts.
+> It posts ONE document to `POST /oneshot` (`panel/routes_oneshot.py`, with
+> `/oneshot/options`, `/estimate`, `/plan`, `/status`), mapped onto make_job by
+> `oneshot_form()` so the tab, the API and /queue/add render the same job. The
+> mode chip, the folded panel and the hidden take fields are gone from the video
+> form; `setMode('oneshot')` and Load Params of a take open the tab. Tests:
+> `test_oneshot_api.py` (9), `OneShotIsATab` in the UI suite (11, the module run
+> in node). Walked live on a scratch panel before it left dev.
+
> **🚀 2026-09-08 — v4.12.2 ships: the morning's field reports.** The beats box no
> longer prefills from the prompt (one written beat + five holds was the half-state
> behind the field report); `h3_build_q8.sh` validates the Q8 pack in a fresh
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index bdbfbc4..02b7321 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -1319,8 +1319,57 @@ def get_settings_public() -> dict:
_SETTINGS = _load_settings()
+def _settings_file_stamp() -> tuple[int, int] | None:
+ try:
+ st = SETTINGS_FILE.stat()
+ return (st.st_mtime_ns, st.st_size)
+ except OSError:
+ return None
+
+
+_SETTINGS_STAMP: tuple[int, int] | None = _settings_file_stamp()
+
+
+def _settings_reload_if_changed() -> None:
+ """Under _SETTINGS_LOCK. Re-read panel_settings.json when another process
+ wrote it — two panels share one state dir on a dev box (the drive
+ symlink), and a second panel's boot or Settings save must be visible here."""
+ global _SETTINGS_STAMP
+ stamp = _settings_file_stamp()
+ if stamp == _SETTINGS_STAMP:
+ return
+ try:
+ with SETTINGS_FILE.open("r") as fh:
+ data = json.load(fh)
+ except Exception: # noqa: BLE001
+ return
+ if isinstance(data, dict):
+ for k, v in _settings_defaults().items():
+ data.setdefault(k, v)
+ _SETTINGS.clear()
+ _SETTINGS.update(data)
+ _SETTINGS_STAMP = stamp
+
+
+def _settings_write_delta(delta: dict) -> None:
+ """Under _SETTINGS_LOCK. Persist ONLY `delta` on top of what is on disk.
+
+ Why (2026-09-08): every writer used to dump this process's whole in-memory
+ dict. A panel that had been running since Sep 5 wrote its bookkeeping over
+ a file another panel had since saved the PostHog query key into, and the
+ key was gone — a secret typed once, silently emptied by an unrelated
+ write. Merging the delta onto the file as it is now means a stale copy can
+ only change the keys it is actually setting."""
+ global _SETTINGS_STAMP
+ _settings_reload_if_changed()
+ _SETTINGS.update(delta)
+ _save_settings(_SETTINGS)
+ _SETTINGS_STAMP = _settings_file_stamp()
+
+
def get_settings() -> dict:
with _SETTINGS_LOCK:
+ _settings_reload_if_changed()
return dict(_SETTINGS)
@@ -1351,11 +1400,11 @@ def update_settings(patch: dict) -> tuple[dict, str | None]:
if err:
return get_settings(), err
with _SETTINGS_LOCK:
- _SETTINGS.update(clean)
try:
- _save_settings(_SETTINGS)
+ _settings_write_delta(clean)
except Exception as exc:
- return get_settings(), f"could not persist settings: {exc}"
+ _SETTINGS.update(clean)
+ return dict(_SETTINGS), f"could not persist settings: {exc}"
return dict(_SETTINGS), None
@@ -12177,8 +12226,7 @@ def _settings_set_internal(**kv) -> None:
a bookkeeping write costs at most one duplicate boot event."""
try:
with _SETTINGS_LOCK:
- _SETTINGS.update(kv)
- _save_settings(_SETTINGS)
+ _settings_write_delta(kv)
except Exception:
pass
@@ -15916,6 +15964,207 @@ def take_ltx_part_frames(n_beats: int) -> int:
return max(1, int(n_beats)) * TAKE_BEAT_SECONDS * 24 + 1
+# ---- ONE SHOT — its own door (2026-09-08) -----------------------------------
+# One Shot is a workflow tab and a first-class API, not a mode of the video
+# form. `POST /oneshot` takes a small JSON (or form) document — prompt,
+# seconds, engine, quality, optional beats / camera / start frame / character —
+# and this mapper turns it into the make_job form the take runner already
+# understands, so the tab and the API render exactly what /queue/add would.
+# One prompt is a complete request: with no beats the prompt carries every five
+# seconds (make_job); everything else is a tweak.
+ONESHOT_HANDOFF_VALUES = ("last", "speech")
+
+
+def _onoff(v, default: str = "on") -> str:
+ s = str(v if v is not None else default).strip().lower()
+ if s in ("", "on", "1", "true", "yes"):
+ return "on" if s or default == "on" else default
+ if s in ("off", "0", "false", "no"):
+ return "off"
+ return default
+
+
+def oneshot_form(data: dict) -> tuple[dict, str | None]:
+ """A One Shot request → the make_job form (values as parse_qs lists).
+ Returns (form, None) or ({}, "what is wrong")."""
+ def g(k: str, d: str = "") -> str:
+ v = data.get(k)
+ if isinstance(v, list):
+ v = v[0] if v else ""
+ return str(v if v is not None else d).strip()
+ prompt = g("prompt")
+ if not prompt:
+ return {}, "prompt is required — describe the whole shot once"
+ raw_secs = g("seconds") or g("take_seconds") or "60"
+ try:
+ seconds = int(float(raw_secs))
+ except ValueError:
+ return {}, f"seconds must be a number, one of {list(TAKE_SECONDS)}"
+ if seconds not in TAKE_SECONDS:
+ return {}, f"seconds must be one of {list(TAKE_SECONDS)} (got {seconds})"
+ engine = (g("engine") or ENGINE_DEFAULT or "ltx").lower()
+ if engine not in ("ltx", "h3"):
+ return {}, "engine must be 'ltx' or 'h3'"
+ if engine == "h3" and not h3_available():
+ return {}, "Hailuo H3 is not installed on this Mac — pick engine 'ltx'"
+ beats_raw = data.get("beats")
+ if isinstance(beats_raw, list):
+ beats_str = json.dumps([str(b or "").strip() for b in beats_raw])
+ else:
+ beats_str = str(beats_raw or "").strip()
+ image = g("image")
+ if image and not Path(image).is_file():
+ return {}, f"start frame not found: {image} — upload it first (POST /upload) and pass the returned path"
+ handoff = (g("handoff") or "").lower()
+ if handoff in ("1", "true", "yes", "on"):
+ handoff = "speech"
+ if handoff and handoff not in ONESHOT_HANDOFF_VALUES:
+ return {}, "handoff must be 'last' or 'speech'"
+ character = g("character_id")
+ form: dict[str, str] = {
+ "engine": engine,
+ "mode": "i2v" if image else "t2v",
+ "prompt": prompt,
+ "take_seconds": str(seconds),
+ "beats": beats_str,
+ "take_camera": g("camera")[:240],
+ "take_light_lock": _onoff(g("light_lock", "on"), "on"),
+ "take_retake": _onoff(g("retake", "on"), "on"),
+ # A character speaks: hand off where the line ends unless told otherwise.
+ "take_handoff": handoff or ("speech" if character else "last"),
+ "seed": g("seed") or "-1",
+ "preset_label": g("label")[:120],
+ "enhance": "off",
+ "accel": "off",
+ "no_music": _onoff(g("no_music", "off"), "off"),
+ }
+ quality = g("quality").lower()
+ if engine == "h3":
+ form["h3_quality"] = quality or "standard"
+ form["h3_length"] = TAKE_H3_PART_LENGTH
+ form["h3_turbo"] = _onoff(g("turbo", "on"), "on")
+ form["h3_upscale"] = g("upscale") or "fit_720p"
+ elif character:
+ form["character_id"] = character
+ form["quality_choice"] = quality or "pro"
+ form["character_strength"] = g("character_strength") or "1.0"
+ form["character_voice_strength"] = g("voice_strength") or "1.0"
+ form["upscale"] = g("upscale") or "fit_720p"
+ form["upscale_method"] = g("upscale_method") or "pipersr"
+ else:
+ form["quality"] = quality or LTX_QUALITY_DEFAULT
+ form["upscale"] = g("upscale") or "off"
+ form["upscale_method"] = g("upscale_method") or "lanczos"
+ if image:
+ form["image"] = image
+ return {k: [v] for k, v in form.items()}, None
+
+
+def oneshot_plan_beats(prompt: str, seconds: int, engine: str = "ltx") -> dict:
+ """Write the beats for a prompt with the Storyboard's planner: the take
+ brief (`_sb_take_concept`) asks for one movement per five seconds, the
+ planner answers N shots, `collapse_take` folds them into one take's beats.
+ Blocks for the planner's 20-40 s; the caller runs it off the UI thread."""
+ prompt = str(prompt or "").strip()
+ try:
+ seconds = int(seconds)
+ except (TypeError, ValueError):
+ return {"ok": False, "error": "seconds must be a number"}
+ if not prompt:
+ return {"ok": False, "error": "prompt is required"}
+ if seconds not in TAKE_SECONDS:
+ return {"ok": False, "error": f"seconds must be one of {list(TAKE_SECONDS)}"}
+ n = max(1, seconds // TAKE_BEAT_SECONDS)
+ concept = _sb_take_concept(prompt, seconds)
+ eng = "h3" if (str(engine or "").lower() == "h3" and _sb_h3_available()) else "ltx"
+ try:
+ res = storyboard_planner.plan_film(
+ concept, n_shots=n, engine=eng,
+ known_character_ids=_sb_known_character_ids(), max_dim=_sb_max_dim())
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "error": f"the planner did not answer: {exc}"}
+ if not isinstance(res, dict) or res.get("error"):
+ err = (res or {}).get("error") if isinstance(res, dict) else res
+ if isinstance(err, dict):
+ err = err.get("message") or err.get("kind") or json.dumps(err)[:200]
+ return {"ok": False, "error": str(err or "the planner returned nothing")}
+ shots = storyboard.collapse_take(res.get("shots") or [], seconds)
+ beats = [str(b or "").strip() for b in ((shots[0].get("beats") if shots else []) or [])]
+ if not any(beats):
+ return {"ok": False, "error": "the planner wrote no beats"}
+ return {"ok": True, "beats": beats, "title": (shots[0].get("title") if shots else "") or "",
+ "seconds": seconds, "engine": eng}
+
+
+def _oneshot_take_view(job: dict | None) -> dict | None:
+ if not isinstance(job, dict):
+ return None
+ p = job.get("params") or {}
+ take = p.get("take") or {}
+ if not take:
+ return None
+ prog = job.get("take_progress") or {}
+ return {"id": job.get("id"), "status": job.get("status"),
+ "label": p.get("label") or p.get("preset_label") or "",
+ "engine": take.get("engine") or p.get("engine"),
+ "seconds": take.get("seconds"), "parts": len(take.get("parts") or []),
+ "part": prog.get("part"), "handoff": take.get("handoff"),
+ "lipsync": job.get("take_lipsync") or [],
+ "drift": [d.get("delta") for d in (job.get("take_drift") or []) if isinstance(d, dict)],
+ "output": job.get("output_path"), "error": job.get("error"),
+ "elapsed_sec": job.get("elapsed_sec")}
+
+
+def oneshot_status() -> dict:
+ """What the One Shot tab shows while a take runs: the take, its part, the
+ per-part verdicts and the take's own log lines."""
+ with QUEUE_COND:
+ cur = STATE.get("current")
+ queued = [j for j in STATE.get("queue", []) if (j.get("params") or {}).get("take")]
+ hist = [j for j in STATE.get("history", [])[:20] if (j.get("params") or {}).get("take")]
+ log = [l for l in STATE.get("log", []) if "[take]" in l][-16:]
+ return {"ok": True, "current": _oneshot_take_view(cur),
+ "queued": [_oneshot_take_view(j) for j in queued],
+ "recent": [_oneshot_take_view(j) for j in hist[:6]],
+ "paused": bool(STATE.get("paused")),
+ "log": log, "server_now": time.time()}
+
+
+def oneshot_options() -> dict:
+ """The choices the tab and the API can make on this Mac."""
+ chars = []
+ try:
+ for c in (list_characters() or []):
+ chars.append({"id": c.get("id"), "name": c.get("name") or c.get("id"),
+ "trigger": c.get("trigger") or c.get("id"),
+ "preview": c.get("preview_url") or c.get("thumb") or None,
+ "has_voice": bool(c.get("voice") or c.get("has_voice"))})
+ except Exception: # noqa: BLE001
+ chars = []
+ return {"ok": True, "seconds": list(TAKE_SECONDS), "beat_seconds": TAKE_BEAT_SECONDS,
+ "engines": {"ltx": {"available": True, "part_seconds": TAKE_LTX_PART_FRAMES // 24,
+ "qualities": [{"key": q, "label": (LTX_QUALITIES.get(q) or {}).get("label") or q.title(),
+ "eta_min": LTX_TIERS.get(f"{q}_10s", {}).get("eta_min")}
+ for q in ("quick", "balanced", "standard", "high")
+ if f"{q}_10s" in LTX_TIERS]},
+ "h3": {"available": bool(h3_available()), "part_seconds": 15,
+ "qualities": [{"key": q["key"], "label": q["label"],
+ "size": f"{q['width']}×{q['height']}"}
+ for q in _h3_qualities().values() if q.get("offered", True)]}},
+ "characters": chars, "handoff": list(ONESHOT_HANDOFF_VALUES),
+ # A trained face renders on the generation's graded recipe ("pro" —
+ # the default the owner graded); Draft is for checking the shot,
+ # High is the two-stage pipeline, which repaints a trained face and
+ # is offered with that warning in its own words.
+ "character_qualities": [
+ {"key": "draft", "label": "Draft", "sub": "a quick look · softer face"},
+ {"key": "pro", "label": "Pro", "sub": "the face holds · recommended"},
+ {"key": "high", "label": "High", "sub": "sharper picture · the face may change"},
+ {"key": "high_720p", "label": "High · 720p", "sub": "the same, exported at 720p"},
+ ],
+ "planner": bool(getattr(storyboard_planner, "DEFAULT_MODEL_PATH", None))}
+
+
def take_beats(raw, n: int) -> list[str]:
"""Exactly `n` beat prompts from what the form sent (a JSON list or a
newline-separated string). A blank beat holds the previous moment; extras
@@ -16068,6 +16317,43 @@ def take_handoff_points(path, back: float = TAKE_TALKING_BACK) -> tuple[float, f
return (round(cut, 3), round(end, 3))
+def sb_lipsync_retake_plan(shots: list, scores: dict, attempts: dict,
+ *, floor: float = TAKE_LIPSYNC_MIN,
+ limit: int = TAKE_LIPSYNC_RETAKES) -> list:
+ """Which board shots get a fresh-seed retake for lip-sync, and with what seed.
+
+ The One Shot runner has measured, gated and retaken every spoken part since
+ 2026-09-07; the Storyboard rendered a spoken shot once and kept whatever
+ came out. The owner's twelve-shot sitcom showed the gap: shots that scored
+ +0.33 next to shots at -0.06 (the panel's own scorer), and every one of
+ them shipped. Same rule here, per shot: a shot whose prompt carries a
+ spoken line, whose score is known and under the floor, and that still has
+ retakes left, is rendered again with a fresh seed; `_sb_lipsync_settle`
+ keeps the best-scoring take.
+
+ Pure: `shots` are board shot dicts, `scores` maps n -> score (None = no
+ face or no speech to judge, never retaken), `attempts` maps n -> retakes
+ already spent. Returns [(n, new_seed)].
+ """
+ out = []
+ for s in shots:
+ n = s.get("n")
+ sc = scores.get(n)
+ if sc is None or sc >= floor:
+ continue
+ if not storyboard._SPOKEN_WORDS_RE.search(str(s.get("prompt") or "")):
+ continue
+ used = int(attempts.get(n) or 0)
+ if used >= limit:
+ continue
+ try:
+ base = int(s.get("seed"))
+ except (TypeError, ValueError):
+ base = 0
+ out.append((n, base + 211 * (used + 1)))
+ return out
+
+
def take_expects_speech(params: dict, beats: list[str] | None = None) -> bool:
"""Whether a take part is expected to carry a spoken line — the only case the
lip-sync gate may judge. A character job speaks with its own voice; a plain
@@ -16285,6 +16571,113 @@ def _sb_sidecar_seed(path) -> int | None:
return None
+def _sb_lipsync_gate(board_id: str, batch: list, key: str, out_key: str, policy: dict,
+ h3_ok: bool, chain_ok: bool, wait) -> None:
+ """Score every spoken shot of a rendered bucket and retake the ones that miss.
+
+ The One Shot runner has done this per part since 2026-09-07; a board shot
+ was rendered once and kept. Each round: reload the board, score the
+ bucket's spoken shots with `take_lipsync_score` (None = nothing to judge),
+ ask `sb_lipsync_retake_plan` which ones go again, queue them with fresh
+ seeds through the same `shot_to_job` path, wait, and keep the best-scoring
+ take per shot (`shot["lipsync"]` records score, attempts and the file
+ kept; the losing take is hidden from the gallery). At most
+ TAKE_LIPSYNC_RETAKES rounds, and never for a shot with no spoken line.
+ """
+ ns = [s.get("n") for s in batch if isinstance(s, dict)]
+ board = storyboard.load_storyboard(STATE_DIR, board_id)
+ shots = {s.get("n"): s for s in (board.get("shots") or []) if isinstance(s, dict)}
+ best: dict = {} # n -> (score, path)
+ # The job id and seed that MADE the kept take travel with it. Without
+ # this the shot keeps pointing at the LAST retake's job, and the next
+ # _sb_reconcile() dutifully repoints the output at that job's file —
+ # the gate chose take 2 of 3 and the board delivered take 3 (2026-09-10,
+ # shot 9 of the sitcom: kept -0.09, delivered -0.27).
+ best_job: dict = {} # n -> job id of the kept take
+ best_seed: dict = {} # n -> seed of the kept take
+ for n in ns:
+ s = shots.get(n)
+ out = s.get(out_key) if s else None
+ if not s or not out or not Path(str(out)).is_file():
+ continue
+ if not storyboard._SPOKEN_WORDS_RE.search(str(s.get("prompt") or "")):
+ continue
+ sc = take_lipsync_score(out)
+ if sc is None:
+ continue
+ best[n] = (sc, str(out))
+ best_job[n] = s.get(key)
+ best_seed[n] = s.get("seed")
+ s["lipsync"] = {"score": round(sc, 3), "attempts": 0, "kept": str(out)}
+ push(f"[storyboard] shot {n}: lip-sync {sc:+.2f}"
+ + ("" if sc >= TAKE_LIPSYNC_MIN else f" — under {TAKE_LIPSYNC_MIN:.2f}, the voice is not on the mouth"))
+ storyboard.save_storyboard(STATE_DIR, board)
+ attempts: dict = {}
+ for _round in range(TAKE_LIPSYNC_RETAKES):
+ plan = sb_lipsync_retake_plan([shots[n] for n in best], {n: best[n][0] for n in best}, attempts)
+ if not plan:
+ break
+ ids = []
+ for n, seed in plan:
+ s = shots[n]
+ attempts[n] = attempts.get(n, 0) + 1
+ s["seed"] = seed
+ form = storyboard.shot_to_job(
+ s, policy, board_id=board_id, board_title=board.get("title") or "",
+ h3_available=h3_ok, engine_mode=board.get("engine_mode") or "auto",
+ h3_chain_prompts=chain_ok, h3_first_frame=bool(h3_ok and h3_supports_first_frame()),
+ locations=storyboard.board_locations(board),
+ wardrobe=storyboard.board_wardrobe(board), long_windows=bool(board.get("long_windows")),
+ style=str(board.get("style") or ""))
+ try:
+ jid = _sb_enqueue({k: ("" if v is None else str(v)) for k, v in form.items()})
+ except Exception as exc: # noqa: BLE001
+ push(f"[storyboard] shot {n}: lip-sync retake could not be queued: {exc}")
+ continue
+ s[key] = jid
+ s["status"] = "queued"
+ ids.append((n, jid))
+ push(f"[storyboard] shot {n}: retaking it for lip-sync with a fresh seed "
+ f"({attempts[n]} of {TAKE_LIPSYNC_RETAKES})")
+ storyboard.save_storyboard(STATE_DIR, board)
+ if not ids:
+ break
+ if not wait([j for _, j in ids]):
+ return
+ idx = _sb_job_index()
+ for n, jid in ids:
+ job = idx.get(jid) or {}
+ out = job.get("output_path") if job.get("status") == "done" else None
+ s = shots[n]
+ sc = take_lipsync_score(out) if out and Path(str(out)).is_file() else None
+ prev_sc, prev_out = best[n]
+ if sc is not None and sc > prev_sc:
+ push(f"[storyboard] shot {n}: the retake syncs better ({sc:+.2f} vs {prev_sc:+.2f}) — using it")
+ try:
+ set_hidden(prev_out, True)
+ except Exception: # noqa: BLE001
+ pass
+ best[n] = (sc, str(out))
+ best_job[n] = jid
+ best_seed[n] = s.get("seed")
+ else:
+ push(f"[storyboard] shot {n}: the retake did not sync better ({sc}) — keeping the earlier one")
+ if out:
+ try:
+ set_hidden(str(out), True)
+ except Exception: # noqa: BLE001
+ pass
+ s[out_key] = best[n][1]
+ if best_job.get(n):
+ s[key] = best_job[n]
+ if best_seed.get(n) is not None:
+ s["seed"] = best_seed[n]
+ s["status"] = "done"
+ s["error"] = None
+ s["lipsync"] = {"score": round(best[n][0], 3), "attempts": attempts.get(n, 0), "kept": best[n][1]}
+ storyboard.save_storyboard(STATE_DIR, board)
+
+
def _sb_reconcile(board: dict) -> bool:
"""Walk each shot's job id and fold the queue's truth back into the board.
@@ -17373,6 +17766,7 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:
h3_available=h3_ok,
engine_mode=board.get("engine_mode") or "auto",
h3_chain_prompts=chain_ok,
+ h3_first_frame=bool(h3_ok and h3_supports_first_frame()),
locations=storyboard.board_locations(board),
wardrobe=storyboard.board_wardrobe(board),
long_windows=bool(board.get("long_windows")),
@@ -17401,17 +17795,22 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:
f"{bucket[0].upper()} — {board.get('title')}")
# Wait for this bucket to go terminal before submitting the next.
- while ids:
- with _SB_LOCK:
- entry = _SB_RENDERS.get(board_id)
- if not entry or entry.get("stop"):
- return
- idx = _sb_job_index()
- live = [j for j in ids
- if (idx.get(j) or {}).get("status") in ("queued", "running")]
- if not live:
- break
- time.sleep(5.0)
+ def _wait(ids_):
+ while ids_:
+ with _SB_LOCK:
+ entry = _SB_RENDERS.get(board_id)
+ if not entry or entry.get("stop"):
+ return False
+ idx = _sb_job_index()
+ live = [j for j in ids_
+ if (idx.get(j) or {}).get("status") in ("queued", "running")]
+ if not live:
+ break
+ time.sleep(5.0)
+ return True
+
+ if not _wait(ids):
+ return
try:
board = storyboard.load_storyboard(STATE_DIR, board_id)
@@ -17419,6 +17818,15 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:
storyboard.save_storyboard(STATE_DIR, board)
except Exception:
pass
+
+ # LIP-SYNC GATE (2026-09-10). Every spoken shot of this bucket is
+ # scored the way a One Shot part is; the ones under the floor are
+ # rendered again with a fresh seed, up to TAKE_LIPSYNC_RETAKES
+ # times, and the best-scoring take is the one the board keeps.
+ try:
+ _sb_lipsync_gate(board_id, batch, key, out_key, policy, h3_ok, chain_ok, _wait)
+ except Exception as exc: # noqa: BLE001
+ push(f"[storyboard] lip-sync gate skipped: {type(exc).__name__}: {exc}")
except Exception as exc: # noqa: BLE001
push(f"[storyboard] render dispatch stopped: {exc}")
finally:
@@ -21957,6 +22365,21 @@ def _preflight_image_job(cfg, *, engine_override: str = "auto") -> None:
push(f"[preflight] skipped via PHOSPHENE_SKIP_PREFLIGHT (engine={engine_override})")
return
+ # HiDream has been hidden from the Studio since issue #15 (it needs a
+ # lab-repo clone no install ships), but its recipes stayed reachable —
+ # the gallery's ✦ Quality chip and a saved Settings default from before
+ # the hide both land here — and each attempt died deep in the engine
+ # with "HiDream venv python not found", counted as a failed render: 81
+ # times from 12 installs in the week to 2026-09-09. Say no at the door,
+ # as a refusal, with the engine that does the same job.
+ if str(engine_override or "").lower().startswith("hidream") and not _hidream_available():
+ raise RenderRefused(
+ "pack_missing",
+ "HiDream isn't installed on this Mac (it needs a separate lab "
+ "checkout that Phosphene does not ship). Use Reference Edit — "
+ "Quality in Image Studio for the same job; the ✦ Quality chip "
+ "now picks it on its own.")
+
need_gb = _preflight_estimate_ram_gb(cfg)
mem = get_memory()
total_gb = float(mem.get("total_gb") or 0.0)
@@ -27303,7 +27726,13 @@ def generate_character_sheet(character_id: str, *,
reproduces from one number).
"""
cid = _character_safe_id(character_id)
- engine_override = (engine_override or "hidream_inline").strip().lower()
+ # The sheet was written against HiDream Medium; on an install without
+ # the lab checkout (every shipped one) the reference-conditioned Qwen
+ # engine does the same job, and asking for HiDream would only fail
+ # after the preflight refusal above.
+ if not (engine_override or "").strip():
+ engine_override = "hidream_inline" if _hidream_available() else "qwen_edit_inline"
+ engine_override = engine_override.strip().lower()
if engine_override not in _CHARACTER_SHEET_ENGINES:
raise ValueError(
f"engine_override {engine_override!r} cannot build a character "
@@ -27671,6 +28100,7 @@ from panel import routes_files as _routes_files
from panel import routes_image as _routes_image
from panel import routes_loras as _routes_loras
from panel import routes_meta as _routes_meta
+from panel import routes_oneshot as _routes_oneshot
from panel import routes_models as _routes_models
from panel import routes_queue as _routes_queue
from panel import routes_storyboard as _routes_storyboard
@@ -27678,7 +28108,7 @@ from panel import routes_stats as _routes_stats
from panel import routes_train as _routes_train
for _routes_mod in (_routes_characters, _routes_files, _routes_image,
- _routes_loras, _routes_meta, _routes_models,
+ _routes_loras, _routes_meta, _routes_models, _routes_oneshot,
_routes_queue, _routes_stats, _routes_storyboard,
_routes_train):
_routes_mod.P = sys.modules[__name__]
@@ -29658,6 +30088,7 @@ class Handler(BaseHTTPRequestHandler):
h3_available=h3_ok,
engine_mode=board.get("engine_mode") or "auto",
h3_chain_prompts=chain_ok,
+ h3_first_frame=bool(h3_ok and h3_supports_first_frame()),
locations=storyboard.board_locations(board),
wardrobe=storyboard.board_wardrobe(board))
job_form = {k: ("" if v is None else str(v))
diff --git a/panel/routes_characters.py b/panel/routes_characters.py
index f9036ea..63cbe2f 100644
--- a/panel/routes_characters.py
+++ b/panel/routes_characters.py
@@ -223,8 +223,9 @@ def post_character_sheet_generate(h, path, qs, ctype) -> None:
try:
result = P.generate_character_sheet(
cid_raw,
- engine_override=(payload.get("engine_override")
- or "hidream_inline"),
+ # An absent engine lets generate_character_sheet pick the one
+ # this Mac has (HiDream only where its lab checkout exists).
+ engine_override=(payload.get("engine_override") or ""),
views=payload.get("views"),
wardrobe=str(payload.get("wardrobe") or ""),
seed=payload.get("seed", -1),
diff --git a/panel/routes_files.py b/panel/routes_files.py
index d6ceb5d..744c216 100644
--- a/panel/routes_files.py
+++ b/panel/routes_files.py
@@ -740,6 +740,8 @@ def get_webapp_file(h, parsed) -> None:
".mjs": "text/javascript; charset=utf-8",
".html": "text/html; charset=utf-8",
".svg": "image/svg+xml",
+ # The Docs pages (webapp/docs/*.md), rendered in the browser.
+ ".md": "text/markdown; charset=utf-8",
}.get(ext, "application/octet-stream")
# Production serves the bytes this process booted with (snapshot taken
# beside HTML at import) so a pull under a running panel can't pair new
diff --git a/panel/routes_oneshot.py b/panel/routes_oneshot.py
new file mode 100644
index 0000000..5dcf885
--- /dev/null
+++ b/panel/routes_oneshot.py
@@ -0,0 +1,123 @@
+"""One Shot — its own door (2026-09-08).
+
+A One Shot is one continuous shot of 30 s – 2 min that never cuts, rendered
+as parts that continue from each other's last frame (`run_take_job_inner`).
+It used to be a mode chip on the video form; it is a workflow tab now, and
+these routes are its API — the same document the tab posts:
+
+ POST /oneshot {prompt, seconds, engine, quality, beats, camera,
+ image, character_id, handoff, light_lock, retake,
+ seed, label, ...} → {ok, id, plan}
+ GET /oneshot/options what this Mac can do: engines, qualities, characters
+ GET /oneshot/estimate ?engine&quality&seconds → parts, minutes, eta
+ POST /oneshot/plan {prompt, seconds, engine} → {ok, beats} (20–40 s)
+ GET /oneshot/status the running take, its parts, verdicts and log
+
+`P.oneshot_form()` maps the document onto the make_job form, so the tab, the
+API and /queue/add render exactly the same job. `P` is assigned by
+mlx_ltx_panel at import-wiring time — see panel/__init__.py.
+"""
+from __future__ import annotations
+
+from urllib.parse import parse_qs
+
+from panel.routes import get, post
+
+P = None # the running mlx_ltx_panel module; assigned at wiring time
+
+MAX_ONESHOT_JSON = 256 * 1024
+
+
+def _read_document(h, ctype) -> dict | None:
+ """The request as one flat dict: a JSON object, or a form (each field's
+ first value). Answers the error itself and returns None when it did."""
+ if (ctype or "").startswith("application/json"):
+ try:
+ length = int(h.headers.get("Content-Length") or "0")
+ except ValueError:
+ h._json({"ok": False, "error": "invalid Content-Length"}, 400); return None
+ if length <= 0:
+ h._json({"ok": False, "error": "Content-Length required for JSON body"}, 411); return None
+ if length > MAX_ONESHOT_JSON:
+ h._json({"ok": False, "error": f"body too large (max {MAX_ONESHOT_JSON} bytes)"}, 413); return None
+ try:
+ doc = P.json.loads(h.rfile.read(length).decode() or "{}")
+ except (P.json.JSONDecodeError, UnicodeDecodeError):
+ h._json({"ok": False, "error": "invalid JSON body"}, 400); return None
+ if not isinstance(doc, dict):
+ h._json({"ok": False, "error": "the body must be a JSON object"}, 400); return None
+ return doc
+ rb = h._read_form_body()
+ if rb is None:
+ return None
+ _body, form = rb
+ return {k: (v[0] if isinstance(v, list) and v else v) for k, v in form.items()}
+
+
+@post("/oneshot")
+def post_oneshot(h, path, qs, ctype) -> None:
+ doc = _read_document(h, ctype)
+ if doc is None:
+ return
+ form, err = P.oneshot_form(doc)
+ if err:
+ h._json({"ok": False, "error": err}, 400); return
+ err = P._validate_character_quality(form)
+ if err:
+ h._json({"ok": False, "error": err}, 400); return
+ try:
+ job = P.make_job(form)
+ except P.CharacterRequestError as exc:
+ h._json({"ok": False, "error": str(exc)}, 400); return
+ take = (job.get("params") or {}).get("take") or {}
+ if not take:
+ # make_job refused the take (it logs why) — say so instead of queueing a clip
+ h._json({"ok": False, "error": "the request did not become a One Shot — check seconds and engine"}, 400); return
+ with P.QUEUE_COND:
+ P.STATE["queue"].append(job)
+ P.QUEUE_COND.notify_all()
+ P.persist_queue()
+ engine = "h3" if take.get("engine") == "h3" else "ltx"
+ quality = (form.get("h3_quality") or form.get("quality") or form.get("quality_choice") or [""])[0]
+ minutes = P.take_estimate_minutes(engine, quality, take.get("seconds"))
+ h._json({"ok": True, "id": job["id"],
+ "plan": {"seconds": take.get("seconds"), "parts": len(take.get("parts") or []),
+ "beats": take.get("beats"), "engine": engine, "handoff": take.get("handoff"),
+ "minutes": minutes, "eta": (P._fmt_eta(minutes) if minutes else None)}})
+
+
+@get("/oneshot/options")
+def get_oneshot_options(h, parsed) -> None:
+ h._json(P.oneshot_options())
+
+
+@get("/oneshot/estimate")
+def get_oneshot_estimate(h, parsed) -> None:
+ q = parse_qs(parsed.query)
+ engine = (q.get("engine", ["ltx"])[0] or "ltx").strip().lower()
+ quality = (q.get("quality", [""])[0] or "").strip().lower()
+ seconds = (q.get("seconds", ["0"])[0] or "0").strip()
+ plan = P.take_plan(seconds, engine)
+ if not plan:
+ h._json({"ok": False, "error": f"seconds must be one of {list(P.TAKE_SECONDS)}",
+ "choices": list(P.TAKE_SECONDS)}, 400); return
+ minutes = P.take_estimate_minutes(engine, quality, seconds)
+ h._json({"ok": True, "seconds": plan["seconds"], "beats": plan["beats"],
+ "parts": len(plan["parts"]), "beats_per_part": plan["beats_per_part"],
+ "part_seconds": (15 if plan["engine"] == "h3" else P.TAKE_LTX_PART_FRAMES // 24),
+ "engine": plan["engine"], "minutes": minutes,
+ "eta": (P._fmt_eta(minutes) if minutes else None)})
+
+
+@post("/oneshot/plan")
+def post_oneshot_plan(h, path, qs, ctype) -> None:
+ doc = _read_document(h, ctype)
+ if doc is None:
+ return
+ res = P.oneshot_plan_beats(doc.get("prompt"), doc.get("seconds") or 60, doc.get("engine") or "ltx")
+ h._json(res, 200 if res.get("ok") else 400)
+
+
+@get("/oneshot/status")
+def get_oneshot_status(h, parsed) -> None:
+ h._json(P.oneshot_status())
diff --git a/scripts/upscale_compare_pipersr.py b/scripts/upscale_compare_pipersr.py
index 98957ec..0f97227 100755
--- a/scripts/upscale_compare_pipersr.py
+++ b/scripts/upscale_compare_pipersr.py
@@ -64,9 +64,16 @@ def probe_video(path: Path) -> dict:
def target_for_mode(width: int, height: int, mode: str) -> tuple[int, int, str]:
+ """The export canvas for a mode, the same three the panel's `upscale` field
+ accepts (`off` never reaches here). `fit_1080p` was missing: the panel hands
+ `run_pipersr_tracked` whatever `upscale` the job carried, and docs/API.md
+ lists fit_1080p as a value, so a Sharp export at 1080p died here with
+ "Unsupported upscale mode" after the whole render (2026-09-09)."""
mode = (mode or "fit_720p").strip().lower()
if mode == "x2":
return width * 2, height * 2, "up2x"
+ if mode in ("fit_1080p", "1080p"):
+ return (1920, 1080, "1080p") if width >= height else (1080, 1920, "v1080p")
if mode not in ("fit_720p", "720p"):
raise SystemExit(f"Unsupported upscale mode for PiperSR compare: {mode}")
if width >= height:
@@ -248,7 +255,7 @@ def main() -> int:
ap.add_argument("--pix-fmt", default="yuv420p")
ap.add_argument("--preset", default="medium")
ap.add_argument("--keep-work", action="store_true")
- ap.add_argument("--mode", default="fit_720p", choices=("fit_720p", "x2"))
+ ap.add_argument("--mode", default="fit_720p", choices=("fit_720p", "fit_1080p", "x2"))
ap.add_argument("--pipersr-only", action="store_true")
ap.add_argument("--output", type=Path, default=None)
args = ap.parse_args()
diff --git a/storyboard.py b/storyboard.py
index 5753970..5c6e888 100644
--- a/storyboard.py
+++ b/storyboard.py
@@ -1282,6 +1282,27 @@ def board_wardrobe(board: dict) -> dict[str, str]:
return out
+_H3_FIELD_BOUNDARY_RE = re.compile(
+ r"\n\s*(?:overall_soundscape|non_diegetic_music)\s*:", re.IGNORECASE)
+
+
+def split_h3_fields(prompt: str) -> tuple[str, str]:
+ """`(description, the rest)` of an H3 three-field prompt; `(prompt, "")` otherwise.
+
+ The rest starts at the first `overall_soundscape:` / `non_diegetic_music:`
+ line and keeps its own leading newlines, so `head + tail` is the prompt
+ byte for byte. A prose prompt (LTX, or an H3 shot written as one
+ paragraph) has no tail and composes exactly as before.
+ """
+ p = prompt or ""
+ if not p.lstrip().lower().startswith("integrated_multimodal_description:"):
+ return p, ""
+ m = _H3_FIELD_BOUNDARY_RE.search(p)
+ if not m:
+ return p, ""
+ return p[:m.start()].rstrip(), p[m.start():]
+
+
def compose_shot_prompt(shot: dict, locations: dict[str, dict] | None = None,
wardrobe: dict[str, str] | None = None) -> str:
"""The prompt that is actually rendered: subject, action, FRAME, PLACE.
@@ -1298,7 +1319,15 @@ def compose_shot_prompt(shot: dict, locations: dict[str, dict] | None = None,
uses it without rewriting anybody's text.
"""
trigger = (shot.get("trigger") or shot.get("character_id") or "").strip()
- parts = [ensure_trigger(shot.get("prompt") or "", trigger)]
+ # H3's three-field prompt. The additions below describe the PICTURE, so
+ # they belong in `integrated_multimodal_description` and nowhere after it:
+ # appended to the whole prompt they landed on the LAST field, and a located
+ # 12-shot sitcom rendered with "..., medium shot, a sitcom apartment" on
+ # the end of `non_diegetic_music: N/A` — the room in the score (measured
+ # 2026-09-08). Split the description off, compose into it, put the sound
+ # and the music back untouched.
+ head, tail = split_h3_fields(ensure_trigger(shot.get("prompt") or "", trigger))
+ parts = [head]
# WARDROBE goes right after the person, where a costume note belongs, and
# only if the shot has not already said it — a board that spells the outfit
@@ -1321,6 +1350,15 @@ def compose_shot_prompt(shot: dict, locations: dict[str, dict] | None = None,
if scene:
parts.append(scene)
+ if tail:
+ # The description's closing full stop moves to the end of the composed
+ # sentence, so the sound field still follows a finished sentence.
+ if len(parts) > 1 and parts[0].endswith("."):
+ parts[0] = parts[0][:-1]
+ body = ", ".join(p for p in parts if p)
+ if len(parts) > 1 and not body.endswith("."):
+ body += "."
+ return body + tail
return ", ".join(p for p in parts if p)
@@ -1469,6 +1507,7 @@ def shot_to_job(shot: dict, policy_pass: dict, *,
h3_available: bool = True,
engine_mode: str = DEFAULT_ENGINE_MODE,
h3_chain_prompts: bool = False,
+ h3_first_frame: bool = False,
long_windows: bool = False,
style: str = "",
locations: dict[str, dict] | None = None,
@@ -1611,8 +1650,14 @@ def shot_to_job(shot: dict, policy_pass: dict, *,
job["frames"] = take_secs * 24 + 1
# ANCHOR STILL. When the shot has a still, the video STARTS from it: the
# ordinary i2v path with the still as the image, anchored (the strict
- # pin, not Inspire). LTX only — H3's i2v is a different contract.
- if shot.get("still") and engine != "h3" and job["mode"] == "t2v":
+ # pin, not Inspire). On H3 the same still is the runner's `--first-frame`
+ # (FL2VA conditioning), which the caller confirms the installed runner has
+ # (`h3_first_frame`) — the panel probes the script for the flag. This is
+ # how a face stays the same face across a board's H3 shots: the still is
+ # made from the character's own frames (2026-09-10, the sitcom's jungle
+ # shots lost the lead's face on every text-only render and kept it on
+ # every render that started from a still).
+ if shot.get("still") and job["mode"] == "t2v" and (engine != "h3" or h3_first_frame):
job["mode"] = "i2v"
job["image"] = str(shot["still"])
job["i2v_reference_mode"] = "anchor"
diff --git a/test_anchor_stills.py b/test_anchor_stills.py
index 41d8c83..6cb0f74 100644
--- a/test_anchor_stills.py
+++ b/test_anchor_stills.py
@@ -38,6 +38,17 @@ def test_shot_with_still_becomes_anchored_i2v():
assert j["i2v_reference_mode"] == "anchor"
+def test_h3_shot_with_still_starts_from_it_when_the_runner_has_first_frame():
+ shot = {"n": 6, "mode": "text", "prompt": "x", "still": "/tmp/s.png", "duration_s": 5}
+ policy = {"quality": "quick", "width": 640, "height": 384}
+ j = sb.shot_to_job(shot, policy, h3_available=True, engine_mode="h3", h3_first_frame=True)
+ assert j["engine"] == "h3" and j["mode"] == "i2v" and j["image"] == "/tmp/s.png"
+ # A runner without --first-frame cannot honour the still: the shot stays text-only
+ # rather than fail on an unknown flag.
+ j2 = sb.shot_to_job(shot, policy, h3_available=True, engine_mode="h3", h3_first_frame=False)
+ assert j2["engine"] == "h3" and j2["mode"] == "t2v" and "image" not in j2
+
+
def test_shot_without_still_stays_t2v():
j = sb.shot_to_job({"n": 1, "mode": "text", "prompt": "x", "duration_s": 4},
{"quality": "balanced"}, h3_available=False)
diff --git a/test_character_sheet.py b/test_character_sheet.py
index 09ff4aa..88ee9fc 100644
--- a/test_character_sheet.py
+++ b/test_character_sheet.py
@@ -485,8 +485,10 @@ class TestSheetGenerateRoute(unittest.TestCase):
def test_empty_body_uses_the_documented_defaults(self):
reply, calls = self._post("/characters/bizarrotrn/sheet/generate")
self.assertEqual(reply["status"], 200, reply)
+ # An empty engine is the contract now: generate_character_sheet
+ # picks HiDream only where its lab checkout exists, else Qwen.
self.assertEqual(calls, [{"cid": "bizarrotrn",
- "engine_override": "hidream_inline",
+ "engine_override": "",
"views": None, "wardrobe": "", "seed": -1}])
self.assertTrue(reply["payload"]["ok"])
diff --git a/test_docs_and_shortcuts.py b/test_docs_and_shortcuts.py
new file mode 100644
index 0000000..baac318
--- /dev/null
+++ b/test_docs_and_shortcuts.py
@@ -0,0 +1,324 @@
+#!/usr/bin/env python3
+"""The keyboard table and the Docs: one source, and nothing may drift from it.
+
+webapp/js/shortcuts.js is the ONE list of shortcuts. The Docs page renders it,
+the Editor's Keys popover renders it, the tooltips read it. These receipts pin
+the four ways that could still go wrong:
+
+ * a shortcut in the table that the Docs page does not show;
+ * a Docs link — in the nav, in a page, in the panel's code — that lands
+ nowhere;
+ * a shortcut that claims a chord the browser or macOS keeps (⌘R was the
+ Editor's Render key: a reload queued a render);
+ * the Editor's real keydown handler and the table disagreeing — driven for
+ real in node with every Editor row's keys, in both directions.
+
+Plus the one new key that can spend a render: ⌘⏎ goes through the Generate
+button's own submit path and does nothing the button would refuse.
+"""
+from __future__ import annotations
+
+import json
+import re
+import shutil
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+WEB = ROOT / "webapp"
+DOCS = WEB / "docs"
+NODE = shutil.which("node")
+
+
+def _node(script: str) -> dict:
+ with tempfile.TemporaryDirectory() as d:
+ f = Path(d) / "harness.mjs"
+ 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.strip().splitlines()[-1])
+
+
+def _url(p: Path) -> str:
+ return p.resolve().as_uri()
+
+
+def _load() -> dict:
+ return _node(f"""
+import {{ installShim }} from '{_url(ROOT / "scripts" / "webapp_import_shim.mjs")}';
+import fs from 'node:fs';
+installShim();
+await import('{_url(WEB / "js" / "shortcuts.js")}');
+await import('{_url(WEB / "js" / "docs.js")}');
+const out = {{ shortcuts: [], reserved: SHORTCUT_RESERVED.map(shortcutNormalise), norm: {{}},
+ sections: DOCS_SECTIONS, rendered: {{}} }};
+for (const s of SHORTCUTS) {{
+ out.shortcuts.push({{ id: s.id, scope: s.scope, combos: s.combos || [], hidden: s.hidden || [],
+ calls: s.calls || null, run: !!s.run, typing: !!s.typing }});
+ for (const c of [...(s.combos || []), ...(s.hidden || [])]) out.norm[c] = shortcutNormalise(c);
+}}
+for (const sec of DOCS_SECTIONS) {{
+ const md = fs.readFileSync('{DOCS.as_posix()}/' + sec.file, 'utf8');
+ const r = docsRender(md, sec.id);
+ out.rendered[sec.id] = {{ html: r.html, anchors: r.headings.map(h => h.anchor) }};
+}}
+console.log(JSON.stringify(out));
+""")
+
+
[email protected](NODE, "node not on PATH")
+class TheDocsShowTheTable(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.r = _load()
+ cls.ids = [s["id"] for s in cls.r["shortcuts"]]
+
+ def test_every_shortcut_appears_on_the_shortcuts_page(self):
+ page = self.r["rendered"]["shortcuts"]["html"]
+ for sid in self.ids:
+ self.assertIn(f'data-shortcut="{sid}"', page, sid)
+
+ def test_ids_are_unique(self):
+ self.assertEqual(len(self.ids), len(set(self.ids)))
+
+ def test_every_nav_section_has_a_page_with_a_title(self):
+ for sec in self.r["sections"]:
+ self.assertTrue((DOCS / sec["file"]).is_file(), sec["file"])
+ self.assertTrue(self.r["rendered"][sec["id"]]["html"].startswith(f'<h1 id="docs-{sec["id"]}">'),
+ sec["id"])
+ # every page on disk is in the nav — an orphan page is unreachable
+ on_disk = sorted(p.name for p in DOCS.glob("*.md"))
+ self.assertEqual(on_disk, sorted(s["file"] for s in self.r["sections"]))
+
+ def test_every_docs_link_lands_on_a_heading(self):
+ sections = {s["id"]: set(self.r["rendered"][s["id"]]["anchors"]) for s in self.r["sections"]}
+ sources = [*DOCS.glob("*.md"), WEB / "index.html", *(WEB / "js").glob("*.js")]
+ found = 0
+ for f in sources:
+ for m in re.finditer(r"#docs/([\w-]+)(?:/([\w-]+))?", f.read_text(encoding="utf-8")):
+ sec, anchor = m.group(1), m.group(2)
+ if sec == "' + sec.id + '" or "+" in m.group(0):
+ continue
+ found += 1
+ self.assertIn(sec, sections, f"{f.name}: {m.group(0)}")
+ if anchor:
+ self.assertIn(anchor, sections[sec], f"{f.name}: {m.group(0)}")
+ self.assertGreater(found, 10)
+ # openDocs('<section>', '<anchor>') calls in the panel's code, too
+ for f in [WEB / "index.html", *(WEB / "js").glob("*.js")]:
+ for m in re.finditer(r"openDocs\('([\w-]+)'(?:,\s*'([\w-]+)')?\)", f.read_text(encoding="utf-8")):
+ self.assertIn(m.group(1), sections, m.group(0))
+ if m.group(2):
+ self.assertIn(m.group(2), sections[m.group(1)], m.group(0))
+
+ def test_every_key_named_in_a_page_exists(self):
+ for sec, r in self.r["rendered"].items():
+ self.assertNotIn("docs-missing", r["html"], sec)
+
+ def test_every_tooltip_names_a_real_shortcut(self):
+ text = (WEB / "index.html").read_text(encoding="utf-8")
+ for m in re.finditer(r'data-shortcut="([\w.-]+)"', text):
+ self.assertIn(m.group(1), self.ids, m.group(0))
+ for f in (WEB / "js").glob("*.js"):
+ 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_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",
+ "mod+tab", "mod+backquote", "mod+space"):
+ self.assertIn(c, reserved, c)
+ for s in self.r["shortcuts"]:
+ for c in s["combos"] + s["hidden"]:
+ self.assertNotIn(self.r["norm"][c], reserved, f"{s['id']} uses {c}")
+
+ def test_only_the_explicit_keys_fire_while_typing(self):
+ typing = sorted(s["id"] for s in self.r["shortcuts"] if s["typing"])
+ self.assertEqual(typing, ["prompt.generate"])
+
+
+# ---- the Editor's real handler, driven with the table's keys --------------------
+_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"}
+
+# State each row needs for its branch to be the one that answers.
+_STATE = {
+ "editor.removeOverlay": {"sel": None, "ovSel": "o1"},
+ "editor.removeTransition": {"txSel": "t1"},
+}
+# Called on the way to an action, or to read state — not actions of their own.
+_HELPERS = {"sbeFps", "sbeFilmDuration", "sbePopAnyOpen", "sbeStop"}
+# Esc closes an open menu or the Versions panel first — documented on the
+# Esc rows, not rows of their own.
+_ESC_COMPANIONS = {"sbePopCloseAll", "sbeVersionsClose"}
+
+
+def _editor_listener(src: str) -> str:
+ mark = "if (!SBE.open || document.body.dataset.workflow !== 'editor') return;"
+ i = src.index(mark)
+ j = src.rindex("document.addEventListener('keydown', (ev) => {", 0, i)
+ body = src[j + len("document.addEventListener('keydown', (ev) => {"):]
+ return body[:body.index("\n});")]
+
+
+def _event(combo: str) -> dict:
+ parts = combo.lower().split("+")
+ key = parts[-1]
+ mods = set(parts[:-1])
+ k = _KEY.get(key, key)
+ if len(k) == 1 and k.isalpha() and "shift" in mods:
+ k = k.upper()
+ return {"key": k, "code": "", "metaKey": "mod" in mods, "ctrlKey": False,
+ "shiftKey": "shift" in mods, "altKey": "alt" in mods}
+
+
[email protected](NODE, "node not on PATH")
+class TheEditorHandlerAgreesWithTheTable(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.src = (WEB / "js" / "editor.js").read_text(encoding="utf-8")
+ cls.body = _editor_listener(cls.src)
+ cls.rows = [s for s in _load()["shortcuts"] if s["scope"] == "editor"]
+ names = sorted(set(re.findall(r"\b(sbe\w+)\(", cls.body)))
+ cases = []
+ for s in cls.rows:
+ for c in s["combos"] + s["hidden"]:
+ cases.append({"id": s["id"], "combo": c, "ev": _event(c), "state": _STATE.get(s["id"], {})})
+ stubs = "\n".join(
+ f"function {n}(...a) {{ calls.push('{n}'); "
+ + ("return 24; }" if n == "sbeFps" else "return 10; }" if n == "sbeFilmDuration"
+ else "return false; }" if n == "sbePopAnyOpen" else "}")
+ for n in names)
+ script = f"""
+let calls = [];
+let SBE;
+const document = {{
+ body: {{ dataset: {{ workflow: 'editor' }} }},
+ querySelector: () => null,
+ getElementById: () => ({{ hidden: true }}),
+}};
+{stubs}
+const listener = (ev) => {{
+{cls.body}
+}};
+const cases = {json.dumps(cases)};
+const out = [];
+for (const c of cases) {{
+ SBE = Object.assign({{ open: true, sel: 'c1', ovSel: null, txSel: null, playhead: 1, muted: false }}, c.state);
+ calls = [];
+ const ev = Object.assign({{ target: {{ tagName: 'DIV', id: '' }}, prevented: false,
+ preventDefault() {{ this.prevented = true; }} }}, c.ev);
+ listener(ev);
+ out.push({{ id: c.id, combo: c.combo, calls, prevented: ev.prevented }});
+}}
+console.log(JSON.stringify({{ out, names: {json.dumps(names)} }}));
+"""
+ cls.result = _node(script)
+
+ def test_every_editor_row_runs_the_function_it_names(self):
+ want = {s["id"]: ([s["calls"]] if isinstance(s["calls"], str) else s["calls"]) for s in self.rows}
+ for r in self.result["out"]:
+ expected = set(want[r["id"]] or [])
+ self.assertTrue(expected, f"{r['id']} has no `calls`")
+ actions = [c for c in r["calls"] if c not in _HELPERS]
+ self.assertTrue(expected & set(actions),
+ f"{r['id']} {r['combo']}: handler called {r['calls']}, table says {sorted(expected)}")
+ self.assertTrue(set(actions) <= expected | _ESC_COMPANIONS,
+ f"{r['id']} {r['combo']}: also called {actions}")
+ self.assertTrue(r["prevented"], f"{r['id']} {r['combo']} left the browser default on")
+
+ def test_every_action_the_handler_takes_is_in_the_table(self):
+ named = set()
+ for s in self.rows:
+ named |= {s["calls"]} if isinstance(s["calls"], str) else set(s["calls"] or [])
+ for n in self.result["names"]:
+ if n in _HELPERS or n in _ESC_COMPANIONS:
+ continue
+ self.assertIn(n, named, f"the Editor answers a key with {n}() and the shortcut table does not list it")
+
+ def test_render_is_not_on_the_reload_chord(self):
+ self.assertNotIn("(ev.key === 'r' || ev.key === 'R') && (ev.metaKey || ev.ctrlKey)", self.body)
+
+
[email protected](NODE, "node not on PATH")
+class CommandReturnIsTheGenerateButton(unittest.TestCase):
+ """⌘⏎ can spend a render, so it must be exactly the button: the same
+ submit listener, and nothing the button would refuse."""
+
+ def _run(self, target_id: str, disabled: bool) -> dict:
+ return _node(f"""
+import {{ installShim, el }} from '{_url(ROOT / "scripts" / "webapp_import_shim.mjs")}';
+installShim();
+globalThis.phosToast = (m) => (globalThis._toasts ||= []).push(m);
+const btn = el('genBtn', {{ disabled: {str(disabled).lower()}, title: 'Needs Q8' }});
+const form = el('genForm');
+form.requestSubmit = (b) => {{ form.submitted = (form.submitted || 0) + 1; form.submitter = b && b.id; }};
+const ibtn = el('imgStudioGenBtn', {{ disabled: {str(disabled).lower()} }});
+globalThis.imgStudioGenerate = () => {{ globalThis._img = (globalThis._img || 0) + 1; }};
+await import('{_url(WEB / "js" / "shortcuts.js")}');
+const row = SHORTCUTS.find(s => s.id === 'prompt.generate');
+const ev = {{ key: 'Enter', metaKey: true, ctrlKey: false, shiftKey: false, altKey: false,
+ target: {{ id: '{target_id}', tagName: 'TEXTAREA' }} }};
+const matched = row.combos.some(c => shortcutMatches(ev, c));
+const res = row.run(ev);
+console.log(JSON.stringify({{ matched, res: res === false ? 'declined' : 'handled',
+ submitted: form.submitted || 0, submitter: form.submitter || '', img: globalThis._img || 0,
+ toasts: globalThis._toasts || [] }}));
+""")
+
+ def test_video_prompt_submits_through_the_generate_button(self):
+ r = self._run("prompt", False)
+ self.assertTrue(r["matched"])
+ self.assertEqual((r["submitted"], r["submitter"]), (1, "genBtn"))
+ self.assertIn("requestSubmit(btn)", (WEB / "js" / "shortcuts.js").read_text(encoding="utf-8"))
+ self.assertIn("document.getElementById('genForm').addEventListener('submit'",
+ (WEB / "js" / "queue.js").read_text(encoding="utf-8"))
+
+ def test_a_disabled_generate_is_not_bypassed(self):
+ r = self._run("prompt", True)
+ self.assertEqual(r["submitted"], 0)
+ self.assertEqual(r["toasts"], ["Needs Q8"])
+ self.assertEqual(self._run("imgStudioPrompt", True)["img"], 0)
+
+ def test_images_prompt_generates_and_other_boxes_are_left_alone(self):
+ self.assertEqual(self._run("imgStudioPrompt", False)["img"], 1)
+ r = self._run("osPrompt", False) # One Shot has its own listener
+ self.assertEqual((r["res"], r["submitted"], r["img"]), ("declined", 0, 0))
+
+
[email protected](NODE, "node not on PATH")
+class TheMatcher(unittest.TestCase):
+
+ def test_chords_match_the_way_a_mac_keyboard_sends_them(self):
+ r = _node(f"""
+import {{ installShim }} from '{_url(ROOT / "scripts" / "webapp_import_shim.mjs")}';
+installShim();
+await import('{_url(WEB / "js" / "shortcuts.js")}');
+const e = (o) => Object.assign({{ key: '', code: '', metaKey: false, ctrlKey: false, shiftKey: false, altKey: false }}, o);
+console.log(JSON.stringify({{
+ question: shortcutMatches(e({{ key: '?', shiftKey: true }}), '?'),
+ shiftDigit: shortcutMatches(e({{ key: '#', code: 'Digit3', shiftKey: true }}), 'shift+digit3'),
+ bareDigit: shortcutMatches(e({{ key: '3', code: 'Digit3' }}), 'shift+digit3'),
+ cmdS: shortcutMatches(e({{ key: 's', metaKey: true }}), 'mod+s'),
+ ctrlS: shortcutMatches(e({{ key: 's', ctrlKey: true }}), 'mod+s'),
+ plainSisNotCmdS: shortcutMatches(e({{ key: 's' }}), 'mod+s'),
+ redo: shortcutMatches(e({{ key: 'Z', metaKey: true, shiftKey: true }}), 'shift+mod+z'),
+ undoIsNotRedo: shortcutMatches(e({{ key: 'z', metaKey: true }}), 'shift+mod+z'),
+ hint: shortcutHint('editor.redo'),
+ split: shortcutHint('editor.split'),
+}}));
+""")
+ self.assertEqual(r, {"question": True, "shiftDigit": True, "bareDigit": False, "cmdS": True,
+ "ctrlS": True, "plainSisNotCmdS": False, "redo": True,
+ "undoIsNotRedo": False, "hint": "⇧⌘Z", "split": "S or ⌘K or ⌘B"})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_geometry_grid.py b/test_geometry_grid.py
index 1f31d88..fd75b00 100644
--- a/test_geometry_grid.py
+++ b/test_geometry_grid.py
@@ -74,7 +74,7 @@ class ControlsHideWithTheirParents(unittest.TestCase):
and Studio."""
SURFACES = ("train", "audio", "storyboard", "editor", "characters",
- "studio")
+ "studio", "oneshot")
@classmethod
def setUpClass(cls):
diff --git a/test_oneshot_api.py b/test_oneshot_api.py
new file mode 100644
index 0000000..7c96ada
--- /dev/null
+++ b/test_oneshot_api.py
@@ -0,0 +1,103 @@
+"""One Shot is its own door: the request document, the routes, the planner seam."""
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+from pathlib import Path
+
+os.environ.setdefault("LTX_STATE_DIR", str(Path(tempfile.mkdtemp(prefix="phos-oneshot-"))))
+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"
+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"
+
+import mlx_ltx_panel as p # noqa: E402
+
+
+def _one(form: dict, k: str) -> str:
+ v = form.get(k)
+ return v[0] if isinstance(v, list) else v
+
+
+def test_routes_are_registered_once():
+ from panel import routes_oneshot # noqa: F401
+ from panel.routes import GET_ROUTES, POST_ROUTES
+ for r in ("/oneshot/options", "/oneshot/estimate", "/oneshot/status"):
+ assert r in GET_ROUTES, r
+ for r in ("/oneshot", "/oneshot/plan"):
+ assert r in POST_ROUTES, r
+
+
+def test_a_prompt_alone_is_a_complete_request():
+ form, err = p.oneshot_form({"prompt": "A tram rolls through a rainy night street."})
+ assert err is None
+ assert _one(form, "take_seconds") == "60" and _one(form, "engine") == "ltx" and _one(form, "mode") == "t2v"
+ assert _one(form, "beats") == "" and _one(form, "take_handoff") == "last"
+ assert _one(form, "quality") == p.LTX_QUALITY_DEFAULT
+ j = p.make_job(form)["params"]
+ assert j["take"]["seconds"] == 60 and len(j["take"]["parts"]) == 6
+ assert all(b.startswith("A tram rolls") for b in j["take"]["beat_prompts"]) # the prompt carries every beat
+
+
+def test_beats_list_camera_and_switches_map_onto_the_take():
+ form, err = p.oneshot_form({"prompt": "x", "seconds": 30, "beats": ["a", "", "c"], "camera": "a slow push in",
+ "light_lock": "off", "retake": False, "handoff": "speech", "seed": 7, "label": "L"})
+ assert err is None
+ assert json.loads(_one(form, "beats")) == ["a", "", "c"]
+ assert _one(form, "take_camera") == "a slow push in" and _one(form, "take_light_lock") == "off"
+ assert _one(form, "take_retake") == "off" and _one(form, "take_handoff") == "speech"
+ assert _one(form, "seed") == "7" and _one(form, "preset_label") == "L"
+ j = p.make_job(form)["params"]
+ assert j["take"]["handoff"] == "speech" and j["take"]["camera"] == "a slow push in"
+ assert j["take"]["beat_prompts"][0].startswith("a") and j["take"]["beat_prompts"][1] == ""
+
+
+def test_a_character_defaults_to_pro_and_a_speech_handoff():
+ form, err = p.oneshot_form({"prompt": "x", "character_id": "someone"})
+ assert err is None
+ assert _one(form, "character_id") == "someone" and _one(form, "quality_choice") == "pro"
+ assert _one(form, "take_handoff") == "speech" and _one(form, "upscale") == "fit_720p"
+ assert _one(form, "upscale_method") == "pipersr"
+
+
+def test_the_refusals_name_the_field():
+ assert "prompt" in p.oneshot_form({})[1]
+ assert "seconds" in p.oneshot_form({"prompt": "x", "seconds": 75})[1]
+ assert "engine" in p.oneshot_form({"prompt": "x", "engine": "wan"})[1]
+ assert "handoff" in p.oneshot_form({"prompt": "x", "handoff": "sideways"})[1]
+ assert "start frame" in p.oneshot_form({"prompt": "x", "image": "/nowhere/at/all.png"})[1]
+
+
+def test_h3_gets_its_own_axes(monkeypatch):
+ monkeypatch.setattr(p, "h3_available", lambda: True)
+ form, err = p.oneshot_form({"prompt": "x", "engine": "h3", "quality": "high", "turbo": "off"})
+ assert err is None
+ assert _one(form, "h3_quality") == "high" and _one(form, "h3_length") == p.TAKE_H3_PART_LENGTH
+ assert _one(form, "h3_turbo") == "off" and _one(form, "h3_upscale") == "fit_720p"
+ monkeypatch.setattr(p, "h3_available", lambda: False)
+ assert "not installed" in p.oneshot_form({"prompt": "x", "engine": "h3"})[1]
+
+
+def test_options_describe_this_mac():
+ o = p.oneshot_options()
+ assert o["ok"] and o["seconds"] == list(p.TAKE_SECONDS) and o["beat_seconds"] == 5
+ assert o["engines"]["ltx"]["part_seconds"] == 10 and o["engines"]["h3"]["part_seconds"] == 15
+ assert [q["key"] for q in o["engines"]["ltx"]["qualities"]][:2] == ["quick", "balanced"]
+ assert isinstance(o["characters"], list) and o["handoff"] == ["last", "speech"]
+
+
+def test_plan_beats_folds_the_planner_answer_into_beats(monkeypatch):
+ def fake_plan(concept, n_shots, **kw):
+ assert "ONE SHOT" in concept and n_shots == 6
+ return {"shots": [{"n": i + 1, "prompt": f"beat {i + 1}", "mode": "text"} for i in range(6)]}
+ monkeypatch.setattr(p.storyboard_planner, "plan_film", fake_plan)
+ res = p.oneshot_plan_beats("a hen skates", 30, "ltx")
+ assert res["ok"] and res["beats"] == [f"beat {i}" for i in range(1, 7)]
+ monkeypatch.setattr(p.storyboard_planner, "plan_film", lambda *a, **k: {"error": {"kind": "timeout", "message": "took too long"}})
+ res = p.oneshot_plan_beats("a hen skates", 30, "ltx")
+ assert not res["ok"] and "took too long" in res["error"]
+ assert not p.oneshot_plan_beats("", 30)["ok"] and not p.oneshot_plan_beats("x", 75)["ok"]
+
+
+def test_status_reports_only_takes():
+ s = p.oneshot_status()
+ assert s["ok"] and "current" in s and isinstance(s["log"], list)
diff --git a/test_remake_quality_engine.py b/test_remake_quality_engine.py
new file mode 100644
index 0000000..7e1bb86
--- /dev/null
+++ b/test_remake_quality_engine.py
@@ -0,0 +1,114 @@
+"""The ✦ Quality chip and the image preflight never send a render to an engine
+this Mac does not have.
+
+HiDream has been hidden from Image Studio since issue #15 (it needs a lab
+checkout no install ships), but the gallery's ✦ Quality chip still swapped the
+engine to hidream_quality_inline and auto-submitted, and each attempt died
+inside the engine with "HiDream venv python not found" — 81 failed renders
+from 12 installs in the week to 2026-09-09. Three things pin the fix: the chip's
+engine choice (run in node, the real function), the preflight refusing HiDream
+at the door as a refusal rather than an error, and the character sheet's
+default engine following the same rule.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT / "scripts"))
+from extract_panel_js import extract_function # noqa: E402
+
+NODE = shutil.which("node")
+
+
+def _run_node(script: str) -> dict:
+ if NODE is None:
+ raise unittest.SkipTest("node not on PATH")
+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:
+ fh.write(script)
+ path = fh.name
+ try:
+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)
+ if r.returncode != 0:
+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-2000:], r.stderr[-2000:]))
+ return json.loads(r.stdout.strip().splitlines()[-1])
+ finally:
+ Path(path).unlink(missing_ok=True)
+
+
+class TheChipPicksAnEngineThisMacHas(unittest.TestCase):
+ def test_hidream_only_when_installed_and_cached(self):
+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")
+ fn = extract_function("remakeQualityEngine", src)
+ got = _run_node(fn + """
+const out = {
+ nothing: remakeQualityEngine({}),
+ undefined_map: remakeQualityEngine(undefined),
+ hidream_absent: remakeQualityEngine({hidream_quality_inline: {family_installed: false, cached: false}}),
+ hidream_listed_not_cached: remakeQualityEngine({hidream_quality_inline: {family_installed: true, cached: false}}),
+ hidream_ready: remakeQualityEngine({hidream_quality_inline: {family_installed: true, cached: true}}),
+};
+console.log(JSON.stringify(out));
+""")
+ self.assertEqual(got["nothing"], "qwen_edit_high_inline")
+ self.assertEqual(got["undefined_map"], "qwen_edit_high_inline")
+ self.assertEqual(got["hidream_absent"], "qwen_edit_high_inline")
+ self.assertEqual(got["hidream_listed_not_cached"], "qwen_edit_high_inline")
+ self.assertEqual(got["hidream_ready"], "hidream_quality_inline")
+
+ def test_the_chip_no_longer_hardcodes_hidream(self):
+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")
+ body = extract_function("remakeInQuality", src)
+ self.assertNotIn("engineEl.value = 'hidream_quality_inline'", body)
+ self.assertIn("remakeQualityEngine(", body)
+
+
+class ThePreflightRefusesHiDreamAtTheDoor(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ tmp = tempfile.mkdtemp(prefix="phos_remake_")
+ os.environ["LTX_STATE_DIR"] = tmp
+ os.environ["LTX_OUTPUT_DIR"] = os.path.join(tmp, "out")
+ os.environ["LTX_UPLOADS_DIR"] = os.path.join(tmp, "up")
+ os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"
+ os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"
+ os.makedirs(os.environ["LTX_OUTPUT_DIR"], exist_ok=True)
+ os.makedirs(os.environ["LTX_UPLOADS_DIR"], exist_ok=True)
+ sys.path.insert(0, str(ROOT))
+ import mlx_ltx_panel as p
+ cls.p = p
+
+ def test_hidream_without_the_checkout_is_a_refusal_not_an_error(self):
+ p = self.p
+ with mock.patch.object(p, "_hidream_available", return_value=False):
+ with self.assertRaises(p.RenderRefused) as cm:
+ p._preflight_image_job(object(), engine_override="hidream_quality_inline")
+ self.assertIn("Reference Edit", str(cm.exception))
+
+ def test_other_engines_get_past_that_gate(self):
+ p = self.p
+ # The gate is the first check; with HiDream absent a Qwen request
+ # must reach the RAM estimate (which raises on a dummy cfg).
+ with mock.patch.object(p, "_hidream_available", return_value=False), \
+ mock.patch.object(p, "_preflight_estimate_ram_gb", side_effect=KeyError("reached")):
+ with self.assertRaises(KeyError):
+ p._preflight_image_job(object(), engine_override="qwen_edit_high_inline")
+
+ def test_the_character_sheet_defaults_to_a_shipped_engine(self):
+ p = self.p
+ with mock.patch.object(p, "_hidream_available", return_value=False), \
+ mock.patch.object(p, "_character_safe_id", side_effect=LookupError("stop here")):
+ with self.assertRaises(LookupError):
+ p.generate_character_sheet("nobody")
+ src = (ROOT / "panel" / "routes_characters.py").read_text(encoding="utf-8")
+ self.assertNotIn('or "hidream_inline"', src)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_settings_merge.py b/test_settings_merge.py
new file mode 100644
index 0000000..f3b17ed
--- /dev/null
+++ b/test_settings_merge.py
@@ -0,0 +1,65 @@
+"""A settings write may only change the keys it is setting (2026-09-08).
+
+Two panels shared one state dir on the dev box. A panel that had been running
+since Sep 5 wrote its own bookkeeping (analytics_last_version and friends) by
+dumping its whole in-memory dict, and the PostHog query key another panel had
+saved into the file in the meantime was gone. Every writer now merges its
+delta onto the file as it is on disk, and a reader re-loads the file when
+another process changed it."""
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+import time
+import unittest
+from pathlib import Path
+
+os.environ["LTX_STATE_DIR"] = str(Path(tempfile.mkdtemp(prefix="phos-settings-")))
+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"
+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"
+
+import mlx_ltx_panel as P # noqa: E402
+
+
+def _other_process_writes(**kv) -> None:
+ """Edit the file the way a second panel (or the owner) would."""
+ data = json.loads(P.SETTINGS_FILE.read_text())
+ data.update(kv)
+ time.sleep(0.01) # a distinct mtime on coarse filesystems
+ P.SETTINGS_FILE.write_text(json.dumps(data, indent=1))
+
+
+class AWriteKeepsWhatOthersSaved(unittest.TestCase):
+ def test_internal_bookkeeping_does_not_blank_a_key_saved_elsewhere(self):
+ P.get_settings() # this process has its copy
+ _other_process_writes(analytics_query_key="phx_secret_from_the_other_panel")
+ P._settings_set_internal(analytics_last_version="9.9.9")
+ on_disk = json.loads(P.SETTINGS_FILE.read_text())
+ self.assertEqual(on_disk["analytics_query_key"], "phx_secret_from_the_other_panel")
+ self.assertEqual(on_disk["analytics_last_version"], "9.9.9")
+
+ def test_a_form_save_does_not_blank_a_key_saved_elsewhere(self):
+ P.get_settings()
+ _other_process_writes(hf_token="hf_from_the_other_panel")
+ cur, err = P.update_settings({"output_preset": "web"})
+ self.assertIsNone(err)
+ on_disk = json.loads(P.SETTINGS_FILE.read_text())
+ self.assertEqual(on_disk["hf_token"], "hf_from_the_other_panel")
+ self.assertEqual(on_disk["output_preset"], "web")
+ self.assertEqual(cur["hf_token"], "hf_from_the_other_panel")
+
+ def test_a_reader_sees_what_another_process_wrote(self):
+ P.get_settings()
+ _other_process_writes(civitai_api_key="civ_from_the_other_panel")
+ self.assertEqual(P.get_settings()["civitai_api_key"], "civ_from_the_other_panel")
+
+ def test_an_explicit_clear_still_clears(self):
+ P.update_settings({"hf_token": "abc"})
+ cur, err = P.update_settings({"hf_token": ""})
+ self.assertIsNone(err)
+ self.assertEqual(json.loads(P.SETTINGS_FILE.read_text())["hf_token"], "")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_sharp_export_modes.py b/test_sharp_export_modes.py
new file mode 100644
index 0000000..c2df55d
--- /dev/null
+++ b/test_sharp_export_modes.py
@@ -0,0 +1,45 @@
+"""The Sharp (PiperSR) export script answers every `upscale` value the panel can
+hand it.
+
+`run_pipersr_tracked` passes the job's own `upscale` field as `--mode`, and the
+API accepts `fit_720p`, `fit_1080p` and `x2`. The script knew two of the three:
+a Sharp export at 1080p died with "Unsupported upscale mode" after the whole
+render had finished (2026-09-09). This pins all three, both orientations.
+"""
+import importlib.util
+import unittest
+from pathlib import Path
+
+SCRIPT = Path(__file__).resolve().parent / "scripts" / "upscale_compare_pipersr.py"
+
+
+def _load():
+ spec = importlib.util.spec_from_file_location("upscale_compare_pipersr", SCRIPT)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+class SharpExportModes(unittest.TestCase):
+ def setUp(self):
+ self.m = _load()
+
+ def test_every_panel_upscale_value_has_a_canvas(self):
+ t = self.m.target_for_mode
+ self.assertEqual(t(1024, 576, "fit_720p"), (1280, 720, "720p"))
+ self.assertEqual(t(576, 1024, "fit_720p"), (720, 1280, "v720p"))
+ self.assertEqual(t(1536, 864, "fit_1080p"), (1920, 1080, "1080p"))
+ self.assertEqual(t(864, 1536, "fit_1080p"), (1080, 1920, "v1080p"))
+ self.assertEqual(t(640, 384, "x2"), (1280, 768, "up2x"))
+
+ def test_an_unknown_mode_still_refuses(self):
+ with self.assertRaises(SystemExit):
+ self.m.target_for_mode(1024, 576, "fit_4k")
+
+ def test_the_cli_offers_the_same_three(self):
+ src = SCRIPT.read_text(encoding="utf-8")
+ self.assertIn('choices=("fit_720p", "fit_1080p", "x2")', src)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_storyboard.py b/test_storyboard.py
index 1a98fd3..4a6c44c 100644
--- a/test_storyboard.py
+++ b/test_storyboard.py
@@ -662,6 +662,45 @@ class Wardrobe(unittest.TestCase):
self.assertIn("Hawaiian", job["prompt"])
+class H3ThreeFieldsCompose(unittest.TestCase):
+ """The room, the frame and the eyeline land INSIDE the H3 description.
+
+ An H3 shot's prompt is the three-field form. Appending the composed parts
+ to the whole prompt put them after `non_diegetic_music: N/A` — a located
+ sitcom shot rendered with the apartment in its score (2026-09-08).
+ """
+ H3 = ("integrated_multimodal_description: [Shot 1] Live-action, a man says: "
+ "<d>[English] Hi.</d> His mouth settles closed. No text appears at any point."
+ "\n\noverall_soundscape: Room tone.\n\nnon_diegetic_music: N/A")
+ LOCS = {"apt": {"id": "apt", "description": "a sitcom apartment"}}
+
+ def test_the_additions_go_into_the_description(self):
+ got = sb.compose_shot_prompt(
+ {"n": 1, "prompt": self.H3, "location_id": "apt", "framing": "medium shot",
+ "eyeline": "right", "pronoun": "he", "engine": "h3"}, self.LOCS)
+ head, tail = got.split("\n\noverall_soundscape:")
+ self.assertIn("medium shot", head)
+ self.assertIn("a sitcom apartment", head)
+ self.assertIn("his eyes fixed past the right edge of frame", head)
+ self.assertTrue(head.endswith("."), head[-40:])
+ self.assertEqual(tail, " Room tone.\n\nnon_diegetic_music: N/A")
+ self.assertNotIn("apartment", tail)
+
+ def test_nothing_to_add_leaves_the_prompt_byte_identical(self):
+ self.assertEqual(sb.compose_shot_prompt({"n": 1, "prompt": self.H3}, {}), self.H3)
+
+ def test_a_prose_prompt_composes_exactly_as_before(self):
+ got = sb.compose_shot_prompt(
+ {"n": 1, "prompt": "a man waves.", "location_id": "apt",
+ "framing": "medium shot"}, self.LOCS)
+ self.assertEqual(got, "a man waves., medium shot, a sitcom apartment")
+
+ def test_split_h3_fields_round_trips(self):
+ head, tail = sb.split_h3_fields(self.H3)
+ self.assertEqual(head + tail, self.H3)
+ self.assertEqual(sb.split_h3_fields("plain prose"), ("plain prose", ""))
+
+
class SpeechLawAtBoardLevel(unittest.TestCase):
"""No mouth moves without words, whoever wrote the shot.
diff --git a/test_storyboard_editor_ui.py b/test_storyboard_editor_ui.py
index 884f434..55701d0 100644
--- a/test_storyboard_editor_ui.py
+++ b/test_storyboard_editor_ui.py
@@ -50,6 +50,25 @@ def panel_html_render() -> str:
.replace("__SEQS__", _p.SEQ_NOUN_PL)
.replace("__SEQ__", _p.SEQ_NOUN))
+def _editor_keydown(src: str) -> str:
+ """The EDITOR's own keydown listener, not the first one in the bundle.
+
+ There is more than one `document.addEventListener('keydown'` in the
+ webapp — the engine menu has its own — so anchoring on the call would
+ read the wrong body and pass or fail for the wrong reason.
+ """
+ mark = "if (!SBE.open || document.body.dataset.workflow !== 'editor') return;"
+ i = src.index(mark)
+ j = src.index("document.addEventListener('keydown'", 0)
+ while True:
+ k = src.find("document.addEventListener('keydown'", j + 1)
+ if k < 0 or k > i:
+ break
+ j = k
+ body = src[j:]
+ return body[:body.index("\n});")]
+
+
NODE = shutil.which("node")
# The model functions are pure — arrays in, arrays out. The four that are not
@@ -141,6 +160,12 @@ FUNCTIONS = (
"sbeAudioDrift", "sbeAudioInSync", "sbeAudioIsThePicture",
"sbeDriftLabel", "sbeSyncBadge",
"sbeSyncMark", "sbeSyncCarry", "sbeResyncAudio",
+ # MOVING SEVERAL CLIPS AT ONCE. Closed-form, and that is the whole point:
+ # the legal range of a group delta is the intersection of "no gap goes
+ # negative" over every boundary between a moving clip and a still one, so
+ # "the selection keeps its spacing" and "it stops at its neighbour" are
+ # arithmetic rather than something to check by dragging and squinting.
+ "sbeGroupLimits", "sbeMoveGroup",
# The save that cannot be dropped, and the failure that cannot be missed.
"sbeSaveInner", "sbeSaveAlarm", "sbeSaveAlarmClear", "sbeQueueSave",
# The crash lane itself, so save → backup → recovery can be DRIVEN rather
@@ -2169,6 +2194,76 @@ out.overlayLayer = (() => {
return { during: during, after: after };
})();
+// ---- MOVING SEVERAL CLIPS AT ONCE ---------------------------------------
+// Four shots, packed, with a deliberate 1s hole between b and c. Every case
+// below is a thing a person would otherwise have to check by dragging.
+const GRP = () => lay([
+ clip({ id: 'a', end: 2, film_start: 0, film_end: 2 }),
+ clip({ id: 'b', end: 2, film_start: 2, film_end: 4 }),
+ clip({ id: 'c', end: 2, film_start: 5, film_end: 7 }),
+ clip({ id: 'd', end: 2, film_start: 7, film_end: 9 })]);
+const at = cs => cs.map(c => [c.id, c.film_start]);
+out.grpPacked = (() => {
+ // a..d is everything, so there is no boundary to stop it going later and
+ // the film's own head stops it coming earlier.
+ const l = sbeGroupLimits(GRP(), ['a', 'b', 'c', 'd']);
+ return [l.lo, l.hi === Infinity];
+})();
+out.grpBoundedBothSides = (() => {
+ // b and c are hemmed in by a (ends at 2) and d: b may not go earlier at
+ // all, and the pair may go later only by the hole in front of d, which is
+ // zero here because c is hard against it.
+ const l = sbeGroupLimits(GRP(), ['b', 'c']);
+ return [l.lo, l.hi];
+})();
+out.grpRoomIsTheGap = (() => {
+ // c and d can slide earlier by exactly the 1s hole in front of c, and
+ // later without limit — nothing follows d.
+ const l = sbeGroupLimits(GRP(), ['c', 'd']);
+ return [l.lo, l.hi === Infinity];
+})();
+out.grpKeepsItsSpacing = (() => {
+ const cs = GRP();
+ const before = at(cs);
+ const r = sbeMoveGroup(cs, ['c', 'd'], 3);
+ const after = at(r.clips);
+ // c and d moved by the same amount, a and b did not move at all, and the
+ // hole INSIDE the selection is exactly as long as it was.
+ return [r.ok, before, after,
+ sbeById(r.clips, 'd').film_start - sbeById(r.clips, 'c').film_start,
+ before[3][1] - before[2][1]];
+})();
+out.grpClampsAtTheNeighbour = (() => {
+ const r = sbeMoveGroup(GRP(), ['c', 'd'], -99);
+ // -99 is impossible; the answer is the 1s hole and not a negative gap.
+ return [r.ok, r.moved, at(r.clips)];
+})();
+out.grpRefusesALockedMember = (() => {
+ const cs = GRP();
+ sbeById(cs, 'c').locked = true;
+ const r = sbeMoveGroup(cs, ['c', 'd'], 1);
+ return [r.ok, r.why, JSON.stringify(at(r.clips)) === JSON.stringify(at(GRP()))];
+})();
+out.grpCarriesTheSound = (() => {
+ // A BLOCK SLIDE IS NOT A J-CUT. Dragging ONE picture deliberately leaves
+ // its strip behind — that is how a J-cut is made — but sliding a selection
+ // means "put these shots a second later", and a strip left behind would be
+ // a sync error nobody asked for. The offset inside the selection survives.
+ let cs = sbeSetAudioLink(GRP(), 'c', false).clips;
+ cs = sbeAudioEdit(cs, 'c', 'move', sbeClipAudio(sbeById(cs, 'c')).film_start + 0.5).clips;
+ const drift0 = sbeAudioDrift(sbeById(cs, 'c'));
+ const r = sbeMoveGroup(cs, ['c', 'd'], 1.5);
+ const c = sbeById(r.clips, 'c');
+ return [r.ok, +drift0.toFixed(4), +sbeAudioDrift(c).toFixed(4),
+ +(c.audio.film_start - 0.5 - 1.5).toFixed(4), +c.film_start.toFixed(4)];
+})();
+out.grpOneClipIsJustAMove = (() => {
+ // The nudge keys go through the same function, so it has to answer for a
+ // selection of one.
+ const r = sbeMoveGroup(GRP(), ['c'], -0.5);
+ return [r.ok, at(r.clips)];
+})();
+
process.stdout.write(JSON.stringify(out));
"""
@@ -2211,6 +2306,53 @@ class TimelineClient(unittest.TestCase):
self.assertIsNone(self.r["peaksNone"])
# ---- the beat grid ---------------------------------------------------
+ # ---- moving several clips at once ------------------------------------
+ def test_the_group_delta_is_clamped_by_every_boundary_it_crosses(self):
+ # a 0-2, b 2-4, [1s hole], c 5-7, d 7-9.
+ lo, unbounded = self.r["grpPacked"]
+ self.assertEqual(lo, 0) # the film's own head
+ self.assertTrue(unbounded) # nothing follows the last clip
+ self.assertEqual(self.r["grpBoundedBothSides"], [0, 0])
+ lo2, unbounded2 = self.r["grpRoomIsTheGap"]
+ self.assertEqual(lo2, -1) # exactly the hole in front of c
+ self.assertTrue(unbounded2)
+
+ def test_the_selection_keeps_its_spacing_and_nothing_else_moves(self):
+ ok, before, after, span, wasSpan = self.r["grpKeepsItsSpacing"]
+ self.assertTrue(ok)
+ self.assertEqual(before[:2], after[:2]) # a and b stay put
+ self.assertEqual([r[1] for r in after[2:]], [8, 10])
+ self.assertEqual(span, wasSpan) # the hole inside it
+ self.assertEqual(after[2][1] - before[2][1], after[3][1] - before[3][1])
+
+ def test_an_impossible_delta_lands_on_the_neighbour_not_through_it(self):
+ ok, moved, pos = self.r["grpClampsAtTheNeighbour"]
+ self.assertTrue(ok)
+ self.assertEqual(moved, -1)
+ self.assertEqual([r[1] for r in pos], [0, 2, 4, 6])
+
+ def test_one_locked_member_refuses_the_whole_slide_and_changes_nothing(self):
+ ok, why, untouched = self.r["grpRefusesALockedMember"]
+ self.assertFalse(ok)
+ self.assertEqual(why, "locked")
+ self.assertTrue(untouched)
+
+ def test_a_block_slide_carries_the_sound_and_keeps_the_j_cut(self):
+ # Dragging ONE picture deliberately leaves its strip behind — that is
+ # how a J-cut is made. Sliding a SELECTION is not that gesture, and a
+ # strip left behind would be a sync error nobody asked for.
+ ok, drift0, drift1, stripDelta, filmStart = self.r["grpCarriesTheSound"]
+ self.assertTrue(ok)
+ self.assertEqual(drift0, drift1) # the offset inside it survives
+ self.assertEqual(stripDelta, 5) # the strip moved by the same 1.5
+ self.assertEqual(filmStart, 6.5)
+
+ def test_a_selection_of_one_goes_through_the_same_function(self):
+ # The nudge keys use it for any count, so it has to answer for one.
+ ok, pos = self.r["grpOneClipIsJustAMove"]
+ self.assertTrue(ok)
+ self.assertEqual([r[1] for r in pos], [0, 2, 4.5, 7])
+
def test_the_grid_carries_beats_and_marks_downbeats(self):
self.assertEqual(self.r["grid"][:3],
[[0, True], [0.5, False], [1, False]])
@@ -3008,10 +3150,19 @@ class SplitEditsInTheBrowser(unittest.TestCase):
inner.index('id="%s"' % b))
def test_the_toggle_is_offered_on_a_video_clip_and_only_there(self):
- fn = extract_function("sbePaintInspector", self.src)
- self.assertIn("sbeToggleAudioLink()", fn)
+ # IT LIVES ON THE CLIP BAR NOW, not in the inspector — it is the verb
+ # the owner named first ("for instance, unlink and link audio") and it
+ # was in a 212px column in the corner. What is gated is unchanged: the
+ # verb exists, it is reachable, and only a video clip is offered it.
+ self.assertIn('id="sbeCbLink"', self.src)
+ self.assertIn('onclick="sbeToggleAudioLink()"', self.src)
+ fn = extract_function("sbeCbarModel", self.src)
+ self.assertIn("sbeCbLink", fn)
self.assertIn("kind === 'video'", fn)
self.assertIn("Unlink sound", fn)
+ # ...and a clip with no sound of its own is told WHY, rather than
+ # having the button quietly dropped.
+ self.assertIn("Only a video clip has sound of its own", fn)
def test_the_height_floor_is_the_sum_of_its_lanes(self):
# sbeFitMonitors budgets the monitors against this constant, so a lane
@@ -3259,10 +3410,17 @@ class TheStripIsAnEditingSurface(unittest.TestCase):
def test_the_verb_is_offered_only_once_the_halves_are_separate(self):
# On a linked clip "delete the sound" and "mute" would be the same
# button twice.
- fn = extract_function("sbePaintInspector", self.src)
- self.assertIn("sbeDeleteStripSel()", fn)
- i = fn.index("sbeDeleteStripSel()")
- self.assertIn("sbeClipAudio(c).split", fn[max(0, i - 400):i])
+ self.assertIn('onclick="sbeDeleteStripSel()"', self.src)
+ fn = extract_function("sbeCbarModel", self.src)
+ # `split` is the gate, and it is derived from the clip's own window.
+ self.assertIn("const split = !!(vid && w && w.split)", fn)
+ i = fn.index("sbeCbDelSound")
+ row = fn[i:i + 900]
+ self.assertIn("!split ?", row)
+ # ...and the refusal SAYS the reason, which the inspector could not:
+ # it dropped the button, so "delete sound" read as a missing feature
+ # on every linked clip, which is almost every clip.
+ self.assertIn("same button twice", row)
def test_the_overlay_lane_teaches_itself(self):
# An empty lane is a sentence, not a blank — the convention the track
@@ -3911,12 +4069,14 @@ class MutingAClipsOwnSound(unittest.TestCase):
# ...and it is NOT the same state as a file with no audio track.
self.assertIn(".sbe-aclip.is-mute", self.src)
- def test_the_inspector_offers_it_on_any_video_clip_with_sound(self):
- fn = extract_function("sbePaintInspector", self.src)
- self.assertIn("sbeToggleClipMute()", fn)
+ def test_the_clip_bar_offers_it_on_any_video_clip_with_sound(self):
+ self.assertIn('id="sbeCbMute"', self.src)
+ self.assertIn('onclick="sbeToggleClipMute()"', self.src)
+ fn = extract_function("sbeCbarModel", self.src)
self.assertIn("Mute sound", fn)
self.assertIn("Unmute sound", fn)
self.assertIn("c.has_audio !== false", fn)
+ self.assertIn("no sound of its own to", fn)
def test_the_PREVIEW_is_the_third_output_and_agrees(self):
# The render drops the clip's lane and the export disables its audio
@@ -4441,13 +4601,20 @@ class TheSoundStaysWhereItWasPut(unittest.TestCase):
# ...and it happens BEFORE the drag is armed, or pointerdown wins.
self.assertLess(body.index("sbe-sync"), body.index("setPointerCapture"))
- def test_the_inspector_offers_the_rematch_next_to_the_relink(self):
- fn = extract_function("sbePaintInspector", self.src)
- self.assertIn("sbeResyncSel()", fn)
+ def test_the_clip_bar_puts_the_rematch_next_to_the_relink(self):
+ self.assertIn('id="sbeCbResync"', self.src)
+ self.assertIn('onclick="sbeResyncSel()"', self.src)
+ fn = extract_function("sbeCbarModel", self.src)
self.assertIn("Resync sound", fn)
self.assertIn("sbeAudioInSync(c)", fn)
- # The two verbs are different and the inspector says which is which.
+ # THE TWO ARE ADJACENT AND SAY WHICH IS WHICH. The thing that is hard
+ # to hold in your head is the difference between them — one makes the
+ # pair permanent, the other only slides the sound back under its own
+ # frame — so they sit side by side and both tooltips name it.
self.assertLess(fn.index("Re-link sound"), fn.index("Resync sound"))
+ self.assertLess(self.src.index('id="sbeCbLink"'),
+ self.src.index('id="sbeCbResync"'))
+ self.assertIn("Resync is the", fn)
def test_a_locked_shot_says_so_instead_of_a_forbidden_cursor(self):
# `.sbe-clip.is-locked` sets `cursor: not-allowed` and hides both
@@ -4457,7 +4624,7 @@ class TheSoundStaysWhereItWasPut(unittest.TestCase):
self.assertIn(".sbe-clip.is-locked { cursor: not-allowed; }", self.src)
body = extract_function("sbeOnTrackDown", self.src)
self.assertIn("c.locked", body)
- self.assertIn("click Unlock in the", body)
+ self.assertIn("press Unlock on the bar", body)
# ...and the refusal happens BEFORE the drag is armed.
self.assertLess(body.index("c.locked"), body.index("setPointerCapture"))
lane = extract_function("sbeOnAudioDown", self.src)
@@ -4623,10 +4790,17 @@ class TheSoundStaysWhereItWasPut(unittest.TestCase):
self.assertIn("SBE.drag = null;", extract_function("sbeOnAudioDown", self.src))
def test_the_toggle_names_the_offset_it_is_about_to_freeze(self):
- fn = extract_function("sbePaintInspector", self.src)
+ fn = extract_function("sbeCbarModel", self.src)
self.assertIn("'Link sound'", fn)
self.assertIn("Re-link sound", fn)
self.assertIn("sbeAudioInSync(c)", fn)
+ # THE OFFSET MOVED FROM THE LABEL TO THE TOOLTIP, and it had to: a
+ # label that grows by "at +0.40s" changes the button's width, and the
+ # clip bar measures its own width to decide what overflows — so the
+ # row would re-fit itself every time a strip was dragged. The number
+ # is still said before it is frozen.
+ i = fn.index("sbeCbLink")
+ self.assertIn("sbeDriftLabel(drift)", fn[i:i + 1600])
def test_every_reflow_marks_the_sound_before_it_moves_the_picture(self):
# The carry is the fix, and a new operation that calls sbeLayout without
@@ -5296,12 +5470,19 @@ class TheLevelLineTeachesItself(unittest.TestCase):
self.assertIn("w.len + 1e-6", fn)
insp = extract_function("sbePaintInspector", self.src)
self.assertIn("sbeAddPointAtPlayhead()", insp)
- self.assertIn("sbeClearPoints()", insp)
+ # CLEARING THEM IS ON THE CLIP BAR — the owner asked for "some kind of
+ # delete button for the anchors of the audio", and the inspector's
+ # version only appeared once there was something to clear, which is a
+ # button nobody could know existed.
+ self.assertIn('id="sbeCbPoints"', self.src)
+ self.assertIn('onclick="sbeClearPoints()"', self.src)
+ self.assertIn("level anchors", extract_function("sbeCbarModel", self.src))
# A linked strip says what to do instead of offering a refusing button.
self.assertIn("unlink the sound to shape its", insp)
def test_the_legend_lists_the_gestures_that_actually_exist(self):
- legend = self.r["legend"]
+ # The rows live in the shortcut table the legend draws.
+ legend = (ROOT / "webapp" / "js" / "shortcuts.js").read_text(encoding="utf-8")
for phrase in ("click the yellow line", "drag it to set",
"right-click it to remove", "top edge"):
self.assertIn(phrase, legend)
@@ -5594,13 +5775,14 @@ class TheCalmChrome(unittest.TestCase):
self.assertIn("document.addEventListener('click', sbePopGlobal, true);",
self.src)
- def test_escape_closes_the_menu_before_the_document(self):
- # Esc has always closed the document here; a menu is one layer above
- # it, and closing the whole cut out from under an open menu is the
- # surprise this ordering exists to prevent.
+ def test_escape_closes_the_menu_and_never_the_document(self):
+ # A menu is the thing on top, so Escape closes it first. And Escape
+ # no longer closes the document at all: the Escape that closed the
+ # Docs (or cleared a selection) used to shut the film behind it.
i = self.src.index("if (sbePopAnyOpen()) { sbePopCloseAll(''); return; }")
- j = self.src.index("sbeClose();", i)
- self.assertLess(i, j)
+ branch = self.src[i:self.src.index("RENDER HAS A KEY", i)]
+ self.assertNotIn("sbeClose();", branch)
+ self.assertIn("return;", branch)
def test_the_soundtracks_row_became_its_lane_header(self):
# It was a full-width strip at the top of the column, four inches from
@@ -5645,6 +5827,370 @@ class TheCalmChrome(unittest.TestCase):
self.assertIn("' of ' + n", fn)
+class TheClipBar(unittest.TestCase):
+ """The verbs an editor uses all day, above the tracks, always on screen.
+
+ "It's really hard when you are using the editor of Phosphene to use the
+ basic tools you actually need to use all the time, for instance, unlink
+ and link audio... We have some, but they are hidden inside that menu, the
+ toggle menu on the right. That is not a good use."
+
+ Every one of them already existed, in the inspector, in a 212px column, in
+ the corner of the screen, drawn identically to a brightness slider — and
+ four of them appeared and disappeared with the clip's state, which is how
+ "Delete sound" managed to be invisible on almost every clip. What is gated
+ here is the SPLIT: the verbs are on the bar, the properties are in the
+ inspector, and neither drifts back into the other.
+ """
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ 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"')]
+
+ # ---- the ten verbs ---------------------------------------------------
+ VERBS = (
+ ("sbeCbSplit", "sbeSplitHere()", "Split"),
+ ("sbeCbLift", "sbeLiftSelected()", "Lift"),
+ ("sbeCbRipple", "sbeRippleSelected()", "Ripple delete"),
+ ("sbeCbDup", "sbeDuplicateSel()", "Duplicate"),
+ ("sbeCbLink", "sbeToggleAudioLink()", "Unlink sound"),
+ ("sbeCbResync", "sbeResyncSel()", "Resync sound"),
+ ("sbeCbMute", "sbeToggleClipMute()", "Mute sound"),
+ ("sbeCbDelSound", "sbeDeleteStripSel()", "Delete sound"),
+ ("sbeCbPoints", "sbeClearPoints()", "Clear points"),
+ ("sbeCbLock", "sbeToggleLock()", "Lock"),
+ )
+
+ def test_every_verb_is_in_the_real_markup_with_a_handler(self):
+ for cid, act, label in self.VERBS:
+ el = extract_element(cid, self.src)
+ self.assertIn('onclick="%s"' % act, el, cid)
+ # the label, read off the row itself (extract_element hands back
+ # the opening tag, and the label is the element's own content)
+ row = self.bar[self.bar.index('id="%s"' % cid):]
+ self.assertIn("<b>%s</b>" % label, row[:400], cid)
+ # ...and the handler is on the GLOBAL scope. editor.js is a module,
+ # so an inline onclick that resolves to a module-private name is a
+ # button that silently does nothing at event time — the v4.9.0
+ # regression, and exactly what lint_webapp.mjs is for.
+ self.assertIn(act.rstrip("()"), self.src)
+
+ def test_the_order_is_the_order_a_cutter_works_in(self):
+ # Cut, then remove, then the sound, then the pin. The sound group is
+ # second because it is the one he named: "I find myself all the time
+ # un-syncing and syncing."
+ pos = [self.bar.index('id="%s"' % cid) for cid, _, _ in self.VERBS]
+ self.assertEqual(pos, sorted(pos))
+
+ def test_the_bar_sits_above_the_tracks_and_below_the_monitors(self):
+ # Where Resolve and Final Cut both put it, and where the owner pointed:
+ # "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"')):
+ 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):
+ # The whole difference between this and the inspector. A control that
+ # is not on screen teaches nothing and reads as a feature that does
+ # not exist; a disabled one carries the sentence that would make it
+ # work. sbePaintCbar sets `disabled` from `why` and puts `why` in the
+ # title, so there is no way to have one without the other.
+ fn = extract_function("sbePaintCbar", self.src)
+ self.assertIn("el.disabled = !!r.why", fn)
+ self.assertIn("el.title = r.why || r.title", fn)
+ model = extract_function("sbeCbarModel", self.src)
+ # ...and with nothing selected, every row that needs a clip has one.
+ self.assertIn("const noSel", model)
+ self.assertIn("Shift-click a second one", model)
+
+ def test_split_keeps_up_with_the_playhead_and_not_just_the_selection(self):
+ # THE ONE ROW WHOSE STATE FOLLOWS THE PLAYHEAD. `sbeSeek` and the
+ # playback loop repaint the head and the time and deliberately not the
+ # rest of the screen — so Split sat greyed out over the middle of a
+ # shot a scrub had just landed in, and stayed that way until the next
+ # real edit. Caught in the browser while shooting the screenshots.
+ self.assertIn("sbeCbarPlayhead()",
+ extract_function("sbePaintHead", self.src))
+ fn = extract_function("sbeCbarPlayhead", self.src)
+ self.assertIn("sbeSplitWhy()", fn)
+ self.assertIn("el.disabled", fn)
+ # One definition of the reason, shared by the full paint and the
+ # per-frame refresh, or the two would drift.
+ self.assertIn("sbeSplitWhy()", extract_function("sbeCbarModel", self.src))
+ why = extract_function("sbeSplitWhy", self.src)
+ self.assertIn("sbeClipAt(SBE.clips, SBE.playhead)", why)
+ self.assertIn("under.locked", why)
+ self.assertIn("SBE_MIN_CLIP", why)
+
+ def test_the_readout_says_what_is_about_to_be_acted_on(self):
+ # "Ripple delete" over an unnamed selection is the one gesture nobody
+ # should have to guess at, and multi-select made the question real.
+ self.assertIn('id="sbeCbarWho"', self.bar)
+ model = extract_function("sbeCbarModel", self.src)
+ self.assertIn("clips selected", model)
+ self.assertIn("Nothing selected", model)
+
+ def test_the_three_toggles_swap_their_icon_as_well_as_their_label(self):
+ model = extract_function("sbeCbarModel", self.src)
+ for icon in ("#ic-link", "#ic-unlink", "#ic-sound", "#ic-mute",
+ "#ic-lock", "#ic-unlock"):
+ self.assertIn(icon, model, icon)
+ self.assertIn('id="%s"' % icon.lstrip("#"), self.html, icon)
+
+ # ---- the split, and that it stays split ------------------------------
+ PROMOTED = ("sbeToggleLock()", "sbeDuplicateSel()", "sbeLiftSelected()",
+ "sbeRippleSelected()", "sbeToggleAudioLink()",
+ "sbeToggleClipMute()", "sbeDeleteStripSel()",
+ "sbeResyncSel()", "sbeClearPoints()")
+
+ def test_the_promoted_verbs_are_NOT_also_in_the_inspector(self):
+ # Not tidiness: two copies of one control is two chances for one of
+ # them to go on offering a verb the model has stopped accepting, and
+ # it puts the clutter back that this whole pass removed.
+ insp = extract_function("sbePaintInspector", self.src)
+ for act in self.PROMOTED:
+ self.assertNotIn(act, insp, act)
+
+ def test_the_inspector_keeps_the_properties_and_says_that_it_has(self):
+ insp = extract_function("sbePaintInspector", self.src)
+ for keep in ("sbeSpeedCommit", "sbeFadeCommit", "sbeBrightCommit",
+ "sbeRetakeSel()", "sbeTxCommit", "sbeOvTextCommit",
+ "sbeFramingCommit", "sbeAudioFadeCommit",
+ "sbeAddPointAtPlayhead()"):
+ self.assertIn(keep, insp, keep)
+ # "You can leave it if the person wants to dig into the options and
+ # then put advanced options there."
+ self.assertIn("Advanced", insp)
+ self.assertIn("the bar above the tracks", insp)
+ self.assertIn(".sbe-sect-lead", self.src)
+
+ def test_nothing_still_points_the_user_at_the_inspector_for_a_moved_verb(self):
+ # Four toasts said "in the inspector" about buttons that are not there
+ # any more. A stale address is worse than no address.
+ js = "\n".join((ROOT / "webapp" / "js" / f).read_text(encoding="utf-8")
+ for f in ("editor.js",))
+ for line in js.splitlines():
+ if line.lstrip().startswith("//"):
+ continue
+ self.assertNotIn("in the inspector", line, line.strip()[:80])
+
+ # ---- it may not push the tracks down ---------------------------------
+ def test_the_bar_overflows_and_NEVER_wraps(self):
+ # `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 {")]
+ self.assertIn("flex-wrap: nowrap", css)
+ self.assertIn("overflow: hidden", css)
+ # ...and the fold is restated, because `display: inline-flex` on the
+ # class beats the UA's `[hidden] { display: none }` — the overflow
+ # button stayed on screen with the attribute set.
+ self.assertIn(".sbe-cbar-btn[hidden]", css)
+ self.assertIn("display: none !important", css)
+ fit = extract_function("sbeCbarFit", self.src)
+ self.assertIn("bar.scrollWidth <= bar.clientWidth", fit)
+ self.assertIn("sbeCbarMenu", fit)
+ # Measured once per width-and-label change, not once per painted frame:
+ # sbePaint runs on every frame of a drag and of playback.
+ self.assertIn("bar.dataset.fit === sig", fit)
+ # Every button comes HOME when the pane is widened — one copy of each
+ # control, in its stamped order, never two.
+ self.assertIn("dataset.ord", fit)
+
+ def test_the_overflow_panel_and_the_context_menu_can_both_be_shut(self):
+ # A fixed panel that Escape and a click elsewhere do not know about is
+ # a panel that sits over the film until the page is reloaded.
+ self.assertIn("const SBE_POPS = [", self.src)
+ pops = self.src[self.src.index("const SBE_POPS = ["):]
+ pops = pops[:pops.index("]")]
+ for p in ("sbeCbarMenu", "sbeCtxMenu"):
+ self.assertIn(p, pops, p)
+ for p in ("sbeCbarMenu", "sbeCtxMenu"):
+ self.assertIn('id="%s"' % p, self.html, p)
+
+
+class SelectingSeveralClips(unittest.TestCase):
+ """"You should be able to select, hit Shift, and select multiple clips and
+ move them together. It's very important."
+
+ The arithmetic is in `TimelineClient`; this is the wiring and the two
+ modifiers that were already taken by the same gesture.
+ """
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.src = panel_source()
+ cls.down = extract_function("sbeOnTrackDown", cls.src)
+ cls.up = extract_function("sbeOnTrackUp", cls.src)
+
+ def test_the_primary_stays_a_single_id_and_the_set_contains_it(self):
+ # `SBE.sel` is read at fifty-odd call sites and every one of them means
+ # "the one clip the inspector is describing". The set is additional,
+ # and its invariant is repaired in ONE place rather than at every
+ # assignment — a set maintained by hand at each of them is a set that
+ # is stale by the next feature.
+ norm = extract_function("sbeSelNormalise", self.src)
+ self.assertIn("SBE.selSet", norm)
+ self.assertIn("s = [String(SBE.sel)]", norm)
+ self.assertIn("sbeSelNormalise()", extract_function("sbePaint", self.src))
+
+ def test_shift_takes_the_range_and_cmd_toggles_one(self):
+ self.assertIn("sbeSelectRange(id)", self.down)
+ self.assertIn("toggle = id", self.down)
+ # ⌘ CANNOT BE DECIDED ON POINTERDOWN: the same chord is ripple-drag.
+ # It is resolved on pointerup, and only if the pointer never moved.
+ self.assertIn("d.toggle", self.up)
+ self.assertIn("!d.moved", self.up)
+ self.assertIn("sbeSelectToggle(d.toggle)", self.up)
+
+ def test_a_click_inside_a_selection_keeps_it_so_the_block_can_be_dragged(self):
+ # The rule Premiere and Resolve share, and the reason a group move is
+ # possible at all. A click that does not drag then collapses to the
+ # one clip, on pointerup.
+ self.assertIn("collapse = id", self.down)
+ self.assertIn("sbeSelectOne(d.collapse)", self.up)
+
+ def test_the_drag_becomes_a_block_slide_and_ONE_undo_step(self):
+ self.assertIn("'movemany'", self.down)
+ self.assertIn("sbeSelIds()", self.down)
+ move = extract_function("sbeOnTrackMove", self.src)
+ self.assertIn("sbeMoveGroup(SBE.clips", move)
+ # The drag registers its single undo step in sbeOnTrackUp from the
+ # pointerdown snapshot, exactly as a one-clip drag does.
+ self.assertIn("SBE.undo.push(d.before)", self.up)
+
+ def test_a_group_verb_is_one_undo_step_and_reports_what_it_skipped(self):
+ fn = extract_function("sbeMutateEach", self.src)
+ self.assertIn("SBE.undo.push(before)", fn)
+ self.assertEqual(fn.count("SBE.undo.push("), 1)
+ # A locked member does not abort the rest — refusing the whole gesture
+ # over one pinned shot would make a multiple selection unusable — and
+ # the ones left alone are named.
+ self.assertIn("why.length", fn)
+ self.assertIn("were left as they were", fn)
+ # Nothing landed means nothing is KEPT: the refusals ran against the
+ # live array, so the snapshot goes back rather than being trusted.
+ self.assertIn("sbeRestore(before)", fn)
+
+ def test_a_mixed_selection_converges_rather_than_inverting_clip_by_clip(self):
+ # Pressing Lock over three shots where one is already pinned has to end
+ # with three pinned shots — that is what the button says. Per-clip
+ # inversion would leave the row half on and half off and the label
+ # lying about both.
+ for fn in ("sbeToggleLock", "sbeToggleAudioLink"):
+ body = extract_function(fn, self.src)
+ self.assertIn("ids", body)
+ self.assertIn("const on = !first.locked",
+ extract_function("sbeToggleLock", self.src))
+
+ def test_empty_track_and_escape_both_clear_it(self):
+ # There is always an obvious way back to nothing, which is what makes
+ # ⌘-click and shift-click safe to experiment with.
+ self.assertIn("SBE.selSet = []", self.down)
+ keys = _editor_keydown(self.src)
+ self.assertIn("sbeSelectAll()", keys)
+ self.assertIn("sbeSelectNone()", keys)
+ # ...and Escape never closes the document: a second Escape used to
+ # throw the editor out of the timeline, and so did the Escape that
+ # closed the Docs on top of it. Closing is the ⋯ menu's Close.
+ esc = keys[keys.index("ev.key === 'Escape'"):]
+ esc = esc[:esc.index("RENDER HAS A KEY")]
+ self.assertIn("sbeSelectNone()", esc)
+ self.assertNotIn("sbeClose()", esc)
+
+ def test_the_selection_is_drawn_on_both_lanes_and_the_primary_is_marked(self):
+ # With four shots selected the inspector still describes ONE of them,
+ # so the primary has to be pickable out of the row.
+ trk = extract_function("sbePaintTrack", self.src)
+ self.assertIn("selMap[String(c.id)]", trk)
+ self.assertIn("is-primary", trk)
+ self.assertIn(".sbe-clip.is-sel.is-primary", self.src)
+ self.assertIn("aSelMap[String(c.id)]",
+ extract_function("sbePaintAudioLane", self.src))
+
+
+class TheEverydayGesturesThatWereMissing(unittest.TestCase):
+ """The audit that came with the toolbar: "find other things that you
+ overlook in the basic design of this thing so we actually have a
+ functional editor." These are the ones that were cheap and safe."""
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.src = panel_source()
+ cls.keys = _editor_keydown(cls.src)
+
+ def test_cmd_s_SAVES_and_does_not_split_the_shot(self):
+ # It has been documented as the manual save since the save model was
+ # written — docs/EDITOR_SAVE_MODEL.md §1, "`Save` (and ⌘S)" — and it
+ # has never done it: the bare-S split took the key first with no
+ # modifier guard, so the one chord every person on a Mac presses to
+ # make their work safe SPLIT THE SHOT under the playhead.
+ i = self.keys.index("sbeSaveNow()")
+ j = self.keys.index("sbeSplitHere()")
+ self.assertLess(i, j)
+ self.assertIn("(ev.metaKey || ev.ctrlKey) && (ev.key === 's'", self.keys)
+ self.assertIn("(ev.key === 's' || ev.key === 'S') && !ev.metaKey",
+ self.keys)
+
+ def test_the_arrows_nudge_the_selection_and_still_move_the_playhead(self):
+ self.assertIn("ev.altKey && (ev.key === 'ArrowLeft'", self.keys)
+ self.assertIn("sbeNudge(", self.keys)
+ # The bare arrows stay the playhead's — the more frequent of the two.
+ self.assertLess(self.keys.index("sbeNudge("),
+ self.keys.index("if (ev.key === 'ArrowLeft')"))
+ fn = extract_function("sbeNudge", self.src)
+ self.assertIn("sbeGroupLimits(", fn)
+ # A CLAMPED NUDGE SAYS SO rather than burning a revision per keypress:
+ # it produces no change, and sbeMutate would still stamp the document
+ # dirty, push an undo step that undoes nothing and queue a save.
+ self.assertIn("nothing to give", fn)
+
+ def test_home_end_and_the_zoom_keys_exist(self):
+ for bit in ("ev.key === 'Home'", "ev.key === 'End'", "sbeZoom("):
+ self.assertIn(bit, self.keys, bit)
+
+ def test_the_sound_pair_has_keys_and_the_legend_names_them(self):
+ self.assertIn("sbeToggleAudioLink()", self.keys)
+ self.assertIn("sbeResyncSel()", self.keys)
+ # The legend draws the ONE shortcut table (webapp/js/shortcuts.js);
+ # the words it teaches are that table's rows.
+ self.assertIn("shortcutRows(['editor', 'editor-mouse']",
+ extract_function("sbeKeysLegend", self.src))
+ table = (ROOT / "webapp" / "js" / "shortcuts.js").read_text(encoding="utf-8")
+ for bit in ("'shift+l'", "'shift+r'", "'home', 'end'", "Nudge the selected clips",
+ "Right-click", "Select the range"):
+ self.assertIn(bit, table, bit)
+
+ def test_a_right_click_answers_with_the_editor_and_not_the_browser(self):
+ fn = extract_function("sbeCtxOpen", self.src)
+ self.assertIn("ev.preventDefault()", fn)
+ self.assertIn("sbeCbarModel()", fn) # one table, never a second copy
+ self.assertIn("if (r.why) continue", fn) # only what can actually fire
+ # A hole's only two verbs.
+ self.assertIn("Close this hole", fn)
+ self.assertIn("sbeGenOpen(", fn)
+ # ...and it is clamped inside the window, at the pointer.
+ self.assertIn("window.innerWidth", fn)
+ self.assertIn("window.innerHeight", fn)
+ wire = self.src[self.src.index("function sbeWire()"):]
+ self.assertIn("track.addEventListener('contextmenu', sbeCtxOpen)", wire)
+
+ def test_a_hole_can_be_closed_and_the_sound_travels_with_it(self):
+ fn = extract_function("sbeCloseGapAt", self.src)
+ self.assertIn("sbeHoles(SBE.clips)", fn)
+ self.assertIn("after._gap = 0", fn)
+ # A CLOSE IS A HEAL, NOT A DRAG — the same reasoning sbeAdoptGaps gives
+ # for the sub-frame version of exactly this operation.
+ self.assertIn("sbeSyncMark(", fn)
+ self.assertIn("sbeSyncCarry(", fn)
+ self.assertLess(fn.index("sbeSyncMark("), fn.index("sbeSyncCarry("))
+
+
class TimelineMarkup(unittest.TestCase):
"""The controls the JS drives have to EXIST, in the real markup."""
@@ -6289,15 +6835,27 @@ class TimelineMarkup(unittest.TestCase):
self.assertIn("event.stopPropagation()", pool)
self.assertIn('onpointerdown="edPoolDragStart(event,', pool)
- def test_shift_reorders_and_a_plain_drag_still_moves(self):
+ def test_altshift_reorders_and_a_plain_drag_still_moves(self):
+ # SHIFT ALONE IS THE RANGE SELECTION NOW — "you should be able to
+ # select, hit Shift, and select multiple clips and move them together.
+ # It's very important." — so reorder took alt+shift, which costs it
+ # nothing: a reorder chooses a NEIGHBOUR rather than a time, so it
+ # never snapped to the grid alt suppresses. It also became two named
+ # items in the right-click menu, which is easier to find than the
+ # modifier it gave up.
down = extract_function("sbeOnTrackDown", self.src)
- self.assertIn("ev.shiftKey ? 'reorder' : 'move'", down)
+ self.assertIn("(ev.shiftKey && ev.altKey) ? 'reorder'", down)
+ self.assertIn("sbeSelectRange(id)", down)
move = extract_function("sbeOnTrackMove", self.src)
self.assertIn("sbeReorderTo(SBE.clips", move)
self.assertIn("sbeMoveTo(SBE.clips", move)
- # The legend teaches it, in the same voice as the Alt override.
- self.assertIn("reorder instead of move", extract_function(
- "sbeKeysLegend", self.src))
+ # The legend teaches both, in the same voice as the Alt override.
+ table = (ROOT / "webapp" / "js" / "shortcuts.js").read_text(encoding="utf-8")
+ self.assertIn("Reorder instead of move", table)
+ self.assertIn("Select the range", table)
+ ctx = extract_function("sbeCtxOpen", self.src)
+ self.assertIn("Move earlier", ctx)
+ self.assertIn("Move later", ctx)
def test_the_nle_export_is_offered_and_says_what_the_audio_is(self):
self.assertIn('id="sbeNleBtn"', self.src)
@@ -6400,18 +6958,25 @@ class TimelineMarkup(unittest.TestCase):
# zeroes the take" is executed, not grepped for.
# ---------------------------------------------------------------------------
+# ---- One Shot is a TAB (2026-09-08) --------------------------------------------
+# Its own composer (webapp/js/oneshot.js), its own API (POST /oneshot). The
+# contract below runs the real module functions in node against a DOM shim:
+# entering the tab, the length chips, the beats gutter, the character pick
+# that turns the handoff on, and the ONE document the tab posts.
ONESHOT_FUNCTIONS = (
- "setMode", "defaultRemixMode", "updatePromptPlaceholder",
- "takePartSeconds", "setTakeSeconds", "takePrefill", "takePrefillClick",
- "beatsInput", "oneshotActive", "oneshotBackendMode", "oneshotEnter",
- "oneshotLeave", "oneshotRefreshLabels", "oneshotSyncAnchor",
- "_setTakeToggle", "setTakeLightLock", "setTakeRetake",
- "takeLengthLabel", "oneshotSummary", "restoreFoldedLtxLength", "framesToDuration",
+ "osEl", "osEsc", "osLengthLabel", "osPartSeconds", "osClock", "osActiveQuality", "osH3Available",
+ "osBeatsList", "osDocument", "osRenderEngine", "osRenderLengths", "osQualityRows", "osRenderQualities",
+ "osRenderCharacters", "osRenderToggles", "osRenderAnchor", "osRenderBeats", "osSetBeats", "osBeatsInput",
+ "osPartsText", "osPartsShort",
+ "osRenderSummary", "osRenderAll", "osSetEngine", "osSetSeconds", "osSetQuality", "osSetCharacter",
+ "osToggle", "osSplitPrompt", "osVerdict", "osPaintStatus", "oneshotOpenFromParams", "osWire",
+ # the async ones osWire binds; the shim's fetch answers {ok:false}, so they are inert here
+ "osPlanBeats", "osGenerate", "osUpload", "osClearAnchor", "osEstimate", "osStatusTick",
+ "osStartStatus", "osStopStatus", "osLoadOptions", "oneshotTabEnter", "oneshotTabLeave",
)
ONESHOT_SHIM = r"""
'use strict';
-// A classList that REMEMBERS, because the assertions read it back.
function _cls() {
const set = new Set();
return {
@@ -6423,230 +6988,220 @@ function _cls() {
};
}
const _els = {};
+const _made = [];
function _mk(id, props) {
let _v = '';
const e = Object.assign({
- id, textContent: '', placeholder: '', className: '', innerHTML: '',
- dataset: {}, hidden: false, style: {}, classList: _cls(), files: [],
- querySelector() { return null; }, querySelectorAll() { return []; },
+ id, textContent: '', placeholder: '', className: '', innerHTML: '', title: '',
+ dataset: {}, hidden: false, style: {}, classList: _cls(), files: [], checked: false, rows: 6, disabled: false,
+ children: [], parentElement: null,
+ querySelector() { return null; },
+ querySelectorAll(sel) { return _qsa(sel, this); },
setAttribute(k, v) { this['_attr_' + k] = v; }, getAttribute(k) { return this['_attr_' + k] ?? null; },
removeAttribute(k) { delete this['_attr_' + k]; if (k === 'src') this.src = ''; },
appendChild() {}, remove() {}, addEventListener() {}, focus() {}, blur() {},
dispatchEvent() { return true; },
}, props || {});
Object.defineProperty(e, 'value', {
- get() { return _v; },
- set(x) { _v = (x === null || x === undefined) ? '' : String(x); },
+ get() { return _v; }, set(x) { _v = (x === null || x === undefined) ? '' : String(x); },
enumerable: true, configurable: true,
});
if (props && Object.prototype.hasOwnProperty.call(props, 'value')) e.value = props.value;
- _els[id] = e;
+ if (id) _els[id] = e;
+ _made.push(e);
return e;
}
-// The REAL chips: every data-mode in #modeGroup, every data-take in #takeGroup,
-// the two toggle pairs — read out of index.html by the test and handed in.
-const MODE_CHIPS = __MODE_CHIPS__.map((m, i) => _mk('_mode' + i, { dataset: { mode: m } }));
-const TAKE_CHIPS = __TAKE_CHIPS__.map((t, i) => {
- const parts = _mk('_parts' + i);
- return _mk('_take' + i, { dataset: { take: String(t) }, querySelector: (sel) => sel === '.take-parts' ? parts : null });
+// innerHTML written by the renderers is parsed for the chips it makes: every
+// <button ... data-os-xxx="v"> becomes a shim button with that dataset entry,
+// and 'active' in its class attribute becomes classList.active.
+function _chipsFrom(html) {
+ const out = [];
+ const re = /<(button|input)[^>]*?class="([^"]*)"[^>]*?data-os-([a-z]+)="([^"]*)"[^>]*>(?:[\s\S]*?<\/button>)?/g;
+ let m;
+ while ((m = re.exec(html))) {
+ const b = _mk('', { dataset: {} });
+ b.dataset['os' + m[3][0].toUpperCase() + m[3].slice(1)] = m[4];
+ if (/\bactive\b/.test(m[2])) b.classList.add('active');
+ if (m[1] === 'input') { const v = m[0].match(/ value="([^"]*)"/); b.value = v ? v[1].replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&') : ''; }
+ b._html = m[0];
+ out.push(b);
+ }
+ return out;
+}
+const _groups = {};
+function _group(id) {
+ if (_groups[id]) return _groups[id];
+ const g = _mk(id, {});
+ let _html = '';
+ Object.defineProperty(g, 'innerHTML', {
+ get() { return _html; },
+ set(h) { _html = String(h || ''); g._chips = _chipsFrom(_html); },
+ enumerable: true, configurable: true,
+ });
+ g._chips = [];
+ g.querySelectorAll = (sel) => g._chips.filter(c => {
+ const m = sel.match(/data-os-([a-z]+)/);
+ return !m || (c.dataset['os' + m[1][0].toUpperCase() + m[1].slice(1)] !== undefined);
+ });
+ _groups[id] = g;
+ return g;
+}
+['osLengthGroup', 'osQualityGroup', 'osCharacterGroup', 'osParts', 'osBeats'].forEach(_group);
+global.window = global; global.window.clipboardData = null;
+const ENGINE_CHIPS = ['ltx', 'h3'].map(e => _mk('', { dataset: { osEngine: e } }));
+const TOGGLES = {};
+[['light', ['on', 'off']], ['retake', ['on', 'off']], ['handoff', ['speech', 'last']]].forEach(([name, vals]) => {
+ const group = _mk('', { dataset: { osToggle: name } });
+ group.parentElement = _mk('', {});
+ const chips = vals.map(v => _mk('', { dataset: { osValue: v } }));
+ group.querySelectorAll = () => chips;
+ TOGGLES[name] = { group, chips };
});
-const LIGHT_CHIPS = ['on', 'off'].map((v, i) => _mk('_light' + i, { dataset: { takeLight: v } }));
-const RETAKE_CHIPS = ['on', 'off'].map((v, i) => _mk('_retake' + i, { dataset: { takeRetake: v } }));
+function _qsa(sel) {
+ if (sel === '#osEngineGroup .pill-btn' || sel === '#osEngineGroup [data-os-engine]') return ENGINE_CHIPS;
+ if (sel === '[data-os-toggle]') return Object.values(TOGGLES).map(t => t.group);
+ if (sel === '[data-os-toggle="handoff"]') return [TOGGLES.handoff.group];
+ return [];
+}
+// the rows box answers its own querySelector (Enter/Backspace focus moves)
+_groups.osBeats.querySelector = () => null;
+function _unusedQsa() {
+}
global.document = {
getElementById: (id) => _els[id] || _mk(id),
- querySelector: () => null,
- querySelectorAll: (sel) => ({
- '#modeGroup .pill-btn': MODE_CHIPS,
- '#takeGroup .pill-btn': TAKE_CHIPS,
- '#takeLightLockGroup .pill-btn': LIGHT_CHIPS,
- '#takeRetakeGroup .pill-btn': RETAKE_CHIPS,
- })[sel] || [],
- createElement: () => _mk('_tmp'),
+ querySelector: (sel) => sel === '[data-os-toggle="handoff"]' ? TOGGLES.handoff.group : null,
+ querySelectorAll: _qsa,
+ createElement: () => _mk(''),
addEventListener: () => {},
readyState: 'complete',
body: { dataset: { engine: 'ltx' }, classList: _cls() },
};
-global.window = global;
global.console = console;
-const FPS = 24;
-// The LTX length axis as BOOT ships it — key + frames is what the restore reads.
-const BOOT = { ltx: { default_length: '5s', lengths: [
- { key: '3s', frames: 73 }, { key: '5s', frames: 121 }, { key: '10s', frames: 241 } ] } };
-// The page's initial state, as the markup ships it.
-_mk('mode', { value: 't2v' });
-_mk('ltx_length', { value: '10s' });
-_mk('frames', { value: '241' });
-_mk('duration', { value: '10.00' });
-_mk('take_seconds', { value: '0' });
-_mk('take_light_lock', { value: 'on' });
-_mk('take_retake', { value: 'on' });
-_mk('takeAxes', { hidden: __PANEL_HIDDEN__ });
-_mk('beatsRow', { hidden: true });
-_mk('prompt', { value: 'She pushes off down the avenue. A van sweeps past. She drops off the kerb.' });
-_mk('i2vMode', { value: 'i2v' }); // Image mode's audio-source select, as shipped
-let currentMode = 't2v';
-// setMode's collaborators. Stubs, not extractions: the property under test is
-// the One Shot contract, not the paint.
-const REMIX_MODES = ['ingredients', 'control', 'restore'];
-let LAST_STATUS = null;
-global.ingredientsServed = () => true;
-global._portalLoraPicker = () => {};
-global.renderLorasList = () => {};
-global.updateAccelAvailability = () => {};
-global.updateTemporalAvailability = () => {};
-global.updateDerived = () => {};
-global.updateCustomizeSummary = () => {};
-global.updateModelsCard = () => {};
-global._updateCharsPickerVisibility = () => {};
-global._autoMainOutputsFilterForMode = () => {};
-global._syncEngineForMode = () => {};
-global.isKeyframeModeChipActive = () => false;
-global.setQuality = () => {};
-const refreshed = [];
-global.takeRefresh = async () => { refreshed.push(document.getElementById('take_seconds').value); };
-global.fetch = async () => ({ json: async () => ({ ok: true }) });
+global.activeElement = null;
+Object.defineProperty(global.document, 'activeElement', { get() { return null; } });
+global.fetch = async () => ({ json: async () => ({ ok: false }) });
+const switched = [];
+global.workflowSwitch = (n) => switched.push(n);
+const OS_SECONDS = [30, 45, 60, 90, 120];
"""
ONESHOT_BODY = r"""
const $ = (id) => document.getElementById(id);
const active = (list, key) => list.filter(b => b.classList.contains('active')).map(b => b.dataset[key]);
+const chipsOf = (id) => $(id)._chips || [];
const out = {};
-out.start = { mode: $('mode').value, take: $('take_seconds').value, panelHidden: $('takeAxes').hidden };
-
-setMode('oneshot');
-out.enter = {
- currentMode, mode: $('mode').value, take: $('take_seconds').value,
- panelHidden: $('takeAxes').hidden, beatsRowHidden: $('beatsRow').hidden,
- bodyClass: document.body.classList.contains('oneshot-mode'),
- chips: active(MODE_CHIPS, 'mode'), takeChips: active(TAKE_CHIPS, 'take'),
- light: $('take_light_lock').value, retake: $('take_retake').value,
- lightChips: active(LIGHT_CHIPS, 'takeLight'), retakeChips: active(RETAKE_CHIPS, 'takeRetake'),
- parts: TAKE_CHIPS.map(b => b.querySelector('.take-parts').textContent),
- note: $('takeEngineNote').textContent,
- beats: $('beats').value, beatsHint: $('beatsHint').textContent,
- placeholder: $('prompt').placeholder,
- refreshed: refreshed.slice(),
-};
-
-// The switcher moves to H3: the parts are 15 s now, and the note says so.
-document.body.dataset.engine = 'h3';
-oneshotRefreshLabels();
-out.h3 = { parts: TAKE_CHIPS.map(b => b.querySelector('.take-parts').textContent), note: $('takeEngineNote').textContent };
-document.body.dataset.engine = 'ltx';
-oneshotRefreshLabels();
-
-// An anchor image flips the backend mode to i2v; clearing it flips back.
-$('image').value = '/uploads/frame_one.png';
-oneshotSyncAnchor();
-out.anchored = { mode: $('mode').value, thumbHidden: $('oneshotAnchorThumb').hidden,
- thumbSrc: $('oneshotAnchorThumb').src, clearHidden: $('oneshotAnchorClear').hidden,
- name: $('oneshotAnchorName').textContent };
-$('image').value = '';
-oneshotSyncAnchor();
-out.unanchored = { mode: $('mode').value, thumbHidden: $('oneshotAnchorThumb').hidden, clearHidden: $('oneshotAnchorClear').hidden };
-
-// The toggles write the hidden fields make_job reads, as on/off.
-setTakeLightLock('off'); setTakeRetake('off');
-out.toggledOff = { light: $('take_light_lock').value, retake: $('take_retake').value,
- lightChips: active(LIGHT_CHIPS, 'takeLight'), retakeChips: active(RETAKE_CHIPS, 'takeRetake') };
-setTakeLightLock('garbage'); setTakeRetake(undefined);
-out.toggledBack = { light: $('take_light_lock').value, retake: $('take_retake').value };
-
-// A longer shot, and the beats button over a box that already has lines.
-setTakeSeconds(120);
-$('beats_text').value = 'only one line';
-beatsInput();
-out.len120 = { take: $('take_seconds').value, takeChips: active(TAKE_CHIPS, 'take'), beats: $('beats').value };
-takePrefillClick();
-out.prefilled = { lines: $('beats_text').value.split('\n').length, beats: $('beats').value };
-
-// The footer strip's summary, per engine, from the same length.
-out.summary = {
- ltx60: oneshotSummary(60, 'ltx'), h3_90: oneshotSummary(90, 'h3'),
- ltx30: oneshotSummary(30, 'ltx'), ltx120: oneshotSummary(120, 'ltx'), off: oneshotSummary(0, 'ltx'),
- labels: [30, 45, 60, 90, 120].map(takeLengthLabel),
+OS.options = {
+ ok: true, seconds: [30, 45, 60, 90, 120], beat_seconds: 5,
+ engines: { ltx: { available: true, part_seconds: 10, qualities: [
+ { key: 'quick', label: 'Quick', eta_min: 2 }, { key: 'balanced', label: 'Balanced', eta_min: 4.6 },
+ { key: 'standard', label: 'Standard', eta_min: 7.7 }, { key: 'high', label: 'High', eta_min: 12 }] },
+ h3: { available: true, part_seconds: 15, qualities: [
+ { key: 'draft', label: 'Draft', size: '640×384' }, { key: 'standard', label: 'Standard', size: '768×448' },
+ { key: 'high', label: 'High', size: '1024×576' }, { key: 'native', label: 'Native', size: '1344×768' }] } },
+ characters: [{ id: 'bizarrotrn', name: 'Bizarro', has_voice: true }],
+ character_qualities: [{ key: 'draft', label: 'Draft', sub: '' }, { key: 'pro', label: 'Pro', sub: '' },
+ { key: 'high', label: 'High', sub: '' }, { key: 'high_720p', label: 'High · 720p', sub: '' }],
+ handoff: ['last', 'speech'], planner: true,
};
-// An engine round trip while the Length strip is folded: H3's tier wrote 73
-// into #frames; the restore puts the folded LTX length (10s → 241) back.
-$('frames').value = '73'; $('duration').value = '3.00';
-out.restored = { ok: restoreFoldedLtxLength(), frames: $('frames').value, duration: $('duration').value };
-// LEAVING the mode: any other setMode zeroes the take and folds the panel —
-// and puts the two continuity fields back to on, so a normal clip's sidecar
-// carries no One Shot noise. Both are left OFF here on purpose.
-setTakeLightLock('off'); setTakeRetake('off');
-setMode('t2v');
-out.leave = {
- currentMode, mode: $('mode').value, take: $('take_seconds').value, beats: $('beats').value,
- panelHidden: $('takeAxes').hidden, bodyClass: document.body.classList.contains('oneshot-mode'),
- chips: active(MODE_CHIPS, 'mode'),
- light: $('take_light_lock').value, retake: $('take_retake').value,
- lightChips: active(LIGHT_CHIPS, 'takeLight'), retakeChips: active(RETAKE_CHIPS, 'takeRetake'),
+OS.optionsAt = Date.now();
+osWire();
+osRenderAll();
+out.enter = {
+ engine: OS.engine, seconds: OS.seconds, quality: osActiveQuality(),
+ lengths: chipsOf('osLengthGroup').map(c => c.dataset.osSeconds), activeLength: active(chipsOf('osLengthGroup'), 'osSeconds'),
+ parts: chipsOf('osLengthGroup').map(c => (c._html.match(/(\d+ × \d+ s(?: \+ \d+ s)?)/) || [])[1]),
+ qualities: chipsOf('osQualityGroup').map(c => c.dataset.osQuality),
+ characters: chipsOf('osCharacterGroup').map(c => c.dataset.osCharacter),
+ beats: osBeatsList(), beatsHint: $('osBeatsHint').textContent,
+ rows: chipsOf('osBeats').length,
+ first: ($('osBeats').innerHTML.match(/<span class="os-stamp">([^<]+)</) || [])[1],
+ handoff: OS.handoff, handoffChips: active(TOGGLES.handoff.chips, 'osValue'),
+ summary: $('osSummary').innerHTML, characterBlockHidden: $('osCharacterBlock').hidden,
};
-// ...including the early-return modes (character returns before the generic
-// path), which is where a hook placed too low would miss.
-setMode('oneshot');
-out.reenter = { take: $('take_seconds').value, panelHidden: $('takeAxes').hidden, takeChips: active(TAKE_CHIPS, 'take') };
-setMode('character');
-out.leaveViaCharacter = { currentMode, mode: $('mode').value, take: $('take_seconds').value, panelHidden: $('takeAxes').hidden };
-// A One Shot with an anchor enters straight into i2v.
-$('image').value = '/uploads/frame_one.png';
-setMode('oneshot');
-out.enterAnchored = { mode: $('mode').value, take: $('take_seconds').value };
-setMode('i2v');
-out.leaveToImage = { mode: $('mode').value, take: $('take_seconds').value, panelHidden: $('takeAxes').hidden };
-process.stdout.write(JSON.stringify(out));
+// The document with only a prompt: one paragraph is a complete request.
+$('osPrompt').value = 'A hen skates down Broadway at night.';
+out.docPromptOnly = osDocument();
+// A shorter shot: the gutter follows the length.
+osSetSeconds(30);
+out.len30 = { seconds: OS.seconds, rows: chipsOf('osBeats').length,
+ activeLength: active(chipsOf('osLengthGroup'), 'osSeconds'), hint: $('osBeatsHint').textContent };
+// Beats typed: the hint counts, rows past the end are flagged, the document carries the list.
+osSetBeats(['she pushes off', '', 'a van sweeps past', '1', '2', '3', '4', '5']);
+out.beats = { hint: $('osBeatsHint').textContent, rows: chipsOf('osBeats').length,
+ over: ($('osBeats').innerHTML.match(/os-beat-row over/g) || []).length, doc: osDocument().beats,
+ values: chipsOf('osBeats').map(c => c.value) };
+// Split the prompt: sentences become lines.
+$('osPrompt').value = 'She pushes off. A van sweeps past! Pigeons burst up? Then nothing.';
+osSplitPrompt();
+out.split = osBeatsList();
+// A character turns the handoff on, the qualities become the character's, and the document names it.
+osSetCharacter('bizarrotrn');
+out.character = { handoff: OS.handoff, handoffChips: active(TOGGLES.handoff.chips, 'osValue'), quality: osActiveQuality(),
+ qualities: chipsOf('osQualityGroup').map(c => c.dataset.osQuality), doc: osDocument() };
+// The user's own choice on the handoff survives picking nobody again.
+osToggle('handoff', 'last');
+osSetCharacter('');
+out.handoffKept = OS.handoff;
+// H3: 15 s parts, its own qualities, no character, no handoff row.
+osSetEngine('h3');
+out.h3 = { parts: chipsOf('osLengthGroup').map(c => (c._html.match(/(\d+ × \d+ s(?: \+ \d+ s)?)/) || [])[1]),
+ qualities: chipsOf('osQualityGroup').map(c => c.dataset.osQuality), quality: osActiveQuality(),
+ characterBlockHidden: $('osCharacterBlock').hidden, handoffRowHidden: TOGGLES.handoff.group.parentElement.hidden,
+ doc: osDocument() };
+// A 45 s shot on LTX is four 10 s parts and one of 5 s, and the tab says so.
+osSetEngine('ltx');
+osSetSeconds(45);
+out.len45 = { summary: $('osSummary').innerHTML, chip: (chipsOf('osLengthGroup').find(c => c.dataset.osSeconds === '45')._html.match(/(\d+ × \d+ s(?: \+ \d+ s)?)/) || [])[1] };
+osSetSeconds(30);
+// Picking a character, then H3: the character is cleared, not carried into a job H3 cannot use.
+osSetCharacter('bizarrotrn');
+osSetEngine('h3');
+out.h3Cleared = { character: OS.character, handoff: OS.handoff, doc: osDocument() };
+osSetEngine('ltx');
+// Load Params of a finished one shot rebuilds the document and opens the tab.
+oneshotOpenFromParams({ prompt: 'the tram', engine: 'ltx', character_id: 'bizarrotrn', quality_choice: 'pro', seed: '4242',
+ take: { seconds: 90, beats: ['a', '', 'c'], camera: 'a slow push in', handoff: 'speech', light_lock: '', retake: false } });
+out.loaded = { engine: OS.engine, seconds: OS.seconds, prompt: $('osPrompt').value, beats: osBeatsList(),
+ camera: $('osCamera').value, handoff: OS.handoff, light: OS.light, retake: OS.retake,
+ character: OS.character, seed: $('osSeed').value, switched: switched.slice() };
+// The verdict words a user reads on the status strip.
+out.verdicts = [0.54, 0.22, -0.13, null].map(v => osVerdict(v).cls);
+osPaintStatus({ ok: true, current: { id: 'j1', label: 'tram', engine: 'ltx', seconds: 30, parts: 3, part: 2, lipsync: [0.4], drift: [0.1] }, queued: [], recent: [], log: ['[10:00:00] [take] part 1: lip-sync +0.40'] });
+out.status = { title: $('osStatusTitle').textContent, meta: $('osStatusMeta').textContent,
+ parts: chipsOf('osParts').length, partsHtml: $('osParts').innerHTML, log: $('osLog').textContent, hidden: $('osStatus').hidden };
+OS.lastSubmitted = 'mine';
+osPaintStatus({ ok: true, current: { id: 'j1', label: 'tram', engine: 'ltx', seconds: 30, parts: 3, part: 2, lipsync: [], drift: [] },
+ queued: [{ id: 'other', label: 'other', seconds: 60, parts: 6 }, { id: 'mine', label: 'coast ride', seconds: 30, parts: 3 }], recent: [], paused: true, log: [] });
+out.statusMine = { title: $('osStatusTitle').textContent, meta: $('osStatusMeta').textContent };
+console.log(JSON.stringify(out));
"""
-def _oneshot_markup(src: str) -> dict:
- """The real chips out of the real markup, for the shim."""
- html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")
- bar = html[html.index('id="modeGroup"'):]
- bar = bar[:bar.index("</div>")]
- modes = re.findall(r'data-mode="([^"]+)"', bar)
- group = html[html.index('id="takeGroup"'):]
- group = group[:group.index("</div>")]
- takes = [int(t) for t in re.findall(r'data-take="(\d+)"', group)]
- panel = extract_element("takeAxes", src)
- return {"modes": modes, "takes": takes, "panel_hidden": " hidden" in panel or panel.endswith("hidden>")}
-
-
def run_oneshot_contract() -> dict:
if NODE is None:
raise unittest.SkipTest("node not on PATH")
source = panel_source()
- m = _oneshot_markup(source)
- shim = (ONESHOT_SHIM
- .replace("__MODE_CHIPS__", json.dumps(m["modes"]))
- .replace("__TAKE_CHIPS__", json.dumps(m["takes"]))
- .replace("__PANEL_HIDDEN__", "true" if m["panel_hidden"] else "false"))
- # The length table is a module const, not a function — read it as it is.
- choices = re.search(r"^const TAKE_CHOICES = \[[^\]]*\];", source, re.M)
- if not choices:
- raise AssertionError("TAKE_CHOICES not found in the panel source")
- # The remembered length is a module `let`, read as it is like the table.
- last = re.search(r"^let _oneshotLastSeconds = \d+;", source, re.M)
- if not last:
- raise AssertionError("_oneshotLastSeconds not found in the panel source")
- script = (shim + choices.group(0) + "\n" + last.group(0) + "\n"
+ state = re.search(r"^const OS = \{.*?^\};", source, re.M | re.S)
+ if not state:
+ raise AssertionError("the OS state object was not found in oneshot.js")
+ script = (ONESHOT_SHIM + state.group(0) + "\n"
+ "\n".join(extract_function(n, source) for n in ONESHOT_FUNCTIONS)
+ "\n" + ONESHOT_BODY)
with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:
fh.write(script)
path = Path(fh.name)
try:
- result = subprocess.run([NODE, str(path)], capture_output=True,
- text=True, timeout=60)
+ result = subprocess.run([NODE, str(path)], capture_output=True, text=True, timeout=60)
if result.returncode:
raise AssertionError(result.stdout + "\n" + result.stderr)
- return json.loads(result.stdout)
+ return json.loads(result.stdout.strip().splitlines()[-1])
finally:
path.unlink(missing_ok=True)
-class OneShotIsAMode(unittest.TestCase):
- """The mode chip, the panel, and the one property that matters most: a
- normal clip never carries take_seconds."""
+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."""
@classmethod
def setUpClass(cls) -> None:
@@ -6655,239 +7210,115 @@ class OneShotIsAMode(unittest.TestCase):
cls.r = run_oneshot_contract()
# ---- the markup ---------------------------------------------------------
- def test_the_chip_is_in_the_mode_bar_between_image_and_fflf(self):
+ def test_the_tab_sits_right_after_video(self):
+ bar = self.html[self.html.index('id="workflowTabs"'):]
+ bar = bar[:bar.index("</nav>")]
+ tabs = re.findall(r'data-workflow="([^"]+)"', bar)
+ self.assertEqual(tabs[:2], ["manual", "oneshot"])
+ self.assertIn(">One Shot</button>", bar.replace("</svg>One Shot", ">One Shot"))
+
+ def test_the_video_form_carries_no_one_shot_any_more(self):
bar = self.html[self.html.index('id="modeGroup"'):]
bar = bar[:bar.index("</div>")]
- modes = re.findall(r'data-mode="([^"]+)"', bar)
- self.assertIn("oneshot", modes)
- self.assertEqual(modes.index("oneshot"), modes.index("i2v") + 1)
- self.assertEqual(modes[modes.index("oneshot") + 1], "keyframe")
- chip = re.search(r'<button[^>]*data-mode="oneshot"[^>]*>(.*?)</button>', bar, re.S).group(1)
- self.assertTrue(chip.startswith("One Shot"))
- self.assertIn("never cuts", chip)
-
- def test_the_panel_ships_folded_and_keeps_its_ids(self):
- el = extract_element("takeAxes", self.src)
- self.assertIn("hidden", el)
- self.assertIn("oneshot-panel", el)
- panel = self.html[self.html.index('id="takeAxes"'):]
- panel = panel[:panel.index('id="takeEngineNote"')]
- for needed in ('id="takeGroup"', 'id="beatsRow"', 'id="beats_text"', 'id="beatsHint"',
- 'id="takeEstimate"', 'id="beatsPrefillBtn"', 'id="oneshotAnchorFile"',
- 'id="oneshotAnchorThumb"', 'id="oneshotAnchorClear"',
- 'id="takeLightLockGroup"', 'id="takeRetakeGroup"',
- 'href="/docs/prompting"'):
- self.assertIn(needed, panel, needed)
- # In its own mode there is no Off chip — leaving the mode is Off.
- takes = re.findall(r'data-take="(\d+)"', panel)
- self.assertEqual(takes, ["30", "45", "60", "90", "120"])
-
- def test_the_two_continuity_fields_are_in_the_video_form_and_default_on(self):
+ self.assertNotIn("oneshot", re.findall(r'data-mode="([^"]+)"', bar))
form = self.html[self.html.index('id="genForm"'):]
form = form[:form.index("</form>")]
- for name in ("take_light_lock", "take_retake"):
- el = extract_element(name, form)
- self.assertIn('type="hidden"', el)
- self.assertIn(f'name="{name}"', el)
- self.assertIn('value="on"', el)
- # ...and the fields they sit beside, so FormData posts the whole shot.
- for name in ("take_seconds", "beats", "image"):
- self.assertIn(f'name="{name}"', form)
-
- def test_the_old_name_is_gone_from_everything_a_user_reads(self):
- stray = []
- files = [ROOT / "webapp" / "index.html", ROOT / "docs" / "PROMPTING.md",
- *sorted((ROOT / "webapp" / "js").glob("*.js"))]
- for f in files:
- for i, line in enumerate(f.read_text(encoding="utf-8").splitlines(), 1):
- if re.search(r"\bone[ -]take\b", line, re.I):
- stray.append(f"{f.name}:{i}: {line.strip()[:80]}")
- self.assertEqual(stray, [], "the feature is called One Shot")
-
- # ---- the executed contract ----------------------------------------------
- def test_a_fresh_page_carries_no_take(self):
- self.assertEqual(self.r["start"], {"mode": "t2v", "take": "0", "panelHidden": True})
-
- def test_entering_the_mode_opens_the_panel_on_t2v_with_a_length(self):
- e = self.r["enter"]
- self.assertEqual(e["currentMode"], "oneshot")
- self.assertEqual(e["mode"], "t2v")
- self.assertEqual(e["take"], "60")
- self.assertFalse(e["panelHidden"])
- self.assertFalse(e["beatsRowHidden"])
- self.assertTrue(e["bodyClass"])
- self.assertEqual(e["chips"], ["oneshot"])
- self.assertEqual(e["takeChips"], ["60"])
- self.assertIn("never cuts", e["placeholder"])
- self.assertEqual(e["refreshed"], ["60"], "the estimate is asked for on entry")
-
- def test_the_beats_prefill_from_the_prompt_on_entry(self):
- e = self.r["enter"]
- self.assertEqual(json.loads(e["beats"])[:3],
- ["She pushes off down the avenue.", "A van sweeps past.", "She drops off the kerb."])
- self.assertIn("12 lines of 5 s", e["beatsHint"])
- self.assertIn("3 written", e["beatsHint"])
- self.assertIn("leave a line blank to hold on the scene", e["beatsHint"])
- self.assertNotIn("beats of", e["beatsHint"])
-
- def test_the_toggles_default_on_and_write_on_off(self):
- e = self.r["enter"]
- self.assertEqual((e["light"], e["retake"]), ("on", "on"))
- self.assertEqual((e["lightChips"], e["retakeChips"]), (["on"], ["on"]))
- t = self.r["toggledOff"]
- self.assertEqual((t["light"], t["retake"]), ("off", "off"))
- self.assertEqual((t["lightChips"], t["retakeChips"]), (["off"], ["off"]))
- self.assertEqual(self.r["toggledBack"], {"light": "on", "retake": "on"})
-
- def test_parts_are_10s_on_ltx_and_15s_on_h3(self):
- # One line per chip — "3 × 10 s", not "3 PARTS OF 10 S" wrapping to a
- # 95px chip — so the strip keeps the Quality strip's height.
- self.assertEqual(self.r["enter"]["parts"],
- ["3 × 10 s", "5 × 10 s", "6 × 10 s", "9 × 10 s", "12 × 10 s"])
- self.assertEqual(self.r["enter"]["note"], "LTX — 10-second parts that continue from the last frame.")
- self.assertEqual(self.r["h3"]["parts"],
- ["2 × 15 s", "3 × 15 s", "4 × 15 s", "6 × 15 s", "8 × 15 s"])
- self.assertEqual(self.r["h3"]["note"], "Hailuo H3 — 15-second parts that continue from each other.")
- self.assertNotIn("proven", self.r["h3"]["note"])
-
- def test_the_footer_strip_says_the_shot_not_a_five_second_clip(self):
- s = self.r["summary"]
- self.assertEqual(s["ltx60"], "1 min · 6 parts of 10 s")
- self.assertEqual(s["h3_90"], "1½ min · 6 parts of 15 s")
- self.assertEqual(s["ltx30"], "30 s · 3 parts of 10 s")
- self.assertEqual(s["ltx120"], "2 min · 12 parts of 10 s")
- self.assertEqual(s["off"], "", "no shot, no summary — the clip line stays")
- self.assertEqual(s["labels"], ["30 s", "45 s", "1 min", "1½ min", "2 min"])
- fn = extract_function("updateDerived", self.src)
- self.assertIn("oneshotSummary", fn)
- self.assertIn("take_seconds", fn)
- self.assertLess(fn.index("derivedFooter"), fn.index("oneshotSummary"),
- "the summary is the FOOTER strip's line")
-
- def test_an_engine_round_trip_leaves_the_folded_ltx_length_alone(self):
- r = self.r["restored"]
- self.assertTrue(r["ok"])
- self.assertEqual((r["frames"], r["duration"]), ("241", "10.00"))
- fn = extract_function("setEngine", self.src)
- self.assertIn("restoreFoldedLtxLength", fn)
- # The snap from H3's 17n+5 grid is what wrote "3s" onto the folded
- # strip; in One Shot the restore runs INSTEAD of it, not after it.
- i = fn.index("currentMode === 'oneshot'")
- self.assertLess(i, fn.index("snapFramesTo8kPlus1();"))
- self.assertIn("setTakeSeconds", fn, "the mode's own state is re-asserted after the swap")
-
- def test_an_anchor_image_makes_it_i2v_and_clearing_it_makes_it_t2v(self):
- a = self.r["anchored"]
- self.assertEqual(a["mode"], "i2v")
- self.assertFalse(a["thumbHidden"])
- self.assertIn("frame_one.png", a["thumbSrc"])
- self.assertFalse(a["clearHidden"])
- self.assertEqual(a["name"], "frame_one.png")
- self.assertEqual(self.r["unanchored"], {"mode": "t2v", "thumbHidden": True, "clearHidden": True})
- self.assertEqual(self.r["enterAnchored"], {"mode": "i2v", "take": "120"},
- "the remembered length, not the default")
-
- def test_a_length_chip_and_the_write_the_beats_button(self):
- self.assertEqual(self.r["len120"]["take"], "120")
- self.assertEqual(self.r["len120"]["takeChips"], ["120"])
- self.assertEqual(json.loads(self.r["len120"]["beats"]), ["only one line"])
- self.assertEqual(self.r["prefilled"]["lines"], 3)
-
- def test_leaving_the_mode_zeroes_the_take_and_folds_the_panel(self):
- for key in ("leave", "leaveViaCharacter", "leaveToImage"):
- l = self.r[key]
- self.assertEqual(l["take"], "0", key)
- self.assertTrue(l["panelHidden"], key)
- l = self.r["leave"]
- self.assertEqual(l["currentMode"], "t2v")
- self.assertEqual(l["mode"], "t2v")
- self.assertEqual(l["beats"], "")
- self.assertFalse(l["bodyClass"])
- self.assertEqual(l["chips"], ["t2v"])
- self.assertEqual(self.r["leaveViaCharacter"]["currentMode"], "character")
- self.assertEqual(self.r["leaveToImage"]["mode"], "i2v")
-
- def test_leaving_the_mode_puts_the_continuity_fields_back_to_on(self):
- # Both were switched OFF before leaving. They are hidden inputs in the
- # video form, so FormData posts them with every clip — a normal clip
- # must not carry an "off" from a mode it is not in.
- l = self.r["leave"]
- self.assertEqual((l["light"], l["retake"]), ("on", "on"))
- self.assertEqual((l["lightChips"], l["retakeChips"]), (["on"], ["on"]))
-
- def test_the_length_is_remembered_across_leaving_and_re_entering(self):
- # 120 was chosen, the mode was left (take → 0) and re-entered: the
- # panel reopens on 2 min, not on the 1 min default.
- self.assertEqual(self.r["reenter"], {"take": "120", "panelHidden": False, "takeChips": ["120"]})
-
- # ---- the copy -----------------------------------------------------------
- def _panel_text(self):
- panel = self.html[self.html.index('id="takeAxes"'):]
- panel = panel[:panel.index('id="takeEngineNote"')]
- panel = re.sub(r"<!--.*?-->", " ", panel, flags=re.S)
- return re.sub(r"<[^>]+>", " ", panel)
+ for name in ("take_seconds", "beats", "take_light_lock", "take_retake", "take_camera"):
+ self.assertNotIn(f'name="{name}"', form, name)
+ self.assertNotIn('id="takeAxes"', self.html)
+
+ def test_the_section_has_its_fields_and_its_module(self):
+ sec = self.html[self.html.index('id="oneshotSectionTab"'):]
+ sec = sec[:sec.index('id="audioSectionTab"')]
+ for needed in ('id="osEngineGroup"', 'id="osPrompt"', 'id="osAnchorFile"', 'id="osCharacterGroup"',
+ 'id="osLengthGroup"', 'id="osQualityGroup"', 'id="osEstimate"', 'id="osBeats"',
+ 'id="osCharacterNote"', 'id="osBeatsHint"', 'id="osSplitBtn"', 'id="osPlanBtn"', 'id="osCamera"',
+ 'data-os-toggle="light"', 'data-os-toggle="retake"', 'data-os-toggle="handoff"',
+ 'id="osSeed"', 'id="osGenBtn"', 'id="osStatus"', 'id="osParts"', 'href="/docs/prompting"'):
+ self.assertIn(needed, sec, needed)
+ self.assertIn('<script type="module" src="/webapp/js/oneshot.js"></script>', self.html)
+ tags = re.findall(r'<script type="module" src="/webapp/js/([\w.-]+)\.js"></script>', self.html)
+ self.assertEqual(tags[-1], "main", "main.js stays the last module")
+ self.assertIn("oneshot", tags)
def test_the_word_take_is_not_in_anything_a_user_reads(self):
- text = self._panel_text()
- self.assertFalse(re.search(r"\b(re)?takes?\b", text, re.I), text)
- for fn in ("beatsInput", "oneshotRefreshLabels", "takeRefresh", "oneshotSummary", "takeLengthLabel"):
- body = extract_function(fn, self.src)
- strings = re.findall(r"""(['"`])((?:(?!\1).)*)\1""", body)
- for _, lit in strings:
- if lit[:1] in "./#": # a selector, an id or a URL — not copy
- continue
- self.assertFalse(re.search(r"\b(re)?takes?\b", lit, re.I), f"{fn}: {lit}")
-
- def test_the_panel_copy(self):
- text = " ".join(self._panel_text().split())
- for needed in ("Start frame", "optional · the shot starts from this picture",
- "Split my prompt into beats",
- "one line per 5 seconds — what happens in that moment",
- "Lock the light", "keeps the time of day and weather the same in every line",
- "Redo a part that drifts", "if a part changes the light, it is rendered once more"):
- self.assertIn(needed, text, needed)
- for gone in ("Anchor image", "Write the beats for me", "Retake", "holds the moment"):
- self.assertNotIn(gone, text, gone)
- # The split button lives in the Beats label row, not on a row of its own.
- row = self.html[self.html.index('id="beatsRow"'):self.html.index('id="beats_text"')]
- self.assertIn('id="beatsPrefillBtn"', row)
- self.assertNotIn("beats-tools", self.html)
- # The hint counter and the overflow line, executed.
- self.assertIn("extra line", extract_function("beatsInput", self.src))
- self.assertIn("will be dropped", extract_function("beatsInput", self.src))
-
- def test_the_storyboard_names_it_one_shot(self):
- chip = re.search(r'<button[^>]*data-sb-shots="take"[^>]*>(.*?)</button>', self.html, re.S).group(1)
- self.assertIn(">One Shot<", chip)
- row = self.html[self.html.index('id="sbTakeRow"'):self.html.index('id="sbTakeGroup"')]
- self.assertIn("One Shot length", row)
- self.assertNotIn("How long", row)
- # ...and the row really folds: .cz-control sets a display of its own.
- css = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")
- self.assertRegex(css, r"\.cz-control\[hidden\]\s*\{\s*display:\s*none\s*!important;?\s*\}")
-
- def test_the_leave_hook_runs_before_every_early_return(self):
- fn = extract_function("setMode", self.src)
- self.assertLess(fn.index("oneshotLeave"), fn.index("if (mode === 'train')"))
- self.assertLess(fn.index("oneshotLeave"), fn.index("if (mode === 'character')"))
- self.assertLess(fn.index("oneshotLeave"), fn.index("if (mode === 'image')"))
-
- def test_load_params_reopens_a_one_shot_from_its_sidecar(self):
- fn = extract_function("loadParams", self.src)
- self.assertIn("setMode('oneshot')", fn)
- self.assertLess(fn.index("setMode('oneshot')"), fn.index("setMode('extend')"))
- self.assertIn("setTakeLightLock", fn)
- self.assertIn("setTakeRetake", fn)
-
- def test_the_engine_switch_refreshes_the_part_labels(self):
- fn = extract_function("setEngine", self.src)
- self.assertIn("oneshotRefreshLabels", fn)
- self.assertIn("takeRefresh", fn)
-
- def test_both_engines_serve_the_mode(self):
- fn = extract_function("engineServesMode", self.src)
- self.assertIn("mode === 'oneshot'", fn)
-
-
-if __name__ == "__main__":
- unittest.main(verbosity=2)
+ sec = self.html[self.html.index('id="oneshotSectionTab"'):]
+ sec = sec[:sec.index('id="audioSectionTab"')]
+ text = re.sub(r"<!--.*?-->", "", sec, flags=re.S)
+ text = re.sub(r"<[^>]+>", " ", text)
+ self.assertNotRegex(text, r"\btake\b", "the user reads 'one shot', never 'take'")
+
+ # ---- the module, run -----------------------------------------------------
+ def test_entering_the_tab_is_one_minute_on_ltx_with_nothing_written(self):
+ e = self.r["enter"]
+ self.assertEqual((e["engine"], e["seconds"], e["quality"]), ("ltx", 60, "balanced"))
+ self.assertEqual(e["lengths"], ["30", "45", "60", "90", "120"])
+ self.assertEqual(e["activeLength"], ["60"])
+ self.assertEqual(e["parts"], ["3 × 10 s", "4 × 10 s + 5 s", "6 × 10 s", "9 × 10 s", "12 × 10 s"])
+ self.assertEqual(e["qualities"], ["quick", "balanced", "standard", "high"])
+ self.assertEqual(e["characters"], ["", "bizarrotrn"])
+ self.assertEqual(e["beats"], [])
+ self.assertIn("the prompt carries the whole shot", e["beatsHint"])
+ self.assertEqual((e["rows"], e["first"]), (12, "0:00"))
+ self.assertEqual((e["handoff"], e["handoffChips"]), ("last", ["last"]))
+ self.assertIn("1 min", e["summary"]); self.assertIn("6 parts of 10 s", e["summary"])
+ self.assertEqual(self.r["len45"]["chip"], "4 × 10 s + 5 s")
+ self.assertIn("4 × 10 s + 5 s", self.r["len45"]["summary"])
+ self.assertFalse(e["characterBlockHidden"])
+
+ def test_one_paragraph_is_a_complete_document(self):
+ d = self.r["docPromptOnly"]
+ self.assertEqual(d["prompt"], "A hen skates down Broadway at night.")
+ self.assertEqual((d["seconds"], d["engine"], d["quality"]), (60, "ltx", "balanced"))
+ self.assertNotIn("beats", d); self.assertNotIn("character_id", d); self.assertNotIn("image", d)
+ self.assertEqual((d["light_lock"], d["retake"], d["handoff"]), ("on", "on", "last"))
+
+ def test_the_rows_and_the_hint_follow_the_length_and_the_lines(self):
+ self.assertEqual(self.r["len30"]["rows"], 6)
+ self.assertEqual(self.r["len30"]["activeLength"], ["30"])
+ b = self.r["beats"]
+ self.assertIn("6 lines of 5 s", b["hint"]); self.assertIn("7 written", b["hint"])
+ self.assertIn("2 rows past the end will be dropped", b["hint"])
+ self.assertEqual((b["rows"], b["over"]), (8, 2))
+ self.assertEqual(b["values"], ["she pushes off", "", "a van sweeps past", "1", "2", "3", "4", "5"])
+ self.assertEqual(b["doc"], ["she pushes off", "", "a van sweeps past", "1", "2", "3", "4", "5"])
+ self.assertEqual(self.r["split"], ["She pushes off.", "A van sweeps past!", "Pigeons burst up?", "Then nothing."])
+
+ def test_a_character_turns_the_handoff_on_and_the_user_can_turn_it_back(self):
+ c = self.r["character"]
+ self.assertEqual((c["handoff"], c["handoffChips"], c["quality"]), ("speech", ["speech"], "pro"))
+ self.assertEqual(c["qualities"], ["draft", "pro", "high", "high_720p"])
+ self.assertEqual((c["doc"]["character_id"], c["doc"]["handoff"], c["doc"]["quality"]), ("bizarrotrn", "speech", "pro"))
+ self.assertEqual(self.r["handoffKept"], "last")
+
+ def test_h3_is_fifteen_second_parts_without_a_character(self):
+ h = self.r["h3"]
+ self.assertEqual(h["parts"], ["2 × 15 s", "3 × 15 s", "4 × 15 s", "6 × 15 s", "8 × 15 s"])
+ self.assertEqual(h["qualities"], ["draft", "standard", "high", "native"])
+ self.assertEqual(h["quality"], "standard")
+ self.assertTrue(h["characterBlockHidden"]); self.assertTrue(h["handoffRowHidden"])
+ self.assertEqual(h["doc"]["engine"], "h3"); self.assertNotIn("character_id", h["doc"])
+ c = self.r["h3Cleared"]
+ self.assertEqual((c["character"], c["handoff"]), ("", "last"))
+ self.assertNotIn("character_id", c["doc"])
+
+ def test_load_params_rebuilds_the_document_and_opens_the_tab(self):
+ l = self.r["loaded"]
+ self.assertEqual((l["engine"], l["seconds"], l["prompt"]), ("ltx", 90, "the tram"))
+ self.assertEqual(l["beats"], ["a", "", "c"])
+ self.assertEqual((l["camera"], l["handoff"], l["light"], l["retake"]), ("a slow push in", "speech", "off", "off"))
+ self.assertEqual((l["character"], l["seed"]), ("bizarrotrn", "4242"))
+ self.assertEqual(l["switched"][-1], "oneshot")
+
+ def test_the_status_strip_names_the_part_and_the_verdict(self):
+ self.assertEqual(self.r["verdicts"], ["ok", "mid", "bad", "quiet"])
+ s = self.r["status"]
+ self.assertFalse(s["hidden"])
+ self.assertIn("Rendering", s["title"]); self.assertIn("tram", s["title"])
+ self.assertIn("part 2 of 3", s["meta"])
+ self.assertEqual(len(re.findall(r'class="os-part ', s["partsHtml"])), 3)
+ self.assertIn("voice on the mouth (+0.40)", s["partsHtml"]); self.assertIn("part 2 · rendering", s["partsHtml"])
+ self.assertIn("lip-sync +0.40", s["log"]); self.assertNotIn("[take]", s["log"])
+ 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"])
diff --git a/test_storyboard_lipsync_gate.py b/test_storyboard_lipsync_gate.py
new file mode 100644
index 0000000..f970d14
--- /dev/null
+++ b/test_storyboard_lipsync_gate.py
@@ -0,0 +1,120 @@
+"""A board shot with a spoken line is scored and retaken the way a One Shot
+part is, and only then.
+
+The Storyboard rendered a spoken shot once and kept whatever came out; the
+owner's twelve-shot sitcom shipped shots at -0.06 next to shots at +0.33 on the
+panel's own scorer (2026-09-10). `sb_lipsync_retake_plan` is the pure decision;
+this pins what it retakes, what it leaves alone, and the seed it hands out.
+"""
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+
+
+class RetakePlan(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ tmp = tempfile.mkdtemp(prefix="phos_lipsync_")
+ os.environ["LTX_STATE_DIR"] = tmp
+ os.environ["LTX_OUTPUT_DIR"] = os.path.join(tmp, "out")
+ os.environ["LTX_UPLOADS_DIR"] = os.path.join(tmp, "up")
+ os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"
+ os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"
+ os.makedirs(os.environ["LTX_OUTPUT_DIR"], exist_ok=True)
+ os.makedirs(os.environ["LTX_UPLOADS_DIR"], exist_ok=True)
+ sys.path.insert(0, str(ROOT))
+ import mlx_ltx_panel as p
+ cls.p = p
+
+ def _shot(self, n, prompt, seed=100):
+ return {"n": n, "prompt": prompt, "seed": seed}
+
+ def test_a_spoken_shot_under_the_floor_is_retaken_with_a_fresh_seed(self):
+ p = self.p
+ shots = [self._shot(4, "George says: <d>[English] I thought it was ashwagandha!</d>", seed=4204)]
+ plan = p.sb_lipsync_retake_plan(shots, {4: -0.01}, {})
+ self.assertEqual(plan, [(4, 4204 + 211)])
+
+ def test_a_shot_that_syncs_is_left_alone(self):
+ p = self.p
+ shots = [self._shot(2, "George says: <d>[English] I saw everything.</d>")]
+ self.assertEqual(p.sb_lipsync_retake_plan(shots, {2: 0.32}, {}), [])
+
+ def test_a_shot_with_no_line_is_never_retaken(self):
+ p = self.p
+ shots = [self._shot(12, "The door bursts open and a tall man slides in, arms out.")]
+ self.assertEqual(p.sb_lipsync_retake_plan(shots, {12: -0.3}, {}), [])
+
+ def test_no_score_means_nothing_to_judge(self):
+ p = self.p
+ shots = [self._shot(6, "He says: <d>[English] Hi.</d>")]
+ self.assertEqual(p.sb_lipsync_retake_plan(shots, {6: None}, {}), [])
+
+ def test_retakes_stop_at_the_limit_and_seeds_keep_moving(self):
+ p = self.p
+ shots = [self._shot(9, "He whispers: <d>[English] This is not ashwagandha.</d>", seed=10)]
+ self.assertEqual(p.sb_lipsync_retake_plan(shots, {9: 0.05}, {9: 1}), [(9, 10 + 422)])
+ self.assertEqual(p.sb_lipsync_retake_plan(shots, {9: 0.05}, {9: p.TAKE_LIPSYNC_RETAKES}), [])
+
+ def test_the_ltx_quote_form_counts_as_a_line_too(self):
+ p = self.p
+ shots = [self._shot(3, "She looks up and says 'It was a tea ceremony, George.'", seed=7)]
+ self.assertEqual(p.sb_lipsync_retake_plan(shots, {3: 0.1}, {}), [(3, 218)])
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+class KeptTakeSurvivesReconcile(unittest.TestCase):
+ """The gate's choice must be the board's choice. The shot's job id and seed
+ follow the KEPT take, so the next reconcile (which repoints outputs at the
+ job the shot names) agrees with the gate instead of undoing it."""
+
+ def test_kept_take_job_and_seed_travel_with_it(self):
+ p = RetakePlan.p if hasattr(RetakePlan, "p") else None
+ if p is None:
+ import mlx_ltx_panel as p
+ import storyboard
+ tmp = Path(tempfile.mkdtemp(prefix="phos_gate_"))
+ files = {}
+ for name in ("a", "b", "c"):
+ f = tmp / f"take_{name}.mp4"; f.write_bytes(b"x"); files[name] = str(f)
+ board = {"id": "sb_test_gate", "title": "t", "shots": [
+ {"n": 9, "mode": "text", "engine": "h3", "duration_s": 5, "seed": 100, "status": "done",
+ "prompt": "He whispers: <d>[English] This is not ashwagandha.</d>",
+ "final_job_id": "j1", "final_output": files["a"]}]}
+ storyboard.save_storyboard(p.STATE_DIR, board)
+ scores = {files["a"]: -0.35, files["b"]: -0.09, files["c"]: -0.27}
+ queued, jobs = [], {"j1": {"status": "done", "output_path": files["a"]}}
+ def fake_enqueue(form):
+ jid = f"j{len(queued) + 2}"; queued.append((jid, int(form["seed"])))
+ jobs[jid] = {"status": "done", "output_path": files["b" if jid == "j2" else "c"]}
+ return jid
+ saved = {k: getattr(p, k) for k in ("take_lipsync_score", "_sb_enqueue", "_sb_job_index", "set_hidden", "push")}
+ try:
+ p.take_lipsync_score = lambda path: scores.get(str(path))
+ p._sb_enqueue = fake_enqueue
+ p._sb_job_index = lambda: dict(jobs)
+ p.set_hidden = lambda path, hidden: None
+ p.push = lambda line: None
+ p._sb_lipsync_gate("sb_test_gate", board["shots"], "final_job_id", "final_output",
+ {"quality": "standard", "width": 1024, "height": 576}, False, False,
+ lambda ids: True)
+ after = storyboard.load_storyboard(p.STATE_DIR, "sb_test_gate")
+ shot = after["shots"][0]
+ self.assertEqual(shot["final_output"], files["b"])
+ self.assertEqual(shot["final_job_id"], "j2")
+ self.assertEqual(shot["seed"], queued[0][1])
+ self.assertEqual(shot["lipsync"]["kept"], files["b"])
+ self.assertEqual(shot["lipsync"]["attempts"], 2)
+ # and the reconcile that runs on every status poll leaves it alone
+ p._sb_reconcile(after)
+ self.assertEqual(after["shots"][0]["final_output"], files["b"])
+ finally:
+ for k, v in saved.items():
+ setattr(p, k, v)
diff --git a/webapp/docs/audio.md b/webapp/docs/audio.md
new file mode 100644
index 0000000..0bf9668
--- /dev/null
+++ b/webapp/docs/audio.md
@@ -0,0 +1,16 @@
+# Audio
+
+The Audio tab makes a **video driven by a sound file you bring** — a voice line, a song. The sound steers the picture while it is generated (it is not laid on afterwards), so a mouth moves to the words and motion follows the music. It does not make sound from text; for that, describe the sound in any Video prompt.
+
+## Making one {#make}
+
+1. Drop the **Audio** — WAV, MP3, M4A or FLAC.
+2. Optional: a **Reference image** to open the clip on that frame — a portrait for a talking head. Leave it empty for pure audio-to-video.
+3. Write the prompt. **Enhance** rewrites it for the model.
+4. Set **Width** and **Height** (default 1024×576), **Audio start** (seconds into the file, e.g. 30 to drive the clip from 0:30) and **Duration** (1–30 s, default 7).
+5. **Audio conditioning strength** (0.5–5.0, default 1.0): higher holds the picture to the audio more tightly and leaves it less free.
+6. **Generate**.
+
+> **Tip** Some seeds do not take — if the mouth does not move, retry with a new seed. A large canvas with a long duration is a very long render; the tab warns you and suggests a smaller size.
+
+Audio always renders on LTX: on the High (Q8) pipeline when it is installed, otherwise on the fast pipeline.
diff --git a/webapp/docs/buttons.md b/webapp/docs/buttons.md
new file mode 100644
index 0000000..f9542dd
--- /dev/null
+++ b/webapp/docs/buttons.md
@@ -0,0 +1,74 @@
+# Buttons and icons
+
+The buttons that show a picture instead of a word. Hover any of them in the panel for its tooltip.
+
+## The header {#header}
+
+| Button | What it does |
+|---|---|
+| **LTX · 2.5** (engine switch) | chooses the engine that renders — LTX or Hailuo H3 |
+| the health chip (a coloured dot and a memory reading) | opens the machine's state: Tier, Memory, Helper, Models, Queue, Render. Green is fine, yellow needs a look, red is blocking |
+| the version pill | **Up to date**, **Update to …** (click to update), or **Restart Phosphene** (click to restart onto the new code) |
+| the bug | **Report a bug** — a GitHub issue pre-filled with your version and log |
+| [[icon:ph-gear-six]] | Settings |
+| [[icon:ph-book-open]] **Docs** | these docs ([[sc:docs.open]] opens them on the shortcuts page) |
+| [[icon:ph-star]] | star Phosphene on GitHub |
+| the X mark | the official @PhospheneAI account on X |
+
+## The player {#player}
+
+| Button | What it does |
+|---|---|
+| **Params** | the settings the selected output was made with |
+| **Extend** · **LTX Upscale** · **To film** · **Animate** | use the selected output as the start of something new |
+| the crossed-out eye (red) | hides this output from the gallery — the file is not deleted |
+| **Expand** | full screen ([[sc:outputs.expand]]; Esc closes it) |
+
+## Output cards {#cards}
+
+| Button | What it does |
+|---|---|
+| **ⓘ** | how this output was made — prompt, engine, quality, seed, LoRAs |
+| [[icon:ph-trash-simple]] | moves the file to the macOS Trash, after asking ([[sc:outputs.trash]] on the selected output) |
+| [[icon:ph-folder-simple]] (Outputs header) | reveals the outputs folder in Finder |
+
+## The queue and the Now card {#queue}
+
+| Button | What it does |
+|---|---|
+| **×** on a queued job | removes it from the queue |
+| **×** on a failed or stopped card | dismisses the message |
+| **Stop** (under Generate) | stops the render in progress |
+| **Stop early** (on the live preview) | stops it after asking — nothing is saved, the queue carries on |
+
+## The Editor {#editor}
+
+| Button | What it does |
+|---|---|
+| 🔊 | mutes the preview only — the film is not changed ([[sc:editor.mute]]) |
+| **▾** beside Render | Deliver as (format, size, finish) and **Export for Premiere / Resolve / AE** |
+| **⋯** | Drafts and versions, Media pool, Auto-edit, Storyboard, Close |
+| **i** | the preview is approximate at cuts; the render is exact |
+| **Keys** | every key and gesture the timeline answers to |
+| **+** on a media pool row | puts the clip at the end of the sequence |
+| **▣** on a still | lays it over the picture at the playhead (the overlay lane) |
+| the +0.25s label on a sound strip | the sound is that far out of sync — click it to put it back |
+
+## Characters and LoRAs {#loras}
+
+| Button | What it does |
+|---|---|
+| [[icon:ph-pencil-simple]] on the character strip | rename or delete characters |
+| [[icon:ph-arrow-clockwise-bold]] on the character strip | rescan for new characters |
+| [[icon:ph-pencil-simple]] on a LoRA | rename it (display name only) |
+| [[icon:ph-download-simple]] on a LoRA | download the file — or, when marked **Update**, its newer version |
+| [[icon:ph-arrow-square-out]] on a LoRA | open its page on CivitAI |
+| [[icon:ph-x-bold]] on a LoRA | delete it from disk (asks first) |
+
+## Storyboard cards {#storyboard}
+
+| Button | What it does |
+|---|---|
+| **↑ / ↓** | move the shot earlier or later |
+| the dice | a new seed for this shot |
+| **✕** | delete the shot |
diff --git a/webapp/docs/editor.md b/webapp/docs/editor.md
new file mode 100644
index 0000000..6474d35
--- /dev/null
+++ b/webapp/docs/editor.md
@@ -0,0 +1,209 @@
+# Editor
+
+The Editor is a timeline for the clips you make — from any engine, from a storyboard or from nothing. Trim and split, move sound for J-cuts and L-cuts, add music, titles and transitions, then render one file or hand the cut to Premiere, Resolve or After Effects.
+
+## Opening a timeline {#open}
+
+- On the **Editor** tab, *Pick a sequence to cut* lists every sequence that has clips — click one.
+- From **Storyboard**: step **3 Edit**, **Open in Editor** on the board list, or **Re-cut in the Editor** on the film screen.
+- The last timeline you had open comes back when you return to the tab. Switching to another tab does not close it; **⋯ → Close** does (nothing is deleted).
+- A new, empty or copied version of a sequence is a draft — see [Saving, drafts and versions](#docs/editor/saving).
+
+## 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 media pool** (left) — **This Sequence**, **Other sequences**, **Generations** and **Images**. 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. **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 tracks**, top to bottom:
+
+| Track | What is on it |
+|---|---|
+| **V2 Overlay** | titles and cards laid over the picture |
+| **V1 Picture** | the shots, in order |
+| **A1 Clip sound** | each shot's own sound |
+| **A2 Music** | the soundtrack |
+
+**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.
+
+## Selecting {#selecting}
+
+- **Click** a clip to select it. Click an empty part of the track to select nothing (and move the playhead there).
+- **⇧-click** selects the range from the selected clip to this one. **⌘-click** adds one clip or drops it.
+- [[sc:editor.selectAll]] selects every clip. [[sc:editor.deselect]] clears the selection — and with nothing selected, closes the timeline.
+- With several clips selected, the clip bar acts on **all** of them, as one undo step; the inspector shows the properties of the one you clicked last. A locked clip in the selection is left alone and named in a message.
+
+## Moving, trimming and splitting {#moving}
+
+- **Drag** a clip to move it. Drag a selected clip and the whole selection moves together, sound included.
+- **Drag the edge** of a clip to trim it. **⌘ while dragging** ripples: everything after it slides too.
+- Clips snap to the beat grid while **Snap to beat** is ticked ([[sc:editor.snap]] toggles it). **⌥ while dragging** ignores the grid for that drag. Sound strips and overlays snap to cuts.
+- **⌥⇧-drag** reorders instead of moving; right-click → **Move earlier** / **Move later** swaps a shot with its neighbour.
+- [[sc:editor.nudge]] nudges the selection one frame (with ⇧, ten).
+- **Split** ([[sc:editor.split]]) cuts the shot under the **playhead** — not the selection — into two.
+
+## 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*).
+
+Every button is always there. When it cannot act, it is greyed out and its tooltip says what would make it work.
+
+| Button | What it does | Greyed out when |
+|---|---|---|
+| **Split** [[sc:editor.split]] | cuts the shot under the playhead in two at the playhead; nothing moves, nothing is lost | the playhead is not over a shot, is exactly on a cut, or the shot is locked |
+| **Lift** [[sc:editor.lift]] | takes the selection out and **leaves the hole** as black, so nothing after it moves | nothing is selected |
+| **Ripple delete** [[sc:editor.ripple]] | takes the selection out and **closes the gap** — everything after slides earlier and the film gets shorter | nothing is selected |
+| **Duplicate** [[sc:editor.duplicate]] | the same shot again right after itself — trim, speed, fades and grade included; everything after slides | nothing is selected |
+| **Unlink sound** / **Link sound** / **Re-link sound** [[sc:editor.link]] | frees the sound from its picture so you can slide it (the J-cut and the L-cut). **Link sound** keeps the offset you made and makes the pair travel together; **Re-link sound** appears when the sound is back exactly under its picture | the selection is a still or black, which has no sound |
+| **Resync sound** [[sc:editor.resync]] | slides the sound back to where its own picture plays it. Your trim is kept and it stays unlinked | the sound is still linked (so it cannot be out of sync), the clip has no sound, or it is already in sync |
+| **Mute sound** / **Unmute sound** | switches this clip's own sound off — in the preview, the render and the export. The strip stays; the music is not affected | the clip has no sound |
+| **Delete sound** | removes the clip's sound; the picture keeps playing, silent. Undo brings it back | the sound is still linked — unlink it first |
+| **Clear points** | deletes the level points (the dots on the yellow line) from the selected strips. Fades are left alone | the sound has no level points |
+| **Lock** / **Unlock** | pins a shot to its place — everything else flows around it, and it cannot be dragged or trimmed | nothing is selected |
+
+When the pane is too narrow, the last buttons move into **More ▾**. **Right-click** a clip for the same actions at the pointer; right-click a hole for **Close this hole** and **Generate a shot here…**.
+
+## 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:
+
+- **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.
+- **Effects** — **Brightness** (−0.5 to +0.5, **Reset**), picture **Fade in** / **Fade out** (**Clear**), and **Zoom** (1× to 3×, **Reset**) with **Across** and **Down** to reframe the zoomed picture.
+
+Select the mark between two clips and the inspector shows the **Transition**; select a title and it shows the **Text**.
+
+## Sound {#sound}
+
+### Linked and unlinked {#linked}
+
+A clip's sound starts **linked**: it moves with its picture, shows dimmer, and cannot be dragged on its own. **Unlink sound** frees it. An unlinked strip can be dragged, trimmed at either end, faded at its corners and shaped with level points — and it can drift out of sync, which is what Resync is for.
+
+### J-cuts and L-cuts {#j-cut}
+
+A **J-cut** starts the next shot's sound before its picture; an **L-cut** lets a shot's sound run on under the next picture. Both are made the same way: unlink the sound, drag or trim the strip under the neighbouring shot, then **Link sound** to keep that offset.
+
+### When sound drifts: Resync {#resync}
+
+An unlinked strip that is not under its own picture shows a label with the offset, such as **+0.25s**. Click the label, or select the clip and press **Resync sound** ([[sc:editor.resync]]), to slide it back. It stays unlinked, so you can move it again.
+
+### Muting {#mute}
+
+- **Mute sound** on the clip bar is a decision about the film: that clip is silent in the preview, the render and the export.
+- 🔊 in the transport ([[sc:editor.mute]]) only silences what you hear while editing. The film is not changed.
+
+### Level points and fades {#levels}
+
+On an **unlinked** strip:
+
+- Drag a strip's **corner handle** inward for a fade.
+- **Click the yellow line** to add a level point, and drag it up or down to set the level. Double-clicking the strip adds one too, and **Add point at playhead** in the inspector puts one exactly there.
+- **⇧-click** or **right-click** a point to remove it; **Clear points** removes them all.
+
+### The music track {#music}
+
+- Open **▾** on the **A2 Music** head, give the soundtrack's path or **Change…**, then **Prepare**: it builds the waveform and finds the beat, which gives the timeline its beat grid.
+- The mode menu: **under the clips** mixes the music under the clips' own sound; **replaces clip sound** uses the music alone — any dialogue in the clips is lost.
+- **Level** sets the music's volume, 0–100%.
+- **Duck under dialogue** (off by default) steps the music back wherever a clip's own sound is playing. If you have drawn your own fades or level points on the music, they drive it instead, and the head says *"off — your own level line is driving the bed"*.
+- The music strip drags, trims, fades and takes level points exactly like a clip's sound.
+
+## 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.
+- **A card** — press **▣** on a still in the media pool to lay it over the picture at the playhead. A black background is removed automatically; **Keep original** puts it back.
+- **Black** — **Add black** appends a black clip; **Lift** leaves one where a shot was.
+
+### Holes {#holes}
+
+A **hole** is empty space on the picture track — made by dragging a clip away from its neighbour. It shows its length and **fill it**. Click it to open *Fill this hole*: write the shot, choose **Length** and **Pass** (Draft or Delivery), and **Queue the shot**. When it lands, it waits under *Rendered but not on the timeline* — press **Place**.
+
+> **Holes close when you render.** The render joins shots end to end, so a hole closes up and everything after it moves earlier. Render asks before it does that. Use black if you want the gap kept.
+
+## Transitions {#transitions}
+
+1. Click the mark between two clips.
+2. In the inspector, choose **Kind**: **None — a hard cut**, **Dissolve** or **Fade through black**, and a **Length** (up to 2 seconds, and no more than half the shorter clip).
+3. **Remove** takes it off again ([[sc:editor.removeTransition]] with the cut selected).
+
+A transition borrows extra picture from beyond each clip's trim, so the cut does not move and neither does the sound. If a clip has no picture to spare, the transition is refused with a message saying which side is short — trim that clip in, or shorten the transition. The preview only approximates a dissolve; the render is exact.
+
+## Saving, drafts and versions {#saving}
+
+- **Save** ([[sc:editor.save]]) is the only thing that writes your draft. The button lights up when there are unsaved changes. Between saves your edits are kept as a backup, and when one is newer than your last save the Editor offers it as an *unsaved snapshot* — **Restore it**, **Discard** or **Later**.
+- If saving keeps failing, a red bar says *SAVING IS FAILING* with **Try again**.
+- **Undo** / **Redo** ([[sc:editor.undo]] / [[sc:editor.redo]]) go back 80 steps. Switching drafts, Auto-edit and swapping in finished shots clear the undo history.
+
+**Drafts** — open them from the draft chip or **⋯ → Drafts and versions…**:
+
+- A sequence can have several drafts. **Copy** starts a new draft from this one, **Empty** starts a blank one; each draft in the list has **Open**, **Copy**, **Rename** and **Delete**.
+- *Your saves of this draft* lists every save with **Restore**. Type a name and press **Keep** to mark a save you want to keep for good — old unnamed saves are pruned, kept ones never are.
+- If the same draft was saved from another tab, the Editor asks: **Load theirs** or **Keep mine**.
+
+## Render and deliver {#render}
+
+**Render** ([[sc:editor.render]]) saves first, then assembles the timeline into one file and opens it on the Storyboard film screen.
+
+**▾ → Deliver as** chooses what the file is; the choices are remembered, and the Render button names them (*Render · 1080p*):
+
+| Row | Choices | Notes |
+|---|---|---|
+| **Format** | **H.264** · **HEVC** · **ProRes** | H.264 plays everywhere, HEVC is half the size, ProRes (.mov) is for grading |
+| **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. 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.
+
+## Common jobs {#jobs}
+
+### Cut a scene out {#job-cut}
+
+1. Put the playhead where the unwanted part starts and press **Split** ([[sc:editor.split]]).
+2. Move to where it ends ([[sc:editor.cut]] jumps between cuts, [[sc:editor.frame]] steps frames) and **Split** again.
+3. Click the piece in the middle.
+4. **Ripple delete** ([[sc:editor.ripple]]) to close the gap — or **Lift** ([[sc:editor.lift]]) to leave black in its place.
+5. **Save**.
+
+### Fix sound that drifted {#job-drift}
+
+1. Find the strip with an offset label (**+0.25s**) on **A1 Clip sound**.
+2. Click the label — or select the clip and press **Resync sound** ([[sc:editor.resync]]).
+3. To stop it drifting again, press **Link sound**.
+4. **Save**.
+
+### Make a J-cut {#job-j-cut}
+
+1. Select the **incoming** shot and press **Unlink sound** ([[sc:editor.link]]).
+2. On **A1 Clip sound**, drag that strip's left end earlier, under the end of the previous shot (hold ⌥ to ignore the grid). The picture does not move.
+3. Optional: drag a corner handle for a short fade in.
+4. Press **Link sound** to keep the offset — the message confirms *Linked at …*.
+5. **Save**.
+
+For an L-cut, do the same with the **outgoing** shot and drag its strip's right end later.
+
+### Replace a shot with a retake {#job-retake}
+
+1. Select the shot. Retake works on shots that came from a storyboard.
+2. In the inspector's **Clip** section press **Retake**.
+3. In *Retake this shot*, edit the prompt if you want, choose **Draft** or **Delivery**, and **Queue the retake**.
+4. When the new take finishes, the Editor says *New take of … is ready*: **Use it** swaps it in with the same cut and timings; **Keep the old one** leaves the timeline as it is (the new take stays in the media pool).
+
+When shots from the board have been finished at the delivery pass since you cut, the Editor offers **Use the finished versions** the same way.
+
+### Deliver 1080p {#job-1080p}
+
+1. Press **▾** beside **Render**.
+2. Under **Deliver as**, choose **H.264**, **1080p** and **Clean** (or a grain).
+3. The button now reads **Render · 1080p**. Press it, or [[sc:editor.render]].
+4. If the timeline has holes, decide whether to let them close.
+5. The film opens on the Storyboard film screen when it is done.
+
+## Keys {#keys}
+
+The same list is behind the **Keys** button above the tracks.
+
+[[shortcuts:editor,editor-mouse]]
diff --git a/webapp/docs/getting-started.md b/webapp/docs/getting-started.md
new file mode 100644
index 0000000..281e21b
--- /dev/null
+++ b/webapp/docs/getting-started.md
@@ -0,0 +1,66 @@
+# Getting started
+
+Phosphene makes video, images and sound on your Mac — nothing is uploaded, nothing is rented. You describe a shot, it goes into a queue, and the finished file lands in Outputs.
+
+## The tabs {#tabs}
+
+The row of tabs at the top of the left column is where you choose what to make. [[sc:tabs.switch]] switches between them from the keyboard.
+
+| Tab | What it is for |
+|---|---|
+| **Video** | A clip from a prompt — or from an image, a first and last frame, keyframes, a clip to extend, or your own media (Remix). See [Video](#docs/video). |
+| **One Shot** | One continuous shot of 30 seconds to 2 minutes that never cuts. See [One Shot](#docs/one-shot). |
+| **Images** | Stills: edit a reference image, or put words on a picture with Ideogram 4. See [Images](#docs/images). |
+| **Storyboard** | Plan a whole film from one idea, render every shot, grade them, cut them. See [Storyboard](#docs/storyboard). |
+| **Editor** | A timeline: trim, split, move sound, add titles and music, render the film. See [Editor](#docs/editor). |
+| **Audio** | A video driven by a sound file you bring — a voice, a song. See [Audio](#docs/audio). |
+| **Train Character** | Teach Phosphene a face (and a voice) from your photos. See [Train Character](#docs/train-character). |
+
+## The engine {#engine}
+
+The switch at the top right of the header chooses which model renders: **LTX** or **Hailuo H3**. They are two different engines with different strengths, not a good one and a spare:
+
+- **LTX** — every Video mode, LoRAs and trained characters.
+- **Hailuo H3** — joint video, dialogue and sound. Text and Image modes.
+
+The form changes with the engine: controls one engine does not use are hidden, and the Quality and Length chips show that engine's own sizes. The switch only appears when this Mac can run more than one engine. [How they compare](#docs/video/engines).
+
+## The queue {#queue}
+
+Everything you generate goes into one queue and renders one job at a time. The panel at the bottom has four tabs:
+
+- **Now** — the render in progress, with a live preview of the shot as it forms. **Stop early** (on the preview) asks first, then stops it: *"nothing is saved"*, and the queue carries on with the next job.
+- **Queue** — the jobs waiting. The × on a card removes it.
+- **Recent** — what finished, filtered by All / Videos / Photos.
+- **Logs** — the render log. See [Reading the log](#docs/troubleshooting/logs).
+
+Under the Generate button: **⊞ Batch** pastes many prompts at once and queues them all; **Pause queue** holds the queue (the button then reads **Resume queue**); **Clear** removes every waiting job — the one running carries on.
+
+## Outputs {#outputs}
+
+The gallery on the right shows what you have made. Click a card to put it on the player.
+
+- **All / Videos / Photos** filter it, and the search box finds outputs by prompt words, model, LoRA, size or seed ([[sc:search.focus]] jumps to it).
+- **Show all** loads older renders than the newest 60.
+- [[sc:outputs.step]] steps through the gallery, [[sc:player.toggle]] plays and pauses, [[sc:outputs.expand]] expands the player to full screen.
+- Under the player, the action row offers what you can do next with that clip: **Extend** it, **LTX Upscale** it, send it **To film**, **Animate** a still, see its **Params**.
+- The trash button on a card moves the file to the macOS Trash after asking — restore it from Finder if you change your mind. [[sc:outputs.trash]] does the same for the selected output.
+
+## Where files go {#files}
+
+| What | Where |
+|---|---|
+| Your renders | the `mlx_outputs` folder inside the Phosphene install. The folder button in the Outputs header opens it in Finder; Pinokio's **Outputs** item opens it too. |
+| Trained characters and downloaded LoRAs | `mlx_models/loras/` |
+| Settings | `panel_settings.json` |
+
+Every render also writes a small sidecar file beside it with its settings. That is what **Params** reads, and what lets Outputs search by LoRA or seed.
+
+## Updating {#update}
+
+- The version pill in the header says where you stand: **Up to date**, or **Update to** a newer version. When one is out, a banner offers **Update now** / **Later**.
+- In Pinokio, the **Update** item in the Phosphene sidebar updates everything, including Python dependencies. Updating keeps your queue, settings and models.
+- After an in-app update the banner reads *"Updated to … — restart to finish"*: click **Stop**, then **Start** in Pinokio. If the update touched dependencies, it tells you to use Pinokio's **Update** instead.
+- If an update started from a very old version only seems to move the panel, click **Update** once more — an old version updates its updater first.
+
+> **Tip** Press [[sc:docs.open]] anywhere to open these docs on the shortcuts page, and use the search box on the left to find any button by the word written on it.
diff --git a/webapp/docs/images.md b/webapp/docs/images.md
new file mode 100644
index 0000000..9bb5c73
--- /dev/null
+++ b/webapp/docs/images.md
@@ -0,0 +1,43 @@
+# Images
+
+The Images tab makes stills. Two kinds of engine live here: **Reference Edit**, which reworks an image you give it, and **Ideogram 4**, which puts words on a picture.
+
+## Choosing the engine {#engines}
+
+| Engine | Use it for |
+|---|---|
+| **Auto (use Settings)** | whatever Settings picks for this Mac |
+| **Reference Edit — Fast** | image-to-image in 4 steps, about 1:20, several references — the default |
+| **Reference Edit — Standard** | 8 steps, about 2:05, no LoRA |
+| **Reference Edit — Quality** | 40 steps, about 3:50 — for final renders |
+| **Ideogram 4 — typography & layout** | text in the image, with an optional reference |
+
+The pill next to the menu says whether that engine is downloaded. An engine that needs more memory than this Mac has is greyed out and labelled *needs a N GB Mac*.
+
+## Reference images {#references}
+
+Reference Edit needs at least one picture: drop it into **Primary**, and up to two more into the **Multi-ref** slots (or click one from *Recent uploads*). With two or more, name them in the prompt — *the jacket from reference 1 and the street from reference 2*.
+
+Then set **Aspect** (16:9 1280×720 by default, down to smaller, faster sizes), **Candidates (n)** — 1 to 8 images per run — and **Seed**, and press **Generate** ([[sc:prompt.generate]] from the prompt).
+
+## Ideogram 4 — words on the picture {#ideogram}
+
+The first render downloads Ideogram 4 (about 28 GB, once). Commercial use needs a license from Ideogram.
+
+- **Simple** — a plain prompt. **Layout** — the visual canvas (below).
+- **Render**: **Design** (illustration, graphic) or **Photographic** (camera realism).
+- **Quality**: Default (20 steps), Turbo (12, faster), Quality (48, slower). **⚡ Fast mode** is lighter on memory for M1/M2 and smaller Macs.
+- **Use reference** appears when a reference is loaded: Ideogram redraws it from a description rather than copying pixels. Leave it off and the reference is ignored — the panel warns you.
+- **Image palette** sets up to 16 colours.
+
+### The Layout canvas {#layout}
+
+1. Choose **Layout**. Drag on the frame to draw a box, or use **Insert text** / **Insert object**. **Examples…** loads a poster, logo, label or meme layout.
+2. With a box selected, set its **Region** (Text or Object), the **Text (literal words)** to render, an optional description, a **Style**, **Align** and **Color**.
+3. Boxes snap to thirds, the centre and each other while **Snap** is on.
+
+Keys on the canvas, with a box selected:
+
+[[shortcuts:canvas]]
+
+A Layout render needs at least one box.
diff --git a/webapp/docs/loras.md b/webapp/docs/loras.md
new file mode 100644
index 0000000..654d514
--- /dev/null
+++ b/webapp/docs/loras.md
@@ -0,0 +1,35 @@
+# LoRAs
+
+A LoRA is a small add-on that teaches a model a face, a style, a motion or a speed-up. The **LoRAs** section of the Video form (it moves into Images too) is where you turn them on.
+
+## The picker {#picker}
+
+- The summary reads *none active*, or how many are installed and active.
+- Click a row to turn a LoRA on or off. Turning one on adds its first trigger word to your prompt; the trigger chips on an active row add them again.
+- **strength** — a slider from -2 to 2. It starts at the LoRA's recommended strength, or 1.0.
+- With five or more LoRAs, a filter box finds them by name or trigger word.
+- The row buttons rename it (display name only), download the file, open it on CivitAI, or delete it from disk (asks first — it is permanent).
+- **Write a guide** has the planner model write what the LoRA does, how to prompt it, and a strength to start from.
+- **?** means its family is unknown — it may or may not work on this engine. **Update** means CivitAI has a newer version (**Check for updates** asks).
+
+LoRAs are per engine: an LTX LoRA cannot load on Hailuo H3 and an H3 LoRA cannot load on LTX. The picker shows the active engine's library and offers *Show N from other modes*.
+
+## Browse CivitAI and Hugging Face {#browse}
+
+**Browse CivitAI** opens the browser.
+
+1. Pick the source — **CivitAI** or **Hugging Face** — and the engine: **All**, **LTX** or **Hailuo H3**.
+2. Search (a name, a style, a creator; on Hugging Face also `author:someone` or `owner/repo`) and press Enter.
+3. **Install** on a result. It lands in `mlx_models/loras/` and turns on in the picker — unless it is for the other engine, in which case it says which engine to switch to.
+
+CivitAI needs an API key to download: paste it in the browser's banner or in Settings → **API tokens**. Hugging Face results can be filtered by kind (Characters, Styles, Motion, Speed) and **With example**; read the repo before you install.
+
+## Adding a file yourself {#import}
+
+- **LTX** — copy `.safetensors` files into `mlx_models/loras/` and press the rescan button.
+- **Hailuo H3** — **Import H3 LoRA** takes a `.safetensors` file (up to 4 GB) and reports how it was read and its recommended strength.
+
+## Stacking LoRAs on Hailuo H3 {#h3-stacking}
+
+- On an H3 install that stacks, up to **4 LoRAs** per render, each with its own strength, and Turbo rides along. Keep the strengths' total near 1.5 or under, and avoid two LoRAs that pull the same thing (two faces, two styles).
+- On an older H3 install there is **one adapter slot**: the **Adapter** row chooses **Turbo** or **My LoRA** for this render. Picking more than the install allows stops the job with a message saying how many to un-pick.
diff --git a/webapp/docs/one-shot.md b/webapp/docs/one-shot.md
new file mode 100644
index 0000000..79441e1
--- /dev/null
+++ b/webapp/docs/one-shot.md
@@ -0,0 +1,32 @@
+# One Shot
+
+One continuous shot of **30 seconds to 2 minutes** that never cuts. You write the whole shot once; Phosphene renders it in parts, each continuing from the last frame of the one before, and joins them into one file.
+
+## Making one {#make}
+
+1. Choose the **Engine**: **LTX 2.5** renders 10 s parts and is the one for faces, voices and dialogue; **Hailuo H3** renders 15 s parts and is the one for motion, landscapes and crowds.
+2. Write **The shot** — who, where, the time of day and the weather, the sound — once, for the whole shot. This is the only thing required.
+3. Pick a **Length**: 30 s, 45 s, 1 min, 1½ min or 2 min. Each chip shows how many beats and parts it makes.
+4. Pick a **Quality**. The estimate line says about how long it takes on this Mac.
+5. Press **Generate** (or [[sc:prompt.generate]] in the prompt box). The whole shot is one request in the queue.
+
+## The optional parts {#options}
+
+- **Start frame** — *Choose an image* and the shot opens on it.
+- **Who is in it** (LTX) — pick a trained character: Quality switches to that character's qualities and **Hand off where the line ends** turns on.
+- **Beats** — one row per 5 seconds, each with its time stamp. Write what happens in each, or let Phosphene fill them: **Split my prompt into beats** puts one sentence per beat, **Write the beats for me** has the planner write them. [[sc:oneshot.beats]] Pasting a list fills the rows.
+- **Camera** — one move for the whole shot, its direction and speed. Every part continues it.
+
+## The three switches {#switches}
+
+| Switch | On | Off |
+|---|---|---|
+| **Lock the light** | the same light in every part (default) | each beat as written |
+| **Redo a part that drifts** | a part that drifts is rendered once more, at most (default) | keep the first pass |
+| **Hand off where the line ends** | for a talking character: the next part starts where the spoken line stops | each part starts from the last frame |
+
+Under **More**: **Seed**, a **Label** for the queue, and **No music** (voice, sound and ambience only).
+
+## Watching it render {#status}
+
+The status card updates every few seconds: *Rendering*, *part 2 of 6*, and when it is done, *in the gallery on the right*. For each finished part with speech it reports whether the voice is on the mouth — **voice on the mouth**, **borderline** or **voice-over** — and **light drifted** when a part's light moved.
diff --git a/webapp/docs/remix.md b/webapp/docs/remix.md
new file mode 100644
index 0000000..25901e7
--- /dev/null
+++ b/webapp/docs/remix.md
@@ -0,0 +1,45 @@
+# Remix
+
+Remix is the last chip on the Video tab — *motion control · refs · color*. It holds four tools that start from **your own media**. Click it, then choose the tool in the row that opens; it remembers the last one you used.
+
+## Ingredients {#ingredients}
+
+*2–8 refs → one clip.* Several reference images — a face, a prop, a location — composed into one new clip.
+
+1. Drop 2 to 8 images into **Reference images** (or click one from *Recent uploads*). They tile into one reference sheet.
+2. The main prompt describes what is in the sheet; **Action / shot to generate** describes the shot.
+3. Optional: a **Character** with **Identity strength** (0.8–1.8; about 1.3 is the sweet spot).
+
+> **Needs LTX-2.3** Ingredients' reference adapter has no LTX-2.5 release yet. On LTX-2.5 the chip is greyed out and says so; use Image mode with **Inspire** instead, or install the 2.3 pack.
+
+## Motion Control {#motion-control}
+
+*Its motion → your scene.* The render copies the motion, camera move, composition and pose of a clip you supply, while your prompt repaints the subject and the scene.
+
+1. Pick the clip in **Control video** (or paste its path). The output has that clip's size and length.
+2. Write the new subject and scene. Leave the camera out of the prompt — the clip already carries it.
+
+An ordinary video works. A pose, depth or edge sequence you already have follows more tightly — Phosphene does not make those sequences for you. It works best on shots whose content changes (camera moves, wide scenes) and worst on a static, high-contrast single subject. On LTX-2.5 the motion and framing still transfer, but the prompt has much weaker control over the new subject — the panel shows that warning.
+
+## Colorize {#colorize}
+
+*B&W clip → color.* Pick the clip in **Source video to colorize** and describe the colours to paint in. The output keeps the source's size and length.
+
+## LTX Upscale {#ltx-upscale}
+
+*Any clip → 2× sharper.* Re-renders a clip at twice its size with generated detail — not a filter. Made for Hailuo H3 drafts, works on any clip.
+
+1. Pick the clip in **Clip to upscale**, or press **LTX Upscale** under the player with a clip selected in Outputs.
+2. Choose a preset:
+
+| Preset | What it does | Time for 5 s at 640×384 on an M4 Max |
+|---|---|---|
+| **Faithful** | sharp, the face stays (default) | about 5.5 min |
+| **Quick** | a touch softer | about 3.75 min |
+| **Re-imagine** | the sharpest, and faces drift | about 7 min |
+
+3. Generate. The sound is kept, the length and (if you leave it empty) the prompt come from the source, and up to 0.3 s may be trimmed at the end. The result is capped at this Mac's Image-to-Video size.
+
+It needs the **LTX-2.5 Pixel Spatial Upscaler** adapter (0.3 GB) — download it from the Models window. A source already near the cap is refused, because it cannot grow enough to be worth the render.
+
+Ingredients, Motion Control and Colorize run on the fast Q4 model — no Q8 download is needed.
diff --git a/webapp/docs/settings.md b/webapp/docs/settings.md
new file mode 100644
index 0000000..7f41ec9
--- /dev/null
+++ b/webapp/docs/settings.md
@@ -0,0 +1,50 @@
+# Settings
+
+The gear in the header opens Settings. Changes are saved to `panel_settings.json` when you press **Apply** and affect every new render; files already in the gallery are not re-encoded.
+
+## Output format {#output-format}
+
+How finished clips are encoded.
+
+| Choice | One line |
+|---|---|
+| **Standard** | visually lossless to almost everyone, about 7 MB per 5 s clip |
+| **Video production (lossless)** | for grading and editing elsewhere, about 50 MB per 5 s clip |
+| **Web / social** | the smallest files, about 3 MB per 5 s clip |
+| **Custom** | set the pixel format and CRF yourself: 0 is lossless, 18 visually lossless, 23 the web default, 28 and up visibly lossy |
+
+## Memory / speed {#memory-speed}
+
+- **Live preview** — *On* shows the shot as it forms in the Now card. It never changes the result (the file is byte-for-byte the same either way); turning it off also removes the **Stop early** button.
+- **Hailuo H3 model** (when H3 is installed) — **Automatic** picks the best this Mac can hold; **Full (bf16)** peaks around 42 GiB; **Compact (Q8)** peaks around 21 GiB, about half the memory for a little more time. On a Mac too small for Full, that option says so and is disabled.
+
+## Model files {#model-files}
+
+**Verify model files (checksum)** checks every installed weight file against its published checksum and offers a one-click re-download of any that are damaged. It takes 1–2 minutes.
+
+## Storage {#storage}
+
+Shown when this disk holds weights this version does not render with by default. Each pack lists its size and a **Remove** button, which asks first. Removing a pack never touches your renders in `mlx_outputs`.
+
+## API tokens {#tokens}
+
+Saved on this Mac only, and sent nowhere except as sign-in to the site they belong to.
+
+- **CivitAI API key** — needed to install LoRAs from CivitAI. **save & test** checks it.
+- **Hugging Face token** — needed for gated models; read access is enough.
+
+## Spicy mode (adult content) {#spicy}
+
+Off by default: the CivitAI browser hides NSFW results and the **Show NSFW** switch. **Enable Spicy mode** asks for a second click, then lets you choose per search.
+
+## Appearance {#appearance}
+
+**Dark**, **Light** or **System** (follows the Mac, live). Saved in this browser only.
+
+## Completion alerts {#alerts}
+
+A chime when a render finishes, and a browser notification when the tab is in the background once you allow it. **Send a test** tries it.
+
+## Anonymous usage analytics {#analytics}
+
+Sends anonymous counts — version, hardware class, engine, tier, resolution, the first line of an error. Never your prompts, file names, paths, images or video; a copy of what is sent is kept in `state/usage-log.jsonl`. **Turn off** stops it.
diff --git a/webapp/docs/shortcuts.md b/webapp/docs/shortcuts.md
new file mode 100644
index 0000000..a39ba84
--- /dev/null
+++ b/webapp/docs/shortcuts.md
@@ -0,0 +1,13 @@
+# Keyboard shortcuts
+
+Phosphene uses the keys you already know from Premiere Pro, Final Cut Pro, DaVinci Resolve, Photoshop and After Effects. Every tooltip that has a shortcut names it in brackets, and the Editor's **Keys** button shows its own list.
+
+> **Conventions** ⌘ is Command (Ctrl works too), ⇧ Shift, ⌥ Option, ⏎ Return, ⌫ Delete. Keys never fire while you are typing in a text box, except ⌘⏎ and Esc. Nothing claims a key your browser or macOS needs — ⌘R still reloads, ⌘W still closes.
+
+[[shortcuts]]
+
+## Not bound, on purpose {#not-bound}
+
+- **J / K / L shuttle** — Space and the arrows play and step. A shuttle needs variable playback speed the Editor's player does not have.
+- **⌘C / ⌘V for clips** — **Duplicate** ([[sc:editor.duplicate]]) covers "again, right here"; pasting at the playhead is not built.
+- **I / O in and out points** — the timeline has no in/out range to mark; trim a clip by dragging its edge.
diff --git a/webapp/docs/storyboard.md b/webapp/docs/storyboard.md
new file mode 100644
index 0000000..8a44018
--- /dev/null
+++ b/webapp/docs/storyboard.md
@@ -0,0 +1,36 @@
+# Storyboard
+
+Storyboard plans a whole film from one idea, renders every shot, lets you grade them, and hands the keepers to the Editor. Its steps run across the top: **1 Plan**, **2 Shots**, **3 Edit**, **4 Film**.
+
+## 1 · The brief {#brief}
+
+- **Concept** — the film in a sentence or two.
+- **Shots** — how many, roughly: 6 *a scene*, 12 *a short*, 24 *a film*, 36 *long*, or **One Shot** with its own length.
+- **Engine** — **Auto** (character shots go to LTX, everything else to Hailuo H3), **Hailuo H3** (voice and sound) or **LTX** (characters).
+- **Soundtrack** — a track turns it into a music video cut to the beat, at 1, 2 or 4 bars.
+- **Look** — goes on every shot. **Who's in it** — optional, with a wardrobe line.
+- **Where it happens** — one line per place; shots reuse them.
+- **Shots it must include** — one per line.
+- **Auto** plans, renders every shot, cuts and makes the film in one go. **Start each shot from a still** (LTX) and **Long shots** (chained 5-second passes, needs the Q8 pack) are further options — the **?** beside them explains each.
+
+Press **Plan film**. Writing the plan takes about a minute and renders nothing yet.
+
+## 2 · The shot list {#shots}
+
+Each shot card has its prompt, its cast and length, a **voice** chip when it has spoken lines, and **↑ / ↓**, the dice (a new seed) and **✕**. Drag cards to reorder, or use **+ Add a shot**. **Draft pass** is what you watch first; **Delivery pass** is what you keep.
+
+**Render all drafts** starts the renders; **Pause**, **Stop shot** and **Stop film** control them (Stop film keeps everything already rendered). **Re-plan…** writes a new shot list from notes while keeping the concept and the look.
+
+## Grading {#grading}
+
+Every rendered clip gets **KEEP**, **RE-ROLL** or **CUT**. RE-ROLL asks *what should change?* — that note goes back to the planner.
+
+[[shortcuts:storyboard]]
+
+- **Rewrite** re-plans only the RE-ROLL shots, from your notes.
+- **Render remaining** renders what is left.
+- **Finish keepers** renders the KEEP shots at the delivery pass.
+
+## 3 · Into the Editor {#edit}
+
+**3 Edit**, **Open in Editor** on the board list, or **Re-cut in the Editor** on the film screen all open the board's shots as a timeline. See [Editor](#docs/editor).
diff --git a/webapp/docs/train-character.md b/webapp/docs/train-character.md
new file mode 100644
index 0000000..85265df
--- /dev/null
+++ b/webapp/docs/train-character.md
@@ -0,0 +1,49 @@
+# Train Character
+
+Train Phosphene on one person's face — and, optionally, their voice — from your own photos. The result is a character you can put in any LTX shot. Training needs at least 24 GB of memory and runs on LTX-2.3 (the tab downloads what it needs).
+
+## The steps {#steps}
+
+1. **Train type** — **Character** (the face, and voice, of one person) or **Style** (a cinematic look, colour, lighting; experimental).
+2. **Dataset** — drop **15 to 50 photos** (up to 500) — PNG, JPG or WEBP, with matching `.txt` captions if you have them — or a ZIP of paired images and captions. Each preview shows the square crop the trainer sees. *How to train a character well* covers the mix of shots, light and backgrounds that works.
+3. **Captions** — see below.
+4. **Trigger word** — a rare, letters-only word the model ties to this character. **↻ Suggest** makes one. Avoid digits: they split into common tokens.
+5. **Quality preset** — see below.
+6. **Crop strategy** — **Center crop** for tight portraits, **Letterbox** to keep wide-shot proportions.
+7. **Voice** (optional) — see below.
+8. Check the estimate — **Estimated wall time**, **Peak RAM** — and press **Train Character**.
+
+## Captions {#captions}
+
+Each image needs a caption in the form `[VISUAL]: trigger, 50–80 words` followed by `[TEXT]: None`; missing tags are added for you. **Auto-caption with Gemma 3** writes one for every image (2–3 seconds each) and overwrites existing captions. A thumbnail marked **no cap** falls back to a caption made from the trigger word alone.
+
+Captions cannot be edited inside the tab: to change one, upload a corrected `.txt` (or ZIP). Training asks before it starts if captions are missing or very short.
+
+## Presets, and what "identity graded" means {#presets}
+
+| Preset | On a Mac with 64 GB or more |
+|---|---|
+| **Quick** | ~30 epochs, rank 8, 512px — a look, not a face · identity ungraded |
+| **Medium** | ~60 epochs, rank 16, 576px — more capacity · identity ungraded |
+| **High** | ~100 epochs, rank 32, 512px — validated for identity (recommended) |
+
+**Identity graded** means the recipe has actually been measured on real faces and holds them. Only **High** on a 64 GB+ Mac is. Quick and Medium are for a fast look or a style, not a person.
+
+On Macs under 64 GB, training runs a compact profile (fewer steps, lower rank), and even "High" there is **not** the graded recipe — the note under the presets says so. **Advanced** exposes rank, steps, learning rate, resolution and caption strategy.
+
+When a run finishes, Phosphene measures the result. A character that came out weak or carries nothing gets a **WEAK** or **DEAD** badge and a banner with advice — usually, train again on High.
+
+## Voice {#voice}
+
+Upload one clean clip — 10 to 25 seconds of a single speaker, MP3, WAV, M4A or FLAC, up to 50 MB — and tick **Train voice LoRA**. **Audio steps**: Smoke 100, Standard 250 (default) or Long 500. The button becomes **Train Character + Voice**.
+
+## Using a character in Video {#use-in-video}
+
+Trained characters land in `mlx_models/loras/` and appear in two places:
+
+- **The Character mode** on the Video tab (LTX): pick the face from the strip. Voiced characters carry a music-note badge. Set **strength** (0–2, default 1.0), or split it into separate **face** and **voice** strengths. **No voice** keeps the face and drops the speech.
+- **The LoRA picker**, marked **Trained**, like any other LoRA.
+
+Use the trigger word in the prompt — *mrztrn man walking on the beach*. A trained character needs the full model: with one active, **Quick** and **Standard** are greyed out and the render uses High. The pencil on the strip renames or deletes a character; the trigger word itself cannot change.
+
+Clicking a character chip under *Use your trained characters* on the Train tab switches to the Video tab in Text mode with that character's LoRA on at strength 1.0, and fills an empty prompt with its trigger word.
diff --git a/webapp/docs/troubleshooting.md b/webapp/docs/troubleshooting.md
new file mode 100644
index 0000000..94f1d04
--- /dev/null
+++ b/webapp/docs/troubleshooting.md
@@ -0,0 +1,49 @@
+# Troubleshooting
+
+When Phosphene refuses a render, it says why and what to do. These are the messages people actually see.
+
+## Memory and this Mac's tier {#memory}
+
+The health chip in the header shows memory at a glance; click it for the **Tier**, **Memory**, **Helper**, **Models**, **Queue** and **Render** rows. Click **Tier** to see what this Mac can run.
+
+- *"Helper killed by the OS — out of memory"* — macOS stopped the render. Close memory-heavy apps (browsers, Slack, the iOS Simulator) and try again, or switch Quality to **Quick**, which uses about half the memory.
+- *"Image pre-flight: … needs a N GB Mac"* — that image engine does not fit this Mac. Pick **Auto** or a lighter preset. *"… needs ~N GB free"* means it fits, but other apps are holding the memory right now.
+- *"Training needs at least 24 GB of memory"* — character training cannot run on this Mac.
+
+### Hailuo H3 on a 36–60 GB Mac {#h3-compact}
+
+H3's full engine needs 60 GB. From 36 GB it runs on its compact Q8 engine, which has to be built once:
+
+> *"Hailuo H3 runs on this Mac — on its reduced-RAM lane … Run 'Install Hailuo H3' from the Phosphene sidebar in Pinokio — it builds that engine locally (~5 minutes, ~22 GB on disk, no extra download)."*
+
+Do that, then choose Settings → **Hailuo H3 model** → Automatic or Compact. Below 36 GB, H3 is not available: render on LTX, which serves every mode.
+
+## A model or add-on is not downloaded {#missing}
+
+- *"Extend needs the LTX-2.5 High add-on (the Q8 model), which isn't downloaded on this Mac yet"* — the same for Keyframes and High quality. Install it from the Models window (click the health chip, then **Models**).
+- *"Upscale ×2 needs the LTX-2.5 Pixel Spatial Upscaler adapter"* — download it from the Models window, then render again.
+- *"Stopped before rendering — the model weights are incomplete"* — a download was interrupted. Open the Models window and resume it. Settings → **Verify model files** checks every file and offers a re-download of any that are damaged.
+
+## "Click Update" — an engine older than the panel {#stale-engine}
+
+*"This install's vendored engine predates LTX-2.5's text encoder … Click Update — and if the first click only moves the panel, click it once more."*
+
+The panel was updated but the engine underneath was not. Click **Update** in Pinokio's Phosphene sidebar. If nothing seems to change, click it a second time: an update started by an old version updates itself first. For H3, *"the installed Hailuo H3 runner is behind this panel"* means: re-run **Install Hailuo H3** — every weight already on disk is kept.
+
+If you updated and the panel still behaves like the old version, it is still running the old code. The version pill in the header then reads **Restart Phosphene** — click it, or click **Stop**, then **Start**, in Pinokio.
+
+## The GPU watchdog {#gpu-watchdog}
+
+*"the macOS GPU watchdog killed a Metal command buffer"* — macOS itself stopped a GPU task that ran too long. It is a driver-level kill, not a Phosphene bug report. Phosphene retries the prompt encoding at a shorter length for the rest of the session. If it keeps happening, the message links to the GitHub issue where chip, macOS version and the crash log help most.
+
+## The queue after a restart {#queue-restart}
+
+Restarting the panel resumes the queue: a queue that was paused when the panel stopped starts again on its own, and the log says so.
+
+## Reading the log {#logs}
+
+The **Logs** tab in the bottom panel shows the render log. When a render dies, the last line that starts with `step:` names the stage it reached — that line is the most useful thing to include in a report. Pinokio's **Terminal** shows the same output.
+
+## Reporting an issue {#report}
+
+The bug button in the header opens **Report a bug**: it fills in the version, your Mac's details and the last 50 log lines, and opens a GitHub issue in a new tab for you to finish — nothing is sent until you submit it there. Issues live at [github.com/mrbizarro/phosphene/issues](https://github.com/mrbizarro/phosphene/issues).
diff --git a/webapp/docs/video.md b/webapp/docs/video.md
new file mode 100644
index 0000000..7b16919
--- /dev/null
+++ b/webapp/docs/video.md
@@ -0,0 +1,137 @@
+# Video
+
+The Video tab turns a prompt — and, if you like, an image or a clip — into a video with sound. Pick a mode, write the prompt, choose Quality and Length, press **Generate** ([[sc:prompt.generate]] from the prompt box).
+
+## Modes {#modes}
+
+The chips across the top of the form. Each one says what it takes.
+
+| Mode | Takes | What you get |
+|---|---|---|
+| **Text** | a prompt | a clip from words alone |
+| **Character** | a trained character + a prompt | your character's face (and voice) in a new shot — LTX only. See [Using a character](#docs/train-character/use-in-video) |
+| **Image** | a reference image + a prompt | a clip that starts from, or is inspired by, your picture |
+| **FFLF** | a start frame and an end frame | a clip that travels from one to the other |
+| **Keyframes** | 3–8 frames | a clip that passes through each |
+| **Extend** | a clip | more of that clip, after or before it |
+| **Remix** | your own media | Ingredients, Motion Control, Colorize, LTX Upscale — see [Remix](#docs/remix) |
+
+Hailuo H3 renders **Text** and **Image**; the other modes are LTX's.
+
+### Image: Anchor or Inspire {#anchor-inspire}
+
+Drop a PNG, JPG or WEBP into **Reference image** — it is cover-cropped to the render size. On LTX-2.5 a **Reference use** row appears:
+
+- **Anchor** — *animate this image*. Your picture is frame one and the clip moves it.
+- **Inspire** — *new shot from it*. The clip takes the character or look into a new scene, and you will not see your picture as frame one. Good for "this character, new scene".
+
+On Hailuo H3 the image is always the first frame.
+
+### FFLF and Keyframes {#fflf}
+
+- **FFLF** — **Start frame (frame 0)** opens the clip and its shape sets the output size; **End frame (last frame)** closes it. A close-up at the end holds a face through the clip.
+- **Keyframes** — choose **3 keyframes** to **8 keyframes**. Start and End are fixed; the others are the beats in between.
+- Both need the LTX High add-on (the Q8 model) and pick High quality on their own. If it is missing, Generate says so and tells you where to install it.
+
+### Extend {#extend}
+
+Pick the **Source video**, set **Extend by (seconds)** (0.5 to 10, default 2) and **Direction** (After or Before). Extend has its own two qualities:
+
+- **Q8 Draft** — 12 steps, safe on a 64 GB Mac.
+- **Q8 Pro** — 30 steps, wants 96 GB or more.
+
+Stay on Q8 Draft unless the Mac has the memory.
+
+## Writing the prompt {#prompt}
+
+Describe the scene **and the sound**. Sound is generated with the picture; a prompt with no sound in it comes out near silent.
+
+- **Enhance** (LTX) rewrites your prompt in the style the model was trained on.
+- **No music** asks for voice, sound and ambience without a score.
+- **No voice** appears when the selected character has a voice: the face still locks, the audio stays ambient.
+
+### The Avoid box {#avoid}
+
+**Avoid +** opens a second box for what the model should *not* make — *blurry hands, distorted fingers, warped text*.
+
+> **When it works** Avoid applies on **High**, **High · 720p**, **Extend**, **FFLF** / **Keyframes** and **Audio**. **Quick**, **Balanced** and **Standard** run without guidance and ignore it. On Hailuo H3 there is no Avoid box: write refusals as plain sentences in the prompt, and only for what H3 adds unasked — camera drift and on-screen text.
+
+## Quality and Length on LTX {#ltx-quality}
+
+Each Quality chip shows its size and an estimate for this Mac. A chip reads *unavailable* when this Mac cannot run it, or names the download it needs.
+
+| Quality | Size | What it is |
+|---|---|---|
+| **Quick** | 640×448 | the fastest look at the shot |
+| **Balanced** | 1024×576 | 16:9 at the size most things are watched — the default |
+| **Standard** | 1280×704 | the largest canvas the fast lane serves — bigger, not more detailed |
+| **High** | 1024×576 | a second, larger pass over the first: sharper detail and steadier motion, for about twice the wait |
+| **High · 720p** | 1280×704 | the High pass at 720p — the most detail LTX makes; measured peak 49.7 GB, so it wants a 64 GB Mac |
+
+Quick, Balanced and Standard run on the fast (distilled) model; High and High · 720p need the High add-on (the Q8 model).
+
+**Length**: 3s, 5s (default), 7s, 10s — and 20s, which is offered at Quick only.
+
+On the fast qualities, a **Speed** row offers **Tuned** or **Fast draft** — a faster schedule that changes the take. High has a **STG — detail guidance** slider.
+
+With a trained character selected the chips become **Q8 Draft** (704×384), **Q8 Pro** (1024×576, *best identity*) and, on LTX-2.5, High and High · 720p. Trained faces hold best on Q8 Pro.
+
+## Quality and Length on Hailuo H3 {#h3-quality}
+
+| Quality | Size | Notes |
+|---|---|---|
+| **Draft** | 640×384 | quick look — faces and fine detail only resolve at Standard and High |
+| **Standard** | 768×448 | the workhorse |
+| **High** | 1024×576 | true 16:9, the recommended delivery size |
+| **Native** | 1344×768 | the most detail H3 can make — worth it with Turbo on, a long wait without |
+
+**Length**: 3s, 5s (the longest single pass), **10s** and **15s**. 10 s and 15 s are chained from 5-second windows at render time, so choose the length before you render — there is no Extend afterwards.
+
+### Turbo and Steps {#turbo}
+
+- **Speed: Standard / Turbo.** Turbo is a 4-step adapter: much faster, and it overrules Steps. If it is not downloaded yet, the chip shows its size.
+- **Steps: Auto / 12 / 16 / 20.** More steps, a longer wait (20 is the official reference recipe, about 2.4× Auto).
+- On H3 installs whose runner has a single adapter slot, an **Adapter** row asks whether that slot goes to **Turbo** or **My LoRA** — they cannot both run. See [LoRAs on H3](#docs/loras/h3-stacking).
+
+### Per-window prompts {#windows}
+
+A 10 s or 15 s H3 clip asks every 5-second window for the same prompt, which can repeat the action. Open **Per-window prompts** and turn on **One line per window**: 10 s gives two boxes, 15 s three. A box left empty uses the main prompt.
+
+### H3 first frame and orientation {#h3-image}
+
+Image mode works on H3 — the picture is the first frame. Under **Customize**, **Orientation** turns the tier's canvas **Portrait** at the same cost.
+
+## Engines side by side {#engines}
+
+| | LTX | Hailuo H3 |
+|---|---|---|
+| Modes | all Video modes, Remix, Audio | Text, Image |
+| Sound | joint with the picture | joint video, dialogue and sound |
+| Characters and LoRAs | trained characters, LoRA stacks | its own H3 LoRA library |
+| Avoid box | on High and the guided modes | none — say it in the prompt |
+| Longest clip | 20s (Quick), 10s otherwise | 15s, chained windows |
+| Memory | the Tier dialog (health chip → Tier) shows which qualities this Mac runs | 36 GB or more (see below) |
+
+**H3 and memory.** The full H3 engine needs 60 GB. From 36 GB up, H3 runs on its compact Q8 engine, which **Install Hailuo H3** in Pinokio's Phosphene sidebar builds locally (about 5 minutes, ~22 GB, no extra download). Settings → **Hailuo H3 model** chooses between Automatic, Full and Compact. Below 36 GB, H3 is not offered — render on LTX. See [Troubleshooting](#docs/troubleshooting/memory).
+
+## Upscale and export {#upscale}
+
+After the render, the clip can be resized without cropping.
+
+**On Hailuo H3** (under Customize → **Upscale**):
+
+- **Native** — as rendered.
+- **720p fit** / **1080p fit** — scaled and padded to fit. 720p fit is the default.
+- **LTX ×2** — *generated detail*: queues an **Upscale ×2** pass right after the draft, which re-renders it at twice the size with LTX-2.5 and keeps the sound. It needs the 0.3 GB Upscale adapter, downloaded from the Models window.
+
+**On LTX** (under Customize → **Export**): **Native** (default), **720p fit**, or **2×**. When it is not Native, **Method** chooses **Fast** (instant) or **Sharp** (a sharper upscaler, +30–90 s).
+
+Any finished clip can also go through [LTX Upscale](#docs/remix/ltx-upscale) later.
+
+## More controls {#more}
+
+- **Seed** — `-1` is random; reuse a seed to get the same take with a changed prompt.
+- **LoRAs** — the add-ons picker. See [LoRAs](#docs/loras).
+- **Orientation** (LTX) — 16:9 or 9:16.
+- **Customize** — width × height, duration and frames, and **Open file when done**.
+- **⊞ Batch** — paste many prompts and queue them all.
diff --git a/webapp/index.html b/webapp/index.html
index c19a888..baf70f8 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -55,6 +55,7 @@
<symbol id="ph-info-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z"/></symbol>
<symbol id="ph-info" viewBox="0 0 256 256"><circle cx="128" cy="128" r="96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="120 120 128 120 128 172 136 172" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="126" cy="84" r="10" fill="currentColor"/></symbol>
<symbol id="ph-magnifying-glass" viewBox="0 0 256 256"><circle cx="112" cy="112" r="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="168.57" y1="168.57" x2="224" y2="224" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
+<symbol id="ph-book-open" viewBox="0 0 256 256"><path d="M128,88a32,32,0,0,1,32-32h72V200H160a32,32,0,0,0-32,32" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M24,200H96a32,32,0,0,1,32,32V88A32,32,0,0,0,96,56H24Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
<symbol id="ph-pause-fill" viewBox="0 0 256 256"><path d="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z"/></symbol>
<symbol id="ph-pencil-simple" viewBox="0 0 256 256"><path d="M92.69,216H48a8,8,0,0,1-8-8V163.31a8,8,0,0,1,2.34-5.65L165.66,34.34a8,8,0,0,1,11.31,0L221.66,79a8,8,0,0,1,0,11.31L98.34,213.66A8,8,0,0,1,92.69,216Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="136" y1="64" x2="192" y2="120" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
<symbol id="ph-play-fill" viewBox="0 0 256 256"><path d="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z"/></symbol>
@@ -253,6 +254,14 @@
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
</svg>
</button>
+ <!-- DOCS. The manual gets a door of its own beside the gear, with a WORD on
+ it: an icon alone is the discoverability problem the Docs exist to fix
+ (users asked for features that already shipped because nothing on
+ screen used their words). ? opens it too, on the shortcuts page. -->
+ <button id="docsBtn" type="button" class="icon-btn docs-btn" onclick="openDocs()"
+ data-shortcut="docs.open" title="Docs — how every tool works, and every shortcut">
+ <svg class="ph" aria-hidden="true"><use href="#ph-book-open"/></svg><span class="docs-btn-word">Docs</span>
+ </button>
<button id="stopComfyBtn" class="ghost-btn" style="display:none" onclick="api('/stop_comfy', 'POST').then(poll)">Stop Comfy</button>
<!-- Official Phosphene account on X (2026-05-18). Sits next to the
"by Bizarro" creator credit so the two brand links read as a
@@ -291,6 +300,11 @@
localStorage so the user lands on the same tab next session. -->
<nav class="workflow-tabs" id="workflowTabs">
<button data-workflow="manual" class="active"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-film-strip"/></svg>Video</button>
+ <!-- One Shot is its own door (2026-09-08): one continuous shot of 30 s – 2 min,
+ with its own composer and its own API (POST /oneshot). It was a mode chip
+ on the video form; a shot that never cuts is a different thing to make
+ than a clip, and it gets the tab. -->
+ <button data-workflow="oneshot"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-target"/></svg>One Shot</button>
<button data-workflow="studio"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-image"/></svg>Images</button>
<!-- Storyboard sits next to the video surfaces; Audio and Train are the
two "go elsewhere and come back" tabs. No NEW badge on purpose —
@@ -348,14 +362,6 @@
toggle inside another mode. Q8-only — hidden on cap_tier="q4". -->
<button type="button" class="mode-chip pill-btn" data-mode="character">Character<span class="mc-sub sub">trained face + voice</span></button>
<button type="button" class="mode-chip pill-btn" data-mode="i2v">Image<span class="mc-sub sub">image + prompt</span></button>
- <!-- ONE SHOT — a different way of making a video, not a length on the
- clip form: one continuous shot of 30 s – 2 min that never cuts,
- written as beats. A UI mode like Character: the hidden #mode input
- ships t2v (or i2v when an anchor image is set) and make_job reads
- take_seconds + beats. setMode('oneshot') in boot.js opens the One
- Shot panel (#takeAxes); every other mode closes it and zeroes
- take_seconds, so a normal clip never carries a take. -->
- <button type="button" class="mode-chip pill-btn" data-mode="oneshot">One Shot<span class="mc-sub sub">30 s – 2 min · never cuts</span></button>
<button type="button" class="mode-chip pill-btn" data-mode="keyframe">FFLF<span class="mc-sub sub">first + last</span></button>
<!-- Multi-keyframe shares backend mode="keyframe"; the form dropdown
chooses any total anchor count from 3–8. -->
@@ -973,10 +979,6 @@
continuity toggles are read by make_job as on/off: light lock
appends the continuity sentence to every beat, retake allows one
re-render of a part whose light drifted. -->
- <input type="hidden" name="take_seconds" id="take_seconds" value="0">
- <input type="hidden" name="beats" id="beats" value="">
- <input type="hidden" name="take_light_lock" id="take_light_lock" value="on">
- <input type="hidden" name="take_retake" id="take_retake" value="on">
<input type="hidden" name="h3_tier" id="h3_tier" value="draft_3s">
<input type="hidden" name="h3_quality" id="h3_quality" value="draft">
<input type="hidden" name="h3_length" id="h3_length" value="3s">
@@ -1110,105 +1112,6 @@
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>
- <!-- ONE SHOT — its own mode, its own panel. Visible ONLY in One Shot
- mode (setMode('oneshot') removes `hidden`; every other mode
- puts it back). A different way of making a video from the clip
- modes above: one continuous shot of 30 s – 2 min, written as
- beats, rendered as parts that continue from each other's last
- frame. The engine's own Length strip is folded while this is
- open — a shot IS the length. Ids are unchanged from the strip
- era (#takeAxes, #takeGroup, data-take, #beatsRow, #beats_text,
- #takeEstimate) so setTakeSeconds / sbSetTake / Load Params
- keep working. The part labels are written by
- oneshotRefreshLabels() from document.body.dataset.engine (15 s
- parts on H3, 10 s on LTX) and refreshed on every setEngine. -->
- <div class="take-axes oneshot-panel" id="takeAxes" hidden>
- <div class="qs-label h3-axis-label">
- <span class="qs-name">Length</span>
- <span class="qs-meta" id="takeHint">one continuous shot · the camera never cuts · <a href="/docs/prompting" target="_blank" rel="noopener">how to write the beats</a></span>
- </div>
- <div class="quality-strip pill-group cols-5" id="takeGroup">
- <button type="button" class="q-chip pill-btn pill-quality" data-take="30" onclick="setTakeSeconds(30)" title="30 seconds, one continuous shot: 6 beats of 5 s.">
- <span class="ql-name">30 s</span><span class="q-spec ql-spec sub">6 beats</span><span class="ql-tier take-parts"></span></button>
- <button type="button" class="q-chip pill-btn pill-quality" data-take="45" onclick="setTakeSeconds(45)" title="45 seconds, one continuous shot: 9 beats of 5 s.">
- <span class="ql-name">45 s</span><span class="q-spec ql-spec sub">9 beats</span><span class="ql-tier take-parts"></span></button>
- <button type="button" class="q-chip pill-btn pill-quality active" data-take="60" onclick="setTakeSeconds(60)" title="One minute, one continuous shot: 12 beats of 5 s.">
- <span class="ql-name">1 min</span><span class="q-spec ql-spec sub">12 beats</span><span class="ql-tier take-parts"></span></button>
- <button type="button" class="q-chip pill-btn pill-quality" data-take="90" onclick="setTakeSeconds(90)" title="A minute and a half, one continuous shot: 18 beats of 5 s.">
- <span class="ql-name">1½ min</span><span class="q-spec ql-spec sub">18 beats</span><span class="ql-tier take-parts"></span></button>
- <button type="button" class="q-chip pill-btn pill-quality" data-take="120" onclick="setTakeSeconds(120)" title="Two minutes, one continuous shot: 24 beats of 5 s.">
- <span class="ql-name">2 min</span><span class="q-spec ql-spec sub">24 beats</span><span class="ql-tier take-parts"></span></button>
- </div>
- <div class="take-beats" id="beatsRow" hidden>
- <!-- The split button sits IN the label row, on the right: it
- is a tool for this box, not a row of its own. It only
- splits sentences, and its name says so. -->
- <div class="qs-label h3-axis-label beats-label">
- <span class="qs-name">Beats</span>
- <span class="qs-meta" id="beatsHint">one line per 5 seconds — what happens in that moment</span>
- <button type="button" class="ghost-btn small" id="beatsPrefillBtn" onclick="takePrefillClick()"
- title="Splits the prompt above into one beat per line — a start to edit, not the final word.">Split my prompt into beats</button>
- </div>
- <textarea id="beats_text" class="sb-textarea" rows="6" spellcheck="false"
- oninput="beatsInput()"
- placeholder="she pushes off down the sunlit avenue&#10;a van sweeps past, pigeons burst up ahead&#10;she drops off the kerb into the road&#10;…"></textarea>
- </div>
- <!-- The camera, once, for the whole shot. The handoff anchors the
- picture between parts but not the motion; this line is carried
- into every part's prompt so the move continues in the same
- direction at the same speed across the join (take_camera_lock).
- Left blank, later parts still get the generic continuity line. -->
- <div class="oneshot-camera" id="oneshotCamera">
- <div class="qs-label h3-axis-label">
- <span class="qs-name">Camera</span>
- <span class="qs-meta">optional · one move for the whole shot, its direction and speed — every part continues it</span>
- </div>
- <input type="text" name="take_camera" id="take_camera" class="sb-input" maxlength="240" autocomplete="off" spellcheck="false"
- placeholder="a slow, steady clockwise arc around the table at eye level, wide to close">
- </div>
- <!-- Start frame (optional). The SAME hidden `image` field as
- Image mode, through the same /upload path (pickerUploadFile),
- so when it is set the hidden #mode becomes i2v and the shot
- starts from this frame. Image mode's own picker stays folded
- in this mode; this is the only surface for it here. -->
- <div class="oneshot-anchor" id="oneshotAnchor">
- <div class="qs-label h3-axis-label">
- <span class="qs-name">Start frame</span>
- <span class="qs-meta">optional · the shot starts from this picture</span>
- </div>
- <div class="oneshot-anchor-row">
- <img class="oneshot-anchor-thumb" id="oneshotAnchorThumb" alt="" hidden>
- <button type="button" class="ghost-btn small" id="oneshotAnchorPick" onclick="document.getElementById('oneshotAnchorFile').click()">Choose an image</button>
- <button type="button" class="ghost-btn small" id="oneshotAnchorClear" onclick="oneshotClearAnchor()" hidden>Clear</button>
- <span class="oneshot-anchor-name sub" id="oneshotAnchorName"></span>
- <input type="file" id="oneshotAnchorFile" accept="image/*" hidden onchange="oneshotAnchorPicked(this)">
- </div>
- </div>
- <!-- Continuity. Both default ON; make_job reads on/off. -->
- <div class="oneshot-toggles">
- <div class="oneshot-toggle">
- <div class="qs-label h3-axis-label">
- <span class="qs-name">Lock the light</span>
- <span class="qs-meta">keeps the time of day and weather the same in every line</span>
- </div>
- <div class="pill-group cols-2" id="takeLightLockGroup">
- <button type="button" class="pill-btn active" data-take-light="on" onclick="setTakeLightLock('on')"><span>On</span><span class="sub">same light, every line</span></button>
- <button type="button" class="pill-btn" data-take-light="off" onclick="setTakeLightLock('off')"><span>Off</span><span class="sub">lines as written</span></button>
- </div>
- </div>
- <div class="oneshot-toggle">
- <div class="qs-label h3-axis-label">
- <span class="qs-name">Redo a part that drifts</span>
- <span class="qs-meta">if a part changes the light, it is rendered once more</span>
- </div>
- <div class="pill-group cols-2" id="takeRetakeGroup">
- <button type="button" class="pill-btn active" data-take-retake="on" onclick="setTakeRetake('on')"><span>On</span><span class="sub">once more, at most</span></button>
- <button type="button" class="pill-btn" data-take-retake="off" onclick="setTakeRetake('off')"><span>Off</span><span class="sub">keep the first pass</span></button>
- </div>
- </div>
- </div>
- <div class="take-estimate" id="takeEstimate" aria-live="polite"></div>
- <div class="oneshot-note" id="takeEngineNote"></div>
</div>
<!-- ========== PER-WINDOW PROMPTS (chained lengths only) ==========
@@ -3019,6 +2922,124 @@
present the pipeline anchors frame 0 (same shape as I2V), so
the same surface covers both pure A2V (audio only) and
Image + Audio (audio + still). -->
+ <!-- ========== ONE SHOT — its own door (2026-09-08) ==========
+ One continuous shot of 30 s – 2 min that never cuts, rendered as parts
+ that continue from each other's last frame. Its own composer: the shot
+ (engine, one prompt, a start frame, who is in it), then length and
+ quality with the cost on this Mac, then direction (beats with a time
+ gutter, one camera line, three continuity switches), then Generate and
+ a part-by-part status. Nothing here rides the video form: webapp/js/
+ oneshot.js reads these fields, posts ONE document to POST /oneshot
+ (panel/routes_oneshot.py — the same document a script posts) and paints
+ the take from GET /oneshot/status. -->
+ <div id="oneshotSectionTab" style="display:none">
+ <div class="composer-card os-card">
+ <h2>One Shot <span class="h2-hint">30 s to 2 min · never cuts</span></h2>
+ <div class="hint os-lead">Write the whole shot once and it renders as parts that continue from each other's last frame. Everything below is optional: the beats direct five seconds each, one camera line holds the move, and a trained character speaks with its own face and voice.</div>
+
+ <div class="os-block">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Engine</span><span class="qs-meta" id="osEngineMeta"></span></div>
+ <div class="pill-group cols-2" id="osEngineGroup" role="group" aria-label="Engine">
+ <button type="button" class="pill-btn active" data-os-engine="ltx" aria-label="LTX 2.5 — 10 second parts, faces, voices, dialogue"><span>LTX 2.5</span><span class="sub">10 s parts · faces, voices, dialogue</span></button>
+ <button type="button" class="pill-btn" data-os-engine="h3" aria-label="Hailuo H3 — 15 second parts, motion, landscapes, crowds"><span>Hailuo H3</span><span class="sub">15 s parts · motion, landscapes, crowds</span></button>
+ </div>
+ </div>
+
+ <div class="os-block">
+ <div class="qs-label h3-axis-label"><span class="qs-name">The shot</span><span class="qs-meta">who, where, the time of day and the weather, the sound — once, for the whole shot</span></div>
+ <textarea id="osPrompt" class="sb-textarea os-prompt" rows="4" spellcheck="false" placeholder="A red vintage tram rolls through a rain-soaked Lisbon street at night, neon on the wet cobbles; a woman with a yellow umbrella waits at the stop. The tram bell rings twice; rain on the roof, distant fado from a bar."></textarea>
+ </div>
+
+ <div class="os-two">
+ <div class="os-block">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Start frame</span><span class="qs-meta">optional · the shot opens on this picture</span></div>
+ <div class="os-anchor" id="osAnchor">
+ <img class="os-anchor-thumb" id="osAnchorThumb" alt="" hidden>
+ <button type="button" class="ghost-btn small" id="osAnchorPick">Choose an image</button>
+ <button type="button" class="ghost-btn small" id="osAnchorClear" hidden>Clear</button>
+ <span class="sub os-anchor-name" id="osAnchorName"></span>
+ <input type="file" id="osAnchorFile" accept="image/*" hidden>
+ </div>
+ </div>
+ <div class="os-block" id="osCharacterBlock">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Who is in it</span><span class="qs-meta" id="osCharacterMeta">optional · a trained character, with its own face and voice</span></div>
+ <div class="pill-group os-characters" id="osCharacterGroup" role="group" aria-label="Who is in it"></div>
+ <div class="hint os-character-note" id="osCharacterNote" hidden></div>
+ </div>
+ </div>
+ </div>
+
+ <div class="composer-card os-card">
+ <div class="os-block">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Length</span><span class="qs-meta" id="osLengthMeta"></span></div>
+ <div class="quality-strip pill-group cols-5" id="osLengthGroup"></div>
+ </div>
+ <div class="os-block">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Quality</span><span class="qs-meta" id="osQualityMeta"></span></div>
+ <div class="quality-strip pill-group" id="osQualityGroup"></div>
+ </div>
+ <div class="os-estimate" id="osEstimate" aria-live="polite"></div>
+ </div>
+
+ <div class="composer-card os-card">
+ <div class="os-block">
+ <div class="qs-label h3-axis-label">
+ <span class="qs-name">Beats</span>
+ <span class="qs-meta" id="osBeatsHint">one line per five seconds · none written — the prompt carries the whole shot</span>
+ </div>
+ <div class="os-beats-tools">
+ <button type="button" class="ghost-btn small" id="osSplitBtn" title="Splits the shot above into one line per sentence — a start to edit, not the final word">Split my prompt into beats</button>
+ <button type="button" class="ghost-btn small" id="osPlanBtn" title="The planner writes one beat per five seconds from the shot above — about half a minute">Write the beats for me</button>
+ </div>
+ <!-- One row per five seconds, the stamp glued to its own field: a
+ beat that wraps or a box that scrolls can never put a stamp
+ beside the wrong line (the reviewer's first finding). -->
+ <div class="os-beat-rows" id="osBeats" role="group" aria-label="Beats, one per five seconds"></div>
+ <div class="hint os-beats-note">A blank row holds that moment. Enter moves to the next row; paste a whole list and it fills the rows. <a href="/docs/prompting" target="_blank" rel="noopener">How to write the beats</a>.</div>
+ </div>
+ <div class="os-block">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Camera</span><span class="qs-meta">optional · one move for the whole shot, its direction and speed — every part continues it</span></div>
+ <input type="text" id="osCamera" class="sb-input" maxlength="240" autocomplete="off" spellcheck="false" placeholder="a slow, steady clockwise arc around the table at eye level, wide to close">
+ </div>
+ <div class="os-toggles">
+ <div class="os-toggle">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Lock the light</span><span class="qs-meta">the time of day and the weather stay the same in every part</span></div>
+ <div class="pill-group cols-2" data-os-toggle="light" role="group" aria-label="Lock the light"><button type="button" class="pill-btn active" data-os-value="on"><span>On</span><span class="sub">same light, every part</span></button><button type="button" class="pill-btn" data-os-value="off"><span>Off</span><span class="sub">beats as written</span></button></div>
+ </div>
+ <div class="os-toggle">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Redo a part that drifts</span><span class="qs-meta">a part whose light changes is rendered once more</span></div>
+ <div class="pill-group cols-2" data-os-toggle="retake" role="group" aria-label="Redo a part that drifts"><button type="button" class="pill-btn active" data-os-value="on"><span>On</span><span class="sub">once more, at most</span></button><button type="button" class="pill-btn" data-os-value="off"><span>Off</span><span class="sub">keep the first pass</span></button></div>
+ </div>
+ <div class="os-toggle">
+ <div class="qs-label h3-axis-label"><span class="qs-name">Hand off where the line ends</span><span class="qs-meta">for dialogue: the next part starts while the mouth still moves</span></div>
+ <div class="pill-group cols-2" data-os-toggle="handoff" role="group" aria-label="Hand off where the line ends"><button type="button" class="pill-btn" data-os-value="speech"><span>On</span><span class="sub">a talking character</span></button><button type="button" class="pill-btn active" data-os-value="last"><span>Off</span><span class="sub">on the last frame</span></button></div>
+ </div>
+ </div>
+ <details class="os-more" id="osMore">
+ <summary>More</summary>
+ <div class="os-more-grid">
+ <label class="os-field"><span class="sub">Seed</span><input type="text" id="osSeed" class="sb-input" inputmode="numeric" placeholder="random" autocomplete="off"></label>
+ <label class="os-field"><span class="sub">Label</span><input type="text" id="osLabel" class="sb-input" maxlength="120" placeholder="how it appears in the queue" autocomplete="off"></label>
+ <label class="os-field os-check"><input type="checkbox" id="osNoMusic"><span>No music</span><span class="sub">voice, sound and ambience only</span></label>
+ </div>
+ </details>
+ </div>
+
+ <div class="form-action-footer os-footer">
+ <div class="queue-strip"><span class="qchip-derived" id="osSummary"></span></div>
+ <div class="actions">
+ <button type="button" class="primary" id="osGenBtn">Generate</button>
+ <button type="button" class="danger" onclick="api('/stop','POST').then(poll)">Stop</button>
+ </div>
+ </div>
+
+ <div class="composer-card os-card os-status" id="osStatus" hidden>
+ <div class="qs-label h3-axis-label"><span class="qs-name" id="osStatusTitle">Rendering</span><span class="qs-meta" id="osStatusMeta"></span></div>
+ <div class="os-parts" id="osParts"></div>
+ <pre class="os-log" id="osLog"></pre>
+ </div>
+ </div>
+
<div id="audioSectionTab" style="display:none">
<div class="composer-card">
<div class="composer-refs">
@@ -3222,7 +3243,7 @@
<select class="sb-input ed-pool-film" id="edPoolFilm" hidden
onchange="edPoolPickFilm(this.value)"
aria-label="Which __SEQ__ to take clips from"></select>
- <input type="text" class="sb-input ed-pool-search" id="edPoolSearch"
+ <input type="text" class="sb-input ed-pool-search" id="edPoolSearch" data-shortcut="search.focus" title="Filter the media pool by name"
spellcheck="false" placeholder="Filter by name"
oninput="edPoolPaint()">
<div class="ed-pool-list" id="edPoolList"></div>
@@ -3428,7 +3449,7 @@
<span class="po-act-label">Hide preview</span>
</button>
<button id="expandBtn" class="po-act" type="button"
- onclick="openExpandLightbox()" title="Expand to fullscreen (Esc to close)">
+ onclick="openExpandLightbox()" title="Expand to fullscreen — Esc closes it" data-shortcut="outputs.expand">
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path d="M3 6 V3 H6 M10 3 H13 V6 M13 10 V13 H10 M6 13 H3 V10"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
@@ -3717,11 +3738,12 @@
<!-- 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">
- <button type="button" class="ghost-btn" id="sbeUndoBtn" onclick="sbeUndo()" title="Undo (⌘Z)" disabled>Undo</button>
- <button type="button" class="ghost-btn" id="sbeRedoBtn" onclick="sbeRedo()" title="Redo (⇧⌘Z)" disabled>Redo</button>
+ <button type="button" class="ghost-btn" id="sbeUndoBtn" onclick="sbeUndo()" title="Undo" data-shortcut="editor.undo" disabled>Undo</button>
+ <button type="button" class="ghost-btn" id="sbeRedoBtn" onclick="sbeRedo()" title="Redo" data-shortcut="editor.redo" disabled>Redo</button>
</span>
<button type="button" class="ghost-btn" id="sbeSaveBtn" onclick="sbeSaveNow()"
- title="Save now and say so. The editor also saves on its own, quietly, a second after every edit.">Save</button>
+ data-shortcut="editor.save"
+ title="Save the draft. Save is the only thing that writes it — between saves your edits are kept as a backup you can restore from Drafts.">Save</button>
<!-- RENDER CAME UP, NOT OUT. It was the far corner of a sticky bar at
the bottom of the column, 54px of chrome under the timeline to
hold two buttons; it is the one thing this screen is FOR, so it is
@@ -3729,7 +3751,8 @@
the render note, because it is the same verb pointed elsewhere. -->
<span class="sbe-split">
<button type="button" class="primary" id="sbeRenderBtn" onclick="sbeRenderFilm()"
- title="Render this timeline into one file (⌘R)">Render</button>
+ data-shortcut="editor.render"
+ title="Render this timeline into one file">Render</button>
<button type="button" class="primary sbe-car-btn" id="sbeRenderMore"
onclick="sbePopToggle('sbeRenderMenu', 'sbeRenderMore')"
aria-haspopup="menu" title="Export, and what the render will do">▾</button>
@@ -3800,7 +3823,20 @@
<div class="sbe-pop sbe-pop-wide" id="sbeKeysPop" hidden>
<span class="sbe-note sbe-keys" id="sbeKeys"></span>
+ <a class="sbe-keys-docs" href="#docs/shortcuts/keys-editor">Every shortcut, in the Docs →</a>
</div>
+ <!-- THE CLIP BAR'S OVERFLOW. Empty in the markup on purpose: the bar
+ MOVES its own buttons in here when the pane is too narrow for them
+ and moves them back out when it is not, so there is exactly one
+ copy of every control and no second set of ids to keep in step. -->
+ <div class="sbe-pop sbe-cbar-pop" id="sbeCbarMenu" hidden></div>
+ <!-- RIGHT-CLICK ON THE TRACK. The same verbs the clip bar carries, at
+ the pointer, because that is the second place every editor's hand
+ goes and this timeline answered a right-click with the browser's
+ own menu. Painted by sbeCtxOpen — a context menu whose items are
+ written for the thing under the pointer is the only kind worth
+ having, and a gap's only verb is "close it". -->
+ <div class="sbe-pop sbe-ctx" id="sbeCtxMenu" hidden></div>
<div class="sbe-pop sbe-pop-wide" id="sbeMusicMenu" hidden>
<span class="sbe-pop-note" id="sbePrepText">The soundtrack drives the waveform and the beat grid.</span>
<input type="text" class="sb-input" id="sbeMusic" spellcheck="false"
@@ -3951,6 +3987,11 @@
<button type="button" class="ghost-btn" id="sbeRelinkBtn"
onclick="sbeRelink()">Use the finished versions</button>
</div>
+ <!-- A RETAKE'S OFFER. One line per new take — "Use it" / "Keep the old
+ one" — painted by sbePaintRelink. It was written into this id from
+ the day Retake shipped and the element did not exist, so a finished
+ retake could never be put on the timeline. -->
+ <div class="sbe-relink sbe-retakes" id="sbeRetakes" hidden></div>
<!-- ============== THE TWO MONITORS =========================
@@ -4050,25 +4091,122 @@
</div>
</div>
+ <!-- ============== THE CLIP BAR ==============================
+ "It's really hard when you are using the editor of Phosphene to
+ use the basic tools you actually need to use all the time, for
+ instance, unlink and link audio… We have some, but they are hidden
+ inside that menu, the toggle menu on the right. That is not a good
+ use."
+
+ Every verb below already existed — inside the inspector, in the
+ rail, beside a brightness slider and a zoom range, which is where
+ an NLE keeps PROPERTIES and not where it keeps VERBS. A cutter
+ reaches for split / lift / ripple / unlink / resync hundreds of
+ times in a session and for "font size" twice, and the two were
+ drawn identically in the same 212px column. So the verbs came out
+ and the properties stayed: see docs/EDITOR_TOOLBAR.md.
+
+ It is the row directly above the tracks, which is where Resolve
+ and Final Cut both put it, and it is the empty half of a row that
+ already existed rather than a new band of chrome — the height
+ budget in sbeFitMonitors measures its children, so a row that
+ costs 30px costs the picture 30px, and the picture is the thing
+ this screen is for.
+
+ EVERY BUTTON IS ALWAYS HERE. They DISABLE rather than disappear,
+ and a disabled button's tooltip says what would have to be true
+ 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. -->
+ <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-unlock"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.5-2"/></g>
+ </defs></svg>
+ <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. -->
+ <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()">
+ <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()">
+ <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()">
+ <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()">
+ <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()">
+ <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()">
+ <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()">
+ <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()">
+ <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()">
+ <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()">
+ <svg class="sbe-cbar-i"><use href="#ic-lock" id="sbeCbLockUse"/></svg><b>Lock</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. -->
+ <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()">Play</button>
+ <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 (M)">🔊</button>
+ 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">
+ <label class="check" style="margin:0;font-size:11px" 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
</label>
<!-- The two sliders an editor expects: the scrollbar on the track
below moves the view, this one changes the scale. All the way
left is the whole film in the window, whatever the window is. -->
<span class="sbe-zoom">
- <button type="button" class="ghost-btn" onclick="sbeZoom(-1)"
- title="Zoom out (alt + wheel over the track does the same, around the pointer)">−</button>
+ <button type="button" class="ghost-btn" onclick="sbeZoom(-1)" title="Zoom out" data-shortcut="editor.zoom">−</button>
<input type="range" id="sbeZoomRange" min="0" max="1000" step="1" value="500"
aria-label="Timeline zoom"
- title="Zoom. Fully left fits the whole __SEQ__ in the window. Over the track: shift + wheel pans, alt + wheel zooms."
+ title="Zoom. Fully left fits the whole __SEQ__ in the window. + and − on the keyboard. Over the track: shift + wheel pans, alt + wheel or a trackpad pinch zooms."
oninput="sbeZoomSlide(this.value)">
- <button type="button" class="ghost-btn" onclick="sbeZoom(1)" title="Zoom in">+</button>
+ <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;
@@ -4241,7 +4379,7 @@
quality, engine, size, seed, LoRA and character names. A
substring test on one lower-cased string per output, so it is
free per keystroke; the title says how many match. -->
- <input type="search" class="sb-input outputs-search" id="outputsSearch"
+ <input type="search" class="sb-input outputs-search" id="outputsSearch" data-shortcut="search.focus" title="Search outputs"
placeholder="Search prompts, models, LoRAs, sizes…" aria-label="Search outputs"
spellcheck="false" oninput="setOutputsQuery(this.value)" onsearch="setOutputsQuery(this.value)">
<span class="ch-spacer"></span>
@@ -4927,6 +5065,41 @@
in the bottom strip until done. Newly-installed models appear in the
local-engine model picker on next refresh. -->
<!-- ============== BATCH MODAL ============== -->
+<!-- THE DOCS VIEW (webapp/js/docs.js; pages in webapp/docs/*.md). A .modal-bg
+ so the Editor's keys stand down while it is open and health.js's Esc and
+ focus trap cover it; the Close button's onclick names close for Esc. -->
+<div class="modal-bg docs-view" id="docsView" role="dialog" aria-modal="true"
+ aria-labelledby="docsViewTitle" onclick="if(event.target===this) closeDocs()">
+ <div class="docs-shell">
+ <aside class="docs-nav" id="docsNav" aria-label="Docs sections">
+ <div class="docs-brand">
+ <svg class="ph" aria-hidden="true"><use href="#ph-book-open"/></svg>
+ <span id="docsViewTitle">Phosphene Docs</span>
+ </div>
+ <label class="docs-search-wrap">
+ <svg class="ph" aria-hidden="true"><use href="#ph-magnifying-glass"/></svg>
+ <input type="search" class="docs-search" id="docsSearch" placeholder="Search the docs"
+ aria-label="Search the docs" spellcheck="false" autocomplete="off">
+ </label>
+ <nav class="docs-toc" id="docsToc"></nav>
+ <div class="docs-results" id="docsResults" hidden></div>
+ </aside>
+ <section class="docs-main">
+ <header class="docs-bar">
+ <button type="button" class="ghost-btn docs-nav-toggle" id="docsNavToggle"
+ aria-controls="docsNav" aria-expanded="false">Sections</button>
+ <span class="docs-crumb" id="docsCrumb"></span>
+ <span class="docs-bar-spacer"></span>
+ <button type="button" class="ghost-btn docs-close" onclick="closeDocs()" title="Close the Docs (⎋ Esc)">Close</button>
+ </header>
+ <div class="docs-scroll" id="docsScroll">
+ <article class="docs-article" id="docsArticle"></article>
+ <nav class="docs-pagenav" id="docsPageNav" aria-label="Previous and next page"></nav>
+ </div>
+ </section>
+ </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>
@@ -5024,6 +5197,8 @@ Third prompt."></textarea>
<script>
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/docs.js"></script>
<script type="module" src="/webapp/js/stage.js"></script>
<script type="module" src="/webapp/js/characters.js"></script>
<script type="module" src="/webapp/js/engines.js"></script>
@@ -5034,6 +5209,7 @@ const BOOT = __BOOTSTRAP__;</script>
<script type="module" src="/webapp/js/health.js"></script>
<script type="module" src="/webapp/js/storyboard.js"></script>
<script type="module" src="/webapp/js/editor.js"></script>
+<script type="module" src="/webapp/js/oneshot.js"></script>
<script type="module" src="/webapp/js/main.js"></script>
<div class="phos-toast-container" id="phosToast" aria-live="polite" aria-atomic="false"></div>
</body>
diff --git a/webapp/js/boot.js b/webapp/js/boot.js
index 08029fd..152bb8e 100644
--- a/webapp/js/boot.js
+++ b/webapp/js/boot.js
@@ -609,6 +609,13 @@ function defaultRemixMode() {
}
function setMode(mode) {
+ // One Shot is a workflow tab now (webapp/js/oneshot.js), not a mode of
+ // this form: a stale 'oneshot' — a saved mode, an old Load Params path —
+ // opens the tab and leaves the video form as it was.
+ if (mode === 'oneshot') {
+ if (typeof workflowSwitch === 'function') { try { workflowSwitch('oneshot'); } catch (e) {} }
+ return;
+ }
// "remix" is a UI GROUP, not a backend mode — clicking the parent Remix pill
// resumes the last-used Remix tool (default Ingredients). Everything below
// (and the backend) only ever sees a real mode from REMIX_MODES.
@@ -643,13 +650,6 @@ function setMode(mode) {
mode = 't2v';
}
currentMode = mode;
- // ONE SHOT is a UI mode with its own panel (#takeAxes). Every OTHER mode
- // closes it and zeroes take_seconds here, before any early return below,
- // so a normal clip never carries a take — the field is hidden and FormData
- // would post it regardless of which chip is lit.
- if (mode !== 'oneshot' && typeof oneshotLeave === 'function') {
- try { oneshotLeave(); } catch (e) {}
- }
// HDR vs Character mutual exclusion — reflect mode change in pill state.
// Runs in a microtask so the rest of setMode finishes setting UI bits
// first (character chip strip visibility, etc.).
@@ -781,11 +781,7 @@ function setMode(mode) {
// picker keeps the previous mode's filter when flipping back from
// Studio to a video mode.
if (typeof renderLorasList === 'function') renderLorasList();
- // One Shot ships a real backend mode: t2v, or i2v when its anchor image is
- // set (the same hidden #image field Image mode fills). make_job reads
- // take_seconds + beats off the same form and turns the clip into parts.
- document.getElementById('mode').value =
- (mode === 'oneshot' && typeof oneshotBackendMode === 'function') ? oneshotBackendMode() : mode;
+ document.getElementById('mode').value = mode;
document.querySelectorAll('#modeGroup .pill-btn').forEach(b => {
if (mode === 'keyframe') {
b.classList.toggle('active', isKeyframeModeChipActive(b, window._kfMode));
@@ -827,11 +823,6 @@ function setMode(mode) {
if (mode === 'keyframe') {
setQuality('high');
}
- // Open the One Shot panel: length chips (default 1 min), beats, anchor,
- // continuity toggles; the engine's own Length strip folds while it is open.
- if (mode === 'oneshot' && typeof oneshotEnter === 'function') {
- try { oneshotEnter(); } catch (e) { console.warn('oneshotEnter failed', e); }
- }
updateAccelAvailability();
updateTemporalAvailability();
updateDerived();
diff --git a/webapp/js/characters.js b/webapp/js/characters.js
index 7792a0a..12f75c4 100644
--- a/webapp/js/characters.js
+++ b/webapp/js/characters.js
@@ -2593,253 +2593,7 @@ function temporalModeAllowed() {
const mode = document.getElementById('mode').value;
return !_qualityUsesHq(q) && currentMode !== 'extend' && currentMode !== 'keyframe' && (mode === 't2v' || mode === 'i2v');
}
-// ---- ONE SHOT ---------------------------------------------------------------
-// One Shot is its own mode (the chip in #modeGroup, setMode('oneshot') in
-// boot.js): one continuous shot of 30 s – 2 min written as beats, one per five
-// seconds, rendered as parts that continue from each other's last frame. The
-// server does the arithmetic (make_job → take_plan); this keeps the form
-// honest: the engine's own length pills fold while the mode is open, the
-// beats box prefills from the prompt the first time, and the estimate comes
-// from /take/estimate. Leaving the mode calls setTakeSeconds(0) so a normal
-// clip never carries take_seconds.
-const TAKE_CHOICES = [0, 30, 45, 60, 90, 120];
-// The last length the user chose, so leaving the mode (which zeroes the
-// hidden field — a normal clip never carries take_seconds) and coming back
-// reopens on THEIR choice, not on the 1 min default every time.
-let _oneshotLastSeconds = 60;
-// A part is what continues from the last frame of the one before it: 15 s
-// (3 beats) on H3, 10 s (2 beats) on LTX. Read from the body's engine so the
-// labels follow the switcher; the server's own number wins in the estimate.
-function takePartSeconds(engine) {
- return (engine || document.body.dataset.engine || 'ltx') === 'h3' ? 15 : 10;
-}
-function setTakeSeconds(s, beats) {
- s = parseInt(s || 0, 10) || 0;
- if (!TAKE_CHOICES.includes(s)) s = 0;
- if (s) _oneshotLastSeconds = s;
- const hid = document.getElementById('take_seconds');
- if (hid) hid.value = String(s);
- document.querySelectorAll('#takeGroup .pill-btn').forEach(b =>
- b.classList.toggle('active', parseInt(b.dataset.take, 10) === s));
- const row = document.getElementById('beatsRow');
- if (row) row.hidden = !s;
- ['h3LengthGroup', 'ltxLengthGroup', 'temporalGroup', 'windowsRow'].forEach(id => {
- const g = document.getElementById(id);
- if (g) g.classList.toggle('take-locked', !!s);
- });
- const ta = document.getElementById('beats_text');
- if (s && ta) {
- // Only an explicit list (Load Params, the Storyboard) fills the box.
- // It used to prefill from the prompt on its own, which put ONE written
- // beat and five blank holds in front of a user who had only typed a
- // prompt — half a shot of prompt, half of hold. An empty box now means
- // "the prompt carries the whole shot" (make_job), and the Split button
- // is the deliberate way to start from the prompt's sentences.
- if (Array.isArray(beats)) ta.value = beats.join('\n');
- beatsInput();
- takeRefresh();
- } else {
- const b = document.getElementById('beats');
- if (b) b.value = '';
- const est = document.getElementById('takeEstimate');
- if (est) est.textContent = '';
- }
- if (typeof updateCustomizeSummary === 'function') updateCustomizeSummary();
- if (typeof updateDerived === 'function') updateDerived();
-}
-// The prompt's sentences, one per beat — the Split button's starting point.
-function takePrefill(s) {
- const prompt = (document.getElementById('prompt') || {}).value || '';
- const n = Math.max(1, Math.round(s / 5));
- const sents = prompt.split(/(?<=[.!?])\s+/).map(x => x.trim()).filter(Boolean);
- const out = [];
- for (let i = 0; i < n; i++) out.push(sents[i] || '');
- while (out.length && !out[out.length - 1]) out.pop();
- return out.join('\n');
-}
-// The "Split my prompt into beats" button: the same prefill, on demand, over
-// whatever is in the box. Explicit because the automatic one only fills an
-// EMPTY box — a user who typed three lines and changed the prompt has no
-// other way to start again from it.
-function takePrefillClick() {
- const ta = document.getElementById('beats_text');
- const s = parseInt((document.getElementById('take_seconds') || {}).value || '0', 10) || 0;
- if (!ta || !s) return;
- ta.value = takePrefill(s);
- beatsInput();
-}
-function beatsInput() {
- const ta = document.getElementById('beats_text');
- const out = document.getElementById('beats');
- const hint = document.getElementById('beatsHint');
- if (!ta || !out) return;
- const lines = String(ta.value || '').split('\n').map(x => x.trim());
- while (lines.length && !lines[lines.length - 1]) lines.pop();
- out.value = lines.length ? JSON.stringify(lines) : '';
- const s = parseInt((document.getElementById('take_seconds') || {}).value || '0', 10) || 0;
- const n = Math.round(s / 5);
- if (hint && n) {
- const filled = lines.filter(Boolean).length;
- const extra = lines.length - n;
- // Zero written is not an error: the prompt is the whole shot. Say so,
- // because a box that reads "0 written" next to a Generate button looks
- // like something the user forgot (field report, 2026-09-08).
- hint.textContent = filled === 0
- ? `${n} lines of 5 s · none written — the prompt carries the whole shot; write a line to direct a moment`
- : `${n} lines of 5 s · ${filled} written`
- + (filled < n ? ' · leave a line blank to hold on the scene' : '')
- + (extra > 0 ? ` · ${extra} extra line${extra === 1 ? '' : 's'} will be dropped` : '');
- }
-}
-let _takeRefreshSeq = 0;
-async function takeRefresh() {
- const el = document.getElementById('takeEstimate');
- const s = parseInt((document.getElementById('take_seconds') || {}).value || '0', 10) || 0;
- if (!el || !s) return;
- const engine = document.body.dataset.engine || 'ltx';
- const quality = engine === 'h3'
- ? ((document.getElementById('h3_quality') || {}).value || 'standard')
- : ((document.getElementById('quality') || {}).value || 'balanced');
- const seq = ++_takeRefreshSeq;
- el.textContent = 'working out the time…';
- try {
- const r = await (await fetch(`/take/estimate?engine=${encodeURIComponent(engine)}&quality=${encodeURIComponent(quality)}&seconds=${s}`)).json();
- if (seq !== _takeRefreshSeq) return;
- if (!r.ok) { el.textContent = r.error || ''; return; }
- const eng = r.engine || engine;
- const partSec = takePartSeconds(eng);
- // The server's count when it sends one; the same arithmetic otherwise.
- const parts = parseInt(r.parts, 10) || Math.ceil(s / partSec);
- const bits = [`${r.beats || Math.round(s / 5)} beats`];
- bits.push(`${parts} parts of ${partSec} s that continue from ` + (eng === 'h3' ? 'each other' : 'the last frame'));
- if (r.eta) bits.push(`about ${r.eta.replace(/^~/, '').replace(' · batch', '')} on this Mac`);
- else if (eng === 'ltx') bits.push('about 7 min per 5 s at Quick on this Mac');
- el.textContent = bits.join(' · ');
- } catch (e) { if (seq === _takeRefreshSeq) el.textContent = ''; }
-}
-// ---- the One Shot panel ----------------------------------------------------
-// What setMode('oneshot') opens and every other setMode closes. The mode-level
-// bits (the chip, currentMode, the hidden #mode) stay in boot.js; this owns
-// the panel: its visibility, the per-engine part labels, the anchor image and
-// the two continuity toggles.
-function oneshotActive() {
- return (typeof currentMode !== 'undefined') && currentMode === 'oneshot';
-}
-// The backend mode a One Shot ships under: i2v when an anchor image is set,
-// t2v otherwise. The same rule Image mode's submit guard applies (an i2v job
-// needs an image), read from the SAME hidden field.
-function oneshotBackendMode() {
- const img = (document.getElementById('image') || {}).value || '';
- return String(img).trim() ? 'i2v' : 't2v';
-}
-function oneshotEnter() {
- const panel = document.getElementById('takeAxes');
- if (panel) panel.hidden = false;
- document.body.classList.add('oneshot-mode');
- oneshotRefreshLabels();
- oneshotSyncAnchor();
- setTakeLightLock((document.getElementById('take_light_lock') || {}).value || 'on');
- setTakeRetake((document.getElementById('take_retake') || {}).value || 'on');
- const cur = parseInt((document.getElementById('take_seconds') || {}).value || '0', 10) || 0;
- setTakeSeconds(cur || _oneshotLastSeconds || 60);
-}
-function oneshotLeave() {
- const panel = document.getElementById('takeAxes');
- if (panel) panel.hidden = true;
- document.body.classList.remove('oneshot-mode');
- const cur = parseInt((document.getElementById('take_seconds') || {}).value || '0', 10) || 0;
- if (cur) setTakeSeconds(0);
- // The two continuity fields are hidden inputs in the video form, so
- // FormData posts them with EVERY clip. Back to their defaults on the way
- // out, or a normal clip's sidecar carries an "off" that meant nothing.
- setTakeLightLock('on');
- setTakeRetake('on');
-}
-// "1 min", "1½ min", "30 s" — the length as the chips name it, for the
-// footer strip and anywhere else the shot is summarised in one line.
-function takeLengthLabel(s) {
- s = parseInt(s || 0, 10) || 0;
- if (s < 60) return `${s} s`;
- const whole = Math.floor(s / 60);
- const rem = s - whole * 60;
- if (!rem) return `${whole} min`;
- if (rem === 30) return `${whole}½ min`;
- return `${whole} min ${rem} s`;
-}
-// The one-line summary of a One Shot for the footer strip: "1 min · 6 parts
-// of 10 s". The parts follow the engine (15 s on H3, 10 s on LTX); the
-// server's own count wins in the estimate, this is the label.
-function oneshotSummary(s, engine) {
- s = parseInt(s || 0, 10) || 0;
- if (!s) return '';
- const partSec = takePartSeconds(engine);
- const parts = Math.ceil(s / partSec);
- return `${takeLengthLabel(s)} · ${parts} part${parts === 1 ? '' : 's'} of ${partSec} s`;
-}
-// The part labels on the length chips and the one-line engine note. Called on
-// entry and from setEngine, because a part is 15 s on H3 and 10 s on LTX.
-function oneshotRefreshLabels() {
- const engine = document.body.dataset.engine || 'ltx';
- const partSec = takePartSeconds(engine);
- document.querySelectorAll('#takeGroup .pill-btn').forEach(b => {
- const s = parseInt(b.dataset.take, 10) || 0;
- const el = b.querySelector('.take-parts');
- if (el && s) {
- const n = Math.ceil(s / partSec);
- // One line, so the chip keeps the Quality strip's height.
- el.textContent = `${n} × ${partSec} s`;
- }
- });
- const note = document.getElementById('takeEngineNote');
- if (note) {
- note.textContent = engine === 'h3'
- ? 'Hailuo H3 — 15-second parts that continue from each other.'
- : 'LTX — 10-second parts that continue from the last frame.';
- }
-}
-// The anchor image. One hidden field (#image) for Image mode and One Shot,
-// one upload path (pickerUploadFile), so the server sees exactly the i2v it
-// already knows. This only mirrors that field into the panel's own thumbnail
-// and flips the hidden #mode while the mode is open.
-function oneshotSyncAnchor() {
- const path = String((document.getElementById('image') || {}).value || '').trim();
- const thumb = document.getElementById('oneshotAnchorThumb');
- const clear = document.getElementById('oneshotAnchorClear');
- const pick = document.getElementById('oneshotAnchorPick');
- const name = document.getElementById('oneshotAnchorName');
- if (thumb) {
- if (path) { thumb.src = `/image?path=${encodeURIComponent(path)}&w=160`; thumb.hidden = false; }
- else { thumb.removeAttribute('src'); thumb.hidden = true; }
- }
- if (clear) clear.hidden = !path;
- if (pick) pick.textContent = path ? 'Change the image' : 'Choose an image';
- if (name) name.textContent = path ? path.split('/').pop() : '';
- if (oneshotActive()) {
- const modeInp = document.getElementById('mode');
- if (modeInp) modeInp.value = oneshotBackendMode();
- }
-}
-async function oneshotAnchorPicked(input) {
- const f = input && input.files && input.files[0];
- if (!f) return;
- if (typeof pickerUploadFile === 'function') await pickerUploadFile('image', f);
- input.value = '';
- oneshotSyncAnchor();
-}
-function oneshotClearAnchor() {
- if (typeof pickerSetImage === 'function') pickerSetImage('image', '');
- oneshotSyncAnchor();
-}
-function _setTakeToggle(hiddenId, groupId, attr, v) {
- v = (String(v || 'on').toLowerCase() === 'off') ? 'off' : 'on';
- const hid = document.getElementById(hiddenId);
- if (hid) hid.value = v;
- document.querySelectorAll(`#${groupId} .pill-btn`).forEach(b =>
- b.classList.toggle('active', b.dataset[attr] === v));
- return v;
-}
-function setTakeLightLock(v) { return _setTakeToggle('take_light_lock', 'takeLightLockGroup', 'takeLight', v); }
-function setTakeRetake(v) { return _setTakeToggle('take_retake', 'takeRetakeGroup', 'takeRetake', v); }
+// ---- ONE SHOT: its own tab and module since 2026-09-08 — webapp/js/oneshot.js ---
function setTemporalMode(t) {
const allowed = temporalModeAllowed();
@@ -3020,8 +2774,6 @@ function updatePromptPlaceholder() {
prompt.placeholder = window._kfMode >= 3 ? keyframeMulti : keyframeTwo;
} else if (currentMode === 'i2v') {
prompt.placeholder = 'Describe how the reference image should move, plus sound cues. The image anchors frame 0; the prompt directs the full clip.';
- } else if (currentMode === 'oneshot') {
- prompt.placeholder = 'Describe the whole shot once — the subject, the world, the time of day and the sound. Then write one beat per five seconds below; the camera never cuts.';
} else if (currentMode === 'ingredients') {
prompt.placeholder = "Describe WHAT'S in the reference sheet — each character, prop, and the location. e.g. a friendly cartoon hedgehog with rounded chestnut fur; a green coiled garden hose; the bright interior of a 'Greenfield' garden store. (The Action field above describes the shot itself.)";
} else if (currentMode === 'control') {
@@ -3107,10 +2859,6 @@ document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b => b.onclick =
// Inline handlers in the markup and the other files resolve these through
// the global scope; everything NOT listed here is private to this module.
Object.assign(globalThis, {
- setTakeSeconds, takePrefill, takePrefillClick, beatsInput, takeRefresh,
- takePartSeconds, takeLengthLabel, oneshotSummary,
- oneshotEnter, oneshotLeave, oneshotBackendMode, oneshotRefreshLabels, oneshotSyncAnchor,
- oneshotAnchorPicked, oneshotClearAnchor, setTakeLightLock, setTakeRetake,
windowPromptsInput,
audioStudioInit, audioStudioDurationChanged, audioStudioEnhancePrompt, audioStudioGenerate,
trainRecommendedPreset, trainUpdatePresetButtons, trainUpdatePresetNote, downloadSampleCharacter,
diff --git a/webapp/js/docs.js b/webapp/js/docs.js
new file mode 100644
index 0000000..836b09e
--- /dev/null
+++ b/webapp/js/docs.js
@@ -0,0 +1,507 @@
+// THE DOCS — the manual, inside the panel.
+//
+// Why a view and not a page: the panel is one window (Pinokio's), the Docs
+// have to open over whatever you are doing and close back onto it with Esc,
+// and the Keyboard shortcuts page has to render from the SAME registry the
+// key handlers read (webapp/js/shortcuts.js) — which only exists in this
+// document. So the Docs are a full-height view in the panel's own chrome,
+// deep-linkable by hash: #docs/<section>/<anchor>.
+//
+// The words live in webapp/docs/*.md — plain Markdown an engineer edits
+// without a build step — and this file renders them with a small renderer
+// that knows exactly what the pages use: headings (with {#anchor}), lists,
+// tables, notes (>), code, links, and three directives:
+//
+// [[shortcuts]] / [[shortcuts:editor,editor-mouse]] the registry's table
+// [[sc:editor.split]] one shortcut's keys
+// [[icon:ph-trash-simple]] a panel icon
+//
+// Served from /webapp/docs/ by the panel itself: no network, no CDN.
+
+const DOCS_SECTIONS = [
+ { id: 'getting-started', title: 'Getting started', group: 'Start', file: 'getting-started.md' },
+ { id: 'video', title: 'Video', group: 'Make', file: 'video.md' },
+ { id: 'one-shot', title: 'One Shot', group: 'Make', file: 'one-shot.md' },
+ { id: 'remix', title: 'Remix', group: 'Make', file: 'remix.md' },
+ { id: 'images', title: 'Images', group: 'Make', file: 'images.md' },
+ { id: 'storyboard', title: 'Storyboard', group: 'Make', file: 'storyboard.md' },
+ { id: 'audio', title: 'Audio', group: 'Make', file: 'audio.md' },
+ { id: 'editor', title: 'Editor', group: 'Cut', file: 'editor.md' },
+ { id: 'train-character', title: 'Train Character', group: 'Characters', file: 'train-character.md' },
+ { id: 'loras', title: 'LoRAs', group: 'Characters', file: 'loras.md' },
+ { id: 'settings', title: 'Settings', group: 'Reference', file: 'settings.md' },
+ { id: 'shortcuts', title: 'Keyboard shortcuts', group: 'Reference', file: 'shortcuts.md' },
+ { id: 'buttons', title: 'Buttons and icons', group: 'Reference', file: 'buttons.md' },
+ { id: 'troubleshooting', title: 'Troubleshooting', group: 'Reference', file: 'troubleshooting.md' },
+];
+
+const DOCS = {
+ md: {}, rendered: {}, index: [], loading: null,
+ section: 'getting-started', returnFocus: null, spyRaf: 0,
+};
+
+// ---- rendering --------------------------------------------------------------
+function docsEsc(t) {
+ return String(t).replace(/[&<>"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[ch]));
+}
+
+function docsSlug(t) {
+ return String(t).toLowerCase()
+ .replace(/\[\[[^\]]*\]\]/g, '').replace(/[`*_]/g, '')
+ .replace(/[^a-z0-9\s-]/g, '').trim().replace(/\s+/g, '-').replace(/-+/g, '-');
+}
+
+// What a heading or a line SAYS, without its markup — for search and the TOC.
+function docsPlain(t) {
+ return String(t)
+ .replace(/\[\[sc:([\w.-]+)\]\]/g, (m, id) => (typeof shortcutHint === 'function' ? shortcutHint(id) : ''))
+ .replace(/\[\[[^\]]*\]\]/g, '')
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
+ .replace(/<\/?kbd>/g, '')
+ .replace(/[`*]/g, '')
+ .replace(/\s+/g, ' ').trim();
+}
+
+function docsInline(raw) {
+ const codes = [];
+ let s = String(raw).replace(/`([^`]+)`/g, (m, c) => { codes.push(c); return '\u0000' + (codes.length - 1) + '\u0000'; });
+ s = docsEsc(s);
+ s = s.replace(/\[\[sc:([\w.-]+)\]\]/g, (m, id) => {
+ const e = (typeof shortcutById === 'function') ? shortcutById(id) : null;
+ return e ? '<span class="docs-sc">' + shortcutKeysHtml(e, 'kbd') + '</span>'
+ : '<span class="docs-missing">' + docsEsc(id) + '</span>';
+ });
+ s = s.replace(/\[\[icon:([\w-]+)\]\]/g,
+ (m, id) => '<svg class="ph docs-icon" aria-hidden="true"><use href="#' + id + '"/></svg>');
+ s = s.replace(/&lt;kbd&gt;(.*?)&lt;\/kbd&gt;/g, '<kbd class="kbd">$1</kbd>');
+ s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, text, href) => {
+ const h = href.replace(/&amp;/g, '&');
+ if (/^#docs\//.test(h)) return '<a href="' + docsEsc(h) + '" class="docs-xref">' + text + '</a>';
+ if (/^https:\/\//.test(h)) return '<a href="' + docsEsc(h) + '" target="_blank" rel="noopener">' + text + '</a>';
+ return text;
+ });
+ s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
+ s = s.replace(/(^|[\s(])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>');
+ s = s.replace(/\u0000(\d+)\u0000/g, (m, i) => '<code>' + docsEsc(codes[Number(i)]) + '</code>');
+ return s;
+}
+
+function docsTable(rows) {
+ const cells = r => r.trim().replace(/^\|/, '').replace(/\|\s*$/, '').split('|').map(c => c.trim());
+ const head = cells(rows[0]);
+ let body = rows.slice(1);
+ if (body.length && /^[\s|:-]+$/.test(body[0])) body = body.slice(1);
+ return '<div class="docs-table-wrap"><table class="docs-table"><thead><tr>' +
+ head.map(h => '<th>' + docsInline(h) + '</th>').join('') + '</tr></thead><tbody>' +
+ body.map(r => '<tr>' + cells(r).map(c => '<td>' + docsInline(c) + '</td>').join('') + '</tr>').join('') +
+ '</tbody></table></div>';
+}
+
+const DOCS_HEADING = /^(#{1,3})\s+(.*?)(?:\s+\{#([\w-]+)\})?\s*$/;
+const DOCS_SC_BLOCK = /^\[\[shortcuts(?::([\w,-]+))?\]\]\s*$/;
+
+// md → { html, headings: [{level, text, anchor}] }. Pure: the tests run it.
+function docsRender(md, sectionId) {
+ const lines = String(md).replace(/\r\n?/g, '\n').split('\n');
+ const out = [];
+ const heads = [];
+ let para = [];
+ let list = null;
+ const flushPara = () => {
+ if (para.length) { out.push('<p>' + docsInline(para.join(' ')) + '</p>'); para = []; }
+ };
+ const renderList = l => '<' + l.type + '>' + l.items.map(it =>
+ '<li>' + docsInline(it.text) + (it.sub ? renderList(it.sub) : '') + '</li>').join('') + '</' + l.type + '>';
+ const flushList = () => { if (list) { out.push(renderList(list)); list = null; } };
+ let i = 0;
+ while (i < lines.length) {
+ const line = lines[i];
+ let m;
+ if (/^```/.test(line)) {
+ flushPara(); flushList();
+ const buf = [];
+ i++;
+ while (i < lines.length && !/^```/.test(lines[i])) buf.push(lines[i++]);
+ i++;
+ out.push('<pre class="docs-pre"><code>' + docsEsc(buf.join('\n')) + '</code></pre>');
+ continue;
+ }
+ if (!line.trim()) { flushPara(); flushList(); i++; continue; }
+ if ((m = line.match(DOCS_HEADING))) {
+ flushPara(); flushList();
+ const level = m[1].length;
+ const text = m[2];
+ if (level === 1) {
+ out.push('<h1 id="docs-' + sectionId + '">' + docsInline(text) + '</h1>');
+ } else {
+ const anchor = m[3] || docsSlug(text);
+ heads.push({ level, text: docsPlain(text), anchor });
+ out.push('<h' + level + ' id="docs-' + sectionId + '-' + anchor + '">' + docsInline(text) +
+ '<a class="docs-anchor" href="#docs/' + sectionId + '/' + anchor + '" aria-label="Link to this part">#</a></h' + level + '>');
+ }
+ i++; continue;
+ }
+ if ((m = line.match(DOCS_SC_BLOCK))) {
+ flushPara(); flushList();
+ const scopes = m[1] ? m[1].split(',') : null;
+ if (typeof shortcutsDocHtml === 'function') {
+ out.push(shortcutsDocHtml(scopes, 'docs-' + sectionId + '-'));
+ for (const sc of SHORTCUT_SCOPES) {
+ if (!scopes || scopes.includes(sc.id)) heads.push({ level: 3, text: sc.title, anchor: 'keys-' + sc.id });
+ }
+ }
+ i++; continue;
+ }
+ if (/^\s*\|/.test(line)) {
+ flushPara(); flushList();
+ const rows = [];
+ while (i < lines.length && /^\s*\|/.test(lines[i])) rows.push(lines[i++]);
+ out.push(docsTable(rows));
+ continue;
+ }
+ if (/^>\s?/.test(line)) {
+ flushPara(); flushList();
+ const buf = [];
+ while (i < lines.length && /^>\s?/.test(lines[i])) buf.push(lines[i++].replace(/^>\s?/, ''));
+ out.push('<div class="docs-note">' + buf.join('\n').split(/\n\s*\n/)
+ .map(p => '<p>' + docsInline(p.replace(/\n/g, ' ')) + '</p>').join('') + '</div>');
+ continue;
+ }
+ if ((m = line.match(/^(\s*)([-*]|\d+\.)\s+(.*)$/))) {
+ flushPara();
+ const type = /\d/.test(m[2]) ? 'ol' : 'ul';
+ if (m[1].length >= 2 && list && list.items.length) {
+ const last = list.items[list.items.length - 1];
+ if (!last.sub) last.sub = { type, items: [] };
+ last.sub.items.push({ text: m[3] });
+ } else {
+ if (list && list.type !== type) flushList();
+ if (!list) list = { type, items: [] };
+ list.items.push({ text: m[3] });
+ }
+ i++; continue;
+ }
+ if (list && /^\s{2,}\S/.test(line)) {
+ const last = list.items[list.items.length - 1];
+ const tgt = last.sub ? last.sub.items[last.sub.items.length - 1] : last;
+ tgt.text += ' ' + line.trim();
+ i++; continue;
+ }
+ if (/^---+\s*$/.test(line)) { flushPara(); flushList(); out.push('<hr>'); i++; continue; }
+ flushList();
+ para.push(line.trim());
+ i++;
+ }
+ flushPara(); flushList();
+ return { html: out.join('\n'), headings: heads };
+}
+
+// ---- search -----------------------------------------------------------------
+// One entry per heading: its words and the words under it, until the next.
+function docsBuildIndex() {
+ const idx = [];
+ for (const sec of DOCS_SECTIONS) {
+ const md = DOCS.md[sec.id] || '';
+ let cur = { section: sec.id, anchor: '', title: sec.title, level: 1, text: [] };
+ const push = () => { if (cur) idx.push({ section: cur.section, anchor: cur.anchor, title: cur.title, level: cur.level, text: cur.text.join(' ') }); };
+ let inCode = false;
+ for (const line of md.split('\n')) {
+ if (/^```/.test(line)) { inCode = !inCode; continue; }
+ const h = !inCode && line.match(DOCS_HEADING);
+ if (h) {
+ if (h[1].length === 1) continue;
+ push();
+ cur = { section: sec.id, anchor: h[3] || docsSlug(h[2]), title: docsPlain(h[2]), level: h[1].length, text: [] };
+ continue;
+ }
+ const sc = !inCode && line.match(DOCS_SC_BLOCK);
+ if (sc && typeof SHORTCUT_SCOPES !== 'undefined') {
+ const scopes = sc[1] ? sc[1].split(',') : SHORTCUT_SCOPES.map(x => x.id);
+ for (const scope of SHORTCUT_SCOPES) {
+ if (!scopes.includes(scope.id)) continue;
+ idx.push({ section: sec.id, anchor: 'keys-' + scope.id, title: scope.title, level: 3,
+ text: SHORTCUTS.filter(s => s.scope === scope.id)
+ .map(s => shortcutHint(s.id) + ' ' + s.label).join(' · ') });
+ }
+ continue;
+ }
+ cur.text.push(docsPlain(line.replace(/^\s*(?:[-*>]|\d+\.)\s+/, '').replace(/\|/g, ' ')));
+ }
+ push();
+ }
+ DOCS.index = idx.filter(e => e.title);
+}
+
+function docsSearch(q) {
+ const terms = String(q || '').toLowerCase().split(/\s+/).filter(Boolean);
+ if (!terms.length) return [];
+ const hits = [];
+ for (const e of DOCS.index) {
+ const title = e.title.toLowerCase();
+ const text = e.text.toLowerCase();
+ const sec = (DOCS_SECTIONS.find(s => s.id === e.section) || {}).title || '';
+ let score = 0;
+ let ok = true;
+ for (const t of terms) {
+ if (title.includes(t)) score += 10;
+ else if (text.includes(t)) score += 2;
+ else if (sec.toLowerCase().includes(t)) score += 1;
+ else { ok = false; break; }
+ }
+ if (ok) hits.push({ e, score: score - e.level * 0.1 });
+ }
+ hits.sort((a, b) => b.score - a.score);
+ return hits.slice(0, 40).map(h => h.e);
+}
+
+function docsSnippet(text, terms) {
+ const low = text.toLowerCase();
+ let at = -1;
+ for (const t of terms) { const k = low.indexOf(t); if (k >= 0 && (at < 0 || k < at)) at = k; }
+ let s = at < 0 ? text.slice(0, 140) : text.slice(Math.max(0, at - 50), at + 110);
+ if (at > 50) s = '…' + s;
+ let html = docsEsc(s);
+ for (const t of terms) {
+ if (!t) continue;
+ const re = new RegExp('(' + docsEsc(t).replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'ig');
+ html = html.replace(re, '<mark>$1</mark>');
+ }
+ return html;
+}
+
+// ---- the view -----------------------------------------------------------------
+function docsEl(id) { return document.getElementById(id); }
+
+async function docsLoad() {
+ if (DOCS.loading) return DOCS.loading;
+ DOCS.loading = Promise.all(DOCS_SECTIONS.map(async sec => {
+ try {
+ const r = await fetch('/webapp/docs/' + sec.file, { cache: 'no-cache' });
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ DOCS.md[sec.id] = await r.text();
+ } catch (e) {
+ DOCS.md[sec.id] = '# ' + sec.title + '\n\nThis page could not be loaded (' + String(e.message || e) +
+ '). The panel serves it from webapp/docs/' + sec.file + '.';
+ }
+ })).then(() => { docsBuildIndex(); });
+ return DOCS.loading;
+}
+
+function docsRendered(id) {
+ if (!DOCS.rendered[id]) DOCS.rendered[id] = docsRender(DOCS.md[id] || '', id);
+ return DOCS.rendered[id];
+}
+
+function docsPaintToc() {
+ const toc = docsEl('docsToc');
+ if (!toc) return;
+ let html = '';
+ let group = '';
+ for (const sec of DOCS_SECTIONS) {
+ if (sec.group !== group) {
+ group = sec.group;
+ html += '<div class="docs-toc-group">' + docsEsc(group) + '</div>';
+ }
+ const on = sec.id === DOCS.section;
+ html += '<a class="docs-toc-sec' + (on ? ' is-active' : '') + '" href="#docs/' + sec.id + '"' +
+ (on ? ' aria-current="page"' : '') + '>' + docsEsc(sec.title) + '</a>';
+ if (on) {
+ const subs = docsRendered(sec.id).headings.filter(h => h.level === 2);
+ if (subs.length) {
+ html += '<div class="docs-toc-subs">' + subs.map(h =>
+ '<a class="docs-toc-sub" data-anchor="' + docsEsc(h.anchor) + '" href="#docs/' + sec.id + '/' + h.anchor + '">' +
+ docsEsc(h.text) + '</a>').join('') + '</div>';
+ }
+ }
+ }
+ toc.innerHTML = html;
+}
+
+function docsGo(section, anchor) {
+ const sec = DOCS_SECTIONS.find(s => s.id === section) || DOCS_SECTIONS[0];
+ const changed = sec.id !== DOCS.section || !docsEl('docsArticle').dataset.section;
+ DOCS.section = sec.id;
+ const art = docsEl('docsArticle');
+ if (changed) {
+ art.innerHTML = docsRendered(sec.id).html;
+ art.dataset.section = sec.id;
+ const i = DOCS_SECTIONS.indexOf(sec);
+ const prev = DOCS_SECTIONS[i - 1];
+ const next = DOCS_SECTIONS[i + 1];
+ docsEl('docsPageNav').innerHTML =
+ (prev ? '<a class="docs-page-prev" href="#docs/' + prev.id + '"><span>Previous</span>' + docsEsc(prev.title) + '</a>' : '<span></span>') +
+ (next ? '<a class="docs-page-next" href="#docs/' + next.id + '"><span>Next</span>' + docsEsc(next.title) + '</a>' : '<span></span>');
+ docsPaintToc();
+ }
+ docsEl('docsCrumb').textContent = sec.group + ' › ' + sec.title;
+ const scroller = docsEl('docsScroll');
+ const target = anchor ? docsEl('docs-' + sec.id + '-' + anchor) : null;
+ requestAnimationFrame(() => {
+ if (target) {
+ scroller.scrollTop += target.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 12;
+ target.classList.remove('docs-flash');
+ void target.offsetWidth;
+ target.classList.add('docs-flash');
+ } else if (changed) {
+ scroller.scrollTop = 0;
+ }
+ docsSpy();
+ });
+ try {
+ const want = '#docs/' + sec.id + (anchor ? '/' + anchor : '');
+ if (location.hash !== want) history.replaceState(null, '', want);
+ } catch (e) {}
+ docsEl('docsView').classList.remove('nav-open');
+}
+
+// The TOC follows the reading position.
+function docsSpy() {
+ const scroller = docsEl('docsScroll');
+ const toc = docsEl('docsToc');
+ if (!scroller || !toc) return;
+ const top = scroller.getBoundingClientRect().top + 90;
+ let current = '';
+ for (const h of docsEl('docsArticle').querySelectorAll('h2[id]')) {
+ if (h.getBoundingClientRect().top <= top) current = h.id.slice(('docs-' + DOCS.section + '-').length);
+ }
+ toc.querySelectorAll('.docs-toc-sub').forEach(a => a.classList.toggle('is-here', a.dataset.anchor === current));
+}
+
+function docsPaintResults(q) {
+ const box = docsEl('docsResults');
+ const toc = docsEl('docsToc');
+ const terms = String(q || '').toLowerCase().split(/\s+/).filter(Boolean);
+ if (!terms.length) { box.hidden = true; toc.hidden = false; box.innerHTML = ''; return; }
+ const hits = docsSearch(q);
+ toc.hidden = true;
+ box.hidden = false;
+ if (!hits.length) {
+ box.innerHTML = '<div class="docs-noresult">Nothing matches “' + docsEsc(q) + '”. Try a word you see on the button, like <b>unlink</b> or <b>upscale</b>.</div>';
+ return;
+ }
+ box.innerHTML = '<div class="docs-toc-group">' + hits.length + (hits.length === 1 ? ' match' : ' matches') + '</div>' +
+ hits.map((e, n) => {
+ const sec = DOCS_SECTIONS.find(s => s.id === e.section);
+ return '<a class="docs-hit" href="#docs/' + e.section + (e.anchor ? '/' + e.anchor : '') + '" data-n="' + n + '">' +
+ '<span class="docs-hit-t">' + docsSnippet(e.title, terms).replace(/^…/, '') + '</span>' +
+ '<span class="docs-hit-s">' + docsEsc(sec ? sec.title : '') + '</span>' +
+ (e.text ? '<span class="docs-hit-x">' + docsSnippet(e.text, terms) + '</span>' : '') + '</a>';
+ }).join('');
+}
+
+function docsParseHash(h) {
+ const m = String(h || '').match(/^#docs(?:\/([\w-]+))?(?:\/([\w-]+))?/);
+ return m ? { section: m[1] || '', anchor: m[2] || '' } : null;
+}
+
+async function openDocs(section, anchor) {
+ const view = docsEl('docsView');
+ if (!view) return;
+ const wasOpen = view.classList.contains('show');
+ if (!wasOpen) {
+ DOCS.returnFocus = document.activeElement;
+ view.classList.add('show');
+ view.style.display = 'flex';
+ document.body.classList.add('modal-open');
+ }
+ await docsLoad();
+ const known = DOCS_SECTIONS.some(s => s.id === section);
+ docsGo(known ? section : DOCS.section, known ? (anchor || '') : '');
+ if (!wasOpen) {
+ const s = docsEl('docsSearch');
+ if (s) setTimeout(() => { try { s.focus({ preventScroll: true }); } catch (e) {} }, 0);
+ }
+}
+
+function closeDocs() {
+ const view = docsEl('docsView');
+ if (!view || !view.classList.contains('show')) return;
+ view.classList.remove('show', 'nav-open');
+ view.style.display = '';
+ if (!document.querySelector('.modal-bg.show')) document.body.classList.remove('modal-open');
+ try {
+ if (/^#docs/.test(location.hash)) history.replaceState(null, '', location.pathname + location.search);
+ } catch (e) {}
+ const back = DOCS.returnFocus;
+ DOCS.returnFocus = null;
+ if (back && back.focus && document.contains(back)) { try { back.focus({ preventScroll: true }); } catch (e) {} }
+}
+
+(function docsWire() {
+ const view = docsEl('docsView');
+ if (!view || !view.addEventListener) return;
+ // Every #docs/ link inside the view — TOC, results, cross-references,
+ // prev / next, heading anchors — goes through docsGo, so clicking the link
+ // you are already on still scrolls to it.
+ view.addEventListener('click', ev => {
+ const a = ev.target.closest && ev.target.closest('a[href^="#docs"]');
+ if (!a) return;
+ const p = docsParseHash(a.getAttribute('href'));
+ if (!p) return;
+ ev.preventDefault();
+ docsGo(p.section || DOCS.section, p.anchor);
+ });
+ const search = docsEl('docsSearch');
+ if (search) {
+ search.addEventListener('input', () => docsPaintResults(search.value));
+ search.addEventListener('keydown', ev => {
+ if (ev.key === 'Enter') {
+ const first = docsEl('docsResults').querySelector('.docs-hit');
+ if (first) { ev.preventDefault(); first.click(); }
+ } else if (ev.key === 'ArrowDown') {
+ const first = docsEl('docsResults').querySelector('.docs-hit');
+ if (first) { ev.preventDefault(); first.focus(); }
+ } else if (ev.key === 'Escape' && search.value) {
+ // The first Esc empties the box; the next one closes the Docs.
+ ev.preventDefault();
+ ev.stopPropagation();
+ search.value = '';
+ docsPaintResults('');
+ }
+ });
+ }
+ const results = docsEl('docsResults');
+ if (results) {
+ results.addEventListener('keydown', ev => {
+ if (ev.key !== 'ArrowDown' && ev.key !== 'ArrowUp') return;
+ const hits = Array.from(results.querySelectorAll('.docs-hit'));
+ const i = hits.indexOf(document.activeElement);
+ if (i < 0) return;
+ ev.preventDefault();
+ if (ev.key === 'ArrowUp' && i === 0) { search.focus(); return; }
+ const next = hits[Math.max(0, Math.min(hits.length - 1, i + (ev.key === 'ArrowDown' ? 1 : -1)))];
+ if (next) next.focus();
+ });
+ }
+ const scroller = docsEl('docsScroll');
+ if (scroller) {
+ scroller.addEventListener('scroll', () => {
+ if (DOCS.spyRaf) return;
+ DOCS.spyRaf = requestAnimationFrame(() => { DOCS.spyRaf = 0; docsSpy(); });
+ }, { passive: true });
+ }
+ const toggle = docsEl('docsNavToggle');
+ if (toggle) {
+ toggle.addEventListener('click', () => {
+ const on = !view.classList.contains('nav-open');
+ view.classList.toggle('nav-open', on);
+ toggle.setAttribute('aria-expanded', on ? 'true' : 'false');
+ });
+ }
+ // A #docs/... link anywhere in the panel — an error message, a tooltip's
+ // "read more", a pasted URL — opens the Docs there.
+ if (typeof window.addEventListener === 'function') {
+ window.addEventListener('hashchange', () => {
+ const p = docsParseHash(location.hash);
+ if (p) openDocs(p.section, p.anchor);
+ });
+ }
+ const p = (typeof location !== 'undefined') ? docsParseHash(location.hash) : null;
+ if (p) openDocs(p.section, p.anchor);
+})();
+
+// ---- published to the page -----------------------------------------------------
+Object.assign(globalThis, {
+ DOCS_SECTIONS, openDocs, closeDocs, docsRender, docsSlug, docsPlain,
+ docsSearch, docsBuildIndex, docsLoad,
+});
diff --git a/webapp/js/editor.js b/webapp/js/editor.js
index 7350e69..f31c9a3 100644
--- a/webapp/js/editor.js
+++ b/webapp/js/editor.js
@@ -179,6 +179,10 @@ window.SBE = {
// wrong one every time Enter is pressed.
renaming: '',
sel: '', playhead: 0, playing: false, curId: '', pps: 42,
+ // THE REST OF THE SELECTION. `sel` is the primary — the one clip the
+ // inspector, the preview and the strip player mean — and `selSet` is every
+ // clip the verbs act on, always including `sel`. See sbeSelNormalise.
+ selSet: [],
undo: [], redo: [], errors: {}, sentOrder: [],
// THE ONE NOTICE SURFACE. `noticeLead` is the chip the user clicked open,
// `backupHidden` is "Later" on the recovery offer (this session, this
@@ -3064,6 +3068,283 @@ function sbeOvDeleteSel() {
if (ok) { SBE.ovSel = ''; sbePaint(); }
}
+// ---------------------------------------------------------------------------
+// THE SELECTION — one clip, or several
+// ---------------------------------------------------------------------------
+// "You should be able to select, hit Shift, and select multiple clips and move
+// them together. It's very important."
+//
+// `SBE.sel` STAYS A SINGLE ID and it stays the PRIMARY: fifty-odd call sites
+// read it, and the inspector, the strip player and the preview all mean "the
+// one clip whose properties are on screen" by it. `SBE.selSet` is the FULL
+// selection, and the invariant is that it always contains `SBE.sel`.
+//
+// That invariant is enforced in ONE place — `sbeSelNormalise`, at the top of
+// `sbePaint` — and not at every assignment. A lift, a duplicate, a resync, a
+// retake and a dozen other paths write `SBE.sel = …` directly; a set that has
+// to be updated by hand at each of them is a set that is stale by the next
+// feature. So anything that points `SBE.sel` at a clip outside the set
+// COLLAPSES the selection to that clip, which is the correct behaviour at
+// every one of those call sites and costs none of them a line.
+function sbeSelNormalise() {
+ const live = {};
+ for (const c of SBE.clips || []) live[String(c.id)] = true;
+ let s = (SBE.selSet || []).filter(id => live[String(id)]);
+ if (!SBE.sel || !live[String(SBE.sel)]) s = [];
+ else if (s.indexOf(String(SBE.sel)) < 0) s = [String(SBE.sel)];
+ SBE.selSet = s;
+ return s;
+}
+
+// Every selected clip, in TIMELINE order — which is the order every group verb
+// needs. A ripple delete running right-to-left would slide the film out from
+// under its own next victim, and a group move reads its boundaries in order.
+function sbeSelIds() {
+ const s = sbeSelNormalise();
+ if (s.length < 2) return s.slice();
+ const pos = {};
+ (SBE.clips || []).forEach((c, i) => { pos[String(c.id)] = i; });
+ return s.slice().sort((a, b) => sbeNum(pos[a]) - sbeNum(pos[b]));
+}
+
+function sbeSelCount() { return sbeSelNormalise().length; }
+function sbeSelMap() {
+ const m = {};
+ for (const id of sbeSelNormalise()) m[String(id)] = true;
+ return m;
+}
+function sbeSelHas(id) { return !!sbeSelMap()[String(id)]; }
+
+// The selected clips themselves, primary first — what the clip bar reads to
+// decide what its buttons say.
+function sbeSelClips() {
+ return sbeSelIds().map(id => sbeById(SBE.clips, id)).filter(Boolean);
+}
+
+function sbeSelectOne(id) {
+ SBE.sel = String(id || '');
+ SBE.selSet = SBE.sel ? [SBE.sel] : [];
+}
+
+// ⌘-click: add one, or take one out. Taking out the PRIMARY hands the role to
+// whatever is left, so the inspector never goes blank over a live selection —
+// and ⌘-clicking the last one standing is a no-op rather than a way to end up
+// with an empty selection you did not ask for.
+function sbeSelectToggle(id) {
+ const want = String(id || '');
+ if (!want) return;
+ const set = sbeSelIds();
+ const i = set.indexOf(want);
+ if (i < 0) { set.push(want); SBE.sel = want; }
+ else if (set.length > 1) {
+ set.splice(i, 1);
+ if (String(SBE.sel) === want) SBE.sel = set[0];
+ } else return;
+ SBE.selSet = set;
+}
+
+// Shift-click: everything from the anchor to here, the range every list in
+// every program answers to. THE ANCHOR DOES NOT MOVE — shift-clicking a third
+// clip extends from where the first click landed, which is what makes a range
+// feel like a range instead of like a pair.
+function sbeSelectRange(id) {
+ const order = (SBE.clips || []).map(c => String(c.id));
+ const a = order.indexOf(String(SBE.sel));
+ const b = order.indexOf(String(id));
+ if (a < 0 || b < 0) { sbeSelectOne(id); return; }
+ SBE.selSet = order.slice(Math.min(a, b), Math.max(a, b) + 1);
+ SBE.sel = order[a];
+}
+
+function sbeSelectAll() {
+ const order = (SBE.clips || []).map(c => String(c.id));
+ if (!order.length) return;
+ SBE.selSet = order;
+ if (order.indexOf(String(SBE.sel)) < 0) SBE.sel = order[0];
+ SBE.ovSel = ''; SBE.txSel = '';
+ sbePaint();
+}
+
+function sbeSelectNone() {
+ SBE.sel = ''; SBE.selSet = []; SBE.ovSel = ''; SBE.txSel = '';
+ sbePaint();
+}
+
+// ONE UNDO STEP FOR ONE GESTURE. Pressing Ripple delete with four clips
+// selected is ONE thing the user did, so ⌘Z has to take back one thing — four
+// `sbeMutate` calls would leave four steps on the stack and a person pressing
+// undo once to find three quarters of his shots still gone.
+//
+// A per-clip refusal does NOT abort the rest, and it is reported. Locking is
+// per clip, so a selection holding one locked shot should still mute the other
+// three and say which one it could not touch; refusing the whole gesture over
+// one member would make a multi-selection unusable the moment anything in it
+// was pinned.
+function sbeMutateEach(ids, fn) {
+ const list = (ids || []).slice();
+ if (!list.length) return false;
+ const before = sbeSnapshot();
+ let done = 0;
+ const why = [];
+ for (const id of list) {
+ const res = fn(SBE.clips, id);
+ if (!res || res.ok === false) { if (res && res.why) why.push(String(res.why)); continue; }
+ SBE.clips = res.clips;
+ if (res.transitions) SBE.transitions = res.transitions;
+ done++;
+ }
+ if (!done) {
+ // NOTHING LANDED, SO NOTHING IS KEPT. The refusals ran against the live
+ // array — most model functions work in place and hand back the array they
+ // were given — so the snapshot goes back rather than being trusted to be
+ // untouched. A refusal that half-wrote would otherwise ride out on the
+ // next paint with no undo step behind it.
+ sbeRestore(before);
+ phosToast(why[0] || 'Nothing on this selection could take that.', {});
+ sbePaint();
+ return false;
+ }
+ SBE.undo.push(before);
+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();
+ SBE.redo.length = 0;
+ SBE.transitions = sbeTxPrune(SBE.transitions || [], SBE.clips);
+ SBE.dirty = true;
+ sbeSetState('unsaved changes', 'dirty');
+ if (why.length) {
+ phosToast(why.length + ' of ' + list.length + ' were left as they were — '
+ + why[0], { duration: 6000 });
+ }
+ sbePaint();
+ sbeQueueSave();
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// MOVING SEVERAL CLIPS AT ONCE
+// ---------------------------------------------------------------------------
+// The layout model is GAPS, not positions (see `sbeLayout`), and that is what
+// makes a group move exact rather than a simulation. Slide a set of clips by
+// `d` and leave everything else where it is: the only gaps that change are the
+// ones on a BOUNDARY between a clip that is moving and a clip that is not, and
+// each of those changes by exactly ±d. So the legal range of d is closed-form
+// — the intersection of "no gap goes negative" over every boundary — which is
+// the same clamp a single-clip move already applies at its two neighbours,
+// written once for any number of clips.
+//
+// Relative spacing is therefore preserved by construction, including the holes
+// inside the selection: nothing is re-packed, so a selection with a deliberate
+// two-second hole in it arrives with the hole still two seconds.
+function sbeGroupLimits(clips, ids) {
+ const sel = {};
+ for (const id of ids || []) sel[String(id)] = true;
+ const list = clips || [];
+ let lo = -Infinity, hi = Infinity;
+ for (let i = 0; i < list.length; i++) {
+ const c = list[i];
+ const prev = i > 0 ? list[i - 1] : null;
+ // The film's own head is a boundary that never moves, which is why the
+ // i === 0 case needs no special term: its gap is `film_start - 0`, and
+ // the rule below already says that gap may not go negative.
+ const gap = sbeNum(c.film_start) - (prev ? sbeNum(prev.film_end) : 0);
+ const k = (sel[String(c.id)] ? 1 : 0) - ((prev && sel[String(prev.id)]) ? 1 : 0);
+ if (k > 0) lo = Math.max(lo, -gap);
+ else if (k < 0) hi = Math.min(hi, gap);
+ }
+ return { lo: lo, hi: hi };
+}
+
+function sbeMoveGroup(clips, ids, delta) {
+ const list = clips || [];
+ const sel = (ids || []).map(String);
+ if (!sel.length) return { clips: list, ok: false, why: 'gone' };
+ for (const id of sel) {
+ const c = sbeById(list, id);
+ if (!c) return { clips: list, ok: false, why: 'gone' };
+ if (c.locked) return { clips: list, ok: false, why: 'locked' };
+ }
+ const lim = sbeGroupLimits(list, sel);
+ const d = sbeRound(Math.max(lim.lo, Math.min(lim.hi, sbeNum(delta))));
+ const mark = sbeSyncMark(list);
+ const set = {};
+ for (const id of sel) set[id] = true;
+ // Every clip's gap is restated from where it actually IS, so the pass is
+ // exact whatever `_gap` happens to be carrying, and then the boundary terms
+ // are applied on top. One layout pass places the result.
+ for (let i = 0; i < list.length; i++) {
+ const c = list[i];
+ const prev = i > 0 ? list[i - 1] : null;
+ const gap = sbeNum(c.film_start) - (prev ? sbeNum(prev.film_end) : 0);
+ const k = (set[String(c.id)] ? 1 : 0) - ((prev && set[String(prev.id)]) ? 1 : 0);
+ c._gap = Math.max(0, sbeRound(gap + k * d));
+ }
+ sbeLayout(list);
+ // THE SOUND COMES TOO, and this is the one place the rule differs from a
+ // single-clip drag. Dragging one picture deliberately leaves its strip
+ // behind — that is how a J-cut is made. Sliding a BLOCK is not that gesture:
+ // it is "put these four shots a second later", and a strip left behind would
+ // be a sync error nobody asked for. Carrying also preserves any J-cut
+ // already inside the selection, because it moves every strip by the same d.
+ sbeSyncCarry(list, mark, []);
+ for (const id of sel) { const c = sbeById(list, id); if (c) c.source = 'human'; }
+ return { clips: list, ok: true, moved: d };
+}
+
+// Closing a hole, which is what a right-click on one offers. The clip that
+// OPENS after the hole loses the gap in front of it and everything behind it
+// slides by exactly that much — the only reading of "close the gap" that
+// leaves the rest of the cut intact.
+function sbeCloseGapAt(t) {
+ const holes = sbeHoles(SBE.clips) || [];
+ const at = sbeNum(t);
+ const h = holes.find(g => at >= sbeNum(g.film_start) - 1e-6
+ && at <= sbeNum(g.film_end) + 1e-6);
+ if (!h) { phosToast('No hole there.', {}); return false; }
+ return sbeMutate(cs => {
+ const mark = sbeSyncMark(cs);
+ let after = null;
+ for (const c of cs) {
+ if (sbeNum(c.film_start) >= sbeNum(h.film_end) - 1e-3) { after = c; break; }
+ }
+ if (!after) return { clips: cs, ok: false, why: 'nothing follows that hole' };
+ if (after.locked) return { clips: cs, ok: false, why: 'locked' };
+ for (let i = 0; i < cs.length; i++) {
+ const prev = i > 0 ? cs[i - 1] : null;
+ cs[i]._gap = Math.max(0, sbeRound(sbeNum(cs[i].film_start)
+ - (prev ? sbeNum(prev.film_end) : 0)));
+ }
+ after._gap = 0;
+ sbeLayout(cs);
+ // A CLOSE IS A HEAL, NOT A DRAG, so the sound travels with the pictures
+ // it belongs to — the same reasoning `sbeAdoptGaps` gives for the
+ // sub-frame version of exactly this operation.
+ sbeSyncCarry(cs, mark, []);
+ return { clips: cs, ok: true };
+ });
+}
+
+// One frame at a time, on whatever is selected. Every NLE has this and this
+// one did not: the arrow keys moved the PLAYHEAD and there was no gesture at
+// all for "a hair later", short of dragging at a zoom high enough to see a
+// frame. Alt is the modifier because the bare arrows are the playhead's and
+// have to stay the playhead's.
+function sbeNudge(dir, big) {
+ const ids = sbeSelIds();
+ if (!ids.length) return;
+ const d = ((big ? 10 : 1) * (dir < 0 ? -1 : 1)) / sbeFps();
+ const lim = sbeGroupLimits(SBE.clips, ids);
+ if (Math.abs(Math.max(lim.lo, Math.min(lim.hi, d))) < 1e-6) {
+ // SAY IT RATHER THAN BURN A REVISION. A clamped move produces no change,
+ // and `sbeMutate` would still stamp the document dirty, push an undo step
+ // that undoes nothing and queue a save — on every repeat of a held key.
+ phosToast(dir < 0
+ ? 'Already hard against what comes before it — nothing to give.'
+ : 'Already hard against what comes after it — nothing to give.',
+ { duration: 5000 });
+ return;
+ }
+ sbeMutate(cs => sbeMoveGroup(cs, ids, d));
+}
+
function sbeMutate(fn) {
const before = sbeSnapshot();
const res = fn(SBE.clips);
@@ -3962,6 +4243,10 @@ function sbePx(t) { return sbeNum(t) * SBE.pps; }
function sbePaint() {
if (!SBE.open) return;
+ // THE SELECTION'S INVARIANT, ENFORCED IN ONE PLACE. Everything downstream —
+ // the track, the strips, the clip bar, the inspector — reads the set, and
+ // this is the only line that repairs it. See sbeSelNormalise.
+ sbeSelNormalise();
const span = sbeSpan();
// NEVER FURTHER OUT THAN "THE WHOLE FILM". The floor moves with the window
// and with the film's length, so widening the window re-fits instead of
@@ -3985,6 +4270,7 @@ function sbePaint() {
sbePaintTrack();
sbePaintAudioLane();
sbePaintHead();
+ sbePaintCbar();
sbePaintInspector();
sbePaintHeads();
sbePaintMix();
@@ -4754,6 +5040,10 @@ function sbePaintMix() {
function sbePaintTrack() {
const track = sbeEl('sbeTrack');
const holes = sbeHoles(SBE.clips);
+ // ONE LOOKUP FOR THE WHOLE LOOP. `sbeSelHas` normalises and sorts on every
+ // call, which is nothing once and O(n^2) inside a sixty-clip paint.
+ const selMap = sbeSelMap();
+ const selN = sbeSelCount();
// THE MESSAGE BELONGS WHERE THE EMPTINESS IS. This sentence used to live in
// the inspector, which is a short auto-scrolled box in the corner — so on a
// brand-new draft the user read "…media pool to put it here, or Add black
@@ -4786,7 +5076,8 @@ function sbePaintTrack() {
// un-scrubbable would be advice to run a Prepare that would do
// nothing.
: (kind === 'video' && !c.proxy ? 'slow' : '')));
- const cls = 'sbe-clip is-' + kind + (c.id === SBE.sel ? ' is-sel' : '')
+ const cls = 'sbe-clip is-' + kind + (selMap[String(c.id)] ? ' is-sel' : '')
+ + ((selN > 1 && String(c.id) === String(SBE.sel)) ? ' is-primary' : '')
+ (c.id === SBE.curId ? ' is-playing' : '')
+ (bad ? ' is-bad' : '') + (c.locked ? ' is-locked' : '')
+ (Math.abs(bright) >= 1e-6 ? ' is-graded' : '')
@@ -4915,6 +5206,7 @@ function sbeSyncBadge(c) {
function sbePaintAudioLane() {
const lane = sbeEl('sbeAudioLane');
if (!lane) return;
+ const aSelMap = sbeSelMap();
let html = '';
for (const c of SBE.clips) {
if (sbeKind(c) !== 'video') continue;
@@ -4934,7 +5226,7 @@ function sbePaintAudioLane() {
+ (w.coupled ? ' is-coupled' : '')
+ (mute ? ' is-mute' : '')
+ (off ? ' is-silenced' : '')
- + (c.id === SBE.sel ? ' is-sel' : '');
+ + (aSelMap[String(c.id)] ? ' is-sel' : '');
// ONE WORD, EIGHT TIMES, IN A 26PX STRIP. The label is only news when the
// sound has been pulled off its picture — the lane's own fill says the
// rest, and a column of identical labels says nothing at all. A COUPLED
@@ -4949,11 +5241,11 @@ function sbePaintAudioLane() {
: (w.linked ? '' : ('sound · ' + w.len.toFixed(2) + 's'))));
html += '<div class="' + cls + '" data-id="' + escapeHtml(c.id) + '" '
+ 'title="' + escapeHtml(off
- ? 'Muted — this clip\'s own sound is switched off in the preview, the render and the export. Unmute it in the inspector.'
+ ? 'Muted — this clip\'s own sound is switched off in the preview, the render and the export. Unmute sound, on the bar above the tracks.'
: w.coupled
? 'Linked at ' + sbeDriftLabel(sbeAudioDrift(c)) + ' — the sound keeps this offset and travels with the picture. Unlink it to slide it on its own.'
: (w.linked
- ? 'This clip\'s sound moves with its picture. Unlink it in the inspector to slide it under the neighbour (a J-cut or an L-cut).'
+ ? 'This clip\'s sound moves with its picture. Unlink sound, on the bar above the tracks, to slide it under the neighbour (a J-cut or an L-cut).'
: 'Unlinked — drag to slide the sound, pull either end to trim it. The picture does not move.')) + '" '
+ 'style="left:' + x.toFixed(1) + 'px;width:' + Math.max(2, px).toFixed(1) + 'px">'
+ (mute ? '' : sbeStripWave(c, w, px))
@@ -5529,30 +5821,43 @@ function sbeAddPointAtPlayhead() {
sbeMutate(() => ({ clips: r.clips, ok: true }));
}
+// "MAYBE SOME KIND OF 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 the two ways to take them off were a right-click on each one and a
+// "Clear 4" button that appeared and disappeared in the rail. This is that
+// button, on the clip bar, over the whole selection.
function sbeClearPoints() {
- const c = sbeById(SBE.clips, SBE.sel);
- if (!c) return;
- sbeMutate(cs => sbeAfxWrite(cs, c.id, []));
+ const ids = sbeSelIds().filter(x => {
+ const c = sbeById(SBE.clips, x);
+ return c && sbeAfx(c, sbeClipAudio(c).len).points.length;
+ });
+ if (!ids.length) return;
+ const n = ids.reduce((a, x) => {
+ const c = sbeById(SBE.clips, x);
+ return a + sbeAfx(c, sbeClipAudio(c).len).points.length;
+ }, 0);
+ const ok = (ids.length === 1)
+ ? sbeMutate(cs => sbeAfxWrite(cs, ids[0], []))
+ : sbeMutateEach(ids, (cs, x) => sbeAfxWrite(cs, x, []));
+ if (ok) {
+ phosToast(n + ' level point' + (n === 1 ? '' : 's') + ' removed. The '
+ + 'fades are untouched — those are the corner handles.',
+ { duration: 6000 });
+ }
}
// THE LEGEND, in one function, because it is the only thing that tells a new
// user what the gestures are and it has to be true. The Keys chip renders it.
+//
+// THE ROWS ARE NOT HERE ANY MORE. They live in webapp/js/shortcuts.js — the
+// one table the Docs page, this popover and the tooltips all read — so the
+// keys a person is told about cannot drift from the keys the handler below
+// answers to (test_docs_and_shortcuts.py drives the real handler with every
+// row). This function only draws them.
function sbeKeysLegend() {
- const k = t => '<span class="sbe-kbd">' + t + '</span>';
- return [
- ['Drag', 'move a clip · handles to trim'],
- [k('Space'), 'play / pause'],
- [k('←') + k('→'), 'one frame'],
- [k('S'), 'split at the playhead'],
- [k('⌫'), 'ripple delete'],
- [k('Alt'), 'held: ignore the beat grid'],
- [k('Shift'), 'held: reorder instead of move'],
- ['Levels', 'click the yellow line to add a point · drag it to set the '
- + 'level · right-click it to remove · ' + k('Shift')
- + '-click removes too'],
- ['Sound', 'the music strip drags and trims like a clip'],
- ['Timeline', 'drag its top edge for more height · double-click to reset'],
- ].map(r => '<span class="sbe-key-row"><b>' + r[0] + '</b>' + r[1] + '</span>')
+ const rows = (typeof shortcutRows === 'function')
+ ? shortcutRows(['editor', 'editor-mouse'], 'sbe-kbd') : [];
+ return rows.map(r => '<span class="sbe-key-row"><b>' + r.keys + '</b>' + r.label + '</span>')
.join('');
}
@@ -5686,15 +5991,15 @@ function sbeOnAudioDown(ev) {
sbePaint();
phosToast(w.coupled
? 'This sound is linked to its picture at ' + sbeDriftLabel(sbeAudioDrift(c))
- + ' and moves with it. Unlink it in the inspector to slide it on its own.'
- : 'That clip\'s sound is linked to its picture. Unlink it in the '
- + 'inspector to slide it under the neighbour.', { duration: 6000 });
+ + ' and moves with it. Press Unlink sound on the bar above the tracks to slide it on its own.'
+ : 'That clip\'s sound is linked to its picture. Press Unlink sound on '
+ + 'the bar above the tracks to slide it under the neighbour.', { duration: 6000 });
return;
}
if (c.locked) {
sbePaint();
- phosToast('That shot is locked, so its sound is locked with it. Click '
- + 'Unlock in the inspector.', { duration: 6000 });
+ phosToast('That shot is locked, so its sound is locked with it. Press '
+ + 'Unlock on the bar above the tracks.', { duration: 6000 });
return;
}
const lane = sbeEl('sbeAudioLane');
@@ -5793,6 +6098,22 @@ function sbeToggleAudioLink() {
if (!c) return;
const w = sbeClipAudio(c);
const drift = sbeAudioDrift(c);
+ const ids = sbeSelIds();
+ if (ids.length > 1) {
+ // THE PRIMARY'S STATE DECIDES FOR THE WHOLE SELECTION, for the same
+ // reason Lock converges: the button's own label reads "Unlink sound", and
+ // it has to mean that for every clip it was pressed over.
+ const want = !w.linked;
+ const ok = sbeMutateEach(ids, (cs, id) => sbeSetAudioLink(cs, id, want));
+ if (ok) {
+ phosToast(want
+ ? ids.length + ' strips unlinked — each one now drags and trims on '
+ + 'its own, under its own picture.'
+ : ids.length + ' strips re-linked — each one travels with its picture '
+ + 'again, keeping whatever offset it had.', { duration: 7000 });
+ }
+ return;
+ }
const ok = sbeMutate(cs => sbeSetAudioLink(cs, c.id, !w.linked));
if (!ok) return;
phosToast(w.linked
@@ -5807,18 +6128,39 @@ function sbeToggleAudioLink() {
}
function sbeDeleteStripSel() {
- const c = sbeById(SBE.clips, SBE.sel);
+ const ids = sbeSelIds();
+ if (!ids.length) return;
+ if (ids.length > 1) {
+ const ok = sbeMutateEach(ids, (cs, id) => sbeDeleteStrip(cs, id));
+ if (ok) {
+ phosToast('Sound removed from the selection — the pictures play silent '
+ + 'and none of them moved.', { duration: 7000 });
+ }
+ return;
+ }
+ const c = sbeById(SBE.clips, ids[0]);
if (!c) return;
const ok = sbeMutate(cs => sbeDeleteStrip(cs, c.id));
if (!ok) return;
phosToast('Sound removed — the picture plays silent and stays exactly where '
- + 'it is. Unmute in Sound to bring it back.', { duration: 7000 });
+ + 'it is. Undo brings it back.', { duration: 7000 });
}
function sbeToggleClipMute() {
const c = sbeById(SBE.clips, SBE.sel);
if (!c) return;
const on = !sbeClipMuted(c);
+ const ids = sbeSelIds();
+ if (ids.length > 1) {
+ const ok = sbeMutateEach(ids, (cs, id) => sbeSetClipMute(cs, id, on));
+ if (ok) {
+ phosToast(on
+ ? 'The selection is muted — their own sound is off in the preview, '
+ + 'the render and the export. The soundtrack is untouched.'
+ : 'The selection is unmuted.', { duration: 6000 });
+ }
+ return;
+ }
const ok = sbeMutate(cs => sbeSetClipMute(cs, c.id, on));
if (!ok) return;
phosToast(on
@@ -5827,8 +6169,26 @@ function sbeToggleClipMute() {
: 'Clip sound unmuted.', { duration: 6000 });
}
-// THE REMATCH, from the flag on either half or from the inspector.
+// THE REMATCH, from the flag on either half, from the clip bar, or from the
+// 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) {
+ if (!id) {
+ const ids = sbeSelIds().filter(x => {
+ const c = sbeById(SBE.clips, x);
+ return c && sbeClipAudio(c).split && !sbeAudioInSync(c);
+ });
+ if (ids.length > 1) {
+ const ok = sbeMutateEach(ids, (cs, x) => sbeResyncAudio(cs, x));
+ if (ok) {
+ phosToast(ids.length + ' strips are back under their own pictures. '
+ + 'They are still unlinked, so they can be moved again.',
+ { duration: 6000 });
+ }
+ return;
+ }
+ if (ids.length === 1) id = ids[0];
+ }
const who = id || SBE.sel;
const c = sbeById(SBE.clips, who);
if (!c) return;
@@ -5845,6 +6205,7 @@ function sbePaintHead() {
const el = sbeEl('sbeHead');
if (el) el.style.left = sbePx(SBE.playhead).toFixed(1) + 'px';
sbeFollow();
+ sbeCbarPlayhead();
const t = sbeEl('sbeTime');
if (t) {
t.innerHTML = escapeHtml(sbeFmtTime(SBE.playhead)) +
@@ -5860,6 +6221,13 @@ function sbePaintHead() {
// panel is `position: fixed` and measured against the anchor, which is the
// whole reason it can exist at all: an open menu must not push the workspace
// around, the same rule the notice surface has always followed.
+// EVERY FIXED PANEL ON THIS SCREEN, in one list. It was written out twice —
+// close-all and any-open — so the clip bar's overflow and the track's context
+// menu would have been two more chances to add a panel that Escape and a
+// click elsewhere could not shut.
+const SBE_POPS = ['sbeRenderMenu', 'sbeMoreMenu', 'sbeKeysPop', 'sbeMusicMenu',
+ 'sbeCbarMenu', 'sbeCtxMenu'];
+
function sbePopToggle(id, anchorId) {
const el = sbeEl(id);
if (!el) return;
@@ -5886,7 +6254,7 @@ function sbePopToggle(id, anchorId) {
}
function sbePopCloseAll(except) {
- for (const id of ['sbeRenderMenu', 'sbeMoreMenu', 'sbeKeysPop', 'sbeMusicMenu']) {
+ for (const id of SBE_POPS) {
if (id === except) continue;
const el = sbeEl(id);
if (el && !el.hidden) el.hidden = true;
@@ -5904,7 +6272,7 @@ function sbePopGlobal(ev) {
}
function sbePopAnyOpen() {
- for (const id of ['sbeRenderMenu', 'sbeMoreMenu', 'sbeKeysPop', 'sbeMusicMenu']) {
+ for (const id of SBE_POPS) {
const el = sbeEl(id);
if (el && !el.hidden) return true;
}
@@ -5944,6 +6312,388 @@ function sbePaintKeys() {
if (el && !el._done) { el.innerHTML = sbeKeysLegend(); el._done = 1; }
}
+// ---------------------------------------------------------------------------
+// THE CLIP BAR
+// ---------------------------------------------------------------------------
+// ONE TABLE, THREE CONSUMERS. The bar above the tracks, the overflow panel it
+// spills into at narrow widths, and the right-click menu on the track all say
+// the same words about the same state, because they all read this. The
+// alternative — three sets of labels — is three chances for one of them to go
+// on offering a verb the model has stopped accepting, which is the defect the
+// inspector kept producing by hiding a control instead of explaining it.
+//
+// A DISABLED BUTTON IS A TEACHER. Every row that cannot fire carries a `why`
+// that says what would have to be true, because that is the sentence the
+// inspector could never carry: it dropped the button, and a control that is
+// not on screen reads as a feature that does not exist. "Delete sound" was
+// invisible on every linked clip, which is every clip, until you happened to
+// unlink one.
+// WHY SPLIT CANNOT FIRE, or '' when it can. Its own function because it is
+// the one row on the bar whose state follows the PLAYHEAD rather than the
+// selection — the selection has nothing to do with it, the same as in every
+// NLE — and the playhead moves without a full `sbePaint`, on every frame of
+// playback and every pixel of a scrub. So two callers share this: the full
+// paint, and the cheap per-frame refresh below.
+function sbeSplitWhy() {
+ const under = sbeClipAt(SBE.clips, SBE.playhead);
+ if (!under) {
+ return 'Put the playhead over a shot first — this cuts whatever is under '
+ + 'it into two.' + sbeKeyHint('editor.split');
+ }
+ if (under.locked) {
+ return 'The shot under the playhead is locked to its place. Unlock it to '
+ + 'cut it.';
+ }
+ const off = SBE.playhead - sbeNum(under.film_start);
+ if (off < SBE_MIN_CLIP || sbeLen(under) - off < SBE_MIN_CLIP) {
+ return 'The playhead is right on a cut — move it into the middle of a '
+ + 'shot to split it.' + sbeKeyHint('editor.split');
+ }
+ return '';
+}
+
+// THE ONE BUTTON THAT HAS TO KEEP UP WITH THE PLAYHEAD. `sbeSeek` and the
+// playback loop repaint the head and the time and deliberately NOT the rest of
+// the screen, which is why Split sat greyed out over the middle of a shot the
+// scrub had just landed in — the stale state lasted until the next real edit.
+// One element, one comparison, no layout read: safe to call per frame.
+function sbeCbarPlayhead() {
+ const el = sbeEl('sbeCbSplit');
+ if (!el) return;
+ const why = sbeSplitWhy();
+ const want = why || SBE_SPLIT_TITLE;
+ if (el.title !== want) el.title = want;
+ if (el.disabled !== !!why) el.disabled = !!why;
+}
+
+const SBE_SPLIT_TITLE = 'Cuts the shot under the playhead into two at the '
+ + 'playhead. Nothing moves and nothing is lost.' + sbeKeyHint('editor.split');
+
+function sbeCbarModel() {
+ const ids = sbeSelIds();
+ const n = ids.length;
+ const many = n > 1;
+ const c = sbeById(SBE.clips, SBE.sel);
+ const kind = c ? sbeKind(c) : '';
+ const vid = !!c && kind === 'video';
+ const w = c ? sbeClipAudio(c) : null;
+ const track = vid && c.has_audio !== false;
+ const split = !!(vid && w && w.split);
+ const drift = c ? sbeAudioDrift(c) : 0;
+ const pts = (c && w) ? sbeAfx(c, w.len).points.length : 0;
+ const some = many ? ('all ' + n + ' shots') : 'this shot';
+ const splitWhy = sbeSplitWhy();
+ const pick = 'Click a shot on the track. Shift-click a second one to take '
+ + 'the range between them, ⌘-click to add or drop one.';
+ const noSel = (!n && SBE.ovSel) ? 'A title or card is selected, not a shot '
+ + '— its own controls are in the panel on the right, and '
+ + '⌫ removes it. ' + pick
+ : ((!n && SBE.txSel) ? 'A cut is selected, not a shot — set its '
+ + 'transition in the panel on the right. ' + pick
+ : pick);
+ const rows = [
+ { id: 'sbeCbSplit', act: 'sbeSplitHere()', label: 'Split',
+ why: splitWhy,
+ title: SBE_SPLIT_TITLE },
+ { id: 'sbeCbLift', act: 'sbeLiftSelected()', label: 'Lift',
+ why: n ? '' : noSel,
+ title: 'Takes ' + some + ' out and LEAVES the hole, so nothing after '
+ + 'it moves.' + sbeKeyHint('editor.lift') },
+ { id: 'sbeCbRipple', act: 'sbeRippleSelected()', label: 'Ripple delete',
+ why: n ? '' : noSel,
+ title: 'Takes ' + some + ' out and CLOSES the gap — everything after '
+ + 'slides earlier and the film gets shorter.' + sbeKeyHint('editor.ripple') },
+ { id: 'sbeCbDup', act: 'sbeDuplicateSel()', label: 'Duplicate',
+ why: n ? '' : noSel,
+ title: (many ? 'Each selected shot again, right behind itself'
+ : 'The same shot again, right after this one')
+ + ' — window, speed, fades and grade included. Everything after '
+ + 'it slides.' + sbeKeyHint('editor.duplicate') },
+ // THE SOUND GROUP. Link and Resync are adjacent on purpose: the thing
+ // that is hard to hold in your head is the difference between them, and
+ // side by side both tooltips can say it.
+ { id: 'sbeCbLink', act: 'sbeToggleAudioLink()',
+ icon: (split && !w.linked) ? '#ic-link' : '#ic-unlink',
+ label: !vid ? 'Unlink sound'
+ : (w.linked ? 'Unlink sound'
+ : (sbeAudioIsThePicture(c) ? 'Re-link sound' : 'Link sound')),
+ why: !n ? noSel : (!vid ? 'Only a video clip has sound of its own — a '
+ + 'still and a black slug have none to unlink.'
+ : ''),
+ title: (w && w.linked)
+ ? 'Frees ' + (many ? 'their' : 'this clip\'s') + ' sound from the '
+ + 'picture so you can slide it under the shot before or after — the '
+ + 'J-cut and the L-cut. The picture does not move.' + sbeKeyHint('editor.link')
+ : ((c && sbeAudioIsThePicture(c))
+ ? 'Puts the sound back under its own picture and keeps the two '
+ + 'together from here.' + sbeKeyHint('editor.link')
+ : 'Keeps the ' + sbeDriftLabel(drift) + ' offset you made and '
+ + 'makes the pair travel together from here. Resync is the '
+ + 'button that puts it back under its own frame.' + sbeKeyHint('editor.link')) },
+ { id: 'sbeCbResync', act: 'sbeResyncSel()', label: 'Resync sound',
+ why: !n ? noSel
+ : (!split ? (w && w.linked
+ ? 'This sound travels with its picture, so it cannot '
+ + 'be out of sync. Unlink it first.'
+ : 'This clip has no sound of its own.')
+ : (sbeAudioInSync(c)
+ ? 'The sound is already under its own picture.' : '')),
+ title: 'Slides the sound back to where its own picture plays it — it is '
+ + sbeDriftLabel(drift) + ' out. The trim you gave it is kept and '
+ + 'it stays unlinked, so it can be moved again.' + sbeKeyHint('editor.resync') },
+ { id: 'sbeCbMute', act: 'sbeToggleClipMute()',
+ icon: (c && sbeClipMuted(c)) ? '#ic-sound' : '#ic-mute',
+ label: (c && sbeClipMuted(c)) ? 'Unmute sound' : 'Mute sound',
+ on: !!(c && sbeClipMuted(c)),
+ why: !n ? noSel : (!track ? 'This clip has no sound of its own to '
+ + 'switch off.' : ''),
+ title: (c && sbeClipMuted(c))
+ ? 'Lets ' + (many ? 'their' : 'this clip\'s') + ' own sound play '
+ + 'again.'
+ : 'Switches ' + (many ? 'their' : 'this clip\'s') + ' own sound off — '
+ + 'in the preview, the render and the export. The strip stays where '
+ + 'it is and the soundtrack is not affected.' },
+ { id: 'sbeCbDelSound', act: 'sbeDeleteStripSel()', label: 'Delete sound',
+ why: !n ? noSel
+ : (!split ? 'Unlink the sound first. On a clip whose sound is '
+ + 'still attached to its picture, removing it and '
+ + 'muting it would be the same button twice.' : ''),
+ title: 'Removes ' + (many ? 'their' : 'this clip\'s') + ' sound. The '
+ + 'picture keeps playing, silent, and does not move. Undo brings '
+ + 'it back.' },
+ { id: 'sbeCbPoints', act: 'sbeClearPoints()', label: 'Clear points',
+ why: !n ? noSel
+ : (!pts ? 'This sound has no level anchors on it. Click the yellow '
+ + 'line on a strip — or double-click the strip — to put '
+ + 'one down.' : ''),
+ title: 'Deletes the level anchors — the dots on the yellow line — from '
+ + (many ? 'every selected strip' : 'this strip') + '. The corner '
+ + 'fades are not points and are left alone.' },
+ { id: 'sbeCbLock', act: 'sbeToggleLock()',
+ icon: (c && c.locked) ? '#ic-unlock' : '#ic-lock',
+ label: (c && c.locked) ? 'Unlock' : 'Lock',
+ on: !!(c && c.locked),
+ why: n ? '' : noSel,
+ title: (c && c.locked)
+ ? 'Lets ' + some + ' move and trim again.'
+ : 'Pins ' + some + ' to its place on the film — everything else '
+ + 'flows around it, and it cannot be dragged or trimmed until it '
+ + 'is unlocked.' },
+ ];
+ // The one readout that makes the rest of the row legible.
+ let who = 'Nothing selected';
+ if (many) who = n + ' clips selected';
+ else if (c) {
+ who = (kind === 'slug') ? 'Black'
+ : sbeNiceName(c.title || String(c.path || '').split('/').pop() || 'clip');
+ } else if (SBE.ovSel) who = 'Title or card selected';
+ else if (SBE.txSel) who = 'Cut selected';
+ return { rows: rows, who: who, count: n, many: many, whoWhy: noSel };
+}
+
+// Apply the table to the row. Labels, tooltips, icons and the disabled state
+// — and nothing is added or removed, which is what lets the overflow below
+// move these very elements around without any of them losing a handler.
+function sbePaintCbar() {
+ const bar = sbeEl('sbeCbar');
+ if (!bar) return;
+ const m = sbeCbarModel();
+ const who = sbeEl('sbeCbarWho');
+ if (who) {
+ who.textContent = m.who;
+ who.title = m.whoWhy;
+ who.classList.toggle('is-many', m.many);
+ }
+ for (const r of m.rows) {
+ const el = sbeEl(r.id);
+ if (!el) continue;
+ const lab = el.querySelector('b');
+ if (lab && lab.textContent !== r.label) lab.textContent = r.label;
+ el.disabled = !!r.why;
+ el.title = r.why || r.title;
+ el.classList.toggle('is-on', !!r.on);
+ if (r.icon) {
+ const use = el.querySelector('use');
+ if (use && use.getAttribute('href') !== r.icon) {
+ use.setAttribute('href', r.icon);
+ }
+ }
+ }
+ sbeCbarFit();
+}
+
+// The row's own order, stamped once, so a button that has been in the
+// overflow can be put back exactly where it came from. Without it the bar
+// slowly re-orders itself every time the pane is resized.
+function sbeCbarStamp(bar) {
+ if (bar.dataset.stamped) return;
+ let i = 0;
+ for (const kid of Array.prototype.slice.call(bar.children)) {
+ kid.dataset.ord = String(i++);
+ }
+ bar.dataset.stamped = '1';
+}
+
+// OVERFLOW, NOT WRAP. `flex-wrap` would answer a narrow pane by growing a
+// second row, and a second row pushes the tracks down the column — which
+// sbeFitMonitors then pays for out of the PICTURE, the one thing this screen
+// is for. So the bar measures itself and moves its tail into #sbeCbarMenu,
+// last button first, until what is left fits. Everything comes home when the
+// pane is widened: there is one copy of every control, never two.
+//
+// MEASURED, NOT GUESSED: the labels are words, the words change with the
+// state (Unlink → Link), and the pane's own width is a drag handle, so the
+// only number worth trusting is the one the browser just laid out. Gated on a
+// signature of that number and those words, because sbePaint runs on every
+// frame of a drag and of playback, and a forced reflow per frame is a
+// stutter.
+function sbeCbarFit(force) {
+ const bar = sbeEl('sbeCbar');
+ const pop = sbeEl('sbeCbarMenu');
+ const more = sbeEl('sbeCbMoreBtn');
+ if (!bar || !pop || !more) return;
+ if (!bar.clientWidth) return; // the timeline is not on screen
+ sbeCbarStamp(bar);
+ const verbs = Array.prototype.slice.call(bar.children)
+ .concat(Array.prototype.slice.call(pop.children))
+ .filter(k => k.classList && k.classList.contains('sbe-cbar-btn')
+ && k !== more)
+ .sort((a, b) => sbeNum(a.dataset.ord) - sbeNum(b.dataset.ord));
+ const sig = bar.clientWidth + '|' + verbs.map(v => v.textContent).join(',');
+ if (!force && bar.dataset.fit === sig) return;
+ bar.dataset.fit = sig;
+ // Home first, in the stamped order, so the measurement below is of the
+ // whole row and not of whatever was left after the last pass.
+ const home = Array.prototype.slice.call(bar.children)
+ .concat(Array.prototype.slice.call(pop.children))
+ .sort((a, b) => sbeNum(a.dataset.ord) - sbeNum(b.dataset.ord));
+ for (const kid of home) bar.appendChild(kid);
+ more.hidden = true;
+ if (window.matchMedia && window.matchMedia('(max-width: 900px)').matches) {
+ // Below the stacking breakpoint the page is the scroller, there is no
+ // column height to protect, and the CSS lets the bar wrap. Nothing to do.
+ return;
+ }
+ // The overflow button has to be paid for out of the row before anything is
+ // measured against it, or the last verb moves in and then does not fit.
+ const spill = [];
+ for (let guard = verbs.length; guard > 0; guard--) {
+ if (bar.scrollWidth <= bar.clientWidth + 1) break;
+ const last = verbs.pop();
+ if (!last) break;
+ spill.unshift(last);
+ more.hidden = false;
+ pop.insertBefore(last, pop.firstChild);
+ }
+ if (!spill.length) {
+ more.hidden = true;
+ if (!pop.hidden) sbePopCloseAll('');
+ }
+ // A GROUP DIVIDER WITH NOTHING LEFT AFTER IT is a hairline floating at the
+ // end of the row. Hidden rather than removed, so homing puts it back.
+ const kids = Array.prototype.slice.call(bar.children);
+ for (let i = 0; i < kids.length; i++) {
+ if (!kids[i].classList.contains('sbe-cbar-sep')) continue;
+ let live = false;
+ for (let j = i + 1; j < kids.length; j++) {
+ if (kids[j].classList.contains('sbe-cbar-btn') && kids[j] !== more) {
+ live = true; break;
+ }
+ }
+ kids[i].hidden = !live;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// RIGHT-CLICK ON THE TRACK
+// ---------------------------------------------------------------------------
+// The second place every editor's hand goes, and this timeline answered it
+// with the browser's own menu. Items are written for whatever is UNDER the
+// pointer: a shot gets the clip bar's verbs (the enabled ones, from the same
+// table, so nothing can drift), and a hole gets the only two things a hole
+// can be asked — close it, or fill it with a new shot.
+function sbeCtxOpen(ev) {
+ const menu = sbeEl('sbeCtxMenu');
+ if (!menu) return;
+ const gap = ev.target.closest ? ev.target.closest('.sbe-gap') : null;
+ const blk = ev.target.closest ? ev.target.closest('.sbe-clip') : null;
+ if (!gap && !blk) return;
+ ev.preventDefault();
+ sbePopCloseAll('');
+ let html = '';
+ if (gap) {
+ const at = sbeNum(gap.dataset.gapStart);
+ const dur = sbeNum(gap.dataset.gapDur);
+ html = '<div class="sbe-ctx-h">Hole · ' + escapeHtml(dur.toFixed(2)) + 's</div>'
+ + '<button type="button" class="sbe-cbar-btn" onclick="sbeCloseGapAt('
+ + (at + dur / 2).toFixed(4) + ')" title="Slides everything after the '
+ + 'hole earlier by ' + escapeHtml(dur.toFixed(2)) + 's, so the film '
+ + 'gets that much shorter.">Close this hole</button>'
+ + '<button type="button" class="sbe-cbar-btn" onclick="sbeGenOpen('
+ + at.toFixed(4) + ',' + dur.toFixed(4) + ')" title="Render a new shot '
+ + 'to fill exactly these seconds.">Generate a shot here…</button>';
+ } else {
+ // A right-click on a shot that is NOT in the selection selects it, which
+ // is what every program does; a right-click INSIDE a selection leaves the
+ // selection alone, so the menu acts on all of it.
+ if (!sbeSelHas(blk.dataset.id)) { sbeSelectOne(blk.dataset.id); sbePaint(); }
+ const m = sbeCbarModel();
+ html = '<div class="sbe-ctx-h">' + escapeHtml(m.who) + '</div>';
+ for (const r of m.rows) {
+ if (r.why) continue; // only what can actually fire
+ html += '<button type="button" class="sbe-cbar-btn" onclick="'
+ + escapeHtml(r.act) + '" title="' + escapeHtml(r.title) + '">'
+ + escapeHtml(r.label) + '</button>';
+ }
+ // REORDER LIVES HERE NOW. It used to be shift+drag, and shift had to go
+ // to the range selection the owner asked for — so the gesture moved to
+ // alt+shift+drag, and it also became two plain items in a menu, which is
+ // strictly more discoverable than the modifier it lost.
+ const order = (SBE.clips || []).map(c => String(c.id));
+ const i = order.indexOf(String(blk.dataset.id));
+ html += '<span class="sbe-pop-sep"></span>';
+ if (i > 0) {
+ html += '<button type="button" class="sbe-cbar-btn" '
+ + 'onclick="sbeReorderSel(-1)" title="Swaps this shot with the one '
+ + 'before it. The film stays exactly as long.">Move earlier</button>';
+ }
+ if (i >= 0 && i < order.length - 1) {
+ html += '<button type="button" class="sbe-cbar-btn" '
+ + 'onclick="sbeReorderSel(1)" title="Swaps this shot with the one '
+ + 'after it. The film stays exactly as long.">Move later</button>';
+ }
+ }
+ menu.innerHTML = html;
+ menu.hidden = false;
+ // At the pointer, kept inside the window — the same rule sbePopToggle
+ // applies to a button-anchored panel, against a point instead of a box.
+ const r = menu.getBoundingClientRect();
+ menu.style.left = Math.max(6, Math.min(ev.clientX,
+ window.innerWidth - r.width - 6)) + 'px';
+ menu.style.top = Math.max(6, Math.min(ev.clientY,
+ window.innerHeight - r.height - 6)) + 'px';
+}
+
+// Swap the selected shot with its neighbour — the reorder verb, reachable by
+// name. It goes through the model's own `sbeReorderTo`, so a locked shot
+// refuses it the way a locked shot refuses everything else.
+function sbeReorderSel(dir) {
+ const id = String(SBE.sel || '');
+ if (!id) return;
+ const i = (SBE.clips || []).map(c => String(c.id)).indexOf(id);
+ if (i < 0) return;
+ // `sbeReorderTo` takes a TIME and turns it into a drop index against the
+ // list with this clip already taken out. So one slot either way is "aim at
+ // the head of the shot before" or "aim at the tail of the shot after",
+ // which lands correctly however long the neighbours are.
+ const rest = (SBE.clips || []).filter(c => String(c.id) !== id);
+ const nb = (dir < 0) ? rest[i - 1] : rest[i];
+ if (!nb) return;
+ const at = (dir < 0) ? sbeNum(nb.film_start) : sbeNum(nb.film_end);
+ sbeMutate(cs => sbeReorderTo(cs, id, at));
+ sbePopCloseAll('');
+}
+
function sbePaintInspector() {
const box = sbeEl('sbeInspect');
// A SELECTED CUT OWNS THE INSPECTOR. The boundary between two clips is a
@@ -6136,10 +6886,21 @@ function sbePaintInspector() {
// become a flat run of buttons with a brightness slider floating in the
// middle. Clip / Sound / Effects — and Effects is the home the ruling asked
// for, so the next one lands without a decision.
- const sect = (name, body) => body
- ? '<div class="sbe-sect"><div class="sbe-sect-h">' + name + '</div>' +
- '<div class="sbe-sect-b">' + body + '</div></div>'
- : '';
+ // THE SECTIONS STILL SAY Clip / Sound / Effects — that is the model
+ // docs/EDITOR_EFFECTS_MODEL.md describes and the home the next effect lands
+ // in without a decision. What is new is the LEAD: the verbs left this box
+ // for the clip bar, so the box says what it is now, once, instead of
+ // looking like a toolbar that has lost most of its buttons.
+ let leadDone = false;
+ const sect = (name, body) => {
+ if (!body) return '';
+ const lead = leadDone ? ''
+ : '<div class="sbe-sect-lead">Advanced \u2014 the everyday verbs are on '
+ + 'the bar above the tracks.</div>';
+ leadDone = true;
+ return lead + '<div class="sbe-sect"><div class="sbe-sect-h">' + name
+ + '</div><div class="sbe-sect-b">' + body + '</div></div>';
+ };
const e = sbeFx(c);
const fadeRow = (edge, val) =>
'<span class="sbe-fade-row">' +
@@ -6154,8 +6915,18 @@ function sbePaintInspector() {
? '<button type="button" class="ghost-btn" onclick="sbeFadeCommit(\'' + edge + '\', 0)">Clear</button>'
: '') +
'</span>';
+ // HOW MANY, AND WHOSE PROPERTIES THESE ARE. With four shots selected the
+ // bar acts on four and this box still describes ONE of them, so it has to
+ // say which — otherwise a speed typed here would read as a speed set on all
+ // of them.
+ const nSel = sbeSelCount();
box.innerHTML =
- '<b>' + escapeHtml(label) + '</b>' + src +
+ '<b>' + escapeHtml(label) + '</b>' +
+ (nSel > 1
+ ? '<span class="sbe-sect-lead">' + nSel + ' clips selected \u00b7 these '
+ + 'are THIS one\'s properties. The bar above the tracks acts on all '
+ + nSel + '.</span>'
+ : '') + src +
'<span>film ' + sbeNum(c.film_start).toFixed(2) + '–' + sbeNum(c.film_end).toFixed(2) + 's</span>' +
'<span>' + escapeHtml(c.source === 'human' ? 'moved by hand' : 'placed by the auto-editor') + '</span>' +
// THE PAIR'S OWN LINE. An unlinked strip is either where the picture would
@@ -6192,68 +6963,32 @@ function sbePaintInspector() {
'title="' + (v === 1 ? 'Normal speed' : (v < 1 ? 'Half speed — twice as long on the film' : 'Double speed — half as long on the film')) + '">' + v + 'x</button>').join('') +
'</span>'
: '') +
- '<button type="button" class="ghost-btn" onclick="sbeToggleLock()" ' +
- 'title="' + (c.locked ? 'Let this shot move and trim again.' : 'Pin this shot to its place on the film; everything else flows around it.') + '">' +
- (c.locked ? 'Unlock' : 'Lock') + '</button>' +
- '<button type="button" class="ghost-btn" onclick="sbeDuplicateSel()" ' +
- 'title="The same shot again, right after this one — window, speed, fades and grade included. Everything after it slides. (D)">Duplicate</button>' +
+ // LOCK, DUPLICATE, LIFT AND RIPPLE DELETE ARE NOT HERE ANY MORE. They
+ // are verbs a cutter reaches for hundreds of times a session and they
+ // were drawn identically to a brightness slider, in a 212px column, in
+ // the corner of the screen: "they are hidden inside that menu, the
+ // toggle menu on the right. That is not a good use." They live on the
+ // clip bar above the tracks now — always visible, always in the same
+ // place, disabled with a reason rather than dropped. What stays here is
+ // what this box is FOR: the properties of the one selected clip.
+ // See docs/EDITOR_TOOLBAR.md.
// RETAKE: send this clip back through the renderer and get a new take
- // offered against it, in place. Only a clip that came from a shot has
- // a prompt to start from — and the inspector says so when it cannot.
+ // offered against it, in place. It stays in the inspector because it is
+ // rare, slow and it opens a dialogue — nothing a toolbar should invite
+ // by accident. Only a clip that came from a shot has a prompt to start
+ // from, and the inspector says so when it cannot.
((kind === 'video' && sbeShotForClip(c))
? '<button type="button" class="ghost-btn" onclick="sbeRetakeSel()" ' +
'title="Render a new take of this shot — same character, a new seed, the prompt to edit. When it lands you choose whether it replaces this clip.">Retake</button>'
- : '') +
- '<button type="button" class="ghost-btn" onclick="sbeLiftSelected()" ' +
- 'title="Take this shot out and leave its hole. Nothing else moves. (Delete)">Lift</button>' +
- '<button type="button" class="ghost-btn" onclick="sbeRippleSelected()" ' +
- 'title="Take this shot out and close the gap. Everything after it slides earlier. (Shift+Delete)">Ripple delete</button>') +
+ : '')) +
sect('Sound',
- // THE J-CUT'S ONE SWITCH. Only a video clip has sound of its own, so
- // only a video clip is offered it.
- (kind === 'video'
- ? '<button type="button" class="ghost-btn" onclick="sbeToggleAudioLink()" ' +
- 'title="' + escapeHtml(sbeClipAudio(c).linked
- ? 'Let this clip\'s sound move and trim on its own — the J-cut and the L-cut. The picture stays draggable from both edges.'
- : (sbeAudioInSync(c)
- ? 'Put the sound back under its own picture'
- : 'Keep the ' + sbeDriftLabel(sbeAudioDrift(c)) + ' offset you made '
- + 'and travel together from here. Resync is the button that '
- + 'puts it back under its own frame.')) + '">' +
- (sbeClipAudio(c).linked ? 'Unlink sound'
- : (sbeAudioIsThePicture(c) ? 'Re-link sound'
- : 'Link sound' + (sbeAudioInSync(c) ? ''
- : ' at ' + sbeDriftLabel(sbeAudioDrift(c))))) + '</button>'
- : '') +
- // MUTE, and it is offered whether the sound is linked, unlinked or
- // travelling — muting silences the CLIP's sound wherever its strip is.
- // Refused only for a clip whose file has no audio track at all, because
- // there is nothing there to switch off.
- ((kind === 'video' && c.has_audio !== false)
- ? '<button type="button" class="ghost-btn" onclick="sbeToggleClipMute()" ' +
- 'title="' + escapeHtml(sbeClipMuted(c)
- ? 'Let this clip\'s own sound play again'
- : 'Switch this clip\'s own sound off — in the preview, in the render '
- + 'and in the export. The soundtrack is not affected.') + '">' +
- (sbeClipMuted(c) ? 'Unmute sound' : 'Mute sound') + '</button>'
- : '') +
- // DELETE THE STRIP, not the clip. Offered only once the two halves are
- // actually separate — on a linked clip "delete the sound" and "mute" would
- // be the same button twice.
- ((kind === 'video' && sbeClipAudio(c).split)
- ? '<button type="button" class="ghost-btn" onclick="sbeDeleteStripSel()" ' +
- 'title="' + escapeHtml('Remove this clip\'s sound. The picture keeps '
- + 'playing, silent, and does not move.') + '">Delete sound</button>'
- : '') +
- // RESYNC IS NOT RE-LINK, and the two sit next to each other so the
- // difference is legible: re-link puts the sound back UNDER the picture
- // permanently, resync only slides it back into place and leaves it free.
- ((kind === 'video' && sbeClipAudio(c).split && !sbeAudioInSync(c))
- ? '<button type="button" class="ghost-btn" onclick="sbeResyncSel()" ' +
- 'title="' + escapeHtml('Slide the sound back to where its own picture '
- + 'plays it. The trim you gave it is kept, and it stays unlinked.') +
- '">Resync sound (' + escapeHtml(sbeDriftLabel(sbeAudioDrift(c))) + ')</button>'
- : '') +
+ // UNLINK / LINK, RESYNC, MUTE AND DELETE SOUND ARE ON THE CLIP BAR NOW.
+ // They were the four the owner named — "for instance, unlink and link
+ // audio… I find myself all the time un-syncing and syncing" — and all
+ // four were inside this box, two of them appearing and disappearing with
+ // the state, which is how "Delete sound" managed to be invisible on every
+ // linked clip and therefore on almost every clip. What is left here is
+ // the sound's SHAPE: its ramps and its level line.
// THE SOUND'S OWN RAMPS LIVE HERE, not under a fourth heading. Three
// sections is what docs/EDITOR_EFFECTS_MODEL.md describes and what the
// rail has room for; a "Sound fades" heading of its own pushed the
@@ -6287,10 +7022,13 @@ function sbePaintInspector() {
+ 'strip: click the yellow line to add one, drag it to set '
+ 'the level, right-click it to remove it.">'
+ 'Add point at playhead</button>'
- + (n ? '<button type="button" class="ghost-btn" '
- + 'onclick="sbeClearPoints()" '
- + 'title="Removes every level point on this strip. The '
- + 'fades stay.">Clear ' + n + '</button>'
+ // "Clear" IS ON THE CLIP BAR — it is the owner's "delete
+ // button for the anchors of the audio", and a button that
+ // only existed once there was something to clear is a
+ // button nobody knew existed. This says how many there are.
+ + (n ? '<span class="sbe-adj-val">' + n + ' point'
+ + (n === 1 ? '' : 's') + ' \u00b7 Clear points on the '
+ + 'bar above</span>'
: '<span class="sbe-adj-val">click the yellow line</span>')
: '<span class="sbe-adj-val">unlink the sound to shape its '
+ 'level</span>')
@@ -6628,14 +7366,46 @@ function sbeOnTrackDown(ev) {
return;
}
const blk = ev.target.closest('.sbe-clip');
- if (!blk) { SBE.txSel = ''; sbeSeek(sbeTimeFromEvent(ev, track)); sbePaint(); return; }
+ // EMPTY TRACK CLEARS THE SELECTION as well as moving the playhead, which is
+ // what every NLE does and what makes ⌘-click and shift-click safe to
+ // experiment with: there is always an obvious way back to nothing.
+ if (!blk) {
+ SBE.txSel = ''; SBE.sel = ''; SBE.selSet = [];
+ sbeSeek(sbeTimeFromEvent(ev, track));
+ sbePaint();
+ return;
+ }
const id = blk.dataset.id;
- SBE.sel = id;
SBE.ovSel = ''; // one inspector, one subject
SBE.txSel = '';
SBE.audioDrag = null; // same insurance the lane takes against the other
const c = sbeById(SBE.clips, id);
if (!c) return;
+ // ---- WHAT THIS CLICK DOES TO THE SELECTION ----------------------------
+ // Two of the three modifiers are already taken by this very gesture — ⌘ is
+ // ripple-drag and shift was reorder-drag — so the selection cannot simply
+ // claim them at pointerdown and hope.
+ //
+ // shift — takes the RANGE, now, because selection feedback that waits
+ // for pointerup feels broken. Reorder therefore moves to
+ // alt+shift (it never snapped, so alt costs it nothing) and to
+ // two named items in the right-click menu.
+ // ⌘/ctrl — cannot be decided here: the same chord means "ripple" once the
+ // pointer moves. Recorded, and resolved on pointerup, and only
+ // if the pointer never moved.
+ // plain — selects this clip, UNLESS it is already part of a multiple
+ // selection, in which case the selection survives so the drag
+ // that follows can move the whole block. Clicking without
+ // dragging then collapses to this clip on pointerup — the rule
+ // Premiere and Resolve share.
+ const meta = !!(ev.metaKey || ev.ctrlKey);
+ const already = sbeSelHas(id);
+ let toggle = '', collapse = '';
+ if (ev.shiftKey && !meta && SBE.sel) sbeSelectRange(id);
+ else if (meta) { toggle = id; }
+ else if (!already) sbeSelectOne(id);
+ else if (sbeSelCount() > 1) { SBE.sel = String(id); collapse = id; }
+ else sbeSelectOne(id);
// A LOCKED SHOT SAYS SO. Until now it refused every drag in silence: the CSS
// turned the cursor to `not-allowed`, hid both grips, and nothing on screen
// said why or what to press. The owner hit it while cutting — "trying to
@@ -6649,8 +7419,8 @@ function sbeOnTrackDown(ev) {
// clip and its sound travel together, which is what he was reaching for
// when he pressed it. That one is Link sound.
phosToast('That shot is locked to its place on the __SEQ__, so it cannot be '
- + 'moved or trimmed from either edge — click Unlock in the '
- + 'inspector. To move a shot and its sound TOGETHER, unlink the '
+ + 'moved or trimmed from either edge — press Unlock on the bar '
+ + 'above the tracks. To move a shot and its sound TOGETHER, unlink the '
+ 'sound, put it where you want it, then press Link sound.',
{ duration: 9000 });
return;
@@ -6679,22 +7449,38 @@ function sbeOnTrackDown(ev) {
if (ev.clientX - br.left <= EDGE) grip = { classList: { contains: () => false } };
else if (br.right - ev.clientX <= EDGE) grip = { classList: { contains: (k) => k === 'r' } };
}
- // SHIFT IS REORDER. The hint strip already teaches "hold Alt to ignore the
- // beat", so a second modifier on the same gesture is the idiom this timeline
- // already has — and it is the only way to offer both verbs without a mode
- // switch nobody would find. Free drag stays the default: it is what every
- // arrangement on disk was made with, and it is the one that can open a hole
- // for the generate control to fill.
+ // ALT+SHIFT IS REORDER. It was shift alone until multi-select needed shift
+ // for the range every list in every program answers to. Alt costs the
+ // gesture nothing — a reorder chooses a NEIGHBOUR, not a time, so it never
+ // snapped to the beat grid that alt suppresses — and the verb also became
+ // two named items in the right-click menu, which is strictly easier to find
+ // than the modifier it gave up. Free drag stays the default: it is what
+ // every arrangement on disk was made with, and it is the one that can open
+ // a hole for the generate control to fill.
+ //
+ // A MULTIPLE SELECTION MAKES THE DRAG A BLOCK SLIDE. Only for `move`: a
+ // trim is one clip's edge whatever else is selected, and a reorder chooses
+ // one clip's neighbour.
+ const many = sbeSelCount() > 1 && sbeSelHas(id);
const mode = grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL')
- : (ev.shiftKey ? 'reorder' : 'move');
+ : ((ev.shiftKey && ev.altKey) ? 'reorder'
+ : (many ? 'movemany' : 'move'));
// ⌘ / CTRL IS RIPPLE: the gesture also slides everything after the clip,
// the way it did before 2026-09-05. Read again on every move so it can be
// pressed or released mid-drag, as in Premiere.
SBE.drag = { id: id, mode: mode, x0: ev.clientX, t0: sbeTimeFromEvent(ev, track),
fs0: sbeNum(c.film_start), fe0: sbeNum(c.film_end), moved: false,
ripple: !!(ev.metaKey || ev.ctrlKey),
+ ids: (mode === 'movemany') ? sbeSelIds() : null,
+ toggle: toggle, collapse: collapse,
before: JSON.stringify(SBE.clips) };
- if (mode === 'move') blk.classList.add('is-drag');
+ if (mode === 'move' || mode === 'movemany') {
+ for (const el of document.querySelectorAll('.sbe-clip')) {
+ if (mode === 'move' ? el === blk : sbeSelHas(el.dataset.id)) {
+ el.classList.add('is-drag');
+ }
+ }
+ }
track.classList.toggle('is-ripple', SBE.drag.ripple);
try { track.setPointerCapture(ev.pointerId); } catch (e) {}
ev.preventDefault();
@@ -6736,7 +7522,15 @@ function sbeOnTrackMove(ev) {
track.classList.toggle('is-ripple', ripple);
SBE.clips = JSON.parse(d.before);
const o = { ripple: ripple };
- if (d.mode === 'move') {
+ if (d.mode === 'movemany') {
+ // THE BLOCK SLIDES BY ONE DELTA, and it is the PRIMARY clip's own start
+ // that is snapped — the beat the user is watching is the one under the
+ // clip he grabbed, and snapping each member separately would stretch
+ // the selection instead of moving it.
+ const want = sbeSnapTime(Math.max(0, d.fs0 + dt), SBE.beats, tol, snapOn, off);
+ const r = sbeMoveGroup(SBE.clips, d.ids || [], want - d.fs0);
+ if (r.ok) SBE.clips = r.clips;
+ } else if (d.mode === 'move') {
const want = sbeSnapTime(Math.max(0, d.fs0 + dt), SBE.beats, tol, snapOn, off);
const r = sbeMoveTo(SBE.clips, d.id, want, o);
if (r.ok) SBE.clips = r.clips;
@@ -6775,7 +7569,17 @@ 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.moved) { sbePaint(); 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
+ // multiple selection had to wait to find out whether it was the start of a
+ // block move or a request to work on this one shot.
+ if (!d.moved) {
+ if (d.toggle) sbeSelectToggle(d.toggle);
+ else if (d.collapse) sbeSelectOne(d.collapse);
+ sbePaint();
+ return;
+ }
// A DRAG THAT MOVED THE POINTER BUT NOT THE FILM IS NOT AN EDIT. Dragging a
// clip left when it is already hard against its neighbour is the common case
// — the maths clamps, nothing lands anywhere new, and without this the
@@ -8155,18 +8959,59 @@ function sbeZoom(dir) {
sbeZoomTo(steps[Math.max(0, Math.min(steps.length - 1, i + dir))]);
}
+// ⇧Z — FIT. The slider's left end already means "all of it"; this is its key.
+function sbeZoomFit() { sbeZoomTo(sbeZoomMin()); }
+
+// ↑ ↓ — THE PREVIOUS / NEXT CUT: every edge a clip has on the picture lane,
+// plus the two ends of the sequence. The playhead lands exactly on one.
+function sbeJumpCut(dir) {
+ const marks = [0, sbeFilmDuration(SBE.clips)];
+ for (const c of SBE.clips || []) marks.push(sbeNum(c.film_start), sbeNum(c.film_end));
+ const eps = 0.5 / sbeFps();
+ const now = SBE.playhead;
+ let want = null;
+ for (const m of marks) {
+ if (dir < 0 && m < now - eps && (want === null || m > want)) want = m;
+ if (dir > 0 && m > now + eps && (want === null || m < want)) want = m;
+ }
+ if (want === null) return;
+ sbeStop();
+ sbeSeek(want);
+}
+
+// N — SNAP. The transport's own checkbox, so the key and the box are one state.
+function sbeToggleSnap() {
+ const box = sbeEl('sbeSnapOn');
+ if (!box) return;
+ box.checked = !box.checked;
+ sbePaint();
+ phosToast(box.checked ? 'Snap to beat is on.' : 'Snap to beat is off — clips move freely.',
+ { duration: 2000 });
+}
+
+// A tooltip's keys, read from the one shortcut table (webapp/js/shortcuts.js).
+function sbeKeyHint(id) {
+ const h = (typeof shortcutHint === 'function') ? shortcutHint(id) : '';
+ return h ? ' (' + h + ')' : '';
+}
+
function sbeZoomSlide(v) {
const lo = sbeZoomMin();
sbeZoomTo(sbeZoomFromSlider(v, lo, Math.max(lo, SBE_PPS_MAX)));
}
-// shift + wheel pans, alt + wheel zooms around the pointer — the two gestures
-// every NLE and every DAW already has. A plain wheel is left alone: it belongs
-// to the column, which scrolls vertically.
+// shift + wheel pans, alt + wheel (or a trackpad pinch) zooms around the
+// pointer — the gestures every NLE and every DAW already has. A plain wheel is
+// left alone: it belongs to the column, which scrolls vertically.
function sbeOnTlWheel(ev) {
const box = sbeEl('sbeScroll');
if (!box) return;
- if (ev.altKey) {
+ // PINCH IS ZOOM, and it was not. A trackpad pinch arrives as a `wheel`
+ // event with `ctrlKey` set — that is how every browser reports it — so the
+ // one zoom gesture a Mac user tries first did nothing here, and on a page
+ // with no handler it would have zoomed the whole panel instead. Alt+wheel
+ // stays for a mouse.
+ if (ev.altKey || ev.ctrlKey) {
ev.preventDefault();
const r = box.getBoundingClientRect();
const at = (box.scrollLeft + (ev.clientX - r.left)) / Math.max(1e-6, SBE.pps);
@@ -8182,21 +9027,53 @@ function sbeOnTlWheel(ev) {
box.scrollLeft += dx;
}
+// THE VERBS, AND THE ONE RULE THEY ALL FOLLOW. Each of these used to read
+// `SBE.sel` and act on exactly one clip. They now act on the whole selection —
+// and on a selection of one they take the SAME path they always did, with the
+// same toast, because that is the behaviour on disk, in the tests and in the
+// owner's hands. Only the plural case is new.
function sbeRippleSelected() {
- if (!SBE.sel) return;
- sbeMutate(cs => sbeRippleDelete(cs, SBE.sel));
- SBE.sel = '';
+ const ids = sbeSelIds();
+ if (!ids.length) return;
+ if (ids.length === 1) {
+ sbeMutate(cs => sbeRippleDelete(cs, ids[0]));
+ } else {
+ // RIGHT TO LEFT. A ripple closes the gap it leaves, so removing the
+ // earliest first slides every later victim earlier — and the ids are
+ // still valid, but the film underneath them is not the one the user was
+ // looking at. Taking the last one first leaves the earlier ones exactly
+ // where they were drawn.
+ sbeMutateEach(ids.slice().reverse(), (cs, id) => sbeRippleDelete(cs, id));
+ }
+ SBE.sel = ''; SBE.selSet = [];
sbePaint();
}
function sbeLiftSelected() {
- if (!SBE.sel) return;
- sbeMutate(cs => sbeLiftDelete(cs, SBE.sel));
- SBE.sel = '';
+ const ids = sbeSelIds();
+ if (!ids.length) return;
+ if (ids.length === 1) sbeMutate(cs => sbeLiftDelete(cs, ids[0]));
+ else sbeMutateEach(ids, (cs, id) => sbeLiftDelete(cs, id));
+ SBE.sel = ''; SBE.selSet = [];
sbePaint();
}
function sbeDuplicateSel() {
+ const many = sbeSelIds();
+ if (many.length > 1) {
+ // Each selected shot gets its own copy right behind it, and the COPIES
+ // become the selection — the same rule the single case follows, so the
+ // next verb acts on the thing just made.
+ const made = [];
+ const ok = sbeMutateEach(many, (cs, id) => {
+ const r = sbeDuplicate(cs, id);
+ if (r.ok && r.added) made.push(String(r.added.id));
+ return r;
+ });
+ if (ok && made.length) { SBE.selSet = made; SBE.sel = made[0]; sbePaint(); }
+ sbeBlurControl();
+ return;
+ }
if (!SBE.sel) return;
let added = null;
const ok = sbeMutate(cs => { const r = sbeDuplicate(cs, SBE.sel); if (r.ok) added = r.added; return r; });
@@ -8212,14 +9089,29 @@ function sbeSplitHere() {
}
function sbeToggleLock() {
- const c = sbeById(SBE.clips, SBE.sel);
- if (!c) return;
+ const ids = sbeSelIds();
+ const first = sbeById(SBE.clips, ids[0]);
+ if (!first) return;
+ // THE PRIMARY DECIDES, so a mixed selection CONVERGES rather than inverting
+ // clip by clip. Pressing Lock over three shots where one is already pinned
+ // should end with three pinned shots, which is what the button says it will
+ // do; per-clip inversion would leave the row half on and half off and the
+ // label lying about both.
+ const on = !first.locked;
const before = JSON.stringify(SBE.clips);
- c.locked = !c.locked;
- if (c.locked) c._pin = sbeNum(c.film_start); else delete c._pin;
- c.source = 'human';
+ let touched = 0;
+ for (const id of ids) {
+ const c = sbeById(SBE.clips, id);
+ if (!c || !!c.locked === on) continue;
+ c.locked = on;
+ if (on) c._pin = sbeNum(c.film_start); else delete c._pin;
+ c.source = 'human';
+ touched++;
+ }
+ if (!touched) return;
sbeLayout(SBE.clips);
SBE.undo.push(before);
+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();
SBE.redo.length = 0;
SBE.dirty = true;
sbeSetState('unsaved changes', 'dirty');
@@ -8590,20 +9482,93 @@ document.addEventListener('keydown', (ev) => {
if (document.querySelector('.modal-bg.show')) return;
const step = 1 / sbeFps();
if (ev.key === ' ') { ev.preventDefault(); sbeTogglePlay(); return; }
+ // ALT+ARROW NUDGES THE SHOT, plain arrow moves the playhead. Every NLE has
+ // the first and this one had only the second: there was no gesture at all
+ // for "a hair later" short of dragging at a zoom high enough to see a
+ // frame. The bare arrows stay the playhead's — they are the more frequent
+ // of the two and changing them would move the ground under everybody.
+ if (ev.altKey && (ev.key === 'ArrowLeft' || ev.key === 'ArrowRight')) {
+ ev.preventDefault();
+ sbeNudge(ev.key === 'ArrowLeft' ? -1 : 1, ev.shiftKey);
+ return;
+ }
if (ev.key === 'ArrowLeft') { ev.preventDefault(); sbeStop(); sbeSeek(SBE.playhead - (ev.shiftKey ? step * 10 : step)); return; }
if (ev.key === 'ArrowRight') { ev.preventDefault(); sbeStop(); sbeSeek(SBE.playhead + (ev.shiftKey ? step * 10 : step)); return; }
+ // ↑ ↓ JUMP BETWEEN CUTS — where Premiere, Final Cut and Resolve all put
+ // "previous / next edit point". The timeline's height handle keeps its own
+ // ↑ ↓ while it has focus.
+ if ((ev.key === 'ArrowUp' || ev.key === 'ArrowDown') && !ev.metaKey && !ev.ctrlKey
+ && !ev.altKey && !(t && t.id === 'sbeTlGrab')) {
+ ev.preventDefault(); sbeJumpCut(ev.key === 'ArrowUp' ? -1 : 1); return;
+ }
+ // THE TWO ENDS OF THE FILM. Missing, and the only way to reach the tail was
+ // to drag the playhead across the whole timeline.
+ if (ev.key === 'Home') { ev.preventDefault(); sbeStop(); sbeSeek(0); return; }
+ if (ev.key === 'End') {
+ ev.preventDefault(); sbeStop(); sbeSeek(sbeFilmDuration(SBE.clips)); return;
+ }
+ // SELECT ALL, and it is a selection of CLIPS — there is nothing else on
+ // this screen a ⌘A could plausibly mean, and the browser's own select-all
+ // over a timeline is never what anybody wanted.
+ if ((ev.metaKey || ev.ctrlKey) && (ev.key === 'a' || ev.key === 'A')) {
+ ev.preventDefault(); sbeSelectAll(); return;
+ }
+ // ZOOM ON THE KEYBOARD. The slider and alt+wheel were the only ways in, and
+ // neither is reachable without letting go of what you were doing.
+ if (!ev.metaKey && !ev.ctrlKey
+ && (ev.key === '+' || ev.key === '=' || ev.key === '-' || ev.key === '_')) {
+ ev.preventDefault();
+ sbeZoom((ev.key === '-' || ev.key === '_') ? -1 : 1);
+ return;
+ }
+ // ⇧Z FITS THE SEQUENCE (Final Cut's ⇧Z, Premiere's \) — the slider's left
+ // end, on a key.
+ if (!ev.metaKey && !ev.ctrlKey && !ev.altKey
+ && ((ev.shiftKey && (ev.key === 'Z' || ev.key === 'z')) || ev.key === '\\')) {
+ ev.preventDefault(); sbeZoomFit(); return;
+ }
+ // N IS SNAPPING in all three NLEs. It flips the transport's own "Snap to
+ // beat" box, so the key and the checkbox are one state.
+ if (!ev.metaKey && !ev.ctrlKey && !ev.altKey && !ev.shiftKey && (ev.key === 'n' || ev.key === 'N')) {
+ ev.preventDefault(); sbeToggleSnap(); return;
+ }
+ // THE SOUND PAIR, on the two keys the clip bar's tooltips name. Shift so
+ // 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.
+ if (ev.shiftKey && !ev.metaKey && !ev.ctrlKey && (ev.key === 'L' || ev.key === 'l')) {
+ ev.preventDefault(); sbeToggleAudioLink(); return;
+ }
+ if (ev.shiftKey && !ev.metaKey && !ev.ctrlKey && (ev.key === 'R' || ev.key === 'r')) {
+ ev.preventDefault(); sbeResyncSel(); return;
+ }
if ((ev.key === 'Delete' || ev.key === 'Backspace') && SBE.txSel) { ev.preventDefault(); sbeTxRemoveSel(); return; }
if ((ev.key === 'Delete' || ev.key === 'Backspace') && SBE.ovSel && !SBE.sel) { ev.preventDefault(); sbeOvDeleteSel(); return; }
if ((ev.key === 'Delete' || ev.key === 'Backspace') && ev.shiftKey) { ev.preventDefault(); sbeRippleSelected(); return; }
if (ev.key === 'Delete' || ev.key === 'Backspace') { ev.preventDefault(); sbeLiftSelected(); return; }
- if (ev.key === 's' || ev.key === 'S') { ev.preventDefault(); sbeSplitHere(); return; }
+ // ⌘S SAVES. It has been documented as the manual save since the save model
+ // was written — docs/EDITOR_SAVE_MODEL.md §1, "`Save` (and ⌘S)" — and it
+ // has never done it: the bare-S split below took the key first, with no
+ // modifier guard, so the one chord every person on a Mac presses to make
+ // their work safe SPLIT THE SHOT under the playhead instead. Found while
+ // adding the clip bar, which is exactly the class of thing this pass is
+ // for.
+ if ((ev.metaKey || ev.ctrlKey) && (ev.key === 's' || ev.key === 'S')) {
+ ev.preventDefault(); sbeSaveNow(); return;
+ }
+ // ⌘K is Premiere's Add Edit and ⌘B the Blade in Final Cut and Resolve —
+ // the same verb as S, so a cutter's hand finds it whichever app it learned in.
+ if (((ev.key === 's' || ev.key === 'S') && !ev.metaKey && !ev.ctrlKey)
+ || ((ev.metaKey || ev.ctrlKey) && !ev.shiftKey && !ev.altKey && /^[kKbB]$/.test(ev.key))) {
+ ev.preventDefault(); sbeSplitHere(); return;
+ }
if ((ev.key === 'd' || ev.key === 'D') && !ev.metaKey && !ev.ctrlKey && SBE.sel) { ev.preventDefault(); sbeDuplicateSel(); return; }
if ((ev.metaKey || ev.ctrlKey) && (ev.key === 'z' || ev.key === 'Z')) {
ev.preventDefault();
ev.shiftKey ? sbeRedo() : sbeUndo();
return;
}
- if (ev.key === 'm' || ev.key === 'M') {
+ if ((ev.key === 'm' || ev.key === 'M') && !ev.metaKey && !ev.ctrlKey && !ev.altKey) {
ev.preventDefault();
SBE.muted ? sbeUnmuteFromRefusal() : sbeSetMute(true);
return;
@@ -8616,10 +9581,25 @@ document.addEventListener('keydown', (ev) => {
if (sbePopAnyOpen()) { sbePopCloseAll(''); return; }
const vers = document.getElementById('sbeVersions');
if (vers && !vers.hidden) { sbeVersionsClose(); return; }
- sbeClose();
+ // THE SELECTION IS A THING ON TOP TOO, and it is the one Escape means far
+ // more often than "shut the film". Multi-select made this urgent: a
+ // person who has just ⌘-clicked eight shots needs one key that means
+ // "never mind", and the key that meant it also closed the document.
+ if (SBE.sel || SBE.ovSel || SBE.txSel) { sbeSelectNone(); return; }
+ // AND NOTHING ELSE. Escape used to fall through to closing the document and
+ // shut the
+ // film: a second Escape after clearing a selection threw the editor out of
+ // its timeline, and so did the Escape that closed the Docs on top of it —
+ // the Docs close on keydown first, this handler then found no dialog up
+ // and closed the document behind it. No editor closes a project on
+ // Escape; closing is a choice, made from the ⋯ menu's Close.
+ return;
}
- // RENDER HAS A KEY NOW that it is the only filled control on the screen.
- if ((ev.key === 'r' || ev.key === 'R') && (ev.metaKey || ev.ctrlKey)) {
+ // RENDER HAS A KEY — ⌘E, Export in Final Cut. It was ⌘R, which is the
+ // browser's reload: refreshing the page queued a render of the timeline
+ // instead. A page never claims a reserved chord (SHORTCUT_RESERVED in
+ // webapp/js/shortcuts.js).
+ if ((ev.key === 'e' || ev.key === 'E') && (ev.metaKey || ev.ctrlKey) && !ev.shiftKey && !ev.altKey) {
ev.preventDefault();
sbeRenderFilm();
}
@@ -8644,6 +9624,19 @@ document.addEventListener('click', (ev) => {
if (!track) return;
sbeSetMute(SBE.muted); // the button must agree with the stored state on load
track.addEventListener('pointerdown', sbeOnTrackDown);
+ // 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.
+ track.addEventListener('contextmenu', sbeCtxOpen);
+ const ctx = document.getElementById('sbeCtxMenu');
+ if (ctx) {
+ // A MENU ITEM CLOSES THE MENU. The click-away guard deliberately spares
+ // anything inside a `.sbe-pop`, which is right for the render menu's
+ // pills and wrong for a list of verbs that each do their thing once.
+ ctx.addEventListener('click', (ev) => {
+ if (ev.target.closest('button')) setTimeout(() => { ctx.hidden = true; }, 0);
+ });
+ }
track.addEventListener('pointermove', sbeOnTrackMove);
track.addEventListener('pointerup', sbeOnTrackUp);
track.addEventListener('pointercancel', sbeOnTrackUp);
@@ -8766,6 +9759,7 @@ function workflowSwitch(name) {
const audioTab = document.getElementById('audioSectionTab');
const sbTab = document.getElementById('sbSectionTab');
const edTab = document.getElementById('edSectionTab');
+ const osTab = document.getElementById('oneshotSectionTab');
const characters = document.getElementById('charactersSection'); // dead HTML; hide defensively
// Set body data attribute so CSS can switch the layout per workflow.
document.body.setAttribute('data-workflow', name);
@@ -8775,6 +9769,8 @@ function workflowSwitch(name) {
if (audioTab) audioTab.style.display = 'none';
if (sbTab) sbTab.style.display = 'none';
if (edTab) edTab.style.display = 'none';
+ if (osTab) osTab.style.display = 'none';
+ if (name !== 'oneshot' && typeof oneshotTabLeave === 'function') { try { oneshotTabLeave(); } catch (e) {} }
if (characters) characters.classList.remove('show');
// The board poller is the Storyboard tab's only timer and it stops on exit —
// no new polling loop runs while the tab is closed.
@@ -8817,6 +9813,13 @@ function workflowSwitch(name) {
if (manual) manual.style.display = 'none';
if (audioTab) audioTab.style.display = 'block';
if (typeof audioStudioInit === 'function') audioStudioInit();
+ } else if (name === 'oneshot') {
+ // One Shot: its own composer and its own API (webapp/js/oneshot.js,
+ // POST /oneshot). A shot that never cuts is a different thing to make
+ // than a clip, so it is a tab beside Video, not a chip inside it.
+ if (manual) manual.style.display = 'none';
+ if (osTab) osTab.style.display = 'grid';
+ if (typeof oneshotTabEnter === 'function') { try { oneshotTabEnter(); } catch (e) { console.warn('oneshotTabEnter failed', e); } }
} else if (name === 'editor') {
// The Editor. Engine-agnostic and board-agnostic: it opens the document
// it had open last, and an empty timeline is a legitimate place to stand.
@@ -8950,11 +9953,24 @@ Object.assign(globalThis, {
sbeSetMute, sbeUnmuteFromRefusal, sbePlay, sbeStop,
sbeFrame, sbeMusicPlay, sbeMusicSync, sbeStripSync,
sbeStripStop, sbeZoomMin, sbeZoomTo, sbeZoom,
- sbeZoomSlide, sbeOnTlWheel, sbePrepare, sbePrepareCancel,
+ sbeZoomSlide, sbeZoomFit, sbeJumpCut, sbeToggleSnap, sbeKeyHint,
+ sbeOnTlWheel, sbePrepare, sbePrepareCancel,
sbeAuto, sbeGenClose, sbeGenSubmit, sbeRenderFilm,
sbeExportNle, sbeTick, workflowSwitch,
// inline-handler targets: generated markup resolves these through the
// global scope (the v4.9.0 regression, PR #69)
sbeLiftSelected, sbeOvDeleteSel, sbeOvFadeCommit, sbePlace,
sbeRippleSelected, sbeToggleLock,
+ // THE SELECTION AND THE CLIP BAR. `sbeSplitHere` and the nine verbs beside
+ // it are reached from onclick attributes in index.html now as well as from
+ // generated markup, and `sbeCtxOpen` writes a menu whose items call back
+ // into the same names — so every one of them has to be on the global scope
+ // or the button is a silent no-op at event time. That is exactly the
+ // module-split hazard scripts/lint_webapp.mjs exists to catch.
+ sbeSelNormalise, sbeSelIds, sbeSelCount, sbeSelMap, sbeSelHas, sbeSelClips,
+ sbeSelectOne, sbeSelectToggle, sbeSelectRange, sbeSelectAll, sbeSelectNone,
+ sbeMutateEach, sbeGroupLimits, sbeMoveGroup, sbeCloseGapAt, sbeNudge,
+ sbeCbarModel, sbePaintCbar, sbeCbarFit, sbeCbarStamp,
+ sbeSplitWhy, sbeCbarPlayhead,
+ sbeCtxOpen, sbeReorderSel, sbeSplitHere, sbeGenOpen,
});
diff --git a/webapp/js/engines.js b/webapp/js/engines.js
index 83a0162..00dd0e7 100644
--- a/webapp/js/engines.js
+++ b/webapp/js/engines.js
@@ -74,7 +74,7 @@ function _currentSurface() {
// leaves the engine switcher visible in a tab that has no engine choice to
// offer — the film decides per shot, not a global toggle.
return ({ manual: 'video', studio: 'image', audio: 'audio', train: 'train',
- storyboard: 'storyboard' })[wf] || 'video';
+ storyboard: 'storyboard', oneshot: 'oneshot' })[wf] || 'video';
}
function engineOnSurface(e) {
return (e.surfaces || ['video']).indexOf(_currentSurface()) !== -1;
diff --git a/webapp/js/oneshot.js b/webapp/js/oneshot.js
new file mode 100644
index 0000000..98d0f81
--- /dev/null
+++ b/webapp/js/oneshot.js
@@ -0,0 +1,565 @@
+// ---- ONE SHOT — its own door (2026-09-08) -----------------------------------
+// One continuous shot of 30 s – 2 min that never cuts, rendered as parts that
+// continue from each other's last frame (run_take_job_inner). It used to be a
+// mode chip on the video form and a folded panel under it; it is a workflow
+// tab now, with its own composer and its own API. Nothing here rides the
+// video form: this module reads the tab's fields, posts ONE document to
+// POST /oneshot (the same document a script would post), and paints the
+// take's progress from GET /oneshot/status. One prompt is a complete request;
+// every other field is a tweak, and the tab is honest about which is which.
+//
+// Publish block at the bottom: what the page and the other modules call.
+
+const OS = {
+ engine: 'ltx',
+ seconds: 60,
+ quality: { ltx: 'balanced', h3: 'standard', character: 'pro' },
+ character: '',
+ image: '',
+ beats: [], // one string per five seconds, as typed; trailing blanks trimmed on read
+ light: 'on',
+ retake: 'on',
+ handoff: 'last',
+ handoffTouched: false, // the user chose; a character pick no longer flips it
+ options: null,
+ optionsAt: 0,
+ statusTimer: null,
+ estimateSeq: 0,
+ wired: false,
+ lastSubmitted: null,
+};
+
+const OS_SECONDS = [30, 45, 60, 90, 120];
+
+// ---- helpers ----------------------------------------------------------------
+function osEl(id) { return document.getElementById(id); }
+function osEsc(s) {
+ // No quote characters inside the regex literals: the test extractor scans
+ // braces with a naive string tracker and a quote in a regex derails it.
+ return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+ .replace(/\x22/g, '&quot;').replace(/\x27/g, '&#39;');
+}
+function osLengthLabel(s) {
+ s = parseInt(s || 0, 10) || 0;
+ if (s < 60) return `${s} s`;
+ const whole = Math.floor(s / 60), rem = s - whole * 60;
+ if (!rem) return `${whole} min`;
+ if (rem === 30) return `${whole}½ min`;
+ return `${whole} min ${rem} s`;
+}
+// The parts a length splits into: whole parts, and a shorter last one when
+// the length is not a multiple (45 s on LTX is four 10 s parts and one of 5 s).
+function osPartsText(seconds, engine) {
+ const part = osPartSeconds(engine);
+ const whole = Math.floor(seconds / part), rem = seconds - whole * part;
+ if (!rem) return `${whole} part${whole === 1 ? '' : 's'} of ${part} s`;
+ return `${whole} × ${part} s + ${rem} s`;
+}
+function osPartsShort(seconds, engine) {
+ const part = osPartSeconds(engine);
+ const whole = Math.floor(seconds / part), rem = seconds - whole * part;
+ return rem ? `${whole} × ${part} s + ${rem} s` : `${whole} × ${part} s`;
+}
+function osPartSeconds(engine) {
+ const o = OS.options && OS.options.engines && OS.options.engines[engine || OS.engine];
+ return (o && o.part_seconds) || ((engine || OS.engine) === 'h3' ? 15 : 10);
+}
+function osClock(sec) {
+ const m = Math.floor(sec / 60), s = sec % 60;
+ return `${m}:${String(s).padStart(2, '0')}`;
+}
+function osActiveQuality() {
+ if (OS.engine === 'h3') return OS.quality.h3;
+ return OS.character ? OS.quality.character : OS.quality.ltx;
+}
+function osH3Available() {
+ const o = OS.options && OS.options.engines && OS.options.engines.h3;
+ return !!(o && o.available);
+}
+
+// ---- the document -----------------------------------------------------------
+// What the tab posts. A script can post the same thing to /oneshot.
+function osBeatsList() {
+ const lines = (OS.beats || []).map(x => String(x || '').trim());
+ while (lines.length && !lines[lines.length - 1]) lines.pop();
+ return lines;
+}
+function osSetBeats(lines) {
+ OS.beats = (lines || []).map(x => String(x || '').replace(/\s+Continuity:.*$/, ''));
+ osRenderBeats();
+ osBeatsInput();
+}
+function osDocument() {
+ const beats = osBeatsList();
+ const doc = {
+ prompt: String((osEl('osPrompt') || {}).value || '').trim(),
+ seconds: OS.seconds,
+ engine: OS.engine,
+ quality: osActiveQuality(),
+ camera: String((osEl('osCamera') || {}).value || '').trim(),
+ light_lock: OS.light,
+ retake: OS.retake,
+ handoff: OS.handoff,
+ };
+ if (beats.some(Boolean)) doc.beats = beats;
+ if (OS.image) doc.image = OS.image;
+ if (OS.engine === 'ltx' && OS.character) doc.character_id = OS.character;
+ const seed = String((osEl('osSeed') || {}).value || '').trim();
+ if (seed) doc.seed = seed;
+ const label = String((osEl('osLabel') || {}).value || '').trim();
+ if (label) doc.label = label;
+ if (osEl('osNoMusic') && osEl('osNoMusic').checked) doc.no_music = 'on';
+ return doc;
+}
+
+// ---- rendering --------------------------------------------------------------
+function osRenderEngine() {
+ const h3ok = osH3Available();
+ document.querySelectorAll('#osEngineGroup .pill-btn').forEach(b => {
+ const e = b.dataset.osEngine;
+ b.classList.toggle('active', e === OS.engine);
+ b.classList.toggle('disabled', e === 'h3' && !h3ok);
+ if (e === 'h3') b.title = h3ok ? '' : 'Hailuo H3 is not installed on this Mac';
+ });
+ const meta = osEl('osEngineMeta');
+ if (meta) {
+ meta.textContent = OS.engine === 'h3'
+ ? 'Hailuo H3 — 15-second parts that continue from each other · motion, landscapes, crowds'
+ : 'LTX 2.5 — 10-second parts that continue from the last frame · faces, voices, dialogue';
+ }
+ const cb = osEl('osCharacterBlock');
+ if (cb) cb.hidden = OS.engine === 'h3';
+ const ho = document.querySelector('[data-os-toggle="handoff"]');
+ if (ho && ho.parentElement) ho.parentElement.hidden = OS.engine === 'h3';
+}
+function osRenderLengths() {
+ const g = osEl('osLengthGroup');
+ if (!g) return;
+ const part = osPartSeconds();
+ g.innerHTML = OS_SECONDS.map(s => {
+ return `<button type="button" class="q-chip pill-btn pill-quality${s === OS.seconds ? ' active' : ''}" data-os-seconds="${s}" title="${osLengthLabel(s)}, one continuous shot: ${s / 5} beats of 5 s" aria-label="${osLengthLabel(s)}">
+ <span class="ql-name">${osLengthLabel(s)}</span><span class="q-spec ql-spec sub">${s / 5} beats</span><span class="ql-tier">${osPartsShort(s)}</span></button>`;
+ }).join('');
+ g.querySelectorAll('[data-os-seconds]').forEach(b => b.onclick = () => osSetSeconds(parseInt(b.dataset.osSeconds, 10)));
+ const meta = osEl('osLengthMeta');
+ if (meta) meta.textContent = `${OS.seconds / 5} beats of five seconds · ${osPartsText(OS.seconds)}`;
+}
+function osQualityRows() {
+ const o = OS.options || {};
+ const eng = (o.engines || {})[OS.engine] || {};
+ if (OS.engine === 'ltx' && OS.character) {
+ return (o.character_qualities || []).map(q => ({ key: q.key, label: q.label, sub: q.sub || '' }));
+ }
+ return (eng.qualities || []).map(q => ({
+ key: q.key, label: q.label,
+ sub: OS.engine === 'h3' ? (q.size || '') : (q.eta_min ? `~${Math.round(q.eta_min)} min a part` : ''),
+ }));
+}
+function osRenderQualities() {
+ const g = osEl('osQualityGroup');
+ if (!g) return;
+ const rows = osQualityRows();
+ const cur = osActiveQuality();
+ if (!rows.length) { g.innerHTML = ''; g.hidden = true; return; }
+ g.hidden = false;
+ g.style.gridTemplateColumns = `repeat(${Math.min(rows.length, 5)}, minmax(0, 1fr))`;
+ g.innerHTML = rows.map(q => `<button type="button" class="q-chip pill-btn pill-quality${q.key === cur ? ' active' : ''}" data-os-quality="${osEsc(q.key)}">
+ <span class="ql-name">${osEsc(q.label)}</span><span class="q-spec ql-spec sub">${osEsc(q.sub)}</span></button>`).join('');
+ g.querySelectorAll('[data-os-quality]').forEach(b => b.onclick = () => osSetQuality(b.dataset.osQuality));
+ const meta = osEl('osQualityMeta');
+ if (meta) {
+ meta.textContent = OS.engine === 'h3'
+ ? 'the size of every part · exports fit 720p'
+ : (OS.character ? 'a trained face keeps its identity on Pro · Draft is a quick look'
+ : 'every part renders at this quality · Balanced exports at 720p');
+ }
+}
+function osRenderCharacters() {
+ const g = osEl('osCharacterGroup');
+ if (!g) return;
+ const chars = ((OS.options || {}).characters || []);
+ const pills = [{ id: '', name: 'Nobody in particular', sub: 'the prompt describes them' }]
+ .concat(chars.map(c => ({ id: c.id, name: c.name || c.id, sub: c.has_voice ? 'face + voice' : 'face' })));
+ g.innerHTML = pills.map(c => `<button type="button" class="pill-btn${c.id === OS.character ? ' active' : ''}" data-os-character="${osEsc(c.id)}">
+ <span>${osEsc(c.name)}</span><span class="sub">${osEsc(c.sub)}</span></button>`).join('');
+ g.querySelectorAll('[data-os-character]').forEach(b => b.onclick = () => osSetCharacter(b.dataset.osCharacter));
+ const meta = osEl('osCharacterMeta');
+ if (meta) meta.textContent = chars.length
+ ? 'optional · a trained character, with its own face and voice'
+ : 'optional · train a character (Train Character tab) and it appears here';
+ const note = osEl('osCharacterNote');
+ if (note) {
+ note.hidden = !OS.character;
+ note.textContent = OS.character
+ ? 'Quality is now the character\'s own set, and "Hand off where the line ends" is on so the next part starts while the mouth still moves — both can be changed below.'
+ : '';
+ }
+}
+function osRenderToggles() {
+ document.querySelectorAll('[data-os-toggle]').forEach(group => {
+ const name = group.dataset.osToggle;
+ const cur = name === 'light' ? OS.light : name === 'retake' ? OS.retake : OS.handoff;
+ group.querySelectorAll('[data-os-value]').forEach(b => b.classList.toggle('active', b.dataset.osValue === cur));
+ });
+}
+function osRenderAnchor() {
+ const thumb = osEl('osAnchorThumb'), clear = osEl('osAnchorClear'), name = osEl('osAnchorName'), pick = osEl('osAnchorPick');
+ const on = !!OS.image;
+ if (thumb) { thumb.hidden = !on; if (on) thumb.src = `/file?path=${encodeURIComponent(OS.image)}`; else thumb.removeAttribute('src'); }
+ if (clear) clear.hidden = !on;
+ if (name) name.textContent = on ? OS.image.split('/').pop() : '';
+ if (pick) pick.textContent = on ? 'Change the image' : 'Choose an image';
+}
+// One row per five seconds, the stamp beside its own field. A row past the
+// length is shown, marked, and dropped on submit — the user sees exactly
+// what will and will not render.
+function osRenderBeats() {
+ const box = osEl('osBeats');
+ if (!box) return;
+ const n = OS.seconds / 5;
+ const beats = OS.beats || [];
+ const rows = Math.max(n, beats.length);
+ const focused = document.activeElement && document.activeElement.dataset ? document.activeElement.dataset.osBeat : null;
+ box.innerHTML = Array.from({ length: rows }, (_, i) => {
+ const over = i >= n;
+ const stamp = over ? '·' : osClock(i * 5);
+ const ph = i === 0 ? 'what happens in the first five seconds' : (over ? 'past the end — will be dropped' : '');
+ return `<div class="os-beat-row${over ? ' over' : ''}"><span class="os-stamp">${stamp}</span>`
+ + `<input type="text" class="sb-input os-beat" data-os-beat="${i}" value="${osEsc(beats[i] || '')}" placeholder="${osEsc(ph)}" `
+ + `autocomplete="off" spellcheck="false" aria-label="beat at ${osClock(i * 5)}"></div>`;
+ }).join('');
+ box.querySelectorAll('[data-os-beat]').forEach(inp => {
+ const idx = parseInt(inp.dataset.osBeat, 10);
+ inp.addEventListener('input', () => { OS.beats[idx] = inp.value; osBeatsInput(); });
+ inp.addEventListener('keydown', e => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ const next = box.querySelector(`[data-os-beat="${idx + 1}"]`);
+ if (next) next.focus();
+ } else if (e.key === 'Backspace' && !inp.value && idx > 0) {
+ e.preventDefault();
+ const prev = box.querySelector(`[data-os-beat="${idx - 1}"]`);
+ if (prev) prev.focus();
+ }
+ });
+ // A pasted list fills this row and the rows after it, one line each.
+ inp.addEventListener('paste', e => {
+ const text = (e.clipboardData || window.clipboardData || {}).getData ? (e.clipboardData || window.clipboardData).getData('text') : '';
+ if (!text || text.indexOf('\n') === -1) return;
+ e.preventDefault();
+ const lines = text.split('\n').map(x => x.trim());
+ lines.forEach((l, k) => { OS.beats[idx + k] = l; });
+ osRenderBeats(); osBeatsInput();
+ const back = box.querySelector(`[data-os-beat="${idx}"]`); if (back) back.focus();
+ });
+ });
+ if (focused !== null) { const again = box.querySelector(`[data-os-beat="${focused}"]`); if (again) again.focus(); }
+}
+function osBeatsInput() {
+ const hint = osEl('osBeatsHint');
+ if (!hint) return;
+ const n = OS.seconds / 5;
+ const lines = osBeatsList();
+ const filled = lines.filter(Boolean).length;
+ const extra = lines.length - n;
+ hint.textContent = filled === 0
+ ? `one line per five seconds · none written — the prompt carries the whole shot`
+ : `${n} lines of 5 s · ${filled} written`
+ + (filled < n ? ' · a blank row holds that moment' : '')
+ + (extra > 0 ? ` · ${extra} row${extra === 1 ? '' : 's'} past the end will be dropped` : '');
+}
+function osRenderSummary() {
+ const el = osEl('osSummary');
+ if (!el) return;
+ const who = (OS.engine === 'ltx' && OS.character)
+ ? (((OS.options || {}).characters || []).find(c => c.id === OS.character) || {}).name || OS.character
+ : '';
+ el.innerHTML = `<strong>${osLengthLabel(OS.seconds)}</strong> · ${osPartsText(OS.seconds)}`
+ + ` · ${OS.engine === 'h3' ? 'Hailuo H3' : 'LTX 2.5'}${who ? ` · ${osEsc(who)}` : ''}`;
+}
+function osRenderAll() {
+ osRenderEngine(); osRenderLengths(); osRenderQualities(); osRenderCharacters();
+ osRenderToggles(); osRenderAnchor(); osRenderBeats(); osBeatsInput(); osRenderSummary();
+ osEstimate();
+}
+
+// ---- state changes ----------------------------------------------------------
+function osSetEngine(e) {
+ e = e === 'h3' ? 'h3' : 'ltx';
+ if (e === 'h3' && !osH3Available()) return;
+ OS.engine = e;
+ if (e === 'h3' && OS.character) {
+ // H3 renders no trained character: the pick is cleared, not carried
+ // silently into a job that cannot use it.
+ OS.character = '';
+ if (!OS.handoffTouched) OS.handoff = 'last';
+ }
+ osRenderAll();
+}
+function osSetSeconds(s) {
+ s = parseInt(s, 10);
+ if (!OS_SECONDS.includes(s)) return;
+ OS.seconds = s;
+ osRenderLengths(); osRenderBeats(); osBeatsInput(); osRenderSummary(); osEstimate();
+}
+function osSetQuality(q) {
+ if (OS.engine === 'h3') OS.quality.h3 = q;
+ else if (OS.character) OS.quality.character = q;
+ else OS.quality.ltx = q;
+ osRenderQualities(); osEstimate();
+}
+function osSetCharacter(id) {
+ OS.character = String(id || '');
+ // A character speaks: unless the user already chose, hand off where the
+ // line ends (the measured cure for the voice-over on the next part).
+ if (!OS.handoffTouched) OS.handoff = OS.character ? 'speech' : 'last';
+ osRenderCharacters(); osRenderQualities(); osRenderToggles(); osRenderSummary(); osEstimate();
+}
+function osToggle(name, value) {
+ if (name === 'light') OS.light = value === 'off' ? 'off' : 'on';
+ else if (name === 'retake') OS.retake = value === 'off' ? 'off' : 'on';
+ else if (name === 'handoff') { OS.handoff = value === 'speech' ? 'speech' : 'last'; OS.handoffTouched = true; }
+ osRenderToggles();
+}
+function osSplitPrompt() {
+ const prompt = String((osEl('osPrompt') || {}).value || '');
+ const sents = prompt.split(/(?<=[.!?])\s+/).map(x => x.trim()).filter(Boolean);
+ const n = OS.seconds / 5;
+ const out = [];
+ for (let i = 0; i < n; i++) out.push(sents[i] || '');
+ while (out.length && !out[out.length - 1]) out.pop();
+ osSetBeats(out);
+}
+async function osPlanBeats() {
+ const btn = osEl('osPlanBtn'), hint = osEl('osBeatsHint');
+ const prompt = String((osEl('osPrompt') || {}).value || '').trim();
+ if (!prompt) { if (hint) hint.textContent = 'write the shot first — the planner writes the beats from it'; return; }
+ if (btn) { btn.disabled = true; btn.textContent = 'Writing the beats…'; }
+ if (hint) hint.textContent = 'the planner is writing one beat per five seconds — about half a minute';
+ try {
+ const r = await fetch('/oneshot/plan', { method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ prompt, seconds: OS.seconds, engine: OS.engine }) });
+ const d = await r.json();
+ if (!d.ok) throw new Error(d.error || 'the planner did not answer');
+ osSetBeats(d.beats || []);
+ } catch (e) {
+ if (hint) hint.textContent = `could not write the beats: ${e.message || e}`;
+ } finally {
+ if (btn) { btn.disabled = false; btn.textContent = 'Write the beats for me'; }
+ }
+}
+async function osEstimate() {
+ const el = osEl('osEstimate');
+ if (!el) return;
+ const seq = ++OS.estimateSeq;
+ el.textContent = `${osLengthLabel(OS.seconds)} · ${osPartsText(OS.seconds)} · pricing…`;
+ try {
+ const q = osActiveQuality();
+ const r = await fetch(`/oneshot/estimate?engine=${encodeURIComponent(OS.engine)}&quality=${encodeURIComponent(q)}&seconds=${OS.seconds}`);
+ const d = await r.json();
+ if (seq !== OS.estimateSeq) return;
+ if (!d.ok) { el.textContent = d.error || ''; return; }
+ el.textContent = `${osLengthLabel(d.seconds)} · ${osPartsText(d.seconds)}`
+ + (d.eta ? ` · about ${String(d.eta).replace(/^~\s*/, '').split(' · ')[0]} on this Mac` : '')
+ + (OS.retake === 'on' ? ' · a part that drifts is rendered once more' : '');
+ } catch (e) {
+ if (seq === OS.estimateSeq) el.textContent = '';
+ }
+}
+async function osUpload(file) {
+ if (!file) return;
+ const name = osEl('osAnchorName');
+ if (name) name.textContent = `Uploading ${file.name}…`;
+ try {
+ const fd = new FormData(); fd.append('image', file);
+ const r = await fetch('/upload', { method: 'POST', body: fd });
+ const d = await r.json();
+ if (!d.ok) throw new Error(d.error || 'upload failed');
+ OS.image = d.path;
+ } catch (e) {
+ alert(`Upload failed: ${e.message || e}`);
+ }
+ osRenderAnchor();
+}
+function osClearAnchor() { OS.image = ''; osRenderAnchor(); }
+
+// ---- generate + status ------------------------------------------------------
+async function osGenerate() {
+ const btn = osEl('osGenBtn'), est = osEl('osEstimate');
+ const doc = osDocument();
+ if (!doc.prompt) {
+ if (est) est.textContent = 'write the shot first — one paragraph is a complete request';
+ const p = osEl('osPrompt'); if (p) p.focus();
+ return;
+ }
+ if (btn) { btn.disabled = true; btn.textContent = 'Queueing…'; }
+ try {
+ const r = await fetch('/oneshot', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(doc) });
+ const d = await r.json();
+ if (!d.ok) throw new Error(d.error || `HTTP ${r.status}`);
+ OS.lastSubmitted = d.id;
+ if (est) {
+ const plan = d.plan || {};
+ est.textContent = `queued · ${osLengthLabel(plan.seconds || OS.seconds)} in ${plan.parts || '?'} parts`
+ + (plan.eta ? ` · about ${String(plan.eta).replace(/^~\s*/, '').split(' · ')[0]}` : '');
+ }
+ osStatusTick();
+ if (typeof poll === 'function') { try { poll(); } catch (e) {} }
+ } catch (e) {
+ if (est) est.textContent = `not queued: ${e.message || e}`;
+ } finally {
+ if (btn) { btn.disabled = false; btn.textContent = 'Generate'; }
+ }
+}
+function osVerdict(v) {
+ if (v === null || v === undefined) return { cls: 'quiet', text: 'silent' };
+ const n = Number(v);
+ if (n >= 0.25) return { cls: 'ok', text: `voice on the mouth (${n >= 0 ? '+' : ''}${n.toFixed(2)})` };
+ if (n >= 0.2) return { cls: 'mid', text: `borderline (${n >= 0 ? '+' : ''}${n.toFixed(2)})` };
+ return { cls: 'bad', text: `voice-over (${n >= 0 ? '+' : ''}${n.toFixed(2)})` };
+}
+function osPaintStatus(d) {
+ const card = osEl('osStatus'), title = osEl('osStatusTitle'), meta = osEl('osStatusMeta'), parts = osEl('osParts'), log = osEl('osLog');
+ if (!card) return;
+ const cur = d.current;
+ const recent = (d.recent || [])[0];
+ const show = cur || (d.queued || []).length || recent;
+ card.hidden = !show;
+ if (!show) return;
+ const queued = d.queued || [];
+ const paused = !!d.paused;
+ // The job this tab queued comes first; otherwise whatever is running.
+ const mineIdx = OS.lastSubmitted ? queued.findIndex(q => q.id === OS.lastSubmitted) : -1;
+ const mine = mineIdx >= 0 ? queued[mineIdx] : null;
+ const t = (cur && cur.id === OS.lastSubmitted) ? cur : (mine || cur || (queued.length ? queued[0] : recent));
+ const name = (j) => (j && j.label) ? ` · ${j.label}` : '';
+ if (cur && t === cur) {
+ if (title) title.textContent = `Rendering${name(cur)}`;
+ if (meta) meta.textContent = `part ${cur.part || 1} of ${cur.parts} · ${osLengthLabel(cur.seconds)} on ${cur.engine === 'h3' ? 'Hailuo H3' : 'LTX 2.5'}`
+ + (queued.length ? ` · ${queued.length} more waiting` : '');
+ } else if (t && queued.indexOf(t) >= 0) {
+ const place = queued.indexOf(t);
+ if (title) title.textContent = `${paused ? 'Queued, paused' : 'Waiting'}${name(t)}`;
+ if (meta) meta.textContent = `${osLengthLabel(t.seconds)} in ${t.parts} parts`
+ + (place === 0 ? (cur ? ' · next after the one rendering' : (paused ? ' · starts when you resume the queue' : ' · starts now')) : ` · ${place} ahead of it`)
+ + (paused && place > 0 ? ' · the queue is paused' : '');
+ } else {
+ const st = recent.status === 'done' ? 'Done' : recent.status === 'cancelled' ? 'Stopped' : 'Failed';
+ if (title) title.textContent = `${st}${recent.label ? ` · ${recent.label}` : ''}`;
+ if (meta) meta.textContent = recent.status === 'done'
+ ? `${osLengthLabel(recent.seconds)} · in the gallery on the right${recent.elapsed_sec ? ` · ${Math.round(recent.elapsed_sec / 60)} min` : ''}`
+ : (recent.error || '');
+ }
+ if (parts) {
+ const n = t.parts || 0, done = (t.lipsync || []).length;
+ parts.innerHTML = Array.from({ length: n }, (_, i) => {
+ const k = i + 1;
+ let cls = 'todo', text = `part ${k}`;
+ if (i < done) {
+ const v = osVerdict((t.lipsync || [])[i]);
+ cls = v.cls; text = `part ${k} · ${v.text}`;
+ const drift = (t.drift || [])[i];
+ if (typeof drift === 'number' && drift > 0.28) text += ' · light drifted';
+ } else if (cur && k === (cur.part || 1)) { cls = 'now'; text = `part ${k} · rendering`; }
+ return `<span class="os-part ${cls}">${osEsc(text)}</span>`;
+ }).join('');
+ }
+ if (log) log.textContent = (d.log || []).slice(-8).map(l => l.replace(/^\[\d\d:\d\d:\d\d\]\s*/, '').replace(/^\[take\]\s*/, '')).join('\n');
+}
+async function osStatusTick() {
+ try {
+ const r = await fetch('/oneshot/status');
+ const d = await r.json();
+ if (d && d.ok) osPaintStatus(d);
+ } catch (e) {}
+}
+function osStartStatus() {
+ osStopStatus();
+ osStatusTick();
+ OS.statusTimer = setInterval(osStatusTick, 3000);
+}
+function osStopStatus() {
+ if (OS.statusTimer) { clearInterval(OS.statusTimer); OS.statusTimer = null; }
+}
+
+// ---- options ----------------------------------------------------------------
+async function osLoadOptions(force) {
+ if (!force && OS.options && (Date.now() - OS.optionsAt) < 60000) return OS.options;
+ try {
+ const r = await fetch('/oneshot/options');
+ const d = await r.json();
+ if (d && d.ok) { OS.options = d; OS.optionsAt = Date.now(); }
+ } catch (e) {}
+ if (OS.engine === 'h3' && !osH3Available()) OS.engine = 'ltx';
+ return OS.options;
+}
+
+// ---- entering, leaving, loading ---------------------------------------------
+function oneshotTabEnter() {
+ osWire();
+ // A pane that scrolled sideways during an earlier layout must not open shifted.
+ const pane = document.querySelector('aside.form-pane');
+ if (pane) { pane.scrollLeft = 0; pane.scrollTop = 0; }
+ osRenderAll();
+ osLoadOptions(true).then(() => osRenderAll());
+ osStartStatus();
+}
+function oneshotTabLeave() {
+ osStopStatus();
+}
+// A finished one shot's Load Params lands here with the job's params: the
+// document is rebuilt from the take block, and the tab opens on it.
+function oneshotOpenFromParams(p) {
+ p = p || {};
+ const take = p.take || {};
+ OS.engine = (take.engine || p.engine) === 'h3' ? 'h3' : 'ltx';
+ const s = parseInt(take.seconds || p.take_seconds || 60, 10);
+ OS.seconds = OS_SECONDS.includes(s) ? s : 60;
+ OS.character = String(p.character_id || '');
+ OS.image = String(p.image || '');
+ OS.light = take.light_lock === '' ? 'off' : 'on';
+ OS.retake = take.retake === false ? 'off' : 'on';
+ OS.handoff = take.handoff === 'speech' ? 'speech' : 'last';
+ OS.handoffTouched = true;
+ if (OS.engine === 'h3') OS.quality.h3 = p.h3_quality || OS.quality.h3;
+ else if (OS.character) OS.quality.character = p.quality_choice || OS.quality.character;
+ else OS.quality.ltx = p.quality || OS.quality.ltx;
+ const prompt = osEl('osPrompt'); if (prompt) prompt.value = String(p.prompt || '');
+ const beats = (take.beats || take.beat_prompts || []);
+ OS.beats = Array.isArray(beats) ? beats.map(b => String(b || '').replace(/\s+Continuity:.*$/, '')) : [];
+ const cam = osEl('osCamera'); if (cam) cam.value = String(take.camera || '');
+ const seed = osEl('osSeed'); if (seed) seed.value = (p.seed && String(p.seed) !== '-1') ? String(p.seed) : '';
+ const label = osEl('osLabel'); if (label) label.value = String(p.preset_label || '');
+ const nm = osEl('osNoMusic'); if (nm) nm.checked = String(p.no_music || '') === 'on';
+ if (typeof workflowSwitch === 'function') workflowSwitch('oneshot');
+ else oneshotTabEnter();
+}
+
+// ---- wiring (once) ----------------------------------------------------------
+function osWire() {
+ if (OS.wired) return;
+ OS.wired = true;
+ document.querySelectorAll('#osEngineGroup [data-os-engine]').forEach(b => b.onclick = () => osSetEngine(b.dataset.osEngine));
+ document.querySelectorAll('[data-os-toggle]').forEach(group => {
+ group.querySelectorAll('[data-os-value]').forEach(b => b.onclick = () => osToggle(group.dataset.osToggle, b.dataset.osValue));
+ });
+ const split = osEl('osSplitBtn'); if (split) split.onclick = osSplitPrompt;
+ const plan = osEl('osPlanBtn'); if (plan) plan.onclick = osPlanBeats;
+ const pick = osEl('osAnchorPick'); const file = osEl('osAnchorFile');
+ if (pick && file) {
+ pick.onclick = () => file.click();
+ file.addEventListener('change', () => { if (file.files[0]) osUpload(file.files[0]); file.value = ''; });
+ }
+ const clear = osEl('osAnchorClear'); if (clear) clear.onclick = osClearAnchor;
+ const gen = osEl('osGenBtn'); if (gen) gen.onclick = osGenerate;
+ const prompt = osEl('osPrompt');
+ if (prompt) prompt.addEventListener('keydown', e => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); osGenerate(); } });
+}
+
+// ---- published to the page --------------------------------------------------
+Object.assign(globalThis, {
+ oneshotTabEnter, oneshotTabLeave, oneshotOpenFromParams, osWire,
+ osSetEngine, osSetSeconds, osSetQuality, osSetCharacter, osToggle,
+ osBeatsInput, osSplitPrompt, osPlanBeats, osGenerate, osDocument, osBeatsList, osSetBeats, osRenderBeats,
+ osLengthLabel, osPartSeconds, osPartsText, osPartsShort, osClock, osVerdict, osPaintStatus,
+});
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index 7111e56..1e23036 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -433,9 +433,7 @@ function setEngine(engine, opts) {
// shot IS the length there, so the LTX length the user had goes back
// exactly as it was (the hidden #ltx_length is H3's one field it never
// touches) instead of being snapped from H3's number.
- if (typeof currentMode !== 'undefined' && currentMode === 'oneshot') {
- try { restoreFoldedLtxLength(); } catch (e) {}
- } else if (typeof snapFramesTo8kPlus1 === 'function') {
+ if (typeof snapFramesTo8kPlus1 === 'function') {
try { snapFramesTo8kPlus1(); } catch (e) {}
}
// Give the active quality preset its upscale back (H3 forced it off).
@@ -465,18 +463,6 @@ function setEngine(engine, opts) {
// reads the engine this call actually settled on rather than the one that
// was requested — a gate may have bounced it back to the built-in.
try { _syncLoraPickerForEngine(); } catch (e) {}
- // A One Shot is priced and labelled per engine: 15 s parts on H3, 10 s
- // parts on LTX. The estimate and the chip labels both follow the switch.
- try { if (typeof oneshotRefreshLabels === 'function') oneshotRefreshLabels(); } catch (e) {}
- // And the mode's own state is re-asserted after the surface swap — the
- // active length chip, the folded strips, the beats row — because the swap
- // above re-rendered the strips it folds. takeRefresh rides inside it.
- if (typeof currentMode !== 'undefined' && currentMode === 'oneshot'
- && typeof setTakeSeconds === 'function') {
- try { setTakeSeconds((document.getElementById('take_seconds') || {}).value || 0); } catch (e) {}
- } else {
- try { if (typeof takeRefresh === 'function') takeRefresh(); } catch (e) {}
- }
return target;
}
@@ -906,16 +892,7 @@ function updateDerived() {
// expanded Customize body).
const derivedFooter = document.getElementById('derivedFooter');
if (derivedFooter) {
- // A One Shot is not a 5 s clip: take_seconds is non-zero only while that
- // mode is open, and then the strip says the shot — "1 min · 6 parts of
- // 10 s" — in front of the same canvas line. The per-part duration in
- // #frames is the engine's business, not the user's.
- const takeS = parseInt(document.getElementById('take_seconds')?.value || '0', 10) || 0;
- const shot = (takeS && typeof oneshotSummary === 'function')
- ? oneshotSummary(takeS, document.body.dataset.engine || 'ltx') : '';
- derivedFooter.innerHTML = shot
- ? `<strong>${shot}</strong> · ${finalRes}`
- : `<strong>${dur}s</strong> · ${finalRes}${temporalText}${accelText}`;
+ derivedFooter.innerHTML = `<strong>${dur}s</strong> · ${finalRes}${temporalText}${accelText}`;
}
// 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.
@@ -965,7 +942,7 @@ function updateDerived() {
const inImageFlow = inI2V || currentMode === 'keyframe';
// One Shot ships i2v when its anchor is set, but the anchor has its own
// surface inside the One Shot panel — Image mode's picker stays folded.
- document.getElementById('imageSection').classList.toggle('show', inI2V && currentMode !== 'keyframe' && currentMode !== 'oneshot');
+ document.getElementById('imageSection').classList.toggle('show', inI2V && currentMode !== 'keyframe');
// The reference-use row lives inside that section and follows the same
// mode question, plus the server's 2.5-only availability flag.
if (typeof _applyI2vRefModeVisibility === 'function') {
@@ -1013,7 +990,7 @@ function updateDerived() {
// In T2V/Extend/FFLF the model generates audio jointly; there's nothing
// to swap out, so the dropdown is just noise.
const i2vAudioSec = document.getElementById('i2vAudioModeSection');
- if (i2vAudioSec) i2vAudioSec.classList.toggle('show', inI2V && currentMode !== 'oneshot');
+ if (i2vAudioSec) i2vAudioSec.classList.toggle('show', inI2V);
// Width/height stays visible in image flows too. (Restored 2026-06-03: the
// 2026-05-17 simplification hid it for I2V/FFLF, which cost users the custom
// I2V sizing they relied on.) The image still drives the DEFAULT —
@@ -1181,12 +1158,6 @@ function pickerSetImage(key, path, opts = {}) {
els.recentStrip.querySelectorAll('img').forEach(img => img.classList.remove('selected'));
}
}
- // The One Shot panel mirrors this same field as its anchor image, and the
- // hidden #mode follows it (i2v with an anchor, t2v without) while that mode
- // is open. Before updateDerived so the visibility pass reads the new mode.
- if (key === 'image' && typeof oneshotSyncAnchor === 'function') {
- try { oneshotSyncAnchor(); } catch (e) {}
- }
updateDerived();
}
@@ -2762,6 +2733,20 @@ async function retryJob(jobId) {
// Fast/Medium previews → bake one at Quality" — adding a dialog would
// burn a click for no information. The Image Studio form is left
// pre-filled so the user can tweak + resubmit if they want.
+// Which engine the ✦ Quality chip re-runs through. HiDream Quality is the
+// recipe the chip was built for, but that engine has been hidden since the
+// lab-repo dependency (issue #15) and no install has it: in the week to
+// 2026-09-09 the fleet logged 81 "HiDream venv python not found" errors from
+// 12 installs — every one of them this chip. So: HiDream when this Mac
+// reports it installed AND cached, otherwise Reference Edit — Quality, the
+// shipped 40-step engine. Pure, so the test can run it in node.
+function remakeQualityEngine(statusMap) {
+ const st = (statusMap && typeof statusMap === 'object') ? statusMap : {};
+ const hd = st.hidream_quality_inline;
+ if (hd && hd.family_installed !== false && hd.cached === true) return 'hidream_quality_inline';
+ return 'qwen_edit_high_inline';
+}
+
async function remakeInQuality(payload) {
if (!payload || !payload.path) {
if (typeof phosToast === 'function') {
@@ -2794,7 +2779,9 @@ async function remakeInQuality(payload) {
const nEl = document.getElementById('imgStudioN');
if (nEl) nEl.value = '1'; // remake just the picked one
const engineEl = document.getElementById('imgStudioEngine');
- if (engineEl) engineEl.value = 'hidream_quality_inline';
+ const remakeEngine = remakeQualityEngine(
+ (typeof imgStudioEngineStatus === 'function') ? imgStudioEngineStatus() : {});
+ if (engineEl) engineEl.value = remakeEngine;
const aspectEl = document.getElementById('imgStudioAspect');
if (aspectEl && sidecar.aspect) aspectEl.value = sidecar.aspect;
@@ -2804,7 +2791,11 @@ async function remakeInQuality(payload) {
IMG_STUDIO.refs[i] = null;
if (typeof imgStudioRenderSlot === 'function') imgStudioRenderSlot(i);
}
- const refs = Array.isArray(sidecar.refs) ? sidecar.refs : [];
+ let refs = Array.isArray(sidecar.refs) ? sidecar.refs : [];
+ // Reference Edit is image-to-image: a photo made without references
+ // (Ideogram, a text-only Qwen) is remade FROM ITSELF, which is what
+ // "the same composition at Quality fidelity" means for it.
+ if (!refs.length && remakeEngine.startsWith('qwen_edit')) refs = [payload.path];
refs.slice(0, IMG_STUDIO.refs.length).forEach((path, i) => {
const fname = String(path).split('/').pop();
IMG_STUDIO.refs[i] = { path, name: fname };
@@ -2820,8 +2811,10 @@ async function remakeInQuality(payload) {
// Auto-submit. imgStudioGenerate reads the now-prefilled fields.
if (typeof imgStudioGenerate === 'function') {
if (typeof phosToast === 'function') {
- phosToast('Remaking in Quality (12-step) · watch Recent → Photos',
- { kind: 'success' });
+ phosToast((remakeEngine === 'hidream_quality_inline'
+ ? 'Remaking in HiDream Quality (12-step)'
+ : 'Remaking in Reference Edit — Quality (40-step)')
+ + ' · watch Recent → Photos', { kind: 'success' });
}
imgStudioGenerate();
}
@@ -3006,7 +2999,7 @@ function renderCarousel() {
const remakeArgs = JSON.stringify({path: o.path}).replace(/"/g, '&quot;');
const remakeChip = (isPhoto && o.has_sidecar)
? `<button class="card-action card-action-photo" type="button"
- title="Re-run this prompt + seed + refs through HiDream Quality (auto-submits)"
+ title="Re-run this prompt + seed + refs at Quality (auto-submits)"
onclick="event.stopPropagation(); remakeInQuality(${remakeArgs})">✦ Quality</button>`
: '';
return `
@@ -3021,7 +3014,7 @@ function renderCarousel() {
<div class="card-chrome">
${remakeChip}
${animateChip}
- <button class="card-action card-action-danger" type="button" title="Delete this file from disk"
+ <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>
</div>
@@ -3363,6 +3356,12 @@ function closeExpandLightbox() {
// Don't steal keystrokes from inputs/textareas.
const tag = (e.target && e.target.tagName) || '';
const inField = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable);
+ // F and the arrows are the GALLERY's only while the gallery is the thing
+ // on screen: in the Editor they are the playhead's (and F opened a hidden
+ // output over the timeline), and with ⌘ / ⌃ / ⌥ held they are somebody
+ // else's chord — ⌘F is Find.
+ if (e.key !== 'Escape' && (e.metaKey || e.ctrlKey || e.altKey
+ || document.body.dataset.workflow === 'editor')) return;
if (e.key === 'Escape' && isOpen) {
closeExpandLightbox();
e.preventDefault();
@@ -3595,8 +3594,12 @@ async function loadParams() {
// character_id above). Checked FIRST because a One Shot with an anchor is
// stored as mode=i2v and would otherwise land in Image mode with its
// length gone.
- const _isTake = !!(p.take && p.take.seconds);
- if (_isTake) setMode('oneshot');
+ // A One Shot reloads into its own tab, rebuilt from the take block; the
+ // video form is left as it was (oneshot.js owns the rest of the restore).
+ if (p.take && p.take.seconds && typeof oneshotOpenFromParams === 'function') {
+ oneshotOpenFromParams(p);
+ return;
+ }
else if (p.mode === 'extend') setMode('extend');
else if (p.mode === 'keyframe') setMode('keyframe');
else if (p.mode === 'i2v_clean_audio' || p.mode === 'i2v') { setMode('i2v'); document.getElementById('i2vMode').value = p.mode; document.getElementById('mode').value = p.mode; }
@@ -3629,24 +3632,6 @@ async function loadParams() {
try { setI2vRefMode(p.i2v_reference_mode || 'anchor'); } catch (e) {}
}
if (p.temporal_mode) setTemporalMode(p.temporal_mode);
- // A take restores as a take (length + beats), not as the fields it was
- // turned into — those are derived, and would re-derive differently.
- if (_isTake && typeof setTakeSeconds === 'function') {
- // The beats as WRITTEN (`beats`), not the beat_prompts the light lock
- // decorated — restoring those would re-append the continuity sentence.
- setTakeSeconds(p.take.seconds, p.take.beats || p.take.beat_prompts || null);
- // The two continuity toggles: light_lock is the sentence the server
- // appended ('' when it was off); retake is a boolean.
- if (typeof setTakeLightLock === 'function') {
- setTakeLightLock(('light_lock' in p.take && !p.take.light_lock) ? 'off' : 'on');
- }
- if (typeof setTakeRetake === 'function') {
- setTakeRetake(p.take.retake === false ? 'off' : 'on');
- }
- // The camera line, as written once for the whole shot (take.camera).
- const _camEl = document.getElementById('take_camera');
- if (_camEl) _camEl.value = p.take.camera || '';
- } else if (typeof setTakeSeconds === 'function') setTakeSeconds(0);
if (p.upscale) setUpscale(p.upscale);
if (p.upscale_method) setUpscaleMethod(p.upscale_method);
document.getElementById('prompt').value = p.prompt || '';
@@ -4708,5 +4693,5 @@ Object.assign(globalThis, {
// inline-handler targets: generated markup resolves these through the
// global scope (the v4.9.0 regression, PR #69)
_copyToClipboard, animateFromPhoto, deleteOutput, openOutputInfoModal,
- remakeInQuality, removeJob, repairModel,
+ remakeInQuality, remakeQualityEngine, removeJob, repairModel,
});
diff --git a/webapp/js/shortcuts.js b/webapp/js/shortcuts.js
new file mode 100644
index 0000000..2133346
--- /dev/null
+++ b/webapp/js/shortcuts.js
@@ -0,0 +1,470 @@
+// THE KEYBOARD, IN ONE TABLE.
+//
+// Every shortcut Phosphene answers to is a row here: the keys, where it
+// works, and what it does. Three consumers read it and nothing else:
+//
+// * the Docs page "Keyboard shortcuts" (webapp/js/docs.js renders it);
+// * the Editor's Keys popover (sbeKeysLegend in editor.js);
+// * the tooltips — any element with data-shortcut="<id>" gets its keys
+// appended to its title, and code that builds a title at runtime calls
+// shortcutHint(id).
+//
+// Rows with `run` are HANDLED here, by the one listener at the bottom, so the
+// row and the behaviour cannot disagree. Rows without `run` describe a
+// handler that lives next to the thing it acts on (the Editor, the Outputs
+// lightbox, the Storyboard grade keys, the Images canvas); `owner` names the
+// file, and test_docs_and_shortcuts.py drives the Editor's real handler with
+// every Editor row's keys and asserts it calls the function the row names.
+//
+// Conventions, so a person who cuts in Premiere / Final Cut / Resolve or
+// works in Photoshop / After Effects already knows them: Space plays,
+// ⌘Z / ⇧⌘Z undo and redo, ⌘S saves, S / ⌘K / ⌘B split at the playhead,
+// ⌫ lifts and ⇧⌫ ripple-deletes, ↑ ↓ jump between cuts, N toggles snapping,
+// ⇧Z fits the timeline, ⌘⏎ submits the prompt you are typing in, ⌘⌫ moves
+// to the Trash like Finder, Esc closes what is on top, ⇧1–⇧7 switch pages the
+// way Resolve's ⇧ + number does. Nothing here claims a combination the
+// browser or macOS reserves (SHORTCUT_RESERVED) — ⌘R is reload, never render.
+
+// Where a shortcut works. The order is the order the Docs page shows them.
+const SHORTCUT_SCOPES = [
+ { id: 'global', title: 'Anywhere',
+ note: 'Not while you are typing in a text box — except ⌘⏎ and Esc.' },
+ { id: 'prompt', title: 'While writing a prompt',
+ note: 'These work inside the text box.' },
+ { id: 'outputs', title: 'Outputs and the player',
+ note: 'On the Video, One Shot, Images and Audio tabs, with an output selected.' },
+ { id: 'editor', title: 'Editor — keys',
+ note: 'With a timeline open on the Editor tab. The Keys button above the tracks shows the same list.' },
+ { id: 'editor-mouse', title: 'Editor — mouse and modifiers',
+ note: 'Hold the modifier while you click or drag.' },
+ { id: 'storyboard', title: 'Storyboard', note: 'Click a shot card first to focus it.' },
+ { id: 'canvas', title: 'Images — Layout canvas',
+ note: 'Ideogram 4 in Layout mode, with a box selected.' },
+];
+
+const SHORTCUT_TABS = ['manual', 'oneshot', 'studio', 'storyboard', 'editor', 'audio', 'train'];
+
+const SHORTCUTS = [
+ // ---- anywhere -------------------------------------------------------------
+ // `?` is what a US keyboard reports; ⇧/ is the same physical chord as some
+ // layouts and synthesized events report it.
+ { id: 'docs.open', scope: 'global', combos: ['?'], hidden: ['shift+slash'], owner: 'shortcuts.js',
+ label: 'Open the Docs on this page',
+ run: () => { if (typeof openDocs !== 'function') return false; openDocs('shortcuts'); } },
+ { id: 'tabs.switch', scope: 'global', owner: 'shortcuts.js',
+ combos: ['shift+digit1', 'shift+digit2', 'shift+digit3', 'shift+digit4',
+ 'shift+digit5', 'shift+digit6', 'shift+digit7'],
+ display: [['⇧', '1'], ['⇧', '7']], displayJoin: '–',
+ label: 'Switch tab: 1 Video · 2 One Shot · 3 Images · 4 Storyboard · 5 Editor · 6 Audio · 7 Train Character',
+ run: (ev) => {
+ const n = Number(String(ev.code || '').replace('Digit', ''));
+ const tab = SHORTCUT_TABS[n - 1];
+ if (!tab || typeof workflowSwitch !== 'function') return false;
+ workflowSwitch(tab);
+ } },
+ { id: 'search.focus', scope: 'global', combos: ['mod+f'], owner: 'shortcuts.js',
+ label: 'Jump to the search box on screen — Outputs, the Editor’s media pool, the LoRA browser or the Docs. Where there is none, the browser’s own Find opens.',
+ run: () => shortcutFocusSearch() },
+ { id: 'escape.close', scope: 'global', combos: ['escape'], owner: 'health.js, engines.js',
+ label: 'Close what is on top — a dialog, a menu, the Docs, the expanded player' },
+
+ // ---- typing a prompt --------------------------------------------------------
+ { id: 'prompt.generate', scope: 'prompt', combos: ['mod+enter'], typing: true,
+ owner: 'shortcuts.js (Video, Images) · oneshot.js (One Shot)',
+ label: 'Generate — from the Video prompt, the Images prompt or the One Shot prompt. Same as pressing the Generate button, so it queues a render.',
+ run: (ev) => shortcutGenerateFrom(ev.target) },
+ { id: 'oneshot.beats', scope: 'prompt', combos: ['enter', 'backspace'], owner: 'oneshot.js',
+ label: 'In One Shot beats: ⏎ goes to the next beat · ⌫ in an empty beat goes back one' },
+
+ // ---- outputs and the player -------------------------------------------------
+ { id: 'player.toggle', scope: 'outputs', combos: ['space'], owner: 'shortcuts.js',
+ label: 'Play / pause the selected output',
+ run: (ev) => shortcutTogglePlayer(ev) },
+ { id: 'outputs.step', scope: 'outputs', combos: ['arrowleft', 'arrowright'], owner: 'queue.js',
+ label: 'Previous / next output — wraps at the ends, works in the expanded player too' },
+ { id: 'outputs.expand', scope: 'outputs', combos: ['f'], owner: 'queue.js',
+ label: 'Expand the selected output to full screen (Esc closes it)' },
+ { id: 'outputs.trash', scope: 'outputs', combos: ['mod+backspace'], owner: 'shortcuts.js',
+ label: 'Move the selected output to the Trash — asks first, like the trash button on the card',
+ run: () => shortcutTrashOutput() },
+
+ // ---- the Editor: keys ---------------------------------------------------------
+ // `calls` is the function the Editor's own keydown handler runs for these
+ // keys; the test drives the real handler and holds it to this.
+ { id: 'editor.play', scope: 'editor', combos: ['space'], owner: 'editor.js',
+ calls: 'sbeTogglePlay', label: 'Play / pause' },
+ { id: 'editor.frame', scope: 'editor', combos: ['arrowleft', 'arrowright'], owner: 'editor.js',
+ calls: 'sbeSeek', label: 'Move the playhead one frame' },
+ { id: 'editor.frame10', scope: 'editor', combos: ['shift+arrowleft', 'shift+arrowright'],
+ owner: 'editor.js', calls: 'sbeSeek', label: 'Move the playhead ten frames' },
+ { id: 'editor.cut', scope: 'editor', combos: ['arrowup', 'arrowdown'], owner: 'editor.js',
+ calls: 'sbeJumpCut', label: 'Jump to the previous / next cut' },
+ { id: 'editor.ends', scope: 'editor', combos: ['home', 'end'], owner: 'editor.js',
+ calls: 'sbeSeek', label: 'Go to the start / the end of the sequence (fn ← / fn → on a laptop)' },
+ { id: 'editor.nudge', scope: 'editor', combos: ['alt+arrowleft', 'alt+arrowright'],
+ hidden: ['alt+shift+arrowleft', 'alt+shift+arrowright'], owner: 'editor.js',
+ calls: 'sbeNudge', label: 'Nudge the selected clips one frame earlier / later · add ⇧ for ten' },
+ { id: 'editor.split', scope: 'editor', combos: ['s', 'mod+k', 'mod+b'], owner: 'editor.js',
+ calls: 'sbeSplitHere', label: 'Split the shot under the playhead (S, or ⌘K as in Premiere, ⌘B as in Final Cut and Resolve)' },
+ { id: 'editor.lift', scope: 'editor', combos: ['backspace'], hidden: ['delete'], owner: 'editor.js',
+ calls: 'sbeLiftSelected', label: 'Lift — take the selected clips out and leave the hole' },
+ { id: 'editor.ripple', scope: 'editor', combos: ['shift+backspace'], hidden: ['shift+delete'],
+ owner: 'editor.js', calls: 'sbeRippleSelected',
+ label: 'Ripple delete — take them out and close the gap' },
+ { id: 'editor.removeOverlay', scope: 'editor', combos: ['backspace'], hidden: ['delete'],
+ owner: 'editor.js', calls: 'sbeOvDeleteSel', label: 'With a title or card selected: remove it' },
+ { id: 'editor.removeTransition', scope: 'editor', combos: ['backspace'], hidden: ['delete'],
+ owner: 'editor.js', calls: 'sbeTxRemoveSel', label: 'With a cut selected: remove its transition' },
+ { id: 'editor.duplicate', scope: 'editor', combos: ['d'], owner: 'editor.js',
+ calls: 'sbeDuplicateSel', label: 'Duplicate the selected clips' },
+ { id: 'editor.link', scope: 'editor', combos: ['shift+l'], owner: 'editor.js',
+ calls: 'sbeToggleAudioLink', label: 'Unlink / link the sound' },
+ { id: 'editor.resync', scope: 'editor', combos: ['shift+r'], owner: 'editor.js',
+ calls: 'sbeResyncSel', label: 'Resync — slide the sound back under its own picture' },
+ { id: 'editor.selectAll', scope: 'editor', combos: ['mod+a'], owner: 'editor.js',
+ calls: 'sbeSelectAll', label: 'Select every clip' },
+ // Escape never closes the timeline: no editor closes a project on Escape,
+ // and the Escape that closed the Docs used to shut the film behind them.
+ // Closing is the ⋯ menu's Close.
+ { id: 'editor.deselect', scope: 'editor', combos: ['escape'], owner: 'editor.js',
+ calls: 'sbeSelectNone', label: 'Close an open menu, then clear the selection (never closes the timeline)' },
+ { id: 'editor.zoom', scope: 'editor', combos: ['plus', 'minus'], hidden: ['equals', 'underscore'],
+ owner: 'editor.js', calls: 'sbeZoom', label: 'Zoom the timeline in / out' },
+ { id: 'editor.fit', scope: 'editor', combos: ['shift+z'], hidden: ['backslash'], owner: 'editor.js',
+ calls: 'sbeZoomFit', label: 'Fit the whole sequence in the window' },
+ { id: 'editor.snap', scope: 'editor', combos: ['n'], owner: 'editor.js',
+ calls: 'sbeToggleSnap', label: 'Snap to beat on / off' },
+ { id: 'editor.mute', scope: 'editor', combos: ['m'], owner: 'editor.js',
+ calls: ['sbeSetMute', 'sbeUnmuteFromRefusal'],
+ label: 'Mute / unmute the preview — the film itself is not changed' },
+ { 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',
+ calls: 'sbeRedo', label: 'Redo' },
+ { id: 'editor.save', scope: 'editor', combos: ['mod+s'], owner: 'editor.js',
+ calls: 'sbeSaveNow', label: 'Save the draft' },
+ { id: 'editor.render', scope: 'editor', combos: ['mod+e'], owner: 'editor.js',
+ calls: 'sbeRenderFilm', label: 'Render the timeline into one file (⌘E, as Export in Final Cut)' },
+
+ // ---- the Editor: mouse -----------------------------------------------------------
+ { id: 'editor.click', scope: 'editor-mouse', display: [['Click']], owner: 'editor.js',
+ label: 'Select a clip · click an empty part of the track to select nothing' },
+ { id: 'editor.shiftClick', scope: 'editor-mouse', display: [['⇧', 'Click']], owner: 'editor.js',
+ label: 'Select the range from the selected clip to this one' },
+ { id: 'editor.cmdClick', scope: 'editor-mouse', display: [['⌘', 'Click']], owner: 'editor.js',
+ label: 'Add one clip to the selection, or drop it' },
+ { id: 'editor.drag', scope: 'editor-mouse', display: [['Drag']], owner: 'editor.js',
+ label: 'Move a clip — or the whole selection, sound included · drag a clip’s edge to trim · the music strip drags and trims the same way' },
+ { id: 'editor.cmdDrag', scope: 'editor-mouse', display: [['⌘', 'Drag']], owner: 'editor.js',
+ label: 'Ripple — everything after the clip slides too' },
+ { id: 'editor.altDrag', scope: 'editor-mouse', display: [['⌥', 'Drag']], owner: 'editor.js',
+ label: 'Ignore the beat grid while dragging' },
+ { id: 'editor.altShiftDrag', scope: 'editor-mouse', display: [['⌥', '⇧', 'Drag']], owner: 'editor.js',
+ label: 'Reorder instead of move' },
+ { id: 'editor.rightClick', scope: 'editor-mouse', display: [['Right-click']], owner: 'editor.js',
+ label: 'The clip bar’s buttons at the pointer, plus Move earlier / Move later · on a hole: Close this hole or Generate a shot here' },
+ { id: 'editor.levels', scope: 'editor-mouse', display: [['Click'], ['⇧', 'Click']], displayJoin: ' / ',
+ owner: 'editor.js',
+ label: 'Level points, on an unlinked sound: click the yellow line to add one · drag it to set the level · ⇧-click it, or right-click it to remove it' },
+ { id: 'editor.wheel', scope: 'editor-mouse', display: [['⌥', 'Scroll'], ['⇧', 'Scroll']], displayJoin: ' / ',
+ owner: 'editor.js',
+ label: 'Over the track: ⌥ + scroll (or a trackpad pinch) zooms · ⇧ + scroll pans' },
+ { id: 'editor.tlEdge', scope: 'editor-mouse', display: [['Drag'], ['Double-click']], displayJoin: ' / ',
+ owner: 'editor.js',
+ label: 'The timeline’s top edge: drag up for taller tracks · double-click to reset · ↑ ↓ when it is focused' },
+
+ // ---- storyboard ------------------------------------------------------------------
+ { id: 'storyboard.grade', scope: 'storyboard', combos: ['k', 'r', 'c'], owner: 'storyboard.js',
+ label: 'Grade the focused shot: K Keep · R Re-roll · C Cut — the same key again clears it' },
+ { id: 'storyboard.collapse', scope: 'storyboard', combos: ['escape'], owner: 'storyboard.js',
+ label: 'Collapse the docked player back to the shot list' },
+
+ // ---- images: the layout canvas -------------------------------------------------
+ { id: 'canvas.nudge', scope: 'canvas', combos: ['arrowleft', 'arrowright', 'arrowup', 'arrowdown'],
+ owner: 'stage.js', label: 'Nudge the selected box · add ⇧ for a bigger step' },
+ { id: 'canvas.delete', scope: 'canvas', combos: ['backspace'], hidden: ['delete'], owner: 'stage.js',
+ label: 'Delete the selected box' },
+ { id: 'canvas.deselect', scope: 'canvas', combos: ['escape'], owner: 'stage.js',
+ label: 'Deselect the box · while editing its words, stop editing' },
+ { id: 'canvas.undo', scope: 'canvas', combos: ['mod+z'], owner: 'stage.js', label: 'Undo' },
+];
+
+// Combinations the browser or macOS keeps for itself. A page that claims one
+// either cannot (the OS wins) or breaks something people rely on — ⌘R was the
+// Editor's Render key and turned a reload into a queued render.
+const SHORTCUT_RESERVED = [
+ 'mod+w', 'mod+q', 'mod+t', 'mod+n', 'mod+r', 'mod+l', 'mod+h', 'mod+m',
+ 'mod+tab', 'mod+backquote', 'mod+space', 'shift+mod+t', 'shift+mod+n',
+ 'shift+mod+r', 'mod+comma', 'mod+p',
+];
+
+// ---- combos ----------------------------------------------------------------
+const _SC_KEYNAMES = {
+ space: ' ', enter: 'enter', escape: 'escape', backspace: 'backspace', delete: 'delete',
+ arrowleft: 'arrowleft', arrowright: 'arrowright', arrowup: 'arrowup', arrowdown: 'arrowdown',
+ home: 'home', end: 'end', plus: '+', minus: '-', equals: '=', underscore: '_',
+ backslash: '\\', backquote: '`', comma: ',', tab: 'tab', slash: '/',
+};
+// Keys whose character already needs Shift on a US layout: their combos do not
+// say shift, and matching ignores it.
+const _SC_SHIFTED = new Set(['?', '+', '_']);
+
+function shortcutParse(combo) {
+ const parts = String(combo).toLowerCase().split('+');
+ const out = { mod: false, shift: false, alt: false, ctrl: false, key: '', code: '' };
+ for (const p of parts) {
+ if (p === 'mod') out.mod = true;
+ else if (p === 'shift') out.shift = true;
+ else if (p === 'alt') out.alt = true;
+ else if (p === 'ctrl') out.ctrl = true;
+ else if (/^digit\d$/.test(p)) out.code = 'Digit' + p.slice(5);
+ else out.key = (p in _SC_KEYNAMES) ? _SC_KEYNAMES[p] : p;
+ }
+ return out;
+}
+
+// One normal form, so `shift+mod+z` and `mod+shift+z` are the same entry in
+// the reserved check and in the tests.
+function shortcutNormalise(combo) {
+ const c = shortcutParse(combo);
+ const bits = [];
+ if (c.ctrl) bits.push('ctrl');
+ if (c.alt) bits.push('alt');
+ if (c.shift) bits.push('shift');
+ if (c.mod) bits.push('mod');
+ const inv = Object.fromEntries(Object.entries(_SC_KEYNAMES).map(([k, v]) => [v, k]));
+ bits.push(c.code ? c.code.toLowerCase() : (inv[c.key] || c.key));
+ return bits.join('+');
+}
+
+function shortcutMatches(ev, combo) {
+ const c = shortcutParse(combo);
+ if (!ev) return false;
+ const mod = !!(ev.metaKey || ev.ctrlKey);
+ if (c.mod !== mod) return false;
+ if (c.alt !== !!ev.altKey) return false;
+ if (c.code) {
+ if (ev.code !== c.code) return false;
+ } else {
+ if (String(ev.key || '').toLowerCase() !== c.key) return false;
+ }
+ if (!_SC_SHIFTED.has(c.key) && c.shift !== !!ev.shiftKey) return false;
+ return true;
+}
+
+// ---- glyphs ----------------------------------------------------------------
+const _SC_GLYPH = {
+ ' ': 'Space', enter: '⏎', escape: '⎋ Esc', backspace: '⌫', delete: '⌦',
+ arrowleft: '←', arrowright: '→', arrowup: '↑', arrowdown: '↓',
+ home: 'Home', end: 'End', '+': '+', '-': '−', '\\': '\\',
+};
+
+// Apple's order: ⌃ ⌥ ⇧ ⌘, then the key.
+function shortcutTokens(combo) {
+ const c = shortcutParse(combo);
+ const t = [];
+ if (c.ctrl) t.push('⌃');
+ if (c.alt) t.push('⌥');
+ if (c.shift) t.push('⇧');
+ if (c.mod) t.push('⌘');
+ if (c.code) t.push(c.code.slice(5));
+ else t.push(_SC_GLYPH[c.key] || c.key.toUpperCase());
+ return t;
+}
+
+function shortcutById(id) {
+ return SHORTCUTS.find(s => s.id === id) || null;
+}
+
+// The token groups a row DISPLAYS: its `display` override, or one group per
+// visible combo.
+function shortcutGroups(s) {
+ if (!s) return [];
+ if (s.display) return s.display;
+ return (s.combos || []).map(shortcutTokens);
+}
+
+// Plain text for a tooltip: "⇧⌘Z", "S or ⌘K or ⌘B".
+function shortcutHint(id) {
+ const s = shortcutById(id);
+ if (!s) return '';
+ const groups = shortcutGroups(s).map(g => g.join(g.some(x => x.length > 1) ? ' ' : ''));
+ return groups.join(s.displayJoin ? s.displayJoin : ' or ');
+}
+
+function _scEsc(t) {
+ return String(t).replace(/[&<>"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[ch]));
+}
+
+// Keycaps as markup. `cls` is the keycap class — the Docs page and the
+// Editor's popover draw keys differently.
+function shortcutKeysHtml(s, cls) {
+ const k = cls || 'kbd';
+ const joiner = s.displayJoin ? s.displayJoin : ' ';
+ return shortcutGroups(s)
+ .map(g => '<span class="sc-chord">' + g.map(x => '<kbd class="' + k + '">' + _scEsc(x) + '</kbd>').join('') + '</span>')
+ .join('<span class="sc-or">' + _scEsc(joiner) + '</span>');
+}
+
+// Rows for a set of scopes, already in markup: [{id, scope, keys, label}].
+function shortcutRows(scopes, cls) {
+ const want = new Set(scopes || SHORTCUT_SCOPES.map(x => x.id));
+ return SHORTCUTS.filter(s => want.has(s.scope))
+ .map(s => ({ id: s.id, scope: s.scope, keys: shortcutKeysHtml(s, cls), label: _scEsc(s.label) }));
+}
+
+// The Docs page's table, grouped by scope. Every row carries data-shortcut so
+// the test can find each registry entry on the page.
+function shortcutsDocHtml(scopes, idPrefix) {
+ const want = scopes ? new Set(scopes) : null;
+ const pre = idPrefix || '';
+ return SHORTCUT_SCOPES.map(sc => {
+ if (want && !want.has(sc.id)) return '';
+ const rows = SHORTCUTS.filter(s => s.scope === sc.id);
+ if (!rows.length) return '';
+ return '<h3 id="' + _scEsc(pre) + 'keys-' + sc.id + '">' + _scEsc(sc.title) + '</h3>' +
+ (sc.note ? '<p class="docs-muted">' + _scEsc(sc.note) + '</p>' : '') +
+ '<table class="docs-keys"><tbody>' +
+ rows.map(s => '<tr data-shortcut="' + _scEsc(s.id) + '"><td class="docs-keys-k">' +
+ shortcutKeysHtml(s, 'kbd') + '</td><td>' + _scEsc(s.label) + '</td></tr>').join('') +
+ '</tbody></table>';
+ }).join('');
+}
+
+// Any element with data-shortcut="<id>" names its keys in its tooltip. The
+// title written in the markup is the base; the keys are appended once.
+function shortcutDecorate(root) {
+ const scope = root || document;
+ if (!scope.querySelectorAll) return;
+ scope.querySelectorAll('[data-shortcut]').forEach(el => {
+ const hint = shortcutHint(el.getAttribute('data-shortcut'));
+ if (!hint) return;
+ if (el.dataset.tipBase === undefined) el.dataset.tipBase = el.getAttribute('title') || '';
+ const base = el.dataset.tipBase;
+ el.setAttribute('title', base ? (base + ' (' + hint + ')') : hint);
+ });
+}
+
+// ---- the handlers this file owns ---------------------------------------------
+function shortcutTyping(t) {
+ if (!t) return false;
+ if (t.isContentEditable) return true;
+ return /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName || '');
+}
+
+function _scVisible(el) {
+ return !!el && (el.offsetWidth > 0 || el.offsetHeight > 0);
+}
+
+// The same list health.js's Esc scaffold closes, plus the Docs.
+function shortcutTopModal() {
+ const sel = '.models-modal, .model-browser-modal, .expand-lightbox, .modal-bg.show';
+ const open = Array.from(document.querySelectorAll(sel)).filter(el =>
+ el.classList.contains('open') || el.classList.contains('show')
+ || el.style.display === 'flex' || el.style.display === 'block');
+ return open.length ? open[open.length - 1] : null;
+}
+
+function shortcutFocusSearch() {
+ const top = shortcutTopModal();
+ let box = null;
+ if (top) {
+ box = Array.from(top.querySelectorAll('input[type="search"], input.docs-search')).find(_scVisible) || null;
+ } else if (document.body.dataset.workflow === 'editor') {
+ box = document.getElementById('edPoolSearch');
+ } else {
+ box = document.getElementById('outputsSearch');
+ }
+ if (!_scVisible(box)) return false;
+ box.focus();
+ if (box.select) box.select();
+}
+
+function shortcutGenerateFrom(t) {
+ const id = t && t.id;
+ if (id === 'prompt') {
+ const form = document.getElementById('genForm');
+ const btn = document.getElementById('genBtn');
+ if (!form || !btn) return false;
+ if (btn.disabled) {
+ if (typeof phosToast === 'function') phosToast(btn.title || 'Generate is not available right now.', { duration: 5000 });
+ return;
+ }
+ // The ONE submit path — the same listener the Generate button fires.
+ if (form.requestSubmit) form.requestSubmit(btn); else btn.click();
+ return;
+ }
+ if (id === 'imgStudioPrompt') {
+ const btn = document.getElementById('imgStudioGenBtn');
+ if (!btn || typeof imgStudioGenerate !== 'function') return false;
+ if (btn.disabled) {
+ if (typeof phosToast === 'function') phosToast(btn.title || 'Generate is not available right now.', { duration: 5000 });
+ return;
+ }
+ imgStudioGenerate();
+ return;
+ }
+ return false; // One Shot's prompt has its own listener (oneshot.js)
+}
+
+const _SC_OUTPUT_TABS = new Set(['manual', 'oneshot', 'studio', 'audio']);
+
+function _scOnOutputsTab() {
+ if (!_SC_OUTPUT_TABS.has(document.body.dataset.workflow || 'manual')) return false;
+ // The Layout canvas owns the arrows and ⌫ while it holds the stage.
+ if (typeof ideoInLayout === 'function' && ideoInLayout()) return false;
+ return true;
+}
+
+function shortcutTogglePlayer(ev) {
+ const t = ev.target;
+ // A focused control keeps Space — that is how a keyboard presses a button.
+ if (t && t.closest && t.closest('button, a, [role="button"], video, audio, summary, label')) return false;
+ const lb = document.getElementById('expandLightbox');
+ const lbOpen = lb && lb.style.display === 'flex';
+ if (!lbOpen && (shortcutTopModal() || !_scOnOutputsTab())) return false;
+ const v = lbOpen
+ ? lb.querySelector('video')
+ : document.querySelector('#playerWrap video');
+ if (!v) return false;
+ window._stagePlaybackIntentAt = Date.now();
+ if (v.paused) { const p = v.play(); if (p && p.catch) p.catch(() => {}); }
+ else v.pause();
+}
+
+function shortcutTrashOutput() {
+ if (shortcutTopModal() || !_scOnOutputsTab()) return false;
+ if (typeof activePath === 'undefined' || !activePath || typeof deleteOutput !== 'function') return false;
+ deleteOutput(activePath); // confirms before it moves anything
+}
+
+document.addEventListener('keydown', (ev) => {
+ if (ev.defaultPrevented || ev.isComposing) return;
+ const typing = shortcutTyping(ev.target);
+ for (const s of SHORTCUTS) {
+ if (!s.run) continue;
+ if (typing && !s.typing) continue;
+ if (!s.typing && ev.target && ev.target.id === 'docsSearch' && s.id !== 'search.focus') continue;
+ const combos = (s.combos || []).concat(s.hidden || []);
+ if (!combos.some(c => shortcutMatches(ev, c))) continue;
+ // The page-level keys stand down while a dialog is up — except ⌘F, which
+ // finds the dialog's own search box, and ?, which is harmless on the Docs.
+ if (s.scope === 'global' && s.id !== 'search.focus') {
+ const top = shortcutTopModal();
+ if (top && !(s.id === 'docs.open' && top.id === 'docsView')) continue;
+ }
+ if (s.run(ev) === false) continue;
+ ev.preventDefault();
+ return;
+ }
+});
+
+shortcutDecorate(document);
+
+// ---- published to the page ---------------------------------------------------
+Object.assign(globalThis, {
+ SHORTCUTS, SHORTCUT_SCOPES, SHORTCUT_RESERVED,
+ shortcutParse, shortcutNormalise, shortcutMatches, shortcutTokens,
+ shortcutById, shortcutHint, shortcutKeysHtml, shortcutRows, shortcutsDocHtml,
+ shortcutDecorate, shortcutTyping,
+});
diff --git a/webapp/js/stage.js b/webapp/js/stage.js
index 92f6d28..da65539 100644
--- a/webapp/js/stage.js
+++ b/webapp/js/stage.js
@@ -62,7 +62,7 @@ function imgStudioUpdateValidity() {
// during in-flight gens.
if (!IMG_STUDIO.busy) {
btn.disabled = !!invalidReason;
- btn.title = invalidReason || 'Generate (Cmd/Ctrl+Enter)';
+ btn.title = invalidReason || ('Generate' + ((typeof shortcutHint === 'function') ? ' (' + shortcutHint('prompt.generate') + ')' : ''));
if (status && !status.textContent.startsWith('Generating')) {
if (invalidReason) {
status.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>' + escapeHtml(invalidReason);
@@ -280,6 +280,11 @@ function imgStudioApplyMemoryFit() {
}
}
+// The last /image/engine_status answer, for the modules that decide an
+// engine off it (the gallery's ✦ Quality chip). Read-only by contract.
+function imgStudioEngineStatus() {
+ return _IMG_ENGINE_STATUS || {};
+}
async function imgStudioRefreshEngineStatus() {
try {
const r = await fetch('/image/engine_status');
@@ -1880,7 +1885,7 @@ function imgStudioCopyPath(path) {
// the global scope; everything NOT listed here is private to this module.
Object.assign(globalThis, {
imgStudioUpdateValidity, imgStudioWireRefSlots, imgStudioRenderSlot, imgStudioUpdateRefWarning,
- imgStudioRefreshEngineStatus, ideoUpdateSetupNote, imgStudioUpdateEstimate, imgStudioRefreshRecent,
+ imgStudioRefreshEngineStatus, imgStudioEngineStatus, ideoUpdateSetupNote, imgStudioUpdateEstimate, imgStudioRefreshRecent,
imgStudioOnPillClick, ideoInLayout, stageSetMode, ideoSyncStage,
ideoSyncVisibility, ideoSyncRefBridge, ideoSetMode, ideoApplyAspect,
ideoSetRender, ideoUndo, ideoInsertBox, ideoUpdateSel,
diff --git a/webapp/js/storyboard.js b/webapp/js/storyboard.js
index 2b03252..540f50d 100644
--- a/webapp/js/storyboard.js
+++ b/webapp/js/storyboard.js
@@ -2264,6 +2264,9 @@ document.addEventListener('keydown', (ev) => {
const li = document.activeElement && document.activeElement.closest
&& document.activeElement.closest('.sb-shot');
if (!li || /^(INPUT|TEXTAREA|SELECT)$/.test((ev.target.tagName || ''))) return;
+ // Bare letters only: ⌘C on a focused card is a copy and ⌘R a reload, and
+ // both used to grade the shot as well.
+ if (ev.metaKey || ev.ctrlKey || ev.altKey) return;
const g = { k: 'keep', r: 'reroll', c: 'cut' }[ev.key.toLowerCase()];
if (!g) return;
const n = Number(li.dataset.n);
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index b6ff3cf..c35232a 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -2048,6 +2048,102 @@
pointer-events: none; max-width: 640px;
}
+ /* ---- THE CLIP BAR -----------------------------------------------
+ The verbs, above the tracks, always on screen. See the block comment
+ in webapp/index.html and docs/EDITOR_TOOLBAR.md.
+
+ NOWRAP IS THE WHOLE POINT. `flex-wrap: wrap` here would answer a
+ narrow pane by growing a second row, which pushes the tracks down the
+ column and takes the height off the picture — so the bar does not
+ wrap, it OVERFLOWS: sbeCbarFit moves the tail into #sbeCbarMenu.
+ min-width:0 so the row may be measured smaller than its content. */
+ .sbe-cbar {
+ display: flex; align-items: center; gap: 5px; flex-wrap: nowrap;
+ min-width: 0; overflow: hidden;
+ }
+ /* THE SPRITE ITSELF NEVER DRAWS. It is a <defs> carrier, and without an
+ explicit zero box a stray <svg> in a flex column is a 300x150 hole. */
+ .sbe-icons { position: absolute; width: 0; height: 0; overflow: hidden; }
+ /* WHAT IS SELECTED, and it is the item that yields: the verbs are all
+ at their intrinsic width, so the prose is the one that can shrink. */
+ .sbe-cbar-who {
+ flex: 0 1 auto; min-width: 42px; overflow: hidden;
+ text-overflow: ellipsis; white-space: nowrap;
+ font-size: var(--fs-xs); color: var(--muted);
+ padding-right: 2px;
+ }
+ .sbe-cbar-who.is-many { color: var(--accent-bright); font-weight: 600; }
+ .sbe-cbar-sep {
+ flex: 0 0 auto; width: 1px; height: 16px; margin: 0 3px;
+ background: var(--border);
+ }
+ /* A VERB, NOT A STICKER. Same family as .ghost-btn — one border, one
+ radius token, the same hover — plus the icon slot, so the row reads as
+ a toolbar at a glance instead of as ten words in a line. */
+ .sbe-cbar-btn {
+ flex: 0 0 auto; width: auto; display: inline-flex; align-items: center;
+ gap: 5px; height: var(--ctl-h-sm); padding: 0 9px;
+ 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-cbar-btn > b { font-weight: 500; }
+ .sbe-cbar-btn:hover:not(:disabled) {
+ background: var(--bg-2); border-color: var(--accent);
+ color: var(--accent-bright);
+ }
+ .sbe-cbar-btn:focus-visible { outline: none; box-shadow: var(--ring); }
+ /* DISABLED, NEVER GONE. Legible enough to read the label and the tooltip
+ that says why — the tooltip is the only thing that can teach "select a
+ clip first", and a button that is not there cannot carry one. */
+ .sbe-cbar-btn:disabled {
+ opacity: 0.42; cursor: default; background: transparent;
+ border-color: var(--border); color: var(--muted);
+ }
+ /* ON. A toggle whose label already flips (Lock → Unlock) still needs to
+ say which way it is pointing at a glance across a ten-button row. */
+ .sbe-cbar-btn.is-on {
+ background: var(--accent-dim); border-color: var(--accent);
+ color: var(--accent-bright);
+ }
+ .sbe-cbar-i {
+ flex: 0 0 auto; width: 13px; height: 13px;
+ fill: none; stroke: currentColor; stroke-width: 1.7;
+ stroke-linecap: round; stroke-linejoin: round;
+ }
+ /* THE FOLD, RESTATED. `display: inline-flex` on the class beats the UA's
+ `[hidden] { display: none }`, so the overflow button and a spent group
+ divider stayed on screen with the attribute set — the same lesson
+ `.quality-strip` and the One Shot panel already paid for. */
+ .sbe-cbar-btn[hidden], .sbe-cbar-sep[hidden] { display: none !important; }
+ .sbe-cbar-more { margin-left: 2px; }
+ .sbe-cbar-more .sbe-car { font-size: 9px; opacity: 0.75; }
+ /* THE OVERFLOW PANEL holds the very same buttons, so they have to stop
+ being a row and become a list once they are in it. */
+ .sbe-cbar-pop { min-width: 170px; }
+ .sbe-cbar-pop .sbe-cbar-btn,
+ .sbe-ctx .sbe-cbar-btn {
+ width: 100%; justify-content: flex-start; height: var(--ctl-h);
+ }
+ .sbe-cbar-pop .sbe-cbar-sep, .sbe-cbar-pop .ch-spacer { display: none; }
+ .sbe-ctx { min-width: 186px; }
+ .sbe-ctx-h {
+ font-size: var(--fs-2xs); text-transform: uppercase;
+ letter-spacing: 0.07em; color: var(--muted);
+ padding: 2px 4px 4px; overflow: hidden;
+ text-overflow: ellipsis; white-space: nowrap;
+ }
+
+ /* Below the stacking breakpoint the PAGE is the scroller — there is no
+ column height to protect, so the bar is allowed to wrap and the
+ overflow logic stands down (sbeCbarFit returns early there). */
+ @media (max-width: 900px) {
+ .sbe-cbar { flex-wrap: wrap; overflow: visible; }
+ }
+
.sbe-transport {
display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
position: relative;
@@ -2412,6 +2508,14 @@
font-size: var(--fs-2xs); letter-spacing: 0.08em; text-transform: uppercase;
color: var(--muted); font-weight: 700;
}
+ /* WHAT THIS BOX IS NOW. Said once, above the first section, because the
+ inspector lost most of its buttons to the clip bar and a panel of
+ properties that used to be a panel of verbs has to name the change or
+ it reads as a panel with things missing. */
+ .sbe-sect-lead {
+ font-size: var(--fs-2xs); color: var(--muted); line-height: 1.45;
+ padding: 2px 0 1px; border-top: 1px solid var(--border); margin-top: 4px;
+ }
.sbe-sect-b { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.sbe-fade-row { display: inline-flex; align-items: center; gap: 5px; }
.sbe-fade-row label { font-size: var(--fs-xs); color: var(--muted); }
@@ -2750,6 +2854,16 @@
border-color: var(--accent);
box-shadow: 0 0 0 1px var(--accent), var(--shadow-2);
}
+ /* WHICH ONE OF A SELECTION THE PANEL IS TALKING ABOUT. With four shots
+ selected the inspector still shows ONE clip's properties and the
+ sound buttons still read one clip's state, so the primary has to be
+ pickable out of the row or the bar is lying about which shot it means.
+ A second ring rather than a different colour: they are all selected,
+ and one of them is also the subject. */
+ .sbe-clip.is-sel.is-primary {
+ box-shadow: 0 0 0 1px var(--accent), 0 0 0 3px var(--accent-dim),
+ var(--shadow-2);
+ }
.sbe-clip.is-playing { border-color: var(--success); }
.sbe-clip.is-playing::after {
content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 2px;
@@ -10078,3 +10192,268 @@ body.oneshot-mode #h3LengthGroup { display: none !important; }
.civitai-chips .pill-btn { width: auto; flex: 0 0 auto; padding: 3px 9px; font-size: 11px; border-radius: 999px; margin: 0; }
.civitai-chips .toggle-pill { margin-left: auto; }
.civitai-toolbar .toggle-pill { margin-left: auto; }
+
+/* ---- One Shot tab (webapp/js/oneshot.js, 2026-09-08) ---------------------- */
+/* The tab owns the left pane the way Audio and Train do: the video form, its
+ mode bar and the models card fold away, and the section takes the column. */
+body[data-workflow="oneshot"] #modelsInline,
+body[data-workflow="oneshot"] #modeGroup,
+body[data-workflow="oneshot"] #remixSubGroup,
+body[data-workflow="oneshot"] aside.form-pane > h2,
+body[data-workflow="oneshot"] #genForm,
+body[data-workflow="oneshot"] #studioSection,
+body[data-workflow="oneshot"] #trainSection,
+body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }
+/* The label row, as the quick-settings cards draw it: name left, meta right. */
+.os-card .qs-label { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 6px; min-width: 0; }
+.os-card .qs-label .qs-name { flex: 0 0 auto; font-size: 10px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; white-space: nowrap; }
+.os-card .qs-label .qs-meta { min-width: 0; font-size: 11px; color: var(--muted); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; text-align: right; white-space: normal; }
+#oneshotSectionTab { display: grid; gap: 10px; min-width: 0; max-width: 100%; }
+/* The same side padding the video form gets, so the cards and the sticky
+ footer's edge-to-edge break-out land where they do on the Video tab. */
+.form-pane > #oneshotSectionTab { padding: 0 18px; }
+#oneshotSectionTab > * { min-width: 0; }
+#oneshotSectionTab[style*="display: none"], #oneshotSectionTab[style*="display:none"] { display: none; }
+.os-card { display: grid; gap: 12px; min-width: 0; overflow-wrap: anywhere; }
+.os-card > * { min-width: 0; }
+.os-card h2 { margin: 0; }
+.os-lead { margin-top: -4px; line-height: 1.45; }
+.os-block { display: grid; gap: 6px; min-width: 0; }
+.os-two { display: grid; grid-template-columns: 1fr; gap: 12px; }
+.os-prompt { min-height: 96px; }
+.os-anchor { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-height: 32px; }
+.os-anchor-thumb { height: 44px; width: auto; border-radius: 6px; border: 1px solid var(--border, #2a2f3a); }
+.os-anchor-thumb[hidden] { display: none !important; }
+.os-anchor-name { color: var(--muted); }
+.os-characters { display: flex; flex-wrap: wrap; gap: 6px; }
+.os-characters .pill-btn { flex: 0 1 auto; min-width: 120px; }
+#osLengthGroup.cols-5 { grid-template-columns: repeat(5, minmax(0, 1fr)); }
+#osLengthGroup .q-chip, #osQualityGroup .q-chip { justify-content: flex-start; min-height: 56px; }
+#osLengthGroup .q-chip .ql-tier { white-space: nowrap; color: var(--muted); }
+#osQualityGroup[hidden] { display: none !important; }
+.os-estimate { font-size: var(--fs-sm, 12px); color: var(--muted); min-height: 1.2em; }
+.os-beats-tools { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; margin-top: -2px; }
+.os-beat-rows { display: grid; gap: 4px; }
+.os-beat-row { display: grid; grid-template-columns: 40px minmax(0, 1fr); align-items: center; gap: 6px; }
+.os-beat-row .os-stamp { font-family: var(--ph-font-mono); font-size: 11px; color: var(--faint, var(--muted)); text-align: right; }
+.os-beat-row.over .os-stamp { color: var(--danger, #f85149); }
+.os-beat-row.over .os-beat { opacity: 0.6; }
+.os-beat-row .os-beat { width: 100%; min-width: 0; box-sizing: border-box; font-size: 12px; }
+.os-beats-note { margin-top: -2px; }
+.os-beats-note a { color: var(--accent-bright); }
+.os-toggles { display: grid; grid-template-columns: 1fr; gap: 10px; }
+.os-toggle { display: grid; gap: 6px; min-width: 0; }
+.os-toggle .pill-group.cols-2 { grid-template-columns: 1fr 1fr; }
+.os-toggle[hidden] { display: none !important; }
+.os-more { margin-top: 2px; }
+.os-more summary { cursor: pointer; color: var(--muted); font-size: var(--fs-sm, 12px); user-select: none; }
+.os-more-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 8px; }
+@media (max-width: 720px) { .os-more-grid { grid-template-columns: 1fr; } }
+.os-field { display: grid; gap: 4px; min-width: 0; }
+.os-field .sub { color: var(--muted); }
+.os-check { grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; }
+.os-check .sub { color: var(--muted); }
+.os-character-note { margin-top: 2px; }
+.os-character-note[hidden] { display: none !important; }
+.os-footer { margin-top: 2px; }
+.os-status .os-parts { display: flex; flex-wrap: wrap; gap: 6px; }
+.os-part { font-size: 11px; padding: 3px 8px; border-radius: 999px; border: 1px solid var(--border, #2a2f3a); color: var(--muted); }
+.os-part.now { color: var(--accent-bright); border-color: var(--accent-bright); }
+.os-part.ok { color: #3fb950; border-color: rgba(63, 185, 80, 0.5); }
+.os-part.mid { color: #d29922; border-color: rgba(210, 153, 34, 0.5); }
+.os-part.bad { color: #f85149; border-color: rgba(248, 81, 73, 0.5); }
+.os-part.quiet { color: var(--muted); }
+.os-log { margin: 0; white-space: pre-wrap; font-family: var(--ph-font-mono); font-size: 11px; line-height: 1.4; color: var(--muted); max-height: 9em; overflow: auto; }
+
+ /* ======================================================================
+ THE DOCS (webapp/js/docs.js, pages in webapp/docs/*.md) and the keycap
+ every shortcut is drawn with. One reading column in the panel's own
+ tokens: the nav is the rail, the article is the page, and the light
+ theme comes free from the same variables.
+ ====================================================================== */
+ kbd.kbd {
+ display: inline-flex; align-items: center; justify-content: center;
+ min-width: 20px; height: 20px; padding: 0 5px; margin: 0 1px;
+ font: 600 11px/1 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
+ color: var(--text); background: var(--panel-2);
+ border: 1px solid var(--border-strong); border-bottom-width: 2px;
+ border-radius: 5px; white-space: nowrap; vertical-align: 1px;
+ }
+ .sc-chord { display: inline-flex; gap: 2px; white-space: nowrap; }
+ .sc-or { color: var(--muted); font-size: var(--fs-xs); margin: 0 5px; }
+ kbd.sbe-kbd { display: inline-block; margin: 0 1px; }
+ .sbe-key-row .sc-or { margin: 0 3px; }
+ .sbe-keys-docs {
+ display: block; margin-top: 10px; padding-top: 8px;
+ border-top: 1px solid var(--border); font-size: var(--fs-xs);
+ color: var(--accent-bright); text-decoration: none;
+ }
+ .sbe-keys-docs:hover { text-decoration: underline; }
+ .sbe-retakes { flex-direction: column; align-items: stretch; margin-top: 6px; }
+ .sbe-relink-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+ .sbe-relink-row > span { flex: 1 1 auto; }
+ .sbe-relink-row .ghost-btn { width: auto; flex: 0 0 auto; }
+
+ body > header .docs-btn {
+ width: auto; padding: 0 10px 0 8px; gap: 6px;
+ font-size: var(--fs-sm); font-weight: 600; color: var(--muted);
+ }
+ body > header .docs-btn:hover { color: var(--text); background: var(--accent-dim); }
+ body > header .docs-btn .ph { width: 16px; height: 16px; }
+ @media (max-width: 1100px) {
+ body > header .docs-btn { width: 34px; padding: 0; }
+ body > header .docs-btn .docs-btn-word { display: none; }
+ }
+
+ .docs-view.show { display: flex; }
+ .docs-view { z-index: 140; padding: 20px; align-items: stretch; justify-content: center; }
+ .docs-shell {
+ display: grid; grid-template-columns: 272px minmax(0, 1fr);
+ width: min(1180px, 100%); height: 100%;
+ background: var(--bg-2); border: 1px solid var(--border-strong);
+ border-radius: var(--r-lg); box-shadow: var(--shadow-2); overflow: hidden;
+ }
+ .docs-nav {
+ display: flex; flex-direction: column; min-height: 0;
+ border-right: 1px solid var(--border); background: var(--bg);
+ }
+ .docs-brand {
+ display: flex; align-items: center; gap: 9px;
+ padding: 18px 18px 12px; font-size: var(--fs-lg); font-weight: 650;
+ letter-spacing: -0.01em; color: var(--text);
+ }
+ .docs-brand .ph { width: 18px; height: 18px; color: var(--accent-bright); }
+ .docs-search-wrap {
+ position: relative; display: block; margin: 0 14px 10px;
+ }
+ .docs-search-wrap .ph {
+ position: absolute; left: 10px; top: 50%; transform: translateY(-50%);
+ width: 14px; height: 14px; color: var(--muted); pointer-events: none;
+ }
+ .docs-search-wrap input.docs-search {
+ width: 100%; height: var(--ctl-h); padding: 0 10px 0 31px;
+ background: var(--panel); border: 1px solid var(--border);
+ border-radius: var(--r-sm); color: var(--text); font: inherit; font-size: var(--fs-md);
+ }
+ .docs-search-wrap input.docs-search:focus { outline: none; border-color: var(--accent); box-shadow: var(--ring); }
+ .docs-toc, .docs-results { flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 4px 8px 18px; }
+ .docs-toc[hidden], .docs-results[hidden] { display: none; }
+ .docs-toc-group {
+ margin: 14px 10px 4px; font-size: var(--fs-2xs); font-weight: 650;
+ letter-spacing: .12em; text-transform: uppercase; color: var(--muted); opacity: .8;
+ }
+ .docs-toc a {
+ display: block; padding: 6px 10px; border-radius: var(--r-xs);
+ color: var(--muted); text-decoration: none; font-size: var(--fs-md); line-height: 1.35;
+ }
+ .docs-toc a:hover { color: var(--text); background: var(--panel); }
+ .docs-toc a.docs-toc-sec.is-active { color: var(--text); background: var(--panel); font-weight: 600; }
+ .docs-toc-subs { margin: 2px 0 6px 10px; padding-left: 8px; border-left: 1px solid var(--border); }
+ .docs-toc a.docs-toc-sub { padding: 4px 10px; font-size: var(--fs-sm); }
+ .docs-toc a.docs-toc-sub.is-here { color: var(--accent-bright); }
+ .docs-hit {
+ display: block; padding: 8px 10px; border-radius: var(--r-sm);
+ text-decoration: none; color: var(--text); border: 1px solid transparent;
+ }
+ .docs-hit:hover, .docs-hit:focus { background: var(--panel); border-color: var(--border); outline: none; }
+ .docs-hit-t { display: block; font-size: var(--fs-md); font-weight: 600; }
+ .docs-hit-s { display: block; font-size: var(--fs-2xs); color: var(--accent-bright); margin-top: 1px; letter-spacing: .02em; }
+ .docs-hit-x { display: block; font-size: var(--fs-xs); color: var(--muted); margin-top: 3px; line-height: 1.45; }
+ .docs-hit mark, .docs-hit-t mark { background: var(--accent-dim); color: var(--text); border-radius: 3px; padding: 0 1px; }
+ .docs-noresult { padding: 14px 10px; color: var(--muted); font-size: var(--fs-sm); line-height: 1.5; }
+
+ .docs-main { display: flex; flex-direction: column; min-width: 0; min-height: 0; background: var(--bg-2); }
+ .docs-bar {
+ display: flex; align-items: center; gap: 10px; flex: 0 0 auto;
+ height: 52px; padding: 0 16px 0 28px; border-bottom: 1px solid var(--border);
+ }
+ .docs-bar .ghost-btn { width: auto; }
+ .docs-nav-toggle { display: none; }
+ .docs-crumb { font-size: var(--fs-sm); color: var(--muted); white-space: pre; overflow: hidden; text-overflow: ellipsis; }
+ .docs-bar-spacer { flex: 1 1 auto; }
+ .docs-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto; scroll-behavior: auto; }
+ .docs-article {
+ max-width: 760px; margin: 0 auto; padding: 30px 40px 12px;
+ font-size: 14px; line-height: 1.68; color: var(--text);
+ }
+ .docs-article h1 {
+ margin: 0 0 6px; font-size: 28px; line-height: 1.2; font-weight: 700; letter-spacing: -0.02em;
+ }
+ .docs-article h1 + p { font-size: 15px; color: var(--muted); margin-top: 6px; }
+ .docs-article h2 {
+ margin: 38px 0 10px; padding-top: 22px; border-top: 1px solid var(--border);
+ font-size: 19px; line-height: 1.3; font-weight: 650; letter-spacing: -0.01em;
+ }
+ .docs-article h3 { margin: 26px 0 8px; font-size: 15px; font-weight: 650; }
+ .docs-article h2, .docs-article h3 { scroll-margin-top: 12px; position: relative; }
+ .docs-anchor {
+ margin-left: 8px; color: var(--muted); text-decoration: none; opacity: 0;
+ font-weight: 400; transition: opacity var(--t-fast);
+ }
+ .docs-article h2:hover .docs-anchor, .docs-article h3:hover .docs-anchor, .docs-anchor:focus { opacity: .7; }
+ .docs-flash { animation: docsFlash 1.4s ease-out; }
+ @keyframes docsFlash { 0% { color: var(--accent-bright); } 100% { color: inherit; } }
+ .docs-article p { margin: 10px 0; }
+ .docs-article ul, .docs-article ol { margin: 10px 0; padding-left: 22px; }
+ .docs-article li { margin: 5px 0; }
+ .docs-article li > ul, .docs-article li > ol { margin: 4px 0; }
+ .docs-article ol > li::marker { color: var(--accent-bright); font-weight: 650; }
+ .docs-article a { color: var(--accent-bright); text-decoration: none; }
+ .docs-article a:hover { text-decoration: underline; }
+ .docs-article strong { font-weight: 650; color: var(--text); }
+ .docs-article code {
+ font: 12.5px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
+ background: var(--panel); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px;
+ }
+ .docs-pre {
+ margin: 12px 0; padding: 12px 14px; overflow-x: auto;
+ background: var(--bg); border: 1px solid var(--border); border-radius: var(--r-sm);
+ }
+ .docs-pre code { background: none; border: 0; padding: 0; }
+ .docs-note {
+ margin: 16px 0; padding: 10px 14px; border-radius: var(--r-sm);
+ background: var(--accent-dim); border-left: 3px solid var(--accent);
+ }
+ .docs-note p { margin: 4px 0; }
+ .docs-muted { color: var(--muted); font-size: var(--fs-sm); margin-top: -2px !important; }
+ .docs-table-wrap { overflow-x: auto; margin: 14px 0; border: 1px solid var(--border); border-radius: var(--r-sm); }
+ .docs-table { width: 100%; border-collapse: collapse; font-size: 13px; line-height: 1.5; }
+ .docs-table th {
+ text-align: left; font-size: var(--fs-xs); font-weight: 650; color: var(--muted);
+ text-transform: uppercase; letter-spacing: .06em; background: var(--bg); padding: 8px 12px;
+ }
+ .docs-table td { padding: 8px 12px; border-top: 1px solid var(--border); vertical-align: top; }
+ .docs-keys { width: 100%; border-collapse: collapse; margin: 6px 0 12px; font-size: 13px; }
+ .docs-keys td { padding: 7px 10px 7px 0; border-top: 1px solid var(--border); vertical-align: top; }
+ .docs-keys tr:first-child td { border-top: 0; }
+ .docs-keys td.docs-keys-k { width: 210px; white-space: normal; }
+ .docs-sc { white-space: nowrap; }
+ .docs-icon { width: 15px; height: 15px; vertical-align: -3px; color: var(--text); }
+ .docs-missing { color: var(--danger); }
+ .docs-article hr { border: 0; border-top: 1px solid var(--border); margin: 26px 0; }
+ .docs-pagenav {
+ display: grid; grid-template-columns: 1fr 1fr; gap: 12px;
+ max-width: 760px; margin: 18px auto 40px; padding: 0 40px;
+ }
+ .docs-pagenav a {
+ display: flex; flex-direction: column; gap: 2px; padding: 12px 14px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ color: var(--text); text-decoration: none; font-weight: 600; font-size: var(--fs-md);
+ }
+ .docs-pagenav a span { font-size: var(--fs-2xs); color: var(--muted); font-weight: 500; text-transform: uppercase; letter-spacing: .1em; }
+ .docs-pagenav a:hover { border-color: var(--accent); }
+ .docs-page-next { text-align: right; grid-column: 2; }
+ @media (max-width: 860px) {
+ .docs-view { padding: 0; }
+ .docs-shell { grid-template-columns: minmax(0, 1fr); border-radius: 0; border: 0; position: relative; }
+ .docs-nav {
+ position: absolute; inset: 52px 0 0 0; z-index: 2; display: none;
+ border-right: 0; box-shadow: var(--shadow-2);
+ }
+ .docs-view.nav-open .docs-nav { display: flex; }
+ .docs-nav-toggle { display: inline-flex; }
+ .docs-bar { padding-left: 12px; }
+ .docs-article { padding: 22px 18px 8px; }
+ .docs-pagenav { padding: 0 18px; }
+ .docs-keys td.docs-keys-k { width: 42%; }
+ }