Skip to content

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

release(v4.11.0): One Shot — its own mode, LTX by last-frame handoff, the planner places one in a film

mrbizarro67ac524e41c1
diff --git a/README.md b/README.md
index f162de0..de4a878 100644
--- a/README.md
+++ b/README.md
@@ -3,9 +3,9 @@
</p>
<p align="center">
- <img src="assets/the_commuter_hero.gif" alt="The Commuter — a 75-second one take made in Phosphene" width="100%">
+ <img src="assets/the_commuter_hero.gif" alt="The Commuter — a 75-second One Shot made in Phosphene" width="100%">
<br>
- <sub><b>The Commuter</b> — a 75-second one take, rendered overnight on one Mac at native 1344×768 with Hailuo H3 and the new One take control, from a single designed still. <a href="https://github.com/mrbizarro/phosphene/releases/latest">Watch the full film in the release</a>.</sub>
+ <sub><b>The Commuter</b> — a 75-second One Shot, rendered overnight on one Mac at native 1344×768 with Hailuo H3 and the new One Shot mode, from a single designed still. <a href="https://github.com/mrbizarro/phosphene/releases/latest">Watch the full film in the release</a>.</sub>
</p>
<p align="center">
@@ -19,7 +19,7 @@
</p>
-> **Current release: v4.10.8.** **LTX Upscale**: any finished clip, an H3 draft above all, re-rendered at twice its size by the LTX-2.5 Pixel Spatial Upscaler with real generated detail, keeping its sound — a button on every video card, a Remix mode, and an **LTX ×2** option in the H3 form that queues the upscale behind the draft in one click. Presets Faithful (face and lips stay), Quick and Re-imagine. Also in this line: Extend renders again (broken since 4.10.2), One take sits under Quality and Length, LoRAs stack on Hailuo H3, Browse CivitAI search works again. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
+> **Current release: v4.11.0.** **One Shot** is its own way of making video: a continuous shot of 30 s to 2 min that never cuts, next to Text, Character and Image — pick a length, write one line per 5 seconds, add a start frame if you like, keep the light locked, and see the real time for your Mac. LTX one shots hold together now (parts that continue from the last frame, like Hailuo H3's), and the Storyboard planner can place a One Shot inside a film. Also in this line: LTX Upscale, Extend fixed, LoRAs stack on Hailuo H3. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
## Overview
diff --git a/VERSION b/VERSION
index 195e81e..a162ea7 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.10.8
+4.11.0
diff --git a/docs/API.md b/docs/API.md
index 0b3cc13..8cbf5a2 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -142,22 +142,42 @@ Submit multiple prompts as one batch.
A clip longer than a single pass, on either engine. `take_seconds` is one of
30 / 45 / 60 / 90 / 120; `beats` is a JSON list (or newline text) with one
prompt per five seconds — a blank beat holds the previous moment, extras are
-dropped. The take overrules the engine's own length field:
+dropped. The take overrules the engine's own length field. On BOTH engines it
+renders as PARTS chained by last-frame handoff — `run_take_job_inner` runs one
+ordinary render per part, each starting from the last frame of the one before
+(i2v, anchored), hides the parts from the gallery and joins them into
+`<name>_take<seconds>s.mp4`:
-| engine | what make_job does | worker |
-|---|---|---|
-| `ltx` | `long_mode=windows`, `frames = seconds·24+1`, `window_prompts = beats` | the windows chain (needs the Q8 pack) |
-| `h3` | `h3_length=15s`, parts of three beats | `run_take_job_inner`: one ordinary H3 render per part, each starting from the last frame of the one before (`--first-frame`), parts hidden from the gallery, joined into `<name>_take<seconds>s.mp4` with a sidecar carrying `take.{seconds,beats,parts}` |
+| engine | part | what make_job does | worker |
+|---|---|---|---|
+| `ltx` | 10 s = two beats = 241 frames (a 45 s take ends on a one-beat 121-frame part) | `frames = 241`, `temporal_mode = native` (a take is never the windows chain, whatever the form sent) | one ordinary LTX render per part through `run_job_inner`: part 1 is `t2v`, or `i2v` from the job's own `image` when it came in as `i2v`; every later part is `i2v` from the previous part's last frame with `i2v_reference_mode = anchor`. Any quality; the Q8 pack is only needed by an HQ quality, as for a single clip |
+| `h3` | 15 s = three beats | `h3_length=15s`, `h3_chain_prompts` = the first part's beats | one ordinary H3 render per part (`--first-frame` from the previous last frame) |
+
+Two optional fields, both default `on`:
+
+| field | `off` means |
+|---|---|
+| `take_light_lock` | the continuity sentence (`take_light_lock()` — "it is still night…") is NOT appended to the beats; `take.light_lock` is `""` and a blank beat holds with the hold sentence alone |
+| `take_retake` | a part whose light drifts past `TAKE_DRIFT_MAX` is kept as rendered instead of being retaken once with a fresh seed; `take.retake` is `false` |
-`params.take` on the job: `{seconds, beats, parts, frames, engine, beat_prompts}`.
-Load Params restores a take as a take.
+`params.take` on the job: `{seconds, beats, parts, frames, part_frames,
+beats_per_part, engine, beat_prompts, light_lock, retake}` — `frames` is the
+whole take (`seconds·24+1` on LTX), `part_frames` one full part. The output's
+sidecar carries `take.{seconds, beats, parts, engine, beats_per_part,
+part_frames, light_lock, retake}` with `parts` the hidden part files, and
+`image` only when the take opened on the user's own anchor. Load Params
+restores a take as a take.
### `GET /take/estimate`
`?engine=h3|ltx&quality=<engine quality key>&seconds=<take_seconds>` →
-`{ ok, seconds, beats, parts, engine, frames, minutes, eta, needs_q8 }`. Minutes
-come from the same cost model as every other estimate (H3: the measured 15 s
-cell × parts); `null` where this Mac has no number (LTX windows are unpriced).
+`{ ok, seconds, beats, parts, beats_per_part, part_frames, engine, frames,
+minutes, eta, needs_q8 }`. `parts` is the part count on both engines. Minutes
+are parts × the single-clip price of one part from the same cost model as
+every other estimate (H3: the measured 15 s cell; LTX: the quality's `10s`
+cell of `LTX_TIERS`, the one-beat tail at its `5s` cell); `null` where this
+Mac has no number. `needs_q8` is always `false` now — an LTX take renders on
+whatever the chosen quality renders on.
### `GET /status`
diff --git a/docs/PROMPTING.md b/docs/PROMPTING.md
index 3d76d67..32acf94 100644
--- a/docs/PROMPTING.md
+++ b/docs/PROMPTING.md
@@ -2,7 +2,7 @@
Copy this whole page into your own assistant (ChatGPT, Claude, Codex) and ask it to write your beats. The Storyboard planner already follows these rules on its own; this page is for when you write by hand.
-## One take (a clip longer than one pass)
+## One Shot (a clip longer than one pass)
- **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.
@@ -20,7 +20,7 @@ Copy this whole page into your own assistant (ChatGPT, Claude, Codex) and ask it
## What not to write
-- No "fast forward", "time-lapse" or "montage" in a one-take: the model cuts.
+- No "fast forward", "time-lapse" or "montage" in a One Shot: the model cuts.
- No two subjects at once unless one of them is the point of the beat.
- No text on screen; no lettering on signs unless you accept invented words.
diff --git a/docs/STATE.md b/docs/STATE.md
index b1bc35b..90e8d91 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,5 +1,35 @@
# Phosphene — project state, history, open work
+> **🚀 2026-09-07 — v4.11.0 ships: One Shot.** The mode chip + panel, LTX
+> one shots by last-frame handoff (proven on a 40 s bar conversation:
+> four 10 s parts, same people, same room, camera moving), the planner's
+> One Shot rule, the UX-walk fixes, the stray `_w0` gallery clip. Carries
+> 4.10.5–4.10.8.
+
+> **🎬 2026-09-07 — One Shot: its own mode, LTX by last-frame handoff, the planner
+> may place one in a film (on dev).** Measured tonight: an LTX 45 s take through
+> the windows chain (Extend with 121 f tail context) turns to mush at the FIRST
+> extension — faces smear, audio of the new piece peaks at −38 dB — at 27 min a
+> window (`mlx_outputs/.experiments/night_ltx_take45/`). So an LTX one shot now
+> renders like H3's: parts by last-frame handoff (10 s / 2 beats on LTX, 15 s /
+> 3 beats on H3), part 1 t2v or from the user's anchor image, later parts i2v
+> anchored on the previous last frame; `take_plan` carries `part_frames` /
+> `beats_per_part`; `run_take_job_inner` is engine-aware and calls
+> `run_job_inner` for LTX parts; new fields `take_light_lock` / `take_retake`;
+> `/take/estimate` returns parts for both engines (`test_take.py`, 22). The
+> windows chain stays only behind Long clips → windows. **UI:** the owner named
+> the feature **One Shot** and wanted it "a different part of the tooling": a
+> `data-mode="oneshot"` chip after Image with its own panel (#takeAxes: length,
+> beats + "Write the beats for me", anchor image reusing the i2v `image` field,
+> Lock the light / Retake toggles, estimate, engine note); leaving the mode
+> resets `take_seconds`; Load Params reopens it from `take.seconds`; "One take"
+> renamed everywhere users read it (`test_storyboard_editor_ui.py`
+> OneShotIsAMode, 16). **Planner:** `_ONE_SHOT` rule block + example in
+> storyboard_planner.py — a shot may carry `take_seconds` + `beats`, chosen for
+> a walk-and-talk / chase or POV / monologue / reveal / arrival, at most one or
+> two per film; storyboard.py validates, prices per engine's parts and posts
+> ONE job (`test_storyboard_one_shot.py`, 14; docs/STORYBOARD.md).
+
> **🚀 2026-09-06 — v4.10.8 ships (dev promoted whole; main = dev tree).**
> Upscale ×2 / LTX Upscale goes public: the card button, Remix → Upscale ×2,
> and LTX ×2 in the H3 form (chain), presets Faithful (3 refine steps from
diff --git a/docs/STORYBOARD.md b/docs/STORYBOARD.md
new file mode 100644
index 0000000..5b2b5c6
--- /dev/null
+++ b/docs/STORYBOARD.md
@@ -0,0 +1,67 @@
+# Storyboard — the planner
+
+The Storyboard tab turns one concept sentence into a film of shots (3 / 5 / 10 s
+each), then renders them through the ordinary job queue. The planner lives in
+`storyboard_planner.py` (`plan_film`: screenplay → geography → shots, then the
+laws); the schema, validation, shooting order, pricing and the shot → job
+mapping live in `storyboard.py`. The HTTP surface is documented in
+`docs/API.md` (the `/storyboard/*` routes); the prompt-writing rules the
+planner follows are in `docs/PROMPTING.md`. This page covers the one planning
+tool that is not a 3 / 5 / 10 s shot.
+
+## One Shot inside a film
+
+**What it is.** A One Shot is one scene of an ordinary multi-shot film rendered
+as a single unbroken take of 30, 45, 60, 90 or 120 seconds: the camera never
+cuts, one movement happens per five-second beat, and the world changes around
+the subject while the subject, the camera position and the light stay
+continuous. The planner chooses it on its own, as a cinematic tool, when a
+scene earns unbroken time — a walk-and-talk, a chase or a POV ride, a
+monologue or a confession, a reveal, an arrival through a place — and leaves
+it alone for a montage, cross-cutting, or anything that needs a reverse angle.
+At most one or two per film, never the whole film unless the brief asks for one
+take (that is the existing whole-film take: the board's `take_seconds` +
+`collapse_take`). A One Shot counts as one shot in the shot count.
+
+**What the planner writes.** The shot keeps every ordinary key and adds two:
+
+| field | value |
+|---|---|
+| `take_seconds` | one of `30, 45, 60, 90, 120` — anything else the model writes snaps to the nearest |
+| `beats` | exactly `take_seconds / 5` strings, in order, each what happens NEXT in the same unbroken shot: led by the movement, naming the sound, with the time of day and the weather stated once in the first beat and never changed |
+
+On the board the shot then carries `take_seconds`, `duration_s == take_seconds`,
+`frames == take_seconds × 24 + 1`, `beat_lines` (the beats as the model wrote
+them — what a re-plan is shown) and `beats` (each beat assembled in the shot's
+own register — the camera law, the face law, the soundscape and the character
+trigger on every beat, the settle on the last written beat only). The shot's
+`prompt` is its first beat. A shot without `take_seconds` is untouched by any
+of this.
+
+**Shaping, never rejecting.** A beat count that is off is padded with blanks
+(the panel holds the previous moment on a blank beat) or trimmed; the planner
+says so in its warnings. A `take_seconds` with no written beat at all is not a
+take — the shot is planned as an ordinary one. A hand-edited `take_seconds`
+that is not one of the five lengths is the one thing the validator refuses
+(`bad_take_seconds`), because the job would otherwise silently render a normal
+clip of the wrong length. The face law scrubs every beat, not just the
+description.
+
+**How it renders.** `shot_to_job` posts the One Shot as ONE job —
+`take_seconds` plus the `beats` JSON, padded to the take's count and each
+written beat composed with the shot's location, wardrobe, framing and eyeline
+(a later part is rendered from its beats alone). The panel then does exactly
+what it does for a take from the Video tab: parts that continue from each
+other's last frame — 15 s parts (three beats) on H3, 10 s parts (two beats) on
+LTX — with the light lock and the drift retake. The estimate prices the take
+by those parts (`take_parts`): on H3 the measured 15 s cell per part, on LTX
+the take's seconds. The take is exempt from the long-shot windows chain.
+
+**Limits.** 30–120 s in the five steps above; one or two per film; the
+planner's laws (camera, faces, dialogue, silence) apply to every beat; the
+whole-film take and a One Shot do not nest — if a film that contains a One
+Shot is collapsed into one take, its beats are kept in order rather than
+dropped.
+
+The tests are `test_storyboard_one_shot.py`; the whole-film take is covered in
+`test_take.py`.
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 363649d..c7867fd 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -15737,10 +15737,17 @@ def _sb_h3_available() -> bool:
# ONE TAKE — a clip longer than one pass, on either engine
# ---------------------------------------------------------------------------
# The user picks a LENGTH (30 s … 2 min) and writes BEATS, one line per five
-# seconds. Nothing else is new: on LTX the take is the existing windows chain
-# (one prompt per 121-frame window); on H3 it is 15-second parts, each three
-# 5-second windows with their own prompt, each part starting from the last
-# frame of the one before (H3's first-frame conditioning), joined at the end.
+# seconds. Nothing else is new: on BOTH engines the take is PARTS chained by
+# last-frame handoff — each part an ordinary render, starting from the last
+# frame of the one before (i2v, anchored), joined at the end. On H3 a part is
+# 15 s (three beats); on LTX a part is 10 s (two beats, 241 frames, the
+# longest single render every quality prices). LTX used to render a take as
+# the windows chain (one Extend context per 121-frame window, 2026-09-06);
+# measured on a 30 s take it turned to mush after the first window — faces
+# dissolved, the audio went near silent — because Extend carries a latent
+# context that degrades on every hop, while a fresh i2v from a clean frame
+# starts every part at full quality. The windows chain stays for users who
+# choose "Long clips → windows" explicitly; a take no longer uses it.
# The words "windows", "chain" and "parts" never reach the user; they see a
# length, beats, and an honest time.
TAKE_SECONDS = (30, 45, 60, 90, 120)
@@ -15748,6 +15755,8 @@ TAKE_BEAT_SECONDS = 5
TAKE_H3_PART_LENGTH = "15s" # the longest single H3 render
TAKE_H3_BEATS_PER_PART = 3
TAKE_H3_PART_FRAMES = 362
+TAKE_LTX_BEATS_PER_PART = 2 # 10 s — the LTX_LENGTHS "10s" cell
+TAKE_LTX_PART_FRAMES = 241 # 10 s × 24 fps + 1 (the 8k+1 grid)
def take_plan(seconds, engine: str) -> dict | None:
@@ -15760,15 +15769,26 @@ def take_plan(seconds, engine: str) -> dict | None:
return None
beats = seconds // TAKE_BEAT_SECONDS
eng = "h3" if (engine or "ltx") == "h3" else "ltx"
+ per_part = TAKE_H3_BEATS_PER_PART if eng == "h3" else TAKE_LTX_BEATS_PER_PART
+ n_parts = -(-beats // per_part)
+ parts = [list(range(i * per_part, min(beats, (i + 1) * per_part))) for i in range(n_parts)]
if eng == "h3":
- n_parts = -(-beats // TAKE_H3_BEATS_PER_PART)
- parts = [list(range(i * TAKE_H3_BEATS_PER_PART,
- min(beats, (i + 1) * TAKE_H3_BEATS_PER_PART))) for i in range(n_parts)]
frames = TAKE_H3_PART_FRAMES * n_parts
+ part_frames = TAKE_H3_PART_FRAMES
else:
- parts = [list(range(beats))]
frames = seconds * 24 + 1 # 8k+1 for every TAKE_SECONDS value
- return {"seconds": seconds, "beats": beats, "parts": parts, "frames": frames, "engine": eng}
+ part_frames = TAKE_LTX_PART_FRAMES
+ # `frames` is the WHOLE take (the sidecar, the gallery, the estimate);
+ # `part_frames` is what one full part asks the engine for. A trailing
+ # one-beat LTX part (45 s → 2,2,2,2,1) renders take_ltx_part_frames(1).
+ return {"seconds": seconds, "beats": beats, "parts": parts, "frames": frames,
+ "part_frames": part_frames, "beats_per_part": per_part, "engine": eng}
+
+
+def take_ltx_part_frames(n_beats: int) -> int:
+ """Frames for an LTX part of `n_beats` beats: 241 for a full two-beat
+ part, 121 for the one-beat tail a 45 s take ends on — always 8k+1."""
+ return max(1, int(n_beats)) * TAKE_BEAT_SECONDS * 24 + 1
def take_beats(raw, n: int) -> list[str]:
@@ -15867,15 +15887,27 @@ def take_drift(path, duration: float | None = None) -> dict:
def take_estimate_minutes(engine: str, quality: str, seconds) -> float | None:
"""Wall clock for the whole take, from the same cost model every other
- estimate uses. None when this Mac has no number for it (LTX windows are
- not priced yet — the chain's extends have no measured model)."""
+ estimate uses: parts × the single-clip price of one part. H3 prices the
+ measured 15 s cell; LTX prices the `<quality>_10s` cell of LTX_TIERS (241
+ frames — exactly what one part renders), the one-beat tail at its 5 s
+ cell. None when this Mac has no number for it."""
plan = take_plan(seconds, engine)
if not plan:
return None
if plan["engine"] == "h3":
per = _sb_h3_cost(quality or "standard", TAKE_H3_PART_LENGTH)
return None if per is None else round(per * len(plan["parts"]) / 60.0, 1)
- return None
+ q = (quality or "").strip().lower()
+ if q not in LTX_QUALITIES:
+ q = LTX_QUALITY_DEFAULT
+ total = 0.0
+ for idxs in plan["parts"]:
+ cell = LTX_TIERS.get(f"{q}_10s" if len(idxs) >= TAKE_LTX_BEATS_PER_PART else f"{q}_5s") or {}
+ per = cell.get("eta_min")
+ if per is None:
+ return None
+ total += float(per)
+ return round(total, 1)
def _sb_h3_cost(quality_key: str, length_key: str):
@@ -16591,7 +16623,7 @@ def _sb_take_concept(concept: str, seconds: int) -> str:
one movement per five-second beat, and the camera never cuts."""
c = str(concept or "").strip()
beats = int(seconds) // TAKE_BEAT_SECONDS
- return (f"{c}\n\nONE TAKE. The whole film is a single continuous shot of "
+ return (f"{c}\n\nONE SHOT. The whole film is a single continuous shot of "
f"{int(seconds)} seconds that never cuts. Write it as {beats} beats of "
f"five seconds each, in order; each beat is what happens NEXT in the "
f"same unbroken shot — lead with the movement (of the subject, of the "
@@ -16675,7 +16707,7 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:
if _take_secs in TAKE_SECONDS:
n_shots = _take_secs // TAKE_BEAT_SECONDS
concept = _sb_take_concept(concept, _take_secs)
- push(f"[storyboard] one take of {_take_secs}s — planning {n_shots} beats")
+ push(f"[storyboard] one shot of {_take_secs}s — planning {n_shots} beats")
storyboard.save_storyboard(STATE_DIR, board)
push(f"[storyboard] planning {n_shots} shots — "
f"the renderer's memory is borrowed for about a minute")
@@ -20546,10 +20578,12 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
requested_upscale_method = "lanczos"
if requested_upscale_method not in ("lanczos", "pipersr"):
requested_upscale_method = "lanczos"
- # ONE TAKE (see take_plan). Read before the fields it overrides: on LTX it
- # is the windows chain with one prompt per window; on H3 it is 15 s parts
- # that continue from each other, run by run_take_job_inner. The form's own
- # length pill is overruled — a take IS the length.
+ # ONE TAKE (see take_plan). Read before the fields it overrides: on both
+ # engines it is parts that continue from each other's last frame, run by
+ # run_take_job_inner — 15 s parts on H3, 10 s parts on LTX. The form's own
+ # length pill is overruled — a take IS the length. `take_light_lock=off`
+ # leaves the beats as written (no continuity sentence); `take_retake=off`
+ # skips the one drift retake per part.
_take: dict | None = None
_take_secs_raw = f("take_seconds", "")
if _take_secs_raw and _take_secs_raw not in ("0", "off"):
@@ -20558,10 +20592,12 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
if _take is None:
push(f"take_seconds={_take_secs_raw!r} is not one of {TAKE_SECONDS} — rendering a normal clip")
else:
- _lock = take_light_lock(f("prompt", ""))
- _take["beat_prompts"] = [(b + " " + _lock) if b else b
+ _lock_on = f("take_light_lock", "on").strip().lower() not in ("off", "0", "false", "no")
+ _lock = take_light_lock(f("prompt", "")) if _lock_on else ""
+ _take["beat_prompts"] = [(b + " " + _lock) if (b and _lock) else b
for b in take_beats(f("beats", ""), _take["beats"])]
_take["light_lock"] = _lock
+ _take["retake"] = f("take_retake", "on").strip().lower() not in ("off", "0", "false", "no")
if _take["engine"] == "h3":
# A take is 15 s parts whatever the form said; without a quality
# the tier composer fell back to draft_3s and every part became
@@ -20570,11 +20606,19 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
if not h3_compose_tier(f("h3_quality", ""), TAKE_H3_PART_LENGTH):
form["h3_quality"] = ["draft"]
form["h3_chain_prompts"] = [json.dumps(
- [_take["beat_prompts"][i] or (TAKE_HOLD + " " + _lock) for i in _take["parts"][0]])]
+ [_take["beat_prompts"][i] or (TAKE_HOLD + (" " + _lock if _lock else ""))
+ for i in _take["parts"][0]])]
else:
- form["temporal_mode"] = ["windows"]
- form["frames"] = [str(_take["frames"])]
- form["window_prompts"] = [json.dumps(_take["beat_prompts"])]
+ # An LTX take is 10 s parts by last-frame handoff, NOT the
+ # windows chain: the parent job carries one part's frames
+ # (what the estimate and the memory plan are sized to) and
+ # the runner derives every part. A leftover
+ # temporal_mode=windows / window_prompts from the form (the
+ # Storyboard door used to send them for a long shot) is
+ # overruled here so the take cannot fall back into the chain.
+ form["frames"] = [str(TAKE_LTX_PART_FRAMES)]
+ form["temporal_mode"] = ["native"]
+ form["window_prompts"] = [""]
temporal_mode = f("temporal_mode", "native").strip().lower()
# SLIDING WINDOWS ride the same control as Long Clip Boost — one "Long
# clips" row, three answers — and are stored as `long_mode` so the render
@@ -23814,14 +23858,20 @@ def _run_windows_chain(job: dict, p: dict, plan: dict, first: Path,
def run_take_job_inner(job: dict) -> None:
- """An H3 take: N parts of 15 s, each three beats, each continuing from the
- last frame of the part before, joined into one clip. Every part is an
- ORDINARY H3 render through run_h3_job_inner with a derived job, so LoRAs,
- Turbo, the export size and the log all behave as they do for a single
- clip. Stop between parts is honoured through the parent's
- `cancel_requested` (a running part dies with the H3 process group)."""
+ """One take on either engine: N parts, each continuing from the last frame
+ of the part before, joined into one clip. H3 parts are 15 s (three beats)
+ and render through run_h3_job_inner with `h3_chain_prompts`; LTX parts are
+ 10 s (two beats, 241 frames) and render through run_job_inner as ordinary
+ t2v / i2v jobs — the first from the user's own anchor image when the job
+ came in as i2v with one, every later part i2v from the previous part's
+ last frame, anchored. Every part is an ORDINARY render with a derived job,
+ so LoRAs, characters, the quality tier, the export size and the log all
+ behave as they do for a single clip. Stop between parts is honoured
+ through the parent's `cancel_requested` (a running part dies with its
+ engine process)."""
p = job["params"]
take = p["take"]
+ engine = "h3" if take.get("engine") == "h3" else "ltx"
beats = list(take.get("beat_prompts") or [])
parts = take["parts"]
n_parts = len(parts)
@@ -23832,48 +23882,88 @@ def run_take_job_inner(job: dict) -> None:
ff = str(FFMPEG)
outs: list[str] = []
last_png: str | None = None
- push(f"[take] {take['seconds']} s · {take['beats']} beats · {n_parts} parts on H3")
- for k, idxs in enumerate(parts):
- if job.get("cancel_requested"):
- raise RuntimeError("stopped between parts")
- lock0 = take.get("light_lock") or take_light_lock(p.get("prompt") or "")
- chain = [(beats[i] if i < len(beats) else "") or (TAKE_HOLD + " " + lock0) for i in idxs]
- child_params = dict(p)
- child_params.update({
+ # The continuity lock: "" when the user switched it off (then blank beats
+ # hold with TAKE_HOLD alone and a retake does not double anything).
+ lock = take.get("light_lock")
+ if lock is None:
+ lock = take_light_lock(p.get("prompt") or "")
+ hold = (TAKE_HOLD + " " + lock) if lock else TAKE_HOLD
+ retake_allowed = take.get("retake", True) is not False
+ # The first part may start from the user's anchor image: an i2v job with
+ # an image is a take that opens on that frame. H3's i2v is the same
+ # contract for the first part (its --first-frame conditioning).
+ first_image = (p.get("image") or "") if p.get("mode") in ("i2v", "i2v_clean_audio") else ""
+ if first_image and not Path(first_image).is_file():
+ first_image = ""
+ render_part = run_h3_job_inner if engine == "h3" else run_job_inner
+ push(f"[take] one shot · {take['seconds']} s · {take['beats']} beats · {n_parts} parts on "
+ f"{'H3' if engine == 'h3' else 'LTX'}"
+ + (" · opens on the reference image" if first_image else ""))
+
+ def _child_params(k: int, idxs: list[int], chain: list[str]) -> dict:
+ cp = dict(p)
+ cp.update({
"take": None,
- "h3_chain_prompts": chain,
- "prompt": chain[0],
- "label": f"{label or 'take'} · part {k + 1} of {n_parts}",
- "mode": "i2v" if last_png else p.get("mode", "t2v"),
+ "label": f"{label or 'one shot'} · part {k + 1} of {n_parts}",
"open_when_done": False,
})
if last_png:
- child_params["image"] = last_png
+ cp["mode"] = "i2v"
+ cp["image"] = last_png
+ elif first_image:
+ cp["mode"] = "i2v"
+ cp["image"] = first_image
+ else:
+ cp["mode"] = "t2v"
+ if engine == "h3":
+ cp["h3_chain_prompts"] = chain
+ cp["prompt"] = chain[0]
+ else:
+ # One prompt per part: its beats in order. A part is a plain LTX
+ # render — never the windows chain, never a Long Clip Boost the
+ # profile did not ask for on its own.
+ cp["prompt"] = " ".join(c for c in chain if c)
+ cp["frames"] = take_ltx_part_frames(len(idxs))
+ cp["h3_chain_prompts"] = []
+ cp["temporal_mode"] = "native"
+ cp["long_mode"] = "native"
+ cp["window_prompts"] = []
+ if cp["mode"] == "i2v":
+ cp["i2v_reference_mode"] = "anchor"
+ return cp
+
+ for k, idxs in enumerate(parts):
+ if job.get("cancel_requested"):
+ raise RuntimeError("stopped between parts")
+ chain = [(beats[i] if i < len(beats) else "") or hold for i in idxs]
+ child_params = _child_params(k, idxs, chain)
child = {"id": f"{job['id']}-p{k + 1}", "params": child_params,
- "status": "running", "created_at": job.get("created_at")}
+ "status": "running", "created_at": job.get("created_at"),
+ "started_ts": time.time()}
push(f"[take] beats {idxs[0] + 1}–{idxs[-1] + 1} of {take['beats']} · part {k + 1} of {n_parts}"
+ (" · continues from the last frame" if last_png else ""))
- run_h3_job_inner(child)
+ render_part(child)
out = child.get("output_path")
if not out or not Path(out).is_file():
raise RuntimeError(f"part {k + 1} produced no clip")
# CONTINUITY CHECK: did the light move across this part? One retake
# with the lock said twice and a fresh seed; keep the steadier clip.
+ # Skipped when the user turned retakes off.
drift = take_drift(out)
- if drift.get("drifted") and not job.get("cancel_requested"):
+ if drift.get("drifted") and retake_allowed and not job.get("cancel_requested"):
push(f"[take] part {k + 1}: the light drifted (luma {drift['luma_first']} → "
- f"{drift['luma_last']}) — retaking it once with the continuity lock doubled")
- lock = take.get("light_lock") or take_light_lock(p.get("prompt") or "")
- retry_params = dict(child_params)
- retry_params["h3_chain_prompts"] = [(c + " " + lock) if c else c for c in chain]
- retry_params["prompt"] = retry_params["h3_chain_prompts"][0]
+ f"{drift['luma_last']}) — retaking it once"
+ + (" with the continuity lock doubled" if lock else " with a fresh seed"))
+ chain2 = [(c + " " + lock) if (c and lock) else c for c in chain]
+ retry_params = _child_params(k, idxs, chain2)
try:
retry_params["seed"] = str(int(retry_params.get("seed") or 0) + 101)
except (TypeError, ValueError):
retry_params["seed"] = "-1"
retry = {"id": f"{job['id']}-p{k + 1}r", "params": retry_params,
- "status": "running", "created_at": job.get("created_at")}
- run_h3_job_inner(retry)
+ "status": "running", "created_at": job.get("created_at"),
+ "started_ts": time.time()}
+ render_part(retry)
out2 = retry.get("output_path")
d2 = take_drift(out2) if out2 and Path(out2).is_file() else {"delta": 9.0}
if d2.get("delta", 9.0) < drift["delta"]:
@@ -23891,10 +23981,13 @@ def run_take_job_inner(job: dict) -> None:
set_hidden(str(out2), True)
except Exception: # noqa: BLE001
pass
+ elif drift.get("drifted"):
+ push(f"[take] part {k + 1}: the light drifted (luma {drift.get('luma_first')} → "
+ f"{drift.get('luma_last')}) — retakes are off, keeping it")
job.setdefault("take_drift", []).append(drift)
outs.append(out)
- # Parts are working files: kept, hidden from the gallery. The take is
- # the output.
+ # Parts are working files: kept, hidden from the gallery. The one shot
+ # is the output.
try:
set_hidden(str(out), True)
except Exception: # noqa: BLE001
@@ -23919,15 +24012,27 @@ def run_take_job_inner(job: dict) -> None:
except (OSError, ValueError):
side = {}
side.update({
- "mode": p.get("mode", "t2v"), "engine": "h3", "prompt": p.get("prompt") or "",
+ "mode": p.get("mode", "t2v"), "engine": engine, "prompt": p.get("prompt") or "",
"label": label, "elapsed_sec": round(time.time() - t0, 1),
"frames": take["frames"], "seconds": take["seconds"],
- "take": {"seconds": take["seconds"], "beats": beats, "parts": outs, "engine": "h3"},
- "h3_chain_prompts": beats,
+ "take": {"seconds": take["seconds"], "beats": beats, "parts": outs, "engine": engine,
+ "beats_per_part": take.get("beats_per_part")
+ or (TAKE_H3_BEATS_PER_PART if engine == "h3" else TAKE_LTX_BEATS_PER_PART),
+ "part_frames": take.get("part_frames"),
+ "light_lock": lock, "retake": retake_allowed},
+ "temporal_mode": "native", "long_mode": "native", "window_prompts": [],
})
+ if engine == "h3":
+ side["h3_chain_prompts"] = beats
+ # The last part's sidecar names ITS image — a handoff frame in the state
+ # dir. The one shot's own image is the user's anchor, or nothing.
+ if first_image:
+ side["image"] = first_image
+ else:
+ side.pop("image", None)
write_sidecar(final.with_suffix(final.suffix + ".json"), side)
job["output_path"] = str(final)
- push(f"[take] done in {round(time.time() - t0)}s → {final.name}")
+ push(f"[take] one shot done in {round(time.time() - t0)}s → {final.name}")
def run_job_inner(job: dict) -> None:
@@ -23948,6 +24053,11 @@ def run_job_inner(job: dict) -> None:
if p.get("take"):
return run_take_job_inner(job)
return run_h3_job_inner(job)
+ # ONE TAKE on LTX: parts by last-frame handoff, each an ordinary render
+ # back through this function with `take` cleared. Before the stale-engine
+ # gate on purpose — the parts hit it one by one, with the same words.
+ if p.get("take"):
+ return run_take_job_inner(job)
# STALE-ENGINE GATE (fleet: 'Model type gemma4_unified not supported.',
# 19 events / 6 installs, every one a legacy install whose vendored engine
# predates the Gemma 4 tower). The render would die at first text-encode
@@ -25657,11 +25767,15 @@ def run_job_inner(job: dict) -> None:
f"{width}x{height} {model_frames}f{temporal_suffix}")
if windows_plan:
- # The first window lands beside the final name; the chain writes
- # `raw_out` itself once the last window is trimmed to length.
+ # The first window is a working file like every other piece of the
+ # chain, so it lives in the job's `.windows/` folder — a `_w0.mp4`
+ # beside the final name showed up in the gallery as its own clip
+ # while the take was still forming (the chain never removed it).
+ # The chain writes `raw_out` itself once the last window is trimmed.
job_spec["params"]["frames"] = windows_plan["window"]
- job_spec["params"]["output_path"] = str(
- raw_out.with_name(raw_out.stem + "_w0" + raw_out.suffix))
+ _w0_dir = OUTPUT / ".windows" / str(job.get("id") or "take")
+ _w0_dir.mkdir(parents=True, exist_ok=True)
+ job_spec["params"]["output_path"] = str(_w0_dir / (raw_out.stem + "_w0" + raw_out.suffix))
result = HELPER.run(job_spec)
if "seed_used" in result:
push(f"seed used: {result['seed_used']}")
diff --git a/panel/routes_meta.py b/panel/routes_meta.py
index 445d699..fd5687b 100644
--- a/panel/routes_meta.py
+++ b/panel/routes_meta.py
@@ -111,10 +111,16 @@ def get_take_estimate(h, parsed) -> None:
"choices": list(P.TAKE_SECONDS)}, 400)
return
minutes = P.take_estimate_minutes(engine, quality, seconds)
+ # `parts` on both engines: H3 15 s parts, LTX 10 s parts (last-frame
+ # handoff, see take_plan). An LTX take is ordinary distilled renders, so
+ # it needs no Q8 pack any more — only an HQ quality would, and that is
+ # the quality chip's own gate.
h._json({"ok": True, "seconds": plan["seconds"], "beats": plan["beats"],
- "parts": len(plan["parts"]), "engine": plan["engine"], "frames": plan["frames"],
+ "parts": len(plan["parts"]), "beats_per_part": plan["beats_per_part"],
+ "part_frames": plan["part_frames"], "engine": plan["engine"],
+ "frames": plan["frames"],
"minutes": minutes, "eta": (P._fmt_eta(minutes) if minutes else None),
- "needs_q8": plan["engine"] == "ltx"})
+ "needs_q8": False})
@get("/panel/bug-context")
diff --git a/storyboard.py b/storyboard.py
index 4e08fae..5753970 100644
--- a/storyboard.py
+++ b/storyboard.py
@@ -585,10 +585,24 @@ def validate_storyboard_detail(
f"{where}: {pacing}.",
n=n_for_ui, field="prompt")
+ # A ONE SHOT (take_seconds + beats) is never rejected for its beat
+ # count — take_beats_for() pads blanks and trims extras at job time —
+ # but a take_seconds that is present and not one of TAKE_SECONDS is
+ # an error: shot_to_job would drop the take and render a normal clip
+ # of the wrong length, silently.
+ _ts_raw = s.get("take_seconds")
+ if _ts_raw not in (None, "", 0, "0", "off", False) \
+ and take_seconds_of(s) is None:
+ add("bad_take_seconds",
+ f"{where}: take_seconds must be one of {', '.join(map(str, TAKE_SECONDS))} "
+ f"(got {_ts_raw!r})",
+ n=n_for_ui, field="take_seconds", take_seconds=_ts_raw,
+ valid=list(TAKE_SECONDS))
+
dur = s.get("duration_s")
# A take shot is as long as the take (up to 2 min); every other shot
# is one clip and stops at 60.
- _dur_cap = max(TAKE_SECONDS) if s.get("take_seconds") in TAKE_SECONDS else 60
+ _dur_cap = max(TAKE_SECONDS) if take_seconds_of(s) else 60
if not isinstance(dur, (int, float)) or not (0 < float(dur) <= _dur_cap):
add("bad_duration",
f"{where}: duration_s must be between 0 and {_dur_cap} (got {dur!r})",
@@ -782,9 +796,10 @@ def shot_render_secs(shot: dict, policy_pass: dict, *, h3_cost=None) -> float:
"""
dur = float(shot.get("duration_s") or 0)
quality = policy_pass.get("quality", "balanced")
- if shot.get("take_seconds") in TAKE_SECONDS and shot_engine(shot) == "h3":
+ take_secs = take_seconds_of(shot)
+ if take_secs and shot_engine(shot) == "h3":
# A take on H3 is parts of 15 s; price the parts, not the duration.
- parts = -(-(int(shot["take_seconds"]) // TAKE_BEAT_SECONDS) // 3)
+ parts = take_parts(shot)
qk = h3_quality_for(quality)
got = None
if h3_cost is not None:
@@ -794,6 +809,12 @@ def shot_render_secs(shot: dict, policy_pass: dict, *, h3_cost=None) -> float:
got = None
per = float(got) if got else _H3_SECS_PER_VIDEO_SEC.get(qk, 109.0) * _H3_LENGTH_SECONDS["15s"]
return per * parts
+ if take_secs:
+ # A take on LTX is 10 s parts (two beats each; 45 s ends on a one-beat
+ # part) rendered back to back, and the parts add up to the take — so
+ # it is priced by the take's own seconds, never by a `duration_s` a
+ # hand edit may have left behind.
+ return float(take_secs) * _SECS_PER_VIDEO_SEC.get(quality, 60.0)
if shot_engine(shot) == "h3":
lk = h3_length_for(dur)
qk = h3_quality_for(quality)
@@ -1319,24 +1340,95 @@ CHARACTER_QUALITY_FOR_PASS: dict[str, str] = {
# ---- ONE TAKE on the board --------------------------------------------------
-# A film that is one shot: the planner writes one movement per five-second
-# beat (as it does for a soundtrack slot), and the board keeps ONE shot that
-# carries the beats. shot_to_job turns it into the panel's take fields, so the
-# render is the same take a person gets from the Video tab.
+# A shot that is one unbroken take: `take_seconds` (30 / 45 / 60 / 90 / 120)
+# plus `beats`, one prompt per five seconds. Two ways it gets onto a board:
+# * the WHOLE FILM is one take — the planner writes N beat-shots and
+# `collapse_take` folds them into one shot (the Video tab's take, by way
+# of the Storyboard door);
+# * ONE SHOT inside an ordinary film — the planner chooses it as a cinematic
+# tool (a walk-and-talk, a chase, a confession; "One Shot" in the UI) and
+# emits the shot with `take_seconds` + `beats` of its own, among normal
+# 3 / 5 / 10 s shots. It stays ONE shot: one card, one job, one clip.
+# Either way shot_to_job turns it into the panel's take fields and the panel
+# renders it as parts that continue from each other's last frame: 15 s parts
+# (three beats) on H3, 10 s parts (two beats) on LTX. The part sizes here
+# mirror mlx_ltx_panel.take_plan and exist so the estimate can count parts
+# without importing the panel.
TAKE_BEAT_SECONDS = 5
TAKE_SECONDS = (30, 45, 60, 90, 120)
+TAKE_BEATS_PER_PART = {"h3": 3, "ltx": 2}
+
+
+def take_seconds_of(shot: dict) -> int | None:
+ """The take length a shot carries, or None when it is an ordinary shot.
+
+ Strict on purpose: only a value in TAKE_SECONDS counts. Anything else
+ (None, 0, "off", 40) is not a take — `validate_storyboard_detail` reports
+ a present-but-illegal value as `bad_take_seconds`, so a hand-edited board
+ cannot silently render a normal clip where a take was meant.
+ """
+ if not isinstance(shot, dict):
+ return None
+ raw = shot.get("take_seconds")
+ if raw is None or isinstance(raw, bool):
+ return None
+ try:
+ secs = int(raw)
+ except (TypeError, ValueError):
+ return None
+ return secs if secs in TAKE_SECONDS else None
+
+
+def take_beats_for(shot: dict, seconds: int | None = None) -> list[str]:
+ """Exactly take_seconds/5 beat prompts for a take shot: extras are dropped,
+ missing ones are blank (the panel holds the previous moment on a blank
+ beat). A newline-separated string is accepted as well as a list, so a
+ beats box pasted by hand shapes up the same way the planner's list does.
+ `[]` for a shot that is not a take."""
+ secs = seconds if seconds in TAKE_SECONDS else take_seconds_of(shot)
+ if not secs:
+ return []
+ n = secs // TAKE_BEAT_SECONDS
+ raw = shot.get("beats")
+ if isinstance(raw, str):
+ items = [ln.strip() for ln in raw.splitlines()]
+ elif isinstance(raw, (list, tuple)):
+ items = [str(b or "").strip() for b in raw]
+ else:
+ items = []
+ items = items[:n]
+ return items + [""] * (n - len(items))
+
+
+def take_parts(shot: dict) -> int:
+ """How many renders the panel makes for a take shot on its engine: beats
+ in threes on H3 (15 s parts), in twos on LTX (10 s parts). 0 for an
+ ordinary shot. 45 s on LTX is 5 parts (2,2,2,2,1), matching take_plan."""
+ secs = take_seconds_of(shot)
+ if not secs:
+ return 0
+ per = TAKE_BEATS_PER_PART.get(shot_engine(shot), TAKE_BEATS_PER_PART["ltx"])
+ return -(-(secs // TAKE_BEAT_SECONDS) // per)
def collapse_take(shots: list[dict], seconds: int) -> list[dict]:
"""The planner's N beat-shots become ONE take shot: the first shot's
identity (mode, character, refs, title) with `beats` = every shot's own
- prompt, padded to the take's beat count, `duration_s` = the take."""
+ prompt, padded to the take's beat count, `duration_s` = the take.
+
+ A beat-shot that is itself a take (the planner chose a One Shot inside a
+ film that was then asked to be one take) contributes its own beats in
+ order rather than just its first, so nothing it wrote is dropped."""
beats_n = max(1, int(seconds) // TAKE_BEAT_SECONDS)
items = [s for s in (shots or []) if isinstance(s, dict)]
if not items:
return []
first = dict(items[0])
- beats = [str(s.get("prompt") or "").strip() for s in items][:beats_n]
+ beats: list[str] = []
+ for s in items:
+ nested = [b for b in take_beats_for(s) if b] if take_seconds_of(s) else []
+ beats += nested or [str(s.get("prompt") or "").strip()]
+ beats = beats[:beats_n]
beats += [""] * (beats_n - len(beats))
first.update({
"n": 1,
@@ -1501,13 +1593,22 @@ def shot_to_job(shot: dict, policy_pass: dict, *,
# identifies itself in the bottom pane with no bottom-pane code at all. `session_tag`
# carries the provenance the badge and the gallery group on. Both keys are already in
# make_job's allowlist — no allowlist edit, which is the point.
- # ONE TAKE. The shot carries `take_seconds` + `beats`; the panel's make_job
- # does the rest (LTX: the windows chain; H3: 15 s parts that continue).
- if shot.get("take_seconds") in TAKE_SECONDS:
- job["take_seconds"] = str(int(shot["take_seconds"]))
- job["beats"] = json.dumps([str(b or "") for b in (shot.get("beats") or [])])
+ # ONE TAKE / ONE SHOT. The shot carries `take_seconds` + `beats`; the
+ # panel's make_job does the rest (parts by last-frame handoff: 10 s on
+ # LTX, 15 s on H3). Exactly ONE job for the whole take — the split into
+ # parts is the panel's, never the board's. The beats go out padded /
+ # trimmed to the take's count, and each written beat is composed the way
+ # the main prompt is (trigger, wardrobe, framing, eyeline, place): a later
+ # part is rendered from ITS beats alone, so a location that reached only
+ # beat 1 would be a different room by part 2.
+ take_secs = take_seconds_of(shot)
+ if take_secs:
+ job["take_seconds"] = str(take_secs)
+ job["beats"] = json.dumps([
+ compose_shot_prompt(dict(shot, prompt=b), locations, wardrobe) if b else ""
+ for b in take_beats_for(shot, take_secs)])
if engine != "h3":
- job["frames"] = int(shot["take_seconds"]) * 24 + 1
+ 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.
@@ -1522,8 +1623,11 @@ def shot_to_job(shot: dict, policy_pass: dict, *,
# Extend cannot re-inject an image per window, so an anchored long shot is
# anchored by its first window only — the still opens it, the chain
# carries it. See ltx_windows.py.
+ # A take is exempt: it is parts by last-frame handoff, not the chain, and
+ # the panel overrules a stray windows flag on a take anyway — this keeps
+ # the job dict honest about what will run.
if long_windows and engine != "h3" and int(job.get("frames") or 0) > 121 \
- and job["mode"] in ("t2v", "i2v"):
+ and job["mode"] in ("t2v", "i2v") and not take_secs:
job["temporal_mode"] = "windows"
inv = [s for s in (style.strip(), str((shot.get("location") or "")).strip()) if s]
if inv:
diff --git a/storyboard_planner.py b/storyboard_planner.py
index 0b0bf6f..6aa5107 100644
--- a/storyboard_planner.py
+++ b/storyboard_planner.py
@@ -427,6 +427,63 @@ fingers gripping objects, and never ask for on-screen text.
"""
+# ONE SHOT — a take that never cuts, offered to the planner as a cinematic tool it may
+# reach for INSIDE an ordinary film. Before this the only way a take reached the board
+# was the whole film being one (`_sb_take_concept` in the panel + collapse_take); the
+# owner's ask was that the director could plan one shot of a film as a real one-shot
+# "so it looks really like a real movie instead of just 5-second clips one after the
+# other". The field names stay `take_seconds` + `beats` — the same wire the Video tab's
+# take and the whole-film take already use — so the panel renders it with no new path.
+_ONE_SHOT = """\
+ONE SHOT - a take that never cuts, used as a cinematic tool
+
+A One Shot is a single unbroken take of 30 to 120 seconds inside an otherwise ordinary
+film: the camera never cuts, ONE movement happens per 5-second beat, and the WORLD changes
+around the subject (a door opens, a street empties, someone steps into frame) while the
+subject, the camera position and the light stay continuous from one beat into the next.
+It is the right tool for a walk-and-talk, a chase or a POV ride, a monologue or a
+confession, a reveal that needs unbroken time, or an arrival through a place. It is the
+WRONG tool for a montage, for cross-cutting between places, and for anything that needs a
+reverse angle or a second camera position - those are ordinary shots. Use it at most once
+or twice per film, only where unbroken time earns something, and never for the whole film
+unless the brief asks for one take. A One Shot counts as ONE shot in the shot count.
+
+How to write one. The shot object keeps every key above and adds exactly two:
+ "take_seconds" one of 30, 45, 60, 90, 120
+ "beats" a list of EXACTLY take_seconds / 5 strings (30 -> 6, 60 -> 12), in
+ order, each one what happens NEXT in the same unbroken shot. Lead every
+ beat with the movement (of the subject, the camera or the world), name
+ the sound in every beat, and state the time of day and the weather ONCE,
+ in the first beat, and never change them - no 'dawn breaks', no lights
+ coming on. Every beat starts exactly where the one before it ends: no
+ new angle, no jump in time.
+"description" is the whole take in one paragraph; "duration_s" equals "take_seconds".
+Every other shot in the film has NEITHER key.
+
+{
+ "n": 3,
+ "title": "Down the corridor",
+ "character_id": null,
+ "duration_s": 30,
+ "camera": "tracking",
+ "face": "medium",
+ "description": "Live-action, cinematic, a medium shot moving backwards ahead of a nurse in pale blue scrubs as she walks the length of a hospital corridor at night under flat fluorescent light, past a wheeled trolley, a closed pharmacy hatch and a waiting man who rises as she passes, to the double doors of a ward, which she pushes open onto a dim room with one lit bed.",
+ "settle": "she stands in the ward doorway, still, the lit bed ahead of her",
+ "soundscape": "Soft soles on vinyl flooring, the fluorescent hum, a distant call bell, the double doors swinging.",
+ "music": "N/A",
+ "take_seconds": 30,
+ "beats": [
+ "Night, flat fluorescent light. She walks straight toward the lens down the empty corridor, soles squeaking on the vinyl, hands loose at her sides.",
+ "A wheeled trolley rolls into frame from the left and she steps around it without slowing, its wheels rattling as it passes.",
+ "The closed pharmacy hatch slides past on her right; her eyes flick to it and then hold the lens again, the fluorescent hum steady.",
+ "A man on a bench rises as she reaches him and falls into step beside her, his coat brushing the wall, a call bell ringing somewhere behind them.",
+ "The corridor bends left and the double doors of the ward come into view ahead; her pace slows and she lifts one hand toward them.",
+ "She pushes the doors open and stops in the doorway, the doors swinging behind her, the one lit bed ahead of her in the dim room."
+ ]
+}
+"""
+
+
def _build_system_prompt(engine_hint: str, has_characters: bool,
allow_hidden: bool = False) -> str:
dialect = """\
@@ -457,7 +514,8 @@ outside the JSON. The object has exactly two keys:
"shots": [ <one object per shot, in story order> ]
}
-Each shot object has exactly these nine keys and no others:
+Each shot object has exactly these keys and no others (a One Shot adds two more - see
+ONE SHOT below):
"n" integer, 1-based, in order
"title" 2-5 words naming the beat
@@ -539,6 +597,10 @@ WRITE WHAT A LENS COULD SEE. "A testament to human ingenuity", "a symbol of hope
that feels lived-in", "his face etched with solitude" are unrenderable - they instruct
nothing. Replace each with the visible fact underneath it.
""")
+ # The One Shot exemplar is written in the H3 register; on an LTX-only film
+ # the style token would teach the exact word the LTX rules forbid.
+ parts.append(_ONE_SHOT if engine_hint != "ltx"
+ else _ONE_SHOT.replace("Live-action, cinematic, a medium shot", "A medium shot"))
if allow_hidden:
parts.append(
"FACES: this brief explicitly asked for hidden or obscured faces, so L11 is "
@@ -1080,6 +1142,12 @@ def _shot_to_model_view(shot: Dict[str, Any]) -> Dict[str, Any]:
("eyeline", "eyeline")):
if shot.get(src):
out[key] = shot[src]
+ # A ONE SHOT keeps its take on a re-plan. Shown as the model wrote it
+ # (`beat_lines`), not as assembled; a whole-film take collapsed from
+ # beat-shots has only `beats`, which is what it gets.
+ if shot.get("take_seconds"):
+ out["take_seconds"] = shot["take_seconds"]
+ out["beats"] = list(shot.get("beat_lines") or shot.get("beats") or [])
return out
@@ -1899,6 +1967,9 @@ def _fix_unbalanced_d(text: str) -> str:
def _snap_duration(value: Any, engine: str, default: float) -> float:
+ """An ORDINARY shot's length on its engine's grid. Never called for a One Shot: a
+ take is as long as its `take_seconds` (30-120 s) and this would clamp it to 60 and,
+ on H3, snap it to 15 — see coerce_spec()."""
try:
d = float(value)
except (TypeError, ValueError):
@@ -1911,6 +1982,87 @@ def _snap_duration(value: Any, engine: str, default: float) -> float:
return float(d)
+# ---- ONE SHOT: carrying `take_seconds` + `beats` through from the model ----------------
+# The table of legal take lengths and the beat length live in storyboard.py (the same
+# numbers the panel's take_plan uses); read from there, never copied — a second copy of
+# a number that has drifted once is the next drift waiting.
+
+def _take_table() -> Tuple[Tuple[int, ...], int]:
+ sb = _storyboard_module()
+ secs = tuple(getattr(sb, "TAKE_SECONDS", ()) or ()) if sb is not None else ()
+ beat = int(getattr(sb, "TAKE_BEAT_SECONDS", 0) or 0) if sb is not None else 0
+ return secs, beat
+
+
+def _coerce_take_seconds(value: Any) -> Optional[int]:
+ """A One Shot's length: the NEAREST legal take (ties to the shorter), or None when the
+ shot is not a take — absent, null, false, 0, "off", or unparseable. "30s" counts."""
+ if value is None or isinstance(value, bool):
+ return None
+ try:
+ secs = float(str(value).strip().lower().rstrip("s"))
+ except (TypeError, ValueError):
+ return None
+ if not secs > 0:
+ return None
+ table, _ = _take_table()
+ if not table:
+ return None
+ return int(min(table, key=lambda t: (abs(t - secs), t)))
+
+
+_BEAT_PREFIX_RE = re.compile(r"^\s*(?:beat\s*\d+\s*[:.)\-]\s*|\d+\s*[:.)]\s+)", re.IGNORECASE)
+
+
+def _beat_items(raw: Any) -> List[str]:
+ """Whatever the model wrote for `beats`, as a flat list of strings: a list of strings,
+ a list of {text|beat|description: ...} objects, a {"1": ..} object, or one
+ newline-separated string. A numbering prefix the model added ("3. ", "Beat 3:") is
+ the model's, not the shot's, and comes off."""
+ if isinstance(raw, dict):
+ raw = list(raw.values())
+ items: List[str] = []
+ if isinstance(raw, str):
+ items = [ln.strip() for ln in raw.splitlines()]
+ elif isinstance(raw, (list, tuple)):
+ for b in raw:
+ if isinstance(b, dict):
+ items.append(_first(b, ("text", "beat", "description", "prompt", "action")))
+ elif b is None:
+ items.append("")
+ else:
+ items.append(str(b).strip())
+ return [_BEAT_PREFIX_RE.sub("", b).strip() for b in items]
+
+
+def _coerce_beats(raw: Any, n: int) -> List[str]:
+ """Exactly `n` beat strings. Extras are dropped, missing ones are blank — the panel
+ holds the previous moment on a blank beat — so a miscounted list is padded or
+ trimmed, never rejected."""
+ items = _beat_items(raw)[:max(0, int(n))]
+ return items + [""] * (max(0, int(n)) - len(items))
+
+
+def _assemble_beats(shot: Dict[str, Any], lines: Sequence[str], style: str,
+ cast: Sequence[Dict[str, str]], sb: Any) -> List[str]:
+ """Each written beat in the shot's own register, as a prompt the panel can hand to a
+ part ON ITS OWN: the camera law, the face law and the soundscape ride on every beat
+ (a later part is rendered from its beats alone, not from the description), the
+ trigger is attached the way the main prompt gets it, and the settle rides on the LAST
+ written beat only — "completely finished before the shot ends" on beat 2 of 12 would
+ stop the take in its tracks. Blank beats stay blank."""
+ out: List[str] = []
+ last = max((i for i, ln in enumerate(lines) if ln), default=-1)
+ for i, line in enumerate(lines):
+ if not line:
+ out.append("")
+ continue
+ view = dict(shot, description=line,
+ settle=(shot.get("settle") or "") if i == last else "")
+ out.append(_reassemble_prompt(view, style, cast, sb))
+ return out
+
+
def _normalise_cast(characters: Optional[Iterable[Any]]) -> List[Dict[str, str]]:
"""Accept list_characters() records, plain ids, or {'id':..,'trigger':..} dicts."""
out: List[Dict[str, str]] = []
@@ -2137,8 +2289,37 @@ def coerce_spec(
eng = "ltx" if char else "h3"
n = len(shots) + 1
- dur = _snap_duration(s.get("duration_s") or s.get("duration") or s.get("seconds"),
- eng, duration_s)
+ # ONE SHOT? `take_seconds` snaps to the nearest legal take; `beats` shapes up to
+ # exactly take/5 entries (padded or trimmed, never rejected). A take with no
+ # written beat at all is not a take — the model put the key on an ordinary
+ # shot — and is planned as one.
+ take_raw = s.get("take_seconds") if "take_seconds" in s else s.get("take")
+ take = _coerce_take_seconds(take_raw)
+ beat_lines: List[str] = []
+ if take:
+ _, beat_secs = _take_table()
+ beat_lines = _coerce_beats(s.get("beats"), take // max(1, beat_secs))
+ if not any(beat_lines):
+ warnings.append("shot %d asked for a One Shot of %d s but wrote no beats — "
+ "planned as an ordinary shot" % (idx + 1, take))
+ take, beat_lines = None, []
+ else:
+ if str(take_raw).strip().lower().rstrip("s") != str(take):
+ warnings.append("shot %d: take_seconds %r is not a legal take length — "
+ "snapped to %d s" % (idx + 1, take_raw, take))
+ given = len(_beat_items(s.get("beats")))
+ if given != len(beat_lines):
+ warnings.append("shot %d wrote %d beats for a %d s One Shot (%d expected) "
+ "— %s" % (idx + 1, given, take, len(beat_lines),
+ "extras dropped" if given > len(beat_lines)
+ else "the missing ones hold the previous moment"))
+ if take:
+ # A One Shot is as long as its take. _snap_duration would clamp it to 60 and,
+ # on H3, snap it to 15 — the exact thing that must not happen to it.
+ dur = float(take)
+ else:
+ dur = _snap_duration(s.get("duration_s") or s.get("duration") or s.get("seconds"),
+ eng, duration_s)
camera, cam_forced = _camera_key(s.get("camera") or s.get("camera_move"))
if cam_forced and str(s.get("camera") or "").strip():
warnings.append("shot %d asked for camera %r, which is not one of %s — locked off"
@@ -2243,6 +2424,30 @@ def coerce_spec(
shot["prompt"] = _assemble_h3_prompt(
"%s The on-screen subject is %s." % (desc, char["trigger"]),
sound, music, camera, settle, face)
+ if take:
+ # The face law applies to every beat, not just the description: a later part
+ # is rendered from its beats alone, so a silhouette written into beat 9 is a
+ # silhouette on screen.
+ if face in ("close", "medium"):
+ cleaned: List[str] = []
+ for bi, line in enumerate(beat_lines):
+ l2, cut = _scrub_face_blocking(line) if line else (line, [])
+ for c in cut:
+ warnings.append("shot %d, beat %d: removed face-hiding framing %r"
+ % (idx + 1, bi + 1, c[:70]))
+ cleaned.append(l2)
+ beat_lines = cleaned
+ shot["take_seconds"] = take
+ # `beat_lines` is what the model wrote (what a re-plan is shown); `beats` is
+ # each of them assembled in the shot's register (what the panel renders) —
+ # the same raw/assembled pair `description` / `prompt` already keep.
+ shot["beat_lines"] = beat_lines
+ shot["beats"] = _assemble_beats(shot, beat_lines, style, cast, storyboard_mod)
+ shot["frames"] = take * 24 + 1
+ # The prompt the panel reads first — the light lock, the file name, part 1 —
+ # is the first beat, as collapse_take does for a whole-film take.
+ if shot["beats"][0]:
+ shot["prompt"] = shot["beats"][0]
shots.append(shot)
if len(shots) != n_shots:
diff --git a/test_storyboard_editor_ui.py b/test_storyboard_editor_ui.py
index e08f332..884f434 100644
--- a/test_storyboard_editor_ui.py
+++ b/test_storyboard_editor_ui.py
@@ -6390,5 +6390,504 @@ class TimelineMarkup(unittest.TestCase):
self.assertIn("var(--border", css)
+# ---------------------------------------------------------------------------
+# ONE SHOT IS A MODE. The owner's ruling: a continuous shot of 30 s – 2 min is
+# a different way of making a video, not a length on the clip form — its own
+# chip in the mode bar, its own panel (length, beats, anchor image, the two
+# continuity toggles), and a normal clip must never carry take_seconds. These
+# run the REAL setMode / oneshotEnter / oneshotLeave / setTakeSeconds against
+# a DOM shim built from the REAL chips in the markup, so "leaving the mode
+# zeroes the take" is executed, not grepped for.
+# ---------------------------------------------------------------------------
+
+ONESHOT_FUNCTIONS = (
+ "setMode", "defaultRemixMode", "updatePromptPlaceholder",
+ "takePartSeconds", "setTakeSeconds", "takePrefill", "takePrefillClick",
+ "beatsInput", "oneshotActive", "oneshotBackendMode", "oneshotEnter",
+ "oneshotLeave", "oneshotRefreshLabels", "oneshotSyncAnchor",
+ "_setTakeToggle", "setTakeLightLock", "setTakeRetake",
+ "takeLengthLabel", "oneshotSummary", "restoreFoldedLtxLength", "framesToDuration",
+)
+
+ONESHOT_SHIM = r"""
+'use strict';
+// A classList that REMEMBERS, because the assertions read it back.
+function _cls() {
+ const set = new Set();
+ return {
+ add(...a) { a.forEach(x => set.add(x)); },
+ remove(...a) { a.forEach(x => set.delete(x)); },
+ toggle(x, f) { const on = (f === undefined) ? !set.has(x) : !!f; on ? set.add(x) : set.delete(x); return on; },
+ contains(x) { return set.has(x); },
+ get list() { return [...set]; },
+ };
+}
+const _els = {};
+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 []; },
+ 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); },
+ enumerable: true, configurable: true,
+ });
+ if (props && Object.prototype.hasOwnProperty.call(props, 'value')) e.value = props.value;
+ _els[id] = 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 });
+});
+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 } }));
+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'),
+ 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 }) });
+"""
+
+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 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),
+};
+// 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'),
+};
+// ...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));
+"""
+
+
+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"
+ + "\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)
+ if result.returncode:
+ raise AssertionError(result.stdout + "\n" + result.stderr)
+ return json.loads(result.stdout)
+ 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."""
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.src = panel_source()
+ cls.html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")
+ cls.r = run_oneshot_contract()
+
+ # ---- the markup ---------------------------------------------------------
+ def test_the_chip_is_in_the_mode_bar_between_image_and_fflf(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):
+ 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)
+
+ 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)
diff --git a/test_storyboard_one_shot.py b/test_storyboard_one_shot.py
new file mode 100644
index 0000000..31cacd8
--- /dev/null
+++ b/test_storyboard_one_shot.py
@@ -0,0 +1,350 @@
+#!/usr/bin/env python3
+"""ONE SHOT inside a film.
+
+The planner may choose a take — `take_seconds` (30 / 45 / 60 / 90 / 120) plus `beats`,
+one per five seconds — for ONE scene of an otherwise ordinary multi-shot film, as a
+cinematic tool (a walk-and-talk, a chase, a confession). Before this a take only reached
+the board when the whole film was one (`collapse_take`). These tests drive the planner's
+coercion, the board's validation / pricing / job mapping and the system prompt text with
+canned model JSON: no model, no panel, no panel JavaScript.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+if str(ROOT) not in sys.path:
+ sys.path.insert(0, str(ROOT))
+
+import storyboard as sb # noqa: E402
+import storyboard_planner as P # noqa: E402
+
+
+KW = dict(concept="a nurse's night shift", n_shots=2, storyboard_mod=sb)
+
+BEATS = [
+ "Night, flat fluorescent light. She walks straight toward the lens down the empty "
+ "corridor, soles squeaking on the vinyl.",
+ "A wheeled trolley rolls into frame from the left and she steps around it, its wheels "
+ "rattling as it passes.",
+ "The closed pharmacy hatch slides past on her right, the fluorescent hum steady.",
+ "A man on a bench rises as she reaches him and falls into step beside her, a call bell "
+ "ringing behind them.",
+ "The corridor bends left and the double doors of the ward come into view; her pace slows.",
+ "She pushes the doors open and stops in the doorway, the doors swinging behind her.",
+]
+
+
+def _normal(n: int, **kw) -> dict:
+ d = {
+ "n": n, "title": "The key", "character_id": None, "duration_s": 5,
+ "camera": "static", "face": "none",
+ "description": "Live-action, cinematic, a close-up of a brass key on a wet stone "
+ "step. Rain beads on the metal and one drop runs off the bow.",
+ "settle": "the key lies still and wet",
+ "soundscape": "Steady rain on stone, a distant gutter running.",
+ "music": "N/A",
+ }
+ d.update(kw)
+ return d
+
+
+def _one_shot(n: int, **kw) -> dict:
+ d = {
+ "n": n, "title": "Down the corridor", "character_id": None, "duration_s": 30,
+ "camera": "tracking", "face": "medium",
+ "description": "Live-action, cinematic, a medium shot moving backwards ahead of a "
+ "nurse in pale blue scrubs as she walks a hospital corridor at night "
+ "to the double doors of a ward and pushes them open.",
+ "settle": "she stands in the ward doorway, still",
+ "soundscape": "Soft soles on vinyl flooring, the fluorescent hum, a distant call bell.",
+ "music": "N/A",
+ "take_seconds": 30,
+ "beats": list(BEATS),
+ }
+ d.update(kw)
+ return d
+
+
+def _plan(*shots, **kw):
+ args = dict(KW, n_shots=len(shots))
+ args.update(kw)
+ return P.coerce_spec({"title": "Night shift", "shots": list(shots)}, **args)
+
+
+# ---- (a) a planner response with one normal shot and one One Shot -----------------
+
+def test_one_shot_among_normal_shots_validates_and_keeps_its_take():
+ spec, warns = _plan(_normal(1), _one_shot(2))
+ assert len(spec["shots"]) == 2
+ a, b = spec["shots"]
+ # the normal shot is untouched by the feature
+ assert "take_seconds" not in a and "beats" not in a and "beat_lines" not in a
+ assert a["duration_s"] == 5.0
+ # the One Shot carries its take, is as long as its take, and is ONE shot
+ assert b["take_seconds"] == 30 and b["duration_s"] == 30.0 and b["frames"] == 721
+ assert b["n"] == 2 and b["engine"] == "h3"
+ assert len(b["beats"]) == 6 and all(b["beats"])
+ assert b["beat_lines"] == BEATS
+ # the prompt the panel reads first is the first beat
+ assert b["prompt"] == b["beats"][0]
+ # the board accepts it: no bad_duration, no bad_take_seconds, nothing at all
+ assert sb.validate_storyboard(spec) == []
+ assert not [w for w in warns if "take" in w.lower()]
+
+
+def test_beats_are_assembled_in_the_register_with_the_settle_on_the_last_only():
+ spec, _ = _plan(_normal(1), _one_shot(2))
+ beats = spec["shots"][1]["beats"]
+ # every beat can render a part on its own: the camera law and the soundscape ride on each
+ for x in beats:
+ assert x.startswith("integrated_multimodal_description: [Shot 1] ")
+ assert "The camera tracks" in x and "\n\noverall_soundscape: " in x
+ # ...but the end state only on the last one — an early settle would stop the take
+ assert "completely finished before the shot ends" in beats[-1]
+ assert not any("completely finished before the shot ends" in x for x in beats[:-1])
+ # the LTX register, when the film is on LTX: prose, no H3 field labels
+ spec2, _ = _plan(_normal(1), _one_shot(2), engine="ltx")
+ for x in spec2["shots"][1]["beats"]:
+ assert "integrated_multimodal_description" not in x and x.endswith(".")
+ assert spec2["shots"][1]["duration_s"] == 30.0
+
+
+def test_take_seconds_snaps_to_the_nearest_take_and_is_never_clamped():
+ for raw, want in ((32, 30), ("60s", 60), (100, 90), (500, 120), (20, 30), ("45", 45)):
+ for engine in ("h3", "ltx"):
+ spec, warns = _plan(_normal(1), _one_shot(2, take_seconds=raw,
+ beats=["b"] * (want // 5)),
+ engine=engine)
+ s = spec["shots"][1]
+ assert s["take_seconds"] == want, (raw, engine)
+ # not clamped to 60, not snapped onto H3's 3/5/10/15 grid
+ assert s["duration_s"] == float(want), (raw, engine, s["duration_s"])
+ assert s["engine"] == engine
+ assert P._coerce_take_seconds(None) is None
+ assert P._coerce_take_seconds(0) is None
+ assert P._coerce_take_seconds("off") is None
+ assert P._coerce_take_seconds(False) is None
+ assert P._coerce_take_seconds(30) == 30
+
+
+# ---- (b) beats padding / trimming ----------------------------------------------------
+
+def test_beats_are_padded_and_trimmed_never_rejected():
+ # too many: extras dropped
+ spec, warns = _plan(_normal(1), _one_shot(2, beats=BEATS + ["one beat too many"]))
+ s = spec["shots"][1]
+ assert len(s["beats"]) == 6 and s["beat_lines"] == BEATS
+ assert any("7 beats" in w and "extras dropped" in w for w in warns)
+ # too few: the missing ones are blank, and stay blank once assembled
+ spec, warns = _plan(_normal(1), _one_shot(2, beats=BEATS[:4]))
+ s = spec["shots"][1]
+ assert s["beat_lines"] == BEATS[:4] + ["", ""]
+ assert s["beats"][4] == "" and s["beats"][5] == "" and all(s["beats"][:4])
+ assert any("4 beats" in w and "previous moment" in w for w in warns)
+ # the settle moved to the last WRITTEN beat
+ assert "completely finished before the shot ends" in s["beats"][3]
+ assert sb.validate_storyboard(spec) == []
+ # shapes a small model actually produces
+ assert P._coerce_beats("a\nb\n\nc", 3) == ["a", "b", ""]
+ assert P._coerce_beats(["1. a", "Beat 2: b", "3) c"], 4) == ["a", "b", "c", ""]
+ assert P._coerce_beats([{"text": "a"}, {"beat": "b"}, None], 3) == ["a", "b", ""]
+ assert P._coerce_beats({"1": "a", "2": "b"}, 2) == ["a", "b"]
+ assert P._coerce_beats(None, 2) == ["", ""]
+ # the board's own shaping, for a hand-edited shot
+ assert sb.take_beats_for({"take_seconds": 30, "beats": "a\nb"}) == ["a", "b", "", "", "", ""]
+ assert sb.take_beats_for({"take_seconds": 30, "beats": ["x"] * 9}) == ["x"] * 6
+ assert sb.take_beats_for({"take_seconds": 5, "beats": ["x"]}) == []
+ assert sb.take_beats_for(_normal(1)) == []
+
+
+def test_a_take_with_no_written_beat_is_an_ordinary_shot():
+ spec, warns = _plan(_normal(1), _one_shot(2, beats=[]))
+ s = spec["shots"][1]
+ assert "take_seconds" not in s and "beats" not in s
+ assert s["duration_s"] == 15.0 # H3's grid, as for any 30 s ordinary shot
+ assert any("wrote no beats" in w for w in warns)
+ spec, _ = _plan(_normal(1), _one_shot(2, beats=["", "", ""]))
+ assert "take_seconds" not in spec["shots"][1]
+
+
+# ---- (c) shot_to_job: the take fields go out for the One Shot and nothing else -------
+
+def test_shot_to_job_posts_take_fields_for_the_one_shot_only():
+ spec, _ = _plan(_normal(1), _one_shot(2))
+ policy = {"quality": "balanced"}
+ jobs = [sb.shot_to_job(s, policy, h3_available=True, board_id="sb1", board_title="Night")
+ for s in sb.shooting_order(spec["shots"])]
+ assert len(jobs) == 2 # one job per shot: the take is not split here
+ normal = next(j for j in jobs if j["preset_label"].startswith("S01"))
+ take = next(j for j in jobs if j["preset_label"].startswith("S02"))
+ for k in ("take_seconds", "beats"):
+ assert k not in normal
+ assert normal["h3_length"] == "5s" and normal["frames"] == 124
+ assert take["take_seconds"] == "30"
+ beats = json.loads(take["beats"])
+ assert len(beats) == 6 and all(beats)
+ assert beats[0].startswith("integrated_multimodal_description: [Shot 1] Night")
+ assert take["engine"] == "h3" and take["h3_length"] == "15s"
+ assert take["session_tag"] == "sb:sb1#2"
+
+
+def test_shot_to_job_on_ltx_is_the_whole_take_and_never_the_windows_chain():
+ spec, _ = _plan(_normal(1), _one_shot(2), engine="ltx")
+ s = spec["shots"][1]
+ j = sb.shot_to_job(s, {"quality": "balanced"}, h3_available=False, long_windows=True)
+ assert j["engine"] == "ltx" and j["take_seconds"] == "30" and j["frames"] == 721
+ assert len(json.loads(j["beats"])) == 6
+ assert "temporal_mode" not in j and "window_invariants" not in j
+ # the ordinary long shot next to it still gets the chain
+ long_shot = dict(spec["shots"][0], duration_s=20.0)
+ j2 = sb.shot_to_job(long_shot, {"quality": "balanced"}, h3_available=False, long_windows=True)
+ assert j2.get("temporal_mode") == "windows"
+
+
+def test_beats_are_padded_at_job_time_and_composed_with_the_place():
+ shot = {"n": 2, "mode": "text", "engine": "h3", "prompt": "a", "duration_s": 30.0,
+ "take_seconds": 30, "beats": ["a", "b"], "location_id": "ward"}
+ locs = {"ward": sb.new_location("ward", "The ward", "a dim ward with one lit bed")}
+ j = sb.shot_to_job(shot, {"quality": "quick"}, locations=locs)
+ beats = json.loads(j["beats"])
+ assert len(beats) == 6 and beats[2:] == ["", "", "", ""]
+ # every written beat carries the location, because a later part renders from ITS beats
+ assert all("a dim ward with one lit bed" in b for b in beats[:2])
+ assert beats[0].startswith("a, ")
+ # a One Shot with a cast character carries the trigger on every written beat
+ cast = P._normalise_cast(["bizarrotrn"])
+ spec, _ = _plan(_normal(1), _one_shot(2, character_id="bizarrotrn"), cast=cast)
+ s = spec["shots"][1]
+ assert s["engine"] == "ltx" and s["character_id"] == "bizarrotrn"
+ assert all("bizarrotrn" in b for b in s["beats"])
+ j3 = sb.shot_to_job(s, {"quality": "balanced"})
+ assert all("bizarrotrn" in b for b in json.loads(j3["beats"]))
+ assert j3["character_id"] == "bizarrotrn" and j3["take_seconds"] == "30"
+
+
+# ---- pricing and parts on both engines -----------------------------------------------
+
+def test_one_shot_is_priced_by_parts_on_both_engines():
+ spec, _ = _plan(_normal(1), _one_shot(2))
+ s = spec["shots"][1]
+ assert sb.take_parts(s) == 2 # 6 beats in threes on H3
+ assert sb.shot_render_secs(s, {"quality": "balanced"},
+ h3_cost=lambda q, l: 1000.0 if l == "15s" else 1.0) == 2000.0
+ ltx = dict(s, engine="ltx")
+ assert sb.take_parts(ltx) == 3 # 6 beats in twos on LTX
+ assert sb.shot_render_secs(ltx, {"quality": "balanced"}) == 30 * 60.0
+ # 45 s on LTX ends on a one-beat part; the parts still add up to the take
+ ltx45 = dict(ltx, take_seconds=45, duration_s=45.0)
+ assert sb.take_parts(ltx45) == 5
+ assert sb.shot_render_secs(ltx45, {"quality": "quick"}) == 45 * 24.0
+ # a stale duration_s does not change what the take costs
+ assert sb.shot_render_secs(dict(ltx, duration_s=5.0), {"quality": "balanced"}) == 30 * 60.0
+ assert sb.take_parts(_normal(1)) == 0
+ # the film estimate counts the take once, in its engine's bucket, with the runtime it has
+ board = sb.new_storyboard("sb_os", "Night shift", shots=spec["shots"])
+ est = sb.estimate(board, pass_name="draft")
+ assert est["shots"] == 2 and est["runtime_secs"] == 35
+
+
+def test_validator_flags_an_illegal_take_length_but_never_the_beat_count():
+ b = sb.new_storyboard("sb_v", "v")
+ good = {"n": 1, "mode": "text", "engine": "h3", "prompt": "p", "duration_s": 30.0,
+ "take_seconds": 30, "beats": ["a", "b"]}
+ b["shots"] = [good]
+ assert sb.validate_storyboard_detail(b) == []
+ b["shots"] = [dict(good, take_seconds=40, duration_s=40.0)]
+ codes = [e["code"] for e in sb.validate_storyboard_detail(b)]
+ assert codes == ["bad_take_seconds"]
+ for off in (None, 0, "0", "off", ""):
+ b["shots"] = [dict(good, take_seconds=off, duration_s=5.0)]
+ assert sb.validate_storyboard_detail(b) == [], off
+ assert sb.take_seconds_of(good) == 30
+ assert sb.take_seconds_of(dict(good, take_seconds="60")) == 60
+ assert sb.take_seconds_of(dict(good, take_seconds=True)) is None
+ assert sb.take_seconds_of(_normal(1)) is None
+
+
+def test_collapse_take_keeps_a_nested_one_shots_beats_in_order():
+ shots = [
+ {"n": 1, "mode": "text", "engine": "h3", "prompt": "p1", "duration_s": 5.0},
+ {"n": 2, "mode": "text", "engine": "h3", "prompt": "a", "duration_s": 30.0,
+ "take_seconds": 30, "beats": ["a", "b", "c"]},
+ {"n": 3, "mode": "text", "engine": "h3", "prompt": "p3", "duration_s": 5.0},
+ ]
+ t = sb.collapse_take(shots, 30)[0]
+ assert t["beats"] == ["p1", "a", "b", "c", "p3", ""]
+ assert t["take_seconds"] == 30 and t["duration_s"] == 30.0 and t["n"] == 1
+
+
+# ---- (d) the system prompt carries the rule and the example --------------------------
+
+def test_system_prompt_carries_the_one_shot_rule_and_the_example():
+ for hint, chars in (("auto", False), ("auto", True), ("h3", False), ("ltx", True)):
+ sp = P._build_system_prompt(hint, chars)
+ assert "ONE SHOT - a take that never cuts, used as a cinematic tool" in sp, hint
+ # what it is, when, when not, how many
+ assert "single unbroken take of 30 to 120 seconds" in sp
+ assert "walk-and-talk, a chase or a POV ride, a monologue or a" in sp
+ assert "WRONG tool for a montage, for cross-cutting" in sp
+ assert "Use it at most once" in sp and "never for the whole film" in sp
+ # how to write it
+ assert '"take_seconds" one of 30, 45, 60, 90, 120' in sp
+ assert "EXACTLY take_seconds / 5 strings" in sp
+ assert "state the time of day and the weather ONCE" in sp
+ # the contract admits the two extra keys
+ assert "a One Shot adds two more" in sp
+ # the example shot object, in the film's own JSON dialect
+ assert '"take_seconds": 30,' in sp and '"beats": [' in sp
+ assert '"title": "Down the corridor"' in sp
+ assert sp.count("Night, flat fluorescent light.") == 1
+ head = '"n": 3,\n "title": "Down the corridor"'
+ ex = sp[sp.index(head):]
+ ex = ex[:ex.index("\n}\n") + 3]
+ obj = json.loads("{" + ex)
+ assert obj["n"] == 3
+ assert obj["take_seconds"] == 30 and len(obj["beats"]) == 6
+ assert obj["duration_s"] == obj["take_seconds"]
+ for key in ("n", "title", "character_id", "duration_s", "camera", "face",
+ "description", "settle", "soundscape", "music"):
+ assert key in obj, key
+ # in the H3 register the example opens with the style token; on an
+ # LTX-only film that word is the one the LTX rules forbid, so it is gone
+ if hint == "ltx":
+ assert "cinematic" not in obj["description"]
+ assert obj["description"].startswith("A medium shot")
+ else:
+ assert obj["description"].startswith("Live-action, cinematic, a medium shot")
+
+
+def test_model_view_shows_the_take_so_a_replan_keeps_it():
+ spec, _ = _plan(_normal(1), _one_shot(2))
+ a, b = spec["shots"]
+ va, vb = P._shot_to_model_view(a), P._shot_to_model_view(b)
+ assert "take_seconds" not in va and "beats" not in va
+ assert vb["take_seconds"] == 30 and vb["beats"] == BEATS # as written, not assembled
+ # a re-plan that returns the take again keeps it, one that drops it loses it
+ again, _ = P._coerce_for_mode(
+ {"title": "Night shift", "shots": [_one_shot(2)]}, "shot", 2, spec,
+ concept=KW["concept"], n_shots=2, style="", cast=[], board_id=spec["id"],
+ engine="auto", tier="draft", duration_s=5.0, seed_base=1, max_dim=None, sb=sb)
+ assert again["shots"][1]["take_seconds"] == 30 and len(again["shots"][1]["beats"]) == 6
+ assert "take_seconds" not in again["shots"][0]
+
+
+def test_face_law_applies_to_every_beat():
+ bad = list(BEATS)
+ bad[3] = "She turns and walks on, seen from behind, her back to the camera."
+ spec, warns = _plan(_normal(1), _one_shot(2, beats=bad))
+ s = spec["shots"][1]
+ assert "seen from behind" not in s["beat_lines"][3]
+ assert "back to the camera" not in s["beats"][3]
+ assert any("beat 4" in w and "face-hiding" in w for w in warns)
+
+
+if __name__ == "__main__":
+ import pytest
+ sys.exit(pytest.main([__file__, "-q", "-p", "no:cacheprovider"]))
diff --git a/test_storyboard_planner.py b/test_storyboard_planner.py
index db9efa6..46dc892 100644
--- a/test_storyboard_planner.py
+++ b/test_storyboard_planner.py
@@ -723,13 +723,15 @@ class TestPromptContent(unittest.TestCase):
sys_p = P._build_system_prompt("auto", True)
# Strip L11 itself, which necessarily quotes the phrases it forbids.
body = sys_p.split("L11 THE FACE IS THE WHOLE POINT")[0]
- for phrase in ("tips his face up", "tipped up", "off-camera", "obscur",
- "from behind", "seen from behind", "back to the camera"):
- self.assertNotIn(phrase, body, "exemplars still teach %r" % phrase)
- self.assertEqual(P._FACE_BLOCK_RE.findall(body), [])
- # Every exemplar declares a face level.
+ # The One Shot exemplar sits AFTER the laws, so it is audited on its own.
+ for text in (body, P._ONE_SHOT):
+ for phrase in ("tips his face up", "tipped up", "off-camera", "obscur",
+ "from behind", "seen from behind", "back to the camera"):
+ self.assertNotIn(phrase, text, "exemplars still teach %r" % phrase)
+ self.assertEqual(P._FACE_BLOCK_RE.findall(text), [])
+ # Every exemplar declares a face level — the last one is the One Shot.
self.assertEqual(re.findall(r'"face": "(\w+)"', sys_p),
- ["close", "medium", "close", "none", "close"])
+ ["close", "medium", "close", "none", "close", "medium"])
def test_ltx_example_appears_only_when_there_is_a_cast(self):
self.assertNotIn("letterbox", P._build_system_prompt("auto", False))
diff --git a/test_take.py b/test_take.py
index 5444700..fd38100 100644
--- a/test_take.py
+++ b/test_take.py
@@ -1,5 +1,6 @@
"""ONE TAKE: the plan arithmetic, the beats, the make_job mapping on both
-engines, the estimate route, and the H3 runner with a stubbed engine."""
+engines, the estimate route, and the runner with a stubbed engine — H3 parts
+of 15 s and LTX parts of 10 s, both chained by last-frame handoff."""
import json
import subprocess
from pathlib import Path
@@ -14,13 +15,26 @@ def test_plan_h3_parts_and_ltx_frames():
assert h["beats"] == 12 and [len(x) for x in h["parts"]] == [3, 3, 3, 3]
assert h["frames"] == 4 * 362
assert p.take_plan(45, "h3")["parts"][-1] == [6, 7, 8]
+ assert h["part_frames"] == 362 and h["beats_per_part"] == 3
l = p.take_plan(30, "ltx")
- assert l["beats"] == 6 and len(l["parts"]) == 1 and l["frames"] == 721
+ assert l["beats"] == 6 and [len(x) for x in l["parts"]] == [2, 2, 2] and l["frames"] == 721
+ assert l["part_frames"] == 241 and l["beats_per_part"] == 2 and l["engine"] == "ltx"
+ assert [len(x) for x in p.take_plan(45, "ltx")["parts"]] == [2, 2, 2, 2, 1]
+ assert p.take_plan(45, "ltx")["parts"][-1] == [8]
for s in p.TAKE_SECONDS: # every length is 8k+1 on LTX
assert (p.take_plan(s, "ltx")["frames"] - 1) % 8 == 0
assert p.take_plan(50, "h3") is None and p.take_plan("x", "h3") is None
+def test_plan_ltx_60s_is_six_parts_of_two_beats():
+ l = p.take_plan(60, "ltx")
+ assert l["beats"] == 12 and [len(x) for x in l["parts"]] == [2] * 6
+ assert l["parts"][0] == [0, 1] and l["parts"][-1] == [10, 11]
+ assert l["frames"] == 1441 and l["part_frames"] == p.TAKE_LTX_PART_FRAMES == 241
+ assert p.take_ltx_part_frames(2) == 241 and p.take_ltx_part_frames(1) == 121
+ assert [len(x) for x in p.take_plan(120, "ltx")["parts"]] == [2] * 12
+
+
def test_beats_normalise_from_json_or_lines():
assert p.take_beats(json.dumps(["a", "b"]), 4) == ["a", "b", "", ""]
assert p.take_beats("a\nb\n\nc", 3) == ["a", "b", ""]
@@ -38,13 +52,63 @@ def test_make_job_h3_take_forces_15s_parts_and_first_chain():
assert q["take"]["beat_prompts"][11].startswith("b11 Continuity")
-def test_make_job_ltx_take_is_the_windows_chain():
+def test_make_job_ltx_take_is_parts_not_the_windows_chain():
j = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "x",
"take_seconds": "30", "beats": "one\ntwo\n"})
q = j["params"]
- assert q["long_mode"] == "windows" and q["frames"] == 721
- assert [w.split(" Continuity")[0] for w in q["window_prompts"][:3]] == ["one", "two", ""]
- assert q["take"]["engine"] == "ltx"
+ assert q["long_mode"] == "native" and q["temporal_mode"] == "native"
+ assert q["frames"] == 241 and q["window_prompts"] == []
+ t = q["take"]
+ assert t["engine"] == "ltx" and t["seconds"] == 30 and t["frames"] == 721
+ assert [len(x) for x in t["parts"]] == [2, 2, 2] and t["part_frames"] == 241
+ assert [b.split(" Continuity")[0] for b in t["beat_prompts"][:3]] == ["one", "two", ""]
+ assert t["beat_prompts"][0].endswith("season.") and t["light_lock"] and t["retake"] is True
+ # a leftover windows request on the form (the Storyboard's long-shot
+ # flag) does not turn the take back into the chain
+ q2 = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "x", "take_seconds": "45",
+ "temporal_mode": "windows", "window_prompts": json.dumps(["a", "b"]),
+ "frames": "1081"})["params"]
+ assert q2["long_mode"] == "native" and q2["frames"] == 241 and q2["window_prompts"] == []
+ assert [len(x) for x in q2["take"]["parts"]] == [2, 2, 2, 2, 1]
+
+
+def test_make_job_take_light_lock_off_leaves_the_beats_alone():
+ q = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "Broadway at night", "take_seconds": "30",
+ "beats": json.dumps(["a", "", "c", "d", "e", "f"]), "take_light_lock": "off"})["params"]
+ assert q["take"]["light_lock"] == ""
+ assert q["take"]["beat_prompts"] == ["a", "", "c", "d", "e", "f"]
+ assert not any("Continuity" in b for b in q["take"]["beat_prompts"])
+ # H3's spelled-out hold carries no lock either
+ h = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "Broadway at night", "take_seconds": "30",
+ "beats": json.dumps(["a", "", "c", "d", "e", "f"]), "take_light_lock": "off"})["params"]
+ assert h["h3_chain_prompts"] == ["a", p.TAKE_HOLD, "c"]
+ # default and explicit "on" both lock
+ on = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "Broadway at night", "take_seconds": "30",
+ "beats": json.dumps(["a"]), "take_light_lock": "on"})["params"]
+ assert "still night" in on["take"]["beat_prompts"][0] and on["take"]["light_lock"]
+
+
+def test_make_job_take_retake_off_is_recorded():
+ q = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "x", "take_seconds": "30",
+ "take_retake": "off"})["params"]
+ assert q["take"]["retake"] is False
+ assert p.make_job({"mode": "t2v", "engine": "h3", "prompt": "x", "take_seconds": "30",
+ "take_retake": "off"})["params"]["take"]["retake"] is False
+ assert p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "x", "take_seconds": "30"})["params"]["take"]["retake"] is True
+
+
+def _tiny_png(path: Path) -> None:
+ subprocess.run([str(p.FFMPEG), "-loglevel", "error", "-y", "-f", "lavfi", "-i",
+ "color=c=green:s=64x64:d=1", "-frames:v", "1", "-update", "1", str(path)], check=True)
+
+
+def test_make_job_ltx_take_from_an_image_keeps_the_anchor(tmp_path):
+ png = tmp_path / "anchor.png"; _tiny_png(png)
+ q = p.make_job({"mode": "i2v", "engine": "ltx", "prompt": "a hen skates", "image": str(png),
+ "take_seconds": "30", "beats": json.dumps(["b1", "b2", "b3"])})["params"]
+ assert q["mode"] == "i2v" and q["image"] == str(png)
+ assert q["take"]["engine"] == "ltx" and q["frames"] == 241 and q["long_mode"] == "native"
+ assert [len(x) for x in q["take"]["parts"]] == [2, 2, 2]
def test_make_job_without_take_is_unchanged():
@@ -60,7 +124,13 @@ def test_estimate_route_registered_and_prices_h3():
assert "/take/estimate" in GET_ROUTES
m = p.take_estimate_minutes("h3", "high", 60)
assert m is None or m > 30 # four 15 s parts, never minutes
- assert p.take_estimate_minutes("ltx", "balanced", 60) is None
+ # LTX: parts × the quality's own 10 s cell — the price of six ordinary
+ # 241-frame renders, not a windows count and not None
+ ten = p.LTX_TIERS["balanced_10s"]["eta_min"]
+ five = p.LTX_TIERS["balanced_5s"]["eta_min"]
+ assert p.take_estimate_minutes("ltx", "balanced", 60) == round(6 * ten, 1)
+ assert p.take_estimate_minutes("ltx", "balanced", 45) == round(4 * ten + five, 1)
+ assert p.take_estimate_minutes("ltx", "", 30) == round(3 * p.LTX_TIERS[f"{p.LTX_QUALITY_DEFAULT}_10s"]["eta_min"], 1)
def _tiny_clip(path: Path, colour: str) -> None:
@@ -117,6 +187,102 @@ def test_take_runner_stops_between_parts(tmp_path, monkeypatch):
p.run_take_job_inner(job)
+def test_ltx_take_runner_chains_parts_by_last_frame_handoff(tmp_path, monkeypatch):
+ out_dir = tmp_path / "out"; out_dir.mkdir()
+ monkeypatch.setattr(p, "OUTPUT", out_dir)
+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")
+ hidden = []
+ monkeypatch.setattr(p, "set_hidden", lambda path, flag: hidden.append((path, flag)))
+ seen = []
+
+ def fake_ltx(child):
+ assert child["params"]["take"] is None # a part is not a take
+ seen.append(dict(child["params"]))
+ out = out_dir / f"{child['id']}.mp4"
+ _tiny_clip(out, "red" if len(seen) == 1 else "blue")
+ (out_dir / f"{child['id']}.mp4.json").write_text(json.dumps(
+ {"width": 64, "height": 64, "seed": 5, "image": child["params"].get("image"), "frames": 241}))
+ child["output_path"] = str(out)
+ monkeypatch.setattr(p, "run_job_inner", fake_ltx)
+ h3_calls = []
+ monkeypatch.setattr(p, "run_h3_job_inner", lambda c: h3_calls.append(c))
+ monkeypatch.setattr(p, "take_drift", lambda *a, **k: {"ok": True, "delta": 0.0, "drifted": False})
+ png = tmp_path / "anchor.png"; _tiny_png(png)
+ j = p.make_job({"mode": "i2v", "engine": "ltx", "prompt": "a hen skates", "image": str(png),
+ "take_seconds": "45", "beats": json.dumps(["b1", "b2", "b3", "", "b5", "b6", "b7", "b8", "b9"]),
+ "preset_label": "ride"})
+ p.run_take_job_inner(j)
+ assert not h3_calls and len(seen) == 5
+ # part 1 opens on the user's own anchor; every later part on the previous last frame
+ assert seen[0]["mode"] == "i2v" and seen[0]["image"] == str(png)
+ assert seen[0]["prompt"].split(" Continuity")[0] == "b1"
+ assert "b2" in seen[0]["prompt"] and seen[0]["frames"] == 241
+ for k in (1, 2, 3, 4):
+ assert seen[k]["mode"] == "i2v" and seen[k]["i2v_reference_mode"] == "anchor"
+ assert Path(seen[k]["image"]).is_file() and seen[k]["image"].endswith(f"part{k}_last.png")
+ assert seen[1]["prompt"].split(" Continuity")[0] == "b3"
+ assert p.TAKE_HOLD in seen[1]["prompt"] # the blank 4th beat holds
+ assert seen[4]["frames"] == 121 # the one-beat tail
+ assert seen[4]["prompt"].split(" Continuity")[0] == "b9"
+ for c in seen: # never the windows chain
+ assert c["long_mode"] == "native" and c["temporal_mode"] == "native"
+ assert c["window_prompts"] == [] and c["h3_chain_prompts"] == []
+ assert c["label"].startswith("ride · part ")
+ final = Path(j["output_path"])
+ assert final.is_file() and final.name.endswith("_take45s.mp4")
+ side = json.loads(final.with_suffix(final.suffix + ".json").read_text())
+ assert side["engine"] == "ltx" and side["mode"] == "i2v" and side["image"] == str(png)
+ assert side["frames"] == 1081 and side["seconds"] == 45
+ assert side["take"]["engine"] == "ltx" and side["take"]["beats_per_part"] == 2
+ assert side["take"]["part_frames"] == 241 and len(side["take"]["parts"]) == 5
+ assert side["long_mode"] == "native" and side["window_prompts"] == []
+ assert [f for f, flag in hidden if flag] == side["take"]["parts"]
+
+
+def test_ltx_take_runner_from_text_starts_t2v_and_drops_the_handoff_image(tmp_path, monkeypatch):
+ out_dir = tmp_path / "out"; out_dir.mkdir()
+ monkeypatch.setattr(p, "OUTPUT", out_dir)
+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")
+ monkeypatch.setattr(p, "set_hidden", lambda *a: None)
+ seen = []
+
+ def fake_ltx(child):
+ seen.append(dict(child["params"]))
+ out = out_dir / f"{child['id']}.mp4"; _tiny_clip(out, "red")
+ (out_dir / f"{child['id']}.mp4.json").write_text(json.dumps({"image": child["params"].get("image")}))
+ child["output_path"] = str(out)
+ monkeypatch.setattr(p, "run_job_inner", fake_ltx)
+ monkeypatch.setattr(p, "take_drift", lambda *a, **k: {"ok": True, "delta": 0.0, "drifted": False})
+ j = p.make_job({"mode": "t2v", "engine": "ltx", "prompt": "x", "take_seconds": "30"})
+ p.run_take_job_inner(j)
+ assert [c["mode"] for c in seen] == ["t2v", "i2v", "i2v"]
+ side = json.loads(Path(j["output_path"]).with_suffix(".mp4.json").read_text())
+ assert "image" not in side and side["mode"] == "t2v"
+
+
+def test_take_runner_retake_off_keeps_a_drifting_part(tmp_path, monkeypatch):
+ out_dir = tmp_path / "out"; out_dir.mkdir()
+ monkeypatch.setattr(p, "OUTPUT", out_dir)
+ monkeypatch.setattr(p, "STATE_DIR", tmp_path / "state")
+ monkeypatch.setattr(p, "set_hidden", lambda *a: None)
+ calls = []
+
+ def fake_h3(child):
+ calls.append(child["id"])
+ out = out_dir / f"{child['id']}.mp4"
+ _lit_clip(out, "0x202020", "0xd0d0d0") # every part drifts
+ (out_dir / f"{child['id']}.mp4.json").write_text("{}")
+ child["output_path"] = str(out)
+ monkeypatch.setattr(p, "run_h3_job_inner", fake_h3)
+ j = p.make_job({"mode": "t2v", "engine": "h3", "prompt": "Broadway at night", "take_seconds": "30",
+ "beats": json.dumps(["b1", "b2", "b3", "b4", "b5", "b6"]), "take_retake": "off"})
+ p.run_take_job_inner(j)
+ assert calls == [f"{j['id']}-p1", f"{j['id']}-p2"] # no -p1r
+ assert j["take_drift"][0]["drifted"] is True
+ side = json.loads(Path(j["output_path"]).with_suffix(".mp4.json").read_text())
+ assert side["take"]["retake"] is False and side["engine"] == "h3"
+
+
# ---- the Storyboard door -------------------------------------------------------
import storyboard as sb
diff --git a/webapp/index.html b/webapp/index.html
index e3782e2..e64bbcd 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -348,6 +348,14 @@
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. -->
@@ -959,11 +967,16 @@
make_job allowlist — a field that isn't listed there silently
no-ops on /queue/add (the known trap). setH3Tier keeps the three
in sync, so there is exactly one state, spelled three ways. -->
- <!-- ONE TAKE: a length past a single pass, and one beat per five
- seconds. make_job turns it into the windows chain (LTX) or
- 15 s parts that continue from each other (H3). -->
+ <!-- ONE SHOT: a length past a single pass, and one beat per five
+ seconds. make_job turns it into parts that continue from each
+ other's last frame (15 s parts on H3, 10 s parts on LTX). The two
+ 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">
@@ -1082,7 +1095,7 @@
than a strip itself. -->
<div class="h3-axes" id="h3TierGroup" hidden>
<div class="quality-strip pill-group" id="h3QualityGroup"></div>
- <div class="qs-label h3-axis-label">
+ <div class="qs-label h3-axis-label" id="h3LengthLabel">
<span class="qs-name">Length</span>
<span class="qs-meta" id="h3LengthMeta"></span>
</div>
@@ -1097,44 +1110,92 @@
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 TAKE — the third axis, for BOTH engines: a length past a
- single clip. Same strip language as Quality and Length above
- (q-chip: name / spec / foot), so it reads as one more length
- choice, not a hidden mode. Picking a take locks the engine's
- own Length strip (a take IS the length), opens the beats box
- and prices the render from /take/estimate. Ids are unchanged
- from the Customize era (#takeGroup, data-take, #beatsRow,
- #beats_text, #takeEstimate) so setTakeSeconds / sbSetTake /
- Load Params keep working. -->
- <div class="take-axes" id="takeAxes">
+ <!-- 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">One take</span>
- <span class="qs-meta" id="takeHint">longer than one clip · the shot never cuts · <a href="/docs/prompting" target="_blank" rel="noopener">how to write the beats</a></span>
+ <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" id="takeGroup">
- <button type="button" class="q-chip pill-btn pill-quality active" data-take="0" onclick="setTakeSeconds(0)" title="One clip at the length chosen above.">
- <span class="ql-name">Off</span><span class="q-spec ql-spec sub">one clip</span><span class="ql-tier">length above</span></button>
- <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, 2 parts on H3.">
- <span class="ql-name">30 s</span><span class="q-spec ql-spec sub">6 beats</span><span class="ql-tier">2 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, 3 parts on H3.">
- <span class="ql-name">45 s</span><span class="q-spec ql-spec sub">9 beats</span><span class="ql-tier">3 parts</span></button>
- <button type="button" class="q-chip pill-btn pill-quality" data-take="60" onclick="setTakeSeconds(60)" title="One minute, one continuous shot: 12 beats of 5 s, 4 parts on H3.">
- <span class="ql-name">1 min</span><span class="q-spec ql-spec sub">12 beats</span><span class="ql-tier">4 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, 6 parts on H3.">
- <span class="ql-name">1½ min</span><span class="q-spec ql-spec sub">18 beats</span><span class="ql-tier">6 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, 8 parts on H3.">
- <span class="ql-name">2 min</span><span class="q-spec ql-spec sub">24 beats</span><span class="ql-tier">8 parts</span></button>
+ <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>
- <div class="qs-label h3-axis-label">
+ <!-- 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 · a blank line holds the moment</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 class="take-estimate" id="takeEstimate" aria-live="polite"></div>
</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) ==========
@@ -1674,10 +1735,9 @@
frames at 12fps, then exports a normal 24fps file with
motion interpolation. This is explicit because dialogue,
lip-sync, and fast motion need user judgment. -->
- <!-- ONE TAKE used to live here, in Customize. It is the length
- control for anything longer than one clip, so it sits with
- the other lengths now — #takeAxes, right under the engine's
- Quality / Length strips. -->
+ <!-- ONE SHOT used to live here, in Customize, then as a length
+ strip under Quality / Length. It is its own mode now — the
+ One Shot chip in the mode bar opens #takeAxes. -->
<div class="cz-control" id="temporalRow" data-ltx-only>
<div class="cz-label">Long clips
@@ -2797,14 +2857,14 @@
<span class="ql-name">24</span><span class="q-spec ql-spec sub">a film</span></button>
<button type="button" class="q-chip pill-btn" data-sb-shots="36">
<span class="ql-name">36</span><span class="q-spec ql-spec sub">long</span></button>
- <!-- ONE TAKE: a film that is one shot. The planner writes beats
+ <!-- ONE SHOT: a film that is one shot. The planner writes beats
(one per 5 s) instead of shots; the render is the Video tab's
- take. -->
+ One Shot. -->
<button type="button" class="q-chip pill-btn" data-sb-shots="take" title="One continuous shot that never cuts — the planner writes one beat per five seconds and the world changes around the subject">
- <span class="ql-name">1</span><span class="q-spec ql-spec sub">one take</span></button>
+ <span class="ql-name">1</span><span class="q-spec ql-spec sub">One Shot</span></button>
</div>
<div class="cz-control" id="sbTakeRow" hidden>
- <div class="cz-label">How long <span class="cz-label-hint">one beat per 5 seconds · the camera never cuts</span></div>
+ <div class="cz-label">One Shot length <span class="cz-label-hint">one beat per 5 seconds · the camera never cuts</span></div>
<div class="pill-group cols-5" id="sbTakeGroup">
<button type="button" class="pill-btn" data-sb-take="30"><span>30 s</span><span class="sub">6 beats</span></button>
<button type="button" class="pill-btn" data-sb-take="45"><span>45 s</span><span class="sub">9 beats</span></button>
diff --git a/webapp/js/boot.js b/webapp/js/boot.js
index 5bd2712..08029fd 100644
--- a/webapp/js/boot.js
+++ b/webapp/js/boot.js
@@ -471,7 +471,7 @@ function _autoMainOutputsFilterForMode(mode) {
// Auto-set NEVER lands on 'all' — that's user-only, per spec.
let target = null;
if (mode === 'image') target = 'photos';
- else if (mode === 't2v' || mode === 'i2v' || mode === 'keyframe' || mode === 'extend' || mode === 'restore' || mode === 'ingredients' || mode === 'control') target = 'videos';
+ else if (mode === 't2v' || mode === 'i2v' || mode === 'oneshot' || mode === 'keyframe' || mode === 'extend' || mode === 'restore' || mode === 'ingredients' || mode === 'control') target = 'videos';
if (!target) return;
// Same-filter early-return is conditional now: if the filter is already
// on `target` but the visible list is empty AND we haven't loaded the
@@ -643,6 +643,13 @@ 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.).
@@ -774,7 +781,11 @@ function setMode(mode) {
// picker keeps the previous mode's filter when flipping back from
// Studio to a video mode.
if (typeof renderLorasList === 'function') renderLorasList();
- document.getElementById('mode').value = mode;
+ // 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.querySelectorAll('#modeGroup .pill-btn').forEach(b => {
if (mode === 'keyframe') {
b.classList.toggle('active', isKeyframeModeChipActive(b, window._kfMode));
@@ -816,6 +827,11 @@ 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 2ef9151..f5cb99f 100644
--- a/webapp/js/characters.js
+++ b/webapp/js/characters.js
@@ -2593,15 +2593,30 @@ function temporalModeAllowed() {
const mode = document.getElementById('mode').value;
return !_qualityUsesHq(q) && currentMode !== 'extend' && currentMode !== 'keyframe' && (mode === 't2v' || mode === 'i2v');
}
-// ---- ONE TAKE ---------------------------------------------------------------
-// A length past a single clip plus one beat per five seconds. The server does
-// the arithmetic (make_job → take_plan); this only keeps the form honest: the
-// engine's own length pills lock while a take is on, the beats box prefills
-// from the prompt the first time, and the estimate comes from /take/estimate.
+// ---- 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 =>
@@ -2621,6 +2636,8 @@ function setTakeSeconds(s, beats) {
} 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();
@@ -2636,6 +2653,17 @@ function takePrefill(s) {
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');
@@ -2648,7 +2676,10 @@ function beatsInput() {
const n = Math.round(s / 5);
if (hint && n) {
const filled = lines.filter(Boolean).length;
- hint.textContent = `${n} beats of 5 s · ${filled} written` + (filled < n ? ' · a blank line holds the moment' : '') + (lines.length > n ? ` · the last ${lines.length - n} won't fit` : '');
+ const extra = lines.length - n;
+ hint.textContent = `${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;
@@ -2666,14 +2697,140 @@ async function takeRefresh() {
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 bits = [`${r.beats} beats`];
- if (r.engine === 'h3') bits.push(`${r.parts} parts of 15 s that continue from each other`);
- else bits.push('EXPERIMENTAL on LTX: the picture drifts across passes — use H3 for a take you will keep');
+ 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 (r.engine === 'ltx') bits.push('about 7 min per 5 s at Quick 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); }
function setTemporalMode(t) {
const allowed = temporalModeAllowed();
@@ -2854,6 +3011,8 @@ 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') {
@@ -2939,7 +3098,10 @@ 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, beatsInput, takeRefresh,
+ 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/engines.js b/webapp/js/engines.js
index f882020..83a0162 100644
--- a/webapp/js/engines.js
+++ b/webapp/js/engines.js
@@ -55,6 +55,11 @@ function engineStatus(e) {
// is the copy that decides.
function engineServesMode(e, mode) {
if (!e) return false;
+ // 'oneshot' is a UI mode that submits t2v (or i2v with an anchor) plus
+ // take_seconds; both engines render it — H3 as 15 s parts, LTX as 10 s —
+ // so it is asked about as the mode it ships under. Without this the chip
+ // would be folded as eng-foreign on H3, the engine the feature was built on.
+ if (mode === 'oneshot') mode = 't2v';
if ((e.excluded_modes || []).indexOf(mode) !== -1) return false;
if (!e.modes) return true;
return e.modes.indexOf(mode) !== -1;
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index fb5b1a6..9afe017 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -426,7 +426,16 @@ function setEngine(engine, opts) {
// which LTX rejects — it needs 8k+1. Snap on the way out so the field the
// user is now looking at is a value LTX will actually accept, and the
// bound Duration stays truthful.
- if (typeof snapFramesTo8kPlus1 === 'function') {
+ //
+ // ...unless One Shot is open. Its Length strip is FOLDED, so the user
+ // cannot see that H3's tier just wrote 73 into #frames, and cannot fix
+ // it: an LTX → H3 → LTX round trip left the folded length on "3s". A
+ // 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') {
try { snapFramesTo8kPlus1(); } catch (e) {}
}
// Give the active quality preset its upscale back (H3 forced it off).
@@ -456,11 +465,38 @@ 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 take's estimate is per engine (parts on H3, a chain on LTX).
- try { if (typeof takeRefresh === 'function') takeRefresh(); } 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;
}
+// The LTX length the user had before an engine round trip, put back from the
+// hidden #ltx_length — the one length field H3's shape writer never touches.
+// Only called while One Shot has the Length strip folded (see setEngine); on
+// the open strip the snap-to-8k+1 path stays, because there the user can see
+// the number and choose.
+function restoreFoldedLtxLength() {
+ const key = (document.getElementById('ltx_length') || {}).value
+ || (BOOT.ltx || {}).default_length || '5s';
+ const hit = ((BOOT.ltx || {}).lengths || []).find(l => l.key === key);
+ if (!hit || !Number.isFinite(Number(hit.frames))) return false;
+ const frames = document.getElementById('frames');
+ const duration = document.getElementById('duration');
+ if (frames) frames.value = hit.frames;
+ if (duration) duration.value = framesToDuration(Number(hit.frames));
+ return true;
+}
+
// The composer tools that SURVIVE an engine switch but change meaning across
// it. Everything else in that strip is folded by a data-<engine>-only rule and
// needs no JS at all — this exists only for the one control whose mechanism
@@ -870,7 +906,16 @@ function updateDerived() {
// expanded Customize body).
const derivedFooter = document.getElementById('derivedFooter');
if (derivedFooter) {
- derivedFooter.innerHTML = `<strong>${dur}s</strong> · ${finalRes}${temporalText}${accelText}`;
+ // 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}`;
}
// 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.
@@ -918,7 +963,9 @@ function updateDerived() {
// Mode-aware visibility
const inI2V = mode === 'i2v' || mode === 'i2v_clean_audio';
const inImageFlow = inI2V || currentMode === 'keyframe';
- document.getElementById('imageSection').classList.toggle('show', 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');
// 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') {
@@ -966,7 +1013,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);
+ if (i2vAudioSec) i2vAudioSec.classList.toggle('show', inI2V && currentMode !== 'oneshot');
// 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 —
@@ -1134,6 +1181,12 @@ 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();
}
@@ -1962,7 +2015,9 @@ async function poll() {
const jp = document.getElementById('jobPill');
if (s.running && s.current) {
const elapsed = Math.max(0, Math.round(s.server_now - s.current.started_ts));
- jp.innerHTML = `<span class="dot"></span>${s.current.params.label || s.current.params.mode} · ${elapsed}s`;
+ const _cp = s.current.params || {};
+ const _cpName = _cp.label || ((_cp.take && _cp.take.seconds) ? `One Shot · ${_cp.take.seconds} s` : _cp.mode);
+ jp.innerHTML = `<span class="dot"></span>${_cpName} · ${elapsed}s`;
jp.className = 'pill pill-running';
} else {
jp.innerHTML = `<span class="dot"></span>idle`;
@@ -2257,8 +2312,13 @@ async function poll() {
if (!s.queue.length) ql.innerHTML = '<li class="empty-state"><span></span><span>Queue empty</span><span></span><span></span></li>';
else ql.innerHTML = s.queue.map((j, i) => {
// Image jobs don't have width/height/frames; show n × aspect instead.
+ // A One Shot is named as one: the t2v/i2v underneath is how it is
+ // rendered, not what was asked for.
+ const _take = j.params.take && j.params.take.seconds;
const params = (j.params.mode === 'image')
? `image · ${j.params.aspect || '?'} · n=${j.params.n || '?'}`
+ : _take
+ ? `One Shot · ${_take} s · ${j.params.width}×${j.params.height}`
: `${j.params.mode} · ${j.params.width}×${j.params.height} · ${j.params.frames}f`;
// Which film this job is a shot of. A pure function of immutable params,
// so the qSig memoisation above needs no change.
@@ -3520,7 +3580,14 @@ async function loadParams() {
// Text. Fixed 2026-05-18: snap to Character mode when the sidecar
// carries a character_id so the form's UI state matches the saved
// intent, not the under-the-hood implementation.
- if (p.mode === 'extend') setMode('extend');
+ // A One Shot reopens as One Shot — the sidecar's `take` block is the intent;
+ // the t2v/i2v underneath is the implementation (the same shape as
+ // 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');
+ 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; }
else if (p.character_id) setMode('character');
@@ -3554,8 +3621,19 @@ async function loadParams() {
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 (p.take && p.take.seconds && typeof setTakeSeconds === 'function') setTakeSeconds(p.take.seconds, p.take.beat_prompts || p.take.beats || null);
- else if (typeof setTakeSeconds === 'function') setTakeSeconds(0);
+ 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');
+ }
+ } 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 || '';
@@ -3990,13 +4068,17 @@ function renderOutputInfoBody(path, data) {
return 'Multi-keyframe';
}
})();
- const modeLabel = ({
+ const _baseModeLabel = ({
t2v: 'Text → Video',
i2v: 'Image → Video',
i2v_clean_audio: 'Image → Video (clean audio)',
keyframe: keyframeModeLabel,
extend: 'Extend',
})[p.mode] || (p.mode || '—');
+ // One Shot is the mode the user chose; t2v/i2v is what it ran as.
+ const modeLabel = (p.take && p.take.seconds)
+ ? `One Shot · ${p.take.seconds} s (${_baseModeLabel})`
+ : _baseModeLabel;
// Compose the dimensions + duration into a single "Format" line — fewer
// grid rows, easier to scan. We separate technical metadata (Format,
diff --git a/webapp/js/storyboard.js b/webapp/js/storyboard.js
index 774b17c..2b03252 100644
--- a/webapp/js/storyboard.js
+++ b/webapp/js/storyboard.js
@@ -377,8 +377,8 @@ function sbLocInput() {
}
let _sbShots = 12;
-// ONE TAKE is the fifth answer on the Shots row: a film that is one shot,
-// planned as beats. `_sbTake` is 0 (off) or the take's length in seconds.
+// ONE SHOT is the fifth answer on the Shots row: a film that is one shot,
+// planned as beats. `_sbTake` is 0 (off) or the shot's length in seconds.
let _sbTake = 0;
function sbSetShots(n, persist) {
const take = (n === 'take');
@@ -1436,7 +1436,7 @@ function sbShotCard(s, r, errs) {
<textarea class="sb-shot-prompt" rows="3" spellcheck="false" data-act="prompt"
${locked ? 'readonly' : ''} title="${escapeHtml(s.title || '')}">${escapeHtml(s.prompt || '')}</textarea>
${s.take_seconds ? `
- <div class="sb-beats-label">One take · ${s.take_seconds} s · ${Math.round(s.take_seconds / 5)} beats <span class="sub">one line per 5 seconds · the first beat is the prompt above</span></div>
+ <div class="sb-beats-label">One Shot · ${s.take_seconds} s · ${Math.round(s.take_seconds / 5)} beats <span class="sub">one line per 5 seconds · the first beat is the prompt above</span></div>
<textarea class="sb-shot-prompt sb-beats" rows="${Math.min(12, Math.round(s.take_seconds / 5))}" spellcheck="false" data-act="beats"
${locked ? 'readonly' : ''}>${escapeHtml((s.beats || []).join('\n'))}</textarea>` : ''}
${mine.length ? `<div class="sb-shot-err">${mine.map(sbErrRow).join('')}</div>` : ''}
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index 640444d..6ecb333 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -5418,6 +5418,10 @@
display: flex; flex-direction: column; gap: 14px;
}
.cz-control { display: block; }
+ /* `display: block` beats the UA's [hidden] rule, so a row the JS folds
+ (#sbTakeRow when another shot count is chosen) kept rendering. Restate
+ the fold for every .cz-control rather than one id at a time. */
+ .cz-control[hidden] { display: none !important; }
.cz-label {
font-size: 11px; font-weight: 600;
color: var(--muted);
@@ -5540,7 +5544,9 @@
small so the bar height stays low. */
.mode-bar {
display: grid;
- grid-template-columns: repeat(5, 1fr);
+ /* Eight chips on LTX: two full rows of four. Five columns left the
+ second row three chips wide with two empty cells, every time. */
+ grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 4px;
padding: 4px;
background: var(--panel);
@@ -5561,6 +5567,10 @@
transition: var(--t-fast);
letter-spacing: 0;
text-align: center;
+ /* The name never breaks ("One / Shot" in a narrow pane); the sub-line
+ below it may. */
+ white-space: nowrap;
+ min-width: 0;
}
.mode-bar .mode-chip:hover {
color: var(--text);
@@ -5579,6 +5589,7 @@
letter-spacing: 0.02em;
text-transform: none;
opacity: 0.85;
+ white-space: normal;
}
.mode-bar .mode-chip.active .mc-sub {
color: var(--accent-bright);
@@ -5596,6 +5607,13 @@
to LTX brings its modes with it. Driven entirely by the ENGINES
registry, so a third engine scopes itself with no new CSS. */
.mode-bar .mode-chip.eng-foreign { display: none; }
+ /* On any other engine most of those chips are folded (H3 shows three), and
+ a fixed four-column grid would leave a hole. auto-fit lays the chips
+ that ARE there across one row — a hidden chip generates no grid item,
+ so it claims no cell. LTX keeps its two rows of four above. */
+ body:not([data-engine="ltx"]) .mode-bar {
+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
+ }
/* The Remix sub-row has THREE tools, not five. It inherited `.mode-bar`'s
5-column grid, so each tool got 3/5 of a column's worth of room and the
@@ -9979,11 +9997,31 @@
.ghost-btn.small { padding: 3px 9px; font-size: var(--fs-sm, 12px); }
.lora-update-badge { cursor: pointer; }
-/* ---- One take ---------------------------------------------------------------- */
-/* One take — the third axis under Quality / Length, same grid rhythm as
- .h3-axes; the beats box opens beneath the strip when a take is picked. */
-.take-axes { display: grid; gap: 8px; margin-top: 2px; }
+/* ---- One Shot ---------------------------------------------------------------- */
+/* One Shot — its own mode's panel (#takeAxes), opened by setMode('oneshot').
+ Same grid rhythm as .h3-axes and the Character strip: label rows, one
+ chip strip, then the beats box, the anchor image, the two continuity pill
+ pairs, the estimate and the engine note. `display: grid` beats the UA's
+ [hidden] rule, so the fold is restated — the same lesson .quality-strip
+ learned. */
+.take-axes { display: grid; gap: 8px; margin-top: 2px; min-width: 0; }
+.take-axes[hidden] { display: none !important; }
+/* Nothing in here may hold a width of its own: a grid child defaults to
+ min-width:auto, and five chips of min-content made the panel ~404px wide
+ and clipped it in a 1100px pane. */
+.take-axes > *, .take-axes .q-chip, .take-axes .pill-group { min-width: 0; }
+.take-axes .quality-strip.cols-5 { grid-template-columns: repeat(5, minmax(0, 1fr)); }
.take-axes .h3-axis-label { margin: 2px 0 -2px 0; }
+/* Label rows: the name never touches the hint. The hint may wrap, right-aligned
+ under itself. */
+.take-axes .qs-label { gap: 10px; }
+.take-axes .qs-label .qs-name { flex: 0 0 auto; white-space: nowrap; }
+.take-axes .qs-label .qs-meta { min-width: 0; white-space: normal; text-align: right; }
+.take-axes a { color: var(--accent-bright); }
+/* The Beats row carries its split button on the right of the label. */
+.take-axes .beats-label { align-items: center; }
+.take-axes .beats-label .qs-meta { flex: 1 1 auto; }
+.take-axes .beats-label .ghost-btn { flex: 0 0 auto; white-space: nowrap; }
.take-axes .take-beats { display: grid; gap: 6px; }
.take-axes .take-beats[hidden] { display: none !important; }
.take-axes .sb-textarea { width: 100%; box-sizing: border-box; }
@@ -9991,6 +10029,33 @@
.take-locked::after { content: ''; }
#beatsRow { margin-top: 8px; }
.take-estimate { margin-top: 6px; font-size: var(--fs-sm, 12px); color: var(--muted); min-height: 1.2em; }
+/* The part labels are written per engine by oneshotRefreshLabels(). */
+.oneshot-panel #takeGroup .q-chip { justify-content: flex-start; min-height: 56px; }
+.oneshot-panel #takeGroup .q-chip .ql-tier { white-space: nowrap; color: var(--muted); }
+.oneshot-panel .oneshot-anchor { display: grid; gap: 6px; margin-top: 4px; }
+.oneshot-panel .oneshot-anchor-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-height: 32px; }
+.oneshot-panel .oneshot-anchor-thumb { width: 56px; height: 56px; object-fit: cover; border-radius: var(--r-sm); border: 1px solid var(--border); }
+.oneshot-panel .oneshot-anchor-thumb[hidden] { display: none !important; }
+.oneshot-panel .oneshot-anchor-name { font-size: var(--fs-sm, 12px); color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 240px; }
+.oneshot-panel .oneshot-toggles { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; margin-top: 4px; }
+.oneshot-panel .oneshot-toggle { display: grid; gap: 6px; min-width: 0; }
+/* A toggle's header stacks the name over its hint: side by side, the name
+ wrapped to three lines beside a three-line hint in half a panel. */
+.oneshot-panel .oneshot-toggle .qs-label { flex-direction: column; align-items: flex-start; gap: 2px; }
+.oneshot-panel .oneshot-toggle .qs-meta { font-family: inherit; white-space: normal; text-align: left; }
+.oneshot-panel .oneshot-toggle .pill-group { margin-bottom: 0; }
+.oneshot-panel .oneshot-note { font-size: var(--fs-sm, 12px); color: var(--muted); }
+/* A shot IS the length: while One Shot is open the engine's own Length
+ strip (and its label) is folded, on both engines. A body class rather than
+ `hidden`, because setEngine re-shows those strips by id on every switch. */
+body.oneshot-mode #ltxAxes,
+body.oneshot-mode #h3LengthLabel,
+body.oneshot-mode #h3LengthGroup { display: none !important; }
+/* Two toggles side by side need more than a narrow pane gives them; 720px
+ was too late — at 1100px each half was already a column of wrapped words. */
+@media (max-width: 1100px) {
+ .oneshot-panel .oneshot-toggles { grid-template-columns: minmax(0, 1fr); }
+}
.sb-beats-label { margin-top: 8px; font-size: var(--fs-sm, 12px); color: var(--muted); }
.sb-beats-label .sub { opacity: .8; margin-left: 6px; }