Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
release(v4.6.0): the timeline stopped being a strip and became an editor
mrbizarroac9b96b34e87
diff --git a/CHAR_QUALITY_NOTES.md b/CHAR_QUALITY_NOTES.mdnew file mode 100644index 0000000..b06125b--- /dev/null+++ b/CHAR_QUALITY_NOTES.md@@ -0,0 +1,124 @@+# LTX-2.5 character quality unlock receipts++## Contract++- `BOOT.ltx.character.tokens` is the shared source for both character quality+ surfaces. LTX-2.5 publishes `draft`, `pro`, `high`, and `high720`; LTX-2.3+ continues to publish only `draft` and `pro`.+- The default remains `pro`, which resolves to the graded q8 + distilled+ `balanced` pipeline at 1024×576.+- `high` resolves to the real `high` HQ cell at 1024×576 (`~4 min / 5s`).+ `high720` resolves to `high_720p` at 1280×704 (`~8 min / 5s`). Both labels+ come from the same `LTX_TIERS` cells the main quality strip renders.+- Draft/Pro require the q8 pack. High/High 720p require the q8 pack and the+ active generation's HQ add-on. Both character surfaces call the main strip's+ `ltxCellNeedsInstall()` / `ltxCellInstallLabel()` helpers, attach+ `.needs-install`, and route clicks to the Models modal.+- Job params record both meanings: `quality_choice` is the four-token UI value;+ `quality` is the actual pipeline quality. This distinguishes Pro from High+ even though both use a 1024×576 canvas.++## Legacy sidecar choice++There is no feature-schema or release field that reliably distinguishes a+pre-unlock bare `quality=high` sidecar from a new one. The accepted migration+choice is therefore:++- on LTX-2.5, a bare legacy `quality=high` now reopens as the first-class High+ chip;+- a sidecar that already carries explicit `quality_choice=pro` remains Pro;+- `quality=high_720p` maps to `high720`, while legacy `balanced` / `standard`+ continue to reopen as Pro.++New sidecars always carry `quality_choice`, so the ambiguity ends at this+feature boundary.++## Rendered DOM receipt++The real `renderCharacterStrip()` and `charactersRenderChips()` functions were+executed in Node against the LTX-2.5 bootstrap payload. Four buttons render in+each surface, and Pro is the sole active default:++```json+{+ "main_character_strip": [+ {"token": "draft", "active": false},+ {"token": "pro", "active": true},+ {"token": "high", "active": false},+ {"token": "high720", "active": false}+ ],+ "characters_tab": [+ {"token": "draft", "active": false},+ {"token": "pro", "active": true},+ {"token": "high", "active": false},+ {"token": "high720", "active": false}+ ]+}+```++With the q8 pack present and the HQ add-on missing, both DOM fragments render+exactly two `.needs-install` chips: `high` and `high720`. Draft and Pro remain+ordinary selectable q8-distilled chips.++## High 720p job-dict receipt++A real local `/queue/add` handler invocation used `quality_choice=high720`, face+strength `0.9`, and voice strength `1.25`. Synthetic safetensors headers kept+the receipt model-free while exercising the real character compatibility and+LoRA-stack construction:++```json+{+ "http_status": 200,+ "quality_choice": "high720",+ "quality": "high_720p",+ "canvas": [1280, 704],+ "pipeline": "hq",+ "dispatch_action": "generate_hq",+ "character_id": "bizarrotrn",+ "character_strength": 0.9,+ "character_voice_strength": 1.25,+ "lora_strengths": [0.9, 1.25]+}+```++The HQ dispatch copies the complete `params.loras` list into `hq_loras`, so the+face and voice adapters reach the two-stage pipeline in the same order and at+the same strengths. Existing no-voice gating is unchanged.++## Gates++```text+test_character_roundtrip.py+ 35 tests, OK+ Includes all four payload -> job params/sidecar -> real JS reload paths.++scripts/assert_registry.py+ 169 passed, 0 failed, 0 known defects++scripts/assert_schedules.py+ 45 passed, 0 failed+ Includes character High for both generations and character High 720p on 2.5.++test_lora_compat.py+ 9 tests, OK++test_storyboard.py+ 55 tests, OK++test_storyboard_planner.py+ 109 tests, OK, 1 opt-in live-model test skipped++Python py_compile, extracted inline JavaScript `node --check`, and+`git diff --check`+ PASS+```++`assert_schedules.py` now loads the checked-in pure-Python scheduler source with+minimal import stubs. The earlier exact command aborted before assertions when+MLX tried to enumerate a sandbox-hidden Metal device, despite this gate using+only sigma lists. No schedule logic is stubbed; the constants and functions+under test still come from the vendored `scheduler.py`.++No GPU render was launched for these receipts. No version, changelog, release+metadata, or remote branch was changed.diff --git a/CLAUDE.md b/CLAUDE.mdindex 7b43c62..123ca70 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8,9 +8,20 @@ section overrides it where they conflict.----## 0. Current state — Phosphene v3.0.6 (current public release, 2026-05-31)+## 0. Current state — read `docs/STATE.md` first-Public release is **v3.0.6**. The v3.0 line launched 2026-05-23 and has+**THE RELEASE FACTS IN THIS SECTION ARE OLD.** `VERSION` on this branch and+`docs/STATE.md` are the two things that are current; the v3.0 history below is+kept as background and nothing else. As of 2026-08-19: `VERSION` reads+**4.6.0**, and public `main` is at **v4.5.0** — v4.6.0 was promoted and+withdrawn the same day (the Editor shipped before the owner had cut with it),+so what a user can install and what this branch is are two different numbers.+Which release the front page advertises, and when v4.6.0 goes back out, are+the owner's calls; do not settle them from a doc-hygiene pass.++### Historical — the v3.0 line++Public release was **v3.0.6**. The v3.0 line launched 2026-05-23 and hasshipped six patch releases: v3.0.0 (Characters/Voice/Image Studio/A2V) →v3.0.1 (FFLF crash fix) → v3.0.2 (Boost/Turbo accel restored after a2-month silent regression) → v3.0.3 (HiDream hidden, issue #15) → v3.0.4@@ -614,58 +625,29 @@ prompts. Below -25 dB peak suggests a regression.symlinked instruction file, replace that one with a 5-line stub pointinghere — do not fork the full content back out.-## 11. HTTP API reference (panel)+## 11. HTTP API reference — see `docs/API.md`-The panel listens on `127.0.0.1:8198` and serves a single-page HTML/JS-UI plus a JSON API. Pinokio proxies its own port 42000 to 8198. All-endpoints are unauthenticated (loopback only).+**There is one API reference and it is `docs/API.md`.** This section used to+carry a second copy of the endpoint tables, and a second copy is a copy that+drifts: it listed ~13 GET and ~20 POST routes and none of Storyboard, Editor,+Characters, Train or the Ideogram API, and it stated the port as `8198` flatly+while §7 states the rule correctly. Both of those were wrong in ways a reader+could not detect from inside this file.-### GET endpoints+The two things worth keeping here, because they are rules rather than tables:-| Path | Returns | Notes |-|---|---|---|-| `/` | HTML | The single-page UI. Built from one big template string in `mlx_ltx_panel.py`. |-| `/status` | JSON | Snapshot of `STATE` — running flag, current job, queue, history (top 20), log tail, tier, memory pressure, helper alive flag, comfy PIDs, repo download state. Polled by the UI every ~1s. |-| `/uploads` | JSON | Recent files in `panel_uploads/` for the picker's "click to reuse" strip. |-| `/models` | JSON | Per-repo install completeness — driven by `required_files.json`. |-| `/settings` | JSON | Returns `{settings, presets, default_preset}`. `settings` is the current `panel_settings.json` content. `presets` is the OUTPUT_PRESETS table (label + blurb + pix_fmt + crf per preset) so the UI doesn't duplicate it. |-| `/loras` | JSON | Returns `{user, curated, loras_dir, civitai_auth}`. `user` is the scanned `mlx_models/loras/*.safetensors` list (each with sidecar metadata if present). `curated` is the curated Lightricks repo registry minus the HDR-toggle entry (which is exposed as a plain checkbox, not in the picker). `civitai_auth` is True iff `CIVITAI_API_KEY` is set in the panel's env. |-| `/civitai/search` | JSON | Proxies CivitAI's `/api/v1/models` filtered to `types=LORA&baseModels=LTXV 2.3`. Query params: `query`, `nsfw` (bool), `cursor` (CivitAI uses cursor pagination), `limit`. Returns `{items, next_cursor, has_more}` with each item carrying `{id, version_id, name, creator, description, downloads, nsfw, preview_url, filename, size_kb, download_url, trigger_words, base_model, civitai_url}`. |-| `/file?path=…` | bytes (mp4/png/jpg) | Range-aware video serve so `<video>` tags can seek without re-downloading. |-| `/image?path=…` | bytes (image) | Same idea for image previews. |-| `/sidecar?path=…` | JSON | Per-output sidecar (job params, output stats) if it exists. |-| `/assets/<file>` | bytes | Static files from `assets/`. |--### POST endpoints--| Path | Body | Returns | Effect |-|---|---|---|---|-| `/run` `/queue/add` | urlencoded job spec | `{ok, id}` | Creates a job, appends to queue. Field reference below. |-| `/queue/batch` | urlencoded with `prompts` (newline-separated, `---` chunks) | `{ok, added, ids}` | Splits the prompts on `^\s*---\s*$` boundaries, creates one job per chunk. |-| `/queue/remove` | `id=<jid>` | `{removed: bool}` | Drop a queued job by id. |-| `/queue/clear` | (none) | `{cleared: int}` | Clear all queued jobs (running job continues). |-| `/queue/pause` | (none) | `{paused: true}` | Worker stops popping new jobs after the current one. |-| `/queue/resume` | (none) | `{paused: false}` | Worker resumes. |-| `/output/hide` | `path=<p>` | `{hidden: path}` | Adds path to the gallery's hidden set (persisted). |-| `/output/show` | `path=<p>` | `{shown: path}` | Inverse. |-| `/output/show_all` | (none) | `{unhidden_count: int}` | Clear hidden set. |-| `/upload` | multipart `image=<file>` | `{ok, path}` | Saves to `panel_uploads/<ts>_<safename>`. |-| `/helper/restart` | (none) | `{ok}` | SIGTERM the helper subprocess; the next job auto-respawns it. Useful for picking up site-packages changes. |-| `/settings` | `output_preset` / `output_pix_fmt` / `output_crf` / `civitai_api_key` / `hf_token` (any subset) | `{ok, settings, helper_restarted}` | Update + persist. Public-safe `settings` view in the response (no token values, just `has_*` booleans). Helper killed on codec change OR token change so the next job spawns with fresh env. Form parser uses `keep_blank_values=True` so `civitai_api_key=` (the Clear button) is treated as "remove this token" rather than dropped silently. Empty input on the front-end Apply path is "leave as-is" — explicit clearing goes through the dedicated Clear button. |-| `/loras/refresh` | (none) | `{ok, user, loras_dir}` | Rescan `mlx_models/loras/`. Filesystem is the source of truth; no caching layer to invalidate. |-| `/loras/delete` | `path=<abs path>` | `{ok, removed}` | Delete a user-installed LoRA + its sidecar. Path must resolve inside `mlx_models/loras/` to prevent traversal. |-| `/civitai/download` | `download_url=<civitai url>`, `meta=<json>` | `{ok, name, path, sidecar_path, size_bytes, skipped}` | Stream-download a LoRA from CivitAI into `mlx_models/loras/`, write a sidecar JSON. Refuses non-civitai.com hosts. Writes to a `.partial` then atomic-renames so a kill mid-write leaves nothing the next scan would mistake for a complete file. Surfaces 401 with a remediation hint pointing at `CIVITAI_API_KEY`. |-| `/stop` | (none) | `{ok}` | Cancel the current job (kills helper + mux). Worker advances. |-| `/stop_comfy` | (none) | `{ok, killed}` | SIGTERM any ComfyUI process matching `LTX_COMFY_PATTERN`. |-| `/open_pinokio` | (none) | `{ok}` | macOS-only: focus the Pinokio app. |-| `/models/download` | `key=q4|q8|gemma` | `{ok}` | Spawn `hf download` for the named repo. Streams to log. |-| `/models/cancel` | (none) | `{ok, killed}` | SIGTERM the active download. |-| `/prompt/enhance` | `prompt=<p>` | `{ok, original, enhanced}` | Calls helper's Gemma-rewrite path. |+- **The port follows the profile.** `DEFAULT_PORT = 8199 if PROFILE == "dev"+ else 8198` (`mlx_ltx_panel.py:275`), overridable with `LTX_PORT`. A dev+ checkout answers on 8199 and shows the DEV badge; a normal install answers+ on 8198. Pinokio proxies its own port 42000 to the panel.+- **Everything is unauthenticated and loopback-only.** There is no auth layer+ to add a route to, so a route that should not be reachable must not exist.## 12. Job spec — the contract for `/run` and `/queue/add`Every form field below maps to `params.<field>` on the resulting job.-`make_job()` in `mlx_ltx_panel.py:1140` is the canonical reference.+`make_job()` in `mlx_ltx_panel.py` is the canonical reference (search for+`def make_job(` — it is around line 16145 and moves with every edit above it).| Field | Type | Default | Meaning ||---|---|---|---|@@ -1353,41 +1335,16 @@ Tracked here so they don't get lost between sessions.- Q8 weights: `dgrauet/ltx-2.3-mlx-q8` on HF- Gemma text encoder: `mlx-community/gemma-3-12b-it-4bit` on HF-## 24. Agentic Flows module (`agent/`, shipped 2026-05-06)--A chat-driven shot planner tab in the form-pane. User pastes a script,-agent breaks it into shots, queues them through the existing `/queue/add`-path, writes a `mlx_outputs/agentflow_<id>/manifest.json`, and finishes.--**See:** `docs/AGENTIC_FLOWS.md` for the user reference.--The `agent/` package is pure-stdlib Python — imports nothing from-`mlx_ltx_panel.py`. The panel injects a `tools.PanelOps` callback bundle-at dispatch time so the agent can submit jobs, snapshot the queue, and-look up jobs by id without circular imports.--| File | Role |-|---|---|-| `agent/engine.py` | OpenAI-compat `chat()` client + `EngineConfig` + role-alternation normalizer for the wire format. |-| `agent/local_server.py` | Spawns `mlx_lm.server` with safe flags (`--prompt-cache-size 0 --prefill-step-size 8192 --prompt-concurrency 1 --decode-concurrency 1` — sidesteps the mlx-lm 0.31.1 cache-merge bug). Discovers chat-capable models in `mlx_models/`. |-| `agent/tools.py` | Tool registry + dispatcher. PanelOps protocol. Tools: `estimate_shot`, `submit_shot`, `get_queue_status`, `wait_for_shot`, `extract_frame`, `upload_image`, `write_session_manifest`, `finish`. |-| `agent/prompts.py` | System prompt builder. Encodes Phosphene's operator manual (modes, empirical wall times from §0, failure modes, prompting rules). Single source of truth — update STATE.md / this file → prompt picks it up next turn. |-| `agent/runtime.py` | Session dataclass, `run_turn()` generator (chat→tool→chat loop with max_steps cap), atomic-replace persistence to `state/agent_sessions/<id>.json`. |--**Tool fenced-block protocol.** Models emit one ` ```action {tool, args} ``` ` block per turn (in their assistant content); the runtime parses, dispatches, feeds the result back as a `<tool_result>...</tool_result>` user message, and loops. No reliance on OpenAI's tool-calling spec — universal across every Chat Completions server.--**Engine pluggability.** Default = Phosphene Local (`mlx_lm.server` against the bundled Gemma 3 12B IT). Custom = any OpenAI-compatible URL + key (Anthropic compat, OpenAI, OpenRouter, LM Studio). Stronger local = drop a chat-capable MLX model in `mlx_models/`. See `docs/AGENTIC_FLOWS.md` § Engine options.--**HTTP endpoints** (added to `mlx_ltx_panel.py`; documented in §11):-- `GET /agent/config`, `GET /agent/sessions`, `GET /agent/sessions/<id>`, `GET /agent/local/status`-- `POST /agent/config`, `POST /agent/local/{start,stop}`, `POST /agent/sessions/new`, `POST /agent/sessions/<id>/{message,delete}`+## 24. Agentic Flows — REMOVED 2026-05-15-**Persistence.** `state/agent_config.json` (engine config, api_key masked in HTTP responses) + `state/agent_sessions/<id>.json` (one chat thread, atomic-replaced on every turn). Both under `state/` which is fs.link symlinked + gitignored.+The in-panel chat agent and its `agent/` package are gone: the `/agent/*`+namespace answers 410 Gone, `agent/` is not on disk and neither is the+`docs/AGENTIC_FLOWS.md` this section used to point at. External agents drive+the panel over the HTTP API instead — `docs/API.md`.-**Don't do** when working in this area:-- Don't add per-provider client code. The OpenAI-compat shape is the universal interface.-- Don't bypass `panel_ops.submit_job` to write directly into `STATE['queue']` — `make_job()` is the canonical job-spec builder, with tier clamps, defaults, and validation. The agent goes through the same path the manual UI does.-- Don't auto-stitch the rendered clips. The user wanted the manifest, not a finished movie. Keep it that way.+This heading is kept rather than deleted because the section it replaces+survived three months of "read CLAUDE.md first" sessions, teaching every one+of them about a subsystem it could not find.---diff --git a/DEBUG_FINDINGS.md b/DEBUG_FINDINGS.mdnew file mode 100644index 0000000..f87c07d--- /dev/null+++ b/DEBUG_FINDINGS.md@@ -0,0 +1,129 @@+# Eltrumpo character/LoRA routing investigation++Date: 2026-08-14++The requested notes directory (`/Users/salo/AI/projects/phosphene/notes/`) is+outside this session's writable sandbox, so this repository-root receipt is the+requested fallback. Nothing under the running production install was modified,+and the panel process on port 8198 was not contacted, restarted, or stopped.++## Production evidence (read-only)++The newest matching sidecar at investigation time was:++`mlx_outputs/eltrumpo_on_a_red_bikini_very_720p.mp4.json`++It recorded:++- `mode`: `t2v`+- `engine`: `ltx`+- `quality`: `balanced`+- active checkpoint: `mlx_models/ltx-2.5-mlx-q8`+- `character_id`: `eltrumpo`+- `character_strength`: `1.0`+- `character_voice_strength`: `1.0`+- face adapter: `mlx_models/loras/eltrumpo_v2.safetensors` at `1.0`+- voice adapter: `mlx_models/loras/eltrumpo.audio.safetensors` at `1.0`+- 1024x576, 241 frames, 8 steps, seed 444027839+- elapsed time: 483.67 seconds++That establishes the **Characters/cast lane**. It was not a bare user-LoRA+picker job and not a hand-written API request. It also rules out class (a): the+character files were present in the serialized job.++The production library held one face adapter and one voice adapter for this+trigger—no duplicate face entry and no alternate `eltrumpo (high)` file:++| File | Bytes | SHA-256 |+|---|---:|---|+| `eltrumpo_v2.safetensors` | 528,644,216 | `374c16b63c8f533d0865b8c22e7508083d6d4510257528dc2eb4c1db99f783f4` |+| `eltrumpo.audio.safetensors` | 176,521,472 | `34f6ab745b123d4955c6bf9960e2a7a0716f9007e4100cbd72a139c9ddbf31fd` |+| `eltrumpo.voice.wav` | 2,205,078 | `d4b288380d17d46887f346fe7a6fed5c3d2e85d399d896327f151ea0363e8ceb` |++`mlx_models/characters/eltrumpo/` contained only `avatar.png`; discovery+therefore followed the legacy, deterministic `<trigger>_v2.safetensors`+convention. The face sidecar's display name is `eltrumpo (high)`, but that is+metadata for the same hash above, not a second adapter. This rules out class+(c).++Header-only comparison against the exact LTX-2.5 Q8 distilled transformer+found a complete match for both files:++```text+eltrumpo_v2.safetensors FUSED=1152/1152 tensors (576/576 modules)+eltrumpo.audio.safetensors FUSED=1152/1152 tensors (576/576 modules)+```++The production log/state trees contained no per-file `FUSED` tally for this+job. The running helper generation logged queueing/fusion intent but did not+persist the loader's applied-module report, so an historical live count cannot+be reconstructed after the fact. The evidence therefore does **not** support a+wrong-layout/zero-match diagnosis for class (b); the files are structurally+valid. It also cannot honestly prove the old process applied all 576 modules.++## Root cause found in the load path++Phosphene still installed its historical subclass fusion shim even though the+pinned LTX engine now has a native LoRA-aware transformer loader. On this exact+Balanced/Q8 path the shim intercepts `DistilledPipeline.load()`, fuses the+adapters into quantized weights, and sets `self.dit` before the native loader+can select its `auto -> unfused` runtime path. The native path exists precisely+to preserve character deltas on quantized checkpoints; bypassing it can weaken+identity while still returning an entirely plausible clip.++This is the actionable routing/loading failure. It is separate from an absent+job entry, duplicate selection, or incompatible key layout, and the old logs+were insufficient to distinguish a degraded application from a full runtime+no-op. The fix makes that ambiguity impossible on future jobs.++## Fix receipts++- `lora_compat.py` reads safetensors headers without materializing weights,+ mirrors the pinned ComfyUI key remap, and requires complete A/B pairs with at+ least 90% module coverage (current valid character files are 100%).+- The modern helper now uses the engine's native exact runtime-LoRA route. The+ old forced-fusion shim remains only as a compatibility fallback for engines+ that lack the native seam.+- Immediately after live attachment, the helper compares the runtime report+ with each file's expected modules. It emits durable lines shaped like+ `LoRA[n] strength=… FUSED=… file=…` and raises a file-naming error for zero or+ anomalously few modules before denoising.+- The Characters endpoint and Ingredients character picker omit incompatible+ bundles. The ordinary LTX LoRA picker hard-hides incompatible rows even when+ “Show other modes” is enabled.+- The enqueue seam repeats the compatibility check, so stale browser state and+ direct API calls cannot bypass the library filter.+- `test_lora_compat.py` covers full, zero, partial, dangling-pair, live-runtime,+ and character-library filtering/refusal cases. Existing character API+ fixtures now use structurally valid synthetic safetensors headers.++## Verification++- `python3 test_lora_compat.py`: **9 passed**+- `python3 test_character_roundtrip.py`: **27 passed**+- Python bytecode compilation for the changed Python files: **passed**+- `git diff --check`: **passed**+- `node scripts/check_pinokio_scripts.js`: **PASS** (53 dispatches; worst 377/500)+- `node scripts/check_ltx_pin.js`: **PASS** (`v0.14.19+ltx25.3`)+- `node scripts/check_post_update.js`: **PASS**+- `python3 scripts/assert_registry.py`: **154 passed, 0 failed**+- `python3 scripts/assert_schedules.py`: the exact requested command cannot+ import `ltx_pipelines_mlx` from the sandbox's system Python. The repository+ venv reaches the package but MLX aborts while enumerating the sandbox-hidden+ Metal device. A no-GPU harness loaded the same checked-in `scheduler.py`+ directly and the gate completed **42 passed, 0 failed**. The source/test+ changes do not touch schedules.++## Delivery status++The fix is present in this dev worktree, but this session could not update Git+metadata or the beta remote:++- `.git/index.lock` creation is denied because `.git` is mounted read-only.+- direct `git fetch`/`git push` cannot resolve `github.com` in the network+ sandbox.+- an authenticated private-beta connector fallback was attempted only after+ verifying `main` still pointed to `d29cdbb`; its upload was cancelled, and a+ read-back confirmed beta remained unchanged at `d29cdbb`.++No public branch or production file was changed.diff --git a/ENHANCE_DEBUG.md b/ENHANCE_DEBUG.mdnew file mode 100644index 0000000..94c260f--- /dev/null+++ b/ENHANCE_DEBUG.md@@ -0,0 +1,112 @@+# `/prompt/enhance` empty-response debug record++Date: 2026-08-14++## Outcome++The helper IPC did not drop a successful reply, and trigger-token restoration+was never reached. The active LTX-2.5 registry selection made the shared+`LTX_GEMMA` environment variable resolve to the vendored Gemma 4 render text+tower. The prompt enhancer then tried to build `GemmaLanguageModel` from that+root. The tower correctly rejected the request because it has no language-model+head or KV cache; prompt rewriting still requires the installed Gemma 3 root.++The client had a 120-second deadline. Loading the wrong tower consumed that+deadline before the helper returned its structured error. The panel caught the+error and called `_json(..., 500)`, but the client socket was already gone, so+`end_headers()` raised `BrokenPipeError`. That ordering explains the observed+empty body: the response serializer did not discard JSON; it tried to write the+JSON error after the caller had timed out.++## Evidence++- The restricted execution sandbox could not connect to the live loopback+ listener even though a read-only `lsof` check showed the production panel on+ `127.0.0.1:8198`. The same sandbox rejected a test `bind()` on port 8262 with+ `EPERM`, so no production process was modified, signalled, or restarted.+- Read-only inspection of the running panel's actual stdout log recovered the+ request traceback. `WarmHelper._dispatch_run_event()` raised the helper's+ explicit error:++ ```text+ Prompt enhancement is not available on the vendored Gemma 4 tower+ (it builds the text-encoder path only — no lm_head, no KV cache).+ Point the enhancer at a Gemma 3 root.+ ```++- The next traceback frame was the handler's attempted JSON 500 response,+ ending in `BrokenPipeError` while flushing headers to the expired client.+- Both model roots are present in the read-only production install: Gemma 3 is+ approximately 7.5 GB and Gemma 4 is approximately 6.3 GB. The Gemma 3 root+ contains both required safetensor shards, tokenizer files, and config. This+ was a resolver regression, not a missing download.+- `f1d2139` introduced the version-aware render-encoder seam:+ `env["LTX_GEMMA"] = text_encoder_dir()`. That is correct for LTX-2.5 render+ conditioning, but `get_gemma_lm()` also consumed `LTX_GEMMA`, incorrectly+ coupling the generative enhancement lane to the active render generation.++## Fix++1. `WarmHelper._ensure()` now exports two independent paths:+ - `LTX_GEMMA`: active generation's render text encoder (Gemma 4 for LTX-2.5).+ - `LTX_ENHANCE_GEMMA`: the installed generative Gemma 3 root.+2. `mlx_warm_helper.py:get_gemma_lm()` loads `LTX_ENHANCE_GEMMA` and retains a+ Gemma 3 Hugging Face fallback for standalone helper use.+3. `/prompt/enhance` passes an enhance-only 90-second helper deadline. A silent+ helper is killed and converted to a JSON 500 before the normal 120-second UI+ or curl deadline can expire.+4. Malformed helper terminal events (non-dict results or non-string enhanced+ prompts) are also converted to JSON 500 responses instead of raising after+ the handler's exception boundary.++## Regression coverage++`test_prompt_enhance_endpoint.py` is an executable stdlib regression test. On a+normal host it starts the real panel on `127.0.0.1:8262`, with isolated state,+output, upload, and model directories under a temporary repo-root scratch+directory. A newline-JSON helper double verifies that the render lane receives+Gemma 4 while enhancement receives Gemma 3, then exercises:++- a successful enhanced-prompt JSON body;+- a structured helper failure with a non-empty JSON 500 body;+- a malformed successful event with a non-empty JSON 500 body;+- a silent helper with a bounded, non-empty JSON timeout body.++The current sandbox cannot bind loopback, so that instance case reports a+precise skip here. Its companion test directly executes the same real+`Handler.do_POST` plus `WarmHelper` subprocess round-trip without a socket; all+four success/error/malformed/timeout assertions pass. No model weights or GPU+are used.++Run:++```bash+python3 test_prompt_enhance_endpoint.py+```++## Verification record++Passed in the shared dev worktree:++- `node scripts/check_pinokio_scripts.js`+- `node scripts/check_ltx_pin.js`+- `node scripts/check_post_update.js`+- `python3 scripts/assert_registry.py` — 154 passed, 0 failed, 0 pinned defects+- `python3 test_prompt_enhance_endpoint.py` — restricted-sandbox handler/IPC+ path passed; the real port-8262 case skipped only because `bind()` returned+ `EPERM`+- Python compile checks for the panel, helper, and regression test+- `git diff --check`++`python3 scripts/assert_schedules.py` could not import the vendored package from+the system interpreter. The repository-venv invocation reached `mlx.core`, but+this sandbox exposes an empty Metal device list and MLX aborted in its native+device constructor before the gate imported the scheduler. This is an+execution-environment block, not a failed schedule assertion; the gate must be+re-run in the normal Pinokio terminal before promotion.++Git finalization is also environment-blocked in this session: the shared+worktree's `.git` directory is mounted read-only (`FETCH_HEAD: Operation not+permitted`), while a disposable writable clone cannot resolve `github.com`.+Consequently the requested rebase, commits, and beta push cannot be performed+from this sandbox unless those restrictions are lifted.diff --git a/README.md b/README.mdindex 4a31926..2d17584 100644--- a/README.md+++ b/README.md@@ -60,6 +60,10 @@ Qwen-Image-Edit (Lightning 4-step) is the default image engine. It handles instrEnd-to-end LoRA training inside the panel. The dataset uploader accepts 15 to 500 images per character. Captions are written by a local Gemma 3 12B (MLX, 4-bit) in roughly 90 seconds for a 37-image dataset, in the `[VISUAL]: <trigger>, <description>` format the LTX trainer expects. The default recipe is rank 32, alpha 32, 100 epochs, lr 1e-4, 512 px resolution, letterbox crop; total step count auto-scales with the dataset (e.g. 50 images → 5000 steps, 100 images → 10000 steps) so adding photos doesn't shift the trained-epochs target. Power users can override any of those in an advanced section. Optional voice LoRA from the same training run.+**Training needs 64 GB, and the panel does not refuse below it — it quietly trains something smaller.** Full 512 px LTX LoRA training materialises backward activations for the dev transformer, and a 48 GB Mac falls into swap thrash and never finishes. So on any Mac with **under 64 GB of unified memory** the panel rewrites all three presets in place: Quick becomes rank 4 / 384 px / 120 steps, Medium rank 8 / 384 px / 300 steps, and **High becomes rank 8 / 448 px / 500 steps** — with the advanced overrides clamped to match, so you cannot ask for the full recipe and get it. The preset names on screen do not change.++Be clear about what that means. **rank 32 is the only recipe anyone has graded for identity.** Below it the training finishes, writes a valid file, loads without a warning, and may simply not move the model. The panel measures that now: every trained LoRA is checked for how much it actually changed, a weak one finishes with a warning instead of a bare "done", and the verdict follows the file into the library so you find out before you spend a render. Quick and Medium say *"identity ungraded"* on their own pills for the same reason. If you are on a sub-64 GB Mac, read a weak verdict as *this hardware, this recipe* — not as a problem with your photos.+<img width="871" height="640" alt="image" src="https://github.com/user-attachments/assets/a25bfc78-671e-4972-bf51-231ae5f5cc04" />The Train tab also exposes **Style** training (experimental in v3.0) — same end-to-end pipeline, different intent: a curated set of movie frames teaches the model an aesthetic (color grading, lighting, composition) rather than an identity. The trained style LoRA stacks with character LoRAs at render time. Lightly validated as of v3.0; please report rough edges via [GitHub Issues](https://github.com/mrbizarro/phosphene/issues).@@ -194,7 +198,7 @@ About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay o## Interface-Four workflow tabs at the top of the panel: Video, Images, Audio, Train Character. Each is a single page; the helper subprocess and model state persist across tab switches.+Workflow tabs at the top of the panel: Video, Images, Storyboard, Audio, Train Character. Each is a single page; the helper subprocess and model state persist across tab switches.<table><tr>@@ -239,7 +243,7 @@ Behavioral changes worth noting in 3.0:## What's in the repo-- `mlx_ltx_panel.py` is the panel HTTP server. One file, around 22k lines, with HTML, CSS, and JS inlined as the page string. Worker thread plus helper subprocess management plus capability tier detection.+- `mlx_ltx_panel.py` is the panel HTTP server. One file, around 64k lines, with HTML, CSS, and JS inlined as the page string. Worker thread plus helper subprocess management plus capability tier detection.- `mlx_warm_helper.py` is the long-running inference subprocess. Holds T2V, I2V, Extend, HQ, and Keyframe pipelines. Reads job specs from stdin, emits events to stdout.- `image_engine.py` dispatches the Image tab. Backends `hidream`, `mflux`, `mock`. Each spawns its own subprocess with `start_new_session=True` so `/stop` kills the whole tree.- `patch_ltx_codec.py` applies one idempotent runtime patch: lossless H.264 output (yuv444p). As of the v0.14.8 pin the memory-frees, VAE streaming, Metal-watchdog and frame_rate patches are all native upstream; the v0.14.19 pin keeps that shape — one edit, one line.diff --git a/SIDE_PAIR_NOTES.md b/SIDE_PAIR_NOTES.mdnew file mode 100644index 0000000..51910cc--- /dev/null+++ b/SIDE_PAIR_NOTES.md@@ -0,0 +1,141 @@+# v4.0.3 side-pair receipts++Scope: clone `phosphene-side`, branch `side/v403-pair`. No running panel or+other checkout was modified or contacted; port 8198 was not used.++## Task 1 — Settings is the only Spicy/NSFW gate++Implementation:++- The CivitAI `Show NSFW` control is fail-closed in the static page markup via+ `data-spicy-only hidden`.+- `spicyModeEnabled()` is the one client predicate used to render the control+ and decide whether either initial search or `Load more` may submit+ `nsfw=true`. Engine selection only changes the LoRA family.+- Modal open waits for `/settings` before its first search, removing the stale+ checkbox/request race.+- `spicy_mode_enabled()` is the server predicate. With Settings off,+ `_civitai_search()` forces the upstream request to `nsfw=false` and filters+ NSFW-flagged response cards as defense in depth.++Executable rendered-page and submit-boundary receipt:++```text+$ PYTHONDONTWRITEBYTECODE=1 python3 test_spicy_contract.py+test_all_four_engine_setting_states ... ok+test_hidden_checked_control_cannot_submit_nsfw ... ok+test_static_markup_starts_hidden ... ok+test_off_forces_safe_query_and_filters_nsfw_response ... ok+Ran 4 tests+OK+```++The real page markup/functions are extracted from `page()` after its server-side+bootstrap/profile/engine substitutions, then run in Node against a DOM shim.+Observed state matrix:++| Engine | Settings | `Show NSFW` | Forced checked state after render |+|---|---:|---|---|+| LTX | on | visible | preserved |+| LTX | off | hidden | cleared |+| Hailuo H3 | on | visible | preserved |+| Hailuo H3 | off | hidden | cleared |++The submit receipt force-checks the hidden box with Settings off and executes+the real `civitaiSearch()` function: its captured URL contains no `nsfw=true`.+The Python boundary receipt independently sends `nsfw=True` while Settings is+off: the captured CivitAI parameters contain `nsfw=false`, and an NSFW response+card is removed.++## Task 2 — H3 Turbo adapter default++Audit note: this branch did not actually resolve LightX2V v0.1; it still used+the older Larry ckpt500-EMA adapter plus a separate AdaLN time embedder. The+implementation was moved directly to the requested LightX2V contract:++- Preferred: `lightx2v_v1.0_768p_ourlayout.safetensors`.+- Fallback only when preferred is absent:+ `lightx2v_v0.1_ourlayout_alpha8.safetensors`.+- Explicitly never selected:+ `minimax_h3_fl2v_turbo_4step_v0.1.safetensors` (raw, alpha not folded) or+ the retired `minimax_h3_turbo_4step_ema_ckpt500.safetensors`.+- Runner argv is `--lora <resolved-path>:1.0`; the Larry-only+ `--lora-adaln` companion path is removed.+- Sidecars now record adapter version, fallback state, and scale.+- The old Larry wall clocks remain historical evidence, but no longer mark+ LightX2V v1.0 estimates as measured.++Executable resolver/dispatch receipt:++```text+$ PYTHONDONTWRITEBYTECODE=1 python3 test_h3_turbo_adapter.py+test_installer_records_exact_publication_todo ... ok+test_unpublished_repack_fails_closed ... ok+test_alpha_folded_v01_is_the_only_fallback ... ok+test_raw_v01_and_old_adapter_are_never_selected ... ok+test_v1_is_preferred_when_both_exist ... ok+Ran 5 tests+OK+```++`install_h3.js` intentionally does not download the raw upstream file. The+runner-layout repack does not yet exist as a digest-pinned release asset, so the+installer records the exact publication contract instead of half-wiring it:++```text+target release asset: lightx2v_v1.0_768p_ourlayout.safetensors+source repo: lightx2v/Minimax-h3-Turbo (Apache-2.0)+source file: minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors+source SHA-256: 1bdabc2e9fce20b1db563b96bcf6e46adcad4c1964f423676436bf266cc7416c+release-asset SHA-256: must be recorded before enabling the fetch+```++The UI and `/h3/turbo/install` fail closed with this publication requirement.+The changelog credits the selection to core_tan's public LoRA testing plus the+owner's visual review.++## Gates++```text+$ node scripts/check_pinokio_scripts.js+53 dispatches across 33 shell.run steps in 10 scripts+RESULT: PASS++$ node scripts/check_ltx_pin.js+RESULT: PASS++$ node scripts/check_post_update.js+RESULT: PASS++$ LTX_MODELS_DIR=/Users/salo/pinokio/api/phosphene.git/mlx_models \+ LTX_Q8_LOCAL=/Users/salo/pinokio/api/phosphene.git/mlx_models/ltx-2.3-mlx-q8 \+ PYTHONDONTWRITEBYTECODE=1 python3 scripts/assert_registry.py+154 passed, 0 failed, 0 known defect(s) pinned+```++The registry gate was first run exactly as listed in the task. It reported 17+missing-pack failures because this isolated clone intentionally contains no+`mlx_models` weights. The passing rerun used only the panel's supported path+overrides to inspect the permitted production model tree read-only; no running+panel, process, or port was contacted.++Additional static/contract gates:++```text+python3 -m py_compile mlx_ltx_panel.py test_spicy_contract.py test_h3_turbo_adapter.py+node --check install_h3.js+node --check <extracted inline panel script>+python3 test_lora_compat.py # 9 tests, OK+```++`scripts/assert_schedules.py` was not run: this clone has no LTX venv and the+gate requires that venv plus Metal, as expected in the task instructions. No+GPU work was performed.++## Repository boundary++No push was attempted. Port 8198 was never contacted. The running install and+other checkouts were not modified. The requested granular commits could not be+created because this session mounts `.git` read-only; both commit attempts+failed before staging with `Unable to create '.git/index.lock': Operation not+permitted`. All source changes remain intact and unstaged in this clone.diff --git a/STAGE_PREVIEW_NOTES.md b/STAGE_PREVIEW_NOTES.mdnew file mode 100644index 0000000..045d5c9--- /dev/null+++ b/STAGE_PREVIEW_NOTES.md@@ -0,0 +1,124 @@+# Main-stage live preview receipts++Date: 2026-08-14+Workspace: `/Users/salo/pinokio/api/phosphene-dev.git` (`dev`)+Requested isolated port: `8272`++## Delivered behavior++- The existing `/status` poll now normalizes one live-preview object for both+ consumers: the compact Now thumbnail and the full-size main stage. No second+ request, timer, or queue-list render path was added.+- A preview-capable render takes the idle stage immediately. Before the+ engine-owned meaningful gate it shows a calm `Finding the shot…` state;+ afterwards it shows the cache-busted preview image with `LIVE`, `forming take+ · step n/m`, ETA and the existing cooperative Stop-early flow.+- A playing video, or a video whose controls were touched in the previous 12+ seconds, retains the stage. A `LIVE · return to render` chip is the explicit+ way back.+- Completion keeps the last preview mounted until `list_outputs()` admits the+ new mp4, then fades the decoded finished video over it. The intentional+ two-second in-flight/mtime listing cutoff therefore produces no empty-player+ flash.+- LTX meaningful thresholds remain server-owned (`6` on distilled lanes, `2`+ published estimates on `res_2s`). H3's `h3-live-preview/1` adapter marks its+ proven first forward meaningful. Special LTX lanes and older H3 runners that+ publish no preview remain unchanged.+- H3 preview wiring is capability-probed. A runner with `--live-preview` and+ `--live-preview-dir` receives the H3 TAE checkpoint and the per-job live+ directory; the currently shipped older runner receives an unchanged argv.+ H3 exit `75` is mapped to `stopped`, never `failed`.++## Rendered-page screenshot receipts++The four requested screenshots could not be captured in this execution+environment. Browser initialization returned `No browser is available`, and+the browser inventory was empty (`[]`). The browser workflow explicitly+forbids replacing the in-app browser with Playwright, shell/CDP, or another+browser backend, so no synthetic screenshots were fabricated.++| Requested receipt | Result | Executable coverage available here |+|---|---|---|+| Warming state | **BLOCKED — no browser backend** | `test_ltx_lane_warms_before_first_meaningful_frame`, `test_h3_capable_lane_warms_before_first_frame` |+| Full-size LIVE state and overlay | **BLOCKED — no browser backend** | `test_meaningful_preview_owns_full_stage` |+| Do-not-steal chip while a clip plays | **BLOCKED — no browser backend** | `test_playing_clip_is_not_stolen`, `test_recently_touched_paused_clip_is_not_stolen` |+| Completion handoff | **BLOCKED — no browser backend** | `test_completion_requests_seamless_handoff`, `test_completion_keeps_last_frame_until_output_is_listed` |++## Isolated end-to-end render receipt++The isolated directories were created under this repository:++- `.stage_preview_test/state`+- `.stage_preview_test/outputs`+- `.stage_preview_test/uploads`++The required locks were checked first and both were absent. Acquisition then+stopped at the first lock, in the required order:++```text+mkdir /Users/salo/AI/projects/hailuo-mlx/.gpu_lock+mkdir: /Users/salo/AI/projects/hailuo-mlx/.gpu_lock: Operation not permitted+```++That directory is outside the session's writable sandbox. The second lock was+not created, no render was launched, no GPU work ran, and no existing lock was+removed.++The isolated panel was also probed independently with port `8272` and its own+state/output/upload directories. It failed before serving a page:++```text+PermissionError: [Errno 1] Operation not permitted+ at ThreadingHTTPServer(("127.0.0.1", 8272), Handler)+```++Ports `8198` and `8199`, the production clone, and production state/output+directories were not touched.++## Executable receipts++The focused contract executes the real client functions extracted from+`mlx_ltx_panel.py` in Node plus the Python H3 file-schema adapter:++```text+./ltx-2-mlx/env/bin/python3.11 test_stage_live_preview.py+Ran 16 tests in 0.133s+OK+```++The broader CPU-only panel suite also passed:++```text+./ltx-2-mlx/env/bin/python3.11 -m unittest -v \+ test_stage_live_preview test_character_roundtrip test_lora_compat \+ test_storyboard_planner test_storyboard+Ran 216 tests in 0.946s+OK (skipped=1)+```++The skip is the existing opt-in live planner-model test. JavaScript syntax,+Python compilation and `git diff --check` also passed.++## Required before/after gates++Both the before and after runs produced the same result:++- `node scripts/check_pinokio_scripts.js` — PASS+- `node scripts/check_ltx_pin.js` — PASS+- `node scripts/check_post_update.js` — PASS+- `python3 scripts/assert_registry.py` — PASS (`154 passed, 0 failed`)+- `./ltx-2-mlx/env/bin/python3.11 scripts/assert_schedules.py` — **environment+ blocked before assertions**. MLX aborts while creating its Metal device with+ `NSRangeException: __NSArray0 objectAtIndex: index 0 beyond bounds for empty+ array`; this sandbox exposes no Metal device. The failure is unchanged from+ the baseline run and occurs before schedule logic executes.++## Private-beta publication++`beta/main` was verified unchanged at+`efb57dbcac0ab30311f05410e9b3d7ea2d046ec5`, matching the local `dev` parent.+The authenticated GitHub write was then rejected before any blob, commit or ref+update (`user cancelled MCP tool call`). The local `.git` directory is+read-only in this execution sandbox and shell network access is disabled, so no+alternate commit/push path was available. The private beta and public `main`+remain untouched; all validated edits remain in this dev working tree.diff --git a/VERSION b/VERSIONindex a84947d..6016e8a 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.5.0+4.6.0diff --git a/caption_with_gemma.py b/caption_with_gemma.pyindex 51c9934..394ee83 100644--- a/caption_with_gemma.py+++ b/caption_with_gemma.py@@ -181,6 +181,14 @@ def main() -> int:system = _SYSTEM_TMPL.format(trigger=args.trigger)n = len(images)t_start = time.time()+ # Counted, not assumed. A per-image failure `continue`s below, so the+ # number of images is NOT the number of captions on disk. Reporting the+ # former made the panel print "done - 24 captions" over a dataset that+ # had 20, and the four images with no caption then trained on the+ # 3-word `<trigger> man` fallback without anyone being told. Same class+ # as the zip filter that dropped 6 of 18 images in #61: a silent loss+ # under a green summary.+ written = 0for i, img_path in enumerate(images, 1):t_step = time.time()messages = [@@ -212,15 +220,29 @@ def main() -> int:_emit("error", message=f"could not write {cap_path}: {e}",i=i, n=n, file=img_path.name)continue+ written += 1_emit("progress",i=i, n=n,file=img_path.name,elapsed_sec=round(time.time() - t_step, 2),caption=caption)+ # Nothing on disk is not a run that finished, whatever the exit code+ # said. Emitting `done` here left the panel green while the whole+ # dataset fell through to the fallback caption at train time.+ if written == 0:+ _emit("error",+ message=f"no captions were written for any of the {n} images "+ f"— every image failed to caption. The dataset is "+ f"unchanged; see the errors above for the cause.",+ count=0, failed=n, total=n)+ return 1+_emit("done",elapsed_sec=round(time.time() - t_start, 2),- count=n)+ count=written,+ failed=n - written,+ total=n)return 0diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.mdindex 44e4961..0a961cf 100644--- a/docs/ANALYTICS.md+++ b/docs/ANALYTICS.md@@ -123,7 +123,7 @@ location the day the disable flag ever went missing.## Events-Five events. That's the whole list. (A sixth is described at the end because+Six events. That's the whole list. (A seventh is described at the end becausepeople expect it — it is documented as the thing we deliberately don't send.)### `app_installed`@@ -242,6 +242,22 @@ A `true → false` transition means a pack that *was* installed is no longerdetectable — a broken install, not a user choice. This is the whole reasonthis event exists: nothing else in the panel notices that today.+### `star_prompt`++Fired when someone answers the one-time GitHub star ask — at most once per+install, and only on a deliberate click. Nothing fires when the ask is+ignored or dismissed.++| Field | Type | Example |+|---|---|---|+| `via` | string | `"link"` — one of `link` (opened the repo) or `already` (said they had already starred) |++A closed two-value vocabulary, coerced in the handler: anything else becomes+`link`. No account, no username, no repo state — the panel cannot see whether+a star was actually given, and does not ask GitHub. `via` exists only to keep+"a click we caused" separate from "a click that told us we did not need to+ask", which is the whole question the ask was added to answer.+### `engine_selected` — not implemented, on purposeThe obvious way to count engine-picker usage is a ping per click. That adds a@@ -401,7 +417,7 @@ passes through, so a future engine is counted for free.python3 scripts/test_analytics_dryrun.py```-43 tests covering: the shipped key is a write-only `phc_` project key and is+48 tests covering: the shipped key is a write-only `phc_` project key and isreally the one that goes on the wire, the toggle and the env kill-switch eachproduce zero sockets *and* zero log lines, the exact field set of every event,every event name the panel can fire is documented on this page, prompt/pathdiff --git a/docs/API.md b/docs/API.mdindex 8a7a315..af73066 100644--- a/docs/API.md+++ b/docs/API.md@@ -4,9 +4,17 @@ External agents (Claude Code, Codex, OSS, or anything that speaks HTTP) drive Ph## Server-- **Base URL:** `http://127.0.0.1:8199`+- **Base URL:** `http://127.0.0.1:8198` on a normal install. **`8199` is the DEV+ profile's port**, and every example on this page uses it because that is the+ panel these were written against. The rule is one line in the source+ (`mlx_ltx_panel.py:275`): `DEFAULT_PORT = 8199 if PROFILE == "dev" else 8198`,+ overridable with `LTX_PORT`. If a request here returns nothing, you are+ almost certainly talking to a port that has no panel on it — try the other one.- **Process:** `mlx_ltx_panel.py` (in the repo root)-- **Wire format:** HTTP/1.1, form-encoded `POST` bodies. JSON exceptions are noted per-endpoint.+- **Wire format:** form-encoded `POST` bodies; JSON exceptions are noted+ per-endpoint. Responses are **HTTP/1.0** — `BaseHTTPRequestHandler`'s+ default, never overridden — so the connection closes after every+ request and there is no keep-alive to pipeline against.- **Auth:** none — bound to loopback only.## Conventions@@ -195,7 +203,23 @@ data = json.loads(raw, strict=False)### `GET /loras`-Returns `{"user": [...], "curated": [...], "loras_dir": "...", ...}`. Each entry has `id`, `name`, `path`, `filename`, `size_bytes`, `recommended_strength`, `kind` (`train_character` for LoRAs trained via the panel; `null` otherwise), and CivitAI metadata if known.+Returns `{"user": [...], "curated": [...], "loras_dir": "...", ...}`. Each entry has `id`, `name`, `path`, `filename`, `size_bytes`, `recommended_strength`, `kind` (`train_character` for LoRAs trained via the panel; `null` otherwise), `adapter_verdict` (see below), and CivitAI metadata if known.++#### `adapter_verdict` — whether this file can do anything++A LoRA can train to completion, write a valid safetensors, load without a warning, and change **nothing**: the deltas it learned are numerically too small to move the model. Every structural gate passes, because every structural gate asks whether the KEYS land and none asks whether there is anything in them (#61, #62).++`adapter_verdict` (`mlx_ltx_panel.py:2200`) is read out of the sidecar's `adapter_strength` block and is one of:++| Value | Meaning |+|---|---|+| `ok` | Measured, and the delta RMS is in the working band. |+| `weak` | Measured, and the deltas are at or under `WEAK_DELTA_RMS` (`2.0e-4`). The file is kept; the render will very likely look LoRA-free. |+| `unknown` | Trained by a build that did not measure. **Not a synonym for `weak`** — silence is not weakness, and every LoRA older than the measurement reads this way. |++Anything else is whatever the trainer called it, passed through verbatim.++Callers should surface `weak` **before** a render is spent finding out, and should not decorate `unknown`.### `POST /loras/refresh`@@ -253,7 +277,7 @@ Kick off a character LoRA training. The panel shells out to `lora_lab.train_char|---|---|---|| `train_job_id` | string | From `/train/upload`. || `trigger` | string | Trigger token, e.g. `bizarrotrn`. Must be compound and rare so it doesn't collide with normal language. The face LoRA lands at `mlx_models/loras/<trigger>_v2.safetensors`; the optional audio LoRA at `<trigger>.audio.safetensors`. |-| `preset` | `quick` \| `medium` \| `high` | Hyperparameter preset. `high` = rank 32, 5000 steps. |+| `preset` | `quick` \| `medium` \| `high` | Hyperparameter preset. See the table below — **the step count is not a constant, and on a sub-64 GB Mac neither is anything else.** || `image_count` | int | Confirmed by the panel from the uploaded images. || `train_audio` | `true` \| `false` | Optional. Default `false`. When `true`, a voice clip must already exist for this `train_job_id` (uploaded via `/train/upload-voice`) — otherwise `/train/start` returns 400. || `audio_steps` | int | Optional. Default `250`. Number of audio-LoRA training steps. Heuristic: ~30 s/step on M4 Max. Smoke = `100`, Standard = `250`, Long = `500`. |@@ -269,6 +293,40 @@ Advanced overrides (all optional, fall back to preset defaults):Returns `{"ok": true, "id": "j-<...>"}`. Track progress via `/status` (the training job appears in `current` then `history`). During the run the `current.progress.phase_label` reads `Training face · step N / M` then `Training voice · step N / M` if the audio phase runs. If audio training fails, the face LoRA is still kept; `error` is set with `audio training failed: …` so callers can surface the partial success.+#### What the presets actually are++Steps are **derived**, not fixed: `steps = epochs × image_count`, floored at 1 and capped by the preset's `max_steps` (`_preset_steps_for`, `mlx_ltx_panel.py:1629`). The cap is part of the server contract — a hand-written API call must not be able to enqueue a multi-thousand-step run on a memory-constrained Mac.++On a Mac with **64 GB or more** (`TRAIN_PRESETS`, `mlx_ltx_panel.py:1558`):++| `preset` | epochs | rank | resolution | `max_steps` | Graded for identity? |+|---|---|---|---|---|---|+| `quick` | 30 | 8 | 512 | 8000 | **No.** The pill says "identity ungraded". |+| `medium` | 60 | 16 | 576 | 12000 | **No.** Same. |+| `high` | 100 | 32 | 512 | 20000 | **Yes** — the validated v2 recipe (Aria_v2, Bizarro_v2). |++So `high` at 50 images is 5000 steps, at 20 images 2000, at 300 images 20000 (capped). Only the rank-32 recipe has ever been put in front of a human eye and called good.++#### ⚠️ Under 64 GB, every preset is quietly a different preset++`_select_train_profile` (`mlx_ltx_panel.py:1650`) runs once at import and, when total RAM is **`0 < ram < 64` GB**, it **mutates `TRAIN_PRESETS` and `TRAIN_STYLE_PRESETS` in place**. The names do not change. The numbers all do:++| `preset` | epochs | rank | resolution | `max_steps` | target modules |+|---|---|---|---|---|---|+| `quick` | 2 | 4 | 384 | 120 | compact set |+| `medium` | 5 | 8 | 384 | 300 | compact set |+| `high` | 10 | 8 | 448 | 500 | compact set |++`make_job` mirrors the same clamps server-side, so `rank` / `steps` / `resolution` passed as advanced overrides are **capped too** (`max_rank` 8, `max_resolution` 448, `max_steps` 500) — you cannot ask for the graded recipe on this hardware and get it.++This is a deliberate trade and the reason for it is real: full 512 px LTX LoRA training materialises backward activations for the dev transformer and a 48 GB Mac falls into swap thrash and never finishes. But be clear about what it means: **on a sub-64 GB Mac there is no preset that trains the recipe anybody has graded.** rank 8 at ≤500 steps is exactly the regime `adapter_verdict` was built to catch, so expect `weak` more often here, and read it as "this hardware, this recipe" rather than "this dataset".++`GET /status` exposes the active profile as `train_profile` (`key`: `compact_training` | `full_training`, plus `label`, `ram_gb`, `max_rank`, `max_resolution`, `max_steps`, `note`) **and the effective tables themselves** as `train_presets` / `train_style_presets` (`mlx_ltx_panel.py:21842-21844`). **Read those before trusting a preset name** — they are the post-mutation values, so they are the only place the two tables above are told apart at runtime.++#### The `adapter_strength` trainer event++Not an analytics event — nothing about it leaves the machine (see [docs/ANALYTICS.md](ANALYTICS.md) for the complete list of what does). It is a progress event on the lora_lab subprocess stream, emitted once after the trainer measures the file it just wrote (`mlx_ltx_panel.py:18005`). The panel logs the median delta RMS, the max, and how many modules are carrying, then **finishes the job in a WARNING state rather than a bare `done`** when the verdict is not `ok`. The verdict is written into the LoRA's sidecar as `adapter_strength: {"verdict": …}` and read back out as `adapter_verdict` on `/loras` and `/characters`.+### `POST /train/install`After training succeeds, the LoRA is automatically copied into `mlx_models/loras/`. This endpoint is for explicit re-install / metadata refresh.@@ -337,6 +395,203 @@ Kept under the legacy `/agent/` path for backward compatibility with the Image S---+## Storyboard — plan a film, then shoot it++A **board** is a film: a concept, a cast, locations, and a numbered shot list. Every render it starts goes through the same `make_job` → queue contract as `/queue/add`; none of these routes has a private execution path. Boards live under `state/storyboards/<board_id>/`, with `storyboard.json` written atomically — renders run for hours and a torn board would lose the whole run.++### Read++| Route | Returns |+|---|---|+| `GET /storyboard/list` | Every board, newest first. |+| `GET /storyboard/get?id=<bid>` | One board document. |+| `GET /storyboard/films` | The assembled films on disk — player path, runtime, picture size, size on disk, when it was made. `list_outputs` globs `OUTPUT/*.mp4` and never descends, so without this the one thing the feature makes is the one thing the app cannot show you. |++### Write — `POST /storyboard/<action>`++Form-encoded unless noted. `id` is the board id throughout.++| Action | Fields | Note |+|---|---|---|+| `plan` | `concept`, `id`, `notes`, `shots`, `must`, `engine`, `character_id`, `style`, `locations`, `wardrobe` | Plan or re-plan. **409 while the renderer holds memory or the one planner slot is taken.** `shots` is honoured or refused — never silently swapped for a different count. A re-plan PATCHES locations and wardrobe rather than overwriting them. |+| `cancel` | `id` | Release a planner slot. |+| `save` | JSON `{id, board}` | Write a hand-edited board. |+| `grade` | `id`, `n`, `grade`, `note` | Grade one shot. |+| `estimate` | `id`, `pass`, `only` | Cost/wall estimate before spending. |+| `render` | `id`, `pass`, `only`, `out`, `music`, `music_mode` | Shoot the board. |+| `stop` | `id` | Stop the running board render. |+| `replan-shots` | `id`, `ns` | Re-roll named shots. A repair that breaks a law is rejected; re-rolls splice into the CURRENT plan, not the original. |+| `add-shot` | `id`, `path` | |+| `import-shots` | `id`, `from`, `only` | REFERENCE clips from another board. Provenance (`imported_from`), the source LOCATIONS and the source CAST all travel with them — leaving any one behind breaks something specific. **Refuses while the target film is rendering.** |+| `export` | `id`, `auto_edit`, `music`, `target_seconds`, `music_mode` | |+| `reveal` | `id`, `name`, `what` | Show in Finder (macOS). |+| `delete` | `id` | |++### Board schema — the geography fields++A shot is composed from its location. Since 2026-08-18 a location can also be **faced from more than one direction**, which is what makes a reverse angle a reverse angle instead of a second location.++```jsonc+"locations": [+ {"id": "carwash", "name": "The car wash", "description": "…",+ "views": [ // ABSENT, never [], when there are none+ {"id": "establishing", "name": "…",+ "light": "camera left", // flips with the camera+ "description": "…"}, // self-contained: readable without the floor plan+ {"id": "reverse", "name": "…",+ "light": "camera right",+ "description": "… no car in frame …"} // says what it does NOT hold, in those words+ ]}+],+"shots": [+ {"n": 1, "location_id": "carwash",+ "view": "reverse", // must be a view id OF that location+ "eyeline": "right", // "left" | "right" | "lens"+ …}+]+```++| Field | Where | Rules |+|---|---|---|+| `locations[].views` | location | List of `{id, name, light, description}`. **Absent, not `[]`,** when a location has none — every board written before views existed has no key, and an empty list would be a new shape for the validator to have opinions about for no gain. Ids follow the same charset as location ids. |+| `shots[].view` | shot | A view id belonging to that shot's `location_id`. A view on a shot with no location, or a view that is not one of that location's, is a **validation error** (`unknown_view`) and fails exactly the way an unknown location does — a silently-dropped view composes the reverse angle from the establishing description, and the car the view existed to get out of frame is back in it with nothing said. |+| `shots[].eyeline` | shot | One of `left`, `right`, `lens` — a fact about the FRAME, not the room. `right` = the eyes go off past the right edge. Anything else is a validation error (`bad_eyeline`). |++**What the server does with them.** `shot_scene_text` injects the VIEW's description when a shot names one and falls back to the location's otherwise — so a board with no views, or a shot that names no view, renders exactly as it always did. `eyeline_clause` composes `"his eyes fixed past the right edge of frame"` at render time; **`lens` deliberately produces nothing** (telling these models to look down the barrel buys a stiffer performance than silence), and it exists so a shot can *say* it holds the lens, which is what lets the 180-degree check tell "faces the camera" apart from "nobody wrote one".++**The 180-degree rule is enforced, not suggested.** After planning, `_enforce_eyelines` walks the shots in *screen* order and flips the second of any two adjacent shots that cut between two **different** characters in the **same** location and both claim the same side, and says so in `warnings`. It repairs mechanically because `eyeline` is a discrete field with exactly one complement — flipping it cannot damage anybody's prose. Prose-level laws get a model round trip instead, precisely because they lack that property.++---++## Editor — the timeline++The Editor is a **top-level workflow**, not a stage of the storyboard: engine-agnostic, opens without a board being mid-render, and its document is `edit.json` under the board dir. One video track, one music lane. Per-clip sound is linked by default and can be pulled apart (J/L cuts) — that is **not** a second audio track.++### Read++| Route | Returns |+|---|---|+| `GET /storyboard/edit?id=<bid>` | The arrangement. On the first call for a board it runs the auto-edit ONCE, persists it into the automatic lane, and returns it with `generated: true`. Every later GET is a file read. A corrupt `edit.json` returns **500 with `corrupt: true`** and is never silently replaced — that would throw away the arrangement it is a broken copy of. |+| `GET /storyboard/edit/status?id=<bid>` | The prepare job's state. |+| `GET /storyboard/edit/peaks?id=<bid>` | The waveform. Hundreds of KB — fetch once, **never on a poll**. `404` until `prepare` has run. |+| `GET /storyboard/edit/proxy?id=<bid>&name=<file>.mp4` | A proxy video, served with **range support**. Safari will not seek a `<video>` whose server answers plain `200`, which would undo the entire reason proxies exist. `name` must match `[A-Za-z0-9._-]{1,120}\.mp4` — it is a basename the server minted, so anything else is a probe. |+| `GET /storyboard/edit/uploads` | Videos the user brought with them (`panel_uploads/timeline/`, newest first, capped at 200). Kept out of `OUTPUT` on purpose, which is why they need a route at all; images do not, they land in the library the gallery already walks. |+| `GET /storyboard/edit/drafts?id=<bid>` | `{active, drafts: [...], backup}` — see **Drafts** below. |+| `GET /storyboard/edit/versions?id=<bid>` | **Metadata only**: name, revision, when kept, clip count, duration, plus `keep` (= `EDIT_HISTORY_KEEP`, 50). The documents themselves are read once, by `restore`, on the user's word. Opening the panel must not be a download. |++### Write — `POST /storyboard/edit/<sub>`++| Sub | Fields | Note |+|---|---|---|+| `prepare` | `id`, `music`, `target_seconds` | Build proxies + peaks. `400` if `music` is not a file. |+| `add-clip` | `id`, `from`, `only`, `path`, `title`, `kind` | `kind` is `video` \| `still` \| `slug` — passing it is what stops an image landing as a video with no frames. |+| `relink` | `id` | Re-point clips at files that moved. |+| `cancel` | `id` | Cancel the prepare job. |+| `auto` | `id`, `music`, `target_seconds`, `min_shot`, `max_shot` | Re-run the machine's cut. Lands in the **automatic** lane. |+| `save` | JSON `{id, edit, expect_revision?}` | See below. |+| `draft` | `id`, `op`, `slug`, `name`, `from` | See **Drafts**. |+| `backup` | JSON `{id, edit}` | The quiet lane. See **Drafts**. |+| `recover` | `id` | Adopt the pending backup. |+| `discard-backup` | `id` | Throw it away. |+| `version` | `id`, `label` | Name a version. **Naming is not saving** — no revision bump, no write to `edit.json`, nothing about the timeline changes, which is exactly why it is safe to press at any moment. |+| `restore` | `id`, `file` | Restore a history entry. Refuses while the film renders. |+| `render` | `id`, `out`, `music`, `music_mode` | Assemble the film. `music_mode` is `replace` \| `under`. |+| `export-nle` | `id` | FCP7 XML + After Effects JSX + linked media. |+| `reveal` | `id`, `what` | Show in Finder. |+| `generate` | `id`, `prompt`, `duration`, `duration_s`, `film_start`, `pass`, `character_id`, `seed`, `title`, `engine`, `trigger` | Shoot a new clip straight into a slot. |++**`save` semantics.** `revision` is the **server's** counter, taken from disk, never from what the client remembered — a stale tab must not be able to wind it backwards. Pass `expect_revision` to find out you were overtaken instead of silently overwriting the other tab: mismatch returns **`409` with `conflict: true`** and the current revision. Validation errors come back as **all of them at once** (`errors: [...]`, `400`) with the file on disk untouched, so a client can highlight every bad clip in one pass instead of playing whack-a-mole.++### `edit.json` schema++`version` is **2** (`EDIT_VERSION`). Version 1 is upgraded on READ only (`migrate_edit`) — bumping the version without a read-path upgrade would not refuse old builds, it would refuse every timeline anybody already had. A version from the future is left alone so the validator can say the honest thing.++```jsonc+{+ "version": 2,+ "board_id": "sb_…",+ "revision": 17,+ "origin": "manual", // "manual" | "auto" | "backup" — who asked for this save+ "updated_at": 1786…,+ "duration": 43.5,+ "clips": [ /* below */ ],+ "audio": { /* below */ },+ "beats": null,+ "settings": {}+}+```++#### `clips[]`++| Field | Note |+|---|---|+| `id`, `path`, `proxy` | `path`/`proxy` are `null` on a slug. |+| `start`, `end` | The window INSIDE the source. |+| `film_start`, `film_end` | The slot on the film. **Never independent** — a clip plays at 1x, so `film_end - film_start == end - start` within `LENGTH_TOLERANCE` (2 ms). |+| `kind` | `video` (**absent means video** — stamping it on 400 clips would rewrite every `edit.json` on the machine to say what its absence already says), `still` (held for the length of its slot; `start`/`end` are synthesised from the slot, `duration: null`), `slug` (black, no file). |+| `source` | `auto` \| `human`. |+| `locked` | bool. |+| `adjust` | `{brightness}`, an ffmpeg `eq=brightness` additive offset clamped to ±`BRIGHTNESS_LIMIT` (0.5). **Neutral is absent** — dragging the slider back to zero leaves a document identical to one that never had a slider. |+| `audio` | The split edit. See below. |++#### `clip.audio` — the J-cut and the L-cut++```jsonc+"audio": {"start": 3.5, "end": 7.0, "film_start": 12.25}+```++Video clips only. Same three numbers as the picture, for the SOUND — so the sound can start before its picture (J) or run past it (L), which is how a cut stops being a butt join.++**Absent means linked**, and that is the whole migration: every clip ever written has no `audio` key and every one of them plays its own sound under its own picture. `EDIT_VERSION` did not move for it and no document was rewritten.++**The PRESENCE of the field is the switch, not the values in it.** Do not derive "linked" from `audio` equalling the picture window: unlinking writes the window the clip already has, so a clip the user had just unlinked would read as linked and refuse to be dragged. The toggle adds the object or deletes it; nothing else decides. `normalise_edit` rounds the field but **never removes it** for the same reason, and strips it entirely from a still or a slug.++Audio windows may not overlap each other any more than the pictures may. This is still one video track and one music lane — a split edit is a butt join that lands somewhere else, not a mix.++#### `audio` — the soundtrack, as an object on the timeline++```jsonc+"audio": {"path": "…", "duration": 180.0, "peaks": "peaks.json",+ "offset": -4.0, "trim_start": 12.0, "trim_end": 96.0}+```++| Field | Meaning |+|---|---|+| `offset` | The second of the TRACK that plays at film time 0. It has meant that since before the editor existed, so every document on disk keeps working. **It may now be negative**: the track begins `-offset` seconds into the film, with silence in front. |+| `trim_start` / `trim_end` | In/out points INSIDE the track, in track seconds. **Absent means untrimmed**, which is why an `edit.json` written before this is still valid: no field, no trim, same filtergraph. A trim at or past the end of the track is not a trim, and `normalise_edit` drops it — a handle dragged all the way back out leaves a byte-identical graph. |++`music_window(audio, duration=…)` is the single place these become the numbers ffmpeg and every exporter need: `start = max(trim_start, offset)` (a head trim and a positive offset are the same gesture from two directions; whichever cuts more wins), `end` or `None` for "play to the end", and `delay`/`film_start` = `start - offset`. **Trimming the left edge does not slide the rest of the track earlier** — that is a ripple, and music does not ripple — so the seconds a head trim removes come back as silence in front. A window the trims close entirely returns "no music" rather than a zero-length `atrim` ffmpeg refuses.++### Drafts, backups, and history — three different things++**Drafts** are named variations of the same film, in `drafts/` with an `index.json` naming the active one. A board that has only `edit.json` has exactly one draft and always did; it just had no name for it. `load_draft_index` names it on the way out rather than in a rewrite pass, so the upgrade cannot half-happen.++`POST /storyboard/edit/draft` is **one route with five verbs** — they are five edits to the same active pointer, and splitting them would be five places for that pointer to be wrong:++| `op` | Extra fields | Effect |+|---|---|---|+| `new` | `name`, `from=current` | New draft, empty or copied from what is on screen. Becomes active. |+| `duplicate` | `slug`, `name` | |+| `rename` | `slug`, `name` | |+| `delete` | `slug` | |+| `activate` | `slug` | Stashes the current active draft first — never loses it. |++`new`, `duplicate`, `delete` and `activate` return **`409` with `busy: true` while that film is rendering** — the render is reading this document clip by clip, and swapping the timeline under it is the same hazard `import-shots` and `restore` refuse.++**The backup is ours, the saving is the user's.** `POST /storyboard/edit/backup` writes `history/backup-<draft>.json` and **nothing else** — no `edit.json`, no revision, no conflict check. The user's saved draft stays exactly what he last saved. It is surfaced by `GET …/drafts` as `backup` and **offered**, never applied: `recover` adopts it, `discard-backup` throws it away.++**History is two lanes plus a keep lane**, told apart by filename prefix rather than by opening the files — a prune that has to read fifty documents to decide what to delete fails halfway on the first corrupt one:++| Prefix | What | Pruned? |+|---|---|---|+| `edit-r*` | An automatic snapshot. | Yes, capped at `EDIT_HISTORY_KEEP` (50). |+| `save-r*` | A save the user pressed. | **Never.** |+| `keep-r*` | A version the user named (`version`). | **Never.** |++Every save archives its predecessor before the new document lands (~5 KB each). History failing must never block a save — losing a breadcrumb is nothing next to refusing to persist the arrangement on screen. `origin` is also stamped inside the JSON, for anything reading one file on its own.++---+## Output management### `POST /output/delete`diff --git a/docs/EDITOR_EFFECTS_MODEL.md b/docs/EDITOR_EFFECTS_MODEL.mdnew file mode 100644index 0000000..9930874--- /dev/null+++ b/docs/EDITOR_EFFECTS_MODEL.md@@ -0,0 +1,254 @@+# The Editor's effects model++Status: **foundation**, 2026-08-20. Sibling to `docs/EDITOR_SAVE_MODEL.md`.++## The ruling++> "If we are doing that, I think we probably need to better organize the+> functionalities. Just set the base to have effects somewhere, and then we+> will find a way to better integrate them." — and, on how:+> "Tightly integrate it. Don't do it in a wrong way; do it in the right way."++So: a base first, features hanging off it. Not six patches.++## The rule that decides what ships++**An effect that cannot be honestly expressed in all three outputs does not+ship.** The three are:++| output | what it is |+|---|---|+| preview | the `<video>` on the stage, the strip player, the music bed |+| render | the one ffmpeg filtergraph `_sb_film_filtergraph` builds |+| export | FCP7 XML (Premiere/Resolve) and the After Effects script |++This is not a style note. `mute` set the standard: it is expressed as **the+absence of an audio lane** in the render — no volume filter, no mixer, nothing+that could sum — as `<enabled>FALSE</enabled>` on the FCP7 audio clipitem+(disabled, not deleted, so the editor downstream can see the decision and undo+it), and as `lay.audioEnabled = false` in AE. Each output says the same thing+in its own idiom rather than one output faking another.++An effect that would need to be baked into pixels to leave the panel, or that+only one of the three can carry, is a worse feature than no feature: it makes+the preview lie.++## Where an effect lives++`clip.fx` is the home. Additive, absent means no effect, and it is written+only when it says something — the same neutral-is-absent rule `adjust`, the+music trims and `mute` already follow, so a timeline nobody has touched is+byte-identical to one from before effects existed.++```jsonc+"fx": { "fade_in": 0.5, "fade_out": 0.75 }+```++`EDIT_VERSION` does not move. The migration rule this repo has used since+`clip.audio` holds: a field whose absence means the old behaviour needs no+version bump, because every document ever written is already valid under it.++### The one legacy citizen++Brightness predates this model and lives at `clip.adjust.brightness`. It is+**not** moved into `fx`. A label is not worth a data migration — the same+reasoning that kept `film_start` when the user-facing noun became "sequence".++What changes is that there is now **one accessor**, `clip_effects(clip)`,+returning `{fade_in, fade_out, brightness}` whatever the storage. Every output+reads that and nothing else, so "where is it stored" stops being a question+any consumer has to answer, and the next effect chooses its storage on its own+merits without a fourth code path appearing.++The inspector presents brightness in the **Effects** section beside the fades,+because that is where a person looks for it. Presentation follows the model;+storage follows history.++## The inspector has sections now++The inspector grew one control at a time and was a flat run of buttons with a+brightness slider floating in the middle. It now has three:++* **Clip** — what this thing is: source window, film slot, provenance, lock,+ ripple delete.+* **Sound** — link/unlink, resync, mute. Everything about the strip.+* **Effects** — brightness, fade in, fade out. The home the ruling asked for,+ and the place the next effect lands without a decision.++## Fades — the first citizen++**Preview**: an honest opacity ramp on the stage element, computed from the+playhead against the clip's own film window. Not a CSS transition — a value+per frame, so scrubbing shows the true opacity at that second.++**Render**: ffmpeg `fade=t=in:st=…:d=…` and `fade=t=out:st=…:d=…` on the+segment's own timeline, after the brightness term and before the format+conversion. Fades are per-segment, so they compose with trims without knowing+about them.++**Export**: opacity keyframes. FCP7 gets a `<filter>` carrying the standard+Opacity effect with four keyframes (0 → 100 → 100 → 0 at the right frames);+AE gets `lay.opacity.setValueAtTime(...)`. Both are native, editable, and+undoable on the far side — nobody receives baked pixels.++### The clamp++Each fade is ≥ 0, and `fade_in + fade_out ≤ the clip's length`. Two fades that+crossed would ask ffmpeg for an opacity that is two things at once, and would+give the NLEs keyframes out of order. The clamp is applied in the model, so+all three outputs get the same already-legal numbers.++## The mix — and the second author it removes++Status: **built**, 2026-08-21.++The renderer was a second author of the soundtrack's level, and an invisible+one. Under `music.mode == "under"` the ffmpeg graph held every bed at a+hard-coded `volume=0.20` (−14 dB) and then pushed it down a further ~11 dB+through a `sidechaincompress` keyed on the clips' own audio. Neither number+was in any document, on any screen, or in the preview:++> "when you render it, there are some weird manipulations… the volume of the+> music goes low when the dialogue appears. The mix is weird."++The duck defended itself in its own comment: it kept lines intelligible+"without anybody automating a volume curve by hand". True when it was written,+false now — the bed and the strips both carry fades, keyframes and level+lines, so the renderer was overriding numbers the user had explicitly+authored. That is the save model's two-writers-no-rule, one floor down.++### Where it lives++`audio.mix`, two fields, both neutral-is-absent:++```jsonc+"mix": { "bed_gain": 0.2, "duck": true }+```++`audio_mix()` is the one accessor. `bed_gain_points()` is the ONE CURVE —+`[[t, gain], …]` on the bed's own clock — and the preview, the ffmpeg render+and the exports read that and nothing else.++### The bed's clock, and what happens when the track will not say++`bed_length()` is that clock: the seconds of the bed that actually PLAY, so a+fade dragged onto the block's corner means the corner it was dragged onto.+It resolves in one order, **and both implementations resolve it the same way**:++1. `trim_end` — an out-point the user set.+2. `audio.duration` — the track's own length, as the document records it.+3. **the FILM** — what is left of `edit_duration()` after the bed starts.++Rule 3 is the fix for the one shape the first mix pass left behind. A bed with+no `duration` and no `trim_end` — reachable from `/storyboard/edit/save`, and+written by `_sbe_auto_edit` itself when both the peaks and the probe fail —+made `bed_length()` return 0, which made the curve EMPTY, which means **no+filter**, which is the bed at FULL LEVEL over the dialogue. Measured+end-to-end on a real ffmpeg render with an 8 kHz bed and a 300 Hz "line":+**+20.5 dB above what the browser drew**, in the direction nobody wants.+Silence-by-empty-curve is the one behaviour nobody asked for and it is the loud+one. The honest reading of a bed of unknown length is that it plays under the+film — the renderer trims the mix to the film anyway — so that is what both+sides now say. Same document, same rig, after: **−0.08 dB.**++**The peaks probe is NOT in that chain, deliberately.** `peaks.json` is a+picture of the file and the renderer has never read it; a bed length taken from+it is a number only the browser can compute, and a gain only one side can+compute is the invisible-second-author defect this whole section exists to+remove. `sbeBedLen(audio, filmLen)` therefore takes the FILM's clock, not the+probe's duration, and is `storyboard_editor.bed_length(audio, film_len)` term+for term.++`test_editor_mix.TheTwoImplementationsAgreeOverEveryShapeOfDocument` is the+gate: real client JS in node against real Python, over a TABLE of documents —+no duration, no trim_end, bed longer than the film, bed shorter than the film,+authored envelopes, duck on and off, muted clips, clips with no audio, J-cuts,+closed windows — asserting the curves are identical POINT FOR POINT and that+the ffmpeg expression, evaluated, is the curve the browser drew. The suite that+missed the divergence compared the five constants and four documents; a mix+that exists as two implementations needs a table, not a spot check.++### The duck is a curve, not a compressor++This is the load-bearing change. A compressor's output is a function of+samples the browser never sees, so it could never be a value in a document and+the preview could never play it. `bed_duck_points()` expresses the same+decision as breakpoints derived from the TIMELINE: the bed steps back wherever+a clip's own sound is playing — `audible_strips()`, which skips muted clips and+clips with no audio track — by the measured **11.4 dB** (linear 0.269), in+5 ms, back up over 400 ms. Windows closer together than one release are merged,+so the bed does not scramble back up between two lines.++Measured on a real render (a 120 Hz bed under a 900 Hz "line", band-split by+projection): the film's bed sits at **0.4995** where the document says 0.5000,+and the duck measures **−11.45 dB** against a model that says −11.40.++### The precedence rule++Three terms, and **never two curves on one level**:++| term | when it applies |+|---|---|+| `bed_gain` | ALWAYS. A scalar fader, not a curve — multiplying an envelope by a fader is what a fader is. |+| `audio.afx` (authored) | ALWAYS, when it exists. |+| the auto-duck | ONLY when there is no authored envelope. |++A person who has drawn the bed's level has said what the bed does. An+automatic curve that then moved it would be the renderer disagreeing with them+again. `bed_duck_suppressed()` answers this, and the A2 head **says so** —+*"off — your own level line is driving the bed"* — because a ticked box quietly+doing nothing is the silent guard this editor keeps paying for.++### Defaults, and the one-time heal++New documents get the honest default: **bed 1.0, no duck.** Documents written+before the controls existed are stamped, on read, with what the renderer was+already doing to them — `{bed_gain: 0.2, duck: true}` — so a film the owner has+already approved keeps the levels it was approved at, the difference being that+they are now on screen. `replace` documents are left completely alone: that+path never touched the bed, so stamping one would invent an attenuation it+never had.++The stamp carries `mix_repair`, unlike the sub-frame gap heal which deliberately+has no marker. It needs one because it is a *decision*, not arithmetic:+`normalise_edit` drops a mix that is back at the default, so without the marker+a user who switched the duck off would have the next read helpfully put it+back — the rival author, wearing a repair's clothes.++### The one term that is NOT in the document++`MIX_CEILING` — the `asoftclip` knee on the summed mix. It is a safety+limiter, not an artistic choice: `amix` runs `normalize=0`, so nothing else+protects the sum, and hot dialogue over a bed peaked the first under-mix film+at 1.31 with 1341 hard-clipped samples and said nothing.++It cannot honestly be in the model, because it acts on the SUM of two signals+and a browser playing two `<audio>` elements never computes that sum — a+preview could only fake it. So instead of faking it, **the render measures what+it did**: `mix_peak`, `mix_ceiling` and `mix_limited` ride on the film's facts+and its sidecar. A net that has acted says so, which is the rule the save model+reduces to.++### The known limit++The assembler CONCATENATES, so a hole in the timeline closes and everything+after it slides earlier. The duck's windows are on the EDIT's clock — the same+clock the bed's own `adelay` placement already uses — so on a film with gaps+the bed and its duck stay consistent with each other and with the preview,+and both are displaced together by exactly the amount `gaps_note` already+discloses. Fixing that means fixing the concatenation, not the mix.++## What is deliberately not built yet++* **Overlay lane** (his headline want: an endcard PNG over the sky). It is the+ next merge, and it uses this model — an overlay item carries `fx` and gets+ its fades from the same accessor and the same three expressions.+* ~~**Audio fades with keyframes**, waveforms on clip strips~~ — shipped, and+ the music bed has them now too: the same `.sbe-fade-band`, the same+ grip-derived clearances, the same 22×22 handles and the same level line with+ points. Its rows are in `scripts/measure_editor_layout.py`'s table, so+ "big enough to hit" and "nothing else claims these pixels" are asserted at+ the lane's floor and its ceiling.++The foundation is here so those land as features rather than as three more+scattered controls.diff --git a/docs/EDITOR_SAVE_MODEL.md b/docs/EDITOR_SAVE_MODEL.mdnew file mode 100644index 0000000..9a2264c--- /dev/null+++ b/docs/EDITOR_SAVE_MODEL.md@@ -0,0 +1,214 @@+# The Editor's save model — an owner architecture ruling++Status: **ruling**, 2026-08-19. Supersedes the two-lane save/backup design that+grew up between `save_edit`, `write_backup` and the recovery bar.++## The ruling, in the owner's words++> "Either the autosave is something on the side that you can always go and+> check the older versions... it only saves the real saves that are manually+> saved and named by the author. We start working in a new timeline, you put a+> name and you save it, and then you save it manually every time. But if you+> forgot to save, you have drafts; you have versioning that you can go back to+> if you want. Like in a normal program. It's intertwined in a way that is+> causing a lot of problems."++The last sentence is the defect. Everything below follows from separating the+two things that were intertwined.++## What went wrong++The editor had **two writers of record** and no rule about which one won.++`save_edit()` writes `edit.json` — the document. `write_backup()` writes+`history/backup-<draft>.json` — a parallel, complete, validated document with+its own revision stamp. On load, `pending_backup()` compared them and, on any+difference, raised a full-width bar offering to install one over the other.++That is not a safety net. It is a second head on the same body, and it+produced, in one session:++* **A permanent interrogation.** The comparison was `json.dumps(clips)` on+ both sides. But `_sbe_payload` REWRITES every clip's `proxy` pointer on the+ way out ("a proxy built after the edit was saved must not need a re-save to+ become visible"), so the client's copy legitimately differs from the file+ for a field the user has never heard of. Any board whose proxies were built+ after its last save compared unequal forever. The bar that resulted read+ *"A backup from 3 min ago holds 10 clip(s), 0:55.11 — the saved draft has+ 10. Nothing has been changed."* — a question about a difference it could not+ name, on a document that had loaded correctly.+* **A stale tab stomping a live one.** A second tab left open on revision 93+ kept writing its own state into the single backup slot on every debounce.+ Minutes after a rev-94 save landed, the backup lane held rev-93 content and+ the offer re-armed. There was no notion of which session was current.+* **A lane that could refuse.** `write_backup` validated like a real save, so+ a document the validator disliked lost BOTH its save and its safety net at+ once. (Fixed in ccae93b for overlap; the shape of the bug was the coupling.)++## The model++### 1. Manual saves are the only truth++A timeline is a **named draft**. `Save` (and ⌘S) writes that draft's+`edit.json` and archives the outgoing document into the draft's history. The+revision counter belongs to the file on disk and moves forward only there.++**Loading a draft always loads its last manual save.** Nothing else is ever+installed on load, by anything, for any reason. This is the property the whole+model exists to guarantee, and it is the one that was negotiable before.++The header says one honest thing: `draft name · saved rev N`, or+`unsaved changes`. Never both, never a third state.++### 2. Autosave is a side archive, full stop++The autosnapshot lane writes continuously and **has no opinions**. It+- never blocks a save,+- never refuses a document (only the errors that would make a snapshot+ unrestorable),+- never competes on load,+- never interrogates the user.++It is bounded and pruned. Losing the oldest snapshot is not an event.++### 3. One versions browser per draft++Manual saves, named versions and autosnapshots are listed **together and+visually distinct**, newest first:++| lane | prefix | pruned | meaning |+|---|---|---|---|+| named | `keep-r*` | never | a version a person stopped to name |+| manual | `save-r*` | never | a save the user pressed |+| auto | `edit-r*` | capped | a snapshot the machine took |++One click restores. **Restore archives the current state first**, so restoring+can never lose anything — including restoring by mistake.++### 4. No recovery wall++If the newest snapshot is newer **and content-different** from the last manual+save, the panel shows **one quiet, dismissible chip**, folded into the single+notice surface: *"Unsaved snapshot from 14:52 — open Versions."* It is an+offer to go and look, not a question that must be answered before working.++**Content-equal shows nothing at all.** Equality is judged by+`edit_digest()`, a canonical fingerprint of the things a person can see and+change — the clip windows, the film slots, the sound, the adjustments, the+soundtrack, the beats — and explicitly NOT of derived or server-rewritten+fields (`proxy`, `revision`, `updated_at`, `origin`, timestamps, the backup's+own bookkeeping). A field the user cannot see may never be the reason they are+asked a question.++### 5. Multi-writer sanity++Each tab holds a **session token**, and the board records which session last+**wrote**. That is all it records, and the only thing it is for is telling a+person that somebody else is editing the same film.++**The claim is taken by writing, never by loading, and it never refuses+anybody.** Both halves of that sentence are paid for.++This used to read: the claim goes to whoever loaded last, and a writer from an+older session is *refused* — it stops writing and says so. It cost the owner an+afternoon on 2026-08-20. A page LOAD claimed the board, so a second window, a+headless browser, an agent reading the board or a preview took the claim+without editing anything; the tab he was actually cutting in was answered+`stale_session` on its next snapshot and stopped writing for seven hours. What+made it fatal rather than annoying is that it went quiet: the tab set a flag,+showed one nine-second toast, and the state line it wrote was overwritten by+the very next edit. The 12-second watchdog built to catch exactly this could+not fire, because the early return sat ABOVE the line that arms its clock.++The refusal was written for a lane with ONE slot per draft, where a stale tab's+write destroyed newer content. §2 removed that lane — one file per snapshot,+pruned, never overwritten — and the refusal outlived its reason. A snapshot+from any tab now costs one file and can only ever ADD a way back; refusing one+can only ever remove one.++Server-side and agent edits are just normal saves. A client sitting on an older+revision gets a quiet chip — *"draft advanced to rev N — reload"* — not a+conflict wall. A conflict wall is for two humans editing the same second; a+revision moving forward underneath a tab that has not touched anything is not+that.++### 5b. `expect_revision` is a compare-and-swap, and both halves are in one place++The guard existed and a race walked straight through it. The HTTP handler read+the revision off disk, compared it, validated, and only *then* called+`save_edit` — and the panel runs on a `ThreadingHTTPServer`. Two tabs whose+debounces landed together both read revision 7, both compared 7 == 7, and both+wrote. **Both got HTTP 200.** One arrangement was gone, recoverable only from+`history/` and only by somebody who knew to look.++So the compare and the swap are now the same critical section, and it lives in+`save_edit()` — the function every writer already goes through — rather than in+the handler, because a guard the caller has to remember to take is a guard.++* `save_edit(board_dir, edit, expect=N)` takes the board's write lock, re-reads+ the on-disk revision **inside** it, and raises `EditConflict` (a subclass of+ `EditError`, so every existing `except` still refuses the write) if it moved.+* The lock is **per board**, keyed by the resolved directory. Two people+ cutting two films never queue behind one another; two tabs on one film+ always do.+* The handler's early check stays, as the *early answer* — so an overtaken tab+ is told without the server first validating and archiving a document it is+ going to refuse. The loser gets the same 409 body either way, which is the+ one the client already knows how to answer.++**A save with no `expect_revision` is accepted, and logged.** Refusing it was+the other option and it is the wrong one: the client deliberately sends no+guard for the "Keep mine" button — a person looking at a conflict notice and+choosing to overwrite — and a 409 that button cannot answer would strand the+arrangement on screen. What changes is that the write stops being silent: the+log names the revision it landed on and says "last write wins", and the+outgoing document is in `history/` either way. A script or an agent that omits+the guard is therefore visible rather than invisible.++### 6. Migration is lossless++Nothing on disk is deleted. The single `history/backup-<draft>.json` is read+as the newest autosnapshot of that draft and folded into the versions list.+Old flat history layouts continue to migrate into per-draft folders as they+already do.++## Invariants a test must hold++1. `load_edit()` returns the last manual save, always. No lane can change that.+2. Content-equal snapshot → `pending_backup()` is `None` → nothing on screen.+3. A `proxy` pointer, a `revision`, or a timestamp differing is not a content+ difference.+4. A snapshot is never refused on session, and a READ never takes the claim —+ a passive viewer cannot disarm the writer. The lane also never writes a+ snapshot identical to its newest (`edit_digest`), so a debounce that fires+ over an unchanged film does not spend the cap.+5. `restore_edit()` archives the current document before overwriting it.+6. The autosnapshot lane never raises on a document a manual save would take.+7. Peaks are invalidated when the soundtrack path changes — a cache that+ outlives its subject is the music strip reading `44.99s` under a different+ file.+8. Two saves carrying the SAME `expect_revision` cannot both be answered 200,+ however close together they arrive. One writes; the other gets the 409 with+ the revision it was overtaken by. Driven with two real threads held past the+ read-and-compare, because a serial test cannot see this defect at all.++## Deliberately not built++* **Merging.** Two divergent arrangements are not mergeable in a way anybody+ would trust. The answer is versions and a restore that archives first.+* **Autosave to `edit.json`.** Explicitly refused by the owner, twice. The+ side archive exists precisely so this stays refused.+* **A lock on the SNAPSHOT lane.** Two tabs both writing snapshots is not a+ conflict — it is two ways back instead of one. The document itself is+ protected by `expect_revision` on the manual save, which is where a conflict+ can actually do damage — and that guard is now atomic per board (§5b). The+ lock there is around one read-check-write, not around a session.++## The rule the whole file reduces to++A control that has stopped protecting the user **says so, loudly, and does not+stop trying**. Every defect this document records is the same shape: something+switched the net off for a defensible local reason and nothing told anybody.+`if (SBE.backup) return false`, then `if (SBE.superseded) return`. The next one+will look reasonable too — so the test to apply to any new guard on a write+path is not "is this correct" but "what does the person see if it fires".diff --git a/docs/STATE.md b/docs/STATE.mdindex 57ea665..d092cf8 100644--- a/docs/STATE.md+++ b/docs/STATE.md@@ -1,5 +1,525 @@# Phosphene — project state, history, open work+> **🎚 2026-08-21 — two release-gate findings closed on `dev` (`947a183`,+> `9c2f63d`, `490d942`). Both were measured, neither was a guess.**+>+> **1. A bed with no stated length rendered at FULL level.** The mix fix in+> `85f3d43` closed the common case; one shape survived. `bed_length` fell back+> to `audio.duration`, so a soundtrack with no `duration` and no `trim_end`+> measured 0 seconds → `bed_gain_points` returned an EMPTY curve → an empty+> curve means *no filter* → the render played the bed at unity over the+> dialogue while the browser drew it 20 dB lower and the preview played what it+> drew. Reachable two ways, both verified: `POST /storyboard/edit/save`+> persists the shape happily, and `_sbe_auto_edit` writes `"duration": None`+> itself when both the peaks and `probe_media` fail.+> **The ruling: the render matches the preview.** A bed of unknown length plays+> UNDER THE FILM — what is left of `edit_duration` after the block starts, which+> is where the renderer trims the mix anyway. Silence-by-empty-curve is the one+> behaviour nobody asked for and it is the loud one.+> **Measured end-to-end** on a real ffmpeg render through+> `_sb_film_filtergraph` (8 kHz bed, 300 Hz "line", band split, browser JS in+> node as the reference): **+20.52 dB before, −0.08 dB after.**+> The client's half is in it too — `sbeBedLen` was handed `SBE.peaks.duration`,+> a probe of the file the renderer has never read, so a bed length only the+> browser could compute. The peaks are out of that chain; `sbeBedLen(audio,+> filmLen)` is `bed_length(audio, film_len)` term for term. The block geometry+> and the waveform still read the probe, which is what a picture of a file is+> for.+> **The gate that missed it is now a TABLE.** `test_editor_mix` compared five+> constants and four documents; it now runs the real client JS in node against+> the real Python over **32 documents** — no duration, no trim_end, bed longer+> than the film, bed shorter, authored envelopes, duck on/off, muted clips,+> clips with no audio, a J-cut, trims that close the window — asserting the+> curves are identical point for point, that they agree *between* the knots,+> and that the ffmpeg expression EVALUATED is the curve the browser drew.+> Removing the fallback turns 21 tests red; the old suite passed.+>+> **2. Two tabs saving at once were both told they had won.**+> `expect_revision` is a compare-and-swap whose compare and whose swap were in+> different critical sections: the handler read the revision, compared it,+> validated, and only then called `save_edit` — on a `ThreadingHTTPServer`. Two+> debounces landing together both read revision 7, both compared 7 == 7, both+> wrote, **both got HTTP 200**, and one arrangement was gone (recoverable only+> from `history/`, and only by somebody who knew to look). Read-check-write is+> one critical section now, and it lives in `save_edit(..., expect=N)` — the+> function every writer already goes through — behind a **per-board** RLock, so+> unrelated films never queue behind one another. The loser gets the identical+> 409 the sequential case produces. `EditConflict` subclasses `EditError`, so+> every existing `except` still refuses. Driven by two real threads held past+> the read-and-compare; a serial test cannot see this defect at all.+> **A save with no `expect_revision` is accepted, and logged** — the client+> deliberately omits it for "Keep mine", so refusing would strand the+> arrangement on screen with no button that could answer. It stops being+> *silent*: the log names the revision it landed on and says "last write wins".+>+> **Also taken, same visit:** `migrate_edit` shallow-copied and then let+> `repair_audio_overlaps` write `clip["audio"]` on clips still shared with the+> caller — a READ editing its argument, which makes the file and the snapshot+> differ over a repair neither contains. The deep-copy dance is one named helper+> (`_clips_copied`) used by both healers.+>+> **Suite: 1558 (was 1537), green** via+> `./ltx-2-mlx/env/bin/python3.11 -m unittest discover -s . -q`.+> (`test_prompt_enhance_endpoint` fails identically on unmodified `dev` in a+> tree without the helper venv — environment, not this work.)+>+> **KNOWN AND DEFERRED — filed here, not fixed:**+> - **A deleted clip source is invisible until render.** `_sb_timeline_segments`+> drops an unreadable input and the assembler concatenates, so the film comes+> out silently shorter. `gaps` get a `gaps_note` sentence in the render+> result; `unreadable` gets a list (`film["unreadable"]`, named in the+> markdown) and **no note** — and nothing on the timeline says a source is+> gone before you press render. The fix is a preflight readability check+> surfaced on `_sbe_payload`, plus the missing note. Not a small change.+> - **The Editor's `do_GET` has no exception handler** where `_storyboard_post`+> has `except Exception → 500 JSON`. An exception in `_storyboard_edit_get`+> propagates and the browser sees a dropped connection instead of a sentence.+> **Deliberately not wrapped here:** the `proxy` branch streams a video+> through `_serve_video_with_range`, so a naive wrapper that answers with+> `_json` after bytes are already on the wire writes a second complete+> response onto the same socket — the exact defect that route's docstring+> records. Doing it safely needs response-started tracking, which is not a+> two-line change.++> **🪪 2026-08-20 — the build stamp names the code that is running.** One+> commit on `dev` (`fe22ed9`), no engine move, no weights move. The header+> stamp is how the owner tells which build he is on; it was answering with the+> working tree, and the page was answering with a commit from May.+>+> **THE REPORT (2026-08-19).** HEAD was `4f65fb5`, the tree was clean, `POST+> /restart` returned ok, the page then served `4f65fb5`'s JS — and the header+> read `dev · c5dc04c`, a SHA from 2026-05-21. The reflog settles it: HEAD went+> `c7d4154 → 4f65fb5` at 13:33 and `→ ccae93b` at 14:28 that day and was never+> `c5dc04c`, so no `git rev-parse` produced that string. **It came out of the+> served page.** A comment inside `renderVersionPill` carried two real SHAs+> formatted exactly like the stamp it described — `"you're on 3.0.0 · dev ·+> c5dc04c (2026-05-21)"` — and the RUNNING build appeared nowhere in the HTML+> at all. Thirteen real commit SHAs ship in that page as historical references+> (`"the loadParams fix (b024bb5)"`); none of them was ever the answer. The+> page answered "which build is this?" with a decoy, confidently, in the right+> format. `<meta name="phosphene-build">` is the answer now, server-rendered,+> and the pill's own comments hold placeholders.+>+> **AND THE STAMP WAS WRONG ANYWAY, in the other direction.** Three failures,+> one defect:+> - **The stamp described the TREE, not the process.** `local_short`,+> `local_version`, `local_branch` and `local_commit_date` are refreshed from+> disk by `_detect_local_install_state()` at the top of every remote poll —+> deliberately, so a tree that was dirty at boot and is clean now stops being+> suppressed. So within thirty minutes of a pull under a live panel the+> header advertises the new build while the old code keeps serving. That is+> v4.4.0's "updates silently kept old code" with the alarm rewired to lie.+> **Reproduced on the real install before the fix**: :8199 was running+> `d8e54cf`, `fe22ed9` landed on disk, one `/version/check` and the header+> claimed `fe22ed9` — code that process had never loaded.+> - **`stale_process` could not cover it.** A boolean bolted onto a+> disk-derived stamp, so the restart tooltip printed the disk label on BOTH+> sides: *"Phosphene 4.6.0 is on disk, but this panel process loaded 4.6.0."*+> Most fixes land without a VERSION bump, so on `dev` that is the normal+> case. Both builds are named with their SHAs now.+> - **The boot SHA was not captured at boot.** `_capture_boot_head()`'s only+> caller was `version_check_loop`, a thread `__main__` starts `if+> VERSION_CHECK_ENABLED`. With `PHOSPHENE_DISABLE_VERSION_CHECK=1` it stayed+> `None`, and `disk != boot` is False when boot is None — the detector dead+> again, for exactly the users who opted out of nagging, under a comment+> claiming it was "deliberately captured at IMPORT".+>+> **THE FIX** is a boot SNAPSHOT rather than a boot SHA — sha, version, branch+> and commit date frozen together at import, beside the definition.+> `get_version_state()` returns both builds unconditionally: `local_*` is what+> the process loaded, `disk_*` is the tree right now. Nothing has to check a+> flag before it may trust a field.+>+> **THE SAME DEFECT, everywhere disk spoke for the process:** the header+> version badge; `/panel/bug-context`, which now also discloses a moved tree+> (*"the fix didn't work"* from an un-restarted panel usually IS that); the+> three analytics events — an `app_boot` from a build that never booted+> corrupts the version funnel; and the film credit, which was crediting a+> renderer that never touched the clip. `running_version()` is the one label+> for all of them.+>+> **GATES.** Nine new tests in `test_stale_process.py` (18 total), and all+> nine fail on the code they replace, each for its own reason: `'n3wn3wn' !=+> '0ld0ld0'` for the stamp following the tree, an unexpectedly-`None` boot SHA+> for the import capture, `['c5dc04c','1ea5f1d'] != []` for the decoy.+> `test_the_version_pill_ships_no_sha_literal` is the one that keeps the decoy+> out: nothing in the code that RENDERS the stamp may carry a SHA of its own.+> 1408 python tests and the three node gates pass.++> **🩹 2026-08-19 overnight — the polish wave: the drafts feature stops+> losing work.** Nine commits on `dev` (`487dd46..HEAD`), no promote, no+> engine move, no weights move. A five-agent review of last night's+> twenty-two commits found four blockers and eighteen confirmed majors in a+> feature that shipped with 1,097 green tests; every one of them lived in the+> gap between "each guard exists" (which the suites pin) and "the state+> machine composes" (which they did not). One claim was REFUTED by the+> red-team and is NOT fixed — see the bottom of this entry.+>+> **THE FOUR BLOCKERS.**+> - **The crash-backup lane destroyed itself.** `sbeBackup` refuses to write+> while a recovery offer is unanswered — correct — and NOTHING answered it.+> A save cleared `dirty` and the alarm and left `SBE.backup` set, so on any+> film that opened with a backup every later backup no-opped, `backedUpAt`+> stayed 0, and the twelve-second watchdog raised the full-width red SAVING+> IS FAILING banner on a panel whose saves were all landing. The amber bar+> stayed over the saved film with a Recover button that would have reverted+> the save. The save route deletes the file now, the client follows the+> payload, and `recover_backup` refuses anything `pending_backup` would not+> have offered. `pending_backup` also stopped deciding on a wall clock: both+> stamps are whole seconds, and every write that is not the user's (a draft+> switch, an auto-edit, a restore) used to bury an offer holding the only+> copy of somebody's afternoon. **An offer ends when the user answers it.**+> - **Copying a draft raised on every board anybody already had.**+> `create_draft(from_current)` and `duplicate_draft` read `edit.json` raw and+> handed it to `save_edit`, whose validator refuses any version but the+> current one — and migration is read-path only, so every board written+> before `EDIT_VERSION` went to 2 is still v1 on disk. Worse, the index was+> written BEFORE the document, so the refusal left the film pointing at a+> draft that was never created. `_land_draft` writes first and moves the+> pointer after, for create, duplicate and activate alike.+> - **History was keyed on revision alone while revisions restart per draft.**+> Draft B's revision 3 collided with draft A's, `archive_edit` dropped the+> collision without a word, and the picker shown while B was open listed A's+> arrangements — with Restore ready to write one of them into B. **History is+> a folder per draft now** (`history/<slug>/`), so the prune, the listing and+> the restore are scoped by construction; what was already on disk moves into+> the FIRST draft's folder. Deleting a draft takes its past saves with it,+> which is what the panel has been claiming it does.+> - **The clip inspector was a 36px scroll window.** At 1440x900 with thirteen+> unplaced shots it held 223px of content in 36px, so "Unlink sound" — the+> only entry point the J/L feature has — was off-screen and the one control+> fully visible at the bottom of that unmarked scroll was Ripple delete. The+> rail's unbounded list is the scroller now, not the inspector.+>+> **THE ARITHMETIC, all three proved in node against the extracted functions.**+> One ⌘Z deleted a peaks-discovered soundtrack (the snapshot read the DOCUMENT+> while `sbeFetchPeaks` deliberately writes only the timeline); a head trim+> past the source dragged the strip's out-point left with it (the clamp landed+> on `start` and not on `film`); and a music drag depended on mouse speed+> (`offset = head - want` folds the previous offset back in, and a pointermove+> stream re-reads the mutated object every event — the same six-second drag+> landed at film 6 as six events and did not move the block at all as one).+>+> **THE REST, briefly.** Nothing swaps the document on a save that did not+> happen (draft switch, restore, relink, render, NLE export — the render most+> visibly, since it would otherwise build the previous cut); the backup names+> the draft it was composed from, so a debounced write cannot land on the one+> you just opened; the geography pass's derived views reach the model even+> when the reply carried no floor plan (they did not, and every shot was then+> coerced onto the establishing view); `GET edit/uploads` answered and then+> told the dispatcher it had not, writing a second 404 behind a 200 — the+> stand-in that hid it now asserts the return value; naming a save is+> reachable again; the two lists in the drafts panel stopped competing for one+> box; and the preview bed plays the window the strip shows.+>+> **THE SURFACE.** Two rung scales (`--ctl-h*`, `--fs-*`) replaced eight+> control heights and eleven type sizes; the header has a hierarchy instead of+> seven identical buttons; the soundtrack is a name rather than an absolute+> path; the rail's unplaced strip is a list rather than a ragged pill shelf;+> the track prettifies model filenames; the alarm reads at 7:1 instead of 3.3;+> the app header stopped clipping its own right edge at 1440.+>+> **NOT FIXED, deliberately.** (1) The claim that a re-plan wipes derived views+> off the board before the planner runs was **REFUTED** by the red-team: the+> guard at `mlx_ltx_panel.py:23504` is never satisfied together with an+> existing board — `sbPlan` sends `locations` and no `id`, `sbReplan`/+> `sbTryAgain` send `id` and no `locations` — so nothing in the panel can+> reach it. Do not re-chase it. (2) README's release banner still says v4.1.1+> and the Editor is still absent from its tab list; both are release+> decisions, and announcing the Editor early is the exact mistake already made+> once. (3) `lora_lab`'s CLI presets still differ from the panel's — the+> comment claiming they are a mirror is gone, the divergence is documented,+> and which way to resolve it is a product call.+>+> Gates at every commit: 21 suites (1,134 tests), `check_ltx_pin`,+> `check_pinokio_scripts`. Verified live on the 8799 test panel, including a+> full 42.9s assemble.++> **✂️ 2026-08-18 night — the Editor stops being a viewer, and a scene stops+> being a list of shots.** Twenty-two commits on `dev`+> (`4a49103..378054a`), no promote, no engine move, no weights move. Two+> campaigns: the timeline became a document somebody can OWN, and the planner+> learned that a scene is a space before it is a shot list.+>+> **THE TIMELINE IS A DOCUMENT NOW, not a render's opinion of itself.**+> - **The music is under the picture, and it is an object.** The soundtrack+> sat above the clips as a global `offset` — one number, clamped to+> non-negative, unreachable in the direction that matters. `music_window()`+> (`storyboard_editor.py:1288`) is the one place that turns three fields into+> the three numbers ffmpeg needs: `offset` may now be NEGATIVE (the track+> starts *into* the film, silence in front), and `trim_start`/`trim_end` are+> in/out points inside the track. A head trim does NOT ripple — music does+> not ripple — so the seconds a trim removes come back as silence. Absent+> means untrimmed and `normalise_edit` deletes a neutral trim+> (`storyboard_editor.py:906-928`), so a handle dragged all the way back out+> leaves a byte-identical filtergraph and every edit.json written before+> tonight is still a valid one.+> - **The timeline outlives the clips.** A board whose renders were deleted used+> to open on nothing, which made "the film" and "the files" the same object.+> They are not.+> - **Split edits — the sound stops being the picture's shadow.** J-cuts and+> L-cuts are one feature and they are the owner's words: *"leave some of the+> audio and drag only the image."* A clip may carry `audio:+> {start, end, film_start}` (`clip_audio`, `storyboard_editor.py:205`). **The+> PRESENCE of the field is the switch, not the values in it** — deriving+> "linked" from equality read as linked the instant somebody unlinked a clip+> they had not yet moved, and the clip refused to drag. It is still ONE video+> track and ONE music lane: a split edit is a butt join that lands somewhere+> else, not a second audio track, and the audio windows may not overlap any+> more than the pictures may. `EDIT_VERSION` did not move for it — an absent+> `audio` key means linked, which every document already says.+> - **DRAFTS: the saving is the user's, the backup is ours.** `drafts/` holds+> named variations with an `index.json` pointing at the active one, and the+> migration happens on READ (`load_draft_index`,+> `storyboard_editor.py:1913`) — a board that has only `edit.json` has+> exactly one draft and always did; it just had no name for it. The upgrade+> cannot half-happen, because the worst case is an index written the first+> time the board is read. `POST /storyboard/edit/draft` is ONE route with+> five verbs (`new` / `duplicate` / `rename` / `delete` / `activate`) because+> they are five edits to the same active pointer and splitting them would be+> five places for it to be wrong; `activate`/`delete`/`new`/`duplicate`+> refuse while that film is rendering, the same guard `import-shots` and+> `restore` take. The unsaved work rides a separate quiet lane —+> `history/backup-<draft>.json`, no `edit.json` write, no revision, no+> conflict check — and is OFFERED back on next open rather than applied.+> - **Two-lane save history.** The owner: *"the auto saves should be saved+> separately from the manual saves."* Three prefixes in one folder, told+> apart by their name rather than by opening them (`storyboard_editor.py:988`):+> `edit-r*` autosave (pruned, capped at `EDIT_HISTORY_KEEP = 50`), `save-r*`+> a save the user pressed, `keep-r*` a version he named. **The prune never+> sees the last two.** A glob and not a flag inside the file, because a prune+> that has to open fifty documents to decide what to delete fails halfway on+> the first corrupt one. `GET /storyboard/edit/versions` is METADATA ONLY —+> opening the panel must not be a download.+> - **A save that cannot be dropped, and a failure that screams.** The editor+> saves on a debounce; a debounce that loses its tab loses the work. The+> failure path is now a banner, not a console line — the one state where+> quiet is the wrong default.+> - **A browser refusing to autoplay is not a preference.** The mute fallback+> is session-only: Chrome's gesture gate made the panel remember a decision+> the user never took.+> - **The pool takes a file you already have.** Upload-to-pool, with the `kind`+> fix, so an image lands as a **still** and not as a video with no frames —+> a still is held for the length of its slot, `start`/`end` synthesised from+> the slot (`normalise_edit`), and a slug is black with no file at all.+> `EDIT_VERSION 1 → 2` is for `kind` + `adjust`; `migrate_edit`+> (`storyboard_editor.py:1182`) upgrades v1 on READ, one way, so bumping the+> version refuses old *builds* and not every timeline anybody already had.+> - **A test instance cannot pass for the real one.** A TEST badge on the+> panel chrome. Two panels on 8198/8199 and no way to tell them apart is how+> an evening gets spent debugging the wrong process.+> - **An empty list is a sentence, not a blank.**+>+> **A SCENE IS A SPACE BEFORE IT IS A SHOT LIST.** The owner: *"a man or woman+> in a bar — behind him there is this, behind her there is that."* The planner+> now blocks the space first (`_GEOGRAPHY_SYSTEM`,+> `storyboard_planner.py:757`): one floor-plan paragraph, then 2–4 named camera+> **views** DERIVED from it. A location carries `views: [{id, name, light,+> description}]` and a shot picks `location_id` + `view` + `eyeline`+> (`storyboard.py:1059-1090`). The car-wash day was the prototype and every+> piece of it was hand-built: `carwash`/`carwash_reverse` as two locations, the+> flipped sun, the no-car reverse background. All of it is derivable from one+> paragraph.+> - **The laws are enforced, not just written.** A view never contains what is+> behind the camera in that view, and it must SAY so in the words "no car in+> frame" — that sentence is what `_ABSENCE_RE`+> (`storyboard_planner.py:2927`) has to stand on. The light flips with the+> camera. Nobody's own body goes in the view behind them.+> - **The 180-degree check reads the CUT, not the file.** `_enforce_eyelines`+> (`storyboard_planner.py:2891`) walks shots in *screen* order and flips the+> second of two adjacent shots that cut between two DIFFERENT characters in+> the SAME place and both claim the same side. Repaired mechanically, which+> is only defensible because `eyeline` is a discrete field with exactly one+> complement: flipping it cannot damage anybody's prose, and the clause is+> composed at render time (`eyeline_clause`). Prose laws get a model round+> trip precisely because they do NOT have that property. `lens` deliberately+> emits nothing — telling these models to look down the barrel buys a stiffer+> performance than saying nothing — but the value exists so a shot can SAY it+> holds the lens, which is what lets the check tell "faces the camera" apart+> from "nobody wrote an eyeline".+> - **The derived views land on the user's OWN locations, and reach the board+> at plan adoption.** `merge_location_views` (`storyboard.py:1098`) dresses+> the board's locations in the views the plan derived and never strips the+> last plan's views, because the shots point at them. Back-compat is one+> line: `shot_scene_text` falls back to the location's description, so a+> board with no views, or a shot that names no view, injects exactly what it+> always did. `views` is ABSENT, never `[]`.+>+> **A GREEN TALLY WAS NEVER PROOF THE FILE COULD DO ANYTHING** (`037f7fc`,+> closing the panel half of the #61/#62 entry below). The trainer measures its+> own delta RMS against `WEAK_DELTA_RMS` and emits `adapter_strength`; the+> panel reads it, logs median/max/carrying-modules, and a verdict that is not+> `ok` finishes the job **in a WARNING state rather than a bare done** — the+> file is kept, but the word for it is not "success". It rides into the sidecar+> and out through `list_characters`/`/loras` as `adapter_verdict`+> (`mlx_ltx_panel.py:2200`), so the library can warn before somebody spends a+> render finding out. A LoRA from a build that never measured reads+> **`unknown`, never `weak`** — silence is not weakness, and a chip on every+> older file would be noise nobody could act on. Same commit: **train preset+> honesty** — the rank-32 recipe is the only one ever graded on faces+> (Aria_v2, Bizarro_v2), so Quick and Medium now say *"identity ungraded"* on+> the pill (`mlx_ltx_panel.py:1567,1573`); saying "fast" and letting the user+> infer "as good, sooner" is the pill doing the lying. **Issue #46** — the A2V+> warning shipped a rule its own reporter refuted: no frames×area constant+> separates the four datapoints (832×480×721 = 287.9 Mpx holds while+> 1024×576×481 = 283.7 Mpx falls apart — a *smaller* product failing), but+> per-frame area separates them cleanly (clean 0.307/0.399, failing+> 0.590/0.922, both dying near frame 450). `A2V_PIXEL_BUDGET` is gone, replaced+> by a knee at **0.45 Mpx/frame**; the canvas is the lever and length is nearly+> free below it. **Pinokio (fuschichou)** — `#remixSubGroup` is a SIBLING of the+> mode bar, not a child, and all six `body[data-workflow] #modeGroup` rules+> omitted it, so the bar hid and the row stayed on Audio, Train, Storyboard,+> Editor, Characters and Studio; added to all six, with a gate that counts the+> two ids and fails if they are ever listed apart. And the **caption green+> summary counted the images, not the files it wrote** (`e35f29b`) — a tally+> that cannot be wrong in the direction that matters. The strength verdict is+> also reachable **from a shell** now, on a file you already have (`9dd90fa`).+>+> **Gates:** `check_pinokio_scripts` PASS (worst dispatch 377/500) ·+> `check_ltx_pin` PASS (unmoved) · analytics dry-run 48 — and its+> "every event the panel fires is documented" test still passes, so+> `docs/ANALYTICS.md` is unchanged **and true**: `adapter_strength` is a+> trainer→panel progress event on the lora_lab stream, not an analytics event,+> and nothing new leaves the machine. Suites touched tonight, all green:+> `test_storyboard` 111 · `test_storyboard_planner` 151 (1 skipped) ·+> `test_storyboard_assembly` 111 · `test_storyboard_editor_api` 250 ·+> `test_storyboard_editor_ui` 181 · `test_lora_compat` 28 ·+> `test_caption_counts` 4 · `test_geometry_grid` 12 · `test_stale_process` 9.+>+> **Docs squared up in the same pass:** `docs/API.md` gained the Storyboard ++> Editor surface it never had (board schema incl. `locations[].views`,+> `shots[].view`, `shots[].eyeline`; `edit.json` incl. `clip.audio` and the+> soundtrack's `offset`/`trim_start`/`trim_end`; the drafts, versions and+> history routes; `adapter_verdict`), and its `/train/start` preset line was+> **wrong** — `high` is not "rank 32, 5000 steps", it is `epochs × image_count`+> capped by the preset, and on a **sub-64 GB Mac `_select_train_profile`+> silently rewrites every preset to rank ≤8 / ≤448 px / ≤500 steps**, which is+> the ungraded regime by definition. That trap is now stated in API.md and in+> the README's Train Character section. **NOT fixed, flagged:**+> `lora_lab/train_character.py:109` still says its presets "must stay in+> lockstep with the panel JS mirror" and they have not been for a long time+> (lab `quick` = rank 16/1500 steps/576 px vs panel `quick` = rank 8/30+> epochs/512 px; two unrelated ETA estimators), and `CLAUDE.md` still opens on+> "Current state — v3.0.6", documents port 8198 only, has no Storyboard or+> Editor in its API section, and its §24 describes an Agentic Flows module that+> was removed in 2026-05.++> **🔍 2026-08-18 — trained LoRAs come out inert (#61, #62): the measurement+> exists now, the cause does not yet.** Two users on v4.5.0 trained characters+> that finished clean and changed nothing. Their render log is the important+> artifact: `LoRA mode unfused: 1152 modules attached … 0 skipped`,+> `FUSED=1152/1152 tensors (576/576 modules)`, `strength=1.00`, on the 2.5 q8+> distilled lane — **every gate we own passed**, because every gate we own asks+> whether the KEYS land, and none asks whether there is anything in them.+> `3c53c21` closes that half: `lora_compat.measure_adapter_effect` returns the+> exact `‖B @ A‖_F` per module (via `trace((BᵀB)(AAᵀ))`, two r×r matmuls, ~1 s+> on a 500 MB adapter), the helper prints `delta_rms` beside the FUSED= tally on+> both LoRA routes, training measures the file it just wrote and stamps the+> verdict into the sidecar, and an adapter whose every product is exactly zero+> is now REFUSED at render instead of returning a LoRA-free video.+>+> **The calibration, measured on this disk** (per-entry delta RMS, median):+> `elontrn_v2` 1.63e-03 · `ariatrn_v2` 1.45e-03 · `eltrumpo_v2` 1.41e-03 ·+> `bizarrotrn_v2` 8.84e-04 · third-party `LTX2.3-Rogue` 1.84e-03 ·+> `Fantasy_Painterly` 5.36e-04 · `bizarrotrn.audio` 4.85e-04 · a+> four-step adapter 1.72e-05. `WEAK_DELTA_RMS = 2.0e-4` sits under everything+> that works and two orders over an untrained file.+>+> **Two negative results, so nobody re-runs them.** (1) *Magnitude is not the+> regression.* Fresh runs on the current pin, same data, rank 8, lr 1e-4:+> 60 steps → 1.43e-04, 240 steps → 2.43e-04. That is √-shaped accumulation+> (4× the steps, 1.7× the delta), and extrapolating it to 5000 steps lands at+> ~1.1e-03 — i.e. exactly where the May-trained `eltrumpo_v2` (1.41e-03)+> actually sits. The current trainer accumulates like the one that produced the+> shipped characters. (2) *Layout is not the regression.* Emitted keys are+> byte-for-byte the layout the shipped adapters carry, and both match the 2.3+> AND 2.5 transformers 576/576 — verified with `inspect_lora_compatibility`.+> What remains is DIRECTION: a 240-step run on the same person's images is no+> more aligned with `eltrumpo_v2` (mean per-module cosine +0.052) than an+> unrelated character is (+0.043), while two runs of the current engine agree+> with each other (+0.171). Suggestive, not conclusive — different rank, 8 of+> 37 images, 240 steps against 5000.+>+> **The two experiments that settle it, in order.** (E1, one minute) @Morac2+> offered his 132 MB adapter and his training data — measure the file with+> `measure_adapter_effect`: in the working band means the file is fine and the+> fault is downstream of it; ~1e-04 means it is not. (E2, one night, needs a+> box with headroom — this 64 GB Mac swapped 27 GB and filled the disk trying)+> the same 37 images at rank 32 / lr 1e-4 / 5000 steps under the current pin+> versus under `v0.14.8`, both measured and both rendered. Panel-side follow-ups+> (the `adapter_strength` event has no UI yet; Quick trains at rank 8 and no+> tier below rank 32 has ever been graded for identity) are written up but NOT+> implemented — another agent held `mlx_ltx_panel.py`.+> ⚠️ **That last sentence is SUPERSEDED as of the night of 2026-08-18**+> (`037f7fc`, top entry): the panel reads `adapter_strength`, warns on a+> not-`ok` verdict, carries it out as `adapter_verdict`, and Quick/Medium say+> "identity ungraded" on the pill. E1 and E2 are still open.++> **⏪ 2026-08-18 — v4.6.0 promoted and WITHDRAWN the same day, on the owner's+> order.** The Editor release went to public `main` (`5b26f91`), tag and GitHub+> release included, and the owner pulled it back within two hours: *"you+> shipped too early... I want to work on it properly."* Public `main` is back+> at v4.5.0 (`ee278e0`); the tag and the release are deleted; the Pinokio+> announcement was never posted. Nothing else moved — `dev` and `beta` keep all+> of it, the from-zero validation stands, and the "SHIPPED in v4.6.0" notes+> below now describe the WITHDRAWN promote. v4.6.0 ships again when the owner+> has cut with the Editor himself and says so — that is the gate that was+> missing: green checks are not the same thing as the owner having used the+> feature.++> **🎬 2026-08-18 — v4.6.0: the Editor becomes a place, and a clip stops having to be a video.** The timeline shipped as the storyboard's sixth stage state, and everything wrong with it followed from that: it could not open without a board, its document id WAS the board id, it died on a tab switch, and its picture was whatever the shot list left over — 150px on any window under 1279px tall. It is now a top-level workflow beside Storyboard, engine-agnostic, with the two columns an editor wants.+>+> - **A media pool, replacing a `window.prompt()` that asked the user to type the NUMBER of a film** — while the gallery holding every clip this panel has ever made was `display:none` for the whole surface. Four sources (this film · other films via `import-shots` · the generations · Images, which the gallery has always held and which nothing could use until a clip could be a STILL) plus an Add black control, because black has no file and therefore no row in any list. One verb: click a row and the clip lands on the track without leaving the Editor. `phos_ed_doc` REMEMBERS the document rather than inheriting it, falling back to the picker when the film it names is gone; leaving the tab SUSPENDS (clock, picture, flushed save) where it used to tear the document down, so glancing at the gallery cost an undo stack.+> - **Three kinds of clip.** `kind: video | still | slug`, absent meaning video, so every `edit.json` on every machine is already a valid v2 document. `EDIT_VERSION 2` shipped WITH the read-path migration, because `validate_edit` hard-refuses a version it does not know — bumping alone would not have refused old builds, it would have refused every timeline anybody already had. A still is `-loop 1 -framerate F -t D` and never goes through ffprobe; a slug consumes no input at all (`color=` is a source filter). That is what forced the input-index refactor: segment index stopped being input index and every input after the first slug shifted. Indices are assigned in one place now, next to the argv fragments that honour them, and the soundtrack is `n_inputs`.+> - **One slider.** Brightness, constant per clip, clamped to ±0.5 and ABSENT when neutral, so a clip nobody graded serialises exactly as it did yesterday. The preview uses CSS `filter: brightness()`, which is MULTIPLICATIVE where ffmpeg's `eq=brightness` is ADDITIVE — CSS has no additive form — so the two are matched at mid-grey, where a person judges exposure, and the strip already says the preview is approximate. `oninput` paints; `onchange` commits, because a slider at pointer speed would otherwise push eighty undo steps and eighty saves for one gesture.+> - **Drag and drop, on the substrate the track already used.** The panel had no `dragstart` anywhere and the track's own gestures are pointerdown/move/up with capture; HTML5 drag-and-drop would have swallowed that capture and the track would never have heard the drop. Same substrate, so the two coexist by construction. A drop lands WHERE IT WAS DROPPED, with ripple, by the midpoint rule every NLE uses; click-to-add still lands at the END, because it cannot move anybody's cuts. On the track, Shift reorders and a plain drag moves — a move puts a clip at a TIME and leaves the hole the generate control fills, a reorder puts it at a POSITION and closes that hole, and neither can be inferred from the pointer. The ghost portals to `<body>`: parented in the pool list it is clipped the instant it leaves the column, which is every drag. A drag ends in a click on a `<button>`, so a flag stops every drop adding its clip a second time.+> - **NLE export — the film as a project somebody else's editor can open.** `<film>_project/` with an FCP7 XML (the one interchange Premiere and Resolve both import), an ExtendScript for After Effects (which has no timeline import at all and never has), and a `media/` of HARDLINKS, `os.link` falling back to a real copy across filesystems. The pathurls are absolute into that `media/`, which is what makes the folder relink on drop. Slugs are written as timeline GAPS rather than generator items: the effect ids for a colour generator differ between the two NLEs, so "one XML for both" would quietly have become one XML for one of them, and a gap reads as black in every editor ever made. The audio is STEMS — clip sound on A1, soundtrack on A2, unducked — because the render's sidechained under-mix has no representation in an NLE timeline, and baking it in would hand an editor a bed they cannot unmix.+> - **ONE assembler.** Export wrote `<slug>_film.mp4` from a second auto-editor over its own copies; the Editor's Render wrote `<slug>_timeline.mp4` from the cut, with the soundtrack. Same folder, same board, two films, and a chip naming the button as the only way to tell them apart. Export now delegates to the timeline whenever an `edit.json` has clips, passes `music`/`music_mode`, and both doors write the same name.+> - **RELINK, the live bug.** `_sbe_board_clips` picks delivery over draft, but `edit.json` freezes the path at the moment of the cut and nothing rewrote it — so "Finish keepers" rendered full-size files the film never used, and the next Prepare pruned their proxies. The server flags them on the GET; one button rewrites the paths, keeps every cut and timing, and builds the delivery proxies before answering. Never automatic: the arrangement is the human's.+> - **A soundtrack can sit UNDER the dialogue instead of deleting it.** `music.mode` is `replace` (unchanged, still the default, byte-identical graph) or `under` (clips keep their audio; the bed is attenuated and then ducked by the dialogue via `sidechaincompress`). The duck constants were MEASURED on a band-split gated-tone rig, not chosen: 0.04/8 gives 5.8 dB, too shallow to hear under a line; 0.02/10 gives 11.4 dB and shipped; 0.01/20 gives 17.7 dB and audibly pumps. The bed returns to full level between lines in all three. End to end through the real filtergraph it measures 7.0 dB with the dialogue intact.+> - **The under-mix was clipping, and the obvious fix is a no-op here.** The first film mixed `under` peaked at 1.31 pre-encode with 1341 hard-clipped samples: `amix` carries `normalize=0` so nothing at all was protecting the sum, and engine dialogue is hot (0.35 RMS on an opening line). `alimiter=limit=0.97` is the filter this obviously wants and on this build it does NOTHING to float samples — measured on the real mix, input peak 1.3075, output peak 1.3075, unchanged with `level=disabled`, unchanged with an `aformat` to s16 before it, unchanged with one after it, reporting nothing either way. A "fixed" render was shipped that measured WORSE (1.279 against 1.216) before anybody looked at the output peak rather than the filtergraph. `asoftclip=type=tanh` at threshold 0.9 holds: the finished film measures peak 0.9678 with zero clipped samples, against 1.279 and 654 before. One test pins the ceiling as the last stage before `[aout]`; a second BANS the string `alimiter` from the graph, so the inviting cleanup cannot be done by someone who has not measured the output.+> - **The trained voice was stripped from every LTX character shot.** Owner-reported more than once. `shot_to_job` decides `no_voice`, and `no_voice=on` drops `<trigger>.audio.safetensors` from the LoRA stack — it decided it with `_HAS_DIALOGUE`, which matches `<d>…</d>` and nothing else. That is exact for H3 and wrong for LTX: `_strip_h3_markup` has ALREADY rewritten the tag away by the time an LTX prompt exists, so `no_voice` was always "on" and every LTX character shot with a line rendered with the face LoRA alone. Confirmed on a real sidecar — `no_voice: true`, LoRA stack of one. It survived because the comment above it said the derivation was exact; it was, for the one engine anybody checked. The gate now shares `_SPOKEN_WORDS_RE` with `shot_speech_problem`, and a test asserts the two agree: when they diverge you get one of exactly two bugs — a mouth with nothing to say, or a real line in a stranger's voice — and this repo has now shipped both.+> - **A line must fit its shot, and it must close.** `shot_pacing_problem()` rejects OVERSTUFFED (more words than the duration can carry) and UNFINISHED (the last line ends on a comma, dash, ellipsis or nothing). The budget BRACKETS the measured evidence rather than guessing: 7 words in 4.04 s delivered fine, so it must allow ≥2.31 w/s; 20 words in 7.04 s was cut mid-phrase, so it must refuse ≥3.31; 2.4 w/s sits between with margin both ways. A warm read is slower — the day's renders split cleanly by voice descriptor at ~2.4 w/s bright against ~1.7 warm, and a 23-word slow read passed the flat budget at 13.04 s and was cut anyway — so `is_slow_read()` reads the descriptor as a tempo marking and both the budget and `speech_fit_frames()` honour it. Hard error on hand-authored boards, where the author is present to choose between cutting words and adding seconds; mechanically REPAIRED at plan adoption, because bouncing a free fix through a 40-second repair round-trip helps nobody. Found in review: the first cut of the descriptor regex was assembled inside a non-raw triple-quoted string, so every `\b` arrived as a literal backspace and the pattern could never have matched — caught because the new tests run against the real module rather than trusting the diff.+> - **LOCATIONS and WARDROBE — written once, injected everywhere.** Four shots of the same character, each saying "dim room, cinematic close-up", came back as a monitor-lit study, a brighter office with papers on the wall, a vintage parlour with no monitors in it, and a near-black void, with the collar changing between them. Nobody wrote a contradiction: the shots simply never agreed on anything, and what a prompt leaves unstated is re-rolled per shot. A location is a board-level entity now — id, name, description — and a shot references one by id; wardrobe rides with the cast member rather than the shot. Both are injected at the single choke point every render path already passes through (`shot_to_job`, `compose_shot_prompt`) rather than at the call sites, which would give the estimate, the re-render and the gap-fill each their own chance to forget. `unknown_location` is the validator that matters most: without it a shot claiming a room this board never heard of renders with no room injected and looks identical to a shot that never claimed one — the continuity failure arriving silently. Additive: a board with no locations composes byte-identically, and schema stays 1.+> - **A screenplay pass, before any shot exists.** `plan_film` now writes concept → screenplay → shots, handing the beats and the actual spoken lines down to the shot pass with the instruction to keep every line word for word. There was no screenplay step at all, so structure and coverage were invented in the same breath. Off by `screenplay=False`; a per-shot re-roll never regenerates it, because the other shots are standing on it; a model that answers with "Sure! Here is the scene:" and no beats is discarded rather than handed down as if it were a scene.+> - **Clips can come from another film.** A board is a timeline, one to one, and coverage is not — the moment B-roll or alternates get rendered as a second board, their clips are unreachable from the first board's timeline, so the answer to "I have clips in two projects" was to render them again. `_sb_import_shots` + `POST /storyboard/import-shots` REFERENCE clips rather than copying them, and three things travel with them because leaving each behind breaks something specific: `imported_from` provenance (without it a re-plan rewrites somebody else's work), the source LOCATIONS (an imported shot pointing at an unknown location correctly refuses to render, so a successful import would produce an unrenderable film), and the source CAST (or wardrobe anchoring silently stops applying). It refuses while the target film is rendering — a running render owns the board file and writes each shot's status back as it lands, so an import holding a read from a second earlier would drop finished clips at the exact moment somebody is collecting them. Found by doing it: an import during a live four-shot render happened to survive, and that is luck, not a design.+> - **The film has a home.** Both assemblies now END on a film state — player, runtime, picture size, size on disk, when it was made, which button made it, the folder it lives in, Show in Finder revealing the FILE, and earlier films listed underneath — served by a new `GET /storyboard/films`. It was needed because `list_outputs` globs `OUTPUT/*.mp4` and never descends, so the one thing this feature makes was the one thing the app could not show you; the user was left on a list of individual shots wondering which one was the movie.+> - **Ten review findings, fixed.** Re-plan erased the film's locations and wardrobe — `/storyboard/plan` assigned both unconditionally from the form and only the FIRST plan's client sends them, so a re-plan wiped the continuity anchors with nothing on any screen showing they were gone; the server patches now instead of overwriting. Prepare DELETED the proxies of exactly the clips the user had just imported, because `plan_proxies` prunes anything not in the clip list it is given and it was given board shots only; it is fed board clips UNION every path in `edit.json`. The step rail — the only door to the editor and the finished film — sat 400+px below the player, nested inside the element that takes the gallery's slot; it is the stage pane's first child now, with a CSS belt so it cannot appear outside the storyboard workflow. The tab strip did not wrap in a 300px pane, so the Editor tab was simply not there to click, the same way the Train tab went missing once. The Render button was 1590px wide — the panel's base `button { width: 100% }` was never overridden in that bar — which made the sticky bar 89px instead of 65. The picture's column budget was stale at 819px, measured with a rail and an 89px bar that are not in the Editor's own tab; re-measured to 748, which took the preview from 173px to 244px on the same window with the column still not scrolling. Intersection callbacks do not run in an occluded tab, so the pool's first screenful loads without waiting for one. The grade flag was wide enough to collide with the clip name, which always ran under it. Four pool sources on a 40% basis wrapped two-and-two instead of three-and-one, which read as Images being an afterthought rather than a peer. And a negative-zero `startTime` in the AE script, which is valid ExtendScript and reads like a bug.+>+> **Validated in a browser and with ffprobe, not asserted.** On a real v1 `edit.json` — nine clips, cut in the Editor, never touched by this branch — opening it returned version 2 with `migrated_from 1`, validated clean, and re-saved with nothing rewritten in any clip. A four-kind timeline was then built through the SHIPPING verbs: ripple delete and the trim handles, a real `PointerEvent` drag from the Images row onto the track, the Add black button, and the inspector's own slider. The drop landed at 1.5 s BETWEEN the two videos by the midpoint rule and rippled the second to 4.5 s; the click that follows every pointerup did not add the clip a second time. **The render ffprobes at 6.500000 s exactly, 156 frames at 24 fps, 1280x720, two streams, 44100 Hz stereo**, and per-slot mean luma proves what the graph did rather than that it ran: video 102.71 · STILL 74.19 with 0 scene changes across the hold · the same window graded −0.30 at 29.30 against 98.28 ungraded · SLUG 16.00, dead flat limited-range black. The under-mix survived a still and a slug in the graph, which is the thing most likely to have broken quietly: max_volume −4.0 dB against the 0.9 ceiling, bed alone under the still (−34.7) and the black (−46.6), ducked under the dialogue (−14.5 / −24.6). The project folder, parsed with `xml.etree`: xmeml v4, timebase 24, ntsc FALSE, 156 frames, ONE video track with three clipitems and the slug left as a 48-frame gap, two audio tracks, four files declared once each with absolute pathurls into the folder's own `media/`, every media file at link count 2 and zero bytes copied. The `.jsx` parses as JavaScript and maps −0.30 to −45.0 of After Effects' Brightness.+>+> **Gates:** `check_ltx_pin` PASS (pin unmoved at `v0.14.19+ltx25.6`) · `check_pinokio_scripts` PASS (worst 377/500) · `check_output_codec` PASS · `node --check` install/update · `py_compile` panel + image engine · Ideogram from-zero (model deleted, token-less re-download and render) PASS · **20 root suites, 826 tests green** · `scripts/test_analytics_dryrun` 48/48, green for the first time since v4.2.0. No engine re-pin, no weights change, no render path touched: `ltx-2-mlx/`, `required_files.json`, `install.js` and `update.js` are byte-identical to v4.5.0.+>+> **Recorded so nobody hunts it, and NOT a regression:** on the validation browser no `<video>` element reaches `readyState 1` at all right now — Chrome's own built-in player stalls on the same proxy file that `curl` serves in 13 ms with correct 206 ranges. Every `<img>` path (stills on the stage, on the track, in the pool) loads fine in the same tab. The timeline's picture was therefore verified through ffprobe and per-slot luma on the rendered file rather than through the live preview.+>+> **A human must still judge by eye:** how the cut FEELS at the seams, whether the beat lines read at default zoom, whether the ducked bed sits right under a real performance, and whether the stage/track proportions are right on a 14" screen.++> **🎞️ 2026-08-16 — SHIPPED in v4.6.0: the timeline gets a face.** ⚠️ **PARTLY SUPERSEDED by the v4.6.0 entry at the top.** The timeline is no longer the storyboard tab's sixth stage state — it is its own top-level Editor tab with its own document id, and the `body.sbe-open` layout takeover described below was deleted rather than kept. Everything else here stands as the record. The editor's server half (proxies, peaks, `edit.json`, eight routes) shipped in `3b129ca`/`3096da5` with nothing to drive it. This is the interface, built as the storyboard tab's **sixth stage state** — not a widget bolted beside it. Vanilla JS, inline CSS, zero dependencies, same idioms as the shot list it sits next to (`sbe*` / `.sbe-*` beside `sb*` / `.sb-*`).+>+> - **One `<video>`, and the measurements say why.** Double-buffering measured no benefit once proxies are all-intra, so there is one element and one decoder. The preview never points at `clip.path` when a proxy exists (235 ms median seek vs 3.5 ms); the one case where it must says `SOURCE (slow — run Prepare)` on the badge instead of pretending. `muted` is set before the first `play()` (Chrome refuses autoplay silently) and nothing is hidden with `display:none` (WebKit will not load it). The approximation is stated once, quietly, under the transport: the browser lands within a few frames of each cut and freezes for about one there; the render is exact.+> - **Every clip owns the gap that precedes it.** That one choice makes a move, a ripple delete and a split one-liners each, and makes `film_end` derivable rather than storable — so the 1x invariant the server refuses an edit for breaking cannot be broken by the client. Both trim handles follow the pointer (left moves the in-point and leaves the tail alone; right ripples), a **locked** clip is an anchor the flow goes around rather than through, and a drag that moves the pointer but not the film is discarded rather than saved as a no-op edit that burns a revision.+> - **The beat grid is never extrapolated.** `beat_map()` fits ONE tempo across a span because real tracks drift; beats outside it do not exist, and neither do lines. Below 0.4 confidence the grid draws muted and the inspector says it is a guess, with the number.+> - **The waveform appears before `edit.json` knows about it.** `prepare` writes `peaks.json`; only an auto-edit writes the soundtrack INTO the edit. Rather than show an empty strip over a track that is right there, the axis comes off the peaks document — and the prepare line says plainly that the arrangement on screen was cut without the grid, and that Auto-edit is what puts the cuts on it.+> - **Filling a hole does NOT move the film after it** — the one operation here that does not ripple, because the shot was generated for that slot so the cuts around it would stay on their beats. `edit/generate` shows the params read back off the QUEUED JOB, not the request, because `make_job` silently drops any field it does not name.+> - **409 is answered honestly:** the other tab's revision, your revision, your arrangement still on screen, and two buttons. `Keep mine` is the only path that drops `expect_revision`, and only because a human clicked it. A 400 lights up every offending clip at once from the server's `errors[]`.+> - **The timeline owns the tab while it is open.** `body.sbe-open` folds the planning column away and gives the stage the window. Not a preference: the brief plans a film that has already been shot by the time anyone opens a timeline, and a timeline is the one surface here whose usefulness is measured in pixels per second.+> - **A narrow-window bug that predates all of this, fixed on the way past.** `.layout` is `flex: 1 1 auto` inside a `display:flex; min-height:100vh` body, so the storyboard breakpoint's `height: auto` never did anything — the grid kept the full 812px, its three `auto` rows were squeezed, the form column got ~316px for ~730px of brief, and `overflow: visible` spilled the remaining **479px straight down through the stage**. The ENGINE strip and the character picker printed over the shot list and over the editor. `flex: 0 0 auto` in that same block is the whole fix, and it is what the block's own comment ("Stacked, the PAGE scrolls") has been promising since it was written.+> - **Validated in a browser, not asserted.** A sandbox panel on :8799 against a real 5-shot board and a real track: prepare built 5 proxies in 0.85 s, tracked 104.195 BPM (confidence 0.54, 82 beats / 20 downbeats), drag-reorder / ripple-trim / split-at-playhead / ⌘Z / place-into-slot all driven with a real pointer, a real 409 forced from a second client, and `edit/render` produced a 27.875 s film with the gaps note disclosed. Checked at **800px and 1400px**: nothing outside `#sbStage` intersects the editor at either width, and the clip track clears the sticky action bar at both. Six bugs were found that way and fixed: `[hidden]` losing to `display:flex`, the stage stealing the track's height inside `#sbStage`'s flex column, the no-op drag, the follower sliding when a hole was filled, the spilled planning column above, and the video's 34vh cap pushing the track under the action bar on a 900px window (it now yields to the timeline: `min(34vh, 340px, calc(100vh - 700px))`).+>+> **Gates:** `check_ltx_pin` PASS · `check_pinokio_scripts` PASS · `check_output_codec` PASS · **588 root tests green** (`test_storyboard_editor_ui.py`, 56 new, extracts the real client functions and runs them in node).+>+> **A human must still judge by eye:** how the cut FEELS at the seams, whether the beat lines read at default zoom, and whether the stage/track proportions are right on a 14" screen.++> **✂️ 2026-08-16 — SHIPPED in v4.6.0: the storyboard export learns to edit.** Assembled films read as clips glued end to end because that is what they were: `_sb_export` concatenated WHOLE clips in `n` order, so every soft head and degrading tail played, and every cut landed wherever a 5.125 s render happened to stop.+>+> - **`storyboard_edit.py`** (new, root) — pure analysis, no HTTP, no panel import, numpy + stdlib only. `best_window()` scores every candidate window inside a clip on sharpness (variance of Laplacian), stability (frame-to-frame difference scored as a BAND, and on the window's quietest quarter as well as its mean, so a mostly-frozen window cannot average its way into the healthy range), luma sanity (near-black and blown-out windows are VETOED, not marked down — the white-tail bug class), and a configurable head/tail positional prior. Every window returns `per_second` diagnostics and a sentence saying what it beat and by how much. `beat_map()` is onset-flux + autocorrelation + a log-normal tempo prior, refined by a phase-folded grid search; it returns `confidence` and the evidence behind it. `plan_cut()` snaps each cut to a downbeat, then a beat, then leaves it alone — and says which, and by how many milliseconds.+> - **Trimming happens in the filtergraph that was already running.** `_sb_film_filtergraph` gained `cuts` and `music`; `trim`/`atrim` + `setpts` per segment, one decode, one encode. A second ffmpeg pass would have cost a whole generation of quality for nothing. The plan is matched to segments **by path, not by position**, because the assembler drops clips ffprobe cannot read.+> - **Opt-in, and provably so.** `_sb_export(auto_edit=False)` is the default, the assembler is called with the same two positional arguments it always was, and `test_no_plan_and_no_music_is_byte_identical_to_the_old_graph` pins the pre-existing graph as a literal.+> - **Validated on the real AURELIUS project**, not on fixtures: ten 1080p renders and AMOR_FATI (7:59). Detected **126.66 BPM** over the first 100 s against the shotbook's ~126, onset energy locked to **±5.55 ms**, **10/10 cuts on the grid** (6 downbeats, 4 beats), 0.00 ms residual, 57.50 s of film in **13.1 s** of wall time. The 60 s target is unreachable and the module says why rather than faking it: eleven beats is 5.211 s and the clips hold 5.167 s, so ten beats per shot is the ceiling.+> - **Honest limits recorded:** the tempo model is ONE constant BPM in 4/4 — the track drifts +0.61 BPM across 100 s and fits at 128.43 across the whole 8 minutes, which is why the grid is fitted to the span being cut rather than the whole file. Octave margin over the 84.4 BPM rival is only 0.15. Grid times carry a measured ~10 ms lead from the analysis window.+>+> **Gates:** `check_ltx_pin` PASS · `check_pinokio_scripts` PASS · `check_output_codec` PASS · 429 root tests green (`test_storyboard_edit` 55 new, `test_storyboard_assembly` 80). `scripts/test_analytics_dryrun` has 3 failures that pre-date this work (verified against a stashed tree) — all three were one undocumented event, `star_prompt`, and were fixed in v4.6.0 (`598d367`).+> **🎛️ 2026-08-16 — v4.5.0: the health cluster becomes one chip, and two fixes that came from outside.**>> - **One health chip.** Six pills truncated on a 14" window and could not take a seventh. The chip states the summary — worst state wins the colour, memory stays on the face — and a portaled popover holds Tier / Memory / Helper / Models / ComfyUI / Queue / Render. The pills are unchanged: same ids, same updaters, relocated once at boot and read back, so the summary can never disagree with them.diff --git a/lora_compat.py b/lora_compat.pyindex ededde8..29a3bd8 100644--- a/lora_compat.py+++ b/lora_compat.py@@ -10,12 +10,25 @@ starts denoising.It deliberately has no MLX or safetensors dependency. The panel uses it whilebuilding the library, and the helper uses the same code against the transformerfile it is about to load.++Names are not effect (#62)+--------------------------+Matching every key is necessary and **not sufficient**. In August 2026 two+users trained characters that attached ``576/576`` modules on the unfused+runtime route — a perfectly green tally — and changed nothing anyone could+see. The adapters were structurally flawless and numerically negligible: the+low-rank product they carry is orders of magnitude below the one recipe that+has ever carried an identity. ``measure_adapter_effect`` puts a number on+that half of the question, cheaply (the exact Frobenius norm of ``B @ A``+without ever forming ``B @ A``), so "it attached" and "it can do something"+stop being the same claim."""from __future__ import annotationsimport jsonimport struct+import sysfrom dataclasses import dataclassfrom functools import lru_cachefrom pathlib import Path@@ -27,6 +40,28 @@ LORA_B_SUFFIX = ".lora_B.weight"MIN_MATCH_RATIO = 0.90MAX_HEADER_BYTES = 64 * 1024 * 1024+#: Per-entry RMS of the low-rank delta, ``‖B @ A‖_F / sqrt(in * out)``, below+#: which an adapter has never been observed to change a render. Calibrated on+#: the adapters this repo actually ships and grades, all measured with+#: :func:`measure_adapter_effect`:+#:+#: =========================================== ========= =========+#: adapter rank median+#: =========================================== ========= =========+#: ``elontrn_v2`` (validated recipe) 32 1.63e-03+#: ``ariatrn_v2`` (validated recipe) 32 1.45e-03+#: ``eltrumpo_v2`` (validated recipe) 32 1.41e-03+#: ``bizarrotrn_v2`` (sample character) 32 8.84e-04+#: ``LTX2.3-Rogue…`` (third-party, works) 16 1.84e-03+#: ``Fantasy_Painterly`` (third-party, works) 32 5.36e-04+#: ``bizarrotrn.audio`` (voice, works) 16 4.85e-04+#: =========================================== ========= =========+#:+#: The floor sits an order of magnitude under the weakest working adapter, so+#: it accuses nothing that has ever worked, and it is two orders above a+#: freshly-initialised adapter (1.7e-05 after four steps).+WEAK_DELTA_RMS = 2.0e-4+class LoraCompatibilityError(RuntimeError):"""The named adapter cannot safely affect the named transformer."""@@ -208,6 +243,194 @@ def inspect_lora_compatibility()+@dataclass(frozen=True)+class AdapterEffect:+ """How much an adapter can move the weights it attaches to.++ ``deltas`` holds one ``‖B @ A‖_F / sqrt(in * out)`` per complete module —+ the RMS of the delta the module will actually add, which is comparable+ across shapes and ranks in a way the raw Frobenius norm is not.+ """++ lora_path: Path+ modules: int+ zero_modules: int+ median_rms: float+ max_rms: float+ floor: float = WEAK_DELTA_RMS++ @property+ def inert(self) -> bool:+ """Every module's delta is exactly zero — the adapter cannot do anything."""+ return self.modules > 0 and self.zero_modules == self.modules++ @property+ def weak(self) -> bool:+ return self.modules > 0 and not self.inert and self.median_rms < self.floor++ @property+ def summary(self) -> str:+ return (+ f"delta_rms median={self.median_rms:.2e} max={self.max_rms:.2e} "+ f"({self.modules - self.zero_modules}/{self.modules} modules carry a delta)"+ )++ def failure_message(self) -> str:+ return (+ f"LoRA '{self.lora_path.name}' carries no weight delta at all: "+ f"{self.summary}. Every low-rank product is exactly zero, so "+ "attaching it cannot change a single pixel. The file is a "+ "freshly-initialised adapter — training never moved it. Rendering "+ "was refused instead of returning a LoRA-free result."+ )++ def weak_message(self) -> str:+ return (+ f"LoRA '{self.lora_path.name}' is far weaker than any adapter that "+ f"has carried an identity here: {self.summary}, against "+ f"{self.floor:.1e} for the weakest working reference and ~1.4e-03 "+ "for the validated character recipe. Expect little or no visible "+ "effect."+ )++ def require_effective(self) -> None:+ if self.inert:+ raise LoraCompatibilityError(self.failure_message())+++def _numpy():+ """Import numpy on demand, or return ``None``.++ This module promises to be importable anywhere — the panel, the helper and+ the trainer all use it, and one of them may be a bare interpreter. The+ strength probe is the only part that needs an array library, so it degrades+ to "not measured" rather than taking the whole module down with it.+ """+ try:+ import numpy # noqa: PLC0415 — deliberate optional dependency+ except ImportError: # pragma: no cover — every supported env ships numpy+ return None+ return numpy+++_DTYPE_READERS = {"F32": ("<f4", None), "F16": ("<f2", None), "BF16": ("<u2", "bf16")}+++def measure_adapter_effect(+ lora_path: str | Path, *, floor: float = WEAK_DELTA_RMS+) -> AdapterEffect | None:+ """Measure the size of the delta an adapter would add, per module.++ ``‖B @ A‖_F`` is computed **without forming** ``B @ A``: for+ ``G = Bᵀ B`` and ``H = A Aᵀ`` (both ``r × r``),+ ``‖B A‖_F² = trace(G H)``. At rank 32 on a 4096-wide projection that is+ two thin matmuls instead of a 16 M-element product, so measuring a whole+ 500 MB character adapter costs about a second and no meaningful memory.++ Returns ``None`` when numpy is unavailable or the file declares no complete+ ``lora_A``/``lora_B`` pair (that second case is already the province of+ :func:`inspect_lora_compatibility`, which fails closed on it).+ """+ np = _numpy()+ if np is None:+ return None+ path = Path(lora_path)+ header = read_tensor_header(path)+ modules = sorted(+ {+ key[: -len(LORA_A_SUFFIX)]+ for key in header+ if key.endswith(LORA_A_SUFFIX)+ }+ & {+ key[: -len(LORA_B_SUFFIX)]+ for key in header+ if key.endswith(LORA_B_SUFFIX)+ }+ )+ if not modules:+ return None++ with path.open("rb") as fh:+ header_size = struct.unpack("<Q", fh.read(8))[0]+ payload_base = 8 + header_size++ def read(key: str):+ info = header[key]+ spec = _DTYPE_READERS.get(str(info.get("dtype")))+ if spec is None:+ return None+ start, end = info["data_offsets"]+ fh.seek(payload_base + start)+ raw = fh.read(end - start)+ dtype, conversion = spec+ flat = np.frombuffer(raw, dtype=dtype)+ if conversion == "bf16":+ flat = (flat.astype(np.uint32) << 16).view(np.float32)+ return flat.astype(np.float32).reshape(info["shape"])++ rms: list[float] = []+ zero = 0+ for module in modules:+ a = read(module + LORA_A_SUFFIX)+ b = read(module + LORA_B_SUFFIX)+ if a is None or b is None or a.ndim != 2 or b.ndim != 2:+ continue+ if a.shape[0] != b.shape[1]:+ continue # rank disagreement: a shape problem, not a size one+ gram = b.T @ b+ cov = a @ a.T+ frob = float(np.sqrt(max(float((gram * cov.T).sum()), 0.0)))+ entries = float(a.shape[1]) * float(b.shape[0])+ value = frob / (entries**0.5) if entries else 0.0+ rms.append(value)+ if value == 0.0:+ zero += 1++ if not rms:+ return None+ rms.sort()+ middle = len(rms) // 2+ median = rms[middle] if len(rms) % 2 else (rms[middle - 1] + rms[middle]) / 2+ return AdapterEffect(+ lora_path=path,+ modules=len(rms),+ zero_modules=zero,+ median_rms=median,+ max_rms=rms[-1],+ floor=floor,+ )+++def validate_adapter_effects(+ loras: Iterable[tuple[str, float]],+ *,+ reporter: Callable[[str], None] | None = None,+) -> list[AdapterEffect]:+ """Report every adapter's strength, and refuse the ones that are all zero.++ Sits beside :func:`validate_lora_stack`: that one answers "can these keys+ land on this checkpoint", this one answers "is there anything in them".+ A weak-but-nonzero adapter is reported, never refused — the owner may be+ deliberately running a light touch, and a threshold has no business+ outranking a person.+ """+ measured: list[AdapterEffect] = []+ for index, (path, strength) in enumerate(loras, start=1):+ if float(strength) == 0.0:+ continue+ effect = measure_adapter_effect(path)+ if effect is None:+ continue+ if reporter is not None:+ reporter(f"LoRA[{index}] {effect.summary} file={effect.lora_path.name}")+ if effect.weak:+ reporter(f"LoRA[{index}] WARNING: {effect.weak_message()}")+ effect.require_effective()+ measured.append(effect)+ return measured++def resolve_distilled_transformer(model_dir: str | Path) -> Path | None:"""Resolve the distilled file using the pinned pipeline's precedence."""root = Path(model_dir)@@ -249,6 +472,80 @@ def validate_lora_stack(return reports+#: Exit codes for :func:`main`. ``weak`` deliberately does NOT fail: a light+#: touch is the owner's call, not a threshold's (same doctrine as+#: :func:`validate_adapter_effects`). Only ``inert`` is unambiguously a failed+#: training, and only an unreadable path is unambiguously the caller's mistake.+_EXIT_FOR_STATUS = {"inert": 1, "missing": 2, "error": 2, "unmeasured": 2}+++def describe_adapter(lora_path: str | Path) -> tuple[str, str]:+ """``(status, line)`` describing what a single adapter can do.++ ``status`` is one of ``ok`` / ``weak`` / ``inert`` / ``missing`` /+ ``error`` / ``unmeasured``; ``line`` is the human-readable report.++ The whole #62 investigation was a person spending days proving a negative+ about a file that was sitting on their disk the entire time. The number+ that answers it costs about a second to compute, so it should not require+ a render, a re-train, or a 500 MB upload to see.+ """+ path = Path(lora_path)+ if not path.is_file():+ return "missing", f"{path.name}: NOT FOUND ({path})"+ try:+ effect = measure_adapter_effect(path)+ except LoraCompatibilityError as exc:+ return "error", f"{path.name}: UNREADABLE — {exc}"+ if effect is None:+ return "unmeasured", (+ f"{path.name}: NOT MEASURED — either numpy is unavailable or the "+ "file declares no complete lora_A/lora_B pair."+ )+ if effect.inert:+ status = "inert"+ verdict = "INERT — training moved nothing; treat the run as failed"+ elif effect.weak:+ status = "weak"+ verdict = (+ f"WEAK — under {effect.floor:.1e}, the floor every adapter that "+ "has carried an identity here sits above"+ )+ else:+ status = "ok"+ verdict = "OK — in the band adapters that work sit in"+ return status, f"{path.name}: {effect.summary} — {verdict}"+++def main(argv: list[str] | None = None) -> int:+ """`python3 lora_compat.py <adapter.safetensors> [...]`.++ Prints the delta each adapter carries and a verdict per file. Exit 1+ means at least one file is INERT (every low-rank product exactly zero) —+ the one state that is unambiguously a failed training. Exit 2 means a+ path could not be measured at all, which is the caller's mistake rather+ than the adapter's. WEAK is reported and never fails the command: a+ light touch is the owner's call, not a threshold's.+ """+ args = list(sys.argv[1:] if argv is None else argv)+ if not args or args[0] in ("-h", "--help"):+ sys.stdout.write(+ "usage: python3 lora_compat.py <adapter.safetensors> [more ...]\n"+ "\n"+ "Measures the size of the weight delta each LoRA carries and says\n"+ "whether it is big enough to change a render. Reference band: the\n"+ "characters this repo ships measure 8.8e-04 to 1.6e-03; a freshly\n"+ "initialised adapter that never trained measures ~1.7e-05.\n"+ )+ return 0 if args else 2+ worst = 0+ for raw in args:+ status, line = describe_adapter(raw)+ sys.stdout.write(line + "\n")+ worst = max(worst, _EXIT_FOR_STATUS.get(status, 0))+ return worst++def validate_runtime_application(loras: Iterable[tuple[LoraCompatibility, float]],applied_module_names: Iterable[str],@@ -288,3 +585,7 @@ def validate_runtime_application(f"(minimum {report.minimum_match_ratio:.0%}). Rendering was ""refused before it could produce a LoRA-free result.")+++if __name__ == "__main__": # pragma: no cover - CLI entry+ raise SystemExit(main())diff --git a/lora_lab/train_audio.py b/lora_lab/train_audio.pyindex 554404a..783e6d9 100644--- a/lora_lab/train_audio.py+++ b/lora_lab/train_audio.py@@ -587,6 +587,16 @@ def run_pipeline(spec_path: Path) -> int:except Exception as exc: # noqa: BLE001emit_error_and_exit("publish", f"failed to copy checkpoint: {exc}")+ # Same honesty the image LoRA gets: say how much delta the voice adapter+ # carries. #62 reported the voice LoRA "equally ignored", and a run that+ # ends with a path and no number gives nobody anything to check.+ try:+ from lora_lab.train_character import report_adapter_strength++ report_adapter_strength(output_path)+ except Exception as exc: # noqa: BLE001 — a probe never fails a finished run+ emit("log", line=f"adapter strength: not measured ({exc})")+emit("done", path=str(output_path))return 0diff --git a/lora_lab/train_character.py b/lora_lab/train_character.pyindex f17c836..f7647fd 100644--- a/lora_lab/train_character.py+++ b/lora_lab/train_character.py@@ -106,7 +106,18 @@ logger = logging.getLogger(__name__)# -----------------------------------------------------------------------# Presets + estimator (both must stay in lockstep with the panel JS mirror)+# CLI-ONLY DEFAULTS. NOT a mirror of the panel's presets — they have never+# matched, and the comment that said they must is what made a change to+# either one look safe.+#+# The panel writes every hyperparameter it cares about into spec.json+# (rank / alpha / steps / lr / resolution), and `resolve_preset` lets those+# `advanced` values win — so on a panel-driven run this table is dead code.+# It is live on the CLI path only, where `--preset quick` trains rank 16+# while the panel's Quick trains rank 8, and the panel derives steps from+# `epochs x image_count` while these are fixed. Same word, two recipes: read+# them as this module's defaults and nothing else. If they ever need to agree,+# make one of them import the other rather than restating it here.# ----------------------------------------------------------------------PRESETS: dict[str, dict[str, Any]] = {@@ -126,7 +137,11 @@ PRESETS: dict[str, dict[str, Any]] = {TARGET_MODULES = ["to_q", "to_k", "to_v", "to_out"]-# Estimator constants — keep in sync with panel mirror.+# Estimator constants for THIS module's estimate. The panel's ETA is a+# different formula, not a copy of this one: it uses a per-preset+# `seconds_per_step` with no fixed term, and `3.0 * image_count` for+# preprocessing. Nothing gates the two against each other because they are+# not the same estimate._BASE_STEP_S = 2.4 # M4 Max 64 GB, 576x576 rank 32_PREPROCESS_FIXED_S = 90.0 # model load + Gemma init_PREPROCESS_PER_IMAGE_S = 2.0 # VAE encode per image@@ -732,6 +747,71 @@ def run_training(# Sidecar# ----------------------------------------------------------------------+def report_adapter_strength(lora_path: Path) -> dict[str, Any] | None:+ """Measure what the finished adapter can actually do, and say so.++ A training run that completes is not a training run that worked. In August+ 2026 two users (issues #61, #62) trained characters that finished clean,+ saved a 132–500 MB file, attached ``576/576`` modules at render — and moved+ nothing a human eye could see. Nothing anywhere in the pipeline had ever+ measured the one quantity that decides it: the size of the low-rank delta+ the file carries. So the run ended with "done ✓" and the user spent days+ proving a negative.++ This emits that number at the end of every training run, next to the file+ it describes, and shouts when it lands below the band every adapter that+ has ever carried an identity here sits in (``lora_compat.WEAK_DELTA_RMS``,+ calibrated against the shipped characters and third-party LoRAs). It does+ not fail the job: the file is still saved, still usable, and the owner may+ want a deliberately light touch. It just stops the silence.+ """+ try:+ from lora_compat import measure_adapter_effect+ except ImportError: # pragma: no cover — panel root is always on PYTHONPATH+ return None+ try:+ effect = measure_adapter_effect(lora_path)+ except Exception as exc: # noqa: BLE001 — a probe must never fail a run+ emit("log", line=f"adapter strength: not measured ({exc})")+ return None+ if effect is None:+ return None++ payload = {+ "modules": effect.modules,+ "carrying_modules": effect.modules - effect.zero_modules,+ "delta_rms_median": effect.median_rms,+ "delta_rms_max": effect.max_rms,+ "floor": effect.floor,+ "verdict": "inert" if effect.inert else ("weak" if effect.weak else "ok"),+ }+ emit("adapter_strength", **payload)+ emit("log", line=f"adapter strength: {effect.summary}")+ if effect.inert:+ emit(+ "warning",+ stage="verify",+ message=(+ f"{lora_path.name} carries no weight delta at all — every "+ "low-rank product is zero, so it cannot change a render. "+ "Training moved nothing; treat this run as failed."+ ),+ )+ elif effect.weak:+ emit(+ "warning",+ stage="verify",+ message=(+ f"{lora_path.name} is much weaker than the adapters that carry "+ f"identity here (measured {effect.median_rms:.2e}, floor "+ f"{effect.floor:.1e}, validated recipe ~1.4e-03). Expect little "+ "or no visible effect. The High preset (rank 32, ~100 epochs, "+ "lr 1e-4) is the only recipe graded for identity."+ ),+ )+ return payload++def write_sidecar(*,lora_path: Path,@@ -739,6 +819,7 @@ def write_sidecar(trigger: str,image_count: int,training_wall_s: float,+ strength: dict[str, Any] | None = None,) -> Path:sidecar_path = lora_path.with_suffix(lora_path.suffix + ".json")payload = {@@ -767,6 +848,11 @@ def write_sidecar("lora_lab_version": "iter5","loadable_via": "ltx_core_mlx.loader.fuse_loras.apply_loras",}+ if strength is not None:+ # Kept with the adapter so a file that turns up months later can be+ # judged without re-measuring, and so the panel can show the verdict+ # next to the character it belongs to.+ payload["adapter_strength"] = strengthsidecar_path.write_text(json.dumps(payload, indent=2))emit("sidecar_written", path=str(sidecar_path))return sidecar_path@@ -935,6 +1021,10 @@ def run_pipeline(spec_path: Path) -> int:except Exception as exc: # noqa: BLE001emit_error_and_exit("publish", f"failed to copy checkpoint: {exc}")+ # Measure before the sidecar so the strength verdict is on record even if+ # sidecar writing fails — the number is the part a stuck user needs.+ strength = report_adapter_strength(output_lora_path)+try:write_sidecar(lora_path=output_lora_path,@@ -942,6 +1032,7 @@ def run_pipeline(spec_path: Path) -> int:trigger=trigger,image_count=image_count,training_wall_s=training_wall_s,+ strength=strength,)except Exception as exc: # noqa: BLE001emit_error_and_exit("sidecar", str(exc))diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex 3481630..efeb32f 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -40,6 +40,16 @@ import urllib.parseimport urllib.requestfrom urllib.parse import parse_qs, quote, urlparse+# WHAT THE USER CALLS THE THING BEING CUT. The owner: "these are not+# films... something less bad than film." One noun, three forms, and every+# user-visible mention in the Editor is a token replaced at serve time — so+# changing his mind costs one line here and nothing else. Internal field+# names (`film_start`, `film_end`, `sbeFilmDuration`) are untouched on+# purpose: they are the schema, and a label is not worth a data migration.+SEQ_NOUN = "sequence"+SEQ_NOUN_PL = "sequences"+SEQ_NOUN_CAP = "Sequence"+# Image generation engine — used by the /image/generate endpoint.# Previously lived at agent/image_engine.py; moved to top level when the# agentic flows feature was removed 2026-05-15. The module is self-contained@@ -160,6 +170,30 @@ COMFY_PATTERN = os.environ.get("LTX_COMFY_PATTERN", "pinokio/api/comfy.git.*main# get a one-time migration of root-level files into state/ at startup# (see _migrate_state_dir below) so users don't lose their queue.STATE_DIR = Path(os.environ.get("LTX_STATE_DIR", str(ROOT / "state")))+++def _state_dir_is_native() -> bool:+ """Is this panel serving the install's OWN films?++ False means somebody pointed LTX_STATE_DIR somewhere else — which is what+ a verification instance does, and what the header has to shout about. The+ symlinked `state/` of a dev clone still counts as native: it is resolved+ on both sides, so a shared drive is the install's state, not a stranger's.+ """+ try:+ return STATE_DIR.resolve() == (ROOT / "state").resolve()+ except OSError:+ return False+# ONE CACHE, HOWEVER THE PANEL WAS LAUNCHED. start.js exports HF_HOME so every+# weight lands in <install>/cache/HF_HOME — but the panel also gets launched+# from bare shells (development, agents, a terminal after a crash), and every+# subprocess it spawns (mflux, hf downloads) then silently re-downloads into+# ~/.cache/huggingface instead of SEEING the tens of GB already on disk. That+# forked cache twice nearly filled the system volume in one week — the second+# time to 177 MB free, mid-render. setdefault, not assignment: an explicit+# HF_HOME (a self-hoster's NAS, a test fixture) still wins.+if (ROOT / "cache" / "HF_HOME").is_dir():+ os.environ.setdefault("HF_HOME", str(ROOT / "cache" / "HF_HOME"))QUEUE_FILE = STATE_DIR / "panel_queue.json"HIDDEN_FILE = STATE_DIR / "panel_hidden.json"# Repo-stats dashboard (Mr Bizarro 2026-05-22: solo-maintainer signal,@@ -181,6 +215,35 @@ PROMPT_ENHANCE_TIMEOUT = max()FPS = 24+# THE MIX LIVES IN THE DOCUMENT NOW — see `storyboard_editor.audio_mix` and+# the block above it. This file used to hold five numbers that decided what a+# film sounded like and appeared on no screen: a hard-coded `volume=0.20` on+# every `under` bed and a `sidechaincompress` keyed on the dialogue, neither of+# them in any document, neither of them in the preview. The renderer was a+# second author of the soundtrack's level, and the owner heard it: "when you+# render it, there are some weird manipulations... the volume of the music goes+# low when the dialogue appears."+#+# They are now `audio.mix.bed_gain` and `audio.mix.duck` on the timeline, read+# by `bed_gain_points` — the ONE curve the preview, the render and the export+# all consume. `migrate_edit` stamps the old pair onto documents that predate+# the controls, so an approved film keeps the levels it was approved at.+#+# ONE THING STAYS HERE, AND ONLY BECAUSE THE PANEL MUST BOOT WITHOUT THE+# EDITOR MODULE: the limiter's last-resort threshold. `MIX_CEILING` in+# `storyboard_editor` is the definition; this is the value used if that import+# fails, and shipping an UNLIMITED mix would be the worse failure of the two.+# `test_the_panel_and_the_model_agree_about_the_ceiling` refuses a drift.+SB_MIX_CEILING_FALLBACK = 0.9+++def _sb_mix_ceiling() -> float:+ """The soft-clip knee, from the one place it is defined."""+ try:+ return float(_sbe_import().MIX_CEILING)+ except Exception: # noqa: BLE001+ return SB_MIX_CEILING_FALLBACK+def _optional_bool_env(name: str) -> bool | None:v = os.environ.get(name, "").strip().lower()@@ -1411,39 +1474,66 @@ _THUMBCACHE = UPLOADS / ".thumbcache"def _ensure_thumbnail(src: Path, width: int) -> Path:- """Return a path to a resized JPEG thumbnail of `src` at `width` pixels.+ """Return a path to a resized thumbnail of `src` at `width` pixels.Cached on disk. Idempotent. Aspect ratio preserved (height derivedfrom the source's aspect). Width is clamped to [16, 2048] beforethe lookup so a malformed query string can't force a giant resize.++ JPEG for an opaque source, PNG for one with an alpha channel."""width = max(16, min(2048, int(width)))try:st = src.stat()except OSError:raise FileNotFoundError(f"source not found: {src}")+ # TWO POSSIBLE OUTPUTS, because JPEG CANNOT CARRY ALPHA. The overlay lane+ # asks this route for a width-limited copy of a transparent card, and a+ # JPEG answer flattened it onto black — the card arrived as a black bar+ # over the picture, which is exactly the thing the lane exists to avoid.+ # A source with alpha is answered in PNG; everything else keeps the JPEG+ # that makes the pool cheap.+ from PIL import Image+ # THE FORMAT IS DECIDED BEFORE THE CACHE IS CONSULTED, not after. Checking+ # the .jpg first would keep serving a thumbnail flattened by the old code+ # for as long as the source went unedited — the cache key is (path, mtime,+ # size, width), and fixing the encoder does not change any of them. Reading+ # the header is cheap: PIL parses it and defers the pixels.+ #+ # `getbands()` RATHER THAN A LIST OF MODES, so LA, PA and RGBA are one+ # question instead of three that have to be remembered — and wrapped,+ # because a header this cannot parse is a thumbnail that should fall back+ # to the old behaviour rather than a 500 on a gallery paint.+ try:+ with Image.open(src) as probe:+ keep_alpha = ("A" in probe.getbands()+ or "transparency" in probe.info)+ except (OSError, ValueError):+ keep_alpha = False# Cache key: hash of (resolved path, mtime, size, width). mtime# and size together catch the common "user edited the file" case# without needing a full content hash.import hashlibraw = f"{src.resolve()}|{st.st_mtime_ns}|{st.st_size}|{width}".encode()key = hashlib.sha1(raw).hexdigest()- out = _THUMBCACHE / f"{key}.jpg"+ out = _THUMBCACHE / f"{key}.{'png' if keep_alpha else 'jpg'}"if out.exists() and out.stat().st_size > 0:return out_THUMBCACHE.mkdir(parents=True, exist_ok=True)- from PIL import Imagewith Image.open(src) as im:- im = im.convert("RGB")+ im = im.convert("RGBA" if keep_alpha else "RGB")# PIL's thumbnail() preserves aspect ratio and only shrinks (never# upscales — passing w=2048 on a 1024-wide source returns the# original size).im.thumbnail((width, width * 10), Image.Resampling.LANCZOS)- # JPEG q=85 hits the sweet spot for thumbnails — visually- # indistinguishable from the source at carousel size, ~5-10x- # smaller than the equivalent PNG.- im.save(out, format="JPEG", quality=85, optimize=True,- progressive=False)+ if keep_alpha:+ im.save(out, format="PNG", optimize=True)+ else:+ # JPEG q=85 hits the sweet spot for thumbnails — visually+ # indistinguishable from the source at carousel size, ~5-10x+ # smaller than the equivalent PNG.+ im.save(out, format="JPEG", quality=85, optimize=True,+ progressive=False)return out@@ -1510,13 +1600,18 @@ TRAIN_PRESETS = {"quick": {"epochs": 30, "rank": 8, "lr": 1e-4, "resolution": 512,"seconds_per_step": 1.5, "ram_peak_gb": 12,"label": "Quick",- "subtitle": "~30 epochs · rank 8 · 512px",+ # HONEST ABOUT WHAT HAS BEEN GRADED. The rank-32 recipe is the+ # one measured on faces (Aria_v2, Bizarro_v2); nobody has ever+ # put a rank-8 result in front of the owner's eye and called+ # the identity good. Saying "fast" and letting the user infer+ # "as good, sooner" is the pill doing the lying.+ "subtitle": "~30 epochs · rank 8 · 512px · fast, identity ungraded","checkpoint_interval": 500,"max_steps": 8000},"medium": {"epochs": 60, "rank": 16, "lr": 1e-4, "resolution": 576,"seconds_per_step": 2.2, "ram_peak_gb": 18,"label": "Medium",- "subtitle": "~60 epochs · rank 16 · 576px",+ "subtitle": "~60 epochs · rank 16 · 576px · identity ungraded","checkpoint_interval": 500,"max_steps": 12000},# high tier mirrors the validated CLI recipe (rank 32 / 100 epochs /@@ -1605,26 +1700,34 @@ def _select_train_profile(total_ram_gb: float, tier_key: str) -> dict:them."""if 0 < float(total_ram_gb or 0) < 64:+ # EVERY PRESET ON THIS HARDWARE IS UNGRADED, and the pills that most+ # need to say so are these. The >=64GB table earns the warning on+ # Quick and Medium because nobody has put a rank-8 identity in front+ # of the owner's eye — down here HIGH is rank 8 at 500 steps, which is+ # by definition the same regime, so a user meeting a `weak` adapter+ # verdict is most likely looking at their machine and not at their+ # photos. The preset NAMES do not change, so the subtitle is the only+ # place this can be said.compact_modules = list(TRAIN_TARGET_MODULES_COMPACT)TRAIN_PRESETS.update({"quick": {"epochs": 2, "rank": 4, "lr": 1e-4, "resolution": 384,"seconds_per_step": 14.0, "ram_peak_gb": 38,"label": "Quick",- "subtitle": "~2 epochs · rank 4 · 384px · max 120 steps",+ "subtitle": "~2 epochs · rank 4 · 384px · max 120 steps · identity ungraded","checkpoint_interval": 100,"max_steps": 120, "max_rank": 4, "max_resolution": 384,"target_modules": compact_modules},"medium": {"epochs": 5, "rank": 8, "lr": 1e-4, "resolution": 384,"seconds_per_step": 16.0, "ram_peak_gb": 40,"label": "Medium",- "subtitle": "~5 epochs · rank 8 · 384px · max 300 steps",+ "subtitle": "~5 epochs · rank 8 · 384px · max 300 steps · identity ungraded","checkpoint_interval": 100,"max_steps": 300, "max_rank": 8, "max_resolution": 384,"target_modules": compact_modules},"high": {"epochs": 10, "rank": 8, "lr": 1e-4, "resolution": 448,"seconds_per_step": 20.0, "ram_peak_gb": 44,"label": "High",- "subtitle": "~10 epochs · rank 8 · 448px · max 500 steps",+ "subtitle": "~10 epochs · rank 8 · 448px · max 500 steps · identity ungraded","checkpoint_interval": 100,"max_steps": 500, "max_rank": 8, "max_resolution": 448,"target_modules": compact_modules},@@ -1793,9 +1896,26 @@ TRAIN_CAPTION_MAX_BYTES = 64 * 1024 # 64 KB per caption (huge headrTRAIN_BUNDLE_MAX_BYTES = 500 * 1024 * 1024 # 500 MB upper boundTRAIN_BUNDLE_MAX_ENTRIES = 200 # paranoia cap on ZIP entries# Allowed entry name pattern — basename only, no subdirs, no path traversal.-# Stem ≤ 64 chars, then a single dot + one of our extensions.+#+# 2026-08-16 (#61): the old pattern was `[A-Za-z0-9_\-]{1,64}` + a+# lower-case extension, which silently rejected the filenames people+# actually have. A user dropped 18 images and 12 arrived; the six that+# vanished were ordinary names. All of these FAILED:+#+# image (1).png parentheses — what every browser download looks like+# shot 04.png a space+# ComfyUI.00012.png a dot inside the stem+# IMG_2213.PNG an upper-case extension+#+# Path safety never depended on this regex: the caller already reduces the+# entry to `Path(info.filename).name`, and Pass 1 RENUMBERS every image on+# save, so the user's characters never reach the filesystem. The pattern's+# only real job is to keep out separators, control characters and the wrong+# file types. It now says exactly that instead of also enforcing a house+# style nobody was told about.TRAIN_BUNDLE_NAME_RE = re.compile(- r"^[A-Za-z0-9_\-]{1,64}\.(png|jpg|jpeg|webp|txt)$"+ r"^(?![.\s])[^/\\\x00-\x1f]{1,120}\.(?:png|jpe?g|webp|txt)$",+ re.IGNORECASE,)# Voice clip rules. The voice clip is optional — if the user uploads one and@@ -2116,10 +2236,31 @@ def _train_list_completed() -> list[dict]:"size_mb": round(stat.st_size / (1024 * 1024), 1),"created_at": meta.get("created_at") or stat.st_mtime,"image_count": meta.get("image_count") or 0,+ # WHETHER THIS FILE CAN DO ANYTHING, carried out of the+ # sidecar so the library can warn before somebody spends a+ # render finding out. "unknown" for anything trained by a+ # build that did not measure — silence is not weakness, and a+ # chip on every older LoRA would be noise nobody could act on.+ "adapter_verdict": _adapter_verdict(meta),})return out+def _adapter_verdict(meta: dict) -> str:+ """`ok` | `unknown` | whatever the trainer called it.++ A LoRA can train to completion, write a valid safetensors, load without a+ warning and change NOTHING — the deltas it learned are numerically too+ small to move the model. Every gate we had said "done"; only the render+ said otherwise. This is the one field that knows.+ """+ a = (meta or {}).get("adapter_strength")+ if isinstance(a, dict):+ v = str(a.get("verdict") or "unknown").lower()+ return v if v else "unknown"+ return "unknown"++def _train_required_models() -> list[dict]:"""Return the list of model files Train Character needs and whether eachis present locally. Surfaces missing models to the UI so the user can@@ -3399,14 +3540,97 @@ def _fetch_raw_text(url: str, timeout: int = 10) -> str | None:## This is deliberately captured at IMPORT, not inside a function that anything# else might call again.+#+# 2026-08-20 — except it was NOT captured at import. The only caller was+# `version_check_loop`, a thread `__main__` starts only `if+# VERSION_CHECK_ENABLED`. `PHOSPHENE_DISABLE_VERSION_CHECK=1` therefore left+# _BOOT_HEAD_SHA at None for the life of the process, and `disk != boot` is+# False when boot is None — the dead detector this comment is about, back+# through the side door. The capture runs beside the definition now, which is+# what "at IMPORT" has to mean.+#+# And it is a SNAPSHOT, not one SHA. Every field the header stamp renders —+# version label, branch, commit date — has to come from the same frozen+# moment. `_VERSION_STATE["local_*"]` re-reads all four from disk on every+# poll, so the stamp described the WORKING TREE, not the running process: pull+# under a live panel and the header immediately advertises the new build while+# the old code keeps serving. The restart tooltip degenerated with it, since+# both sides of "X is on disk but this process loaded Y" read the same+# disk-derived label — "Phosphene 4.6.0 is on disk, but this panel process+# loaded 4.6.0". The stamp is how the owner tells which build he is on; it+# has to name the code that is answering him._BOOT_HEAD_SHA: str | None = None+_BOOT_VERSION: str | None = None+_BOOT_BRANCH: str | None = None+_BOOT_COMMIT_DATE: str | None = Nonedef _capture_boot_head() -> None:- """Record this process's HEAD exactly once. Idempotent by design."""- global _BOOT_HEAD_SHA- if _BOOT_HEAD_SHA is None:- _BOOT_HEAD_SHA = _git_capture(["rev-parse", "HEAD"])+ """Record what THIS process loaded, exactly once. Idempotent by design.++ Runs at import. `version_check_loop` still calls it, belt-and-braces for+ any path that reaches the loop without the import-time call having taken+ (a test that reset the globals, a future entry point); the guard makes the+ second call a no-op rather than a re-point at whatever is on disk now."""+ global _BOOT_HEAD_SHA, _BOOT_VERSION, _BOOT_BRANCH, _BOOT_COMMIT_DATE+ if _BOOT_VERSION is None:+ # A zip install has no git and still ships a VERSION file. That file+ # is a property of the code this process loaded, so freeze it whether+ # or not the SHA lookup below works.+ _BOOT_VERSION = _read_local_version()+ if _BOOT_HEAD_SHA is not None:+ return+ sha = _git_capture(["rev-parse", "HEAD"])+ if not sha:+ return # not a checkout — the SHA fields stay None+ _BOOT_HEAD_SHA = sha+ _BOOT_BRANCH = _git_capture(["rev-parse", "--abbrev-ref", "HEAD"])+ _BOOT_COMMIT_DATE = _git_capture(+ ["log", "-1", "--format=%cd", "--date=format:%Y-%m-%d"])+++def boot_build_stamp() -> dict:+ """What this process is running. ONE accessor, so a second reader cannot+ quietly grow a second answer to "which build is this?"."""+ return {+ "sha": _BOOT_HEAD_SHA,+ "short": _BOOT_HEAD_SHA[:7] if _BOOT_HEAD_SHA else None,+ "version": _BOOT_VERSION,+ "branch": _BOOT_BRANCH,+ "commit_date": _BOOT_COMMIT_DATE,+ }+++def running_version() -> str:+ """The VERSION label of the code THIS PROCESS is running.++ Everything that stamps a label onto something the process produced — an+ analytics event, a rendered film, a sidecar — has to name the build that+ produced it. `_read_local_version()` re-reads the tree, so after a pull+ under a running panel every one of those said the NEW number while the+ OLD code was doing the work: an app_boot event from a build that never+ booted, a film crediting a renderer that never touched it. Same defect as+ the header stamp, same fix. Disk is the fallback for a zip install with+ no git, where the boot capture has no SHA to anchor to."""+ return boot_build_stamp()["version"] or _read_local_version() or "dev"+++def build_stamp_text() -> str:+ """The build stamp as one greppable line, for the `phosphene-build` meta+ tag. The page is full of real SHAs in comments that reference historical+ commits ("the loadParams fix (b024bb5)"); thirteen of them as of today,+ and NONE of them the running build, which appeared nowhere in the served+ HTML at all. Anyone answering "which build is this?" by searching the page+ hit a decoy. This is the one line that is the answer."""+ b = boot_build_stamp()+ parts = [b["version"] or "dev", b["branch"] or "no-branch",+ b["short"] or "no-git"]+ if b["commit_date"]:+ parts.append(b["commit_date"])+ return " · ".join(parts)+++_capture_boot_head() # AT IMPORT — before anything can serve a requestdef _detect_local_install_state() -> None:@@ -3589,24 +3813,42 @@ def get_version_state() -> dict:"""Snapshot of _VERSION_STATE for the /version endpoint. Returns a copyso the caller can't mutate the live state under the lock.- STALE-PROCESS DETECTION (v4.0.5): local_* is the boot snapshot, so a- checkout that advances UNDER a running panel — a promote landing while a- long-lived daemon serves, the exact 2026-08-14 incident where :8198- served pre-4.0.4 HTML for three hours after the folder updated — used to- be invisible: /version reported the boot SHA and nothing compared it to- disk. One git rev-parse per /version request (the pill polls every 5- minutes) answers the only question that matters: is the code on disk the- code this process loaded?"""+ TWO BUILDS, ALWAYS BOTH. `local_*` is what THIS PROCESS LOADED — the boot+ snapshot, frozen at import. `disk_*` is the working tree right now, one+ `git rev-parse` per request (the pill polls every 5 minutes). On a healthy+ install they are equal, and that is the point: when they diverge the+ header has to keep naming the code that is actually answering, or the+ stamp stops being the thing the owner uses to tell which build he is on.+ The 2026-08-14 incident where :8198 served pre-4.0.4 HTML for three hours+ after the folder updated is what `stale_process` is for.++ `_VERSION_STATE["local_*"]` is NOT that snapshot, despite the name. It is+ re-detected from disk at the top of every remote poll, deliberately, so a+ tree that was dirty at boot and is clean now stops being suppressed+ without a restart. It stays the basis for `behind_by` — being behind+ origin/main is a fact about the TREE — and is overwritten here for+ display, which is a fact about the PROCESS."""with _VERSION_LOCK:snap = dict(_VERSION_STATE)+ boot = boot_build_stamp()disk_sha = _git_capture(["rev-parse", "HEAD"])- # _BOOT_HEAD_SHA, never snap["local_sha"]: the latter is re-detected on- # every remote poll and therefore always agrees with disk.- boot_sha = _BOOT_HEAD_SHA- snap["stale_process"] = bool(disk_sha and boot_sha and disk_sha != boot_sha)- if snap["stale_process"]:- snap["disk_short"] = disk_sha[:7]- snap["disk_version"] = _read_local_version()+ # The header stamp answers exactly one question — what code is this+ # process running — so it is answered from the boot snapshot or not at+ # all. Never snap["local_*"]: that agrees with disk within one poll.+ if boot["sha"]:+ snap["local_sha"] = boot["sha"]+ snap["local_short"] = boot["short"]+ snap["local_version"] = boot["version"]+ snap["local_branch"] = boot["branch"] or snap.get("local_branch")+ snap["local_commit_date"] = boot["commit_date"]+ # Unconditional, not "only when stale". A consumer that must check+ # stale_process before it may trust disk_short is a consumer that will+ # eventually forget to.+ snap["disk_sha"] = disk_sha+ snap["disk_short"] = disk_sha[:7] if disk_sha else None+ snap["disk_version"] = _read_local_version()+ snap["stale_process"] = bool(+ disk_sha and boot["sha"] and disk_sha != boot["sha"])return snap@@ -9496,9 +9738,9 @@ def h3_status() -> dict:"note": ("" if (available and h3_live_preview_ready())else ("This Hailuo H3 pack predates the live preview. "- "Re-run \'Install Hailuo H3\' from the Phosphene "- "sidebar in Pinokio to update the runner — your "- "weights stay. Renders are unaffected meanwhile.")+ "Run \'Update Hailuo H3 runner\' from the Phosphene "+ "sidebar in Pinokio — your weights stay. Renders are "+ "unaffected meanwhile.")if (available and not h3_supports_live_preview()) else ""),},# Turbo — the 4-step distill LoRA. A separate block rather than a bare@@ -10337,13 +10579,13 @@ def _analytics_boot() -> None:# fresh install (new UUID) reports its own app_installed once.if not bool(get_settings().get("analytics_install_reported")):_analytics_capture("app_installed", {- "version": _read_local_version() or "unknown",+ "version": running_version(),"chip_family": _analytics_chip_family(),"ram_gb": int(round(SYSTEM_RAM_GB)),})_settings_set_internal(analytics_install_reported=True)_analytics_capture("app_boot", {- "version": _read_local_version() or "unknown",+ "version": running_version(),"os_version": _analytics_os_version(),"chip_family": _analytics_chip_family(),"ram_gb": int(round(SYSTEM_RAM_GB)),@@ -10579,7 +10821,7 @@ def _analytics_render_event(job: dict) -> None:# by chip" and "wall time by machine class" are one-click# PostHog breakdowns instead of an unwritten join. No new# information about the person — only the render.- "version": _read_local_version() or "unknown",+ "version": running_version(),"chip_family": _analytics_chip_family(),"ram_gb": int(round(SYSTEM_RAM_GB)),"os_version": _analytics_os_version(),@@ -11564,12 +11806,33 @@ def list_outputs(image_root = UPLOADS / "library" / "manual"image_exts = {".png", ".jpg", ".jpeg", ".webp"}image_candidates: list[tuple[Path, float]] = []+ # OUTPUT HOLDS PICTURES TOO, and this listing did not know it. The image+ # queue drops its renders into the library below, so that is where the+ # gallery looked — but an endcard, a reference sheet or a saved frame that+ # lands in `mlx_outputs/` alongside the clips was invisible everywhere the+ # gallery is the source: the carousel, and the Editor's Images tab, which+ # is where a still becomes an overlay. The symptom was a user being told to+ # pick a card that was sitting in his outputs folder and not in the list.+ #+ # NON-RECURSIVE, exactly like the `OUTPUT.glob("*.mp4")` above it. The+ # subfolders under OUTPUT are working directories — proxies, per-film+ # project folders, report intermediates — and they are not outputs; the+ # root is. Both lists then go through the same merge-by-mtime and the same+ # post-build limit, so no kind gets a private cap.+ for p in OUTPUT.glob("*"):+ try:+ if p.suffix.lower() in image_exts and p.is_file():+ image_candidates.append((p, p.stat().st_mtime))+ except OSError:+ continueif image_root.exists():# Safety bound — still cap at a generous value so a misconfigured# library (someone pointing panel_uploads at /Users) can't stall# the request. 5000 is well above any realistic single-machine- # gallery while keeping the worst-case rglob bounded.- MAX_IMG = 5000+ # gallery while keeping the worst-case rglob bounded. Counted from+ # where the OUTPUT pass left off, so the library's own bound is the+ # same 5000 it always was.+ MAX_IMG = 5000 + len(image_candidates)try:for p in image_root.rglob("*"):if len(image_candidates) >= MAX_IMG:@@ -13338,9 +13601,23 @@ def _sb_board_summary(board: dict) -> dict:"title": board.get("title") or "","shots": len(shots),"done": sum(1 for s in shots if s.get("status") == "done"),+ # `done` counts shots THIS PANEL rendered as jobs. A board can hold+ # finished clips it never ran — imported with add-shot, restored from+ # an export, or written by hand — and those boards are exactly as+ # editable. Gating the editor on `done` hid the timeline on a film+ # whose clips were sitting right there. `clips` counts what is on+ # disk, which is the question the editor actually asks.+ "clips": sum(1 for s in shots+ if isinstance(s, dict)+ and (s.get("final_output") or s.get("draft_output"))+ and Path(str(s.get("final_output")+ or s.get("draft_output"))).is_file()),"failed": sum(1 for s in shots if s.get("status") == "failed"),"running": running,"planning": planning,+ # A board that has produced a film says so on its row. Cheap by+ # construction — see `_sb_film_summary`.+ "film": _sb_film_summary(board),}@@ -13403,6 +13680,99 @@ def storyboard_status() -> dict:}+def _sb_import_shots(board: dict, src: dict, only: set[int] | None = None) -> tuple[list, list]:+ """Bring rendered shots from `src` into `board`. Returns (imported, skipped).++ A BOARD IS A TIMELINE, ONE TO ONE, and that is the problem this solves. The+ moment coverage for a film is rendered as a second board — B-roll, pickups,+ alternates, a re-plan — its clips are unreachable from the first board's+ timeline. There was no way to move a clip between films and no way to cut+ with both, so "I have clips in two projects" had no answer but re-rendering.++ Clips are NOT copied on disk. A shot carries the path to its output, so an+ import is a reference: it costs a JSON edit and no render time.++ Mutates `board` in place; the caller saves.+ """+ have = {str(s.get("final_output") or s.get("draft_output") or "")+ for s in (board.get("shots") or [])}+ have.discard("")+ nxt = len(board.get("shots") or [])+ brought: list[dict] = []+ skipped: list[dict] = []+ for s in (src.get("shots") or []):+ if only and s.get("n") not in only:+ continue+ out = str(s.get("final_output") or s.get("draft_output") or "")+ if not out or not Path(out).is_file():+ skipped.append({"n": s.get("n"), "why": "not rendered yet"})+ continue+ if out in have:+ skipped.append({"n": s.get("n"), "why": "already here"})+ continue+ nxt += 1+ copy = dict(s)+ copy["n"] = nxt+ # Provenance stays ON the shot. Without it an imported clip is+ # indistinguishable from one this film planned, and a re-plan would+ # rewrite somebody else's shot.+ copy["imported_from"] = {"board": src.get("id") or "",+ "n": s.get("n"), "title": src.get("title") or ""}+ copy["status"] = "done"+ board.setdefault("shots", []).append(copy)+ have.add(out)+ brought.append({"n": nxt, "title": copy.get("title") or ""})++ # The source's locations and cast come too, or an imported shot points at a+ # location this board has never heard of — which the validator correctly+ # refuses to render, turning a successful import into an unrenderable film.+ known = {l.get("id") for l in (board.get("locations") or [])}+ for loc in (src.get("locations") or []):+ if loc.get("id") and loc["id"] not in known:+ board.setdefault("locations", []).append(loc)+ cast_ids = {c.get("id") for c in (board.get("cast") or [])}+ for row in (src.get("cast") or []):+ if row.get("id") and row["id"] not in cast_ids:+ board.setdefault("cast", []).append(row)+ return brought, skipped+++def _sb_parse_locations(text: str) -> list[dict]:+ """`name: description` per line -> the board's `locations`.++ Mirrors sbParseLocations in the client. Parsed AGAIN on the server because+ the client's version exists to render a live summary, not to be trusted —+ this is what actually reaches the board and gets injected into prompts.+ A line with no colon becomes its own description with a derived name rather+ than being dropped: silently discarding what somebody just typed is worse+ than an awkward name.+ """+ out: list[dict] = []+ seen: set[str] = set()+ for line in (text or "").splitlines():+ raw = line.strip()+ if not raw:+ continue+ name, _, desc = raw.partition(":")+ if not desc.strip():+ name, desc = re.split(r"[,.]", raw, 1)[0], raw+ name, desc = name.strip()[:60], desc.strip()[:storyboard.LOCATION_DESC_MAX]+ if not name or not desc:+ continue+ lid = re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")[:40]+ if not lid:+ lid = f"loc{len(out) + 1}"+ if not lid[0].isalnum():+ lid = "l" + lid+ base, i = lid, 2+ while lid in seen:+ lid = f"{base}{i}"+ i += 1+ seen.add(lid)+ out.append(storyboard.new_location(lid, name, desc))+ return out++def _sb_policy_for(draft_quality: str, final_quality: str) -> dict:"""The board's two passes, in the panel's own geometry vocabulary, clampedto what this Mac can actually render."""@@ -13546,6 +13916,7 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:# there is only one answer it could honestly give.engine=(brief.get("engine_mode") or "auto") if _sb_h3_available() else "ltx",board_id=board_id,+ locations=brief.get("locations") or None,known_character_ids=_sb_known_character_ids(),max_dim=_sb_max_dim(),session=session,@@ -13591,6 +13962,29 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:_prev_out[_s["n"]] = (_s.get("draft_output") or _s.get("final_output")or _s.get("stale_output"))board["shots"] = result.get("shots") or []+ # DIALOGUE MUST FIT THE SHOT. The validator rejects a line the clock+ # cannot carry (`dialogue_does_not_fit`), because it renders as a+ # sentence cut off mid-word. For planner output the fix is mechanical+ # and free — extend the shot to the smallest legal frame count that+ # fits the line — so it happens here, at adoption, rather than being+ # bounced back through a 40-second repair round-trip. Hand-authored+ # boards get no such mercy: there the author is present to decide+ # whether to cut words or add seconds.+ for _s in board["shots"]:+ if not isinstance(_s, dict):+ continue+ _spans = storyboard.spoken_spans(_s.get("prompt") or "")+ if not _spans:+ continue+ _words = sum(len(x.split()) for x in _spans)+ _need = storyboard.speech_fit_frames(+ _words, slow=storyboard.is_slow_read(_s.get("prompt") or ""))+ if int(_s.get("frames") or 0) < _need:+ _s["frames"] = _need+ _s["duration_s"] = round(_need / 24.0, 2)+ meta.setdefault("warnings", []).append(+ "shot %s: extended to %.1fs so its %d-word line is not cut off"+ % (_s.get("n"), _s["duration_s"], _words))# A rewritten shot must go back to being UN-RENDERED. Without this it# kept `status: "done"` with no output, and since shooting_order() and# estimate() both exclude "done" the film skipped it forever — the user@@ -13611,6 +14005,13 @@ def _sb_plan_thread(board_id: str, brief: dict, previous: dict | None) -> None:"draft_job_id", "final_job_id", "error"):_s.pop(_k, None)board["cast"] = result.get("cast") or board.get("cast") or []+ # THE GEOGRAPHY PASS'S VIEWS MUST REACH THE BOARD. Every planned shot+ # now names a view id; without this merge the ids point at nothing and+ # unknown_view — a HARD validator error — refuses the whole film.+ # merge_location_views is patch-never-overwrite: the user's typed+ # name/description win, a plan with no views leaves existing ones alone.+ board["locations"] = storyboard.merge_location_views(+ board.get("locations"), result.get("locations"))# The POLICY is the panel's, not the planner's: the user picked the two# passes in the film-level Quality control and a re-plan must not silently# reset them.@@ -13717,7 +14118,9 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:board_id=board_id, board_title=board.get("title") or "",h3_available=h3_ok,engine_mode=board.get("engine_mode") or "auto",- h3_chain_prompts=chain_ok)+ h3_chain_prompts=chain_ok,+ locations=storyboard.board_locations(board),+ wardrobe=storyboard.board_wardrobe(board))# make_job reads a form: every value is a string (or a list of# them). Normalise here so a bool/int never reaches f().job_form = {k: ("" if v is None else str(v)) for k, v in form.items()}@@ -13775,6 +14178,41 @@ def _sb_render_thread(board_id: str, pass_name: str, only: list | None) -> None:pass+def _sb_cancel_running_shot(job_ids) -> str | None:+ """Cancel the in-flight render IF it is one of this film's shots.++ Stop used to mean only "queue no more shots". Pressing it during a 20-minute+ H3 render therefore left that render holding the GPU and ~40 GiB for another+ 20 minutes, with the UI already saying the film had stopped — the button did+ not do the thing its label promises.++ The cancellation is the panel's ONE existing job-cancel path,+ `stop_current_job()` — the same call POST /stop makes. Nothing new is+ invented here, and that matters for the aftermath as much as the kill: it+ sets `cancel_requested` on the job, which is what makes the worker record+ the job as **cancelled** rather than **failed**, and `_sb_reconcile()`+ already knows how to fold a cancelled job back onto its shot. It also takes+ down the H3 / mux / training process groups the helper does not own.++ It fires ONLY when the running job is one of `job_ids`. Another film's shot,+ an Image Studio generation or a LoRA training run is not this film's to+ kill, and a blanket stop_current_job() here would have made Stop on a+ finished board silently abort somebody else's work.++ Returns the cancelled job id, or None when nothing of ours was running.+ """+ ids = set(job_ids or ())+ if not ids:+ return None+ with LOCK:+ cur = STATE.get("current") or {}+ jid = cur.get("id") if isinstance(cur, dict) else None+ if not jid or jid not in ids:+ return None+ stop_current_job()+ return str(jid)++def _sb_boot_reconcile() -> None:"""Boot hook — no planner survives a panel restart, so no board may claim one.@@ -13858,16 +14296,1513 @@ def _sb_slug(text: str, words: int = 5) -> str:return "-".join(parts[:words]) or "shot"-def _sb_export(board: dict) -> dict:- """A folder and a manifest. No editor, no timeline, no assembly UI.+def _sb_film_dir(board: dict) -> Path:+ """The ONE folder a board's finished films and shot copies land in.++ Three call sites computed this by hand — Export, `reveal`, and the+ timeline's render — which is three chances for a film to be written+ somewhere the screen that shows films does not look. One function, one+ convention: `<OUTPUT>/storyboards/<created-date>_<slug>/`.+ """+ title = board.get("title") or "storyboard"+ day = time.strftime("%Y-%m-%d",+ time.localtime(board.get("created_at") or time.time()))+ return OUTPUT / "storyboards" / f"{day}_{_sb_slug(title, 6)}"+++def _sb_display_path(p) -> str:+ """A path a human can read.++ Relative to the install when it is inside it (`mlx_outputs/storyboards/…`),+ else relative to the outputs root, else the absolute path. Never a lie: the+ fallback is the real path, however long.+ """+ # LEXICAL first, resolved second. `mlx_outputs` is a symlink into Pinokio's+ # drive store on a real install, so resolving both ends walks the path+ # clean out of the repo and the answer comes back absolute — for a+ # directory the user thinks of as `mlx_outputs/storyboards/…`.+ q = Path(p)+ forms = [q]+ bases = [ROOT, OUTPUT.parent]+ try:+ forms.append(q.resolve())+ bases += [Path(b).resolve() for b in (ROOT, OUTPUT.parent)]+ except OSError:+ pass+ for form in forms:+ for base in bases:+ try:+ return str(form.relative_to(base))+ except ValueError:+ continue+ return str(q)+++# Fallback audio rate for the assembled film when NOTHING in the cut carries a+# sound track (a film of silent character tests). 48 kHz is what the LTX+# vocoder writes; H3 writes 32 kHz, which is exactly why the assembler picks a+# single rate rather than assuming one.+_SB_FILM_SAMPLE_RATE = 48000+++def _sb_probe_clip(path) -> dict | None:+ """Geometry + audio facts for one clip, or None when ffprobe can't read it.- Clips are COPIED, never moved — the gallery keeps them.+ Returns {"w", "h", "duration", "has_audio", "sample_rate"}. `duration` is+ the VIDEO stream's duration, not the container's: an H3 clip's AAC track+ runs ~40 ms past its last frame, and a concat that believed the container+ would drift the sound later and later behind the picture across a 30-shot+ film. The video is the timeline; the audio gets padded/trimmed to it.++ None means "do not put this clip in the film" — same verdict a missing file+ gets. It never means "fail the export".+ """+ p = Path(str(path))+ try:+ out = subprocess.run(+ [str(FFPROBE), "-v", "error", "-show_entries",+ "stream=codec_type,width,height,sample_rate,duration:format=duration",+ "-of", "json", str(p)],+ capture_output=True, text=True, timeout=60,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ if out.returncode != 0:+ return None+ try:+ data = json.loads(out.stdout or "{}")+ except (ValueError, TypeError):+ return None+ if not isinstance(data, dict):+ return None++ def _num(raw) -> float:+ try:+ v = float(raw)+ except (TypeError, ValueError):+ return 0.0+ return v if v == v and v not in (float("inf"), float("-inf")) and v > 0 else 0.0++ w = h = 0+ v_dur = 0.0+ has_audio = False+ rate = 0+ for st in (data.get("streams") or []):+ if not isinstance(st, dict):+ continue+ kind = str(st.get("codec_type") or "")+ if kind == "video" and not w:+ try:+ w, h = int(st.get("width") or 0), int(st.get("height") or 0)+ except (TypeError, ValueError):+ w = h = 0+ v_dur = _num(st.get("duration"))+ elif kind == "audio":+ has_audio = True+ try:+ rate = max(rate, int(st.get("sample_rate") or 0))+ except (TypeError, ValueError):+ pass+ if w <= 0 or h <= 0:+ return None+ duration = v_dur or _num((data.get("format") or {}).get("duration"))+ if duration <= 0:+ return None+ return {"w": w, "h": h, "duration": round(duration, 6),+ "has_audio": has_audio, "sample_rate": rate}+++def _sb_probe_still(path) -> dict | None:+ """Geometry for a STILL, or None. Deliberately not `_sb_probe_clip`.++ That one refuses anything with no duration — correct for a shot, and it is+ exactly what an image is: a video stream of one frame with no clock.+ Returning the same `{"w","h",...}` shape means the target-geometry maths in+ `_sb_assemble_film` does not have to know which kind it is looking at.++ `has_audio` is always False and `duration` is always 0: a still's length is+ the slot the timeline gave it, never a property of the file.+ """+ p = Path(str(path))+ try:+ out = subprocess.run(+ [str(FFPROBE), "-v", "error", "-select_streams", "v:0",+ "-show_entries", "stream=width,height", "-of", "json", str(p)],+ capture_output=True, text=True, timeout=60)+ except (OSError, subprocess.SubprocessError):+ return None+ if out.returncode != 0:+ return None+ try:+ data = json.loads(out.stdout or "{}")+ st = (data.get("streams") or [{}])[0]+ w, h = int(st.get("width") or 0), int(st.get("height") or 0)+ except (ValueError, TypeError, IndexError, AttributeError):+ return None+ if w <= 0 or h <= 0:+ return None+ return {"w": w, "h": h, "duration": 0.0, "has_audio": False,+ "sample_rate": 0}+++# ---------------------------------------------------------------------------+# AN OVERLAY THAT ARRIVES ON A BLACK PLATE+# ---------------------------------------------------------------------------+# "If the picture comes in a format that doesn't work, automatically make it+# work."+#+# THE CASE. A card generated elsewhere HAS an alpha channel, so every tool that+# looks at the header calls it transparent — but the artwork sits on an opaque+# black backdrop and only the outer margins are clear. On the file that produced+# the report the alpha over the neon burst is a SOLID DISC: the black between+# the rays is declared fully opaque, so the overlay lane composited black over+# the sky. Correctly. It read as "transparency not working", and it is not: the+# file is telling the truth about an alpha channel that is wrong.+#+# WHY IT IS SAFE TO REBUILD THE ALPHA FROM THE PICTURE'S OWN LIGHT. Art drawn on+# black is ADDITIVE — brightness IS coverage, and where the picture is black it+# is contributing nothing. So `alpha' = alpha * max(R,G,B)/255` with the colour+# divided back out reproduces the ORIGINAL EXACTLY over black (a'·C' = a·m/255 ·+# C·255/m = a·C) and shows the background everywhere the backdrop was. That+# identity is the reason this transform is defensible rather than a guess, and+# `test_storyboard_editor_api` pins it.+#+# WHAT IS NOT BUILT: an edge-flood key for a flat NON-black plate. The identity+# above only holds over black, so a white or grey plate would need a tolerance+# nobody can pick for the user and a hard-edged matte with no soft edge left. A+# non-black plate is therefore left alone rather than guessed at — the picture+# lane still shows it, and the notice never lies about what was done.+#+# EVERY THRESHOLD BELOW IS A MEASUREMENT. Fixtures, measured 2026-08-20:+#+# file clear opaque dark hot flat ink+# the reported ChatGPT endcard 43.3% 41.2% 9.5% 27.2% 0.25 53.1% KEY+# ...the same card at 1/1.5 43.3% 41.2% 9.6% 26.8% 0.34 52.9% KEY+# ...the same card at 1/2.5 43.3% 41.2% 9.6% 26.0% 0.49 52.9% KEY+# the same card once keyed 46.2% 11.6% 0.0% 97.0% - 69.9% leave+# endcard_..._overlay_A (real alpha) 75.9% 2.2% 0.0% 54.7% - 72.1% leave+# endcard_..._overlay_B (real alpha) 84.4% 2.2% 90.9% 0.0% 0.00 43.5% leave+# endcard_..._overlay_C (real alpha) 82.8% 2.2% 0.0% 100% - 74.0% leave+# an opaque RGBA render 0.0% 100% 52.0% 0.5% 0.63 19.5% leave+# 88 photographs matted into overlays — every render in `mlx_outputs`, cut+# with an ellipse, each also at a quarter brightness — ZERO keyed.+#+# The two clauses that do the work, and why neither alone is enough:+#+# `flat` separates a synthetic backdrop from a photograph's shadows — the mean+# distance from a 3x3 box mean, measured on the dark pixels whose whole+# neighbourhood is also dark, so the ink's own crisp border is not counted as+# "texture". The reported card reads 0.25; a matted photograph reads 0.3-1.5,+# and the two populations OVERLAP: four of the 88 come in under 0.35.+#+# `hot` is what closes that gap. Additive artwork has a saturated ceiling as+# well as a black floor — neon, a logo and rendered type all clip at 255, while+# a photograph's highlights roll off. The reported card is 27.2% saturated and+# stays above 26% at every scale down to 1/2.5; the highest of the 88 controls+# reaches 10.2%. That is the only measurement in this report that separates the+# two populations cleanly, with 1.5x of daylight on both sides.+#+# `ink` is the safety net that does not care which population a file is in: if+# keying would erase the design instead of freeing it — black artwork on+# transparency, a dark cut-out — it is refused whatever else says.+SBE_PLATE_SUFFIX = ".keyed.png"+SBE_PLATE_CLEAR_A = 8 # alpha at or below this reads as "clear"+SBE_PLATE_OPAQUE_A = 248 # alpha at or above this reads as "opaque"+SBE_PLATE_DARK_M = 32 # max(R,G,B) at or below this reads as "black"+SBE_PLATE_HOT_M = 240 # ...and at or above this reads as "saturated"+SBE_PLATE_CLEAR_MIN = 0.15 # the file must CLAIM transparency, and mean it+SBE_PLATE_OPAQUE_MIN = 0.15 # ...and still declare a large solid body+SBE_PLATE_DARK_SHARE_MIN = 0.05 # ...part of which is black+SBE_PLATE_DARK_IMAGE_MIN = 0.02 # ...and not just a handful of pixels+SBE_PLATE_HOT_SHARE_MIN = 0.15 # ...with saturated ink on it, not a photograph+SBE_PLATE_FLAT_MAX = 0.60 # ...and black that is a backdrop, not shadow+SBE_PLATE_INK_MIN = 0.30 # ...and keying must leave a card, not a hole+SBE_PLATE_MAX_PIXELS = 40_000_000+++def _sbe_plate_report(path) -> dict:+ """Measure an overlay candidate. Reads one file and writes nothing.++ Returns `{"ok", "plate", "why", ...numbers}`. `plate` is True only when+ every threshold above is met; `why` names the FIRST clause that refused, so+ a false negative can be diagnosed from the response instead of from a+ rebuild.+ """+ try:+ from PIL import Image, ImageFilter+ import numpy as np+ except Exception as exc: # noqa: BLE001+ return {"ok": False, "plate": False, "why": f"no image library: {exc}"}+ p = Path(str(path))+ if p.name.lower().endswith(SBE_PLATE_SUFFIX):+ # OUR OWN DERIVATIVE. The measurement below already refuses it (keying+ # leaves no black under an opaque alpha), but a name check costs+ # nothing and makes the idempotence obvious to a reader.+ return {"ok": True, "plate": False, "why": "already keyed"}+ try:+ with Image.open(p) as im:+ if im.width * im.height > SBE_PLATE_MAX_PIXELS:+ return {"ok": True, "plate": False, "why": "too large to measure"}+ if "A" not in im.getbands() and "transparency" not in im.info:+ # A FILE THAT NEVER CLAIMED TRANSPARENCY IS NOT LYING ABOUT IT.+ # This is the clause that makes a photograph — jpg, or an+ # opaque png — unreachable by any of the maths below.+ return {"ok": True, "plate": False, "why": "no alpha channel"}+ rgba = im.convert("RGBA")+ arr = np.asarray(rgba, dtype=np.float32)+ # RGBA -> RGB in Pillow DISCARDS alpha, it does not composite, so this+ # is the picture's own colour and not the picture over black.+ blur = np.asarray(rgba.convert("RGB").filter(ImageFilter.BoxBlur(1)),+ dtype=np.float32)+ except (OSError, ValueError) as exc:+ return {"ok": False, "plate": False, "why": str(exc)}+ if arr.ndim != 3 or arr.shape[2] != 4 or arr.size == 0:+ return {"ok": False, "plate": False, "why": "unreadable pixels"}+ a = arr[..., 3]+ rgb = arr[..., :3]+ m = rgb.max(axis=2)+ opaque = a >= SBE_PLATE_OPAQUE_A+ dark = opaque & (m <= SBE_PLATE_DARK_M)+ n_op = float(opaque.sum())+ n_dark = float(dark.sum())+ a_sum = float(a.sum())+ # THE BACKDROP'S INTERIOR, NOT ITS EDGES. Flatness is measured on the dark+ # pixels whose whole 3x3 neighbourhood is also dark — the ink's own border+ # is a step of 200-odd levels and would read as "texture" in every drawing+ # ever made, which said far more about the artwork being crisp than about+ # where it came from. Eroding the mask first asks the only question worth+ # asking: is the BACKDROP itself smooth?+ core = np.asarray(+ Image.fromarray((dark * 255).astype(np.uint8)).filter(+ ImageFilter.MinFilter(3)), dtype=np.float32) > 127+ n_core = float(core.sum())+ rep = {+ "ok": True,+ "plate": False,+ "why": "",+ "clear_share": round(float((a <= SBE_PLATE_CLEAR_A).mean()), 5),+ "opaque_share": round(float(opaque.mean()), 5),+ "dark_share": round((n_dark / n_op) if n_op else 0.0, 5),+ "dark_of_image": round(n_dark / float(a.size), 5),+ # THE OTHER END OF THE HISTOGRAM, and it is the clause that tells a+ # design from a photograph. Additive artwork has a saturated ceiling as+ # well as a black floor — neon, a logo, rendered type all clip at 255 —+ # while a photograph's highlights roll off. Measured over 88 controls+ # (every render in `mlx_outputs`, matted into an overlay, each also at+ # a quarter brightness): the reported card is 27.2% saturated and holds+ # 25.5-27.2% at every scale from 1/3 to 1x, and the highest any of the+ # 88 reaches is 10.2%. Nothing else in this report separates those two+ # populations; this does, with 1.5x of daylight on both sides.+ "hot_share": round(float((m[opaque] >= SBE_PLATE_HOT_M).mean())+ if n_op else 0.0, 5),+ "flat": (round(float(np.abs(rgb[core] - blur[core]).mean()), 4)+ if n_core >= 64 else None),+ "ink_kept": round((float((a * (m / 255.0)).sum()) / a_sum)+ if a_sum else 0.0, 5),+ }+ for why, ok in (+ ("the alpha channel is barely used", rep["clear_share"] >= SBE_PLATE_CLEAR_MIN),+ ("nothing large is declared opaque", rep["opaque_share"] >= SBE_PLATE_OPAQUE_MIN),+ ("the opaque part is not black", rep["dark_share"] >= SBE_PLATE_DARK_SHARE_MIN),+ ("too little of it to be a backdrop", rep["dark_of_image"] >= SBE_PLATE_DARK_IMAGE_MIN),+ ("it reads as a photograph, not as artwork on black",+ rep["hot_share"] >= SBE_PLATE_HOT_SHARE_MIN),+ ("the black has photographic detail in it",+ rep["flat"] is not None and rep["flat"] <= SBE_PLATE_FLAT_MAX),+ ("keying it would erase the picture", rep["ink_kept"] >= SBE_PLATE_INK_MIN)):+ if not ok:+ rep["why"] = why+ return rep+ rep["plate"] = True+ return rep+++def _sbe_key_plate(path) -> dict:+ """Write the keyed DERIVATIVE next to the original. Never edits the source.++ `alpha' = alpha * max(R,G,B)/255` and `colour' = colour / (max(R,G,B)/255)`,+ which is the straight-alpha spelling of "this was composited over black".+ Both the browser's `<img>`, ffmpeg's `overlay` filter and every NLE on the+ far side read straight alpha, so ONE file is what preview, render and export+ all receive — the parity is by construction, not by three code paths+ agreeing.+ """+ try:+ from PIL import Image+ import numpy as np+ except Exception as exc: # noqa: BLE001+ return {"ok": False, "error": f"no image library: {exc}"}+ p = Path(str(path))+ dest = p.with_name(p.stem + SBE_PLATE_SUFFIX)+ try:+ if dest.is_file() and dest.stat().st_mtime >= p.stat().st_mtime:+ # Already built for this exact source. Placing the same card twice+ # should cost nothing and must not produce a second file.+ return {"ok": True, "path": str(dest), "reused": True}+ except OSError:+ pass+ try:+ with Image.open(p) as im:+ arr = np.asarray(im.convert("RGBA"), dtype=np.float32)+ a = arr[..., 3]+ rgb = arr[..., :3]+ cover = rgb.max(axis=2) / 255.0+ lit = cover > 0.0+ # Unpremultiply only where there is light. Where there is none the+ # pixel is fully transparent, so its colour cannot be observed and+ # dividing by zero would be inventing one.+ out = np.zeros_like(arr)+ scale = np.where(lit, 1.0 / np.where(lit, cover, 1.0), 0.0)+ out[..., :3] = np.clip(rgb * scale[..., None], 0.0, 255.0)+ out[..., 3] = a * cover+ img = Image.fromarray(np.rint(out).astype(np.uint8), "RGBA")+ tmp = dest.with_name(dest.name + ".part")+ img.save(tmp, "PNG")+ os.replace(tmp, dest)+ except (OSError, ValueError) as exc:+ return {"ok": False, "error": str(exc)}+ return {"ok": True, "path": str(dest), "reused": False}+++def _sb_probe_audio_rate(path) -> int:+ """Sample rate of a soundtrack, or 0. Separate from `_sb_probe_clip`+ because that one answers None for a file with no VIDEO stream — correct+ for a shot, useless for an mp3."""+ try:+ out = subprocess.run(+ [str(FFPROBE), "-v", "error", "-select_streams", "a:0",+ "-show_entries", "stream=sample_rate", "-of",+ "default=nw=1:nk=1", str(path)],+ capture_output=True, text=True, timeout=60)+ except (OSError, subprocess.SubprocessError):+ return 0+ try:+ return int((out.stdout or "0").strip().splitlines()[0])+ except (ValueError, IndexError):+ return 0+++def _sb_cut_index(plan) -> dict:+ """{resolved path: [{start, end}, ...]} from a cut plan, or {}.++ Keyed by path rather than by position because `_sb_assemble_film` DROPS+ clips ffprobe cannot read, and a positional plan would then apply shot 4's+ window to shot 5 — silently, and only in the presence of a broken file.++ The value is a LIST, in plan order, because one source can legitimately+ appear in the cut more than once: the timeline editor's whole reason for+ existing is that a shot can be used twice or split in half, and a+ path->one-window map collapsed both occurrences onto the last window+ silently. Callers consume the list in order (`_sb_segment_windows`); a+ single dict is still accepted there, so a hand-built `cuts` from before+ this change behaves exactly as it did.+ """+ if not plan:+ return {}+ out: dict[str, list] = {}+ for entry in plan:+ if not isinstance(entry, dict) or not entry.get("path"):+ continue+ try:+ start = float(entry.get("start") or 0.0)+ end = float(entry.get("end") or 0.0)+ except (TypeError, ValueError):+ continue+ if end <= start:+ continue+ # WIDENED (Wave 2). This copy used to be `{"start", "end"}` and threw+ # everything else away, which made it the reason a per-clip treatment+ # could not exist: the list is already per-OCCURRENCE, so the same+ # source used twice can carry two different grades — the index just+ # never carried anything to differ about. Extra keys are added ONLY+ # when the entry says something, so a plan of plain trims produces the+ # identical index it always did and the graph below is unchanged.+ win = {"start": start, "end": end}+ kind = str(entry.get("kind") or "video")+ if kind != "video":+ win["kind"] = kind+ adjust = entry.get("adjust")+ if isinstance(adjust, dict) and adjust:+ win["adjust"] = dict(adjust)+ if entry.get("mute") is True:+ win["mute"] = True+ if isinstance(entry.get("fx"), dict) and entry["fx"]:+ win["fx"] = dict(entry["fx"])+ out.setdefault(str(Path(str(entry["path"]))), []).append(win)+ return out+++def _sb_segment_windows(probes: list[tuple], cuts: dict | None) -> list:+ """The window each INPUT plays, or None for "play the whole clip".++ One pass, consumed in order per path, so the second appearance of a source+ gets the second window planned for it. A path with no entry — or one whose+ windows are already spent — plays whole, which is the documented behaviour+ of a partial plan and the reason a missing entry can never trim a shot to+ zero.+ """+ queues: dict[str, list] = {}+ for key, val in (cuts or {}).items():+ queues[key] = [val] if isinstance(val, dict) else list(val or [])+ out: list = []+ for clip, _info in probes:+ q = queues.get(str(Path(str(clip))))+ out.append(q.pop(0) if q else None)+ return out+++def _sb_volume_term(curve) -> str:+ """A `volume` envelope from `[[t, gain], ...]`, or "" for a flat one.++ THE EMPTY STRING IS THE POINT, the third time: a sound with no envelope+ adds no filter, so every film ever exported builds the identical audio+ graph. The curve comes from `audio_gain_points`, which has already folded+ the fades and the keyframes into ONE breakpoint list — so a fade and a+ keyframed dip cannot disagree here about what the sound does.++ `eval=frame` because the expression is a function of `t`; without it+ ffmpeg evaluates once at init and the envelope becomes a constant. The+ expression is piecewise-linear between breakpoints, which is exactly what+ the level line on the strip draws and what the NLE keyframes describe.+ """+ pts = [(float(t), float(g)) for t, g in (curve or [])]+ if len(pts) < 2:+ return ""+ expr = f"{pts[-1][1]:.6f}"+ for (t0, g0), (t1, g1) in reversed(list(zip(pts, pts[1:]))):+ if t1 - t0 <= 1e-9:+ continue+ seg = (f"{g0:.6f}+({g1 - g0:.6f})*(t-{t0:.6f})/{t1 - t0:.6f}")+ expr = f"if(lt(t,{t1:.6f}),{seg},{expr})"+ return f"volume=volume='{expr}':eval=frame,"+++def _sb_fade_term(fx, seconds: float, *, alpha: bool = False) -> str:+ """`fade=t=in…,fade=t=out…,` for a clip with fades, or "" for the rest.++ THE EMPTY STRING IS THE POINT, the same rule `_sb_brightness_term` follows:+ a clip with no fade adds no filter at all, so every film ever exported+ builds the identical graph and the byte-for-byte default the assembly+ suite pins is untouched.++ ON THE SEGMENT'S OWN TIMELINE. The fade runs after `trim`+`setpts`, so+ `st=0` is this clip's first frame whatever window it plays — fades compose+ with trims without either knowing about the other. This is a fade to BLACK+ on the picture lane, which is what a fade means on a bottom track; the+ overlay lane will want `alpha=1`, and that is a different lane's decision.++ `clip_effects` has already clamped the pair so they cannot cross.+ """+ if not isinstance(fx, dict):+ return ""+ try:+ fin = float(fx.get("fade_in") or 0.0)+ fout = float(fx.get("fade_out") or 0.0)+ except (TypeError, ValueError):+ return ""+ # `alpha=1` RAMPS THE ALPHA CHANNEL instead of mixing toward black. On the+ # picture lane a fade IS to black — it is the bottom track. On the OVERLAY+ # lane fading to black would paint a black card over the picture, which is+ # the exact failure the whole feature is about; there, the ramp has to be+ # transparency.+ a = ":alpha=1" if alpha else ""+ out = ""+ if fin == fin and fin > 1e-9:+ out += f"fade=t=in:st=0:d={fin:.6f}{a},"+ if fout == fout and fout > 1e-9 and seconds > 0:+ st = max(0.0, seconds - fout)+ out += f"fade=t=out:st={st:.6f}:d={fout:.6f}{a},"+ return out+++def _sb_brightness_term(adjust) -> str:+ """`eq=brightness=X,` for a graded segment, or "" for every other one.++ THE EMPTY STRING IS THE POINT. A neutral clip must add no filter at all —+ not `eq=brightness=0.000000`, which would change the graph of every film+ ever exported to express nothing, and would break the byte-for-byte+ default the assembly suite pins.++ ffmpeg's `eq=brightness` is an ADDITIVE offset in [-1, 1]. The client+ previews it with CSS `filter: brightness()`, which is MULTIPLICATIVE, so+ the two agree at mid-grey and drift at the ends — the preview says so, and+ the render is the one that is exact.+ """+ if not isinstance(adjust, dict):+ return ""+ try:+ b = float(adjust.get("brightness") or 0.0)+ except (TypeError, ValueError):+ return ""+ if b != b or b in (float("inf"), float("-inf")) or abs(b) < 1e-9:+ return ""+ b = max(-0.5, min(0.5, b))+ return f"eq=brightness={b:.6f},"+++def _sb_film_segments(probes: list[tuple], cuts: dict | None) -> list[dict]:+ """The legacy `probes` list, expressed as segments.++ ONE INPUT PER PROBE, IN ORDER — which is the assumption the whole module+ made implicitly until stills and slugs arrived and segment index stopped+ being input index. Keeping the derivation here means the old positional+ path produces a segment list that is indistinguishable from the one it+ used to build inline, and the graph below has exactly one shape to render.+ """+ windows = _sb_segment_windows(probes, cuts)+ out: list[dict] = []+ for idx, (_clip, info) in enumerate(probes):+ win = windows[idx]+ out.append({"kind": "video", "input": idx, "info": info,+ "window": ({"start": win["start"], "end": win["end"]}+ if win else None),+ "adjust": (win or {}).get("adjust")})+ return out+++def _sb_seg_seconds(sg: dict) -> float:+ """How long ONE segment plays. The same arithmetic the graph loop does,+ factored out because the split-audio plan has to know it BEFORE the loop+ emits anything — where each segment lands in the concatenated film is what+ a decoupled sound is offset from."""+ kind = str(sg.get("kind") or "video")+ if kind in ("slug", "still"):+ return max(0.0, float(sg.get("duration") or 0.0))+ info = sg.get("info") or {}+ cut = sg.get("window")+ if cut:+ return min(max(0.0, float(cut["end"]) - float(cut["start"])),+ float(info["duration"]))+ return float(info["duration"])+++def _sb_split_audio_plan(segs: list[dict]) -> dict:+ """Where every clip's SOUND plays in the concatenated film.++ Returns {"split": bool, "total": float, "lanes": [{idx, start, end, at,+ len}]}. `split` is False when nothing is unlinked, and that is what keeps+ the ordinary graph byte-identical: the whole decoupled path is skipped.++ ONE LANE, ENFORCED HERE TOO. The validator refuses overlapping sound in+ the EDITOR's clock, but the assembler closes gaps, so two clips can slide+ into each other on the way out. Rather than emit a graph that would need a+ mixer, a later lane's head is trimmed to the one before it — deterministic,+ and the only alternative is the second audio track this feature is+ explicitly not.+ """+ cum, rows, split = 0.0, [], False+ for i, sg in enumerate(segs):+ n = _sb_seg_seconds(sg)+ kind = str(sg.get("kind") or "video")+ has_audio = bool((sg.get("info") or {}).get("has_audio")) and kind == "video"+ # MUTE IS THE ABSENCE OF A LANE. This graph lays sound and silence end+ # to end with `concat`, so "do not play this clip" is expressed by+ # contributing no row and letting the hush fill the slot — no volume+ # filter, no mixer, and nothing that could sum. It also FORCES the+ # split path: without it a film whose only decoupling was a mute would+ # take the plain `concat ... a=1` branch and play the audio the user+ # had just switched off.+ if has_audio and sg.get("mute"):+ split = True+ has_audio = False+ aud = sg.get("audio") if isinstance(sg.get("audio"), dict) else None+ if has_audio:+ if aud:+ split = True+ rows.append({"idx": i, "start": float(aud["start"]),+ "end": float(aud["end"]),+ "at": cum + float(aud.get("delta") or 0.0)})+ else:+ cut = sg.get("window")+ st = float(cut["start"]) if cut else 0.0+ rows.append({"idx": i, "start": st, "end": st + n, "at": cum})+ cum += n+ total = round(cum, 6)+ rows.sort(key=lambda r: r["at"])+ lanes = []+ for r in rows:+ at, st, en = r["at"], r["start"], r["end"]+ if at < 0:+ # A J-cut on the FIRST clip has nothing to lead from, so the head+ # is CUT rather than shifted — shifting would slide the whole+ # performance late against a picture that did not move.+ st += -at+ at = 0.0+ if en - st <= 1e-6 or at >= total - 1e-6:+ continue+ if at + (en - st) > total: # an L-cut past the last frame is cut+ en = st + (total - at)+ lanes.append({"idx": r["idx"], "start": st, "end": en, "at": at})+ # THE INCOMING SOUND WINS ITS OWN START, and that IS the J-cut: the+ # OUTGOING clip's tail is what gives way. Trimming the incoming head+ # instead would put its first syllable back where the picture cuts, which+ # is the edit the user was trying to get away from.+ for a, b in zip(lanes, lanes[1:]):+ room = b["at"] - a["at"]+ if a["end"] - a["start"] > room + 1e-9:+ a["end"] = a["start"] + max(0.0, room)+ out = []+ for L in lanes:+ n = L["end"] - L["start"]+ if n <= 1e-6:+ continue # entirely covered by its neighbour+ out.append({"idx": L["idx"], "start": round(L["start"], 6),+ "end": round(L["end"], 6), "at": round(L["at"], 6),+ "len": round(n, 6)})+ return {"split": split, "total": total, "lanes": out}+++def _sb_split_audio_chains(lanes: list[dict], total: float, rate: int,+ out_label: str) -> list[str]:+ """The film's ONE audio lane, as silence and sound laid end to end.++ `concat` and not `amix`, deliberately: concat cannot sum, so this graph is+ incapable of becoming the mixer the refuse list bans, and the gaps between+ split edits are honest `anullsrc` rather than an input that happens to be+ quiet.+ """+ chains, parts, cursor, n = [], [], 0.0, 0++ def hush(seconds: float) -> None:+ nonlocal n+ lab = f"aq{n}"+ n += 1+ chains.append(f"anullsrc=channel_layout=stereo:sample_rate={rate}:"+ f"d={seconds:.6f}[{lab}]")+ parts.append(f"[{lab}]")++ for lane in lanes:+ if lane["at"] - cursor > 1e-6:+ hush(lane["at"] - cursor)+ parts.append(f"[a{lane['idx']}]")+ cursor = lane["at"] + lane["len"]+ if total - cursor > 1e-6:+ hush(total - cursor)+ if not parts:+ hush(max(total, 1e-3))+ chains.append(f"{''.join(parts)}concat=n={len(parts)}:v=0:a=1{out_label}")+ return chains+++def _sb_music_head(music: dict | None, n_inputs: int) -> str:+ """The soundtrack's own trim/place chain, up to (not including) resample.++ ONE PLACE, TWO CALLERS. `replace` and `under` both open with the same three+ decisions about the track — where it starts, where it stops, and how far+ into the film it drops in — and they had drifted into two copies of one+ line that only differed by what came after it.++ `start` is where playback begins IN THE TRACK, `end` where it stops (None+ plays to the end), and `delay` the film second the music lands on. The+ string is CHARACTER-FOR-CHARACTER what it was before trims existed when+ `end` is None and `delay` is 0, which is every timeline written before+ today and every one where the music still starts with the film.++ `adelay` and NOT a longer `atrim`: silence in front of a track is not a+ property of the track, and asking atrim for negative time is asking for+ nothing at all. `all=1` because the delay must apply to both channels and+ the default applies it to the first one only — a music bed that arrives in+ the left speaker is the failure mode this argument exists for.+ """+ m = music or {}+ start = max(0.0, float(m.get("start") or 0.0))+ end = m.get("end")+ delay = max(0.0, float(m.get("delay") or 0.0))+ trim = f"atrim=start={start:.6f}"+ if end is not None and float(end) > start:+ trim += f":end={float(end):.6f}"+ head = f"[{n_inputs}:a]{trim},asetpts=PTS-STARTPTS,"+ if delay > 1e-6:+ head += f"adelay=delays={int(round(delay * 1000))}:all=1,"+ return head+++def _sb_film_filtergraph(probes: list[tuple], target_w: int, target_h: int,+ rate: int, pix_fmt: str,+ cuts: dict | None = None,+ music: dict | None = None,+ overlays: list | None = None,+ overlay_base: int = 0,+ segments: list[dict] | None = None) -> tuple[str, str]:+ """The concat FILTER graph for a mixed-geometry cut → (graph, video_label).++ A bare concat DEMUXER cannot do this job. The shots in one film are not+ uniform and never were: the draft pass writes 640×448, delivery writes+ 1024×576, H3's own export lands 768×448 or 1280×720, LTX carries 48 kHz+ audio and H3 carries 32 kHz, and a character test may carry none at all.+ The demuxer requires identical streams and answers a mismatch with either a+ hard failure or — worse — a file that plays the first shot and then garbles.++ So every segment is normalised into one geometry first:+ * `fps` → one frame rate for the whole film;+ * `scale=…:force_original_aspect_ratio=decrease` + `pad` → the picture+ fits inside the target with bars, never cropped and never stretched;+ * `setsar=1` → square pixels, so a 4:3-flagged source can't skew the cut;+ * `format=<the requested pix_fmt>` → concat negotiates ONE pixel format+ across its inputs, and this makes that format the one the encode was+ going to write anyway.+ and every segment is guaranteed an audio stream: a real track is resampled+ to the film's rate and padded/trimmed to the picture's length, and a SILENT+ clip gets `anullsrc` of exactly that length. Without that, the graph has an+ uneven stream count and ffmpeg refuses to build it at all.++ `cuts` (from `storyboard_edit.plan_cut`, keyed by path) turns each segment+ into the WINDOW of the clip the auto-editor chose, with `trim`/`atrim` in+ THIS graph — the same single pass, the same single encode. Trimming in a+ separate ffmpeg run would mean decoding and re-encoding every shot twice,+ which costs both time and a generation of quality for nothing.++ `music` carries a soundtrack, and `music["mode"]` decides what happens to+ the sound the clips already have:++ * `replace` (default) — the segments carry picture only, concat is asked+ for video alone, and the audio output is the music trimmed to the+ film's length. This is what a beat-aligned cut needs: the cuts were+ planned against THIS track's grid, so the track has to be what plays.++ * `under` — the clips keep their audio and the music plays beneath it.+ Needed the moment a film has anyone speaking in it: `replace` on a+ dialogue cut silences the performance, which is not "adding a+ soundtrack", it is deleting the acting.++ `music["gain"]` is the BED'S CURVE, from `bed_render_gain` — the fader,+ the authored envelope and the auto-duck already resolved into one+ breakpoint list on the film's clock. Absent means unity means no filter.+ Every gain this graph applies to the bed comes from there and from nowhere+ else, which is the property that makes the preview able to play the same+ mix; the only term left outside the document is the limiter on the sum.++ With neither argument the graph is character-for-character what it was+ before either existed. That is the point: the auto-edit is opt-in, and the+ default path cannot change behaviour by accident.+ """+ chains: list[str] = []+ pads: list[str] = []+ segs = segments if segments is not None else _sb_film_segments(probes, cuts)+ # THE MUSIC IS THE LAST INPUT, AND `-i` COUNT IS NO LONGER SEGMENT COUNT.+ # A slug consumes no input at all (it is a `color=` source inside the+ # graph), so `len(probes)` stopped being the soundtrack's index the moment+ # black became first-class. Counting the segments that actually carry an+ # input is the only thing that stays true for every mix of kinds.+ n_inputs = sum(1 for s in segs if s.get("input") is not None)+ # THE SPLIT PLAN IS COMPUTED FIRST, because a decoupled sound's place in+ # the film depends on where its clip lands in the concatenation, and the+ # loop below only learns that as it goes. `split` False leaves every line+ # after this exactly as it was.+ aplan = _sb_split_audio_plan(segs)+ alane = {L["idx"]: L for L in aplan["lanes"]}+ split = bool(aplan["split"])+ music_mode = str((music or {}).get("mode") or "replace").lower()+ if music_mode not in ("replace", "under"):+ music_mode = "replace"+ # Only `replace` throws the clips' own audio away. `under` needs it — it is+ # the thing the bed is ducking against.+ silent_segments = bool(music) and music_mode == "replace"+ total = 0.0+ for idx, sg in enumerate(segs):+ kind = str(sg.get("kind") or "video")+ info = sg.get("info") or {}+ inp = sg.get("input")+ cut = sg.get("window")+ bright = _sb_brightness_term(sg.get("adjust"))+ fx = sg.get("fx")+ has_audio = bool(info.get("has_audio")) and kind == "video"+ if kind == "slug":+ # NO FILE, NO INPUT, NO PROBE. `color` is a source filter, so the+ # cheapest of the three kinds is also the one that needed the+ # refactor: it is a chain in the graph and nothing else.+ seg = max(0.0, float(sg.get("duration") or 0.0))+ dur = f"{seg:.6f}"+ total += seg+ chains.append(+ f"color=c=black:s={target_w}x{target_h}:r={FPS}:d={dur},"+ f"setsar=1,{bright}{_sb_fade_term(fx, seg)}format={pix_fmt}[v{idx}]")+ elif kind == "still":+ # The picture arrives already looped to length by `-loop 1 -t D`+ # on the input; the trim here pins it to the exact slot so the+ # video and the synthesised silence below cannot disagree by a+ # frame, which is all concat needs to go wrong.+ seg = max(0.0, float(sg.get("duration") or 0.0))+ dur = f"{seg:.6f}"+ total += seg+ chains.append(+ f"[{inp}:v]trim=0:{dur},setpts=PTS-STARTPTS,fps={FPS},"+ f"scale={target_w}:{target_h}:force_original_aspect_ratio=decrease,"+ f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2,"+ f"setsar=1,{bright}{_sb_fade_term(fx, seg)}format={pix_fmt}[v{idx}]")+ else:+ if cut:+ seg = max(0.0, float(cut["end"]) - float(cut["start"]))+ seg = min(seg, float(info["duration"]))+ head = (f"[{inp}:v]trim=start={float(cut['start']):.6f}:"+ f"end={float(cut['end']):.6f},setpts=PTS-STARTPTS,")+ ahead = (f"[{inp}:a]atrim=start={float(cut['start']):.6f}:"+ f"end={float(cut['end']):.6f},asetpts=PTS-STARTPTS,")+ else:+ seg = float(info["duration"])+ head = f"[{inp}:v]"+ ahead = f"[{inp}:a]"+ total += seg+ dur = f"{seg:.6f}"+ chains.append(+ f"{head}fps={FPS},"+ f"scale={target_w}:{target_h}:force_original_aspect_ratio=decrease,"+ f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2,"+ f"setsar=1,{bright}{_sb_fade_term(fx, seg)}format={pix_fmt}[v{idx}]")+ if silent_segments:+ pads.append(f"[v{idx}]")+ continue+ if has_audio and split:+ # THE SOUND HAS ITS OWN WINDOW NOW. Same input, same filters, a+ # different pair of numbers — and it is padded to the length of+ # the SOUND, not of the picture, because the two stopped being the+ # same fact the moment they were unlinked.+ L = alane.get(idx)+ if L:+ # NO ENVELOPE, NO FILTER — and no trailing `anull` either. A+ # sound nobody shaped must build the identical chain it always+ # did, or every film ever exported changes to express nothing.+ vol = _sb_volume_term(sg.get("gain"))+ vtail = ("," + vol.rstrip(",")) if vol else ""+ chains.append(+ f"[{inp}:a]atrim=start={L['start']:.6f}:end={L['end']:.6f},"+ f"asetpts=PTS-STARTPTS,aresample={rate},"+ f"aformat=sample_fmts=fltp:channel_layouts=stereo,"+ f"apad,atrim=0:{L['len']:.6f},asetpts=PTS-STARTPTS"+ f"{vtail}[a{idx}]")+ pads.append(f"[v{idx}]")+ continue+ if split:+ pads.append(f"[v{idx}]")+ continue+ if has_audio:+ vol = _sb_volume_term(sg.get("gain"))+ vtail = ("," + vol.rstrip(",")) if vol else ""+ chains.append(+ f"{ahead}aresample={rate},"+ f"aformat=sample_fmts=fltp:channel_layouts=stereo,"+ f"apad,atrim=0:{dur},asetpts=PTS-STARTPTS"+ f"{vtail}[a{idx}]")+ else:+ # A still and a slug are silent by construction; a silent clip is+ # silent by accident. All three need the same synthesised track or+ # concat has an uneven stream count and refuses to build at all.+ chains.append(+ f"anullsrc=channel_layout=stereo:sample_rate={rate}:d={dur}"+ f"[a{idx}]")+ pads.append(f"[v{idx}][a{idx}]")+ music_head = _sb_music_head(music, n_inputs)+ # THE BED'S OWN ENVELOPE, and it is the SAME curve the preview plays and+ # the level line on the block draws — `storyboard_editor.bed_render_gain`,+ # already on the film's clock. Empty for a bed nobody has mixed, which is+ # what keeps the graph character-for-character what it was for every film+ # written before the mix was a control. It applies in BOTH modes: "fade+ # the music out under the last shot" is the same request whether or not+ # the clips kept their own sound.+ bed_env = _sb_volume_term((music or {}).get("gain"))+ bed_tail = ("," + bed_env.rstrip(",")) if bed_env else ""+ if silent_segments:+ chains.append(f"{''.join(pads)}concat=n={len(segs)}:v=1:a=0[vcat]")+ # `apad` before the trim so a soundtrack shorter than the film ends in+ # silence rather than ending the film.+ chains.append(+ f"{music_head}aresample={rate},"+ f"aformat=sample_fmts=fltp:channel_layouts=stereo,"+ f"apad,atrim=0:{total:.6f},asetpts=PTS-STARTPTS"+ f"{bed_tail}[aout]")+ elif music and music_mode == "under":+ if split:+ # The picture concatenates on its own; the sound was already laid+ # out end to end by the plan, gaps and all.+ chains.append(f"{''.join(pads)}concat=n={len(segs)}:v=1:a=0[vcat]")+ chains.extend(_sb_split_audio_chains(aplan["lanes"], total, rate,+ "[acat]"))+ else:+ chains.append(+ f"{''.join(pads)}concat=n={len(segs)}:v=1:a=1[vcat][acat]")+ # The bed: same trim/pad treatment as `replace`, then the document's+ # own curve and nothing else.+ #+ # THE DUCK IS IN THAT CURVE NOW, NOT IN A COMPRESSOR. What stood here+ # was `volume=0.20` followed by `[bed][key]sidechaincompress=...`, keyed+ # on an `asplit` of the clip audio. It worked, and it was unknowable: a+ # compressor's output is a function of samples, so there was no value+ # anywhere the preview could read to play the same mix, and the one+ # surface the user checks his work on played a film that did not exist.+ # `storyboard_editor.bed_duck_points` expresses the same decision — the+ # bed steps back by the measured 11.4 dB wherever a clip's own sound is+ # playing, in 5 ms, back up over 400 ms — as breakpoints derived from+ # the TIMELINE, which the preview and the export can read too. Same+ # depth, same times, three outputs that agree.+ chains.append(+ f"{music_head}aresample={rate},"+ f"aformat=sample_fmts=fltp:channel_layouts=stereo,"+ f"apad,atrim=0:{total:.6f},asetpts=PTS-STARTPTS"+ f"{bed_tail}[bed]")+ # normalize=0 or amix halves everything to protect a headroom budget we+ # have already set deliberately; duration=first pins the result to the+ # picture rather than to whichever input happens to run longer.+ # normalize=0 stops amix halving both inputs — and it also means NOTHING+ # is protecting the sum. Engine dialogue comes out hot (0.35 RMS on a+ # measured opening line), and hot dialogue plus a bed peaked the first+ # under-mix film at 1.31 pre-encode, 1341 hard-clipped samples, silent+ # about it.+ #+ # asoftclip and NOT alimiter. alimiter is the filter this obviously+ # wants, and on this build it is a NO-OP on float samples — measured on+ # the real mix, input peak 1.3075, output peak 1.3075, with and without+ # level=disabled, and unchanged by an aformat to s16 on either side of+ # it. asoftclip actually holds: same signal comes out at 0.98 for 7% of+ # RMS. Do not "fix" this back to alimiter without re-measuring the peak+ # of the output — it fails silently and the failure is audible.+ #+ # THE LIMITER IS THE ONE TERM THAT IS NOT IN THE DOCUMENT, and it is+ # the honest exception rather than a leak: it acts on the SUM of two+ # signals, which a browser playing two <audio> elements never computes,+ # so a preview could only fake it. It is a safety net, not a mix+ # decision — and the render MEASURES what it did (`mix_peak`) and says+ # so, which is what a net owes the person it is under.+ chains.append(+ "[acat][bed]amix=inputs=2:duration=first:dropout_transition=0:"+ f"normalize=0,asoftclip=type=tanh:threshold={_sb_mix_ceiling():g}"+ "[aout]")+ elif split:+ chains.append(f"{''.join(pads)}concat=n={len(segs)}:v=1:a=0[vcat]")+ chains.extend(_sb_split_audio_chains(aplan["lanes"], total, rate,+ "[aout]"))+ else:+ chains.append(+ f"{''.join(pads)}concat=n={len(segs)}:v=1:a=1[vcat][aout]")+ # ---- THE OVERLAY LANE, composited over the finished picture ----------+ # A SECOND VIDEO TRACK, and the alpha is the whole of it. The card arrives+ # 1536x832 for a 768x416 frame — authored at 2x on purpose — so it is+ # DOWNSCALED, and a scale that drops the alpha channel delivers a black+ # rectangle where the transparency was. That is the failure mode this lane+ # exists to avoid, so `format=rgba` is asserted on BOTH sides of the+ # scale: once to make sure what enters the scaler carries alpha, once+ # because a scaler is free to pick an output format that does not.+ base = "[vcat]"+ total_v = total+ rows = list(overlays or [])+ if rows:+ # A CARD MAY OUTLIVE THE LAST SHOT. The picture lane ends where its+ # clips end; an endcard laid over the final seconds can legitimately+ # run past that, and vanishing at the last frame of picture would be+ # the wrong answer. The base is padded with black so the card+ # composites over something.+ far = max(float(r.get("film_end") or 0.0) for r in rows)+ if far > total_v + 1e-6:+ chains.append(f"{base}tpad=stop_mode=add:stop_duration="+ f"{far - total_v:.6f}:color=black[vpad]")+ base = "[vpad]"+ total_v = far+ for i, r in enumerate(rows):+ fs = max(0.0, float(r.get("film_start") or 0.0))+ fe = max(fs, float(r.get("film_end") or 0.0))+ span = fe - fs+ if span <= 1e-6:+ continue+ inp = overlay_base + i+ fade = _sb_fade_term(r.get("fx"), span, alpha=True)+ chains.append(+ f"[{inp}:v]format=rgba,"+ f"scale={target_w}:{target_h}:flags=lanczos,"+ f"format=rgba,setsar=1,{fade}"+ # The overlay stream's own clock starts at 0; this puts its+ # first frame at the film second it was placed on.+ f"setpts=PTS+{fs:.6f}/TB[ov{i}]")+ # `repeatlast=0` or the last frame of the card sticks for the rest+ # of the film; `enable` is what makes the lane a lane rather than a+ # watermark.+ chains.append(+ f"{base}[ov{i}]overlay=0:0:eof_action=pass:repeatlast=0:"+ f"enable='between(t,{fs:.6f},{fe:.6f})'[vov{i}]")+ base = f"[vov{i}]"+ # THE SOUND IS NOT PADDED, and does not need to be. Nothing is mapped+ # but `[vout]` and `[aout]`, and with no `-shortest` the output runs as+ # long as the LONGEST mapped stream — so the padded picture sets the+ # length and the audio simply ends where the last clip's sound ended,+ # which is what silence after the final shot means anyway. A pad chain+ # here would have been a label nothing maps.+ tail = bt709_vf("")+ if tail:+ chains.append(f"{base}{tail}[vout]")+ return ";".join(chains), "[vout]"+ return ";".join(chains), base+++def _sb_timeline_segments(timeline: list) -> tuple[list[dict], list[str], list]:+ """A timeline (from `edit_to_cuts`) → (segments, unreadable, inputs).++ THE REFACTOR THE WHOLE OF WAVE 2 TURNS ON. Until stills and slugs existed,+ segment index WAS ffmpeg input index — `-i` per probe, in probe order, and+ the soundtrack addressed as `len(probes)`. A slug consumes no input; a+ still consumes one but arrives through `-loop 1 -framerate F -t D` and+ never reaches ffprobe. So the segment list and the input list stop being+ the same list, and every index after the first slug shifts.++ Assigning the indices in ONE place, next to the argv that will honour them,+ is what stops that shift being discovered by a film whose sound is one shot+ late. `inputs` is the argv fragment list, in the exact order the graph+ expects; `segments[i]["input"]` is the index into it, or None.+ """+ segs: list[dict] = []+ unreadable: list[str] = []+ inputs: list[list[str]] = []+ for entry in timeline or []:+ if not isinstance(entry, dict):+ continue+ kind = str(entry.get("kind") or "video")+ try:+ start = float(entry.get("start") or 0.0)+ end = float(entry.get("end") or 0.0)+ except (TypeError, ValueError):+ continue+ length = max(0.0, end - start)+ if length <= 0:+ continue+ adjust = entry.get("adjust") if isinstance(entry.get("adjust"), dict) else None+ if kind == "slug":+ segs.append({"kind": "slug", "input": None, "info": None,+ "window": None, "adjust": adjust,+ "duration": length})+ continue+ path = str(entry.get("path") or "")+ if kind == "still":+ info = _sb_probe_still(path)+ if info is None:+ unreadable.append(Path(path).name)+ continue+ segs.append({"kind": "still", "input": len(inputs), "info": info,+ "window": None, "adjust": adjust,+ "duration": length, "path": path})+ # `-loop 1` with an explicit `-t` is what turns one image into a+ # stream of the right length. Without `-t` the loop is infinite and+ # ffmpeg runs until the disk is full.+ inputs.append(["-loop", "1", "-framerate", str(FPS),+ "-t", f"{length:.6f}", "-i", path])+ continue+ info = _sb_probe_clip(path)+ if info is None:+ unreadable.append(Path(path).name)+ continue+ seg = {"kind": "video", "input": len(inputs), "info": info,+ "window": {"start": start, "end": end},+ "adjust": adjust,+ "duration": min(length, float(info["duration"])),+ "path": path}+ if entry.get("mute") is True:+ seg["mute"] = True+ if isinstance(entry.get("fx"), dict) and entry["fx"]:+ seg["fx"] = dict(entry["fx"])+ if entry.get("gain"):+ seg["gain"] = [list(pt) for pt in entry["gain"]]+ aud = entry.get("audio")+ if isinstance(aud, dict):+ # A DELTA, NOT A FILM SECOND. The assembler CONCATENATES, so a+ # hole in the timeline closes and every clip after it slides+ # earlier — an absolute offset taken from the editor's clock would+ # put the sound where the picture used to be. What survives the+ # slide is how far the sound sits from ITS OWN clip.+ try:+ seg["audio"] = {+ "start": float(aud.get("start") or 0.0),+ "end": float(aud.get("end") or 0.0),+ "delta": round(float(aud.get("film_start") or 0.0)+ - float(entry.get("film_start") or 0.0), 6),+ }+ except (TypeError, ValueError):+ pass+ segs.append(seg)+ inputs.append(["-i", path])+ return segs, unreadable, inputs+++def _sb_assemble_film(clips: list, out_path, *, plan: list | None = None,+ timeline: list | None = None,+ overlays: list | None = None,+ music=None, music_start: float = 0.0,+ music_end: float | None = None,+ music_delay: float = 0.0,+ music_mode: str = "replace",+ music_gain: list | None = None) -> dict:+ """Concatenate the exported shots into ONE playable film.++ `clips` is the export directory's own copies, in `n` order, already+ filtered by the copy loop — the film is exactly what the folder contains,+ never a second, differently-derived selection.++ Encodes with the panel's output settings (`output_codec_settings()`, the+ same call the upscale/H3-export/mux passes make) plus `+faststart`, so the+ film is subject to the same codec gate as every other file the panel emits.++ `plan` is an OPTIONAL cut plan from `storyboard_edit.plan_cut()` — a list+ of {"path", "start", "end"} — and `music` an OPTIONAL soundtrack path.+ With neither, this is the whole-clip concatenation it has always been, so+ an existing export cannot change under anybody. With them, each shot is+ trimmed to its chosen window and the soundtrack replaces the clip audio,+ both inside the ONE filtergraph pass that was already going to run: the+ auto-edit costs no extra decode and no second generation of encoding.++ `timeline` is the Editor's own list (`edit_to_cuts`) and, when present, it+ REPLACES `clips`/`plan` as the description of the film: it is the only+ shape that can carry a kind, because a slug has no file to appear in a+ `clips` list at all.++ Returns {"ok": True, "path", "clips", "width", "height", "duration"} or+ {"ok": False, "error"}. It NEVER raises: the folder + manifest are the+ export's contract and an assembly that could not run must not take them+ down with it. Source clips are only ever read.+ """+ out_path = Path(str(out_path))+ segments: list[dict] | None = None+ seg_inputs: list[list[str]] = []+ if timeline is not None:+ segments, unreadable, seg_inputs = _sb_timeline_segments(timeline)+ if not segments:+ return {"ok": False,+ "error": "nothing on the timeline could be read"}+ probes = [(Path(s["path"]), s["info"]) for s in segments+ if s.get("path") and s.get("info")]+ else:+ if not clips:+ return {"ok": False, "error": "no clips to assemble"}+ probes = []+ unreadable = []+ for c in clips:+ info = _sb_probe_clip(c)+ if info is None:+ unreadable.append(Path(str(c)).name)+ continue+ probes.append((Path(str(c)), info))+ if not probes:+ return {"ok": False,+ "error": "ffprobe could not read any exported clip"}++ # Target geometry = the largest picture in the cut, so nothing is ever+ # scaled DOWN and no detail is thrown away; every smaller shot is+ # letter/pillarboxed up to it. Even numbers because H.264 4:2:0 has no+ # odd-dimension form.+ #+ # A film of nothing but slugs has no picture to measure, and `color=`+ # still has to be told a size — so the fallback is the panel's own default+ # geometry rather than a crash on max() of an empty list.+ target_w = max([i["w"] for _, i in probes] or [1024])+ target_h = max([i["h"] for _, i in probes] or [576])+ target_w += target_w % 2+ target_h += target_h % 2+ rates = [i["sample_rate"] for _, i in probes if i["sample_rate"]]+ rate = max(rates) if rates else _SB_FILM_SAMPLE_RATE+ if music:+ # When a soundtrack replaces the clip audio, the clips' rates are+ # irrelevant and actively harmful: the LTX/H3 tracks are 32-48 kHz and+ # resampling a 44.1 kHz song DOWN to a rate no longer in the film is a+ # quality loss for nothing.+ m_rate = _sb_probe_audio_rate(music)+ if m_rate:+ rate = m_rate++ cuts = _sb_cut_index(plan)+ # `music_start` is where in the TRACK the film begins — the timeline+ # editor's audio offset. The filtergraph has always read it; before the+ # editor there was nothing that could set it, so it was pinned at 0.+ # `music_end` and `music_delay` are the soundtrack's other two edges: where+ # the trim stops it, and how far into the film it drops in. Both default to+ # "no opinion", so a caller that predates the music being an object builds+ # the identical graph it always did.+ #+ # `music_gain` is the bed's resolved curve on the film's clock. It was the+ # one field the graph already read (`(music or {}).get('gain')`) and that+ # NOTHING EVER SET — so the bed's `afx`, which the model normalised,+ # validated and drew, reached the render as silence about itself. A fade on+ # the soundtrack was expressible everywhere except in the file.+ music_arg = ({"path": str(music), "start": max(0.0, float(music_start or 0.0)),+ "end": (float(music_end) if music_end is not None else None),+ "delay": max(0.0, float(music_delay or 0.0)),+ "mode": str(music_mode or "replace").lower(),+ "gain": [list(p) for p in (music_gain or [])]}+ if music else None)+ # THE OVERLAY LANE'S INPUTS GO LAST, after the segments and after the+ # music. Anywhere else and every index after them shifts: the music is+ # addressed as `len(segment inputs)` and the graph would start reading a+ # card where it expected a soundtrack.+ ov_rows, ov_inputs = [], []+ for o in (overlays or []):+ if not isinstance(o, dict):+ continue+ fs = max(0.0, float(o.get("film_start") or 0.0))+ fe = max(fs, float(o.get("film_end") or 0.0))+ if fe - fs <= 1e-6:+ continue+ src = str(o.get("path") or "")+ if not src or not Path(src).is_file():+ unreadable.append(Path(src).name if src else "overlay")+ continue+ if str(o.get("kind") or "still") == "still":+ # `-loop 1` with an explicit `-t` is what turns one PNG into a+ # stream of the right length, the same shape a still CLIP uses.+ ov_inputs.append(["-loop", "1", "-framerate", str(FPS),+ "-t", f"{fe - fs:.6f}", "-i", src])+ else:+ ov_inputs.append(["-i", src])+ ov_rows.append(o)+ overlay_base = (len(seg_inputs) if segments is not None else len(probes)) \+ + (1 if music else 0)+ codec = output_codec_settings()+ graph, vlabel = _sb_film_filtergraph(probes, target_w, target_h, rate,+ codec["pix_fmt"], cuts=cuts,+ music=music_arg, segments=segments,+ overlays=ov_rows,+ overlay_base=overlay_base)++ cmd = [str(FFMPEG), "-y"]+ if segments is not None:+ # THE ARGV THE SEGMENT LIST PROMISED. Built by the same function that+ # assigned the indices, in the same order, so `[3:v]` in the graph and+ # the fourth `-i` on the command line cannot come apart.+ for frag in seg_inputs:+ cmd += frag+ else:+ for clip, _ in probes:+ cmd += ["-i", str(clip)]+ if music_arg:+ cmd += ["-i", music_arg["path"]]+ for frag in ov_inputs:+ cmd += frag+ cmd += [+ "-filter_complex", graph,+ "-map", vlabel, "-map", "[aout]",+ "-c:v", "libx264", "-pix_fmt", codec["pix_fmt"], "-crf", codec["crf"],+ "-preset", "medium",+ *BT709_FLAGS,+ "-movflags", "+faststart",+ "-c:a", "aac", "-b:a", "192k", "-ar", str(rate),+ str(out_path),+ ]+ try:+ run_ffmpeg_tracked(cmd, "Storyboard film")+ except Exception as exc: # noqa: BLE001+ # A half-written mp4 is worse than none — it looks like a finished film+ # in Finder and plays for two seconds.+ try:+ out_path.unlink()+ except OSError:+ pass+ return {"ok": False, "error": f"ffmpeg could not assemble the film: {exc}"}+ if not out_path.is_file() or out_path.stat().st_size == 0:+ return {"ok": False, "error": "ffmpeg exited cleanly but wrote no film"}+ # The SAME per-occurrence consumption the graph just did, so the reported+ # duration and the film agree even when one source is used twice — and, on+ # the timeline path, even when some of what played was never a file.+ if segments is not None:+ played = sum(float(s.get("duration") or 0.0) for s in segments)+ n_clips = len(segments)+ else:+ played = sum(+ min(float(w["end"]) - float(w["start"]), i["duration"]) if w+ else i["duration"]+ for (_c, i), w in zip(probes, _sb_segment_windows(probes, cuts)))+ n_clips = len(probes)+ facts = {"ok": True, "path": str(out_path), "clips": n_clips,+ "width": target_w, "height": target_h,+ "sample_rate": rate,+ "duration": round(played, 3),+ "trimmed": bool(cuts) or segments is not None,+ "music": bool(music_arg),+ "kinds": ({k: sum(1 for s in segments if s["kind"] == k)+ for k in ("video", "still", "slug")}+ if segments is not None else None),+ "unreadable": unreadable}+ # WHAT THE LIMITER DID, MEASURED. It is the one gain in this graph that is+ # not a value in the document, because it acts on the sum of two signals+ # and nothing outside ffmpeg has those samples — so instead of a preview+ # pretending to apply it, the render reports it. A peak sitting above the+ # soft-clip knee is the knee working: tanh only pushes a sample past the+ # threshold when it was already over it.+ if music_arg and str(music_arg.get("mode") or "") == "under":+ peak = _sb_audio_peak(out_path)+ if peak is not None:+ facts["mix_peak"] = round(peak, 4)+ facts["mix_ceiling"] = round(_sb_mix_ceiling(), 4)+ facts["mix_limited"] = bool(peak > _sb_mix_ceiling() + 1e-4)+ # What the assembler already knows, written down beside the film. Without+ # it the only way to answer "how long is this film" is an ffprobe, and the+ # board list asks that question every two seconds.+ _sb_write_film_sidecar(out_path, facts)+ return facts+++def _sb_audio_peak(path) -> float | None:+ """The finished film's true peak, LINEAR, or None when it cannot be had.++ `volumedetect` reports dBFS; the mix works in linear 0..1 because that is+ what `volume` and `asoftclip` take, so the conversion happens here and the+ rest of the panel never sees two units for one quantity. Best-effort by+ construction: a peak nobody could measure must not fail a film that+ rendered perfectly well.+ """+ try:+ res = subprocess.run(+ [FFMPEG, "-v", "info", "-nostdin", "-i", str(path),+ "-map", "0:a:0", "-af", "volumedetect", "-f", "null", "-"],+ capture_output=True, text=True, timeout=120, check=False)+ except (OSError, subprocess.SubprocessError):+ return None+ m = re.search(r"max_volume:\s*(-?\d+(?:\.\d+)?)\s*dB",+ (res.stderr or "") + (res.stdout or ""))+ if not m:+ return None+ try:+ return float(10.0 ** (float(m.group(1)) / 20.0))+ except (TypeError, ValueError, OverflowError):+ return None+++def _sb_plan_auto_edit(clips: list, *, music=None,+ target_seconds: float | None = None,+ min_shot: float = 1.5,+ max_shot: float | None = None) -> tuple[list | None, str]:+ """Ask `storyboard_edit` for a cut plan → (plan, one-line summary).++ Imported HERE rather than at module scope, and behind a try, for two+ reasons: the panel must still boot on an install whose `storyboard_edit.py`+ is missing or broken, and nothing in the default export path should pay for+ an import it will not use. A failure is (None, "why") — the export then+ assembles whole clips exactly as it always did.+ """+ try:+ import storyboard_edit as sedit # noqa: PLC0415+ except Exception as exc: # noqa: BLE001+ return None, f"auto-edit unavailable ({type(exc).__name__}: {exc})"+ try:+ plan = sedit.plan_cut([str(c) for c in clips], audio=music,+ target_seconds=target_seconds,+ min_shot=min_shot, max_shot=max_shot)+ except Exception as exc: # noqa: BLE001+ return None, f"auto-edit failed ({type(exc).__name__}: {exc})"+ if not plan:+ return None, "auto-edit produced no plan"+ snapped = sum(1 for p in plan if p["snap"]["kind"] != "none")+ return plan, (f"auto-edit: {len(plan)} shots, "+ f"{sedit.plan_total(plan):g} s, {snapped}/{len(plan)} cuts "+ f"on the grid")+++def _sb_film_name(board: dict) -> str:+ """ONE film per board, one name.++ Export wrote `<slug>_film.mp4` and the timeline's render wrote+ `<slug>_timeline.mp4`, into the same folder, from the same assembler — so+ one board produced two films of the same movie and the Film screen could+ only tell them apart by a chip that said which button you had pressed.+ That is the whole of the 2026-08-17 "two films in one folder" finding.+ """+ return f"{_sb_slug(board.get('title') or 'storyboard', 6)}_film.mp4"+++def _sbe_render_edit(board: dict, edit: dict, *, music=None,+ music_mode: str | None = None,+ out_name: str | None = None) -> dict:+ """Assemble the film the TIMELINE describes. The one assembler.++ Both doors come here now: the Editor's Render, and Export whenever the+ board has an edit.json. The alternative — Export running its own second+ auto-editor over its own copies — meant the same board rendered two+ different films depending on which button was nearer.+ """+ sedit = _sbe_import()+ cuts = sedit.edit_to_cuts(edit)+ if not cuts:+ # `status` rides along so the HTTP seam can keep telling a bad request+ # apart from a failed encode. A caller that ignores it loses nothing.+ return {"ok": False, "error": "the timeline is empty", "status": 400}+ audio = edit.get("audio") or {}+ music = music or audio.get("path") or None+ if music and not Path(str(music)).is_file():+ return {"ok": False, "error": f"no soundtrack at {music}",+ "status": 400}+ # The soundtrack's three numbers, from the one function that owns them —+ # so the render, the NLE export and the waveform on screen cannot disagree+ # about where the music starts.+ win = sedit.music_window(audio)+ dest = _sb_film_dir(board)+ dest.mkdir(parents=True, exist_ok=True)+ name = out_name or _sb_film_name(board)+ gaps = sedit.edit_gaps(edit)+ kinds = {}+ for c in cuts:+ kinds[str(c.get("kind") or "video")] = kinds.get(+ str(c.get("kind") or "video"), 0) + 1+ push(f"[timeline] rendering {len(cuts)} clip(s) → {name}"+ + (f" ({kinds.get('still', 0)} still, {kinds.get('slug', 0)} black)"+ if (kinds.get("still") or kinds.get("slug")) else ""))+ # `under` keeps the clips' own audio and ducks the bed beneath it. It is+ # the right default for anything with a voice in it, but `replace` stays+ # the default HERE because a beat-cut music video wants the track and+ # nothing else, and that is what this path has always done.+ mmode = str(music_mode or audio.get("mode") or "replace").lower()+ # `timeline=` rather than `clips=` + `plan=`: the cut list is the film now,+ # kinds and all. A slug has no path, so it could never have appeared in the+ # `clips` argument, and a still's `-i` needs `-loop 1 -t` in front of it —+ # neither is expressible in a list of filenames.+ # THE MIX, FROM THE DOCUMENT. One curve — the bed fader, whatever envelope+ # the user drew, and the auto-duck if it is on and nothing outranks it —+ # resolved by the model, so the file that comes out plays what the Editor+ # played. Nothing about the level is decided in this function or below it.+ film = _sb_assemble_film(+ [c["path"] for c in cuts if c.get("path")], dest / name,+ timeline=cuts, music=music, music_start=win["start"],+ music_end=win["end"], music_delay=win["delay"], music_mode=mmode,+ music_gain=sedit.bed_render_gain(edit),+ overlays=sedit.overlay_items(edit))+ film["gaps"] = gaps+ if gaps:+ # An honest limitation, disclosed rather than discovered: this+ # assembler concatenates, so a hole in the timeline closes and+ # everything after it slides earlier — off the beat it was cut to.+ film["gaps_note"] = (+ f"{len(gaps)} gap(s) totalling "+ f"{sum(g['duration'] for g in gaps):.2f}s were closed by the "+ f"concatenation — the film is that much shorter than the "+ f"timeline.")+ film["timeline_duration"] = sedit.edit_duration(edit)+ return film+++def _sb_export(board: dict, *, auto_edit: bool = False, music=None,+ music_mode: str | None = None,+ target_seconds: float | None = None,+ min_shot: float = 1.5,+ max_shot: float | None = None) -> dict:+ """A folder, a manifest, and ONE playable film.++ ONE ASSEMBLER (2026-08-17). When the board has an `edit.json` — i.e. the+ user has been in the Editor — the film is the CUT, rendered by the same+ path the Editor's Render button uses, under the same name. Export used to+ ignore the timeline entirely and run a second auto-editor over its own+ copies, so a board that had been cut produced two differently-named films+ from one folder and neither the screen nor the file said which was the+ real one. The folder and the manifest are unchanged; only who assembles+ the film changed.++ Clips are COPIED, never moved — the gallery keeps them — and the film is+ built from those copies, so the sources are read-only throughout.++ Assembly is best-effort by design: if ffmpeg is missing, wedged, or refuses+ the cut, the folder and the shot list still land and the return payload and+ the markdown both say so in plain words.++ `auto_edit` is OFF by default and the only thing that turns it on. With it,+ `storyboard_edit` chooses the best window inside each shot and lands the+ cuts on the soundtrack's beat; without it the film is the whole-clip+ concatenation it has always been. An auto-edit that cannot run is a note in+ the manifest, never a failed export."""title = board.get("title") or "storyboard"- day = time.strftime("%Y-%m-%d", time.localtime(board.get("created_at") or time.time()))- dest = OUTPUT / "storyboards" / f"{day}_{_sb_slug(title, 6)}"+ dest = _sb_film_dir(board)dest.mkdir(parents=True, exist_ok=True)rows, cut, files = [], [], []+ cut_list: list = [] # the copies, in `n` orderfor s in sorted((board.get("shots") or []), key=lambda x: x.get("n") or 0):if not isinstance(s, dict):continue@@ -13886,6 +15821,11 @@ def _sb_export(board: dict) -> dict:push(f"[storyboard] could not copy shot {n}: {exc}")continuefiles.append(name)+ # ONE list, built by the loop that already made the include/exclude+ # decision. The film is assembled from these exact copies, in this+ # exact order, so "what is in the folder" and "what is in the film"+ # can never drift apart.+ cut_list.append(dest / name)rows.append(f"| {n:02d} | {name} | {s.get('duration_s')} s | "f"{s.get('seed')} | {which} | "f"{(s.get('prompt') or '')[:90].replace('|', '/')}… |")@@ -13895,18 +15835,827 @@ def _sb_export(board: dict) -> dict:if isinstance(s, dict) and s.get("status") != "skipped")cast = ", ".join(sorted({str(s.get("character_id")) for s in (board.get("shots") or [])if isinstance(s, dict) and s.get("character_id")})) or "none"+ # ---- the film -------------------------------------------------------+ # Assembled from the copies above, so a failure here cannot touch a source+ # clip, and cannot stop the folder + manifest from being written.+ film_name = _sb_film_name(board)+ film: dict = {"ok": False, "error": "no shots to assemble"}+ plan = None+ edit_note = ""+ # THE TIMELINE WINS. An arrangement a human made outranks anything this+ # function could derive from the shot list, and rendering the shot list+ # instead is how "Export" and "Render the timeline" came to mean two+ # different films.+ sedit_edit = None+ try:+ sedit_edit = _sbe_import().load_edit(_sbe_board_dir(board.get("id") or ""))+ except Exception: # noqa: BLE001+ sedit_edit = None+ if sedit_edit and (sedit_edit.get("clips") or []):+ try:+ film = _sbe_render_edit(board, sedit_edit, music=music,+ music_mode=music_mode,+ out_name=film_name)+ except Exception as exc: # noqa: BLE001+ film = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}+ edit_note = "assembled from the timeline in the Editor"+ push(f"[storyboard] {edit_note} → {film_name}")+ elif cut_list and auto_edit:+ plan, edit_note = _sb_plan_auto_edit(+ cut_list, music=music, target_seconds=target_seconds,+ min_shot=min_shot, max_shot=max_shot)+ push(f"[storyboard] {edit_note}")+ if cut_list and not (sedit_edit and (sedit_edit.get("clips") or [])):+ push(f"[storyboard] assembling {len(cut_list)} shot(s) into "+ f"{film_name} — mixed sizes are normalised, this re-encodes")+ try:+ # The default call is the call that always was — same arguments,+ # same argv, same bytes out. The auto-edit only ever ADDS kwargs,+ # and only when it actually produced a plan.+ if plan:+ film = _sb_assemble_film(cut_list, dest / film_name,+ plan=plan, music=music)+ else:+ film = _sb_assemble_film(cut_list, dest / film_name)+ except Exception as exc: # noqa: BLE001+ film = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}+ if film.get("ok"):+ push(f"[storyboard] film ready → {film_name} "+ f"({film['clips']} shots, {film['width']}×{film['height']}, "+ f"{film['duration']:g} s)")+ film_md = (f"**Film:** [`{film_name}`]({film_name}) — {film['clips']} "+ f"shots joined, {film['width']}×{film['height']} @ {FPS} fps, "+ f"{film['duration']:g} s.")+ if film.get("unreadable"):+ film_md += (" Left out of the cut (unreadable): "+ + ", ".join(f"`{u}`" for u in film["unreadable"]) + ".")+ if sedit_edit and (sedit_edit.get("clips") or []):+ film_md += (f" Assembled from the timeline in the Editor "+ f"({len(sedit_edit.get('clips') or [])} clips) — the "+ f"same file that button renders, under the same name.")+ elif plan:+ snapped = sum(1 for p in plan if p["snap"]["kind"] != "none")+ film_md += (f" Auto-edited: each shot trimmed to its best window, "+ f"{snapped} of {len(plan)} cuts landed on the beat.")+ elif auto_edit and edit_note:+ film_md += f" Whole clips — {edit_note}."+ else:+ push(f"[storyboard] film not assembled: {film.get('error')} — "+ f"the folder and the shot list are complete")+ film_md = (f"**Film:** not assembled — {film.get('error')}. "+ f"The clips above and this list are complete; re-run Export "+ f"to try the assembly again.")+md = [f"# {title}", "",f"{len(board.get('shots') or [])} shots planned · {delivered} delivered · "f"{round(runtime)} s", "",- f"Rendered with Phosphene {_read_local_version() or 'dev'} · character: {cast}", "",+ f"Rendered with Phosphene {running_version()} · character: {cast}", "",+ film_md, "","| # | file | length | seed | pass | prompt |","|---|---|---|---|---|---|"] + rows+ if plan:+ # The edit, in the manifest, in the same place the shot list is — so+ # "why is shot 3 only four seconds and why does it start at 0.86" is+ # answerable without re-running anything.+ md += ["", "## The edit", "",+ "| # | file | window | length | at | cut on | shift |",+ "|---|---|---|---|---|---|---|"]+ for p in plan:+ md.append(f"| {p['n']:02d} | {Path(p['path']).name} | "+ f"{p['start']:.2f}–{p['end']:.2f} s | "+ f"{p['duration']:.3f} s | {p['film_start']:.3f} s | "+ f"{p['snap']['kind']} | "+ f"{p['snap']['shift_ms']:+.0f} ms |")+ md += [""] + [f"- **S{p['n']:02d}** — {p['window']['reason']}"+ for p in plan]if cut:md += ["", "## Cut", ""] + cut(dest / "storyboard.md").write_text("\n".join(md) + "\n", encoding="utf-8")(dest / "storyboard.json").write_text(json.dumps(board, indent=2, ensure_ascii=False), encoding="utf-8")- return {"ok": True, "dir": str(dest), "files": files}+ if plan:+ (dest / "storyboard_edit.json").write_text(+ json.dumps(plan, indent=2, ensure_ascii=False), encoding="utf-8")+ return {"ok": True, "dir": str(dest), "files": files,+ "film": film.get("path") if film.get("ok") else None,+ "film_name": film_name if film.get("ok") else None,+ "film_error": None if film.get("ok") else str(film.get("error") or ""),+ "film_duration": film.get("duration") if film.get("ok") else None,+ "auto_edit": bool(plan),+ "auto_edit_note": edit_note or None}+++# ===========================================================================+# THE FILMS A BOARD HAS PRODUCED+# ===========================================================================+# Both assemblies — Export's whole-clip join and the timeline's render — write+# an mp4 into `_sb_film_dir(board)` and then said nothing about it. The panel's+# gallery could not help either: `list_outputs` globs `OUTPUT/*.mp4` and never+# descends, so the finished film was the one thing the app made that the app+# could not show you. Everything below exists to answer one question the owner+# asked out loud — "where is the finalized clip?".++# A shot copy is `S07_the-empty-hall.mp4`; anything else ending in .mp4 in that+# folder is a film. That is the export's own naming, so a film can never be+# mistaken for one of its own shots.+_SB_SHOT_COPY_RE = re.compile(r"^S\d+_")++_SB_FILM_FACTS: dict = {} # (path, mtime, size) -> probed facts+++def _sb_film_sidecar(path) -> Path:+ p = Path(str(path))+ return p.with_name(p.name + ".json")+++def _sb_write_film_sidecar(path, facts: dict) -> None:+ """Best-effort, and silent when it fails: a missing sidecar costs one+ ffprobe, never a film."""+ try:+ _sb_film_sidecar(path).write_text(json.dumps({+ "film": {k: facts.get(k) for k in+ ("clips", "width", "height", "duration", "sample_rate",+ "trimmed", "music")},+ "created_at": time.time(),+ "phosphene": running_version(),+ }, indent=2), encoding="utf-8")+ except (OSError, TypeError, ValueError):+ pass+++def _sb_sidecar_is_current(side: Path, film_stat) -> bool:+ """Was this sidecar written for the film that is there NOW?++ A one-second slack because the sidecar is written immediately AFTER the+ mp4 and both timestamps come from the same second's worth of syscalls;+ anything genuinely stale is stale by minutes.+ """+ try:+ return side.stat().st_mtime >= film_stat.st_mtime - 1.0+ except OSError:+ return False+++def _sb_film_facts(path: Path, *, probe: bool = True) -> dict:+ """Duration and geometry for one film. Sidecar first, ffprobe once.++ `probe=False` is the polling path: the board list wants to say "this one+ has a film" every two seconds and must not shell out to do it.+ """+ facts = {"duration": None, "width": None, "height": None, "clips": None}+ try:+ st = path.stat()+ except OSError:+ return facts+ key = (str(path), int(st.st_mtime), st.st_size)+ hit = _SB_FILM_FACTS.get(key)+ if hit is not None:+ return dict(hit)+ side = _sb_film_sidecar(path)+ # A SIDECAR OLDER THAN ITS FILM IS A CACHE THAT OUTLIVED ITS SUBJECT —+ # the same rule the peaks lane already follows ("a cache that outlives its+ # subject is the music strip reading 44.99s under a different file"). One+ # film per board and one name for it means every re-render lands on the+ # same path, so a sidecar that was not rewritten describes a film that is+ # no longer there. Cheap: a stat that was already taken.+ if side.is_file() and _sb_sidecar_is_current(side, st):+ try:+ doc = json.loads(side.read_text(encoding="utf-8"))+ f = doc.get("film") if isinstance(doc, dict) else None+ if isinstance(f, dict):+ for k in facts:+ if f.get(k) is not None:+ facts[k] = f[k]+ except (OSError, ValueError):+ pass+ if probe and facts["duration"] is None:+ info = _sb_probe_clip(path)+ if info:+ facts["duration"] = round(float(info["duration"]), 3)+ facts["width"] = info["w"]+ facts["height"] = info["h"]+ # Films assembled before sidecars existed get one now, so the board+ # list can say how long they are without shelling out. Same idiom+ # as the thumbnail cache: a derived file beside the source.+ _sb_write_film_sidecar(path, facts)+ if facts["duration"] is not None:+ _SB_FILM_FACTS[key] = dict(facts)+ return facts+++def _sb_films(board: dict, *, probe: bool = True) -> list[dict]:+ """Every finished film this board has produced, newest first."""+ d = _sb_film_dir(board)+ out: list[dict] = []+ try:+ entries = sorted(d.iterdir())+ except OSError:+ return out+ for p in entries:+ if p.suffix.lower() != ".mp4" or _SB_SHOT_COPY_RE.match(p.name):+ continue+ try:+ st = p.stat()+ except OSError:+ continue+ row = {+ "name": p.name,+ "path": str(p),+ # `&v=<mtime>` — THE SAME CACHE BUST `list_outputs` HAS CARRIED+ # SINCE Y1.039, and this list never got it. It matters more here+ # than anywhere: there is exactly ONE film per board and one name+ # for it (`_sb_film_name`), so every re-render replaces the bytes+ # behind a URL that does not change by one character. The `<video>`+ # on the Film screen is built from this string, and a media element+ # asked for a URL it already has will happily play what it already+ # holds. "The sound issues are still there. Maybe it's caching, I+ # don't know." — the answer to which was yes, it can be.+ "url": f"/file?path={quote(str(p))}&v={int(st.st_mtime)}",+ "bytes": st.st_size,+ "at": st.st_mtime,+ # There is ONE assembler now, and one name, so a new `_film.mp4`+ # is just "the film" — labelling it "Export" would name a button+ # that no longer decides anything. `_timeline.mp4` is kept as a+ # legacy label: those files were written before the merge and the+ # screen should not pretend they were not.+ "kind": ("timeline" if p.stem.endswith("_timeline") else "film"),+ }+ row.update(_sb_film_facts(p, probe=probe))+ out.append(row)+ out.sort(key=lambda r: r.get("at") or 0, reverse=True)+ return out+++def _sb_film_summary(board: dict) -> dict | None:+ """The newest film, cheap enough for a two-second poll.++ One directory read, one stat, and whatever the assembler wrote down. Never+ an ffprobe — a board list that shells out is a board list that stutters.+ """+ try:+ films = _sb_films(board, probe=False)+ except Exception: # noqa: BLE001+ return None+ if not films:+ return None+ f = films[0]+ return {"name": f["name"], "at": f["at"], "bytes": f["bytes"],+ "duration": f["duration"], "kind": f["kind"], "count": len(films)}+++# ===========================================================================+# THE TIMELINE EDITOR — proxies, peaks, edit.json, and the endpoints for them+# ===========================================================================+# The measurement this whole section is built around: OUR RENDERED CLIPS+# CONTAIN EXACTLY ONE KEYFRAME. The entire clip is a single GOP, because that+# is what the encoder writes for a 5 s clip at these settings, and nothing ever+# needed otherwise — the gallery plays clips from the start.+#+# A timeline does not play from the start. It seeks, constantly, and a seek+# into a single-GOP file decodes from frame zero. Measured in Chrome on this+# corpus: 235 ms median, 1266 ms p90 per seek. Against an all-intra proxy the+# same seek is 3.5 ms — two orders of magnitude, and the difference between a+# scrub and a slideshow.+#+# What that costs, measured on ten AURELIUS clips (56.25 s of 1024x576, 25.7 MB+# of source): 0.81 s of ffmpeg for all ten, 8.16 MB of proxy — 0.14 s and+# 1.45 MB per 10 s of video. Verified all-intra: 123 keyframes in a 123-frame+# proxy, against 1 in its source.+#+# So proxies are not an optimisation to add later. They are the floor the+# feature stands on, which is why `prepare` builds them before the UI is+# allowed to believe it has a timeline.+#+# `storyboard_editor.py` owns the formats and the file writes (and stays+# importable without the panel). Everything here is the part that needs the+# panel: the queue, the process group, the log pane, the HTTP seam.++_SBE_LOCK = threading.Lock()+_SBE_JOBS: dict = {} # board_id -> prepare job state+++def _sbe_import():+ """`storyboard_editor`, imported late and behind a try.++ Same rule as `_sb_plan_auto_edit`: the panel must boot on an install whose+ editor module is missing or broken, and the storyboard tab must keep+ working when it is. A failure here is a 503 on the editor routes, never a+ dead panel.+ """+ import storyboard_editor as sedit # noqa: PLC0415+ return sedit+++def _sbe_board_dir(board_id: str) -> Path:+ return storyboard.board_dir(STATE_DIR, board_id)+++def _sbe_board_clips(board: dict) -> list[dict]:+ """The shots that HAVE a rendered file, in `n` order.++ Exactly the selection `_sb_export` makes — delivery beats draft, skipped+ shots are out, a shot whose file is gone is out — because a timeline built+ from a different selection than the export's would show the user a film+ they cannot render.+ """+ out: list[dict] = []+ for s in sorted((board.get("shots") or []), key=lambda x: x.get("n") or 0):+ if not isinstance(s, dict) or s.get("status") == "skipped":+ continue+ src = s.get("final_output") or s.get("draft_output")+ if not src or not Path(str(src)).is_file():+ continue+ out.append({+ "n": s.get("n"),+ "path": str(src),+ "title": (s.get("title") or s.get("prompt") or "")[:80],+ "pass": "delivery" if s.get("final_output") else "draft",+ "duration_s": s.get("duration_s"),+ # Where the person who ordered this shot wanted it to land. Set by+ # `edit/generate`; the client uses it to drop a freshly rendered+ # clip into the hole it was generated for instead of at the end.+ "slot": s.get("edit_slot"),+ })+ return out+++def _sbe_job_state(board_id: str) -> dict:+ with _SBE_LOCK:+ job = _SBE_JOBS.get(board_id)+ return dict(job) if job else {}+++def _sbe_set(board_id: str, **kw) -> None:+ with _SBE_LOCK:+ job = _SBE_JOBS.get(board_id)+ if job is not None:+ job.update(kw)+++def _sbe_cancelled(board_id: str) -> bool:+ with _SBE_LOCK:+ return bool((_SBE_JOBS.get(board_id) or {}).get("cancel"))+++def _sbe_prepare_thread(board_id: str, music: str | None,+ target_seconds: float | None) -> None:+ """Build the proxies, the peaks and the beat grid for one board.++ Ordered deliberately: proxies FIRST, because they are what the timeline+ cannot open without, and each one that lands is immediately usable — the+ progress this reports is real progress, not a spinner. Peaks and beats are+ one decode of the soundtrack each and land at the end.++ Cancellation is checked between clips. One proxy is ~0.22 s, so `cancel`+ is honoured within about a fifth of a second, and the panel's own /stop+ still kills an ffmpeg in flight because every proxy runs through+ `run_ffmpeg_tracked` — the same tracked process group as every other+ post-process here. Nothing gets a private subprocess path.+ """+ try:+ _sbe_prepare_inner(board_id, music, target_seconds)+ except Exception as exc: # noqa: BLE001+ # A prepare that dies must leave a job the client can SEE die. A+ # thread that vanishes leaves "running" on the poll forever, which+ # reads as a hang and is the worst of the possible failures.+ push(f"[timeline] prepare failed: {exc}")+ _sbe_set(board_id, state="failed", error=str(exc), stage=None,+ finished_at=time.time())+++def _sbe_prepare_inner(board_id: str, music: str | None,+ target_seconds: float | None) -> None:+ sedit = _sbe_import()+ board = storyboard.load_storyboard(STATE_DIR, board_id)+ bdir = _sbe_board_dir(board_id)+ clips = _sbe_board_clips(board)+ # PROXIES FOLLOW THE TIMELINE, NOT JUST THE BOARD. plan_proxies prunes+ # anything not in `clips`, and the timeline may legally hold clips that are+ # not live board shots — imported ones, and clips whose shot was later+ # re-rolled. Feeding it board shots alone made Prepare DELETE the proxies+ # of exactly the clips the user just imported, so every import scrubbed at+ # source speed again after the next Prepare. (2026-08-17 review, live bug.)+ try:+ _edit = sedit.load_edit(bdir) or {}+ _have = {c["path"] for c in clips}+ for _c in (_edit.get("clips") or []):+ # A STILL AND A SLUG ARE NOT PROXY WORK. The slug has no file; the+ # still is one frame the browser paints from an <img>, so an+ # all-intra proxy of it would be an mp4 nothing ever plays — built+ # every Prepare, and counted as "wanted" so the prune has to keep+ # it forever.+ if sedit.clip_kind(_c) != "video":+ continue+ _p = str(_c.get("path") or "")+ if _p and _p not in _have and Path(_p).is_file():+ clips.append({"path": _p, "title": _c.get("title") or ""})+ _have.add(_p)+ except Exception: # noqa: BLE001+ pass+ plan = sedit.plan_proxies(clips, bdir)+ plan["dir"].mkdir(parents=True, exist_ok=True)+ total = len(plan["build"])+ _sbe_set(board_id, state="running", stage="proxies", done=0, total=total,+ reused=len(plan["reuse"]), built=0, failed=[],+ clips=len(clips))+ t0 = time.time()+ built = 0+ failed: list[dict] = []+ for i, row in enumerate(plan["build"]):+ if _sbe_cancelled(board_id):+ _sbe_set(board_id, state="cancelled", stage=None,+ finished_at=time.time())+ return+ _sbe_set(board_id, stage="proxies", done=i,+ current=Path(row["path"]).name)+ try:+ run_ffmpeg_tracked(+ sedit.proxy_cmd(FFMPEG, row["path"], row["proxy"]),+ "Timeline proxy")+ built += 1+ except Exception as exc: # noqa: BLE001+ # One unreadable clip must not cost the other eleven their+ # timeline. Record it and keep going; the edit will carry a null+ # proxy for that clip and the UI can show it as un-scrubbable.+ failed.append({"path": row["path"], "error": str(exc)})+ try:+ Path(row["proxy"]).unlink()+ except OSError:+ pass+ freed = sedit.prune_proxies(plan["stale"])+ proxy_secs = round(time.time() - t0, 3)+ _sbe_set(board_id, done=total, built=built, failed=failed,+ pruned=freed, proxy_seconds=proxy_secs)+ if built or plan["reuse"]:+ push(f"[timeline] {built} proxy(s) built in {proxy_secs:g}s, "+ f"{len(plan['reuse'])} reused, {freed} stale removed")++ # ---- the soundtrack: peaks, then the grid ---------------------------+ peaks_info = None+ beats_info = None+ # TWO errors, not one. The waveform and the beat grid are independent+ # decodes with independent failure modes, and folding them into a single+ # `music_error` meant the second one overwrote the first — so a track that+ # failed both reported only the tracker, and a UI could not tell the user+ # which half of the soundtrack it actually lost.+ peaks_err = None+ beats_err = None+ if music and Path(str(music)).is_file():+ if _sbe_cancelled(board_id):+ _sbe_set(board_id, state="cancelled", finished_at=time.time())+ return+ _sbe_set(board_id, stage="peaks")+ t1 = time.time()+ try:+ peaks = sedit.compute_peaks(music)+ sedit.save_peaks(bdir, peaks)+ peaks_info = {"count": peaks["count"],+ "duration": peaks["duration"],+ "buckets_per_second": peaks["buckets_per_second"],+ "bytes": sedit.peaks_path(bdir).stat().st_size,+ "seconds": round(time.time() - t1, 3)}+ push(f"[timeline] waveform: {peaks['count']} buckets, "+ f"{peaks_info['bytes'] / 1024:.0f} KB, "+ f"{peaks_info['seconds']:g}s")+ except Exception as exc: # noqa: BLE001+ peaks_err = f"waveform failed: {exc}"+ if not _sbe_cancelled(board_id):+ _sbe_set(board_id, stage="beats")+ try:+ import storyboard_edit as _se # noqa: PLC0415+ span = _se.audio_span_for(+ target_seconds or sum(+ float(c.get("duration_s") or 0) for c in clips) or None)+ beats_info = _se.beat_map(music, span=span)+ except Exception as exc: # noqa: BLE001+ beats_err = f"beat tracking failed: {exc}"+ _sbe_set(board_id, state="done", stage=None, finished_at=time.time(),+ peaks=peaks_info, peaks_error=peaks_err,+ beats_error=beats_err,+ music_error="; ".join(x for x in (peaks_err, beats_err) if x)+ or None,+ beats={"bpm": beats_info.get("bpm"),+ "confidence": beats_info.get("confidence"),+ "n_beats": len(beats_info.get("beats") or [])}+ if beats_info else None)++ # The prepared analysis is cached beside the board so `GET /storyboard/edit`+ # can auto-generate an edit without re-running any of it.+ try:+ cache = {"music": str(music) if music else None,+ "beats": beats_info, "built_at": int(time.time())}+ (bdir / "edit_prepare.json").write_text(+ json.dumps(cache, ensure_ascii=False), encoding="utf-8")+ except OSError:+ pass+++def _sbe_prepare_cache(board_dir: Path) -> dict:+ try:+ data = json.loads((board_dir / "edit_prepare.json").read_text(+ encoding="utf-8"))+ except (OSError, ValueError):+ return {}+ return data if isinstance(data, dict) else {}+++def _sbe_proxy_map(board_dir: Path, clips: list[dict], sedit) -> dict:+ """{source path: "proxy/<name>.mp4"} for the proxies that EXIST.++ Relative, because the client fetches it by name from+ `/storyboard/edit/proxy` and an absolute path there would be a file+ browser for the whole disk. Missing proxies are simply absent, so a clip+ with no proxy carries `null` and the UI can say so instead of showing a+ broken player.+ """+ out: dict[str, str] = {}+ d = sedit.proxy_dir(board_dir)+ for c in clips:+ name = sedit.proxy_name(c["path"])+ if (d / name).is_file():+ out[c["path"]] = f"proxy/{name}"+ return out+++def _sbe_accept_upload(filename: str, data: bytes, *,+ images: set, videos: set) -> dict:+ """One uploaded file → a pool row, or an honest refusal.++ WHERE THE BYTES LAND IS THE WHOLE DESIGN:++ * a PICTURE goes into `UPLOADS/library/manual/<date>/uploads/`, which+ `list_outputs` already walks — so it turns up in the Images source on the+ next refresh and STAYS there across restarts, with no second listing to+ keep in sync with the first;+ * a CLIP goes into `UPLOADS/timeline/`, listed by+ `GET /storyboard/edit/uploads`. NOT into OUTPUT: the gallery scans+ `OUTPUT/*.mp4`, and dropping somebody's phone clip in among the renders+ would put a file the panel never made into the one folder whose whole+ meaning is "the panel made this".++ Both roots are already inside `_sbe_pool_path_ok`, which is what makes an+ uploaded file addable by exactly the rule everything else is.++ THE FILE IS PROBED BEFORE THIS ANSWERS. A .png that is not a png would+ otherwise sit in the pool looking perfectly fine and fail at the render+ hours later, with the upload long forgotten — so it is opened here, while+ there is still a filename on screen to blame.+ """+ raw = Path(str(filename or "")).name+ suffix = Path(raw).suffix.lower()+ if suffix in images:+ kind = "still"+ dest_dir = (UPLOADS / "library" / "manual"+ / time.strftime("%Y%m%d") / "uploads")+ elif suffix in videos:+ kind = "video"+ dest_dir = UPLOADS / "timeline"+ else:+ return {"ok": False, "status": 400,+ "error": f"{suffix or 'that file'} is not a picture or a clip "+ f"this panel can read"}+ dest_dir.mkdir(parents=True, exist_ok=True)+ safe = re.sub(r"[^A-Za-z0-9._-]+", "_", raw) or ("file" + suffix)+ dest = dest_dir / f"{int(time.time() * 1000)}_{safe}"+ dest.write_bytes(data or b"")+ info = (_sb_probe_still(str(dest)) if kind == "still"+ else _sb_probe_clip(str(dest)))+ if not info:+ try:+ dest.unlink()+ except OSError:+ pass+ return {"ok": False, "status": 400,+ "error": f"{raw} is not a "+ f"{'picture' if kind == 'still' else 'clip'} this "+ f"panel can read"}+ push(f"[timeline] uploaded {dest.name} ({kind})")+ return {"ok": True, "path": str(dest), "kind": kind,+ "title": Path(raw).stem[:80],+ "w": info.get("w"), "h": info.get("h"),+ "duration_s": (round(float(info.get("duration") or 0), 3)+ if kind == "video" else None)}+++def _sbe_pool_path_ok(path: str) -> bool:+ """Is this a file the Editor is allowed to put on a timeline?++ The pool draws from three places and all three are the panel's own: the+ outputs gallery (OUTPUT), the boards' folders (STATE_DIR), and — since+ stills — the image library (UPLOADS/library/manual, where the image queue+ worker drops every render). Anything else — a path typed into a request, a+ symlink out of the tree — is refused here rather than at the ffmpeg that+ would otherwise read it. Resolved first, so `..` cannot walk out of any+ root.++ UPLOADS is the same root `/image` already serves from, which is what makes+ a still previewable and addable by the same rule.+ """+ try:+ target = Path(str(path)).resolve()+ except OSError:+ return False+ if not target.is_file():+ return False+ for root in (OUTPUT, STATE_DIR, UPLOADS):+ try:+ if target.is_relative_to(Path(root).resolve()):+ return True+ except OSError: # noqa: PERF203+ continue+ return False+++def _sbe_proxy_now(board_dir: Path, paths: list[str], sedit) -> dict:+ """Build proxies for EXACTLY these paths, and prune nothing.++ The Prepare job is the wrong tool for one clip: it re-plans the whole+ board, and its `stale` set would delete the proxies of everything the+ timeline holds that the board does not. This is the scoped version — the+ same `proxy_cmd`, the same tracked process group, one clip at a time, and+ `plan_proxies`' own reuse check so a clip that already has a proxy costs+ nothing.++ Synchronous on purpose: one proxy is ~0.22 s measured, and a click that+ lands a scrubbable clip is worth a fifth of a second more than a spinner+ and a poll.+ """+ rows = [{"path": q} for q in paths if q]+ if not rows:+ return {"built": 0, "reused": 0, "failed": []}+ plan = sedit.plan_proxies(rows, board_dir)+ plan["dir"].mkdir(parents=True, exist_ok=True)+ built, failed = 0, []+ for row in plan["build"]:+ try:+ run_ffmpeg_tracked(+ sedit.proxy_cmd(FFMPEG, row["path"], row["proxy"]),+ "Timeline proxy")+ built += 1+ except Exception as exc: # noqa: BLE001+ failed.append({"path": row["path"], "error": str(exc)})+ try:+ Path(row["proxy"]).unlink()+ except OSError:+ pass+ return {"built": built, "reused": len(plan["reuse"]), "failed": failed}+++def _sbe_auto_edit(board: dict, *, music: str | None = None,+ target_seconds: float | None = None,+ min_shot: float = 1.5,+ max_shot: float | None = None) -> dict:+ """Derive an `edit.json` from the board with the auto-editor.++ This is the ONLY place an edit is invented. Every other path either reads+ the file or saves what a human sent, which is what makes "the auto-edit+ overwrote my arrangement" impossible rather than unlikely.+ """+ sedit = _sbe_import()+ import storyboard_edit as _se # noqa: PLC0415+ bdir = _sbe_board_dir(board["id"])+ clips = _sbe_board_clips(board)+ cache = _sbe_prepare_cache(bdir)+ music = music or cache.get("music")+ beats = cache.get("beats") if (music and cache.get("music") == music) else None+ if not clips:+ return sedit.edit_from_plan([], board_id=board["id"])+ audio_arg = beats or (music if music and Path(str(music)).is_file() else None)+ plan = _se.plan_cut([c["path"] for c in clips], audio=audio_arg,+ target_seconds=target_seconds, min_shot=min_shot,+ max_shot=max_shot)+ if beats is None and audio_arg and not isinstance(audio_arg, dict):+ # plan_cut fitted a grid we did not have cached; recover it for the+ # timeline rather than making the client ask for it separately.+ try:+ beats = _se.beat_map(music, span=_se.audio_span_for(+ target_seconds or _se.plan_total(plan)))+ except Exception: # noqa: BLE001+ beats = None+ audio = None+ if music and Path(str(music)).is_file():+ peaks = sedit.load_peaks(bdir)+ # The track's length is what a waveform axis is drawn against, so it+ # must be present whether or not the peaks have been built yet —+ # otherwise the ruler has no scale until `prepare` finishes.+ dur = (peaks or {}).get("duration")+ if dur is None:+ dur = (_se.probe_media(music) or {}).get("duration")+ audio = {"path": str(music), "offset": 0.0,+ "peaks": "peaks.json" if peaks else None,+ "duration": dur}+ return sedit.edit_from_plan(+ plan, board_id=board["id"], audio=audio, beats=beats,+ proxies=_sbe_proxy_map(bdir, clips, sedit),+ labels={c["path"]: f"S{(c.get('n') or 0):02d} · {c['title']}"+ for c in clips},+ settings={"target_seconds": target_seconds, "min_shot": min_shot,+ "max_shot": max_shot})+++def _sbe_relinks(board: dict, edit: dict) -> list[dict]:+ """Timeline clips still pointing at a draft whose delivery now exists.++ THE LIVE BUG THIS ANSWERS (2026-08-17 review): `_sbe_board_clips` picks+ delivery over draft, and its docstring says so — but `edit.json` freezes+ the PATH at the moment the cut was made, and nothing rewrote it. So+ "Finish keepers" rendered full-size files the film never used: the user+ waited for a delivery pass and then rendered the drafts again, silently.++ Detection only. The rewrite is one button, never automatic, because the+ arrangement is the human's — the same rule `_sbe_payload` already states.+ """+ finals: dict[str, dict] = {}+ for s in (board.get("shots") or []):+ if not isinstance(s, dict):+ continue+ draft, final = s.get("draft_output"), s.get("final_output")+ if not draft or not final or draft == final:+ continue+ if not Path(str(final)).is_file():+ continue+ finals[str(draft)] = {"to": str(final), "n": s.get("n"),+ "title": (s.get("title") or s.get("prompt")+ or "")[:80]}+ out: list[dict] = []+ for c in (edit.get("clips") or []):+ if not isinstance(c, dict):+ continue+ hit = finals.get(str(c.get("path") or ""))+ if hit:+ out.append({"id": c.get("id"), "path": str(c.get("path")),+ **hit})+ return out+++def _sbe_payload(board: dict, edit: dict) -> dict:+ """The editor's read shape. One object, everything a timeline needs."""+ sedit = _sbe_import()+ bdir = _sbe_board_dir(board["id"])+ clips = _sbe_board_clips(board)+ # Only the clips that ARE a video file can be `placed` for proxy purposes:+ # a slug has no path at all and a still is painted by an <img>, so putting+ # either in this set would ask `_sbe_proxy_map` to fingerprint the string+ # "None".+ placed = {str(c.get("path")) for c in (edit.get("clips") or [])+ if isinstance(c, dict) and sedit.clip_kind(c) == "video"+ and c.get("path")}+ # THE MAP FOLLOWS THE TIMELINE, NOT JUST THE BOARD — the same rule+ # `_sbe_prepare_inner` follows when it decides what to build. A timeline+ # may legally hold clips that are not board shots (anything added from the+ # media pool, and clips whose shot was later re-rolled), and a map built+ # from board shots alone answered `null` for exactly those: the proxy was+ # on disk, freshly built, and the payload said there was none, so the+ # player fell back to the source and the clip scrubbed at 235 ms a seek.+ proxies = _sbe_proxy_map(+ bdir, clips + [{"path": q} for q in sorted(placed)+ if q not in {c["path"] for c in clips}], sedit)+ # Refresh every clip's proxy pointer on the way out: a proxy built after+ # the edit was saved must not need a re-save to become visible, and one+ # that was pruned must not leave a dead URL behind.+ for c in (edit.get("clips") or []):+ if isinstance(c, dict):+ c["proxy"] = proxies.get(str(c.get("path")))+ return {+ "ok": True,+ "id": board["id"],+ "title": board.get("title") or "",+ # WHICH SESSION OWNS THE SNAPSHOT LANE. Claimed by whoever loaded+ # last, because that is the tab the person is looking at; an older one+ # is told rather than merged. See docs/EDITOR_SAVE_MODEL.md §5.+ "session": sedit.current_session(bdir),+ "edit": edit,+ "duration": sedit.edit_duration(edit),+ "gaps": sedit.edit_gaps(edit),+ # ...and the same kind of answer for the SOUND: which unlinked strips+ # no longer line up with their own picture, and where each one goes+ # back to. Never an error — a J-cut is a deliberate drift — but the+ # panel cannot flag what the server does not say.+ "sync": sedit.edit_sync_flags(edit),+ # Board clips that are NOT on the timeline — a shot rendered after the+ # edit was saved, or one generated into a gap that has just landed.+ # Never auto-inserted: the arrangement is the human's, and a server+ # that quietly appends to it is a server that moves their cuts.+ "unplaced": [dict(c, proxy=proxies.get(c["path"])) for c in clips+ if c["path"] not in placed],+ # EVERY clip this film has, placed or not, for the media pool. The+ # pool is a place to browse from, so it shows what is already on the+ # track as well — marked, so adding it twice is a choice and not an+ # accident.+ "clips": [dict(c, proxy=proxies.get(c["path"]),+ placed=c["path"] in placed) for c in clips],+ # Shots finished since this cut was made. See _sbe_relinks.+ "relink": _sbe_relinks(board, edit),+ "prepare": _sbe_job_state(board["id"]),+ # DRAFTS RIDE ON EVERY READ. The panel has to know which document it is+ # looking at and whether a crash left something newer behind, and both+ # are cheap enough that a second round trip to learn them would be the+ # only slow part of opening a film.+ "drafts": sedit.list_drafts(bdir),+ "active_draft": sedit.load_draft_index(bdir)["active"],+ "backup": sedit.pending_backup(bdir),+ "proxy_url": "/storyboard/edit/proxy?id=" + board["id"] + "&name=",+ }class CharacterRequestError(ValueError):@@ -15602,6 +18351,21 @@ def run_image_job_inner(job: dict) -> None:_TRAIN_LOCK = threading.Lock()+# Abort signatures worth naming in a training failure. Same family the render+# helper's _METAL_TIMEOUT_RX watches, plus the bare C++ abort line the trainer+# prints on its way out — training runs in its own process and never saw any of+# this mitigation (#61).+_TRAIN_ABORT_RX = re.compile(+ r"kIOGPUCommandBufferCallbackErrorTimeout"+ r"|kIOGPUCommandBufferCallbackErrorImpactingInteractivity"+ r"|Caused GPU Timeout Error"+ r"|Impacting Interactivity"+ r"|libc\+\+abi.*terminating"+ r"|Command buffer execution failed",+ re.IGNORECASE,+)++def run_train_job_inner(job: dict) -> None:"""Run a Train Character job. Reads the dataset that /train/upload builtunder state/train_character/<train_job_id>/, writes a job-spec JSON the@@ -15620,6 +18384,11 @@ def run_train_job_inner(job: dict) -> None:actionable error in the job's `error` field — the job card stillshows up in Recent, just marked failed."""+ _train_watchdog_seen = False # set when the trainer logs a GPU-abort signature (#61)+ # The trainer's own verdict on whether the adapter it wrote can move the+ # model at all. "unknown" until it says — an older trainer emits nothing+ # and must not be reported as weak for staying silent.+ train_verdict = "unknown"p = job["params"]try:train_job_id = _safe_job_id(p.get("train_job_id") or "")@@ -15913,6 +18682,37 @@ def run_train_job_inner(job: dict) -> None:push(f"[train] step {last_step}/{total_steps} loss={last_loss}")elif evt == "log":push(f"[train] {payload.get('msg', '')}")+ elif evt == "adapter_strength":+ # A GREEN TALLY WAS NEVER PROOF THE FILE COULD DO+ # ANYTHING. A LoRA can train to completion, write a+ # perfectly valid safetensors, load without a warning and+ # change NOTHING in the picture — because the deltas it+ # learned are numerically too small to move the model.+ # Every gate we had said "done"; only the render said+ # otherwise, hours later, on the owner's eye.+ #+ # The trainer measures the adapter's own delta RMS against+ # a floor and says so. Surfacing it here is the difference+ # between a training run that reports success and one that+ # reports the truth.+ med = payload.get("delta_rms_median")+ mx = payload.get("delta_rms_max")+ verdict = str(payload.get("verdict") or "unknown")+ carrying = payload.get("carrying_modules")+ mods = payload.get("modules")+ bits = [f"median={med}", f"max={mx}"]+ if carrying is not None and mods is not None:+ bits.append(f"{carrying}/{mods} modules carrying")+ if payload.get("floor") is not None:+ bits.append(f"floor={payload.get('floor')}")+ push(f"[train] adapter strength: delta_rms "+ f"{' · '.join(bits)} ({verdict})")+ train_verdict = verdict+ if verdict != "ok":+ push("[train] WARNING: this adapter may not visibly "+ "change anything it is applied to. Train longer, "+ "raise the rank, or check the captions — a file "+ "that loads is not a file that works.")elif evt == "checkpoint":push(f"[train] checkpoint → {payload.get('path', '?')}")elif evt == "done":@@ -15921,12 +18721,34 @@ def run_train_job_inner(job: dict) -> None:push(f"[train] {line}")else:push(f"[train] {line}")+ # The trainer dies by SIGABRT when macOS kills its GPU command+ # buffer, and `code -6` on its own tells the user nothing. Watch+ # the same signatures the render helper watches (#61).+ if not _train_watchdog_seen and _TRAIN_ABORT_RX.search(line or ""):+ _train_watchdog_seen = Truerc = proc.wait()proc = Nonewith LOCK:STATE["pid"] = NoneSTATE["train_pgid"] = Noneif rc != 0:+ # -6 is SIGABRT. With a watchdog signature in the log it is macOS+ # killing the GPU command buffer, not our code faulting — and the+ # lever is the canvas, not the preset. Reported in #61: 576x576+ # aborted on quick AND medium while 512x512 trained fine, which is+ # canvas-shaped, not preset-shaped.+ if rc == -6 and _train_watchdog_seen:+ raise RuntimeError(+ "macOS killed the training GPU command buffer (Metal "+ "watchdog, SIGABRT). This is the canvas, not the preset — "+ "512x512 is the shape that survives on machines where "+ "576x576 aborts. Retry at 512x512, and close other GPU "+ "apps. See Logs for the raw abort.")+ if rc == -6:+ raise RuntimeError(+ f"training aborted (SIGABRT, code {rc}). No Metal-watchdog "+ "signature was logged, so this is a crash rather than a "+ "GPU timeout — please attach the Logs tail to an issue.")raise RuntimeError(f"training exited with code {rc} — see Logs for stack trace")finally:@@ -15987,6 +18809,11 @@ def run_train_job_inner(job: dict) -> None:"created_at": time.time(),"elapsed_sec": elapsed,"source": sidecar_source,+ # THE ONLY FIELD THAT SAYS WHETHER THE FILE CAN DO ANYTHING. Written+ # so the library can warn BEFORE somebody spends a render finding out.+ # Absent on runs by an older trainer, which is why "unknown" is not a+ # warning — silence is not weakness.+ "adapter_strength": {"verdict": train_verdict},}try:final_sidecar_path.write_text(json.dumps(sidecar, indent=2), encoding="utf-8")@@ -16013,6 +18840,17 @@ def run_train_job_inner(job: dict) -> None:except OSError as e:push(f"[train] warn: could not copy avatar: {e}")+ # A TRAINING RUN THAT PRODUCED AN INERT ADAPTER IS NOT A SUCCESS, and+ # "done" is the one word that would hide it. The file is kept — it may+ # still be worth something at a higher strength — but the job says what it+ # is, in the place the user is already looking when it finishes.+ if train_verdict not in ("ok", "unknown"):+ job["warning"] = (+ f"The adapter came out weak ({train_verdict}): its learned deltas "+ f"may be too small to visibly change anything. Train longer, raise "+ f"the rank, or check the captions.")+ push("[train] finished with a WARNING — see the adapter strength line "+ "above. The file was kept.")job["output_path"] = str(final_lora_path)job["raw_path"] = str(final_lora_path)p["elapsed_seconds"] = elapsed@@ -20097,16 +22935,21 @@ class Handler(BaseHTTPRequestHandler):# server-side and ship it back as a single JSON payload. Used to# pre-fill the description textarea in openBugModal().try:- ver = _read_local_version() or "unknown"- sha = _VERSION_STATE.get("local_short") or ""- branch = ""- try:- branch = subprocess.run(- ["git", "rev-parse", "--abbrev-ref", "HEAD"],- capture_output=True, text=True, timeout=2, cwd=str(ROOT),- ).stdout.strip()- except Exception: # noqa: BLE001- pass+ # The build the PROCESS is running, never the working tree.+ # A report filed from a panel that has not been restarted has+ # to name the code that produced the bug — and when disk has+ # moved on, say so in the report, because that is frequently+ # the bug ("the fix didn't work" from a panel still serving+ # the code from before the fix).+ _boot = boot_build_stamp()+ _live = get_version_state()+ ver = _boot["version"] or _read_local_version() or "unknown"+ sha = _boot["short"] or ""+ branch = _boot["branch"] or ""+ if _live.get("stale_process"):+ sha = (f"{sha or '?'} (RUNNING; disk is at "+ f"{_live.get('disk_short') or '?'} — panel not "+ f"restarted since the update)")mac_ver = ""try:mac_ver = subprocess.run(@@ -20424,6 +23267,20 @@ class Handler(BaseHTTPRequestHandler):if parsed.path == "/storyboard/list":self._json({"ok": True, "boards": _sb_all_summaries()})return+ # The finished films, for the screen that shows them. Reads the folder+ # the assemblers write into; makes nothing, changes nothing.+ if parsed.path == "/storyboard/films":+ bid = (parse_qs(parsed.query).get("id") or [""])[0].strip()+ try:+ board = storyboard.load_storyboard(STATE_DIR, bid)+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False, "error": str(exc)}, 404)+ return+ d = _sb_film_dir(board)+ self._json({"ok": True, "dir": str(d),+ "dir_short": _sb_display_path(d),+ "films": _sb_films(board)})+ returnif parsed.path == "/storyboard/get":bid = (parse_qs(parsed.query).get("id") or [""])[0].strip()try:@@ -20442,6 +23299,14 @@ class Handler(BaseHTTPRequestHandler):self._json(_sb_payload(board))return+ # ---- Timeline editor reads -------------------------------------+ # Its own method rather than four more branches in a 3,000-line+ # do_GET: these routes have to be reachable from a test without+ # standing up a socket, and a route nobody can test is a route that+ # regresses quietly.+ if self._storyboard_edit_get(parsed):+ return+# Progress poll for the one-click sample-character download.if parsed.path == "/characters/download-sample/status":with _sample_char_lock:@@ -21059,6 +23924,233 @@ class Handler(BaseHTTPRequestHandler):# normalise it, reply with the full payload the plan screen repaints from).# Called from do_POST AFTER the body/form parse — the routes below read# both, and /storyboard/save posts JSON rather than a form.+ def _storyboard_edit_get(self, parsed) -> bool:+ """The timeline editor's SEVEN read routes. Every branch returns True.++ `edit` is the arrangement, `status` is the prepare job, `peaks` is the+ waveform (fetched once — it is a few hundred KB and must never ride on+ a poll), `uploads` is the pool's list of clips somebody brought with+ them, `drafts` is the index plus any crash offer, `versions` is the+ history metadata, and `proxy` is a video file and therefore goes+ through the SAME range-request path the gallery uses. That last one is+ not cosmetic: Safari will not seek a `<video>` whose server does not+ answer 206, so a proxy served as a plain 200 would undo the entire+ reason proxies exist.++ TRUE == HANDLED, on EVERY branch — do_GET reads the answer as "did+ anybody serve this" and falls through to send_error(404) when it is+ false. `uploads` used to end in a bare `return`, so a request that had+ already been answered in full got a second, complete 404 response+ written onto the same socket behind it. It survives only because this+ handler never sets protocol_version and HTTP/1.0 closes the+ connection; turning on keep-alive would make those bytes the head of+ the next response. An enumeration in a docstring stops being+ exhaustive silently, which is how a route ends up in neither this list+ nor the contract — so the rule is stated once, above, and applies to+ all of them.+ """+ path = parsed.path+ if not path.startswith("/storyboard/edit"):+ return False+ q = parse_qs(parsed.query)+ bid = (q.get("id") or [""])[0].strip()++ if path == "/storyboard/edit/status":+ self._json({"ok": True, "id": bid, "prepare": _sbe_job_state(bid)})+ return True++ if path == "/storyboard/edit/proxy":+ name = (q.get("name") or [""])[0].strip()+ # The name is a BASENAME the server itself minted, so anything+ # that is not one is a probe, not a typo. Rejecting on the SHAPE+ # (rather than resolving and hoping) keeps the containment check+ # from being the only thing between this route and the disk.+ if not bid or not re.fullmatch(r"[A-Za-z0-9._-]{1,120}\.mp4", name):+ self.send_error(400)+ return True+ try:+ sedit = _sbe_import()+ except Exception: # noqa: BLE001+ self.send_error(503)+ return True+ root = sedit.proxy_dir(_sbe_board_dir(bid)).resolve()+ try:+ target = (root / name).resolve()+ except OSError:+ self.send_error(400)+ return True+ if not target.is_relative_to(root) or not target.is_file():+ self.send_error(404)+ return True+ self._serve_video_with_range(target)+ return True++ try:+ sedit = _sbe_import()+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False,+ "error": f"timeline editor unavailable: {exc}"}, 503)+ return True++ if path == "/storyboard/edit/peaks":+ # SCOPED TO THE TRACK THE TIMELINE ACTUALLY CARRIES. A waveform+ # cached from the soundtrack that was swapped out is a wrong+ # duration on the music strip, and the strip has no way to know.+ want_track = ""+ if bid:+ try:+ cur = sedit.load_edit(_sbe_board_dir(bid)) or {}+ want_track = str((cur.get("audio") or {}).get("path") or "")+ except Exception: # noqa: BLE001+ want_track = ""+ peaks = (sedit.load_peaks(_sbe_board_dir(bid), path=want_track)+ if bid else None)+ if not peaks:+ self._json({"ok": False,+ "error": "no waveform yet — run "+ "/storyboard/edit/prepare"}, 404)+ return True+ self._json(peaks)+ return True++ if path == "/storyboard/edit/clip-peaks":+ # ONE SOURCE, ON DEMAND, CACHED. Computed the first time a strip+ # asks and read from disk forever after — the same `compute_peaks`+ # the bed uses, so there is one waveform implementation and not a+ # second one that could disagree with it.+ want = (q.get("path") or [""])[0]+ if not bid or not want:+ self._json({"ok": False, "error": "need id and path"}, 400)+ return True+ try:+ data = sedit.clip_peaks(_sbe_board_dir(bid), want)+ except sedit.EditError as exc:+ # A take with no audio track is a FACT, not a failure: the lane+ # already draws that state and must not show an error for it.+ self._json({"ok": False, "silent": True,+ "error": str(exc)}, 404)+ return True+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False, "error": str(exc)}, 500)+ return True+ self._json(data)+ return True++ if path == "/storyboard/edit/uploads":+ # The clips somebody brought with them. Images need no route —+ # they land in the library the gallery already walks — but a video+ # is deliberately kept out of OUTPUT (see the upload handler), so+ # this is how the pool finds it. Newest first, capped, and every+ # row is a file that exists right now.+ root = UPLOADS / "timeline"+ rows = []+ if root.is_dir():+ exts = {".mp4", ".mov", ".m4v", ".webm"}+ try:+ found = [p for p in root.iterdir()+ if p.is_file() and p.suffix.lower() in exts]+ except OSError:+ found = []+ for p in sorted(found, key=lambda q: q.stat().st_mtime,+ reverse=True)[:200]:+ # The stored name is `<unix-ms>_<their name>`; showing the+ # stamp would be showing them our bookkeeping.+ label = re.sub(r"^\d{10,}_", "", p.name)+ rows.append({"path": str(p), "name": label,+ "mtime": int(p.stat().st_mtime)})+ self._json({"ok": True, "uploads": rows})+ return True++ if path == "/storyboard/edit/drafts":+ if not bid:+ self._json({"ok": False, "error": "no film"}, 400)+ return True+ # The same existence check every other editor route takes. Without+ # it `?id=../../..` walks out of state/storyboards/ and this route+ # reports on whatever it finds — read-only and same-origin, but it+ # is the one containment rule the rest of this file keeps without+ # exception.+ try:+ storyboard.load_storyboard(STATE_DIR, bid)+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False, "error": str(exc)}, 404)+ return True+ bdir = _sbe_board_dir(bid)+ self._json({"ok": True, "id": bid,+ "active": sedit.load_draft_index(bdir)["active"],+ "drafts": sedit.list_drafts(bdir),+ "backup": sedit.pending_backup(bdir)})+ return True++ if path == "/storyboard/edit/versions":+ # METADATA ONLY. The picker shows what each entry WOULD restore —+ # its name, its revision, when it was kept, how many clips and how+ # long — and nothing in this list is big enough to make opening the+ # panel a download. The documents themselves are read once, by+ # `restore`, on the user's word.+ if not bid:+ self._json({"ok": False, "error": "no film"}, 400)+ return True+ try:+ storyboard.load_storyboard(STATE_DIR, bid)+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False, "error": str(exc)}, 404)+ return True+ self._json({"ok": True, "id": bid,+ "keep": sedit.EDIT_HISTORY_KEEP,+ "versions": sedit.list_history(_sbe_board_dir(bid))})+ return True++ if path != "/storyboard/edit":+ return False++ try:+ board = storyboard.load_storyboard(STATE_DIR, bid)+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False, "error": str(exc)}, 404)+ return True+ bdir = _sbe_board_dir(bid)+ try:+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ # A corrupt edit is NEVER silently replaced with a fresh+ # auto-edit — that would throw away the arrangement it is a+ # broken copy of. Say so, and let a human decide.+ self._json({"ok": False, "error": str(exc), "corrupt": True}, 500)+ return True+ fresh = edit is None+ if fresh:+ # The auto-edit runs ONCE, here, and is persisted — it decodes+ # every clip in the board and a read route that did that on every+ # poll would be unusable. Every later GET is a file read.+ try:+ target = float((q.get("target_seconds") or [""])[0] or 0) or None+ except ValueError:+ target = None+ music = (q.get("music") or [""])[0].strip() or None+ edit = _sbe_auto_edit(board, music=music, target_seconds=target)+ try:+ # THE MACHINE'S OWN CUT. It lands in the automatic lane so a+ # user walking back through his work meets his decisions+ # first, not the auto-editor's.+ sedit.save_edit(bdir, edit, origin="auto")+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False,+ "error": f"auto-edit refused: {exc}"}, 500)+ return True+ # A READ CLAIMS NOTHING. This used to claim the board for whoever+ # loaded last, which meant a page LOAD — a second window, a headless+ # browser, an agent reading the film, a preview — took the snapshot+ # lane away from the tab the person was actually cutting in, and that+ # tab then stopped writing snapshots. Opening a film is not editing it.+ # The claim is taken by the write path now; see the block above+ # `SESSION_STALE_AFTER` in storyboard_editor.py.+ payload = _sbe_payload(board, edit)+ payload["generated"] = fresh+ self._json(payload)+ return True+def _storyboard_post(self, action: str, body: str, form: dict) -> None:def f(name: str, default: str = "") -> str:v = form.get(name, default)@@ -21157,9 +24249,26 @@ class Handler(BaseHTTPRequestHandler):board["concept"] = conceptboard["style"] = f("style", "")board["must"] = must+ # PATCH, never overwrite. Re-plan and Try again rebuild this+ # form by hand and send neither `locations` nor `wardrobe`, so+ # unconditional assignment ERASED both on the first re-plan —+ # the exact continuity drift the fields were built to prevent,+ # returned as data loss. An absent field keeps the board's+ # value; only a field the client actually sent replaces it.+ # (Confirmed by the 2026-08-17 UX review, red-team verified.)+ if "locations" in form:+ board["locations"] = _sb_parse_locations(f("locations", ""))board["shots_target"] = shots_n+ # One wardrobe line for the whole film, attached to the cast+ # member rather than repeated per shot — the same fix locations+ # are, one axis over. Repeating it per shot is what drifts.+ _prev_ward = {c.get("id"): c.get("wardrobe") or ""+ for c in (board.get("cast") or [])}+ wardrobe = (f("wardrobe", "") if "wardrobe" in form else None)board["cast"] = [{"id": c.get("id"),- "trigger": c.get("trigger") or c.get("id")}+ "trigger": c.get("trigger") or c.get("id"),+ "wardrobe": (wardrobe if wardrobe is not None+ else _prev_ward.get(c.get("id"), ""))}for c in chars]board.setdefault("policy", _sb_policy_for(get_settings().get("storyboard_draft_quality", "quick"),@@ -21177,6 +24286,7 @@ class Handler(BaseHTTPRequestHandler):args=(bid, {"concept": concept, "n_shots": shots_n,"style": board["style"], "characters": chars,"must": must, "feedback": notes or None,+ "locations": board.get("locations") or [],"engine_mode": emode},previous if notes else None))with _SB_LOCK:@@ -21392,13 +24502,24 @@ class Handler(BaseHTTPRequestHandler):removed = before - len(STATE["queue"])QUEUE_COND.notify_all()persist_queue()+ # ...and cancel the shot ALREADY RENDERING, through the panel's+ # own /stop path. Dropping the queue alone left an H3 shot+ # burning the GPU for another 20 minutes after the user had+ # been told the film stopped.+ cancelled = _sb_cancel_running_shot(mine)for s in (board.get("shots") or []):if isinstance(s, dict) and s.get("status") in ("queued",):s["status"] = "pending"+ # The cancelled shot is deliberately NOT rewritten here. The+ # worker is still unwinding the kill; its job goes terminal a+ # moment later and _sb_reconcile() folds that verdict onto the+ # shot on the next read. Guessing the outcome now would race it.storyboard.save_storyboard(STATE_DIR, board)push(f"[storyboard] stopped — {removed} queued shot(s) removed; "- f"the shot in flight finishes")- self._json({"ok": True, "removed": removed})+ + (f"cancelled the shot in flight ({cancelled})"+ if cancelled else "nothing was rendering"))+ self._json({"ok": True, "removed": removed,+ "cancelled": cancelled})returnif action == "replan-shots":@@ -21437,6 +24558,7 @@ class Handler(BaseHTTPRequestHandler):"style": board.get("style") or "","characters": chars,"must": board.get("must") or [],+ "locations": board.get("locations") or [],"feedback": "\n".join(notes),"engine_mode": board.get("engine_mode") or "auto","reroll_ns": ns},@@ -21498,23 +24620,101 @@ class Handler(BaseHTTPRequestHandler):"title": board.get("title") or ""})return+ if action == "import-shots":+ # A BOARD IS A TIMELINE, ONE TO ONE, and that is the whole+ # problem this fixes. The moment coverage for a film gets+ # rendered as a second board — B-roll, pickups, alternates, a+ # re-plan — its clips are unreachable from the first board's+ # timeline. There was no way to move a clip between films and+ # no way to cut with both, so the answer to "I have clips in+ # two projects" was "render them again".+ #+ # This is the media-pool answer at the size that fits here: pull+ # the shots you want into the film you are cutting. The clips+ # are NOT copied on disk — a shot carries the path to its output,+ # so an import is a reference and costs nothing but a JSON edit.+ bid = f("id", "")+ src_id = f("from", "")+ if not bid or not src_id or bid == src_id:+ self._json({"ok": False,+ "error": "import needs a different source film"}, 400)+ return+ # A RUNNING RENDER OWNS THE BOARD FILE. It writes each shot's+ # status and output back as the shot lands, so an import that+ # read the board a second earlier would save a copy with those+ # writes missing — losing rendered clips, silently, at the exact+ # moment somebody is trying to collect them. Verified live: an+ # import during a four-shot render happened to survive, which is+ # luck, not a design.+ with _SB_LOCK:+ live = _SB_RENDERS.get(bid)+ busy = bool(live and not live.get("stop"))+ if busy:+ self._json({"ok": False, "busy": True,+ "error": "This film is rendering. Importing now could "+ "drop a clip that just finished — try again "+ "when it stops."}, 409)+ return+ board = load(bid)+ src = load(src_id)+ if not src:+ self._json({"ok": False, "error": f"no film {src_id!r}"}, 404)+ return+ want = {int(x) for x in (f("only", "") or "").split(",")+ if x.strip().lstrip("-").isdigit()}+ brought, skipped = _sb_import_shots(board, src, want or None)+ _sb_normalize(board)+ storyboard.save_storyboard(STATE_DIR, board)+ self._json({"ok": True, "id": bid, "imported": brought,+ "skipped": skipped,+ "shots": len(board.get("shots") or [])})+ return+# ---- export / housekeeping -----------------------------------if action == "export":board = load(f("id", ""))- self._json(_sb_export(board))+ # Opt-in, and only from an explicit request. Absent these the+ # export is byte-for-byte the one that shipped: whole clips,+ # clip audio, no analysis run at all.+ auto = f("auto_edit", "") in ("1", "true", "on", "yes")+ music = f("music", "") or None+ if music and not Path(music).is_file():+ self._json({"ok": False,+ "error": f"no soundtrack at {music}"}, 400)+ return+ try:+ target = float(f("target_seconds", "") or 0) or None+ except ValueError:+ target = None+ # The soundtrack the CUT was made with, when there is a cut.+ # Export posted `id` and nothing else, so a film with a score+ # in the Editor came out silent from this door — one screen+ # apart, two different films. `_sbe_render_edit` reads the+ # edit's own audio when these are empty.+ mmode = f("music_mode", "") or None+ self._json(_sb_export(board, auto_edit=auto, music=music,+ music_mode=mmode, target_seconds=target))returnif action == "reveal":board = load(f("id", ""))- title = board.get("title") or "storyboard"- day = time.strftime("%Y-%m-%d",- time.localtime(board.get("created_at") or time.time()))- d = OUTPUT / "storyboards" / f"{day}_{_sb_slug(title, 6)}"+ d = _sb_film_dir(board)if not d.is_dir():self._json({"ok": False, "error": "nothing exported yet"}, 404)return+ # `name` reveals ONE file inside that folder, selected in+ # Finder — the film the user is looking at, not the folder it+ # is buried in. Constrained to a plain filename that resolves+ # inside the board's own directory, so it can never become an+ # argument to `open` pointing somewhere else.+ cmd = ["open", str(d)]+ name = f("name", "")+ if name and re.fullmatch(r"[A-Za-z0-9._-]{1,120}", name):+ cand = d / name+ if cand.is_file():+ cmd = ["open", "-R", str(cand)]try:- subprocess.Popen(["open", str(d)])+ subprocess.Popen(cmd)except Exception as exc: # noqa: BLE001self._json({"ok": False, "error": str(exc)}, 500)return@@ -21535,6 +24735,842 @@ class Handler(BaseHTTPRequestHandler):self._json({"ok": True})return+ # ---- the timeline editor -------------------------------------+ # Same shapes, same auth, same error style as everything above.+ # The one structural difference is that these read and write+ # `edit.json`, never `storyboard.json` — except `edit/generate`,+ # which adds a SHOT, because a shot to be rendered is intent and+ # intent lives on the board.+ if action.startswith("edit/"):+ try:+ sedit = _sbe_import()+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False,+ "error": f"timeline editor unavailable: {exc}"},+ 503)+ return+ sub = action[len("edit/"):]++ if sub == "prepare":+ bid = f("id", "")+ board = load(bid)+ music = f("music", "") or None+ if music and not Path(music).is_file():+ self._json({"ok": False,+ "error": f"no soundtrack at {music}"}, 400)+ return+ try:+ target = float(f("target_seconds", "") or 0) or None+ except ValueError:+ target = None+ with _SBE_LOCK:+ live = _SBE_JOBS.get(bid)+ if live and live.get("state") == "running":+ self._json({"ok": False, "busy": True,+ "error": "Already preparing this "+ "timeline.",+ "prepare": dict(live)}, 409)+ return+ _SBE_JOBS[bid] = {"id": bid, "state": "running",+ "stage": "start", "cancel": False,+ "done": 0, "total": 0,+ "started_at": time.time(),+ "music": music}+ th = threading.Thread(+ target=_sbe_prepare_thread, daemon=True,+ name=f"phos-sbe-prep-{bid}", args=(bid, music, target))+ th.start()+ self._json({"ok": True, "id": bid,+ "prepare": _sbe_job_state(bid)}, 202)+ return++ if sub == "overlay-key":+ # THE OVERLAY LANE'S DOOR, and only the overlay lane's. A+ # still on the PICTURE lane legitimately keeps its black —+ # it is the whole frame there, nothing is underneath it —+ # so this runs on the way to V2 and nowhere else.+ path = f("path", "")+ if not path or not _sbe_pool_path_ok(path):+ self._json({"ok": False,+ "error": "that image is not in this "+ "panel's outputs"}, 400)+ return+ rep = _sbe_plate_report(path)+ out = {"ok": True, "keyed": False, "path": path,+ "original": path, "why": rep.get("why") or "",+ "measured": {k: v for k, v in rep.items()+ if k not in ("ok", "plate", "why")}}+ if not rep.get("plate"):+ self._json(out)+ return+ made = _sbe_key_plate(path)+ if not made.get("ok"):+ # A KEY THAT COULD NOT BE WRITTEN IS NOT AN ERROR THE+ # USER HAS TO ANSWER. The card still goes on the lane+ # exactly as it arrived; it just arrives plated.+ out["why"] = made.get("error") or "could not be written"+ self._json(out)+ return+ push(f"[timeline] keyed the black backdrop off "+ f"{Path(path).name}")+ out.update({"keyed": True, "path": made["path"],+ "name": re.sub(r"^\d{10,}_", "",+ Path(path).name)})+ self._json(out)+ return++ if sub == "add-clip":+ # THE MEDIA POOL'S ONE VERB. Everything the pool offers —+ # this film's own shots, a clip from another film, anything+ # in the generations gallery — arrives here as a path, and+ # leaves with a proxy already built. That last part is the+ # point: a clip added without one scrubs at source speed+ # (235 ms a seek, measured) and reads as the editor being+ # broken. The client places it on the TRACK and saves, so+ # the next Prepare keeps the proxy (pruning follows+ # timeline ∪ board).+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ src_id = f("from", "")+ only = f("only", "")+ path = f("path", "")+ title = f("title", "")+ n = None+ # A STILL SHORT-CIRCUITS ALL OF IT. It is not a board shot+ # (no prompt, no seed, nothing rendered it), it needs no+ # proxy (a browser paints an <img> exactly and instantly),+ # and it has no source duration — the hold is whatever slot+ # the timeline gives it. What it DOES need is the same+ # containment check every other path gets, which is the+ # only reason it comes through the server at all.+ # THE SERVER DECIDES WHAT A FILE IS. The client used to+ # be the only thing that knew, and the first time a pool+ # row reached this route without its `kind` — an upload+ # dragged onto the track — the picture became a "video":+ # the client asked for /file instead of /image, loaded a+ # PNG into a <video>, and the preview went black with+ # nothing on screen to say why. A suffix is not a guess+ # here, it is the same test `_STILL_SUFFIXES` already+ # makes for the NLE export.+ _sfx = Path(str(path or "")).suffix.lower()+ if f("kind", "") == "still" or (+ path and not src_id+ and _sfx in sedit._STILL_SUFFIXES):+ if not path or not _sbe_pool_path_ok(path):+ self._json({"ok": False,+ "error": "that image is not in this "+ "panel's outputs"}, 400)+ return+ geo = _sb_probe_still(path) or {}+ if not geo:+ self._json({"ok": False,+ "error": "that file is not an image "+ "this panel can read"}, 400)+ return+ self._json({"ok": True, "id": bid,+ "clip": {"path": path, "kind": "still",+ "title": title or Path(path).stem[:80],+ "proxy": None, "duration_s": None,+ "w": geo.get("w"),+ "h": geo.get("h")}})+ return+ if src_id:+ # Another film's clip. Import it as a shot first —+ # references, not copies — so the board carries its+ # prompt and seed and the clip stops being an orphan.+ if src_id == bid:+ self._json({"ok": False,+ "error": "that clip is already in "+ "this film"}, 400)+ return+ with _SB_LOCK:+ live = _SB_RENDERS.get(bid)+ busy = bool(live and not live.get("stop"))+ if busy:+ self._json({"ok": False, "busy": True,+ "error": "This film is rendering. "+ "Importing now could drop a "+ "clip that just finished — "+ "try again when it stops."},+ 409)+ return+ src = load(src_id)+ want = {int(x) for x in (only or "").split(",")+ if x.strip().lstrip("-").isdigit()}+ # The file we are after, resolved from the SOURCE+ # before anything is renumbered: `_sb_import_shots`+ # returns positions, and _sb_normalize may move them.+ # The path is the one identity that survives both.+ wanted_path = ""+ for row in (src.get("shots") or []):+ if want and row.get("n") not in want:+ continue+ cand = str(row.get("final_output")+ or row.get("draft_output") or "")+ if cand:+ wanted_path = cand+ title = title or (row.get("title")+ or row.get("prompt") or "")[:80]+ break+ brought, _skipped = _sb_import_shots(board, src,+ want or None)+ if not brought:+ # Already here is not a failure — the pool can+ # still put it on the track, which is what the+ # click asked for.+ if not wanted_path:+ self._json({"ok": False,+ "error": "that clip has not "+ "rendered yet"}, 404)+ return+ else:+ _sb_normalize(board)+ storyboard.save_storyboard(STATE_DIR, board)+ for row in (board.get("shots") or []):+ cand = str(row.get("final_output")+ or row.get("draft_output") or "")+ if cand and cand == wanted_path:+ n = row.get("n")+ break+ path = wanted_path+ if not path or not _sbe_pool_path_ok(path):+ self._json({"ok": False,+ "error": "that file is not in this "+ "panel's outputs"}, 400)+ return+ # What the timeline needs to place it: how long it is.+ dur = None+ try:+ import storyboard_edit as _se # noqa: PLC0415+ dur = (_se.probe_media(path) or {}).get("duration")+ except Exception: # noqa: BLE001+ dur = None+ proxied = _sbe_proxy_now(bdir, [path], sedit)+ pmap = _sbe_proxy_map(bdir, [{"path": path}], sedit)+ if not title:+ title = Path(path).stem[:80]+ self._json({"ok": True, "id": bid,+ "clip": {"path": path, "title": title,+ "n": n, "duration_s": dur,+ "proxy": pmap.get(path)},+ "proxy": proxied})+ return++ if sub == "relink":+ # Draft → delivery, on the user's word. Server-side because+ # it is one write: load, rewrite the paths the GET already+ # flagged, save, and build the delivery proxies before+ # answering, so the timeline that comes back is scrubbable.+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ try:+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 500)+ return+ if not edit:+ self._json({"ok": False,+ "error": "no timeline to relink"}, 404)+ return+ swaps = {r["path"]: r["to"] for r in _sbe_relinks(board, edit)}+ if not swaps:+ self._json(_sbe_payload(board, edit))+ return+ for c in (edit.get("clips") or []):+ if not isinstance(c, dict):+ continue+ to = swaps.get(str(c.get("path") or ""))+ if to:+ c["path"] = to+ # The proxy belonged to the DRAFT. Dropping it here+ # stops the player showing yesterday's file under+ # today's path until the rebuild lands.+ c["proxy"] = None+ try:+ sedit.save_edit(bdir, edit)+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False,+ "error": f"relink refused: {exc}"}, 500)+ return+ _sbe_proxy_now(bdir, sorted(set(swaps.values())), sedit)+ push(f"[timeline] relinked {len(swaps)} clip(s) to their "+ f"finished versions")+ payload = _sbe_payload(board, sedit.load_edit(bdir))+ payload["relinked"] = len(swaps)+ self._json(payload)+ return++ if sub == "cancel":+ bid = f("id", "")+ with _SBE_LOCK:+ job = _SBE_JOBS.get(bid)+ if job:+ job["cancel"] = True+ self._json({"ok": True, "prepare": _sbe_job_state(bid)})+ return++ if sub == "auto":+ # Deliberate, explicit, destructive: rebuild the+ # arrangement from the auto-editor and throw away what was+ # there. Nothing else in this API does that, and GET never+ # does it to an edit that exists.+ bid = f("id", "")+ board = load(bid)+ music = f("music", "") or None+ try:+ target = float(f("target_seconds", "") or 0) or None+ except ValueError:+ target = None+ try:+ min_shot = float(f("min_shot", "1.5") or 1.5)+ except ValueError:+ min_shot = 1.5+ try:+ max_shot = float(f("max_shot", "") or 0) or None+ except ValueError:+ max_shot = None+ edit = _sbe_auto_edit(board, music=music,+ target_seconds=target,+ min_shot=min_shot, max_shot=max_shot)+ old = None+ try:+ old = sedit.load_edit(_sbe_board_dir(bid))+ except sedit.EditError:+ old = None+ if old:+ edit["revision"] = int(old.get("revision") or 0)+ try:+ sedit.save_edit(_sbe_board_dir(bid), edit, origin="auto")+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 400)+ return+ self._json(_sbe_payload(+ board, sedit.load_edit(_sbe_board_dir(bid))))+ return++ if sub == "save":+ try:+ payload = json.loads(body or "{}")+ except json.JSONDecodeError as exc:+ self._json({"ok": False,+ "error": f"bad JSON: {exc}"}, 400)+ return+ bid = str(payload.get("id") or "").strip()+ incoming = payload.get("edit")+ if not isinstance(incoming, dict):+ self._json({"ok": False, "error": "no edit"}, 400)+ return+ board = load(bid)+ incoming["board_id"] = bid+ # `revision` is the SERVER's counter, based on what is on+ # disk rather than on what the client remembered. A stale+ # tab must not be able to wind it backwards, and+ # `expect_revision` lets a client that cares find out it+ # was overtaken instead of silently overwriting the other+ # tab's arrangement.+ #+ # THIS CHECK IS THE EARLY ANSWER, NOT THE GUARD. It exists+ # so an overtaken tab is told so without the server first+ # validating and archiving a document it is going to+ # refuse. The guard that actually holds is inside+ # `save_edit`, under the board's write lock, because the+ # panel is a ThreadingHTTPServer and this read and that+ # write used to be in different critical sections: two+ # tabs whose debounces landed together both read revision+ # 7, both compared 7 == 7, and both got HTTP 200. One+ # arrangement was gone, recoverable only from history/ and+ # only by somebody who knew to look.+ try:+ current = sedit.load_edit(_sbe_board_dir(bid)) or {}+ except sedit.EditError:+ current = {}+ on_disk = int(current.get("revision") or 0)+ expect = payload.get("expect_revision")+ if expect is not None and int(expect) != on_disk:+ self._json({"ok": False, "conflict": True,+ "revision": on_disk,+ "error": f"this timeline moved on without "+ f"you — it is at revision "+ f"{on_disk}, you saved from "+ f"{expect}"}, 409)+ return+ incoming["revision"] = on_disk+ errs = sedit.validate_edit(incoming)+ blocking = sedit.blocking_errors(errs)+ if blocking:+ # Structured, ALL of them, and the file on disk is+ # untouched — the client can highlight every bad clip+ # at once instead of playing whack-a-mole.+ self._json({"ok": False, "errors": blocking,+ "error": blocking[0]["message"]}, 400)+ return+ # A WARNING NEVER STOPS A WRITE. It rides back on the+ # payload so the panel can note it beside the clip without+ # the document being held hostage to it.+ warnings = [e for e in errs if e not in blocking]+ # AN ABSENT GUARD IS ACCEPTED, AND LOGGED. Refusing it was+ # the other option and it is the wrong one: the client+ # sends no `expect_revision` on purpose for the "Keep+ # mine" button — a user looking at a conflict notice and+ # choosing to overwrite — and a 409 that button cannot+ # answer would strand the arrangement on screen. So the+ # unguarded write stays last-write-wins, but it stops+ # being SILENT: it says whose revision it landed on, in+ # the log the panel already shows, and the outgoing+ # document is in history/ either way.+ if expect is None:+ push(f"[timeline] unguarded save on {bid} — no "+ f"expect_revision, overwriting revision "+ f"{on_disk} (last write wins)")+ try:+ sedit.save_edit(_sbe_board_dir(bid), incoming,+ expect=expect)+ except sedit.EditConflict as exc:+ # THE RACE, CAUGHT AT THE WRITE. Same body the+ # sequential case produces, because to the tab that+ # lost it is the same event: somebody else is ahead,+ # your arrangement is still on your screen.+ self._json({"ok": False, "conflict": True,+ "revision": exc.revision,+ "error": str(exc)}, 409)+ return+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 400)+ return+ # A SAVE ANSWERS THE RECOVERY OFFER. The crash backup is+ # insurance against work that never reached edit.json, and+ # the moment the user presses Save it has. Leaving the file+ # behind kept the amber bar on screen over a saved film,+ # armed a "Recover it" button that would revert the save+ # the user had just made, and — because `write_backup`+ # refuses to overwrite an unanswered offer — killed the+ # backup lane for the rest of the session, at which point+ # the watchdog started calling a perfectly healthy panel+ # broken.+ sedit.discard_backup(_sbe_board_dir(bid))+ out = _sbe_payload(board, sedit.load_edit(_sbe_board_dir(bid)))+ if warnings:+ out["warnings"] = warnings+ self._json(out)+ return++ if sub == "draft":+ # ONE ROUTE, FIVE VERBS, because they are five edits to the+ # same index and splitting them would be five places for+ # the active pointer to be wrong.+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ op = (f("op", "") or "").strip().lower()+ slug = f("slug", "")+ name = f("name", "")+ with _SB_LOCK:+ live = _SB_RENDERS.get(bid)+ busy = bool(live and not live.get("stop"))+ if busy and op in ("activate", "delete", "new", "duplicate"):+ # Same guard import-shots and restore take: the render+ # is reading this document clip by clip.+ self._json({"ok": False, "busy": True,+ "error": "This film is rendering. Changing "+ "drafts now would swap the "+ "timeline out from under it — try "+ "again when it stops."}, 409)+ return+ try:+ if op == "new":+ out = sedit.create_draft(+ bdir, name,+ from_current=(f("from", "") == "current"))+ elif op == "duplicate":+ out = sedit.duplicate_draft(bdir, slug, name)+ elif op == "rename":+ out = sedit.rename_draft(bdir, slug, name)+ elif op == "delete":+ out = sedit.delete_draft(bdir, slug)+ elif op == "activate":+ out = sedit.activate_draft(bdir, slug)+ else:+ self._json({"ok": False,+ "error": f"unknown draft action "+ f"{op!r}"}, 400)+ return+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 400)+ return+ payload = _sbe_payload(board, sedit.load_edit(bdir) or {})+ payload["draft"] = out+ payload["op"] = op+ self._json(payload)+ return++ if sub == "backup":+ # THE QUIET LANE, AND IT IS QUIET IN BOTH DIRECTIONS. It+ # writes history/backup-<draft>.json and nothing else: no+ # edit.json, no revision, no conflict check. The user's+ # saved draft is exactly what he last saved.+ try:+ payload = json.loads(body or "{}")+ except json.JSONDecodeError as exc:+ self._json({"ok": False,+ "error": f"bad JSON: {exc}"}, 400)+ return+ bid = str(payload.get("id") or "").strip()+ incoming = payload.get("edit")+ if not isinstance(incoming, dict):+ self._json({"ok": False, "error": "no edit"}, 400)+ return+ load(bid)+ incoming["board_id"] = bid+ # THE PAYLOAD SAYS WHICH DRAFT IT WAS COMPOSED FROM, and+ # write_backup refuses it if that draft has been left. The+ # client debounces this write and the server is threaded,+ # so without the name a backup of draft A can land as+ # draft B's unsaved work.+ # ...AND WHICH SESSION, which now CLAIMS rather than is+ # checked. This route used to answer a session that did not+ # hold the claim with 409 `stale_session`, and the claim was+ # taken by loading the page — so a passive page load in+ # another browser stopped this lane in the tab the person+ # was working in, for as long as it stayed open. The safety+ # net may not have an opinion; this was its last one.+ token = str(payload.get("session") or "")+ bdir = _sbe_board_dir(bid)+ try:+ sedit.write_backup(bdir, incoming,+ draft=str(payload.get("draft") or ""),+ session=token)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 400)+ return+ # WHO ELSE IS EDITING, as information. A tab that finds+ # another token on the claim tells its user there is a+ # second editor — and keeps writing, because being second+ # is not a reason to stop protecting somebody.+ self._json({"ok": True, "id": bid, "at": int(time.time()),+ "session": sedit.current_session(bdir)})+ return++ if sub == "recover":+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ try:+ edit = sedit.recover_backup(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 400)+ return+ push(f"[timeline] recovered the unsaved backup "+ f"({len(edit.get('clips') or [])} clips)")+ self._json(_sbe_payload(board, edit))+ return++ if sub == "discard-backup":+ bid = f("id", "")+ load(bid)+ sedit.discard_backup(_sbe_board_dir(bid))+ self._json({"ok": True, "id": bid})+ return++ if sub == "version":+ # NAMING A VERSION IS NOT SAVING ONE. The document on disk+ # is already the arrangement on screen (the editor saves on+ # a debounce); what this adds is a copy of it that the+ # fifty-save prune will never take, under a name a person+ # chose. So: no revision bump, no write to edit.json, and+ # nothing about the timeline changes — which is exactly why+ # it is safe to press at any moment.+ bid = f("id", "")+ load(bid) # 404s an unknown film+ bdir = _sbe_board_dir(bid)+ label = (f("label", "") or "").strip()[:80]+ if not label:+ self._json({"ok": False,+ "error": "a version needs a name"}, 400)+ return+ try:+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 500)+ return+ if not edit:+ self._json({"ok": False,+ "error": "there is no timeline to keep "+ "yet"}, 404)+ return+ dst = sedit.archive_edit(bdir, edit, label)+ self._json({"ok": True, "id": bid, "label": label,+ "file": (dst.name if dst else ""),+ "already": dst is None,+ "revision": int(edit.get("revision") or 0),+ "versions": sedit.list_history(bdir)})+ return++ if sub == "restore":+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ # A RUNNING RENDER OWNS THIS FILM. The same guard+ # import-shots takes, for the same reason: the render is+ # reading the arrangement clip by clip, and swapping the+ # document under it produces a film that is half of one cut+ # and half of another with nothing on screen to say so.+ with _SB_LOCK:+ live = _SB_RENDERS.get(bid)+ busy = bool(live and not live.get("stop"))+ if busy:+ self._json({"ok": False, "busy": True,+ "error": "This film is rendering. "+ "Restoring now would swap the "+ "timeline out from under it — "+ "try again when it stops."}, 409)+ return+ try:+ edit = sedit.restore_edit(bdir, f("file", ""))+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 400)+ return+ push(f"[timeline] restored {f('file', '')} "+ f"({len(edit.get('clips') or [])} clips)")+ payload = _sbe_payload(board, edit)+ payload["restored"] = f("file", "")+ payload["versions"] = sedit.list_history(bdir)+ self._json(payload)+ return++ if sub == "render":+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ try:+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 500)+ return+ if not edit:+ self._json({"ok": False,+ "error": "no edit to render — "+ "GET /storyboard/edit first"}, 404)+ return+ name = f("out", "") or _sb_film_name(board)+ if not re.fullmatch(r"[A-Za-z0-9._-]{1,120}\.mp4", name):+ self._json({"ok": False,+ "error": "out must be a plain .mp4 "+ "filename"}, 400)+ return+ # The SAME assembler the export uses, given one plan entry+ # per timeline clip — repeats included, which is why+ # `_sb_cut_index` keeps a list per path.+ film = _sbe_render_edit(+ board, edit, music=f("music", "") or None,+ music_mode=f("music_mode", "") or None,+ out_name=name)+ self._json(film if film.get("ok") else (film | {"ok": False}),+ 200 if film.get("ok")+ else int(film.get("status") or 500))+ return++ if sub == "export-nle":+ # THE FILM, AS A PROJECT SOMEBODY ELSE'S EDITOR CAN OPEN.+ # A folder next to the film: one FCP7 XML (the single+ # interchange Premiere and Resolve both import), one+ # ExtendScript for After Effects (which has no timeline+ # import at all), and a `media/` of hardlinks so the whole+ # thing relinks by name wherever it is dropped.+ bid = f("id", "")+ board = load(bid)+ bdir = _sbe_board_dir(bid)+ try:+ edit = sedit.load_edit(bdir)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 500)+ return+ if not edit or not (edit.get("clips") or []):+ self._json({"ok": False,+ "error": "there is no timeline to "+ "export"}, 404)+ return+ dest = _sb_film_dir(board)+ dest.mkdir(parents=True, exist_ok=True)+ audio = edit.get("audio") or None+ if audio and not Path(str(audio.get("path") or "")).is_file():+ audio = None++ def _probe(p):+ """Geometry for the XML, per clip. A still has no+ duration and `_sb_probe_clip` refuses it for exactly+ that reason, so the two probes are tried in turn."""+ return _sb_probe_clip(p) or _sb_probe_still(p)++ try:+ res = sedit.export_nle(+ edit.get("clips") or [], dest,+ name=Path(_sb_film_name(board)).stem,+ fps=FPS, audio=audio, probe=_probe)+ except sedit.EditError as exc:+ self._json({"ok": False, "error": str(exc)}, 400)+ return+ except OSError as exc:+ self._json({"ok": False,+ "error": f"could not write the project "+ f"folder: {exc}"}, 500)+ return+ push(f"[timeline] project folder → "+ f"{Path(res['dir']).name} ({res['clips']} clips, "+ f"{res['linked']} hardlinked, {res['copied']} copied)")+ self._json(res)+ return++ if sub == "reveal":+ # `open -R` on a path the SERVER computed. The client sends+ # nothing but the board id, so this can never become an+ # argument to `open` pointing outside the board's folder.+ bid = f("id", "")+ board = load(bid)+ what = f("what", "")+ d = _sb_film_dir(board)+ target = d+ if what == "project":+ cand = d / (+ re.sub(r"[^a-zA-Z0-9]+", "-",+ Path(_sb_film_name(board)).stem).strip("-")+ .lower() + "_project")+ if cand.is_dir():+ target = cand+ if not target.is_dir():+ self._json({"ok": False,+ "error": "nothing exported yet"}, 404)+ return+ try:+ subprocess.Popen(["open", str(target)])+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False, "error": str(exc)}, 500)+ return+ self._json({"ok": True, "path": str(target)})+ return++ if sub == "generate":+ bid = f("id", "")+ board = load(bid)+ prompt = f("prompt", "")+ if not prompt:+ self._json({"ok": False,+ "error": "Write what the shot shows."}, 400)+ return+ try:+ dur = float(f("duration", "") or f("duration_s", "")+ or 5.0)+ except ValueError:+ dur = 5.0+ if not (0 < dur <= 60):+ self._json({"ok": False,+ "error": f"duration must be between 0 and "+ f"60 s (got {dur})"}, 400)+ return+ try:+ film_start = float(f("film_start", "0") or 0.0)+ except ValueError:+ film_start = 0.0+ pass_name = "final" if f("pass", "draft") == "final" else "draft"+ cid = f("character_id", "")+ if cid and cid not in set(_sb_known_character_ids()):+ self._json({"ok": False,+ "error": f"character {cid!r} is not "+ f"installed"}, 400)+ return+ try:+ seed = int(f("seed", "-1") or -1)+ except ValueError:+ seed = -1+ shots = [s for s in (board.get("shots") or [])+ if isinstance(s, dict)]+ n = max([int(s.get("n") or 0) for s in shots] or [0]) + 1+ shot = {+ "n": n,+ "title": (f("title", "") or prompt)[:60],+ "mode": "character" if cid else "text",+ "engine": (f("engine", "")+ or board.get("engine_mode") or "ltx"),+ "prompt": prompt,+ "duration_s": dur,+ "seed": seed,+ "refs": [],+ "status": "pending",+ # The hole this shot was ordered for. Carried on the+ # BOARD (it is intent) and echoed to the client on the+ # edit payload's `unplaced` list when the clip lands.+ "edit_slot": {"film_start": round(film_start, 6),+ "duration": round(dur, 6)},+ }+ if cid:+ shot["character_id"] = cid+ shot["trigger"] = f("trigger", "") or cid+ board.setdefault("shots", []).append(shot)+ _sb_normalize(board)+ # `_sb_normalize` may renumber; find the shot again by the+ # object identity the list still holds.+ shot = board["shots"][-1]+ policy = ((board.get("policy") or {}).get(pass_name)+ or _sb_policy_for(+ get_settings().get("storyboard_draft_quality",+ "quick"),+ get_settings().get("storyboard_final_quality",+ "standard"))[pass_name])+ h3_ok = _sb_h3_available()+ try:+ chain_ok = bool(h3_ok and h3_supports_chain_prompts())+ except Exception: # noqa: BLE001+ chain_ok = False+ form_out = storyboard.shot_to_job(+ shot, policy, board_id=bid,+ board_title=board.get("title") or "",+ h3_available=h3_ok,+ engine_mode=board.get("engine_mode") or "auto",+ h3_chain_prompts=chain_ok,+ locations=storyboard.board_locations(board),+ wardrobe=storyboard.board_wardrobe(board))+ job_form = {k: ("" if v is None else str(v))+ for k, v in form_out.items()}+ try:+ jid = _sb_enqueue(job_form)+ except Exception as exc: # noqa: BLE001+ self._json({"ok": False,+ "error": f"could not queue the shot: "+ f"{exc}"}, 500)+ return+ shot[storyboard.pass_job_key(pass_name)] = jid+ shot["status"] = "queued"+ storyboard.save_storyboard(STATE_DIR, board)+ # THE ALLOWLIST CHECK, RUN LIVE. `make_job` silently drops+ # any form field it does not name, so a control can look+ # perfectly wired and do nothing. Rather than trust that,+ # read the params back off the job that is now in the queue+ # and hand them to the client: what you see here is what+ # will actually render.+ landed = {}+ with LOCK:+ for j in (STATE.get("queue") or []):+ if j.get("id") == jid:+ p = j.get("params") or {}+ landed = {k: p.get(k) for k in+ ("mode", "engine", "prompt", "frames",+ "width", "height", "quality", "seed",+ "session_tag", "label", "enhance",+ "h3_length", "h3_quality")}+ break+ push(f"[timeline] queued a shot for the {film_start:.2f}s "+ f"slot — {dur:g}s, {pass_name} pass")+ self._json({"ok": True, "id": bid, "job_id": jid,+ "n": shot.get("n"), "pass": pass_name,+ "shot": shot, "params": landed}, 202)+ return++ self._json({"ok": False,+ "error": f"unknown editor action: {sub}"}, 404)+ return+self._json({"ok": False, "error": f"unknown storyboard action: {action}"}, 404)except storyboard.StoryboardError as exc:_sb_release_stranded_claim(action)@@ -21624,6 +25660,57 @@ class Handler(BaseHTTPRequestHandler):self._json({"error": f"upload failed: {exc}"}, 500)return+ # ====== the Editor's media pool — bring your own file =============+ # "You cannot upload your own images and insert them into the+ # timeline." The pool could show everything the panel MADE and nothing+ # the user already had, which for a title card, a logo or a phone clip+ # meant re-rendering something that was already on disk.+ #+ # WHERE THE BYTES LAND IS THE WHOLE DESIGN. An image goes into+ # UPLOADS/library/manual/, which `list_outputs` already walks — so it+ # appears in the Images source on the next refresh and STAYS there+ # across restarts, with no second listing to keep in sync. A video+ # goes into UPLOADS/timeline/, which `_sbe_pool_path_ok` already+ # accepts, and is listed by the route below: the gallery scans+ # OUTPUT/*.mp4 only, and dropping somebody's phone clip in among the+ # renders would put a file the panel never made into the one folder+ # that means "the panel made this".+ if path == "/storyboard/edit/upload" and ctype.startswith("multipart/form-data"):+ # 320 MB. `_parse_multipart_form` reads the body into memory, so+ # this is a real ceiling and not a formality — big enough for any+ # clip somebody drags in, small enough that two at once cannot+ # take the panel down.+ SBE_UPLOAD_MAX = 320 * 1024 * 1024+ SBE_UPLOAD_IMAGE = {".png", ".jpg", ".jpeg", ".webp"}+ SBE_UPLOAD_VIDEO = {".mp4", ".mov", ".m4v", ".webm"}+ try:+ clen = int(self.headers.get("Content-Length") or "0")+ except ValueError:+ clen = 0+ if clen <= 0:+ self._json({"ok": False, "error": "Content-Length required"}, 411)+ return+ if clen > SBE_UPLOAD_MAX:+ self._json({"ok": False,+ "error": f"that file is larger than "+ f"{SBE_UPLOAD_MAX // (1024 * 1024)} MB"}, 413)+ return+ try:+ form = _parse_multipart_form(self.rfile, ctype, clen)+ fld = form["file"] if "file" in form else None+ if fld is None or not getattr(fld, "filename", None):+ self._json({"ok": False, "error": "no file"}, 400)+ return+ out = _sbe_accept_upload(str(fld.filename), fld.file.read(),+ images=SBE_UPLOAD_IMAGE,+ videos=SBE_UPLOAD_VIDEO)+ except Exception as exc: # noqa: BLE001+ out = {"ok": False, "error": f"upload failed: {exc}",+ "status": 500}+ self._json({k: v for k, v in out.items() if k != "status"},+ 200 if out.get("ok") else int(out.get("status") or 400))+ return+# ====== Train Character — multipart dataset upload ===============# POSTs one file per request (image OR caption), accumulating under# state/train_character/<job_id>/{images,captions}/. Captions are@@ -23436,6 +27523,47 @@ class Handler(BaseHTTPRequestHandler):_analytics_capture("star_prompt", {"via": _via})self._json({"ok": True}); return+ if path == "/restart":+ # The "Restart to finish update" pill used to open an alert() that+ # told the user to go and do it themselves in Pinokio — a button+ # naming an action and delivering a paragraph. Worse, Chrome+ # silently swallows repeat dialogs once "prevent additional+ # dialogs" is ticked, so for some users the click did visibly+ # nothing at all (reported 2026-08-16).+ #+ # os.execv REPLACES this process with a fresh one: same pid, same+ # port, same argv and cwd, running the code that is on disk NOW.+ # That is exactly what a stale process needs. The queue and+ # settings live on disk, so nothing in flight is lost EXCEPT a+ # running render — which is why a busy panel refuses instead.+ with LOCK:+ _busy = STATE.get("current") is not None+ if _busy:+ self._json({"ok": False, "busy": True,+ "error": "A render is running. Stop it first, or "+ "wait for it to finish — restarting now "+ "would kill it."}, 409); return+ persist_queue()+ self._json({"ok": True, "restarting": True})+ try:+ self.wfile.flush()+ except Exception: # noqa: BLE001+ pass++ def _reexec() -> None:+ # Give the response a moment to reach the browser; the socket+ # is non-inheritable (PEP 446) so exec closes the listener and+ # the new image rebinds the port cleanly.+ time.sleep(0.4)+ try:+ os.chdir(str(ROOT))+ os.execv(sys.executable, [sys.executable] + sys.argv)+ except Exception as exc: # noqa: BLE001+ sys.stderr.write(f"restart failed: {exc}\n")+ threading.Thread(target=_reexec, name="panel-restart",+ daemon=True).start()+ return+if path == "/queue/pause":with QUEUE_COND:STATE["paused"] = True@@ -23886,6 +28014,10 @@ class Handler(BaseHTTPRequestHandler):with _VERSION_LOCK:_VERSION_STATE["pull_state"] = "pulled"_VERSION_STATE["pull_message"] = (pull_out.splitlines() or ["pulled"])[-1]+ # _VERSION_STATE, not the /version snapshot: these two+ # mean "what we pulled TO", which is a fact about the tree.+ # The snapshot's local_* deliberately means the opposite —+ # the build this process is still running._VERSION_STATE["pull_pulled_to_short"] = _VERSION_STATE["local_short"]_VERSION_STATE["pull_pulled_to_version"] = _VERSION_STATE["local_version"]_VERSION_STATE["pull_requires_full_update"] = deps_touched@@ -25303,15 +29435,47 @@ def page() -> str:+ str(PORT) + '">DEV</span>'if PROFILE == "dev" else "")+ # A TEST PANEL MUST NOT BE ABLE TO IMPERSONATE THE REAL ONE. A verifying+ # agent runs a second copy against a throwaway LTX_STATE_DIR so it can+ # cut, save and restore without touching the owner's films — and an+ # abandoned tab of THAT is indistinguishable from his own panel showing a+ # stale build. It cost an evening: he read a test instance as his install+ # and reported the app had gone backwards.+ #+ # The tell is the state dir, because that is exactly what makes it a+ # different panel: a STATE_DIR outside the install root is by definition+ # not the install's own films. Loud badge, and the tab title changes too —+ # a background tab is a title and a favicon and nothing else.+ is_test = not _state_dir_is_native()+ if is_test:+ profile_badge = (+ '<span class="profile-badge test-badge" title="This is a TEST panel. '+ 'Its ' + SEQ_NOUN_PL + ' live in ' + html.escape(str(STATE_DIR)) + ', not in this '+ 'install — nothing you do here touches your own work.">TEST PANEL</span>'+ + profile_badge)return (HTML+ .replace("__SEQCAP__", SEQ_NOUN_CAP)+ .replace("__SEQS__", SEQ_NOUN_PL)+ .replace("__SEQ__", SEQ_NOUN)+ .replace("<title>Phosphene</title>",+ "<title>Phosphene TEST</title>" if is_test+ else "<title>Phosphene</title>").replace("__BOOTSTRAP__", bootstrap).replace("__PROFILE_BADGE__", profile_badge).replace("__Q8_CHARACTER_INSTALL_COPY__",q8_character_install_copy())+ .replace("__BUILD_STAMP__", html.escape(build_stamp_text()))# The header badge used to be the literal string "3.0", so it kept# claiming 3.0 through every release since. It reads the VERSION# file now — the same source /version and the update pill use.- .replace("__PANEL_VERSION__", html.escape(_read_local_version() or "dev"))+ #+ # The BOOT version, not the file on disk. _read_local_version()+ # re-reads the tree, so a pull under a running panel moved this+ # badge to the new number while the old code kept serving. The+ # disk fallback covers a zip install with no git.+ .replace("__PANEL_VERSION__",+ html.escape(boot_build_stamp()["version"]+ or _read_local_version() or "dev")).replace("__ENGINE_RULES__", _engine_css()).replace("__CAP_TIER__", cap_tier))@@ -25322,6 +29486,10 @@ HTML = r"""<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Phosphene</title>+ <!-- The build this PROCESS is serving, not the one in the working tree.+ Server-rendered, so it answers before a byte of JS runs and survives+ a page saved to disk. See build_stamp_text(). -->+ <meta name="phosphene-build" content="__BUILD_STAMP__"><link rel="icon" type="image/png" sizes="64x64" href="/assets/favicon-64.png"><link rel="icon" type="image/png" sizes="256x256" href="/assets/favicon.png"><style>@@ -25347,6 +29515,16 @@ HTML = r"""<!doctype html>--shadow-2: 0 8px 24px rgba(0,0,0,0.40);--ring: 0 0 0 3px var(--accent-dim);--r-xs: 6px; --r-sm: 8px; --r-md: 10px; --r-lg: 14px; --r-pill: 999px;+ /* TWO RUNGS FOR CONTROLS AND FIVE FOR TYPE, because the Editor had+ eight control heights and eleven type sizes on one screen — four of+ them half a pixel apart, which is below the threshold where a+ difference reads as hierarchy and above the one where it reads as+ sloppiness. Half-pixel sizes also land on non-integer line boxes,+ which is why rows in the rail and the drafts panel came out a pixel+ off each other. Anything new picks a rung; nothing declares its own. */+ --ctl-h: 32px; --ctl-h-sm: 28px; --ctl-h-lg: 36px;+ --fs-2xs: 10px; --fs-xs: 11px; --fs-sm: 12px; --fs-md: 13px;+ --fs-lg: 15px;--t-fast: 120ms cubic-bezier(.2,.8,.2,1);--t-base: 180ms cubic-bezier(.2,.8,.2,1);--t-slow: 240ms cubic-bezier(.2,.8,.2,1);@@ -25396,6 +29574,13 @@ HTML = r"""<!doctype html>}.brand { display: inline-flex; align-items: center; flex-shrink: 0; }.brand img { height: 124px; width: auto; display: block; }+ /* The impostor badge. Red, first in the row, and deliberately the loudest+ thing in the header: its whole job is to stop somebody reading a+ throwaway instance as their own install. */+ .profile-badge.test-badge {+ background: var(--danger); border-color: var(--danger); color: #fff;+ letter-spacing: 0.06em;+ }/* DEV badge — visible only on the dev panel (PROFILE == 'dev'). Sitsnext to the Phosphene wordmark so it's the first thing you noticewhen comparing dev vs production tabs. */@@ -25861,7 +30046,15 @@ HTML = r"""<!doctype html>stays visible — training surfaces progress through the existing Now /Queue / Recent / Logs panes. */body[data-workflow="train"] #modelsInline,+ /* #remixSubGroup RIDES WITH #modeGroup IN ALL SIX RULES, and it has to be+ said once so the seventh surface does not repeat it. The Remix sub-row+ is a SIBLING of the mode bar, not a child — it sits outside #genForm —+ so hiding the bar left the row behind on every non-Video surface. A+ Pinokio user (fuschichou) found it as a stray control on the Audio tab.+ The rule to keep: the sub-row is visible exactly when its parent bar is,+ which means these two ids are never listed apart. */body[data-workflow="train"] #modeGroup,+ body[data-workflow="train"] #remixSubGroup,body[data-workflow="train"] aside.form-pane > h2,body[data-workflow="train"] #genForm,body[data-workflow="train"] #studioSection,@@ -25874,6 +30067,7 @@ HTML = r"""<!doctype html>Hides the manual-only chrome the same way Train / Studio do. */body[data-workflow="audio"] #modelsInline,body[data-workflow="audio"] #modeGroup,+ body[data-workflow="audio"] #remixSubGroup,body[data-workflow="audio"] aside.form-pane > h2,body[data-workflow="audio"] #genForm,body[data-workflow="audio"] #studioSection,@@ -25893,6 +30087,7 @@ HTML = r"""<!doctype html>fonts, no libraries — the panel is offline-capable and dark-only. */body[data-workflow="storyboard"] #modelsInline,body[data-workflow="storyboard"] #modeGroup,+ body[data-workflow="storyboard"] #remixSubGroup,body[data-workflow="storyboard"] aside.form-pane > h2,body[data-workflow="storyboard"] #genForm,body[data-workflow="storyboard"] #studioSection,@@ -26414,7 +30609,58 @@ HTML = r"""<!doctype html>.sb-runbar .sb-danger { color: var(--danger); border-color: rgba(248,81,73,0.4); }/* ---- board list -------------------------------------------------- */- .sb-boardlist li { grid-template-columns: 1fr auto auto auto; cursor: pointer; }+ /* Five columns, and the TITLE keeps the flexible one. The first cut of+ this row gave `.params` its natural width and left `.ttl` a 1fr that+ collapsed to nothing — at 1000px the rows read "7 shots · 0… PLAN ONLY+ Edit ×" with no film name anywhere on screen. minmax(0,1fr) on the title+ and a shrinkable, ellipsised `.params` puts the name back. */+ .sb-boardlist li {+ grid-template-columns: minmax(0, 1fr) auto auto max-content auto !important;+ cursor: pointer;+ }+ .sb-boardlist li .ttl { min-width: 0; overflow: hidden; text-overflow: ellipsis; }+ /* The sidebar copy of the same list is ~230 px wide, and one line cannot+ hold a film's name, a shot count, a state badge, a chip and a delete+ button. The name is what lost: at 1000 px the rows read "DRAFTS DONE+ Film · 0:28 ×" with no title on them at all. So the narrow copy drops+ the shot count and goes to two lines — the name, then what it is and+ where it goes. */+ #sbBoardListMini li .params { display: none; }+ /* And it gets its own scroll box. Two lines a board is worth it for names+ you can read, but twelve boards must not push `Plan film` off the+ column — the list scrolls, the brief below it does not move. */+ #sbBoardListMini { max-height: 184px; overflow-y: auto; padding-right: 2px; }+ #sbBoardListMini li {+ grid-template-columns: minmax(0, 1fr) 22px !important;+ row-gap: 5px; padding: 6px 9px;+ }+ #sbBoardListMini li .ttl { grid-area: 1 / 1 / 2 / 2; }+ #sbBoardListMini li > button:last-child { grid-area: 1 / 2 / 2 / 3; }+ #sbBoardListMini li .badge {+ grid-area: 2 / 1 / 3 / 3; justify-self: start;+ max-width: 52%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ #sbBoardListMini li .sb-row-go { grid-area: 2 / 1 / 3 / 3; justify-self: end; }+ /* The trailing slot names the FURTHEST place this board has got to —+ "Film" once one exists, "Edit" once there are clips to arrange, nothing+ before that. One slot, never two, and it always points forward. */+ /* Specificity, not luck: `.row-list li button` is 22x22 with no padding and+ is defined further down the sheet, so a plain `.sb-row-go` lost and the+ label overflowed across the badge beside it. Three classes deep beats it+ wherever either rule ends up. */+ .sb-boardlist li .sb-row-go {+ display: inline-flex; align-items: center; gap: 5px;+ width: auto; height: auto;+ padding: 3px 9px; font-size: 11.5px; font-weight: 600; cursor: pointer;+ color: var(--accent-bright); background: var(--accent-dim);+ border: 1px solid var(--accent);+ border-radius: var(--r-pill); white-space: nowrap;+ }+ .sb-boardlist li .sb-row-go:hover {+ color: var(--accent-bright); background: rgba(47,129,247,0.30);+ border-color: var(--accent);+ }+ .sb-boardlist li .sb-row-go .ph { width: 13px; height: 13px; }.sb-boardlist li .badge { color: var(--muted); background: rgba(255,255,255,0.05); }.sb-boardlist li.is-live .badge {color: var(--accent-bright); background: var(--accent-dim);@@ -26449,6 +30695,1676 @@ HTML = r"""<!doctype html>any tier the registry grows. */body[data-cap-tier="q4"] #sbFinalQuality [data-pack="q8"] { display: none !important; }+ /* =========================================================+ THE RAIL — one place that says where you are and what is next.+ =========================================================+ Six stage states shared one scroller and nothing said which of them you+ were in, so the timeline was findable only by knowing it was the fifth+ button in a five-button grading bar. This is the fix: the four things a+ film goes through, always in the same place, on every screen that has a+ board open. It is navigation, not decoration — every step is a door. */+ .sb-rail {+ /* No longer sticky: the rail now lives ABOVE the player as the pane's+ first child, permanently on screen, instead of being sticky inside+ #sbStage's scroller — where it shared top:0 with the stats row and+ ate it, and sat BELOW the video whenever a clip was showing. */+ z-index: 6;+ display: flex; align-items: center; gap: 2px;+ flex: 0 0 auto; flex-wrap: wrap;+ /* Deliberately thin. The timeline below it is the one surface in this+ app whose usefulness is measured in pixels per second, and the rail+ is navigation — it earns its ~34 px and not one more. */+ margin: 0 0 10px; padding: 4px 6px;+ background: var(--panel); border: 1px solid var(--border);+ border-radius: var(--r-md);+ }+ .sb-rail[hidden] { display: none !important; }+ /* Belt for the new position: the rail is now a direct child of the shared+ stage pane, so CSS — not just the JS `hidden` flag — guarantees it can+ never appear on Video/Images/Audio/Train. */+ body:not([data-workflow="storyboard"]) .sb-rail { display: none !important; }+ /* `width: auto` on both, because the panel's base rule makes a bare+ <button> fill its parent — without it the rail stacks four steps down+ the page instead of across it. */+ .sb-rail-back {+ display: inline-flex; align-items: center; gap: 5px; width: auto;+ flex: 0 0 auto;+ padding: 4px 9px; margin-right: 4px; font-size: 11.5px;+ color: var(--muted); background: transparent;+ border: 1px solid transparent; border-radius: var(--r-pill);+ cursor: pointer; white-space: nowrap;+ }+ .sb-rail-back:hover { color: var(--text); background: var(--panel-2); }+ .sb-rail-back .ph { width: 12px; height: 12px; }+ .sb-rail-step {+ display: inline-flex; align-items: baseline; gap: 6px; width: auto;+ flex: 0 0 auto;+ padding: 3px 10px; font-size: 12px; font-weight: 600;+ color: var(--muted); background: transparent;+ border: 1px solid transparent; border-radius: var(--r-pill);+ cursor: pointer; white-space: nowrap; font-family: inherit;+ }+ .sb-rail-step .sb-rail-n {+ font-size: 9.5px; font-weight: 700; letter-spacing: 0.04em;+ color: var(--muted); opacity: 0.75;+ }+ .sb-rail-step .sb-rail-sub {+ font-size: 10.5px; font-weight: 500; color: var(--muted); opacity: 0.85;+ }+ .sb-rail-step:hover { color: var(--text); background: var(--panel-2); }+ .sb-rail-step.is-done { color: var(--text); }+ .sb-rail-step.is-done .sb-rail-n { color: var(--success); opacity: 1; }+ .sb-rail-step.is-now {+ color: var(--accent-bright); background: var(--accent-dim);+ border-color: var(--accent);+ }+ .sb-rail-step.is-now .sb-rail-n,+ .sb-rail-step.is-now .sb-rail-sub { color: var(--accent-bright); opacity: 1; }+ /* Locked is not hidden. A step you cannot reach yet still has to say what+ it is and what would unlock it — that is the whole point of a path. */+ .sb-rail-step.is-locked { opacity: 0.42; cursor: not-allowed; }+ .sb-rail-step.is-locked:hover { color: var(--muted); background: transparent; }+ .sb-rail-sep {+ flex: 0 0 auto; width: 14px; height: 1px; background: var(--border-strong);+ opacity: 0.7;+ }+ @media (max-width: 900px) { .sb-rail-sep { width: 6px; } }++ /* =========================================================+ THE FILM — the seventh stage state, and the point of the other six.+ =========================================================+ Both assemblers wrote an mp4 and then said nothing, so the user was left+ looking at a list of shots wondering which one was the movie. This is+ the movie: one player, four facts, and the folder it lives in. Built+ from the same primitives as the shot list (.carousel-head, .sb-summary,+ .row-list) because it is the same screen's last page, not a second app. */+ .sb-film { gap: 10px; }+ .sb-film > * { flex: 0 0 auto; }+ .sb-film-stage {+ position: relative; background: #000;+ border: 1px solid var(--border); border-radius: var(--r-md);+ overflow: hidden; line-height: 0;+ }+ .sb-film-stage video {+ display: block; width: 100%; max-height: min(56vh, 560px);+ background: #000; object-fit: contain;+ }+ .sb-film-name {+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap;+ margin-top: 10px; font-size: 12.5px; color: var(--text);+ }+ .sb-film-name code {+ font-size: 11.5px; color: var(--muted); background: var(--panel-2);+ border: 1px solid var(--border); border-radius: var(--r-xs);+ padding: 2px 7px;+ }+ .sb-film-kind {+ font-size: 9px; font-weight: 700; letter-spacing: 0.07em;+ text-transform: uppercase; padding: 2px 7px;+ border-radius: var(--r-pill);+ color: var(--accent-bright); background: var(--accent-dim);+ border: 1px solid var(--accent);+ }+ .sb-film-where {+ font-size: 11.5px; color: var(--muted); margin-top: 2px;+ overflow-wrap: anywhere;+ }+ .sb-film-actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 4px; }+ /* .ghost-btn is display:block and .ph is display:block, so an icon inside+ one lands on its own line. Every other icon+label button in the panel+ flips to inline-flex for exactly this reason. */+ .sb-film-actions .ghost-btn, .sb-film-actions .primary {+ width: auto; padding: 7px 14px;+ display: inline-flex; align-items: center; gap: 6px;+ }+ .sb-film-actions .ph { width: 14px; height: 14px; }+ .sb-filmlist li { grid-template-columns: minmax(0, 1fr) auto auto !important; cursor: pointer; }+ .sb-filmlist li .ttl { min-width: 0; overflow: hidden; text-overflow: ellipsis; }+ .sb-filmlist li.is-open { border-color: var(--accent); background: var(--accent-dim); }++ /* =========================================================+ THE TIMELINE EDITOR — the sixth storyboard stage state.+ =========================================================+ Same tokens, same radii, same motion as every other storyboard+ surface: this is the shot list's next screen, not a second app. The+ only new primitive is the track, and it is built from the same+ --panel / --border / --accent scale as the cards above it.++ NOTE ON TOKENS: the panel's palette is --text / --muted / --border /+ --panel / --panel-2 / --accent. The ink/line scale some other Anthropic+ surfaces use is NOT defined in this app — the dozen or so references to+ it that exist here all carry a hard-coded fallback and are therefore+ decorative. Nothing below invents one. */+ /* THE EDITOR OWNS ITS OWN WINDOW.+ This block used to read `body[data-workflow="storyboard"].sbe-open` and+ fold the storyboard's planning column away while the timeline was open+ — a mode, inside another tab, which is exactly what the 2026-08-17 UX+ review took apart: "the editor deserves its own window … for all+ models … called Editor". It is a workflow now, so there is nothing to+ fold and nothing to steal. The two columns are the media pool and the+ cut, which is the layout every editor on earth uses.++ 300px is the pool: wide enough for a thumbnail, a title and an Add+ button, and no wider — the cut is what the window is for. */+ body[data-workflow="editor"] main.layout {+ grid-template-columns: minmax(0, 300px) minmax(0, 1fr);+ }+ body[data-workflow="editor"] main.layout > aside.form-pane {+ /* Anything that cannot survive 300px scrolls. */+ overflow-x: hidden;+ }+ /* THE CUT SPANS BOTH ROWS, exactly as the base layout does for every+ other workflow. This rule said `grid-row: 1 / 2` for two releases, so+ row 2 — the bottomPane's own height, 170px measured at 1440x900 — was+ reserved across the WHOLE grid while only the 300px left column had+ anything in it. The remaining 1140x170 under the timeline was page+ background and nothing else: the band the owner circled and called+ "black space down below". Spanning gives it back to the picture. */+ body[data-workflow="editor"] main.layout > .stage-pane {+ grid-column: 2 / 3; grid-row: 1 / span 2;+ }+ /* Below this the two columns stack. The pool is a short list, not the+ storyboard's ~730px brief, so it stacks above the cut rather than+ folding away — losing the pool would lose the tab's other half. */+ @media (max-width: 1100px) {+ body[data-workflow="editor"] main.layout {+ grid-template-columns: minmax(0, 1fr);+ }+ body[data-workflow="editor"] main.layout > aside.form-pane {+ grid-column: 1 / 2; grid-row: 1 / 2; max-height: 38vh;+ }+ body[data-workflow="editor"] main.layout > .stage-pane {+ grid-column: 1 / 2; grid-row: 2 / 3;+ }+ body[data-workflow="editor"] main.layout > #bottomPane {+ grid-column: 1 / 2; grid-row: 3 / 4;+ }+ }+ /* The queue and the log stay: a shot generated into a hole is rendering+ somewhere, and that is where it reports. */+ body[data-workflow="editor"] main.layout > #bottomPane {+ grid-column: 1 / 2; grid-row: 2 / 3;+ }++ /* ---- the Editor workflow fold ------------------------------------+ Same shape as the storyboard fold above: the form pane becomes the+ media pool, the stage column becomes the cut. The player surface and+ the carousel go — the editor IS a player, and a second one beside it+ is two videos competing for one decoder. */+ body[data-workflow="editor"] #modelsInline,+ body[data-workflow="editor"] #modeGroup,+ body[data-workflow="editor"] #remixSubGroup,+ body[data-workflow="editor"] aside.form-pane > h2,+ body[data-workflow="editor"] #genForm,+ body[data-workflow="editor"] #studioSection,+ body[data-workflow="editor"] #trainSection,+ body[data-workflow="editor"] #sbSectionTab,+ body[data-workflow="editor"] #audioSectionTab { display: none !important; }+ body[data-workflow="editor"] #edSectionTab { display: flex; }+ .form-pane > #edSectionTab { padding: 0 18px; }+ body[data-workflow="editor"] .stage-pane > .player-surface,+ body[data-workflow="editor"] .stage-pane > .carousel-wrap,+ body[data-workflow="editor"] .ideo-stage-bar,+ body[data-workflow="editor"] .ideo-canvas-host { display: none !important; }+ /* #modelTag names ONE model; a cut is made of clips from many. */+ body[data-workflow="editor"] #modelTag { display: none !important; }+ body[data-workflow="editor"] #edStage { display: flex; }+ #edStage {+ display: none;+ flex: 1 1 auto;+ flex-direction: column;+ min-height: 240px;+ overflow-y: auto;+ padding-right: 2px;+ }+ #edStage > .sbe { flex: 1 1 auto; }+ /* The empty state is the whole column when there is no document. */+ #edEmpty { margin: auto 0; }+ /* ---- the media pool ---------------------------------------------+ A column, not a grid: at 300px a two-up grid gives 130px tiles that+ can hold neither a title nor a button, and the thing being chosen here+ is "which clip", which is a name and a length before it is a picture.+ The picture is still there — a 64px frame, loaded as metadata only, so+ a pool of two hundred clips costs two hundred headers and no decode. */+ #edSectionTab { flex-direction: column; min-height: 0; gap: 8px; padding-bottom: 14px; }+ .ed-pool-head { margin: 0; }+ .ed-pool-head h3 { margin: 0; }+ .ed-pool-tabs { display: flex; gap: 6px; flex-wrap: wrap; }+ /* Four sources in a ~200px column. `flex: 1 1 auto` laid them out three+ and one, which reads as the fourth being an afterthought rather than a+ peer. A 40% basis wraps them two and two. */+ .ed-pool-tabs .pill-btn { flex: 1 1 40%; width: auto; }+ .ed-pool-film, .ed-pool-search { width: 100%; }+ .ed-pool-film[hidden] { display: none !important; }+ .ed-pool-list {+ display: flex; flex-direction: column; gap: 4px;+ overflow-y: auto; min-height: 120px; flex: 1 1 auto;+ padding-right: 2px;+ }+ .ed-pool-row {+ display: flex; align-items: center; gap: 9px; width: 100%;+ padding: 5px 7px; text-align: left; cursor: pointer;+ user-select: none; -webkit-user-select: none;+ background: var(--panel-2); border: 1px solid var(--border);+ border-radius: var(--r-sm); color: var(--text);+ font-family: inherit; font-size: var(--fs-sm);+ }+ .ed-pool-row:hover { border-color: var(--accent); background: var(--panel); }+ .ed-pool-row:disabled { opacity: .55; cursor: default; }+ /* THE STILL WAS NOT IN THIS RULE, and the still branch emits a bare+ <img>. So an image row had no width cap: the picture took 180px of a+ 261px row, the text column was squeezed to 22px, and every filename+ ellipsised to one character and a dot — rows three times the height of+ the Generations tab next door, two of them visible at a time. */+ .ed-pool-row img, .ed-pool-row video, .ed-pool-row .ed-pool-blank {+ width: 64px; height: 36px; flex: 0 0 auto; object-fit: cover;+ border-radius: 3px; background: #000; pointer-events: none;+ }+ .ed-pool-row .ed-pool-meta {+ min-width: 0; flex: 1 1 auto; display: flex; flex-direction: column;+ gap: 1px;+ }+ .ed-pool-row .ed-pool-name {+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ .ed-pool-row .ed-pool-sub { color: var(--muted); font-size: var(--fs-xs); }+ /* + IS ITS OWN BUTTON NOW. The whole row used to be one <button> whose+ click added the clip; clicking a row previews it instead, so the verb+ that still adds needs a control of its own — and a <button> inside a+ <button> is not markup, which is why the row became a div with a+ role. The panel's base `button { width: 100% }` would make this 200px+ wide, hence the override. */+ .ed-pool-row .ed-pool-add {+ margin-left: auto; flex: 0 0 auto; width: auto; padding: 2px 7px;+ color: var(--muted); font-size: var(--fs-lg); line-height: 1;+ background: transparent; border: 1px solid transparent;+ border-radius: var(--r-xs); font-family: inherit; cursor: pointer;+ }+ .ed-pool-row:hover .ed-pool-add { color: var(--accent); }+ .ed-pool-row .ed-pool-add:hover {+ color: var(--accent-bright); border-color: var(--accent);+ background: var(--accent-dim);+ }+ /* Which row the source monitor is showing. The pool is a list of things+ you are choosing between, so it has to say which one you are looking+ at — otherwise the left screen is unattributed. */+ .ed-pool-row.is-source {+ border-color: var(--accent); background: var(--accent-dim);+ }+ .ed-pool-note { color: var(--muted); font-size: var(--fs-xs); line-height: 1.5; }+ /* ---- the relink banner ------------------------------------------- */+ .sbe-relink {+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;+ padding: 8px 10px; border-radius: var(--r-sm);+ border: 1px solid var(--warning); background: var(--panel-2);+ color: var(--text); font-size: var(--fs-sm);+ }+ .sbe-relink[hidden] { display: none !important; }+ .sbe-relink .sbe-relink-why { color: var(--muted); font-size: var(--fs-xs); }+ .ed-pick {+ display: flex; flex-direction: column; gap: 6px;+ margin-top: 14px; width: 100%; max-width: 460px;+ margin-inline: auto; text-align: left;+ }+ .ed-pick button {+ display: flex; align-items: center; gap: 10px; width: 100%;+ padding: 9px 12px; text-align: left;+ background: var(--panel-2); border: 1px solid var(--border);+ border-radius: var(--r-sm); color: var(--text);+ font-size: var(--fs-sm); font-family: inherit; cursor: pointer;+ }+ .ed-pick button:hover { border-color: var(--accent); background: var(--panel); }+ .ed-pick button .sub { color: var(--muted); font-size: var(--fs-xs); margin-left: auto; }++ /* 8px, not 10. Seven gaps at 10px is 70px of the column, and 14 of them+ bought nothing that the borders below were not already saying. */+ .sbe { gap: 8px; }+ /* ---- the command bar's own controls -----------------------------+ The draft chip is IDENTITY, so it sits beside the name and is drawn+ quieter than a verb; the split primary is the only filled thing on the+ screen; the kebab is a square. */+ .sbe-draftchip { width: auto; gap: 6px; color: var(--muted); }+ .sbe-draftchip #sbeDraftName { color: var(--text); font-weight: 600; }+ .sbe-car { color: var(--muted); font-size: var(--fs-2xs); }+ .sbe-split { display: inline-flex; }+ .sbe-split > .primary:first-child {+ border-top-right-radius: 0; border-bottom-right-radius: 0;+ }+ .sbe-split > .sbe-car-btn {+ border-top-left-radius: 0; border-bottom-left-radius: 0;+ width: auto; padding-inline: 8px; margin-left: 1px;+ }+ .sbe-kebab { width: auto; padding-inline: 9px; letter-spacing: 0.06em; }+ /* ---- the popover, four times ------------------------------------+ FIXED, so an open menu is not part of the column's height and cannot+ push the workspace around — the rule the notice surface set. */+ .sbe-pop {+ position: fixed; z-index: 60; min-width: 190px; max-width: 360px;+ display: flex; flex-direction: column; gap: 6px; padding: 8px;+ background: var(--panel); border: 1px solid var(--border-strong);+ border-radius: var(--r-md); box-shadow: var(--shadow-2);+ }+ .sbe-pop[hidden] { display: none !important; }+ .sbe-pop-wide { min-width: 300px; }+ .sbe-pop .ghost-btn {+ width: 100%; justify-content: flex-start; text-align: left;+ height: var(--ctl-h-sm); padding-inline: 10px; font-size: var(--fs-xs);+ }+ .sbe-pop-row { display: flex; gap: 6px; }+ .sbe-pop-row .ghost-btn { width: auto; flex: 1 1 auto; }+ .sbe-pop-note {+ font-size: var(--fs-xs); color: var(--muted); line-height: 1.4;+ }+ .sbe-pop-sep { height: 1px; background: var(--border); margin: 2px 0; }+ .sbe-pop .sbe-keys { grid-template-columns: 1fr; }+ /* The ⓘ that two lines of prose became. */+ .sbe-info {+ width: 17px; height: 17px; flex: 0 0 auto; border-radius: 50%;+ border: 1px solid var(--border-strong); color: var(--muted);+ display: inline-flex; align-items: center; justify-content: center;+ font-size: var(--fs-2xs); font-style: italic; cursor: help;+ }+ .sbe-info:hover { color: var(--text); border-color: var(--accent); }+ /* ---- the lane gutter --------------------------------------------+ Its heads read the SAME variables the lanes do, so the two columns+ cannot drift apart at any height the handle is dragged to. The two+ +1s are the scroller's own borders, which the gutter does not have. */+ .sbe-tlwrap {+ flex: 1 1 auto; display: flex; min-width: 0;+ min-height: var(--sbe-tl-h, 280px);+ }+ .sbe-gutter {+ flex: 0 0 124px; display: flex; flex-direction: column; min-width: 0;+ border: 1px solid var(--border); border-right: 0;+ border-radius: var(--r-md) 0 0 var(--r-md);+ background: var(--bg-2); overflow: hidden;+ }+ .sbe-gh {+ display: flex; flex-direction: column; justify-content: center;+ gap: 2px; padding: 0 9px; min-width: 0; overflow: hidden;+ }+ .sbe-gh-top { flex: 0 0 calc(18px + 1px); border-bottom: 1px solid var(--border); }+ .sbe-gh-ov { flex: 0 0 var(--sbe-ov-h, 32px); border-bottom: 1px solid var(--border); }+ .sbe-gh-pic {+ flex: 1 1 auto; min-height: var(--sbe-track-h, 64px); max-height: 120px;+ justify-content: flex-start; padding-top: 8px;+ }+ .sbe-gh-aud {+ flex: 0 0 var(--sbe-alane-h, 44px); border-top: 1px solid var(--border);+ justify-content: flex-start; padding-top: 6px;+ }+ .sbe-gh-mus {+ flex: 0 0 var(--sbe-wave-h, 108px); border-top: 1px solid var(--border);+ justify-content: flex-start; padding-top: 6px; gap: 4px;+ }+ .sbe-gh-foot { flex: 0 0 13px; }+ .sbe-gh-tag {+ display: flex; align-items: center; gap: 5px; min-width: 0;+ font-size: var(--fs-2xs); color: var(--text); font-weight: 600;+ }+ .sbe-gh-tag i {+ font-style: normal; font-size: 9px; letter-spacing: 0.04em;+ color: var(--muted); border: 1px solid var(--border);+ border-radius: 3px; padding: 1px 3px; flex: 0 0 auto;+ }+ .sbe-gh-tag b { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .sbe-gh-sub {+ font-size: var(--fs-2xs); color: var(--muted); overflow: hidden;+ text-overflow: ellipsis; white-space: nowrap;+ }+ .sbe-gh-sub.is-live { color: var(--accent-bright); }+ .sbe-gh-more {+ margin-left: auto; flex: 0 0 auto; width: 18px; height: 16px;+ border: 1px solid var(--border); border-radius: var(--r-xs);+ background: var(--panel); color: var(--muted); cursor: pointer;+ font-size: 9px; line-height: 1; padding: 0;+ }+ .sbe-gh-more:hover { border-color: var(--accent); color: var(--text); }+ .sbe-gh-mode {+ height: 20px; padding: 0 4px; font-size: var(--fs-2xs); width: 100%;+ min-width: 0;+ }+ .sbe-gh-mus .sbe-music-name {+ font-size: var(--fs-2xs); color: var(--muted); overflow: hidden;+ text-overflow: ellipsis; white-space: nowrap; max-width: 100%;+ }+ /* THE MIX, ON THE HEAD THAT OWNS IT. Two controls that used to be two+ constants in the renderer. They are deliberately plain — a level and a+ checkbox — because the interesting thing about them is that they exist+ and that the render obeys them, not that they are pretty. */+ .sbe-mix-row {+ display: flex; flex-direction: column; gap: 3px; width: 100%;+ min-width: 0;+ }+ .sbe-mix-lvl {+ display: flex; align-items: center; gap: 4px; margin: 0;+ font-size: var(--fs-2xs); color: var(--muted); min-width: 0;+ }+ .sbe-mix-lvl > span { flex: 0 0 auto; }+ .sbe-mix-lvl input[type=range] {+ flex: 1 1 auto; min-width: 0; height: 12px; margin: 0; accent-color: var(--accent);+ }+ .sbe-mix-lvl b {+ flex: 0 0 auto; font-weight: 600; color: var(--text);+ font-variant-numeric: tabular-nums; min-width: 30px; text-align: right;+ }+ .sbe-gh-mus .sbe-mix-duck {+ margin: 0; font-size: var(--fs-2xs); color: var(--muted);+ display: flex; align-items: center; gap: 4px; min-width: 0;+ }+ .sbe-gh-mus .sbe-mix-duck input { margin: 0; flex: 0 0 auto; }+ .sbe-gh-mus .sbe-mix-duck span {+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ /* A CONTROL THAT HAS STOPPED ACTING SAYS SO. The duck stands down under an+ authored envelope (see sbeBedDuckSuppressed) and a checkbox that stayed+ ticked while doing nothing would be the silent guard this editor keeps+ paying for. */+ .sbe-mix-note {+ font-size: 9px; line-height: 1.25; color: var(--warn, #d29922);+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ .sbe-gh-mus.is-duck-off .sbe-mix-duck { opacity: 0.55; }+ /* #edStage is the scroller (flex column, overflow-y auto). Its children+ must keep their natural height or the track ends up half a track tall —+ which is exactly what happened the first time this was rendered in a+ browser: the stage stole the space and the clip blocks were clipped out+ of the scroll box. ONE exception, stated here as well as on the rule+ itself: the timeline is what absorbs the slack. */+ .sbe > * { flex: 0 0 auto; }+ .sbe > .sbe-tlwrap { flex: 1 1 auto; }+ /* [hidden] is display:none only until something gives the element a+ display. Four things here do, so four things here have to say it. */+ .sbe-conflict[hidden], .sbe-prep[hidden], .sbe-unplaced[hidden],+ .sbe-wave[hidden], .sbe-wave-none[hidden], .sbe-errs[hidden],+ .sbe-params[hidden] { display: none !important; }+ /* ONE ROW, ALWAYS. `flex-wrap: wrap` was the second half of a live bug:+ the owner saw "the save button pops up sometimes and it's super big" —+ 1554px wide, in a 1920px window, with the header three rows tall.+ WRAPPING WAS NOT THE CAUSE, IT WAS THE PERMISSION. The cause is one line+ below; wrap is what let an over-wide item take a row of its own instead+ of being shrunk into the line with everything else. A header that stacks+ is never the right answer here — it pushes the monitors and the timeline+ down the column, which is the one thing this layout is built not to do —+ so it degrades by ELLIPSIS and by folding, never by wrapping. */+ /* TWO CLASSES, DELIBERATELY. The element is `carousel-head sbe-head`, and+ `.carousel-head { flex-wrap: wrap }` is declared LATER in this sheet —+ equal specificity, so it wins. Written as a single class this rule was+ silently a no-op, which is how the first version of this fix measured a+ header that still wrapped. */+ .carousel-head.sbe-head {+ position: relative; z-index: 4; gap: 8px; flex-wrap: nowrap;+ }+ /* SEVEN IDENTICAL BUTTONS, NO PRIMARY. Undo, Redo, Save, the draft name,+ Drafts, Storyboard and Close all rendered at the same fill, border,+ height and type — so the safest action in the row and the one that+ LEAVES looked alike, and the row did not change when the state chip+ went amber. Save earns the fill exactly while there is something to+ save; Undo/Redo become one segmented control; and Close is pushed to+ the far end behind a divider, so leaving does not sit in the same+ cluster as saving. */+ /* THE BUG, AND THE WHOLE OF IT. The global form rule is+ `input, textarea, select, button { width: 100% }`; `.ghost-btn` cancels+ it with `width: auto`, and `button.primary` NEVER DID. Save is a ghost+ button until there is something to save and `sbePaintChrome` swaps it to+ `.primary` — so the moment the owner made an edit, Save's flex basis+ became 100% of the header, which is 1554px, and the row wrapped around+ it. "Sometimes" was exactly "while unsaved", which is why it looked+ random. The same trap is why Render survived: it sits inside+ `.sbe-split`, whose inline-flex shrink-to-fit made its 100% resolve+ against its own content. `.sbe-actions` used to carry this rule for the+ old bottom bar's primary; deleting that bar moved the primary into a row+ that had no such rule. Both widths are stated here so neither control+ can inherit a stretch again. */+ .sbe-head .ghost-btn, .sbe-head .primary {+ height: var(--ctl-h-sm); padding-block: 0; font-size: var(--fs-xs);+ width: auto; flex: 0 0 auto;+ }+ .sbe-head .sbe-undogroup { display: inline-flex; gap: 0; }+ .sbe-head .sbe-undogroup .ghost-btn:first-child {+ border-top-right-radius: 0; border-bottom-right-radius: 0;+ }+ .sbe-head .sbe-undogroup .ghost-btn:last-child {+ border-top-left-radius: 0; border-bottom-left-radius: 0;+ border-left-color: transparent; margin-left: -1px;+ }+ .sbe-head #sbeCloseBtn {+ margin-left: 10px; padding-left: 14px;+ border-left: 1px solid var(--border);+ border-top-left-radius: 0; border-bottom-left-radius: 0;+ }+ /* THE ONE THING THAT YIELDS. Everything else in the row is a control at+ its intrinsic width; the title is prose, so it is the item that shrinks+ and ellipsises when the window does. Without `min-width: 0` a flex item+ refuses to go below its content and the row overflows instead. */+ .sbe-head .sbe-title {+ font-size: var(--fs-md); font-weight: 600; color: var(--text);+ min-width: 40px; flex: 0 1 auto;+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ /* ...and the two things that FOLD, in the order they stop being worth+ their width: the save state's words go first (the dot still carries the+ state, and the chip's title says it in full), then the draft chip's+ name. Neither is a control that can only be reached here — Drafts is in+ the ⋯ menu — so folding them costs nothing a narrow window cannot pay. */+ .sbe-head .sbe-state { flex: 0 1 auto; min-width: 0; overflow: hidden; }+ @media (max-width: 1180px) {+ .sbe-head .sbe-state #sbeStateText { display: none; }+ }+ @media (max-width: 1040px) {+ .sbe-head .sbe-draftchip #sbeDraftName { display: none; }+ .sbe-head .sbe-draftchip { padding-inline: 8px; }+ }+ .sbe-state {+ font-size: var(--fs-xs); color: var(--muted); display: inline-flex;+ align-items: center; gap: 6px; white-space: nowrap;+ }+ .sbe-state .sbe-dot {+ width: 6px; height: 6px; border-radius: 999px; background: var(--muted);+ }+ .sbe-state.is-dirty { color: var(--warning); }+ .sbe-state.is-dirty .sbe-dot { background: var(--warning); }+ .sbe-state.is-saved { color: var(--success); }+ .sbe-state.is-saved .sbe-dot { background: var(--success); }++ /* ---- THE TWO MONITORS — source and program ----------------------+ The classic NLE stage, asked for by name: "a split screen with the+ left screen showing you when you click on the clips … you have two+ screens." LEFT is the source — a media-pool clip, auditioned before+ it is cut in — and RIGHT is the program, which is the timeline and+ everything it already did.++ This does NOT break the one-decoder rule the single-stage comment+ below was written for. That rule was about double-BUFFERING one+ stream: two elements taking turns on the same timeline bought+ nothing against all-intra proxies. These two show different things+ and never both play — sbeSrcPlay stops the program, sbePlay stops+ the source — so it is still one decode at a time.++ THE HEIGHT IS COMPUTED, NOT GUESSED. sbeFitMonitors() measures the+ column and this row and writes --sbe-prog-h / --sbe-src-h; the+ values here are what the page shows for the frame before it runs,+ and if JS ever dies. See sbeMonitorFit() for the arithmetic and for+ why the split slides between 40/60 and 50/50 rather than being+ fixed: a 16:9 pair needs ~2.96 px of width per px of height, and no+ window this app runs in has that much width to spare AND that much+ height at once.++ THE FALLBACK BUDGET, RE-MEASURED 2026-08-18 in the Editor's own tab,+ with the row-span fix above: the column is 100vh - 116px (88px of+ header + 28px of stage-pane padding), and everything else inside it+ comes to 452px — header 50, prepare 55, transport 32, ruler ++ waveform + 78px track + 26px audio lane + 12px scrollbar 190, inspector 38, action bar+ 65, six 8px gaps 48. Hence 100vh - 568px, still capped at 34vh so a+ very tall window does not hand the whole screen to one frame. Do not+ round it DOWN without re-measuring — what it buys is silent and it+ lands on the timeline. */+ .sbe-monitors {+ display: flex; gap: 12px; align-items: flex-start;+ justify-content: center; min-width: 0;+ --sbe-prog-h: min(34vh, 460px, calc(100vh - 568px));+ --sbe-src-h: calc(var(--sbe-prog-h) * 2 / 3);+ }+ .sbe-mon { display: flex; flex-direction: column; gap: 6px; min-width: 0; }+ .sbe-mon-label {+ font-size: var(--fs-2xs); letter-spacing: 0.08em; text-transform: uppercase;+ color: var(--muted); font-weight: 700; flex: 0 0 auto;+ }+ .sbe-mon-src .sbe-mon-label { color: var(--accent-bright); }+ /* The bar under each monitor: which screen this is, what is on it, and —+ on the source — the one verb. `min-height` on BOTH so the two columns+ have the same overhead above the picture, which is the assumption+ sbeFitMonitors makes when it reads the row's chrome off the program+ side. `nowrap`, because a bar that wraps changes that overhead and the+ budget silently goes wrong by a line. */+ .sbe-mon-bar {+ display: flex; align-items: center; gap: 8px; min-width: 0;+ font-size: var(--fs-xs); color: var(--muted); flex-wrap: nowrap;+ min-height: 24px; overflow: hidden;+ }+ .sbe-mon-bar .sbe-mon-name {+ min-width: 0; flex: 1 1 90px; overflow: hidden;+ text-overflow: ellipsis; white-space: nowrap;+ }+ /* The two bars under the monitors and the transport share the header's+ rung: they are the same rank of control and were 29px against 28. */+ .sbe-mon-bar .ghost-btn, .sbe-transport .ghost-btn,+ .sbe-transport .primary {+ width: auto; flex: 0 0 auto; height: var(--ctl-h-sm);+ padding-block: 0; padding-inline: 10px; font-size: var(--fs-xs);+ }+ .sbe-mon-src .sbe-stage { height: var(--sbe-src-h); }+ /* The rail takes an EXPLICIT height, never `stretch`. A stretched flex+ item still offers its content height as the line's hypothetical size,+ so a long inspector would have grown the row and pushed the picture+ back down — the budget solving itself into the opposite of what it+ was solving for. This height comes from the program column, which is+ always the taller of the two monitors, and anything longer scrolls. */+ .sbe-rail {+ flex: 0 0 auto; display: flex; flex-direction: column; gap: 8px;+ width: var(--sbe-rail-w, 240px);+ height: var(--sbe-row-h, auto); min-height: 0; overflow-y: auto;+ overflow-x: hidden;+ }+ .sbe-rail > * { flex: 0 0 auto; }+ /* WHICH CHILD SCROLLS IS THE WHOLE QUESTION, and it was answered the+ wrong way round. The inspector was the one that absorbed the rail's+ shortfall while the unplaced strip below it — an unbounded list, 695px+ at thirteen shots — never shrank. So on a 900px screen the inspector+ came out THIRTY-SIX PIXELS tall around 223px of content: "Unlink+ sound", the single entry point to the J/L feature, was off-screen, and+ the one control fully visible at the bottom of that unmarked scroll was+ Ripple delete. The inspector's content is bounded and known; the list+ is not, so the list is the scroller.+ The inspector still fills the rail when there is nothing unplaced —+ otherwise it is a 70px card floating in 255px of page background, which+ is the dead-space bug one column over. */+ .sbe-rail > .sbe-inspect {+ flex: 0 0 auto; align-content: flex-start; overflow: visible;+ }+ .sbe-rail:has(> .sbe-unplaced[hidden]) > .sbe-inspect { flex: 1 1 auto; }+ .sbe-rail > .sbe-unplaced {+ flex: 1 1 auto; min-height: 84px; overflow-y: auto;+ /* A clipped list has to READ as clipped. */+ scrollbar-color: var(--border) transparent; scrollbar-width: thin;+ }+ /* ---- the stage: ONE <video> per monitor. Double-buffering measured no+ benefit once proxies are all-intra, and two elements on one stream is+ two decoders for nothing. ---- */+ .sbe-stage {+ /* `width: 100%` + `aspect-ratio` + `max-height` DO NOT COMPOSE. A block+ box's auto width is stretch-fit, which outranks the ratio, so the cap+ won on height, the stretch won on width, and the box came out 1070x300+ — a 3.6:1 slot with a 16:9 picture floating in the middle of it and+ ~270px of black either side. That is what the owner saw and called+ warped, and it was not the video: the video was fine, the frame around+ it was the wrong shape.+ `height` (definite) + `width: fit-content` resolves the other way+ round: the ratio now feeds the intrinsic width, so the box is exactly+ as wide as the picture is tall x 16/9, and it centres. */+ position: relative; aspect-ratio: 16 / 9;+ width: fit-content; max-width: 100%; margin-inline: auto;+ /* THE PICTURE YIELDS TO THE TIMELINE, because the timeline is the+ point — and the height that expresses that now lives on+ .sbe-monitors above, where both monitors can read it and where+ sbeFitMonitors() can overwrite it with a measured one. The+ previous constant (100vh - 748px) is gone: it was measured against+ a column that was 170px shorter than this one and against a stage+ that was alone on its row. min-height keeps the frame watchable+ when the budget runs out; inside the narrow breakpoint the PAGE+ scrolls instead, so the cap relaxes there. */+ height: var(--sbe-prog-h);+ min-height: 120px;+ background: #000; overflow: hidden;+ border: 1px solid var(--border); border-radius: var(--r-md);+ box-shadow: var(--shadow-1);+ }+ /* opacity, NEVER display:none — WebKit will not load a display:none+ <video>, which is one of the two traps this feature already paid for. */+ .sbe-stage video {+ position: absolute; inset: 0; width: 100%; height: 100%;+ object-fit: contain; opacity: 0; background: #000;+ }+ .sbe-stage video.is-on { opacity: 1; }+ /* A STILL IS AN <img>, NOT A ONE-FRAME PROXY. Seeking an image is a+ no-op, so the proxy an all-intra mp4 buys would be an encode nobody+ ever plays; an <img> is exact, free, and cannot land on the wrong+ frame. Same opacity rule as the video for the same WebKit reason. */+ .sbe-stage img.sbe-still {+ position: absolute; inset: 0; width: 100%; height: 100%;+ object-fit: contain; opacity: 0; background: #000;+ }+ .sbe-stage img.sbe-still.is-on { opacity: 1; }+ .sbe-stage-badge {+ position: absolute; left: 8px; top: 8px; z-index: 3;+ background: rgba(0,0,0,0.62); border: 1px solid var(--border);+ border-radius: var(--r-xs); padding: 3px 8px;+ font-size: var(--fs-xs); color: var(--muted); pointer-events: none;+ max-width: calc(100% - 16px); overflow: hidden;+ text-overflow: ellipsis; white-space: nowrap;+ }+ .sbe-stage-empty {+ position: absolute; inset: 0; display: flex; align-items: center;+ justify-content: center; color: var(--muted); font-size: var(--fs-sm);+ text-align: center; padding: 0 24px;+ }+ /* `display: flex` above outranks the UA's [hidden] rule, so the source+ monitor's hint would never go away once a clip was loaded behind it. */+ .sbe-stage-empty[hidden] { display: none !important; }+ /* The empty timeline explains itself ON the timeline. It used to say so in+ the inspector, a short auto-scrolled box in the corner, where a new+ draft's user met the sentence starting mid-word. */+ .sbe-track-empty {+ position: absolute; inset: 0; display: flex; align-items: center;+ padding: 0 14px; color: var(--muted); font-size: var(--fs-sm);+ pointer-events: none; max-width: 640px;+ }++ .sbe-transport {+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap;+ position: relative;+ }+ /* ---- THE TIMELINE'S TOP EDGE, as a handle ------------------------+ "It needs to allow you to drag the upper side of the timeline, which+ will change the layout a little bit, enabling expansion in case you+ have some sound editing in there."++ It is a CHILD OF THE TRANSPORT, positioned over the 8px gap below it,+ so it costs the column no height of its own — sbeFitMonitors budgets+ against every child it can measure, and a 10px strip plus its gap would+ have come straight off the picture to pay for a grip. `bottom: -8px`+ puts it exactly on the seam the pointer is already aiming at. */+ .sbe-tl-grab {+ position: absolute; left: 0; right: 0; bottom: -8px; height: 10px;+ cursor: row-resize; touch-action: none; z-index: 5;+ }+ .sbe-tl-grab::after {+ content: ''; position: absolute; left: 50%; top: 4px;+ width: 46px; height: 3px; margin-left: -23px; border-radius: 999px;+ background: var(--border-strong); opacity: 0.6;+ transition: background var(--t-fast), opacity var(--t-fast);+ }+ .sbe-tl-grab:hover::after, .sbe-tl-grab:focus-visible::after,+ body.sbe-resizing .sbe-tl-grab::after {+ background: var(--accent); opacity: 1;+ }+ .sbe-tl-grab:focus-visible { outline: none; }+ /* A drag that selects the transport's labels on the way past ends with+ half the editor highlighted blue, and the cursor has to stay row-resize+ even when the pointer has run off the 10px strip it started on. */+ body.sbe-resizing { user-select: none; cursor: row-resize; }+ body.sbe-resizing .sbe-tl { border-color: var(--accent); }+ /* The mute button carries state, so it has to look like it does — a muted+ editor that looks identical to an audible one is the bug this whole pass+ is about. */+ .sbe-music-warn {+ font-size: var(--fs-xs); color: var(--warning); white-space: nowrap;+ }+ .sbe-mute { min-width: 34px; padding-left: 8px; padding-right: 8px; font-size: var(--fs-md); }+ .sbe-mute.is-off { opacity: .55; }+ .sbe-time {+ font-variant-numeric: tabular-nums; font-size: var(--fs-sm); color: var(--text);+ min-width: 104px;+ }+ .sbe-time span { color: var(--muted); }+ .sbe-approx {+ flex: 1 1 220px; font-size: var(--fs-xs); color: var(--muted);+ line-height: 1.35; min-width: 0;+ }+ /* THE SECOND SLIDER. "Normal video editors usually have two sliders: one+ to move and one to make the clips smaller." The first is the scrollbar+ on .sbe-tl below; this is the other one. The − / + buttons stay — they+ are the keyboard-free way to step through the same scale — and both+ ends of the slider are honest: its minimum is whatever px/sec puts the+ WHOLE film in the box, recomputed on every paint and every resize. */+ .sbe-zoom { display: inline-flex; gap: 6px; align-items: center; }+ .sbe-zoom .ghost-btn { width: auto; padding: 4px 9px; }+ .sbe-zoom input[type="range"] {+ width: 116px; flex: 0 0 auto; accent-color: var(--accent);+ margin: 0; cursor: ew-resize;+ }++ /* ---- the track ----+ THE SCROLLBAR IS THE "MOVE" SLIDER, AND IT HAS TO BE VISIBLE.+ `overflow-x: auto` was here from the first version and the box really+ did scroll — but macOS overlay scrollbars paint nothing until+ something is already scrolling, and nothing on a mouse scrolls a+ horizontal box. So on the owner's 71.6s film at 42 px/s the inner was+ 3031px wide inside a 1108px viewport and the last 35 seconds were+ simply unreachable: "when you get to the 36 seconds, you cannot+ scroll." Declaring ::-webkit-scrollbar opts the element out of+ overlay scrollbars in Chrome and Safari, which is the whole fix; the+ 12px it costs is in the height budget above. `scroll`, not `auto`, so+ the gutter never appears and disappears under the pointer. */+ .sbe-tl {+ position: relative; border: 1px solid var(--border);+ border-radius: var(--r-md); background: var(--bg-2);+ overflow-x: scroll; overflow-y: hidden; padding: 0;+ box-shadow: var(--shadow-1);+ /* ---- WHERE THE EDGE GESTURES END AND THE CORNER GESTURE BEGINS ----+ Declared ONCE, here, because the fade handle's position is DERIVED+ from the grip's: the two used to be written as independent numbers and+ they landed on top of each other. "Not sure that grabbing the top+ corner is working. I'm not being able to do it." — measured on his+ screen: a 12x12 fade handle at `top:0; left:0` inside a grip whose hit+ area covers the same column for the block's whole height. The fade+ owned the top 12px of that corner and the trim owned the other 40, so+ aiming at "the top corner" of a 52px block hit trim four times in five.++ The two gestures are SEPARATED IN SPACE now, not stacked:+ · the grip keeps the outer vertical strip, full height — trimming is+ an EDGE gesture and the edge is where the hand goes;+ · the fade handle sits INSET from that strip, starting exactly where+ the grip's hit area stops. The band's inset is `grip width ++ skirt`, so no arithmetic can drift: change the grip and the handle+ moves with it. Resolve puts its fade handles in the same place for+ the same reason.++ AND THE SIZE IS INDEPENDENT OF THE LANE'S HEIGHT. The 12px was a+ fraction of a lane the user can drag, so the calm-chrome rebalance+ (picture base 78 -> 64, cap 240 -> 120) shrank it without anybody+ touching it. 22px is a real target at the SHORTEST height SBE_LANES+ allows — a 52px picture block, a 37px sound strip — and it does not+ move when the lane does. `scripts/measure_editor_layout.py` measures+ both ends in a real browser and fails on either. */+ --sbe-grip-w: 9px; /* what a grip DRAWS */+ --sbe-grip-skirt: 3px; /* ...and how far past that it can be hit */+ --sbe-fade-hit: 22px; /* the fade handle's target, square */+ --sbe-fade-draw: 15px; /* ...and the triangle drawn inside it */+ /* NO `scrollbar-width` HERE, deliberately. Chrome 121+ treats the+ standard property as the authority and ignores every+ ::-webkit-scrollbar rule the moment it is present — and+ `scrollbar-width: thin` on macOS is still an OVERLAY scrollbar, which+ paints nothing until you are already scrolling. Measured: with it,+ offsetHeight - clientHeight was 2px (the borders) and there was no+ gutter at all; without it, 12px and a bar you can see and drag. */+ /* The one row that takes what the monitors leave. Without this, a+ window taller than the picture needs puts the slack UNDER the+ sticky action bar, which is a dead band; with it the track gets+ taller and the column always ends where the viewport does. */+ /* THE FLOOR IS A VARIABLE NOW, because the user owns it: the handle on+ the transport's bottom edge writes --sbe-tl-h and sbeFitMonitors+ budgets the monitors against whatever it says. It lives on the WRAPPER+ since the gutter shares the height; this row only has to fill it. */+ flex: 1 1 auto; min-width: 0; min-height: 0;+ border-radius: 0 var(--r-md) var(--r-md) 0;+ }+ .sbe-tl::-webkit-scrollbar { height: 12px; }+ .sbe-tl::-webkit-scrollbar-track { background: transparent; }+ .sbe-tl::-webkit-scrollbar-thumb {+ background: var(--border-strong); border-radius: 999px;+ border: 3px solid transparent; background-clip: content-box;+ }+ .sbe-tl::-webkit-scrollbar-thumb:hover { background-color: var(--muted); }+ .sbe-tl-inner {+ position: relative; min-width: 100%;+ display: flex; flex-direction: column; min-height: 100%;+ }+ /* Same reason .sbe > * carries it: the ruler and the waveform have exact+ heights and a flex column would otherwise shrink them. */+ .sbe-tl-inner > * { flex: 0 0 auto; }+ .sbe-ruler {+ position: relative; height: 18px; border-bottom: 1px solid var(--border);+ color: var(--muted); font-size: var(--fs-2xs); user-select: none; cursor: pointer;+ }+ .sbe-ruler i {+ position: absolute; top: 0; bottom: 0; width: 1px;+ background: var(--border);+ }+ .sbe-ruler b {+ position: absolute; top: 3px; font-weight: 500;+ transform: translateX(3px); font-variant-numeric: tabular-nums;+ }+ /* The soundtrack lane lives UNDER the picture now, so the rule that+ separates it from the track is its own top border — the track's was+ removed for the same reason, or the ruler's bottom edge would have been+ drawn twice. */+ .sbe-wave {+ display: block; width: 100%; height: var(--sbe-wave-h, 108px);+ cursor: crosshair;+ border-top: 1px solid var(--border);+ }+ .sbe-wave-none {+ height: var(--sbe-wave-h, 108px); display: flex; align-items: center; gap: 8px;+ padding: 0 10px; color: var(--muted); font-size: var(--fs-xs);+ border-top: 1px solid var(--border);+ }+ /* The lane is the positioning context for the block; the canvas keeps its+ own borders and heights, so the lane adds nothing to the 164px floor. */+ .sbe-lane { position: relative; }+ /* The per-clip sound. Slim on purpose: it is a second reading of blocks+ you have already read, and a lane as tall as the pictures would say the+ two matter equally. */+ /* THE OVERLAY LANE. Shallower than the picture track — a card is placed,+ not performed — and it sits ABOVE it so the lane order on screen is the+ stacking order in the film. */+ .sbe-ovlane {+ position: relative; height: var(--sbe-ov-h, 32px);+ border-bottom: 1px solid var(--border);+ user-select: none; touch-action: none;+ }+ .sbe-ov {+ position: absolute; top: 3px; bottom: 3px; border-radius: var(--r-xs);+ background: rgba(190,120,255,0.20); border: 1px solid #a970ff;+ color: #d9bcff; font-size: var(--fs-2xs); line-height: 22px;+ padding: 0 6px; overflow: hidden; white-space: nowrap; cursor: grab;+ }+ .sbe-ov.is-sel { box-shadow: 0 0 0 1px #a970ff; }+ .sbe-ovlane-empty {+ position: absolute; inset: 0; display: flex; align-items: center;+ padding-left: 10px; font-size: var(--fs-2xs); color: var(--muted);+ pointer-events: none; white-space: nowrap; overflow: hidden;+ }+ .sbe-ov.is-drag { cursor: grabbing; opacity: 0.85; }+ .sbe-ov-thumb {+ position: absolute; inset: 0; width: 100%; height: 100%;+ object-fit: contain; opacity: 0.35; pointer-events: none;+ }+ .sbe-ov .sbe-cl-fade { border-radius: var(--r-xs); }+ /* THE STAGE'S OWN OVERLAY, positioned over the picture and nothing else:+ the card composites over whatever is beneath, exactly as the render+ will, and carries its own opacity so its fade is independent of the+ picture's. */+ .sbe-ov-layer {+ position: absolute; inset: 0; width: 100%; height: 100%;+ object-fit: contain; pointer-events: none; display: none; z-index: 4;+ }+ .sbe-ov-layer.is-on { display: block; }+ /* THE LANE THE HANDLE EXISTS FOR. 26px was a second reading of blocks you+ had already read; it is now a waveform with a level line and draggable+ points on it, and a point you cannot hit is a control you do not have.+ Its height is the biggest share of every pixel the top edge is dragged+ — see sbeLaneHeights. */+ .sbe-alane {+ position: relative; height: var(--sbe-alane-h, 44px);+ border-top: 1px solid var(--border);+ user-select: none; touch-action: none;+ }+ .sbe-aclip {+ position: absolute; top: 3px; bottom: 3px; border-radius: var(--r-xs);+ background: rgba(88,166,255,0.14); border: 1px solid var(--border-strong);+ overflow: hidden; font-size: var(--fs-2xs); color: var(--muted);+ padding: 0 6px; line-height: 18px; white-space: nowrap;+ }+ /* LINKED IS THE DEFAULT AND IT LOOKS LIKE IT: dimmer, no grips, and it+ cannot be grabbed — a strip that moves when you did not unlink it is+ the bug this whole default exists to prevent. */+ .sbe-aclip.is-linked { opacity: 0.55; cursor: default; }+ .sbe-aclip.is-split {+ cursor: grab; border-color: var(--accent); color: var(--accent-bright);+ background: rgba(88,166,255,0.22);+ }+ .sbe-aclip.is-split.is-drag { cursor: grabbing; opacity: 0.85; }+ .sbe-aclip.is-sel { box-shadow: 0 0 0 1px var(--accent); }+ /* A strip is thinner than a block, so its grips are too — and because the+ fade handle's inset is derived from this number, saying it once here+ moves the handle with it. */+ .sbe-aclip { --sbe-grip-w: 7px; }+ /* THE WAVEFORM, behind everything else in the strip. The label sits on+ top of it with its own z-index so a loud passage cannot swallow the+ one word the strip says. */+ /* IT FILLS THE STRIP, and the `inset: 3px 0` it replaces did not: the+ height attribute the JS writes over-constrained the box, so the picture+ started 3px down and its last 3px were cut off by the strip's own+ `overflow: hidden` — the bottom of the level line, which is silence,+ was drawn outside the box. `height: 100%` outranks a presentation+ attribute, so the viewBox now maps onto the real strip whatever height+ the lane was given. */+ .sbe-wave-svg {+ position: absolute; inset: 0; width: 100%; height: 100%; z-index: 0;+ }+ .sbe-wave-p { stroke: currentColor; stroke-width: 1; opacity: 0.42; }+ .sbe-aclip-t { position: relative; z-index: 2; }+ /* THE LEVEL LINE. Unity at the TOP — a gain of 1 is all of it, and a line+ that sat in the middle at unity would read as half.+ IT HAS TO READ AS A CONTROL AT REST. "I still don't understand how to+ add keyframes": a 1.5px line at 0.9 opacity, drawn over a waveform in a+ 20px band, is decoration. Two strokes now — a dark one underneath so it+ survives a loud passage, and the line itself, opaque and 2px — and a+ third, fat and invisible, that is the TARGET. */+ .sbe-lvl {+ fill: none; stroke: var(--warning); stroke-width: 2; opacity: 1;+ pointer-events: none;+ }+ .sbe-lvl-u {+ fill: none; stroke: rgba(6,10,26,0.85); stroke-width: 4.5;+ pointer-events: none;+ }+ /* `pointer-events: stroke` makes an invisible path hittable along its+ length — this is what turns the level from something you look at into+ something you can click. */+ .sbe-lvl-hit {+ fill: none; stroke: transparent; stroke-width: 14;+ pointer-events: stroke; cursor: ns-resize;+ }+ /* THE GHOST. Where the click would put a point, drawn before it is+ clicked — the answer to "how do I add one" arriving before the+ question is finished. */+ .sbe-kf-ghost {+ fill: rgba(210,153,34,0.28); stroke: var(--warning); stroke-width: 1.5;+ stroke-dasharray: 2.5 2; pointer-events: none;+ }+ .sbe-kf {+ fill: var(--warning); stroke: #1a1200; stroke-width: 1;+ cursor: ns-resize; pointer-events: auto;+ }+ /* The dot's radius is a variable now, because the strip's height is one:+ a flat `r: 4.5` on hover SHRANK the handle on a lane that had been+ dragged tall. The 3.2px fallback is the size it has always been. */+ .sbe-kf:hover { r: calc(var(--kf-r, 3.2px) * 1.35); }+ /* The legend row inside the Keys sheet: a term and what it does. */+ .sbe-key-row {+ display: flex; gap: 8px; align-items: baseline;+ font-size: var(--fs-xs); color: var(--muted); line-height: 1.5;+ }+ .sbe-key-row b {+ flex: 0 0 74px; color: var(--text); font-weight: 600;+ display: flex; gap: 3px; align-items: center; flex-wrap: wrap;+ }+ /* A clip with no sound at all still gets a slot, and it says so rather+ than leaving a gap that reads as a bug. */+ .sbe-aclip.is-mute { background: transparent; border-style: dashed; opacity: 0.4; }+ /* ---- the inspector's three sections ----+ It grew one control at a time and had become a flat run of buttons with+ a brightness slider floating in the middle. Clip / Sound / Effects. */+ .sbe-sect { display: flex; flex-direction: column; gap: 4px; margin-top: 6px; }+ .sbe-sect-h {+ font-size: var(--fs-2xs); letter-spacing: 0.08em; text-transform: uppercase;+ color: var(--muted); font-weight: 700;+ }+ .sbe-sect-b { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }+ .sbe-fade-row { display: inline-flex; align-items: center; gap: 5px; }+ .sbe-fade-row label { font-size: var(--fs-xs); color: var(--muted); }+ .sbe-fade-num {+ width: 66px; height: var(--ctl-h-sm); padding: 0 6px;+ font-size: var(--fs-xs); font-variant-numeric: tabular-nums;+ }+ /* THE CORNER HANDLE, which is how a fade is set in every NLE ever made:+ drag the top corner inward and the ramp follows. Intuitive first; the+ numeric field beside it is the precise second. Drawn as a triangle so+ the shape itself says "ramp". */+ /* THE BAND IS WHY THE TWO HANDLES CANNOT COLLIDE WITH EACH OTHER EITHER.+ They used to be two absolutely positioned boxes at `left:0` and+ `right:0`, so on a block narrower than their combined width they+ overlapped — at 22px each that would start happening at ordinary zooms.+ A flex row inset from both grips instead: `space-between` puts one at+ each end, and `flex: 0 1` makes them SHARE a band too narrow for both+ rather than stack on it. Zero overlap is structural here, not+ arithmetic, so it holds at every zoom and every lane height with no+ magic number to keep in step.++ `pointer-events: none` on the band and `auto` on the handles: the band+ is layout, not a target, so the strip body underneath it — the level+ line, the double-click that adds a point — keeps every pixel the two+ handles are not standing on. */+ .sbe-fade-band {+ position: absolute; top: 0; z-index: 7; pointer-events: none;+ left: calc(var(--sbe-grip-w, 9px) + var(--sbe-grip-skirt, 3px));+ right: calc(var(--sbe-grip-w, 9px) + var(--sbe-grip-skirt, 3px));+ height: var(--sbe-fade-hit, 22px);+ display: flex; justify-content: space-between; align-items: stretch;+ }+ .sbe-fade-h {+ position: relative; pointer-events: auto; cursor: ew-resize;+ flex: 0 1 var(--sbe-fade-hit, 22px); min-width: 0;+ }+ /* IT HAS TO READ AS A CONTROL AT REST — the same thing that was wrong with+ the level line, and the same fix. `opacity: 0.55` on a small dark+ triangle over a clip's own thumbnail is decoration: there was nothing on+ screen to aim AT, which is half of "I'm not being able to do it". Full+ strength now, with a dark halo under it so it survives a bright frame+ (the level line spends a whole second 4.5px stroke on exactly this), and+ it grows to fill its entire target on hover — the same answer `.sbe-kf`+ gives when the pointer comes near it. */+ .sbe-fade-h::before {+ content: ''; position: absolute; top: 0;+ width: min(100%, var(--sbe-fade-draw, 15px));+ height: var(--sbe-fade-draw, 15px);+ background: var(--accent-bright);+ filter: drop-shadow(0 0 1.5px rgba(6,10,26,0.95));+ transition: width var(--t-fast), height var(--t-fast);+ }+ .sbe-fade-h.in::before { left: 0; clip-path: polygon(0 0, 100% 0, 0 100%); }+ .sbe-fade-h.out::before { right: 0; clip-path: polygon(0 0, 100% 0, 100% 100%); }+ .sbe-fade-h:hover::before {+ width: 100%; height: var(--sbe-fade-hit, 22px);+ }+ .sbe-clip.is-locked .sbe-fade-band,+ .sbe-clip.is-locked .sbe-fade-h { display: none; }+ /* The ramp itself, painted on the block so the length is visible without+ selecting the clip. */+ .sbe-cl-fade {+ position: absolute; top: 0; bottom: 0; z-index: 2; pointer-events: none;+ background: linear-gradient(90deg, rgba(0,0,0,0.66), transparent);+ }+ .sbe-cl-fade.out {+ background: linear-gradient(270deg, rgba(0,0,0,0.66), transparent);+ }+ /* THE SYNC FLAG, on BOTH halves of a pair that has drifted. Every NLE+ prints this number and nothing else does the job: the two blocks sit in+ different lanes, so "are these still together" is not a question the eye+ can answer at fit zoom. It is a button, not a warning — one click is the+ rematch — so it is the one thing inside a clip block that takes the+ pointer, and both pointerdown handlers step around it. */+ .sbe-sync {+ position: absolute; right: 4px; top: 50%; transform: translateY(-50%);+ z-index: 3; padding: 0 5px; border-radius: var(--r-xs);+ background: var(--warning); color: #1a1200; cursor: pointer;+ font-size: var(--fs-2xs); font-weight: 700; line-height: 15px;+ font-variant-numeric: tabular-nums; letter-spacing: 0.02em;+ border: 1px solid rgba(0,0,0,0.25); pointer-events: auto;+ }+ .sbe-sync:hover { filter: brightness(1.12); }+ /* Clear of BOTH grips (9px + a 3px hit-area skirt) so the flag can never+ stand between a pointer and the edge it was reaching for. */+ /* ...AND CLEAR OF THE FADE HANDLE TOO, which is the same rule applied to+ the control that has just moved into that corner. At `right: 14px` the+ flag stood in the middle of the fade-out target, and the fade handle,+ being higher in the stack, would have swallowed the clicks meant for it.+ Derived from the same three variables the handle is, so it cannot be+ left behind again; `z-index: 8` above the band is the belt to that pair+ of braces, since both pointerdown handlers already test the flag first. */+ .sbe-sync {+ right: calc(var(--sbe-grip-w, 9px) + var(--sbe-grip-skirt, 3px)+ + var(--sbe-fade-hit, 22px) + 3px);+ z-index: 8;+ }+ .sbe-clip .sbe-sync { top: 6px; transform: none; }+ .sbe-clip.has-flag .sbe-sync { top: 22px; }+ /* MUTED. The strip STAYS — it is still where the sound would be, and the+ decision has to be visible and reversible in the place it was made — so+ it is struck through rather than removed. Distinct from `.is-mute`,+ which means the FILE has no audio track at all: one is a decision and+ one is a fact about the source, and they must not read the same. */+ .sbe-aclip.is-silenced {+ background: repeating-linear-gradient(135deg,+ rgba(248,81,73,0.10), rgba(248,81,73,0.10) 5px,+ transparent 5px, transparent 10px);+ border-color: var(--danger); color: var(--danger);+ text-decoration: line-through; opacity: 0.85;+ }+ /* A COUPLED strip is not a linked one: it is offset on purpose and it+ travels with its picture, so it reads as deliberate rather than dimmed+ out. It still cannot be grabbed — the picture drags the pair. */+ .sbe-aclip.is-coupled {+ opacity: 1; cursor: default; border-style: dashed;+ border-color: var(--accent); color: var(--accent-bright);+ background: rgba(88,166,255,0.16);+ }+ /* The alarm. Deliberately the only thing in the Editor with a filled+ danger background: it must not read as one more chip in a row of chips. */+ /* ---- the one notice surface ----+ A row, not a stack: whichever notice is leading takes the width it needs+ and the others sit beside it as chips. Four full-width blocks cost ~180px+ of the timeline when they coincided, which is exactly when they matter+ least — the film they are about goes off the bottom of the screen. */+ /* Quiet by default — it is good news most of the time — and it turns into+ the danger colour on the same threshold the watchdog alarms on, so the+ chip and the banner can never disagree about whether work is safe. */+ .sbe-protected {+ font-size: var(--fs-xs); color: var(--text-dim); white-space: nowrap;+ }+ .sbe-protected[hidden] { display: none; }+ .sbe-protected.is-cold { color: var(--danger); font-weight: 600; }+ .sbe-notices {+ display: flex; align-items: stretch; gap: 8px; flex-wrap: wrap;+ }+ .sbe-notices[hidden] { display: none; }+ .sbe-notices > * { flex: 1 1 auto; min-width: 0; margin: 0; }+ /* FOLDED IS A CHIP AND NOTHING ELSE. The children keep their own markup —+ every gate that reads this HTML still finds the sentence it is looking+ for — and CSS is what decides whether it is on screen, so folding can+ never be the reason a message does not exist. */+ .sbe-notices > .is-folded {+ flex: 0 0 auto; cursor: pointer; padding: 6px 10px; gap: 0;+ font-size: var(--fs-xs); box-shadow: none;+ }+ .sbe-notices > .is-folded > * { display: none !important; }+ .sbe-notices > .is-folded::before {+ content: attr(data-short); display: inline; white-space: nowrap;+ font-weight: 600;+ }+ .sbe-notices > .is-folded::after {+ content: ' \2039 open'; opacity: 0.7; white-space: nowrap;+ }+ .sbe-alarm {+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;+ padding: 9px 12px; border-radius: var(--r-md);+ /* WHITE ON RAW DANGER RED IS 3.3:1, and the line that says WHY the save+ failed is the one thing in the Editor that has to be read under+ stress. The red moves into the surface and the border: the banner is+ still the only filled danger object on the screen, and its body text+ now clears 7:1. */+ background: rgba(248,81,73,0.16); color: var(--text);+ border: 1px solid var(--danger); font-size: var(--fs-sm);+ box-shadow: var(--shadow-2);+ }+ .sbe-alarm[hidden] { display: none; }+ .sbe-alarm b { letter-spacing: 0.01em; color: var(--danger); font-weight: 700; }+ .sbe-alarm .ghost-btn {+ width: auto; height: var(--ctl-h-sm); padding-block: 0; padding-inline: 12px;+ font-size: var(--fs-xs);+ background: var(--panel); color: var(--text); border-color: var(--danger);+ }+ /* The chip agrees with the banner. A red chip beside a red banner is one+ message; a grey chip beside a red banner is two, and the grey one wins+ the glance. */+ .sbe-state.is-alarm { color: #fff; background: var(--danger); border-color: var(--danger); }+ .sbe-state.is-alarm .sbe-dot { background: #fff; }+ /* ---- the versions panel ----+ `position: fixed` and portalled to <body>: every ancestor it was born+ under carries overflow, and a panel clipped at the header's edge is the+ bug this app has already paid for twice. */+ .sbe-vers {+ position: fixed; z-index: 120; width: 400px; max-width: calc(100vw - 24px);+ background: var(--panel); border: 1px solid var(--border-strong);+ border-radius: var(--r-md); box-shadow: var(--shadow-2);+ display: flex; flex-direction: column; overflow: hidden;+ max-height: min(60vh, 520px);+ }+ .sbe-vers[hidden] { display: none; }+ .sbe-vers > header {+ display: flex; align-items: center; gap: 8px; padding: 8px 10px;+ border-bottom: 1px solid var(--border); font-size: var(--fs-sm);+ flex: 0 0 auto;+ }+ .sbe-vers > header .ghost-btn { width: auto; padding: 4px 10px; font-size: var(--fs-xs); }+ .sbe-vers-new {+ display: flex; gap: 6px; padding: 8px 10px; flex: 0 0 auto;+ border-bottom: 1px solid var(--border);+ }+ .sbe-vers-new .sb-input { flex: 1 1 auto; min-width: 0; font-size: var(--fs-sm); }+ .sbe-vers-new .primary { flex: 0 0 auto; width: auto; padding: 6px 14px; font-size: var(--fs-sm); }+ .sbe-vers-note {+ padding: 6px 10px; font-size: var(--fs-xs); color: var(--muted);+ line-height: 1.4; flex: 0 0 auto;+ }+ .sbe-vers-list { overflow-y: auto; flex: 1 1 auto; min-height: 0; }+ /* TWO LISTS, ONE BOX, AND ONLY ONE OF THEM IS UNBOUNDED. Both carried+ `flex: 1 1 auto; min-height: 0`, so whichever had more content took the+ space: expanding fifty automatic snapshots collapsed "This film's+ drafts" — the headline of the whole feature — to an eleven-pixel+ sliver, with the row for the draft you have OPEN the one cut in half.+ A film has a handful of drafts and hundreds of saves, so the drafts are+ always shown and the saves are the grower. */+ #sbeDraftList { flex: 0 0 auto; max-height: 176px; }+ #sbeVersList { flex: 1 1 auto; min-height: 108px; }+ .sbe-vers-row {+ display: flex; align-items: center; gap: 8px; padding: 7px 10px;+ border-top: 1px solid var(--border); font-size: var(--fs-xs); min-width: 0;+ }+ .sbe-vers-row:hover { background: var(--panel-2); }+ .sbe-vers-row .ghost-btn.is-danger {+ color: var(--danger); border-color: var(--danger);+ }+ .sbe-vers-row .sbe-vr-main { min-width: 0; flex: 1 1 auto; }+ .sbe-vers-row .sbe-vr-name {+ color: var(--text); font-weight: 600; overflow: hidden;+ text-overflow: ellipsis; white-space: nowrap;+ }+ /* A version somebody stopped to name is not a breadcrumb, and the prune+ never takes it — so it does not look like one either. */+ .sbe-vers-row.is-kept .sbe-vr-name { color: var(--accent-bright); }+ .sbe-vers-row.is-bad .sbe-vr-name { color: var(--danger); }+ .sbe-vers-row .sbe-vr-meta {+ color: var(--muted); font-size: var(--fs-xs); font-variant-numeric: tabular-nums;+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ .sbe-vers-row .ghost-btn { width: auto; flex: 0 0 auto; padding: 4px 10px; font-size: var(--fs-xs); }+ .sbe-vers-empty { padding: 14px 10px; color: var(--muted); font-size: var(--fs-xs); }+ /* The automatic lane: present, reachable, and folded away. */+ .sbe-vers-auto > summary {+ padding: 7px 10px; font-size: var(--fs-2xs); letter-spacing: 0.08em;+ text-transform: uppercase; color: var(--muted); font-weight: 700;+ border-top: 1px solid var(--border); cursor: pointer;+ }+ .sbe-vers-auto > summary:hover { color: var(--text); }+ .sbe-vers-row.is-active { background: rgba(88,166,255,0.10); }+ .sbe-vers-row.is-active .sbe-vr-name { color: var(--accent-bright); }+ .sbe-vers-head {+ padding: 7px 10px 4px; font-size: var(--fs-2xs); letter-spacing: 0.08em;+ text-transform: uppercase; color: var(--muted); font-weight: 700;+ border-top: 1px solid var(--border);+ position: sticky; top: 0; background: var(--panel); z-index: 1;+ }+ /* The hint that rides on a lane heading: same line, not shouting. */+ .sbe-vers-head span {+ text-transform: none; letter-spacing: 0; font-weight: 500;+ opacity: 0.72; margin-left: 6px;+ }+ /* The unsaved dot. One pixel of state beside the draft's own name, which+ is where somebody looking for "did that land" actually looks. */+ .sbe-draft-dot {+ display: inline-block; width: 6px; height: 6px; border-radius: 50%;+ background: var(--warning); margin-right: 6px; vertical-align: middle;+ }+ .sbe-draft-dot[hidden] { display: none; }+ /* The recovery offer. Amber, not red: nothing is broken and nothing is+ lost — there is simply a choice to make. */+ .sbe-recover {+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;+ padding: 8px 12px; border-radius: var(--r-md); font-size: var(--fs-sm);+ background: rgba(210,153,34,0.14); border: 1px solid var(--warning);+ color: var(--text);+ }+ .sbe-recover[hidden] { display: none; }+ .sbe-recover .ghost-btn, .sbe-recover .primary {+ width: auto; padding: 5px 12px; font-size: var(--fs-xs); flex: 0 0 auto;+ }+ /* THE MUSIC, AS A THING YOU CAN PICK UP. Same grips, same cursors and the+ same selected outline as a clip — the owner asked for "features similar+ to what you did with the clips", and an object that behaves like a clip+ but does not LOOK like one is a second idiom to learn. Translucent,+ because the waveform underneath is what tells you where you are in the+ track while you drag it. */+ .sbe-music-clip {+ position: absolute; top: 3px; bottom: 3px; border-radius: var(--r-sm);+ border: 1px solid var(--border-strong); cursor: grab;+ background: rgba(88,166,255,0.10); z-index: 4; overflow: hidden;+ min-width: 3px;+ }+ .sbe-music-clip:hover { border-color: var(--accent); }+ .sbe-music-clip.is-sel {+ border-color: var(--accent); background: rgba(88,166,255,0.16);+ box-shadow: 0 0 0 1px var(--accent);+ }+ .sbe-music-clip.is-drag { cursor: grabbing; opacity: 0.85; }+ .sbe-music-clip[hidden] { display: none; }+ .sbe-mc-name {+ padding: 3px 8px; font-size: var(--fs-2xs); font-weight: 600;+ color: var(--accent-bright); white-space: nowrap; overflow: hidden;+ text-overflow: ellipsis; pointer-events: none;+ font-variant-numeric: tabular-nums;+ position: relative; z-index: 1;+ }+ /* THE LEVEL LINE ON THE BED, and it is the same SVG the strips carry: an+ absolute layer over the block so the label above it keeps its own box.+ `pointer-events: none` on the layer and `stroke` on the fat transparent+ path inside it — the line is a thing you can hit, the empty space around+ it belongs to the drag underneath. */+ .sbe-mc-lvl {+ position: absolute; inset: 0; pointer-events: none;+ }+ .sbe-mc-lvl svg { display: block; width: 100%; height: 100%; }+ .sbe-music-clip .sbe-lvl-hit, .sbe-music-clip .sbe-kf { pointer-events: auto; }+ .sbe-music-clip { --sbe-grip-w: 7px; }+ /* The lane grows into whatever .sbe-tl was given above its floor, and the+ blocks grow with it (top/bottom insets, not a fixed 66px). Capped, or a+ 1600px-tall display would draw 400px clip blocks. It keeps `flex: 1 1+ auto` as well as the variable: the variable is its SHARE of a dragged+ edge, the flex is what absorbs the rounding and any height the monitors+ could not use. */+ .sbe-track {+ position: relative; min-height: var(--sbe-track-h, 64px); max-height: 120px;+ flex: 1 1 auto;+ user-select: none; touch-action: none;+ }+ .sbe-clip {+ position: absolute; top: 6px; bottom: 6px; border-radius: var(--r-sm);+ background: linear-gradient(180deg, var(--panel-2), var(--panel));+ border: 1px solid var(--border-strong); overflow: hidden; cursor: grab;+ box-shadow: var(--shadow-1); transition: box-shadow var(--t-fast);+ }+ .sbe-clip:hover { border-color: var(--accent); }+ .sbe-clip.is-sel {+ border-color: var(--accent);+ box-shadow: 0 0 0 1px var(--accent), var(--shadow-2);+ }+ .sbe-clip.is-playing { border-color: var(--success); }+ .sbe-clip.is-playing::after {+ content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 2px;+ background: var(--success);+ }+ .sbe-clip.is-bad { border-color: var(--danger); box-shadow: 0 0 0 1px var(--danger); }+ .sbe-clip.is-drag { opacity: 0.8; cursor: grabbing; z-index: 20; }+ .sbe-clip.is-locked { cursor: not-allowed; }+ .sbe-clip .sbe-cl-name {+ padding: 6px 8px 0; font-size: var(--fs-xs); font-weight: 600; color: var(--text);+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;+ pointer-events: none;+ }+ .sbe-clip .sbe-cl-meta {+ padding: 2px 8px; font-size: var(--fs-2xs); color: var(--muted);+ white-space: nowrap; overflow: hidden; pointer-events: none;+ font-variant-numeric: tabular-nums;+ }+ .sbe-clip .sbe-cl-flag {+ position: absolute; right: 6px; top: 6px; font-size: var(--fs-2xs);+ letter-spacing: 0.06em; text-transform: uppercase; font-weight: 700;+ color: var(--accent-bright); pointer-events: none;+ font-variant-numeric: tabular-nums;+ }+ /* The flag is absolutely positioned, so the name runs UNDER it. It always+ did — "lock" and "slow" are short enough to hide it — and a grade like+ "-0.30" is wide enough to make it obvious. The name yields; it already+ ellipsises. */+ .sbe-clip.has-flag .sbe-cl-name { padding-right: 44px; }+ .sbe-clip[data-source="human"] .sbe-cl-name { color: var(--accent-bright); }+ /* ---- the three kinds, told apart without clicking ----+ A track whose blocks all look identical is a track you have to select+ your way through to read. A still shows its own picture behind its name;+ a slug is the only thing on the timeline that is actually black, so it+ is drawn black and says so. */+ .sbe-clip.is-still { border-style: dashed; }+ .sbe-clip .sbe-cl-thumb {+ position: absolute; inset: 0; width: 100%; height: 100%;+ object-fit: cover; opacity: 0.38; z-index: 0; pointer-events: none;+ }+ .sbe-clip .sbe-cl-name, .sbe-clip .sbe-cl-meta { position: relative; z-index: 1; }+ .sbe-clip.is-slug {+ background: #000; border-color: var(--border-strong);+ }+ .sbe-clip.is-slug .sbe-cl-name { color: var(--muted); }+ .sbe-clip.is-graded .sbe-cl-flag { color: var(--warning); }+ /* The insertion point a drop is aiming at. Painted on the track rather+ than as a cursor, because the question the user is asking is "between+ WHICH two clips", and only the track can answer that. */+ .sbe-drop-line {+ position: absolute; top: 0; bottom: 0; width: 2px; z-index: 25;+ background: var(--accent); pointer-events: none;+ box-shadow: 0 0 6px var(--accent);+ }+ .sbe-track.is-dropping { background: rgba(255,255,255,0.035); }+ .sbe-grip {+ position: absolute; top: 0; bottom: 0; width: var(--sbe-grip-w, 9px);+ z-index: 6;+ cursor: ew-resize; background: linear-gradient(90deg, rgba(255,255,255,0.10), transparent);+ }+ .sbe-grip.r { right: 0; background: linear-gradient(270deg, rgba(255,255,255,0.10), transparent); }+ /* THE TARGET IS BIGGER THAN THE PAINT. The grips sat inside the clip's+ 1px border, so the exact pixel column somebody aims at when they reach+ for an edge belonged to the MOVE handler: a drag begun on the music+ block's leftmost pixel slid the whole block instead of trimming it.+ `left: 0` covers the border column and the pseudo-element widens the+ hit area by 3px either side without widening what is drawn.++ ...AND IT MUST NOT REACH THE RIGHT ONE. This rule is written after+ `.sbe-grip.r`, so it gave the right grip `left: 0` on top of its own+ `right: 0`. An absolutely positioned box with left, right AND width all+ set is over-constrained, and in a left-to-right document the browser+ drops `right` — so BOTH grips rendered on top of each other at the LEFT+ edge of every clip. Measured in the panel: clip at x 315–455, `.l` at+ 316–325, `.r` at 316–325. The consequences are the owner's report+ exactly: the right edge of a clip had NO handle on it (hit-testing the+ last pixel column returned the block, so pulling the tail MOVED the+ clip), and the left edge hit `.r` — later in DOM order — so reaching for+ the head performed a TAIL trim. "Trying to drag the video clip from+ either edge" did something other than what the edge promised, on the+ track and on the sound lane both. `left: auto` puts it back; the 3px+ skirt still covers the border column on that side. */+ .sbe-grip { left: 0; }+ .sbe-grip.r { left: auto; right: 0; }+ /* The skirt is a VARIABLE because the fade handle's inset is measured from+ the far side of it — `grip-w + skirt` is the first pixel that is not a+ trim, and hard-coding the 3 in two places is how those two numbers drift+ apart. `measure_editor_layout.py` reads the same custom property off the+ live grip to reconstruct the rectangle a pointer actually sees. */+ .sbe-grip::before {+ content: ''; position: absolute;+ inset: 0 calc(-1 * var(--sbe-grip-skirt, 3px));+ }+ .sbe-grip:hover { background: var(--accent); }+ .sbe-clip.is-locked .sbe-grip { display: none; }+ .sbe-gap {+ position: absolute; top: 6px; bottom: 6px; border-radius: var(--r-sm);+ border: 1px dashed var(--border-strong); cursor: pointer;+ background: repeating-linear-gradient(45deg,+ rgba(255,255,255,0.03), rgba(255,255,255,0.03) 6px,+ transparent 6px, transparent 12px);+ display: flex; align-items: center; justify-content: center;+ color: var(--muted); font-size: var(--fs-xs); text-align: center;+ padding: 0 4px; overflow: hidden;+ }+ .sbe-gap:hover { border-color: var(--accent); color: var(--text); }+ .sbe-head-line {+ position: absolute; top: 0; bottom: 0; width: 2px; z-index: 30;+ background: var(--warning); pointer-events: none;+ box-shadow: 0 0 6px rgba(210,153,34,0.7);+ }++ /* ---- inspector + lists ---- */+ .sbe-inspect {+ display: flex; gap: 10px; align-items: flex-start; flex-wrap: wrap;+ background: var(--panel); border: 1px solid var(--border);+ border-radius: var(--r-md); padding: 8px 10px; font-size: var(--fs-xs);+ color: var(--muted); min-height: 38px;+ }+ .sbe-inspect b { color: var(--text); font-weight: 600; }+ /* The legend, laid out as rows rather than one run-on sentence: it is a+ reference, and a reference you have to parse is a reference nobody+ reads. */+ .sbe-keys {+ display: grid; grid-template-columns: 1fr 1fr; gap: 1px 18px;+ align-items: baseline;+ }+ .sbe-levels label { flex: 0 0 auto; }+ .sbe-inspect .sbe-why { flex: 1 1 240px; min-width: 0; }+ /* ONE SLIDER, FLAT. CapCut's Adjust panel, not Resolve's Color page —+ constant per clip, no curve, no keyframe, no wheel. */+ .sbe-adjust {+ display: flex; align-items: center; gap: 6px;+ flex: 1 1 220px; min-width: 190px;+ }+ .sbe-adjust input[type="range"] {+ flex: 1 1 auto; min-width: 80px; accent-color: var(--accent);+ }+ .sbe-adjust .sbe-adj-val {+ font-variant-numeric: tabular-nums; color: var(--text);+ min-width: 42px; text-align: right;+ }+ .ed-pool-make { display: flex; gap: 6px; align-items: center; }+ .ed-pool-make .sb-input { width: 66px; flex: 0 0 auto; }+ .ed-pool-make .ghost-btn { flex: 1 1 auto; }+ /* The thing under the pointer while a pool row is being dragged onto the+ track. PORTALLED TO <body> — inside .ed-pool-list it would be clipped+ by the list's own overflow the instant it left the column. */+ .ed-drag-ghost {+ position: fixed; z-index: 9999; pointer-events: none;+ background: var(--panel-2); border: 1px solid var(--accent);+ border-radius: var(--r-sm); padding: 4px 8px; font-size: var(--fs-xs);+ color: var(--text); box-shadow: var(--shadow-2); opacity: 0.96;+ max-width: 220px; overflow: hidden; white-space: nowrap;+ text-overflow: ellipsis;+ }+ .sbe-errs {+ background: rgba(248,81,73,0.10); border: 1px solid rgba(248,81,73,0.45);+ border-radius: var(--r-md); padding: 8px 10px; font-size: var(--fs-xs);+ color: var(--text);+ }+ .sbe-errs ul { margin: 4px 0 0; padding-left: 16px; }+ .sbe-errs li { margin: 2px 0; }+ .sbe-conflict {+ background: rgba(210,153,34,0.10); border: 1px solid rgba(210,153,34,0.5);+ border-radius: var(--r-md); padding: 8px 10px; font-size: var(--fs-xs);+ display: flex; gap: 8px; align-items: center; flex-wrap: wrap;+ }+ .sbe-prep {+ background: var(--panel); border: 1px solid var(--border);+ border-radius: var(--r-md); padding: 8px 10px; font-size: var(--fs-xs);+ color: var(--muted); display: flex; gap: 8px; align-items: center;+ flex-wrap: wrap;+ }+ /* ONE RUNG PER ROW. Measured before: an input at 37px beside a select at+ 35 beside three buttons at 29, all `align-items: center`, so no top+ edge, no bottom edge and no baseline in the row agreed. */+ .sbe-prep .sb-input, .sbe-prep select,+ .sbe-prep .ghost-btn, .sbe-prep .primary {+ height: var(--ctl-h); padding-block: 0; font-size: var(--fs-sm);+ }+ /* THE SOUNDTRACK IS A NAME, NOT A PATH. It was a 291px input holding+ "/Users/salo/pinokio/drive/drivers/peers/d17777…" truncated mid+ directory — the most machine-looking element on the screen, in the row+ the user reads first after opening a film. The full path is on the+ title and one click away. */+ .sbe-music-name {+ display: inline-flex; align-items: center; height: var(--ctl-h);+ max-width: 240px; overflow: hidden; text-overflow: ellipsis;+ white-space: nowrap; color: var(--text); font-size: var(--fs-sm);+ }+ .sbe-prep.is-editing #sbeMusicPath,+ .sbe-prep.is-editing #sbeMusicChange { display: none; }+ .sbe-prep:not(.is-editing) #sbeMusic { display: none; }+ .sbe-bar {+ flex: 1 1 140px; height: 5px; border-radius: 999px;+ background: var(--panel-2); overflow: hidden; min-width: 80px;+ }+ .sbe-bar i {+ display: block; height: 100%; background: var(--accent);+ transition: width var(--t-base);+ }+ .sbe-unplaced { display: flex; flex-direction: column; gap: 6px; }+ .sbe-unplaced-head {+ font-size: var(--fs-2xs); letter-spacing: 0.08em; text-transform: uppercase;+ color: var(--muted); font-weight: 700;+ /* The strip scrolls inside the rail now, and a heading that scrolls+ away leaves a column of unlabelled chips. */+ position: sticky; top: 0; z-index: 1;+ background: var(--panel); padding-bottom: 2px;+ }+ .sbe-chiprow { display: flex; gap: 6px; flex-wrap: wrap; }+ .sbe-chip {+ display: inline-flex; align-items: center; gap: 6px; max-width: 100%;+ background: var(--panel-2); border: 1px solid var(--border);+ border-radius: var(--r-pill); padding: 3px 5px 3px 10px;+ font-size: var(--fs-xs); color: var(--text);+ }+ .sbe-chip span { color: var(--muted); font-size: var(--fs-xs); }+ .sbe-chip button { padding: 3px 9px; font-size: var(--fs-xs); }+ /* IN THE RAIL IT IS A LIST, NOT A SHELF. The wrapping-pill idiom belongs+ on a wide horizontal strip; in a 230px column every pill wrapped+ differently, so no two rows shared a height and no two buttons shared a+ width — measured 48/48/48/32px tall with buttons at four widths — and+ the identical action read out thirteen times as "Place at 0:46.70". */+ .sbe-rail .sbe-chiprow { flex-direction: column; flex-wrap: nowrap; gap: 4px; }+ .sbe-rail .sbe-chip {+ width: 100%; flex-wrap: nowrap; justify-content: space-between;+ height: var(--ctl-h); border-radius: var(--r-sm); gap: 8px;+ }+ .sbe-rail .sbe-chip b {+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ flex: 1 1 auto; font-weight: 500;+ }+ .sbe-rail .sbe-chip span { flex: 0 0 auto; }+ .sbe-rail .sbe-chip button { flex: 0 0 auto; height: 22px; padding-block: 0; }+ /* Every other row idiom in this panel answers the pointer. */+ .sbe-chip:hover { border-color: var(--accent); }+ .sbe-params {+ font: 10.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;+ color: var(--muted); background: var(--bg-2); border: 1px solid var(--border);+ border-radius: var(--r-sm); padding: 6px 8px; margin-top: 8px;+ max-height: 132px; overflow: auto; white-space: pre-wrap;+ }+ /* Sticky, exactly like .sb-actionbar on the shot list next door: the+ inspector and the unplaced strip both grow, and a Render button that+ falls below the fold is a Render button nobody finds. */+ .sbe-actions {+ position: sticky; bottom: 0; z-index: 4;+ display: flex; gap: 8px; align-items: center; flex-wrap: wrap;+ padding: 10px 0 12px; border-top: 1px solid var(--border);+ background: linear-gradient(180deg, rgba(0,6,26,0) 0%,+ rgba(0,6,26,0.85) 22%, var(--bg) 50%, var(--bg) 100%);+ backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);+ }+ .sbe-actions .sbe-spacer { flex: 1 1 auto; }+ /* Two buttons that differ by 13px of height read as two ranks. They are+ one rank with two jobs; the FILL says which is the one you came for. */+ .sbe-actions .primary, .sbe-actions .ghost-btn {+ height: var(--ctl-h-lg); padding-block: 0; font-size: var(--fs-sm);+ }+ /* The panel's base rule is `button { width: 100% }`, and this bar never+ overrode it — so "Render the timeline" was 1590px wide, wrapped onto its+ own line, and made the sticky bar 89px tall instead of 40px. At a 1000px+ window that bar came down on top of the inspector, which is the ONLY+ surface that explains a cut. `.sb-film-actions` and `.sb-rail-step` both+ carry this same line, for this same reason. (2026-08-17 review.) */+ .sbe-actions .primary, .sbe-actions .ghost-btn { width: auto; }+ .sbe-note { font-size: var(--fs-xs); color: var(--muted); }+ .sbe-kbd {+ font: 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;+ border: 1px solid var(--border); border-radius: 4px;+ padding: 2px 4px; color: var(--muted); background: var(--panel-2);+ }+/* The panel has no layout breakpoint today. Storyboard adds one, scopedto itself so nothing else can regress. */@media (max-width: 900px) {@@ -26462,6 +32378,18 @@ HTML = r"""<!doctype html>height: auto;min-height: 0;overflow: visible;+ /* `height: auto` NEVER DID ANYTHING HERE, and the rule above has been+ promising a scrolling page since it was written. `.layout` is+ `flex: 1 1 auto` inside a `display:flex; min-height:100vh` body, so+ the flex algorithm stretched it to the leftover viewport height —+ 812px on a 900px window — whatever `height` said. The three `auto`+ rows were then squeezed into that, the form column got ~316px for+ ~730px of brief, and `overflow: visible` spilled the remaining+ ~480px straight down THROUGH the stage: the shot list and the+ timeline both had the ENGINE strip and the character picker printed+ over them. Opting out of the stretch is the whole fix — the grid+ takes its content height and the page scrolls, as advertised. */+ flex: 0 0 auto;}body[data-workflow="storyboard"] main.layout > aside.form-pane {grid-column: 1; grid-row: 1;@@ -26477,6 +32405,29 @@ HTML = r"""<!doctype html>.sb-shot-head { flex-wrap: wrap; }.sb-summary { flex-direction: column; align-items: stretch; gap: 8px; }.sb-runbar { flex-wrap: wrap; }+ /* Here the PAGE is the scroller, not #sbStage, so the picture is not+ competing with the track for a fixed box and the tight third term of+ its cap would only make it small for nothing. */+ /* The var, not the element: both monitors read it, and sbeFitMonitors+ is told to stand down at this width (there is no fixed column to+ budget against once the page is the scroller). Side by side, two+ 16:9 frames in a ~880px page are two postage stamps, so they stack+ and the source goes second — it is the one you are done with. */+ .sbe-monitors {+ flex-direction: column; align-items: stretch;+ --sbe-prog-h: min(38vh, 340px);+ --sbe-src-h: min(30vh, 260px);+ }+ .sbe-monitors .sbe-mon-prog { order: 1; }+ .sbe-monitors .sbe-mon-src { order: 2; }+ /* Stacked, the rail is a row again and takes its own height back. */+ .sbe-rail { order: 3; width: auto; height: auto; overflow: visible; }+ .sbe-time { min-width: 0; }+ /* NO HANDLE HERE, and sbeFitMonitors stands down at the same width for+ the same reason: the page is the scroller, the column has no fixed+ height, and there is nothing for the timeline to take height FROM. A+ grip that moved nothing would be worse than no grip. */+ .sbe-tl-grab { display: none; }}/* =========================================================@@ -27776,6 +33727,7 @@ HTML = r"""<!doctype html>Mirrors the train workflow rules above. */body[data-workflow="characters"] #modelsInline,body[data-workflow="characters"] #modeGroup,+ body[data-workflow="characters"] #remixSubGroup,body[data-workflow="characters"] aside.form-pane > h2,body[data-workflow="characters"] #genForm,body[data-workflow="characters"] #studioSection { display: none !important; }@@ -27788,6 +33740,7 @@ HTML = r"""<!doctype html>which workflowSwitch calls when entering this branch. */body[data-workflow="studio"] #modelsInline,body[data-workflow="studio"] #modeGroup,+ body[data-workflow="studio"] #remixSubGroup,body[data-workflow="studio"] aside.form-pane > h2,body[data-workflow="studio"] #genForm,body[data-workflow="studio"] #trainSection,@@ -32160,6 +38113,23 @@ HTML = r"""<!doctype html>-webkit-backdrop-filter: blur(12px);overflow: hidden;}+ /* THE END OF THE BAR IS NOT THE PART THAT SHOULD YIELD. `nowrap` ++ `overflow: hidden` means the LAST element is cut rather than wrapped or+ shrunk, and at 1440 the creator link ran 9px past the viewport with no+ scroll to recover it: "by Biz", the X icon gone. The middle of the bar+ is the part that can afford to give — so the status cluster shrinks and+ the two right-hand links never do. Below 1500 the words go and the+ marks stay. */+ body > header > *:not(.brand):not(.creator-link):not(.icon-btn):not(.phosphene-x-link) {+ min-width: 0;+ }+ body > header .creator-link,+ body > header .phosphene-x-link,+ body > header .icon-btn { flex: 0 0 auto; }+ @media (max-width: 1500px) {+ body > header .creator-link > span:not(.x-icon) { display: none; }+ body > header .creator-link { padding-right: 8px; }+ }body > header .brand {display: inline-flex;align-items: center;@@ -32740,7 +38710,13 @@ HTML = r"""<!doctype html>border: 1px solid var(--ph-border-soft);border-radius: 7px;width: auto;- max-width: max-content;+ /* IT MUST WRAP. `max-content` + nowrap ran the strip past the right+ edge of a narrow form pane, and the pane clips — so the last tabs+ were simply not there to click. That is how the Train tab went+ missing once, and the Editor tab is the sixth. Capped at the+ column, not at the content. */+ flex-wrap: wrap;+ max-width: calc(100% - 36px);}.workflow-tabs button {/* Override the global `button { width: 100% }` rule. Without@@ -33215,6 +39191,7 @@ HTML = r"""<!doctype html><symbol id="ph-download-simple" viewBox="0 0 256 256"><line x1="128" y1="144" x2="128" y2="32" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="216 144 216 208 40 208 40 144" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><polyline points="168 104 128 144 88 104" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-film-slate" viewBox="0 0 256 256"><path d="M216,112H40a8,8,0,0,0-8,8v88a8,8,0,0,0,8,8H216a8,8,0,0,0,8-8V120A8,8,0,0,0,216,112Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M32,112,50.6,44.7a8,8,0,0,1,9.8-5.6L213.3,80.4a8,8,0,0,1,5.6,9.8L213,112" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="110.1" y1="59.5" x2="83.2" y2="112" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="163.9" y1="74" x2="137" y2="112" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-film-strip" viewBox="0 0 256 256"><rect x="32" y="48" width="192" height="160" rx="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="128" y1="48" x2="128" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="32" y1="80" x2="224" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="32" y1="176" x2="224" y2="176" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="80" y1="48" x2="80" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="176" y1="48" x2="176" y2="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="80" y1="176" x2="80" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="176" y1="176" x2="176" y2="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>+<symbol id="ph-scissors" viewBox="0 0 256 256"><circle cx="76" cy="68" r="28" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="76" cy="188" r="28" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96.9" y1="86.6" x2="200" y2="200" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="96.9" y1="169.4" x2="200" y2="56" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-gear-six" viewBox="0 0 256 256"><circle cx="128" cy="128" r="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M130.05,206.11c-1.34,0-2.69,0-4,0L94,224a104.61,104.61,0,0,1-34.11-19.2l-.12-36c-.71-1.12-1.38-2.25-2-3.41L25.9,147.24a99.15,99.15,0,0,1,0-38.46l31.84-18.1c.65-1.15,1.32-2.29,2-3.41l.16-36A104.58,104.58,0,0,1,94,32l32,17.89c1.34,0,2.69,0,4,0L162,32a104.61,104.61,0,0,1,34.11,19.2l.12,36c.71,1.12,1.38,2.25,2,3.41l31.85,18.14a99.15,99.15,0,0,1,0,38.46l-31.84,18.1c-.65,1.15-1.32,2.29-2,3.41l-.16,36A104.58,104.58,0,0,1,162,224Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-image" viewBox="0 0 256 256"><rect x="32" y="48" width="192" height="160" rx="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="156" cy="100" r="12"/><path d="M147.31,164,173,138.34a8,8,0,0,1,11.31,0L224,178.06" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M32,168.69l54.34-54.35a8,8,0,0,1,11.32,0L191.31,208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol><symbol id="ph-info-fill" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z"/></symbol>@@ -33467,6 +39444,10 @@ HTML = r"""<!doctype html>yesterday, plus one calm word. The count span is filled only whilea storyboard render is actually in flight. --><button data-workflow="storyboard"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-film-slate"/></svg>Storyboard<span class="new-badge sb-live" id="sbTabCount" hidden></span></button>+ <!-- The Editor is a PLACE, not a room inside the Storyboard. It opens+ with no board, on clips from any engine, and it stays open while+ you go and look at something else. -->+ <button data-workflow="editor"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-scissors"/></svg>Editor</button><button data-workflow="audio"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-music-notes"/></svg>Audio<span class="new-badge">NEW</span></button><button data-workflow="train"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-user-plus"/></svg>Train Character</button></nav>@@ -35827,6 +41808,25 @@ HTML = r"""<!doctype html>onclick="downloadSampleCharacter()">get a sample character (Bizarro)</button>.</div><div class="chars-q4-note">__Q8_CHARACTER_INSTALL_COPY__</div>+ <!-- Wardrobe rides with the CHARACTER, not the shot. "A man in a dark+ suit" is a different suit every time it is re-rolled — measured:+ four shots of one man came back in two suits and two different+ period collars. -->+ <input type="text" id="sbWardrobe" class="sb-input" style="margin-top:8px"+ placeholder="what they wear in this film — e.g. a loud floral Hawaiian shirt, collar open">+ </div>++ <!-- LOCATIONS. A model re-invents everything the prompt does not pin, so+ four shots that each said "dim room" came back as four different+ rooms — one of them a vintage parlour with no monitors in it. Writing+ the room ONCE and injecting it into every shot that claims it is the+ only thing that survives shots being re-rendered one at a time. -->+ <div class="cz-control" id="sbLocRow">+ <div class="cz-label">Where it happens+ <span class="cz-label-hint">one line per place — shots reuse them</span></div>+ <textarea id="sbLocations" class="sb-textarea" rows="3" oninput="sbLocInput()"+ placeholder="the study: dark oak panelling, three curved monitors glowing cold blue, a brass desk lamp the driveway: bright suburban driveway, red convertible, late afternoon sun"></textarea>+ <div class="cz-meta" id="sbLocMeta">no locations — every shot invents its own</div></div><details class="customize-section" id="sbMustSection">@@ -36008,6 +42008,65 @@ HTML = r"""<!doctype html></div></div>++ <!-- ============== THE MEDIA POOL — the Editor's left column ==========+ What replaced a window.prompt(). Until Wave 1 the only way to bring a+ clip into a cut was a native text box asking the user to type the+ NUMBER of a film from a numbered list — while the outputs gallery,+ which holds every clip this panel has ever made, was display:none for+ the whole surface. The owner's ask was one sentence: "pick from the+ generations whatever you want."++ Three sources, one verb. Clicking a row puts the clip on the END of+ the track, builds its proxy, saves, and leaves you exactly where you+ were. Drag is Wave 2; click is the floor. -->+ <div id="edSectionTab" style="display:none">+ <header class="carousel-head ed-pool-head">+ <h3>Media pool</h3>+ <span class="ch-spacer"></span>+ <!-- BRING YOUR OWN. A title card, a logo, a phone clip — the pool+ showed everything the panel MADE and nothing the user already+ had. The input is hidden because a bare file input cannot be+ styled to look like anything else in this panel; the button is+ the control. Shown on the Images source, which is where what it+ uploads appears. -->+ <input type="file" id="edPoolFile" multiple hidden+ accept=".png,.jpg,.jpeg,.webp,.mp4,.mov,.m4v,.webm"+ onchange="edPoolUpload(this.files); this.value = '';">+ <button type="button" class="ghost-btn" id="edPoolUploadBtn" hidden+ onclick="document.getElementById('edPoolFile').click()"+ title="Add a picture or a clip from this Mac. Pictures land as stills, clips land as clips.">Upload</button>+ <button type="button" class="ghost-btn" id="edPoolRefreshBtn"+ onclick="edPoolRefresh(true)" title="Re-read the clips on disk">Refresh</button>+ </header>+ <div class="ed-pool-tabs" id="edPoolTabs">+ <button type="button" class="pill-btn active" data-src="film">This __SEQCAP__</button>+ <button type="button" class="pill-btn" data-src="other">Other __SEQS__</button>+ <button type="button" class="pill-btn" data-src="gallery">Generations</button>+ <!-- IMAGES. The gallery has always held them — the image queue drops+ every render into panel_uploads/library/manual — and until a clip+ could be a STILL there was nothing a timeline could do with one. -->+ <button type="button" class="pill-btn" data-src="images">Images</button>+ </div>+ <!-- BLACK IS NOT SOMETHING YOU PICK FROM A LIST. It has no file, so it+ has no row; it is made, with a length, which is its only property. -->+ <div class="ed-pool-make">+ <input type="number" class="sb-input" id="edSlugSecs" value="2.0"+ min="0.2" max="60" step="0.5" aria-label="Seconds of black">+ <button type="button" class="ghost-btn" id="edAddSlugBtn"+ onclick="edAddSlug()"+ title="Black, for as long as you say. No file, no proxy — it is drawn by the render.">Add black</button>+ </div>+ <select class="sb-input ed-pool-film" id="edPoolFilm" hidden+ onchange="edPoolPickFilm(this.value)"+ aria-label="Which __SEQ__ to take clips from"></select>+ <input type="text" class="sb-input ed-pool-search" id="edPoolSearch"+ spellcheck="false" placeholder="Filter by name"+ oninput="edPoolPaint()">+ <div class="ed-pool-list" id="edPoolList"></div>+ <div class="ed-pool-note" id="edPoolNote"></div>+ </div>+</aside><!-- ============== STAGE PANE: PLAYER + CAROUSEL ============== -->@@ -36023,6 +42082,35 @@ HTML = r"""<!doctype html>(#filterAll/#filterHidden retired with the Visible/Hiddensegmented control — orphan textContent/setFilter calls removed.) --><section class="stage-pane">+ <!-- ============== THE RAIL ==================================+ Four steps, one place, every screen that has a board open —+ ABOVE the player, first thing in the pane, because this is the+ navigation and the video is the content. It lived inside+ #sbStage (the slot BELOW the player) and the owner read that,+ correctly, as the menu jumping underneath the example video.+ Shown only while the storyboard workflow is active, so+ "where am I / what is next / how do I get to the editor" has one+ answer instead of none. Painted by sbRailPaint() from sbRailModel(),+ which is pure and under test. -->+ <nav class="sb-rail" id="sbRail" hidden aria-label="This film, step by step">+ <button type="button" class="sb-rail-back" onclick="sbBackToList()"+ title="Every storyboard on this Mac">All storyboards</button>+ <button type="button" class="sb-rail-step" data-step="plan" onclick="sbGo('plan')">+ <span class="sb-rail-n">1</span><span class="sb-rail-t">Plan</span>+ <span class="sb-rail-sub" data-sub="plan"></span></button>+ <span class="sb-rail-sep" aria-hidden="true"></span>+ <button type="button" class="sb-rail-step" data-step="shots" onclick="sbGo('shots')">+ <span class="sb-rail-n">2</span><span class="sb-rail-t">Shots</span>+ <span class="sb-rail-sub" data-sub="shots"></span></button>+ <span class="sb-rail-sep" aria-hidden="true"></span>+ <button type="button" class="sb-rail-step" data-step="edit" onclick="sbGo('edit')">+ <span class="sb-rail-n">3</span><span class="sb-rail-t">Edit</span>+ <span class="sb-rail-sub" data-sub="edit"></span></button>+ <span class="sb-rail-sep" aria-hidden="true"></span>+ <button type="button" class="sb-rail-step" data-step="film" onclick="sbGo('film')">+ <span class="sb-rail-n">4</span><span class="sb-rail-t">Film</span>+ <span class="sb-rail-sub" data-sub="film"></span></button>+ </nav><!-- Ideogram Layout editor: the placement canvas (#ideoStageWrap) portalsinto #ideoCanvasHost here in the big right column, and the Edit/Resulttoggle flips between the canvas and the rendered output. Both are@@ -36230,6 +42318,7 @@ HTML = r"""<!doctype html>and exactly one is visible at a time. --><div id="sbStage">+<!-- Empty: no board open, none on disk. --><div class="sb-empty" id="sbEmpty" hidden><div class="sb-empty-icon">@@ -36290,7 +42379,9 @@ HTML = r"""<!doctype html><button type="button" class="smt-btn active" data-sb-stage="list" onclick="sbSetStage('list')">Shot list</button><button type="button" class="smt-btn" data-sb-stage="player" onclick="sbSetStage('player')">Player</button></div>- <button type="button" class="ghost-btn" onclick="sbBackToList()">All storyboards</button>+ <!-- "All storyboards" used to sit here. It lives on the rail now,+ with the rest of the navigation, so there is one place to look+ rather than a different one on every stage state. --></header><div class="sb-runbar engine-hint" id="sbRunBar" hidden>@@ -36361,13 +42452,563 @@ HTML = r"""<!doctype html><div class="sb-actionbar sb-tally" id="sbTally" hidden title="Focus a shot and press K, R or C"><span id="sbTallyText">nothing graded yet</span><span class="sb-actionbar-spacer"></span>+ <!-- The timeline used to be the fifth button in this row of five,+ which is exactly why nobody found it. It is step 3 on the rail+ now — always on screen, in the same place on every state — and+ this bar is left to do its own job: grade, then finish. --><button type="button" class="ghost-btn" id="sbExportBtn" onclick="sbExport()" hidden>Export</button><button type="button" class="ghost-btn" id="sbRewriteBtn" onclick="sbRewrite()" hidden>Rewrite</button><button type="button" class="ghost-btn" id="sbResumeBtn" onclick="sbRenderRemaining()" hidden>Render remaining</button><button type="button" class="primary" id="sbFinishBtn" onclick="sbFinish()">Finish keepers</button></div>- <div class="sb-export-note" id="sbExportNote" hidden>Assembling these into a single cut is a script for now — <code>scripts/</code> has the After Effects pass. One-click assembly is not in this version.</div>+ <div class="sb-export-note" id="sbExportNote" hidden>Export writes a folder with every kept shot, a shot list, and <strong>one playable film</strong>. If you have cut this film in the Editor, that film IS your cut — same clips, same trims, same soundtrack, same filename the Editor's own Render writes. Otherwise it is the shots joined in order, mixed sizes normalised to the largest. The clips in the gallery are never touched.</div>+ </div>++ <!-- ============== THE FILM — the point of the other six ===========+ A render or an export writes an mp4 into mlx_outputs/storyboards/+ and, until this screen existed, told nobody. The gallery could not+ help: it globs OUTPUT/*.mp4 and never descends. So the one thing the+ feature makes was the one thing it could not show you.++ Everything here is painted by sbFilmPaint() from /storyboard/films,+ which reads the folder the assemblers already write into. No new+ storage, no second source of truth. -->+ <div class="sb-plan sb-film" id="sbFilm" hidden>+ <header class="carousel-head">+ <h3>The film</h3>+ <span class="sb-plan-status" id="sbFilmStatus"></span>+ <span class="ch-spacer"></span>+ </header>+ <div id="sbFilmBody"></div>+ </div>+ </div>+++ <!-- ============== THE EDITOR — its own window ======================+ Wave 1 of the Editor restructure (2026-08-17). The timeline used to+ be the sixth state of #sbStage, which made it a room inside the+ storyboard rather than a place of its own: it could not open without+ a board, it died on a tab switch, and its picture was whatever the+ shot list left over. It is a top-level workflow now — engine-+ agnostic, always reachable, one document at a time.++ #edStage is the editor's scroller, the exact counterpart of+ #sbStage. The media pool lives in the form pane (#edSectionTab), so+ this column is the viewer and the track and nothing else. -->+ <div id="edStage">++ <!-- No document open. Not an error state: the Editor is reachable+ from a cold boot with nothing on disk, and this is what it says+ then. The film list is painted by edPaintEmpty(). -->+ <div class="sb-empty" id="edEmpty" hidden>+ <div class="sb-empty-icon">+ <svg width="56" height="56" viewBox="0 0 256 256" aria-hidden="true"><use href="#ph-film-strip"/></svg>+ </div>+ <div class="sb-empty-title">Pick a __SEQ__ to cut.</div>+ <div class="sb-empty-sub">The Editor opens one timeline at a time. Choose a __SEQ__ below, or add clips from the media pool on the left — anything in your generations can go straight onto the track.</div>+ <div class="ed-pick" id="edPick"></div>+ </div>++ <!-- ============== THE TIMELINE — arrangement, not intent ==========+ The sixth stage state. The shot list above says WHAT the film+ contains; this says what plays, from which second of which file, at+ which second of the film. Two documents, side by side on disk+ (storyboard.json / edit.json), for the reason storyboard_editor.py+ gives at length: the moment one shot is used twice they are+ different shapes forever.++ Everything here is proxy-driven. A source clip is a single GOP —+ 235 ms to seek in Chrome, measured — and a timeline is a machine+ for seeking. The proxies are all-intra and seek in 3.5 ms. -->+ <div class="sb-plan sbe" id="sbTimeline" hidden>+ <!-- THE COMMAND BAR. Identity on the left — what am I cutting, which+ draft, is it saved — and four verbs on the right. It was eleven+ controls in one row, all drawn identically, so the safest thing on+ the screen and the one that LEAVES looked alike. Navigation nests+ under the ⋯; the only filled control on the screen is Render. -->+ <header class="carousel-head sbe-head">+ <span class="sbe-title" id="sbeTitle">Editor</span>+ <!-- WHICH DOCUMENT AM I CUTTING, and which of its drafts. Identity, so+ it sits beside the name rather than among the verbs. -->+ <button type="button" class="ghost-btn sbe-draftchip" id="sbeKeepBtn"+ onclick="sbeVersionsOpen(true)"+ title="New draft, duplicate, rename — and every draft this __SEQ__ has">+ <span id="sbeDraftDot" class="sbe-draft-dot" hidden></span><span id="sbeDraftName">Draft</span><span class="sbe-car">▾</span>+ </button>+ <span class="sbe-state" id="sbeState"><i class="sbe-dot"></i><span id="sbeStateText">loading…</span></span>+ <!-- WHEN THE NET LAST CAUGHT THIS TAB. A dead snapshot lane used to be+ invisible: the only way to find out was to list a history folder+ AFTER losing something. This says it in the one place a person+ already looks to find out whether their work is safe. -->+ <span class="sbe-protected" id="sbeProtected" hidden></span>+ <span class="ch-spacer" style="flex:1 1 auto"></span>+ <!-- One gesture, two directions: a segmented pair rather than two+ free-standing buttons that happen to sit next to each other. -->+ <span class="sbe-undogroup">+ <button type="button" class="ghost-btn" id="sbeUndoBtn" onclick="sbeUndo()" title="Undo (⌘Z)" disabled>Undo</button>+ <button type="button" class="ghost-btn" id="sbeRedoBtn" onclick="sbeRedo()" title="Redo (⇧⌘Z)" disabled>Redo</button>+ </span>+ <button type="button" class="ghost-btn" id="sbeSaveBtn" onclick="sbeSaveNow()"+ title="Save now and say so. The editor also saves on its own, quietly, a second after every edit.">Save</button>+ <!-- RENDER CAME UP, NOT OUT. It was the far corner of a sticky bar at+ the bottom of the column, 54px of chrome under the timeline to+ hold two buttons; it is the one thing this screen is FOR, so it is+ the one filled control on it. Export nests under the caret, with+ the render note, because it is the same verb pointed elsewhere. -->+ <span class="sbe-split">+ <button type="button" class="primary" id="sbeRenderBtn" onclick="sbeRenderFilm()"+ title="Render this timeline into one file (⌘R)">Render</button>+ <button type="button" class="primary sbe-car-btn" id="sbeRenderMore"+ onclick="sbePopToggle('sbeRenderMenu', 'sbeRenderMore')"+ aria-haspopup="menu" title="Export, and what the render will do">▾</button>+ </span>+ <button type="button" class="ghost-btn sbe-kebab" id="sbeMoreBtn"+ onclick="sbePopToggle('sbeMoreMenu', 'sbeMoreBtn')"+ aria-haspopup="menu" title="Drafts, soundtrack, media pool, auto-edit, storyboard, close">⋯</button>+ </header>++ <!-- THE FOUR POPOVERS. Their contents are the REAL controls, moved+ rather than rebuilt: every id the client already writes to is still+ here, so nothing that pokes at a button has to learn a new home.+ They are `position: fixed` and hidden, so an open menu cannot push+ the workspace around — the same rule the notice surface follows. -->+ <div class="sbe-pop" id="sbeRenderMenu" hidden>+ <button type="button" class="ghost-btn" id="sbeNleBtn" onclick="sbeExportNle()"+ title="A folder with an FCP7 XML (Premiere + Resolve), an After Effects script, and hardlinked media. Audio comes out as stems, not the ducked mix.">Export for Premiere / Resolve / AE</button>+ <span class="sbe-pop-note" id="sbeRenderNote"></span>+ </div>++ <div class="sbe-pop" id="sbeMoreMenu" hidden>+ <button type="button" class="ghost-btn" id="sbeVersBtn" onclick="sbeVersionsOpen(false)"+ title="Every draft this __SEQ__ has, and every past save of this one">Drafts and versions…</button>+ <button type="button" class="ghost-btn" id="sbeImportBtn" onclick="edPoolFocus()"+ title="This __SEQ__'s shots, other __SEQS__' clips, and everything in your generations.">Media pool</button>+ <button type="button" class="ghost-btn" id="sbeAutoBtn" onclick="sbeAuto()"+ title="Re-cuts the __SEQ__ from scratch. Throws away this arrangement.">Auto-edit…</button>+ <span class="sbe-pop-sep"></span>+ <button type="button" class="ghost-btn" id="sbeBoardBtn" onclick="sbeGoToBoard()"+ title="Open this __SEQ__'s shot list in the Storyboard tab" hidden>Storyboard</button>+ <button type="button" class="ghost-btn" id="sbeCloseBtn" onclick="sbeClose()"+ title="Close this timeline (Esc). Nothing is deleted.">Close</button>+ </div>++ <div class="sbe-pop sbe-pop-wide" id="sbeKeysPop" hidden>+ <span class="sbe-note sbe-keys" id="sbeKeys"></span>+ </div>+ <div class="sbe-pop sbe-pop-wide" id="sbeMusicMenu" hidden>+ <span class="sbe-pop-note" id="sbePrepText">The soundtrack drives the waveform and the beat grid.</span>+ <input type="text" class="sb-input" id="sbeMusic" spellcheck="false"+ onblur="sbeMusicEditPath(false)"+ placeholder="/path/to/the/soundtrack.wav">+ <span class="sbe-pop-row">+ <button type="button" class="ghost-btn" id="sbeMusicChange"+ onclick="sbeMusicEditPath(true)"+ title="Point at a different audio file">Change…</button>+ <button type="button" class="ghost-btn" id="sbePrepBtn" onclick="sbePrepare()">Prepare</button>+ <button type="button" class="ghost-btn" id="sbePrepCancel" onclick="sbePrepareCancel()" hidden>Cancel</button>+ </span>+ <span class="sbe-bar" id="sbePrepBar" hidden><i style="width:0%"></i></span>+ <span class="sbe-music-warn" id="sbeMusicWarn" hidden></span>+ </div>+++ <!-- ONE SURFACE, NOT FOUR. Conflict, save-alarm, recovery and the+ validation list are four full-width blocks stacked in the same+ column, and they are not mutually exclusive — the day the overlap+ rule refused a J-cut the owner had three of them on screen at once,+ the timeline pushed off the bottom, and the sentence that mattered+ was the third one down. They still exist as themselves; the+ container shows the most urgent OPEN and folds the rest to a chip+ you click to read. -->+ <div class="sbe-notices" id="sbeNotices"+ onclick="sbeNoticeClick(event)" hidden>+ <div class="sbe-conflict" id="sbeConflict" data-short="Version conflict" hidden>+ <span id="sbeConflictText"></span>+ <span style="flex:1 1 auto"></span>+ <button type="button" class="ghost-btn" onclick="sbeTakeTheirs()">Load theirs</button>+ <button type="button" class="ghost-btn" onclick="sbeForceSave()">Keep mine</button>+ </div>++ <!-- SAVING IS FAILING. Not a status — an emergency, and the loudest+ thing this screen can say. The owner cut for twenty minutes against+ a timeline that was not being written, and the only thing that knew+ was a small grey chip reading "not saved". This says it in words+ nobody can read past, names the reason, and does not go away until a+ save actually lands. -->+ <div class="sbe-alarm" id="sbeAlarm" data-short="Saving is failing" hidden>+ <b>SAVING IS FAILING — your changes are not being stored.</b>+ <span id="sbeAlarmWhy"></span>+ <span style="flex:1 1 auto"></span>+ <button type="button" class="ghost-btn" onclick="sbeSaveNow()">Try again</button>+ </div>++ <!-- THE RECOVERY OFFER. A backup newer than the saved draft is a+ question, never an action: the autosave the owner asked us to+ remove would be exactly this, applied without asking. It says what+ is in the backup so the choice can be made on facts. -->+ <!-- NO RECOVERY WALL. This was a full-width bar with a primary button,+ asking a question that had to be answered before the film could be+ worked on — and asking it over a document that had loaded correctly,+ because the comparison behind it counted a rewritten `proxy`+ pointer as a difference. It is now the quietest thing on the+ screen: a chip that says a snapshot exists and offers to open the+ place where snapshots live. Content-equal shows nothing at all.+ See docs/EDITOR_SAVE_MODEL.md §4. -->+ <div class="sbe-recover" id="sbeRecover" data-short="Unsaved snapshot"+ data-quiet="1" hidden>+ <b>Unsaved snapshot</b>+ <span id="sbeRecoverWhat"></span>+ <span style="flex:1 1 auto"></span>+ <button type="button" class="ghost-btn" onclick="sbeVersionsOpen()">Open Versions</button>+ <button type="button" class="ghost-btn" onclick="sbeRecover()">Restore it</button>+ <button type="button" class="ghost-btn" onclick="sbeDiscardBackup()">Discard</button>+ <!-- DISMISSIBLE WITHOUT ANSWERING. Discard DELETES the backup, so it+ is not the button for "not now" — and with no third option the+ bar sat across the top of the film for the rest of the session+ over a question the user was not ready to answer. This one hides+ it and touches nothing; it is back on the next read. -->+ <button type="button" class="ghost-btn" onclick="sbeNoticeLater()">Later</button>+ </div>++ <div class="sbe-errs" id="sbeErrors" data-short="Not saved" hidden></div>++ <!-- THE AUTO-KEY RECEIPT. "If the picture comes in a format that doesn't+ work, automatically make it work" — and then say so. A card whose+ alpha channel declared a black backdrop opaque was keyed on its way+ to the overlay lane; the original file was NOT touched, and this is+ the one click back to it. Quiet, because nothing here went wrong,+ and because a receipt that took the width would push the timeline+ down the screen for a change the user is going to keep. -->+ <div class="sbe-recover" id="sbeKeyed" data-short="Black background removed"+ data-quiet="1" hidden>+ <b>Black background removed</b>+ <span id="sbeKeyedWhat"></span>+ <span style="flex:1 1 auto"></span>+ <button type="button" class="ghost-btn" onclick="sbeKeyedKeepOriginal()">Keep original</button>+ <button type="button" class="ghost-btn" onclick="sbeKeyedDismiss()">Dismiss</button>+ </div>+ </div>++ <!-- THE DRAFTS PANEL. Declared here so it is real markup a gate can+ read, and PORTALLED TO <body> the first time it opens: the editor+ header and the stage column both carry overflow, and a panel+ rendered inside either is sliced at its edge — the same clipping+ that cut the avatar off the header and the drag ghost off the pool.+ Positioned fixed, under the button that opened it. -->+ <div class="sbe-vers" id="sbeVersions" hidden>+ <header>+ <b>Drafts</b>+ <span style="flex:1 1 auto"></span>+ <button type="button" class="ghost-btn" onclick="sbeVersionsClose()">Close</button>+ </header>+ <!-- NEW DRAFT. Two doors on purpose: an empty timeline to start an+ idea from nothing, and a copy of what is on screen to try a+ variation without risking the cut it came from. "He should be+ able to start a new draft and work on it, as well as copy and+ paste drafts." -->+ <div class="sbe-vers-new">+ <input type="text" class="sb-input" id="sbeVersName" maxlength="60"+ spellcheck="false" placeholder="Name a draft, or this save…"+ onkeydown="if (event.key === 'Enter') { event.preventDefault(); sbeNameEnter(); }">+ <button type="button" class="primary" id="sbeVersKeep"+ onclick="sbeNameEnter()"+ title="A new draft holding a copy of the timeline on screen">Copy</button>+ <button type="button" class="ghost-btn" id="sbeDraftEmpty"+ onclick="sbeDraftNew(false)"+ title="A new draft with an empty timeline (the soundtrack comes with it)">Empty</button>+ <!-- NAMING A SAVE IS NOT SAVING ONE, and it is not making a draft+ either — it marks the save already on disk so the fifty-save+ prune can never take it. The route has been alive and+ documented the whole time; the drafts rewrite left the panel+ with no way to reach it, while the history went on rendering+ named saves in their own accent because the owner's film+ already contains one. -->+ <button type="button" class="ghost-btn" id="sbeKeepSaveBtn"+ onclick="sbeKeepVersion()"+ title="Give the save on disk a name, so it is never pruned">Keep</button>+ </div>+ <div class="sbe-vers-list" id="sbeDraftList"></div>+ <div class="sbe-vers-note" id="sbeVersNote"></div>+ <div class="sbe-vers-list" id="sbeVersList"></div>+ </div>++ <!-- DRAFT → DELIVERY. "Finish keepers" renders full-size files, and+ until Wave 1 the timeline went on pointing at the drafts it was cut+ from — so the delivery pass produced files the film never used, and+ the next Prepare pruned their proxies. Detected on the server (see+ _sbe_relinks), never applied without this button: the arrangement is+ the human's. -->+ <div class="sbe-relink" id="sbeRelink" hidden>+ <span id="sbeRelinkText"></span>+ <span class="sbe-relink-why">Same cuts, same timings — only the files change.</span>+ <span style="flex:1 1 auto"></span>+ <button type="button" class="ghost-btn" id="sbeRelinkBtn"+ onclick="sbeRelink()">Use the finished versions</button>+ </div>+++ <!-- ============== THE TWO MONITORS =========================+ Source on the left, program on the right, which is the layout+ every NLE has had since tape: one screen for the thing you are+ considering, one for the thing you have built. Asked for in+ those words — "a split screen with the left screen showing you+ when you click on the clips … you can watch the clips before you+ add them".++ The source is a PLAYER, not a second editor. It has no timeline,+ no trim, no scrub: clicking a pool row loads the clip and plays+ it, and the only verb under it is the one that puts it on the+ track. The + on the pool row still adds without previewing, so+ nobody who already knows what a clip is has to watch it first.++ Sound is the program's switch, for both: sbeSetMute owns the+ mute state of every element on this row, and only one of the two+ ever plays. -->+ <div class="sbe-monitors" id="sbeMonitors">+ <div class="sbe-mon sbe-mon-src">+ <div class="sbe-stage" id="sbeSrcStage">+ <!-- Same opacity rule as the program monitor, for the same+ WebKit reason: a display:none <video> is never loaded. -->+ <video id="sbeSrcVideo" playsinline preload="auto"></video>+ <img id="sbeSrcStill" class="sbe-still" alt="">+ <div class="sbe-stage-badge" id="sbeSrcBadge" hidden></div>+ <div class="sbe-stage-empty" id="sbeSrcEmpty">Click a clip to preview it.</div>+ </div>+ <!-- ONE bar per monitor, and both the same height, because the row+ is as tall as the taller column and the budget maths in+ sbeFitMonitors reads its overhead off the program side. The+ label lives IN the bar rather than above the picture: two+ captions per column is 38px of a budget that is already the+ tightest thing on this screen. -->+ <div class="sbe-mon-bar">+ <span class="sbe-mon-label">Source</span>+ <button type="button" class="ghost-btn" id="sbeSrcPlayBtn"+ onclick="sbeSrcToggle()" disabled>Play</button>+ <span class="sbe-mon-name" id="sbeSrcName">Nothing loaded</span>+ <button type="button" class="ghost-btn" id="sbeSrcAddBtn"+ onclick="sbeSrcAdd()" disabled+ title="Puts this clip at the end of the __SEQ__ — exactly what the + on its row does.">Add to timeline</button>+ </div>+ </div>+ <div class="sbe-mon sbe-mon-prog">+ <div class="sbe-stage" id="sbeStage">+ <!-- ONE video. Double-buffering measured no benefit against+ all-intra proxies, and hiding it with display:none would stop+ WebKit loading it at all — hence opacity. -->+ <!-- No `muted` attribute. It was here as "belt and braces" for a+ loader that hard-muted anyway, and it now contradicts the only+ thing that owns this state: sbeSetMute. There is no `autoplay`+ here, so nothing plays without sbePlay, and sbePlay sets muted+ explicitly and falls back if the browser refuses. -->+ <video id="sbeVideo" playsinline preload="auto"></video>+ <!-- The still layer. A slug needs no element at all: hiding both of+ these leaves the stage's own #000 background, which is exactly+ what a slug renders. -->+ <img id="sbeStill" class="sbe-still" alt="">+ <!-- THE OVERLAY LANE ON THE STAGE. Over the picture and the still+ both, carrying its own opacity so a card's fade is independent of+ whatever is beneath it — which is what a second track means. -->+ <img id="sbeOvLayer" class="sbe-ov-layer" alt="">+ <div class="sbe-stage-badge" id="sbeBadge">idle</div>+ <div class="sbe-stage-empty" id="sbeStageEmpty" hidden></div>+ </div>+ <div class="sbe-mon-bar">+ <span class="sbe-mon-label">Program</span>+ <span class="sbe-mon-name" id="sbeProgName"></span>+ </div>+ </div>++ <!-- THE RAIL, and why it exists. Two 16:9 monitors need 2.96px of+ width for every px of height. Measured in this column, at+ 1440x900, there are 307px of height to spare and 1110px of width+ — the pair can span 886 of them. Something has to hold the other+ 224, and the choice is between black page background (the exact+ thing the owner circled) and the two panels that were sitting+ under the timeline eating 46px of the height that made the+ picture small in the first place. Resolve and Premiere both put+ the inspector beside the monitors; so does this. Its width is+ whatever the pair leaves — see sbeFitMonitors — clamped so it can+ be neither a slot nor a second sidebar. Below the stacking+ breakpoint it goes back to being a row. -->+ <div class="sbe-rail" id="sbeRail">+ <div class="sbe-inspect" id="sbeInspect"></div>+ <div class="sbe-unplaced" id="sbeUnplacedWrap" hidden>+ <div class="sbe-unplaced-head">Rendered but not on the timeline</div>+ <div class="sbe-chiprow" id="sbeUnplaced"></div>+ </div>+ </div>+ </div>++ <div class="sbe-transport">+ <button type="button" class="ghost-btn" id="sbePlayBtn" onclick="sbeTogglePlay()">Play</button>+ <button type="button" class="ghost-btn sbe-mute" id="sbeMuteBtn"+ onclick="SBE.muted ? sbeUnmuteFromRefusal() : sbeSetMute(true)" title="Mute / unmute (M)">🔊</button>+ <span class="sbe-time" id="sbeTime">0:00.00 <span>/ 0:00.00</span></span>+ <label class="check" style="margin:0;font-size:11px">+ <input type="checkbox" id="sbeSnapOn" checked onchange="sbePaint()"> Snap to beat+ </label>+ <!-- The two sliders an editor expects: the scrollbar on the track+ below moves the view, this one changes the scale. All the way+ left is the whole film in the window, whatever the window is. -->+ <span class="sbe-zoom">+ <button type="button" class="ghost-btn" onclick="sbeZoom(-1)"+ title="Zoom out (alt + wheel over the track does the same, around the pointer)">−</button>+ <input type="range" id="sbeZoomRange" min="0" max="1000" step="1" value="500"+ aria-label="Timeline zoom"+ title="Zoom. Fully left fits the whole __SEQ__ in the window. Over the track: shift + wheel pans, alt + wheel zooms."+ oninput="sbeZoomSlide(this.value)">+ <button type="button" class="ghost-btn" onclick="sbeZoom(1)" title="Zoom in">+</button>+ </span>+ <!-- PROSE DEMOTED TO AN AFFORDANCE. Two lines of explanation sat+ across the middle of the transport for the life of the feature;+ it is true, it is worth saying once, and it is not worth 220px of+ the row every time. -->+ <span class="sbe-info" id="sbeApprox" tabindex="0"+ title="The preview is approximate: the browser lands within a few frames of each cut and freezes for about one there. The render is exact.">i</span>+ <span style="flex:1 1 auto"></span>+ <button type="button" class="ghost-btn" id="sbeKeysBtn"+ onclick="sbePopToggle('sbeKeysPop', 'sbeKeysBtn')"+ aria-haspopup="menu" title="Every gesture this timeline answers to">Keys</button>+ <!-- THE TIMELINE'S TOP EDGE. It lives in the transport because the+ transport is the element directly above the seam and an absolute+ child costs the column nothing; what it drags is one number+ (SBE.tlH), and the monitors are sized off whatever is left. Up is+ more track, down is more picture, and neither element is resized+ directly — see sbeFitMonitors. -->+ <div class="sbe-tl-grab" id="sbeTlGrab" role="separator"+ aria-orientation="horizontal"+ aria-label="Resize the timeline — drag up for taller lanes"+ tabindex="0"+ title="Drag up to make the timeline taller — the sound strips take the biggest share. Double-click to reset. ↑ / ↓ when focused."+ onpointerdown="sbeTlGrabDown(event)"+ onpointermove="sbeTlGrabMove(event)"+ onpointerup="sbeTlGrabUp(event)"+ onpointercancel="sbeTlGrabUp(event)"+ ondblclick="sbeTlReset()"+ onkeydown="sbeTlGrabKey(event)"></div>+ </div>++ <!-- NAMED TRACKS. A timeline whose lanes are unlabelled asks you to+ infer which one is which from what happens to be on it, and the+ soundtrack's whole control row was a full-width strip at the top of+ the column, four inches from the lane it acts on. The gutter is+ 124px that says V2 / V1 / A1 / A2 and gives A2 the file it is+ playing, the way it sits under the clips, and a ▾ for the rest.+ Every head's height is the SAME variable its lane reads, so the two+ columns cannot drift apart. -->+ <div class="sbe-tlwrap" id="sbeTlWrap">+ <div class="sbe-gutter" id="sbeGutter">+ <div class="sbe-gh sbe-gh-top"></div>+ <div class="sbe-gh sbe-gh-ov">+ <span class="sbe-gh-tag"><i>V2</i><b>Overlay</b></span>+ </div>+ <div class="sbe-gh sbe-gh-pic">+ <span class="sbe-gh-tag"><i>V1</i><b>Picture</b></span>+ <span class="sbe-gh-sub" id="sbeHeadPic"></span>+ </div>+ <div class="sbe-gh sbe-gh-aud">+ <span class="sbe-gh-tag"><i>A1</i><b>Clip sound</b></span>+ <span class="sbe-gh-sub" id="sbeHeadAud"></span>+ </div>+ <div class="sbe-gh sbe-gh-mus">+ <span class="sbe-gh-tag"><i>A2</i><b>Music</b>+ <button type="button" class="sbe-gh-more" id="sbeMusicMore"+ onclick="sbePopToggle('sbeMusicMenu', 'sbeMusicMore')"+ aria-haspopup="menu"+ title="The file, Change…, Prepare — the soundtrack's own controls">▾</button>+ </span>+ <span class="sbe-music-name" id="sbeMusicPath" title="">no soundtrack</span>+ <select class="sb-input sbe-gh-mode" id="sbeMusicMode"+ onchange="sbeSetMusicMode(this.value)"+ title="Under: the clips keep their sound and the track plays beneath it. Replace: the track is the only sound.">+ <option value="under">under the clips</option>+ <option value="replace">replaces clip sound</option>+ </select>+ <!-- THE TWO NUMBERS THE RENDERER USED TO KEEP TO ITSELF. Until+ today the ffmpeg graph held every `under` bed at 0.20 and+ ducked it against the dialogue; neither decision was in any+ document, on any screen, or in the preview. They are controls+ now, and they live HERE because this head is already where the+ soundtrack's other controls are — the file, Change…, Prepare+ and the mode. -->+ <div class="sbe-mix-row">+ <label class="sbe-mix-lvl"+ title="How loud the soundtrack plays. 100% is the file's own level; the render applies exactly this and so does the preview.">+ <span>Level</span>+ <input type="range" id="sbeBedGain" min="0" max="100" step="1"+ value="100" aria-label="Music bed level"+ oninput="sbeBedGainSlide(this.value)"+ onchange="sbeBedGainCommit(this.value)">+ <b id="sbeBedGainNum">100%</b>+ </label>+ <label class="check sbe-mix-duck"+ title="Steps the music back wherever a clip's own sound is playing, and lets it up again after. Off by default — an authored fade or level line on the bed switches it off, because two curves moving one level is nobody's mix.">+ <input type="checkbox" id="sbeBedDuck"+ onchange="sbeSetBedDuck(this.checked)">+ <span>Duck under dialogue</span>+ </label>+ <span class="sbe-mix-note" id="sbeBedDuckNote" hidden></span>+ </div>+ </div>+ <div class="sbe-gh sbe-gh-foot"></div></div>+ <div class="sbe-tl" id="sbeScroll">+ <!-- TOP TO BOTTOM: ruler, picture, sound. Every NLE ever made stacks+ it that way and the owner read the old order — music ABOVE the+ clips — as the app not knowing the convention: "it is unusual+ that the music is above the clips; it's not normal." The order+ here IS the order on screen (the inner is a flex column), so the+ fix is the markup, not a transform. -->+ <div class="sbe-tl-inner" id="sbeInner">+ <div class="sbe-ruler" id="sbeRuler"></div>+ <!-- THE OVERLAY LANE, ABOVE THE PICTURE, because that is where it+ is in the film: a second video track whose items composite over+ the track below. -->+ <div class="sbe-ovlane" id="sbeOverlayLane"+ onpointerdown="sbeOnOvDown(event)"+ onpointermove="sbeOnOvMove(event)"+ onpointerup="sbeOnOvUp(event)"+ onpointercancel="sbeOnOvUp(event)"></div>+ <div class="sbe-track" id="sbeTrack"></div>+ <!-- THREE LAYERS, TOP TO BOTTOM: video blocks, each clip's own+ sound, the music. The owner's list exactly. A clip's strip sits+ directly under its block and moves with it — until it is+ unlinked, which is the whole of the J-cut and the L-cut. -->+ <div class="sbe-alane" id="sbeAudioLane"></div>+ <!-- The soundtrack lane. The canvas is the picture of the track and+ the block over it is the OBJECT: drag it to place the music,+ pull either end to trim it. Two elements rather than one canvas+ because a grip has to be hit-tested, and hit-testing a painted+ rectangle is a job the DOM already does. -->+ <div class="sbe-lane" id="sbeMusicLane">+ <canvas class="sbe-wave" id="sbeWave" height="72"></canvas>+ <div class="sbe-wave-none" id="sbeWaveNone" hidden></div>+ <!-- THE BED IS A STRIP NOW, not a rectangle you can only slide.+ "Fade the music out under the last shot" is the most ordinary+ request in editing and was, until this, impossible: the model+ read `audio.afx`, normalised it and could render it, and there+ was no markup anywhere that could produce one. Same three+ affordances the clip strips grew — two corner fade handles in+ the band, a level line you can hit, and points on it — built+ out of the SAME geometry (`.sbe-fade-band`, the grip skirt+ derivation, the 22px square, SBE_LVL_PAD) rather than a fourth+ set of numbers that could drift on its own. -->+ <div class="sbe-music-clip" id="sbeMusicClip" hidden>+ <div class="sbe-mc-name" id="sbeMusicName"></div>+ <div class="sbe-mc-lvl" id="sbeMusicLevel"></div>+ <div class="sbe-grip l"></div><div class="sbe-grip r"></div>+ <div class="sbe-fade-band" id="sbeMusicFades">+ <div class="sbe-fade-h in" data-bfade="in"></div>+ <div class="sbe-fade-h out" data-bfade="out"></div>+ </div>+ </div>+ </div>+ <div class="sbe-head-line" id="sbeHead" style="left:0"></div>+ </div>+ </div>+ </div>++ </div></div><!-- Combined filter + title row. One row, three regions: title +@@ -37040,6 +43681,41 @@ Third prompt."></textarea></div></div>+<!-- Generate a shot INTO a hole in the timeline. Same reason the re-plan modal+ exists — it needs a text field — and written here at column 0 so the+ global _phosModalScaffold IIFE picks it up at boot (Esc, focus trap,+ scroll lock). The shot lands on the BOARD, because a shot to be rendered+ is intent; the timeline only learns about it when the clip exists. -->+<div class="modal-bg" id="sbeGenModal" onclick="if(event.target===this)sbeGenClose()">+ <div class="modal">+ <h3>Fill this hole</h3>+ <div class="hint" id="sbeGenWhere"></div>+ <textarea class="batch" id="sbeGenPrompt" rows="4"+ placeholder="A slow push in on the empty gym, dust in the light."></textarea>+ <div class="cz-control" style="margin-top:12px">+ <div class="cz-label">Length <span class="cz-label-hint">seconds of film</span></div>+ <input type="number" class="sb-input" id="sbeGenDuration" min="0.5" max="60" step="0.5" value="5">+ </div>+ <div class="cz-control" style="margin-top:10px">+ <div class="cz-label">Pass <span class="cz-label-hint">draft is cheap, delivery is what you keep</span></div>+ <div class="pill-group cols-2" id="sbeGenPass">+ <button type="button" class="pill-btn active" data-pass="draft">Draft</button>+ <button type="button" class="pill-btn" data-pass="final">Delivery</button>+ </div>+ </div>+ <!-- make_job SILENTLY DROPS any form field it does not name, so a control+ can look perfectly wired and do nothing. The server reads the params+ back off the queued job and hands them here: this is what will+ actually render, not what we asked for. -->+ <div class="sbe-params" id="sbeGenParams" hidden></div>+ <div class="hint" style="margin-top:6px">The clip renders into the queue like any other shot. When it lands it appears under the timeline, and you place it — nothing moves your cuts on its own.</div>+ <div class="modal-actions">+ <button class="small" onclick="sbeGenClose()">Cancel</button>+ <button class="small primary" style="padding:6px 14px" id="sbeGenGo" onclick="sbeGenSubmit()">Queue the shot</button>+ </div>+ </div>+</div>+<!-- The raw planner reply, for a bug report. Never shown by default. --><div class="modal-bg" id="sbRawModal" onclick="if(event.target===this)document.getElementById('sbRawModal').classList.remove('show')"><div class="modal">@@ -39789,12 +46465,25 @@ function audioStudioRenderSlots() {// So the budget is frames x AREA, and the old warning was simply wrong in the// case that matters most: it shouted at a 640x480 20 s render that works.//-// A2V_PIXEL_BUDGET is the largest configuration anyone has reported working —-// 640x480 x 481 = 147.7 Mpx — rounded to 150. It is a field observation from-// one machine, not a measurement made here, and the copy says so. Anything-// derived from it (the max frames for the chosen canvas) is presented as-// guidance, never as a cap: the slider keeps its full range.-const A2V_PIXEL_BUDGET = 150e6;+// AND THEN THE REPORTER'S OWN FOUR DATAPOINTS REFUTED THAT. No frames x area+// constant can separate them: 832x480 x 721 = 287.9 Mpx holds together, while+// 1024x576 x 481 = 283.7 Mpx falls apart — a SMALLER product failing. A budget+// that calls the working one worse than the failing one is not a budget, it is+// a coin toss with a number on it.+//+// They separate cleanly on PER-FRAME AREA. Clean: 0.307 and 0.399 Mpx/frame,+// at 721 and 481 frames. Failing: 0.590 and 0.922 Mpx/frame, both giving out+// around frame 450. So the lever is the CANVAS, and length is nearly free+// below the knee — which is the opposite of what the old warning told people,+// and it told them so at exactly the 640x480 20 s render that works.+//+// The knee sits at ~0.45 Mpx a frame, between the highest clean reading and+// the lowest failing one. Below it, nothing is warned about within the+// slider's range; above it, the warning names the canvas as the lever and+// ~450 frames as where the picture gives out. Still field reports from other+// people's machines, not a limit measured here, and the copy still says so.+const A2V_AREA_KNEE = 0.45e6; // pixels per frame+const A2V_KNEE_FRAMES = 450; // where the reports say the picture goesfunction _a2vFramesForSeconds(sec) {const target = Math.max(1, Math.round(sec * 24));return ((target - 1 + 7) >> 3 << 3) + 1; // round up to 8k+1@@ -39813,20 +46502,23 @@ function audioStudioDurationChanged(val) {const w = parseInt((document.getElementById('audioStudioWidth') || {}).value || '1024', 10);const h = parseInt((document.getElementById('audioStudioHeight') || {}).value || '576', 10);const area = (w > 0 && h > 0) ? w * h : 1024 * 576;- if (frames * area > A2V_PIXEL_BUDGET) {- // The longest length that fits this canvas, on the 8k+1 grid, in seconds.- const maxFrames = Math.max(9, ((Math.floor(A2V_PIXEL_BUDGET / area) - 1) >> 3) * 8 + 1);- const maxSec = Math.max(1, Math.floor((maxFrames - 1) / 24));+ // THE CANVAS IS THE LEVER, NOT THE LENGTH. Below the knee the reports run+ // clean to 721 frames, so there is nothing to say; above it they give out+ // around frame 450 whatever the length asked for.+ if (area > A2V_AREA_KNEE && frames > A2V_KNEE_FRAMES) {+ const kneeSec = Math.max(1, Math.floor((A2V_KNEE_FRAMES - 1) / 24));warn.style.display = '';- warn.innerHTML = '<b>' + frames + ' frames at ' + w + '\u00d7' + h + '</b> — bigger than any '- + 'Audio \u2192 Video render that has been reported holding together. What gives out is the '- + 'picture, not the sound: the audio plays to the end while anatomy drifts and the frame '- + 'washes out. It is <b>frames \u00d7 canvas</b>, not length alone \u2014 640\u00d7480 has been '- + 'reported fine at the full 20 s, while 1024\u00d7576 died around frame 454 on the same machine '+ warn.innerHTML = '<b>' + w + '\u00d7' + h + '</b> is past the canvas where '+ + 'long Audio \u2192 Video renders have been reported holding together. '+ + 'What gives out is the picture, not the sound: the audio plays to the '+ + 'end while anatomy drifts and the frame washes out, and the reports put '+ + 'that around <b>frame ' + A2V_KNEE_FRAMES + '</b> (~' + kneeSec + ' s) '+ + 'whatever length was asked for. It is the <b>canvas</b>, not the length: '+ + '832\u00d7480 has been reported clean at 721 frames, while 1024\u00d7576 '+ + 'died around frame 454 on the same machine '+ '(<a href="https://github.com/mrbizarro/Phosphene/issues/46" target="_blank" rel="noopener">#46</a> '+ '\u2014 field reports, not a limit measured here). '- + 'At this canvas, about <b>' + maxSec + ' s</b> (' + maxFrames + ' frames) is the last stop under it; '- + 'a smaller canvas buys length. Longer still renders.';+ + 'Drop to about 832\u00d7480 or smaller and the length comes back. Longer still renders.';} else {warn.style.display = 'none';warn.textContent = '';@@ -45632,10 +52324,19 @@ async function poll() {nowCard.querySelector('.ttl').textContent = snippet(s.current.params.label || s.current.params.prompt, 80);// Image jobs don't have width/height/frames; show n × aspect instead.// Falls through to the video shape when those fields ARE present.+ //+ // TRAINING has no frames either, and printed the literal string+ // "undefinedf" for the whole run — reported in #61 as+ // `train · 512×512 · undefinedf · 5m 39s`. A training job's shape is its+ // canvas; the step count is already carried by phaseLabel underneath.+ // Anything else missing frames drops the token rather than inventing one.const cur = s.current.params;+ const shape = [cur.width && cur.height ? `${cur.width}×${cur.height}` : null,+ (cur.frames != null && cur.frames !== '') ? `${cur.frames}f` : null]+ .filter(Boolean).join(' · ');const baseMeta = (cur.mode === 'image')? `image · ${cur.aspect || '?'} · n=${cur.n || '?'} · ${cur.engine_override || 'auto'} · ${timing}`- : `${cur.mode} · ${cur.width}×${cur.height} · ${cur.frames}f · ${timing}`;+ : [cur.mode, shape, timing].filter(Boolean).join(' · ');nowCard.querySelector('.meta').innerHTML = phaseLabel? `${baseMeta}<br><span style="color:var(--muted)">${escapeHtml(phaseLabel)}</span>`: baseMeta;@@ -52173,6 +58874,14 @@ function _versionRemoteLabel(s) {return s.remote_version || s.remote_short || 'latest';}+function _versionBuildLabel(version, short) {+ // A build is named unambiguously only by BOTH halves: the VERSION label is+ // what a user recognises, the SHA is what actually separates two builds+ // carrying the same label.+ if (version && short) return `${version} (${short})`;+ return version || short || 'an unknown build';+}+function renderVersionPill() {const pill = document.getElementById('versionPill');if (!pill) return;@@ -52208,10 +58917,13 @@ function renderVersionPill() {if (s.stale_process) {pill.classList.add('pill-restart');pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-arrow-clockwise-bold"/></svg>Restart to finish update';- const v = s.disk_version || s.disk_short || 'newer code';- pill.title = `Phosphene ${v} is on disk, but this panel process loaded `- + `${local} before the update landed. Click Stop → Start in Pinokio `- + `(or restart the panel) to load it.`;+ // Name BOTH builds, each with its SHA. Most fixes land without a VERSION+ // bump, so on dev the two labels read the same number and a tooltip built+ // from labels alone said "Phosphene 4.6.0 is on disk, but this panel+ // process loaded 4.6.0" — an alarm that names nothing.+ pill.title = `Running ${_versionBuildLabel(s.local_version, s.local_short)}`+ + ` — but ${_versionBuildLabel(s.disk_version, s.disk_short)} is on disk.`+ + ` Click Stop → Start in Pinokio (or restart the panel) to load it.`;return;}// Suppressed (dev branch / dirty tree / no git).@@ -52219,8 +58931,15 @@ function renderVersionPill() {// because the pill showed an old VERSION string (e.g. "2.0.5") while// they had pulled fresh code. Now we append the short SHA + commit// date so every dev build is uniquely identifiable. Lets us tell a- // user "you're on 3.0.0 · dev · c5dc04c (2026-05-21) — please pull- // again, latest is 1ea5f1d (2026-05-21)" instead of just shrugging.+ // user "you're on 3.0.0 · dev · <your-sha> (2026-05-21) — please+ // pull again, latest is <newer-sha>" instead of just shrugging.+ //+ // The placeholders are deliberate. This comment used to carry two REAL+ // SHAs, formatted exactly like the stamp it describes, and it ships inside+ // the served page — so grepping the page for the running build answered+ // with a 2026-05-21 commit, in the stamp's own format, with total+ // confidence. build_stamp_text() puts the true answer in the page now, as+ // <meta name="phosphene-build">.if (s.suppress_reason) {pill.classList.add('pill-dev');const sha = s.local_short || '';@@ -52585,6 +59304,35 @@ document.addEventListener('keydown', (ev) => {window.addEventListener('resize', closeHealthPop);// One click — does the right thing for the current state. Magic button.+async function panelRestart() {+ const pill = document.getElementById('versionPill');+ const say = (t) => { if (pill) pill.textContent = t; };+ try {+ const r = await fetch('/restart', {method: 'POST'});+ const d = await r.json().catch(() => ({}));+ if (r.status === 409) {+ phosToast(d.error || 'A render is running — stop it first.', 'warn');+ return;+ }+ if (!d.ok) { phosToast(d.error || 'Restart failed.', 'error'); return; }+ } catch (e) {+ // The process may have exec'd before the response reached us. That is a+ // SUCCESSFUL restart, not a failure — fall through to polling.+ }+ say('restarting…');+ // Poll until the new image answers, then reload so the browser gets the+ // new HTML too (the whole point: the old page is the stale code).+ const deadline = Date.now() + 60000;+ while (Date.now() < deadline) {+ await new Promise(r => setTimeout(r, 700));+ try {+ const r = await fetch('/version', {cache: 'no-store'});+ if (r.ok) { location.reload(); return; }+ } catch (e) { /* still down */ }+ }+ phosToast('Panel did not come back within 60s — start it from Pinokio.', 'error');+}+async function versionPillClick() {if (_versionRestartPending) {// Educational click: tell the user what's needed.@@ -52596,6 +59344,14 @@ async function versionPillClick() {return;}if ((_versionState || {}).stale_process) {+ // Actually restart, rather than telling the user to go and do it. The+ // panel re-execs itself: same pid, same port, code from disk. We poll+ // until it answers again and then reload, so the click finishes the job+ // the button's own label promised.+ await panelRestart();+ return;+ }+ if (false) {const s = _versionState || {};alert(`Phosphene ${s.disk_version || s.disk_short || '(newer)'} is on `+ `disk, but this running panel loaded `@@ -52616,7 +59372,11 @@ async function versionPillClick() {+ `· ${s.local_branch || 'branch?'} `+ `· ${s.local_short || 'sha?'}`+ (s.local_commit_date ? ` (${s.local_commit_date})` : '')- + (s.local_dirty ? ' · dirty tree' : '');+ + (s.local_dirty ? ' · dirty tree' : '')+ // The whole point of this string is "which build produced the bug".+ // If the tree has moved on, the panel is running neither what the+ // header first suggested nor what a maintainer would check out.+ + (s.stale_process ? ` · NOT RESTARTED, disk is at ${s.disk_short || '?'}` : '');try {await navigator.clipboard.writeText(debug);alert(`Update check is paused: ${s.suppress_reason}.\n\n`@@ -52922,6 +59682,16 @@ let SB = {primed: false, // brief defaults are read from BOOT once, not per entryboards: [], // /status.storyboards, refreshed by poll()lastUndo: null,+ // Which of the seven stage states is on screen. sbShow() is the only writer.+ // The rail reads it to say where you are, and sbLoad() reads it so a 2 s poll+ // cannot yank someone off the film screen back onto the shot list.+ stage: '',+ films: [], // /storyboard/films for the open board, newest first+ filmsFor: '', // which board `films` belongs to — never another one+ filmDir: '',+ filmShort: '',+ filmOpen: '', // the film being played, by name+ boardsSig: '', // last painted board-row signature (see sbPollHook)};const SB_BOOT = (typeof BOOT !== 'undefined' && BOOT.storyboard) ? BOOT.storyboard : {};@@ -52969,6 +59739,54 @@ function sbShotEst(secs) {if (!secs) return '';return secs < 90 ? `~${Math.round(secs)} s` : `~${Math.round(secs / 60)} m`;}+// A film's length is read off a player, so it is written the way a player+// writes it — 0:31, 2:04 — not "31 s of film".+function sbFmtClock(secs) {+ const t = Math.max(0, Math.round(Number(secs) || 0));+ const m = Math.floor(t / 60), s = t % 60;+ return m + ':' + (s < 10 ? '0' : '') + s;+}+function sbFmtBytes(n) {+ const b = Number(n) || 0;+ if (b >= 1073741824) return (b / 1073741824).toFixed(1) + ' GB';+ if (b >= 1048576) return Math.round(b / 1048576) + ' MB';+ if (b >= 1024) return Math.round(b / 1024) + ' KB';+ return b + ' B';+}+// "when was this made" in the only units that answer it without arithmetic.+// `now` is a parameter so the gate can pin it.+function sbFmtAgo(ts, now) {+ const t = Number(ts) || 0;+ if (!t) return '';+ const secs = Math.max(0, ((now || Date.now()) / 1000) - t);+ if (secs < 90) return 'just now';+ const m = Math.round(secs / 60);+ if (m < 60) return m + (m === 1 ? ' minute ago' : ' minutes ago');+ const h = Math.round(m / 60);+ if (h < 24) return h + (h === 1 ? ' hour ago' : ' hours ago');+ const d = Math.round(h / 24);+ if (d < 30) return d + (d === 1 ? ' day ago' : ' days ago');+ try { return new Date(t * 1000).toLocaleDateString(); } catch (e) { return ''; }+}+// Which button made this file. Two mp4s in one folder otherwise look identical.+function sbFilmKind(f) {+ const k = (f || {}).kind;+ if (k === 'timeline') return 'Timeline render';+ if (k === 'export') return 'Export';+ return 'Film';+}+// The film on screen: the one the caller asked for by name, else the newest.+// Pure, because "which film am I looking at" is exactly the kind of thing that+// silently picks the wrong one.+function sbFilmPick(films, want) {+ const list = films || [];+ if (!list.length) return null;+ if (want) {+ const hit = list.filter(f => f.name === want || f.path === want)[0];+ if (hit) return hit;+ }+ return list[0];+}// ---- tab lifecycle ---------------------------------------------------------// The delivery-pass chips, from the registry. Three static buttons carried@@ -53037,6 +59855,9 @@ function sbInit() {}function sbTeardown() {+ // The board poller, and nothing else. It used to tear the EDITOR down too,+ // back when the timeline was a state of this tab — so leaving the storyboard+ // closed a document that had nothing to do with it.if (SB.timer) { clearInterval(SB.timer); SB.timer = null; }}@@ -53084,6 +59905,10 @@ async function sbTick() {if (document.body.dataset.workflow !== 'storyboard') return;// The global poll skips hidden tabs; this one should too.if (document.hidden) return;+ // The timeline has its own clock and its own document. Repainting the shot+ // list under it would be work nobody can see, and sbLoad() reaches into the+ // player — which the timeline is currently using.+ if (typeof SBE !== 'undefined' && SBE.open) return;if (sbHoldingShots()) {// Don't fetch over someone's typing. The run bar is the one thing that// moves on its own, and it lives outside #sbShots, so keep it live.@@ -53119,6 +59944,42 @@ function sbMustInput() {meta.textContent = n === 0 ? 'none' : (n === 1 ? '1 shot' : `${n} shots`);}+// LOCATIONS. Free text, one per line, `name: description`. A list of objects+// behind a form builder would be more correct and nobody would fill it in;+// this is the shape people already type into the Look field.+function sbParseLocations(text) {+ const out = [];+ const seen = {};+ ((text || '').split('\n')).forEach(line => {+ const raw = line.trim();+ if (!raw) return;+ const at = raw.indexOf(':');+ // No colon = the whole line is the description and the name is derived.+ // Refusing the line instead would lose what somebody just typed.+ const name = (at > 0 ? raw.slice(0, at) : raw.split(/[,.]/)[0]).trim().slice(0, 60);+ const desc = (at > 0 ? raw.slice(at + 1) : raw).trim();+ if (!name || !desc) return;+ let id = name.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 40);+ if (!id) id = 'loc' + (out.length + 1);+ if (!/^[a-z0-9]/.test(id)) id = 'l' + id;+ while (seen[id]) id = id.replace(/\d*$/, m => String((parseInt(m || '1', 10) || 1) + 1));+ seen[id] = 1;+ out.push({ id: id, name: name, description: desc });+ });+ return out;+}++function sbLocInput() {+ const meta = sbEl('sbLocMeta');+ if (!meta) return;+ const locs = sbParseLocations((sbEl('sbLocations') || {}).value);+ meta.textContent = locs.length === 0+ ? 'no locations — every shot invents its own'+ : locs.map(l => l.name).join(' · ') ++ (locs.length === 1 ? ' — 1 place, pinned on every shot that uses it'+ : ` — ${locs.length} places, pinned on every shot that uses them`);+}+let _sbShots = 12;function sbSetShots(n, persist) {_sbShots = Number(n) || 12;@@ -53334,6 +60195,8 @@ async function sbPlan() {fd.set('shots', String(sbShotsValue()));fd.set('style', (sbEl('sbStyle') || {}).value || '');fd.set('must', (sbEl('sbMust') || {}).value || '');+ fd.set('locations', (sbEl('sbLocations') || {}).value || '');+ fd.set('wardrobe', (sbEl('sbWardrobe') || {}).value || '');fd.set('engine', _sbEngineMode);if (_sbCastId) fd.set('character_id', _sbCastId);let r;@@ -53451,18 +60314,129 @@ function sbShowRaw() {}// ---- board open / load -----------------------------------------------------+// RETURNS THE LOAD. It used to swallow it, and `await sbOpen(id)` therefore+// awaited `undefined` — so the row's "Edit" button opened the timeline and then+// the load that was still in flight called sbShow('plan') and tore it straight+// back down. Clicking Edit landed on the shot list. Handing the promise back is+// the whole fix, and sbOpenAt() is the caller that needed it.function sbOpen(id) {+ // Another board's films are not this board's. Without this the rail carried+ // the last film you looked at onto the next storyboard's step 4.+ if (id !== SB.id) { SB.films = []; SB.filmsFor = ''; SB.filmOpen = ''; }SB.id = id;try { localStorage.setItem('phos_sb_open', id); } catch (e) {}- sbLoad(id);+ return sbLoad(id);+}+// Open a board AND land on a named step. The board list's rows use it, so a+// film with a finished cut is one click from the cut, not four.+async function sbOpenAt(id, step) {+ await sbOpen(id);+ if (step) sbGo(step);}function sbBackToList() {SB.id = '';SB.payload = null;+ SB.films = [];+ SB.filmsFor = '';+ SB.filmOpen = '';try { localStorage.removeItem('phos_sb_open'); } catch (e) {}sbRefreshBoards().then(() => sbShow(SB.boards.length ? 'list' : 'empty'));}+// ---- the rail: plan → shots → arrange → film -------------------------------+// One model function, pure, so the thing that decides what is reachable is+// testable without a browser. `snap` is {clips, film, stage, shots, done}.+function sbRailModel(snap) {+ const s = snap || {};+ const clips = Number(s.clips || 0);+ const stage = s.stage || '';+ const film = s.film || null;+ // A step is 'now' when you are standing in it, 'locked' when it cannot do+ // anything yet (and says what would unlock it), 'done' when it has produced+ // what it produces, 'ready' otherwise. Locked is never hidden: a path you+ // cannot see the end of is not a path.+ const shotsSub = !s.shots ? ''+ : (clips ? clips + ' of ' + s.shots + ' rendered' : s.shots + ' planned');+ const arrangeLocked = !clips;+ return [+ { key: 'plan', label: 'Plan', n: 1, state: 'done', sub: '',+ hint: 'The brief this film was planned from — open it to re-plan.' },+ { key: 'shots', label: 'Shots', n: 2,+ state: stage === 'plan' ? 'now' : (clips ? 'done' : 'ready'),+ sub: shotsSub,+ hint: 'Read the shot list, fix a prompt, render, grade what came back.' },+ // Step 3 is a DOOR now, not a room: it switches to the Editor tab+ // carrying this film. The word is Editor everywhere — tab, header, this+ // step, and the board row's button.+ { key: 'edit', label: 'Edit', n: 3,+ state: stage === 'editor' ? 'now'+ : arrangeLocked ? 'locked' : (film ? 'done' : 'ready'),+ sub: '',+ hint: arrangeLocked+ ? 'Render a shot first — there is nothing to edit yet.'+ : 'Open this film in the Editor: trim, reorder, cut to the beat, then render the film.' },+ { key: 'film', label: 'Film', n: 4,+ state: stage === 'film' ? 'now'+ : arrangeLocked ? 'locked' : (film ? 'done' : 'ready'),+ sub: film && film.duration ? sbFmtClock(film.duration) : '',+ hint: arrangeLocked ? 'Render a shot first.'+ : film ? 'Watch the finished film.'+ : 'Nothing rendered yet — arrange the shots and render the timeline.' },+ ];+}+function sbRailPaint() {+ const rail = sbEl('sbRail');+ if (!rail) return;+ const open = !!SB.id && ['plan', 'film'].indexOf(SB.stage) !== -1;+ rail.hidden = !open;+ if (!open) return;+ const b = ((SB.payload || {}).board) || {};+ const row = SB.boards.filter(x => x.id === SB.id)[0] || {};+ const shots = (b.shots || []).length;+ const clips = (b.shots || []).filter(s => s.draft_output || s.final_output).length;+ // The open board's own film list wins over the poll's summary — after a+ // render the screen must not still be saying "no film".+ const mine = SB.filmsFor === SB.id ? (SB.films || []) : [];+ const film = mine[0] || row.film || null;+ // "You are here" survives the tab move: while the Editor holds THIS film,+ // step 3 is the step you are standing in, wherever the body happens to be.+ const inEditor = typeof SBE !== 'undefined' && SBE.open && SBE.id === SB.id;+ const model = sbRailModel({ clips: clips, shots: shots, film: film,+ stage: inEditor ? 'editor' : SB.stage });+ model.forEach(step => {+ const el = rail.querySelector('.sb-rail-step[data-step="' + step.key + '"]');+ if (!el) return;+ el.classList.toggle('is-now', step.state === 'now');+ el.classList.toggle('is-done', step.state === 'done');+ el.classList.toggle('is-locked', step.state === 'locked');+ el.disabled = step.state === 'locked';+ el.title = step.hint;+ const sub = el.querySelector('.sb-rail-sub');+ if (sub) sub.textContent = step.sub ? '· ' + step.sub : '';+ });+}+// Every door in one function, so "go to the editor" means the same thing+// wherever it is asked from.+function sbGo(step) {+ if (!SB.id) return;+ if (step === 'plan') {+ sbOpenReplan();+ return;+ }+ if (step === 'shots') {+ sbShow('plan');+ if (SB.payload) sbRenderPlan(SB.payload);+ return;+ }+ if (step === 'edit') {+ // Not a stage swap any more — a tab switch that carries the film. The+ // Editor is its own window; this is the door into it from a board.+ edOpenBoard(SB.id);+ return;+ }+ if (step === 'film') sbFilmOpen();+}+async function sbLoad(id, quiet) {let r;try {@@ -53491,8 +60465,12 @@ async function sbLoad(id, quiet) {return;}sbPlanBtnReset();- sbShow('plan');+ // A 2 s poll must not yank someone off the film screen and back onto the+ // shot list. The shot list is still repainted underneath — it just isn't+ // shoved in front of the film the user asked to watch.+ sbShow(SB.stage === 'film' ? 'film' : 'plan');sbRenderPlan(r);+ if (SB.stage === 'film') return;// The player keeps whatever was last selected globally, so opening a film// showed an unrelated Video-tab render under the film's own title. Put the// film's newest clip up — but only when the current one isn't already one of@@ -53529,17 +60507,30 @@ function sbRenderPlanFail(p) {// is on while there is nothing for the player to show — the same trick the// Ideogram layout editor uses to take the whole column.function sbShow(which) {+ // Five states now, not six: `timeline` moved out to the Editor tab, which+ // owns its own visibility. A stage state was the wrong home for a document.const states = { empty: 'sbEmpty', list: 'sbList', planning: 'sbPlanning',- planfail: 'sbPlanFail', plan: 'sbPlan' };+ planfail: 'sbPlanFail', plan: 'sbPlan',+ film: 'sbFilm' };+ SB.stage = which;Object.keys(states).forEach(k => {const el = sbEl(states[k]);if (el) el.hidden = (k !== which);});+ // A <video> left playing behind a hidden div is a decoder and a soundtrack+ // nobody can see. Leaving the film screen stops it.+ if (which !== 'film') {+ const v = sbEl('sbFilmVideo');+ if (v) { try { v.pause(); } catch (e) {} }+ }// The brief's board list is a way BACK to another film while one is open.// While the stage is already showing the list, it would be the same list// twice in one screen — so it folds away.const boards = sbEl('sbBoards');- if (boards) boards.hidden = !SB.boards.length || which === 'list' || which === 'empty';+ if (boards) {+ boards.hidden = !SB.boards.length || which === 'list' || which === 'empty';+ }+ sbRailPaint();sbSyncStage();}@@ -53551,6 +60542,16 @@ function sbHasClip() {function sbSyncStage() {const on = document.body.dataset.workflow === 'storyboard';const hasClip = on && sbHasClip();+ // The editor no longer lives in this column, so this function no longer+ // decides anything about it — `body.sbe-open` and the layout takeover it+ // drove are both gone with the move to the Editor tab.+ // The film screen IS a player, so it takes the column on those terms.+ if (on && SB.stage === 'film') {+ document.body.classList.add('sb-full');+ const t = sbEl('sbStageToggle');+ if (t) t.hidden = true;+ return;+ }let full;if (!on) full = false;else if (SB.stageMode === 'list') full = true;@@ -53947,6 +60948,10 @@ function sbRenderTally(shots, r) {const canExport = shots.some(s => s.final_output);sbEl('sbExportBtn').hidden = !canExport;sbEl('sbExportNote').hidden = !canExport;+ // The timeline works off ANY rendered clip — draft or delivery — because+ // that is the same selection the exporter makes (_sbe_board_clips).+ const tl = sbEl('sbTimelineBtn');+ if (tl) tl.hidden = !shots.some(s => s.draft_output || s.final_output);}// The shots that never got a draft — after a Stop, or when a shot was added by@@ -54321,7 +61326,7 @@ async function sbStopFilm() {const shots = (((SB.payload || {}).board) || {}).shots || [];const waiting = shots.filter(s => s.status === 'queued').length;if (!confirm('Stop this storyboard?\n\n' +- `The shot that's rendering will finish. The ${waiting} shot${waiting === 1 ? '' : 's'} still waiting ${waiting === 1 ? 'is' : 'are'} removed from the queue.\n` ++ `The shot that's rendering is cancelled — its clip is lost. The ${waiting} shot${waiting === 1 ? '' : 's'} still waiting ${waiting === 1 ? 'is' : 'are'} removed from the queue.\n` +'Everything already rendered stays.')) return;const fd = new URLSearchParams(); fd.set('id', SB.id);try { await fetch('/storyboard/stop', { method: 'POST', body: fd }); } catch (e) {}@@ -54329,18 +61334,148 @@ async function sbStopFilm() {}async function sbExport() {+ // Export used to be a handful of file copies and came back instantly. It now+ // ALSO encodes the whole film, which takes as long as an encode takes — so+ // the button has to hold itself shut, or an impatient second click starts a+ // second ffmpeg writing the same file as the first.+ const btn = sbEl('sbExportBtn');+ if (btn.dataset.busy === '1') return;+ const prev = btn.textContent;+ btn.dataset.busy = '1';+ btn.disabled = true;+ btn.textContent = 'Assembling…';const fd = new URLSearchParams(); fd.set('id', SB.id);let r;try { r = await (await fetch('/storyboard/export', { method: 'POST', body: fd })).json(); }catch (e) { r = { ok: false, error: String(e) }; }+ finally { btn.dataset.busy = ''; btn.disabled = false; btn.textContent = prev; }if (!r.ok) { phosToast(r.error || 'Export failed.', { kind: 'danger' }); return; }- phosToast(`Exported ${r.files.length} clips + a shot list to ${r.dir}`,- { kind: 'success', duration: 6000 });- const btn = sbEl('sbExportBtn');- const prev = btn.textContent;- btn.textContent = 'Show in Finder';- btn.onclick = () => fetch('/storyboard/reveal', { method: 'POST', body: fd });- setTimeout(() => { btn.textContent = prev; btn.onclick = sbExport; }, 10000);+ // The film is best-effort: the folder + shot list always land, so a failed+ // assembly is a NOTE on a successful export, never a failed export.+ if (r.film_name) {+ phosToast(`Exported ${r.files.length} clips + ${r.film_name} `+ + `(${Math.round(r.film_duration || 0)} s) to ${r.dir}`,+ { kind: 'success', duration: 8000 });+ // AND SHOW IT. A toast that fades is what made the finished film invisible:+ // the panel wrote a film, said so for eight seconds, and then left the user+ // on a list of individual shots. The export ends on the film it made.+ sbFilmOpen({ focus: r.film_name });+ } else {+ phosToast(`Exported ${r.files.length} clips + a shot list to ${r.dir}. `+ + `The single film could not be assembled: ${r.film_error || 'unknown reason'}`,+ { duration: 9000 });+ }+}++// ---- THE FILM SCREEN -------------------------------------------------------+// The seventh stage state, and the one the other six are for. Reads+// /storyboard/films — the folder both assemblers already write into — so this+// screen invents no storage and can never disagree with what is on disk.+async function sbFilmOpen(opts) {+ if (!SB.id) return;+ const o = opts || {};+ if (o.focus) SB.filmOpen = String(o.focus).split('/').pop();+ // Never show the LAST board's film while this board's list is in flight.+ if (SB.filmsFor !== SB.id) { SB.films = []; sbEl('sbFilmBody').innerHTML = ''; }+ sbShow('film');+ const stage = sbEl('sbStage');+ if (stage) stage.scrollTop = 0;+ sbEl('sbFilmStatus').textContent = 'looking…';+ await sbFilmLoad();+}+async function sbFilmLoad() {+ let r;+ try {+ r = await (await fetch('/storyboard/films?id=' + encodeURIComponent(SB.id))).json();+ } catch (e) { r = null; }+ if (!r || !r.ok) {+ SB.films = [];+ sbEl('sbFilmStatus').textContent = '';+ sbEl('sbFilmBody').innerHTML =+ '<div class="sb-empty"><div class="sb-empty-title">Could not read the films folder.</div>'+ + '<div class="sb-empty-sub">' + escapeHtml((r && r.error) || 'the panel did not answer')+ + '</div></div>';+ return;+ }+ SB.films = r.films || [];+ SB.filmsFor = SB.id;+ SB.filmDir = r.dir || '';+ SB.filmShort = r.dir_short || r.dir || '';+ sbFilmPaint();+ sbRailPaint();+}+function sbFilmPaint() {+ const body = sbEl('sbFilmBody');+ const status = sbEl('sbFilmStatus');+ if (!body) return;+ const film = sbFilmPick(SB.films, SB.filmOpen);+ if (!film) {+ // Honest, and it names the button that would fix it. The old behaviour was+ // to show nothing at all and let the user conclude the film didn't exist.+ const shots = ((((SB.payload || {}).board) || {}).shots) || [];+ const clips = shots.filter(s => s.draft_output || s.final_output).length;+ status.textContent = 'nothing rendered yet';+ body.innerHTML = `+ <div class="sb-empty">+ <div class="sb-empty-icon"><svg width="56" height="56" viewBox="0 0 256 256" aria-hidden="true"><use href="#ph-film-slate"/></svg></div>+ <div class="sb-empty-title">No film yet.</div>+ <div class="sb-empty-sub">${clips+ ? 'Arrange the ' + clips + ' clip' + (clips === 1 ? '' : 's') + ' you have on the timeline and render. The finished film lands in <code>' + escapeHtml(SB.filmShort || 'mlx_outputs/storyboards/') + '</code> and appears here.'+ : 'Render some shots first — a film is the shots, joined. Nothing to arrange yet.'}</div>+ ${clips ? '<div class="sb-film-actions"><button type="button" class="primary" onclick="sbGo(\'arrange\')">Open the timeline</button></div>' : ''}+ </div>`;+ return;+ }+ SB.filmOpen = film.name;+ const dims = (film.width && film.height) ? `${film.width}×${film.height}` : '';+ // The header stays quiet once there is a film on screen — the facts row below+ // says all of it, and saying it twice is how a screen starts feeling padded.+ status.textContent = '';+ const others = (SB.films || []).filter(f => f.name !== film.name);+ body.innerHTML = `+ <div class="sb-film-stage">+ <video id="sbFilmVideo" controls playsinline preload="metadata"+ src="${escapeHtml(film.url)}"></video>+ </div>+ <div class="sb-film-name">+ <span class="sb-film-kind">${escapeHtml(sbFilmKind(film))}</span>+ <code>${escapeHtml(film.name)}</code>+ </div>+ <div class="sb-summary">+ <div class="sb-sum-cell"><b>${film.duration ? escapeHtml(sbFmtClock(film.duration)) : '—'}</b><span>${film.clips ? film.clips + ' shots joined' : 'runtime'}</span></div>+ <div class="sb-sum-cell"><b>${escapeHtml(dims || '—')}</b><span>${escapeHtml(sbFmtBytes(film.bytes))} on disk</span></div>+ <div class="sb-sum-cell"><b>${escapeHtml(sbFmtAgo(film.at) || '—')}</b><span>${escapeHtml(sbFilmKind(film).toLowerCase())}</span></div>+ </div>+ <div class="sb-film-where">Lives in <code>${escapeHtml(SB.filmShort || SB.filmDir)}</code></div>+ <div class="sb-film-actions">+ <button type="button" class="ghost-btn" onclick="sbFilmReveal()">+ <svg class="ph" aria-hidden="true"><use href="#ph-folder-simple"/></svg>Show in Finder</button>+ <button type="button" class="ghost-btn" onclick="sbGo('edit')"+ title="Back to the cut this was assembled from — re-cut it in the Editor and render again.">Re-cut in the Editor</button>+ </div>+ ${others.length ? `+ <header class="carousel-head" style="margin-top:6px"><h3>Earlier films</h3></header>+ <ul class="row-list sb-filmlist">+ ${others.map(f => `+ <li onclick="sbFilmSelect('${escapeHtml(f.name)}')">+ <span class="ttl">${escapeHtml(f.name)}</span>+ <span class="params">${f.duration ? escapeHtml(sbFmtClock(f.duration)) + ' · ' : ''}${escapeHtml(sbFmtBytes(f.bytes))}</span>+ <span class="badge">${escapeHtml(sbFmtAgo(f.at))}</span>+ </li>`).join('')}+ </ul>` : ''}`;+}+function sbFilmSelect(name) {+ SB.filmOpen = name;+ sbFilmPaint();+}+async function sbFilmReveal() {+ const fd = new URLSearchParams();+ fd.set('id', SB.id);+ if (SB.filmOpen) fd.set('name', SB.filmOpen);+ let r;+ try { r = await (await fetch('/storyboard/reveal', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) phosToast(r.error || 'Could not open the folder.', { kind: 'danger' });}// ---- board lists -----------------------------------------------------------@@ -54348,12 +61483,38 @@ function sbBoardChip(b) {if (b.planning) return 'planning';if (b.running) return 'rendering';if (b.failed) return `${b.failed} failed`;- if (!b.done) return 'plan only';+ // `done` counts shots THIS PANEL rendered as jobs; `clips` counts what is on+ // disk. A board of imported or restored clips has done === 0, and the chip+ // called it "plan only" while seven finished shots sat in the folder.+ if (!b.done) return b.clips ? `${b.clips} clips` : 'plan only';if (b.done >= b.shots) return 'drafts done';// Partway and idle — stopped, or one shot retried. Saying "rendering" here// would be the chip claiming something the machine isn't doing.return `${b.done} of ${b.shots}`;}+// The row's trailing slot names the FURTHEST place this board has got to, and+// goes there. One slot, never two.+//+// The owner could not find the editor ("it doesn't even have a button") and+// could not find his film ("where is the finalized clip?"). Both answers are+// the same answer: from the list of films, the next thing you want is one+// click away, and the row says which thing that is.+function sbRowAction(b) {+ if (b.film) {+ const len = b.film.duration ? ' · ' + sbFmtClock(b.film.duration) : '';+ return `<button class="sb-row-go" title="Watch the finished film"+ onclick="event.stopPropagation();sbOpenAt('${escapeHtml(b.id)}','film')">+ <svg class="ph" aria-hidden="true"><use href="#ph-film-slate"/></svg>Film${escapeHtml(len)}</button>`;+ }+ // `clips` is what is on disk; `done` is only what this panel rendered as a+ // job. A board of imported clips is editable and must show the way in.+ if (b.clips || b.done) {+ return `<button class="sb-row-go" title="Open this film in the Editor"+ onclick="event.stopPropagation();sbOpenAt('${escapeHtml(b.id)}','edit')">+ <svg class="ph" aria-hidden="true"><use href="#ph-scissors"/></svg>Open in Editor</button>`;+ }+ return '';+}function sbRenderBoardLists() {const rows = SB.boards.map(b => `<li data-id="${escapeHtml(b.id)}" class="${b.running || b.planning ? 'is-live' : ''}"@@ -54361,6 +61522,7 @@ function sbRenderBoardLists() {<span class="ttl">${escapeHtml(b.title || 'Untitled film')}</span><span class="params">${b.shots} shots · ${b.done} rendered</span><span class="badge">${escapeHtml(sbBoardChip(b))}</span>+ ${sbRowAction(b)}<button title="Delete this storyboard" onclick="event.stopPropagation();sbDeleteBoard('${escapeHtml(b.id)}','${escapeHtml((b.title || '').replace(/'/g, ''))}')"><svg class="ph" aria-hidden="true"><use href="#ph-x-bold"/></svg></button></li>`).join('');const full = sbEl('sbBoardList');@@ -54412,6 +61574,17 @@ function sbOpenFromClip(id) {// ---- the one cross-tab hook, called at the end of poll() -------------------function sbPollHook(s) {SB.boards = s.storyboards || [];+ // Repaint the rows only when the rows changed. /status carries the film+ // summary now, so "this board has a film" lights up the moment ffmpeg+ // finishes — without rebuilding a list under the cursor twice a second.+ const sig = JSON.stringify(SB.boards.map(b => [b.id, b.title, b.shots, b.done,+ b.clips, b.failed, b.running, b.planning,+ b.film ? [b.film.name, b.film.at, b.film.count] : 0]));+ if (sig !== SB.boardsSig) {+ SB.boardsSig = sig;+ sbRenderBoardLists();+ if (SB.id) sbRailPaint();+ }const live = SB.boards.filter(b => b.running);const count = sbEl('sbTabCount');if (count) {@@ -54573,6 +61746,7727 @@ document.addEventListener('dragend', () => {document.querySelectorAll('.sb-shot').forEach(el =>el.classList.remove('is-dragging', 'sb-drop-before', 'sb-drop-after'));});+// ===========================================================================+// THE TIMELINE — the client half of /storyboard/edit+// ===========================================================================+//+// The shot list is INTENT: what the film should contain, one card per thing to+// render. This is ARRANGEMENT: what plays, from which second of which file, at+// which second of the film. Two documents on disk for the reason+// storyboard_editor.py gives — the moment one shot is used twice, or one is+// split in half, they are different shapes forever.+//+// THREE MEASURED FACTS SHAPE EVERY DECISION BELOW.+//+// 1. A source clip is a single GOP: 235 ms median to seek in Chrome, 1266 ms+// p90. The all-intra proxy seeks in 3.5 ms. So the preview NEVER points at+// clip.path when clip.proxy exists, and the one place it may (no proxy yet)+// says so on the badge instead of pretending.+//+// 2. Two <video> elements measured NO benefit over one once proxies are in+// play — the swap costs what the seek costs, and two decoders is two+// decoders. There is one video element here, deliberately.+//+// 3. The preview freezes 50-67 ms at each cut (1.2-1.6 frames at 24 fps) and+// Safari's seeking is accurate to 3-6 frames. That is stated once, quietly,+// under the transport, and never papered over: the render is exact, the+// preview is an approximation of it.+//+// Two traps this feature already paid for, both load-bearing: `muted` is set+// BEFORE the first play() or Chrome silently refuses autoplay, and elements are+// hidden with opacity, never display:none, or WebKit will not load them.++// ---- HOW TALL THE TIMELINE IS, AND WHERE THE HEIGHT GOES ----------------+// Declared HERE rather than with the other SBE_* constants below, because+// SBE's own initialiser reads the stored preference through them and a `const`+// three hundred lines further down is a temporal dead zone, not a value.+//+// The timeline box is a ruler, four lanes, a scrollbar gutter and two borders.+// Only the lanes grow.+const SBE_TL_CHROME = 32; // 18 ruler + 12 scrollbar gutter + 2 border+// THE LANES, in the order they are on screen. `base` is the floor each one has+// always had, `cap` is the point past which more height stops buying anything,+// and `share` is what fraction of every dragged pixel it takes.+//+// DISTRIBUTED BY SHARE, NOT PROPORTIONAL TO WHAT IS THERE. Proportional+// scaling would hand the picture track 41% of the drag (78 of the 188px of+// lane) and the sound strip 14% — the exact opposite of the reason the handle+// was asked for. 70% of every pixel goes to the two SOUND lanes instead, so+// 100px of drag turns a 26px strip into ~68px: the level line's usable band+// more than triples and a keyframe becomes a target rather than a rumour. The+// ruler takes none of it — a ruler is not more legible for being taller.+//+// REBALANCED 2026-08-20, after the owner used it: "the squares for the video+// design, like the video in the timeline, are expanded too much; they are too+// big. They don't need to be this big." A picture block is a LABEL WITH A+// THUMBNAIL HINT — a name, a timecode, and enough of the frame behind them to+// tell two shots apart. It is not a poster: the frame it stands for is already+// on the program monitor, full size, two inches above. So the picture lane's+// base drops 78 -> 64 (a 52px block: name row, meta row, and a band of picture)+// and its ceiling 240 -> 120, which is the tallest a block can be and still+// read as a block. Both ends were checked on screen.+//+// The height it gave up went to the sound, and so does the drag: the picture's+// share falls 0.22 -> 0.14 and the two sound lanes rise to 0.78 of every+// dragged pixel. The bases rise too — 26 -> 44 on the clip strip and 54 -> 72+// on the soundtrack — because the level line has to be legible AT REST, not+// only after somebody has discovered the handle and pulled it.+const SBE_LANES = [+ { key: 'ov', base: 32, cap: 56, share: 0.08 }, // overlay: a card is placed, not performed+ { key: 'track', base: 64, cap: 120, share: 0.14 }, // the picture: a labelled block, not a poster+ { key: 'alane', base: 44, cap: 190, share: 0.44 }, // per-clip sound: waveform, level line, points+ // The soundtrack. Its base rose 72 -> 108 when the bed stopped being a+ // rectangle you can only slide: it now carries a waveform, a level line,+ // draggable points and two corner fade handles, exactly like the strip lane+ // above it — and that lane's base rose 26 -> 44 for the same reason, which+ // is that a control has to be legible AT REST and not only after somebody+ // has discovered it. The HEAD grew with it (the level and the duck now live+ // there), and head and lane read the same variable on purpose.+ { key: 'wave', base: 108, cap: 240, share: 0.34 }, // the soundtrack+];+// Both ends are the SUM of the parts, never a hand-picked round number — the+// floor is every lane at its base (which is what the box needs to draw itself+// without clipping) and the ceiling is every lane at its cap (past which the+// drag would be buying dead band). `test_the_height_floor_is_the_sum_of_its+// _lanes` asserts exactly that, because the 190 this replaced was itemised in+// a comment and the overlay lane was added without moving it: the box has+// been 30px short of its own contents, with `overflow-y: hidden` over the+// difference, since that lane shipped.+const SBE_TL_MIN_H = 280;+const SBE_TL_MAX_H = 638;+// How far one arrow key moves the edge, and one arrow key with Shift.+const SBE_TL_STEP = 12;+const SBE_TL_STEP_BIG = 40;++// ---- THE CORNER HANDLES' FOOTPRINT, as the SVG has to know it -----------+// These MIRROR `--sbe-grip-w`, `--sbe-grip-skirt` and `--sbe-fade-hit` in the+// stylesheet, and they are here because the level line is drawn, not styled:+// its target is a path this file emits, so the only way to keep that path off+// the fade handles' pixels is to know in JS where those pixels are.+//+// A MIRROR IS A THING THAT DRIFTS, so the browser is what catches it, not a+// grep: `scripts/measure_editor_layout.py` measures the three rectangles in a+// laid-out page and fails if any two of them intersect. If somebody changes+// the CSS and forgets these, the gate goes red with both numbers in it.+const SBE_AGRIP_W = 7; // a strip's grip is thinner than a block's+const SBE_GRIP_SKIRT = 3; // ...and can be hit this far past what it draws+const SBE_FADE_HIT = 22; // the fade handle's square target+// The first x on a strip that no corner handle stands on, and the last.+// THE +1 IS THE SVG'S OWN ROUNDING. The strip's <svg> carries an integer+// `width` attribute over a viewBox of the same integer, but the element is+// laid out at the strip's REAL fractional width — so one user unit is+// px/round(px) CSS pixels and the clip lands up to half a pixel off. Measured+// without it: the target's left edge came back at 471.84 against a handle+// ending at 472.00, which is a 0.16px overlap and a red gate. A pixel of+// margin costs nothing and is not a number anybody has to maintain.+const SBE_LVL_CLEAR = SBE_AGRIP_W + SBE_GRIP_SKIRT + SBE_FADE_HIT + 1;+// Below this there is no line left to aim at, so none is offered.+const SBE_LVL_MIN_SPAN = 12;++// ---- THE LEVEL LINE'S GEOMETRY, in ONE place ----------------------------+// "I still don't understand how to add keyframes, to be honest." — said after+// using it, which makes it a discoverability defect and not a user one. The+// gesture was double-click-to-add, drag-to-set, shift-click-to-remove: three+// things knowable only by being told.+//+// Everything that reads or writes a level now goes through this pair, because+// three gestures were each carrying their own copy of the arithmetic and two+// of them had already drifted onto a hard-coded 20px band. `sbeStripY` and+// `sbeStripGain` are exact inverses at every strip height — there is a test+// that round-trips them at five of them.+// HEADROOM, AND IT IS THE WHOLE OF WHY THE LINE IS DRAGGABLE. "You are able to+// drag the sound thingy, but it's not super user-friendly. Maybe you should put+// the orange line a little lower so it feels more draggable." At 1px, unity was+// drawn ON the strip's own top edge: the target is a 14px stroke centred on the+// line, so six of its seven upper pixels fell outside the strip and were+// clipped away by the SVG viewport, leaving a one-sided sliver to aim at that+// also competed with the lane's border.+//+// EIGHT IS DERIVED, NOT PICKED: half of `.sbe-lvl-hit`'s 14px stroke, plus one,+// so the entire target lies inside the strip at every height the share table+// can produce — 37px at the floor included. Unity still means "the top of the+// scale", which was built deliberately and is not what he asked to change; it+// simply no longer means "the top pixel of the box".+const SBE_LVL_PAD = 8; // the line never touches the strip's own edge+// How near the pointer has to be for the LINE to answer rather than the strip+// under it. Twelve pixels is the same order as the dot's own target, and it is+// what makes "click the line" a gesture instead of a bullseye.+const SBE_LVL_GRAB = 12;+function sbeStripY(gain, H) {+ const h = Math.max(2 * SBE_LVL_PAD + 1, sbeNum(H));+ return (1 - Math.max(0, Math.min(1, sbeNum(gain)))) * (h - 2 * SBE_LVL_PAD)+ + SBE_LVL_PAD;+}+function sbeStripGain(y, top, H) {+ const h = Math.max(2 * SBE_LVL_PAD + 1, sbeNum(H));+ return Math.max(0, Math.min(1,+ 1 - (sbeNum(y) - sbeNum(top) - SBE_LVL_PAD) / (h - 2 * SBE_LVL_PAD)));+}++window.SBE = {+ open: false, id: '', title: '',+ edit: null, clips: [], audio: null, beats: null,+ peaks: null, peaksFor: '', unplaced: [], pool: [], relink: [], prepare: {},+ onMissing: null,+ proxyUrl: '', revision: 0, dirty: false, saving: false, conflict: 0,+ // THE SAVE'S OWN BOOKKEEPING. `savePending` is the save that arrived while+ // another was in flight and used to be thrown away; `dirtyAt` is when the+ // oldest unwritten change was made, which is what lets the tick notice that+ // nothing has reached the disk for too long; `saveFailed` is the reason the+ // alarm is up, and it is a string precisely so it can be shown.+ savePending: false, dirtyAt: 0, saveFailed: '',+ // The quiet lane's own two facts, and the drafts this film has.+ backingUp: false, backedUpAt: 0,+ drafts: [], activeDraft: '', backup: null,+ // Which row the name field is currently editing, '' when it is making a new+ // draft. One field with two verbs and no mode is a field that picks the+ // wrong one every time Enter is pressed.+ renaming: '',+ sel: '', playhead: 0, playing: false, curId: '', pps: 42,+ undo: [], redo: [], errors: {}, sentOrder: [],+ // THE ONE NOTICE SURFACE. `noticeLead` is the chip the user clicked open,+ // `backupHidden` is "Later" on the recovery offer (this session, this+ // offer), `errsOpen` is the validation list unfolded past its first line.+ noticeLead: '', backupHidden: false, errsOpen: false,+ // THE OVERLAY LANE — a second video track, above the picture. Its own list+ // for the same reason the server keeps one: the picture lane may not+ // overlap itself, and an overlay's whole job is to sit ON a picture.+ overlays: [], ovSel: '', ovDrag: null,+ // The last card whose black backdrop was keyed on the way in: which overlay+ // it became, and the untouched file it came from. This is what "Keep+ // original" undoes, and it is null whenever that receipt is not on screen.+ keyed: null,+ // One waveform per SOURCE, not per clip: the same take used twice draws the+ // same picture and each strip slices its own window out of it.+ clipPeaks: null, kfDrag: null,+ // THIS TAB'S IDENTITY, for the life of the tab. Whoever loaded last owns+ // the snapshot lane; a tab that finds another editor is TOLD, and goes on+ // read-only rather than writing its stale state over the live one every+ // debounce. See docs/EDITOR_SAVE_MODEL.md §5.+ session: 'ss' + Math.random().toString(16).slice(2, 10) ++ (Date.now() % 1048576).toString(16),+ // WHO ELSE IS EDITING, and when this tab was last actually protected.+ // There is deliberately no flag here that can stop the writer: the one that+ // used to exist (`superseded`) was set by a passive page load in another+ // browser and switched this tab's safety net off for seven hours.+ otherEditor: '', protectedAt: 0,+ timer: null, saveTimer: null, raf: 0, drag: null, awaitingClip: 0,+ // The soundtrack's own drag. Separate from `drag` because the two lanes are+ // separate objects and a pointer is only ever on one of them.+ musicDrag: null, audioDrag: null,+ music: '', musicEl: null, musicOk: true, rendering: false, muteToasted: false,+ // `dropAt` is where the insertion line is painted while something is being+ // dragged onto the track — null when nothing is. `lastTs` is the wall clock+ // the transport falls back on for the clips that carry no <video> to read a+ // currentTime off (a still, a slug, a hole).+ dropAt: null, lastTs: 0,+ // THE SOURCE MONITOR. `source` is the pool row on the left screen (null+ // when nothing has been clicked yet) and `srcIndex` is where it sat in the+ // painted pool, which is what "Add to timeline" hands back to edPoolAdd so+ // the two doors take exactly the same path. Never both monitors at once:+ // sbeSrcPlay stops the program and sbePlay stops the source.+ source: null, srcIndex: -1, srcPlaying: false,+ // Sound is ON. It survives a reload because a muted editor is indistinguishable+ // from a broken one, and that is the bug this default is paying off.+ muted: (localStorage.getItem('sbeMuted') === '1'),+ // HOW TALL THE TIMELINE IS, and who decides. `tlH` is the user's preference+ // — restored from this browser, never from the document — `tlNow` is what+ // the layout could actually give it once the window had its say, and+ // `tlMax` is what the window has left before the monitors stop being+ // monitors. The handle drags `tlH`; sbeFitMonitors writes the other two.+ // `laneAt` is the height the two SOUND lanes were last DRAWN at, which is+ // not always the height they are currently given — see the end of+ // sbeFitMonitors for the one pass where those two disagree.+ tlH: sbeTlPrefRead(), tlNow: 0, tlMax: 0, tlDrag: null, laneAt: -1,+ // THE GHOST POINT. Where a click on the level line would put one — null+ // whenever the pointer is not near a line it could edit. It is the whole of+ // "hover teaches": the control answers before it is used.+ kfGhost: null,+};++const SBE_MIN_CLIP = 0.2; // shorter than this is not a shot, it is a blink+const SBE_UNDO_MAX = 80;+const SBE_SNAP_PX = 9; // how near the pointer must be to catch a beat+const SBE_GUESS_CONFIDENCE = 0.4; // below this the grid is drawn as a guess+// The same clamp `storyboard_editor.BRIGHTNESS_LIMIT` enforces on the way in.+// Half of ffmpeg's additive range is already past "unusable" in both+// directions, and a slider that can ask for a value the server will refuse is+// a slider that produces a red error box instead of a picture.+const SBE_BRIGHT_MAX = 0.5;+// How long a still holds when it lands. Long enough to read a title card,+// short enough that nobody has to trim it DOWN before the film is watchable —+// and it is the trim handles' job from there.+const SBE_STILL_SECONDS = 3.0;+// ---- the two sliders, and the two monitors ------------------------------+// sbePaint pads the inner by this much past the last frame, so "the whole+// film fits" means (viewport - SBE_TL_PAD) / span, not viewport / span.+const SBE_TL_PAD = 24;+// THE TIMELINE DOES NOT END WHERE THE CLIPS END. "The film's length and the+// audio's placement are independent facts and the UI must treat them that+// way" — so the scroller runs past the last frame by this much, and the music+// can be dragged out there instead of stopping dead against the final cut.+// Proportional with both ends pinned: 3 s is enough room to grab an edge on a+// short cut, 15 s stops a ten-minute film from opening on two minutes of+// nothing.+const SBE_SLACK_MIN = 3;+const SBE_SLACK_MAX = 15;+const SBE_SLACK_RATIO = 0.15;+// An EMPTY timeline is still a timeline: a ruler you can read and a lane the+// music can be dropped into. Without a floor the span is one second, the+// ruler is a single tick, and the first thing the Editor shows a new film is+// a box that looks broken.+const SBE_SPAN_MIN = 10;+// The shortest the soundtrack can be trimmed to. Same reason SBE_MIN_CLIP+// exists: a zero-length window is one ffmpeg refuses and one no pointer can+// grab back.+const SBE_MIN_MUSIC = 0.5;+// HALF A FRAME AT 24 fps, and the same number the server's TOUCH_TOLERANCE+// uses to decide whether two clips touch. Below it a sound is in sync: every+// window on the timeline is rounded to a microsecond, so an exact-zero test+// would flag a strip that is one float away from where it started.+const SBE_SYNC_TOL = 1 / 48;+// The timeline's floor, its ceiling and the lanes between them are declared+// with SBE itself, up where its initialiser can read them.+const SBE_PPS_MAX = 200; // the old zoom ladder's top step+const SBE_PPS_FLOOR = 0.5; // below this a cut is thinner than a pixel+const SBE_ZOOM_TICKS = 1000; // the range input's resolution+// The gap between the monitors, and the smallest picture worth calling one.+const SBE_MON_GAP = 12;+const SBE_MON_MIN_H = 120;+// Source height / program height. 2/3 is the 40/60 split by width that was+// asked for; sbeMonitorFit widens it toward 1 (equal monitors) when the+// window is too short to fill the row at 40/60, because a symmetric black+// gutter either side of the pair is the thing this whole pass is removing.+const SBE_MON_RATIO = 2 / 3;+const SBE_MON_RATIO_MAX = 1;+// The inspector rail beside the monitors. Narrower than this it is a slot,+// wider than this it is a second sidebar — and either way it is the width the+// monitors could not use, not a width of its own choosing.+const SBE_RAIL_MIN = 200;+const SBE_RAIL_MAX = 380;++function sbeEl(id) { return document.getElementById(id); }+function sbeNum(v, d) { const n = Number(v); return (n === n && isFinite(n)) ? n : (d || 0); }+function sbeRound(v) { return Math.round(sbeNum(v) * 1e6) / 1e6; }+function sbeFps() { return (typeof FPS === 'number' && FPS > 0) ? FPS : 24; }++// ---------------------------------------------------------------------------+// THE MODEL. Everything in this section is pure: arrays in, arrays out, no DOM,+// no fetch. That is what makes the drag maths, the snap, the ripple and the+// save payload testable in node rather than by eye — see+// test_storyboard_editor_ui.py, which runs these exact functions.+// ---------------------------------------------------------------------------+function sbeLen(c) { return Math.max(SBE_MIN_CLIP, sbeNum(c.end) - sbeNum(c.start)); }++// Each clip owns the gap that PRECEDES it. That single choice is what makes+// every operation below a one-liner: a move is "change which gap you own", a+// ripple delete is "take your gap with you", and the film position of every+// clip is a running total that cannot drift from its own source window.+// A LEAD GAP LIVES ON THE FRAME GRID. Under one frame is NO gap.+//+// The owner's report was "a black frame that flashes for a microsecond... I+// tried to drag them close and whatever" — and the second half is the defect.+// The holes were 0.503, 0.380 and 0.096 of a frame: too small to see at any+// zoom, too small for any pixel to address, and the stage paints black+// wherever no clip is playing. Rounding to the NEAREST frame would have turned+// the 0.503 into a whole frame of black, which is the same bug one frame+// louder; anything under a frame is float noise from a drag and a JSON round+// trip, and zero is its only honest reading. See the block above `film_fps` in+// storyboard_editor.py for why the grid is enforced on gaps and not on+// absolute film positions.+function sbeGridGap(gap) {+ const f = 1 / sbeFps();+ const g = Math.max(0, sbeNum(gap));+ // A LARGER GAP IS LEFT EXACTLY AS AUTHORED. Snapping a 43.2-frame slug to+ // 43 frames would rewrite a number the user chose to buy a property nothing+ // reads: the cuts either side of a gap are already exact once the gap is a+ // fixed quantity. See `quantise_gap` in storyboard_editor.py.+ return (g < f - 1e-9) ? 0 : sbeRound(g);+}++function sbeAdoptGaps(clips) {+ let cursor = 0;+ // A HEAL CARRIES THE SOUND; A GESTURE DOES NOT. Closing a sub-frame hole is+ // not the user sliding a picture, so an unlinked strip travels with it by+ // the same delta and the J-cut's offset is exactly what it was. Dragging is+ // the opposite by design — the picture moves and the strip stays, which is+ // how a J-cut is made in the first place — so `sbeLayout` never does this.+ for (const c of clips) {+ const raw = Math.max(0, sbeNum(c.film_start) - cursor);+ const gap = sbeGridGap(raw);+ const shift = raw - gap;+ if (shift > 1e-9 && c.audio && c.audio.film_start !== undefined+ && c.audio.film_start !== null) {+ c.audio = Object.assign({}, c.audio,+ { film_start: sbeRound(sbeNum(c.audio.film_start) - shift) });+ }+ c._gap = gap;+ if (c.locked) c._pin = sbeNum(c.film_start);+ cursor = sbeNum(c.film_end) || (sbeNum(c.film_start) + sbeLen(c));+ }+ return clips;+}++// Re-derive film_start / film_end from the lead gaps. film_end is NEVER an+// independent number — nothing plays at anything but 1x, and the server refuses+// an edit whose slot and window disagree by more than a millisecond.+function sbeLayout(clips) {+ const locks = [];+ for (const c of clips) {+ if (c.locked) {+ const s = (c._pin === undefined || c._pin === null) ? sbeNum(c.film_start) : sbeNum(c._pin);+ locks.push([s, s + sbeLen(c)]);+ }+ }+ locks.sort((a, b) => a[0] - b[0]);+ let cursor = 0;+ for (const c of clips) {+ const len = sbeLen(c);+ if (c.locked) {+ const s = (c._pin === undefined || c._pin === null) ? sbeNum(c.film_start) : sbeNum(c._pin);+ c._pin = s;+ c.film_start = sbeRound(s);+ c.film_end = sbeRound(s + len);+ cursor = Math.max(cursor, c.film_end);+ continue;+ }+ // ON THE GRID AT THE LAST POSSIBLE MOMENT. Adopting quantises what came+ // off disk; this quantises what a DRAG just produced, so a gesture cannot+ // reopen the hole a load closed. Both call the same function, so there is+ // one definition of "a gap" and not two that agree today.+ let s = cursor + sbeGridGap(c._gap);+ // A locked clip is an anchor, so a free one flows AROUND it rather than+ // through it. Bounded restart: every push moves s strictly forward.+ for (let pass = 0; pass < locks.length + 1; pass++) {+ let moved = false;+ for (const L of locks) {+ if (s < L[1] - 1e-9 && s + len > L[0] + 1e-9) { s = L[1]; moved = true; }+ }+ if (!moved) break;+ }+ c.film_start = sbeRound(s);+ c.film_end = sbeRound(s + len);+ cursor = c.film_end;+ }+ clips.sort((a, b) => sbeNum(a.film_start) - sbeNum(b.film_start));+ return clips;+}++// ONE LANGUAGE ON THE TRACK. Adjacent blocks were labelled in two: one said+// what the shot IS, the next was a model filename complete with resolution,+// an extension tag and a timestamp — "bizarrotrn_the_man_in_the_loud_4_+// dn768x416_ext6_20260818_215…" — and at fit zoom both truncate, so the track+// read as a row of half-words. The exact filename stays on the block's title.+function sbeNiceName(s) {+ let t = String(s || '').trim();+ if (!t) return '';+ if (t.indexOf('/') >= 0) t = t.split('/').pop();+ t = t.replace(/\.[a-z0-9]{2,5}$/i, '');+ t = t.replace(/_\d{8}_\d{6}$/, '')+ .replace(/_dn\d+x\d+/gi, '')+ .replace(/_ext\d+/gi, '')+ .replace(/_\d+p\b/gi, '')+ .replace(/_seed_\d+$/i, '')+ .replace(/_\d+$/, '');+ t = t.replace(/[_-]+/g, ' ').replace(/\s+/g, ' ').trim();+ if (!t) return String(s || '');+ return t.charAt(0).toUpperCase() + t.slice(1);+}++function sbeFilmDuration(clips) {+ let m = 0;+ for (const c of clips || []) m = Math.max(m, sbeNum(c.film_end));+ return sbeRound(m);+}++// THE SOUNDTRACK IS AN OBJECT, and this is its geometry. The mirror of+// `music_window()` in storyboard_editor.py — the same three fields turned into+// the same numbers, so what the strip shows and what the render builds cannot+// come apart.+// offset the TRACK second that plays at film 0. Negative means the+// music starts that many seconds INTO the film.+// trim_start the in-point inside the track. Absent means 0.+// trim_end the out-point inside the track. Absent means "to the end".+// Returns the block's film span and the window it plays from the track.+function sbeMusicWindow(audio, dur) {+ const a = audio || {};+ const off = sbeNum(a.offset);+ const total = Math.max(0, sbeNum(dur, 0) || sbeNum(a.duration, 0));+ const ts = Math.max(0, sbeNum(a.trim_start));+ let te = (a.trim_end === null || a.trim_end === undefined)+ ? null : sbeNum(a.trim_end);+ // A handle dragged back out to the end of the track is not a trim — the+ // same rule the server's `music_window` and `normalise_edit` follow, so the+ // strip stops calling itself trimmed the moment the field stops being saved.+ if (te !== null && total > 0) te = (te >= total - 1e-6) ? null : Math.min(te, total);+ if (te !== null && te <= ts) te = null;+ const head = Math.max(0, ts, off);+ let tail = (te !== null) ? te : (total > 0 ? total : null);+ if (tail !== null && tail <= head) tail = null;+ // Where the block sits on the FILM. A head trim does not slide the rest of+ // the track earlier — music does not ripple — so the seconds it removes come+ // back as silence in front, which is exactly `head - offset`.+ const filmStart = sbeRound(Math.max(0, head - off));+ const filmEnd = (tail !== null) ? sbeRound(tail - off) : null;+ return { offset: off, duration: total, head: sbeRound(head),+ tail: (tail === null ? null : sbeRound(tail)),+ trimmed: (ts > 0) || (te !== null),+ film_start: filmStart,+ film_end: (filmEnd === null ? null : Math.max(filmStart, filmEnd)) };+}++// One gesture on the music, as pure arithmetic. `mode` is 'move' | 'trimL' |+// 'trimR' and `want` the film second the pointer landed on; the return is the+// three fields to write back, never a mutation — the same contract every clip+// edit above follows, and the reason a drag can be tested in node.+function sbeMusicEdit(audio, mode, want, dur) {+ const w = sbeMusicWindow(audio, dur);+ const total = w.duration;+ const ts = Math.max(0, sbeNum((audio || {}).trim_start));+ const te = (w.tail === null) ? (total > 0 ? total : null) : w.tail;+ const out = { offset: w.offset, trim_start: ts,+ trim_end: ((audio || {}).trim_end === null+ || (audio || {}).trim_end === undefined)+ ? null : sbeNum((audio || {}).trim_end) };+ if (mode === 'move') {+ // Dragging the block moves the whole object: the window into the track is+ // untouched, only where it lands on the film changes.+ //+ // SOLVED FOR THE OFFSET, NOT ROUTED THROUGH THE HEAD. `w.head` is+ // max(0, trim_start, offset), so on a document whose offset is positive —+ // a documented, supported state; `music_window`'s own docstring calls it a+ // head trim — writing `head - want` fed the PREVIOUS offset back into the+ // answer. A pointermove stream re-reads the already-mutated object every+ // event, so the same six-second drag landed at film 6 when it arrived as+ // six events and did not move the block at all when it arrived as one: a+ // gesture whose result depended on how fast the mouse was going. Worse,+ // `offset` changed even when the block visibly did not, so the drag+ // marked the film dirty, burned an undo step and queued a write.+ // Both branches below give film_start === t under sbeMusicWindow and+ // neither reads the offset, so N events converge on what one event does.+ const t = Math.max(0, sbeNum(want));+ out.offset = sbeRound(ts > 0 ? (ts - t) : -t);+ return out;+ }+ if (mode === 'trimL') {+ // The left edge chooses a new in-point. Bounded by the head of the track+ // one way and by the out-point (less the floor) the other.+ const filmEnd = (w.film_end === null) ? null : w.film_end;+ let t = Math.max(0, sbeNum(want));+ if (filmEnd !== null) t = Math.min(t, filmEnd - SBE_MIN_MUSIC);+ let inPoint = sbeRound(t + w.offset);+ inPoint = Math.max(0, inPoint);+ if (te !== null) inPoint = Math.min(inPoint, sbeRound(te - SBE_MIN_MUSIC));+ out.trim_start = Math.max(0, sbeRound(inPoint));+ return out;+ }+ // trimR — the out-point, bounded by the in-point and by the track's own end.+ let t = Math.max(0, sbeNum(want));+ let outPoint = sbeRound(t + w.offset);+ outPoint = Math.max(sbeRound(Math.max(ts, w.head) + SBE_MIN_MUSIC), outPoint);+ if (total > 0) outPoint = Math.min(outPoint, sbeRound(total));+ out.trim_end = sbeRound(outPoint);+ return out;+}++// The times a music edge is allowed to click onto: the start of the film and+// every cut in it. NOT the beat grid — the grid is derived from this very+// track at this very offset, so snapping the music to it would be snapping a+// ruler to marks the ruler drew.+function sbeMusicSnaps(clips) {+ const out = [0];+ for (const c of clips || []) {+ out.push(sbeRound(sbeNum(c.film_start)));+ out.push(sbeRound(sbeNum(c.film_end)));+ }+ return out;+}++function sbeSnapToList(t, marks, tol, enabled) {+ if (!enabled) return sbeRound(t);+ let best = null, dist = Infinity;+ for (const m of marks || []) {+ const d = Math.abs(m - t);+ if (d > tol || d >= dist - 1e-9) continue;+ dist = d; best = m;+ }+ return best === null ? sbeRound(t) : sbeRound(best);+}++// THE CLIP'S OWN SOUND, and the mirror of `clip_audio()` on the server.+// ABSENT MEANS LINKED — the field appears only once somebody has pulled the+// picture and the sound apart, so every clip on every disk is already valid.+function sbeClipAudio(c) {+ const vs = sbeNum((c || {}).start), ve = sbeNum((c || {}).end);+ const fs = sbeNum((c || {}).film_start);+ const a = (c || {}).audio;+ if (!a || typeof a !== 'object' || sbeKind(c) !== 'video') {+ return { start: vs, end: ve, film_start: fs, linked: true,+ coupled: false, split: false, len: Math.max(0, ve - vs) };+ }+ // THE PRESENCE OF THE FIELD IS THE SWITCH, not the values in it. Unlinking+ // writes the window the clip already has, so an equality test read a+ // just-unlinked clip as linked and refused to drag it.+ //+ // ...AND `audio.linked` IS THE THIRD STATE: split, but travelling with its+ // picture at the offset the user chose. `linked` still means "this strip+ // cannot be dragged on its own", which is true of both; `split` means "the+ // sound is described separately", which is what the assembler needs.+ const s2 = sbeNum(a.start, vs), e2 = sbeNum(a.end, ve);+ const f2 = sbeNum(a.film_start, fs);+ const coupled = a.linked === true;+ return { start: sbeRound(s2), end: sbeRound(e2), film_start: sbeRound(f2),+ linked: coupled, coupled: coupled, split: true,+ len: Math.max(0, sbeRound(e2 - s2)) };+}++// Rebuild the stored object from a window, keeping the coupling flag out of+// the document unless it is true — a free strip must be byte-identical to the+// one every edit.json on disk already carries.+function sbeAudioField(w, coupled) {+ const o = { start: sbeRound(w.start), end: sbeRound(w.end),+ film_start: Math.max(0, sbeRound(w.film_start)) };+ if (coupled) o.linked = true;+ return o;+}++// UNLINKING IS NOT AN EDIT TO THE SOUND. It writes the window the clip+// already had, which is what makes the toggle safe to press: nothing moves+// until you move it.+//+// AND NEITHER IS RE-LINKING, ANY MORE. It used to DELETE the field, which+// snapped the sound back under the picture — so the moment the owner had+// built the J-cut he wanted, the one button that said "link" threw it away,+// and he reached for LOCK instead (which makes a clip refuse every drag with+// a forbidden cursor, and looked like the editor had broken). Re-linking now+// FREEZES the relationship: the window stays exactly where he put it and the+// pair travels as one from then on. "You just drag it, and the sound below+// stays, and then you can lock it and move it, and then the sound starts+// before the clip starts."+//+// An IN-SYNC re-link still deletes the field outright, so a split somebody+// tried and undid leaves a document identical to one that never had it.+function sbeSetAudioLink(clips, id, linked) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (sbeKind(c) !== 'video') {+ return { clips: clips, ok: false, why: 'only a video clip has sound of its own' };+ }+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ const w = sbeClipAudio(c);+ if (linked) {+ if (sbeAudioIsThePicture(c)) delete t.audio;+ else t.audio = sbeAudioField(w, true);+ } else {+ t.audio = sbeAudioField(w, false);+ }+ t.source = 'human';+ return { clips: out, ok: true, coupled: linked && !!t.audio };+}++// One gesture on one clip's sound. `mode` is 'move' | 'trimL' | 'trimR', and+// none of them touches the picture — that is the entire point of the feature.+// A LINKED clip refuses: a strip that moved without being unlinked would be+// the accident the default exists to prevent.+function sbeAudioEdit(clips, id, mode, want) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ const w = sbeClipAudio(c);+ if (w.coupled) {+ return { clips: clips, ok: false,+ why: 'this sound travels with its picture at the offset you set — unlink it to move it on its own' };+ }+ if (w.linked) return { clips: clips, ok: false, why: 'unlink the sound first' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const src = sbeNum(c.duration, 0);+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ let start = w.start, end = w.end, film = w.film_start;+ const t0 = Math.max(0, sbeNum(want));+ if (mode === 'move') {+ film = sbeRound(t0);+ } else if (mode === 'trimL') {+ // The left edge picks a new IN-POINT and leaves the rest where it is —+ // the same rule the music's head trim follows, and the reason an L-cut+ // does not drag the next line early with it.+ //+ // THE CLAMP IS FOLDED BACK INTO BOTH FIELDS OR IT IS NOT A CLAMP. `start`+ // used to stop at the head of the source while `film` kept sliding, so+ // asking for more head than the take has moved the strip's OUT-point+ // left — the one thing a left-edge trim must never do. That is the L-cut+ // case exactly: you pull his line back under the previous shot and the+ // tail silently loses the same seconds off the end of the line you were+ // keeping.+ const room = Math.min(t0, sbeRound(film + (end - start) - SBE_MIN_CLIP));+ let delta = sbeRound(room - film);+ if (start + delta < 0) delta = sbeRound(-start);+ start = sbeRound(start + delta);+ film = sbeRound(film + delta);+ } else {+ let e = sbeRound(start + Math.max(SBE_MIN_CLIP, t0 - film));+ if (src > 0) e = Math.min(e, sbeRound(src));+ end = Math.max(sbeRound(start + SBE_MIN_CLIP), e);+ }+ t.audio = { start: sbeRound(start), end: sbeRound(end),+ film_start: Math.max(0, sbeRound(film)) };+ t.source = 'human';+ return { clips: out, ok: true };+}++// ---- the pair, and how far it has come apart -------------------------------+// THE MIRROR OF `clip_audio_drift()`. Both halves map film time to source time+// with one constant each — the picture's `film_start - start`, the strip's+// `audio.film_start - audio.start` — so the difference between the two is the+// number an NLE prints on its sync flag. POSITIVE means the sound plays LATE+// against the frame it was recorded with. A linked clip cannot drift.+function sbeAudioDrift(c) {+ const w = sbeClipAudio(c);+ if (!w.split) return 0;+ return sbeRound((w.film_start - w.start)+ - (sbeNum((c || {}).film_start) - sbeNum((c || {}).start)));+}++function sbeAudioInSync(c) { return Math.abs(sbeAudioDrift(c)) <= SBE_SYNC_TOL; }++// IN SYNC IS NOT THE SAME AS "NOTHING TO SAY". A head trim moves the picture's+// in-point and its slot together, so the strip is left reaching a second back+// under the shot before it — the J-cut he described, "you start hearing the+// character before you see it" — and its DRIFT is zero, because the same+// source second still plays at the same film second. Only a strip that is+// literally the picture's own window can be dropped; deciding on drift alone+// deleted the field and took that extra second of sound with it.+// THE CLIP'S OWN SOUND, SWITCHED OFF. The mirror of `clip_muted()`.+// "We should have an option to mute the clip sound." An H3 shot arrives with+// baked-in wind and ambience under the line, and on a music cut that is not a+// performance to be balanced — it is noise to be removed so the track can+// carry the moment.+//+// NOT `has_audio === false`, which says the FILE has no audio track and is a+// fact about the source. This is a decision about the edit, and the two are+// painted differently for that reason. It composes with unlinking in both+// directions: `mute` describes the sound wherever its strip happens to be.+function sbeClipMuted(c) {+ return !!(c && c.mute === true) && sbeKind(c) === 'video';+}++// ABSENT IS AUDIBLE, the same rule `adjust` and `audio` follow: an unmuted+// clip is byte-identical to one written before mute existed.+function sbeSetClipMute(clips, id, on) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (sbeKind(c) !== 'video') {+ return { clips: clips, ok: false, why: 'only a video clip has sound to mute' };+ }+ if (c.has_audio === false) {+ return { clips: clips, ok: false,+ why: 'this clip has no sound of its own to mute' };+ }+ if (!!c.mute === !!on) return { clips: clips, ok: false, why: 'no change' };+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ if (on) t.mute = true; else delete t.mute;+ t.source = 'human';+ return { clips: out, ok: true };+}++function sbeAudioIsThePicture(c) {+ const w = sbeClipAudio(c);+ if (!w.split) return true;+ return Math.abs(w.start - sbeNum((c || {}).start)) < 1e-9+ && Math.abs(w.end - sbeNum((c || {}).end)) < 1e-9+ && Math.abs(w.film_start - sbeNum((c || {}).film_start)) < 1e-9;+}++function sbeDriftLabel(d) {+ const v = sbeNum(d);+ return (v > 0 ? '+' : '-') + Math.abs(v).toFixed(2) + 's';+}++// ---- carrying the sound through a RIPPLE ----------------------------------+// THE BUG THIS EXISTS FOR. `audio.film_start` is an absolute film anchor, and+// `sbeLayout` re-derives the film position of every clip from the running+// total of the lead gaps — the PICTURE's position and nothing else. So a right+// trim, a move, a ripple delete, an insert or a reorder slid every clip after+// it while every unlinked strip stood still, and a J-cut the user had placed+// three shots earlier silently came apart:+//+// "instead of allowing me to remove or move what video is visible while+// leaving the sound intact and then rematching it, it is actually getting+// the audio out of sync."+//+// A ripple is a RIGID TRANSLATION of everything downstream, so the sound rides+// with it — that is what keeps a pair in sync through an edit made somewhere+// else. The clip the gesture is actually ON is exempt: moving a picture off+// its own sound is the whole point of the feature, and `sbeAudioEdit` is the+// only other thing allowed to write the strip's position.+// WHAT IS RECORDED IS THE ANCHOR, not the film position: `film_start - start`+// is the film second at which this take's source zero would play, and it is+// the only number a sound has to follow. A ripple changes it by the whole+// translation; a head trim moves the slot and the in-point together and does+// not change it at all, which is exactly why a trim must leave the strip+// alone while a ripple must not.+function sbeSyncMark(clips) {+ const m = {};+ for (const c of clips || []) {+ if (!c || c.id === undefined || c.id === null) continue;+ if (sbeClipAudio(c).split) {+ m[c.id] = sbeRound(sbeNum(c.film_start) - sbeNum(c.start));+ }+ }+ return m;+}++function sbeSyncCarry(clips, mark, exempt) {+ const skip = {};+ for (const id of (exempt || [])) skip[String(id)] = true;+ for (const c of clips || []) {+ if (!c) continue;+ const a = c.audio;+ if (!a || typeof a !== 'object') continue;+ // THE EXEMPTION IS FOR A FREE STRIP ONLY. A COUPLED pair travels with its+ // picture by definition — that is what the user froze when he re-linked+ // it — so the gesture that moves the picture moves it too, including the+ // deliberate drag the free strip is exempt from.+ if (a.linked !== true && skip[String(c.id)]) continue;+ const was = mark ? mark[c.id] : undefined;+ if (was === undefined) continue;+ const d = sbeRound((sbeNum(c.film_start) - sbeNum(c.start)) - was);+ if (Math.abs(d) < 1e-9) continue;+ c.audio = sbeAudioField(+ { start: sbeNum(a.start), end: sbeNum(a.end),+ film_start: sbeNum(a.film_start) + d }, a.linked === true);+ }+ return clips;+}++// THE REMATCH the owner asked for by name. One click puts the sound back under+// the frame it came from: the strip keeps its own in-point — re-matching is not+// un-trimming, an L-cut's tail stays as long as it was made — and moves to the+// film second where that source second now plays.+function sbeResyncAudio(clips, id) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ const w = sbeClipAudio(c);+ if (!w.split) {+ return { clips: clips, ok: false,+ why: 'this clip\'s sound is already under its own picture' };+ }+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const want = sbeRound(sbeNum(c.film_start) + (w.start - sbeNum(c.start)));+ if (want < 0) {+ return { clips: clips, ok: false,+ why: 'the sound would have to start before the __SEQ__ does — move the picture later first' };+ }+ if (Math.abs(want - w.film_start) < 1e-9) {+ return { clips: clips, ok: false, why: 'that sound is already in sync' };+ }+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ // A COUPLED pair rematched is a pair with nothing left to say, so the field+ // goes rather than persisting as a coupling at zero offset.+ t.audio = sbeAudioField({ start: w.start, end: w.end, film_start: want },+ w.coupled);+ // A COUPLED pair rematched onto its own window is exactly a plain linked+ // clip, so the field goes. A FREE strip keeps its field even when the+ // numbers now match the picture: the user unlinked it on purpose and+ // stripping it here would silently re-link a strip he still means to drag —+ // the same rule `normalise_edit` follows on the way to disk.+ if (w.coupled && sbeAudioIsThePicture(t)) delete t.audio;+ t.source = 'human';+ return { clips: out, ok: true };+}++// ---- THE STRIP PLAYER'S MODEL -------------------------------------------+// THE PREVIEW MUST PLAY WHAT THE DOCUMENT SAYS. Until now it could not: the+// transport plays ONE <video> at a time and enters each clip at its picture+// boundary, so a clip's sound always landed with its picture no matter where+// its strip sat. The whole J/L-cut feature was inaudible — correct on disk,+// correct in the render's concat lanes, correct in the NLE export, and+// missing from the one place the user checks his work:+//+// "I wanted it a little before her showing up, and I cut it that way. But+// no matter what I do, this is always out."+//+// WHO OWNS A CLIP'S SOUND. Exactly one of the two, never both, or the same+// seconds play twice. The picture element keeps it when the strip IS the+// picture — that is every ordinary clip, and it costs nothing. The moment a+// strip exists in its own right, the player takes it.+// ---- THE EFFECTS MODEL, client side -------------------------------------+// The mirror of `clip_effects()`. ONE ACCESSOR, whatever the storage: `fx` is+// the home for effects, and brightness stays where history put it because a+// label is not worth a data migration. See docs/EDITOR_EFFECTS_MODEL.md.+function sbeClipLen(c) {+ const n = sbeNum((c || {}).film_end) - sbeNum((c || {}).film_start);+ return Math.max(0, n > 0 ? n : (sbeNum((c || {}).end) - sbeNum((c || {}).start)));+}++function sbeFx(c) {+ const fx = ((c || {}).fx && typeof c.fx === 'object') ? c.fx : {};+ const n = sbeClipLen(c);+ let fin = Math.max(0, sbeNum(fx.fade_in));+ let fout = Math.max(0, sbeNum(fx.fade_out));+ if (n > 0) {+ fin = Math.min(fin, n); fout = Math.min(fout, n);+ // THE SAME CLAMP THE SERVER APPLIES, and it is here for the same reason:+ // two fades that crossed would ask for an opacity that is two things at+ // once. Proportional, because "two long fades" means mostly-ramp and+ // zeroing one of them is not that.+ const over = fin + fout - n;+ if (over > 0) {+ const total = fin + fout;+ fin -= over * (fin / total); fout -= over * (fout / total);+ }+ }+ return { fade_in: sbeRound(fin), fade_out: sbeRound(fout),+ brightness: sbeBright(c) };+}++// THE OPACITY AT A FILM SECOND, and the preview's whole honesty about fades:+// a value per frame rather than a CSS transition, so scrubbing shows what is+// true at that second instead of an animation that started when you arrived.+function sbeFadeOpacityAt(c, t) {+ const e = sbeFx(c);+ if (e.fade_in <= 1e-9 && e.fade_out <= 1e-9) return 1;+ const fs = sbeNum((c || {}).film_start), fe = sbeNum((c || {}).film_end);+ const now = sbeNum(t);+ let o = 1;+ if (e.fade_in > 1e-9 && now < fs + e.fade_in) {+ o = Math.min(o, Math.max(0, (now - fs) / e.fade_in));+ }+ if (e.fade_out > 1e-9 && now > fe - e.fade_out) {+ o = Math.min(o, Math.max(0, (fe - now) / e.fade_out));+ }+ return Math.max(0, Math.min(1, sbeRound(o)));+}++// One fade, set in seconds. Clamped by `sbeFx` on the way back out, so the UI+// can hand this a drag distance without doing the arithmetic itself.+function sbeSetFade(clips, id, edge, seconds) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const key = (edge === 'out') ? 'fade_out' : 'fade_in';+ const want = Math.max(0, Math.min(sbeClipLen(c), sbeNum(seconds)));+ const now = sbeFx(c);+ if (Math.abs(now[key] - want) < 1e-6 && !(want === 0 && c.fx && c.fx[key])) {+ return { clips: clips, ok: false, why: 'no change' };+ }+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ const fx = Object.assign({}, t.fx || {});+ if (want > 1e-9) fx[key] = sbeRound(want); else delete fx[key];+ // NEUTRAL IS ABSENT: a clip whose fades are both zero carries no `fx` at+ // all, so it is byte-identical to one from before effects existed.+ if (fx.fade_in > 1e-9 || fx.fade_out > 1e-9) t.fx = fx; else delete t.fx;+ t.source = 'human';+ return { clips: out, ok: true };+}++// ---- PER-SOURCE WAVEFORMS -----------------------------------------------+// THE STRIP'S OWN SOURCE WINDOW, never the picture's. A strip trimmed to+// 1.2–3.4 draws those seconds of the take; a J-cut that slides its sound half+// a second earlier still draws the seconds it PLAYS, because the window is a+// fact about the sound and the film position is not.+function sbeWaveSlice(peaks, from, to, cols) {+ if (!peaks || !peaks.peaks || !peaks.count) return [];+ const bps = sbeNum(peaks.buckets_per_second, 100) || 100;+ const scale = sbeNum(peaks.scale, 127) || 127;+ const n = Math.max(1, Math.floor(sbeNum(cols)));+ const b0 = Math.max(0, Math.floor(sbeNum(from) * bps));+ const b1 = Math.min(sbeNum(peaks.count), Math.ceil(sbeNum(to) * bps));+ const span = Math.max(1, b1 - b0);+ const out = [];+ for (let i = 0; i < n; i++) {+ // One column may cover many buckets when the strip is zoomed out; take+ // the extremes across them, or a quiet frame in the middle of a loud+ // second draws a hole that is not there.+ const s0 = b0 + Math.floor((i / n) * span);+ const s1 = Math.max(s0 + 1, b0 + Math.floor(((i + 1) / n) * span));+ let lo = 0, hi = 0;+ for (let b = s0; b < s1 && b < b1; b++) {+ const mn = peaks.peaks[b * 2], mx = peaks.peaks[b * 2 + 1];+ if (mn < lo) lo = mn;+ if (mx > hi) hi = mx;+ }+ out.push([lo / scale, hi / scale]);+ }+ return out;+}++// Lazily, once per source, and never twice for the same take.+function sbeWaveWant(path) {+ const key = String(path || '');+ if (!key || !SBE.open) return null;+ if (!SBE.clipPeaks) SBE.clipPeaks = {};+ if (Object.prototype.hasOwnProperty.call(SBE.clipPeaks, key)) {+ return SBE.clipPeaks[key];+ }+ SBE.clipPeaks[key] = null; // in flight: ask once+ fetch('/storyboard/edit/clip-peaks?id=' + encodeURIComponent(SBE.id)+ + '&path=' + encodeURIComponent(key))+ .then(r => r.json())+ .then(d => {+ // A take with no audio is a FACT, and `false` is how the lane+ // remembers it so it never asks again.+ SBE.clipPeaks[key] = (d && d.peaks) ? d : false;+ sbePaintAudioLane();+ })+ .catch(() => { SBE.clipPeaks[key] = false; });+ return null;+}++// ---- THE SOUND'S OWN ENVELOPE -------------------------------------------+// The mirror of `audio_gain_points()`. ONE CURVE, fades and keyframes folded+// together, read by the preview exactly as the render and the export read the+// server's copy — so the simple case never has to discover keyframes and a+// keyframed envelope never has to be re-expressed. `t` is STRIP-RELATIVE, so+// sliding a J-cut does not drag every point with it.+function sbeAfx(item, len) {+ const a = ((item || {}).afx && typeof item.afx === 'object') ? item.afx : {};+ const n = Math.max(0, sbeNum(len));+ let fin = Math.max(0, sbeNum(a.fade_in));+ let fout = Math.max(0, sbeNum(a.fade_out));+ if (n > 0) {+ fin = Math.min(fin, n); fout = Math.min(fout, n);+ const over = fin + fout - n;+ if (over > 0) {+ const total = fin + fout;+ fin -= over * (fin / total); fout -= over * (fout / total);+ }+ }+ const pts = [];+ for (const row of (a.points || [])) {+ if (!row || row.length !== 2) continue;+ let t = sbeNum(row[0]);+ if (n > 0) t = Math.max(0, Math.min(n, t));+ pts.push([sbeRound(t), sbeRound(Math.max(0, Math.min(1, sbeNum(row[1]))))]);+ }+ pts.sort((x, y) => x[0] - y[0]);+ return { fade_in: sbeRound(fin), fade_out: sbeRound(fout), points: pts };+}++function sbeLerpGain(pts, t) {+ if (!pts || !pts.length) return 1;+ if (t <= pts[0][0]) return pts[0][1];+ if (t >= pts[pts.length - 1][0]) return pts[pts.length - 1][1];+ for (let i = 0; i < pts.length - 1; i++) {+ const a = pts[i], b = pts[i + 1];+ if (t >= a[0] && t <= b[0]) {+ if (b[0] - a[0] <= 1e-9) return b[1];+ return a[1] + (b[1] - a[1]) * ((t - a[0]) / (b[0] - a[0]));+ }+ }+ return pts[pts.length - 1][1];+}++function sbeGainPoints(item, len) {+ const n = Math.max(0, sbeNum(len));+ if (n <= 0) return [];+ const e = sbeAfx(item, n);+ const marks = { 0: true };+ marks[n] = true;+ for (const p of e.points) marks[Math.min(n, Math.max(0, p[0]))] = true;+ if (e.fade_in > 1e-9) marks[e.fade_in] = true;+ if (e.fade_out > 1e-9) marks[Math.max(0, n - e.fade_out)] = true;+ const out = [];+ for (const k of Object.keys(marks).map(Number).sort((a, b) => a - b)) {+ let g = sbeLerpGain(e.points, k);+ if (e.fade_in > 1e-9 && k < e.fade_in) g *= k / e.fade_in;+ if (e.fade_out > 1e-9 && k > n - e.fade_out) {+ g *= Math.max(0, (n - k) / e.fade_out);+ }+ out.push([sbeRound(k), sbeRound(Math.max(0, Math.min(1, g)))]);+ }+ // A FLAT UNITY CURVE IS NO CURVE, the same rule the server follows.+ return out.every(p => Math.abs(p[1] - 1) < 1e-9) ? [] : out;+}++function sbeGainAt(item, len, t) {+ const curve = sbeGainPoints(item, len);+ if (!curve.length) return 1;+ return sbeRound(sbeLerpGain(curve, Math.max(0, sbeNum(t))));+}++// ---- THE MIX: the bed's level, and what happens to it under a line -------+// The browser half of `storyboard_editor.audio_mix` and everything under it.+// Every function here is a mirror of a Python one of the same shape, and that+// is the entire point of the feature: the render used to hold the bed at a+// hard-coded 0.20 and duck it through a compressor keyed on the dialogue,+// while the preview applied neither — so the one surface the user checks his+// work on played a mix the file never had. A gain that only one of the three+// outputs can express is not in the model.+//+// KEEP THESE EQUAL TO THE SERVER'S. A drifted constant here is a preview that+// plays a different film from the render, quietly, which is the exact defect+// this block exists to close. `test_the_client_and_the_server_agree_about_the+// _mix_constants` reads both out and refuses a difference.+const SBE_MIX_BED_GAIN = 1.0;+const SBE_MIX_DUCK = false;+const SBE_MIX_DUCK_GAIN = 0.269; // the measured 11.4 dB, in linear+const SBE_MIX_DUCK_ATTACK = 0.005;+const SBE_MIX_DUCK_RELEASE = 0.4;++function sbeAudioMix(audio) {+ const a = audio || {};+ const m = (a.mix && typeof a.mix === 'object') ? a.mix : {};+ const g = (m.bed_gain === null || m.bed_gain === undefined)+ ? SBE_MIX_BED_GAIN : Math.max(0, Math.min(1, sbeNum(m.bed_gain)));+ const d = (m.duck === null || m.duck === undefined) ? SBE_MIX_DUCK : !!m.duck;+ return { bed_gain: sbeRound(g), duck: d };+}++// THE BED'S ENVELOPE IS ON THE PLAYED WINDOW, not on the track — zero is the+// first second you hear, exactly as a clip strip's envelope is on the strip+// and not on the source file. That is what makes the corner handles mean the+// corner they were dragged onto after the music has been trimmed or moved.+//+// THE DOCUMENT ONLY, AND THEN THE FILM. `filmLen` is `sbeFilmDuration(clips)`+// and the peaks probe is deliberately NOT in this chain, which is the second+// half of the fix the film-clock fallback belongs to. The renderer cannot see+// peaks.json — it reads edit.json — so a bed length taken from the probe is a+// number only one of the two sides can compute, and a gain only one side can+// compute is exactly the invisible-second-author defect this whole block+// exists to remove. `storyboard_editor.bed_length(audio, film_len)` is this+// function, term for term, and `test_editor_mix` runs the two side by side+// over a TABLE of documents so a divergence turns a suite red instead of+// turning the preview into a liar.+function sbeBedLen(audio, filmLen) {+ const a = audio || {};+ const w = sbeMusicWindow(a, 0); // 0 => the document's own duration+ if (w.film_end === null) {+ // No stated length. The bed plays under the FILM — what remains of it+ // after the block starts — because that is where the render stops the mix+ // anyway. Returning 0 here is what used to empty the curve, and an empty+ // curve means NO FILTER, which is the bed at full level over the dialogue.+ return Math.max(0, sbeRound(Math.max(0, sbeNum(filmLen)) - w.film_start));+ }+ return Math.max(0, sbeRound(w.film_end - w.film_start));+}++// The film seconds where a clip's OWN sound plays. What the duck is keyed on,+// and the reason it can be a document value at all: a compressor asks "are+// these samples loud", this asks "is there a sound strip here" — a question+// the document answers and the browser can answer identically.+function sbeAudibleStrips(clips) {+ const wins = [];+ for (const c of (clips || [])) {+ if (sbeKind(c) !== 'video') continue;+ if (c.has_audio === false || sbeClipMuted(c)) continue;+ const w = sbeClipAudio(c);+ if (w.len > 1e-9) wins.push([sbeRound(w.film_start), sbeRound(w.film_start + w.len)]);+ }+ wins.sort((a, b) => a[0] - b[0] || a[1] - b[1]);+ const out = [];+ for (const [s, e] of wins) {+ // Merged when they sit closer than one release: a bed that recovered+ // fully in the eighth of a second between two lines would pump, and+ // merging is also what keeps every knot of the curve below on a mark.+ if (out.length && s - out[out.length - 1][1] < SBE_MIX_DUCK_RELEASE - 1e-9) {+ out[out.length - 1][1] = Math.max(out[out.length - 1][1], e);+ } else out.push([s, e]);+ }+ return out;+}++function sbeDuckGainAt(wins, t) {+ let g = 1;+ for (const [s, e] of wins) {+ if (t < s - 1e-9) continue;+ let v;+ if (t <= e + 1e-9) {+ const k = SBE_MIX_DUCK_ATTACK <= 0 ? 1+ : Math.min(1, (t - s) / SBE_MIX_DUCK_ATTACK);+ v = 1 - (1 - SBE_MIX_DUCK_GAIN) * Math.max(0, k);+ } else {+ const k = SBE_MIX_DUCK_RELEASE <= 0 ? 1 : (t - e) / SBE_MIX_DUCK_RELEASE;+ if (k >= 1) continue;+ v = SBE_MIX_DUCK_GAIN + (1 - SBE_MIX_DUCK_GAIN) * k;+ }+ g = Math.min(g, v);+ }+ return Math.max(0, Math.min(1, g));+}++function sbeBedDuckPoints(clips, len, delay) {+ const n = Math.max(0, sbeNum(len));+ if (n <= 0) return [];+ const d = sbeNum(delay);+ const wins = sbeAudibleStrips(clips)+ .map(([s, e]) => [s - d, e - d]).filter(([s, e]) => e > 0 && s < n);+ if (!wins.length) return [];+ const marks = new Set([0, sbeRound(n)]);+ for (const [s, e] of wins) {+ for (const m of [s, s + SBE_MIX_DUCK_ATTACK, e, e + SBE_MIX_DUCK_RELEASE]) {+ if (m >= -1e-9 && m <= n + 1e-9) marks.add(sbeRound(Math.max(0, Math.min(n, m))));+ }+ }+ const out = Array.from(marks).sort((a, b) => a - b)+ .map(t => [t, sbeRound(sbeDuckGainAt(wins, t))]);+ return out.every(p => Math.abs(p[1] - 1) < 1e-9) ? [] : out;+}++// THE PRECEDENCE, ASKED ONCE. A person who has drawn the bed's level has said+// what the bed does; an automatic curve that then moved it would be the+// renderer disagreeing with them again — the invisible second author, one+// layer up. So the authored envelope WINS and the duck stands down, and the+// track head says so rather than leaving two controls quietly fighting.+function sbeBedDuckSuppressed(audio, filmLen) {+ if (!sbeAudioMix(audio).duck) return false;+ return sbeGainPoints(audio || {}, sbeBedLen(audio, filmLen)).length > 0;+}++// THE ONE BED CURVE. Preview, render and export read this and nothing else.+// Three terms: the static fader (always), the authored envelope (always, when+// it exists), the auto-duck (only when nothing was authored). Never two+// curves at once.+function sbeBedGainPoints(audio, clips, filmLen) {+ const a = audio || {};+ if (!a.path) return [];+ const n = sbeBedLen(a, filmLen);+ if (n <= 0) return [];+ const mix = sbeAudioMix(a);+ let curve = sbeGainPoints(a, n);+ if (!curve.length && mix.duck) {+ curve = sbeBedDuckPoints(clips, n, sbeMusicWindow(a, 0).film_start);+ }+ const g0 = mix.bed_gain;+ if (!curve.length) {+ if (Math.abs(g0 - 1) < 1e-9) return [];+ return [[0, sbeRound(g0)], [sbeRound(n), sbeRound(g0)]];+ }+ return curve.map(p => [p[0], sbeRound(Math.max(0, Math.min(1, p[1] * g0)))]);+}++function sbeBedGainAt(audio, clips, filmLen, t) {+ const curve = sbeBedGainPoints(audio, clips, filmLen);+ if (!curve.length) return 1;+ return sbeRound(sbeLerpGain(curve, Math.max(0, sbeNum(t))));+}++// ---- writing the mix back ----------------------------------------------+// Same shape as `sbeAfxWrite`: a new object out, neutral fields deleted, so a+// bed nobody has mixed is byte-identical to one from before the mix existed.+function sbeMixWrite(audio, patch) {+ const a = Object.assign({}, audio || {});+ const mix = Object.assign({}, sbeAudioMix(a), patch || {});+ const out = {};+ if (Math.abs(mix.bed_gain - SBE_MIX_BED_GAIN) > 1e-9) out.bed_gain = sbeRound(mix.bed_gain);+ if (!!mix.duck !== SBE_MIX_DUCK) out.duck = !!mix.duck;+ if (Object.keys(out).length) a.mix = out; else delete a.mix;+ return a;+}++function sbeBedAfxWrite(audio, afx) {+ const a = Object.assign({}, audio || {});+ const has = afx && (afx.fade_in > 1e-9 || afx.fade_out > 1e-9+ || (afx.points && afx.points.length));+ if (has) a.afx = afx; else delete a.afx;+ return a;+}++function sbeSetBedFade(audio, edge, seconds, filmLen) {+ const n = Math.max(0, sbeBedLen(audio, filmLen));+ const key = (edge === 'out') ? 'fade_out' : 'fade_in';+ const afx = Object.assign({}, (audio || {}).afx || {});+ const want = Math.max(0, Math.min(n, sbeNum(seconds)));+ if (want > 1e-9) afx[key] = sbeRound(want); else delete afx[key];+ return sbeBedAfxWrite(audio, afx);+}++function sbeBedPointsWrite(audio, pts, filmLen) {+ const n = Math.max(0, sbeBedLen(audio, filmLen));+ const afx = Object.assign({}, (audio || {}).afx || {});+ const kept = (pts || []).slice().sort((x, y) => x[0] - y[0])+ .map(pr => [sbeRound(Math.max(0, Math.min(n, pr[0]))),+ sbeRound(Math.max(0, Math.min(1, pr[1])))]);+ if (kept.length) afx.points = kept; else delete afx.points;+ return sbeBedAfxWrite(audio, afx);+}++function sbeBedAddKeyframe(audio, t, gain, filmLen) {+ const n = Math.max(0, sbeBedLen(audio, filmLen));+ const at = Math.max(0, Math.min(n, sbeNum(t)));+ const pts = sbeAfx(audio || {}, n).points.slice();+ // A SECOND POINT ON THE SAME SECOND IS NOT A POINT — the same rule the+ // strips follow, and for the same reason: the envelope cannot express a+ // discontinuity and the NLEs would import the keyframes out of order.+ for (const pr of pts) if (Math.abs(pr[0] - at) < 1e-3) return null;+ pts.push([at, Math.max(0, Math.min(1, sbeNum(gain, 1)))]);+ return sbeBedPointsWrite(audio, pts, filmLen);+}++function sbeBedMoveKeyframe(audio, index, t, gain, filmLen) {+ const n = Math.max(0, sbeBedLen(audio, filmLen));+ const pts = sbeAfx(audio || {}, n).points.slice();+ if (!pts.length) return null;+ const i = Math.max(0, Math.min(pts.length - 1, sbeNum(index)));+ pts[i] = [Math.max(0, Math.min(n, sbeNum(t))),+ Math.max(0, Math.min(1, sbeNum(gain)))];+ return sbeBedPointsWrite(audio, pts, filmLen);+}++function sbeBedDeleteKeyframe(audio, index, filmLen) {+ const n = Math.max(0, sbeBedLen(audio, filmLen));+ const pts = sbeAfx(audio || {}, n).points.slice();+ const i = sbeNum(index);+ if (i < 0 || i >= pts.length) return null;+ pts.splice(i, 1);+ return sbeBedPointsWrite(audio, pts, filmLen);+}++// ---- KEYFRAMES: the control case ---------------------------------------+// Points are STRIP-RELATIVE seconds and a linear 0..1 gain, exactly as the+// server stores them. Adding, dragging and deleting are three ops on one+// list, and all three go through `sbeAfx` on the way out so what the UI holds+// is always what the three outputs will read.+function sbeAfxWrite(clips, id, pts) {+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ const afx = Object.assign({}, t.afx || {});+ const kept = (pts || []).slice().sort((a, b) => a[0] - b[0])+ .map(pr => [sbeRound(pr[0]), sbeRound(Math.max(0, Math.min(1, pr[1])))]);+ if (kept.length) afx.points = kept; else delete afx.points;+ const has = afx.fade_in > 1e-9 || afx.fade_out > 1e-9+ || (afx.points && afx.points.length);+ if (has) t.afx = afx; else delete t.afx;+ t.source = 'human';+ return { clips: out, ok: true };+}++function sbeAddKeyframe(clips, id, t, gain) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const w = sbeClipAudio(c);+ const at = Math.max(0, Math.min(w.len, sbeNum(t)));+ const pts = sbeAfx(c, w.len).points.slice();+ // A SECOND POINT ON THE SAME SECOND IS NOT A POINT, it is a discontinuity+ // the envelope cannot express and the NLEs would import out of order.+ for (const pr of pts) {+ if (Math.abs(pr[0] - at) < 1e-3) {+ return { clips: clips, ok: false, why: 'there is already a point here' };+ }+ }+ pts.push([at, Math.max(0, Math.min(1, sbeNum(gain, 1)))]);+ return sbeAfxWrite(clips, id, pts);+}++function sbeMoveKeyframe(clips, id, index, t, gain) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const w = sbeClipAudio(c);+ const pts = sbeAfx(c, w.len).points.slice();+ const i = Math.max(0, Math.min(pts.length - 1, sbeNum(index)));+ if (!pts.length) return { clips: clips, ok: false, why: 'gone' };+ pts[i] = [Math.max(0, Math.min(w.len, sbeNum(t))),+ Math.max(0, Math.min(1, sbeNum(gain)))];+ return sbeAfxWrite(clips, id, pts);+}++function sbeDeleteKeyframe(clips, id, index) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const w = sbeClipAudio(c);+ const pts = sbeAfx(c, w.len).points.slice();+ const i = sbeNum(index);+ if (i < 0 || i >= pts.length) return { clips: clips, ok: false, why: 'gone' };+ pts.splice(i, 1);+ return sbeAfxWrite(clips, id, pts);+}++// AFTER UNLINK, BOTH HALVES ARE FIRST-CLASS. "You can unlock the clips, but+// you cannot unlock the clip and delete the upper part, nor delete the lower+// part of the sound."+//+// DELETING THE STRIP leaves the picture playing SILENT, and that state is+// exactly expressible today: drop the window and mute the clip. Absent+// `audio` alone would mean LINKED, which plays the clip's own sound again —+// the opposite of what was asked for — so the mute is what makes the silence+// real, in the preview, the render and the export alike.+//+// NOT A RIPPLE. Removing a sound must not move the picture it was under, nor+// anything after it: this is one clip's own field, and nothing reflows.+function sbeDeleteStrip(clips, id) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ if (sbeKind(c) !== 'video') {+ return { clips: clips, ok: false, why: 'only a video clip has sound' };+ }+ if (sbeClipMuted(c) && !sbeClipAudio(c).split) {+ return { clips: clips, ok: false, why: 'this clip is already silent' };+ }+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ delete t.audio;+ delete t.afx; // an envelope with nothing to shape+ t.mute = true;+ t.source = 'human';+ return { clips: out, ok: true };+}++// One audio fade, in seconds, on a clip's strip. Mirrors `sbeSetFade` so the+// muscle memory from the picture's corner handle transfers exactly.+function sbeSetAudioFade(clips, id, edge, seconds) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const w = sbeClipAudio(c);+ const len = Math.max(0, w.len);+ const key = (edge === 'out') ? 'fade_out' : 'fade_in';+ const want = Math.max(0, Math.min(len, sbeNum(seconds)));+ const out = clips.map(x => Object.assign({}, x));+ const t = sbeById(out, id);+ const afx = Object.assign({}, t.afx || {});+ if (want > 1e-9) afx[key] = sbeRound(want); else delete afx[key];+ const has = afx.fade_in > 1e-9 || afx.fade_out > 1e-9+ || (afx.points && afx.points.length);+ if (has) t.afx = afx; else delete t.afx;+ t.source = 'human';+ return { clips: out, ok: true };+}++// ---- THE OVERLAY LANE'S MODEL -------------------------------------------+// Overlays do NOT ripple. A card is placed where somebody wants it in the+// finished film, so moving one moves one, and trimming one changes only its+// own window — the picture underneath is not consulted and does not shift.+function sbeOvKind(o) {+ const k = String((o || {}).kind || '').toLowerCase();+ if (k === 'still' || k === 'video') return k;+ return /\.(png|webp|tiff?)$/i.test(String((o || {}).path || ''))+ ? 'still' : 'video';+}++function sbeOvAt(overlays, t) {+ const now = sbeNum(t);+ for (const o of overlays || []) {+ if (now >= sbeNum(o.film_start) - 1e-6 && now < sbeNum(o.film_end)) return o;+ }+ return null;+}++function sbeOvById(overlays, id) {+ for (const o of overlays || []) if (o.id === id) return o;+ return null;+}++// ONE LANE, so a move that would land on top of another card is refused+// rather than silently stacked — the same rule the picture lane lives by.+function sbeOvFits(overlays, id, fs, fe) {+ for (const o of overlays || []) {+ if (o.id === id) continue;+ if (fs < sbeNum(o.film_end) - 1e-6 && fe > sbeNum(o.film_start) + 1e-6) {+ return false;+ }+ }+ return true;+}++function sbeOvMove(overlays, id, filmStart) {+ const o = sbeOvById(overlays, id);+ if (!o) return { overlays: overlays, ok: false, why: 'gone' };+ if (o.locked) return { overlays: overlays, ok: false, why: 'locked' };+ const len = Math.max(SBE_MIN_CLIP, sbeNum(o.film_end) - sbeNum(o.film_start));+ const fs = Math.max(0, sbeNum(filmStart));+ if (!sbeOvFits(overlays, id, fs, fs + len)) {+ return { overlays: overlays, ok: false,+ why: 'another overlay is already there' };+ }+ const out = overlays.map(x => Object.assign({}, x));+ const t = sbeOvById(out, id);+ t.film_start = sbeRound(fs);+ t.film_end = sbeRound(fs + len);+ if (sbeOvKind(t) === 'still') { t.start = 0; t.end = sbeRound(len); }+ t.source = 'human';+ return { overlays: out, ok: true };+}++function sbeOvTrim(overlays, id, edge, filmTime) {+ const o = sbeOvById(overlays, id);+ if (!o) return { overlays: overlays, ok: false, why: 'gone' };+ if (o.locked) return { overlays: overlays, ok: false, why: 'locked' };+ let fs = sbeNum(o.film_start), fe = sbeNum(o.film_end);+ if (edge === 'l') fs = Math.min(fe - SBE_MIN_CLIP, Math.max(0, sbeNum(filmTime)));+ else fe = Math.max(fs + SBE_MIN_CLIP, sbeNum(filmTime));+ if (!sbeOvFits(overlays, id, fs, fe)) {+ return { overlays: overlays, ok: false, why: 'another overlay is there' };+ }+ const out = overlays.map(x => Object.assign({}, x));+ const t = sbeOvById(out, id);+ t.film_start = sbeRound(fs);+ t.film_end = sbeRound(fe);+ // A STILL IS ITS SLOT, the same synthesis a still clip gets — which is why+ // a card is resized by dragging its edges and nothing else.+ if (sbeOvKind(t) === 'still') { t.start = 0; t.end = sbeRound(fe - fs); }+ t.source = 'human';+ return { overlays: out, ok: true };+}++function sbeOvAdd(overlays, item, filmStart) {+ const dur = Math.max(SBE_MIN_CLIP, sbeNum(item.duration_s, 0) || 3);+ let fs = Math.max(0, sbeNum(filmStart));+ // Land somewhere free rather than refusing: the lane is one track, and a+ // card dropped onto another card means "after it".+ for (let i = 0; i < (overlays || []).length + 1; i++) {+ if (sbeOvFits(overlays, null, fs, fs + dur)) break;+ let push = fs;+ for (const o of overlays) {+ if (fs < sbeNum(o.film_end) - 1e-6 && fs + dur > sbeNum(o.film_start) + 1e-6) {+ push = Math.max(push, sbeNum(o.film_end));+ }+ }+ fs = push;+ }+ const o = {+ id: sbeNewId(), kind: /\.(png|webp|tiff?)$/i.test(String(item.path || ''))+ ? 'still' : 'video',+ path: item.path, title: item.title || '',+ start: 0, end: sbeRound(dur),+ film_start: sbeRound(fs), film_end: sbeRound(fs + dur),+ source: 'human', locked: false,+ };+ return { overlays: (overlays || []).concat([o]), ok: true, added: o };+}++function sbeOvDelete(overlays, id) {+ const o = sbeOvById(overlays, id);+ if (!o) return { overlays: overlays, ok: false, why: 'gone' };+ if (o.locked) return { overlays: overlays, ok: false, why: 'locked' };+ // NOT A RIPPLE. Removing a card must not move the picture under it, nor the+ // next card: the lane is a set of placements, not a queue.+ return { overlays: (overlays || []).filter(x => x.id !== id), ok: true };+}++function sbeStripOwned(c) {+ if (sbeKind(c) !== 'video') return false;+ if (sbeClipMuted(c)) return false; // muted plays from nowhere+ return !!sbeClipAudio(c).split;+}++function sbePictureCarriesSound(c) {+ return sbeKind(c) === 'video' && !sbeClipMuted(c) && !sbeClipAudio(c).split;+}++// EVERY STRIP AUDIBLE AT FILM SECOND `t`, and the SOURCE second each one is+// at. More than one is the normal case across a split edit — a J-cut is two+// sounds overlapping by construction — so this returns a list and the player+// gives each a voice of its own. The render's concat lane resolves the same+// overlap by trimming the outgoing tail; here they simply sum, which is what+// the person cutting needs to hear.+function sbeStripsAt(clips, t) {+ const now = sbeNum(t);+ const out = [];+ for (const c of clips || []) {+ if (!sbeStripOwned(c)) continue;+ const w = sbeClipAudio(c);+ const from = w.film_start, to = sbeRound(w.film_start + w.len);+ if (now < from - 1e-6 || now >= to) continue;+ out.push({ id: c.id, path: c.path || '',+ at: sbeRound(w.start + (now - from)),+ from: from, to: to });+ }+ out.sort((a, b) => (a.from - b.from) || String(a.id).localeCompare(String(b.id)));+ return out;+}++function sbeClipAt(clips, t) {+ for (const c of clips || []) {+ if (t >= sbeNum(c.film_start) && t < sbeNum(c.film_end)) return c;+ }+ return null;+}++// The holes, recomputed locally while dragging. The server reports the same+// list on every read (edit_gaps); this is the live copy so the track does not+// have to round-trip to draw a hole the user just opened.+// HALF A FRAME AT THIS SEQUENCE'S RATE, and it used to be the literal 1/48 —+// which is half a frame at 24 fps and the wrong number at any other. It is+// also why the header said "1 hole · 0.02s" over a film with three holes in+// it: two were under half a frame, so this list did not contain them and+// nothing else was counting. Sub-frame holes cannot exist any more (they are+// closed on load and unreachable by a drag), so what this threshold means now+// is "shorter than half a frame is float noise" — which is the only thing it+// can honestly mean once every hole is a whole number of frames.+function sbeHoles(clips, tolerance) {+ const tol = (tolerance === undefined) ? 0.5 / sbeFps() : tolerance;+ const spans = (clips || []).filter(c => sbeNum(c.film_end) > sbeNum(c.film_start))+ .map(c => [sbeNum(c.film_start), sbeNum(c.film_end)])+ .sort((a, b) => a[0] - b[0]);+ const out = [];+ let cursor = 0;+ for (const s of spans) {+ if (s[0] - cursor > tol) {+ out.push({ film_start: sbeRound(cursor), film_end: sbeRound(s[0]),+ duration: sbeRound(s[0] - cursor) });+ }+ cursor = Math.max(cursor, s[1]);+ }+ return out;+}++// THE BEAT GRID, AND THE PROMISE NOT TO EXTRAPOLATE IT.+//+// beat_map() fits ONE constant tempo across a SPAN, because real tracks drift+// and a grid fitted over eight minutes is wrong at both ends. Beats outside+// that span do not exist — asking for one gets "no beat here" from the server,+// and inventing one here would put a confident wrong line under someone's cut.+function sbeBeatGrid(beats, from, to, offset) {+ if (!beats) return [];+ const off = sbeNum(offset);+ const span = Array.isArray(beats.span) ? beats.span : null;+ const lo = span ? sbeNum(span[0]) : -Infinity;+ const hi = span ? sbeNum(span[1]) : Infinity;+ const downs = {};+ for (const d of (beats.downbeats || [])) downs[sbeRound(d)] = true;+ const out = [];+ for (const b of (beats.beats || [])) {+ const t = sbeNum(b);+ if (t < lo - 1e-6 || t > hi + 1e-6) continue; // never past the fit+ const film = sbeRound(t - off);+ if (film < from - 1e-6 || film > to + 1e-6) continue;+ out.push({ t: film, down: !!downs[sbeRound(t)] });+ }+ // A downbeat the beat list does not carry is still a downbeat.+ for (const d of (beats.downbeats || [])) {+ const t = sbeNum(d);+ if (t < lo - 1e-6 || t > hi + 1e-6) continue;+ const film = sbeRound(t - off);+ if (film < from - 1e-6 || film > to + 1e-6) continue;+ if (!out.some(x => Math.abs(x.t - film) < 1e-6)) out.push({ t: film, down: true });+ }+ out.sort((a, b) => a.t - b.t);+ return out;+}++function sbeGridIsAGuess(beats) {+ return !!beats && sbeNum(beats.confidence, 1) < SBE_GUESS_CONFIDENCE;+}++// Nearest beat within `tol` seconds, downbeats winning ties. `enabled` false+// (the checkbox off, or Alt held) returns t untouched — the override has to be+// a straight bypass or it is not an override.+function sbeSnapTime(t, beats, tol, enabled, offset) {+ if (!enabled || !beats) return sbeRound(t);+ const grid = sbeBeatGrid(beats, t - tol, t + tol, offset);+ if (!grid.length) return sbeRound(t);+ let best = null, dist = Infinity;+ for (const g of grid) {+ const d = Math.abs(g.t - t);+ if (d > tol) continue;+ if (d < dist - 1e-9 || (Math.abs(d - dist) < 1e-9 && g.down && (!best || !best.down))) {+ dist = d; best = g;+ }+ }+ return best ? sbeRound(best.t) : sbeRound(t);+}++// ---- the four edits -------------------------------------------------------+// Each takes the clip array and returns {clips, ok, why}. None of them touches+// a locked clip, and every one of them stamps source:'human' — a promise the+// server keeps in the other direction: a later re-plan can leave a human's cut+// alone precisely because it is labelled.+function sbeById(clips, id) {+ for (const c of clips || []) if (c.id === id) return c;+ return null;+}++function sbeMoveTo(clips, id, filmStart) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const len = sbeLen(c);+ const want = Math.max(0, sbeNum(filmStart));+ const centre = want + len / 2;+ const mark = sbeSyncMark(clips);+ const rest = clips.filter(x => x !== c);+ let idx = 0;+ for (const x of rest) {+ if (sbeNum(x.film_start) + sbeLen(x) / 2 < centre) idx++; else break;+ }+ rest.splice(idx, 0, c);+ c._gap = 0;+ sbeLayout(rest); // where would it land packed tight?+ const prev = rest[rest.indexOf(c) - 1];+ const floor = prev ? sbeNum(prev.film_end) : 0;+ c._gap = Math.max(0, sbeRound(want - floor));+ sbeLayout(rest);+ // The clip being dragged is exempt: its sound stays exactly where it is,+ // which is the J-cut. Everything the reflow pushed takes its sound along.+ sbeSyncCarry(rest, mark, [id]);+ c.source = 'human';+ return { clips: rest, ok: true };+}++// Both handles follow the pointer, which is the property that makes a timeline+// feel like a timeline. The left one moves the clip's in-point AND its slot, so+// the tail does not move and a hole opens behind it (holes are legal here —+// they are what the generate control fills). The right one changes the length,+// so everything after it ripples.+function sbeTrim(clips, id, edge, filmTime) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const mark = sbeSyncMark(clips);+ if (edge === 'l') {+ const d = sbeNum(filmTime) - sbeNum(c.film_start);+ let s = sbeNum(c.start) + d;+ s = Math.max(0, Math.min(sbeNum(c.end) - SBE_MIN_CLIP, s));+ // A HEAD TRIM MOVES THE SLOT WITH THE IN-POINT OR IT IS NOT A TRIM. The+ // lead gap used to clamp at zero on its own, so pulling the head of a+ // butt-joined clip further open moved `start` while `film_start` stood+ // still: the picture SLIPPED inside its slot, the clip grew to the right+ // instead of the left (against this function's own contract, "the tail+ // does not move"), and an unlinked sound was left describing a frame that+ // no longer plays under it. Trimming may not change the film→source+ // mapping of the frames it keeps; that invariant is what makes "the sound+ // stays put" correct rather than lucky.+ const room = Math.max(0, sbeNum(c._gap));+ if (s < sbeNum(c.start) - room) s = sbeRound(sbeNum(c.start) - room);+ const applied = s - sbeNum(c.start);+ if (Math.abs(applied) < 1e-9) return { clips: clips, ok: false, why: 'edge' };+ c.start = sbeRound(s);+ c._gap = Math.max(0, sbeRound(sbeNum(c._gap) + applied));+ } else {+ const d = sbeNum(filmTime) - sbeNum(c.film_end);+ let e = sbeNum(c.end) + d;+ const srcDur = sbeNum(c.duration, 0);+ if (srcDur > 0) e = Math.min(srcDur, e);+ e = Math.max(sbeNum(c.start) + SBE_MIN_CLIP, e);+ if (Math.abs(e - sbeNum(c.end)) < 1e-9) return { clips: clips, ok: false, why: 'edge' };+ c.end = sbeRound(e);+ }+ c.source = 'human';+ sbeLayout(clips);+ // The trimmed clip keeps its own mapping by construction (the head moves the+ // slot with the in-point, the tail moves neither), so its sound must NOT be+ // touched. A tail trim ripples everything after it, and those take theirs.+ sbeSyncCarry(clips, mark, [id]);+ return { clips: clips, ok: true };+}++function sbeRippleDelete(clips, id) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const mark = sbeSyncMark(clips);+ const out = clips.filter(x => x !== c); // its lead gap leaves with it+ sbeLayout(out);+ sbeSyncCarry(out, mark, []); // nothing here is a deliberate slide+ return { clips: out, ok: true, removed: c };+}++function sbeSplitAt(clips, t, newId) {+ const c = sbeClipAt(clips, t);+ if (!c) return { clips: clips, ok: false, why: 'nothing there' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const off = sbeNum(t) - sbeNum(c.film_start);+ if (off < SBE_MIN_CLIP || sbeLen(c) - off < SBE_MIN_CLIP) {+ return { clips: clips, ok: false, why: 'too close to an edge' };+ }+ // THE SOUND IS CUT WHERE THE PICTURE IS, NOT COPIED TWICE. The deep copy+ // below used to carry `audio` into the new half verbatim, so one strip became+ // two claiming the same seconds of the same take — which the server refuses+ // as `clips_audio_overlap`, and which would have played the line twice if it+ // had not. The cut is expressed in the SOURCE clock both halves share, so+ // each half comes out of the split at the drift it went in with.+ const w = sbeClipAudio(c);+ let cutA = null, cutB = null;+ if (w.split) {+ const sp = sbeRound(sbeNum(c.start) + off);+ if (sp < w.start + SBE_MIN_CLIP || sp > w.end - SBE_MIN_CLIP) {+ // The strip has been trimmed to a window this cut falls outside, so one+ // half would end up with no sound at all — a state the document cannot+ // express (an absent `audio` means LINKED, which would invent sound the+ // film does not have). Say so instead of guessing.+ return { clips: clips, ok: false,+ why: 'the unlinked sound does not reach this cut — move the '+ + 'strip back or re-link it first' };+ }+ cutA = sbeAudioField({ start: w.start, end: sp,+ film_start: w.film_start }, w.coupled);+ cutB = sbeAudioField({ start: sp, end: w.end,+ film_start: w.film_start + (sp - w.start) },+ w.coupled);+ }+ const mark = sbeSyncMark(clips);+ const b = JSON.parse(JSON.stringify(c));+ b.id = newId || sbeNewId();+ b.start = sbeRound(sbeNum(c.start) + off);+ b._gap = 0;+ b.source = 'human';+ c.end = b.start;+ c.source = 'human';+ if (cutA) { c.audio = cutA; b.audio = cutB; } else { delete b.audio; }+ const out = clips.slice();+ out.splice(out.indexOf(c) + 1, 0, b);+ sbeLayout(out);+ // Both halves were just given the position they are meant to have; the+ // reflow only ever moves what is AFTER them.+ sbeSyncCarry(out, mark, [c.id, b.id]);+ return { clips: out, ok: true, added: b };+}++function sbeNewId() {+ return 'k' + Math.random().toString(16).slice(2, 10) ++ (Date.now() % 65536).toString(16);+}++// A clip the board has rendered but the timeline has never seen. `slot` is+// where the person who ordered it wanted it — carried on the board by+// edit/generate — so a shot generated for a hole lands in that hole rather than+// at the end of the film.+function sbePlaceUnplaced(clips, item, filmStart) {+ const dur = Math.max(SBE_MIN_CLIP, sbeNum(item.duration_s, 0)+ || sbeNum((item.slot || {}).duration, 0) || 5);+ const c = {+ id: sbeNewId(), path: item.path, proxy: item.proxy || null,+ start: 0, end: sbeRound(dur), film_start: 0, film_end: 0,+ source: 'human', locked: false, n: item.n,+ title: item.title || '', duration: sbeNum(item.duration_s, 0) || null,+ };+ const want = Math.max(0, sbeNum(filmStart));+ const mark = sbeSyncMark(clips);+ const out = clips.slice();+ let idx = out.length;+ for (let i = 0; i < out.length; i++) {+ if (sbeNum(out[i].film_start) >= want - 1e-6) { idx = i; break; }+ }+ // Where the clip AFTER the hole is standing, before any of this. Filling a+ // hole must not move the rest of the film: a shot was generated for this+ // slot precisely so the cuts around it would stay on their beats. Every+ // other operation here ripples; this one does not, and that is the whole+ // difference between "fill the hole" and "insert a clip".+ const follower = out[idx] || null;+ const pinned = follower ? sbeNum(follower.film_start) : null;+ out.splice(idx, 0, c);+ c._gap = 0;+ sbeLayout(out);+ const prev = out[out.indexOf(c) - 1];+ c._gap = Math.max(0, sbeRound(want - (prev ? sbeNum(prev.film_end) : 0)));+ sbeLayout(out);+ if (follower && pinned !== null) {+ // If the new clip overruns where the follower stood there is no room to+ // keep the promise, and the tail rides along rather than overlapping.+ follower._gap = Math.max(0, sbeRound(pinned - sbeNum(c.film_end)));+ sbeLayout(out);+ }+ sbeSyncCarry(out, mark, []);+ return { clips: out, ok: true, added: c };+}++// ---------------------------------------------------------------------------+// THE THREE KINDS+// ---------------------------------------------------------------------------+// ABSENT IS VIDEO, on the client for the same reason it is on the server: every+// clip in every edit.json written before today has no `kind`, and every one of+// them is a video. Reading the default rather than stamping it means nothing+// has to be rewritten and a v1 document is correct the moment it loads.+function sbeKind(c) {+ const k = String((c && c.kind) || '').toLowerCase();+ if (k === 'still' || k === 'slug' || k === 'video') return k;+ // ABSENT NO LONGER MEANS VIDEO ON ITS OWN — see clip_kind() in+ // storyboard_editor.py. A pool image can reach the picture lane unstamped,+ // and answering "video" for a .png handed a still to a <video> element:+ // format error, black stage, and the same mistake in the render. The+ // overlay lane has always read the suffix here; both lanes now agree.+ return /\.(png|jpe?g|webp|tiff?)$/i.test(String((c && c.path) || ''))+ ? 'still' : 'video';+}++function sbeBright(c) {+ const a = (c && c.adjust) || {};+ return Math.max(-SBE_BRIGHT_MAX, Math.min(SBE_BRIGHT_MAX, sbeNum(a.brightness, 0)));+}++// THE PREVIEW IS AN APPROXIMATION AND SAYS SO. ffmpeg's `eq=brightness` is an+// ADDITIVE offset; CSS `filter: brightness()` is MULTIPLICATIVE, and CSS has no+// additive form. So the two are matched where a viewer judges exposure — at+// mid-grey, where `0.5 + b` and `0.5 * (1 + 2b)` are the same number. The ends+// drift, the badge says approximate, and the render is the exact one.+function sbeBrightnessCss(b) {+ return Math.max(0, sbeRound(1 + 2 * sbeNum(b)));+}++function sbeSetBrightness(clips, id, v) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ const b = Math.max(-SBE_BRIGHT_MAX, Math.min(SBE_BRIGHT_MAX, sbeNum(v)));+ if (Math.abs(b - sbeBright(c)) < 1e-6) return { clips: clips, ok: false, why: 'unchanged' };+ // NEUTRAL IS ABSENT, exactly as the server normalises it: dragging back to+ // zero must leave a clip identical to one nobody ever touched, or every clip+ // anybody ever selected carries a dead field for the rest of its life.+ if (Math.abs(b) < 1e-6) delete c.adjust;+ else c.adjust = Object.assign({}, c.adjust || {}, { brightness: sbeRound(b) });+ c.source = 'human';+ return { clips: clips, ok: true };+}++// WHERE A DROP LANDS. The midpoint rule every NLE uses: on the left half of a+// clip means before it, on the right half means after it — which is the only+// reading that makes a drop exactly on a boundary unambiguous.+function sbeDropIndex(clips, filmTime) {+ const want = Math.max(0, sbeNum(filmTime));+ for (let i = 0; i < (clips || []).length; i++) {+ if (want < sbeNum(clips[i].film_start) + sbeLen(clips[i]) / 2) return i;+ }+ return (clips || []).length;+}++// INSERT WITH RIPPLE — the opposite of sbePlaceUnplaced, and both are right.+// Filling a hole must NOT move the film: a shot was generated for that slot+// precisely so the cuts around it stayed on their beats. Dropping a NEW clip+// between two others must move it, or the drop silently overwrites whatever it+// landed on.+function sbeInsertAt(clips, item, filmTime) {+ const kind = String(item.kind || 'video');+ const dur = Math.max(SBE_MIN_CLIP,+ sbeNum(item.duration_s, 0) || sbeNum(item.duration, 0) || 5);+ const c = {+ id: sbeNewId(),+ path: (kind === 'slug') ? null : (item.path || ''),+ proxy: item.proxy || null,+ start: 0, end: sbeRound(dur), film_start: 0, film_end: 0,+ source: 'human', locked: false,+ title: item.title || '',+ // A still and a slug have no source clock, so they have no source+ // duration — and a `duration` left over from a video would clamp the trim+ // that is the only way to change how long they hold.+ duration: (kind === 'video') ? (sbeNum(item.duration_s, 0) || null) : null,+ };+ if (kind !== 'video') c.kind = kind;+ if (item.n !== undefined && item.n !== null) c.n = item.n;+ const mark = sbeSyncMark(clips);+ const out = clips.slice();+ const idx = sbeDropIndex(out, filmTime);+ out.splice(idx, 0, c);+ c._gap = 0; // hard against its new neighbour+ sbeLayout(out); // everything after it rides along+ sbeSyncCarry(out, mark, []); // ...sound included+ return { clips: out, ok: true, added: c, index: idx };+}++// REORDER: a ripple delete and an insert, in one gesture. sbeMoveTo puts a clip+// at a TIME and leaves a hole where it was; this puts it at a POSITION and+// closes the hole behind it, which is what "drag to reorder" means everywhere+// else. Both are on the same drag, told apart by Shift, because both are things+// people want and neither can be inferred from the pointer.+function sbeReorderTo(clips, id, filmTime) {+ const c = sbeById(clips, id);+ if (!c) return { clips: clips, ok: false, why: 'gone' };+ if (c.locked) return { clips: clips, ok: false, why: 'locked' };+ const mark = sbeSyncMark(clips);+ const rest = clips.filter(x => x !== c);+ const idx = sbeDropIndex(rest, filmTime);+ rest.splice(idx, 0, c);+ c._gap = 0;+ sbeLayout(rest);+ sbeSyncCarry(rest, mark, [id]); // the clip being dragged keeps its J-cut+ c.source = 'human';+ return { clips: rest, ok: true, index: idx };+}++// ---- the save payload -----------------------------------------------------+// Transient client bookkeeping (`_gap`, `_pin`) is stripped: it is derivable+// from what is saved, and a field the server does not know is a field that+// outlives the reason it existed.+function sbeCleanClip(c) {+ const out = {};+ for (const k of Object.keys(c)) {+ if (k.charAt(0) === '_') continue;+ out[k] = c[k];+ }+ out.start = sbeRound(out.start);+ out.end = sbeRound(out.end);+ out.film_start = sbeRound(out.film_start);+ out.film_end = sbeRound(out.film_end);+ out.locked = !!out.locked;+ out.source = (out.source === 'human') ? 'human' : 'auto';+ const kind = sbeKind(c);+ if (kind === 'video') {+ delete out.kind;+ } else {+ out.kind = kind;+ // SYNTHESISED, the same way normalise_edit synthesises them, so the+ // document the client sends and the document the server writes back are+ // the same document. Trimming a still moves its slot; the window follows.+ out.start = 0;+ out.end = sbeRound(Math.max(0, out.film_end - out.film_start));+ out.duration = null;+ if (kind === 'slug') { out.path = null; out.proxy = null; }+ }+ const b = sbeBright(out);+ if (Math.abs(b) < 1e-6) delete out.adjust;+ else out.adjust = { brightness: sbeRound(b) };+ return out;+}++function sbeSaveBody(state) {+ const edit = Object.assign({}, state.edit || {});+ edit.clips = (state.clips || []).map(sbeCleanClip);+ // The lane travels with the document. Client-only bookkeeping is stripped+ // the same way a clip's is.+ edit.overlays = (state.overlays || []).map(o => {+ const out = {};+ for (const k of Object.keys(o)) if (k.charAt(0) !== '_') out[k] = o[k];+ return out;+ });+ edit.board_id = state.id;+ const body = { id: state.id, edit: edit };+ if (state.expect !== null && state.expect !== undefined) body.expect_revision = state.expect;+ return body;+}++// The server answers a bad save with EVERY error at once and writes nothing, so+// the client can light up every offending clip in one pass instead of playing+// whack-a-mole. `where` is the index in the array we sent.+function sbeErrorsByClip(errors, order) {+ const out = { doc: [], byId: {} };+ for (const e of errors || []) {+ const w = e.where;+ if (w === null || w === undefined || !order || !order.length || !order[w]) {+ out.doc.push(e);+ continue;+ }+ const id = order[w];+ (out.byId[id] = out.byId[id] || []).push(e);+ }+ return out;+}++// Interleaved int16 over `scale`, which is how a five-minute track arrives as+// 326 KB instead of 85 MB of Float32Array. The client draws; it never decodes.+function sbeDecodePeaks(doc) {+ if (!doc || !Array.isArray(doc.peaks)) return null;+ const scale = sbeNum(doc.scale, 127) || 127;+ const n = Math.min(sbeNum(doc.count, 0) || (doc.peaks.length >> 1),+ doc.peaks.length >> 1);+ const lo = new Array(n), hi = new Array(n);+ for (let i = 0; i < n; i++) {+ lo[i] = sbeNum(doc.peaks[i * 2]) / scale;+ hi[i] = sbeNum(doc.peaks[i * 2 + 1]) / scale;+ }+ return { count: n, lo: lo, hi: hi,+ rate: sbeNum(doc.buckets_per_second, 100) || 100,+ duration: sbeNum(doc.duration, 0) };+}++function sbeFmtTime(t) {+ t = Math.max(0, sbeNum(t));+ const m = Math.floor(t / 60);+ const s = t - m * 60;+ return m + ':' + (s < 10 ? '0' : '') + s.toFixed(2);+}++// ---------------------------------------------------------------------------+// PAN AND ZOOM — the two sliders, as arithmetic+// ---------------------------------------------------------------------------+// Everything here is pure: seconds and pixels in, pixels out. The DOM callers+// are sbeZoomTo / sbeZoomSlide / sbePaintHead, and the reason these are+// separate is that "zooming keeps the playhead where it was" is the one part+// of a timeline nobody can check by eye and everybody notices when it is+// wrong — so it is checked in node instead. See test_storyboard_editor_ui.py.++// The scale at which the WHOLE film is inside the window. This is the+// minimum of the zoom slider, which is why a 71.6s film can never again be+// longer than the box it is drawn in.+function sbeZoomFitPps(span, viewport) {+ const w = Math.max(80, sbeNum(viewport) - SBE_TL_PAD);+ const s = Math.max(0.1, sbeNum(span));+ return Math.max(SBE_PPS_FLOOR, w / s);+}++// The slider is logarithmic. Linear px/sec spends four fifths of its travel+// between 100 and 200 px/sec, where nothing changes, and crosses the useful+// range — a whole film to a single cut — in the first inch.+function sbeZoomFromSlider(v, minPps, maxPps) {+ const lo = Math.max(SBE_PPS_FLOOR, sbeNum(minPps, 1));+ const hi = Math.max(lo * 1.0001, sbeNum(maxPps, SBE_PPS_MAX));+ const f = Math.max(0, Math.min(1, sbeNum(v) / SBE_ZOOM_TICKS));+ return lo * Math.pow(hi / lo, f);+}++function sbeZoomToSlider(pps, minPps, maxPps) {+ const lo = Math.max(SBE_PPS_FLOOR, sbeNum(minPps, 1));+ const hi = Math.max(lo * 1.0001, sbeNum(maxPps, SBE_PPS_MAX));+ const p = Math.max(lo, Math.min(hi, sbeNum(pps, lo)));+ return Math.round(Math.log(p / lo) / Math.log(hi / lo) * SBE_ZOOM_TICKS);+}++// WHAT THE VIEW HOLDS STILL WHILE THE SCALE CHANGES. The playhead if it is on+// screen — that is the frame you are looking at and the one an NLE anchors on+// — and the middle of the view if it is not.+function sbeZoomAnchor(playhead, scrollLeft, viewport, pps, at) {+ if (at !== undefined && at !== null) {+ return { t: Math.max(0, sbeNum(at)), px: sbeNum(at) * sbeNum(pps) - sbeNum(scrollLeft) };+ }+ const px = sbeNum(playhead) * sbeNum(pps) - sbeNum(scrollLeft);+ if (px >= 0 && px <= sbeNum(viewport)) return { t: Math.max(0, sbeNum(playhead)), px: px };+ const mid = sbeNum(viewport) / 2;+ return { t: Math.max(0, (sbeNum(scrollLeft) + mid) / Math.max(1e-6, sbeNum(pps))), px: mid };+}++// Where the scroller has to sit for `anchor.t` to land back under+// `anchor.px` at the new scale, clamped to what there is to scroll.+function sbeZoomScroll(anchor, pps, maxScroll) {+ const want = sbeNum(anchor.t) * sbeNum(pps) - sbeNum(anchor.px);+ return Math.max(0, Math.min(Math.max(0, sbeNum(maxScroll)), want));+}++// PAGE, DO NOT CHASE. A view that re-centres on every frame fights the user's+// own panning and makes the track feel like it is sliding out from under the+// pointer; Resolve pages when the head crosses the edge, so this does too —+// one jump, then the head walks across a fresh screenful. Returns the CURRENT+// scroll unchanged while the head is still on screen, which is how the caller+// knows to leave the DOM alone.+function sbeFollowScroll(headPx, scrollLeft, viewport, maxScroll) {+ const sl = Math.max(0, sbeNum(scrollLeft));+ const w = Math.max(1, sbeNum(viewport));+ const x = sbeNum(headPx);+ if (x >= sl && x <= sl + w - 2) return sl;+ const lead = w * 0.12;+ return Math.max(0, Math.min(Math.max(0, sbeNum(maxScroll)), x - lead));+}++// ---------------------------------------------------------------------------+// THE MONITOR ROW — how two 16:9 pictures fill one strip+// ---------------------------------------------------------------------------+// A 16:9 pair at the asked-for 40/60 needs 2.96 px of width for every px of+// height. No window this panel runs in has that much of both: measured at+// 1440x900, the cut column is 1110px wide and has ~307px of height to spare,+// and 307px of height buys a pair 886px wide. The other 224px is the rail —+// the inspector and the unplaced strip, moved out of the vertical stack and+// into the space the monitors cannot reach. That is what makes "fill the+// width" true instead of aspirational.+//+// * Height first: the monitors get the whole vertical budget, because+// height is the scarce thing and a bigger picture is what was asked for.+// * Then the rail gets what the pair leaves, clamped. If the leftover is+// wider than the clamp, the SOURCE widens toward the program — up to+// equal monitors and no further, since the program is the one being cut.+// * If the width runs out first (a tall, narrow window), the pair takes the+// width-derived height at exactly 40/60 and the leftover HEIGHT goes to+// the timeline, which is the row that grows.+function sbeMonitorFit(width, budget, opts) {+ const o = opts || {};+ const gap = sbeNum(o.gap, SBE_MON_GAP);+ const minH = sbeNum(o.minH, SBE_MON_MIN_H);+ const pref = sbeNum(o.ratio, SBE_MON_RATIO);+ const maxR = sbeNum(o.maxRatio, SBE_MON_RATIO_MAX);+ const railMin = sbeNum(o.railMin, SBE_RAIL_MIN);+ const railMax = sbeNum(o.railMax, SBE_RAIL_MAX);+ const A = 16 / 9;+ const total = Math.max(2 * minH * A + railMin + 2 * gap, sbeNum(width));+ const cap = Math.max(minH, sbeNum(budget));+ // The most the pair may ever take, and the height at which 40/60 fills it.+ const pairMax = total - railMin - 2 * gap;+ const wide = (pairMax - gap) / (A * (1 + pref));+ let h, r;+ if (wide <= cap) { h = wide; r = pref; }+ else {+ h = cap;+ // Widen the source only as far as the rail's own maximum allows: past+ // that the rail stops being leftover and starts being a panel.+ const room = total - railMax - 2 * gap - gap;+ r = Math.max(pref, Math.min(maxR, room / (A * h) - 1));+ }+ const progW = h * A;+ const srcW = h * r * A;+ const rail = Math.max(railMin, Math.min(railMax, total - progW - srcW - 2 * gap));+ return { progH: h, progW: progW, srcH: h * r, srcW: srcW, ratio: r,+ rail: rail, gap: gap, total: progW + srcW + rail + 2 * gap };+}++// ---------------------------------------------------------------------------+// THE TIMELINE'S HEIGHT — one number, dragged from its top edge+// ---------------------------------------------------------------------------+// "The timeline is too constricted and cannot be expanded vertically. It needs+// to allow you to drag the upper side of the timeline, which will change the+// layout a little bit, enabling expansion in case you have some sound editing+// in there."+//+// Nothing here resizes an element. The drag moves ONE number — how much of the+// cut column the timeline is entitled to — and sbeFitMonitors sizes the+// monitors off whatever is left, which is the arithmetic that was already+// there. So up is "more track, smaller picture", down is its exact inverse,+// and no two boxes can ever overlap or leave a gutter between them.++// What the layout will allow, given what the window has left. Both ends are+// hard: the timeline may never be shorter than its own contents, and it may+// never take so much that the monitors stop being monitors — `max` is+// sbeFitMonitors' measurement of that, and it is clamped again here so a+// caller that has not measured yet cannot ask for a screenful.+function sbeTlClamp(want, max) {+ const hi = Math.max(SBE_TL_MIN_H,+ Math.min(SBE_TL_MAX_H, sbeNum(max, SBE_TL_MAX_H)));+ return Math.round(Math.max(SBE_TL_MIN_H,+ Math.min(hi, sbeNum(want, SBE_TL_MIN_H))));+}++// WHERE A DRAGGED PIXEL LANDS. Every lane starts at the height it has always+// had and takes its share of what the drag added, up to its own cap; whatever+// a capped lane cannot take is offered again to the ones still growing, so the+// height is spent rather than lost. Pure: px in, px out, no DOM — the+// distribution is the whole feature and it is not checkable by eye.+function sbeLaneHeights(tlH) {+ const out = { ruler: 18 };+ for (const L of SBE_LANES) out[L.key] = L.base;+ let left = Math.max(0, Math.round(sbeNum(tlH, SBE_TL_MIN_H)) - SBE_TL_MIN_H);+ // Four passes is one more than the number of lanes that can cap while+ // another still has room, so this terminates with the height spent or every+ // lane full. A `while` here would be a loop whose bound is an argument.+ for (let pass = 0; pass < 4 && left > 0.5; pass++) {+ let share = 0;+ for (const L of SBE_LANES) if (out[L.key] < L.cap) share += L.share;+ if (share <= 0) break;+ const pool = left;+ for (const L of SBE_LANES) {+ if (out[L.key] >= L.cap) continue;+ const take = Math.min(pool * (L.share / share), L.cap - out[L.key]);+ out[L.key] += take;+ left -= take;+ }+ }+ for (const L of SBE_LANES) out[L.key] = Math.round(out[L.key]);+ return out;+}++// THE PREFERENCE IS THIS BROWSER'S, NOT THE FILM'S. It never goes near+// edit.json: a window height is not sequence data, writing it there would bump+// the document's revision every time somebody dragged an edge, put one+// machine's screen into a file two other surfaces render, and race the+// snapshot lane for a number no renderer will ever read. localStorage is where+// every other view preference in this panel already lives — `sbeMuted`, the+// open document, the workflow tab.+function sbeTlPrefRead() {+ let v = NaN;+ try { v = parseInt(localStorage.getItem('phos_sbe_tl_h') || '', 10); } catch (e) {}+ return (v === v) ? sbeTlClamp(v, SBE_TL_MAX_H) : SBE_TL_MIN_H;+}+function sbeTlPrefWrite(px) {+ try {+ localStorage.setItem('phos_sbe_tl_h',+ String(sbeTlClamp(px, SBE_TL_MAX_H)));+ } catch (e) {}+}++// ---------------------------------------------------------------------------+// LOADING AND SAVING+// ---------------------------------------------------------------------------+// ---------------------------------------------------------------------------+// THE EDITOR TAB — the surface, and which document is in it+// ---------------------------------------------------------------------------+// The document id is NOT the open board's id any more. It is remembered, it+// survives a tab switch and a reload, and it can be nothing at all: an Editor+// that only exists inside an open storyboard is an editor most clips can never+// reach. `edDoc()` and `edRemember()` are the whole of that memory.+function edDoc() {+ try { return localStorage.getItem('phos_ed_doc') || ''; } catch (e) { return ''; }+}+function edRemember(id) {+ try {+ if (id) localStorage.setItem('phos_ed_doc', id);+ else localStorage.removeItem('phos_ed_doc');+ } catch (e) {}+}++// Exactly one of the two states is on screen: a document, or the invitation+// to pick one. `hidden` alone, no classes — #edStage is a plain flex column.+function edShow(which) {+ const doc = document.getElementById('sbTimeline');+ const empty = document.getElementById('edEmpty');+ if (doc) doc.hidden = (which !== 'doc');+ if (empty) empty.hidden = (which !== 'empty');+ const stage = document.getElementById('edStage');+ if (stage) stage.scrollTop = 0;+}++// Entering the tab. Re-entry is not re-opening: if the document is already+// loaded it is resumed, because a tab switch is not a close.+function edInit() {+ if (SBE.open && SBE.id) { sbeResume(); return; }+ const last = edDoc();+ if (last) {+ // A remembered id can point at a film that was deleted while the Editor+ // was closed. Opening it must fail into the picker, not into a red box —+ // the silent-failure restore the review flagged.+ sbeOpen(last, { onMissing: () => { edRemember(''); edShowPicker(); } });+ return;+ }+ edShowPicker();+}++// The empty state, painted from the board list. This is "pick a film / start+// from clips": every film with something on disk, plus the pool on the left.+async function edShowPicker() {+ edShow('empty');+ // With no document open "this film" has nothing in it, so the pool opens+ // on the generations — which is the source that always has something.+ if (ED.src === 'film') edPoolSrc('gallery'); else edPoolRefresh();+ const box = document.getElementById('edPick');+ if (box) box.innerHTML = '<span class="sbe-note">reading your __SEQS__…</span>';+ let boards = [];+ try {+ const r = await (await fetch('/storyboard/list')).json();+ boards = ((r && r.boards) || []).filter(b => (b.clips || 0) > 0);+ } catch (e) { boards = []; }+ if (!box) return;+ if (!boards.length) {+ box.innerHTML = '<span class="sbe-note">Nothing has been rendered yet. ' ++ 'Anything you generate — on any engine — shows up in the media pool ' ++ 'on the left, and one click puts it on the track.</span>';+ return;+ }+ box.innerHTML = boards.map(b =>+ '<button type="button" onclick="edOpenBoard(\'' + escapeHtml(b.id) + '\')">' ++ '<svg class="ph" aria-hidden="true"><use href="#ph-film-strip"/></svg>' ++ escapeHtml(b.title || b.id) ++ '<span class="sub">' + (b.clips || 0) + ' clip' + ((b.clips === 1) ? '' : 's') ++ '</span></button>').join('');+}++// The one door, from anywhere: the rail's step 3, a board row, the picker.+function edOpenBoard(id) {+ if (!id) return;+ if (typeof workflowSwitch === 'function') workflowSwitch('editor');+ sbeOpen(id);+}++function sbeOpen(id, opts) {+ const want = String(id || SBE.id || edDoc() || '');+ if (!want) { edShowPicker(); return; }+ if (SBE.open && SBE.id && SBE.id !== want) sbeCloseDoc({ quiet: true });+ SBE.open = true;+ SBE.id = want;+ SBE.onMissing = (opts && opts.onMissing) || null;+ edRemember(want);+ // The title comes off the edit payload (it always carried one). Reading it+ // off the open board tied the Editor's header to the Storyboard's state.+ SBE.title = (SBE.id === SB.id+ ? ((((SB.payload || {}).board) || {}).title || '') : '') || SBE.title || 'Editor';+ sbeEl('sbeTitle').textContent = SBE.title;+ edShow('doc');+ sbeSetState('loading…', '');+ sbeLoad();+ if (SBE.timer) clearInterval(SBE.timer);+ SBE.timer = setInterval(sbeTick, 1500);+ window.addEventListener('resize', sbePaint);+ if (typeof edPoolRefresh === 'function') edPoolRefresh();+}++// Leaving the TAB. The document stays open — clips, undo stack, playhead and+// all — and only the things that cost something while nobody is looking stop.+function sbeSuspend() {+ if (!SBE.open) return;+ sbeStop();+ sbeSrcStop(); // both screens, or the left one plays on in a tab nobody is looking at+ if (SBE.dirty && !SBE.conflict) sbeSave(true);+ if (SBE.timer) { clearInterval(SBE.timer); SBE.timer = null; }+ window.removeEventListener('resize', sbePaint);+}++function sbeResume() {+ if (!SBE.open) return;+ edShow('doc');+ if (SBE.timer) clearInterval(SBE.timer);+ SBE.timer = setInterval(sbeTick, 1500);+ window.removeEventListener('resize', sbePaint);+ window.addEventListener('resize', sbePaint);+ sbePaint();+ sbeLoad(true);+ if (typeof edPoolRefresh === 'function') edPoolRefresh();+}++// Closing the DOCUMENT. This is the only thing that drops SBE.open, and it is+// reached from Esc, from the header's Close, and from opening another film.+function sbeCloseDoc(opts) {+ sbeStop();+ sbeVersionsClose(); // a picker for a document that is gone is a lie+ // NOT A SAVE. Leaving the tab is not the user asking for his draft to be+ // rewritten; the backup is what catches the work, and the offer on the way+ // back in is what returns it.+ if (SBE.open && SBE.dirty && !SBE.conflict) {+ // Fire-and-forget, because leaving is not a thing to be refused — but+ // SAID OUT LOUD if it did not land, since after this the only copy of+ // those minutes was the one that was not written.+ const was = SBE.title || 'this draft';+ sbeBackup(true).then(kept => {+ if (!kept) {+ phosToast('The unsaved changes in "' + was + '" could not be backed ' ++ 'up before it closed. Open it again and press Save if it ' ++ 'still has them.', { kind: 'danger', duration: 9000 });+ }+ });+ }+ if (SBE.timer) { clearInterval(SBE.timer); SBE.timer = null; }+ if (SBE.saveTimer) { clearTimeout(SBE.saveTimer); SBE.saveTimer = null; }+ SBE.open = false;+ SBE.id = '';+ SBE.clips = [];+ SBE.undo.length = 0; SBE.redo.length = 0;+ window.removeEventListener('resize', sbePaint);+ if (!(opts && opts.quiet)) { edRemember(''); edShowPicker(); }+}++// Kept under its old name because it is the door Esc and the header use.+function sbeClose() { sbeCloseDoc(); }++// The film this cut belongs to, in the tab that owns films. One direction of+// the door the rail's step 3 opens the other way.+function sbeGoToBoard() {+ if (!SBE.id) return;+ if (typeof workflowSwitch === 'function') workflowSwitch('storyboard');+ if (typeof sbOpenAt === 'function') sbOpenAt(SBE.id, 'shots');+}++// The document is gone and nothing about it is worth keeping.+function sbeTeardown() { sbeCloseDoc({ quiet: true }); }++async function sbeLoad(quiet) {+ let r;+ try {+ r = await (await fetch('/storyboard/edit?id=' + encodeURIComponent(SBE.id)+ + '&session=' + encodeURIComponent(SBE.session))).json();+ } catch (e) {+ if (!quiet) sbeSetState('the panel did not answer', 'dirty');+ return;+ }+ if (!r || !r.ok) {+ // THE DOCUMENT IS GONE, not broken. A remembered id whose film was+ // deleted has to land on the picker — the Editor's own empty state — and+ // not on an error box for a film the user never asked to open.+ if (SBE.onMissing && r && !r.corrupt) {+ const fn = SBE.onMissing;+ SBE.onMissing = null;+ SBE.open = false; SBE.id = '';+ if (SBE.timer) { clearInterval(SBE.timer); SBE.timer = null; }+ fn();+ return;+ }+ // A corrupt edit.json is NEVER silently replaced — the server says so and+ // the only honest thing to do is repeat it.+ sbeShowDocError(r && r.corrupt+ ? (r.error || 'edit.json is corrupt') + ' — nothing was overwritten. Fix or delete the file beside the board.'+ : ((r && r.error) || 'could not read this timeline'));+ return;+ }+ sbeAdopt(r, quiet);+}++function sbeAdopt(r, quiet) {+ SBE.onMissing = null;+ // The payload has always carried the title; the Editor now uses it, so the+ // header names the film it is cutting rather than whatever board is open.+ if (r.title) {+ SBE.title = r.title;+ const t = sbeEl('sbeTitle');+ if (t) t.textContent = SBE.title;+ }+ SBE.edit = r.edit || {};+ SBE.audio = SBE.edit.audio || null;+ SBE.beats = SBE.edit.beats || null;+ SBE.revision = sbeNum(SBE.edit.revision, 0);+ SBE.proxyUrl = r.proxy_url || '';+ SBE.unplaced = r.unplaced || [];+ SBE.pool = r.clips || [];+ SBE.relink = r.relink || [];+ SBE.prepare = r.prepare || {};+ if (r.drafts) SBE.drafts = r.drafts;+ if (r.active_draft !== undefined) SBE.activeDraft = r.active_draft || '';+ SBE.backup = r.backup || null;+ SBE.backupHidden = false; // a NEW offer is not the one dismissed+ SBE.overlays = (SBE.edit.overlays || []).map(o => Object.assign({}, o));+ SBE.ovSel = '';+ SBE.clips = sbeAdoptGaps((SBE.edit.clips || []).map(c => Object.assign({}, c)));+ sbeLayout(SBE.clips);+ SBE.dirty = false;+ SBE.conflict = 0;+ SBE.errors = {};+ sbeEl('sbeConflict').hidden = true;+ // The auto-key receipt is about ONE placement on the timeline that was just+ // replaced. Carrying it across a load would leave an "undo" pointing at an+ // overlay id that is no longer in the document.+ if (typeof sbeKeyedDismiss === 'function') sbeKeyedDismiss();+ sbePaintNotices();+ if (SBE.audio && SBE.audio.path && !sbeEl('sbeMusic').value) {+ sbeEl('sbeMusic').value = SBE.audio.path;+ }+ sbePaintMusicName();+ // The saved mode wins over the control's default, or reopening a film would+ // silently re-arm `replace` on a timeline that was mixed `under`.+ sbeSetMusicMode((SBE.audio && SBE.audio.mode) || 'under');+ sbeSetState(r.generated ? 'cut by the auto-editor' : 'saved · revision ' + SBE.revision,+ 'saved');+ sbeSyncMusic();+ sbePaintDraft();+ sbePaintRecovery();+ sbePaintRelink();+ if (ED.src === 'film') edPoolRefresh();+ sbeFetchPeaks();+ sbePaint();+ // Land on a picture, not on black. A timeline that opens dark reads as+ // broken for the second and a half before the first click.+ if (!SBE.playing && !SBE.drag) sbeShowFrameAt(SBE.playhead);+ if (!quiet && r.generated) {+ phosToast('No timeline existed, so the auto-editor cut one — every shot at its best window, on the beat.',+ { duration: 7000 });+ }+}++async function sbeFetchPeaks() {+ try {+ const res = await fetch('/storyboard/edit/peaks?id=' + encodeURIComponent(SBE.id));+ if (!res.ok) { SBE.peaks = null; SBE.peaksFor = ''; sbePaint(); return; }+ const doc = await res.json();+ SBE.peaks = sbeDecodePeaks(doc);+ SBE.peaksFor = String(doc.path || '');+ // THE WAVEFORM EXISTS BEFORE THE EDIT KNOWS ABOUT IT. `prepare` writes+ // peaks.json beside the board; only an auto-edit writes the soundtrack+ // INTO edit.json. Showing an empty strip over a track that is right there+ // would be the UI lying about the server's own state — so the axis comes+ // off the peaks document, which carries its own path and duration. This+ // does NOT touch SBE.edit, so nothing here can be saved as if the+ // arrangement had a soundtrack it was never cut to.+ if (!SBE.audio && doc && doc.path) {+ SBE.audio = { path: String(doc.path), offset: 0, peaks: 'peaks.json',+ duration: sbeNum(doc.duration) };+ if (!sbeEl('sbeMusic').value) {+ sbeEl('sbeMusic').value = String(doc.path);+ sbePaintMusicName();+ }+ }+ } catch (e) { SBE.peaks = null; SBE.peaksFor = ''; }+ sbePaint();+}++// The soundtrack row, as a name. `sbeMusic` is still the input every other+// caller reads and writes — this only decides which of the two is on screen.+function sbeMusicEditPath(on) {+ const row = sbeEl('sbePrepare');+ if (row && row.classList) row.classList.toggle('is-editing', !!on);+ if (on) { const b = sbeEl('sbeMusic'); if (b && b.focus) { try { b.focus(); b.select(); } catch (e) {} } }+ else sbePaintMusicName();+}++function sbePaintMusicName() {+ // `sbeMusicPath`, NOT `sbeMusicName` — the latter is the label painted onto+ // the music BLOCK down on the timeline, and two elements answering to one+ // id is one element and one bug.+ const el = sbeEl('sbeMusicPath');+ if (!el) return;+ const full = String((sbeEl('sbeMusic') || {}).value || '');+ const base = full.split('/').pop() || '';+ el.textContent = base || 'no soundtrack';+ el.title = full || 'No soundtrack yet — press Change… to point at one';+}++// "PROTECTED 4s AGO", or the truth when it is not. Painted from the tick, so+// the number is the real age and not the age it had when something last+// happened to call a setter.+function sbePaintProtected() {+ const el = sbeEl('sbeProtected');+ if (!el) return;+ if (!SBE.open || !SBE.id) { el.hidden = true; return; }+ const age = SBE.backedUpAt ? Math.round((Date.now() - SBE.backedUpAt) / 1000) : null;+ // COLD IS "THERE IS UNSAVED WORK AND THE NET HAS NOT CAUGHT THIS TAB", and+ // it is deliberately the SAME threshold the watchdog alarms on, so the chip+ // and the banner can never disagree. Stated against `backedUpAt` rather than+ // against `dirtyAt`: the outage this exists for froze `dirtyAt` in the past+ // while `backedUpAt` stayed ahead of it, and every test written in terms of+ // that pair read "protected" for seven hours. How long ago the net actually+ // caught this tab cannot be faked by a stuck flag.+ const cold = SBE.dirty && (!SBE.backedUpAt+ || (Date.now() - SBE.backedUpAt) > SBE_SAVE_GRACE_MS);+ let text;+ if (age === null) text = SBE.dirty ? 'not backed up yet' : '';+ else if (age < 60) text = 'protected ' + age + 's ago';+ else text = 'protected ' + Math.round(age / 60) + 'm ago';+ if (cold) text = 'NOT PROTECTED — ' + text;+ // A SECOND EDITOR IS INFORMATION, NEVER A REASON TO STOP. It used to be the+ // reason this tab stopped writing entirely.+ if (SBE.otherEditor) text = (text ? text + ' · ' : '') + 'also open elsewhere';+ el.textContent = text;+ el.hidden = !text;+ el.classList.toggle('is-cold', !!cold);+}++function sbeSetState(text, kind) {+ const el = sbeEl('sbeState');+ if (!el) return;+ sbeEl('sbeStateText').textContent = text;+ el.classList.toggle('is-dirty', kind === 'dirty');+ el.classList.toggle('is-saved', kind === 'saved');+ el.classList.toggle('is-alarm', kind === 'alarm');+ // The dot beside the draft's name agrees with the chip, always — two+ // indicators that can disagree are one indicator and one bug.+ if (typeof sbePaintDraft === 'function') sbePaintDraft();+ if (typeof sbePaintProtected === 'function') sbePaintProtected();+}++function sbeShowDocError(msg) {+ const box = sbeEl('sbeErrors');+ box.hidden = false;+ box.innerHTML = '<b>' + escapeHtml(String(msg)) + '</b>';+ sbeSetState('not saved', 'dirty');+}++// Every mutation goes through here: one undo snapshot, one layout, one repaint,+// one debounced save. Nothing else is allowed to touch SBE.clips, which is why+// undo can be a straight array of snapshots rather than a command log.+// ONE UNDO STEP, WHATEVER MOVED. The stack used to hold a bare array of+// clips, which was true for exactly as long as the arrangement was only+// clips: the soundtrack is an object on the timeline now, and an object you+// cannot ⌘Z is half an object. A snapshot carries both. The array form is+// still accepted on the way back in, because a clip drag takes its own+// snapshot at pointerdown and there is no reason to make it carry audio it+// cannot change.+// THE SNAPSHOT IS OF THE TIMELINE, NOT OF THE DOCUMENT. It used to read+// `SBE.edit.audio`, and `sbeFetchPeaks` deliberately fills `SBE.audio`+// WITHOUT touching the document — a soundtrack discovered from peaks.json is+// on the timeline before the arrangement was ever cut to it. So on a film+// that was Prepared but never auto-edited, the snapshot carried `audio: null`+// and one ⌘Z of any clip edit deleted the track: the block vanished, the+// preview bed went silent, and redo could not bring it back because the redo+// stack had been handed the same null. Only a reload restored it.+function sbeSnapshot(audio) {+ return JSON.stringify({+ clips: SBE.clips,+ // THE LANE IS PART OF THE ARRANGEMENT, so undo and redo cover it. Without+ // this a card placed and then undone would stay on screen while the+ // pictures walked back without it.+ overlays: SBE.overlays || [],+ audio: (audio === undefined)+ ? (SBE.audio || (SBE.edit && SBE.edit.audio) || null) : audio,+ });+}++function sbeRestore(json) {+ const s = JSON.parse(json);+ if (Array.isArray(s)) { SBE.clips = s; return; }+ SBE.clips = s.clips || [];+ // An older snapshot (one taken before the lane existed) carries no+ // `overlays`, and restoring `undefined` over a live lane would delete a+ // card nobody asked to remove — absent means "unchanged", not "empty".+ if (s.overlays !== undefined) SBE.overlays = s.overlays || [];+ SBE.edit = SBE.edit || {};+ // ...and a restore never COMMITS a discovered track into the document. The+ // arrangement owns a soundtrack only once somebody has placed it (see+ // sbeApplyMusic); undoing a trim must not be what saves one.+ if (SBE.edit.audio) SBE.edit.audio = s.audio || null;+ SBE.audio = s.audio || null;+}++// The overlay lane's own door, and it is the same door: one undo step, one+// dirty flag, one queued snapshot. `sbeMutate` works on clips; this works on+// the lane, and both push the SAME snapshot shape so undo walks either.+function sbeOvMutate(fn) {+ const before = sbeSnapshot();+ const res = fn(SBE.overlays || []);+ if (!res || res.ok === false) {+ if (res && res.why) phosToast(res.why, {});+ return false;+ }+ SBE.undo.push(before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.overlays = res.overlays;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+ // The mutation's own result, so a caller that needs to talk ABOUT what it+ // added — the auto-key notice needs the id to be able to undo it — does not+ // have to guess which row is new.+ return res;+}++function sbeOvAddAt(item, at) {+ const res = sbeOvMutate(os => sbeOvAdd(os, item, at));+ if (!res) return null;+ phosToast('Overlay added — it composites over the picture. Drag it along '+ + 'the lane, pull either end for its length, and fade it in from '+ + 'Effects.', { duration: 7000 });+ return res.added || null;+}++// THE ONE PLACE A KEYED OVERLAY GOES BACK TO THE FILE IT CAME FROM.+// "Keep original" is a normal edit — one undo step, one dirty flag — because+// it is a decision the user made, and every other decision in this editor is+// undoable. The original was never modified, so this is a pointer swap.+function sbeOvSetPath(overlays, id, path) {+ const o = sbeOvById(overlays, id);+ if (!o) return { overlays: overlays, ok: false, why: 'gone' };+ const out = overlays.map(x => Object.assign({}, x));+ sbeOvById(out, id).path = path;+ return { overlays: out, ok: true };+}++function sbeOvDeleteSel() {+ if (!SBE.ovSel) return;+ const id = SBE.ovSel;+ const ok = sbeOvMutate(os => sbeOvDelete(os, id));+ if (ok) { SBE.ovSel = ''; sbePaint(); }+}++function sbeMutate(fn) {+ const before = sbeSnapshot();+ const res = fn(SBE.clips);+ if (!res || res.ok === false) {+ if (res && res.why === 'locked') phosToast('That shot is locked.', {});+ else if (res && res.why) phosToast(res.why, {});+ return false;+ }+ SBE.undo.push(before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.clips = res.clips;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+ return true;+}++function sbeUndo() {+ if (!SBE.undo.length) return;+ SBE.redo.push(sbeSnapshot());+ sbeRestore(SBE.undo.pop());+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+}++function sbeRedo() {+ if (!SBE.redo.length) return;+ SBE.undo.push(sbeSnapshot());+ sbeRestore(SBE.redo.pop());+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+}++// NOTHING WRITES THE USER'S DRAFT BUT THE USER. The owner, after losing an+// afternoon to a save he could not see: "it's better that the user has the+// power to manage this feature... he should have control over the saving, and+// only he should have that control. You can keep a backup in case it's+// needed."+//+// So this — the lane every mutation calls — no longer saves. It writes a+// CRASH BACKUP to a file beside the draft, which never lands on edit.json and+// never moves a revision. The Save button is the only thing that writes the+// document he named, and the only thing that can change what he gets back.+function sbeQueueSave() {+ // THE WATCHDOG'S CLOCK IS ARMED FIRST, BEFORE ANY EARLY RETURN CAN SKIP IT.+ // This line used to sit UNDER `if (SBE.superseded) return`, and that one+ // line's position is the whole of a seven-hour outage: once a tab was+ // superseded, `dirtyAt` froze at its last pre-supersede value while+ // `backedUpAt` stayed AHEAD of it, so the 12-second watchdog's+ // `backedUpAt < dirtyAt` test read "this work is backed up" forever and the+ // alarm it exists to raise could never fire. Nothing may be allowed to+ // return from this function without first recording that there is unwritten+ // work and when it appeared.+ if (!SBE.dirtyAt) SBE.dirtyAt = Date.now();+ if (SBE.saveTimer) clearTimeout(SBE.saveTimer);+ SBE.saveTimer = setTimeout(() => { SBE.saveTimer = null; sbeBackup(); }, 1400);+}++// The backup. Same payload the save sends, a different door, and it answers+// to nobody: no expect_revision (it cannot conflict with anything), no adopt+// (it changes nothing on screen), no toast when it works.+// TRUE MEANS "WHAT IS ON SCREEN IS ALSO SOMEWHERE ELSE" — and it is the+// answer callers act on, so every path that does NOT write says false. Three+// of them used to return `undefined`, which `sbeDraftOp` read as fine and+// then cleared `dirty` on.+async function sbeBackup(quiet) {+ if (!SBE.open || !SBE.id) return false;+ // A POST already in flight carries the state it was built from, not the+ // edit that arrived since — so it is not this call landing.+ if (SBE.backingUp) return false;+ // THE LANE NEVER STOPS. It used to refuse while an offer was unanswered —+ // there was exactly ONE backup file per draft, so writing a new one would+ // have destroyed the work the offer was holding. The cure was worse than+ // the disease: a chip nobody dismissed switched the safety net off for the+ // rest of the session, silently. The lane is versioned now (one file per+ // snapshot, pruned), so a new snapshot cannot eat an old one and there is+ // nothing left to guard. See docs/EDITOR_SAVE_MODEL.md §2.+ if (SBE.saveTimer) { clearTimeout(SBE.saveTimer); SBE.saveTimer = null; }+ SBE.backingUp = true;+ let r;+ try {+ const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,+ overlays: SBE.overlays, expect: null });+ // WHICH DRAFT THIS WAS COMPOSED FROM. The server files the backup under+ // the draft that is active when the write LANDS, and this one is+ // debounced — so without the name in the body, a backup of the draft you+ // just left is offered back as the unsaved work of the one you opened.+ body.draft = SBE.activeDraft || '';+ body.session = SBE.session;+ const res = await fetch('/storyboard/edit/backup', {+ method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body) });+ r = await res.json();+ } catch (e) {+ r = { ok: false, error: String(e) };+ } finally {+ SBE.backingUp = false;+ }+ if (r && r.ok) {+ SBE.backedUpAt = Date.now();+ // Somebody else is editing this film too. Worth saying; never worth+ // stopping for.+ const cur = (r.session || {}).token || '';+ SBE.otherEditor = (cur && cur !== SBE.session) ? cur : '';+ sbeSaveAlarmClear();+ sbePaintProtected();+ return true;+ }+ // A REFUSED SNAPSHOT IS THE SAFETY NET OFF, whatever the reason given.+ // `stale_session` used to be handled HERE as a special non-failure: the tab+ // set a flag, cleared the alarm, showed one 9-second toast and never wrote+ // again. The state line it set was overwritten by the very next edit, so a+ // tab that had stopped protecting its user looked completely normal — the+ // same class as the `if (SBE.backup) return false` this file already had to+ // delete. The server no longer refuses on session; if some future build+ // does, it falls through to the alarm below like every other failure, and+ // the alarm does not go away until a write lands.+ // A BACKUP THAT IS NOT BEING WRITTEN IS THE SAFETY NET GONE, and the user+ // cannot tell by looking. It is the same alarm because it is the same+ // sentence: what is on screen is not anywhere else.+ sbeSaveAlarm('the crash backup is not being written (' ++ ((r && r.error) || 'the panel did not answer') ++ ') — press Save');+ return false;+}++// THE OUTER HALF OF SAVING, AND IT EXISTS BECAUSE OF A REAL LOSS. The owner+// cut for twenty minutes and nothing reached the disk: edit.json sat frozen+// while he kept working, and the only thing on screen that knew was a small+// grey chip. Two defects made that possible and both are closed here.+//+// ONE — `if (SBE.saving) return` DROPPED THE SAVE. A debounced save that+// arrived while another was in flight simply vanished: `SBE.dirty` stayed+// true, no timer was left pending, and that edit was never written again+// unless the user happened to touch the film once more. Now it is remembered+// and re-queued the moment the one in flight lands.+//+// TWO — THE FLAG COULD STICK. `SBE.saving = false` sat on the happy path,+// after code that can throw (the payload is built before the fetch). One+// throw and the editor stops saving FOREVER, silently, for the rest of the+// session. `finally` is the whole fix, and it is the difference between an+// error and a lost afternoon.+async function sbeSave(quiet, force) {+ if (!SBE.open) return;+ // WHAT KIND OF WRITE IS PENDING, not just that one is. `sbeQueueSave` no+ // longer saves — it schedules a crash BACKUP — so remembering a dropped+ // save as a bare `true` and re-queuing through that lane turned the second+ // of two rapid Save presses into a backup write, leaving edit.json at the+ // older revision with the alarm reading clear.+ if (SBE.saving) { SBE.savePending = quiet ? 'backup' : 'save'; return 'busy'; }+ if (SBE.saveTimer) { clearTimeout(SBE.saveTimer); SBE.saveTimer = null; }+ SBE.saving = true;+ let ok = false;+ try {+ ok = await sbeSaveInner(quiet, force);+ } catch (e) {+ // A throw here is the case that used to wedge the flag. It is also the+ // one nothing on screen could have told you about.+ sbeSaveAlarm('the editor could not build the save (' ++ ((e && e.message) || String(e)) + ')');+ } finally {+ SBE.saving = false;+ const again = SBE.savePending;+ SBE.savePending = false;+ if (again && SBE.dirty && !SBE.conflict) {+ if (again === 'save') sbeSave(quiet, force);+ else sbeQueueSave();+ }+ }+ return ok;+}++// THE ALARM. A save that is not happening is not a status, it is an+// emergency: everything on screen is about to be lost and only this says so.+// It survives until a save actually lands — no timeout, no fade — because the+// failure it reports survives too.+function sbeSaveAlarm(why) {+ SBE.saveFailed = why || 'the panel did not store your changes';+ const box = sbeEl('sbeAlarm');+ if (box) {+ box.hidden = false;+ sbeEl('sbeAlarmWhy').textContent = SBE.saveFailed;+ }+ sbePaintNotices();+ sbeSetState('NOT SAVED', 'alarm');+}++function sbeSaveAlarmClear() {+ if (!SBE.saveFailed) return;+ SBE.saveFailed = '';+ const box = sbeEl('sbeAlarm');+ if (box) box.hidden = true;+ if (SBE.noticeLead === 'sbeAlarm') SBE.noticeLead = '';+ sbePaintNotices();+}++async function sbeSaveInner(quiet, force) {+ const order = SBE.clips.map(c => c.id);+ SBE.sentOrder = order;+ const body = sbeSaveBody({ id: SBE.id, edit: SBE.edit, clips: SBE.clips,+ overlays: SBE.overlays,+ expect: force ? null : SBE.revision });+ let r;+ try {+ const res = await fetch('/storyboard/edit/save', {+ method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body) });+ r = await res.json();+ r._status = res.status;+ } catch (e) {+ r = { ok: false, error: String(e), _status: 0 };+ }+ if (r.ok) {+ SBE.errors = {};+ sbeEl('sbeErrors').hidden = true;+ // Adopt the server's copy of the document, but NOT its clip array — the+ // user may have moved something in the milliseconds the save was in+ // flight, and throwing that away is the one thing an editor must never do.+ SBE.edit = Object.assign({}, r.edit || {}, { clips: SBE.edit.clips || [] });+ SBE.revision = sbeNum((r.edit || {}).revision, SBE.revision + 1);+ SBE.unplaced = r.unplaced || [];+ SBE.prepare = r.prepare || SBE.prepare;+ SBE.dirty = false;+ SBE.conflict = 0;+ sbeEl('sbeConflict').hidden = true;+ sbePaintNotices();+ SBE.dirtyAt = 0;+ // A SAVE IS THE USER ANSWERING THE OFFER. The server deletes the backup+ // on a successful save, so this follows it rather than deciding on its+ // own — and clearing it is what brings the crash lane back to life:+ // sbeBackup refuses to write while an offer is unanswered, so a film that+ // opened with one used to lose its safety net for the whole session and+ // then be told, every twelve seconds, that saving was failing.+ SBE.backup = r.backup || null;+ SBE.backupHidden = false; // a NEW offer is not the one dismissed+ sbePaintRecovery();+ // The drafts rows carry clip counts and "saved N min ago" — the first+ // thing a user checks after saving is the panel that reports on saving.+ if (r.drafts) { SBE.drafts = r.drafts; sbePaintDraft(); }+ sbeSaveAlarmClear();+ sbeSetState('saved · revision ' + SBE.revision, 'saved');+ sbePaint();+ return true;+ }+ if (r._status === 409 && r.conflict) {+ // Honest, and it does not choose for you: another tab is ahead, your+ // arrangement is still on this screen, and both ways out are one click.+ SBE.conflict = sbeNum(r.revision, 0);+ sbeEl('sbeConflict').hidden = false;+ sbePaintNotices();+ sbeEl('sbeConflictText').textContent =+ 'Another tab saved this timeline (it is at revision ' + SBE.conflict ++ ', you started from ' + SBE.revision + '). Nothing here has been lost.';+ sbeSaveAlarm('another tab is at revision ' + SBE.conflict ++ ' and this one is not being stored — choose which arrangement wins');+ return false;+ }+ if (Array.isArray(r.errors) && r.errors.length) {+ SBE.errors = sbeErrorsByClip(r.errors, order);+ SBE.errors.all = r.errors || [];+ sbeRenderErrors(r.errors);+ sbeSaveAlarm(r.errors.length + ' problem' + (r.errors.length === 1 ? '' : 's') ++ ' in the timeline — nothing was written');+ sbePaint();+ return false;+ }+ // LOUD WHETHER OR NOT ANYBODY ASKED. This branch used to be silent for the+ // autosave — `if (!quiet)` — which is precisely the path that runs while+ // somebody is working and precisely the path that lost twenty minutes.+ sbeSaveAlarm(r.error || 'the panel did not answer the save');+ if (!quiet) phosToast(r.error || 'Could not save the timeline.', { kind: 'danger' });+ return false;+}++function sbeRenderErrors(errors) {+ const box = sbeEl('sbeErrors');+ if (!errors || !errors.length) {+ box.hidden = true; box.innerHTML = '';+ if (SBE.noticeLead === 'sbeErrors') SBE.noticeLead = '';+ sbePaintNotices();+ return;+ }+ box.hidden = false;+ // THE FIRST SENTENCE, THEN THE REST ON REQUEST. Nine clips failing the same+ // rule printed nine lines of the same sentence and pushed the timeline off+ // the screen; the one thing the reader needs is what is wrong and how many+ // are wrong with it.+ const rest = errors.length - 1;+ box.innerHTML = '<b>The timeline was not saved.</b><ul>' ++ errors.map((e, i) => '<li' + (i && !SBE.errsOpen ? ' hidden' : '') + '>' ++ escapeHtml(e.message || e.code || '') + '</li>').join('') ++ '</ul>' ++ (rest > 0+ ? '<button type="button" class="ghost-btn" onclick="sbeErrsToggle()">'+ + (SBE.errsOpen ? 'Show less' : escapeHtml('and ' + rest + ' more'))+ + '</button>'+ : '');+ sbePaintNotices();+}++function sbeErrsToggle() {+ SBE.errsOpen = !SBE.errsOpen;+ sbeRenderErrors(SBE.errors && SBE.errors.all);+}++async function sbeTakeTheirs() {+ SBE.conflict = 0;+ SBE.dirty = false;+ sbeEl('sbeConflict').hidden = true;+ sbePaintNotices();+ await sbeLoad();+ phosToast('Loaded the other tab\'s arrangement.', {});+}++async function sbeForceSave() {+ const ok = await sbeSave(false, true);+ if (ok) phosToast('Saved over the other tab\'s version.', { kind: 'success' });+}++// ---------------------------------------------------------------------------+// SAVE, SAID OUT LOUD — and the versions behind it+// ---------------------------------------------------------------------------+// The autosave stays SILENT: it fires a second after every drag, and a toast+// on each one would be a notification storm that teaches you to ignore+// notifications. The button is the opposite — it is pressed by somebody who+// wants to be told it worked, so it says which revision they now have.+async function sbeSaveNow() {+ const ok = await sbeSave(false);+ if (ok) {+ phosToast('Saved — revision ' + SBE.revision, { kind: 'success' });+ } else if (ok === 'busy') {+ // Two very different reasons used to arrive as the same `undefined`, and+ // this is the one where telling somebody their work needed no saving is+ // exactly wrong: it is unwritten and a save is on its way.+ phosToast('A save is already on its way — this one will follow it.', {});+ } else if (ok === undefined) {+ phosToast('Nothing to save yet.', {});+ }+}++// "4 minutes ago", in the smallest unit that still reads as a duration. Pure,+// and `now` is a parameter so the gate is not a clock race.+function sbeAgo(when, now) {+ const t = sbeNum(when, 0);+ if (!t) return '';+ const d = Math.max(0, sbeNum(now, Date.now() / 1000) - t);+ if (d < 45) return 'just now';+ if (d < 5400) return Math.round(d / 60) + ' min ago';+ if (d < 172800) return Math.round(d / 3600) + ' h ago';+ return Math.round(d / 86400) + ' d ago';+}++// One row of the picker, as the two strings it shows. Pure so the wording is+// a gate rather than something to squint at in a screenshot.+function sbeVersionLine(v, now) {+ const row = v || {};+ // THE FALLBACK FOLLOWS THE LANE. The split exists to separate the user's+ // decisions from the machine's, and then labelled his decisions with the+ // machine's word: the lane headed YOUR SAVES OF THIS DRAFT listed rows+ // called "autosave", which is the one word that means "not yours".+ const name = row.label ? String(row.label)+ : (row.readable === false ? 'unreadable'+ : (row.manual ? 'Save' : 'autosave'));+ const bits = [];+ if (row.revision !== null && row.revision !== undefined) {+ bits.push('revision ' + sbeNum(row.revision, 0));+ }+ if (row.clips !== null && row.clips !== undefined) {+ bits.push(sbeNum(row.clips, 0) + (sbeNum(row.clips, 0) === 1 ? ' clip' : ' clips'));+ }+ if (sbeNum(row.duration, 0) > 0) bits.push(sbeFmtTime(row.duration));+ const ago = sbeAgo(row.archived_at || row.saved_at, now);+ if (ago) bits.push(ago);+ return { name: name, meta: bits.join(' · '),+ kept: !!row.kept, bad: row.readable === false };+}++function sbeVersionsEl() {+ const el = sbeEl('sbeVersions');+ // PORTAL, on first open. The header and the stage column both carry+ // overflow, so a panel left where it was declared is sliced at their edge.+ if (el && el.parentElement !== document.body) document.body.appendChild(el);+ return el;+}++function sbeVersionsClose() {+ const el = sbeEl('sbeVersions');+ if (el) el.hidden = true;+}++async function sbeVersionsOpen(focusName) {+ if (!SBE.open || !SBE.id) {+ phosToast('Open a __SEQ__ first — versions belong to a timeline.', {});+ return;+ }+ const el = sbeVersionsEl();+ if (!el) return;+ // A SECOND PRESS CLOSES IT. Every other popover in this panel toggles;+ // this one re-positioned itself and fired another /versions fetch.+ const from = focusName ? 'keep' : 'vers';+ if (!el.hidden && el.dataset.from === from) { sbeVersionsClose(); return; }+ el.dataset.from = from;+ const trig = sbeEl(focusName ? 'sbeKeepBtn' : 'sbeVersBtn');+ const r = trig ? trig.getBoundingClientRect() : { bottom: 60, right: 400 };+ el.hidden = false;+ el.style.top = (r.bottom + 6) + 'px';+ el.style.left = Math.max(8, Math.min(window.innerWidth - 408,+ r.right - 400)) + 'px';+ if (focusName) {+ const q = sbeEl('sbeVersName');+ if (q && q.focus) { try { q.focus(); q.select(); } catch (e) {} }+ }+ await sbeVersionsLoad();+}++async function sbeVersionsLoad() {+ const list = sbeEl('sbeVersList');+ if (list) list.innerHTML = '<div class="sbe-vers-empty">Reading the history…</div>';+ let r;+ try {+ r = await (await fetch('/storyboard/edit/versions?id=' ++ encodeURIComponent(SBE.id))).json();+ } catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ if (list) {+ list.innerHTML = '<div class="sbe-vers-empty">' ++ escapeHtml((r && r.error) || 'could not read this __SEQ__\'s history') ++ '</div>';+ }+ return;+ }+ sbeVersionsPaint(r.versions || [], sbeNum(r.keep, 50));+}++function sbeDraftsPaint() {+ const list = sbeEl('sbeDraftList');+ if (!list) return;+ const rows = SBE.drafts || [];+ list.innerHTML = '<div class="sbe-vers-head">This __SEQCAP__\'s drafts</div>' ++ rows.map(d => {+ const meta = [sbeNum(d.clips, 0) + ' clip' + (sbeNum(d.clips, 0) === 1 ? '' : 's')];+ if (sbeNum(d.duration, 0) > 0) meta.push(sbeFmtTime(d.duration));+ if (d.saved_at) meta.push('saved ' + sbeAgo(d.saved_at));+ else meta.push('never saved');+ return '<div class="sbe-vers-row' + (d.active ? ' is-active' : '') + '">' ++ '<span class="sbe-vr-main">' ++ '<span class="sbe-vr-name">' + escapeHtml(d.name) ++ (d.active ? ' · open' : '') + '</span>' ++ '<div class="sbe-vr-meta">' + escapeHtml(meta.join(' · ')) + '</div>' ++ '</span>' ++ (d.active ? '' : '<button type="button" class="ghost-btn" data-op="open" data-slug="' ++ escapeHtml(d.slug) + '" data-name="' + escapeHtml(d.name) + '">Open</button>') ++ '<button type="button" class="ghost-btn" data-op="dup" data-slug="' ++ escapeHtml(d.slug) + '" data-name="' + escapeHtml(d.name) + '">Copy</button>' ++ '<button type="button" class="ghost-btn" data-op="rename" data-slug="' ++ escapeHtml(d.slug) + '" data-name="' + escapeHtml(d.name) + '">Rename</button>' ++ (rows.length > 1 ? '<button type="button" class="ghost-btn" data-op="del" data-slug="' ++ escapeHtml(d.slug) + '" data-name="' + escapeHtml(d.name) + '">Delete</button>' : '') ++ '</div>';+ }).join('');+ list.querySelectorAll('button[data-op]').forEach(b => {+ b.addEventListener('click', () => {+ const slug = b.dataset.slug, name = b.dataset.name;+ if (b.dataset.op === 'open') sbeDraftOpen(slug, name);+ else if (b.dataset.op === 'dup') sbeDraftDuplicate(slug, name);+ else if (b.dataset.op === 'rename') sbeDraftRename(slug, name);+ else sbeDraftDelete(slug, name, b);+ });+ });+}++function sbeVersionsPaint(rows, keep) {+ const list = sbeEl('sbeVersList');+ const note = sbeEl('sbeVersNote');+ sbeDraftsPaint();+ if (note) {+ note.textContent = 'Save writes the draft — nothing else does. Below are ' ++ 'this draft\'s past saves: every Save keeps the one before it, the last ' ++ keep + ' of them, and Restore keeps what it replaces.';+ }+ if (!list) return;+ if (!rows.length) {+ list.innerHTML = '<div class="sbe-vers-head">Past saves of this draft</div>' ++ '<div class="sbe-vers-empty">None yet — the second Save writes the ' ++ 'first one.</div>';+ return;+ }+ const now = Date.now() / 1000;+ // HIS DECISIONS FIRST. "The auto saves should be saved separately from the+ // manual saves, at least, so the user can go back and see the manual+ // saves." The automatic lane is real history and stays reachable — it is+ // just not what somebody walking back through their own work is looking+ // for, and a wall of debounce noise buries the four saves that matter.+ const mine = rows.filter(v => v.manual !== false);+ const auto = rows.filter(v => v.manual === false);+ const draw = (v) => {+ const line = sbeVersionLine(v, now);+ return '<div class="sbe-vers-row' + (line.kept ? ' is-kept' : '') ++ (line.bad ? ' is-bad' : '') + '">' ++ '<span class="sbe-vr-main">' ++ '<span class="sbe-vr-name">' + escapeHtml(line.name) + '</span>' ++ '<div class="sbe-vr-meta">' + escapeHtml(line.meta) + '</div>' ++ '</span>' ++ (line.bad ? '' :+ '<button type="button" class="ghost-btn" data-file="' ++ escapeHtml(v.file) + '">Restore</button>') ++ '</div>';+ };+ list.innerHTML =+ '<div class="sbe-vers-head">Your saves of this draft ' ++ '<span>type a name above and press Keep to mark one</span></div>' ++ (mine.length ? mine.map(draw).join('')+ : '<div class="sbe-vers-empty">None yet — press Save.</div>') ++ (auto.length+ ? '<details class="sbe-vers-auto"><summary>' + auto.length ++ ' automatic snapshot' + (auto.length === 1 ? '' : 's') + '</summary>' ++ auto.map(draw).join('') + '</details>'+ : '');+ list.querySelectorAll('button[data-file]').forEach(b => {+ b.addEventListener('click', () => sbeRestoreVersion(b.dataset.file));+ });+}++// ---- the drafts, as verbs -------------------------------------------------+// Every one of these lands through the SAME door — POST edit/draft — because+// they are five edits to one index, and five routes would be five places for+// the active pointer to end up wrong. Each answers with the whole read+// payload, so the client adopts a document rather than reasoning about one.+async function sbeDraftOp(op, extra, note) {+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ fd.set('op', op);+ for (const k in (extra || {})) fd.set(k, String(extra[k]));+ // The draft on screen is about to stop being the active one. Its unsaved+ // work goes to its backup first — the server moves the SAVED file, and+ // without this the last few minutes would be left pointing at a draft+ // nobody is looking at any more.+ //+ // AND THE ANSWER IS CHECKED. The invariant this call exists for is the one+ // line above; ignoring its result meant the switch went ahead anyway, then+ // cleared `dirty` and adopted the server's document — while `activate_draft`+ // stashes the last SAVED file, so the work on screen went with no offer, no+ // toast and nothing to click.+ if (SBE.dirty && !SBE.conflict && !(await sbeBackup(true))) {+ phosToast('This draft has unsaved changes that could not be snapshotted. ' ++ 'Press Save first — switching now would leave them behind.',+ { kind: 'danger', duration: 8000 });+ return false;+ }+ let r;+ try { r = await (await fetch('/storyboard/edit/draft', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'That draft action did not work.', { kind: 'danger' });+ return false;+ }+ sbeNameMode('');+ if (op !== 'rename') {+ SBE.undo.length = 0; SBE.redo.length = 0;+ SBE.dirty = false; SBE.dirtyAt = 0;+ sbeAdopt(r, true);+ } else {+ SBE.drafts = r.drafts || SBE.drafts;+ sbePaintDraft();+ }+ await sbeVersionsLoad();+ if (note) phosToast(note(r), { kind: 'success', duration: 5000 });+ return true;+}++// ONE FIELD, AND IT KNOWS WHICH VERB IT IS. Enter used to be hard-wired to+// "new draft", so pressing Rename on a row, typing, and pressing Enter — the+// obvious gesture — created a duplicate draft carrying the half-edited name+// instead of renaming anything.+function sbeNameEnter() {+ if (SBE.renaming) return sbeDraftRename(SBE.renaming, '');+ return sbeDraftNew(true);+}++function sbeNameMode(slug) {+ SBE.renaming = slug || '';+ const btn = sbeEl('sbeVersKeep');+ if (btn) {+ btn.textContent = SBE.renaming ? 'Rename' : 'Copy';+ btn.title = SBE.renaming+ ? 'Rename the draft — the timeline is not touched'+ : 'A new draft holding a copy of the timeline on screen';+ }+}++function sbeDraftNew(fromCurrent) {+ const box = sbeEl('sbeVersName');+ const name = String((box && box.value) || '').trim();+ if (!name) {+ phosToast('Give the draft a name — that is how you get back to it.', {});+ if (box && box.focus) { try { box.focus(); } catch (e) {} }+ return;+ }+ sbeNameMode('');+ if (box) box.value = '';+ return sbeDraftOp('new', { name: name, from: fromCurrent ? 'current' : 'empty' },+ () => 'Working on "' + name + '" now. ' ++ (fromCurrent ? 'It holds a copy of the cut you were on.'+ : 'Empty timeline, same soundtrack.'));+}++function sbeDraftDuplicate(slug, name) {+ return sbeDraftOp('duplicate', { slug: slug },+ r => 'Copied "' + name + '" — you are on the copy now.');+}++function sbeDraftOpen(slug, name) {+ return sbeDraftOp('activate', { slug: slug },+ () => 'Opened "' + name + '".');+}++function sbeDraftRename(slug, was) {+ // The panel's own input, reused: a rename is a name, and names in this app+ // are typed into panel controls, never into a browser dialog.+ const box = sbeEl('sbeVersName');+ const name = String((box && box.value) || '').trim();+ if (!name) {+ // ARMED, NOT JUST ASKED. The field is prefilled and SELECTED, and the+ // panel remembers which row it belongs to — the old order focused first+ // and wrote the value after, so the caret sat behind the old name and+ // typing appended to it.+ phosToast('Edit the name above, then press Rename.', {});+ sbeNameMode(slug);+ if (box) {+ box.value = was || '';+ try { box.focus(); box.select(); } catch (e) {}+ }+ return;+ }+ sbeNameMode('');+ if (box) box.value = '';+ return sbeDraftOp('rename', { slug: slug, name: name },+ () => 'Renamed to "' + name + '".');+}++// The verb the drafts rewrite dropped. It names the save ALREADY ON DISK —+// no revision bump, no write to edit.json, nothing about the timeline+// changes, which is exactly why it is safe to press at any moment.+async function sbeKeepVersion() {+ const box = sbeEl('sbeVersName');+ const label = String((box && box.value) || '').trim();+ if (!label) {+ phosToast('Type a name for this save first — that is what makes it one ' ++ 'you can find again.', {});+ if (box && box.focus) { try { box.focus(); } catch (e) {} }+ return;+ }+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ fd.set('label', label);+ let r;+ try { r = await (await fetch('/storyboard/edit/version', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'That save could not be named.', { kind: 'danger' });+ return;+ }+ sbeNameMode('');+ if (box) box.value = '';+ if (r.already) {+ phosToast('That save already has a name — nothing was changed.', {});+ } else {+ phosToast('Kept "' + label + '" — revision ' + sbeNum(r.revision, 0) ++ '. The fifty-save prune will never take it.',+ { kind: 'success', duration: 5000 });+ }+ await sbeVersionsLoad();+}++// A DESTRUCTIVE ACTION ASKS IN THE PANEL'S OWN VOICE. This used to be a+// `window.confirm` — a Chrome-chrome modal in the middle of a claude.ai-grade+// surface, and the only piece of UI in this feature that was not the app's+// own. Its sibling `sbeDraftRename` carries the comment saying so, and the+// test enforcing it named only `window.prompt`, which is how the confirm+// walked past. Two clicks, four seconds to change your mind.+function sbeDraftDelete(slug, name, btn) {+ if (btn && btn.dataset && btn.dataset.armed !== '1') {+ btn.dataset.armed = '1';+ btn.dataset.was = btn.textContent;+ btn.textContent = 'Delete?';+ btn.title = 'Press again to delete "' + name + '". Its past saves go with '+ + 'it; the other drafts are untouched.';+ btn.classList.add('is-danger');+ setTimeout(() => {+ if (!btn.dataset || btn.dataset.armed !== '1') return;+ btn.dataset.armed = '';+ btn.textContent = btn.dataset.was || 'Delete';+ btn.classList.remove('is-danger');+ }, 4000);+ return;+ }+ return sbeDraftOp('delete', { slug: slug }, () => 'Deleted "' + name + '".');+}++// The draft's name IS the button, so which document is being cut is on screen+// without asking; the dot is the whole of "not saved yet".+function sbePaintDraft() {+ const row = (SBE.drafts || []).filter(d => d.active)[0];+ const el = sbeEl('sbeDraftName');+ // "Draft 2 of 3", not "Draft 2": the chip is the ONE place this __SEQ__ says+ // how many drafts it has, now that the Drafts button is inside the ⋯ menu.+ // Without the count the chip reads as a label rather than as a door.+ const n = (SBE.drafts || []).length;+ if (el) {+ el.textContent = ((row && row.name) || 'Draft')+ + (n > 1 ? ' of ' + n : '');+ }+ const dot = sbeEl('sbeDraftDot');+ if (dot) dot.hidden = !SBE.dirty;+ const btn = sbeEl('sbeKeepBtn');+ if (btn) {+ btn.title = SBE.dirty+ ? 'Unsaved changes in "' + ((row && row.name) || 'this draft') ++ '" — press Save to store them'+ : 'Draft "' + ((row && row.name) || '') + '" — saved';+ }+}++// The offer, never the action.+// WHICH ONE IS OPEN. Urgency order, and it is not the DOM order: a conflict+// means two tabs are fighting over the file and every other message is about+// the file you are about to lose; the alarm means nothing is being stored at+// all; the validation list means this particular save did not land; the+// recovery offer is a question about last session and can wait behind all+// three. `SBE.noticeLead` is the user overriding that — clicking a chip opens+// it — and it is cleared the moment that notice goes away.+// `sbeKeyed` sits last on purpose: it reports something that ALREADY WORKED —+// a card was made usable — so it is the one notice on this screen that is never+// a question, and it must not out-rank a save that is failing.+const SBE_NOTICE_ORDER = ['sbeConflict', 'sbeAlarm', 'sbeErrors', 'sbeRecover',+ 'sbeKeyed'];++function sbePaintNotices() {+ const wrap = sbeEl('sbeNotices');+ if (!wrap || !wrap.classList) return;+ const open = SBE_NOTICE_ORDER.filter(id => {+ const el = sbeEl(id);+ return el && el.hidden === false;+ });+ wrap.hidden = !open.length;+ // A QUIET NOTICE IS A CHIP EVEN WHEN IT IS ALONE. The snapshot offer is an+ // invitation to go and look, not a question that must be answered before the+ // film can be worked on — so it never takes the width, and it never becomes+ // the lead unless the user clicks it open.+ const loud = open.filter(id => !((sbeEl(id).dataset || {}).quiet));+ let lead = open.indexOf(SBE.noticeLead) >= 0 ? SBE.noticeLead : loud[0];+ for (const id of SBE_NOTICE_ORDER) {+ const el = sbeEl(id);+ if (!el || !el.classList) continue;+ // A LONE NOTICE IS NEVER A CHIP. Folding the only thing on screen would+ // hide the sentence to save room nothing else is asking for — and a+ // notice that is not up at all is not a chip either, or the class outlives+ // the message and the next one to open arrives already folded.+ const fold = open.indexOf(id) >= 0 && id !== lead+ && (open.length > 1 || !!((el.dataset || {}).quiet));+ el.classList.toggle('is-folded', fold);+ }+ return lead;+}++// Clicking a folded chip promotes it. Bound on the CONTAINER, so it survives+// every repaint of the children and needs no rebinding anywhere.+function sbeNoticeOpen(id) {+ SBE.noticeLead = id;+ sbePaintNotices();+}++function sbeNoticeClick(ev) {+ const chip = ev.target.closest ? ev.target.closest('.is-folded') : null;+ if (!chip || !chip.id) return;+ ev.preventDefault();+ sbeNoticeOpen(chip.id);+}++// "Later" — hide the recovery offer for this session without answering it.+// Discard DELETES the backup, so it was never the button for "not now".+function sbeNoticeLater() {+ SBE.backupHidden = true;+ sbePaintRecovery();+}++function sbePaintRecovery() {+ const bar = sbeEl('sbeRecover');+ if (!bar) return;+ const b = SBE.backup;+ bar.hidden = !b || !!SBE.backupHidden;+ if (bar.hidden) { sbePaintNotices(); return; }+ // WHAT IT IS, NOT WHAT TO DO ABOUT IT. The old sentence read out both clip+ // counts and then declared that nothing had changed — a question about a+ // difference it could not name, over a document that had loaded correctly.+ // This says when, and how big, and leaves the decision where versions live.+ sbeEl('sbeRecoverWhat').textContent =+ 'from ' + sbeAgo(b.at) + ' · ' + sbeNum(b.clips, 0) + ' clips · ' ++ sbeFmtTime(b.duration) + ' — your saved draft is untouched.';+ sbePaintNotices();+}++async function sbeRecover() {+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ let r;+ try { r = await (await fetch('/storyboard/edit/recover', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'That backup could not be recovered.', { kind: 'danger' });+ return;+ }+ SBE.undo.length = 0; SBE.redo.length = 0;+ SBE.dirty = false; SBE.dirtyAt = 0;+ sbeAdopt(r, true);+ phosToast('Recovered — ' + SBE.clips.length + ' clip(s). The draft it ' ++ 'replaced was kept in this draft\'s history.',+ { kind: 'success', duration: 6000 });+}++async function sbeDiscardBackup() {+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ try { await fetch('/storyboard/edit/discard-backup', { method: 'POST', body: fd }); }+ catch (e) {}+ SBE.backup = null;+ sbePaintRecovery();+}++async function sbeRestoreVersion(file) {+ if (!file) return;+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ fd.set('file', file);+ // The arrangement on screen is about to be replaced, so it goes to disk+ // first — the server archives what it overwrites, and an unsaved drag would+ // otherwise be the one thing in this feature that history could not keep.+ // Checked, for the same reason `sbeDraftOp` checks its backup: if the save+ // 409s or errors the server archives the OLD document, restore overwrites,+ // and the work goes with the undo stack that could have brought it back.+ if (SBE.dirty && !SBE.conflict && !(await sbeSave(true))) {+ phosToast('Your current arrangement could not be saved, so restoring ' ++ 'would lose it. Fix the save first.',+ { kind: 'danger', duration: 8000 });+ return;+ }+ let r;+ try { r = await (await fetch('/storyboard/edit/restore', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'That version could not be restored.', { kind: 'danger' });+ return;+ }+ SBE.undo.length = 0; SBE.redo.length = 0;+ sbeAdopt(r, true);+ sbeVersionsPaint(r.versions || [], 50);+ phosToast('Restored — ' + (SBE.clips.length) + ' clip(s), ' ++ sbeFmtTime(sbeFilmDuration(SBE.clips)) ++ '. The arrangement it replaced was kept.',+ { kind: 'success', duration: 6000 });+}++// ---------------------------------------------------------------------------+// PAINT+// ---------------------------------------------------------------------------+function sbeSpan() {+ // THE SCROLLER RUNS PAST THE LAST FRAME. The ruler is drawn against the+ // longer of the film and the soundtrack — and then past both, by the slack+ // above, because "the film's length and the audio's placement are+ // independent facts". Without the tail the music could not be dragged one+ // second beyond the final cut: there was no timeline out there to drag it+ // onto. The old `film + 120` ceiling is gone with it; it capped the RULER+ // while the waveform kept going, so the far end of a long track was drawn+ // and unreachable at the same time.+ const film = sbeFilmDuration(SBE.clips);+ const w = sbeMusicWindow(SBE.audio, SBE.peaks ? SBE.peaks.duration : 0);+ const music = (w.film_end === null) ? w.film_start : w.film_end;+ const base = Math.max(film, music, 0);+ const slack = Math.min(SBE_SLACK_MAX,+ Math.max(SBE_SLACK_MIN, base * SBE_SLACK_RATIO));+ return Math.max(SBE_SPAN_MIN, base + slack);+}++function sbePx(t) { return sbeNum(t) * SBE.pps; }++function sbePaint() {+ if (!SBE.open) return;+ const span = sbeSpan();+ // NEVER FURTHER OUT THAN "THE WHOLE FILM". The floor moves with the window+ // and with the film's length, so widening the window re-fits instead of+ // leaving a strip of empty track on the right, and the slider's left end+ // keeps meaning what it says.+ const floor = sbeZoomMin();+ if (SBE.pps < floor) SBE.pps = floor;+ const width = Math.max(320, Math.ceil(span * SBE.pps) + SBE_TL_PAD);+ const inner = sbeEl('sbeInner');+ if (!inner) return;+ inner.style.width = width + 'px';+ sbePaintRuler(span, width);+ sbePaintWave(span, width);+ sbePaintMusic(width);+ sbePaintOverlays();+ sbePaintTrack();+ sbePaintAudioLane();+ sbePaintHead();+ sbePaintInspector();+ sbePaintHeads();+ sbePaintMix();+ sbePaintKeys();+ sbePaintChrome();+ // AN EDIT MOVES THE GROUND. Every mutation, undo, redo and adopt lands+ // here, so this is the one place that cannot be forgotten. Unforced: the+ // slip tolerance keeps a drag from re-seeking sixty times a second.+ sbeStripSync();+ // LAST, and after the inspector: the row's budget is what the column has+ // left once everything else has been laid out, and the inspector is the+ // one that changes height when a clip is selected.+ sbeFitMonitors();+}++// Measure, then size. Everything in the cut column except the monitor row and+// the timeline is read off the DOM here; the timeline is counted at the height+// it is ENTITLED to rather than at its live height, because it is the row that+// absorbs whatever is left over — reading it would make this function its own+// input and the two would oscillate. That entitlement used to be the CSS floor+// and is now the user's own number, which is the whole of the resize handle:+// nothing is resized, one term of this subtraction moved.+function sbeFitMonitors() {+ const row = sbeEl('sbeMonitors');+ const col = sbeEl('edStage');+ const plan = sbeEl('sbTimeline');+ if (!row || !col || !plan || plan.hidden) return;+ // Inside the stacking breakpoint the PAGE is the scroller and the column+ // has no fixed height to budget against, so the CSS there is the answer.+ if (window.matchMedia && window.matchMedia('(max-width: 900px)').matches) {+ for (const p of ['--sbe-prog-h', '--sbe-src-h', '--sbe-rail-w', '--sbe-row-h']) {+ row.style.removeProperty(p);+ }+ // The lanes go back to their CSS heights too — a stacked page has no+ // column to take the height from, and the handle is display:none there.+ for (const p of ['--sbe-tl-h', '--sbe-ov-h', '--sbe-track-h',+ '--sbe-alane-h', '--sbe-wave-h']) {+ plan.style.removeProperty(p);+ }+ return;+ }+ const gap = parseFloat(getComputedStyle(plan).rowGap) || 8;+ let used = 0, shown = 0;+ for (const kid of plan.children) {+ const h = kid.getBoundingClientRect().height;+ if (!h && kid !== row) continue;+ shown++;+ if (kid === row) continue;+ used += (kid.id === 'sbeTlWrap') ? 0 : h;+ }+ // A monitor column is taller than its picture by its own label bar and the+ // gap above it. Read off the PROGRAM column, not the row: the row's height+ // is the thing being solved for, and reading that would be a circle. The+ // bar has a fixed min-height and does not wrap, so this is a constant.+ const prog = sbeEl('sbeStage');+ const col2 = prog ? prog.parentElement : null;+ const chrome = (prog && col2)+ ? Math.max(0, Math.round(col2.getBoundingClientRect().height -+ prog.getBoundingClientRect().height))+ : 30;+ // WHAT THE TWO OF THEM HAVE TO SHARE, and then the split. The ceiling on+ // the timeline's share is the one clamp that keeps this honest: whatever the+ // handle was dragged to, the monitors keep SBE_MON_MIN_H — a 120px picture+ // is small but it is still a picture, and it is the same floor sbeMonitorFit+ // has always refused to go under.+ const avail = col.clientHeight - used - gap * Math.max(0, shown - 1) - chrome;+ SBE.tlMax = Math.max(SBE_TL_MIN_H,+ Math.min(SBE_TL_MAX_H, Math.round(avail - SBE_MON_MIN_H)));+ // The PREFERENCE is never overwritten by a window that cannot honour it —+ // shrink the browser and the timeline gives the height back; widen it again+ // and the drag the user made is still there.+ const want = sbeTlClamp(SBE.tlH, SBE.tlMax);+ const budget = avail - want;+ const apply = (b) => {+ const fit = sbeMonitorFit(row.clientWidth, b);+ row.style.setProperty('--sbe-prog-h', Math.round(fit.progH) + 'px');+ row.style.setProperty('--sbe-src-h', Math.round(fit.srcH) + 'px');+ row.style.setProperty('--sbe-rail-w', Math.round(fit.rail) + 'px');+ row.style.setProperty('--sbe-row-h', Math.round(fit.progH + chrome) + 'px');+ // A 16:9 PAIR IS USUALLY WIDTH-LIMITED, so the monitors routinely decline+ // part of the budget they were offered. That leftover has always gone to+ // the timeline — it is the flex row — but it went entirely onto the+ // picture track, which is capped at 240 and then wastes it. Handing it to+ // the same distribution the drag uses means a tall window arrives with+ // taller sound lanes instead of a dead band under them.+ // THE TERM IS SIGNED, and that is what makes the correction below work at+ // the top of the handle's range: there the monitors are already at their+ // own floor and cannot give anything back, so whatever the column is+ // overflowing by has to come off the TIMELINE or it does not come off+ // anything. Floored, never negative — the box may not shrink into itself.+ sbeApplyTl(Math.max(SBE_TL_MIN_H, want + Math.round(b - fit.progH)));+ };+ apply(budget);+ // ONE CORRECTION, NEVER A LOOP. Rounding, a sticky bar's own padding and a+ // row that came out a pixel taller than the sum of its parts all land here+ // as a few pixels of column scroll — measured at 10px at 1900x1000. Reading+ // the overflow back and taking it off the budget is exact where a guessed+ // safety margin would be a permanent tax on the picture. Guarded so it can+ // only ever shrink, and only once per paint.+ const over = col.scrollHeight - col.clientHeight;+ if (over > 1 && over < 200) apply(budget - over);+ // THE TWO SOUND LANES ARE DRAWN, NOT STYLED, so a variable cannot resize+ // them on its own: the soundtrack's canvas carries a backing store and a+ // clip strip's waveform is emitted at its own height. Both were painted+ // BEFORE this function ran — it is deliberately last, because the+ // inspector's height is one of its inputs — so when this pass moves the+ // height, they are one pass behind and a 54px bitmap is left stretched over+ // a 122px lane. Redrawn here, and only when the number actually moved.+ if (SBE.laneAt !== SBE.tlNow) {+ SBE.laneAt = SBE.tlNow;+ sbePaintAudioLane();+ const inner = sbeEl('sbeInner');+ if (inner) sbePaintWave(sbeSpan(), parseFloat(inner.style.width) || 0);+ }+}++// The one writer of the timeline's height. Five variables on #sbTimeline: the+// box, and the four lanes inside it. Everything downstream — the CSS, the+// strip waveform's viewBox, the soundtrack canvas — reads the same numbers, so+// the picture and the pointer maths cannot disagree about where a strip is.+function sbeApplyTl(px) {+ const tl = Math.max(SBE_TL_MIN_H, Math.round(sbeNum(px, SBE_TL_MIN_H)));+ SBE.tlNow = tl;+ const plan = sbeEl('sbTimeline');+ if (!plan || !plan.style) return;+ const L = sbeLaneHeights(tl);+ plan.style.setProperty('--sbe-tl-h', tl + 'px');+ plan.style.setProperty('--sbe-ov-h', L.ov + 'px');+ plan.style.setProperty('--sbe-track-h', L.track + 'px');+ plan.style.setProperty('--sbe-alane-h', L.alane + 'px');+ plan.style.setProperty('--sbe-wave-h', L.wave + 'px');+}++// How tall one clip's sound strip is drawn, in the same pixels the lane was+// given. Read from the number rather than from the DOM because the lane is+// painted BEFORE sbeFitMonitors runs in any given paint, and a strip that+// measured the live lane would be drawing last frame's height.+function sbeStripH() {+ // SEVEN, not six: the lane is border-box with a 1px top rule, and the strip+ // inside it is inset 3px top and bottom. Off by that one pixel the viewBox+ // and the box disagree and every waveform is drawn 4% tall.+ return Math.max(14, sbeLaneHeights(SBE.tlNow || SBE.tlH).alane - 7);+}++// ---- the drag itself ----------------------------------------------------+// Pointer capture, because a resize that stops working the moment the pointer+// leaves the 10px strip it started on is a resize that fights you.+function sbeTlGrabDown(ev) {+ SBE.tlDrag = { y0: ev.clientY, h0: SBE.tlNow || SBE.tlH };+ try { ev.currentTarget.setPointerCapture(ev.pointerId); } catch (e) {}+ document.body.classList.add('sbe-resizing');+ // NOT preventDefault: cancelling pointerdown suppresses the compatibility+ // mouse events, and the double-click reset is one of them. The body class+ // is what stops the drag selecting the transport's labels.+}++function sbeTlGrabMove(ev) {+ const d = SBE.tlDrag;+ if (!d) return;+ // UP IS TALLER. clientY falls as the pointer rises, so the delta is+ // subtracted and the edge follows the pointer exactly.+ sbeTlSet(d.h0 - (ev.clientY - d.y0));+ ev.preventDefault();+}++function sbeTlGrabUp(ev) {+ if (!SBE.tlDrag) return;+ SBE.tlDrag = null;+ document.body.classList.remove('sbe-resizing');+ try { ev.currentTarget.releasePointerCapture(ev.pointerId); } catch (e) {}+ sbeTlPrefWrite(SBE.tlH);+}++// Set, lay out, repaint — in that order. sbeApplyTl runs FIRST so the lanes+// already have their new heights when sbePaint draws into them, and+// sbeFitMonitors (last inside sbePaint) gives the monitors what is left and+// corrects tlNow for what the window could actually spare.+function sbeTlSet(px) {+ SBE.tlH = sbeTlClamp(px, SBE.tlMax);+ sbeApplyTl(SBE.tlH);+ sbePaint();+}++// DOUBLE-CLICK RESETS, the same gesture the fade corners and the level line+// already answer to on this timeline.+function sbeTlReset() {+ sbeTlSet(SBE_TL_MIN_H);+ sbeTlPrefWrite(SBE.tlH);+}++function sbeTlGrabKey(ev) {+ const step = ev.shiftKey ? SBE_TL_STEP_BIG : SBE_TL_STEP;+ const now = SBE.tlNow || SBE.tlH;+ if (ev.key === 'ArrowUp') sbeTlSet(now + step);+ else if (ev.key === 'ArrowDown') sbeTlSet(now - step);+ else if (ev.key === 'Home') sbeTlSet(SBE_TL_MIN_H);+ else return;+ // The Editor's own shortcuts own the arrows (a frame at a time) and Home.+ // A focused handle is not the timeline, so the event stops here.+ ev.preventDefault();+ ev.stopPropagation();+ sbeTlPrefWrite(SBE.tlH);+}++function sbePaintRuler(span, width) {+ const r = sbeEl('sbeRuler');+ const steps = [0.5, 1, 2, 5, 10, 15, 30, 60, 120];+ let step = steps[steps.length - 1];+ for (const s of steps) { if (s * SBE.pps >= 54) { step = s; break; } }+ // ONE FORMAT PER ZOOM, DECIDED FROM THE STEP. Stripping the fractional+ // zeros per LABEL made neighbouring ticks different shapes — 0:00.50 beside+ // 0:01 beside 0:01.50 — so the eye read a rhythm change where the time is+ // perfectly regular, and tabular numerals cannot save a ruler whose labels+ // have different lengths.+ const decimals = step < 1;+ let html = '';+ for (let t = 0; t <= span + 1e-6; t += step) {+ const x = sbePx(t);+ const lab = decimals ? sbeFmtTime(t) : sbeFmtTime(t).replace(/\.00$/, '');+ html += '<i style="left:' + x.toFixed(1) + 'px"></i>' ++ '<b style="left:' + x.toFixed(1) + 'px">' + lab + '</b>';+ }+ r.innerHTML = html;+ r.style.width = width + 'px';+}++function sbePaintWave(span, width) {+ const cv = sbeEl('sbeWave');+ const none = sbeEl('sbeWaveNone');+ // The soundtrack's lane takes its share of a dragged edge too — it is the+ // other surface you edit sound on. Read from the same distribution the CSS+ // variable came from, so the canvas's backing store and its box agree.+ const h = sbeLaneHeights(SBE.tlNow || SBE.tlH).wave;+ if (!SBE.peaks) {+ cv.hidden = true;+ none.hidden = false;+ none.style.width = width + 'px';+ none.innerHTML = SBE.audio && SBE.audio.path+ ? 'No waveform yet — press Prepare to build the proxies, the waveform and the beat grid.'+ : 'No soundtrack on this timeline. Point one at it below and press Prepare.';+ return;+ }+ none.hidden = true;+ cv.hidden = false;+ const dpr = window.devicePixelRatio || 1;+ cv.width = Math.ceil(width * dpr);+ cv.height = Math.ceil(h * dpr);+ cv.style.width = width + 'px';+ cv.style.height = h + 'px';+ const g = cv.getContext('2d');+ g.setTransform(dpr, 0, 0, dpr, 0, 0);+ g.clearRect(0, 0, width, h);+ const css = getComputedStyle(document.body);+ const mid = h / 2;++ // Beats go UNDER the waveform — they are the reference, not the subject.+ // Downbeats go OVER it, further down this function: a bar line you cannot+ // find behind the loudest part of the track is not a grid, it is a texture.+ const guess = sbeGridIsAGuess(SBE.beats);+ const grid = sbeBeatGrid(SBE.beats, 0, sbeSpan(), (SBE.audio || {}).offset);+ for (const b of grid) {+ if (b.down) continue;+ g.strokeStyle = guess ? 'rgba(182,191,209,0.16)' : 'rgba(88,166,255,0.30)';+ g.lineWidth = 1;+ const x = Math.round(sbePx(b.t)) + 0.5;+ g.beginPath(); g.moveTo(x, 0); g.lineTo(x, h); g.stroke();+ }++ const off = sbeNum((SBE.audio || {}).offset);+ const p = SBE.peaks;+ const win = sbeMusicWindow(SBE.audio, p.duration);+ const w = Math.max(1, SBE.pps / p.rate);+ const strong = (css.getPropertyValue('--border-strong') || '#3d477a').trim();+ // THE TRIMMED-AWAY PART IS STILL DRAWN, faintly. A trim you cannot see the+ // other side of is a trim you cannot pull back — the seconds are not gone,+ // they are outside the window, and the picture should say which.+ for (let i = 0; i < p.count; i++) {+ const tt = i / p.rate; // where this bucket is IN THE TRACK+ const t = tt - off; // ...and where that lands on the film+ if (t < 0) continue;+ const x = sbePx(t);+ if (x > width) break;+ const live = tt >= win.head - 1e-9+ && (win.tail === null || tt <= win.tail + 1e-9);+ g.fillStyle = strong;+ g.globalAlpha = live ? 1 : 0.28;+ const y0 = mid - p.hi[i] * mid * 0.94;+ const y1 = mid - p.lo[i] * mid * 0.94;+ g.fillRect(x, y0, w, Math.max(1, y1 - y0));+ }+ g.globalAlpha = 1;+ for (const b of grid) {+ if (!b.down) continue;+ g.strokeStyle = guess ? 'rgba(182,191,209,0.42)' : 'rgba(88,166,255,0.85)';+ g.lineWidth = 1;+ const x = Math.round(sbePx(b.t)) + 0.5;+ g.beginPath(); g.moveTo(x, 0); g.lineTo(x, h); g.stroke();+ }++ // Where the music runs out. Past this line there is no grid and no waveform,+ // and the film is on its own.+ if (p.duration > 0) {+ const x = Math.round(sbePx(p.duration - off)) + 0.5;+ if (x < width) {+ g.strokeStyle = 'rgba(210,153,34,0.6)';+ g.lineWidth = 1;+ g.beginPath(); g.moveTo(x, 0); g.lineTo(x, h); g.stroke();+ }+ }+}++// THE BLOCK, over the picture of the track. It exists whenever there is a+// soundtrack and a length to give it — the waveform is not a precondition,+// because `audio.duration` is known before prepare has run and a strip you+// cannot grab until you have pressed Prepare is a strip that looks broken.+function sbePaintMusic(width) {+ const el = sbeEl('sbeMusicClip');+ if (!el) return;+ const a = SBE.audio;+ const w = sbeMusicWindow(a, SBE.peaks ? SBE.peaks.duration : 0);+ if (!a || !a.path || w.duration <= 0 || w.tail === null) {+ el.hidden = true;+ return;+ }+ el.hidden = false;+ const left = sbePx(w.film_start);+ const right = sbePx(w.film_end === null ? w.film_start : w.film_end);+ el.style.left = left.toFixed(1) + 'px';+ el.style.width = Math.max(3, right - left).toFixed(1) + 'px';+ el.classList.toggle('is-sel', SBE.sel === '@music');+ const name = String(a.path || '').split('/').pop();+ const played = Math.max(0, (w.film_end === null ? 0 : w.film_end) - w.film_start);+ const label = name + ' · ' + sbeFmtTime(w.film_start) + ' · ' ++ played.toFixed(2) + 's' + (w.trimmed ? ' · trimmed' : '');+ sbeEl('sbeMusicName').textContent = (right - left > 120) ? label : '';+ el.title = name + '\nStarts at ' + sbeFmtTime(w.film_start) ++ ' of the __SEQ__, from ' + sbeFmtTime(w.head) + ' of the track.' ++ '\nDrag to place it · pull either end to trim · hold Alt to ignore the cuts.' ++ '\nCorners fade it · double-click the level line to add a point.';+ sbePaintBedLevel(el, Math.max(3, right - left));+}++// THE BED'S LEVEL LINE, POINTS AND FADE RAMPS. Everything here is the strip+// painter's arithmetic with one substitution — the bed's curve instead of a+// clip's — because a second copy of it is a second thing to drift. The+// waveform is NOT redrawn: `#sbeWave` already paints the whole track under+// this block, and drawing it twice would be two pictures of one sound.+function sbePaintBedLevel(el, px) {+ const layer = el.querySelector('.sbe-mc-lvl');+ const band = el.querySelector('.sbe-fade-band');+ if (!layer) return;+ const a = SBE.audio || {};+ // THE FILM, NOT THE PROBE. The bed's clock is the document's own length and+ // the film's when the document is silent — the render reads edit.json and+ // has never seen peaks.json, so anything the probe contributed here would be+ // a level only the browser could compute. See `sbeBedLen`.+ const dur = sbeFilmDuration(SBE.clips);+ const n = sbeBedLen(a, dur);+ const H = Math.max(14, Math.round(el.getBoundingClientRect().height)+ || (sbeLaneHeights(SBE.tlNow || SBE.tlH).wave - 8));+ // WHAT THE RENDER WILL DO, not what was authored. The fader and the duck+ // are in this line as well as the envelope, so the picture of the level is+ // the level — which is the entire complaint this feature answers.+ const curve = sbeBedGainPoints(a, SBE.clips, dur);+ const pts = curve.length ? curve : [[0, 1], [n || 1, 1]];+ const yOf = g => sbeStripY(g, H);+ const xOf = t => (n > 0 ? (t / n) * px : 0);+ let line = '';+ for (let i = 0; i < pts.length; i++) {+ line += (i ? 'L' : 'M') + xOf(pts[i][0]).toFixed(2) + ','+ + yOf(pts[i][1]).toFixed(2);+ }+ let body = '<path class="sbe-lvl-u" d="' + line + '"/>'+ + '<path class="sbe-lvl" d="' + line + '"/>';+ // THE TARGET STOPS WHERE THE CORNER HANDLES START — the same clip the+ // strips apply, for the same reason: two controls claiming one rectangle is+ // how the fade handle got lost inside the trim grip in the first place.+ const hit = sbeLvlHitPath(pts, xOf, yOf, SBE_LVL_CLEAR, px - SBE_LVL_CLEAR);+ if (hit) body += '<path class="sbe-lvl-hit" d="' + hit + '"/>';+ const gh = SBE.kfGhost;+ if (gh && gh.id === '@music') {+ body += '<circle class="sbe-kf-ghost" cx="' + xOf(gh.t).toFixed(2) + '" '+ + 'cy="' + yOf(gh.g).toFixed(2) + '" r="'+ + Math.max(3.6, Math.min(6.5, H / 5.5)).toFixed(2) + '"/>';+ }+ // Only the USER's points get a handle, exactly as on a strip: the fade+ // corners are already a gesture of their own, and a dot on them would offer+ // two ways to drag one number in opposite directions.+ const own = sbeAfx(a, n).points;+ const R = Math.max(3.2, Math.min(6, H / 6));+ for (let i = 0; i < own.length; i++) {+ body += '<circle class="sbe-kf" data-bkf="' + i + '" '+ + 'cx="' + xOf(own[i][0]).toFixed(2) + '" '+ + 'cy="' + yOf(sbeLerpGain(curve.length ? curve : own, own[i][0])).toFixed(2) + '" '+ + 'style="--kf-r:' + R.toFixed(2) + 'px" '+ + 'r="' + R.toFixed(2) + '"/>';+ }+ layer.innerHTML = '<svg width="' + Math.max(1, px).toFixed(0) + '" height="' + H+ + '" viewBox="0 0 ' + Math.max(1, px).toFixed(0) + ' ' + H+ + '" preserveAspectRatio="none">' + body + '</svg>';+ // A BED TOO SHORT TO CARRY THEM OFFERS NEITHER. An 8px stub of a control is+ // worse than none — the same rule the strips' handles follow.+ if (band) band.hidden = !(px >= 2 * SBE_LVL_CLEAR + SBE_LVL_MIN_SPAN);+}++// ---- the music, dragged --------------------------------------------------+// Same three modes as a clip, the same pointer-capture shape, and the same+// rule about a gesture that moved the pointer without moving the film.+// WHERE THE POINTER IS ON THE BED, in the coordinates a level cares about.+// The strip lane's `sbeStripAt` for the soundtrack: how far along the played+// window, and what gain that height means.+function sbeBedAt(ev) {+ const el = sbeEl('sbeMusicClip');+ if (!el || el.hidden) return null;+ const a = SBE.audio;+ if (!a || !a.path) return null;+ // NOT WHILE THE POINTER IS ON A CORNER HANDLE. The clipped hit path keeps+ // the LINE off those pixels, but the proximity test below knows nothing+ // about paths — and it is what the hover ghost asks, so without this a fade+ // handle would sit under a ghost promising a point it could never place.+ if (ev.target.closest('.sbe-fade-h')) return null;+ const r = el.getBoundingClientRect();+ const n = sbeBedLen(a, sbeFilmDuration(SBE.clips));+ if (n <= 0) return null;+ return {+ rect: r, len: n,+ t: n * Math.max(0, Math.min(1, (ev.clientX - r.left) / Math.max(1, r.width))),+ g: sbeStripGain(ev.clientY, r.top, r.height),+ };+}++// A click within SBE_LVL_GRAB of the bed's level places a point and starts+// dragging it — one gesture, the same one the strips answer to.+function sbeBedLevelClick(ev) {+ const at = sbeBedAt(ev);+ if (!at) return false;+ const dur = sbeFilmDuration(SBE.clips);+ const onLine = sbeStripY(sbeBedGainAt(SBE.audio, SBE.clips, dur, at.t),+ at.rect.height);+ const near = Math.abs((ev.clientY - at.rect.top) - onLine) <= SBE_LVL_GRAB;+ if (!near && !ev.target.closest('.sbe-lvl-hit')) return false;+ const before = JSON.stringify(SBE.audio || {});+ const next = sbeBedAddKeyframe(SBE.audio, at.t, at.g, dur);+ if (!next) return false;+ sbeSetAudio(next);+ SBE.sel = '@music';+ SBE.kfGhost = null;+ const pts = sbeAfx(SBE.audio, at.len).points;+ let idx = 0;+ for (let i = 0; i < pts.length; i++) {+ if (Math.abs(pts[i][0] - sbeRound(at.t)) < 1e-3) { idx = i; break; }+ }+ SBE.musicDrag = { mode: 'bkf', index: idx, rect: at.rect,+ before: before, moved: true };+ try { sbeEl('sbeMusicLane').setPointerCapture(ev.pointerId); } catch (e) {}+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ return true;+}++function sbeOnMusicDown(ev) {+ const el = sbeEl('sbeMusicClip');+ if (!el || el.hidden) return;+ const a = SBE.audio;+ if (!a || !a.path) return;+ const lane = sbeEl('sbeMusicLane');+ const w = sbeMusicWindow(a, SBE.peaks ? SBE.peaks.duration : 0);+ // The BED's clock, which is not the block's picture: see `sbeBedLen`.+ const dur = sbeFilmDuration(SBE.clips);+ SBE.sel = '@music';+ // GESTURE PRECEDENCE, MOST SPECIFIC FIRST, and it is deliberately the same+ // list the clip-sound lane uses — one rule for both, or the soundtrack would+ // behave differently from the strip above it for no reason a user could name.+ // 1. a point on the level line+ // 2. a corner fade handle (sits over the grip's hit area)+ // 3. the level line itself+ // 4. the grips (trim)+ // 5. the block (move)+ const kf = ev.target.closest('.sbe-kf');+ if (kf && kf.dataset.bkf !== undefined) {+ const before = JSON.stringify(a);+ // SHIFT-CLICK DELETES. A modifier rather than a second affordance drawn on+ // a 6px target, which would be a delete nobody meant.+ if (ev.shiftKey) {+ const gone = sbeBedDeleteKeyframe(a, sbeNum(kf.dataset.bkf), dur);+ if (gone) { sbeSetAudio(gone); sbeMusicCommit(before); }+ ev.preventDefault();+ return;+ }+ SBE.musicDrag = { mode: 'bkf', index: sbeNum(kf.dataset.bkf),+ rect: el.getBoundingClientRect(),+ before: before, moved: false };+ try { lane.setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+ return;+ }+ const fh = ev.target.closest('.sbe-fade-h');+ if (fh && fh.dataset.bfade !== undefined) {+ const e0 = sbeAfx(a, sbeBedLen(a, dur));+ SBE.musicDrag = {+ mode: 'bfade', edge: fh.dataset.bfade, x0: ev.clientX,+ f0: (fh.dataset.bfade === 'out') ? e0.fade_out : e0.fade_in,+ before: JSON.stringify(a), moved: false,+ };+ try { lane.setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+ return;+ }+ if (!ev.target.closest('.sbe-grip') && sbeBedLevelClick(ev)) {+ ev.preventDefault();+ return;+ }+ const grip = ev.target.closest('.sbe-grip');+ SBE.musicDrag = {+ mode: grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL') : 'move',+ x0: ev.clientX,+ t0: sbeTimeFromEvent(ev, lane),+ fs0: w.film_start,+ fe0: (w.film_end === null ? w.film_start : w.film_end),+ before: JSON.stringify(a), moved: false,+ };+ el.classList.add('is-drag');+ try { lane.setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+}++// ONE WRITER for the soundtrack object, so every gesture that changes it —+// drag, trim, fade, point, level, duck — marks the document dirty the same way+// and none of them can forget the queued save.+function sbeSetAudio(next) {+ SBE.audio = next;+ SBE.edit = SBE.edit || {};+ SBE.edit.audio = next;+}++function sbeMusicCommit(beforeJson) {+ // THE FINGERPRINT IS THE WHOLE OBJECT, not a list of three field names. The+ // list was `offset`, `trim_start`, `trim_end` — written when those were all+ // a soundtrack had — and a fade, a keyframe or a level change would have+ // compared EQUAL and been silently discarded on pointerup. That defect has+ // already shipped twice on this timeline under the name `sbeDragFingerprint`.+ if (JSON.stringify(SBE.audio || {}) === beforeJson) { sbePaint(); return; }+ SBE.undo.push(sbeSnapshot(JSON.parse(beforeJson)));+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+}++function sbeOnMusicMove(ev) {+ const d = SBE.musicDrag;+ const dur = sbeFilmDuration(SBE.clips); // the BED's clock — see sbeBedLen+ // NOTHING BEING DRAGGED IS A HOVER, and a hover is where the level line+ // teaches — the same answer the strip lane gives.+ if (!d) { sbeBedGhost(ev); return; }+ if (d.mode === 'bkf') {+ const r = d.rect;+ const n = sbeBedLen(SBE.audio, dur);+ const t = n * Math.max(0, Math.min(1,+ (ev.clientX - r.left) / Math.max(1, r.width)));+ d.moved = true;+ const next = sbeBedMoveKeyframe(SBE.audio, d.index, t,+ sbeStripGain(ev.clientY, r.top, r.height), dur);+ if (next) sbeSetAudio(next);+ sbePaint();+ return;+ }+ if (Math.abs(ev.clientX - d.x0) > 3) d.moved = true;+ if (!d.moved) return;+ if (d.mode === 'bfade') {+ // The out-fade grows LEFTWARD from the block's right edge, so its pointer+ // delta is negated — same as the strips'.+ const adt = (d.edge === 'out') ? -(ev.clientX - d.x0) / SBE.pps+ : (ev.clientX - d.x0) / SBE.pps;+ sbeSetAudio(sbeSetBedFade(SBE.audio, d.edge, Math.max(0, d.f0 + adt), dur));+ sbePaint();+ return;+ }+ const dt = (ev.clientX - d.x0) / SBE.pps;+ const tol = SBE_SNAP_PX / SBE.pps;+ const snapOn = sbeSnapEnabled(ev);+ const marks = sbeMusicSnaps(SBE.clips);+ const anchor = (d.mode === 'trimR') ? d.fe0 : d.fs0;+ const want = sbeSnapToList(Math.max(0, anchor + dt), marks, tol, snapOn);+ const next = sbeMusicEdit(SBE.audio, d.mode, want,+ SBE.peaks ? SBE.peaks.duration : 0);+ sbeApplyMusic(next);+ sbePaint();+}++function sbeOnMusicUp(ev) {+ const d = SBE.musicDrag;+ SBE.musicDrag = null;+ if (!d) return;+ const el = sbeEl('sbeMusicClip');+ if (el) el.classList.remove('is-drag');+ if (!d.moved) {+ // A press that never travelled is a scrub, exactly as it is anywhere else+ // on this lane — the block covers most of the waveform, so swallowing the+ // click would take the lane's scrubber away with it. A press that landed+ // ON a control is not a scrub, though: a point tapped and released has+ // selected itself, and jumping the playhead would be a surprise.+ if (d.mode !== 'bkf' && d.mode !== 'bfade') {+ sbeSeek(sbeTimeFromEvent(ev, sbeEl('sbeMusicLane')));+ return;+ }+ }+ sbeMusicCommit(d.before);+}++// HOVER TEACHES, on the bed as on the strips: near the line, a ghost point+// follows the pointer so the gesture is visible before it is performed.+function sbeBedGhost(ev) {+ const at = sbeBedAt(ev);+ if (at) {+ const dur = sbeFilmDuration(SBE.clips);+ const onLine = sbeStripY(sbeBedGainAt(SBE.audio, SBE.clips, dur, at.t),+ at.rect.height);+ if (Math.abs((ev.clientY - at.rect.top) - onLine) <= SBE_LVL_GRAB) {+ const g = SBE.kfGhost;+ if (!g || g.id !== '@music' || Math.abs(g.t - at.t) > 0.01) {+ SBE.kfGhost = { id: '@music', t: at.t, g: at.g };+ sbePaint();+ }+ return;+ }+ }+ if (SBE.kfGhost && SBE.kfGhost.id === '@music') {+ SBE.kfGhost = null;+ sbePaint();+ }+}++// DOUBLE-CLICK ADDS A POINT on the bed's body, exactly as on a strip. Plain+// drag stays "move the music" — the gesture this lane already had — so the+// control case is opt-in and the simple case is untouched.+function sbeOnMusicDbl(ev) {+ const el = sbeEl('sbeMusicClip');+ if (!el || el.hidden || !ev.target.closest('#sbeMusicClip')) return;+ if (ev.target.closest('.sbe-kf') || ev.target.closest('.sbe-fade-h')) return;+ const at = sbeBedAt(ev);+ if (!at) return;+ const before = JSON.stringify(SBE.audio || {});+ const next = sbeBedAddKeyframe(SBE.audio, at.t, at.g,+ sbeFilmDuration(SBE.clips));+ if (!next) return;+ SBE.sel = '@music';+ sbeSetAudio(next);+ sbeMusicCommit(before);+ ev.preventDefault();+}++// Writing the three fields back, and the ONE place that commits a soundtrack+// discovered from peaks.json into the document. `sbeFetchPeaks` deliberately+// does not — a track the arrangement was never cut to must not be saved as if+// it had been — but dragging its strip IS the user saying "this one, here",+// so from that gesture on it belongs to the edit.+function sbeApplyMusic(fields) {+ const a = Object.assign({}, SBE.audio || {});+ a.offset = sbeRound(sbeNum(fields.offset));+ if (fields.trim_start > 0) a.trim_start = sbeRound(fields.trim_start);+ else delete a.trim_start;+ if (fields.trim_end !== null && fields.trim_end !== undefined+ && sbeNum(fields.trim_end) > 0) a.trim_end = sbeRound(fields.trim_end);+ else delete a.trim_end;+ sbeSetAudio(a);+}++// ---- THE MIX CONTROLS, on the A2 head -----------------------------------+// The two numbers the renderer used to keep to itself. `sbeBedGainSlide` is+// the live one — the slider moves, the level line under it moves, the bed you+// are hearing moves — and the commit is what enters the undo stack, so a drag+// across the whole range is one undo and not sixty.+function sbeBedGainSlide(v) {+ if (!SBE.audio || !SBE.audio.path) return;+ if (!SBE.bedGainBefore) SBE.bedGainBefore = JSON.stringify(SBE.audio);+ sbeSetAudio(sbeMixWrite(SBE.audio, { bed_gain: Math.max(0, Math.min(1, sbeNum(v) / 100)) }));+ sbePaintMix();+ sbePaint();+ sbeMusicSync();+}++function sbeBedGainCommit(v) {+ if (!SBE.audio || !SBE.audio.path) return;+ const before = SBE.bedGainBefore || JSON.stringify(SBE.audio);+ SBE.bedGainBefore = null;+ sbeSetAudio(sbeMixWrite(SBE.audio, { bed_gain: Math.max(0, Math.min(1, sbeNum(v) / 100)) }));+ sbePaintMix();+ sbeMusicCommit(before);+ sbeMusicSync();+}++function sbeSetBedDuck(on) {+ if (!SBE.audio || !SBE.audio.path) {+ // Nothing to duck. Put the box back rather than recording a decision+ // about a soundtrack that does not exist.+ sbePaintMix();+ return;+ }+ const before = JSON.stringify(SBE.audio);+ sbeSetAudio(sbeMixWrite(SBE.audio, { duck: !!on }));+ sbePaintMix();+ sbeMusicCommit(before);+}++// The head, painted from the document — never the other way round, which is+// the bug `sbeSetMusicMode`'s comment records: a control that writes on every+// load turns every OPEN of a film into a save the user never made.+function sbePaintMix() {+ const a = SBE.audio || {};+ const has = !!a.path;+ const mix = sbeAudioMix(a);+ const sl = sbeEl('sbeBedGain');+ const num = sbeEl('sbeBedGainNum');+ const dk = sbeEl('sbeBedDuck');+ const note = sbeEl('sbeBedDuckNote');+ const head = document.querySelector('.sbe-gh-mus');+ const pct = Math.round(mix.bed_gain * 100);+ if (sl) { sl.value = String(pct); sl.disabled = !has; }+ if (num) num.textContent = pct + '%';+ if (dk) { dk.checked = !!mix.duck; dk.disabled = !has; }+ // A CONTROL THAT HAS STOPPED ACTING SAYS SO, LOUDLY. The duck stands down+ // under an authored envelope — never two curves on one level — and a ticked+ // box that was quietly doing nothing is the silent guard this editor has+ // paid for more than once.+ const off = has && sbeBedDuckSuppressed(a, sbeFilmDuration(SBE.clips));+ if (note) {+ note.hidden = !off;+ note.textContent = off ? 'off — your own level line is driving the bed' : '';+ }+ if (head) head.classList.toggle('is-duck-off', off);+}++function sbePaintTrack() {+ const track = sbeEl('sbeTrack');+ const holes = sbeHoles(SBE.clips);+ // THE MESSAGE BELONGS WHERE THE EMPTINESS IS. This sentence used to live in+ // the inspector, which is a short auto-scrolled box in the corner — so on a+ // brand-new draft the user read "…media pool to put it here, or Add black+ // for a gap to fill", starting mid-word, while the track itself, the thing+ // that was empty, rendered nothing at all.+ let html = SBE.clips.length ? '' :+ '<div class="sbe-track-empty">Nothing on the timeline yet — click a clip '+ + 'in the media pool to put it here, or Add black for a gap to fill.</div>';+ for (const g of holes) {+ const w = sbePx(g.duration);+ html += '<div class="sbe-gap" data-gap-start="' + g.film_start + '" ' ++ 'data-gap-dur="' + g.duration + '" ' ++ 'title="Nothing plays here. Click to generate a shot for it." ' ++ 'style="left:' + sbePx(g.film_start).toFixed(1) + 'px;width:' + w.toFixed(1) + 'px">' ++ (w > 84 ? escapeHtml(g.duration.toFixed(2) + 's hole · fill it') : '+') ++ '</div>';+ }+ for (const c of SBE.clips) {+ const w = sbePx(sbeLen(c));+ const kind = sbeKind(c);+ const bright = sbeBright(c);+ const bad = SBE.errors.byId && SBE.errors.byId[c.id];+ const flag = c.locked ? 'lock'+ : (Math.abs(bright) >= 1e-6+ ? (bright > 0 ? '+' : '') + bright.toFixed(2)+ // "slow" is a VIDEO's problem. A still has no proxy because it needs+ // none and a slug has no file at all, so flagging either as+ // un-scrubbable would be advice to run a Prepare that would do+ // nothing.+ : (kind === 'video' && !c.proxy ? 'slow' : ''));+ const cls = 'sbe-clip is-' + kind + (c.id === SBE.sel ? ' is-sel' : '')+ + (c.id === SBE.curId ? ' is-playing' : '')+ + (bad ? ' is-bad' : '') + (c.locked ? ' is-locked' : '')+ + (Math.abs(bright) >= 1e-6 ? ' is-graded' : '')+ + (flag ? ' has-flag' : '');+ // A still and a slug have no source window to report — their only number+ // is the hold, and printing "0.00→3.00" of a clock they do not have reads+ // as a trim somebody made.+ const meta = (kind === 'video')+ ? (sbeNum(c.start).toFixed(2) + '→' + sbeNum(c.end).toFixed(2) ++ ' · ' + sbeLen(c).toFixed(2) + 's')+ : (sbeLen(c).toFixed(2) + 's hold');+ const label = (kind === 'slug')+ ? 'black'+ : (c.title || String(c.path || '').split('/').pop() || 'clip');+ // The still paints its own picture behind its name. One <img> per still on+ // the track, which is the same budget the pool already spends per row and+ // nothing like the media-element cap a <video> would eat.+ const thumb = (kind === 'still' && c.path)+ ? '<img class="sbe-cl-thumb" alt="" src="/image?w=240&path=' ++ encodeURIComponent(c.path) + '">'+ : '';+ html += '<div class="' + cls + '" data-id="' + escapeHtml(c.id) + '" '+ + 'data-kind="' + escapeHtml(kind) + '" '+ + 'data-source="' + escapeHtml(c.source || 'auto') + '" '+ + 'title="' + escapeHtml(label + (bad ? '\n' + bad[0].message : '')) + '" '+ + 'style="left:' + sbePx(c.film_start).toFixed(1) + 'px;width:' + w.toFixed(1) + 'px">'+ + thumb+ + '<div class="sbe-cl-name">' + escapeHtml(sbeNiceName(label)) + '</div>'+ + (w > 96 ? '<div class="sbe-cl-meta">' + escapeHtml(meta) + '</div>' : '')+ + (flag ? '<div class="sbe-cl-flag">' + escapeHtml(flag) + '</div>' : '')+ + sbeSyncBadge(c)+ + sbeFadeMarks(c)+ + '<div class="sbe-grip l"></div><div class="sbe-grip r"></div>'+ // THE TWO CORNER HANDLES, IN A BAND INSET FROM BOTH GRIPS. The+ // wrapper is what keeps the fade gesture and the trim gesture off+ // each other's pixels (see `.sbe-fade-band`) — they were stacked in+ // the same corner and the trim won almost every aim.+ + (c.locked ? ''+ : '<div class="sbe-fade-band">'+ + '<div class="sbe-fade-h in" data-fade="in"></div>'+ + '<div class="sbe-fade-h out" data-fade="out"></div>'+ + '</div>')+ + '</div>';+ }+ track.innerHTML = html;+ track.style.width = sbeEl('sbeInner').style.width;+ if (SBE.dropAt !== null && SBE.dropAt !== undefined) {+ const line = document.createElement('div');+ line.className = 'sbe-drop-line';+ line.style.left = sbePx(SBE.dropAt).toFixed(1) + 'px';+ track.appendChild(line);+ }+}++// The ramps, drawn to scale on the block: a fade you can see the length of+// without selecting the clip.+function sbeFadeMarks(c) {+ const e = sbeFx(c);+ let out = '';+ if (e.fade_in > 1e-9) {+ out += '<div class="sbe-cl-fade in" style="left:0;width:'+ + sbePx(e.fade_in).toFixed(1) + 'px"></div>';+ }+ if (e.fade_out > 1e-9) {+ out += '<div class="sbe-cl-fade out" style="right:0;width:'+ + sbePx(e.fade_out).toFixed(1) + 'px"></div>';+ }+ return out;+}++// THE SYNC FLAG, and it goes on BOTH halves — the picture block and the sound+// strip — because the pair is what has drifted and either one is where the eye+// happens to be. It is a button: clicking it is the rematch.+function sbeSyncBadge(c) {+ if (sbeKind(c) !== 'video') return '';+ const w = sbeClipAudio(c);+ // A COUPLED pair is never flagged: its offset is the relationship the user+ // froze and the two travel together, so it cannot come apart. Flagging it+ // would put a permanent warning on every J-cut in the film.+ if (!w.split || w.coupled || sbeAudioInSync(c)) return '';+ const d = sbeAudioDrift(c);+ return '<div class="sbe-sync" data-sync="' + escapeHtml(c.id) + '" '+ + 'title="' + escapeHtml('The sound is ' + sbeDriftLabel(d) + ' out of sync '+ + 'with its own picture (' + (d > 0 ? 'late' : 'early') + '). '+ + 'Click to put it back under the frame it came from.') + '">'+ + escapeHtml(sbeDriftLabel(d)) + '</div>';+}++// THE SOUND, UNDER THE PICTURE THAT MADE IT. One strip per video clip,+// directly beneath its block: linked ones are dim and inert, unlinked ones+// carry the same grips a clip does.+function sbePaintAudioLane() {+ const lane = sbeEl('sbeAudioLane');+ if (!lane) return;+ let html = '';+ for (const c of SBE.clips) {+ if (sbeKind(c) !== 'video') continue;+ const w = sbeClipAudio(c);+ const x = sbePx(w.film_start);+ const px = sbePx(w.len);+ // A CLIP WITH NO SOUND AT ALL SAYS SO. `has_audio` rides on the pool row+ // and the clip (the probe already reads streams for `duration`), and it+ // is absent on documents written before it existed — so only an explicit+ // false is silence, and everything else draws as it always did. The rule+ // that paints this state has shipped since the lane did; the flag that+ // reaches it was hard-coded to false, so the lane claimed sound it did+ // not have.+ const mute = c.has_audio === false;+ const off = sbeClipMuted(c);+ const cls = 'sbe-aclip ' + (w.linked ? 'is-linked' : 'is-split')+ + (w.coupled ? ' is-coupled' : '')+ + (mute ? ' is-mute' : '')+ + (off ? ' is-silenced' : '')+ + (c.id === SBE.sel ? ' is-sel' : '');+ // ONE WORD, EIGHT TIMES, IN A 26PX STRIP. The label is only news when the+ // sound has been pulled off its picture — the lane's own fill says the+ // rest, and a column of identical labels says nothing at all. A COUPLED+ // strip is news of a different kind: it is offset ON PURPOSE and moving+ // with its picture, so the label is the offset itself.+ // MUTED SAYS MUTED, over everything else the strip might have said. The+ // strip STAYS — it is still where the sound would be, and the decision has+ // to be visible and reversible in the place it was made.+ const label = mute ? 'no sound'+ : (off ? ('MUTED · ' + w.len.toFixed(2) + 's')+ : (w.coupled ? ('J-cut · ' + sbeDriftLabel(sbeAudioDrift(c)))+ : (w.linked ? '' : ('sound · ' + w.len.toFixed(2) + 's'))));+ html += '<div class="' + cls + '" data-id="' + escapeHtml(c.id) + '" '+ + 'title="' + escapeHtml(off+ ? 'Muted — this clip\'s own sound is switched off in the preview, the render and the export. Unmute it in the inspector.'+ : w.coupled+ ? 'Linked at ' + sbeDriftLabel(sbeAudioDrift(c)) + ' — the sound keeps this offset and travels with the picture. Unlink it to slide it on its own.'+ : (w.linked+ ? 'This clip\'s sound moves with its picture. Unlink it in the inspector to slide it under the neighbour (a J-cut or an L-cut).'+ : 'Unlinked — drag to slide the sound, pull either end to trim it. The picture does not move.')) + '" '+ + 'style="left:' + x.toFixed(1) + 'px;width:' + Math.max(2, px).toFixed(1) + 'px">'+ + (mute ? '' : sbeStripWave(c, w, px))+ + (px > 70 ? '<span class="sbe-aclip-t">' + escapeHtml(label) + '</span>' : '')+ + (px > 46 ? sbeSyncBadge(c) : '')+ + sbeAudioFadeMarks(c, w)+ + (w.linked ? '' : '<div class="sbe-grip l"></div><div class="sbe-grip r"></div>')+ // The same band the picture block uses, on a strip that can be+ // shorter still — 37px at the lane's floor, which is why the handle+ // is sized against that floor and not against the lane.+ + (w.linked || c.locked ? ''+ : '<div class="sbe-fade-band">'+ + '<div class="sbe-fade-h in" data-afade="in"></div>'+ + '<div class="sbe-fade-h out" data-afade="out"></div>'+ + '</div>')+ + '</div>';+ }+ lane.innerHTML = html;+ lane.style.width = sbeEl('sbeInner').style.width;+}++async function edPoolOverlay(i) {+ const rows = (document.getElementById('edPoolList') || {})._rows || [];+ const r = rows[i];+ if (!r || !SBE.open) {+ phosToast('Open a __SEQ__ first — an overlay belongs to a timeline.', {});+ return;+ }+ // A CARD THAT ARRIVES ON A BLACK PLATE IS FIXED ON THE WAY IN, and only on+ // the way to THIS lane. The server measures the file and either hands back a+ // keyed derivative or the path exactly as it came; either way the lane gets+ // one path, and preview, render and export all read that same file.+ const item = { path: r.path, title: r.title || '', duration_s: 3 };+ let keyed = null;+ try {+ // URLSearchParams, like every other editor POST. A `FormData` here sends+ // multipart, which `_storyboard_post` does not parse — the route answered+ // "that image is not in this panel's outputs" for a file sitting in the+ // outputs folder, and the card was placed plated with nothing on screen+ // to say the fix had not run.+ const fd = new URLSearchParams();+ fd.set('path', r.path);+ const res = await (await fetch('/storyboard/edit/overlay-key',+ { method: 'POST', body: fd })).json();+ if (res && res.ok && res.keyed && res.path) { item.path = res.path; keyed = res; }+ } catch (e) {+ // The lane still works with the file exactly as it arrived. A card that+ // could not be measured is not a card that cannot be placed.+ }+ const added = sbeOvAddAt(item, SBE.playhead);+ if (added && keyed) sbeKeyedNotice(added.id, keyed);+}++// SAY SO QUIETLY, AND ALLOW UNDO. Automatic is not the same as silent, and it+// is certainly not the same as irreversible: the picture the user chose was+// changed, so the change is named, and the file it came from is one click away.+// It goes in the ONE notice surface, as a quiet chip, so it can never push the+// timeline down the screen — the rule the four stacked banners broke.+function sbeKeyedNotice(ovId, res) {+ const bar = sbeEl('sbeKeyed');+ if (!bar) return;+ SBE.keyed = { id: ovId, original: res.original || '', path: res.path || '' };+ const what = sbeEl('sbeKeyedWhat');+ if (what) {+ what.textContent = 'from ' + sbeNiceName(+ res.name || String(res.original || '').split('/').pop() || 'that image');+ }+ bar.hidden = false;+ sbePaintNotices();+}++function sbeKeyedKeepOriginal() {+ const k = SBE.keyed;+ sbeKeyedDismiss();+ if (!k || !k.id || !k.original) return;+ if (sbeOvMutate(os => sbeOvSetPath(os, k.id, k.original))) {+ phosToast('Kept the original — the card is back on its black background.',+ { duration: 5000 });+ }+}++function sbeKeyedDismiss() {+ SBE.keyed = null;+ const bar = sbeEl('sbeKeyed');+ if (bar) bar.hidden = true;+ if (SBE.noticeLead === 'sbeKeyed') SBE.noticeLead = '';+ sbePaintNotices();+}++function sbePaintOverlays() {+ const lane = sbeEl('sbeOverlayLane');+ if (!lane || !lane.classList) return;+ let html = '';+ for (const o of SBE.overlays || []) {+ const x = sbePx(sbeNum(o.film_start));+ const w = Math.max(2, sbePx(sbeNum(o.film_end) - sbeNum(o.film_start)));+ const e = sbeFx(o);+ const name = sbeNiceName(o.title || String(o.path || '').split('/').pop() || 'card');+ html += '<div class="sbe-ov' + (o.id === SBE.ovSel ? ' is-sel' : '') + '" '+ + 'data-id="' + escapeHtml(o.id) + '" '+ + 'title="' + escapeHtml('Overlay — composited over the picture. '+ + 'Drag to move, pull either end to change how long.') + '" '+ + 'style="left:' + x.toFixed(1) + 'px;width:' + w.toFixed(1) + 'px">'+ + (sbeOvKind(o) === 'still' && o.path+ ? '<img class="sbe-ov-thumb" alt="" src="/image?w=240&path='+ + encodeURIComponent(o.path) + '">'+ : '')+ + (w > 60 ? escapeHtml(name) : '')+ + (e.fade_in > 1e-9 ? '<div class="sbe-cl-fade in" style="left:0;width:'+ + sbePx(e.fade_in).toFixed(1) + 'px"></div>' : '')+ + (e.fade_out > 1e-9 ? '<div class="sbe-cl-fade out" style="right:0;width:'+ + sbePx(e.fade_out).toFixed(1) + 'px"></div>' : '')+ + '<div class="sbe-grip l"></div><div class="sbe-grip r"></div>'+ + '</div>';+ }+ // AN EMPTY LANE IS A SENTENCE, NOT A BLANK — the convention the track and+ // the four pool sources already follow. Without it the overlay lane is a+ // strip of nothing that teaches nobody it exists.+ lane.innerHTML = html || '<div class="sbe-track-empty sbe-ovlane-empty">'+ + 'Overlay lane — drop a still here, or press \u25a3 on an image in the '+ + 'media pool to lay it over the picture at the playhead.</div>';+ lane.style.width = sbeEl('sbeInner').style.width;+}++// THE STAGE'S CARD. Driven by the playhead like the strip player, because an+// overlay is its own lane and does not care which picture is underneath.+function sbeOvPaint(t) {+ const el = sbeEl('sbeOvLayer');+ if (!el || !el.classList) return;+ const now = (t === undefined) ? SBE.playhead : sbeNum(t);+ const o = sbeOvAt(SBE.overlays, now);+ if (!o || !o.path) { el.classList.remove('is-on'); return; }+ const url = '/image?w=1280&path=' + encodeURIComponent(o.path);+ if (el.getAttribute('src') !== url) el.setAttribute('src', url);+ el.style.opacity = String(sbeFadeOpacityAt(o, now));+ el.classList.add('is-on');+}++function sbeOnOvDown(ev) {+ const blk = ev.target.closest ? ev.target.closest('.sbe-ov') : null;+ if (!blk) { SBE.ovSel = ''; sbePaint(); return; }+ const id = blk.dataset.id;+ SBE.ovSel = id;+ SBE.sel = '';+ const o = sbeOvById(SBE.overlays, id);+ if (!o) return;+ const grip = ev.target.closest('.sbe-grip');+ SBE.ovDrag = { id: id, x0: ev.clientX,+ mode: grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL') : 'move',+ fs0: sbeNum(o.film_start), fe0: sbeNum(o.film_end),+ moved: false, lane0: JSON.stringify(SBE.overlays),+ before: sbeSnapshot() };+ try { sbeEl('sbeOverlayLane').setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+}++function sbeOnOvMove(ev) {+ const d = SBE.ovDrag;+ if (!d) return;+ if (Math.abs(ev.clientX - d.x0) > 3) d.moved = true;+ if (!d.moved) return;+ const dt = (ev.clientX - d.x0) / SBE.pps;+ const tol = SBE_SNAP_PX / SBE.pps;+ const marks = sbeMusicSnaps(SBE.clips); // the CUTS: what a card aims at+ let r;+ if (d.mode === 'move') {+ r = sbeOvMove(SBE.overlays, d.id,+ sbeSnapToList(Math.max(0, d.fs0 + dt), marks, tol,+ sbeSnapEnabled(ev)));+ } else if (d.mode === 'trimL') {+ r = sbeOvTrim(SBE.overlays, d.id, 'l',+ sbeSnapToList(Math.max(0, d.fs0 + dt), marks, tol,+ sbeSnapEnabled(ev)));+ } else {+ r = sbeOvTrim(SBE.overlays, d.id, 'r',+ sbeSnapToList(Math.max(0, d.fe0 + dt), marks, tol,+ sbeSnapEnabled(ev)));+ }+ if (r && r.ok) SBE.overlays = r.overlays;+ sbePaint();+}++function sbeOnOvUp(ev) {+ const d = SBE.ovDrag;+ SBE.ovDrag = null;+ if (!d) return;+ if (!d.moved) { sbePaint(); return; }+ if (d.lane0 === JSON.stringify(SBE.overlays)) { sbePaint(); return; }+ SBE.undo.push(d.before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+}++// The strip's own ramps, drawn to scale. The SAME triangle the picture uses,+// because it is the same gesture and the muscle memory should transfer.+// The waveform and the level line, as ONE inline SVG per strip. An <svg>+// rather than a <canvas> because the lane is repainted on every drag and a+// canvas would need its own size/DPR bookkeeping to stay crisp; the point+// count here is a few hundred, which is nothing for the DOM.+// THE LEVEL LINE'S TARGET, CUT TO THE SPAN NOBODY ELSE OWNS. Same polyline as+// the one that is drawn, clipped to [x0, x1] with the y at each cut+// interpolated along the segment it falls in — so the target sits exactly on+// the line it belongs to rather than on a straight line between whole points.+// Returns '' when there is not enough left to aim at, and the caller then+// offers no target at all: an 8px stub of a control is worse than none, and+// the inspector's Sound section is the route that never depends on width.+function sbeLvlHitPath(pts, xOf, yOf, x0, x1) {+ if (!pts || pts.length < 2 || !(x1 - x0 >= SBE_LVL_MIN_SPAN)) return '';+ let d = '';+ for (let i = 0; i < pts.length - 1; i++) {+ const ax = xOf(pts[i][0]), bx = xOf(pts[i + 1][0]);+ const ay = yOf(pts[i][1]), by = yOf(pts[i + 1][1]);+ if (bx < x0 || ax > x1) continue;+ const sx = Math.max(ax, x0), ex = Math.min(bx, x1);+ const yAt = (x) => (bx - ax <= 1e-9) ? by : ay + (by - ay) * ((x - ax) / (bx - ax));+ d += (d ? 'L' : 'M') + sx.toFixed(2) + ',' + yAt(sx).toFixed(2)+ + 'L' + ex.toFixed(2) + ',' + yAt(ex).toFixed(2);+ }+ return d;+}++function sbeStripWave(c, w, px) {+ const peaks = sbeWaveWant(c.path);+ // THE STRIP IS AS TALL AS THE LANE WAS DRAGGED TO. Everything below is+ // expressed in H, so a taller lane is not a stretched picture — it is more+ // waveform, a longer level line and a point that is genuinely easier to hit.+ const H = sbeStripH(), MID = H / 2;+ const cols = Math.max(4, Math.floor(px));+ let body = '';+ if (peaks) {+ const slice = sbeWaveSlice(peaks, w.start, w.end, cols);+ let d = '';+ for (let i = 0; i < slice.length; i++) {+ const lo = Math.max(-1, slice[i][0]), hi = Math.min(1, slice[i][1]);+ const x = (i / cols) * px;+ d += 'M' + x.toFixed(2) + ',' + (MID - hi * MID).toFixed(2)+ + 'L' + x.toFixed(2) + ',' + (MID - lo * MID).toFixed(2);+ }+ body += '<path class="sbe-wave-p" d="' + d + '"/>';+ }+ // THE LEVEL LINE, drawn ON the waveform because that is what it acts on.+ // Unity sits at the top: a gain of 1 is "all of it", and a line that fell+ // to the middle at unity would read as half.+ const curve = sbeGainPoints(c, w.len);+ const pts = curve.length ? curve : [[0, 1], [w.len, 1]];+ const yOf = g => sbeStripY(g, H);+ const xOf = t => (w.len > 0 ? (t / w.len) * px : 0);+ let line = '';+ for (let i = 0; i < pts.length; i++) {+ line += (i ? 'L' : 'M') + xOf(pts[i][0]).toFixed(2) + ','+ + yOf(pts[i][1]).toFixed(2);+ }+ // THREE PATHS, ONE LINE. A dark stroke underneath so the level reads over a+ // loud passage instead of dissolving into it; the line itself; and a fat+ // transparent one on top that is the TARGET — `pointer-events: stroke`, so+ // the line is a thing you can hit rather than a thing you can see. Without+ // it the only way to reach a level was to already know a gesture.+ body += '<path class="sbe-lvl-u" d="' + line + '"/>';+ body += '<path class="sbe-lvl" d="' + line + '"/>';+ const shape = sbeStripEditable(c);+ // THE TWO ENDS OF THE LINE BELONG TO THE FADE HANDLES. The line is DRAWN end+ // to end, because that is the truth about the gain — but its TARGET stops+ // where the corner handles start, so the third affordance in this corner+ // cannot be ambiguous with the other two either. Without this the fat+ // transparent stroke ran the full width, under both 22px handles: the+ // handles win on z-index so nothing was actually stolen, but two controls+ // claiming the same rectangle is how the fade handle got lost inside the+ // trim grip in the first place, and "it happens to stack right" is not a+ // property anybody can see or keep.+ if (shape) {+ // IN USER UNITS, WHICH ARE NOT CSS PIXELS HERE. The strip is border-box+ // and 1px of border on each side, so its <svg> is laid out over `px - 2`+ // CSS pixels while its viewBox is `px` units wide — every user unit is a+ // hair narrower than a pixel, and the clip landed INSIDE the handle by+ // that fraction. Small on a wide strip and not small on a narrow one+ // (the error is 2/px of the span), so it is converted rather than padded.+ const scale = px / Math.max(1, px - 2);+ const clear = SBE_LVL_CLEAR * scale;+ const hit = sbeLvlHitPath(pts, xOf, yOf, clear, px - clear);+ if (hit) body += '<path class="sbe-lvl-hit" d="' + hit + '"/>';+ }+ // THE GHOST: where the click would land, drawn before it is clicked.+ const gh = SBE.kfGhost;+ if (shape && gh && gh.id === c.id) {+ body += '<circle class="sbe-kf-ghost" cx="' + xOf(gh.t).toFixed(2) + '" '+ + 'cy="' + yOf(gh.g).toFixed(2) + '" r="'+ + Math.max(3.6, Math.min(6.5, H / 5.5)).toFixed(2) + '"/>';+ }+ // Only the USER's points get a handle. The fade corners are already a+ // gesture of their own, and putting a dot on them would offer two ways to+ // drag the same number in opposite directions.+ const own = sbeAfx(c, w.len).points;+ // The dot grows with the strip, within reason: 3.2 was the whole of the+ // target in a 20px lane and is the floor here, and past ~6 a handle starts+ // hiding the line it is on.+ const R = Math.max(3.2, Math.min(6, H / 6));+ for (let i = 0; i < own.length; i++) {+ body += '<circle class="sbe-kf" data-kf="' + i + '" '+ + 'cx="' + xOf(own[i][0]).toFixed(2) + '" '+ + 'cy="' + yOf(sbeLerpGain(curve.length ? curve : own, own[i][0])).toFixed(2) + '" '+ + 'style="--kf-r:' + R.toFixed(2) + 'px" '+ + 'r="' + R.toFixed(2) + '"/>';+ }+ return '<svg class="sbe-wave-svg" width="' + Math.max(1, px).toFixed(0)+ + '" height="' + H + '" viewBox="0 0 ' + Math.max(1, px).toFixed(0)+ + ' ' + H + '" preserveAspectRatio="none">' + body + '</svg>';+}++// ONE RULE, ASKED ONCE. A level belongs to a strip you can shape: not locked,+// and unlinked — the same rule the double-click has always enforced, now named+// so the line, the ghost, the click and the inspector cannot disagree about it.+function sbeStripEditable(c) {+ if (!c || c.locked) return false;+ if (c.has_audio === false) return false;+ return !sbeClipAudio(c).linked;+}++// Where the pointer is, in the coordinates a level cares about: which strip,+// how far along it, and what gain that height means. Null when the pointer is+// not over a strip that could take a point.+function sbeStripAt(ev) {+ const blk = ev.target && ev.target.closest ? ev.target.closest('.sbe-aclip') : null;+ if (!blk) return null;+ // NOT WHILE THE POINTER IS ON A CORNER HANDLE. The clipped hit path already+ // keeps the LINE off those pixels, but this pair also answers a proximity+ // test that knows nothing about paths — and it is what the hover ghost asks,+ // so without this a fade handle would sit under a ghost promising a+ // keyframe it could never place. Asked of the real hit target rather than of+ // a rectangle, so it stays exact at every lane height and every zoom.+ if (ev.target.closest('.sbe-fade-h')) return null;+ const c = sbeById(SBE.clips, blk.dataset.id);+ if (!c || !sbeStripEditable(c)) return null;+ const r = blk.getBoundingClientRect();+ const w = sbeClipAudio(c);+ return {+ c: c, id: c.id, rect: r, len: w.len,+ t: w.len * Math.max(0, Math.min(1, (ev.clientX - r.left) / Math.max(1, r.width))),+ g: sbeStripGain(ev.clientY, r.top, r.height),+ };+}++// HOVER TEACHES. Near the line, a ghost point follows the pointer and the+// cursor turns into the one you use to change a level — so the answer to "how+// do I add a keyframe" is visible before anything is clicked. Away from it the+// strip is what it always was: a thing you drag.+function sbeAudioGhost(ev) {+ const at = sbeStripAt(ev);+ let want = null;+ if (at) {+ const H = at.rect.height;+ const onLine = sbeStripY(sbeGainAt(at.c, at.len, at.t), H);+ if (Math.abs((ev.clientY - at.rect.top) - onLine) <= SBE_LVL_GRAB) {+ want = { id: at.id, t: sbeRound(at.t), g: sbeRound(at.g) };+ }+ }+ const now = SBE.kfGhost;+ const same = (!want && !now) || (want && now && want.id === now.id+ && Math.abs(want.t - now.t) < 1e-4 && Math.abs(want.g - now.g) < 2e-3);+ if (same) return;+ SBE.kfGhost = want;+ // ONE LANE, NOT THE WHOLE TIMELINE. A ghost that repainted every clip block+ // and both canvases on every mouse move would make the pointer feel heavy+ // over the one lane this is meant to make inviting.+ sbePaintAudioLane();+}++function sbeAudioGhostClear() {+ if (!SBE.kfGhost) return;+ SBE.kfGhost = null;+ sbePaintAudioLane();+}++// A SINGLE CLICK ON THE LINE PLACES A POINT — and the same gesture goes on to+// drag it, so "click, then set the level" is one movement. Double-click still+// works, because muscle memory should not be taken away to teach somebody+// else. Returns true when it claimed the gesture.+function sbeLevelClick(ev) {+ const at = sbeStripAt(ev);+ if (!at) return false;+ const H = at.rect.height;+ const onLine = sbeStripY(sbeGainAt(at.c, at.len, at.t), H);+ const near = Math.abs((ev.clientY - at.rect.top) - onLine) <= SBE_LVL_GRAB;+ if (!near && !ev.target.closest('.sbe-lvl-hit')) return false;+ const before = sbeSnapshot();+ const r = sbeAddKeyframe(SBE.clips, at.id, at.t, at.g);+ if (!r.ok) return false;+ SBE.clips = r.clips;+ SBE.sel = at.id;+ SBE.kfGhost = null;+ // The point it just made is the point the drag continues on, so a level is+ // set in one gesture rather than two.+ const pts = sbeAfx(sbeById(SBE.clips, at.id), at.len).points;+ let idx = 0;+ for (let i = 0; i < pts.length; i++) {+ if (Math.abs(pts[i][0] - sbeRound(at.t)) < 1e-3) { idx = i; break; }+ }+ SBE.kfDrag = { id: at.id, index: idx, before: before, moved: true,+ rect: at.rect };+ try { sbeEl('sbeAudioLane').setPointerCapture(ev.pointerId); } catch (e) {}+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ return true;+}++// RIGHT-CLICK REMOVES. Shift-click still does too, but a modifier on a 6px+// target is not a route anybody finds — and a context menu is where every+// other application on this machine keeps "remove".+function sbeOnAudioMenu(ev) {+ const kf = ev.target && ev.target.closest ? ev.target.closest('.sbe-kf') : null;+ if (!kf) return;+ const blk = ev.target.closest('.sbe-aclip');+ const c = blk ? sbeById(SBE.clips, blk.dataset.id) : null;+ if (!c || c.locked) return;+ ev.preventDefault();+ SBE.sel = c.id;+ sbeMutate(cs => sbeDeleteKeyframe(cs, c.id, sbeNum(kf.dataset.kf)));+}++// THE ROUTE THAT NEEDS NO GESTURE AT ALL. The inspector's Sound section can+// put a point exactly where the playhead is, which is also the only way to+// place one at a frame you have actually listened to.+function sbeAddPointAtPlayhead() {+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) return;+ if (!sbeStripEditable(c)) {+ phosToast('Unlink this clip\'s sound first — a level line belongs to a '+ + 'strip you can shape.', { duration: 6000 });+ return;+ }+ const w = sbeClipAudio(c);+ const t = sbeNum(SBE.playhead) - sbeNum(w.film_start);+ if (t < -1e-6 || t > w.len + 1e-6) {+ phosToast('Move the playhead over this clip\'s sound first — a point is '+ + 'placed where you are listening.', { duration: 6000 });+ return;+ }+ const at = Math.max(0, Math.min(w.len, t));+ const r = sbeAddKeyframe(SBE.clips, c.id, at, sbeGainAt(c, w.len, at));+ if (!r.ok) {+ phosToast(r.why === 'there is already a point here'+ ? 'There is already a point at the playhead — drag it, or right-click it '+ + 'to remove it.' : 'That clip is locked.', { duration: 6000 });+ return;+ }+ sbeMutate(() => ({ clips: r.clips, ok: true }));+}++function sbeClearPoints() {+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) return;+ sbeMutate(cs => sbeAfxWrite(cs, c.id, []));+}++// THE LEGEND, in one function, because it is the only thing that tells a new+// user what the gestures are and it has to be true. The Keys chip renders it.+function sbeKeysLegend() {+ const k = t => '<span class="sbe-kbd">' + t + '</span>';+ return [+ ['Drag', 'move a clip · handles to trim'],+ [k('Space'), 'play / pause'],+ [k('←') + k('→'), 'one frame'],+ [k('S'), 'split at the playhead'],+ [k('⌫'), 'ripple delete'],+ [k('Alt'), 'held: ignore the beat grid'],+ [k('Shift'), 'held: reorder instead of move'],+ ['Levels', 'click the yellow line to add a point · drag it to set the '+ + 'level · right-click it to remove · ' + k('Shift')+ + '-click removes too'],+ ['Sound', 'the music strip drags and trims like a clip'],+ ['Timeline', 'drag its top edge for more height · double-click to reset'],+ ].map(r => '<span class="sbe-key-row"><b>' + r[0] + '</b>' + r[1] + '</span>')+ .join('');+}++function sbeAudioFadeMarks(c, w) {+ const e = sbeAfx(c, w.len);+ let out = '';+ if (e.fade_in > 1e-9) {+ out += '<div class="sbe-cl-fade in" style="left:0;width:'+ + sbePx(e.fade_in).toFixed(1) + 'px"></div>';+ }+ if (e.fade_out > 1e-9) {+ out += '<div class="sbe-cl-fade out" style="right:0;width:'+ + sbePx(e.fade_out).toFixed(1) + 'px"></div>';+ }+ return out;+}++// DOUBLE-CLICK ADDS A POINT, on the strip body and nowhere else. Plain drag+// stays "move the strip" — the gesture every lane on this timeline already+// uses — so the control case is opt-in and the simple case is untouched.+function sbeOnAudioDbl(ev) {+ const blk = ev.target.closest ? ev.target.closest('.sbe-aclip') : null;+ if (!blk) return;+ if (ev.target.closest('.sbe-kf') || ev.target.closest('.sbe-fade-h')) return;+ const c = sbeById(SBE.clips, blk.dataset.id);+ if (!c) return;+ const w = sbeClipAudio(c);+ if (w.linked) {+ phosToast('Unlink this clip\'s sound first — a level line belongs to a '+ + 'strip you can shape.', { duration: 6000 });+ return;+ }+ const r = blk.getBoundingClientRect();+ const t = w.len * Math.max(0, Math.min(1, (ev.clientX - r.left) / Math.max(1, r.width)));+ // THE STRIP'S OWN RECTANGLE, through the one pair every gesture shares. The+ // `- 3` and `/ 20` this replaces were a lane that no longer has that inset+ // and a height the top edge can now drag to four times over: on a tall strip+ // every double-click past the first fourteen pixels landed a point at+ // silence, whatever the pointer was actually pointing at.+ const g = sbeStripGain(ev.clientY, r.top, r.height);+ SBE.sel = c.id;+ sbeMutate(cs => sbeAddKeyframe(cs, c.id, t, g));+ ev.preventDefault();+}++function sbeAudioFadeCommit(edge, v) {+ if (!SBE.sel) return;+ sbeMutate(cs => sbeSetAudioFade(cs, SBE.sel, edge, v));+}++function sbeOnAudioDown(ev) {+ // The sync flag is a BUTTON inside the strip, and pointerdown would start a+ // drag before its click ever fired.+ const badge = ev.target.closest('.sbe-sync');+ if (badge) { ev.preventDefault(); sbeResyncSel(badge.dataset.sync); return; }+ // THE SAME PRECEDENCE THE PICTURE LANE SET: the corner handle sits over the+ // left grip's hit area, and a fade drag is the more specific gesture of the+ // two, so it is tested first. One rule for both lanes or the strip would+ // behave differently from the block above it for no reason a user could+ // name.+ // GESTURE PRECEDENCE ON THIS LANE, most specific first, and it is the same+ // shape the picture lane already uses:+ // 1. the sync flag — a button+ // 2. a keyframe dot — 6px of target inside the strip body+ // 3. the corner handle — sits over the left grip's hit area+ // 4. the grips — trim+ // 5. the strip body — move (and DOUBLE-CLICK there adds a point)+ // The dot is smaller than the body and is tested before it, so grabbing a+ // point can never be mistaken for moving the strip.+ const kf = ev.target.closest('.sbe-kf');+ if (kf) {+ const blk1 = ev.target.closest('.sbe-aclip');+ const c1 = blk1 ? sbeById(SBE.clips, blk1.dataset.id) : null;+ if (c1 && !c1.locked) {+ SBE.sel = c1.id;+ // SHIFT-CLICK DELETES. A modifier rather than a second affordance+ // drawn on a 6px target, which would be a delete nobody meant.+ if (ev.shiftKey) {+ sbeMutate(cs => sbeDeleteKeyframe(cs, c1.id, sbeNum(kf.dataset.kf)));+ ev.preventDefault();+ return;+ }+ SBE.kfDrag = { id: c1.id, index: sbeNum(kf.dataset.kf),+ before: sbeSnapshot(), moved: false,+ rect: blk1.getBoundingClientRect() };+ try { sbeEl('sbeAudioLane').setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+ }+ return;+ }+ const afh = ev.target.closest('.sbe-fade-h');+ if (afh) {+ const blk0 = ev.target.closest('.sbe-aclip');+ const c0 = blk0 ? sbeById(SBE.clips, blk0.dataset.id) : null;+ if (c0) {+ SBE.sel = c0.id;+ const w0 = sbeClipAudio(c0);+ const e0 = sbeAfx(c0, w0.len);+ SBE.audioDrag = {+ id: c0.id, mode: 'afade', edge: afh.dataset.afade, x0: ev.clientX,+ f0: (afh.dataset.afade === 'out') ? e0.fade_out : e0.fade_in,+ before: sbeSnapshot(), moved: false,+ };+ try { sbeEl('sbeAudioLane').setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+ }+ return;+ }+ // THE LINE ITSELF, after the two handles at the strip's corners and before+ // the strip body: a click within SBE_LVL_GRAB of the level places a point+ // and starts dragging it, which is the gesture the owner could not find. The+ // grips are tested first — they are 7px of edge and the more specific target+ // — so trimming a strip can never be mistaken for shaping it.+ if (!ev.target.closest('.sbe-grip') && sbeLevelClick(ev)) {+ ev.preventDefault();+ return;+ }+ const blk = ev.target.closest('.sbe-aclip');+ if (!blk) return;+ const id = blk.dataset.id;+ SBE.sel = id;+ SBE.drag = null; // a pointerup lost off the edge must not wedge a lane+ const c = sbeById(SBE.clips, id);+ if (!c) return;+ const w = sbeClipAudio(c);+ if (w.linked) {+ // Not an error — an instruction. The toggle is one click away and the+ // inspector is already showing this clip.+ sbePaint();+ phosToast(w.coupled+ ? 'This sound is linked to its picture at ' + sbeDriftLabel(sbeAudioDrift(c))+ + ' and moves with it. Unlink it in the inspector to slide it on its own.'+ : 'That clip\'s sound is linked to its picture. Unlink it in the '+ + 'inspector to slide it under the neighbour.', { duration: 6000 });+ return;+ }+ if (c.locked) {+ sbePaint();+ phosToast('That shot is locked, so its sound is locked with it. Click '+ + 'Unlock in the inspector.', { duration: 6000 });+ return;+ }+ const lane = sbeEl('sbeAudioLane');+ const grip = ev.target.closest('.sbe-grip');+ SBE.audioDrag = {+ id: id, mode: grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL') : 'move',+ x0: ev.clientX, fs0: w.film_start, fe0: w.film_start + w.len,+ before: sbeSnapshot(), moved: false,+ };+ blk.classList.add('is-drag');+ try { lane.setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+}++function sbeOnAudioMove(ev) {+ const k = SBE.kfDrag;+ // NOTHING IS BEING DRAGGED: this is a hover, and a hover is where the level+ // line teaches. Cheap and early — one rect read, and a repaint only when the+ // ghost actually moves.+ if (!k && !SBE.audioDrag) { sbeAudioGhost(ev); return; }+ if (k) {+ const c = sbeById(SBE.clips, k.id);+ if (!c) return;+ const w = sbeClipAudio(c);+ const r = k.rect;+ const t = w.len * Math.max(0, Math.min(1,+ (ev.clientX - r.left) / Math.max(1, r.width)));+ // THE BAND IS THE STRIP, measured. It used to be `- 3` and `/ 20`: a 3px+ // inset the SVG no longer has and the height of a lane that can now be+ // dragged to eight times that. `r` is the strip's own rectangle, so the+ // maths follows the lane wherever the handle put it. UNITY IS THE TOP, so+ // the gain falls as the pointer descends — which is what the line the user+ // is looking at does.+ const g = sbeStripGain(ev.clientY, r.top, r.height);+ k.moved = true;+ const res = sbeMoveKeyframe(SBE.clips, k.id, k.index, t, g);+ if (res.ok) SBE.clips = res.clips;+ sbePaint();+ return;+ }+ const d = SBE.audioDrag;+ if (!d) return;+ if (Math.abs(ev.clientX - d.x0) > 3) d.moved = true;+ if (!d.moved) return;+ if (d.mode === 'afade') {+ const adt = (d.edge === 'out') ? -(ev.clientX - d.x0) / SBE.pps+ : (ev.clientX - d.x0) / SBE.pps;+ const r2 = sbeSetAudioFade(SBE.clips, d.id, d.edge, Math.max(0, d.f0 + adt));+ if (r2.ok) SBE.clips = r2.clips;+ sbePaint();+ return;+ }+ const dt = (ev.clientX - d.x0) / SBE.pps;+ const tol = SBE_SNAP_PX / SBE.pps;+ const marks = sbeMusicSnaps(SBE.clips); // the CUTS: what a J-cut aims at+ const anchor = (d.mode === 'trimR') ? d.fe0 : d.fs0;+ const want = sbeSnapToList(Math.max(0, anchor + dt), marks, tol,+ sbeSnapEnabled(ev));+ const r = sbeAudioEdit(SBE.clips, d.id, d.mode, want);+ if (r.ok) SBE.clips = r.clips;+ sbePaint();+}++function sbeOnAudioUp(ev) {+ const k = SBE.kfDrag;+ SBE.kfDrag = null;+ if (k) {+ if (k.moved) {+ SBE.undo.push(k.before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbeQueueSave();+ }+ sbePaint();+ return;+ }+ const d = SBE.audioDrag;+ SBE.audioDrag = null;+ if (!d) return;+ document.querySelectorAll('.sbe-aclip.is-drag').forEach(el => el.classList.remove('is-drag'));+ if (!d.moved) { sbePaint(); return; }+ SBE.undo.push(d.before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+}++function sbeToggleAudioLink() {+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) return;+ const w = sbeClipAudio(c);+ const drift = sbeAudioDrift(c);+ const ok = sbeMutate(cs => sbeSetAudioLink(cs, c.id, !w.linked));+ if (!ok) return;+ phosToast(w.linked+ ? 'Sound unlinked — drag the strip under this clip to slide it, or pull '+ + 'either end. The picture stays where it is, and it stays draggable '+ + 'from both edges.'+ : (Math.abs(drift) > SBE_SYNC_TOL+ ? 'Linked at ' + sbeDriftLabel(drift) + ' — the sound keeps that '+ + 'offset and now travels with the picture. Resync puts it back '+ + 'under its own frame.'+ : 'Sound re-linked to the picture.'), { duration: 7000 });+}++function sbeDeleteStripSel() {+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) return;+ const ok = sbeMutate(cs => sbeDeleteStrip(cs, c.id));+ if (!ok) return;+ phosToast('Sound removed — the picture plays silent and stays exactly where '+ + 'it is. Unmute in Sound to bring it back.', { duration: 7000 });+}++function sbeToggleClipMute() {+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) return;+ const on = !sbeClipMuted(c);+ const ok = sbeMutate(cs => sbeSetClipMute(cs, c.id, on));+ if (!ok) return;+ phosToast(on+ ? 'Clip sound muted — it is off in the preview, the render and the export. '+ + 'The strip stays where it is, and unmuting puts it back.'+ : 'Clip sound unmuted.', { duration: 6000 });+}++// THE REMATCH, from the flag on either half or from the inspector.+function sbeResyncSel(id) {+ const who = id || SBE.sel;+ const c = sbeById(SBE.clips, who);+ if (!c) return;+ SBE.sel = who;+ const was = sbeAudioDrift(c);+ const ok = sbeMutate(cs => sbeResyncAudio(cs, who));+ if (!ok) { sbePaint(); return; }+ phosToast('Sound rematched to its picture — it was ' + sbeDriftLabel(was)+ + ' out. It is still unlinked, so it can be moved again.',+ { duration: 6000 });+}++function sbePaintHead() {+ const el = sbeEl('sbeHead');+ if (el) el.style.left = sbePx(SBE.playhead).toFixed(1) + 'px';+ sbeFollow();+ const t = sbeEl('sbeTime');+ if (t) {+ t.innerHTML = escapeHtml(sbeFmtTime(SBE.playhead)) ++ ' <span>/ ' + escapeHtml(sbeFmtTime(sbeFilmDuration(SBE.clips))) + '</span>';+ }+}++// ---------------------------------------------------------------------------+// THE POPOVER, once, for four menus+// ---------------------------------------------------------------------------+// Every menu on this screen holds the REAL controls — moved, not rebuilt — so+// an id the client already writes to keeps working wherever it now lives. The+// panel is `position: fixed` and measured against the anchor, which is the+// whole reason it can exist at all: an open menu must not push the workspace+// around, the same rule the notice surface has always followed.+function sbePopToggle(id, anchorId) {+ const el = sbeEl(id);+ if (!el) return;+ const open = el.hidden;+ sbePopCloseAll(open ? id : '');+ if (!open) return;+ el.hidden = false;+ const a = sbeEl(anchorId);+ const r = a ? a.getBoundingClientRect() : null;+ const box = el.getBoundingClientRect();+ if (r) {+ // Right-aligned to the anchor, flipped up when there is no room below,+ // and clamped so a menu can never be opened off the edge of the window.+ let left = Math.min(window.innerWidth - box.width - 8,+ Math.max(8, r.right - box.width));+ let top = r.bottom + 6;+ if (top + box.height > window.innerHeight - 8) {+ top = Math.max(8, r.top - box.height - 6);+ }+ el.style.left = Math.round(left) + 'px';+ el.style.top = Math.round(top) + 'px';+ }+ el.dataset.anchor = anchorId || '';+}++function sbePopCloseAll(except) {+ for (const id of ['sbeRenderMenu', 'sbeMoreMenu', 'sbeKeysPop', 'sbeMusicMenu']) {+ if (id === except) continue;+ const el = sbeEl(id);+ if (el && !el.hidden) el.hidden = true;+ }+}++// A menu closes when you click away from it, and when you press Escape —+// except that Escape already closes the DOCUMENT here, so an open menu eats+// the first press and the second one leaves, which is the order every other+// application uses.+function sbePopGlobal(ev) {+ if (ev.target && ev.target.closest+ && (ev.target.closest('.sbe-pop') || ev.target.closest('[aria-haspopup]'))) return;+ sbePopCloseAll('');+}++function sbePopAnyOpen() {+ for (const id of ['sbeRenderMenu', 'sbeMoreMenu', 'sbeKeysPop', 'sbeMusicMenu']) {+ const el = sbeEl(id);+ if (el && !el.hidden) return true;+ }+ return false;+}++// The two lane heads that carry a fact rather than a label: how much picture+// there is, and how much of the sound has been pulled off it.+function sbePaintHeads() {+ const pic = sbeEl('sbeHeadPic');+ if (pic) {+ const n = SBE.clips.length;+ pic.textContent = n+ ? n + ' clip' + (n === 1 ? '' : 's') + ' · ' + sbeFmtTime(sbeFilmDuration(SBE.clips))+ : 'empty';+ }+ const aud = sbeEl('sbeHeadAud');+ if (aud) {+ let split = 0, muted = 0;+ for (const c of SBE.clips) {+ if (sbeKind(c) !== 'video') continue;+ if (sbeClipAudio(c).split) split++;+ if (sbeClipMuted(c)) muted++;+ }+ const bits = [];+ if (split) bits.push(split + ' unlinked');+ if (muted) bits.push(muted + ' muted');+ aud.textContent = bits.length ? bits.join(' · ') : 'linked to the picture';+ aud.classList.toggle('is-live', split > 0);+ }+}++// The legend is painted rather than written into the markup so there is one+// copy of it — see sbeKeysLegend.+function sbePaintKeys() {+ const el = sbeEl('sbeKeys');+ if (el && !el._done) { el.innerHTML = sbeKeysLegend(); el._done = 1; }+}++function sbePaintInspector() {+ const box = sbeEl('sbeInspect');+ // A SELECTED CARD OWNS THE INSPECTOR. It is a lane of its own, so it gets+ // the same two sections that mean anything for it — what it is, and its+ // effects — and none of the Sound section, which it has no half of.+ const ov = sbeOvById(SBE.overlays, SBE.ovSel);+ if (ov && !SBE.sel) {+ const oe = sbeFx(ov);+ const orow = (edge, val) =>+ '<span class="sbe-fade-row">' ++ '<label for="sbeOvFade' + edge + '">Fade ' + edge + '</label>' ++ '<input type="number" class="sb-input sbe-fade-num" id="sbeOvFade' + edge + '" ' ++ 'min="0" step="0.05" value="' + val.toFixed(2) + '" ' ++ 'onchange="sbeOvFadeCommit(\'' + edge + '\', this.value)">' ++ '<span class="sbe-adj-val">s</span></span>';+ box.innerHTML =+ '<b>' + escapeHtml(sbeNiceName(ov.title+ || String(ov.path || '').split('/').pop() || 'overlay')) + '</b>' ++ '<span>overlay · ' + escapeHtml(sbeOvKind(ov)) + '</span>' ++ '<span>' + sbeNum(ov.film_start).toFixed(2) + '–' ++ sbeNum(ov.film_end).toFixed(2) + 's on the __SEQ__</span>' ++ '<span class="sbe-why">Composited over the picture. Its transparency is '+ + 'kept in the preview, the render and the export.</span>' ++ '<div class="sbe-sect"><div class="sbe-sect-h">Effects</div>' ++ '<div class="sbe-sect-b">' + orow('in', oe.fade_in)+ + orow('out', oe.fade_out) + '</div></div>' ++ '<div class="sbe-sect"><div class="sbe-sect-h">Overlay</div>' ++ '<div class="sbe-sect-b">' ++ '<button type="button" class="ghost-btn" onclick="sbeOvDeleteSel()">Remove overlay</button>' ++ '</div></div>';+ return;+ }+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) {+ const n = SBE.clips.length;+ const holes = sbeHoles(SBE.clips);+ const guess = sbeGridIsAGuess(SBE.beats);+ let bits = [n + ' clip' + (n === 1 ? '' : 's'),+ sbeFmtTime(sbeFilmDuration(SBE.clips)) + ' of the __SEQ__'];+ if (holes.length) {+ bits.push(holes.length + ' hole' + (holes.length === 1 ? '' : 's') + ' · ' ++ holes.reduce((a, g) => a + g.duration, 0).toFixed(2) + 's');+ }+ if (SBE.beats && SBE.beats.bpm) {+ bits.push(Math.round(SBE.beats.bpm) + ' bpm' ++ (guess ? ' — a guess, confidence ' + sbeNum(SBE.beats.confidence).toFixed(2) : ''));+ }+ box.innerHTML = '<span class="sbe-why">' + escapeHtml(bits.join(' · ')) ++ (n ? '. Click a clip to see why it was cut where it was.'+ : '.') + '</span>';+ return;+ }+ const a = c.analysis || {};+ const kind = sbeKind(c);+ const bright = sbeBright(c);+ const errs = (SBE.errors.byId || {})[c.id] || [];+ const why = [];+ if (a.reason) why.push(a.reason);+ if (a.snap && a.snap.kind && a.snap.kind !== 'none') {+ why.push('snapped to the ' + a.snap.kind + ' (' + Math.round(sbeNum(a.snap.shift_ms)) + ' ms)');+ }+ if (a.usable === false) why.push('the auto-editor did not think this window was usable');+ for (const note of (a.notes || [])) why.push(note);+ const label = (kind === 'slug') ? 'Black'+ : (c.title || String(c.path || '').split('/').pop() || 'clip');+ // Only a video HAS a source window; the other two are their slot and nothing+ // else, so the line that would report their in/out is the line that would+ // invent one.+ const src = (kind === 'video')+ ? ('<span>source ' + sbeNum(c.start).toFixed(2) + '–' + sbeNum(c.end).toFixed(2) + 's' ++ (c.duration ? ' of ' + sbeNum(c.duration).toFixed(2) + 's' : '') + '</span>')+ : ('<span>' + escapeHtml(kind === 'slug'+ ? 'black — no file, drawn by the render'+ : 'a still, held for its slot') ++ ' · drag a handle to change how long</span>');+ // BRIGHTNESS, AND NOT A COLOUR PAGE. One constant-per-clip value, the flat+ // Adjust panel CapCut ships, refused for a slug because a slug's colour is+ // what a slug IS.+ const adjust = (kind === 'slug') ? '' :+ '<span class="sbe-adjust">Brightness' ++ '<input type="range" id="sbeBright" min="-0.5" max="0.5" step="0.01" ' ++ 'value="' + bright.toFixed(2) + '" ' ++ 'oninput="sbeBrightPreview(this.value)" ' ++ 'onchange="sbeBrightCommit(this.value)" ' ++ 'title="Approximate on screen, exact in the render.">' ++ '<span class="sbe-adj-val" id="sbeBrightVal">' ++ (bright > 0 ? '+' : '') + bright.toFixed(2) + '</span>' ++ (Math.abs(bright) >= 1e-6+ ? '<button type="button" class="ghost-btn" onclick="sbeBrightCommit(0)">Reset</button>'+ : '') ++ '</span>';+ // THREE SECTIONS, because the inspector grew one control at a time and had+ // become a flat run of buttons with a brightness slider floating in the+ // middle. Clip / Sound / Effects — and Effects is the home the ruling asked+ // for, so the next one lands without a decision.+ const sect = (name, body) => body+ ? '<div class="sbe-sect"><div class="sbe-sect-h">' + name + '</div>' ++ '<div class="sbe-sect-b">' + body + '</div></div>'+ : '';+ const e = sbeFx(c);+ const fadeRow = (edge, val) =>+ '<span class="sbe-fade-row">' ++ '<label for="sbeFade' + edge + '">Fade ' + (edge === 'in' ? 'in' : 'out') + '</label>' ++ '<input type="number" class="sb-input sbe-fade-num" id="sbeFade' + edge + '" ' ++ 'min="0" max="' + sbeClipLen(c).toFixed(2) + '" step="0.05" ' ++ 'value="' + val.toFixed(2) + '" ' ++ 'onchange="sbeFadeCommit(\'' + edge + '\', this.value)" ' ++ 'title="Seconds. Drag the corner of the clip for the same thing by eye.">' ++ '<span class="sbe-adj-val">s</span>' ++ (val > 1e-6+ ? '<button type="button" class="ghost-btn" onclick="sbeFadeCommit(\'' + edge + '\', 0)">Clear</button>'+ : '') ++ '</span>';+ box.innerHTML =+ '<b>' + escapeHtml(label) + '</b>' + src ++ '<span>film ' + sbeNum(c.film_start).toFixed(2) + '–' + sbeNum(c.film_end).toFixed(2) + 's</span>' ++ '<span>' + escapeHtml(c.source === 'human' ? 'moved by hand' : 'placed by the auto-editor') + '</span>' ++ // THE PAIR'S OWN LINE. An unlinked strip is either where the picture would+ // have played it or it is not, and the number is the only way to tell at+ // any zoom — this is the sentence the owner had no way to read.+ ((kind === 'video' && sbeClipAudio(c).split)+ ? '<span>' + escapeHtml(sbeClipAudio(c).coupled+ ? 'sound linked at ' + sbeDriftLabel(sbeAudioDrift(c))+ + ' — it travels with this picture'+ : (sbeAudioInSync(c)+ ? 'sound unlinked, in sync with its picture'+ : 'sound unlinked, ' + sbeDriftLabel(sbeAudioDrift(c)) + ' out of sync ('+ + (sbeAudioDrift(c) > 0 ? 'late' : 'early') + ')')) + '</span>'+ : '') ++ ((kind === 'video' && !c.proxy)+ ? '<span>no proxy — scrubbing this one decodes from the top of the clip</span>' : '') ++ adjust ++ '<span class="sbe-why">' + escapeHtml(why.join(' · ')) + '</span>' ++ (errs.length ? '<span style="color:var(--danger)">' + escapeHtml(errs[0].message) + '</span>' : '') ++ sect('Clip',+ '<button type="button" class="ghost-btn" onclick="sbeToggleLock()">' ++ (c.locked ? 'Unlock' : 'Lock') + '</button>' ++ '<button type="button" class="ghost-btn" onclick="sbeRippleSelected()">Ripple delete</button>') ++ sect('Sound',+ // THE J-CUT'S ONE SWITCH. Only a video clip has sound of its own, so+ // only a video clip is offered it.+ (kind === 'video'+ ? '<button type="button" class="ghost-btn" onclick="sbeToggleAudioLink()" ' ++ 'title="' + escapeHtml(sbeClipAudio(c).linked+ ? 'Let this clip\'s sound move and trim on its own — the J-cut and the L-cut. The picture stays draggable from both edges.'+ : (sbeAudioInSync(c)+ ? 'Put the sound back under its own picture'+ : 'Keep the ' + sbeDriftLabel(sbeAudioDrift(c)) + ' offset you made '+ + 'and travel together from here. Resync is the button that '+ + 'puts it back under its own frame.')) + '">' ++ (sbeClipAudio(c).linked ? 'Unlink sound'+ : (sbeAudioIsThePicture(c) ? 'Re-link sound'+ : 'Link sound' + (sbeAudioInSync(c) ? ''+ : ' at ' + sbeDriftLabel(sbeAudioDrift(c))))) + '</button>'+ : '') ++ // MUTE, and it is offered whether the sound is linked, unlinked or+ // travelling — muting silences the CLIP's sound wherever its strip is.+ // Refused only for a clip whose file has no audio track at all, because+ // there is nothing there to switch off.+ ((kind === 'video' && c.has_audio !== false)+ ? '<button type="button" class="ghost-btn" onclick="sbeToggleClipMute()" ' ++ 'title="' + escapeHtml(sbeClipMuted(c)+ ? 'Let this clip\'s own sound play again'+ : 'Switch this clip\'s own sound off — in the preview, in the render '+ + 'and in the export. The soundtrack is not affected.') + '">' ++ (sbeClipMuted(c) ? 'Unmute sound' : 'Mute sound') + '</button>'+ : '') ++ // DELETE THE STRIP, not the clip. Offered only once the two halves are+ // actually separate — on a linked clip "delete the sound" and "mute" would+ // be the same button twice.+ ((kind === 'video' && sbeClipAudio(c).split)+ ? '<button type="button" class="ghost-btn" onclick="sbeDeleteStripSel()" ' ++ 'title="' + escapeHtml('Remove this clip\'s sound. The picture keeps '+ + 'playing, silent, and does not move.') + '">Delete sound</button>'+ : '') ++ // RESYNC IS NOT RE-LINK, and the two sit next to each other so the+ // difference is legible: re-link puts the sound back UNDER the picture+ // permanently, resync only slides it back into place and leaves it free.+ ((kind === 'video' && sbeClipAudio(c).split && !sbeAudioInSync(c))+ ? '<button type="button" class="ghost-btn" onclick="sbeResyncSel()" ' ++ 'title="' + escapeHtml('Slide the sound back to where its own picture '+ + 'plays it. The trim you gave it is kept, and it stays unlinked.') ++ '">Resync sound (' + escapeHtml(sbeDriftLabel(sbeAudioDrift(c))) + ')</button>'+ : '') ++ // THE SOUND'S OWN RAMPS LIVE HERE, not under a fourth heading. Three+ // sections is what docs/EDITOR_EFFECTS_MODEL.md describes and what the+ // rail has room for; a "Sound fades" heading of its own pushed the+ // inspector past 460px and made two adjacent headings both say "sound".+ ((kind === 'video' && c.has_audio !== false)+ ? (() => {+ const w2 = sbeClipAudio(c);+ const ae = sbeAfx(c, w2.len);+ const arow = (edge, val) =>+ '<span class="sbe-fade-row">' ++ '<label for="sbeAFade' + edge + '">Fade ' + edge + '</label>' ++ '<input type="number" class="sb-input sbe-fade-num" ' ++ 'id="sbeAFade' + edge + '" min="0" max="' + w2.len.toFixed(2) + '" ' ++ 'step="0.05" value="' + val.toFixed(2) + '" ' ++ 'onchange="sbeAudioFadeCommit(\'' + edge + '\', this.value)" ' ++ 'title="Seconds. Drag the corner of the sound strip for the same thing by eye, or double-click the strip to add a level point.">' ++ '<span class="sbe-adj-val">s</span></span>';+ // LEVELS, SPELLED OUT. The line on the strip is the fast way and it+ // now teaches itself; this is the way that needs no gesture at all,+ // and it is also the only way to place a point at a frame you have+ // actually listened to. On a linked strip it says what to do rather+ // than offering a button that would refuse.+ const shape = sbeStripEditable(c);+ const n = ae.points.length;+ const levels = '<span class="sbe-fade-row sbe-levels">'+ + '<label>Levels</label>'+ + (shape+ ? '<button type="button" class="ghost-btn" '+ + 'onclick="sbeAddPointAtPlayhead()" '+ + 'title="Puts a level point where the playhead is. On the '+ + 'strip: click the yellow line to add one, drag it to set '+ + 'the level, right-click it to remove it.">'+ + 'Add point at playhead</button>'+ + (n ? '<button type="button" class="ghost-btn" '+ + 'onclick="sbeClearPoints()" '+ + 'title="Removes every level point on this strip. The '+ + 'fades stay.">Clear ' + n + '</button>'+ : '<span class="sbe-adj-val">click the yellow line</span>')+ : '<span class="sbe-adj-val">unlink the sound to shape its '+ + 'level</span>')+ + '</span>';+ return arow('in', ae.fade_in) + arow('out', ae.fade_out) + levels;+ })()+ : '') ++ '') ++ // EFFECTS. Brightness is the one legacy citizen — it stays at+ // `adjust.brightness` on disk, because a label is not worth a data+ // migration — and it is PRESENTED here, beside the fades, because this is+ // where a person looks for it.+ sect('Effects', adjust + fadeRow('in', e.fade_in) + fadeRow('out', e.fade_out));+}++// The slider moves at pointer speed and the undo stack does not. `oninput`+// paints the CSS filter and the number and touches NOTHING else; `onchange`,+// which fires once when the drag ends, is the edit. Committing on every input+// event would push eighty undo steps and eighty saves for one gesture.+function sbeBrightPreview(v) {+ const b = Math.max(-SBE_BRIGHT_MAX, Math.min(SBE_BRIGHT_MAX, sbeNum(v)));+ const out = sbeEl('sbeBrightVal');+ if (out) out.textContent = (b > 0 ? '+' : '') + b.toFixed(2);+ sbeApplyPreviewFilter(b);+}++function sbeOvFadeCommit(edge, v) {+ if (!SBE.ovSel) return;+ const id = SBE.ovSel;+ sbeOvMutate(os => {+ const o = sbeOvById(os, id);+ if (!o) return { overlays: os, ok: false, why: 'gone' };+ const len = Math.max(0, sbeNum(o.film_end) - sbeNum(o.film_start));+ const key = (edge === 'out') ? 'fade_out' : 'fade_in';+ const want = Math.max(0, Math.min(len, sbeNum(v)));+ const out = os.map(x => Object.assign({}, x));+ const t = sbeOvById(out, id);+ const fx = Object.assign({}, t.fx || {});+ if (want > 1e-9) fx[key] = sbeRound(want); else delete fx[key];+ if (fx.fade_in > 1e-9 || fx.fade_out > 1e-9) t.fx = fx; else delete t.fx;+ t.source = 'human';+ return { overlays: out, ok: true };+ });+}++function sbeFadeCommit(edge, v) {+ if (!SBE.sel) return;+ const ok = sbeMutate(cs => sbeSetFade(cs, SBE.sel, edge, v));+ if (!ok) { sbePaintInspector(); return; }+}++function sbeBrightCommit(v) {+ if (!SBE.sel) return;+ const ok = sbeMutate(cs => sbeSetBrightness(cs, SBE.sel, v));+ if (!ok) { sbePaintInspector(); return; }+ sbeQueueSave();+}++// One place decides what the stage looks like, so the video layer and the+// still layer can never disagree about the grade.+// THE PREVIEW'S OPACITY, a value per frame rather than a CSS transition: a+// scrub has to show what is TRUE at that second, not an animation that+// started when you arrived. The stage's black is what a fade to black fades+// to, so this is the whole of it on the picture lane.+function sbeFadePaint(t) {+ const v = sbeEl('sbeVideo');+ const img = sbeEl('sbeStill');+ const now = (t === undefined) ? SBE.playhead : sbeNum(t);+ // THE CLIP AT THE PLAYHEAD, not `curId`. `curId` is the transport's own+ // bookkeeping and is only current while something is playing — reading it+ // during a SCRUB gave the stale clip, or none at all, and the ramp a person+ // is dragging is exactly the one they are scrubbing to look at.+ const c = sbeClipAt(SBE.clips, now) || sbeById(SBE.clips, SBE.curId);+ const o = c ? sbeFadeOpacityAt(c, now) : 1;+ // OPACITY IS ALSO THE LAYER SWITCH. `.sbe-still` is opacity:0 until it wins+ // `.is-on`, so writing the ramp onto BOTH layers turned the hidden one on --+ // and the still, being last in the stage and backed with #000, painted a+ // black rectangle over a perfectly loaded video. Grade the layer that is+ // showing; hand the other one back to the stylesheet.+ const paint = (el) => {+ if (!el) return;+ el.style.opacity = el.classList.contains('is-on') ? String(o) : '';+ };+ paint(v);+ paint(img);+}++function sbeApplyPreviewFilter(b) {+ const css = (Math.abs(sbeNum(b)) < 1e-6) ? '' : 'brightness(' + sbeBrightnessCss(b) + ')';+ const v = sbeEl('sbeVideo');+ const i = sbeEl('sbeStill');+ if (v) v.style.filter = css;+ if (i) i.style.filter = css;+}++function sbePaintChrome() {+ const board = sbeEl('sbeBoardBtn');+ if (board) board.hidden = !SBE.id;+ sbeEl('sbeUndoBtn').disabled = !SBE.undo.length;+ sbeEl('sbeRedoBtn').disabled = !SBE.redo.length;+ const save = sbeEl('sbeSaveBtn');+ save.disabled = !SBE.dirty || SBE.saving;+ // THE ROW HAS A HIERARCHY WHILE THERE IS SOMETHING TO DO. Seven buttons at+ // one fill made the safest action and the one that LEAVES look alike, and+ // nothing in the row changed when the state chip went amber.+ if (save.classList) {+ save.classList.toggle('primary', !!SBE.dirty && !SBE.saving);+ save.classList.toggle('ghost-btn', !(SBE.dirty && !SBE.saving));+ }+ sbeEl('sbePlayBtn').textContent = SBE.playing ? 'Pause' : 'Play';+ // The zoom slider is a VIEW of SBE.pps, not a second copy of it: the − / ++ // buttons, alt + wheel and a resize all move the handle by coming through+ // here, so the control can never disagree with the track it is scaling.+ const zr = sbeEl('sbeZoomRange');+ if (zr) {+ const lo = sbeZoomMin();+ zr.value = String(sbeZoomToSlider(SBE.pps, lo, Math.max(lo, SBE_PPS_MAX)));+ }+ const pn = sbeEl('sbeProgName');+ if (pn) {+ const n = SBE.clips.length;+ pn.textContent = n + ' clip' + (n === 1 ? '' : 's') + ' · ' ++ sbeFmtTime(sbeFilmDuration(SBE.clips));+ }+ // THE PROGRAM MONITOR'S EMPTY STATE WAS MARKUP NOBODY FILLED. The element+ // and its style shipped with the two-monitor pass and nothing ever set its+ // text, so the source monitor greeted an empty state with a sentence while+ // the program monitor showed a black rectangle and a 10px chip — two+ // monitors speaking two languages about the same condition.+ const pe = sbeEl('sbeStageEmpty');+ if (pe) {+ if (SBE.clips.length) { pe.hidden = true; pe.textContent = ''; }+ else {+ pe.textContent = 'Nothing on the timeline yet — drag a clip from the '+ + 'media pool, or press + on one.';+ pe.hidden = false;+ }+ }+ // The source monitor's own chrome — same rule, one painter.+ sbePaintSource();+ // unplaced+ const wrap = sbeEl('sbeUnplacedWrap');+ const list = SBE.unplaced || [];+ wrap.hidden = !list.length;+ if (list.length) {+ sbeEl('sbeUnplaced').innerHTML = list.map((u, i) => {+ const at = (u.slot && u.slot.film_start !== undefined)+ ? sbeNum(u.slot.film_start) : sbeFilmDuration(SBE.clips);+ // The timecode is the same on every row, so it belongs on the button's+ // title rather than repeated thirteen times down a 230px column.+ return '<span class="sbe-chip" title="' ++ escapeHtml((u.title || ('shot ' + u.n)) + ' — would land at ' ++ sbeFmtTime(at)) + '">' ++ '<b>' + escapeHtml(sbeNiceName(u.title || ('shot ' + u.n))) + '</b>' ++ '<span>' + escapeHtml(u.duration_s ? sbeNum(u.duration_s).toFixed(1) + 's' : (u.pass || '')) + '</span>' ++ '<button type="button" class="ghost-btn" onclick="sbePlace(' + i + ')">Place</button></span>';+ }).join('');+ }+ // prepare+ const job = SBE.prepare || {};+ const running = job.state === 'running';+ sbeEl('sbePrepBtn').disabled = running;+ sbeEl('sbePrepCancel').hidden = !running;+ sbeEl('sbeAutoBtn').disabled = running;+ const bar = sbeEl('sbePrepBar');+ bar.hidden = !running;+ if (running) {+ const total = sbeNum(job.total, 0);+ const pct = total ? Math.min(100, Math.round(sbeNum(job.done) / total * 100)) : 12;+ bar.querySelector('i').style.width = pct + '%';+ const stage = { proxies: 'building proxies', peaks: 'reading the waveform',+ beats: 'finding the beat', start: 'starting' }[job.stage] || job.stage || 'working';+ sbeEl('sbePrepText').textContent = stage ++ (total ? ' · ' + sbeNum(job.done) + ' of ' + total : '') ++ (job.current ? ' · ' + job.current : '');+ } else if (job.state === 'failed') {+ sbeEl('sbePrepText').textContent = 'Prepare failed: ' + (job.error || 'unknown reason');+ } else if (job.state === 'cancelled') {+ sbeEl('sbePrepText').textContent = 'Prepare cancelled. Whatever it built is kept.';+ } else if (job.state === 'done') {+ const failed = (job.failed || []).length;+ sbeEl('sbePrepText').textContent =+ 'Ready · ' + sbeNum(job.built) + ' proxy(s) built' ++ (failed ? ', ' + failed + ' clip(s) could not be read' : '') ++ (job.peaks_error ? ' · ' + job.peaks_error : '') ++ (job.beats_error ? ' · ' + job.beats_error : '') ++ // A grid the ARRANGEMENT has never seen. Prepare found the beat, but only+ // the auto-editor writes it into edit.json — so say that plainly instead+ // of drawing a timeline with no lines on it and letting the user wonder.+ ((job.beats && !SBE.beats)+ ? ' · found the beat at ' + Math.round(sbeNum(job.beats.bpm)) ++ ' bpm — this arrangement was cut without it, so Auto-edit is what ' ++ 'puts the cuts on it'+ : '');+ } else {+ sbeEl('sbePrepText').textContent =+ 'The soundtrack drives the waveform and the beat grid.';+ }+}++// ---------------------------------------------------------------------------+// POINTER: scrub, drag, trim+// ---------------------------------------------------------------------------+function sbeTimeFromEvent(ev, el) {+ const r = el.getBoundingClientRect();+ return Math.max(0, (ev.clientX - r.left + el.scrollLeft * 0) / SBE.pps);+}++function sbeSnapEnabled(ev) {+ const box = sbeEl('sbeSnapOn');+ const on = !box || box.checked;+ return on && !(ev && (ev.altKey || ev.metaKey)); // Alt is the override+}++function sbeOnTrackDown(ev) {+ const track = sbeEl('sbeTrack');+ // Same as the lane: the flag is a button, not part of the block.+ const badge = ev.target.closest('.sbe-sync');+ if (badge) { ev.preventDefault(); sbeResyncSel(badge.dataset.sync); return; }+ const gap = ev.target.closest('.sbe-gap');+ if (gap) {+ sbeGenOpen(sbeNum(gap.dataset.gapStart), sbeNum(gap.dataset.gapDur));+ return;+ }+ const blk = ev.target.closest('.sbe-clip');+ if (!blk) { sbeSeek(sbeTimeFromEvent(ev, track)); return; }+ const id = blk.dataset.id;+ SBE.sel = id;+ SBE.ovSel = ''; // one inspector, one subject+ SBE.audioDrag = null; // same insurance the lane takes against the other+ const c = sbeById(SBE.clips, id);+ if (!c) return;+ // A LOCKED SHOT SAYS SO. Until now it refused every drag in silence: the CSS+ // turned the cursor to `not-allowed`, hid both grips, and nothing on screen+ // said why or what to press. The owner hit it while cutting — "trying to+ // drag the video clip from EITHER edge shows a forbidden cursor" — because+ // Lock was the only button that sounded like "keep these two together",+ // which is what re-link now actually does.+ if (c.locked) {+ sbePaint();+ // AND IT NAMES THE OTHER VERB. Lock pins a shot to its place on the film+ // so everything else flows around it; it is NOT the button that makes a+ // clip and its sound travel together, which is what he was reaching for+ // when he pressed it. That one is Link sound.+ phosToast('That shot is locked to its place on the __SEQ__, so it cannot be '+ + 'moved or trimmed from either edge — click Unlock in the '+ + 'inspector. To move a shot and its sound TOGETHER, unlink the '+ + 'sound, put it where you want it, then press Link sound.',+ { duration: 9000 });+ return;+ }+ // THE CORNER HANDLE, before the grips: it sits on top of the left grip's+ // hit area at the head of the block, and a fade drag is the more specific+ // gesture of the two.+ const fh = ev.target.closest('.sbe-fade-h');+ if (fh) {+ const e0 = sbeFx(c);+ SBE.drag = { id: id, mode: 'fade', edge: fh.dataset.fade, x0: ev.clientX,+ f0: (fh.dataset.fade === 'out') ? e0.fade_out : e0.fade_in,+ moved: false, before: JSON.stringify(SBE.clips) };+ try { track.setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+ return;+ }+ const grip = ev.target.closest('.sbe-grip');+ // SHIFT IS REORDER. The hint strip already teaches "hold Alt to ignore the+ // beat", so a second modifier on the same gesture is the idiom this timeline+ // already has — and it is the only way to offer both verbs without a mode+ // switch nobody would find. Free drag stays the default: it is what every+ // arrangement on disk was made with, and it is the one that can open a hole+ // for the generate control to fill.+ const mode = grip ? (grip.classList.contains('r') ? 'trimR' : 'trimL')+ : (ev.shiftKey ? 'reorder' : 'move');+ SBE.drag = { id: id, mode: mode, x0: ev.clientX, t0: sbeTimeFromEvent(ev, track),+ fs0: sbeNum(c.film_start), fe0: sbeNum(c.film_end), moved: false,+ before: JSON.stringify(SBE.clips) };+ if (mode === 'move') blk.classList.add('is-drag');+ try { track.setPointerCapture(ev.pointerId); } catch (e) {}+ ev.preventDefault();+ sbePaint();+}++function sbeOnTrackMove(ev) {+ const d = SBE.drag;+ if (!d) return;+ const track = sbeEl('sbeTrack');+ const dt = (ev.clientX - d.x0) / SBE.pps;+ if (Math.abs(ev.clientX - d.x0) > 3) d.moved = true;+ if (!d.moved) return;+ const tol = SBE_SNAP_PX / SBE.pps;+ const snapOn = sbeSnapEnabled(ev);+ const off = (SBE.audio || {}).offset;+ if (d.mode === 'fade') {+ // Dragging INWARD lengthens the ramp, whichever end you grabbed — the+ // gesture every NLE uses, and the only one that reads as "pull the fade+ // out of the corner".+ const dt = (d.edge === 'out') ? -(ev.clientX - d.x0) / SBE.pps+ : (ev.clientX - d.x0) / SBE.pps;+ const r = sbeSetFade(SBE.clips, d.id, d.edge, Math.max(0, d.f0 + dt));+ if (r.ok) SBE.clips = r.clips;+ sbePaint();+ return;+ }+ if (d.mode === 'reorder') {+ // No snap: a reorder does not choose a TIME, it chooses a neighbour, and+ // pulling the drop index onto a beat would mean nothing.+ const r = sbeReorderTo(SBE.clips, d.id, Math.max(0, d.t0 + dt));+ if (r.ok) SBE.clips = r.clips;+ } else if (d.mode === 'move') {+ const want = sbeSnapTime(Math.max(0, d.fs0 + dt), SBE.beats, tol, snapOn, off);+ const r = sbeMoveTo(SBE.clips, d.id, want);+ if (r.ok) SBE.clips = r.clips;+ } else if (d.mode === 'trimL') {+ const want = sbeSnapTime(Math.max(0, d.fs0 + dt), SBE.beats, tol, snapOn, off);+ sbeTrim(SBE.clips, d.id, 'l', want);+ } else {+ const want = sbeSnapTime(Math.max(0, d.fe0 + dt), SBE.beats, tol, snapOn, off);+ sbeTrim(SBE.clips, d.id, 'r', want);+ }+ sbePaint();+}++// EVERYTHING A DRAG ON THE TRACK CAN MOVE, in one string. `sbeOnTrackUp` asks+// "did the film actually change" and restores the pointerdown snapshot when it+// did not — dragging a clip left when it is already hard against its neighbour+// is the common case, and without this every such gesture would burn a+// revision and push an undo step that undoes nothing.+//+// SO THE LIST HAS TO BE COMPLETE, and twice now it has not been: a gesture+// whose only effect was on a strip compared equal and was discarded, and then+// a fade did the same. The rule is that every field any `SBE.drag.mode` writes+// belongs here — trimL and trimR move `start`/`end`, move and reorder move+// `film_start`, a ripple moves `audio`, and fade moves `fx`. Named and pure so+// a new mode can be checked against it instead of against a closure.+function sbeDragFingerprint(cs) {+ return (cs || []).map(c => [c.id, c.start, c.end, c.film_start,+ JSON.stringify(c.audio || null),+ JSON.stringify(c.fx || null)].join(':')).join('|');+}++function sbeOnTrackUp(ev) {+ const d = SBE.drag;+ SBE.drag = null;+ if (!d) return;+ document.querySelectorAll('.sbe-clip.is-drag').forEach(el => el.classList.remove('is-drag'));+ if (!d.moved) { sbePaint(); return; }+ // A DRAG THAT MOVED THE POINTER BUT NOT THE FILM IS NOT AN EDIT. Dragging a+ // clip left when it is already hard against its neighbour is the common case+ // — the maths clamps, nothing lands anywhere new, and without this the+ // document would still come back dirty, stamped `human`, with a revision+ // burned and an undo step that undoes nothing.+ // ...AND THE SOUND IS PART OF THE GEOMETRY. The fingerprint listed four+ // picture fields, so a gesture whose only effect was on a strip — a ripple+ // carrying an unlinked sound, a coupled pair travelling with its picture —+ // compared equal to the state it started from, and this line then RESTORED+ // the snapshot: the edit was discarded, the document was never marked+ // dirty, and the header went on saying "saved · revision N" over work that+ // had just been thrown away.+ // ...AND SO IS THE FADE, which is the SECOND HALF of "not sure that grabbing+ // the top corner is working. I'm not being able to do it." The corner handle+ // was too small to hit — that is the CSS — but on the times he DID hit it,+ // this comparison then threw the result away: `mode: 'fade'` moves `fx` and+ // nothing else, `fx` was not in the fingerprint, so the drag compared equal+ // to the state it started from and the snapshot was restored on pointerup.+ // The ramp followed the pointer the whole way and snapped back the moment he+ // let go. Exactly the bug the paragraph above describes, one field along —+ // which is why the fingerprint is a NAMED function now, listing every field+ // a track drag can move, rather than a closure written to the needs of+ // whichever gesture was being added at the time.+ const before = JSON.parse(d.before);+ if (sbeDragFingerprint(before) === sbeDragFingerprint(SBE.clips)) {+ SBE.clips = before; sbePaint(); return;+ }+ // The drag mutated SBE.clips live so the block could follow the pointer;+ // register the ONE undo step now, from the snapshot taken on pointerdown.+ SBE.undo.push(d.before);+ if (SBE.undo.length > SBE_UNDO_MAX) SBE.undo.shift();+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+}++function sbeSeek(t) {+ const dur = Math.max(sbeFilmDuration(SBE.clips), 0);+ SBE.playhead = Math.max(0, Math.min(dur, sbeNum(t)));+ sbePaintHead();+ // A SCRUB LANDS ON THE RIGHT SOURCE SECOND. Forced, because the ground has+ // moved: the slip tolerance is for drift during playback, not for a seek.+ sbeStripSync(true);+ sbeShowFrameAt(SBE.playhead);+}++// ---------------------------------------------------------------------------+// PREVIEW — one <video>, proxies, and no pretence of frame accuracy+// ---------------------------------------------------------------------------+function sbeClipUrl(c) {+ // A STILL IS SERVED BY /image, NOT /file. `/file` is OUTPUT-bound and the+ // image library lives under panel_uploads — so the obvious fallback here+ // would 404 every still in the panel. `/image` already accepts OUTPUT,+ // UPLOADS and the state dir, which is exactly the set the pool draws from.+ if (sbeKind(c) === 'still') {+ return '/image?path=' + encodeURIComponent(c.path);+ }+ if (c.proxy && SBE.proxyUrl) {+ return SBE.proxyUrl + encodeURIComponent(String(c.proxy).split('/').pop());+ }+ return '/file?path=' + encodeURIComponent(c.path);+}++function sbeLoadInto(v, c, at) {+ return new Promise(resolve => {+ // The picture used to be hard-muted here, on the reasoning that sound comes+ // from the soundtrack <audio> and Chrome refuses unmuted autoplay. Both+ // halves were wrong once proxies carried an audio track: most timelines have+ // no soundtrack at all, and their sound — dialogue, the thing you are+ // cutting on — lives in the clips. Play is user-initiated, so there is+ // activation to spend; sbePlay falls back to muted if Chrome disagrees.+ // THE THIRD OUTPUT. The render drops the clip's lane and the export+ // disables its audio track; the preview has to agree or the one place the+ // user checks his work is the one place the decision does not exist.+ //+ // ...AND IT YIELDS TO THE STRIP PLAYER. A clip whose sound is described+ // separately is played by `sbeStripSync` at the strip's own film position;+ // leaving it on the picture element too would play those seconds twice,+ // a beat apart.+ v.muted = !!SBE.muted || !sbePictureCarriesSound(c);+ v.volume = 1;+ v.playsInline = true;+ const url = sbeClipUrl(c);+ const seek = () => {+ const t = Math.max(0, Math.min(sbeNum(c.end) - 1e-3, sbeNum(at)));+ const done = () => { v.removeEventListener('seeked', done); resolve(); };+ v.addEventListener('seeked', done);+ try { v.currentTime = t; } catch (e) { v.removeEventListener('seeked', done); resolve(); }+ setTimeout(() => { v.removeEventListener('seeked', done); resolve(); }, 2500);+ };+ if (v.dataset.src === url && v.readyState >= 1) { seek(); return; }+ v.dataset.src = url;+ const meta = () => { v.removeEventListener('loadedmetadata', meta); seek(); };+ v.addEventListener('loadedmetadata', meta);+ const fail = () => { v.removeEventListener('error', fail); resolve(); };+ v.addEventListener('error', fail);+ v.src = url;+ try { v.load(); } catch (e) {}+ });+}++async function sbeShowFrameAt(t) {+ const v = sbeEl('sbeVideo');+ const img = sbeEl('sbeStill');+ if (!v) return;+ // THE OVERLAY LANE IS NOT THE PICTURE'S BUSINESS, so it is painted BEFORE+ // any of the picture's early returns. A card may outlive the last shot —+ // that is the whole reason the render pads the base with black — and this+ // function bails out as soon as no clip covers the playhead, which left the+ // card stuck on screen at full opacity past its own end. Caught on the test+ // panel, not by a unit test.+ sbeOvPaint(t);+ const c = sbeClipAt(SBE.clips, t);+ SBE.curId = c ? c.id : '';+ if (!c) {+ v.classList.remove('is-on');+ if (img) img.classList.remove('is-on');+ sbeEl('sbeBadge').textContent = SBE.clips.length ? 'nothing plays here' : 'no clips';+ return;+ }+ const kind = sbeKind(c);+ sbeApplyPreviewFilter(sbeBright(c));+ if (kind === 'slug') {+ // NO FILE, SO NOTHING TO LOAD. Both layers off leaves the stage's own+ // black, which is the frame the render will write — the one case where the+ // preview is not an approximation at all.+ v.classList.remove('is-on');+ if (img) img.classList.remove('is-on');+ sbeEl('sbeBadge').textContent = 'black · ' + sbeLen(c).toFixed(2) + 's';+ sbePaintTrack();+ return;+ }+ if (kind === 'still') {+ // An <img> cannot land on the wrong frame and cannot be slow to seek, so+ // a still never reaches the missing-proxy path the badge exists to warn+ // about. Swap the src only when it changed — reassigning it re-decodes.+ v.classList.remove('is-on');+ if (img) {+ const url = sbeClipUrl(c);+ if (img.getAttribute('src') !== url) img.src = url;+ img.classList.add('is-on');+ }+ sbeEl('sbeBadge').textContent =+ (c.title || String(c.path || '').split('/').pop()) + ' · still · ' ++ sbeLen(c).toFixed(2) + 's';+ sbePaintTrack();+ return;+ }+ if (img) img.classList.remove('is-on');+ await sbeLoadInto(v, c, sbeNum(c.start) + (t - sbeNum(c.film_start)));+ v.classList.add('is-on');+ sbeEl('sbeBadge').textContent =+ (c.title || c.path.split('/').pop()) + ' · ' + sbeNum(c.start).toFixed(2) + '–' ++ sbeNum(c.end).toFixed(2) + ' · ' + (c.proxy ? 'proxy' : 'SOURCE (slow — run Prepare)');+ // A SCRUB SHOWS THE TRUE OPACITY at the second it landed on, which is the+ // only way a fade can be judged without playing the whole clip.+ sbeFadePaint(t);+ sbePaintTrack();+}++// ---------------------------------------------------------------------------+// THE SOURCE MONITOR — the left screen+// ---------------------------------------------------------------------------+// A pool row is a path and a title, not a clip: it has no proxy of its own+// until it lands on the track, and a row from the Generations tab has never+// been near this document. So the URL is the proxy of a clip already cut from+// the same file when there is one, and the file itself when there is not.+// That is fine here in a way it would not be on the timeline: a source+// monitor plays forward from zero, it does not scrub, so the 235 ms seek that+// makes source files useless under a playhead never happens.+function sbeSrcUrl(row) {+ if (!row || !row.path) return '';+ if (row.kind === 'still') return '/image?path=' + encodeURIComponent(row.path);+ const cut = (SBE.clips || []).find(c => c.path === row.path && c.proxy);+ if (cut && SBE.proxyUrl) {+ return SBE.proxyUrl + encodeURIComponent(String(cut.proxy).split('/').pop());+ }+ return '/file?path=' + encodeURIComponent(row.path);+}++// CLICKING A ROW WATCHES IT. It does not add it — that was the old verb for+// the whole row and it is now the + at the row's right edge, which is the+// swap the two-screen layout is for: "you can watch the clips before you add+// them".+function edPoolPreview(i) {+ // A drag ends in a click event on the row it started from. edPoolAdd has+ // carried this guard since drag-to-drop shipped; the preview needs it for+ // the same reason, or every drop would also change the left screen.+ if (ED.suppressClick) { ED.suppressClick = false; return; }+ const list = document.getElementById('edPoolList');+ const row = ((list || {})._rows || [])[i];+ if (!row) return;+ SBE.source = row;+ SBE.srcIndex = i;+ // Mark the row in place rather than repainting the list: a repaint drops+ // and re-attaches every thumbnail's src, which is sixty decoders for a+ // one-class change.+ list.querySelectorAll('.ed-pool-row').forEach((el, k) =>+ el.classList.toggle('is-source', k === i));+ sbeSrcLoad(row);+ sbePaintSource();+}++function sbeSrcLoad(row) {+ const v = sbeEl('sbeSrcVideo');+ const img = sbeEl('sbeSrcStill');+ const empty = sbeEl('sbeSrcEmpty');+ if (empty) empty.hidden = true;+ const url = sbeSrcUrl(row);+ if (row.kind === 'still') {+ sbeSrcStop();+ if (v) { try { v.pause(); } catch (e) {} v.classList.remove('is-on'); }+ if (img) {+ if (img.getAttribute('src') !== url) img.src = url;+ img.classList.add('is-on');+ }+ return;+ }+ if (img) img.classList.remove('is-on');+ if (!v) return;+ if (v.getAttribute('src') !== url) { v.src = url; try { v.load(); } catch (e) {} }+ v.classList.add('is-on');+ // Clicking a clip means "let me see it", so it plays. The program stops+ // first — one picture, one soundtrack, one thing to listen to.+ sbeSrcPlay();+}++async function sbeSrcPlay() {+ const v = sbeEl('sbeSrcVideo');+ if (!v || !SBE.source || SBE.source.kind === 'still') return;+ sbeStop(); // the program yields; they never overlap+ v.muted = !!SBE.muted;+ v.volume = 1;+ SBE.srcPlaying = true;+ try { await v.play(); }+ catch (e) {+ // NOT EVERY REJECTED play() IS AN AUTOPLAY REFUSAL. Calling pause() while+ // a play promise is pending rejects it with AbortError — and pressing+ // Play on the program does exactly that, on purpose. The first version of+ // this caught that abort, decided the browser had blocked sound, muted+ // the editor and started the source playing again UNDER the program.+ // Measured: source paused:false, readyState 0, and a muted timeline.+ if (!SBE.srcPlaying) return; // stopped on purpose; stay stopped+ if (e && e.name === 'AbortError') return;+ // Same autoplay bargain the program makes: losing the sound beats losing+ // the picture, and a Play button that visibly does nothing is worse still.+ if (!v.muted) {+ v.muted = true;+ sbeSetMute(true, 'browser blocked sound — click 🔊 to unmute', false);+ try { await v.play(); } catch (e2) {}+ }+ }+ sbePaintSource();+}++function sbeSrcStop() {+ const v = sbeEl('sbeSrcVideo');+ SBE.srcPlaying = false;+ if (v) { try { v.pause(); } catch (e) {} }+ sbePaintSource();+}++function sbeSrcToggle() { SBE.srcPlaying ? sbeSrcStop() : sbeSrcPlay(); }++// The button under the left screen. Exactly the + on the row, by construction:+// same function, same index, same server call.+function sbeSrcAdd() {+ if (!SBE.source || SBE.srcIndex < 0) return;+ edPoolAdd(SBE.srcIndex);+}++function sbePaintSource() {+ const row = SBE.source;+ const name = sbeEl('sbeSrcName');+ const add = sbeEl('sbeSrcAddBtn');+ const play = sbeEl('sbeSrcPlayBtn');+ const badge = sbeEl('sbeSrcBadge');+ const empty = sbeEl('sbeSrcEmpty');+ if (!name) return;+ if (!row) {+ name.textContent = 'Nothing loaded';+ if (add) add.disabled = true;+ if (play) { play.disabled = true; play.textContent = 'Play'; }+ if (badge) badge.hidden = true;+ if (empty) empty.hidden = false;+ return;+ }+ const secs = sbeNum(row.duration_s, 0);+ name.textContent = (row.title || String(row.path || '').split('/').pop() || 'clip') ++ (secs ? ' · ' + secs.toFixed(1) + 's' : '');+ name.title = row.path || '';+ // Disabled when the row is no longer in the painted pool — a search or a+ // tab change can take it away, and an Add that pointed at whatever moved+ // into that slot would put the wrong clip on the film.+ if (add) add.disabled = !(SBE.open && SBE.id) || SBE.srcIndex < 0;+ if (play) {+ play.disabled = (row.kind === 'still');+ play.textContent = SBE.srcPlaying ? 'Pause' : 'Play';+ }+ if (empty) empty.hidden = true;+ if (badge) {+ // The same honesty the program badge carries: say when the picture is the+ // source file rather than a proxy, because that is the slow one.+ const proxied = (SBE.clips || []).some(c => c.path === row.path && c.proxy);+ badge.hidden = false;+ badge.textContent = (row.kind === 'still') ? 'still'+ : (proxied ? 'proxy' : 'source file');+ }+}++// What the soundtrack does to the clips' own sound. Lives on the edit so it+// survives a reload and so the render uses what the screen is showing.+function sbeMusicMode() {+ const el = sbeEl('sbeMusicMode');+ return (el && el.value === 'replace') ? 'replace' : 'under';+}++// SETTING A CONTROL TO WHAT IT ALREADY SAYS IS NOT AN EDIT. `sbeAdopt` calls+// this on every load to make the dropdown agree with the document — and it+// was marking that document dirty and queueing a write, so EVERY OPEN of+// every film produced a save the user never made. Under the old autosave that+// was silent revision churn; under drafts it would have been worse, because+// the backup lane would have overwritten an unanswered recovery offer with+// the very arrangement the offer existed to replace.+function sbeSetMusicMode(v) {+ const mode = (v === 'replace') ? 'replace' : 'under';+ const el = sbeEl('sbeMusicMode');+ if (el) el.value = mode;+ if (SBE.audio) {+ if (String(SBE.audio.mode || 'under') === mode) return;+ SBE.audio.mode = mode;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbeQueueSave();+ }+ // Only `replace` needs saying: it is the one that destroys something.+ const warn = sbeEl('sbeMusicWarn');+ if (warn) {+ warn.hidden = (mode !== 'replace');+ warn.textContent = 'any dialogue in the clips is lost';+ }+}++// ---------------------------------------------------------------------------+// THE MEDIA POOL — three sources, one verb+// ---------------------------------------------------------------------------+// `ED.src` is which source is showing, `ED.rows` is what it holds. Nothing is+// cached across sources on purpose: the gallery changes while you cut, and a+// pool that shows yesterday's list is worse than a pool that takes 40 ms.+window.ED = { src: 'film', rows: [], films: [], film: '', loading: false,+ limit: 60, io: null, drag: null, suppressClick: false,+ // What THIS session uploaded, kept in front of the list. The+ // server puts an image somewhere the gallery already walks and a+ // clip somewhere the uploads route lists, so both come back on+ // their own — but `list_outputs` holds a file back for two+ // seconds while it decides nobody is still writing it, and "it+ // appears in a moment" is not what "immediately" means.+ uploaded: [] };++function edPoolSrc(name) {+ ED.src = name;+ const tabs = document.getElementById('edPoolTabs');+ if (tabs) tabs.querySelectorAll('.pill-btn').forEach(b =>+ b.classList.toggle('active', b.dataset.src === name));+ const pick = document.getElementById('edPoolFilm');+ if (pick) pick.hidden = (name !== 'other');+ // Upload belongs to the source that shows what was uploaded.+ const up = document.getElementById('edPoolUploadBtn');+ if (up) up.hidden = (name !== 'images');+ ED.limit = 60;+ edPoolRefresh();+}++// BRING YOUR OWN FILE. "You cannot upload your own images and insert them+// into the timeline" — and a clip from a phone is the same feature, so both+// are taken. One request per file so a rejected one names itself instead of+// failing a batch, and the answers go straight to the front of the pool.+async function edPoolUpload(files) {+ const list = Array.from(files || []);+ if (!list.length) return;+ const btn = document.getElementById('edPoolUploadBtn');+ if (btn) { btn.disabled = true; btn.textContent = 'Uploading…'; }+ const bad = [];+ let done = 0;+ for (const f of list) {+ const fd = new FormData();+ fd.append('file', f);+ let r;+ try {+ r = await (await fetch('/storyboard/edit/upload',+ { method: 'POST', body: fd })).json();+ } catch (e) { r = { ok: false, error: String(e) }; }+ if (r && r.ok) {+ done++;+ ED.uploaded = [edPoolUploadRow(r)].concat(+ (ED.uploaded || []).filter(x => x.path !== r.path));+ } else {+ bad.push((f.name || 'file') + ' — ' + ((r && r.error) || 'upload failed'));+ }+ }+ if (btn) { btn.disabled = false; btn.textContent = 'Upload'; }+ if (ED.src !== 'images') edPoolSrc('images'); else await edPoolRefresh(true);+ if (done) {+ phosToast(done + (done === 1 ? ' file is' : ' files are') ++ ' in the pool — press + to put it at the end, or drag it onto '+ + 'the track.',+ { kind: 'success', duration: 5000 });+ }+ for (const msg of bad) phosToast(msg, { kind: 'danger', duration: 7000 });+}++// One upload's answer, as the row shape every pool source produces.+function edPoolUploadRow(r) {+ const still = String(r.kind || 'still') === 'still';+ return {+ path: r.path, title: r.title || String(r.path || '').split('/').pop(),+ kind: still ? 'still' : undefined,+ sub: 'uploaded · ' + (still ? 'still' : 'clip') ++ (r.duration_s ? ' · ' + sbeNum(r.duration_s).toFixed(1) + 's' : ''),+ duration_s: still ? SBE_STILL_SECONDS : r.duration_s,+ uploaded: true,+ };+}++// One row shape for all three sources, so the paint and the click do not have+// to know where a clip came from: {path, title, sub, duration_s, from, only}.+async function edPoolRefresh(force) {+ const list = document.getElementById('edPoolList');+ const note = document.getElementById('edPoolNote');+ if (!list) return;+ if (ED.loading) return;+ ED.loading = true;+ if (force) ED.limit = 60;+ list.innerHTML = '<span class="ed-pool-note">reading…</span>';+ if (note) note.textContent = '';+ try {+ if (ED.src === 'film') {+ ED.rows = (SBE.pool || []).map(c => ({+ path: c.path, title: c.title || ('shot ' + c.n),+ sub: (c.pass || '') + (c.duration_s ? ' · ' + sbeNum(c.duration_s).toFixed(1) + 's' : '') ++ (c.placed ? ' · on the track' : ''),+ duration_s: c.duration_s, placed: !!c.placed, n: c.n,+ }));+ } else if (ED.src === 'other') {+ await edPoolLoadFilms();+ ED.rows = await edPoolLoadFilmShots(ED.film);+ } else if (ED.src === 'images') {+ // THE GALLERY ALWAYS HAD THESE. `/outputs` has carried `kind: 'image'`+ // since the unified gallery shipped; what was missing was a clip that+ // could BE one. A still lands with a default hold and is resized by the+ // same trim handles every other block has.+ const r = await (await fetch('/outputs?limit=400&offset=0')).json();+ const gallery = ((r && r.outputs) || [])+ .filter(o => o.kind === 'image' && !o.hidden)+ .map(o => ({+ path: o.path, title: o.name, kind: 'still',+ sub: 'still · ' + (o.engine ? String(o.engine).toUpperCase() + ' · ' : '') ++ (o.mtime || '').slice(0, 10),+ duration_s: SBE_STILL_SECONDS,+ }));+ // The clips somebody brought with them. Deliberately NOT in OUTPUT —+ // that folder means "the panel made this" — so they come from their own+ // listing and sit at the front, with this session's uploads ahead of+ // them so a file is in the list the instant it lands.+ let mine = [];+ try {+ const u = await (await fetch('/storyboard/edit/uploads')).json();+ mine = ((u && u.uploads) || []).map(o => ({+ path: o.path, title: o.name, sub: 'uploaded · clip',+ uploaded: true,+ }));+ } catch (e) { mine = []; }+ const seen = {};+ ED.rows = (ED.uploaded || []).concat(mine, gallery)+ .filter(row => (row.path && !seen[row.path]) && (seen[row.path] = 1));+ } else {+ const r = await (await fetch('/outputs?limit=400&offset=0')).json();+ ED.rows = ((r && r.outputs) || [])+ .filter(o => o.kind === 'video' && !o.hidden)+ .map(o => ({+ path: o.path, title: o.name,+ sub: (o.clip_sec ? sbeNum(o.clip_sec).toFixed(1) + 's · ' : '') ++ (o.engine ? String(o.engine).toUpperCase() + ' · ' : '') ++ (o.mtime || '').slice(0, 10),+ duration_s: o.clip_sec,+ }));+ }+ } catch (e) {+ ED.rows = [];+ if (note) note.textContent = 'The panel did not answer.';+ }+ ED.loading = false;+ edPoolPaint();+}++async function edPoolLoadFilms() {+ let boards = [];+ try {+ const r = await (await fetch('/storyboard/list')).json();+ boards = ((r && r.boards) || []).filter(b => (b.clips || 0) > 0 && b.id !== SBE.id);+ } catch (e) { boards = []; }+ ED.films = boards;+ if (!ED.film || !boards.some(b => b.id === ED.film)) {+ ED.film = boards.length ? boards[0].id : '';+ }+ const pick = document.getElementById('edPoolFilm');+ if (pick) {+ pick.innerHTML = boards.map(b =>+ '<option value="' + escapeHtml(b.id) + '"' + (b.id === ED.film ? ' selected' : '') ++ '>' + escapeHtml(b.title || b.id) + ' · ' + (b.clips || 0) + ' clips</option>').join('');+ }+}++function edPoolPickFilm(id) { ED.film = id; ED.limit = 60; edPoolRefresh(); }++async function edPoolLoadFilmShots(id) {+ if (!id) return [];+ let r;+ try { r = await (await fetch('/storyboard/get?id=' + encodeURIComponent(id))).json(); }+ catch (e) { return []; }+ const shots = (((r || {}).board) || {}).shots || [];+ return shots.map(sh => {+ const path = sh.final_output || sh.draft_output || '';+ if (!path || sh.status === 'skipped') return null;+ return { path: path, title: sh.title || sh.prompt || ('shot ' + sh.n),+ sub: 'S' + String(sh.n).padStart(2, '0') + ' · ' ++ (sh.final_output ? 'delivery' : 'draft') ++ (sh.duration_s ? ' · ' + sbeNum(sh.duration_s).toFixed(1) + 's' : ''),+ duration_s: sh.duration_s, from: id, only: sh.n };+ }).filter(Boolean);+}++function edPoolPaint() {+ const list = document.getElementById('edPoolList');+ const note = document.getElementById('edPoolNote');+ if (!list) return;+ const q = ((document.getElementById('edPoolSearch') || {}).value || '')+ .trim().toLowerCase();+ const rows = (ED.rows || []).filter(r =>+ !q || (r.title || '').toLowerCase().indexOf(q) !== -1 ||+ (r.path || '').toLowerCase().indexOf(q) !== -1);+ if (!rows.length) {+ list.innerHTML = '<span class="ed-pool-note">' ++ // AN EMPTY LIST IS A SENTENCE, NOT A BLANK. Each of these says what is+ // true of THIS source and what the next move is — a pool that goes+ // quiet reads as broken, and the four sources fail for four different+ // reasons.+ (q+ ? 'Nothing here matches “' + escapeHtml(q) + '”. Clear the filter to see everything.'+ : ED.src === 'gallery'+ ? 'No generations yet. Render something in Video or Storyboard and it lands here.'+ : ED.src === 'images'+ ? 'No images yet — press Upload to bring one in from this Mac, or make one in the Image studio.'+ : ED.src === 'other'+ ? (ED.films && ED.films.length+ ? 'That __SEQ__ has no rendered clips yet.'+ : 'No other __SEQS__ yet. Every __SEQ__ you make shows up here to borrow clips from.')+ : 'This __SEQ__ has no rendered clips yet. Render its shots in Storyboard, or take one from another source above.') + '</span>';+ if (note) note.textContent = '';+ return;+ }+ const show = rows.slice(0, ED.limit);+ // `#t=0.1` is what makes a <video preload="metadata"> paint a frame instead+ // of black — no thumbnail pipeline, no extra request, and it is the same+ // /file route with ranges the gallery already uses.+ //+ // The src is NOT in the markup. Chrome caps how many media elements one+ // document may have (the carousel alone already holds ~240 on a working+ // install), and a pool that attached sixty more on paint would spend that+ // budget on rows nobody has scrolled to. `data-src` + an observer means at+ // most the visible dozen are ever loaded, and leaving a row unloads it.+ // A ROW IS A DIV WITH A ROLE, NOT A BUTTON. It has to hold a button of its+ // own now — the + that still adds without previewing — and a <button>+ // inside a <button> is not markup any browser will keep.+ const srcPath = (SBE.source || {}).path || '';+ list.innerHTML = show.map((r, i) =>+ '<div class="ed-pool-row' + ((srcPath && r.path === srcPath) ? ' is-source' : '') ++ '" role="button" tabindex="0" onclick="edPoolPreview(' + i + ')" ' ++ 'onkeydown="if(event.key===\'Enter\'||event.key===\' \'){event.preventDefault();edPoolPreview(' + i + ');}" ' ++ 'onpointerdown="edPoolDragStart(event,' + i + ')" ' ++ 'title="' + escapeHtml(r.path) + '">' ++ // An image has no frame to seek to, so it is an <img> — and the /image+ // route's own `w=` resize is what keeps a 14 MB PNG from being decoded at+ // full size for a 44 px thumbnail.+ (r.kind === 'still'+ ? '<img alt="" data-src="/image?w=180&path=' + encodeURIComponent(r.path) + '">'+ : '<video preload="metadata" muted playsinline data-src="/file?path=' ++ encodeURIComponent(r.path) + '#t=0.1"></video>') ++ '<span class="ed-pool-meta">' ++ '<span class="ed-pool-name">' + escapeHtml(sbeNiceName(r.title || '')) + '</span>' ++ '<span class="ed-pool-sub">' + escapeHtml(r.sub || '') + '</span>' ++ '</span>' ++ '<button type="button" class="ed-pool-add" ' ++ 'title="Put this clip at the end of the __SEQ__" ' ++ 'onclick="event.stopPropagation();edPoolAdd(' + i + ')">+</button>' ++ // AN IMAGE CAN BE A CARD. A transparent PNG belongs on the overlay lane,+ // not at the end of the picture track, and this is the one click that+ // says so — it lands at the playhead, where you are looking.+ (r.kind === 'still'+ ? '<button type="button" class="ed-pool-add ed-pool-ov" ' ++ 'title="Lay this over the picture at the playhead (overlay lane)" ' ++ 'onclick="event.stopPropagation();edPoolOverlay(' + i + ')">▣</button>'+ : '') ++ '</div>').join('');+ list._rows = show;+ edPoolObserve(list);+ // The row the source monitor is showing may have moved, or be gone: a+ // search, a tab change and a refresh all repaint this list, and the index+ // "Add to timeline" hands back has to be the one in the list on screen.+ if (SBE.source) {+ SBE.srcIndex = show.findIndex(r => r.path === SBE.source.path);+ sbePaintSource();+ }+ if (note) {+ note.textContent = rows.length > show.length+ ? (show.length + ' of ' + rows.length + ' shown.')+ : (rows.length + ' clip' + (rows.length === 1 ? '' : 's') ++ ' · click one to watch it, + to put it at the end, or drag it onto the track.');+ }+}++// One observer for the pool's whole life, re-pointed at each repaint. It+// attaches a thumbnail's src on the way in and takes it away on the way out,+// so the number of live decoders is the number of rows you can see.+function edPoolObserve(list) {+ if (!('IntersectionObserver' in window)) {+ list.querySelectorAll('[data-src]').forEach(v => {+ v.src = v.dataset.src; });+ return;+ }+ if (ED.io) ED.io.disconnect();+ // The first screenful loads WITHOUT waiting for the observer. Intersection+ // callbacks do not run while a tab is occluded, and a pool of black+ // rectangles is indistinguishable from a pool of broken clips — so the rows+ // that are on screen at paint time never depend on a callback at all.+ [...list.querySelectorAll('[data-src]')].slice(0, 12).forEach(v => {+ if (!v.getAttribute('src')) v.src = v.dataset.src;+ });+ ED.io = new IntersectionObserver((entries) => {+ for (const e of entries) {+ const v = e.target;+ if (e.isIntersecting) {+ if (!v.getAttribute('src') && v.dataset.src) v.src = v.dataset.src;+ } else if (v.getAttribute('src')) {+ v.removeAttribute('src');+ // Only a <video> holds a decoder to release; load() on an <img> is not+ // a function, and calling it would throw once per row leaving the view.+ if (v.tagName === 'VIDEO') { try { v.load(); } catch (err) {} }+ }+ }+ }, { root: list, rootMargin: '150px' });+ list.querySelectorAll('[data-src]').forEach(v => ED.io.observe(v));+}++// THE VERB. A clip joins the timeline, gets its proxy built before it lands,+// and the user does not move: adding to a cut is not a reason to leave it.+async function edPoolAdd(i, dropAt) {+ const list = document.getElementById('edPoolList');+ const row = ((list || {})._rows || [])[i];+ if (!row) return;+ // A DRAG ENDS IN A CLICK EVENT. The browser fires one after every pointerup+ // on a <button>, so without this flag every drop would also add the clip a+ // second time, at the end of the track.+ if (ED.suppressClick && dropAt === undefined) { ED.suppressClick = false; return; }+ if (!SBE.open || !SBE.id) {+ phosToast('Open a __SEQ__ first — the Editor holds one timeline at a time.', {});+ return;+ }+ // The row's own word first, then the file's. The server checks the suffix+ // too — this is the half that keeps the CLIENT from asking /file for a+ // picture, which is what painted a black frame.+ const isStill = (row.kind === 'still')+ || /\.(png|jpe?g|webp|bmp|tiff?)$/i.test(String(row.path || ''));+ const note = document.getElementById('edPoolNote');+ if (note) {+ note.textContent = isStill+ ? ('reading ' + (row.title || 'that image') + '…')+ : ('building the proxy for ' + (row.title || 'that clip') + '…');+ }+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ if (isStill) { fd.set('kind', 'still'); fd.set('path', row.path); }+ else if (row.from) { fd.set('from', row.from); fd.set('only', String(row.only)); }+ else fd.set('path', row.path);+ if (row.title) fd.set('title', row.title);+ let r;+ try { r = await (await fetch('/storyboard/edit/add-clip', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) {+ if (note) note.textContent = '';+ phosToast(r.error || 'That clip could not be added.', { kind: 'danger' });+ return;+ }+ const c = r.clip || {};+ const item = {+ path: c.path || row.path, proxy: c.proxy || null,+ kind: isStill ? 'still' : 'video',+ duration_s: (isStill ? SBE_STILL_SECONDS+ : (c.duration_s || row.duration_s || null)),+ title: c.title || row.title || '', n: c.n,+ };+ // A CLICK LANDS AT THE END; A DROP LANDS WHERE IT WAS DROPPED. The first+ // cannot move anybody's cuts, which is why it is still the default verb; the+ // second was ASKED for, and a drop that ignored where the pointer was would+ // be a drag with no meaning.+ let at;+ const ok = sbeMutate(cs => {+ if (dropAt === undefined || dropAt === null) {+ at = sbeFilmDuration(cs);+ return sbePlaceUnplaced(cs, item, at);+ }+ at = Math.max(0, sbeNum(dropAt));+ return sbeInsertAt(cs, item, at);+ });+ if (!ok) { if (note) note.textContent = ''; return; }+ await sbeSave(true);+ if (note) note.textContent = '';+ phosToast('Added at ' + sbeFmtTime(at) ++ (isStill ? ' · still' : ' · proxy ready.'),+ { kind: 'success', duration: 4000 });+ // The board may have gained a shot (an import), and the payload's `unplaced`+ // and `clips` are now stale. Re-read quietly; nothing on screen moves.+ sbeLoad(true);+}++// ---------------------------------------------------------------------------+// DRAG: a pool row onto the track+// ---------------------------------------------------------------------------+// POINTER EVENTS, NOT HTML5 DRAG-AND-DROP. The track's own move/trim gestures+// are already pointerdown/move/up with pointer capture, and mixing the two+// models means a dragstart that swallows the capture and a drop the track+// never hears. This is the same substrate the track uses, so the two coexist+// by construction rather than by luck. Click-to-add is untouched: a press that+// never travels more than a few pixels is still a click.+function edPoolDragStart(ev, i) {+ const list = document.getElementById('edPoolList');+ const row = ((list || {})._rows || [])[i];+ if (!row || !SBE.open || !SBE.id) return;+ if (ev.button !== undefined && ev.button !== 0) return;+ // The ELEMENT the press started on, not just the data row — the guard at+ // the end of the drag needs to know whether the click the browser is about+ // to fire will land back here.+ ED.drag = { row: row, index: i, x0: ev.clientX, y0: ev.clientY,+ moved: false, ghost: null,+ el: (ev.target && ev.target.closest)+ ? ev.target.closest('.ed-pool-row') : null };+ // The pool's drag is the one gesture in this panel that let the browser+ // start a text selection underneath it, so every drop painted the entire+ // editor — labels, times, hint bar, rail — in selection blue until the+ // next click.+ if (ev.preventDefault) ev.preventDefault();+ window.addEventListener('pointermove', edPoolDragMove);+ window.addEventListener('pointerup', edPoolDragEnd, { once: true });+}++function edPoolDragMove(ev) {+ const d = ED.drag;+ if (!d) return;+ if (!d.moved) {+ if (Math.abs(ev.clientX - d.x0) + Math.abs(ev.clientY - d.y0) < 5) return;+ d.moved = true;+ // PORTALLED TO <body>, because the pool list has its own overflow and a+ // ghost parented inside it is clipped the instant it leaves the column —+ // which is every drag, since the track is in the other column.+ d.ghost = document.createElement('div');+ d.ghost.className = 'ed-drag-ghost';+ d.ghost.textContent = d.row.title || d.row.path || 'clip';+ document.body.appendChild(d.ghost);+ }+ d.ghost.style.left = (ev.clientX + 12) + 'px';+ d.ghost.style.top = (ev.clientY + 12) + 'px';+ const track = sbeEl('sbeTrack');+ const over = edPoolOverTrack(ev, track);+ track.classList.toggle('is-dropping', over);+ SBE.dropAt = over ? edPoolDropTime(ev, track) : null;+ sbePaintTrack();+}++// The film time under the pointer, snapped to the boundary a drop would use —+// so the line the user sees is the position the clip will take, not the pixel+// their finger happens to be over.+function edPoolDropTime(ev, track) {+ const t = sbeTimeFromEvent(ev, track);+ const idx = sbeDropIndex(SBE.clips, t);+ const prev = SBE.clips[idx - 1];+ return prev ? sbeNum(prev.film_end) : 0;+}++function edPoolOverTrack(ev, track) {+ if (!track) return false;+ const r = track.getBoundingClientRect();+ // Generous vertically: a drop aimed at a 78px strip from another column+ // should not fail because the pointer was four pixels high.+ return ev.clientX >= r.left && ev.clientX <= r.right &&+ ev.clientY >= r.top - 24 && ev.clientY <= r.bottom + 24;+}++async function edPoolDragEnd(ev) {+ const d = ED.drag;+ ED.drag = null;+ window.removeEventListener('pointermove', edPoolDragMove);+ if (!d) return;+ if (d.ghost) d.ghost.remove();+ const track = sbeEl('sbeTrack');+ if (track) track.classList.remove('is-dropping');+ const at = SBE.dropAt;+ SBE.dropAt = null;+ sbePaintTrack();+ if (!d.moved) return; // a press that never travelled+ // ARMED ONLY IF THE CLICK IS ACTUALLY COMING. "A drag ends in a click event+ // on the row it started from" is true for a press that never left the row+ // and false for every drag onto the track — which is all of them. So the+ // flag outlived the gesture and ate the user's next genuine click: you drop+ // a clip on the timeline, click another clip to preview it, and the source+ // monitor does nothing until you click a second time.+ ED.suppressClick = !!(d.el && ev.target && d.el.contains(ev.target));+ if (at === null || at === undefined) return; // dropped in open space+ await edPoolAdd(d.index, at);+}++// ---------------------------------------------------------------------------+// BLACK — the one clip with no file+// ---------------------------------------------------------------------------+// No server round trip, because there is nothing on disk to check, no+// geometry to probe and no proxy to build. It is a length and a kind.+function edAddSlug() {+ if (!SBE.open || !SBE.id) {+ phosToast('Open a __SEQ__ first — the Editor holds one timeline at a time.', {});+ return;+ }+ const box = document.getElementById('edSlugSecs');+ const secs = Math.max(SBE_MIN_CLIP, Math.min(60, sbeNum(box && box.value, 2) || 2));+ const at = sbeFilmDuration(SBE.clips);+ const ok = sbeMutate(cs => sbeInsertAt(cs, {+ kind: 'slug', title: 'black', duration_s: secs,+ }, at));+ if (!ok) return;+ sbeSave(true);+ phosToast(secs.toFixed(1) + 's of black at ' + sbeFmtTime(at) + '.',+ { kind: 'success', duration: 3500 });+}++// ---------------------------------------------------------------------------+// RELINK — draft → delivery+// ---------------------------------------------------------------------------+function sbePaintRelink() {+ const bar = sbeEl('sbeRelink');+ if (!bar) return;+ const rows = SBE.relink || [];+ bar.hidden = !rows.length;+ if (!rows.length) return;+ sbeEl('sbeRelinkText').textContent = rows.length ++ (rows.length === 1 ? ' shot was' : ' shots were') ++ ' finished since this cut — use the finished versions.';+}++async function sbeRelink() {+ const btn = sbeEl('sbeRelinkBtn');+ if (btn) btn.disabled = true;+ // Save first: the server rewrites the file on disk, and an unsaved+ // arrangement would be rewritten out from under itself. CHECKED — a save+ // that did not land means the server is holding an older cut, and relinking+ // that one writes it back over what is on screen.+ if (SBE.dirty && !SBE.conflict && !(await sbeSave(true))) {+ if (btn) btn.disabled = false;+ phosToast('Your arrangement could not be saved, and relinking works on ' ++ 'the saved file — fix the save first.',+ { kind: 'danger', duration: 8000 });+ return;+ }+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ let r;+ try { r = await (await fetch('/storyboard/edit/relink', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (btn) btn.disabled = false;+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'Those clips could not be relinked.', { kind: 'danger' });+ return;+ }+ SBE.undo.length = 0; SBE.redo.length = 0;+ sbeAdopt(r, true);+ phosToast((r.relinked || 0) + ' clip(s) now play the finished files. ' ++ 'Same cuts, same timings.', { kind: 'success', duration: 6000 });+}++// ---------------------------------------------------------------------------+// IMPORT — clips from another film, into this one+// ---------------------------------------------------------------------------+// The pool is a column away, and on a stacked window it is above the fold.+// This is the way back to it from the prepare bar.+function edPoolFocus() {+ const pane = document.getElementById('edSectionTab');+ if (pane && pane.scrollIntoView) pane.scrollIntoView({ behavior: 'smooth', block: 'start' });+ const q = document.getElementById('edPoolSearch');+ if (q) { try { q.focus(); } catch (e) {} }+}++function sbeTogglePlay() { SBE.playing ? sbeStop() : sbePlay(); }++// Sound. One switch drives the picture, the soundtrack bed and the button, so+// they can never disagree about whether this timeline is audible.+// A BROWSER REFUSING TO AUTOPLAY IS NOT A PREFERENCE, and this is the second+// half of why the Editor could go permanently silent. When Chrome declines an+// unmuted play() the editor mutes itself so the picture still runs — right+// call — but it wrote that decision to localStorage, so ONE refusal silenced+// every later session: clips AND soundtrack, across reloads, with a 34px+// speaker button as the only way back. Reported as total preview audio loss,+// which is exactly what it is.+//+// `remember` is FALSE for that path: the mute lasts as long as the tab, the+// stored preference is left alone, and it says so out loud instead of+// appending a sentence to a 10.5px line under the transport.+function sbeSetMute(on, note, remember) {+ SBE.muted = !!on;+ if (remember !== false) {+ try { localStorage.setItem('sbeMuted', SBE.muted ? '1' : '0'); } catch (e) {}+ }+ const v = sbeEl('sbeVideo');+ if (v) { v.muted = SBE.muted; v.volume = 1; }+ // ONE OPINION ABOUT SOUND, across both monitors. A source screen with its+ // own mute would be a second source of truth for the exact state this+ // switch exists to keep single.+ const sv = sbeEl('sbeSrcVideo');+ if (sv) { sv.muted = SBE.muted; sv.volume = 1; }+ const a = SBE.musicEl;+ if (a) { a.muted = SBE.muted; }+ const b = sbeEl('sbeMuteBtn');+ if (b) {+ b.textContent = SBE.muted ? '🔇' : '🔊';+ b.classList.toggle('is-off', SBE.muted);+ b.title = note || (SBE.muted ? 'Sound off — click to unmute (M)' : 'Sound on (M)');+ }+ if (note) {+ const el = sbeEl('sbeApprox');+ if (el && el.dataset.muteNoted !== '1') {+ el.dataset.muteNoted = '1';+ el.textContent = note + ' ' + el.textContent;+ }+ if (typeof phosToast === 'function' && !SBE.muteToasted) {+ SBE.muteToasted = true;+ phosToast('The browser would not start sound without a click, so the '+ + 'preview is muted for now — press the speaker (or M) to '+ + 'turn it back on. Your setting has not been changed.',+ { kind: 'warn', duration: 9000 });+ }+ }+}++// THE ONE-CLICK WAY BACK, and the reason the refusal above is survivable: a+// press of the speaker is a user gesture, so the sound it turns on is sound+// the browser will now allow.+function sbeUnmuteFromRefusal() {+ SBE.muteToasted = false;+ sbeSetMute(false);+ if (SBE.playing) { const v = sbeEl('sbeVideo'); if (v) { try { v.play(); } catch (e) {} } }+ sbeMusicPlay();+}++// TAKE THE STAGE TO A CLIP, WHATEVER KIND IT IS. The video branch loads,+// seeks and plays; the other two only decide which layer is lit, because+// there is nothing to decode, nothing to seek, and no clock to start.+async function sbeEnter(c, at) {+ const v = sbeEl('sbeVideo');+ const img = sbeEl('sbeStill');+ sbeApplyPreviewFilter(sbeBright(c));+ const kind = sbeKind(c);+ if (kind === 'video') {+ if (img) img.classList.remove('is-on');+ await sbeLoadInto(v, c, (at === undefined || at === null) ? sbeNum(c.start) : sbeNum(at));+ v.classList.add('is-on');+ try { await v.play(); } catch (e) {}+ return;+ }+ try { v.pause(); } catch (e) {}+ v.classList.remove('is-on');+ if (img) {+ if (kind === 'still' && c.path) {+ const url = sbeClipUrl(c);+ if (img.getAttribute('src') !== url) img.src = url;+ img.classList.add('is-on');+ } else {+ img.classList.remove('is-on'); // a slug: the stage's own black+ }+ }+}++async function sbePlay() {+ if (SBE.playing) return;+ const c = sbeClipAt(SBE.clips, SBE.playhead) || SBE.clips[0];+ if (!c) return;+ sbeSrcStop(); // the source yields; the two monitors never overlap+ SBE.playing = true;+ SBE.lastTs = 0;+ sbePaintChrome();+ if (!sbeClipAt(SBE.clips, SBE.playhead)) SBE.playhead = sbeNum(c.film_start);+ const v = sbeEl('sbeVideo');+ SBE.curId = c.id;+ if (sbeKind(c) === 'video') {+ await sbeLoadInto(v, c, sbeNum(c.start) + (SBE.playhead - sbeNum(c.film_start)));+ v.classList.add('is-on');+ try {+ await v.play();+ } catch (e) {+ // NotAllowedError = no user activation to spend (autoplay policy). Losing+ // the picture is worse than losing the sound, so fall back to muted and say+ // so, rather than leaving a Play button that visibly does nothing.+ // An AbortError is a pause we asked for (the source monitor taking the+ // screen), and treating that as a block would mute the editor for a+ // reason that has nothing to do with the browser.+ if (!SBE.playing || (e && e.name === 'AbortError')) { /* stopped on purpose */ }+ else if (!v.muted) {+ v.muted = true;+ sbeSetMute(true, 'browser blocked sound — click 🔊 to unmute', false);+ try { await v.play(); } catch (e2) {}+ }+ }+ sbeApplyPreviewFilter(sbeBright(c));+ } else {+ await sbeEnter(c);+ }+ sbeMusicPlay();+ sbeStripSync(true);+ SBE.raf = requestAnimationFrame(sbeFrame);+}++function sbeStop() {+ SBE.playing = false;+ SBE.lastTs = 0;+ if (SBE.raf) { cancelAnimationFrame(SBE.raf); SBE.raf = 0; }+ const v = sbeEl('sbeVideo');+ if (v) { try { v.pause(); } catch (e) {} }+ sbeMusicStop();+ sbeStripStop();+ if (SBE.open) sbePaintChrome();+}++async function sbeFrame() {+ if (!SBE.playing) return;+ const v = sbeEl('sbeVideo');+ // THE WALL CLOCK, for the clips that do not carry one. A still and a slug+ // have no <video> whose currentTime the playhead can be read off, so without+ // this the transport froze the instant a film reached its first black.+ // Capped at a quarter second so a backgrounded tab resumes rather than+ // jumping half a film forward on its first frame back.+ const now = (typeof performance !== 'undefined' && performance.now)+ ? performance.now() : Date.now();+ const dt = SBE.lastTs ? Math.max(0, Math.min(0.25, (now - SBE.lastTs) / 1000)) : 0;+ SBE.lastTs = now;+ const c = sbeById(SBE.clips, SBE.curId);+ if (c && sbeKind(c) !== 'video') {+ SBE.playhead += dt;+ if (SBE.playhead >= sbeNum(c.film_end) - 1e-3) {+ const next = SBE.clips[SBE.clips.indexOf(c) + 1];+ if (!next) {+ SBE.playhead = sbeNum(c.film_end);+ sbeStop(); sbePaintHead(); return;+ }+ SBE.playing = false; // hold the loop across the cut+ SBE.playhead = sbeNum(next.film_start);+ SBE.curId = next.id;+ await sbeEnter(next);+ SBE.playing = true;+ sbeMusicSync();+ sbePaintTrack();+ }+ } else if (c) {+ SBE.playhead = sbeNum(c.film_start) + Math.max(0, v.currentTime - sbeNum(c.start));+ if (v.currentTime >= sbeNum(c.end) - 1e-3 || v.ended) {+ const next = SBE.clips[SBE.clips.indexOf(c) + 1];+ if (!next) { sbeStop(); sbePaintHead(); return; }+ SBE.playing = false; // hold the loop across the cut+ SBE.playhead = sbeNum(next.film_start);+ SBE.curId = next.id;+ await sbeEnter(next);+ SBE.playing = true;+ sbeMusicSync();+ sbePaintTrack();+ }+ } else {+ // A hole: the picture goes black and the clock keeps running, which is+ // exactly what the render will do if the gap is ever filled.+ v.classList.remove('is-on');+ const img = sbeEl('sbeStill');+ if (img) img.classList.remove('is-on');+ const nxt = SBE.clips.find(x => sbeNum(x.film_start) > SBE.playhead);+ SBE.playhead += dt || (1 / 60);+ if (!nxt) { sbeStop(); sbePaintHead(); return; }+ if (SBE.playhead >= sbeNum(nxt.film_start)) {+ SBE.curId = nxt.id;+ await sbeEnter(nxt);+ sbeMusicSync();+ }+ }+ // EVERY FRAME, because a strip starts and stops on its own clock rather+ // than at the cuts — `sbeMusicSync` can ride the transitions, this cannot.+ sbeStripSync();+ sbeFadePaint();+ sbeOvPaint();+ sbePaintHead();+ SBE.raf = requestAnimationFrame(sbeFrame);+}++// The soundtrack is best-effort and says so when it cannot be had: /file serves+// what is under mlx_outputs, and a track living anywhere else is still perfectly+// good for the waveform, the grid and the render — it just cannot be auditioned+// in this browser.+function sbeSyncMusic() {+ const path = (SBE.audio || {}).path || '';+ if (!path) { SBE.musicEl = null; SBE.music = ''; return; }+ if (SBE.music === path && SBE.musicEl) return;+ SBE.music = path;+ SBE.musicOk = true;+ const a = new Audio('/file?path=' + encodeURIComponent(path));+ a.preload = 'auto';+ a.muted = !!SBE.muted;+ a.addEventListener('error', () => {+ SBE.musicOk = false;+ const el = sbeEl('sbeApprox');+ if (el && el.dataset.musicNoted !== '1') {+ el.dataset.musicNoted = '1';+ el.textContent = el.textContent ++ ' The soundtrack cannot be played from here (it lives outside mlx_outputs) — the waveform, the beat grid and the render still use it.';+ }+ });+ SBE.musicEl = a;+}++// THE BED PLAYS THE WINDOW THE STRIP SHOWS. Both of these read `offset` and+// nothing else, so a track whose intro had been trimmed off played untrimmed+// in the Editor and trimmed in the file — the exact "what the strip shows and+// what the render builds cannot come apart" contract sbeMusicWindow claims to+// establish, broken on the one surface the user listens to.+function sbeMusicAt(t) {+ const w = sbeMusicWindow(SBE.audio, SBE.peaks ? SBE.peaks.duration : 0);+ if (t < w.film_start - 1e-3) return null; // not in yet+ if (w.film_end !== null && t >= w.film_end) return null; // out already+ return Math.max(0, w.head + (t - w.film_start));+}+function sbeMusicPlay() {+ const a = SBE.musicEl;+ if (!a || !SBE.musicOk) return;+ const at = sbeMusicAt(SBE.playhead);+ try {+ if (at === null) { a.pause(); return; }+ a.currentTime = at;+ a.play().catch(() => {});+ } catch (e) {}+}+function sbeMusicSync() {+ const a = SBE.musicEl;+ if (!a || !SBE.musicOk || !SBE.playing) return;+ const want = sbeMusicAt(SBE.playhead);+ if (want === null) { try { if (!a.paused) a.pause(); } catch (e) {} return; }+ // THE MIX, HEARD. Not the bed's envelope alone — the whole of what the+ // render will apply to this track: the fader, the envelope, and the duck if+ // it is on and nothing outranks it. `sbeBedGainPoints` is the same function+ // the render's `volume` expression is built from and the same one the level+ // line draws, so this <audio> element and the mp4 cannot come apart. It was+ // the envelope and nothing else, while the render silently held the bed at+ // 0.20 and ducked it — "when you render it, there are some weird+ // manipulations... the volume of the music goes low when the dialogue+ // appears."+ //+ // ON THE BED'S OWN CLOCK, which is the played window and not the track: the+ // playhead less the film second the music starts at.+ const bw = sbeMusicWindow(SBE.audio, SBE.peaks ? SBE.peaks.duration : 0);+ a.volume = sbeBedGainAt(SBE.audio || {}, SBE.clips,+ sbeFilmDuration(SBE.clips),+ SBE.playhead - bw.film_start);+ try {+ if (a.paused) a.play().catch(() => {});+ if (Math.abs(a.currentTime - want) > 0.25) a.currentTime = want;+ } catch (e) {}+}+function sbeMusicStop() { const a = SBE.musicEl; if (a) { try { a.pause(); } catch (e) {} } }++// ---- THE STRIP PLAYER ---------------------------------------------------+// A POOL, NOT AN ELEMENT. The music bed is one track and one <audio>; clip+// strips overlap by design — that is what a split edit IS — so a J-cut needs+// two voices sounding at once across the cut. Three: two for the overlap and+// one spare, so a strip that starts while two are still ringing does not have+// to steal one that is audible.+const SBE_STRIP_VOICES = 3;+// The same tolerance the music bed uses. Re-seeking on every frame would+// stutter; letting it drift further than a quarter second would be audible.+const SBE_STRIP_SLIP = 0.25;++function sbeStripPool() {+ if (!SBE.stripEls) SBE.stripEls = [];+ while (SBE.stripEls.length < SBE_STRIP_VOICES) {+ const a = new Audio();+ a.preload = 'auto';+ a.dataset.clip = '';+ SBE.stripEls.push(a);+ }+ return SBE.stripEls;+}++// Drive every audible strip from the PLAYHEAD, exactly as the bed is driven —+// independent of which picture is on stage, which is the entire point.+// `force` re-seeks rather than tolerating slip: a scrub or an edit has moved+// the ground, so "close enough" is the wrong answer.+function sbeStripSync(force) {+ if (!SBE.open) return;+ const pool = sbeStripPool();+ const want = sbeStripsAt(SBE.clips, SBE.playhead);+ const live = {};+ for (const w of want) live[w.id] = w;+ // A voice whose strip has gone quiet is released BEFORE any is claimed, or+ // an overlap of two would find the pool full of yesterday's clips.+ for (const a of pool) {+ if (a.dataset.clip && !live[a.dataset.clip]) {+ try { a.pause(); } catch (e) {}+ a.dataset.clip = '';+ }+ }+ for (const w of want) {+ let a = null;+ for (const el of pool) if (el.dataset.clip === w.id) { a = el; break; }+ let fresh = false;+ if (!a) {+ for (const el of pool) if (!el.dataset.clip) { a = el; break; }+ if (!a) continue; // more overlap than voices: skip one+ a.dataset.clip = w.id;+ fresh = true;+ }+ const url = w.path ? ('/file?path=' + encodeURIComponent(w.path)) : '';+ if (url && a.dataset.src !== url) {+ a.dataset.src = url;+ a.src = url;+ fresh = true;+ }+ a.muted = !!SBE.muted;+ // THE ENVELOPE, HEARD. The render builds a `volume` expression and the+ // export writes level keyframes; the preview has to move the same number+ // or the one place the user checks his work is the one place the fade+ // does not exist. `w.at - w.start` is the STRIP-relative second, which is+ // the envelope's own clock.+ const c2 = sbeById(SBE.clips, w.id);+ const win = c2 ? sbeClipAudio(c2) : null;+ a.volume = win ? sbeGainAt(c2, win.len, w.at - win.start) : 1;+ try {+ if (fresh || force || Math.abs(a.currentTime - w.at) > SBE_STRIP_SLIP) {+ a.currentTime = w.at;+ }+ if (SBE.playing) { if (a.paused) a.play().catch(() => {}); }+ else if (!a.paused) a.pause();+ } catch (e) {}+ }+}++function sbeStripStop() {+ for (const a of (SBE.stripEls || [])) {+ try { a.pause(); } catch (e) {}+ }+}++// ---------------------------------------------------------------------------+// COMMANDS+// ---------------------------------------------------------------------------+// THE VIEW FOLLOWS THE PICTURE, ONE SCREENFUL AT A TIME. Called from+// sbePaintHead, which runs on every animation frame while the film plays, so+// the cheap early return in sbeFollowScroll is what keeps it from writing+// scrollLeft sixty times a second and cancelling a drag of the scrollbar.+function sbeFollow() {+ if (!SBE.playing) return;+ const box = sbeEl('sbeScroll');+ if (!box) return;+ const max = Math.max(0, box.scrollWidth - box.clientWidth);+ if (max <= 0) return;+ const want = sbeFollowScroll(sbePx(SBE.playhead), box.scrollLeft,+ box.clientWidth, max);+ if (Math.abs(want - box.scrollLeft) > 1) box.scrollLeft = want;+}++// ---- zoom, all three doors: the buttons, the slider, and alt + wheel ----+// The floor is never a constant: it is whatever puts THIS film in THIS+// window, so the slider's left end always means "all of it".+function sbeZoomMin() {+ const box = sbeEl('sbeScroll');+ return sbeZoomFitPps(sbeSpan(), box ? box.clientWidth : 900);+}++// `at` is a film time to hold still (alt + wheel passes the one under the+// pointer); without it the playhead is held if it is on screen, the middle of+// the view if it is not.+function sbeZoomTo(pps, at) {+ const box = sbeEl('sbeScroll');+ const lo = sbeZoomMin();+ const hi = Math.max(lo, SBE_PPS_MAX);+ const want = Math.max(lo, Math.min(hi, sbeNum(pps, SBE.pps)));+ if (!box) { SBE.pps = want; sbePaint(); return; }+ const anchor = sbeZoomAnchor(SBE.playhead, box.scrollLeft, box.clientWidth,+ SBE.pps, at);+ SBE.pps = want;+ sbePaint();+ box.scrollLeft = sbeZoomScroll(anchor, SBE.pps,+ Math.max(0, box.scrollWidth - box.clientWidth));+ sbePaintChrome();+}++// The − / + buttons keep the old ladder, clamped to the live floor so they can+// never step past "the whole film" and leave the slider disagreeing with them.+function sbeZoom(dir) {+ const lo = sbeZoomMin();+ const steps = [8, 12, 18, 26, 42, 64, 96, 140, 200].filter(s => s > lo);+ steps.unshift(lo);+ let i = 0;+ for (let k = 0; k < steps.length; k++) if (steps[k] <= SBE.pps + 1e-6) i = k;+ sbeZoomTo(steps[Math.max(0, Math.min(steps.length - 1, i + dir))]);+}++function sbeZoomSlide(v) {+ const lo = sbeZoomMin();+ sbeZoomTo(sbeZoomFromSlider(v, lo, Math.max(lo, SBE_PPS_MAX)));+}++// shift + wheel pans, alt + wheel zooms around the pointer — the two gestures+// every NLE and every DAW already has. A plain wheel is left alone: it belongs+// to the column, which scrolls vertically.+function sbeOnTlWheel(ev) {+ const box = sbeEl('sbeScroll');+ if (!box) return;+ if (ev.altKey) {+ ev.preventDefault();+ const r = box.getBoundingClientRect();+ const at = (box.scrollLeft + (ev.clientX - r.left)) / Math.max(1e-6, SBE.pps);+ const k = Math.pow(1.0015, -(ev.deltaY || 0));+ sbeZoomTo(SBE.pps * k, at);+ return;+ }+ // A trackpad sends horizontal intent as deltaX with no modifier at all, and+ // refusing that would be refusing the one gesture Mac users already know.+ const dx = (ev.shiftKey ? (ev.deltaY || ev.deltaX) : ev.deltaX) || 0;+ if (!dx) return;+ ev.preventDefault();+ box.scrollLeft += dx;+}++function sbeRippleSelected() {+ if (!SBE.sel) return;+ sbeMutate(cs => sbeRippleDelete(cs, SBE.sel));+ SBE.sel = '';+ sbePaint();+}++function sbeSplitHere() {+ sbeMutate(cs => sbeSplitAt(cs, SBE.playhead));+}++function sbeToggleLock() {+ const c = sbeById(SBE.clips, SBE.sel);+ if (!c) return;+ const before = JSON.stringify(SBE.clips);+ c.locked = !c.locked;+ if (c.locked) c._pin = sbeNum(c.film_start); else delete c._pin;+ c.source = 'human';+ sbeLayout(SBE.clips);+ SBE.undo.push(before);+ SBE.redo.length = 0;+ SBE.dirty = true;+ sbeSetState('unsaved changes', 'dirty');+ sbePaint();+ sbeQueueSave();+}++function sbePlace(i) {+ const u = (SBE.unplaced || [])[i];+ if (!u) return;+ const at = (u.slot && u.slot.film_start !== undefined)+ ? sbeNum(u.slot.film_start) : sbeFilmDuration(SBE.clips);+ const ok = sbeMutate(cs => sbePlaceUnplaced(cs, u, at));+ if (ok) {+ SBE.unplaced = SBE.unplaced.filter((_, k) => k !== i);+ sbePaint();+ }+}++// ---------------------------------------------------------------------------+// PREPARE / AUTO / GENERATE / RENDER+// ---------------------------------------------------------------------------+async function sbePrepare() {+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ const music = (sbeEl('sbeMusic').value || '').trim();+ if (music) fd.set('music', music);+ let r;+ try { r = await (await fetch('/storyboard/edit/prepare', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) {+ phosToast(r.error || 'Could not start.', { kind: 'danger' });+ if (r.prepare) { SBE.prepare = r.prepare; sbePaintChrome(); }+ return;+ }+ SBE.prepare = r.prepare || { state: 'running', stage: 'start' };+ sbePaintChrome();+}++async function sbePrepareCancel() {+ const fd = new URLSearchParams(); fd.set('id', SBE.id);+ try { await fetch('/storyboard/edit/cancel', { method: 'POST', body: fd }); } catch (e) {}+}++async function sbeAuto() {+ if (!confirm('Re-cut this film from scratch?\n\n' ++ 'The auto-editor picks the best window of every clip and cuts on the beat. ' ++ 'It THROWS AWAY the arrangement on screen — every trim, every move, every split.\n\n' ++ 'The clips themselves are untouched.')) return;+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ const music = (sbeEl('sbeMusic').value || '').trim();+ if (music) fd.set('music', music);+ let r;+ try { r = await (await fetch('/storyboard/edit/auto', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) { phosToast(r.error || 'The auto-edit failed.', { kind: 'danger' }); return; }+ SBE.undo.length = 0; SBE.redo.length = 0;+ sbeAdopt(r, true);+ phosToast('Re-cut · ' + (r.edit.clips || []).length + ' clips.', { kind: 'success' });+}++let _sbeGenAt = 0;+function sbeGenOpen(filmStart, duration) {+ _sbeGenAt = sbeNum(filmStart);+ sbeEl('sbeGenWhere').textContent =+ 'Nothing plays between ' + sbeFmtTime(filmStart) + ' and ' ++ sbeFmtTime(sbeNum(filmStart) + sbeNum(duration)) + '. This shot is written to the ' ++ 'storyboard and rendered like any other.';+ // FLOOR, not round: a shot longer than the hole it was ordered for pushes+ // everything after it off the beat the moment it is placed.+ sbeEl('sbeGenDuration').value =+ Math.max(0.5, Math.floor(sbeNum(duration) * 10) / 10).toFixed(1);+ sbeEl('sbeGenParams').hidden = true;+ sbeEl('sbeGenParams').textContent = '';+ sbeEl('sbeGenGo').disabled = false;+ sbeEl('sbeGenModal').classList.add('show');+ setTimeout(() => { try { sbeEl('sbeGenPrompt').focus(); } catch (e) {} }, 30);+}+function sbeGenClose() { sbeEl('sbeGenModal').classList.remove('show'); }++async function sbeGenSubmit() {+ const prompt = (sbeEl('sbeGenPrompt').value || '').trim();+ if (!prompt) { phosToast('Write what the shot shows.', {}); return; }+ const btn = sbeEl('sbeGenGo');+ btn.disabled = true;+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ fd.set('prompt', prompt);+ fd.set('duration', String(sbeNum(sbeEl('sbeGenDuration').value, 5)));+ fd.set('film_start', String(_sbeGenAt));+ const on = document.querySelector('#sbeGenPass .pill-btn.active');+ fd.set('pass', (on && on.dataset.pass) || 'draft');+ let r;+ try { r = await (await fetch('/storyboard/edit/generate', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ if (!r.ok) {+ btn.disabled = false;+ phosToast(r.error || 'Could not queue the shot.', { kind: 'danger' });+ return;+ }+ // WHAT WILL ACTUALLY RENDER. make_job silently drops any form field it does+ // not name, so the server reads the params back off the queued job and hands+ // them here rather than echoing the request.+ const box = sbeEl('sbeGenParams');+ box.hidden = false;+ box.textContent = 'queued as shot ' + r.n + ' (job ' + r.job_id + ')\n' ++ Object.keys(r.params || {}).map(k => k + ': ' + r.params[k]).join('\n');+ SBE.awaitingClip = Date.now();+ phosToast('Shot ' + r.n + ' is in the queue. It appears under the timeline when it lands.',+ { kind: 'success', duration: 6000 });+}++async function sbeRenderFilm() {+ if (SBE.rendering) return;+ // THE RENDER READS THE SAVED FILE, so a save that did not land renders the+ // previous cut — a film that is silently not the one on screen, which is+ // the worst possible way to find out about a failing save.+ if (SBE.dirty && !(await sbeSave(true))) {+ phosToast('The timeline could not be saved, and the render builds from ' ++ 'the saved file — it would make the previous cut. Fix the save ' ++ 'first.', { kind: 'danger', duration: 8000 });+ return;+ }+ const holes = sbeHoles(SBE.clips);+ if (holes.length && !confirm(+ holes.length + ' hole(s) totalling ' ++ holes.reduce((a, g) => a + g.duration, 0).toFixed(2) + 's are still empty.\n\n' ++ 'The assembler CONCATENATES — a hole closes and everything after it slides ' ++ 'earlier, off the beat it was cut to.\n\nRender anyway?')) return;+ const btn = sbeEl('sbeRenderBtn');+ const prev = btn.textContent;+ SBE.rendering = true;+ btn.disabled = true;+ btn.textContent = 'Assembling…';+ sbeEl('sbeRenderNote').textContent =+ 'One ffmpeg pass over ' + SBE.clips.length + ' clips. This takes as long as an encode takes.';+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ const music = (sbeEl('sbeMusic').value || '').trim();+ if (music) { fd.set('music', music); fd.set('music_mode', sbeMusicMode()); }+ let r;+ try { r = await (await fetch('/storyboard/edit/render', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ SBE.rendering = false;+ btn.disabled = false;+ btn.textContent = prev;+ if (!r.ok) {+ sbeEl('sbeRenderNote').textContent = '';+ phosToast(r.error || 'The film could not be assembled.', { kind: 'danger', duration: 8000 });+ return;+ }+ sbeEl('sbeRenderNote').textContent = (r.gaps_note || '') ++ ' Wrote ' + Math.round(sbeNum(r.duration)) + 's to ' + (r.path || '').split('/').pop();+ phosToast('Rendered ' + r.clips + ' clips · ' + Math.round(sbeNum(r.duration)) + 's' ++ (r.gaps_note ? ' — ' + r.gaps_note : ''),+ { kind: 'success', duration: r.gaps_note ? 11000 : 6000 });+ // The render ENDS ON THE FILM. Before this the timeline wrote an mp4 into+ // mlx_outputs/storyboards/, printed one line of grey text under the button,+ // and left the user looking at the timeline wondering where the film went.+ // The Editor's document is not necessarily the storyboard's open board any+ // more, so the board is opened before the film screen is asked for it.+ const focus = (r.path || '').split('/').pop();+ if (typeof workflowSwitch === 'function') workflowSwitch('storyboard');+ if (SBE.id !== SB.id && typeof sbOpen === 'function') await sbOpen(SBE.id);+ sbFilmOpen({ focus: focus });+}++// ---------------------------------------------------------------------------+// EXPORT FOR AN NLE — the film as a project the next room can open+// ---------------------------------------------------------------------------+async function sbeExportNle() {+ if (!SBE.open || !SBE.id) return;+ // Same rule as the render: the project is written from the saved file.+ if (SBE.dirty && !(await sbeSave(true))) {+ phosToast('The timeline could not be saved, and the project is written ' ++ 'from the saved file — fix the save first.',+ { kind: 'danger', duration: 8000 });+ return;+ }+ const btn = sbeEl('sbeNleBtn');+ const prev = btn.textContent;+ btn.disabled = true;+ btn.textContent = 'Writing the project…';+ const fd = new URLSearchParams();+ fd.set('id', SBE.id);+ let r;+ try { r = await (await fetch('/storyboard/edit/export-nle', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false, error: String(e) }; }+ btn.disabled = false;+ btn.textContent = prev;+ if (!r || !r.ok) {+ phosToast((r && r.error) || 'The project folder could not be written.',+ { kind: 'danger', duration: 8000 });+ return;+ }+ const folder = (r.dir || '').split('/').pop();+ // WHAT CAME OUT AND WHAT DID NOT, in the note rather than in a support+ // thread later: the audio is stems, and a slug is a gap the NLE draws black.+ sbeEl('sbeRenderNote').textContent =+ folder + ' · ' + r.clips + ' clips · open the .xml in Premiere or Resolve, ' ++ 'run the _ae.jsx from After Effects. Sound comes out as STEMS — clip audio ' ++ 'and the soundtrack on separate tracks, not the ducked mix.' ++ ((r.missing || []).length ? ' ' + r.missing.length + ' file(s) were gone and left out.' : '');+ phosToast('Project folder ready · ' + r.clips + ' clips, ' ++ (r.linked || 0) + ' hardlinked' ++ ((r.copied || 0) ? ', ' + r.copied + ' copied' : ''),+ { kind: 'success', duration: 8000 });+ // The folder, revealed. A path in a toast is a path somebody has to+ // retype; `open` on the server is the one honest "here it is".+ const rf = new URLSearchParams();+ rf.set('id', SBE.id);+ rf.set('what', 'project');+ try { await fetch('/storyboard/edit/reveal', { method: 'POST', body: rf }); }+ catch (e) {}+}++// ---------------------------------------------------------------------------+// TICK, KEYS, WIRING+// ---------------------------------------------------------------------------+// How long an unwritten change may sit before the editor stops calling it+// "unsaved changes" and starts calling it what it is. Three ticks: long enough+// that a slow save is not slandered, short enough that nobody gets twenty+// minutes into a cut that is not being stored.+const SBE_SAVE_GRACE_MS = 12000;++async function sbeTick() {+ if (!SBE.open || document.hidden) return;+ // THE WATCHDOG, AND IT RUNS BEFORE ANYTHING ELSE IN THE TICK. Every earlier+ // path out of this function was also a path past the one check that notices+ // work is not reaching the disk.+ //+ // Two jobs. First, nothing unsaved is ever left with no save on its way:+ // dirty, not saving, no timer pending is a dropped save, and re-queueing is+ // free. Second, if the oldest unwritten change is older than the grace, the+ // alarm goes up — whatever the reason, whoever swallowed it.+ // UNSAVED IS A LEGITIMATE STATE NOW — it means the user has not pressed+ // Save, which is his call. What is NOT legitimate is unsaved AND unbacked:+ // that is work living in one browser tab and nowhere else. So the watchdog+ // guards the BACKUP, not the save.+ sbePaintProtected();+ if (SBE.dirty && !SBE.conflict && SBE.id) {+ if (!SBE.backingUp && !SBE.saveTimer) sbeQueueSave();+ if (SBE.dirtyAt && Date.now() - SBE.dirtyAt > SBE_SAVE_GRACE_MS+ && SBE.backedUpAt < SBE.dirtyAt) {+ sbeSaveAlarm('these changes have not been backed up for ' ++ Math.round((Date.now() - SBE.dirtyAt) / 1000) ++ ' seconds — press Save to store them');+ }+ }+ const job = SBE.prepare || {};+ if (job.state === 'running') {+ try {+ const r = await (await fetch('/storyboard/edit/status?id=' ++ encodeURIComponent(SBE.id))).json();+ const was = job.state;+ SBE.prepare = r.prepare || {};+ sbePaintChrome();+ if (was === 'running' && SBE.prepare.state !== 'running') {+ SBE.peaksFor = '';+ await sbeLoad(true);+ }+ } catch (e) {}+ return;+ }+ // A shot generated into a hole is rendering somewhere in the panel's one+ // queue. Poll for it — but never while the user has unsaved work in flight,+ // because a reload would be a reload over their arrangement.+ if (SBE.awaitingClip && !SBE.dirty && !SBE.drag && !SBE.saving) {+ const before = (SBE.unplaced || []).length;+ await sbeLoad(true);+ if ((SBE.unplaced || []).length > before) {+ SBE.awaitingClip = 0;+ phosToast('The new shot has landed — place it on the timeline.', { kind: 'success' });+ } else if (Date.now() - SBE.awaitingClip > 45 * 60 * 1000) {+ SBE.awaitingClip = 0;+ }+ }+}++document.addEventListener('keydown', (ev) => {+ if (!SBE.open || document.body.dataset.workflow !== 'editor') return;+ const t = ev.target;+ if (t && /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName || '')) return;+ if (document.querySelector('.modal-bg.show')) return;+ const step = 1 / sbeFps();+ if (ev.key === ' ') { ev.preventDefault(); sbeTogglePlay(); return; }+ if (ev.key === 'ArrowLeft') { ev.preventDefault(); sbeStop(); sbeSeek(SBE.playhead - (ev.shiftKey ? step * 10 : step)); return; }+ if (ev.key === 'ArrowRight') { ev.preventDefault(); sbeStop(); sbeSeek(SBE.playhead + (ev.shiftKey ? step * 10 : step)); return; }+ if (ev.key === 'Delete' || ev.key === 'Backspace') { ev.preventDefault(); sbeRippleSelected(); return; }+ if (ev.key === 's' || ev.key === 'S') { ev.preventDefault(); sbeSplitHere(); return; }+ if ((ev.metaKey || ev.ctrlKey) && (ev.key === 'z' || ev.key === 'Z')) {+ ev.preventDefault();+ ev.shiftKey ? sbeRedo() : sbeUndo();+ return;+ }+ if (ev.key === 'm' || ev.key === 'M') {+ ev.preventDefault();+ SBE.muted ? sbeUnmuteFromRefusal() : sbeSetMute(true);+ return;+ }+ if (ev.key === 'Escape') {+ ev.preventDefault();+ // The panel first: Escape means "close the thing on top", and closing the+ // whole document out from under an open picker is a surprise. A menu is+ // the same argument one layer higher.+ if (sbePopAnyOpen()) { sbePopCloseAll(''); return; }+ const vers = document.getElementById('sbeVersions');+ if (vers && !vers.hidden) { sbeVersionsClose(); return; }+ sbeClose();+ }+ // RENDER HAS A KEY NOW that it is the only filled control on the screen.+ if ((ev.key === 'r' || ev.key === 'R') && (ev.metaKey || ev.ctrlKey)) {+ ev.preventDefault();+ sbeRenderFilm();+ }+});++// A menu closes when you click away from it. Capture phase, like the picker+// below, so the control underneath still gets its click.+document.addEventListener('click', sbePopGlobal, true);++// Click-away, the same shape the engine menu uses. Capture phase, so a click+// on a control underneath still lands after the panel is gone.+document.addEventListener('click', (ev) => {+ const vers = document.getElementById('sbeVersions');+ if (!vers || vers.hidden) return;+ if (ev.target.closest('#sbeVersions') || ev.target.closest('#sbeVersBtn')+ || ev.target.closest('#sbeKeepBtn')) return;+ sbeVersionsClose();+}, true);++(function sbeWire() {+ const track = document.getElementById('sbeTrack');+ if (!track) return;+ sbeSetMute(SBE.muted); // the button must agree with the stored state on load+ track.addEventListener('pointerdown', sbeOnTrackDown);+ track.addEventListener('pointermove', sbeOnTrackMove);+ track.addEventListener('pointerup', sbeOnTrackUp);+ track.addEventListener('pointercancel', sbeOnTrackUp);+ // Pan and zoom over the whole scroller — ruler, waveform and track at once,+ // because they are one view of one film and panning one of them alone would+ // be a bug. `passive: false` or preventDefault is a no-op and the column+ // scrolls out from under the gesture.+ const box = document.getElementById('sbeScroll');+ if (box) box.addEventListener('wheel', sbeOnTlWheel, { passive: false });+ // A RESIZE OBSERVER ON THE COLUMN, not just window.onresize. Measured: a+ // viewport change from 1900x1000 to 1440x900 left both monitors 437px tall+ // in a 501px column — 16:9 boxes squashed to 1.15:1 by `max-width` because+ // the window event never reached sbePaint. The column is the box the budget+ // is actually about, and it changes for reasons the window never hears:+ // the bottom pane opening, a scrollbar arriving, the pool being folded.+ // Coalesced on a TIMER, not on requestAnimationFrame. rAF does not run in+ // a tab the compositor has decided is not visible — measured in a headless+ // preview pane, where the callback simply never fired and the monitors kept+ // the previous window's height — and a resize is exactly the moment a+ // background tab is about to become the foreground one. sbePaint cannot+ // change this box's size, so this cannot feed itself.+ const colBox = document.getElementById('edStage');+ if (colBox && 'ResizeObserver' in window) {+ let pending = 0;+ new ResizeObserver(() => {+ if (pending) return;+ pending = setTimeout(() => { pending = 0; if (SBE.open) sbePaint(); }, 0);+ }).observe(colBox);+ }+ // THE MUSIC LANE. Listeners on the LANE and not on the block: the block is+ // repainted (and its class list rewritten) on every frame of the drag, and a+ // pointer captured by an element the paint replaces is a drag that dies+ // halfway. The lane outlives the gesture.+ const lane = document.getElementById('sbeMusicLane');+ if (lane) {+ lane.addEventListener('pointerdown', (ev) => {+ if (!ev.target.closest('#sbeMusicClip')) return;+ sbeStop();+ sbeOnMusicDown(ev);+ });+ lane.addEventListener('pointermove', sbeOnMusicMove);+ lane.addEventListener('pointerup', sbeOnMusicUp);+ lane.addEventListener('pointercancel', sbeOnMusicUp);+ lane.addEventListener('dblclick', sbeOnMusicDbl);+ // The ghost belongs to the pointer, so it goes when the pointer does.+ lane.addEventListener('pointerleave', () => {+ if (SBE.kfGhost && SBE.kfGhost.id === '@music') {+ SBE.kfGhost = null;+ sbePaint();+ }+ });+ }+ const alane = document.getElementById('sbeAudioLane');+ if (alane) {+ alane.addEventListener('pointerdown', (ev) => { sbeStop(); sbeOnAudioDown(ev); });+ alane.addEventListener('dblclick', sbeOnAudioDbl);+ alane.addEventListener('pointermove', sbeOnAudioMove);+ alane.addEventListener('pointerup', sbeOnAudioUp);+ alane.addEventListener('pointercancel', sbeOnAudioUp);+ // The two halves of "hover teaches": the ghost follows the pointer while+ // it is near a level, and it goes when the pointer does.+ alane.addEventListener('pointerleave', sbeAudioGhostClear);+ alane.addEventListener('contextmenu', sbeOnAudioMenu);+ }+ const scrubbers = ['sbeRuler', 'sbeWave', 'sbeWaveNone'];+ for (const id of scrubbers) {+ const el = document.getElementById(id);+ if (!el) continue;+ el.addEventListener('pointerdown', (ev) => {+ sbeStop();+ el.setPointerCapture && el.setPointerCapture(ev.pointerId);+ el.dataset.scrub = '1';+ sbeSeek(sbeTimeFromEvent(ev, el));+ });+ el.addEventListener('pointermove', (ev) => {+ if (el.dataset.scrub !== '1') return;+ SBE.playhead = Math.max(0, Math.min(sbeFilmDuration(SBE.clips),+ sbeTimeFromEvent(ev, el)));+ sbePaintHead();+ });+ const end = (ev) => {+ if (el.dataset.scrub !== '1') return;+ el.dataset.scrub = '';+ sbeSeek(sbeTimeFromEvent(ev, el));+ };+ el.addEventListener('pointerup', end);+ el.addEventListener('pointercancel', end);+ }+ const tabs = document.getElementById('edPoolTabs');+ if (tabs) {+ tabs.addEventListener('click', (ev) => {+ const b = ev.target.closest('.pill-btn');+ if (b) edPoolSrc(b.dataset.src);+ });+ }+ const pass = document.getElementById('sbeGenPass');+ if (pass) {+ pass.addEventListener('click', (ev) => {+ const b = ev.target.closest('.pill-btn');+ if (!b) return;+ pass.querySelectorAll('.pill-btn').forEach(x => x.classList.toggle('active', x === b));+ });+ }+})();+document.getElementById('sbStyle') && document.getElementById('sbStyle').addEventListener('input', () => {});@@ -54589,6 +69483,7 @@ function workflowSwitch(name) {const train = document.getElementById('trainSection');const audioTab = document.getElementById('audioSectionTab');const sbTab = document.getElementById('sbSectionTab');+ const edTab = document.getElementById('edSectionTab');const characters = document.getElementById('charactersSection'); // dead HTML; hide defensively// Set body data attribute so CSS can switch the layout per workflow.document.body.setAttribute('data-workflow', name);@@ -54597,6 +69492,7 @@ function workflowSwitch(name) {if (train) train.classList.remove('show');if (audioTab) audioTab.style.display = 'none';if (sbTab) sbTab.style.display = 'none';+ if (edTab) edTab.style.display = 'none';if (characters) characters.classList.remove('show');// The board poller is the Storyboard tab's only timer and it stops on exit —// no new polling loop runs while the tab is closed.@@ -54604,6 +69500,12 @@ function workflowSwitch(name) {if (typeof sbTeardown === 'function') sbTeardown();document.body.classList.remove('sb-full');}+ // LEAVING THE EDITOR IS NOT CLOSING THE DOCUMENT. The storyboard's own+ // teardown used to take the editor down with it, so glancing at the gallery+ // threw away the undo stack and the open timeline; you came back to the shot+ // list. Suspend stops the clock and the picture and keeps everything else —+ // the document closes when the user closes it, and only then.+ if (name !== 'editor' && typeof sbeSuspend === 'function') sbeSuspend();if (name === 'storyboard') {// Storyboard is a layer ABOVE the video modes, not one of them: it submits// a brief to a planner and its output is a plan, not a clip. Hence a@@ -54633,6 +69535,12 @@ function workflowSwitch(name) {if (manual) manual.style.display = 'none';if (audioTab) audioTab.style.display = 'block';if (typeof audioStudioInit === 'function') audioStudioInit();+ } else if (name === 'editor') {+ // The Editor. Engine-agnostic and board-agnostic: it opens the document+ // it had open last, and an empty timeline is a legitimate place to stand.+ if (manual) manual.style.display = 'none';+ if (edTab) edTab.style.display = 'flex';+ if (typeof edInit === 'function') edInit();} else {// Manual — show the video form, restore the previous video mode.if (manual) manual.style.display = '';@@ -54664,8 +69572,9 @@ try {// 2026-05-18 — 'audio' is the Audio → Video workflow tab.// 2026-08-11 — 'storyboard' is the plan-a-film workflow tab. It MUST be in// this list or the tab simply never restores across a reload.+ // 2026-08-17 — 'editor' is the timeline's own tab. Same rule, same list.if (saved === 'studio' || saved === 'train' || saved === 'characters' ||- saved === 'audio' || saved === 'storyboard') {+ saved === 'audio' || saved === 'storyboard' || saved === 'editor') {workflowSwitch(saved);}// Clear any stale agent-fullscreen flag from the removed chat surface.diff --git a/mlx_warm_helper.py b/mlx_warm_helper.pyindex b745ddc..a257546 100644--- a/mlx_warm_helper.py+++ b/mlx_warm_helper.py@@ -741,9 +741,21 @@ def _install_lora_fusion_patches() -> None:for path, strength in pending if float(strength) != 0.0]self._phosphene_lora_preflight = []if active:- from lora_compat import validate_lora_stack+ from lora_compat import (+ validate_adapter_effects,+ validate_lora_stack,+ )reports = validate_lora_stack(active, transformer_path)+ # Names are not effect (#62). A character adapter can match+ # every key, attach on every module, report a green tally —+ # and still be numerically negligible, which two users spent+ # days chasing because nothing in the log ever said how much+ # weight the file actually carries. Now every render says it.+ validate_adapter_effects(+ active,+ reporter=lambda line: emit({"event": "log", "line": line}),+ )self._phosphene_lora_preflight = list(zip(reports, (strength for _, strength in active)))@@ -980,12 +992,19 @@ def _preflight_distilled_loras(loras: list[tuple[str, float]], model_dir: str | Path) -> None:"""Fail closed for IC-LoRA pipelines that own their fusion internally."""- from lora_compat import resolve_distilled_transformer, validate_lora_stack+ from lora_compat import (+ resolve_distilled_transformer,+ validate_adapter_effects,+ validate_lora_stack,+ )active = [(path, float(strength)) for path, strength in lorasif float(strength) != 0.0]if not active:return+ validate_adapter_effects(+ active, reporter=lambda line: emit({"event": "log", "line": line})+ )transformer = resolve_distilled_transformer(model_dir)if transformer is None:raise RuntimeError(diff --git a/scripts/measure_editor_layout.py b/scripts/measure_editor_layout.pynew file mode 100644index 0000000..1f22782--- /dev/null+++ b/scripts/measure_editor_layout.py@@ -0,0 +1,1057 @@+#!/usr/bin/env python3.11+"""A REAL browser geometry gate for the Editor.++WHY THIS EXISTS. Every layout defect the Editor has shipped was invisible to+the suite because the suite reads MARKUP. `.sbe-head .primary { width: auto }`+is a string in a test either way; what broke the owner's screen was that the+global `button { width: 100% }` rule resolved Save's flex basis to 1554px the+moment `sbePaintChrome` swapped it to `.primary`, the header wrapped to two+rows, and the column overflowed. No amount of grepping the stylesheet can see+that. Only a browser that has actually laid the page out can.++So this boots the panel out of THIS working tree against a throwaway state+directory, drives a headless Chrome over CDP with a websocket client written+here (the panel's python has no selenium, no playwright, no `websockets`, and+adding one would put a pip dependency into every Pinokio install), opens the+Editor on a seeded board, and reads five numbers off the live DOM at four+widths:++ header_rows the editor header must be ONE row+ save_width Save must be a button, not a 1554px bar+ column_overflow #edStage must not scroll sideways+ timeline_clip the timeline floor must not clip the music lane+ stage_layers_both_visible the <video> and the still must never both be on++Everything is measured with getBoundingClientRect / scrollWidth / clientHeight+and computed opacity. Nothing is read out of CSS text.++ ./ltx-2-mlx/env/bin/python3.11 scripts/measure_editor_layout.py++Exit codes: 0 all measurements pass, 1 a measurement FAILED, 3 no browser on+this machine (the unittest skips on this), 4 the harness itself could not get+far enough to measure — which is never reported as a pass.+"""++from __future__ import annotations++import argparse+import base64+import json+import os+import shutil+import signal+import socket+import struct+import subprocess+import sys+import tempfile+import time+import urllib.error+import urllib.request+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent++# The owner's live panel. Nothing here may ever bind it.+FORBIDDEN_PORTS = {8199}++WIDTHS = (1920, 1520, 1280, 1100)+VIEWPORT_H = 1000++# The board the Editor is opened on. A board with no rendered shot is a+# legitimate document — the panel's own comment says "an empty timeline is a+# legitimate place to stand" — and it is the only seed that does not make the+# auto-editor decode video, which would put ffmpeg in the middle of a layout+# test.+BOARD_ID = "sb_geom_gate"++SAVE_MIN, SAVE_MAX = 40.0, 200.0+OVERFLOW_TOL = 1.0++# ---------------------------------------------------------------------------+# THE TIMELINE'S DRAGGABLE AFFORDANCES — one table, not three special cases+# ---------------------------------------------------------------------------+# WHY THIS IS A TABLE. Two defects of the SAME SHAPE reached the owner one+# after the other: a 12x12 fade handle sitting inside the trim grip's hit area+# ("not sure that grabbing the top corner is working — I'm not being able to do+# it"), and a level line drawn on the strip's own top edge with most of its+# 14px target clipped away outside the box ("you are able to drag the sound+# thingy, but it's not super user-friendly"). Both are the same two questions:+# is this thing BIG ENOUGH to hit, and does anything ELSE claim its pixels.+#+# So they are asked here of every draggable thing in the timeline, in a table a+# fifth affordance can join by adding a row rather than by writing a fourth+# special case. Every rectangle is the one a POINTER sees, not the one that is+# painted: a grip is grown by its `--sbe-grip-skirt`, and the level line — an+# SVG path whose own box has no height at all — is grown by half its stroke.+#+# The floor and the ceiling are both measured because the lanes are USER-SIZED.+# A control sized in absolute pixels inside a lane whose height is dragged will+# keep breaking, which is exactly how the fade handle came to be a fifth of the+# corner it was supposed to own: nobody moved it, the lane moved under it.+HANDLE_ENDS = ("floor", "ceiling")++# The viewport each end is measured in. The floor is only REACHABLE in a short+# window: `sbeFitMonitors` hands the timeline whatever the monitors decline, so+# in a tall one the picture track is flexed well past its own minimum and the+# shortest block never appears. Measured: at 560px the lanes sit exactly on+# their bases (a 52px picture block, a 37px sound strip); at 1000px the same+# call leaves the track at 84px and the gate would be testing nothing.+HANDLE_VIEWPORT = {"floor": (1280, 560), "ceiling": (1280, 1200)}+HANDLE_TL = {"floor": "SBE_TL_MIN_H", "ceiling": "SBE_TL_MAX_H"}++# What must be on screen at all. A gate that measured an empty timeline would+# report nothing and pass.+HANDLE_ROWS = {+ "clip": ("grip_l", "grip_r", "fade_in", "fade_out"),+ "aclip": ("grip_l", "grip_r", "fade_in", "fade_out", "level", "kf"),+ # THE MUSIC BED, which grew the same three affordances the strips have.+ # It is a ROW here rather than a fourth special case because that is what+ # the table is for: "fade the music out under the last shot" is the most+ # ordinary request in editing, and the bed had no fade, no level and no+ # points at all — so the handles had to be built, and a handle that is+ # built is a handle that can be too small or can sit on top of another one.+ "mclip": ("grip_l", "grip_r", "fade_in", "fade_out", "level", "kf"),+}++# The smallest each target may be, in the axis that matters for it. 20x20 is+# the floor for anything you are asked to grab with a mouse; the level line is+# a BAND, so its short axis is the stroke and its long axis is how much of the+# line is left after the corner handles have taken their ends.+MIN_HIT = {+ "grip_l": (12.0, 20.0),+ "grip_r": (12.0, 20.0),+ "fade_in": (20.0, 20.0),+ "fade_out": (20.0, 20.0),+ "level": (20.0, 12.0),+ "kf": (6.0, 6.0),+}++# Pairs that MAY share pixels, and the reason. Everything else in the same+# block must be disjoint. A keyframe dot lives ON the line by construction —+# it is the more specific target on it, not a rival to it, and `sbeOnAudioDown`+# tests it first — so demanding they not touch would be demanding the dot leave+# the line it belongs to.+ALLOWED_OVERLAP = {("kf", "level")}++CHROME_CANDIDATES = (+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ "/Applications/Chromium.app/Contents/MacOS/Chromium",+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",+)+++class HarnessError(RuntimeError):+ """The measurement could not be taken. NOT a failed measurement."""+++class NoBrowser(HarnessError):+ """No Chrome/Chromium/Edge on this machine."""+++# ---------------------------------------------------------------------------+# A websocket client, because the alternative is a pip install+# ---------------------------------------------------------------------------+# RFC6455, client side, only as much of it as CDP uses: one text stream, no+# extensions, no compression. Client frames MUST be masked or Chrome closes the+# socket; server frames never are. Continuation and 64-bit lengths are handled+# because a `Runtime.evaluate` result carrying a DOM measurement is small but a+# `Page` event is not, and a frame we cannot parse desynchronises the stream+# for every message after it.+class WebSocket:+ def __init__(self, url: str, timeout: float = 30.0):+ if not url.startswith("ws://"):+ raise HarnessError(f"only ws:// is supported, got {url!r}")+ rest = url[len("ws://"):]+ netloc, _, path = rest.partition("/")+ path = "/" + path+ host, _, port_s = netloc.partition(":")+ port = int(port_s or 80)+ self.sock = socket.create_connection((host, port), timeout=timeout)+ self.sock.settimeout(timeout)+ self._buf = b""+ self._handshake(host, port, path)++ def _handshake(self, host: str, port: int, path: str) -> None:+ key = base64.b64encode(os.urandom(16)).decode("ascii")+ req = (+ f"GET {path} HTTP/1.1\r\n"+ f"Host: {host}:{port}\r\n"+ "Upgrade: websocket\r\n"+ "Connection: Upgrade\r\n"+ f"Sec-WebSocket-Key: {key}\r\n"+ "Sec-WebSocket-Version: 13\r\n"+ "\r\n"+ )+ self.sock.sendall(req.encode("ascii"))+ while b"\r\n\r\n" not in self._buf:+ chunk = self.sock.recv(4096)+ if not chunk:+ raise HarnessError("devtools closed the socket during handshake")+ self._buf += chunk+ head, _, self._buf = self._buf.partition(b"\r\n\r\n")+ status = head.split(b"\r\n", 1)[0].decode("latin-1")+ if "101" not in status:+ raise HarnessError(f"websocket upgrade refused: {status}")++ # -- framing ----------------------------------------------------------+ def _read_exact(self, n: int) -> bytes:+ while len(self._buf) < n:+ chunk = self.sock.recv(65536)+ if not chunk:+ raise HarnessError("devtools closed the socket")+ self._buf += chunk+ out, self._buf = self._buf[:n], self._buf[n:]+ return out++ def _send_frame(self, opcode: int, payload: bytes) -> None:+ head = bytearray([0x80 | opcode])+ n = len(payload)+ if n < 126:+ head.append(0x80 | n)+ elif n < (1 << 16):+ head.append(0x80 | 126)+ head += struct.pack("!H", n)+ else:+ head.append(0x80 | 127)+ head += struct.pack("!Q", n)+ mask = os.urandom(4)+ head += mask+ masked = bytes(b ^ mask[i & 3] for i, b in enumerate(payload))+ self.sock.sendall(bytes(head) + masked)++ def _recv_frame(self) -> tuple[bool, int, bytes]:+ b0, b1 = self._read_exact(2)+ fin = bool(b0 & 0x80)+ opcode = b0 & 0x0F+ masked = bool(b1 & 0x80)+ n = b1 & 0x7F+ if n == 126:+ n = struct.unpack("!H", self._read_exact(2))[0]+ elif n == 127:+ n = struct.unpack("!Q", self._read_exact(8))[0]+ mask = self._read_exact(4) if masked else b""+ data = self._read_exact(n) if n else b""+ if masked:+ data = bytes(b ^ mask[i & 3] for i, b in enumerate(data))+ return fin, opcode, data++ def send_text(self, text: str) -> None:+ self._send_frame(0x1, text.encode("utf-8"))++ def recv_text(self) -> str:+ parts: list[bytes] = []+ want_text = False+ while True:+ fin, opcode, data = self._recv_frame()+ if opcode == 0x8: # close+ raise HarnessError("devtools sent a close frame")+ if opcode == 0x9: # ping -> pong+ self._send_frame(0xA, data)+ continue+ if opcode == 0xA: # pong+ continue+ if opcode == 0x1:+ parts = [data]+ want_text = True+ elif opcode == 0x2: # binary: not ours+ parts = []+ want_text = False+ elif opcode == 0x0: # continuation+ parts.append(data)+ if fin:+ if want_text:+ return b"".join(parts).decode("utf-8", "replace")+ parts = []++ def close(self) -> None:+ try:+ self._send_frame(0x8, b"")+ except OSError:+ pass+ try:+ self.sock.close()+ except OSError:+ pass+++# ---------------------------------------------------------------------------+# CDP+# ---------------------------------------------------------------------------+class CDP:+ def __init__(self, ws: WebSocket):+ self.ws = ws+ self._id = 0++ def call(self, method: str, params: dict | None = None,+ timeout: float = 40.0) -> dict:+ self._id += 1+ mine = self._id+ self.ws.send_text(json.dumps({"id": mine, "method": method,+ "params": params or {}}))+ deadline = time.monotonic() + timeout+ while True:+ msg = json.loads(self.ws.recv_text())+ if msg.get("id") == mine:+ if "error" in msg:+ raise HarnessError(f"{method}: {msg['error']}")+ return msg.get("result") or {}+ if time.monotonic() > deadline:+ raise HarnessError(f"{method}: no reply in {timeout}s")++ def evaluate(self, expr: str, *, await_promise: bool = False,+ timeout: float = 40.0):+ r = self.call("Runtime.evaluate",+ {"expression": expr, "returnByValue": True,+ "awaitPromise": await_promise},+ timeout=timeout)+ det = r.get("exceptionDetails")+ if det:+ exc = (det.get("exception") or {})+ raise HarnessError("page threw: " ++ str(exc.get("description") or det.get("text")))+ return (r.get("result") or {}).get("value")+++# ---------------------------------------------------------------------------+# processes+# ---------------------------------------------------------------------------+def free_port() -> int:+ for _ in range(40):+ s = socket.socket()+ try:+ s.bind(("127.0.0.1", 0))+ port = s.getsockname()[1]+ finally:+ s.close()+ if port not in FORBIDDEN_PORTS:+ return port+ raise HarnessError("could not find a free port")+++def _http_json(url: str, timeout: float = 3.0):+ with urllib.request.urlopen(url, timeout=timeout) as r:+ return json.loads(r.read().decode("utf-8"))+++def _http_ok(url: str, timeout: float = 3.0) -> bool:+ try:+ with urllib.request.urlopen(url, timeout=timeout) as r:+ return 200 <= r.status < 400+ except (urllib.error.URLError, OSError, TimeoutError):+ return False+++def seed_board(state_dir: Path) -> None:+ """One board on disk, so the Editor has a document to open.++ Written as plain JSON rather than through `storyboard.save_storyboard` so+ this script stays importable-free: it must run on a python that has only+ the standard library, and the stdlib-only rule is a test.++ AND AN `edit.json`, because the handle gate needs something to measure.+ An empty timeline draws no clip block, no sound strip, no grips and no+ corner handles — a gate run against it would report nothing and pass, which+ is precisely the failure mode it exists to prevent. The clips point at+ files that do not exist ON PURPOSE: `validate_edit` only demands a file for+ a STILL, so a video clip with a missing path is a valid document, draws+ every affordance, and puts no ffmpeg anywhere near a layout test.++ Clip 1 carries `audio` (so its strip is unlinked and gets grips and corner+ handles of its own) and one gain point in the middle of it (so the level+ line's dot is on screen to be measured).+ """+ d = state_dir / "storyboards" / BOARD_ID+ d.mkdir(parents=True, exist_ok=True)+ board = {+ "schema": 1, "id": BOARD_ID, "title": "Geometry gate",+ "created_at": 1_700_000_000, "cast": [], "engine_mode": "ltx",+ "policy": {},+ "shots": [{"n": i + 1, "title": f"shot {i + 1}", "mode": "text",+ "engine": "ltx",+ "prompt": "the gate does not render anything",+ "duration_s": 5.0, "seed": 101 + i, "refs": [],+ "status": "planned"} for i in range(2)],+ }+ (d / "storyboard.json").write_text(json.dumps(board, indent=2),+ encoding="utf-8")++ def clip(i: int, film_start: float, dur: float = 5.0, **extra) -> dict:+ c = {+ "id": f"kgeom{i}", "path": str(d / f"shot{i}.mp4"), "proxy": None,+ "kind": "video", "start": 0.0, "end": dur,+ "film_start": film_start, "film_end": film_start + dur,+ "source": "auto", "locked": False,+ }+ c.update(extra)+ return c++ edit = {+ "version": 2, "board": BOARD_ID, "revision": 1,+ # A SOUNDTRACK, for the same reason the clips carry one: the bed's+ # block is hidden without a path and a duration, and a gate measuring+ # a hidden block reports nothing and passes. `afx` puts a point on the+ # level line so the dot is on screen to be measured, exactly as clip 1+ # does one field down. The file does not exist ON PURPOSE — the block,+ # the grips, the corner handles and the level line are all drawn from+ # `audio.duration`, and the waveform (which would need the file) is+ # not one of the things under test.+ "audio": {"path": str(d / "bed.wav"), "duration": 40.0, "offset": 0.0,+ "mode": "under", "afx": {"points": [[12.0, 0.55]]}},+ "overlays": [], "beats": None,+ "clips": [+ clip(0, 0.0,+ audio={"start": 0.0, "end": 5.0, "film_start": 0.0},+ afx={"points": [[2.5, 0.6]]}),+ clip(1, 5.0),+ ],+ }+ (d / "edit.json").write_text(json.dumps(edit, indent=2), encoding="utf-8")+++def start_panel(work: Path, log: Path, verbose: bool) -> tuple[subprocess.Popen, str]:+ port = free_port()+ state = work / "state"+ state.mkdir(parents=True, exist_ok=True)+ (work / "outputs").mkdir(exist_ok=True)+ (work / "uploads").mkdir(exist_ok=True)+ seed_board(state)++ env = dict(os.environ)+ env.update({+ "LTX_PORT": str(port),+ "LTX_STATE_DIR": str(state),+ "LTX_OUTPUT_DIR": str(work / "outputs"),+ "LTX_UPLOADS_DIR": str(work / "uploads"),+ # Nothing here should phone home or open a window.+ "LTX_NO_BROWSER": "1",+ "PHOSPHENE_NO_TELEMETRY": "1",+ })+ fh = log.open("wb")+ proc = subprocess.Popen(+ [sys.executable, "mlx_ltx_panel.py"],+ cwd=str(ROOT), env=env, stdout=fh, stderr=subprocess.STDOUT,+ start_new_session=True,+ )+ base = f"http://127.0.0.1:{port}"+ deadline = time.monotonic() + 90.0+ while time.monotonic() < deadline:+ if proc.poll() is not None:+ raise HarnessError(+ f"the panel exited with {proc.returncode} before answering. "+ f"log tail: {_tail(log)}")+ if _http_ok(base + "/"):+ if verbose:+ print(f"panel up on {base}", file=sys.stderr)+ return proc, base+ time.sleep(0.25)+ raise HarnessError(f"the panel never answered GET / on {base}. "+ f"log tail: {_tail(log)}")+++def _tail(p: Path, n: int = 6) -> str:+ try:+ lines = p.read_text(encoding="utf-8", errors="replace").splitlines()+ except OSError:+ return "(no log)"+ return " | ".join(lines[-n:])+++def find_browser() -> str:+ env = os.environ.get("CHROME_PATH", "").strip()+ if env and Path(env).exists():+ return env+ for c in CHROME_CANDIDATES:+ if Path(c).exists():+ return c+ for name in ("google-chrome", "chromium", "chromium-browser"):+ found = shutil.which(name)+ if found:+ return found+ raise NoBrowser(+ "no Chrome/Chromium/Edge found - set CHROME_PATH to a browser binary")+++def start_chrome(binary: str, profile: Path,+ verbose: bool) -> tuple[subprocess.Popen, str]:+ port = free_port()+ proc = subprocess.Popen(+ [binary,+ f"--remote-debugging-port={port}",+ "--remote-allow-origins=*",+ "--headless=new",+ "--no-first-run",+ "--no-default-browser-check",+ f"--user-data-dir={profile}",+ "--disable-gpu",+ "--disable-extensions",+ "--disable-background-networking",+ "--disable-dev-shm-usage",+ "--mute-audio",+ "--window-size=1920,1000",+ "about:blank"],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ start_new_session=True,+ )+ base = f"http://127.0.0.1:{port}"+ deadline = time.monotonic() + 45.0+ while time.monotonic() < deadline:+ if proc.poll() is not None:+ raise HarnessError(f"the browser exited with {proc.returncode}")+ try:+ _http_json(base + "/json/version", timeout=1.0)+ if verbose:+ print(f"devtools up on {base}", file=sys.stderr)+ return proc, base+ except Exception: # noqa: BLE001+ time.sleep(0.2)+ raise HarnessError("the browser never opened its devtools port")+++def page_socket(devtools: str) -> str:+ deadline = time.monotonic() + 20.0+ while time.monotonic() < deadline:+ try:+ for t in _http_json(devtools + "/json/list", timeout=2.0):+ if t.get("type") == "page" and t.get("webSocketDebuggerUrl"):+ return t["webSocketDebuggerUrl"]+ except Exception: # noqa: BLE001+ pass+ time.sleep(0.2)+ raise HarnessError("devtools listed no page target")+++def kill(proc: subprocess.Popen | None) -> None:+ if proc is None or proc.poll() is not None:+ return+ for sig in (signal.SIGTERM, signal.SIGKILL):+ try:+ os.killpg(os.getpgid(proc.pid), sig)+ except (ProcessLookupError, PermissionError, OSError):+ try:+ proc.kill()+ except OSError:+ pass+ try:+ proc.wait(timeout=6)+ return+ except subprocess.TimeoutExpired:+ continue+++# ---------------------------------------------------------------------------+# the page side+# ---------------------------------------------------------------------------+# Opening the Editor is the app's own door: `edOpenBoard` is what the picker,+# the board row and the rail's step 3 all call, and it does the tab switch and+# the document load together. Poking `#sbTimeline.hidden` directly would give a+# header laid out in a column that never ran `sbeFitMonitors`, which is exactly+# the measurement that would be worthless.+JS_OPEN = """+(() => {+ try { localStorage.setItem('phos_ed_doc', %(board)s); } catch (e) {}+ if (typeof workflowSwitch !== 'function') return 'workflowSwitch missing';+ if (typeof edOpenBoard !== 'function') return 'edOpenBoard missing';+ workflowSwitch('editor');+ edOpenBoard(%(board)s);+ return 'ok';+})()+"""++JS_READY = """+(() => {+ const plan = document.getElementById('sbTimeline');+ const scroll = document.getElementById('sbeScroll');+ const head = document.querySelector('#sbTimeline > header.sbe-head')+ || document.querySelector('#sbTimeline .sbe-head');+ if (!plan) return 'no #sbTimeline';+ if (plan.hidden) return 'the editor document is hidden';+ if (!window.SBE || !SBE.open) return 'SBE.open is false';+ if (!SBE.edit) return 'no edit loaded yet';+ if (!head) return 'no editor header';+ if (!scroll || scroll.clientHeight <= 0) return 'the timeline has no height';+ if (head.getBoundingClientRect().height <= 0) return 'the header has no height';+ return 'ok';+})()+"""++# ONE evaluate per width, and every number in it comes off the laid-out DOM.+#+# The Save button is measured TWICE on purpose. `sbePaintChrome` swaps it+# between `.ghost-btn` and `.primary` on SBE.dirty, and the 1554px defect only+# ever existed in the `.primary` half - "sometimes" was exactly "while+# unsaved". A gate that measured the idle button would have passed the whole+# time the owner's header was wrapped, so the asserted number is the dirty one.+JS_MEASURE = r"""+(async () => {+ const raf = () => new Promise(r => requestAnimationFrame(() => r()));+ const settle = async () => { await raf(); await raf(); await raf(); };++ const el = id => document.getElementById(id);+ const num = v => (typeof v === 'number' && isFinite(v)) ? Math.round(v * 100) / 100 : null;+ const out = { errors: [], missing: [] };+ const need = (id) => { const e = el(id); if (!e) out.missing.push('#' + id); return e; };++ await settle();++ const head = document.querySelector('#sbTimeline > header.sbe-head')+ || document.querySelector('#sbTimeline .sbe-head');+ if (!head) out.missing.push('.sbe-head');+ const save = need('sbeSaveBtn');+ const col = need('edStage');+ const scroll = need('sbeScroll');+ const plan = need('sbTimeline');+ const video = need('sbeVideo');+ const still = need('sbeStill');++ out.viewport_width = window.innerWidth;+ out.viewport_height = window.innerHeight;+ out.editor_open = !!(window.SBE && SBE.open) && !!plan && !plan.hidden;+ out.stacked = !!(window.matchMedia && window.matchMedia('(max-width: 900px)').matches);++ // The button as it sits when there is nothing to save.+ out.save_width_idle = save ? num(save.getBoundingClientRect().width) : null;+ out.save_class_idle = save ? save.className : null;++ // ...and as it sits the moment there is. This is the state the header+ // wrapped in, so this is the state the gate measures.+ try {+ if (window.SBE) { SBE.dirty = true; SBE.saving = false; }+ if (typeof sbePaint === 'function') sbePaint();+ else if (typeof sbePaintChrome === 'function') sbePaintChrome();+ } catch (e) { out.errors.push('paint threw: ' + e); }+ await settle();++ out.save_class = save ? save.className : null;+ out.save_primary = !!(save && save.classList.contains('primary'));+ out.save_width = save ? num(save.getBoundingClientRect().width) : null;++ // HEADER ROWS - the number of distinct rendered rows among the header's own+ // visible children.+ //+ // NOT a set of rounded `top` values, and the reason is in the stylesheet:+ // `.carousel-head` is align-items:center, so a 6px state dot, a 20px title+ // and a 28px button sitting in the SAME row have three different tops+ // (measured: 123 / 116 / 112 at 1100px). Counting tops would report that row+ // as three. What is invariant across a centered row is the CENTRE, so rows+ // are clustered on it - and the two cases are an order of magnitude apart:+ // same row is under a pixel, a wrapped row is a whole control height (28px+)+ // away. Every child's top, height and centre is reported below so the number+ // can be checked by hand.+ const centres = [];+ const kids = [];+ if (head) {+ for (const kid of head.children) {+ if (kid.offsetParent === null) continue;+ const r = kid.getBoundingClientRect();+ if (r.width <= 0 || r.height <= 0) continue;+ const c = Math.round(r.top + r.height / 2);+ kids.push({ id: kid.id || kid.className || kid.tagName,+ top: Math.round(r.top), h: num(r.height), centre: c,+ w: num(r.width) });+ if (!centres.some(x => Math.abs(x - c) <= 8)) centres.push(c);+ }+ }+ centres.sort((a, b) => a - b);+ out.header_rows = head ? centres.length : null;+ out.header_row_centres = centres;+ out.header_children = kids;+ out.header_height = head ? num(head.getBoundingClientRect().height) : null;++ // THE COLUMN. A header that wrapped, or a control that stretched, shows up+ // here as sideways scroll on the editor's own scroller.+ out.column_scroll_width = col ? col.scrollWidth : null;+ out.column_client_width = col ? col.clientWidth : null;+ out.column_overflow = col ? (col.scrollWidth - col.clientWidth) : null;++ // THE TIMELINE FLOOR. `.sbe-tl` is overflow-y:hidden, so a floor too short+ // for its lanes does not scroll - it CLIPS, and what falls off the bottom is+ // the soundtrack. scrollHeight still reports the content, which is why this+ // is measurable at all.+ out.timeline_scroll_height = scroll ? scroll.scrollHeight : null;+ out.timeline_client_height = scroll ? scroll.clientHeight : null;+ out.timeline_clip = scroll ? (scroll.scrollHeight - scroll.clientHeight) : null;+ out.timeline_floor_h = plan+ ? (getComputedStyle(plan).getPropertyValue('--sbe-tl-h') || '').trim() : null;+ const music = el('sbeMusicLane');+ if (music && scroll) {+ const m = music.getBoundingClientRect(), s = scroll.getBoundingClientRect();+ out.music_lane_bottom_overhang = num(m.bottom - s.bottom);+ }++ // THE TWO STAGE LAYERS. Neither is ever display:none - a hidden <video> is+ // never loaded by WebKit - so `is-on` and opacity are the switch, and the+ // only thing that can be wrong is both of them being on at once.+ const on = (e) => {+ if (!e) return false;+ const cs = getComputedStyle(e);+ if (cs.display === 'none' || cs.visibility === 'hidden') return false;+ const r = e.getBoundingClientRect();+ if (r.width <= 0 || r.height <= 0) return false;+ return parseFloat(cs.opacity || '1') > 0.01;+ };+ out.video_opacity = video ? num(parseFloat(getComputedStyle(video).opacity)) : null;+ out.still_opacity = still ? num(parseFloat(getComputedStyle(still).opacity)) : null;+ out.video_visible = on(video);+ out.still_visible = on(still);+ out.stage_layers_both_visible = on(video) && on(still);++ // Put it back, so the next width does not start from a forced state.+ try {+ if (window.SBE) SBE.dirty = false;+ if (typeof sbePaint === 'function') sbePaint();+ } catch (e) {}++ return out;+})()+"""+++# ONE END OF THE LANE RANGE, MEASURED. `sbeTlSet` is the app's own writer of+# the timeline's height — the same one the drag handle and the keyboard call —+# so this drives the lanes the way a user does rather than poking a variable.+JS_HANDLES = r"""+(async () => {+ const raf = () => new Promise(r => requestAnimationFrame(() => r()));+ const settle = async () => { await raf(); await raf(); await raf(); };+ const num = v => Math.round(v * 100) / 100;+ const out = { blocks: {}, errors: [] };++ if (typeof sbeTlSet !== 'function') { out.errors.push('sbeTlSet missing'); return out; }+ sbeTlSet(%(tl)s);+ if (typeof sbePaint === 'function') sbePaint();+ await settle();+ await settle();++ const plan = document.getElementById('sbTimeline');+ const cs = plan ? getComputedStyle(plan) : null;+ out.tl_now = (window.SBE || {}).tlNow;+ out.lane_track = cs ? cs.getPropertyValue('--sbe-track-h').trim() : null;+ out.lane_alane = cs ? cs.getPropertyValue('--sbe-alane-h').trim() : null;++ // A rectangle a POINTER sees: the painted box grown by whatever is hittable+ // past it. `padX`/`padY` are how the two cases differ and nothing else does.+ const grown = (el, padX, padY) => {+ const r = el.getBoundingClientRect();+ return { left: num(r.left - padX), top: num(r.top - padY),+ right: num(r.right + padX), bottom: num(r.bottom + padY),+ w: num(r.width + 2 * padX), h: num(r.height + 2 * padY) };+ };+ const cssNum = (el, prop) =>+ parseFloat(getComputedStyle(el).getPropertyValue(prop)) || 0;++ for (const [key, sel] of [['clip', '.sbe-clip'], ['aclip', '.sbe-aclip'],+ ['mclip', '#sbeMusicClip']]) {+ const blk = document.querySelector(sel);+ if (!blk) { out.blocks[key] = null; continue; }+ const rows = {};+ const put = (name, el, padX, padY) => {+ if (el) rows[name] = grown(el, padX || 0, padY || 0);+ };+ for (const [name, s] of [['grip_l', '.sbe-grip.l'], ['grip_r', '.sbe-grip.r']]) {+ const g = blk.querySelector(s);+ // THE SKIRT IS THE TARGET. `.sbe-grip::before` widens what can be hit by+ // `--sbe-grip-skirt` on each side without widening what is drawn, and+ // the fade handle's inset is measured from the far side of it — so the+ // gate has to reconstruct it or it would be comparing the wrong box.+ if (g) put(name, g, cssNum(g, '--sbe-grip-skirt'), 0);+ }+ put('fade_in', blk.querySelector('.sbe-fade-h.in'), 0, 0);+ put('fade_out', blk.querySelector('.sbe-fade-h.out'), 0, 0);+ const lvl = blk.querySelector('.sbe-lvl-hit');+ if (lvl) {+ // AN SVG PATH'S OWN BOX IS ITS GEOMETRY, so a level line at unity+ // measures zero pixels tall. What a pointer can reach is that box grown+ // by half the stroke — `pointer-events: stroke` is what makes the line a+ // target at all, and the stroke is where the target lives.+ //+ // ACROSS THE LINE ONLY, unless the caps say otherwise. A `butt` cap —+ // the default, and what this line uses — ends the stroke exactly at the+ // last point, so the target does NOT reach half a stroke past either+ // end. Growing X anyway reported a 7px overhang at both ends of the+ // strip and failed this gate against the fade handles for pixels no+ // pointer can reach. `round` and `square` DO overhang, so they still+ // get the pad and a change of cap cannot quietly widen a target.+ const s = getComputedStyle(lvl);+ const half = (parseFloat(s.strokeWidth) || 0) / 2;+ const cap = (s.strokeLinecap || 'butt').trim();+ put('level', lvl, cap === 'butt' ? 0 : half, half);+ }+ put('kf', blk.querySelector('.sbe-kf'), 0, 0);+ rows.__block = grown(blk, 0, 0);+ const svg = blk.querySelector('.sbe-wave-svg');+ if (svg) rows.__svg = { attr: svg.getAttribute('width'),+ viewBox: svg.getAttribute('viewBox'),+ css: num(svg.getBoundingClientRect().width),+ style: blk.style.width,+ d: (lvl && lvl.getAttribute('d') || '').slice(0, 40) };+ out.blocks[key] = rows;+ }+ return out;+})()+"""+++def _overlap(a: dict, b: dict) -> float:+ w = min(a["right"], b["right"]) - max(a["left"], b["left"])+ h = min(a["bottom"], b["bottom"]) - max(a["top"], b["top"])+ return round(max(0.0, w) * max(0.0, h), 2)+++def check_handles(end: str, m: dict) -> list[str]:+ """Every failure names the affordance and both numbers."""+ bad: list[str] = []+ for e in (m.get("errors") or []):+ bad.append(f"handles/{end}: {e}")+ for block, want in HANDLE_ROWS.items():+ rows = (m.get("blocks") or {}).get(block)+ if not rows:+ bad.append(f"handles/{end}/{block}: nothing was on screen to "+ f"measure - the gate would have passed on an empty "+ f"timeline")+ continue+ missing = [n for n in want if n not in rows]+ if missing:+ bad.append(f"handles/{end}/{block}: no {', '.join(missing)} on the "+ f"block (measured {sorted(k for k in rows if k != '__block')})")+ # -- big enough to hit ------------------------------------------+ for name in want:+ r = rows.get(name)+ if not r:+ continue+ mw, mh = MIN_HIT[name]+ if r["w"] + 0.01 < mw or r["h"] + 0.01 < mh:+ bad.append(f"handles/{end}/{block}: {name} is "+ f"{r['w']}x{r['h']}, under the {mw:g}x{mh:g} it "+ f"needs to be grabbable (block is "+ f"{rows['__block']['w']}x{rows['__block']['h']})")+ # -- and nothing else claims its pixels -------------------------+ names = [n for n in want if n in rows]+ for i, a in enumerate(names):+ for b in names[i + 1:]:+ if tuple(sorted((a, b))) in ALLOWED_OVERLAP:+ continue+ area = _overlap(rows[a], rows[b])+ if area > 0:+ bad.append(f"handles/{end}/{block}: {a} and {b} share "+ f"{area}px2 - {a} is {rows[a]}, {b} is "+ f"{rows[b]}. A pointer aimed at one of them "+ f"gets whichever is higher in the stack, which "+ f"is how the fade handle was lost inside the "+ f"trim grip")+ return bad+++# THE GATE'S OWN GATE. A geometry test that has never been seen to fail is a+# test whose selectors might all be wrong; it would report five green numbers+# about elements it never found and nobody would know. This puts the three+# shipped defects BACK - the two stylesheet rules that made Save 1554px wide+# and let the header wrap, and a floor too short for the lanes - so the gate+# can be watched failing on demand:+#+# scripts/measure_editor_layout.py --inject-defect # must exit 1+#+# It changes nothing on disk and is never on in a normal run.+JS_DEFECT = """+(() => {+ const s = document.createElement('style');+ s.id = 'phos-injected-defect';+ s.textContent = [+ /* the global `button { width: 100% }` that `.primary` never cancelled */+ '.sbe-head .primary { width: 100% !important; flex: 1 1 auto !important; }',+ /* ...and the wrap that let the row grow a second line around it */+ '.carousel-head.sbe-head { flex-wrap: wrap !important; }',+ /* a timeline floor shorter than the lanes standing in it */+ '#sbTimeline { --sbe-tl-h: 150px !important; }',+ /* ...and the corner handle back inside the trim grip, 12x12 at `left:0`,+ which is the shape the owner could not hit */+ '.sbe-fade-band { left: 0 !important; right: 0 !important;',+ ' height: 12px !important; }',+ '.sbe-fade-h { flex: 0 1 12px !important; }'+ ].join('\\n');+ document.head.appendChild(s);+ return 'injected';+})()+"""+++def check(width: int, m: dict) -> list[str]:+ """Every failure names the measurement and both numbers."""+ w = str(width)+ bad: list[str] = []+ if m.get("missing"):+ bad.append(f"{w}: elements not on the page: {', '.join(m['missing'])}")+ for e in (m.get("errors") or []):+ bad.append(f"{w}: {e}")+ if not m.get("editor_open"):+ bad.append(f"{w}: the editor was not open - nothing measured is meaningful")+ return bad++ rows = m.get("header_rows")+ if rows != 1:+ bad.append(f"{w}: header_rows {rows} != 1 "+ f"(row centres {m.get('header_row_centres')})")++ sw = m.get("save_width")+ if sw is None or not (SAVE_MIN <= sw <= SAVE_MAX):+ bad.append(f"{w}: save_width {sw} outside "+ f"[{SAVE_MIN:g}, {SAVE_MAX:g}] "+ f"(class {m.get('save_class')!r})")++ over = m.get("column_overflow")+ if over is None or over > OVERFLOW_TOL:+ bad.append(f"{w}: column_overflow {over} > {OVERFLOW_TOL:g} "+ f"(scrollWidth {m.get('column_scroll_width')} vs "+ f"clientWidth {m.get('column_client_width')})")++ clip = m.get("timeline_clip")+ if clip is None or clip > OVERFLOW_TOL:+ bad.append(f"{w}: timeline_clip {clip} > {OVERFLOW_TOL:g} "+ f"(scrollHeight {m.get('timeline_scroll_height')} vs "+ f"clientHeight {m.get('timeline_client_height')}, "+ f"floor {m.get('timeline_floor_h')})")++ both = m.get("stage_layers_both_visible")+ if both is not False:+ bad.append(f"{w}: stage_layers_both_visible {both} != false "+ f"(video opacity {m.get('video_opacity')}, "+ f"still opacity {m.get('still_opacity')})")+ return bad+++def run(verbose: bool, inject_defect: bool = False) -> tuple[dict, int]:+ binary = find_browser() # raises NoBrowser -> exit 3++ # NOT "phos-geom-": test_geometry_grid.py already owns that prefix and+ # leaves its directories behind, and two different things sharing a prefix+ # makes "did the gate clean up?" unanswerable by looking.+ work = Path(tempfile.mkdtemp(prefix="phos-editor-geom-"))+ profile = work / "chrome"+ profile.mkdir()+ log = work / "panel.log"+ panel = chrome = None+ ws = None+ try:+ panel, base = start_panel(work, log, verbose)+ chrome, devtools = start_chrome(binary, profile, verbose)+ ws = WebSocket(page_socket(devtools))+ cdp = CDP(ws)+ cdp.call("Page.enable")+ cdp.call("Runtime.enable")+ cdp.call("Emulation.setDeviceMetricsOverride",+ {"width": WIDTHS[0], "height": VIEWPORT_H,+ "deviceScaleFactor": 1, "mobile": False})+ cdp.call("Page.navigate", {"url": base + "/"})++ deadline = time.monotonic() + 45.0+ while True:+ state = cdp.evaluate("document.readyState")+ if state == "complete":+ break+ if time.monotonic() > deadline:+ raise HarnessError(f"the panel page never finished loading "+ f"(readyState {state!r})")+ time.sleep(0.2)++ opened = cdp.evaluate(JS_OPEN % {"board": json.dumps(BOARD_ID)})+ if opened != "ok":+ raise HarnessError(f"could not open the Editor: {opened}")++ deadline = time.monotonic() + 30.0+ why = "never checked"+ while time.monotonic() < deadline:+ why = cdp.evaluate(JS_READY)+ if why == "ok":+ break+ time.sleep(0.25)+ if why != "ok":+ raise HarnessError(f"the Editor never came up: {why}")+ if verbose:+ print("editor open", file=sys.stderr)++ if inject_defect:+ cdp.evaluate(JS_DEFECT)+ if verbose:+ print("the shipped defects were injected - expecting failures",+ file=sys.stderr)++ widths: dict[str, dict] = {}+ failures: list[str] = []+ for w in WIDTHS:+ cdp.call("Emulation.setDeviceMetricsOverride",+ {"width": w, "height": VIEWPORT_H,+ "deviceScaleFactor": 1, "mobile": False})+ m = cdp.evaluate(JS_MEASURE, await_promise=True)+ if not isinstance(m, dict):+ raise HarnessError(f"{w}: the page returned {m!r}, not a "+ f"measurement")+ widths[str(w)] = m+ failures.extend(check(w, m))+ if verbose:+ print(f"{w}: rows={m.get('header_rows')} "+ f"save={m.get('save_width')} "+ f"col={m.get('column_overflow')} "+ f"clip={m.get('timeline_clip')}", file=sys.stderr)++ # THE AFFORDANCES, AT BOTH ENDS OF THE LANE RANGE. Last, and in its own+ # viewports, because the floor is only reachable in a short window —+ # see HANDLE_VIEWPORT. Nothing after this reads the width loop's+ # metrics, so the change is safe to leave in place.+ handles: dict[str, dict] = {}+ for end in HANDLE_ENDS:+ vw, vh = HANDLE_VIEWPORT[end]+ cdp.call("Emulation.setDeviceMetricsOverride",+ {"width": vw, "height": vh, "deviceScaleFactor": 1,+ "mobile": False})+ m = cdp.evaluate(JS_HANDLES % {"tl": HANDLE_TL[end]},+ await_promise=True)+ if not isinstance(m, dict):+ raise HarnessError(f"handles/{end}: the page returned {m!r}, "+ f"not a measurement")+ handles[end] = m+ failures.extend(check_handles(end, m))+ if verbose:+ rows = (m.get("blocks") or {}).get("aclip") or {}+ print(f"handles/{end}: tl={m.get('tl_now')} "+ f"track={m.get('lane_track')} alane={m.get('lane_alane')} "+ f"fade_in={(rows.get('fade_in') or {}).get('w')}x"+ f"{(rows.get('fade_in') or {}).get('h')}",+ file=sys.stderr)++ return ({"ok": not failures, "widths": widths, "handles": handles,+ "failures": failures},+ 1 if failures else 0)+ finally:+ if ws is not None:+ ws.close()+ kill(chrome)+ kill(panel)+ shutil.rmtree(work, ignore_errors=True)+++def main(argv: list[str]) -> int:+ ap = argparse.ArgumentParser(description=__doc__ and __doc__.splitlines()[0])+ ap.add_argument("-v", "--verbose", action="store_true",+ help="progress on stderr; stdout stays one JSON document")+ ap.add_argument("--inject-defect", action="store_true",+ help="put the shipped layout defects back in the browser "+ "only, to prove this gate can fail. Exits 1 when it "+ "is working. Changes nothing on disk.")+ args = ap.parse_args(argv)+ try:+ doc, code = run(args.verbose, args.inject_defect)+ except NoBrowser as exc:+ print(f"no browser: {exc}", file=sys.stderr)+ return 3+ except HarnessError as exc:+ print(json.dumps({"ok": False, "widths": {},+ "failures": [f"harness: {exc}"]}))+ print(f"harness: {exc}", file=sys.stderr)+ return 4+ print(json.dumps(doc, indent=2))+ return code+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/scripts/test_analytics_dryrun.py b/scripts/test_analytics_dryrun.pyindex caac229..a01cc27 100644--- a/scripts/test_analytics_dryrun.py+++ b/scripts/test_analytics_dryrun.py@@ -762,6 +762,10 @@ class TestReceiverDirectives(AnalyticsTestCase):"status": "failed", "error": "OOM during VAE decode","elapsed_sec": 30.0,"params": {"mode": "i2v", "engine": "h3", "h3_tier": "hq_5s"}})+ # star_prompt has no boot or render path to ride in on — it is fired+ # straight from the /star-click handler, so it is captured directly+ # here with the same closed vocabulary that handler coerces `via` to.+ P._analytics_capture("star_prompt", {"via": "link"})drain()seen = {b["event"]: b["properties"] for b in self.spy.bodies}# Coverage, read off the source rather than trusted: if someone adds adiff --git a/storyboard.py b/storyboard.pyindex c82a8a6..e3feff7 100644--- a/storyboard.py+++ b/storyboard.py@@ -394,6 +394,84 @@ def validate_storyboard_detail(policy = board.get("policy") or {}seen_n: set[int] = set()+ # ---- locations ------------------------------------------------------+ locs = board.get("locations")+ known_locs: set[str] = set()+ known_views: dict[str, set[str]] = {}+ if locs is not None and not isinstance(locs, list):+ add("locations_shape", "storyboard.locations must be a list")+ else:+ seen_loc: set[str] = set()+ for i, loc in enumerate(locs or []):+ if not isinstance(loc, dict):+ add("location_not_object", f"location {i + 1}: not an object")+ continue+ lid = str(loc.get("id") or "").strip().lower()+ if not LOCATION_ID_RE.match(lid):+ add("location_id", f"location {i + 1}: id {loc.get('id')!r} must be "+ f"lowercase letters, digits, - or _", got=loc.get("id"))+ continue+ if lid in seen_loc:+ add("location_duplicate", f"location {i + 1}: duplicate id {lid!r}",+ duplicate=lid)+ continue+ seen_loc.add(lid)+ known_locs.add(lid)+ desc = str(loc.get("description") or "").strip()+ if not desc:+ # An empty location is worse than none: it reads as continuity+ # being handled while injecting nothing at all.+ add("location_empty", f"location {lid!r} has no description — "+ f"it would pin nothing", location_id=lid)+ elif len(desc) > LOCATION_DESC_MAX:+ add("location_too_long",+ f"location {lid!r}: description is {len(desc)} characters "+ f"(max {LOCATION_DESC_MAX})", location_id=lid, length=len(desc))++ # ---- views: the same place, faced the other way -------------+ views = loc.get("views")+ known_views[lid] = set()+ if views is not None and not isinstance(views, list):+ add("views_shape", f"location {lid!r}: views must be a list",+ location_id=lid)+ continue+ seen_view: set[str] = set()+ for j, view in enumerate(views or []):+ vid = str((view or {}).get("id") or "").strip().lower() \+ if isinstance(view, dict) else ""+ if not VIEW_ID_RE.match(vid):+ add("view_id",+ f"location {lid!r}, view {j + 1}: id "+ f"{(view or {}).get('id') if isinstance(view, dict) else view!r} "+ f"must be lowercase letters, digits, - or _",+ location_id=lid, got=(view.get("id") if isinstance(view, dict)+ else view))+ continue+ if vid in seen_view:+ add("view_duplicate",+ f"location {lid!r}: duplicate view id {vid!r}",+ location_id=lid, duplicate=vid)+ continue+ seen_view.add(vid)+ # KNOWN even when its description is wrong: the view exists,+ # and reporting the real fault plus `unknown_view` on every+ # shot that names it buries the one line worth reading.+ known_views[lid].add(vid)+ vdesc = str(view.get("description") or "").strip()+ if not vdesc:+ # Worse than no view: a shot naming it would fall back to+ # the location description — the establishing angle — which+ # is the exact prompt the reverse angle exists to escape.+ add("view_empty",+ f"location {lid!r}: view {vid!r} has no description — a shot "+ f"naming it would fall back to the establishing angle",+ location_id=lid, view=vid)+ elif len(vdesc) > LOCATION_DESC_MAX:+ add("view_too_long",+ f"location {lid!r}, view {vid!r}: description is {len(vdesc)} "+ f"characters (max {LOCATION_DESC_MAX})",+ location_id=lid, view=vid, length=len(vdesc))+for idx, s in enumerate(shots):# `where` used to be computed from s.get() BEFORE the isinstance check, so a shot that# was a string (exactly the case the next line reports) raised AttributeError instead@@ -415,6 +493,45 @@ def validate_storyboard_detail(else:seen_n.add(n)+ # A shot that names a location the board does not have would render+ # with NO location injected and look exactly like a shot that never+ # claimed one — the continuity failure arriving silently, which is the+ # thing locations exist to stop.+ lref = s.get("location_id")+ if lref is not None and str(lref).strip():+ lref = str(lref).strip().lower()+ if lref not in known_locs:+ add("unknown_location",+ f"{where}: location {lref!r} is not on this storyboard",+ n=n_for_ui, field="location_id", location_id=lref,+ known=sorted(known_locs))+ else:+ lref = ""++ # A shot naming a view that is gone fails EXACTLY the way an unknown+ # location fails — the reverse angle silently composes from the+ # establishing description, so the car the whole view existed to get+ # out of frame is back in frame, and nothing said a word about it.+ vref = s.get("view")+ if vref is not None and str(vref).strip():+ vref = str(vref).strip().lower()+ if not lref:+ add("unknown_view",+ f"{where}: view {vref!r} but the shot names no location — "+ f"a view belongs to a location",+ n=n_for_ui, field="view", view=vref)+ elif vref not in (known_views.get(lref) or set()):+ add("unknown_view",+ f"{where}: view {vref!r} is not a view of location {lref!r}",+ n=n_for_ui, field="view", view=vref, location_id=lref,+ known=sorted(known_views.get(lref) or ()))++ eye = s.get("eyeline")+ if eye is not None and str(eye).strip() and str(eye).strip().lower() not in EYELINES:+ add("bad_eyeline",+ f"{where}: eyeline {eye!r} is not one of {', '.join(EYELINES)}",+ n=n_for_ui, field="eyeline", eyeline=eye, valid=list(EYELINES))+mode = s.get("mode")if mode not in VALID_MODES:add("bad_mode",@@ -446,6 +563,28 @@ def validate_storyboard_detail(f"{where}: mode 'character' requires a character_id",n=n_for_ui, field="character_id")+ # No mouth moves without words. This blocks the render rather than+ # warning, on the same principle as everything else here: the failure+ # it prevents is a finished clip of somebody babbling, and you only+ # find out after the render.+ verb = shot_speech_problem(prompt)+ if verb:+ add("speech_without_words",+ f"{where}: {verb!r} implies someone is speaking, but no spoken "+ f"line is written — the model renders a moving mouth with "+ f"nothing to say. Write the line in quotes, or describe the "+ f"shot without speech.",+ n=n_for_ui, field="prompt", verb=verb)+ # And the inverse failure: words that exist but cannot survive the+ # clock. Blocks the render for the same reason everything here does —+ # the defect (a sentence cut off mid-word) is only visible AFTER the+ # render time is spent.+ pacing = shot_pacing_problem(prompt, s.get("duration_s") or 0)+ if pacing:+ add("dialogue_does_not_fit",+ f"{where}: {pacing}.",+ n=n_for_ui, field="prompt")+dur = s.get("duration_s")if not isinstance(dur, (int, float)) or not (0 < float(dur) <= 60):add("bad_duration",@@ -744,11 +883,395 @@ def ensure_trigger(prompt: str, trigger: str) -> str:return f"{t} {p}" if p else t+# =============================================================================+# THE SPEECH LAW, AT BOARD LEVEL — no mouth moves without words to say+# =============================================================================+# `storyboard_planner` has enforced this on shots IT writes since the owner+# first reported "talking gibberish": a prompt that says a man is speaking and+# gives him nothing to say leaves the audio branch babbling. The law was+# correct and it was in the wrong place — it ran inside the planner, so a shot+# authored any other way (by hand, by the add-shot route, by an importer) sailed+# past it. The owner reported gibberish a SECOND time on a hand-written board,+# which is the same bug arriving through the door the first fix did not cover.+#+# This is the engine-agnostic form, and it deliberately does NOT reuse the+# planner's `_speech_violations`: that one runs on the planner's own draft,+# where a line lives in `<d>[English] ...</d>` and prose quotes are a FORM+# error to be rewrapped. By the time a shot is on a board its prompt is+# finished — H3 keeps the tag, LTX has already been converted to single quotes+# by `_strip_h3_markup` — so at this level the only question is whether WORDS+# ARE PRESENT AT ALL, in either wrapper.+_SPOKEN_WORDS_RE = re.compile(+ r"<d>\s*(?:\[[^\]]*\]\s*)?[^<]*\w+[^<]*</d>" # H3: the tag, with content+ r"|['‘“\"]\s*[^'’”\"]*\w+\s+[^'’”\"]*['’”\"]",+ re.DOTALL) # LTX: a quoted phrase, 2+ words++# Deliberately narrower than the planner's list: this one BLOCKS A RENDER, so+# it only carries verbs that unambiguously mean a mouth is producing speech.+# `brief` needs an object — a "briefing room" is a room, which is a false+# positive the planner's version already paid for once.+_IMPLIES_SPEECH_RE = re.compile(+ r"\b(?:explain(?:s|ing)?|describ(?:es|ing) (?:to|the situation)|discuss(?:es|ing)|"+ r"talk(?:s|ing)|speak(?:s|ing)|says?|saying|tell(?:s|ing)|address(?:es|ing)"+ r"|announc(?:es|ing)|declar(?:es|ing)|recit(?:es|ing)|narrat(?:es|ing)"+ r"|murmur(?:s|ing)|mutter(?:s|ing)|whisper(?:s|ing)|mumbl(?:es|ing)"+ r"|ask(?:s|ing)|answer(?:s|ing)|repl(?:y|ies|ying)|shout(?:s|ing)"+ r"|order(?:s|ing) (?:him|her|them|the)|instruct(?:s|ing))\b"+ r"|\b(?:his|her|their|its) voice\b"+ r"|\bin a (?:low|quiet|soft|hushed|loud|steady|calm|firm|gravelly|deep) voice\b"+ r"|\bmid-sentence\b|\bmid-speech\b", re.IGNORECASE)+++def shot_speech_problem(prompt: str) -> str | None:+ """The speech verb in `prompt` that has no words to go with it, or None.++ A shot is SPOKEN (the words are in it) or SILENT (nothing implies a mouth+ moving). Implying speech and providing none is the one combination that is+ always wrong, because the model renders a talking head with nothing to say.+ """+ p = prompt or ""+ if _SPOKEN_WORDS_RE.search(p):+ return None+ m = _IMPLIES_SPEECH_RE.search(p)+ return m.group(0) if m else None+++# --- dialogue PACING: a line must fit its shot, and it must CLOSE -----------+# The owner hit the same truncation twice in one day: a line sized to the idea+# instead of to the clock renders as a sentence that stops mid-word when the+# shot ends. His ruling, verbatim: "when people talk, there is a structure to+# the talk... a beginning and an end. It's not just open-ended sentences that+# get cut."+#+# The budget is measured, not guessed, and it BRACKETS the evidence: a 7-word+# line in a 4.04s shot delivered fine (needs the budget to allow >= 2.31 w/s+# after settle), and a 20-word line in a 7.04s shot was cut mid-phrase (needs+# it to refuse >= 3.31). 2.4 sits between the two with margin on both sides.+SPEECH_WORDS_PER_SEC = 2.4+# A WARM READ IS SLOWER, and the evidence forced this split: a 9-word line+# delivered "quietly, almost under her breath" truncated in a 5.04s shot that+# the 2.4 budget approves, and a 23-word slow read truncated at 13.04s. Both+# land near 1.7 w/s. One constant cannot bracket a game-show host and a lazy+# half-smile; the descriptor in front of the line is the tempo marking.+SPEECH_WORDS_PER_SEC_SLOW = 1.7+_SLOW_READ_RE = re.compile(+ r"\bsays? (?:[a-z]+[ ,]+)*?(?:slowly|softly|quietly|low\b|lazily)"+ r"|\bunder (?:his|her|their) breath\b|\blazy half-smile\b"+ r"|\bdrawls?\b|\bwhispers?\b",+ re.IGNORECASE)+SPEECH_SETTLE_S = 1.0+++def is_slow_read(prompt: str) -> bool:+ """True when the voice descriptor asks for slow delivery."""+ return bool(_SLOW_READ_RE.search(prompt or ""))++# Spoken spans, with their words, in both dialects. The single-quote form must+# survive apostrophes: a quote FLANKED BY LETTERS is punctuation inside a word+# ("There's"), not the end of the line — without that rule the counter stops+# counting at the first contraction.+_D_SPAN_RE = re.compile(r"<d>\s*(?:\[[^\]]*\]\s*)?(.*?)</d>", re.DOTALL)+_Q_SPAN_RE = re.compile(+ r"(?<![A-Za-z])'((?:[^']|(?<=[A-Za-z])'(?=[A-Za-z]))+?)'(?![A-Za-z])",+ re.DOTALL)+++def spoken_spans(prompt: str) -> list[str]:+ """Every spoken line in `prompt`, tag form and quote form both."""+ p = prompt or ""+ out = [m.group(1).strip() for m in _D_SPAN_RE.finditer(p)]+ stripped = _D_SPAN_RE.sub(" ", p)+ out += [m.group(1).strip() for m in _Q_SPAN_RE.finditer(stripped)]+ return [s for s in out if s]+++def speech_fit_frames(word_count: int, fps: int = 24, slow: bool = False) -> int:+ """The smallest legal frame count (fps*n+1) that fits `word_count` words."""+ rate = SPEECH_WORDS_PER_SEC_SLOW if slow else SPEECH_WORDS_PER_SEC+ need_s = word_count / rate + SPEECH_SETTLE_S+ n = max(1, int((need_s * fps + fps - 1) // fps))+ return fps * n + 1+++def shot_pacing_problem(prompt: str, duration_s: float) -> str | None:+ """Why this shot's dialogue will not survive its duration, or None.++ Two failure shapes, both of which render as a cut-off sentence:+ * OVERSTUFFED — more words than the clock can carry;+ * UNFINISHED — the last line ends on a comma/dash/ellipsis/nothing, so+ even at a fitting length it sounds like the start of a thought.+ """+ spans = spoken_spans(prompt)+ if not spans:+ return None+ # Punctuation-only tokens are not words — an em-dash between clauses was+ # counted once and pushed a delivered-fine line over the budget.+ words = sum(1 for sp in spans for t in sp.split() if any(c.isalnum() for c in t))+ try:+ dur = float(duration_s or 0)+ except (TypeError, ValueError):+ dur = 0.0+ if dur > 0:+ slow = is_slow_read(prompt)+ rate = SPEECH_WORDS_PER_SEC_SLOW if slow else SPEECH_WORDS_PER_SEC+ allowed = max(0.0, (dur - SPEECH_SETTLE_S) * rate)+ if words > allowed:+ pace = "at this SLOW delivery" if slow else "at speaking pace"+ return (f"{words} spoken words in a {dur:.1f}s shot — {pace} only "+ f"~{int(allowed)} fit, so the line is cut off "+ f"mid-sentence. Shorten the line, or lengthen the shot to "+ f"at least {speech_fit_frames(words, slow=slow)} frames")+ last = spans[-1].rstrip()+ if last and last[-1] not in ".!?":+ return (f"the line ends {last[-12:]!r} — no full stop, so it plays as "+ f"a sentence that never finishes. Close the thought")+ return None+++# =============================================================================+# LOCATIONS — the same room in every shot that claims to be in it+# =============================================================================+# A text-to-video model re-invents everything the prompt does not pin. Four+# shots that all said "dim room, cinematic close-up" came back as four rooms:+# a monitor-lit study, a brighter office with papers on the wall, a VINTAGE+# PARLOUR with no monitors at all, and a near-black void — with the collar+# changing between them. Nobody wrote a contradiction; the shots simply never+# agreed on anything, and unstated means re-rolled.+#+# So a location is a board-level ENTITY, exactly like a cast member, and a shot+# references it by id. The description is written once and injected into every+# shot that claims that location, which is the only way "the same room" can+# survive shots being re-rendered one at a time months apart.+LOCATION_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$")+LOCATION_DESC_MAX = 600++# ---- VIEWS: a location is a place seen from ANGLES ---------------------------+# One description per location is one CAMERA POSITION pretending to be a place.+# Measured on the car-wash day: the establishing description ("a soapy blue+# sedan on the driveway") actively FIGHTS the reverse shot — the moment he+# turns to talk to her, the car is behind the camera and must not be in the+# prompt at all, the houses across the street must be, and the low sun that+# raked in from camera left now rakes in from camera RIGHT. That was hand-built+# as a second location (`carwash_reverse`); a view is that, first-class.+#+# So a location carries named VIEWS. Each view is a self-contained description+# of what the camera sees FACING that direction, light side included, and a+# shot picks `location_id` + `view`. A location with no views behaves exactly+# as it always has: its description is the only view there is.+VIEW_ID_RE = LOCATION_ID_RE++# Where the subject is looking, as a fact about the FRAME rather than about the+# room: off past the left edge, off past the right edge, or down the lens.+# Two shots that cut between two people must not claim the same one — that is+# the 180-degree line, and it is why this is a vocabulary and not free text.+EYELINES = ("left", "right", "lens")+++def new_view(view_id: str, name: str, description: str = "") -> dict:+ return {"id": str(view_id).strip().lower(),+ "name": str(name).strip(),+ "description": str(description).strip()}+++def new_location(loc_id: str, name: str, description: str = "",+ views: list[dict] | None = None) -> dict:+ loc = {"id": str(loc_id).strip().lower(),+ "name": str(name).strip(),+ "description": str(description).strip()}+ # ABSENT, not empty, when there are none. Every board written before views+ # existed has no `views` key, and an empty list would be a new shape for+ # the panel and the validator to have opinions about for no gain.+ if views:+ loc["views"] = list(views)+ return loc+++def board_locations(board: dict) -> dict[str, dict]:+ """`{id: location}` for a board, skipping anything malformed."""+ out: dict[str, dict] = {}+ for loc in (board.get("locations") or []):+ if isinstance(loc, dict) and str(loc.get("id") or "").strip():+ out[str(loc["id"]).strip().lower()] = loc+ return out+++def merge_location_views(board_locs: list[dict] | None,+ plan_locs: list[dict] | None) -> list[dict]:+ """The board's locations, wearing the views the planner derived.++ PATCH, NEVER OVERWRITE — the rule locations already cost this project once,+ when a re-plan assigned the board's `locations` wholesale and erased what+ the user had typed. The board's row stays authoritative for id, name and+ description: those are the user's own words out of the Locations box. Only+ `views` come from the plan, and only when the plan actually derived some —+ a re-plan with the geography pass off, or one whose floor plan came back as+ chatter, must not strip the views the last plan produced, because the shots+ on the board still name them and an unknown view id is a hard error.++ A location the plan knows and the board does not is appended rather than+ dropped: its shots point at it, and a board missing it fails validation on+ every one of them.+ """+ out: list[dict] = []+ plan_by_id = {str(l.get("id") or "").strip().lower(): l+ for l in (plan_locs or []) if isinstance(l, dict) and l.get("id")}+ seen: set[str] = set()+ for loc in (board_locs or []):+ if not isinstance(loc, dict) or not str(loc.get("id") or "").strip():+ continue+ lid = str(loc["id"]).strip().lower()+ seen.add(lid)+ row = dict(loc)+ views = (plan_by_id.get(lid) or {}).get("views")+ if views:+ row["views"] = [dict(v) for v in views if isinstance(v, dict)]+ out.append(row)+ for lid, loc in plan_by_id.items():+ if lid not in seen:+ out.append(dict(loc))+ return out+++def location_views(loc: dict | None) -> dict[str, dict]:+ """`{id: view}` for one location, skipping anything malformed."""+ out: dict[str, dict] = {}+ for v in ((loc or {}).get("views") or []):+ if isinstance(v, dict) and str(v.get("id") or "").strip():+ out[str(v["id"]).strip().lower()] = v+ return out+++def shot_view(shot: dict, locations: dict[str, dict] | None = None) -> dict | None:+ """The view a shot names, or None when it names none / names one that is gone."""+ vid = str((shot or {}).get("view") or "").strip().lower()+ if not vid:+ return None+ loc = (locations or {}).get(str((shot or {}).get("location_id") or "").strip().lower())+ return location_views(loc).get(vid)+++def shot_scene_text(shot: dict, locations: dict[str, dict] | None = None) -> str:+ """What the camera sees: the VIEW's description, else the location's.++ The fallback is the whole back-compat story in one line — a board with no+ views, or a shot that names no view, injects exactly what it always did.+ """+ view = shot_view(shot, locations)+ if view is not None:+ desc = str(view.get("description") or "").strip()+ if desc:+ return desc+ loc = (locations or {}).get(str((shot or {}).get("location_id") or "").strip().lower())+ return str((loc or {}).get("description") or "").strip()+++def eyeline_clause(eyeline: str | None, pronoun: str = "") -> str:+ """"his eyes fixed past the right edge of frame" — or "" for lens/none.++ `lens` deliberately produces NOTHING. Looking down the barrel is what these+ models do unprompted for a piece to camera, and a sentence telling them to+ do it buys a stiffer performance than saying nothing. The value still+ exists because a shot has to be able to SAY it holds the lens — that is+ what makes the 180-degree check able to tell "faces the camera" apart from+ "nobody wrote an eyeline".+ """+ side = str(eyeline or "").strip().lower()+ if side not in ("left", "right"):+ return ""+ poss = {"he": "his", "she": "her", "they": "their",+ "him": "his", "her": "her"}.get(str(pronoun or "").strip().lower(), "")+ return "%seyes fixed past the %s edge of frame" % (poss + " " if poss else "", side)+++def eyeline_complement(eyeline: str | None) -> str:+ """The other side of the line. `lens` and nothing have no complement."""+ return {"left": "right", "right": "left"}.get(str(eyeline or "").strip().lower(), "")+++def board_wardrobe(board: dict) -> dict[str, str]:+ """`{character_id: what they are wearing in THIS film}`.++ The same failure locations fixed, one axis over. Four shots of one man came+ back in a navy suit, a navy suit, a period collar and a different period+ collar, because "a man in a dark suit" is a different suit every time it is+ re-rolled. Writing the outfit ONCE and attaching it to the character is the+ only version of this that holds across shots rendered separately — and it+ is what a hand-written board makes you do by copy-paste, which is exactly+ the copy-paste that drifts.+ """+ out: dict[str, str] = {}+ for row in (board.get("cast") or []):+ if isinstance(row, dict) and row.get("id"):+ w = str(row.get("wardrobe") or "").strip()+ if w:+ out[str(row["id"]).strip()] = w+ return out+++def compose_shot_prompt(shot: dict, locations: dict[str, dict] | None = None,+ wardrobe: dict[str, str] | None = None) -> str:+ """The prompt that is actually rendered: subject, action, FRAME, PLACE.++ Order is deliberate and matches how these models read a prompt — the+ subject and what it is doing first, then how it is framed, then where it+ is. Putting the location first buries the action in scenery. The EYELINE+ rides with the framing rather than with the room, because where a person+ looks is a fact about the frame, not about the scenery behind them.++ Every addition is appended rather than merged into `shot["prompt"]`, so+ the shot keeps the sentence a human wrote and editing a location — or+ flipping an eyeline to fix the 180-degree line — re-flows every shot that+ uses it without rewriting anybody's text.+ """+ trigger = (shot.get("trigger") or shot.get("character_id") or "").strip()+ parts = [ensure_trigger(shot.get("prompt") or "", trigger)]++ # WARDROBE goes right after the person, where a costume note belongs, and+ # only if the shot has not already said it — a board that spells the outfit+ # out per shot must not get it twice.+ cid = str(shot.get("character_id") or "").strip()+ outfit = (wardrobe or {}).get(cid, "").strip().rstrip(",")+ if outfit and outfit.lower() not in parts[0].lower():+ parts.append(outfit)++ framing = str(shot.get("framing") or "").strip().rstrip(",")+ if framing:+ parts.append(framing)++ eyes = eyeline_clause(shot.get("eyeline"), shot.get("pronoun") or "")+ if eyes:+ parts.append(eyes)++ # The VIEW, if the shot names one, otherwise the location as before.+ scene = shot_scene_text(shot, locations).rstrip(",")+ if scene:+ parts.append(scene)++ return ", ".join(p for p in parts if p)+++# The pass's PIPELINE quality -> the CHARACTER quality token make_job accepts.+# Chosen by canvas and pipeline, not by name: quick is the small distilled+# draft (704x384), balanced/standard are the graded 1024x576 distilled recipe+# ("pro" — the one that holds identity best), and the two High tiers keep their+# own two-stage pipeline. Anything unrecognised lands on "pro", which is the+# recipe the character work is actually validated at.+CHARACTER_QUALITY_FOR_PASS: dict[str, str] = {+ "quick": "draft",+ "balanced": "pro",+ "standard": "pro",+ "high": "high",+ "high_720p": "high720",+}++def shot_to_job(shot: dict, policy_pass: dict, *,board_id: str = "", board_title: str = "",h3_available: bool = True,engine_mode: str = DEFAULT_ENGINE_MODE,- h3_chain_prompts: bool = False) -> dict:+ h3_chain_prompts: bool = False,+ locations: dict[str, dict] | None = None,+ wardrobe: dict[str, str] | None = None) -> dict:"""Translate one storyboard shot into the panel's ORDINARY job form fields.Deliberately produces the same shape a human clicking Generate would produce, so shots@@ -761,10 +1284,12 @@ def shot_to_job(shot: dict, policy_pass: dict, *,NOTE `enhance: "off"` is not optional — see ensure_trigger() above."""- trigger = (shot.get("trigger") or shot.get("character_id") or "").strip()- prompt = shot.get("prompt") or ""- if trigger:- prompt = ensure_trigger(prompt, trigger)+ # compose_shot_prompt, not shot["prompt"] — the framing and the location+ # have to reach the model, and this is the one place every shot passes+ # through on its way to a render. Doing it at the call sites instead would+ # mean the estimate, the re-render and the gap-fill each getting their own+ # chance to forget.+ prompt = compose_shot_prompt(shot, locations, wardrobe)# The engine. Without this the job dict has no `engine` key, make_job falls back to# ENGINE_DEFAULT ("ltx"), and every H3 shot the planner wrote renders silently on a@@ -813,6 +1338,22 @@ def shot_to_job(shot: dict, policy_pass: dict, *,if shot.get("character_id"):job["character_id"] = shot["character_id"]+ # A CHARACTER JOB SPEAKS A DIFFERENT QUALITY VOCABULARY, and make_job+ # REFUSES the pipeline one. `resolve_character_quality()` accepts only+ # draft / pro / high / high720; a job carrying `quality="quick"` (the+ # default draft pass) or `"standard"` (the default delivery pass)+ # raises CharacterRequestError, which `_sb_render_thread` catches and+ # turns into a failed shot. Every cast shot in every film, both passes,+ # with the message "character quality must be draft, pro, high or+ # high720" as the only clue. Translating here is what makes the pass+ # policy and the character surfaces speak to the same make_job.+ #+ # The panel's `resolve_character_quality` is the source of truth for+ # what these keys MEAN; this table only says which of them a pass maps+ # onto. `test_storyboard_editor_api` pins the pair together so the two+ # cannot drift apart in silence.+ job["quality"] = CHARACTER_QUALITY_FOR_PASS.get(+ str(policy_pass.get("quality", "balanced")).strip().lower(), "pro")# THE VOICE LOADS ONLY WHEN THERE ARE LINES TO SAY.## Stacking a character's audio LoRA on a shot with no speech spends the@@ -826,7 +1367,23 @@ def shot_to_job(shot: dict, policy_pass: dict, *,# shot with a <d> tag that has any content speaks; one without does not.# (The Manual tab cannot know this and does not pretend to — it sets a# default and says it did.)- job["no_voice"] = "off" if _HAS_DIALOGUE.search(prompt) else "on"+ # ENGINE-AGNOSTIC, and it was not. This read `_HAS_DIALOGUE`, which+ # matches `<d>…</d>` and nothing else, under a comment claiming "it is+ # exact here… a derivation, not a heuristic". That is true of H3 and+ # FALSE of LTX: `_strip_h3_markup` has already turned the tag into+ # 'single quotes' by the time an LTX prompt exists, so the tag is never+ # present, `no_voice` was ALWAYS "on", and the trained voice LoRA was+ # stripped from EVERY LTX character shot that had a line to say.+ # The owner heard it as the characters never using their own voices,+ # reported it repeatedly, and it survived because the comment sounded+ # authoritative and was only checked against the engine it was true for.+ #+ # `_SPOKEN_WORDS_RE` is the same detector `shot_speech_problem` uses.+ # That is deliberate: one asks "are there words?" to decide whether the+ # shot is honest, the other to decide whether the voice loads. If those+ # two ever disagree you get one of the two bugs — a mouth with nothing+ # to say, or a line delivered by a stranger.+ job["no_voice"] = "off" if _SPOKEN_WORDS_RE.search(prompt) else "on"if shot.get("seed") is not None:job["seed"] = shot["seed"]@@ -870,7 +1427,8 @@ def default_policy() -> dict:def new_storyboard(board_id: str, title: str, *, shots: list[dict] | None = None,- cast: list[dict] | None = None, policy: dict | None = None) -> dict:+ cast: list[dict] | None = None, policy: dict | None = None,+ locations: list[dict] | None = None) -> dict:"""Build an empty, schema-correct storyboard. Kept here so the planner, the tests and anyfuture importer all produce the identical shape."""return {@@ -879,6 +1437,7 @@ def new_storyboard(board_id: str, title: str, *, shots: list[dict] | None = None"title": title,"created_at": int(time.time()),"cast": cast or [],+ "locations": locations or [],"policy": policy or default_policy(),"shots": shots or [],}diff --git a/storyboard_edit.py b/storyboard_edit.pynew file mode 100644index 0000000..0d69de6--- /dev/null+++ b/storyboard_edit.py@@ -0,0 +1,1303 @@+#!/usr/bin/env python3+"""Auto-editor — pick the good part of each clip, and cut on the beat.++WHY THIS EXISTS+---------------+`_sb_export()` in the panel assembles a film by concatenating WHOLE clips in+`n` order. That is the right default (it is exactly what the folder contains,+and it never surprises anyone), but it is not an edit — it is a playlist. Two+things are wrong with a playlist made of generated video:++1. **A generated clip is not uniformly good.** The first frames are often soft+ while the sampler settles, the tail commonly degrades — softening, smearing,+ sometimes washing to white — and in between there are usually two or three+ seconds that are clearly the shot. Playing all of it spends the viewer's+ attention on the parts you would have cut by hand.+2. **The cuts ignore the music.** A cut lands wherever the clip happened to+ end, so a 5.125 s render cuts at 5.125 s, then 10.250 s, then 15.375 s —+ a grid that has nothing to do with the track under it. The eye notices;+ that is most of why an assembled film reads as "clips glued end to end"+ while the same shots cut on the downbeat read as a film.++This module fixes both, as ANALYSIS ONLY. It opens no sockets, imports nothing+from `mlx_ltx_panel`, loads no model, and writes no video. It answers two+questions — "which stretch of this clip is the good one" and "where are the+beats" — and turns the answers into a cut plan that the panel's existing+assembler can execute in the filtergraph pass it was already running.++ storyboard_edit.py which seconds, and where the cuts go (this file)+ mlx_ltx_panel.py copies, filtergraph, encode, gallery++DEPENDENCIES: numpy and the standard library. Nothing else. Not librosa, not+opencv, not torch, not decord. Everything below is FFT, autocorrelation and+array slicing, decoded through the ffmpeg the panel already ships with. That+is a deliberate constraint: this feature must not turn a 20 GB install into a+20 GB install plus a scientific Python stack.++HONESTY ABOUT WHAT THE MEASUREMENTS ARE+---------------------------------------+None of these are perceptual quality models. They are cheap proxies with known+failure modes, and every one of them reports its raw numbers so a human can+disagree:++ * *Sharpness* = variance of the Laplacian on a downscaled grey frame. It goes+ down for blur AND up for noise/grain. Within ONE clip (same scene, same+ grain, same encoder) that confound is mostly constant, which is why the+ score is normalised against the clip's own distribution and never compared+ across clips.+ * *Stability* = mean absolute frame-to-frame difference. Near zero means the+ picture is frozen (dead footage, or the sampler stopped moving); very high+ means thrash — strobing, a scene break inside the clip, or the artefacting+ that generated video does when it loses the plot. Both ends are bad, so the+ score is a band, not a maximum — and it is scored on the window's quietest+ quarter as well as its average, because a window that is mostly frozen and+ briefly busy averages into the healthy band and plays as a still frame.+ * *Luma sanity* = mean brightness plus the fraction of crushed / blown+ pixels. This one exists because of a real bug class: renders that go white+ (or black) in the last second. A window that contains that is rejected+ outright, not merely marked down.+ * *Head / tail guard* = a positional penalty, configurable, because "the tail+ softens" is a property of the GENERATOR, not something the pixels always+ reveal. It is a prior, and it is applied as one.++ * *Beat tracking* is a constant-tempo model: one BPM, one phase, 4/4. It is+ right on the electronic/orchestral material this was built for and it will+ be wrong on rubato, on a live drummer, and on anything that changes tempo+ mid-track. `beat_map()` therefore returns a `confidence` and the raw+ evidence behind it, and `plan_cut()` will happily produce an unsnapped+ plan when the caller decides the confidence is too low. A confident wrong+ answer is the one outcome this module is built to avoid.++DETERMINISM+-----------+Every function here is deterministic: fixed sample grids, no randomness, no+dict-ordering dependence, ties broken by the earlier candidate. The same+inputs give byte-identical plans, which is what makes a plan reviewable and a+test possible.+"""++from __future__ import annotations++import bisect+import json+import math+import os+import shutil+import subprocess+from pathlib import Path++import numpy as np++__all__ = [+ "best_window", "beat_map", "snap", "plan_cut",+ "probe_media", "format_plan", "plan_total", "audio_span_for",+]+++# ---------------------------------------------------------------------------+# ffmpeg — resolved the same way the panel resolves it, but WITHOUT importing+# the panel. This module has to stay importable from a test, a CLI, or a+# future tool that has no business booting a web server.+# ---------------------------------------------------------------------------+def _resolve_ffmpeg() -> Path:+ candidates = [+ os.environ.get("LTX_FFMPEG"),+ shutil.which("ffmpeg"),+ str(Path.home() / "pinokio/bin/ffmpeg-env/bin/ffmpeg"),+ "/opt/homebrew/bin/ffmpeg",+ "/usr/local/bin/ffmpeg",+ ]+ for c in candidates:+ if c and Path(c).exists():+ return Path(c)+ return Path("/usr/local/bin/ffmpeg")+++FFMPEG = _resolve_ffmpeg()+FFPROBE = FFMPEG.parent / "ffprobe"+++# ---------------------------------------------------------------------------+# Analysis constants. All of them are arguments somewhere below; these are the+# defaults, gathered here so a person recalibrating has one place to look.+# ---------------------------------------------------------------------------+ANALYSIS_FPS = 4.0 # frames per second SAMPLED, not the clip's rate.+ANALYSIS_WIDTH = 320 # grey analysis frames are 320 px wide.++# Motion, in mean absolute 8-bit grey levels between samples 1/ANALYSIS_FPS+# apart. Calibrated on real LTX-2 / H3 renders: a locked-off shot with only+# hair and breath moving sits at 1-3, ordinary camera movement at 4-12, a whip+# pan or a hard cut inside the clip at 25+.+MOTION_DEAD = 0.30 # below this the picture is not moving at all+MOTION_LOW = 1.20 # bottom of the "alive" band+MOTION_HIGH = 18.0 # top of the "alive" band+MOTION_THRASH = 38.0 # above this it is strobing / breaking up++# Luma, 0-255 on the grey analysis frame.+LUMA_BLACK = 8.0 # window mean below this = the render went dark+LUMA_WHITE = 243.0 # window mean above this = the render went white+LUMA_GOOD_LO = 18.0 # soft band; outside it the score ramps down+LUMA_GOOD_HI = 232.0+CRUSH_LEVEL = 8 # a pixel at or below this is crushed+BLOWN_LEVEL = 247 # a pixel at or above this is blown+# Veto thresholds, deliberately high. A night exterior on this corpus runs 72 %+# crushed and is perfectly good footage; only a frame that is essentially ALL+# black or ALL white is a render failure rather than a look.+CRUSH_VETO = 0.96+BLOWN_VETO = 0.96++# Score weights. The positives sum to 1.0 so a raw score reads as a fraction.+W_SHARP = 0.45+W_STABLE = 0.35+W_LUMA = 0.20+# Positional priors. The tail is weighted heavier than the head because the+# tail failure (softening, drift, wash-out) is both more common and more+# visible than the head one (a soft first frame or two).+HEAD_GUARD_S = 0.30+TAIL_GUARD_S = 0.75+HEAD_WEIGHT = 0.10+TAIL_WEIGHT = 0.25++# Beat tracking.+AUDIO_SR = 22050+N_FFT = 1024+HOP = 256+BPM_MIN, BPM_MAX = 60.0, 200.0+BPM_PRIOR_CENTER = 120.0 # log-normal tempo prior, in BPM+BPM_PRIOR_OCTAVES = 0.9 # sigma, in octaves+LOW_BAND_HZ = 250.0 # "kick band", used to choose the downbeat phase+DEFAULT_METER = 4+++def _f(x, default: float = 0.0) -> float:+ try:+ v = float(x)+ except (TypeError, ValueError):+ return default+ if v != v or v in (float("inf"), float("-inf")):+ return default+ return v+++# ===========================================================================+# Probing+# ===========================================================================+def probe_media(path) -> dict | None:+ """Geometry + duration + audio facts, or None when ffprobe can't read it.++ Deliberately its own function rather than a call into the panel: the panel+ imports mlx, and an editor that needs a 20 GB model loaded to measure a+ Laplacian is not an editor. The shape of the return matches the panel's+ `_sb_probe_clip()` so a caller can hand either one to `best_window()`.+ """+ p = Path(str(path))+ try:+ out = subprocess.run(+ [str(FFPROBE), "-v", "error", "-show_entries",+ "stream=codec_type,width,height,sample_rate,duration,avg_frame_rate"+ ":format=duration", "-of", "json", str(p)],+ capture_output=True, text=True, timeout=120)+ except (OSError, subprocess.SubprocessError):+ return None+ if out.returncode != 0:+ return None+ try:+ data = json.loads(out.stdout or "{}")+ except (ValueError, TypeError):+ return None+ if not isinstance(data, dict):+ return None++ w = h = 0+ v_dur = 0.0+ fps = 0.0+ has_audio = False+ rate = 0+ for st in (data.get("streams") or []):+ if not isinstance(st, dict):+ continue+ kind = str(st.get("codec_type") or "")+ if kind == "video" and not w:+ try:+ w, h = int(st.get("width") or 0), int(st.get("height") or 0)+ except (TypeError, ValueError):+ w = h = 0+ v_dur = _f(st.get("duration"))+ raw = str(st.get("avg_frame_rate") or "0/1")+ if "/" in raw:+ num, _, den = raw.partition("/")+ fps = _f(num) / _f(den, 1.0) if _f(den, 1.0) else 0.0+ else:+ fps = _f(raw)+ elif kind == "audio":+ has_audio = True+ try:+ rate = max(rate, int(st.get("sample_rate") or 0))+ except (TypeError, ValueError):+ pass+ duration = v_dur or _f((data.get("format") or {}).get("duration"))+ if duration <= 0:+ return None+ if w <= 0 or h <= 0:+ # Audio-only file (a soundtrack). Still a valid probe.+ return {"w": 0, "h": 0, "duration": round(duration, 6), "fps": 0.0,+ "has_audio": has_audio, "sample_rate": rate}+ return {"w": w, "h": h, "duration": round(duration, 6),+ "fps": round(fps, 6), "has_audio": has_audio, "sample_rate": rate}+++# ===========================================================================+# PART A — which seconds of this clip are the good ones+# ===========================================================================+def _decode_grey(path, width: int, height: int, fps: float) -> np.ndarray:+ """Decode the clip to a stack of small grey frames, `fps` samples/second.++ Sampling rather than decoding every frame is the whole performance story:+ a 5 s 1920x1080 clip is 124 frames, and 20 of them at 320 px answer the+ question just as well for a fiftieth of the work. `format=gray` means one+ byte per pixel, so the raw stream is parsed with a single reshape and no+ colour conversion of our own.+ """+ cmd = [str(FFMPEG), "-v", "error", "-nostdin", "-i", str(path),+ "-map", "0:v:0", "-an", "-sn", "-dn",+ "-vf", f"fps={fps:g},scale={width}:{height}:flags=bicubic,format=gray",+ "-f", "rawvideo", "-pix_fmt", "gray", "-"]+ try:+ out = subprocess.run(cmd, capture_output=True, timeout=900)+ except (OSError, subprocess.SubprocessError) as exc:+ raise RuntimeError(f"ffmpeg could not decode {Path(path).name}: {exc}")+ if out.returncode != 0:+ err = (out.stderr or b"").decode("utf-8", "replace").strip()[-400:]+ raise RuntimeError(f"ffmpeg could not decode {Path(path).name}: {err}")+ stride = width * height+ n = len(out.stdout) // stride+ if n < 1:+ raise RuntimeError(f"{Path(path).name} decoded to no frames")+ buf = np.frombuffer(out.stdout[:n * stride], dtype=np.uint8)+ return buf.reshape(n, height, width)+++def _frame_metrics(frames: np.ndarray) -> dict:+ """Per-sampled-frame numbers. Everything downstream is a mean of these."""+ f = frames.astype(np.float32)+ # 4-neighbour Laplacian, done with slices rather than a convolution import.+ lap = (4.0 * f[:, 1:-1, 1:-1]+ - f[:, :-2, 1:-1] - f[:, 2:, 1:-1]+ - f[:, 1:-1, :-2] - f[:, 1:-1, 2:])+ n = f.shape[0]+ sharp = lap.reshape(n, -1).var(axis=1)+ luma = f.reshape(n, -1).mean(axis=1)+ crushed = (frames <= CRUSH_LEVEL).reshape(n, -1).mean(axis=1)+ blown = (frames >= BLOWN_LEVEL).reshape(n, -1).mean(axis=1)+ if n > 1:+ motion = np.abs(np.diff(f, axis=0)).reshape(n - 1, -1).mean(axis=1)+ # motion[i] describes the step INTO frame i, so index 0 has none;+ # repeating the first real value keeps the arrays the same length+ # without inventing movement that was never measured.+ motion = np.concatenate([motion[:1], motion])+ else:+ motion = np.zeros(1, dtype=np.float32)+ return {"sharp": sharp.astype(np.float64), "luma": luma.astype(np.float64),+ "motion": motion.astype(np.float64),+ "crushed": crushed.astype(np.float64),+ "blown": blown.astype(np.float64)}+++def _ramp(x: float, lo: float, hi: float) -> float:+ """0 below `lo`, 1 above `hi`, linear between. `hi` may be below `lo`."""+ if hi == lo:+ return 1.0 if x >= hi else 0.0+ t = (x - lo) / (hi - lo)+ return float(min(1.0, max(0.0, t)))+++def _motion_score(m: float) -> float:+ """A band, not a maximum: frozen is dead, thrashing is artefacting."""+ if m <= MOTION_DEAD or m >= MOTION_THRASH:+ return 0.0+ if m < MOTION_LOW:+ return _ramp(m, MOTION_DEAD, MOTION_LOW)+ if m > MOTION_HIGH:+ return 1.0 - _ramp(m, MOTION_HIGH, MOTION_THRASH)+ return 1.0+++def _luma_score(mean_luma: float) -> float:+ if mean_luma <= LUMA_BLACK or mean_luma >= LUMA_WHITE:+ return 0.0+ if mean_luma < LUMA_GOOD_LO:+ return _ramp(mean_luma, LUMA_BLACK, LUMA_GOOD_LO)+ if mean_luma > LUMA_GOOD_HI:+ return 1.0 - _ramp(mean_luma, LUMA_GOOD_HI, LUMA_WHITE)+ return 1.0+++def best_window(video_path, want_seconds: float, *, probe: dict | None = None,+ analysis_fps: float = ANALYSIS_FPS,+ head_guard: float = HEAD_GUARD_S,+ tail_guard: float = TAIL_GUARD_S,+ head_weight: float = HEAD_WEIGHT,+ tail_weight: float = TAIL_WEIGHT,+ weights: tuple[float, float, float] | None = None) -> dict:+ """Pick the best `want_seconds` inside one clip.++ Returns::++ {"start", "end", "score", "reason", "per_second", "components",+ "runner_up", "duration", "usable", "candidates"}++ `start`/`end` are seconds into the SOURCE clip and `end - start` is exactly+ `want_seconds` unless the clip is shorter than that, in which case the whole+ clip is returned and `reason` says so.++ The score is the weighted sum of three normalised terms (sharpness,+ stability, luma) minus the head/tail positional penalty. Sharpness is+ normalised against THIS clip's own 5th-95th percentile, so the number+ answers "which part of this clip" and must never be compared between+ clips. Stability and luma are absolute, because "frozen", "thrashing",+ "black" and "blown" mean the same thing everywhere.++ A window containing a near-black or blown-out stretch is vetoed rather+ than merely marked down; if EVERY window is vetoed the least-bad one is+ returned with `usable=False` so the caller can drop the shot instead of+ discovering the problem in the finished film.+ """+ w_sharp, w_stable, w_luma = weights or (W_SHARP, W_STABLE, W_LUMA)+ path = Path(str(video_path))+ info = probe or probe_media(path)+ if not info or _f(info.get("duration")) <= 0:+ raise RuntimeError(f"could not probe {path.name}")+ duration = float(info["duration"])+ src_w = int(info.get("w") or 0) or ANALYSIS_WIDTH+ src_h = int(info.get("h") or 0) or int(ANALYSIS_WIDTH * 9 / 16)++ aw = min(ANALYSIS_WIDTH, src_w - src_w % 2)+ ah = max(2, int(round(aw * src_h / src_w)))+ ah -= ah % 2+ frames = _decode_grey(path, aw, ah, analysis_fps)+ met = _frame_metrics(frames)+ n = frames.shape[0]+ step = 1.0 / analysis_fps+ times = np.arange(n) * step++ # Sharpness is normalised inside the clip. p05/p95 rather than min/max so+ # one glitched frame cannot define the scale.+ lo = float(np.percentile(met["sharp"], 5))+ hi = float(np.percentile(met["sharp"], 95))+ flat = (hi - lo) < 1e-6+ if flat:+ sharp_norm = np.full(n, 0.5)+ else:+ sharp_norm = np.clip((met["sharp"] - lo) / (hi - lo), 0.0, 1.0)++ per_second: list[dict] = []+ for sec in range(int(math.ceil(duration - 1e-9)) or 1):+ sel = (times >= sec) & (times < sec + 1)+ if not sel.any():+ continue+ per_second.append({+ "t": float(sec),+ "sharpness": round(float(met["sharp"][sel].mean()), 2),+ "sharpness_norm": round(float(sharp_norm[sel].mean()), 4),+ "motion": round(float(met["motion"][sel].mean()), 3),+ "luma": round(float(met["luma"][sel].mean()), 2),+ "crushed": round(float(met["crushed"][sel].mean()), 4),+ "blown": round(float(met["blown"][sel].mean()), 4),+ })++ # Asking for at least the whole clip is legal and common — the plan is+ # capacity-bound. Clamp rather than refuse, and let the normal path run so+ # the single candidate still gets a real score and real diagnostics; only+ # `forced` differs, and the reason line says so.+ want = float(want_seconds)+ if want <= 0 or want > duration:+ want = duration++ win = max(2, int(round(want * analysis_fps)))+ win = min(win, n)+ last_start = max(0, n - win)++ cands: list[dict] = []+ for i in range(last_start + 1):+ start = min(i * step, duration - want)+ start = max(0.0, round(start, 6))+ end = round(start + want, 6)+ sl = slice(i, i + win)+ m_sharp = float(sharp_norm[sl].mean())+ # motion[i] is the step INTO frame i, so the movement WITHIN the+ # window is measured from its second sample onwards.+ msl = slice(i + 1, i + win) if win > 1 else sl+ m_motion = float(met["motion"][msl].mean())+ peak_motion = float(met["motion"][msl].max())+ # The QUIETEST quarter of the window, not just its average. A window+ # that is two thirds frozen and one third moving averages into the+ # healthy band and looks fine to a mean — and plays as a still frame+ # that eventually twitches. Asking "was it alive throughout?" as well+ # as "was it alive on average?" is what separates those two.+ low_motion = float(np.percentile(met["motion"][msl], 25))+ m_luma = float(met["luma"][sl].mean())+ crushed = float(met["crushed"][sl].max())+ blown = float(met["blown"][sl].max())++ s_sharp = m_sharp+ s_stable = 0.5 * _motion_score(m_motion) + 0.5 * _motion_score(low_motion)+ # A single violent sample inside an otherwise calm window is a cut, a+ # flash or a glitch — worse than steady fast motion, so it is charged+ # separately rather than being averaged away.+ if peak_motion >= MOTION_THRASH and m_motion < MOTION_HIGH:+ s_stable *= 0.35+ s_luma = _luma_score(m_luma)++ head_over = max(0.0, min(end, head_guard) - start)+ tail_over = max(0.0, end - max(start, duration - tail_guard))+ pen = head_weight * (head_over / want) + tail_weight * (tail_over / want)++ vetoed = (m_luma <= LUMA_BLACK or m_luma >= LUMA_WHITE+ or crushed >= CRUSH_VETO or blown >= BLOWN_VETO)+ score = w_sharp * s_sharp + w_stable * s_stable + w_luma * s_luma - pen+ cands.append({+ "start": start, "end": end,+ "score": round(score, 6), "vetoed": bool(vetoed),+ "components": {+ "sharpness": round(s_sharp, 4),+ "stability": round(s_stable, 4),+ "luma": round(s_luma, 4),+ "penalty": round(pen, 4),+ "motion_raw": round(m_motion, 3),+ "motion_low": round(low_motion, 3),+ "motion_peak": round(peak_motion, 3),+ "luma_raw": round(m_luma, 2),+ "crushed_max": round(crushed, 4),+ "blown_max": round(blown, 4),+ },+ })++ # Deterministic order: not vetoed first, then score, then the EARLIER+ # start. Never a dict iteration order, never a stable-sort accident.+ ranked = sorted(cands, key=lambda c: (c["vetoed"], -c["score"], c["start"]))+ best = ranked[0]+ runner = next((c for c in ranked[1:]+ if abs(c["start"] - best["start"]) >= step - 1e-9), None)++ comp = best["components"]+ bits = [f"sharpness {comp['sharpness']:.2f}",+ f"stability {comp['stability']:.2f} ({comp['motion_raw']:.1f}/frame)",+ f"luma {comp['luma_raw']:.0f}"]+ if comp["penalty"] > 0.001:+ bits.append(f"head/tail cost {comp['penalty']:.3f}")+ reason = (f"{best['start']:.2f}-{best['end']:.2f}s scored "+ f"{best['score']:.3f} — " + ", ".join(bits))+ if last_start == 0:+ reason += (f"; the only window there is — {want:.2f}s asked of a "+ f"{duration:.2f}s clip leaves nothing to choose")+ if flat:+ reason += "; sharpness was flat across the clip, so it did not decide"+ if runner:+ reason += (f"; beat {runner['start']:.2f}s "+ f"({runner['score']:.3f}) by "+ f"{best['score'] - runner['score']:.3f}")+ if best["vetoed"]:+ reason += ("; EVERY window failed the luma check (near-black or "+ "blown) — this is the least bad one")++ return {+ "path": str(path),+ "start": best["start"], "end": best["end"],+ "score": best["score"], "usable": not best["vetoed"],+ "reason": reason, "components": comp,+ "runner_up": ({"start": runner["start"], "score": runner["score"]}+ if runner else None),+ "per_second": per_second,+ "duration": round(duration, 6),+ "forced": last_start == 0,+ "candidates": len(cands),+ }+++# ===========================================================================+# PART B — where the beats are+# ===========================================================================+def _decode_pcm(path, sr: int = AUDIO_SR,+ span: tuple[float, float] | None = None) -> np.ndarray:+ """Mono float32 in [-1, 1]. One ffmpeg call, one reshape, no resampler.++ `span` is (start, end) in seconds and is applied by ffmpeg, so analysing+ the first 90 s of an eight-minute track costs 90 s of decode, not 479.+ """+ cmd = [str(FFMPEG), "-v", "error", "-nostdin"]+ if span:+ cmd += ["-ss", f"{float(span[0]):.6f}"]+ cmd += ["-i", str(path)]+ if span:+ cmd += ["-t", f"{max(0.0, float(span[1]) - float(span[0])):.6f}"]+ cmd += ["-map", "0:a:0", "-vn", "-ac", "1", "-ar", str(sr),+ "-f", "s16le", "-acodec", "pcm_s16le", "-"]+ try:+ out = subprocess.run(cmd, capture_output=True, timeout=1800)+ except (OSError, subprocess.SubprocessError) as exc:+ raise RuntimeError(f"ffmpeg could not decode audio: {exc}")+ if out.returncode != 0:+ err = (out.stderr or b"").decode("utf-8", "replace").strip()[-400:]+ raise RuntimeError(f"ffmpeg could not decode audio: {err}")+ pcm = np.frombuffer(out.stdout[:len(out.stdout) // 2 * 2], dtype="<i2")+ if pcm.size == 0:+ raise RuntimeError(f"{Path(path).name} carries no audio")+ return (pcm.astype(np.float32) / 32768.0)+++def _onset_envelopes(x: np.ndarray, sr: int, n_fft: int = N_FFT,+ hop: int = HOP) -> tuple[np.ndarray, np.ndarray, float]:+ """Spectral flux, full band and kick band, at `sr / hop` frames a second.++ Chunked so the magnitude spectrogram of an eight-minute track never exists+ in memory all at once — only a 1-D envelope survives each chunk.+ """+ if x.size < n_fft * 2:+ raise RuntimeError("audio is too short to analyse")+ view = np.lib.stride_tricks.sliding_window_view(x, n_fft)[::hop]+ n_frames = view.shape[0]+ win = np.hanning(n_fft).astype(np.float32)+ low_bin = max(2, int(round(LOW_BAND_HZ / (sr / n_fft))) + 1)++ flux = np.zeros(n_frames, dtype=np.float32)+ flux_low = np.zeros(n_frames, dtype=np.float32)+ prev = None+ chunk = 2048+ for c0 in range(0, n_frames, chunk):+ blk = np.asarray(view[c0:c0 + chunk], dtype=np.float32) * win+ mag = np.abs(np.fft.rfft(blk, axis=1)).astype(np.float32)+ spec = np.log1p(10.0 * mag)+ if prev is None:+ d = np.diff(spec, axis=0, prepend=spec[:1])+ else:+ d = np.diff(spec, axis=0, prepend=prev[None, :])+ pos = np.maximum(d, 0.0)+ flux[c0:c0 + spec.shape[0]] = pos.sum(axis=1)+ flux_low[c0:c0 + spec.shape[0]] = pos[:, :low_bin].sum(axis=1)+ prev = spec[-1]+ frame_rate = sr / float(hop)++ def _rectify(env: np.ndarray) -> np.ndarray:+ k = max(1, int(round(0.5 * frame_rate)))+ local = np.convolve(env, np.ones(k, dtype=np.float32) / k, mode="same")+ out = np.maximum(env - local, 0.0)+ s = float(out.std())+ return (out / s) if s > 1e-9 else out++ return _rectify(flux), _rectify(flux_low), frame_rate+++def _autocorr(env: np.ndarray) -> np.ndarray:+ e = env - env.mean()+ n = e.size+ size = 1 << int(math.ceil(math.log2(max(4, 2 * n))))+ spec = np.fft.rfft(e, size)+ ac = np.fft.irfft(spec * np.conj(spec), size)[:n]+ ac /= np.arange(n, 0, -1) # unbiased-ish+ peak = ac[0]+ return ac / peak if peak > 1e-12 else ac+++def _grid_score(env: np.ndarray, frame_rate: float, period: float,+ phase: float) -> float:+ """Mean onset strength ON the grid, relative to the track's own mean.++ >1 means the grid sits on the onsets. This is what separates a real tempo+ from an autocorrelation artefact, and it is also what makes an octave+ error visible: a grid at double tempo lands half its beats on nothing.+ """+ if period <= 0:+ return 0.0+ n = env.size+ k = np.arange(int((n / frame_rate - phase) / period) + 1)+ idx = np.rint((phase + k * period) * frame_rate).astype(np.int64)+ idx = idx[(idx >= 0) & (idx < n)]+ if idx.size < 8:+ return 0.0+ base = float(env.mean())+ return float(env[idx].mean() / base) if base > 1e-9 else 0.0+++def _phase_profile(env: np.ndarray, frame_rate: float, period: float,+ nbins: int = 256) -> np.ndarray:+ """Mean onset strength as a function of phase, for ALL phases at once.++ Folding every sample into a phase bin is O(n) and answers the same+ question the naive sweep answers in O(phases x beats). It is what makes+ a two-hundred-step tempo refinement cost a tenth of a second instead of a+ minute — and the refinement is not optional: one autocorrelation lag is+ 11.6 ms at this frame rate, which is 2.4 % of a 126 BPM beat, and 2.4 %+ of tempo error is a whole beat of drift after 40 seconds of film.+ """+ if period <= 0 or env.size == 0:+ return np.zeros(nbins)+ t = np.arange(env.size, dtype=np.float64) / frame_rate+ b = np.floor((np.mod(t, period) / period) * nbins).astype(np.int64) % nbins+ total = np.bincount(b, weights=env.astype(np.float64), minlength=nbins)+ count = np.bincount(b, minlength=nbins).astype(np.float64)+ count[count == 0] = 1.0+ return total / count+++def _best_phase(env: np.ndarray, frame_rate: float, period: float,+ nbins: int = 256) -> tuple[float, float]:+ """Phase with the strongest onsets on it, then an exact local refinement."""+ prof = _phase_profile(env, frame_rate, period, nbins)+ ph = float(np.argmax(prof)) * period / nbins+ best, best_phase = _grid_score(env, frame_rate, period, ph), ph+ span = period / nbins+ for i in range(-12, 13):+ cand = (ph + span * i / 6.0) % period+ sc = _grid_score(env, frame_rate, period, cand)+ if sc > best + 1e-12:+ best, best_phase = sc, cand+ return float(best_phase % period), float(best)+++def _refine_period(env: np.ndarray, frame_rate: float, period: float,+ rel: float = 0.045, steps: int = 180) -> tuple[float, float, float]:+ """Local tempo sweep by grid score → (period, phase, score).++ Two passes: `rel` wide at `steps` resolution, then a tenth as wide. The+ grid score is extremely sensitive to tempo over a long span (drift+ accumulates), which is exactly what makes it a better final estimator than+ the autocorrelation peak that seeded it.+ """+ best = (-1.0, period, 0.0)+ for width, n in ((rel, steps), (rel / 10.0, steps // 2)):+ centre = best[1] if best[0] >= 0 else period+ for i in range(n + 1):+ p = centre * (1.0 - width) + centre * 2.0 * width * i / n+ if p <= 0:+ continue+ ph, sc = _best_phase(env, frame_rate, p)+ if sc > best[0] + 1e-12:+ best = (sc, p, ph)+ return best[1], best[2], best[0]+++def _strong_onsets(env: np.ndarray, frame_rate: float,+ count: int = 400) -> np.ndarray:+ idx = [i for i in range(1, env.size - 1)+ if env[i] >= env[i - 1] and env[i] > env[i + 1] and env[i] > 0]+ idx.sort(key=lambda i: (-float(env[i]), i))+ return np.asarray(sorted(idx[:count]), dtype=np.float64) / frame_rate+++def _phase_coherence(onsets: np.ndarray, period: float, phase: float) -> float:+ """Rayleigh vector of onset PEAK TIMES against the grid, 0…1.++ Reported, never scored. On dense percussive material it is close to zero+ even when the grid is perfect, because sixteenth-note peaks sit at four+ equally spaced phases and their unit vectors cancel exactly. It is kept+ because it is the right statistic for sparse material and because a+ reader who knows the difference should be able to see the number.+ `grid_lock_ms` below is the statistic to trust here.+ """+ if onsets.size < 8 or period <= 0:+ return 0.0+ ang = 2.0 * math.pi * ((onsets - phase) / period)+ return float(abs(np.mean(np.exp(1j * ang))))+++def _grid_lock_ms(env: np.ndarray, frame_rate: float, period: float,+ phase: float, nbins: int = 256) -> float:+ """Half-width at half-maximum of the onset-energy peak, in milliseconds.++ THE honest accuracy number. Fold the onset envelope by the period and you+ get energy as a function of phase; if the grid is real that curve has a+ spike at the beat, and its half-width says how tightly the music is+ actually locked to the grid we are about to cut on. A width approaching+ an eighth of a beat means there is no spike and the "grid" is decoration.+ """+ prof = _phase_profile(env, frame_rate, period, nbins)+ if prof.size == 0 or float(prof.max()) <= 0:+ return float("nan")+ top = int(np.argmax(prof))+ prof = np.roll(prof, -top)+ half = (float(prof[0]) + float(np.median(prof))) / 2.0+ right = 0+ while right < nbins // 2 and prof[right] > half:+ right += 1+ left = 0+ while left < nbins // 2 and prof[(-left) % nbins] > half:+ left += 1+ return float((right + left) / 2.0 * period / nbins * 1000.0)+++def _tempo_prior(bpm: float) -> float:+ return float(math.exp(-0.5 * (math.log2(bpm / BPM_PRIOR_CENTER)+ / BPM_PRIOR_OCTAVES) ** 2))+++def beat_map(audio_path, *, meter: int = DEFAULT_METER, sr: int = AUDIO_SR,+ span: tuple[float, float] | None = None) -> dict:+ """Tempo, beat grid and downbeats for a soundtrack.++ Returns::++ {"bpm", "beats": [t…], "downbeats": [t…], "confidence",+ "period", "phase", "meter", "span", "duration", "diagnostics"}++ `span` is (start, end) in seconds and limits BOTH the analysis and the+ beats returned. That is not a performance shortcut, it is a correctness+ one: the model here is ONE constant tempo, and real tracks — generated+ ones especially — drift. Fitting a single BPM across eight minutes buys a+ grid that is wrong at both ends; fitting it across the ninety seconds you+ are actually cutting buys one that is right where it is used. Beats are+ never extrapolated past the fitted span, so a caller that asks for a cut+ beyond it gets "no beat here" rather than a confident wrong answer.++ `confidence` is built from four independent pieces of evidence, all of+ which are in `diagnostics`:++ * `pulse_ratio` — onset strength on the grid over onset strength+ everywhere. 1.0 means the grid is no better than chance.+ * `acf_salience` — how far the winning autocorrelation lag stands above+ the rest of the searched range, in standard deviations.+ * `octave_margin` — how far the winning tempo beat its own half, double+ and two-thirds. A small margin is the classic 63-vs-126 ambiguity and+ it is reported, not hidden.+ * `grid_lock_ms` — the half-width of the onset-energy spike at the+ beat. Ten milliseconds means the music really is locked to this grid;+ a width approaching an eighth of a beat means it is decoration.++ And `tempo_drift_bpm` compares the first half of the span with the second.+ A non-zero drift is the constant-tempo model admitting its own limit.+ """+ t0 = float(span[0]) if span else 0.0+ x = _decode_pcm(audio_path, sr, span)+ duration = x.size / float(sr)+ env, env_low, frame_rate = _onset_envelopes(x, sr)++ ac = _autocorr(env)+ lag_lo = max(2, int(math.floor(60.0 / BPM_MAX * frame_rate)))+ lag_hi = min(ac.size - 2, int(math.ceil(60.0 / BPM_MIN * frame_rate)))+ if lag_hi <= lag_lo:+ raise RuntimeError("audio is too short for a tempo estimate")+ band = ac[lag_lo:lag_hi + 1]++ peaks = [i for i in range(1, band.size - 1)+ if band[i] >= band[i - 1] and band[i] > band[i + 1]]+ if not peaks:+ peaks = [int(np.argmax(band))]+ peaks.sort(key=lambda i: (-float(band[i]), i))++ # Hypotheses: the strongest autocorrelation peaks, plus each one's octave+ # and triplet relatives. The relatives matter because a 3:2 confusion+ # (126 heard as 84) is the failure this corpus actually produces, and the+ # autocorrelation often carries only one of the pair.+ hypotheses: list[float] = []+ for i in peaks[:6]:+ base = (lag_lo + i) / frame_rate+ for mult in (0.5, 2.0 / 3.0, 1.0, 1.5, 2.0):+ p = base * mult+ bpm = 60.0 / p+ if BPM_MIN <= bpm <= BPM_MAX and all(abs(p - q) > 1e-3+ for q in hypotheses):+ hypotheses.append(p)++ onsets = _strong_onsets(env, frame_rate)+ scored = []+ for p0 in hypotheses:+ period, phase, grid = _refine_period(env, frame_rate, p0)+ bpm = 60.0 / period+ if not (BPM_MIN <= bpm <= BPM_MAX):+ continue+ prior = _tempo_prior(bpm)+ # Onset energy ON the grid, times a log-normal tempo prior. The prior+ # is what stops the half-tempo grid from winning by explaining fewer+ # onsets more strongly; the refinement above is what makes the grid+ # score trustworthy enough to be compared at all.+ scored.append({"period": period, "bpm": bpm, "phase": phase,+ "grid": grid, "prior": prior,+ "coherence": _phase_coherence(onsets, period, phase),+ "final": grid * prior})+ if not scored:+ raise RuntimeError("no usable tempo hypothesis")+ scored.sort(key=lambda s: (-s["final"], -s["bpm"]))+ win = scored[0]+ period, phase = win["period"], win["phase"]++ # Evidence.+ li = int(round(period * frame_rate))+ acf_at = float(ac[li]) if lag_lo <= li <= lag_hi else float(band.max())+ salience = (acf_at - float(band.mean())) / (float(band.std()) + 1e-9)+ rivals = [s["final"] for s in scored[1:]+ if abs(math.log2(s["bpm"] / win["bpm"])) > 0.25]+ octave_margin = (1.0 - max(rivals) / win["final"]+ if rivals and win["final"] > 1e-9 else 1.0)++ # Drift: the constant-tempo model checking itself. Each half is refined+ # around the winner, narrowly, so this measures drift and not a re-run of+ # the octave argument.+ half = env.size // 2+ drift = None+ if half > int(20 * frame_rate):+ p_a, _, _ = _refine_period(env[:half], frame_rate, period,+ rel=0.02, steps=80)+ p_b, _, _ = _refine_period(env[half:], frame_rate, period,+ rel=0.02, steps=80)+ drift = round(60.0 / p_b - 60.0 / p_a, 3)++ # Frame f of the envelope describes samples [f*hop, f*hop + n_fft), and is+ # timestamped at f/frame_rate — the window's START. A click at time T+ # therefore raises the flux at roughly T - n_fft/sr, so the grid computed+ # above sits systematically EARLY by about half a window once the Hann+ # taper is accounted for. Everything internal is consistent in that frame,+ # so the correction belongs here, once, on the times that leave: shift the+ # phase to the window's centre. Measured residual on a synthetic click+ # track after this correction: about 10 ms, a quarter of a video frame at+ # 24 fps.+ lead = N_FFT / (2.0 * sr)+ n_beats = int((duration - phase) / period) + 1+ local = [phase + k * period for k in range(max(0, n_beats))]+ beats = [round(t0 + b + lead, 6) for b in local+ if b + lead <= duration + 1e-9]++ # Downbeat phase: which of the `meter` beat classes carries the kick.+ downbeat_offset, best_low = 0, -1.0+ idx_all = np.rint(np.asarray(local[:len(beats)]) * frame_rate).astype(np.int64)+ idx_all = idx_all[(idx_all >= 0) & (idx_all < env_low.size)]+ for off in range(meter):+ sel = idx_all[off::meter]+ if sel.size < 4:+ continue+ v = float(env_low[sel].mean())+ if v > best_low + 1e-12:+ best_low, downbeat_offset = v, off+ downbeats = beats[downbeat_offset::meter]++ lock_ms = _grid_lock_ms(env, frame_rate, period, phase)+ pulse_ratio = float(win["grid"])+ c_pulse = min(1.0, max(0.0, (pulse_ratio - 1.0) / 2.0))+ c_sal = 1.0 - math.exp(-max(0.0, salience) / 3.0)+ c_oct = min(1.0, max(0.0, octave_margin))+ # An eighth of a beat is the width at which "on the grid" stops meaning+ # anything, so that is the scale the lock is measured against.+ c_lock = (1.0 - min(1.0, lock_ms / (period * 1000.0 / 8.0))+ if lock_ms == lock_ms else 0.0)+ confidence = round(0.3 * c_pulse + 0.25 * c_sal + 0.2 * c_oct+ + 0.25 * c_lock, 4)++ return {+ "bpm": round(60.0 / period, 4),+ "period": round(period, 8),+ "phase": round(t0 + phase + lead, 6),+ "meter": meter,+ "beats": beats,+ "downbeats": downbeats,+ "confidence": confidence,+ "span": [round(t0, 4), round(t0 + duration, 4)],+ "duration": round(duration, 4),+ "diagnostics": {+ "pulse_ratio": round(pulse_ratio, 4),+ "acf_salience": round(float(salience), 4),+ "octave_margin": round(float(octave_margin), 4),+ "grid_lock_ms": round(lock_ms, 2) if lock_ms == lock_ms else None,+ "coherence": round(float(win["coherence"]), 4),+ "tempo_drift_bpm": drift,+ "beat_ms": round(period * 1000.0, 2),+ "n_beats": len(beats),+ "n_downbeats": len(downbeats),+ "downbeat_offset": downbeat_offset,+ "frame_rate": round(frame_rate, 4),+ "n_onsets": int(onsets.size),+ "runners_up": [{"bpm": round(s["bpm"], 3),+ "grid": round(s["grid"], 4),+ "coherence": round(s["coherence"], 4),+ "final": round(s["final"], 4)}+ for s in scored[1:4]],+ },+ }+++def audio_span_for(target_seconds: float | None) -> tuple[float, float] | None:+ """The stretch of music a film of `target_seconds` should be fitted to.++ One definition, used by `plan_cut()` and by the CLI, so a plan built two+ different ways is built against the same grid. The 1.5x + 10 s margin+ covers a cut that overruns its target and keeps the grid from ending+ mid-film; it is not tuned, it is simply generous.+ """+ if not target_seconds or target_seconds <= 0:+ return None+ return (0.0, float(target_seconds) * 1.5 + 10.0)+++def snap(t: float, beats, max_shift: float) -> float:+ """Nearest beat within `max_shift`, else `t` unchanged.++ Bisection, not a scan — `plan_cut()` calls this once per candidate cut+ against a thousand-beat grid, and a linear search there is the difference+ between instant and noticeable.+ """+ t = float(t)+ if not beats or max_shift is None or max_shift <= 0:+ return t+ arr = list(beats)+ i = bisect.bisect_left(arr, t)+ best, dist = None, None+ for j in (i - 1, i, i + 1):+ if 0 <= j < len(arr):+ d = abs(arr[j] - t)+ # `<` keeps the EARLIER beat when a cut falls exactly between two.+ if dist is None or d < dist - 1e-12:+ best, dist = float(arr[j]), d+ # Inclusive of its own edge, with a float-comparison margin: a tolerance+ # of exactly half a beat has to accept a cut exactly half a beat away, or+ # the caller's arithmetic and this function's disagree at the boundary.+ if best is None or dist > float(max_shift) + 1e-9:+ return t+ return best+++# ===========================================================================+# PART C — the cut plan+# ===========================================================================+def _snap_in_range(t: float, grid, tol: float,+ lo: float, hi: float) -> float | None:+ """Closest grid point to `t` that is ALSO inside [lo, hi]. None if there+ is none.++ This is `snap()` with the planner's constraints folded in, and it is a+ different function on purpose. `snap()` looks at the nearest beat and+ stops — which is the right public contract, and exactly wrong here: the+ nearest downbeat to a wanted cut is very often one that would make the+ shot longer than the clip, and answering "no beat then" would leave a cut+ unsnapped while a perfectly good beat sat 200 ms away. So this walks+ outward from `t` and returns the first candidate that satisfies both the+ tolerance and the shot-length limits. Ties break EARLIER, so the plan is+ the same every time.+ """+ if grid is None or tol is None or tol <= 0 or hi < lo:+ return None+ arr = list(grid)+ if not arr:+ return None+ left = max(lo, t - float(tol))+ right = min(hi, t + float(tol))+ if right < left:+ return None+ i = bisect.bisect_left(arr, left - 1e-9)+ best, dist = None, None+ while i < len(arr) and arr[i] <= right + 1e-9:+ d = abs(arr[i] - t)+ if dist is None or d < dist - 1e-12:+ best, dist = float(arr[i]), d+ i += 1+ return best+++def _balance(avail: list[float], target: float, min_shot: float) -> list[float]:+ """Split `target` over the clips without asking any clip for more than it+ has, and without producing a shot below `min_shot`.++ Water-filling: scale everything to the target, clamp to+ [min_shot, available], hand the deficit or surplus back to the clips that+ still have room, repeat. Bounded to eight passes so it always terminates.+ """+ n = len(avail)+ if n == 0:+ return []+ want = [min(a, target / n) for a in avail]+ for _ in range(8):+ total = sum(want)+ if abs(total - target) < 1e-6:+ break+ room = [(avail[i] - want[i]) if total < target+ else (want[i] - min_shot) for i in range(n)]+ room = [max(0.0, r) for r in room]+ pool = sum(room)+ if pool <= 1e-9:+ break+ delta = target - total+ for i in range(n):+ want[i] += delta * (room[i] / pool)+ want = [min(avail[i], max(min(min_shot, avail[i]), want[i]))+ for i in range(n)]+ return want+++def plan_cut(clips, *, audio=None, target_seconds: float | None = None,+ min_shot: float = 1.5, max_shot: float | None = None,+ meter: int = DEFAULT_METER,+ downbeat_tolerance: float | None = None,+ beat_tolerance: float | None = None,+ min_confidence: float = 0.0,+ audio_span: tuple[float, float] | None = None,+ window_kwargs: dict | None = None,+ probes: dict | None = None) -> list[dict]:+ """Turn a list of clips into a cut a human can read and ffmpeg can execute.++ `clips` is paths (str/Path) or dicts carrying at least `path`. `audio` is a+ soundtrack path, an already-computed `beat_map()` result, or None. The+ returned list is one entry per clip, IN THE ORDER GIVEN — this plans the+ edit, it does not reorder the film:++ {"n", "path", "start", "end", "duration", # what to play+ "film_start", "film_end", # where it lands+ "snap": {"kind", "wanted", "landed", "shift_ms"},+ "window": {"score", "reason", "components", "runner_up", "usable"},+ "notes": [...]}++ Boundaries prefer downbeats, fall back to beats, and fall back again to the+ unsnapped time — and every one of those says which it was and by how many+ milliseconds it moved, because "beat-aligned" is a claim, and a claim needs+ a number next to it.++ `min_shot` is never violated by the snapping: a candidate cut that would+ make the shot too short is not a candidate. The one exception is a source+ clip shorter than `min_shot`, which is used whole and flagged in `notes`.++ When `audio` is a PATH and `target_seconds` is known, the beat grid is+ fitted to the stretch of music the film will actually cover (plus a+ margin), not to the whole track — see `beat_map`'s `span`. A single+ constant tempo fitted across eight minutes of a generated track is a+ compromise at both ends; fitted across the ninety seconds being cut it is+ right where it is used. Pass `audio_span` to override, or hand in a+ pre-computed beat map to take full control.+ """+ items: list[dict] = []+ for c in clips:+ if isinstance(c, dict):+ items.append({"path": str(c.get("path")), "probe": c.get("probe")})+ else:+ items.append({"path": str(c), "probe": None})+ if not items:+ return []++ for it in items:+ if not it["probe"] and probes:+ it["probe"] = probes.get(it["path"])+ if not it["probe"]:+ it["probe"] = probe_media(it["path"])+ if not it["probe"]:+ raise RuntimeError(f"could not probe {Path(it['path']).name}")++ # ---- the music ------------------------------------------------------+ bm: dict | None = None+ music_note: list[str] = []+ if audio is not None:+ if isinstance(audio, dict):+ bm = audio+ else:+ span = audio_span or audio_span_for(target_seconds)+ bm = beat_map(audio, meter=meter, span=span)+ if bm.get("confidence", 0.0) < min_confidence:+ music_note.append(+ f"beat confidence {bm.get('confidence'):.2f} is below the "+ f"{min_confidence:.2f} the caller asked for — cutting "+ f"unsnapped rather than cutting to a grid we do not trust")+ bm = None+ period = float(bm["period"]) if bm else 0.0+ bar = period * meter if bm else 0.0+ if bm:+ if downbeat_tolerance is None:+ downbeat_tolerance = bar / 2.0+ if beat_tolerance is None:+ # A WHOLE beat, not half of one. Half a beat is the tolerance you+ # want when a cut can land anywhere; here it cannot — the shot may+ # not outrun its clip — and the nearest beat under that ceiling is+ # frequently just past half a beat away. With the tight tolerance+ # those cuts fell through to "unsnapped", and a film that lands+ # every other cut on the grid reads worse than one that lands all+ # of them a beat early. One beat is also the worst case for shot+ # length: 474 ms off a five-second shot.+ beat_tolerance = period++ # ---- how long each shot wants to be ---------------------------------+ durations = [float(it["probe"]["duration"]) for it in items]+ avail = [min(d, max_shot) if max_shot else d for d in durations]+ if target_seconds and target_seconds > 0:+ want = _balance(avail, float(target_seconds), min_shot)+ else:+ want = list(avail)++ # ---- walk the timeline, placing every cut ---------------------------+ plan: list[dict] = []+ cursor = 0.0+ for i, it in enumerate(items):+ notes: list[str] = list(music_note) if i == 0 else []+ src_dur = durations[i]+ lo = min_shot+ hi = avail[i]+ if hi < lo:+ notes.append(f"source is only {src_dur:.2f}s — shorter than the "+ f"{min_shot:.2f}s minimum, so it is used whole")+ lo = hi+ wanted_end = cursor + min(hi, max(lo, want[i]))++ kind, landed = "none", wanted_end+ if bm:+ cand = _snap_in_range(wanted_end, bm["downbeats"],+ downbeat_tolerance,+ cursor + lo, cursor + hi)+ if cand is not None:+ kind, landed = "downbeat", cand+ else:+ cand = _snap_in_range(wanted_end, bm["beats"], beat_tolerance,+ cursor + lo, cursor + hi)+ if cand is not None:+ kind, landed = "beat", cand+ else:+ notes.append("no beat inside tolerance that also respects "+ "the shot-length limits — left unsnapped")+ shot = max(lo, min(hi, landed - cursor))+ landed = cursor + shot+ shot = round(shot, 6)++ win = best_window(it["path"], shot, probe=it["probe"],+ **(window_kwargs or {}))+ # best_window returns the whole clip when there is nothing to choose;+ # honour the plan's length rather than the clip's in that case.+ start = float(win["start"])+ if win.get("forced") and (win["end"] - win["start"]) > shot:+ start = min(start, max(0.0, src_dur - shot))+ end = round(start + shot, 6)+ if end > src_dur + 1e-6:+ start = max(0.0, round(src_dur - shot, 6))+ end = round(start + shot, 6)+ if not win.get("usable", True):+ notes.append("every window in this clip failed the luma check")++ plan.append({+ "n": i + 1,+ "path": it["path"],+ # Free — the probe that read this clip's geometry read its streams+ # too. The timeline's audio lane needs it to tell a clip with no+ # sound from one whose sound is simply linked to its picture.+ "has_audio": bool((it.get("probe") or {}).get("has_audio")),+ "start": round(start, 6),+ "end": round(end, 6),+ "duration": shot,+ "film_start": round(cursor, 6),+ "film_end": round(landed, 6),+ "snap": {"kind": kind,+ "wanted": round(wanted_end, 6),+ "landed": round(landed, 6),+ "shift_ms": round((landed - wanted_end) * 1000.0, 2)},+ "window": {"score": win["score"], "reason": win["reason"],+ "components": win["components"],+ "runner_up": win["runner_up"],+ "usable": win.get("usable", True),+ "source_duration": round(src_dur, 6),+ "slack": round(max(0.0, src_dur - shot), 6)},+ "per_second": win.get("per_second", []),+ "notes": notes,+ })+ cursor = landed+ return plan+++def plan_total(plan: list[dict]) -> float:+ return round(sum(float(p["duration"]) for p in plan), 6)+++def format_plan(plan: list[dict], beats: dict | None = None) -> str:+ """The plan as text, for a manifest or a terminal. No colour, no cleverness."""+ out: list[str] = []+ if beats:+ d = beats.get("diagnostics", {})+ out.append(f"Music: {beats['bpm']:.2f} BPM, {beats['meter']}/4, "+ f"beat {d.get('beat_ms')} ms, confidence "+ f"{beats['confidence']:.2f} "+ f"(pulse {d.get('pulse_ratio')}, salience "+ f"{d.get('acf_salience')}, octave margin "+ f"{d.get('octave_margin')}, onset energy locked to "+ f"+/-{d.get('grid_lock_ms')} ms)")+ out.append(f"{len(plan)} shots, {plan_total(plan):.3f} s total")+ out.append("")+ out.append(f"{'#':>2} {'shot':<34} {'window':<16} {'len':>6} "+ f"{'at':>7} {'snap':<9} {'shift':>8} score")+ for p in plan:+ name = Path(p["path"]).name+ if len(name) > 34:+ name = name[:31] + "..."+ out.append(f"{p['n']:>2} {name:<34} "+ f"{p['start']:>6.2f}-{p['end']:<6.2f} "+ f"{p['duration']:>6.3f} {p['film_start']:>7.3f} "+ f"{p['snap']['kind']:<9} "+ f"{p['snap']['shift_ms']:>7.0f}ms "+ f"{p['window']['score']:.3f}")+ out.append("")+ for p in plan:+ out.append(f"S{p['n']:02d} {Path(p['path']).name}")+ out.append(f" {p['window']['reason']}")+ for note in p["notes"]:+ out.append(f" NOTE: {note}")+ return "\n".join(out)+++# ===========================================================================+# CLI — the same three questions, from a terminal+# ===========================================================================+def _main(argv: list[str]) -> int:+ import argparse # noqa: PLC0415++ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ sub = ap.add_subparsers(dest="cmd", required=True)++ w = sub.add_parser("window", help="best window inside one clip")+ w.add_argument("clip")+ w.add_argument("seconds", type=float)+ w.add_argument("--json", action="store_true")++ b = sub.add_parser("beats", help="tempo + beat grid for a soundtrack")+ b.add_argument("audio")+ b.add_argument("--span", type=float,+ help="analyse only the first N seconds (see beat_map)")+ b.add_argument("--json", action="store_true")++ p = sub.add_parser("plan", help="a cut plan for a list of clips")+ p.add_argument("clips", nargs="+")+ p.add_argument("--audio")+ p.add_argument("--span", type=float,+ help="fit the beat grid to the first N seconds only")+ p.add_argument("--target", type=float)+ p.add_argument("--min-shot", type=float, default=1.5)+ p.add_argument("--max-shot", type=float)+ p.add_argument("--json", action="store_true")++ a = ap.parse_args(argv)+ if a.cmd == "window":+ res = best_window(a.clip, a.seconds)+ if a.json:+ print(json.dumps(res, indent=2))+ else:+ print(f"{Path(a.clip).name}: {res['start']:.3f}-{res['end']:.3f}s")+ print(f" {res['reason']}")+ return 0+ if a.cmd == "beats":+ res = beat_map(a.audio, span=(0.0, a.span) if a.span else None)+ if a.json:+ slim = dict(res)+ slim["beats"] = res["beats"][:16]+ slim["downbeats"] = res["downbeats"][:8]+ print(json.dumps(slim, indent=2))+ else:+ d = res["diagnostics"]+ print(f"{res['bpm']:.2f} BPM confidence {res['confidence']:.2f} "+ f"{d['n_beats']} beats, {d['n_downbeats']} downbeats")+ print(f" pulse {d['pulse_ratio']} salience {d['acf_salience']} "+ f"octave margin {d['octave_margin']} "+ f"lock +/-{d['grid_lock_ms']} ms")+ print(f" onset energy peaks within {d['grid_lock_ms']} ms of the grid"+ + (f", tempo drifts {d['tempo_drift_bpm']:+.2f} BPM across "+ f"the analysed span" if d.get("tempo_drift_bpm") else ""))+ return 0+ bm = (beat_map(a.audio, span=((0.0, a.span) if a.span+ else audio_span_for(a.target)))+ if a.audio else None)+ plan = plan_cut(a.clips, audio=bm, target_seconds=a.target,+ min_shot=a.min_shot, max_shot=a.max_shot)+ if a.json:+ print(json.dumps(plan, indent=2))+ else:+ print(format_plan(plan, bm))+ return 0+++if __name__ == "__main__":+ import sys # noqa: PLC0415+ raise SystemExit(_main(sys.argv[1:]))diff --git a/storyboard_editor.py b/storyboard_editor.pynew file mode 100644index 0000000..4fde666--- /dev/null+++ b/storyboard_editor.py@@ -0,0 +1,4278 @@+#!/usr/bin/env python3+"""The timeline editor's SERVER SIDE — proxies, peaks, and `edit.json`.++WHY THIS EXISTS+---------------+`storyboard_edit.py` answers "which seconds are good" and "where are the+beats". It produces a PLAN — a one-shot artefact, computed and consumed in the+same breath by the exporter. That is enough for an auto-edit and nowhere near+enough for a timeline a human can drag.++Three things have to exist before a browser can show a timeline at all, and+none of them belong in the panel's HTTP handler:++1. **PROXIES, and they are not an optimisation.** Measured on this corpus:+ our rendered clips contain exactly ONE keyframe — the whole clip is a+ single GOP — so a browser asked to seek to t=3.2 s must decode from frame+ zero. Chrome takes a **235 ms median, 1266 ms p90** to do it. Against an+ all-intra proxy the same seek is **3.5 ms**. A timeline is a machine for+ seeking; at a quarter of a second per scrub there is no timeline, there is+ a slideshow that apologises. Measured on ten AURELIUS clips (56.25 s of+ 1024x576): 0.14 s of ffmpeg and 1.45 MB of proxy per 10 s of video, and+ the result really is all-intra — 123 keyframes in a 123-frame proxy,+ against 1 in its source. That trade is not close.++2. **WAVEFORM PEAKS, computed here.** A five-minute track decoded in the+ browser is ~85 MB of Float32Array before a single pixel is drawn. The same+ track reduced to min/max pairs at 100 buckets a second is 697 bytes per+ second of audio — 326 KB for the 479 s AMOR_FATI master, produced in+ 0.42 s of numpy. The client draws; it does not decode.++3. **`edit.json`, which is NOT the storyboard.** The board is INTENT — the+ shots the film wants to contain, one entry per thing to render. The edit is+ ARRANGEMENT — what plays, from which second of which file, at which second+ of the film. They are the same list exactly until the first time somebody+ uses one shot twice or splits one in half, and then they are different+ shapes forever. Merging them would mean the render queue and the timeline+ fighting over one array. So: two files, side by side, `storyboard.json` and+ `edit.json`, and one function (`edit_from_plan`) that derives the second+ from the first when there isn't one yet.++WHAT THIS MODULE WILL NOT DO+----------------------------+It opens no sockets, imports nothing from `mlx_ltx_panel`, and runs no+subprocess of its own except ffprobe-free peak decoding through+`storyboard_edit`. Proxy building is expressed as an ARGV LIST that the panel+runs through its own `run_ffmpeg_tracked`, because the panel owns process+groups, cancellation and the log pane, and a module that shells out behind the+panel's back is a module that cannot be stopped.++DEPENDENCIES: numpy and the standard library. Same constraint, same reason, as+`storyboard_edit.py`.+"""++from __future__ import annotations++import hashlib+import json+import math+import os+import re+import tempfile+import threading+import time+from pathlib import Path++import numpy as np++__all__ = [+ "EDIT_VERSION", "PEAKS_VERSION", "PROXY_RECIPE_VERSION",+ "CLIP_KINDS", "BRIGHTNESS_LIMIT",+ "proxy_dir", "proxy_fingerprint", "proxy_name", "proxy_cmd",+ "plan_proxies", "prune_proxies",+ "peaks_path", "compute_peaks", "save_peaks", "load_peaks",+ "clip_peaks_path", "clip_peaks", "prune_clip_peaks",+ "edit_path", "load_edit", "save_edit", "validate_edit", "normalise_edit",+ "migrate_edit", "clip_kind", "clip_brightness", "clip_carries_media",+ "clip_audio", "clip_audio_drift", "clip_audio_resync", "clip_muted",+ "clip_effects", "clip_length",+ "audio_effects", "audio_gain_points", "audio_gain_at",+ "MIX_BED_GAIN", "MIX_DUCK", "MIX_LEGACY_BED_GAIN", "MIX_DUCK_GAIN",+ "MIX_DUCK_ATTACK", "MIX_DUCK_RELEASE", "MIX_CEILING",+ "MIX_REPAIR_VERSION", "audio_mix", "bed_length", "audible_strips",+ "bed_duck_points", "bed_duck_suppressed", "bed_gain_points",+ "bed_gain_at", "bed_render_gain", "heal_mix",+ "overlay_items", "overlay_kind", "OVERLAY_SUFFIXES",+ "blocking_errors", "WARNING_CODES", "repair_audio_overlaps",+ "edit_digest", "session_token_path", "claim_session", "current_session",+ "session_is_current", "SESSION_STALE_AFTER",+ "edit_from_plan", "edit_to_cuts", "edit_duration", "edit_gaps",+ "edit_sync_flags",+ "music_window", "new_clip", "EditError", "EditConflict",+ "board_write_lock", "on_disk_revision",+ "history_dir", "archive_edit", "prune_history", "list_history",+ "restore_edit",+ "drafts_dir", "load_draft_index", "list_drafts", "create_draft",+ "duplicate_draft", "rename_draft", "delete_draft", "activate_draft",+ "write_backup", "pending_backup", "recover_backup", "discard_backup",+ "DRAFT_NAME_MAX",+ "export_nle", "NLE_FPS",+ "film_fps", "frame_seconds", "quantise_gap", "heal_subframe_gaps",+]+++# 2 (2026-08-18) — clips grew `kind` and `adjust`. The bump is not decoration:+# `validate_edit` HARD-REFUSES any version it does not recognise, so a v2+# document opened by an older Phosphene stops loudly instead of silently+# dropping every slug and sliding the whole film off its beats. The read path+# upgrades v1 in place (`migrate_edit`), so nothing anyone has already cut has+# to be touched or re-saved.+EDIT_VERSION = 2+PEAKS_VERSION = 1++# WHAT A CLIP CAN BE. Three, and the list is closed on purpose:+# video — a file with a picture and a source window. What the machine made.+# still — an image held for the length of its slot. What the machine cannot+# make: a title card, a photograph, a beat of nothing moving.+# slug — black, for a duration, with no file at all. Descript calls it a gap+# clip; it is the primitive the render used to apologise for not+# having ("N gap(s) … were closed by the concatenation").+# An ABSENT kind is a video, so every edit.json ever written is already valid.+CLIP_KINDS = ("video", "still", "slug")++# The one adjustment. ffmpeg's `eq=brightness` is an ADDITIVE offset in+# [-1, 1]; half of that range is already past "this shot is unusable" in both+# directions, and a clamp the validator enforces is what stops a typo in a+# saved document from rendering an hour of white.+BRIGHTNESS_LIMIT = 0.5++# Bumped whenever the proxy RECIPE changes. It is part of the content hash, so+# a bump rebuilds every proxy on the next prepare instead of leaving a mixed+# population of old and new files that all look equally valid.+PROXY_RECIPE_VERSION = 3++# 640 was chosen for seek speed and it made the preview look like a bad stream:+# the stage is ~1360 px wide on a normal window, so a 640-wide proxy was being+# upscaled >2x and the owner read it, correctly, as "the quality is pretty bad".+# All-intra is what makes seeking fast, not the pixel count — 1280 costs bytes+# on disk and nothing in seek latency.+PROXY_WIDTH = 1280+PROXY_CRF = "23"+PROXY_PRESET = "veryfast"+PROXY_PIX_FMT = "yuv420p"+PROXY_ABITRATE = "96k" # proxy audio: intelligible, not archival++PEAKS_BUCKETS_PER_SECOND = 100+PEAKS_SCALE = 127 # peaks are ints in [-127, 127]+PEAKS_SR = 22050++# A timeline clip's source window and its slot on the film must be the same+# length — nothing here plays at anything but 1x. One millisecond of slack+# absorbs float rounding through JSON and no more.+# How many past saves each film keeps in history/. Fifty debounced saves at+# ~5 KB each is a quarter-megabyte for a full working session — nothing, next+# to what losing one good arrangement costs.+EDIT_HISTORY_KEEP = 50++LENGTH_TOLERANCE = 0.002+# Two clips that overlap by less than a frame at 24 fps are touching, not+# overlapping; the UI's drag maths lands there constantly.+TOUCH_TOLERANCE = 1.0 / 48.0++# Codes `validate_edit` reports but NO writer may refuse on. A warning is a+# note on a document that is going to disk either way — the rule is that+# persisting the user's work always wins, because the alternative was a red+# banner over an afternoon of cutting that could not be stored anywhere.+WARNING_CODES = frozenset({"clips_audio_overlap"})+++class EditError(Exception):+ """Raised for an edit that must not be written. Message is user-facing."""+++class EditConflict(EditError):+ """The document moved on between the caller's read and its write.++ A SUBCLASS SO NOBODY HAS TO CATCH IT TO STAY CORRECT: every existing+ `except EditError` around a save still refuses the write and still shows a+ sentence. A caller that WANTS to tell "somebody else got there first" from+ "this document is invalid" catches this first and reads `.revision`, which+ is what is actually on disk right now.+ """++ def __init__(self, message: str, *, revision: int = 0) -> None:+ super().__init__(message)+ self.revision = int(revision)+++def _f(x, default: float = 0.0) -> float:+ try:+ v = float(x)+ except (TypeError, ValueError):+ return default+ if v != v or v in (float("inf"), float("-inf")):+ return default+ return v+++def _slug(text: str, limit: int = 40) -> str:+ s = re.sub(r"[^a-zA-Z0-9]+", "-", str(text or "")).strip("-").lower()+ return (s[:limit] or "clip").strip("-") or "clip"+++# The suffixes the media pool itself accepts as pictures, plus the two the+# overlay lane's own resolver already reads. One list, so a file that is a+# still on one lane cannot be a video on the other.+STILL_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff")+++def _looks_like_a_still(path) -> bool:+ return str(path or "").strip().lower().endswith(STILL_SUFFIXES)+++def clip_kind(clip) -> str:+ """`video` | `still` | `slug`. ABSENT IS `video`, and that is the migration.++ Every clip in every edit.json written before 2026-08-18 has no `kind`, and+ every one of them is a video. Reading the default here rather than stamping+ it on disk means a v1 document is v2-correct the moment it is loaded, with+ no rewrite pass and nothing to go wrong halfway through one.+ """+ if not isinstance(clip, dict):+ return "video"+ k = str(clip.get("kind") or "").strip().lower()+ if k in CLIP_KINDS:+ return k+ # ABSENT NO LONGER MEANS VIDEO ON ITS OWN. The paragraph above was true+ # while only renders reached the picture lane; a pool image can land here+ # now, and an unstamped .png answered "video" — which handed a still to a+ # <video> element (format error, black stage) and to the concat graph.+ # The overlay lane has always read the suffix when the field is absent+ # (`sbeOvKind`); this is the same rule, so the two lanes cannot disagree.+ # A pre-2026-08-18 document is unaffected: its clips are all .mp4.+ if _looks_like_a_still(clip.get("path")):+ return "still"+ return "video"+++def clip_carries_media(clip) -> bool:+ """Does this clip point at a file on disk?++ A slug does not — it is `color=black` in the filtergraph and nothing else —+ which is why proxy planning, relink and the media-pool round trip all have+ to ask before they touch `clip["path"]`.+ """+ return clip_kind(clip) in ("video", "still")+++def clip_brightness(clip) -> float:+ """`adjust.brightness`, clamped, or 0.0 — the neutral that renders nothing.++ Zero is not "apply eq=brightness=0", it is "insert no filter at all", so an+ untouched clip's segment in the graph stays byte-identical to the graph+ that existed before adjustments did.+ """+ if not isinstance(clip, dict):+ return 0.0+ adj = clip.get("adjust")+ if not isinstance(adj, dict):+ return 0.0+ b = _f(adj.get("brightness"), 0.0)+ return max(-BRIGHTNESS_LIMIT, min(BRIGHTNESS_LIMIT, b))+++def clip_audio(clip) -> dict:+ """The clip's SOUND window: `{start, end, film_start, linked}`.++ THE J-CUT AND THE L-CUT, and they are the same feature. The owner: "like a+ normal video editor... the sound attached to every clip... in case I want+ to move the clip, cut a little bit of the image, but leave the sound below+ and then connect it to make better transitions." And again: "you can edit+ dialogue in a way that you hear her voice while you're seeing him... I+ need to be able to leave some of the audio and drag only the image."++ ABSENT MEANS LINKED, and that is the whole migration: every clip ever+ written has no `audio` key and every one of them plays its own sound under+ its own picture. So EDIT_VERSION does not move, no document is rewritten,+ and a clip only carries the field once somebody has actually pulled the+ two apart.++ NOT A SECOND AUDIO TRACK. The refuse list still holds: one video track,+ one music lane, and per-clip sound that is linked by default. The audio+ windows may not overlap each other any more than the pictures may — a+ split edit is a butt join that lands somewhere else, not a mix.+ """+ if not isinstance(clip, dict):+ return {"start": 0.0, "end": 0.0, "film_start": 0.0,+ "linked": True, "coupled": False, "split": False}+ vs, ve = _f(clip.get("start")), _f(clip.get("end"))+ fs = _f(clip.get("film_start"))+ a = clip.get("audio")+ if not isinstance(a, dict) or clip_kind(clip) != "video":+ return {"start": round(vs, 6), "end": round(ve, 6),+ "film_start": round(fs, 6),+ "linked": True, "coupled": False, "split": False}+ # THE PRESENCE OF THE FIELD IS THE SWITCH, not the values in it. Deriving+ # "linked" from equality looked tidier and was wrong in the one case that+ # matters: unlinking writes the window the clip already has, so a clip the+ # user had just unlinked read as linked and refused to be dragged. The+ # toggle adds the object or deletes it; nothing else decides.+ #+ # ...AND `audio.linked` IS THE THIRD STATE. Re-linking used to DELETE the+ # field, which snapped the sound back under the picture and threw away the+ # J-cut the user had just built. The owner, describing what he wanted:+ # "You just drag it, and the sound below stays, and then you can lock it+ # and move it, and then the sound starts before the clip starts." So+ # re-linking now FREEZES the relationship instead: the window stays, the+ # flag says the two travel together, and the pair moves as one from then+ # on. Absent still means linked-and-in-sync, so no document written before+ # today changes and an in-sync re-link still deletes the field outright.+ s = _f(a.get("start"), vs)+ e = _f(a.get("end"), ve)+ f = _f(a.get("film_start"), fs)+ coupled = a.get("linked") is True+ return {"start": round(s, 6), "end": round(e, 6),+ "film_start": round(f, 6),+ # `linked` has always meant "this strip cannot be dragged on its+ # own", and that is true of a coupled pair too.+ "linked": coupled, "coupled": coupled, "split": True}+++def clip_muted(clip) -> bool:+ """Is this clip's OWN sound silenced? `mute: true`, and nothing else.++ THE OWNER'S CASE: "We should have an option to mute the clip sound." An H3+ shot arrives with baked-in wind and ambience under the line, and on a music+ cut that is not a performance to be balanced — it is noise to be removed so+ the track can carry the moment.++ NOT THE SAME AS `has_audio: false`, which says the FILE has no audio track+ and is a fact about the source. This is a decision about the edit, and the+ two are painted differently for that reason.++ NOT THE SAME AS UNLINKING EITHER, and it composes with it in both+ directions: a J-cut can be muted (the strip stays where it was put, and is+ silent), and a muted clip can then be unlinked and slid. `mute` describes+ the sound wherever its strip happens to be.++ ABSENT IS AUDIBLE, the same migration `audio` gets: every clip ever written+ plays its own sound, so EDIT_VERSION does not move and nothing is rewritten+ until somebody actually presses the button.+ """+ if not isinstance(clip, dict):+ return False+ return clip.get("mute") is True and clip_kind(clip) == "video"+++def clip_length(clip) -> float:+ """How long this clip plays. The film slot and the source window agree."""+ if not isinstance(clip, dict):+ return 0.0+ n = _f(clip.get("film_end")) - _f(clip.get("film_start"))+ if n <= 0:+ n = _f(clip.get("end")) - _f(clip.get("start"))+ return max(0.0, round(n, 6))+++def clip_effects(clip) -> dict:+ """THE ONE ACCESSOR. `{fade_in, fade_out, brightness}`, whatever the storage.++ See docs/EDITOR_EFFECTS_MODEL.md. `clip.fx` is the home for effects and+ absent means none, so no document ever written has to change and+ EDIT_VERSION does not move.++ BRIGHTNESS IS THE ONE LEGACY CITIZEN. It predates the model and stays at+ `clip.adjust.brightness` — a label is not worth a data migration, the same+ reasoning that kept `film_start` when the user-facing noun became+ "sequence". What changes is that "where is it stored" stops being a+ question any consumer has to answer: every output reads this and nothing+ else, so the next effect picks its storage on its own merits instead of+ adding a fourth code path.++ THE CLAMP LIVES HERE so all three outputs are handed numbers that are+ already legal. Two fades that crossed would ask ffmpeg for an opacity that+ is two things at once and would hand the NLEs keyframes out of order.+ """+ c = clip if isinstance(clip, dict) else {}+ fx = c.get("fx")+ fx = fx if isinstance(fx, dict) else {}+ n = clip_length(c)+ fin = max(0.0, _f(fx.get("fade_in")))+ fout = max(0.0, _f(fx.get("fade_out")))+ if n > 0:+ fin, fout = min(fin, n), min(fout, n)+ over = fin + fout - n+ if over > 0:+ # Give the overrun back proportionally rather than truncating one+ # of them: an edit that asked for two long fades meant "mostly+ # ramp", and silently zeroing the out-fade is not that.+ total = fin + fout+ fin, fout = fin - over * (fin / total), fout - over * (fout / total)+ return {"fade_in": round(fin, 6), "fade_out": round(fout, 6),+ "brightness": clip_brightness(c)}+++# ---------------------------------------------------------------------------+# THE OVERLAY LANE — a SECOND video track, above the picture+# ---------------------------------------------------------------------------+# WHY ITS OWN LIST AND NOT A `kind` ON `clips`. The picture lane is ONE track+# and `validate_edit` refuses any two clips that overlap on it — that rule is+# what stops a concat from being handed two pictures for the same second. An+# overlay's whole purpose is to sit ON one of them, so putting overlays in the+# same list would mean weakening the rule that keeps the picture lane honest.+# A second list keeps both rules exact: pictures may not overlap each other,+# overlays may not overlap each other, and an overlay over a picture is not an+# overlap at all — it is the feature.+#+# The owner's case: an endcard PNG with real transparency, laid over the last+# seconds of the pull-out so the card sits in the sky.+OVERLAY_SUFFIXES = (".png", ".webp", ".tif", ".tiff")+++def overlay_kind(item) -> str:+ """`still` or `video`. A card is a still; a matte or a loop is a video."""+ if not isinstance(item, dict):+ return "still"+ k = str(item.get("kind") or "").strip().lower()+ if k in ("still", "video"):+ return k+ return "still" if str(item.get("path") or "").lower().endswith(+ OVERLAY_SUFFIXES) else "video"+++def overlay_items(edit) -> list[dict]:+ """The overlay lane, in film order. Absent is an empty lane."""+ rows = (edit or {}).get("overlays")+ if not isinstance(rows, list):+ return []+ out = [o for o in rows if isinstance(o, dict)]+ out.sort(key=lambda o: (_f(o.get("film_start")), str(o.get("id") or "")))+ return out+++# ---------------------------------------------------------------------------+# THE SOUND'S OWN ENVELOPE — fades, and the keyframes underneath them+# ---------------------------------------------------------------------------+# "Fading and fade-out with keyframes should be very simple and intuitive for+# the sound as well."+#+# BOTH, FROM ONE MODEL. `fade_in`/`fade_out` are the simple case and the only+# thing the corner handles touch; `points` are the control case. They are not+# two features with two code paths — `audio_gain_points()` folds the fades into+# the point list and returns ONE breakpoint curve, and the preview, the render+# and the export all read that. So the simple case never has to discover+# keyframes, and a keyframed envelope never has to be re-expressed.+#+# `t` IS STRIP-RELATIVE SECONDS, never film seconds: a J-cut that slides its+# sound half a second earlier must not move every keyframe with it. Gain is+# LINEAR 0..1, because that is what ffmpeg's `volume` takes and what a level+# line on a strip means; dB is an export-time concern.+def audio_effects(item, length: float = 0.0) -> dict:+ """`{fade_in, fade_out, points}` for a strip or the bed. Clamped."""+ it = item if isinstance(item, dict) else {}+ afx = it.get("afx")+ afx = afx if isinstance(afx, dict) else {}+ n = max(0.0, _f(length))+ fin = max(0.0, _f(afx.get("fade_in")))+ fout = max(0.0, _f(afx.get("fade_out")))+ if n > 0:+ fin, fout = min(fin, n), min(fout, n)+ over = fin + fout - n+ if over > 0:+ total = fin + fout+ fin, fout = fin - over * (fin / total), fout - over * (fout / total)+ pts = []+ for row in (afx.get("points") or []):+ if not isinstance(row, (list, tuple)) or len(row) != 2:+ continue+ t, g = _f(row[0]), _f(row[1])+ if t != t or g != g:+ continue+ if n > 0:+ t = max(0.0, min(n, t))+ pts.append([round(max(0.0, t), 6), round(max(0.0, min(1.0, g)), 6)])+ pts.sort(key=lambda r: r[0])+ return {"fade_in": round(fin, 6), "fade_out": round(fout, 6),+ "points": pts}+++def _lerp_gain(pts, t: float) -> float:+ """The point curve at `t`. No points is a flat 1.0."""+ if not pts:+ return 1.0+ if t <= pts[0][0]:+ return pts[0][1]+ if t >= pts[-1][0]:+ return pts[-1][1]+ for (t0, g0), (t1, g1) in zip(pts, pts[1:]):+ if t0 <= t <= t1:+ if t1 - t0 <= 1e-9:+ return g1+ return g0 + (g1 - g0) * ((t - t0) / (t1 - t0))+ return pts[-1][1]+++def audio_gain_points(item, length: float) -> list[list[float]]:+ """THE ONE CURVE: `[[t, gain], ...]` with the fades folded in.++ Every output reads this and nothing else, so a fade and a keyframe cannot+ disagree about what the sound does. Breakpoints are the union of the+ envelope's own points and the fade corners, each multiplied by the fade+ factor there — which is what makes a fade and a keyframed dip compose+ instead of one overriding the other.+ """+ n = max(0.0, _f(length))+ if n <= 0:+ return []+ e = audio_effects(item, n)+ fin, fout, pts = e["fade_in"], e["fade_out"], e["points"]+ marks = {0.0, n}+ for t, _ in pts:+ marks.add(min(n, max(0.0, t)))+ if fin > 1e-9:+ marks.add(fin)+ if fout > 1e-9:+ marks.add(max(0.0, n - fout))+ out = []+ for t in sorted(marks):+ g = _lerp_gain(pts, t)+ if fin > 1e-9 and t < fin:+ g *= t / fin+ if fout > 1e-9 and t > n - fout:+ g *= max(0.0, (n - t) / fout)+ out.append([round(t, 6), round(max(0.0, min(1.0, g)), 6)])+ # A FLAT UNITY CURVE IS NO CURVE. Saying "the volume is 1 the whole way"+ # would put a filter in every graph to express nothing.+ if all(abs(g - 1.0) < 1e-9 for _, g in out):+ return []+ return out+++def audio_gain_at(item, length: float, t: float) -> float:+ """The gain at one second. The preview's per-frame answer."""+ curve = audio_gain_points(item, length)+ if not curve:+ return 1.0+ return round(_lerp_gain(curve, max(0.0, _f(t))), 6)+++# ---------------------------------------------------------------------------+# THE MIX — the bed's level, and what happens to it under a line+# ---------------------------------------------------------------------------+# THE DEFECT THIS CLOSES: the renderer was a SECOND AUTHOR of the soundtrack's+# level, and an invisible one. Under `mode: "under"` the ffmpeg graph held the+# bed at a hard-coded 0.20 (-14 dB) and then pushed it down a further ~11 dB+# through a `sidechaincompress` keyed on the clips' own audio — two decisions+# nobody made, in no document, on no screen. The preview applied neither, so+# the one surface the user checks his work on played a mix the file never had:+# "when you render it, there are some weird manipulations... the volume of the+# music goes low when the dialogue appears."+#+# The duck's own comment defended itself by saying it kept lines intelligible+# "without anybody automating a volume curve by hand". That was true when it+# was written and is false now — the bed and the strips both carry fades,+# keyframes and level lines, so the renderer is overriding numbers the user+# explicitly authored. Same shape as the save model's two-writers-no-rule.+#+# So the mix is a MODEL, and `docs/EDITOR_EFFECTS_MODEL.md` decides its shape:+# if the preview and the render can disagree about a gain, that gain is not in+# the model. A compressor's output is not a value in a document — it is a+# function of samples the browser never sees — so the duck is expressed the+# way every other effect here is: as a curve derived from the document, read+# identically by the preview, the ffmpeg render and (were it ever wanted) the+# NLE export. `bed_gain_points` is the one accessor, the way `clip_effects`+# and `audio_gain_points` are for their subjects.++# What a NEW timeline gets, and it is the honest one: the bed plays at the+# level the file is at, and nothing moves it.+MIX_BED_GAIN = 1.0+MIX_DUCK = False++# What the renderer USED to do to every `under` mix, with nobody's consent.+# `migrate_edit` writes this pair onto documents that predate the controls, so+# a film the owner has already approved keeps the levels it was approved at —+# the difference being that now they are on screen and he can change them.+MIX_LEGACY_BED_GAIN = 0.2++# HOW FAR THE BED STEPS BACK, and the numbers are the measured ones. The old+# `sidechaincompress` was tuned on a gated-tone rig (tone-under-tone, band+# split so neither leaked into the other's reading): threshold 0.04 / ratio 8+# measured 5.8 dB, which is not enough to hear under a line; 0.01 / 20+# measured 17.7 dB, which audibly pumps; 0.02 / 10 measured **11.4 dB** with+# the bed returning to full level between lines, which is the broadcast range.+# 11.4 dB down is a linear 0.269, so that is the depth the envelope uses and+# the reason it is not a round number.+MIX_DUCK_GAIN = 0.269+# Fast in so the bed is already down on the first syllable; slow out so it+# does not pump between the words of a sentence. Same pair as the compressor's+# attack/release, in seconds.+MIX_DUCK_ATTACK = 0.005+MIX_DUCK_RELEASE = 0.4++# THE SAFETY LIMITER, and it is NOT an artistic choice — it is the only thing+# standing between a hot line over a bed and a hard-clipped output. `amix`+# runs with `normalize=0` (halving both inputs to protect a headroom budget we+# have already set deliberately would be worse), so nothing else protects the+# sum: engine dialogue comes out at 0.35 RMS, and dialogue plus bed peaked the+# first under-mix film at 1.31 pre-encode with 1341 hard-clipped samples and+# not a word said about it. A THRESHOLD, not a ceiling — tanh saturates+# smoothly above it, so the true peak lands a little over (0.9 measured 0.98+# on the real film) while nothing hard-clips.+MIX_CEILING = 0.9++# THE MIX HEAL IS A ONE-TIME STAMP, so it needs a marker — unlike the+# sub-frame gap heal, which is arithmetic that finds nothing to do on a second+# run. Without the marker, a user who deliberately set the bed back to 1.0 and+# switched the duck off would have `normalise_edit` drop the now-neutral `mix`+# key and the next READ would helpfully put 0.20-and-ducked back: the rival+# author this whole file exists to remove, wearing a repair's clothes.+MIX_REPAIR_VERSION = 1+++def audio_mix(audio) -> dict:+ """THE ONE ACCESSOR for the mix: `{bed_gain, duck}`, whatever the storage.++ Absent means the new default, which is "play the track and leave it+ alone". Every consumer reads this and nothing else, so "is there a mix+ block on this document" stops being a question anybody has to answer.+ """+ a = audio if isinstance(audio, dict) else {}+ m = a.get("mix")+ m = m if isinstance(m, dict) else {}+ g = m.get("bed_gain")+ gain = MIX_BED_GAIN if g is None else max(0.0, min(1.0, _f(g)))+ d = m.get("duck")+ return {"bed_gain": round(gain, 6),+ "duck": MIX_DUCK if d is None else bool(d)}+++def bed_length(audio, film_len: float = 0.0) -> float:+ """How many seconds of the bed actually PLAY. The bed envelope's clock.++ THE BED'S ENVELOPE IS ON THE PLAYED WINDOW, not on the track, exactly as a+ clip strip's envelope is on the strip and not on the source file. Zero is+ the first second you hear, so trimming the head does not slide every+ keyframe with it and a fade dragged onto the block's corner means the+ corner it was dragged onto.++ THE FILM IS THE FALLBACK CLOCK, and this is the whole of the fix for the+ one shape the first mix pass left behind. A soundtrack whose document says+ nothing about how long the track is — no `duration`, no `trim_end` — used+ to make this return 0, which made `bed_gain_points` return an EMPTY curve,+ which means "no filter", which means the render played the bed at UNITY+ under the dialogue while the preview's own model drew it 19.6 dB lower.+ Silence-by-empty-curve is the one behaviour nobody asked for and it is the+ LOUD one, which is what made it dangerous rather than merely wrong.++ The honest reading of a bed with no stated length is that it plays under+ the FILM: the renderer trims the mix to the film anyway, so the last second+ anybody hears is the film's last second. That is a number both the browser+ and the render can compute from the same document, which is the only test+ a value in this model has to pass. `film_len` is `edit_duration(edit)` —+ the timeline's clock — and it is only ever consulted when the track's own+ length is absent.+ """+ a = audio if isinstance(audio, dict) else {}+ w = music_window(a)+ end = w["end"]+ if end is None:+ end = _f(a.get("duration"))+ if end <= 0:+ # WHAT REMAINS OF THE FILM after the bed starts, not the film's+ # whole length: a track that comes in at 0:04 of a six-second film+ # is heard for two seconds, and its envelope's clock is those two.+ return round(max(0.0, _f(film_len) - w["film_start"]), 6)+ return round(max(0.0, _f(end) - w["start"]), 6)+++def audible_strips(edit) -> list[list[float]]:+ """The film seconds where a clip's OWN sound is playing: `[[start, end]]`.++ What the duck is keyed on, and the whole reason it can be a document value+ at all. A compressor asks "are these samples loud"; this asks "is there a+ sound strip here", which is a question the document answers and the+ browser can answer too. A clip with no audio track (`has_audio` false) and+ a MUTED clip are both silence — neither contributes a lane to the render,+ so neither may duck anything.++ Windows are merged when they touch, overlap, or sit closer together than+ one release: a bed that recovered fully in the eighth of a second between+ two lines would pump, which is the failure the release time exists to+ prevent, and merging is also what keeps the returned list non-overlapping+ so the curve built from it has its knots exactly at the marks.+ """+ wins: list[list[float]] = []+ for c in (edit or {}).get("clips") or []:+ if not isinstance(c, dict) or clip_kind(c) != "video":+ continue+ if c.get("has_audio") is False or clip_muted(c):+ continue+ w = clip_audio(c)+ s = _f(w["film_start"])+ e = s + max(0.0, _f(w["end"]) - _f(w["start"]))+ if e - s > 1e-9:+ wins.append([round(s, 6), round(e, 6)])+ wins.sort()+ out: list[list[float]] = []+ for s, e in wins:+ if out and s - out[-1][1] < MIX_DUCK_RELEASE - 1e-9:+ out[-1][1] = max(out[-1][1], e)+ else:+ out.append([s, e])+ return out+++def _duck_gain_at(wins, t: float) -> float:+ """The duck's value at one second, from the merged windows. Piecewise."""+ g = 1.0+ for s, e in wins:+ if t < s - 1e-9:+ continue+ if t <= e + 1e-9:+ k = 1.0 if MIX_DUCK_ATTACK <= 0 else min(1.0, (t - s) / MIX_DUCK_ATTACK)+ v = 1.0 - (1.0 - MIX_DUCK_GAIN) * max(0.0, k)+ else:+ k = 1.0 if MIX_DUCK_RELEASE <= 0 else (t - e) / MIX_DUCK_RELEASE+ if k >= 1.0:+ continue+ v = MIX_DUCK_GAIN + (1.0 - MIX_DUCK_GAIN) * k+ g = min(g, v)+ return max(0.0, min(1.0, g))+++def bed_duck_points(edit, length: float, delay: float = 0.0) -> list[list[float]]:+ """The auto-duck as a breakpoint curve on the BED's clock.++ `delay` is the film second the bed starts at, so the windows — which are+ in film seconds — land on the bed's own zero. Knots go exactly where the+ function bends: each window's start, the end of its attack, its end, and+ the end of its release. Because `audible_strips` has already merged+ anything closer than one release, no release ramp ever meets the next+ attack, so linear interpolation between these knots is the function+ EXACTLY rather than an approximation of it.+ """+ n = max(0.0, _f(length))+ if n <= 0:+ return []+ d = _f(delay)+ wins = [[s - d, e - d] for s, e in audible_strips(edit)]+ wins = [[s, e] for s, e in wins if e > 0 and s < n]+ if not wins:+ return []+ marks = {0.0, round(n, 6)}+ for s, e in wins:+ for m in (s, s + MIX_DUCK_ATTACK, e, e + MIX_DUCK_RELEASE):+ if -1e-9 <= m <= n + 1e-9:+ marks.add(round(max(0.0, min(n, m)), 6))+ out = [[t, round(_duck_gain_at(wins, t), 6)] for t in sorted(marks)]+ if all(abs(g - 1.0) < 1e-9 for _, g in out):+ return []+ return out+++def bed_duck_suppressed(edit) -> bool:+ """True when the duck is switched on but an authored envelope outranks it.++ THE PRECEDENCE RULE, and the reason it is a rule rather than a product:+ two curves multiplied together is exactly the invisible-second-author+ defect this model exists to remove, one layer up. A person who has drawn+ the bed's level has said what the bed does; an automatic curve that then+ moved it would be the renderer disagreeing with them again.+ """+ aud = (edit or {}).get("audio")+ if not isinstance(aud, dict):+ return False+ if not audio_mix(aud)["duck"]:+ return False+ return bool(audio_gain_points(aud, bed_length(aud, edit_duration(edit))))+++def bed_gain_points(edit) -> list[list[float]]:+ """THE ONE BED CURVE: `[[t, gain], ...]` on the bed's own clock.++ Preview, render and export read this and nothing else, so there is no+ second place a gain can come from. Three terms, and the order they compose+ in is the whole of the precedence:++ 1. `bed_gain` — a STATIC fader. Always applied. A scalar is not a curve;+ it is the number under the track head, and multiplying an envelope by+ a fader is what a fader IS in every mixer ever built.+ 2. The AUTHORED envelope (`audio.afx`) — always applied when it exists.+ 3. The AUTO-DUCK — applied ONLY when there is no authored envelope. See+ `bed_duck_suppressed`: never two curves at once, ever.++ An empty list means unity, and unity means NO FILTER — the same rule+ `audio_gain_points` follows, so a timeline nobody has mixed builds the+ identical ffmpeg graph it always did.+ """+ aud = (edit or {}).get("audio")+ if not isinstance(aud, dict) or not aud.get("path"):+ return []+ # THE FILM IS THE CLOCK WHEN THE TRACK WILL NOT SAY. See `bed_length`: a+ # bed of unknown length plays under the film, ducked as the document says,+ # rather than falling through an empty curve to full level.+ n = bed_length(aud, edit_duration(edit))+ if n <= 0:+ return []+ mix = audio_mix(aud)+ curve = audio_gain_points(aud, n)+ if not curve and mix["duck"]:+ curve = bed_duck_points(edit, n, music_window(aud)["delay"])+ g0 = mix["bed_gain"]+ if not curve:+ if abs(g0 - 1.0) < 1e-9:+ return []+ return [[0.0, round(g0, 6)], [round(n, 6), round(g0, 6)]]+ return [[t, round(max(0.0, min(1.0, g * g0)), 6)] for t, g in curve]+++def bed_gain_at(edit, t: float) -> float:+ """The bed's gain at one second of its own clock. The preview's answer."""+ curve = bed_gain_points(edit)+ if not curve:+ return 1.0+ return round(_lerp_gain(curve, max(0.0, _f(t))), 6)+++def bed_render_gain(edit) -> list[list[float]]:+ """The same curve on the FILM's clock — what the render's `volume` sees.++ The bed lane's chain is `atrim, asetpts, adelay, aresample, apad, atrim,+ asetpts`, and after that `t` is FILM seconds from zero. The bed's own zero+ is film second `delay`, so the one conversion between the two clocks lives+ here rather than in the renderer, where it would be a second opinion about+ what the curve means.+ """+ curve = bed_gain_points(edit)+ if not curve:+ return []+ d = music_window((edit or {}).get("audio") or {})["delay"]+ return [[round(t + d, 6), g] for t, g in curve]+++def clip_audio_drift(clip) -> float:+ """How far an UNLINKED sound has drifted from the picture it came from.++ Both halves map film time to source time with a single constant — the+ clip's `film_start - start`, the strip's `audio.film_start - audio.start` —+ so the difference between the two constants is the number an NLE prints on+ its sync flag. POSITIVE means the sound plays LATE against the frame it was+ recorded with; zero means the strip is exactly where the picture would have+ played it. A linked clip cannot drift, by construction.++ DRIFT IS NOT AN ERROR. A J-cut IS a deliberate drift and the document is+ valid either way — this is the same kind of answer `edit_gaps` gives, so+ the panel can show the offset and offer to close it.+ """+ w = clip_audio(clip)+ if not w["split"]:+ return 0.0+ c = clip if isinstance(clip, dict) else {}+ return round((w["film_start"] - w["start"])+ - (_f(c.get("film_start")) - _f(c.get("start"))), 6)+++def clip_audio_resync(clip) -> float:+ """The film second an unlinked strip has to start at to be in sync again.++ The strip keeps its own IN-POINT — re-matching is not un-trimming — so the+ answer is "where does that source second play now that the picture has+ moved", which is the picture's own mapping applied to `audio.start`.+ """+ w = clip_audio(clip)+ c = clip if isinstance(clip, dict) else {}+ return round(_f(c.get("film_start")) + (w["start"] - _f(c.get("start"))), 6)+++# ===========================================================================+# PART A — proxies+# ===========================================================================+def proxy_dir(board_dir) -> Path:+ """`<board>/proxy/`. Not created here — `plan_proxies` does that."""+ return Path(str(board_dir)) / "proxy"+++def proxy_fingerprint(src) -> str:+ """Content address for one source clip: path + mtime + size + recipe.++ NOT a hash of the file's bytes. Hashing 150 clips of 30 MB each to decide+ whether to rebuild a 7 MB proxy costs more than rebuilding all of them, and+ the panel's own outputs are write-once — a clip whose mtime and size are+ unchanged is the same clip. The recipe version is in the hash so changing+ the proxy settings invalidates every proxy exactly once, by construction.++ A missing file gets a fingerprint too (mtime and size read as 0), so the+ caller can plan the work and let ffmpeg produce the honest error.+ """+ p = Path(str(src))+ try:+ st = p.stat()+ mtime_ns, size = st.st_mtime_ns, st.st_size+ except OSError:+ mtime_ns, size = 0, 0+ raw = f"{p.resolve() if p.exists() else p}\0{mtime_ns}\0{size}\0{PROXY_RECIPE_VERSION}"+ return hashlib.sha1(raw.encode("utf-8", "replace")).hexdigest()[:12]+++def proxy_name(src) -> str:+ """`<slug-of-the-source-name>_<fingerprint>.mp4`.++ The slug is decoration for a human reading the folder; the fingerprint is+ the identity. Two different sources that happen to share a basename get+ different files, and the same source rebuilt at the same mtime gets the+ same name — which is what makes reuse a `Path.is_file()` check rather than+ a manifest that can go stale.+ """+ p = Path(str(src))+ return f"{_slug(p.stem)}_{proxy_fingerprint(p)}.mp4"+++def proxy_cmd(ffmpeg, src, dest, *, width: int = PROXY_WIDTH) -> list[str]:+ """The argv for ONE proxy. All-intra, small, picture only.++ `-g 1` (with `keyint_min=1` and `sc_threshold=0`, because libx264 will+ otherwise still make its own decisions) is the entire point: every frame is+ an I-frame, so a seek decodes exactly one frame instead of the whole clip.+ That is what turns a 235 ms scrub into a 3.5 ms one.++ `-bf 0` removes B-frames so display order and decode order are the same —+ a browser seeking backwards through B-pyramids re-reads more than it needs.++ AUDIO IS CARRIED (recipe v2). It was dropped on the reasoning that "the+ timeline's sound is the soundtrack" — true for a music video, wrong for+ everything else. On a dialogue film the clips ARE the performance, so a+ silent preview cannot tell you whether a cut lands on the line or halfway+ through the word. Reported by the owner cutting a dialogue short: "when you+ play the videos, they don't have sound."++ `0:a:0?` is optional on purpose — a clip with no audio track must still+ produce a proxy rather than failing the whole prepare. AAC at 96k is+ intelligible and costs a few hundred KB across a film.+ """+ return [+ str(ffmpeg), "-y", "-v", "error", "-nostdin",+ "-i", str(src),+ "-map", "0:v:0", "-map", "0:a:0?", "-sn", "-dn",+ "-c:a", "aac", "-b:a", PROXY_ABITRATE, "-ac", "2",+ # -2 keeps the height even (H.264 4:2:0 has no odd-dimension form) and+ # preserves the source aspect: a proxy that is a different SHAPE from+ # its source would put the playhead over the wrong part of the picture.+ #+ # min(width, iw) NEVER UPSCALES. Engine output is commonly 1024 wide, so+ # a flat `scale=1280` would spend bytes and encode time inventing detail+ # that is not in the source, and the preview would look no better for it.+ # Downscale-only: the proxy is either the source size or smaller.+ "-vf", f"scale='min({int(width)},iw)':-2:flags=bicubic",+ "-c:v", "libx264",+ "-g", "1", "-keyint_min", "1", "-sc_threshold", "0", "-bf", "0",+ "-crf", PROXY_CRF, "-preset", PROXY_PRESET,+ "-pix_fmt", PROXY_PIX_FMT,+ "-movflags", "+faststart",+ str(dest),+ ]+++def plan_proxies(clips, board_dir, *, width: int = PROXY_WIDTH) -> dict:+ """Decide what to build, what to reuse, and what is now junk.++ Returns::++ {"dir": Path, "width": int,+ "build": [{"path", "proxy", "name"}], # in the order given+ "reuse": [{"path", "proxy", "name"}],+ "stale": [Path]} # files to delete++ Deduplicated by fingerprint: a board that uses one shot three times builds+ ONE proxy. `stale` is every mp4 in the proxy directory that no live clip+ points at — which is exactly the set a re-render or a deleted shot leaves+ behind, and the only reason the folder does not grow forever.+ """+ d = proxy_dir(board_dir)+ build: list[dict] = []+ reuse: list[dict] = []+ wanted: set[str] = set()+ for c in clips:+ # A SLUG IS NOT A FILE and a still is not a seek. Neither has anything+ # an all-intra proxy could speed up — the slug has no source at all and+ # the still is one frame a browser paints from an <img> — so building+ # one would spend ffmpeg on a video nothing will ever play, and,+ # worse, put a name in `wanted` that a later prune would have to keep.+ if isinstance(c, dict) and clip_kind(c) != "video":+ continue+ raw = c.get("path") if isinstance(c, dict) else c+ if not raw:+ continue+ src = Path(str(raw))+ name = proxy_name(src)+ if name in wanted:+ continue+ wanted.add(name)+ row = {"path": str(src), "name": name, "proxy": str(d / name)}+ (reuse if (d / name).is_file() else build).append(row)+ stale = []+ if d.is_dir():+ for f in sorted(d.iterdir()):+ if f.is_file() and f.suffix == ".mp4" and f.name not in wanted:+ stale.append(f)+ return {"dir": d, "width": int(width), "build": build,+ "reuse": reuse, "stale": stale}+++def prune_proxies(stale) -> int:+ """Delete the files `plan_proxies` called junk. Never raises."""+ n = 0+ for f in stale or []:+ try:+ Path(str(f)).unlink()+ n += 1+ except OSError:+ continue+ return n+++# ===========================================================================+# PART B — waveform peaks+# ===========================================================================+def peaks_path(board_dir) -> Path:+ return Path(str(board_dir)) / "peaks.json"+++def compute_peaks(audio_path, *,+ buckets_per_second: int = PEAKS_BUCKETS_PER_SECOND,+ sr: int = PEAKS_SR, decoder=None) -> dict:+ """Min/max pairs for a soundtrack, at `buckets_per_second` a second.++ Returns::++ {"version", "path", "duration", "sample_rate", "buckets_per_second",+ "count", "scale", "peaks": [min0, max0, min1, max1, ...]}++ Interleaved rather than two arrays because it halves the JSON punctuation,+ and integer rather than float because three characters per value instead of+ eighteen is the difference between 36 KB and 400 KB for the same picture. A+ waveform is drawn at one pixel per bucket; nothing downstream can see more+ precision than `scale` provides.++ `decoder` exists for tests and for a caller that already has the PCM;+ by default this uses `storyboard_edit._decode_pcm`, the same one ffmpeg+ call the beat tracker makes, so a board never decodes its track twice with+ two different resamplers.+ """+ if decoder is None:+ import storyboard_edit as sedit # noqa: PLC0415+ decoder = lambda p, rate: sedit._decode_pcm(p, rate) # noqa: E731+ x = np.asarray(decoder(str(audio_path), sr), dtype=np.float32)+ if x.size == 0:+ raise EditError(f"{Path(str(audio_path)).name} carries no audio")+ bps = max(1, int(buckets_per_second))+ per = max(1, int(round(sr / float(bps))))+ n = int(x.size // per)+ if n < 1:+ n, per = 1, int(x.size)+ trimmed = x[:n * per].reshape(n, per)+ lo = np.clip(trimmed.min(axis=1) * PEAKS_SCALE, -PEAKS_SCALE, PEAKS_SCALE)+ hi = np.clip(trimmed.max(axis=1) * PEAKS_SCALE, -PEAKS_SCALE, PEAKS_SCALE)+ inter = np.empty(n * 2, dtype=np.int16)+ inter[0::2] = np.rint(lo).astype(np.int16)+ inter[1::2] = np.rint(hi).astype(np.int16)+ return {+ "version": PEAKS_VERSION,+ "path": str(audio_path),+ "duration": round(x.size / float(sr), 6),+ "sample_rate": int(sr),+ "buckets_per_second": round(sr / float(per), 6),+ "count": int(n),+ "scale": PEAKS_SCALE,+ "peaks": [int(v) for v in inter],+ }+++def save_peaks(board_dir, peaks: dict) -> Path:+ # COMPACT, not pretty. `indent=2` puts every one of ~96,000 integers on its+ # own line and turns a 345 KB file into 795 KB — measured, on the real+ # 479 s track. Nobody reads a waveform by hand; the edit next door is the+ # document, this is data.+ return _atomic_json(peaks_path(board_dir), peaks, prefix=".peaks-",+ indent=None)+++def _same_file(a, b) -> bool:+ """Do these two strings name the same file? RESOLVED, not compared.++ `mlx_outputs/` is a symlink into Pinokio's shared drive, so the very same+ soundtrack is spelled two ways — `…/phosphene-dev.git/mlx_outputs/x.wav`+ and `…/drive/drives/peers/…/mlx_outputs/x.wav` — depending on which side+ wrote it down. A raw string compare called those different files and would+ have blanked the waveform on boards where nothing had changed at all: the+ invalidation fix, arriving as a worse bug than the one it fixed.+ """+ sa, sb = str(a or "").strip(), str(b or "").strip()+ if not sa or not sb:+ return sa == sb+ if sa == sb:+ return True+ try:+ return Path(sa).resolve() == Path(sb).resolve()+ except OSError:+ return False+++def load_peaks(board_dir, *, path=None) -> dict | None:+ """The cached waveform, or None — INCLUDING when it is about another file.++ `peaks.json` records the track it was computed from. After the owner+ swapped the soundtrack the strip went on reading "44.99s" under a+ different file, because nothing compared the two: a cache that outlives+ its subject is not a cache, it is a wrong answer with a timestamp. A+ caller that knows which track is on the timeline passes it, and a+ disagreement reads as "no waveform yet" — which is true, and which the+ prepare step already knows how to fix.+ """+ p = peaks_path(board_dir)+ if not p.is_file():+ return None+ try:+ data = json.loads(p.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ if not isinstance(data, dict):+ return None+ want = str(path or "").strip()+ if want and not _same_file(data.get("path"), want):+ return None+ return data+++# ===========================================================================+# PART C — edit.json+# ===========================================================================+# ---------------------------------------------------------------------------+# PER-SOURCE WAVEFORMS — the same machinery the bed uses, one file per take+# ---------------------------------------------------------------------------+# A strip with no waveform is a rectangle you have to play to understand. The+# bed has had one since the lane existed; the clips' own sound — the thing you+# are actually cutting on a dialogue film — did not.+#+# ONE FILE PER SOURCE, NOT PER CLIP. The same take used twice draws the same+# waveform, and the strip decides which SLICE of it to show from its own source+# window — so trimming a strip re-slices rather than recomputing, and a J-cut+# that slides its sound shows the seconds it actually plays instead of the+# picture's.+#+# The name carries `proxy_fingerprint`, which is already path + mtime + size:+# a re-rendered take gets a new name and the stale one is simply never asked+# for again, so there is no invalidation to get wrong.+def clip_peaks_dir(board_dir) -> Path:+ return Path(str(board_dir)) / "peaks"+++def clip_peaks_path(board_dir, src) -> Path:+ p = Path(str(src))+ return clip_peaks_dir(board_dir) / f"{_slug(p.stem, 32)}_{proxy_fingerprint(p)}.json"+++def clip_peaks(board_dir, src, *, decoder=None,+ buckets_per_second: int = PEAKS_BUCKETS_PER_SECOND) -> dict:+ """The waveform for ONE source, cached beside the board.++ Raises `EditError` when the file has no audio, which is a fact about the+ take and not a failure: the lane already draws that state.+ """+ dst = clip_peaks_path(board_dir, src)+ got = _read_json(dst) if dst.is_file() else None+ if isinstance(got, dict) and got.get("peaks") is not None:+ return got+ data = compute_peaks(src, buckets_per_second=buckets_per_second,+ decoder=decoder)+ dst.parent.mkdir(parents=True, exist_ok=True)+ _atomic_json(dst, data, prefix=".peaks-")+ return data+++def prune_clip_peaks(board_dir, keep_paths) -> int:+ """Drop waveforms for takes the timeline no longer uses."""+ d = clip_peaks_dir(board_dir)+ if not d.is_dir():+ return 0+ wanted = {clip_peaks_path(board_dir, p).name for p in (keep_paths or [])}+ gone = 0+ for f in d.glob("*.json"):+ if f.name in wanted:+ continue+ try:+ f.unlink()+ gone += 1+ except OSError:+ continue+ return gone+++def edit_path(board_dir) -> Path:+ return Path(str(board_dir)) / "edit.json"+++def _atomic_json(target: Path, payload, *, prefix: str,+ indent: int | None = 2) -> Path:+ """Same write `save_storyboard` uses, for the same reason.++ A torn `edit.json` is an hour of somebody's arrangement gone. Temp file in+ the SAME directory (os.replace is only atomic within a filesystem), fsync,+ replace.+ """+ target = Path(str(target))+ target.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp = tempfile.mkstemp(dir=str(target.parent), prefix=prefix,+ suffix=".json")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as fh:+ json.dump(payload, fh, indent=indent, ensure_ascii=False,+ separators=(",", ":") if indent is None else None)+ fh.flush()+ os.fsync(fh.fileno())+ os.replace(tmp, target)+ except BaseException:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+ return target+++def new_clip(path, start: float, end: float, film_start: float, *,+ source: str = "auto", **extra) -> dict:+ """One timeline clip, with the film slot derived rather than passed twice.++ `film_end` is never an independent number: a clip plays at 1x, so its slot+ is exactly as long as its window. Deriving it here is what stops the two+ from drifting apart in the one place they are both first written.+ """+ start, end = round(_f(start), 6), round(_f(end), 6)+ fs = round(_f(film_start), 6)+ clip = {+ "id": extra.pop("id", "") or _clip_id(path, start, fs),+ "path": str(path),+ "proxy": extra.pop("proxy", None),+ "start": start,+ "end": end,+ "film_start": fs,+ "film_end": round(fs + (end - start), 6),+ "source": source if source in ("auto", "human") else "auto",+ "locked": bool(extra.pop("locked", False)),+ }+ clip.update(extra)+ return clip+++def _clip_id(path, start: float, film_start: float) -> str:+ raw = f"{path}\0{start:.6f}\0{film_start:.6f}\0{time.time_ns()}"+ return "k" + hashlib.sha1(raw.encode("utf-8", "replace")).hexdigest()[:10]+++def edit_from_plan(plan, *, board_id: str = "", audio: dict | None = None,+ beats: dict | None = None, proxies: dict | None = None,+ settings: dict | None = None,+ labels: dict | None = None) -> dict:+ """Derive a fresh `edit.json` from a `storyboard_edit.plan_cut()` plan.++ Every field the planner already computed is carried through unchanged —+ `start`/`end`/`film_start`/`film_end` are the plan's own numbers, not a+ re-derivation — and everything the planner explains (the snap, the window+ score, the notes) rides along as `analysis` so the UI can show WHY a cut+ landed where it did without asking the server a second question.++ `source` is `"auto"` on every clip, and that is a promise the save path+ keeps: a clip a human has touched comes back as `"human"` and a later+ re-plan can leave it alone.+ """+ proxies = proxies or {}+ labels = labels or {}+ clips = []+ for entry in plan or []:+ if not isinstance(entry, dict) or not entry.get("path"):+ continue+ path = str(entry["path"])+ # Only a KNOWN answer is carried. An absent `has_audio` means nobody+ # probed, which is not the same as silence — the lane draws such a+ # clip exactly as it always did.+ extra = ({"has_audio": bool(entry["has_audio"])}+ if isinstance(entry.get("has_audio"), bool) else {})+ clips.append(new_clip(+ path,+ _f(entry.get("start")), _f(entry.get("end")),+ _f(entry.get("film_start")),+ source="auto",+ proxy=proxies.get(path),+ n=entry.get("n"),+ title=labels.get(path) or Path(path).stem,+ duration=round(_f((entry.get("window") or {}).get("source_duration")), 6) or None,+ analysis={+ "score": (entry.get("window") or {}).get("score"),+ "reason": (entry.get("window") or {}).get("reason"),+ "usable": (entry.get("window") or {}).get("usable", True),+ "snap": entry.get("snap"),+ "notes": entry.get("notes") or [],+ },+ **extra,+ ))+ return normalise_edit({+ "version": EDIT_VERSION,+ "board_id": board_id,+ "revision": 0,+ "source": "auto",+ "audio": audio,+ "beats": _slim_beats(beats),+ "clips": clips,+ "settings": settings or {},+ })+++def _slim_beats(beats: dict | None) -> dict | None:+ """The beat grid a timeline needs, without the megabyte of diagnostics.++ `beat_map()` returns per-second metrics and runner-up hypotheses because a+ human recalibrating the tracker needs them. A timeline needs the grid and+ the confidence, and shipping the rest on every poll is 40x the payload for+ a number nobody draws.+ """+ if not isinstance(beats, dict):+ return None+ d = beats.get("diagnostics") or {}+ return {+ "bpm": beats.get("bpm"),+ "period": beats.get("period"),+ "phase": beats.get("phase"),+ "meter": beats.get("meter"),+ "confidence": beats.get("confidence"),+ "span": beats.get("span"),+ "beats": list(beats.get("beats") or []),+ "downbeats": list(beats.get("downbeats") or []),+ "grid_lock_ms": d.get("grid_lock_ms"),+ "tempo_drift_bpm": d.get("tempo_drift_bpm"),+ }+++def validate_edit(edit) -> list[dict]:+ """Every reason this edit must not be written. Empty list == good.++ Each entry is `{"code", "where", "message"}` — a stable machine name, the+ clip index (or None for the document), and a sentence a person can act on.+ Structured for the same reason `validate_storyboard_detail` is: a UI that+ has to regex an error string is a UI that breaks when the string improves.++ Only genuine corruption is an ERROR. A gap in the timeline is not corrupt —+ it is the hole somebody is about to generate a shot into, and refusing to+ save it would make the feature impossible. Gaps come back from+ `edit_gaps()` as information; overlaps of the PICTURE are errors, because a+ single-track concat has no way to play two clips at once and the render+ would silently pick one.++ OVERLAPPING SOUND IS A WARNING, AND THAT COST A MAN HIS AFTERNOON.+ `clips_audio_overlap` was an error, and every writer of this document —+ Save, the autosave and the crash backup alike — refuses on any error. So+ the moment a J-cut pulled one line a quarter of a second under the outgoing+ shot, which is the most ordinary edit this feature exists to make, the+ board became unsaveable AND unbackupable: a red "SAVING IS FAILING" banner+ over work that could not be stored anywhere, while the user kept cutting.++ Two sounds meeting for 0.25 s is a crossfade in every NLE ever shipped, and+ the assembler has always resolved it deterministically — the incoming+ sound wins its start and the outgoing tail gives way (`_sb_split_audio_plan`+ in mlx_ltx_panel.py). So there is no corruption here to protect anyone+ from, only a note worth showing. `WARNING_CODES` names the codes that must+ never block a write; `blocking_errors()` is what a writer asks.++ PERSISTING THE USER'S WORK WINS. If a rule cannot decide between "refuse+ the save" and "let it through with a note", it says note.+ """+ errs: list[dict] = []++ def bad(code: str, message: str, where=None) -> None:+ e = {"code": code, "where": where, "message": message}+ if code in WARNING_CODES:+ e["severity"] = "warning"+ errs.append(e)++ if not isinstance(edit, dict):+ bad("not_an_object", "the edit is not a JSON object")+ return errs+ if edit.get("version") != EDIT_VERSION:+ bad("version", f"edit version {edit.get('version')!r} — this build "+ f"understands {EDIT_VERSION}")+ clips = edit.get("clips")+ if not isinstance(clips, list):+ bad("clips_not_a_list", "clips must be a list")+ return errs++ audio = edit.get("audio")+ if audio is not None and not isinstance(audio, dict):+ bad("audio_shape", "audio must be an object or null")+ elif isinstance(audio, dict) and audio.get("path") is not None \+ and not isinstance(audio.get("path"), str):+ bad("audio_path", "audio.path must be a string")+ if isinstance(audio, dict) and audio.get("mode") is not None \+ and audio.get("mode") not in ("under", "replace"):+ # `replace` deletes every line of dialogue in the film, so a typo here+ # must not fall through to it by accident.+ bad("audio_mode", "audio.mode must be 'under' or 'replace'")+ if isinstance(audio, dict):+ # THE MIX IS OPTIONAL, the same migration the trims are: absent means+ # the new default, so every edit.json ever written is already valid.+ mix = audio.get("mix")+ if mix is not None and not isinstance(mix, dict):+ bad("audio_mix", "audio.mix must be an object or absent")+ elif isinstance(mix, dict):+ bg = mix.get("bed_gain")+ if bg is not None:+ if not isinstance(bg, (int, float)) or isinstance(bg, bool) \+ or bg != bg or bg in (float("inf"), float("-inf")):+ bad("audio_mix_bed_gain",+ "audio.mix.bed_gain must be a number or absent")+ elif not 0.0 <= float(bg) <= 1.0:+ bad("audio_mix_bed_gain_range",+ "audio.mix.bed_gain must be between 0 and 1")+ dk = mix.get("duck")+ if dk is not None and not isinstance(dk, bool):+ bad("audio_mix_duck",+ "audio.mix.duck must be true, false or absent")+ # THE TRIMS ARE OPTIONAL AND THAT IS THE MIGRATION. Absent means+ # untrimmed, so every edit.json ever written is already valid here and+ # EDIT_VERSION does not move for them.+ for key in ("trim_start", "trim_end"):+ v = audio.get(key)+ if v is None:+ continue+ if not isinstance(v, (int, float)) or isinstance(v, bool) \+ or v != v or v in (float("inf"), float("-inf")):+ bad(f"audio_{key}", f"audio.{key} must be a number or absent")+ elif v < 0:+ bad(f"audio_{key}_range", f"audio.{key} must be >= 0")+ ts, te = audio.get("trim_start"), audio.get("trim_end")+ if isinstance(ts, (int, float)) and not isinstance(ts, bool) \+ and isinstance(te, (int, float)) and not isinstance(te, bool) \+ and float(te) <= float(ts):+ bad("audio_trim_window",+ f"audio.trim_end ({te}) must be after audio.trim_start ({ts})")+ off = audio.get("offset")+ if off is not None and (not isinstance(off, (int, float))+ or isinstance(off, bool) or off != off+ or off in (float("inf"), float("-inf"))):+ # NEGATIVE IS LEGAL — it is the music starting later than the film.+ # Only a non-number is refused.+ bad("audio_offset", "audio.offset must be a number")+ # THE BED'S OWN ENVELOPE, held to the same shape a strip's is. It was+ # readable by the model and normalised on the way out from the day the+ # envelope maths was shared, and validated by nothing — so a hand-+ # edited or agent-written `audio.afx` of the wrong shape reached+ # `bed_gain_points` instead of reaching a sentence.+ bafx = audio.get("afx")+ if bafx is not None and not isinstance(bafx, dict):+ bad("audio_afx", "audio.afx must be an object or absent")+ elif isinstance(bafx, dict):+ for key in ("fade_in", "fade_out"):+ v = bafx.get(key)+ if v is None:+ continue+ if not isinstance(v, (int, float)) or isinstance(v, bool) \+ or v != v or v in (float("inf"), float("-inf")):+ bad(f"audio_afx_{key}",+ f"audio.afx.{key} must be a number")+ elif v < 0:+ bad(f"audio_afx_{key}_range",+ f"audio.afx.{key} must be >= 0")+ bpts = bafx.get("points")+ if bpts is not None and not isinstance(bpts, list):+ bad("audio_afx_points",+ "audio.afx.points must be a list or absent")+ elif isinstance(bpts, list):+ for row in bpts:+ if not isinstance(row, (list, tuple)) or len(row) != 2 \+ or any(not isinstance(x, (int, float))+ or isinstance(x, bool) or x != x+ for x in row):+ bad("audio_afx_point",+ "every audio.afx point is [seconds, gain]")+ break++ spans: list[tuple[float, float, int]] = []+ for i, c in enumerate(clips):+ if not isinstance(c, dict):+ bad("clip_not_an_object", f"clip {i + 1} is not an object", i)+ continue+ if c.get("kind") is not None and str(c.get("kind")) not in CLIP_KINDS:+ bad("clip_kind", f"clip {i + 1}: kind must be one of "+ f"{', '.join(CLIP_KINDS)} (got "+ f"{c.get('kind')!r})", i)+ continue+ kind = clip_kind(c)+ path = c.get("path")+ # A SLUG HAS NO FILE. That is the whole of what a slug is: black for a+ # duration, `color=` in the graph, nothing on disk, nothing to probe,+ # nothing to proxy. Demanding a path from one is demanding a file for+ # the absence of a file.+ if kind != "slug":+ if not isinstance(path, str) or not path.strip():+ bad("clip_path", f"clip {i + 1} has no path", i)+ continue+ # A STILL'S IMAGE MUST EXIST, and it is checked HERE rather than at+ # the ffmpeg that would otherwise discover it. A video clip whose+ # file has gone still renders — the assembler drops it and says so+ # in `unreadable` — but a still is nothing BUT its image, so a+ # missing one is a clip that can never play.+ elif kind == "still" and not Path(path).is_file():+ bad("still_missing",+ f"clip {i + 1}: there is no image at {path}", i)+ start, end = _f(c.get("start"), -1.0), _f(c.get("end"), -1.0)+ fs, fe = _f(c.get("film_start"), -1.0), _f(c.get("film_end"), -1.0)+ if fs < 0:+ bad("clip_film_start", f"clip {i + 1}: film_start must be >= 0", i)+ if fe <= fs:+ # For a still and a slug this is the ONLY length that exists — the+ # hold is the slot, so "a still needs a duration" and "film_end is+ # after film_start" are the same sentence.+ bad("clip_film_window", f"clip {i + 1}: film_end ({fe}) must be "+ f"after film_start ({fs})", i)+ # THE SOURCE WINDOW IS A VIDEO'S PROBLEM ALONE. A still has no source+ # clock to be a window into and a slug has no source at all; both have+ # their start/end SYNTHESISED from the slot by `normalise_edit`, so+ # policing a window they do not own would refuse the document for a+ # number the server itself wrote.+ if kind == "video":+ if start < 0:+ bad("clip_start", f"clip {i + 1}: start must be >= 0", i)+ if end <= start:+ bad("clip_window", f"clip {i + 1}: end ({end}) must be after "+ f"start ({start})", i)+ if end > start and fe > fs \+ and abs((end - start) - (fe - fs)) > LENGTH_TOLERANCE:+ bad("clip_length_mismatch",+ f"clip {i + 1}: the source window is {end - start:.3f}s "+ f"but its slot on the film is {fe - fs:.3f}s — nothing "+ f"plays at anything but 1x", i)+ dur = c.get("duration")+ if isinstance(dur, (int, float)) and dur > 0 \+ and end > float(dur) + 1e-3:+ bad("clip_past_the_end",+ f"clip {i + 1}: the window ends at {end:.3f}s but the "+ f"source is {float(dur):.3f}s long", i)+ adj = c.get("adjust")+ if adj is not None:+ if not isinstance(adj, dict):+ bad("clip_adjust", f"clip {i + 1}: adjust must be an object "+ f"or absent", i)+ elif adj.get("brightness") is not None:+ b = adj.get("brightness")+ if not isinstance(b, (int, float)) or isinstance(b, bool) \+ or b != b or b in (float("inf"), float("-inf")):+ bad("clip_brightness",+ f"clip {i + 1}: adjust.brightness must be a number", i)+ elif abs(float(b)) > BRIGHTNESS_LIMIT + 1e-9:+ bad("clip_brightness_range",+ f"clip {i + 1}: adjust.brightness is {float(b):+.3f} — "+ f"it must be between {-BRIGHTNESS_LIMIT:+.1f} and "+ f"{BRIGHTNESS_LIMIT:+.1f}", i)+ aud = c.get("audio")+ if aud is not None:+ # A STILL AND A SLUG HAVE NO SOUND TO SPLIT. Letting them carry the+ # field would be letting a document describe an edit the assembler+ # has no input to make.+ if kind != "video":+ bad("clip_audio_kind",+ f"clip {i + 1}: only a video clip has sound to unlink", i)+ elif not isinstance(aud, dict):+ bad("clip_audio_shape",+ f"clip {i + 1}: audio must be an object or absent", i)+ else:+ if aud.get("linked") is not None \+ and not isinstance(aud.get("linked"), bool):+ bad("clip_audio_linked",+ f"clip {i + 1}: audio.linked must be true or absent", i)+ w = clip_audio(c)+ if w["start"] < 0:+ bad("clip_audio_start",+ f"clip {i + 1}: audio.start must be >= 0", i)+ if w["end"] <= w["start"]:+ bad("clip_audio_window",+ f"clip {i + 1}: audio.end ({w['end']}) must be after "+ f"audio.start ({w['start']})", i)+ if w["film_start"] < 0:+ bad("clip_audio_film_start",+ f"clip {i + 1}: audio.film_start must be >= 0", i)+ dur = c.get("duration")+ if isinstance(dur, (int, float)) and dur > 0 \+ and w["end"] > float(dur) + 1e-3:+ bad("clip_audio_past_the_end",+ f"clip {i + 1}: the sound ends at {w['end']:.3f}s but "+ f"the source is {float(dur):.3f}s long", i)+ afx = c.get("afx")+ if afx is not None and not isinstance(afx, dict):+ bad("clip_afx", f"clip {i + 1}: afx must be an object or absent", i)+ elif isinstance(afx, dict):+ for key in ("fade_in", "fade_out"):+ v = afx.get(key)+ if v is None:+ continue+ if not isinstance(v, (int, float)) or isinstance(v, bool) \+ or v != v or v in (float("inf"), float("-inf")):+ bad(f"clip_a{key}",+ f"clip {i + 1}: afx.{key} must be a number", i)+ elif float(v) < 0:+ bad(f"clip_a{key}_range",+ f"clip {i + 1}: afx.{key} must be >= 0", i)+ pts = afx.get("points")+ if pts is not None and not isinstance(pts, list):+ bad("clip_afx_points",+ f"clip {i + 1}: afx.points must be a list or absent", i)+ elif isinstance(pts, list):+ for row in pts:+ if not isinstance(row, (list, tuple)) or len(row) != 2 \+ or not all(isinstance(x, (int, float))+ and not isinstance(x, bool)+ for x in row):+ bad("clip_afx_point",+ f"clip {i + 1}: every afx point is [seconds, gain]",+ i)+ break+ fx = c.get("fx")+ if fx is not None:+ if not isinstance(fx, dict):+ bad("clip_fx", f"clip {i + 1}: fx must be an object or absent", i)+ else:+ for key in ("fade_in", "fade_out"):+ v = fx.get(key)+ if v is None:+ continue+ if not isinstance(v, (int, float)) or isinstance(v, bool) \+ or v != v or v in (float("inf"), float("-inf")):+ bad(f"clip_{key}",+ f"clip {i + 1}: fx.{key} must be a number", i)+ elif float(v) < 0:+ bad(f"clip_{key}_range",+ f"clip {i + 1}: fx.{key} must be >= 0", i)+ if c.get("mute") is not None:+ if not isinstance(c.get("mute"), bool):+ bad("clip_mute",+ f"clip {i + 1}: mute must be true or absent", i)+ elif c.get("mute") and kind != "video":+ bad("clip_mute_kind",+ f"clip {i + 1}: only a video clip has sound to mute", i)+ if c.get("source") not in ("auto", "human"):+ bad("clip_source", f"clip {i + 1}: source must be 'auto' or "+ f"'human' (got {c.get('source')!r})", i)+ if not isinstance(c.get("locked", False), bool):+ bad("clip_locked", f"clip {i + 1}: locked must be true or false", i)+ proxy = c.get("proxy")+ if proxy is not None:+ if not isinstance(proxy, str):+ bad("clip_proxy", f"clip {i + 1}: proxy must be a string or "+ f"null", i)+ elif Path(proxy).is_absolute() or ".." in Path(proxy).parts:+ # The proxy is served by name out of the board's own folder.+ # An absolute path or a `..` would make that route a file+ # browser for the whole disk.+ bad("clip_proxy_escapes",+ f"clip {i + 1}: proxy must be a relative name inside the "+ f"board folder (got {proxy!r})", i)+ if fe > fs:+ spans.append((fs, fe, i))++ # THE OVERLAY LANE, held to the same rule as the picture lane and for the+ # same reason: it is ONE track, so two cards cannot play at once. An+ # overlay sitting ON a clip is not an overlap — that is the feature.+ ov = edit.get("overlays") if isinstance(edit, dict) else None+ if ov is not None and not isinstance(ov, list):+ bad("overlays_shape", "overlays must be a list or absent")+ elif isinstance(ov, list):+ ospans = []+ for j, o in enumerate(ov):+ if not isinstance(o, dict):+ bad("overlay_shape", f"overlay {j + 1}: must be an object", None)+ continue+ ofs, ofe = _f(o.get("film_start")), _f(o.get("film_end"))+ if ofs < 0:+ bad("overlay_film_start",+ f"overlay {j + 1}: film_start must be >= 0")+ if ofe <= ofs:+ bad("overlay_window",+ f"overlay {j + 1}: film_end ({ofe}) must be after "+ f"film_start ({ofs})")+ if overlay_kind(o) == "video" and not str(o.get("path") or ""):+ bad("overlay_path", f"overlay {j + 1}: needs a file")+ ofx = o.get("fx")+ if ofx is not None and not isinstance(ofx, dict):+ bad("overlay_fx",+ f"overlay {j + 1}: fx must be an object or absent")+ elif isinstance(ofx, dict):+ for key in ("fade_in", "fade_out"):+ v = ofx.get(key)+ if v is None:+ continue+ if not isinstance(v, (int, float)) or isinstance(v, bool) \+ or v != v or v in (float("inf"), float("-inf")):+ bad(f"overlay_{key}",+ f"overlay {j + 1}: fx.{key} must be a number")+ elif float(v) < 0:+ bad(f"overlay_{key}_range",+ f"overlay {j + 1}: fx.{key} must be >= 0")+ if ofe > ofs:+ ospans.append((ofs, ofe, j))+ ospans.sort()+ for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(ospans, ospans[1:]):+ if b_s < a_e - TOUCH_TOLERANCE:+ bad("overlays_overlap",+ f"overlays {a_i + 1} and {b_i + 1} overlap "+ f"({a_s:.3f}-{a_e:.3f}s and {b_s:.3f}-{b_e:.3f}s) — one "+ f"overlay lane can only show one of them")+ spans.sort()+ for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(spans, spans[1:]):+ if b_s < a_e - TOUCH_TOLERANCE:+ bad("clips_overlap",+ f"clips {a_i + 1} and {b_i + 1} overlap on the film "+ f"({a_s:.3f}-{a_e:.3f}s and {b_s:.3f}-{b_e:.3f}s) — one video "+ f"track can only play one of them", b_i)+ # THE SAME RULE FOR THE SOUND, and it is what keeps a split edit from+ # becoming the multi-track mixer the refuse list bans. A J-cut is a butt+ # join that lands somewhere the picture does not; it is still one lane, so+ # two clips' sound may no more overlap than two clips' pictures.+ asp: list[tuple[float, float, int]] = []+ for i, c in enumerate(clips):+ if not isinstance(c, dict) or clip_kind(c) != "video":+ continue+ w = clip_audio(c)+ if w["end"] > w["start"]:+ asp.append((w["film_start"],+ w["film_start"] + (w["end"] - w["start"]), i))+ asp.sort()+ for (a_s, a_e, a_i), (b_s, b_e, b_i) in zip(asp, asp[1:]):+ if b_s < a_e - TOUCH_TOLERANCE:+ bad("clips_audio_overlap",+ f"the sound of clips {a_i + 1} and {b_i + 1} overlaps "+ f"({a_s:.3f}-{a_e:.3f}s and {b_s:.3f}-{b_e:.3f}s) — a split "+ f"edit moves the sound, it does not add a second track", b_i)+ return errs+++# The fields a digest IGNORES, and why each one is on the list. A field the+# user cannot see may never be the reason they are asked a question.+_DIGEST_SKIP_DOC = ("revision", "updated_at", "origin", "duration",+ "migrated_from", "repaired_audio_overlaps", "audio_repair",+ # The mix heal's own bookkeeping. `audio.mix` IS content —+ # it is two controls on screen — but the marker that says+ # the stamp has run is not, and a document differing only+ # by it must not raise a chip about a field nobody can see.+ "repaired_mix", "mix_repair",+ "archived_at", "label", "backup_of", "backed_up_at",+ "backup_revision", "session", "session_at")+_DIGEST_SKIP_CLIP = ("proxy", "analysis", "has_audio", "n", "title",+ "placed", "duration")+++def _digest_clip(c) -> dict:+ """One clip, reduced to what a person can see and change."""+ if not isinstance(c, dict):+ return {}+ out = {k: v for k, v in c.items() if k not in _DIGEST_SKIP_CLIP}+ for k in ("start", "end", "film_start", "film_end"):+ if k in out:+ out[k] = round(_f(out.get(k)), 6)+ return out+++def edit_digest(edit) -> str:+ """A canonical fingerprint of the ARRANGEMENT, and nothing else.++ THE BUG THIS EXISTS FOR. The recovery offer compared `json.dumps(clips)` on+ both sides — but `_sbe_payload` REWRITES every clip's `proxy` pointer on+ the way out, deliberately, so a proxy built after the last save becomes+ visible without a re-save. The client's copy therefore differs from the+ file in a field the user has never heard of, on any board whose proxies+ were built after its last save. Forever. What that produced was a+ full-width bar reading "A backup from 3 min ago holds 10 clip(s) — the+ saved draft has 10. Nothing has been changed": a question about a+ difference it could not name, over a document that had loaded correctly.++ So the comparison is of the things somebody edited — the windows, the+ slots, the sound, the adjustments, the soundtrack, the beats — with every+ derived, rewritten and bookkeeping field removed by name. Two documents+ with the same digest are the same film, and the panel has nothing to say.+ """+ doc = edit if isinstance(edit, dict) else {}+ body = {k: v for k, v in doc.items()+ if k not in _DIGEST_SKIP_DOC and k != "clips"}+ body["clips"] = [_digest_clip(c) for c in (doc.get("clips") or [])+ if isinstance(c, dict)]+ raw = json.dumps(body, sort_keys=True, separators=(",", ":"),+ default=str)+ return hashlib.sha1(raw.encode("utf-8", "replace")).hexdigest()[:16]+++# ---- which tab is EDITING ------------------------------------------------+# THE CLAIM IS A LABEL, NOT A LOCK, AND IT IS TAKEN BY WRITING.+#+# It used to be taken by LOADING, and it used to gate the snapshot lane. That+# combination cost the owner an afternoon: a passive page load — a headless+# browser, a second window, an agent reading the board, a preview — claimed the+# board without editing anything, and the tab the person was actually cutting+# in was told `stale_session` and stopped writing snapshots for seven hours.+# Nothing on screen said so (see `sbeQueueSave`), and the safety net that was+# meant to catch exactly this had been starved of the timestamp it watches.+#+# Two rules come out of that, and both are load-bearing:+#+# 1. A READ CLAIMS NOTHING. Looking at a film is not editing it. Anything+# that only reads — every GET, every agent, every preview — leaves the+# claim exactly where it was.+# 2. THE LANE NEVER REFUSES. `write_backup`'s own docstring says the safety+# net may not have an opinion; the session check was the last opinion it+# had, and it was the one that switched the net off. The lane is versioned+# now — ONE FILE PER SNAPSHOT, pruned, never overwritten — so the failure+# the token was introduced for (a stale tab stomping a single shared slot)+# cannot happen: a snapshot from any tab costs one file and can only ever+# ADD a way back. Refusing one can only ever remove one.+#+# What the claim is still for: saying, in a tab, that somebody else is editing+# this film too. That is information a person can act on. It is never a reason+# to stop protecting them.+SESSION_STALE_AFTER = 60 * 60 * 12 # a token nobody has used all day+++def session_token_path(board_dir) -> Path:+ return Path(str(board_dir)) / "session.json"+++def current_session(board_dir) -> dict:+ """{"token", "at"} for the session that last claimed this board."""+ doc = _read_json(session_token_path(board_dir)) or {}+ if not isinstance(doc, dict):+ return {"token": "", "at": 0}+ return {"token": str(doc.get("token") or ""),+ "at": int(doc.get("at") or 0)}+++def claim_session(board_dir, token: str) -> dict:+ """This tab is the one EDITING. Returns the claim.++ Called from the write path and from nowhere else. Claiming is not a lock+ and never refuses anybody: what it buys is that a tab can be TOLD another+ tab is editing the same film.+ """+ tok = str(token or "").strip()[:64]+ if not tok:+ raise EditError("a session needs a token")+ Path(str(board_dir)).mkdir(parents=True, exist_ok=True)+ doc = {"token": tok, "at": int(time.time())}+ _atomic_json(session_token_path(board_dir), doc, prefix=".session-")+ return doc+++def session_is_current(board_dir, token: str) -> bool:+ """Does this token hold the claim? An UNCLAIMED board says yes.++ INFORMATION, NOT PERMISSION. Nothing refuses a write on this any more —+ see the block above `SESSION_STALE_AFTER`. It answers the question a tab+ asks in order to tell its user that somebody else is editing too.++ A board nobody has claimed is every board written before this existed, and+ an agent or a script posting to the routes has no tab to claim one — so the+ absence of a claim can never be a refusal. Only a claim by SOMEBODY ELSE,+ recently, is.+ """+ tok = str(token or "").strip()+ cur = current_session(board_dir)+ if not cur["token"] or not tok:+ return True+ if cur["token"] == tok:+ return True+ return (int(time.time()) - cur["at"]) > SESSION_STALE_AFTER+++def blocking_errors(errs) -> list[dict]:+ """The subset of `validate_edit`'s answer that must stop a write."""+ return [e for e in (errs or [])+ if isinstance(e, dict) and e.get("code") not in WARNING_CODES]+++def repair_audio_overlaps(edit: dict) -> int:+ """Trim the DUPLICATED strips an old split left behind. Returns how many.++ The split before the J-cut fix deep-copied `clip.audio` into the new half,+ so one strip became two claiming the same seconds of the same take. The+ document was legal when it was written and became unsaveable the day the+ overlap rule arrived — a board carrying the artifact could not be stored at+ all, which is a migration problem wearing a validation error's clothes.++ A MIGRATION, NOT A RESIDENT. This used to run on every read, which makes+ it a second author of a document the user owns — the exact thing the+ save-model ruling abolished. A repair that is wrong even once is then+ wrong forever, invisibly, on every load. `migrate_edit` runs it ONCE per+ board and stamps `audio_repair` so it never runs again.++ ONLY THE ARTIFACT, AND THE ARTIFACT IS NARROW. Using one take twice is+ ordinary editing, so "two clips of the same source" is evidence of+ nothing. What the old deep copy produced is far more specific:++ * BOTH halves carry an EXPLICIT `audio` object. A clip with no strip of+ its own gets a SYNTHESISED window from `clip_audio`, and comparing a+ synthesised window against a real one compares an edit to a default.+ * The two objects are IDENTICAL — the same source window AND the same+ `film_start` — because they are one dict copied twice.+ * They are ADJACENT and butt-joined, being the two halves of one clip.+ * NEITHER carries a deliberate offset. A strip whose `film_start`+ differs from its picture's is somebody's J-cut, and a J-cut is never+ repair material: "I wanted it a little before her showing up, and I+ cut it that way."+ """+ clips = [c for c in (edit or {}).get("clips") or [] if isinstance(c, dict)]+ order = sorted(clips, key=lambda x: _f(x.get("film_start")))+ fixed = 0+ for a, b in zip(order, order[1:]):+ if clip_kind(a) != "video" or clip_kind(b) != "video":+ continue+ # BOTH halves carry an EXPLICIT strip. A clip with no `audio` of its+ # own gets a SYNTHESISED window, and comparing that against a real one+ # compares an edit to a default — which is how a second, deliberate+ # use of the same take read as a copy of the first.+ aa, ba = a.get("audio"), b.get("audio")+ if not isinstance(aa, dict) or not isinstance(ba, dict):+ continue+ if str(a.get("path") or "") != str(b.get("path") or ""):+ continue+ wa, wb = clip_audio(a), clip_audio(b)+ # ONE DICT, COPIED TWICE: identical source window AND identical+ # film_start. The second half's `film_start` still points at the+ # FIRST half's position, which is exactly what makes it stale.+ if (wa["start"], wa["end"], wa["film_start"]) != \+ (wb["start"], wb["end"], wb["film_start"]):+ continue+ # The original was in sync, so the FIRST half still is. A first half+ # carrying an offset is somebody's J-cut, not a copy.+ if abs(wa["film_start"] - _f(a.get("film_start"))) > TOUCH_TOLERANCE:+ continue+ # The two halves of one split are adjacent AND butt-joined.+ if abs(_f(a.get("film_end")) - _f(b.get("film_start"))) > TOUCH_TOLERANCE:+ continue+ # Re-cut both at the picture's own boundary, in the SOURCE clock the+ # halves share — the rule the fixed `sbeSplitAt` follows, after the+ # fact.+ sp = _f(a.get("end"))+ if not (wa["start"] + TOUCH_TOLERANCE < sp < wa["end"] - TOUCH_TOLERANCE):+ continue+ a["audio"] = {"start": wa["start"], "end": round(sp, 6),+ "film_start": wa["film_start"]}+ if wa.get("coupled"):+ a["audio"]["linked"] = True+ b["audio"] = {"start": round(sp, 6), "end": wb["end"],+ "film_start": round(wb["film_start"] + (sp - wb["start"]), 6)}+ if wb.get("coupled"):+ b["audio"]["linked"] = True+ fixed += 1+ return fixed+++def normalise_edit(edit: dict) -> dict:+ """Sort by film position, round, fill in what can be derived. No policy.++ Deliberately does NOT close gaps, renumber, or re-snap: an editor that+ quietly rearranges what the user saved is an editor the user stops+ trusting. The only thing invented here is a missing `id`.+ """+ out = dict(edit or {})+ out["version"] = EDIT_VERSION+ clips = [c for c in (out.get("clips") or []) if isinstance(c, dict)]+ clips.sort(key=lambda c: (_f(c.get("film_start")), str(c.get("path"))))+ for c in clips:+ for k in ("start", "end", "film_start", "film_end"):+ if k in c:+ c[k] = round(_f(c.get(k)), 6)+ kind = clip_kind(c)+ if kind == "video":+ # An absent `kind` stays absent. Stamping "video" on 400 clips+ # would rewrite every edit.json on the machine to say the thing+ # its absence already says.+ c.pop("kind", None)+ else:+ c["kind"] = kind+ # SYNTHESISED, not trusted. A still and a slug have exactly one+ # length — the slot — and deriving the window from it here is what+ # lets the client's trim machinery resize a still by moving its+ # slot and nothing else.+ c["start"] = 0.0+ c["end"] = round(max(0.0, _f(c.get("film_end"))+ - _f(c.get("film_start"))), 6)+ if kind == "slug":+ c["path"] = None+ c["proxy"] = None+ # Neither has a source clock, so neither has a source duration —+ # and a `duration` left over from a video would clamp the trim.+ c["duration"] = None+ # NEUTRAL IS ABSENT, the rule `adjust` and the music trims follow: an+ # unmuted clip is byte-identical to one written before mute existed.+ if kind == "video" and c.get("mute") is True:+ c["mute"] = True+ else:+ c.pop("mute", None)+ # NEUTRAL IS ABSENT here too, so a timeline nobody has put an effect on+ # is byte-identical to one from before effects existed. The values are+ # written back CLAMPED, so what is on disk is what all three outputs+ # will be handed.+ e = clip_effects(c)+ keep = {k: e[k] for k in ("fade_in", "fade_out") if e[k] > 1e-9}+ if keep:+ c["fx"] = keep+ else:+ c.pop("fx", None)+ # THE SOUND'S ENVELOPE, same neutral-is-absent rule. Clamped on the+ # way to disk so all three outputs read the same legal curve.+ if kind == "video":+ w = clip_audio(c)+ ae = audio_effects(c, max(0.0, w["end"] - w["start"]))+ akeep = {k: ae[k] for k in ("fade_in", "fade_out") if ae[k] > 1e-9}+ if ae["points"]:+ akeep["points"] = ae["points"]+ if akeep:+ c["afx"] = akeep+ else:+ c.pop("afx", None)+ else:+ c.pop("afx", None)+ if kind != "video":+ c.pop("audio", None)+ elif isinstance(c.get("audio"), dict):+ # Rounded, never removed: re-linking is the TOGGLE's job (it+ # deletes the field), and stripping it here because the numbers+ # happen to match the picture would silently re-link a clip the+ # user had deliberately unlinked and not yet moved.+ w = clip_audio(c)+ c["audio"] = {"start": w["start"], "end": w["end"],+ "film_start": w["film_start"]}+ # ONLY WHEN IT SAYS SOMETHING, the rule `adjust` and the music+ # trims already follow: a free strip is the absence of the flag,+ # so a document that never coupled anything is byte-identical to+ # one written before coupling existed.+ if w["coupled"]:+ c["audio"]["linked"] = True+ elif c.get("audio") is not None:+ c.pop("audio", None)+ adj = c.get("adjust")+ if isinstance(adj, dict):+ b = clip_brightness(c)+ rest = {k: v for k, v in adj.items() if k != "brightness"}+ # NEUTRAL IS ABSENT. Dragging the slider back to zero must leave a+ # document identical to one that never had a slider, or every clip+ # anyone ever touched carries a dead field forever.+ if abs(b) < 1e-9 and not rest:+ c.pop("adjust", None)+ else:+ c["adjust"] = dict(rest, brightness=round(b, 6)) if abs(b) >= 1e-9 else rest+ elif adj is not None:+ c.pop("adjust", None)+ if not c.get("id"):+ c["id"] = _clip_id(c.get("path"), _f(c.get("start")),+ _f(c.get("film_start")))+ if c.get("source") not in ("auto", "human"):+ c["source"] = "auto"+ c["locked"] = bool(c.get("locked", False))+ out["clips"] = clips+ # THE OVERLAY LANE. Same discipline as the clips: rounded, sorted, derived+ # where it can be derived, and NOTHING invented. An empty lane is an absent+ # key, so a timeline that has never had an overlay is byte-identical to one+ # from before the lane existed.+ ovs = [o for o in (out.get("overlays") or []) if isinstance(o, dict)]+ ovs.sort(key=lambda o: (_f(o.get("film_start")), str(o.get("path") or "")))+ for o in ovs:+ for k in ("film_start", "film_end"):+ o[k] = round(_f(o.get(k)), 6)+ o["kind"] = overlay_kind(o)+ if o["kind"] == "still":+ # A still is its slot and nothing else — the same synthesis a+ # still CLIP gets, and the reason the trim handles can resize it.+ o["start"] = 0.0+ o["end"] = round(max(0.0, o["film_end"] - o["film_start"]), 6)+ o["duration"] = None+ else:+ for k in ("start", "end"):+ o[k] = round(_f(o.get(k)), 6)+ if not o.get("id"):+ o["id"] = _clip_id(o.get("path"), _f(o.get("start")),+ _f(o.get("film_start")))+ if o.get("source") not in ("auto", "human"):+ o["source"] = "human"+ o["locked"] = bool(o.get("locked", False))+ e = clip_effects(o)+ keep = {k: e[k] for k in ("fade_in", "fade_out") if e[k] > 1e-9}+ if keep:+ o["fx"] = keep+ else:+ o.pop("fx", None)+ if ovs:+ out["overlays"] = ovs+ else:+ out.pop("overlays", None)+ out.setdefault("board_id", "")+ # NEUTRAL IS ABSENT, the same rule `adjust` follows one block up. Dragging+ # a trim handle back to the end of the track must leave a document+ # identical to one that was never trimmed, or every timeline anybody ever+ # touched the music on carries two dead fields forever.+ aud = out.get("audio")+ if isinstance(aud, dict):+ aud = dict(aud)+ if "offset" in aud:+ aud["offset"] = round(_f(aud.get("offset")), 6)+ ts = aud.get("trim_start")+ if isinstance(ts, (int, float)) and not isinstance(ts, bool):+ ts = round(max(0.0, _f(ts)), 6)+ if ts <= 0:+ aud.pop("trim_start", None)+ else:+ aud["trim_start"] = ts+ elif ts is not None:+ aud.pop("trim_start", None)+ te = aud.get("trim_end")+ if isinstance(te, (int, float)) and not isinstance(te, bool):+ te = round(_f(te), 6)+ dur = _f(aud.get("duration"))+ if te <= 0 or (dur > 0 and te >= dur - 1e-6):+ aud.pop("trim_end", None)+ else:+ aud["trim_end"] = te+ elif te is not None:+ aud.pop("trim_end", None)+ bed_afx = aud.get("afx")+ if isinstance(bed_afx, dict):+ # CLAMPED TO THE PLAYED WINDOW, not to the track. `bed_length` is+ # the bed envelope's clock (see its docstring) — clamping against+ # the whole file would let a fade-out sit past the last second+ # anybody hears, where no output could express it.+ be = audio_effects(aud, bed_length(aud, edit_duration(out)))+ bkeep = {k: be[k] for k in ("fade_in", "fade_out") if be[k] > 1e-9}+ if be["points"]:+ bkeep["points"] = be["points"]+ if bkeep:+ aud["afx"] = bkeep+ else:+ aud.pop("afx", None)+ elif bed_afx is not None:+ aud.pop("afx", None)+ # NEUTRAL IS ABSENT, the rule the trims and `afx` above already+ # follow. A mix left at the new default is byte-identical to a+ # document written before the mix was a thing anybody could set.+ mx = aud.get("mix")+ if isinstance(mx, dict):+ m = audio_mix(aud)+ mkeep = {}+ if abs(m["bed_gain"] - MIX_BED_GAIN) > 1e-9:+ mkeep["bed_gain"] = m["bed_gain"]+ if m["duck"] != MIX_DUCK:+ mkeep["duck"] = m["duck"]+ if mkeep:+ aud["mix"] = mkeep+ else:+ aud.pop("mix", None)+ elif mx is not None:+ aud.pop("mix", None)+ out["audio"] = aud+ out.setdefault("audio", None)+ out.setdefault("beats", None)+ out.setdefault("settings", {})+ out.setdefault("source", "auto")+ out["duration"] = edit_duration(out)+ return out+++# ---------------------------------------------------------------------------+# ONE WRITER AT A TIME, PER BOARD+# ---------------------------------------------------------------------------+# THE DEFECT: `expect_revision` is a compare-and-swap whose compare and whose+# swap were in different places. The HTTP handler read the revision off disk,+# compared it, validated, and only then called `save_edit` — and the panel runs+# on a `ThreadingHTTPServer`, so two tabs whose debounces landed together both+# read revision 7, both compared 7 == 7, and both wrote. Both got HTTP 200.+# One arrangement was gone, recoverable only from `history/` and only by+# somebody who knew to look. The guard existed and the race walked through it.+#+# So the read, the check and the write happen inside ONE critical section, and+# it lives HERE rather than in the handler because this is the function every+# writer already goes through — the auto-editor, the relink, the drafts, the+# restore. A guard the caller has to remember to take is a guard.+#+# PER BOARD, KEYED BY THE RESOLVED DIRECTORY. Two people cutting two different+# films have nothing to say to each other and must not queue behind one+# another; two tabs on one film have everything to say to each other. An RLock+# so a writer that reaches a second write on the same board cannot deadlock+# itself. The registry is bounded by the number of boards that have ever been+# saved in this process, which is the number of boards.+_BOARD_LOCKS: dict[str, threading.RLock] = {}+_BOARD_LOCKS_GUARD = threading.Lock()+++def board_write_lock(board_dir) -> threading.RLock:+ """The one lock that serialises writes to one board's edit.json."""+ key = str(Path(str(board_dir)).resolve())+ with _BOARD_LOCKS_GUARD:+ lk = _BOARD_LOCKS.get(key)+ if lk is None:+ lk = _BOARD_LOCKS[key] = threading.RLock()+ return lk+++def on_disk_revision(board_dir) -> int:+ """The revision in the file RIGHT NOW, read raw and cheaply.++ Deliberately not `load_edit`: the question is "what number is on disk",+ not "what does this document mean once migrated", and a migration that+ ever touched `revision` would turn a comparison into a coin toss. A+ missing or unreadable file is revision 0 — the same answer the handler's+ `load_edit(...) or {}` already gives — because refusing a save over a file+ nobody can read would strand the work rather than persist it.+ """+ try:+ p = edit_path(board_dir)+ if not p.is_file():+ return 0+ doc = json.loads(p.read_text(encoding="utf-8"))+ return int((doc or {}).get("revision") or 0)+ except (OSError, ValueError, TypeError):+ return 0+++def save_edit(board_dir, edit: dict, *, bump: bool = True,+ origin: str = "manual", expect: int | None = None) -> Path:+ """Validate, then write atomically. A bad edit NEVER lands on a good one.++ This is the whole reason `validate_edit` returns structured errors instead+ of raising at the first one: the caller gets the complete list of what is+ wrong with the document it tried to save, and the document already on disk+ is untouched. `os.replace` after `fsync` means the reader either sees the+ old file or the new one — never half of either.++ `expect` is the revision the caller believes is on disk, and passing it+ makes this a COMPARE-AND-SWAP rather than a write: the comparison happens+ under the board's write lock, in the same critical section as the write, so+ a second tab that slipped in between the caller's read and this call raises+ `EditConflict` instead of silently overwriting an arrangement. `None` means+ last-write-wins, which is what the deliberate "Keep mine" button asks for.++ THE LOCK IS TAKEN WHETHER OR NOT `expect` IS. Two unguarded writers still+ must not interleave a history copy with a replace.+ """+ errs = blocking_errors(validate_edit(edit))+ if errs:+ raise EditError("; ".join(e["message"] for e in errs[:6])+ + (f" (+{len(errs) - 6} more)" if len(errs) > 6 else ""))+ doc = normalise_edit(edit)+ with board_write_lock(board_dir):+ return _save_edit_locked(board_dir, doc, bump=bump, origin=origin,+ expect=expect)+++def _save_edit_locked(board_dir, doc: dict, *, bump: bool, origin: str,+ expect: int | None) -> Path:+ """The critical section: compare, stamp, archive, replace. Lock held."""+ if expect is not None:+ current = on_disk_revision(board_dir)+ try:+ want = int(expect)+ except (TypeError, ValueError):+ want = -1+ if want != current:+ raise EditConflict(+ f"this timeline moved on without you — it is at revision "+ f"{current}, you saved from {expect}", revision=current)+ # THE COUNTER IS THE SERVER'S, and it counts from what is on disk. A+ # stale tab must not be able to wind it backwards, which is the same+ # rule the handler stated and could not enforce on its own.+ doc["revision"] = current+ if bump:+ try:+ doc["revision"] = int(doc.get("revision") or 0) + 1+ except (TypeError, ValueError):+ doc["revision"] = 1+ doc["updated_at"] = int(time.time())+ # WHO ASKED FOR THIS SAVE. Stamped in the document so a file read on its+ # own can still answer, and read by `archive_edit` to decide which lane+ # the OUTGOING document belongs in.+ doc["origin"] = origin if origin in ORIGINS else "manual"+ # EVERY SAVE KEEPS ITS PREDECESSOR. The editor used to hold exactly one+ # save per film: no history, and the undo stack dies with the tab — so an+ # arrangement edited past was gone the moment the debounce fired, with the+ # owner asking "there was a version I was working on that was better than+ # this one — is it lost?" and the only honest answer being yes. Before the+ # new document lands, the outgoing one is copied into history/, named by+ # its own revision. ~5 KB per save, capped, and a cut is suddenly a thing+ # you can walk back through instead of a thing you can only overwrite.+ try:+ cur = edit_path(board_dir)+ if cur.is_file():+ archive_edit(board_dir, json.loads(cur.read_text()))+ prune_history(board_dir)+ except Exception: # noqa: BLE001+ # History must never block a save — losing a breadcrumb is nothing+ # next to refusing to persist the arrangement on screen.+ pass+ return _atomic_json(edit_path(board_dir), doc, prefix=".edit-")+++# ---------------------------------------------------------------------------+# PART C2 — history: the autosaves, and the ones somebody named+# ---------------------------------------------------------------------------+# TWO KINDS OF FILE IN ONE FOLDER, told apart by their prefix rather than by+# reading them: `edit-r*.json` is an autosave and the prune walks it,+# `keep-r*.json` is a version a person named and the prune never sees it. That+# is the whole exemption, and it is a glob rather than a flag inside the file+# because a prune that has to open fifty documents to decide what to delete is+# a prune that fails halfway on the first corrupt one.+# THREE LANES IN ONE FOLDER, told apart by their PREFIX rather than by reading+# them. The owner: "the auto saves should be saved separately from the manual+# saves, at least, so the user can go back and see the manual saves." A person+# walking back through their work should meet their own decisions first, not a+# wall of machine noise — and the prune should never be able to eat a decision.+# edit-r* an automatic snapshot. Pruned, capped, secondary in the list.+# save-r* a save the USER pressed. Never auto-pruned, primary in the list.+# keep-r* a version the user NAMED. Never auto-pruned either.+# A glob rather than a flag inside the file, because a prune that has to open+# fifty documents to decide what to delete fails halfway on the first corrupt+# one. The origin is stamped in the JSON too, for anything reading a file on+# its own.+# Bumped only if a NEW legacy artifact is ever found. A board stamped with the+# current number has been through the migration and is never re-examined.+AUDIO_REPAIR_VERSION = 1+_AUTO_PREFIX = "edit-r"+# THE SIDE ARCHIVE. One file per snapshot, named by the clock, in the draft's+# own history folder — so writing a new one can never destroy the last one.+# The single `backup-<draft>.json` slot it replaces is why the client had to+# carry `if (SBE.backup) return false`: with one slot, snapshotting while an+# unanswered offer was on screen would have eaten the work the offer held, so+# the lane switched itself off for the rest of the session the moment a chip+# appeared. A lane that stops is not a safety net. See+# docs/EDITOR_SAVE_MODEL.md §2.+_SNAP_PREFIX = "snap-"+SNAPSHOT_KEEP = 20+_KEPT_PREFIX = "keep-r"+_MANUAL_PREFIX = "save-r"+ORIGINS = ("manual", "auto", "backup")+++def _history_root(board_dir) -> Path:+ """Where the crash backups live, and the drafts' history folders under it."""+ return Path(str(board_dir)) / "history"+++def _migrate_history_layout(board_dir) -> int:+ """Fold pre-drafts history entries into the FIRST draft's folder.++ Entries used to be named by revision alone — `save-r00003.json` — in one+ folder per BOARD, while every new draft restarts its revision counter at+ zero. So draft B's revision 3 collided with draft A's, `archive_edit`+ dropped the collision without a word (`if dst.exists(): return None`), and+ the rows that survived were listed with no draft attribution at all: the+ picker shown while B was open offered A's arrangements, and Restore wrote+ one of them into B — the exact overwrite the history folder exists to+ prevent, arriving through its own front door.++ What is on disk from before that fix belongs to the film's FIRST draft:+ those entries predate the second draft's existence, and the ones a second+ draft did write were the ones the collision swallowed. So they move there,+ rather than being left in a folder nothing lists any more.+ """+ root = _history_root(board_dir)+ if not root.is_dir():+ return 0+ legacy = [p for p in root.iterdir()+ if p.is_file() and p.name.endswith(".json")+ and p.name.startswith((_AUTO_PREFIX, _MANUAL_PREFIX,+ _KEPT_PREFIX))]+ if not legacy:+ return 0+ rows = load_draft_index(board_dir)["drafts"]+ home = root / _slug(str(rows[0]["slug"]), 40)+ home.mkdir(parents=True, exist_ok=True)+ moved = 0+ for src in legacy:+ dst = home / src.name+ if dst.exists():+ dst = home / (src.stem + "-legacy.json")+ try:+ src.replace(dst)+ moved += 1+ except OSError:+ continue+ return moved+++def history_dir(board_dir, slug: str = "") -> Path:+ """The history folder for ONE draft — the named one, or the active one.++ A FOLDER PER DRAFT RATHER THAN A NAME PER DRAFT. The alternative was to+ fold the slug into the filename, which puts the draft's identity in a+ string three different globs have to parse back out — and a draft named+ `r00007` would then be indistinguishable from a revision. A directory+ scopes the prune, the listing and the restore by construction, and+ deleting a draft's past saves becomes deleting a directory.+ """+ _migrate_history_layout(board_dir)+ return _history_root(board_dir) / _slug(+ str(slug or load_draft_index(board_dir)["active"]), 40)+++def archive_edit(board_dir, doc: dict, label: str = "") -> Path | None:+ """Copy a document into `history/`. Returns the file, or None if it exists.++ The label rides BOTH in the filename (so the prune can see it without+ opening anything) and inside the JSON (so the listing does not have to+ parse filenames back into prose). `archived_at` is stamped here because a+ file's mtime is the one piece of this that a backup restore can change.+ """+ hist = history_dir(board_dir)+ hist.mkdir(parents=True, exist_ok=True)+ try:+ rev = int(doc.get("revision") or 0)+ except (TypeError, ValueError):+ rev = 0+ text = str(label or "").strip()[:80]+ origin = str(doc.get("origin") or "auto").lower()+ if text:+ dst = hist / f"{_KEPT_PREFIX}{rev:05d}-{_slug(text, 40)}.json"+ elif origin == "manual":+ dst = hist / f"{_MANUAL_PREFIX}{rev:05d}.json"+ else:+ dst = hist / f"{_AUTO_PREFIX}{rev:05d}.json"+ if dst.exists():+ return None+ out = dict(doc)+ if text:+ out["label"] = text+ out["archived_at"] = int(time.time())+ dst.write_text(json.dumps(out), encoding="utf-8")+ return dst+++def prune_history(board_dir, *, keep: int = EDIT_HISTORY_KEEP) -> int:+ """Drop the oldest AUTOSAVES past the cap. Named versions are never touched.++ A version somebody stopped to name is the one thing in this folder that is+ not a breadcrumb, and the fifty-save cap would otherwise delete it in an+ afternoon of debounced saves.+ """+ hist = history_dir(board_dir)+ if not hist.is_dir():+ return 0+ files = sorted(hist.glob(f"{_AUTO_PREFIX}*.json"))+ gone = 0+ for stale in files[:max(0, len(files) - int(keep))]:+ try:+ stale.unlink()+ gone += 1+ except OSError:+ continue+ return gone+++def _history_meta(path: Path) -> dict:+ """One row for the picker. A file it cannot read is REPORTED, not skipped.++ A history entry that silently vanishes from the list is indistinguishable+ from one that was never written, and the whole point of this folder is that+ the user can see what they still have.+ """+ kept = path.name.startswith(_KEPT_PREFIX)+ manual = kept or path.name.startswith(_MANUAL_PREFIX)+ snap = path.name.startswith(_SNAP_PREFIX)+ row = {"file": path.name, "label": "", "revision": None, "snapshot": snap,+ "clips": None, "duration": None,+ "saved_at": None, "archived_at": None,+ "kept": kept, "manual": manual,+ "origin": "manual" if manual else "auto", "readable": True}+ try:+ st = path.stat()+ row["archived_at"] = int(st.st_mtime)+ except OSError:+ pass+ try:+ doc = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ row["readable"] = False+ return row+ if not isinstance(doc, dict):+ row["readable"] = False+ return row+ row["label"] = str(doc.get("label") or "")[:80]+ if doc.get("origin") in ORIGINS:+ row["origin"] = str(doc["origin"])+ row["manual"] = row["manual"] or row["origin"] == "manual"+ if snap:+ row["origin"] = "backup"+ row["manual"] = False+ try:+ row["revision"] = int(doc.get("revision") or 0)+ except (TypeError, ValueError):+ row["revision"] = 0+ clips = doc.get("clips")+ row["clips"] = len(clips) if isinstance(clips, list) else 0+ row["duration"] = edit_duration(doc)+ for key in ("archived_at", "updated_at"):+ v = doc.get(key)+ if isinstance(v, (int, float)) and not isinstance(v, bool):+ row["archived_at" if key == "archived_at" else "saved_at"] = int(v)+ return row+++def list_history(board_dir) -> list[dict]:+ """The ACTIVE draft's archived documents, NEWEST FIRST.++ Scoped to the draft on screen, because a version picker that offers+ another draft's arrangements is a Restore button that overwrites the film+ you are looking at with a film you are not.+ """+ hist = history_dir(board_dir)+ if not hist.is_dir():+ return []+ # A WHITELIST, NOT A BLACKLIST. pathlib's glob returns dotfiles, and+ # `_atomic_json` writes its temp beside the target with a leading dot — so+ # a crash between mkstemp and os.replace left `.edit-XXXX.json` in here,+ # which listed as an unnamed row with revision None and was clickable.+ # Naming the three lanes we write means nothing else can appear.+ rows = [_history_meta(p) for p in hist.glob("*.json")+ if p.is_file() and p.name.startswith((_AUTO_PREFIX, _MANUAL_PREFIX,+ _KEPT_PREFIX, _SNAP_PREFIX))]+ rows.sort(key=lambda r: (r.get("archived_at") or 0,+ r.get("revision") or 0), reverse=True)+ return rows+++def restore_edit(board_dir, name: str) -> dict:+ """Put a history entry back, keeping what it replaced. Returns the document.++ THE CURRENT ARRANGEMENT IS ARCHIVED FIRST. Restore is the one action in+ this editor that overwrites a document the user can see, and a restore that+ ate the thing it replaced would be the same bug the history folder exists+ to fix, arriving through the fix's own front door.++ The revision goes FORWARD, never back to the archived one: `revision` is+ how two tabs tell who moved last, and handing back an older number would+ make a stale tab look current.+ """+ hist = history_dir(board_dir)+ safe = Path(str(name or "")).name+ if not safe or safe != str(name or "") or not safe.endswith(".json") \+ or not safe.startswith((_AUTO_PREFIX, _MANUAL_PREFIX,+ _KEPT_PREFIX, _SNAP_PREFIX)):+ raise EditError("that is not a version of this film")+ # `hist` is the ACTIVE draft's folder, so a filename from another draft's+ # picker resolves outside it and is refused here rather than installed.+ src = hist / safe+ if not src.is_file() or src.resolve().parent != hist.resolve():+ raise EditError("there is no version by that name")+ try:+ doc = json.loads(src.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ raise EditError(f"that version cannot be read: {exc}") from exc+ if not isinstance(doc, dict):+ raise EditError("that version is not an edit document")+ # A history file may predate the current schema — it is a document like any+ # other, and the read path is where documents are brought forward.+ doc = migrate_edit(doc)+ doc.pop("label", None)+ doc.pop("archived_at", None)+ current = None+ try:+ cur = edit_path(board_dir)+ if cur.is_file():+ current = json.loads(cur.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ current = None+ if current is not None:+ archive_edit(board_dir, current)+ prune_history(board_dir)+ try:+ doc["revision"] = int((current or {}).get("revision") or 0)+ except (TypeError, ValueError):+ doc["revision"] = 0+ # BLOCKING ONLY, for the same reason `recover_backup` does it: every+ # writer archives documents that carry warnings, so every reader must be+ # able to hand them back. A history entry holding a J-cut was+ # unrestorable — the version picker offered it and then refused it.+ errs = blocking_errors(validate_edit(doc))+ if errs:+ raise EditError("that version cannot be restored: "+ + "; ".join(e["message"] for e in errs[:3]))+ save_edit(board_dir, doc)+ return load_edit(board_dir)+++# ---------------------------------------------------------------------------+# THE FRAME GRID — a hole nobody can see, and nobody can close+# ---------------------------------------------------------------------------+# "There is like a black frame that flashes for a microsecond... it's not all+# the cuts, but some of the cuts have like a black frame between them. I tried+# to drag them close and whatever."+#+# The last sentence is the defect. Measured on the sequence that produced the+# report — 24 fps, one frame = 41.67 ms — three holes, all SHORTER THAN A+# FRAME: 20.94 ms (0.503 frame), 15.84 ms (0.380) and 4.00 ms (0.096). A hole+# that size is+#+# * invisible — at the deepest zoom the timeline offers it is a fraction of+# a pixel, so there is nothing on screen to drag;+# * unreachable — dragging sets a gap from a pixel, and no pixel maps to+# 4 ms;+# * unreportable — `edit_gaps` and `sbeHoles` both ignored anything under+# half a frame, which is why the header read "1 hole" while three existed;+# * and still LOUD, because the stage paints black wherever no clip is+# playing, so a third of a frame of nothing is a black frame.+#+# WHERE THE GRID IS ENFORCED, AND WHERE IT IS NOT. On the GAPS, not on the+# absolute film positions. A clip's slot length IS its source trim — the+# validator refuses a document whose slot and window disagree by more than+# `LENGTH_TOLERANCE`, and rightly, because nothing here plays at anything but+# 1x — so snapping `film_end` to a frame would mean re-trimming what the user+# cut. With every gap an exact multiple of a frame and the film starting at 0,+# every CUT between two adjacent clips is exact, which is the property the+# black frame needed. Absolute positions inherit the trims' own precision and+# nothing but ordering reads them.+#+# WHY THIS RUNS ON EVERY READ AND `repair_audio_overlaps` DOES NOT. That one is+# a heuristic about intent and carries a version marker so a false positive+# costs one pass instead of every load. This is not a heuristic: a POSITIVE gap+# shorter than one frame cannot be authored, cannot be seen and cannot be+# rendered, so closing it removes nothing anybody put there. It is idempotent+# by construction — the second pass finds no gap to close — and a test pins+# that, because "fixes itself on open" and "drifts a little every open" look+# identical from one screenshot.+def film_fps(edit) -> float:+ """The sequence's frame rate. `NLE_FPS` unless the document names one."""+ fps = _f((edit or {}).get("fps"), 0.0)+ return fps if fps > 0 else float(NLE_FPS)+++def frame_seconds(edit) -> float:+ """One frame, in seconds, at this sequence's rate."""+ return 1.0 / film_fps(edit)+++def quantise_gap(gap: float, frame: float) -> float:+ """A lead gap, made legal: under one frame is NO gap. Larger is UNTOUCHED.++ Two things this deliberately is not.++ It is not `round(gap / frame)`. The reported 0.503-frame hole rounds UP to+ a whole frame of black, which is the same bug one frame louder.++ And it does not snap a LARGER gap to the grid. A gap of 43.2 frames is a+ black slug somebody placed on purpose, and moving it 8 ms to sit on a frame+ boundary would be rewriting a number the user chose to buy a property+ nothing reads — the cut either side of it is already exact once the gap is+ a fixed quantity. The rule is therefore the narrow one that closes the+ defect: a gap is either ZERO or at least one frame, and a gap somebody can+ see is never touched.+ """+ g = _f(gap)+ return 0.0 if g < frame - 1e-9 else round(g, 9)+++def heal_subframe_gaps(edit: dict) -> list[dict]:+ """Close every sub-frame hole, rippling what follows. Mutates `edit`.++ Returns one row per hole closed, so a caller can say what it did. A LOCKED+ clip is an anchor and is never moved — the hole before it stays, because+ the alternative is honouring a pin by breaking it — and the ripple restarts+ from there so nothing downstream of an anchor inherits a shift the anchor+ did not take.++ An unlinked sound strip travels with its picture by the SAME delta, so a+ J-cut's offset is exactly what it was: `clip_audio_drift` is a difference+ of two constants and moving both by one number leaves it alone.+ """+ if not isinstance(edit, dict):+ return []+ clips = [c for c in (edit.get("clips") or []) if isinstance(c, dict)]+ clips.sort(key=lambda c: _f(c.get("film_start")))+ frame = frame_seconds(edit)+ closed: list[dict] = []+ cursor, delta = 0.0, 0.0+ for i, c in enumerate(clips):+ length = _f(c.get("film_end")) - _f(c.get("film_start"))+ if c.get("locked"):+ # An anchor does not move, so nothing after it is carrying a shift.+ cursor = max(cursor, _f(c.get("film_end")))+ delta = 0.0+ continue+ fs = _f(c.get("film_start")) - delta+ gap = fs - cursor+ if 1e-9 < gap < frame - 1e-9:+ closed.append({"after": i - 1, "film_start": round(cursor, 6),+ "duration": round(gap, 6),+ "frames": round(gap / frame, 4)})+ delta += gap+ fs = cursor+ if delta > 1e-9:+ c["film_start"] = round(fs, 6)+ c["film_end"] = round(fs + length, 6)+ aud = c.get("audio")+ if isinstance(aud, dict) and aud.get("film_start") is not None:+ aud["film_start"] = round(_f(aud.get("film_start")) - delta, 6)+ cursor = _f(c.get("film_end"))+ return closed+++def heal_mix(edit: dict) -> bool:+ """Write the render's old hidden levels onto a document that predates the+ controls. Mutates `edit`; True when it wrote something.++ WHY A HEAL AND NOT A DEFAULT. Until today the ffmpeg graph held every+ `under` bed at 0.20 and ducked it against the dialogue, with no field+ anywhere saying so. Making the honest default (`1.0`, no duck) apply to+ those documents would silently re-mix films the owner has already listened+ to and approved. So the old behaviour is written DOWN, once, as the two+ values it always was: same render, and now it is on screen and reversible.++ ONLY `under` DOCUMENTS. `replace` never touched the bed — no gain term, no+ compressor — so stamping one would invent an attenuation that path never+ had. A `replace` timeline keeps the new default and renders byte-identical.+ """+ aud = edit.get("audio")+ if not isinstance(aud, dict) or not aud.get("path"):+ return False+ if isinstance(aud.get("mix"), dict):+ return False+ if str(aud.get("mode") or "replace").lower() != "under":+ return False+ aud["mix"] = {"bed_gain": MIX_LEGACY_BED_GAIN, "duck": True}+ return True+++def _clips_copied(edit: dict) -> dict:+ """A shallow copy of `edit` whose CLIPS are copies too, strips included.++ `dict(edit)` copies the document and shares every clip in it, so a repair+ that writes `clip["audio"]` writes it into the caller's document — the+ exact defect `test_the_read_does_not_mutate_the_document_it_was_given`+ exists for, one level deeper than it was looking. `pending_backup` compares+ raw JSON on both sides, so a read that edits its argument makes the file+ and the snapshot differ over a repair neither of them contains.+ """+ out = dict(edit or {})+ out["clips"] = [dict(c) if isinstance(c, dict) else c+ for c in (out.get("clips") or [])]+ for c in out["clips"]:+ if isinstance(c, dict) and isinstance(c.get("audio"), dict):+ c["audio"] = dict(c["audio"])+ return out+++def migrate_edit(edit: dict) -> dict:+ """Bring an older document up to `EDIT_VERSION`. One way, on READ only.++ THE TRAP THIS EXISTS FOR: `validate_edit` refuses any version but the+ current one, and `save_edit` refuses to write anything `validate_edit`+ complained about. Bumping the version without a read-path upgrade would+ therefore not "refuse old builds" — it would refuse every timeline anybody+ already had, on their own machine, with their own build.++ Version 1 → 2 is a promotion and nothing else: v1 knew only video clips,+ and an absent `kind` already MEANS video (`clip_kind`). So the upgrade is+ the stamp on the document and no edit to a single clip — which is also why+ it cannot half-fail.++ A version from the FUTURE is left exactly as it arrived, so `validate_edit`+ gets to say the honest thing ("this build understands 2") instead of this+ function quietly pretending a document it has never seen is fine.+ """+ if not isinstance(edit, dict):+ return edit+ try:+ v = int(edit.get("version") or 0)+ except (TypeError, ValueError):+ return edit+ if 0 < v < EDIT_VERSION:+ edit = dict(edit)+ edit["version"] = EDIT_VERSION+ edit["migrated_from"] = v+ # THE DUPLICATED-STRIP ARTIFACT IS A ONE-TIME MIGRATION. It used to run on+ # every read, which made it a rival author: a document the user owns,+ # rewritten by a heuristic, every time it was opened. The marker is what+ # makes it a migration — a board that has been looked at once is never+ # looked at again, so a false positive can cost at most one pass instead+ # of every load for the life of the film.+ #+ # AND IT COPIES THE CLIPS FIRST. `repair_audio_overlaps` writes+ # `clip["audio"]` on both halves of a duplicated strip, and `dict(edit)`+ # shares every clip with the caller — so this repair used to reach back+ # into the document it was handed, which is the same "the read edited my+ # file" defect the mix stamp below already guards against.+ if edit.get("audio_repair") != AUDIO_REPAIR_VERSION:+ edit = _clips_copied(edit)+ if repair_audio_overlaps(edit):+ edit["repaired_audio_overlaps"] = True+ edit["audio_repair"] = AUDIO_REPAIR_VERSION+ # THE MIX STAMP, and it is a migration for the same reason: a document the+ # user owns must not be rewritten by a heuristic on every read. The marker+ # is what makes it one — see `MIX_REPAIR_VERSION` for what re-running it+ # would do to somebody who deliberately turned the duck off.+ #+ # COPY BEFORE WRITING. `pending_backup` compares raw JSON on both sides,+ # so a read that edits its argument in place makes the file and the+ # snapshot differ over a repair neither of them contains — which resurrects+ # the permanent interrogation `docs/EDITOR_SAVE_MODEL.md` exists to kill.+ # `test_the_read_does_not_mutate_the_document_it_was_given` is the gate.+ if edit.get("mix_repair") != MIX_REPAIR_VERSION:+ edit = dict(edit)+ if isinstance(edit.get("audio"), dict):+ edit["audio"] = dict(edit["audio"])+ if heal_mix(edit):+ edit["repaired_mix"] = True+ edit["mix_repair"] = MIX_REPAIR_VERSION+ # A HOLE SHORTER THAN A FRAME IS NOT A HOLE. See the block above+ # `film_fps`: unlike the audio repair, this carries no marker, because it+ # is not a heuristic about intent and running it twice finds nothing to do.+ edit = _clips_copied(edit)+ healed = heal_subframe_gaps(edit)+ # SET OR CLEARED, never left behind. A record of what THIS read closed that+ # survived into a read which closed nothing would report the same repair+ # forever — the panel would keep announcing a fix it had already made.+ if healed:+ edit["healed_subframe_gaps"] = healed+ else:+ edit.pop("healed_subframe_gaps", None)+ return edit+++def load_edit(board_dir) -> dict | None:+ """The edit on disk, or None. A corrupt file raises rather than lying.++ Migration happens HERE, before anything else sees the document, because+ every other reader (the payload, the renderer, the validator on the way+ back in) would otherwise each need to know what version 1 looked like.+ """+ p = edit_path(board_dir)+ if not p.is_file():+ return None+ try:+ data = json.loads(p.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ raise EditError(f"edit.json is corrupt: {exc}") from exc+ if not isinstance(data, dict):+ raise EditError("edit.json is not an object")+ return migrate_edit(data)+++def edit_to_cuts(edit: dict) -> list[dict]:+ """The film order, as the plan shape `_sb_assemble_film` already takes.++ One entry PER TIMELINE CLIP, in film order, including repeats of the same+ source — which is exactly the case the board could never express and the+ reason this file exists.+ """+ out = []+ for c in (edit or {}).get("clips") or []:+ if not isinstance(c, dict):+ continue+ kind = clip_kind(c)+ if kind != "slug" and not c.get("path"):+ continue+ fs, fe = _f(c.get("film_start")), _f(c.get("film_end"))+ if kind == "video":+ start, end = _f(c.get("start")), _f(c.get("end"))+ else:+ # A still and a slug are their slot. `normalise_edit` already wrote+ # this pair; deriving it again here means a hand-built edit that+ # never went through normalise still renders the right length.+ start, end = 0.0, max(0.0, fe - fs)+ if end <= start:+ continue+ entry = {"path": (str(c["path"]) if c.get("path") else None),+ "start": round(start, 6), "end": round(end, 6),+ "film_start": round(fs, 6)}+ # ONLY WHEN THEY SAY SOMETHING. `_sb_cut_index` copies these through to+ # the filtergraph, and a plan that carried `kind: "video"` and an empty+ # `adjust` on every entry would change the assembler's output for every+ # film ever exported, to say nothing new.+ if kind != "video":+ entry["kind"] = kind+ b = clip_brightness(c)+ if abs(b) >= 1e-9:+ entry["adjust"] = {"brightness": round(b, 6)}+ if kind == "video":+ w = clip_audio(c)+ # Only a SPLIT clip says anything here, so a plan of ordinary cuts+ # produces the identical list it always did and the assembler below+ # builds the identical graph. A coupled pair is split too — its+ # offset is the J-cut, and an assembler that ignored it would+ # render the sound back under the picture.+ if w["split"]:+ entry["audio"] = {"start": w["start"], "end": w["end"],+ "film_start": w["film_start"]}+ # Only when it says something, so a film with nothing muted builds+ # the identical graph it always did.+ if clip_muted(c):+ entry["mute"] = True+ # EFFECTS RIDE ON EVERY KIND — a still and a slug fade like anything+ # else, and all three outputs read the same entry.+ e = clip_effects(c)+ fx = {k: e[k] for k in ("fade_in", "fade_out") if e[k] > 1e-9}+ if fx:+ entry["fx"] = fx+ if kind == "video":+ w = clip_audio(c)+ gain = audio_gain_points(c, max(0.0, w["end"] - w["start"]))+ if gain:+ entry["gain"] = gain+ out.append(entry)+ out.sort(key=lambda e: e["film_start"])+ return out+++def edit_duration(edit: dict) -> float:+ """Where the last clip ends on the film — INCLUDING any gaps before it."""+ ends = [_f(c.get("film_end")) for c in (edit or {}).get("clips") or []+ if isinstance(c, dict)]+ return round(max(ends), 6) if ends else 0.0+++def music_window(audio, *, duration: float | None = None) -> dict:+ """What the soundtrack actually plays: `{start, end, delay, film_start}`.++ THE SOUNDTRACK IS AN OBJECT ON THE TIMELINE, not a global offset, and this+ is the one place that turns its three fields into the three numbers ffmpeg+ (and every exporter) needs. The owner's words: "features similar to what+ you did with the clips" — drag it, trim both ends, and it stays where it+ was put.++ The fields, and why they mean what they mean:++ * `offset` — the second of the TRACK that plays at film time 0. It has+ meant exactly that since before the editor existed, so every document on+ disk keeps working. What is new is that it may be NEGATIVE: the track+ begins `-offset` seconds INTO the film, with silence before it. That is+ the direction the old clamp made unreachable, and it is half of "back+ and forth however you want".+ * `trim_start` / `trim_end` — the in/out points INSIDE the track, in track+ seconds. ABSENT MEANS UNTRIMMED, which is why an edit.json written before+ today is still a valid one: no field, no trim, same graph.++ Returned:++ * `start` — where playback begins in the track: `max(trim_start, offset)`.+ A head trim and a positive offset are the same gesture from two+ directions, and whichever cuts more wins.+ * `end` — where it stops in the track, or None for "play to the end".+ * `delay`/`film_start` — the film second the music starts at, which is+ `start - offset`. Trimming the left edge must NOT slide the rest of the+ track earlier (that is a ripple, and music does not ripple), so the+ seconds a head trim removes come back as silence in front.+ """+ a = audio if isinstance(audio, dict) else {}+ off = _f(a.get("offset"))+ dur = _f(duration if duration is not None else a.get("duration"))+ ts = max(0.0, _f(a.get("trim_start")))+ te = a.get("trim_end")+ tail = _f(te) if isinstance(te, (int, float)) and not isinstance(te, bool) else None+ if tail is not None:+ if dur > 0:+ # A trim at (or past) the end of the track is not a trim — and+ # saying so here is what keeps the filtergraph byte-identical for+ # a handle dragged all the way back out. `normalise_edit` drops+ # the field for the same reason.+ tail = None if tail >= dur - 1e-6 else min(tail, dur)+ if tail is not None and tail <= ts:+ tail = None+ start = max(0.0, ts, off)+ if tail is not None and tail <= start:+ # A window the trims closed entirely. Nothing to play, and the honest+ # shape for that is "no music", not a zero-length atrim ffmpeg refuses.+ tail = None+ start = max(0.0, off)+ delay = max(0.0, start - off)+ return {"start": round(start, 6),+ "end": (round(tail, 6) if tail is not None else None),+ "delay": round(delay, 6),+ "film_start": round(delay, 6)}+++def edit_gaps(edit: dict, *, tolerance: float | None = None) -> list[dict]:+ """Holes in the timeline: `[{"film_start", "film_end", "duration",+ "after"}]`.++ THE TOLERANCE IS HALF A FRAME AT THIS SEQUENCE'S RATE, and it used to be+ the constant `TOUCH_TOLERANCE` — which is 1/48, i.e. half a frame at 24 fps+ and the wrong number at any other rate. It also made this function the+ reason the header read "1 hole · 0.02s" over a film with THREE holes in it:+ two of them were under half a frame, so this list did not contain them and+ nothing else was looking. That class is closed at the source — `migrate_edit`+ heals a sub-frame hole out of existence on read — so what is left here is a+ threshold that means "shorter than half a frame is float noise", which is+ the only thing it can honestly mean once a hole is a whole number of frames.++ `after` is the index of the clip the hole follows, or -1 for a hole at the+ head of the film. This is the list the "generate into a gap" control is+ built from, and it is also the list the renderer has to disclose: the+ existing assembler CONCATENATES, so a gap closes and everything after it+ slides earlier. Reporting it is the difference between a known limitation+ and a film that mysteriously fell off the beat.+ """+ if tolerance is None:+ tolerance = frame_seconds(edit) / 2.0+ spans = sorted(+ ((_f(c.get("film_start")), _f(c.get("film_end")), i)+ for i, c in enumerate((edit or {}).get("clips") or [])+ if isinstance(c, dict) and _f(c.get("film_end")) > _f(c.get("film_start"))),+ key=lambda s: s[0])+ gaps: list[dict] = []+ cursor, after = 0.0, -1+ for s, e, i in spans:+ if s - cursor > tolerance:+ gaps.append({"film_start": round(cursor, 6),+ "film_end": round(s, 6),+ "duration": round(s - cursor, 6), "after": after})+ cursor = max(cursor, e)+ after = i+ return gaps+++def edit_sync_flags(edit: dict, *,+ tolerance: float = TOUCH_TOLERANCE) -> list[dict]:+ """Every unlinked pair whose sound no longer lines up with its picture.++ The sibling of `edit_gaps`, and information for exactly the same reason: a+ split edit IS a deliberate drift, so this can never be an error. What it+ can be is VISIBLE — the owner unlinked a clip, moved the picture, and had+ no way to see how far the two had come apart or to put them back:++ "instead of allowing me to remove or move what video is visible while+ leaving the sound intact and then rematching it, it is actually getting+ the audio out of sync."++ `resync_to` is the film second the strip goes back to; the panel prints+ `drift` on both halves and spends one click on the difference.+ """+ out: list[dict] = []+ for i, c in enumerate((edit or {}).get("clips") or []):+ if not isinstance(c, dict) or clip_kind(c) != "video":+ continue+ w = clip_audio(c)+ # A COUPLED PAIR IS NOT A DRIFT. Its offset is the relationship the+ # user froze, and the two travel together from then on — flagging it+ # would put a permanent warning on every J-cut in the film.+ if not w["split"] or w["coupled"]:+ continue+ drift = clip_audio_drift(c)+ if abs(drift) <= tolerance:+ continue+ out.append({"id": str(c.get("id") or ""), "where": i,+ "drift": drift, "film_start": w["film_start"],+ "resync_to": clip_audio_resync(c)})+ return out+++# ===========================================================================+# PART D — the film, as a project somebody else's editor can open+# ===========================================================================+# WHY A FOLDER AND NOT A FILE. An XML that names `/Users/salo/mlx_outputs/…`+# is a project that works on exactly one machine until the first time anything+# moves, and then it is a timeline of red offline clips. Premiere and Resolve+# both relink by NAME within the project's own directory before they give up,+# so a folder whose XML points at a `media/` sitting beside it relinks on drop+# — on this machine, on the colourist's, on a drive.+#+# WHY HARDLINKS. The same bytes, a second name, no copy: a 30-shot film exports+# in milliseconds and costs nothing on disk. `os.link` fails across+# filesystems (EXDEV) and on exotic mounts, and the fallback is a real copy,+# because an export that refuses to happen is worse than an export that costs+# disk.+#+# WHY FCP7 XML. It is the ONE interchange both Premiere Pro and DaVinci Resolve+# import. AAF is Avid-first and lossy through Resolve; EDL cannot carry a still+# or a per-clip effect; Premiere's own .prproj is undocumented binary. Every+# other choice is two exporters.+#+# WHY A SEPARATE SCRIPT FOR AFTER EFFECTS. AE has no timeline-XML import at+# all — never has. The seamless path there is an ExtendScript the user runs+# from File > Scripts > Run Script File, which is why one is written next to+# the XML rather than a second XML AE would refuse.+NLE_FPS = 24++# The image extensions the still branch recognises. Deliberately short: this+# decides whether a clipitem is written with a source duration or as a held+# frame, and a wrong guess is a clip of the wrong length in somebody's NLE.+_STILL_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff")+++def _xml_text(s) -> str:+ """Escape for XML character data AND attribute values."""+ return (str(s if s is not None else "")+ .replace("&", "&").replace("<", "<").replace(">", ">")+ .replace('"', """).replace("'", "'"))+++def _jsx_string(s) -> str:+ """A path as an ExtendScript double-quoted literal.++ Windows paths and macOS volume names both put characters in here that end+ the string early: a backslash escapes the quote after it, a quote closes+ the literal, and a newline in a filename (legal on macOS) makes the script+ a syntax error. All three are escaped, and the result is wrapped in its own+ quotes so callers cannot forget to.+ """+ out = (str(s if s is not None else "")+ .replace("\\", "\\\\").replace('"', '\\"')+ .replace("\r", "\\r").replace("\n", "\\n"))+ return '"' + out + '"'+++def _pathurl(p) -> str:+ """`file://localhost/…` with everything URL-unsafe percent-encoded.++ A space in a filename is the common case (a board titled "Gut Health") and+ an un-encoded one makes the pathurl unparseable to Premiere — the clip+ imports offline with no error anybody can act on. `quote` keeps `/` so the+ path survives as a path.+ """+ from urllib.parse import quote # noqa: PLC0415+ return "file://localhost" + quote(str(Path(str(p)).as_posix()), safe="/")+++def _frames(seconds: float, fps: int = NLE_FPS) -> int:+ """Seconds → whole frames, rounded. An NLE has no other unit."""+ return int(round(_f(seconds) * float(fps)))+++def _nle_media_name(src: Path, taken: dict) -> str:+ """A unique name inside `media/`, stable for the same source.++ Two shots called `S01_open.mp4` from two different boards would otherwise+ become one file and one of them would silently play the other. The+ fingerprint suffix only appears when there IS a collision, so the common+ export keeps readable names.+ """+ key = str(src)+ if key in taken:+ return taken[key]+ name = src.name+ if name in set(taken.values()):+ h = hashlib.sha1(key.encode("utf-8", "replace")).hexdigest()[:6]+ name = f"{src.stem}_{h}{src.suffix}"+ taken[key] = name+ return name+++def _link_or_copy(src: Path, dest: Path, *, link=None) -> str:+ """Hardlink, or copy when the filesystem says no. Returns "link"|"copy".++ `link` is injectable so the fallback branch is testable without a second+ filesystem — the branch that only fires on a cross-device export is+ exactly the branch nobody would otherwise ever run.+ """+ import shutil # noqa: PLC0415+ linker = link or os.link+ if dest.exists():+ try:+ dest.unlink()+ except OSError:+ pass+ try:+ linker(str(src), str(dest))+ return "link"+ except (OSError, NotImplementedError, AttributeError):+ shutil.copy2(str(src), str(dest))+ return "copy"+++def _nle_segments(clips, *, probe=None) -> list[dict]:+ """The export's own view of the timeline: one row per clip, in film order.++ `probe` answers {"w","h","duration"} for a file and is injected rather than+ imported, for the same reason `compute_peaks` takes a decoder: this module+ runs no subprocess of its own, and the panel already owns ffprobe.+ """+ rows: list[dict] = []+ for c in clips or []:+ if not isinstance(c, dict):+ continue+ kind = clip_kind(c)+ fs, fe = _f(c.get("film_start")), _f(c.get("film_end"))+ if fe <= fs:+ continue+ path = str(c.get("path") or "") if kind != "slug" else ""+ if kind != "slug" and not path:+ continue+ if kind == "video":+ start, end = _f(c.get("start")), _f(c.get("end"))+ else:+ start, end = 0.0, fe - fs+ info = {}+ if path and probe:+ try:+ info = probe(path) or {}+ except Exception: # noqa: BLE001+ info = {}+ rows.append({+ "kind": kind,+ "path": path,+ "title": str(c.get("title") or (Path(path).stem if path else "black")),+ "start": start, "end": end,+ "film_start": fs, "film_end": fe,+ "brightness": clip_brightness(c),+ "fx": clip_effects(c),+ "w": int(info.get("w") or 0), "h": int(info.get("h") or 0),+ "has_audio": bool(info.get("has_audio")),+ "gain": audio_gain_points(+ c, max(0.0, clip_audio(c)["end"] - clip_audio(c)["start"]))+ if clip_kind(c) == "video" else [],+ # Carried, never applied here: the export DISABLES the audio+ # clipitem rather than dropping it, so the editor on the far end+ # can see the decision and undo it.+ "muted": clip_muted(c),+ "source_duration": _f(info.get("duration"))+ or (fe - fs if kind != "video" else 0.0),+ })+ rows.sort(key=lambda r: r["film_start"])+ return rows+++def _fcp7_levels(curve, fps: int = NLE_FPS) -> str:+ """The sound's envelope as LEVEL keyframes, which is what an NLE calls it.++ The same discipline the opacity keyframes follow: the decision travels, not+ a pre-mixed result. An editor on the far side gets a rubber-band they can+ drag rather than audio that has already been ducked into the file.++ FCP7's `audiolevels` parameter is linear 0..1 with 1 as unity, which is the+ same number `audio_gain_points` produces — so no conversion, and nothing to+ get wrong between the render and the export.+ """+ pts = list(curve or [])+ if len(pts) < 2:+ return ""+ kf = "".join(+ f"<keyframe><when>{_frames(t, fps)}</when><value>{g:.4f}</value></keyframe>"+ for t, g in pts)+ return ("<filter><effect><name>Audio Levels</name>"+ "<effectid>audiolevels</effectid>"+ "<effectcategory>audiolevels</effectcategory>"+ "<effecttype>audiolevels</effecttype><mediatype>audio</mediatype>"+ "<parameter><parameterid>level</parameterid><name>Level</name>"+ "<valuemin>0</valuemin><valuemax>3.98108</valuemax>"+ f"{kf}</parameter></effect></filter>")+++def _fcp7_opacity(seg: dict, fps: int = NLE_FPS) -> str:+ """Fades as OPACITY KEYFRAMES, which is what an NLE calls this.++ NOBODY RECEIVES BAKED PIXELS. The alternative — pre-rendering the ramp+ into the media — would hand the next room a clip they cannot un-fade, and+ the export exists so the decision travels, not just its result. Opacity is+ a standard FCP7 filter that Premiere and Resolve both import, and the+ keyframes are draggable on arrival.++ Four keyframes, or none: 0 at the head, 100 once the in-fade lands, 100+ where the out-fade starts, 0 at the tail. `clip_effects` has already+ clamped them so the middle pair cannot cross.+ """+ fx = seg.get("fx") or {}+ fin = _f(fx.get("fade_in"))+ fout = _f(fx.get("fade_out"))+ if fin <= 1e-9 and fout <= 1e-9:+ return ""+ span = max(1, _frames(_f(seg.get("film_end")) - _f(seg.get("film_start")), fps))+ keys = []+ if fin > 1e-9:+ keys.append((0, 0.0))+ keys.append((min(span, _frames(fin, fps)), 100.0))+ else:+ keys.append((0, 100.0))+ if fout > 1e-9:+ keys.append((max(0, span - _frames(fout, fps)), 100.0))+ keys.append((span, 0.0))+ else:+ keys.append((span, 100.0))+ kf = "".join(f"<keyframe><when>{w}</when><value>{v:.2f}</value></keyframe>"+ for w, v in keys)+ return ("<filter><effect><name>Opacity</name><effectid>opacity</effectid>"+ "<effectcategory>motion</effectcategory>"+ "<effecttype>motion</effecttype><mediatype>video</mediatype>"+ "<parameter><parameterid>opacity</parameterid>"+ "<name>opacity</name><valuemin>0</valuemin><valuemax>100</valuemax>"+ f"{kf}</parameter></effect></filter>")+++def _fcp7_rate(fps: int = NLE_FPS) -> str:+ # ntsc FALSE is load-bearing: at ntsc TRUE an NLE reads timebase 24 as+ # 23.976 and every cut past the first drifts one frame per 1000.+ return f"<rate><timebase>{int(fps)}</timebase><ntsc>FALSE</ntsc></rate>"+++def _fcp7_file(fid: str, seg: dict, media_abs: Path, *, fps: int,+ declared: set) -> str:+ """A `<file>` element — full the FIRST time, an id reference after.++ FCP7 XML's rule, and both importers rely on it: a file is described once+ and every later clipitem points at the same id. Re-describing it makes+ Premiere import the same clip several times as several master items.+ """+ if fid in declared:+ return f'<file id="{_xml_text(fid)}"/>'+ declared.add(fid)+ name = Path(media_abs).name+ body = [f'<file id="{_xml_text(fid)}">',+ f"<name>{_xml_text(name)}</name>",+ f"<pathurl>{_xml_text(_pathurl(media_abs))}</pathurl>",+ _fcp7_rate(fps)]+ if seg["kind"] == "video" and seg["source_duration"] > 0:+ body.append(f"<duration>{_frames(seg['source_duration'], fps)}</duration>")+ body.append("<media><video><samplecharacteristics>")+ body.append(_fcp7_rate(fps))+ if seg["w"] and seg["h"]:+ body.append(f"<width>{int(seg['w'])}</width>"+ f"<height>{int(seg['h'])}</height>")+ body.append("</samplecharacteristics></video>")+ if seg["has_audio"]:+ body.append("<audio><samplecharacteristics><depth>16</depth>"+ "<samplerate>48000</samplerate></samplecharacteristics>"+ "<channelcount>2</channelcount></audio>")+ body.append("</media></file>")+ return "".join(body)+++def fcp7_xml(segments, *, name: str, media: dict, width: int, height: int,+ base, fps: int = NLE_FPS, audio: dict | None = None,+ overlays: list | None = None) -> str:+ """The sequence, as the one XML both Premiere and Resolve import.++ SLUGS ARE GAPS. A slug could be written as a `<generatoritem>` with the+ Slug/Color effect, and the effect ids for that differ between Premiere and+ Resolve — so the "one XML for both" promise would quietly become "one XML+ for one of them, and a red error in the other". A gap on a video track+ reads as black in every NLE ever made, costs nothing, and is honest. The AE+ script, which has no such ambiguity, gets real black solids.++ THE AUDIO IS STEMS, NOT THE MIX. The clips' own sound goes on A1 and the+ soundtrack goes on A2, unducked. The under-mix the renderer builds —+ sidechain compression against the dialogue, then a tanh ceiling — has no+ representation in an NLE's timeline at all, so baking it in would hand an+ editor a bed they cannot unmix and cannot re-balance. Stems are what the+ next room actually wants.+ """+ declared: set = set()+ # ABSOLUTE pathurls, pointing at the copies in this project's OWN media/.+ # A relative pathurl is not something either importer accepts, and an+ # absolute one into the original gallery is a project that dies the first+ # time anything moves. Absolute-into-media/ is the pair that works: it+ # opens instantly here, and when the folder is handed over, Premiere and+ # Resolve both fall back to matching by NAME inside the project's own+ # directory — which is precisely where the file is.+ mdir = Path(str(base)) / "media"+ file_ids: dict = {}+ total = max([_frames(s["film_end"], fps) for s in segments] or [0])+ v_items, a_items = [], []+ for i, seg in enumerate(segments):+ if seg["kind"] == "slug":+ continue # a gap on the track IS the slug+ abs_media = mdir / media[seg["path"]]+ # THE ID IS THE SOURCE'S, NOT THE SEGMENT'S. Keying it by position+ # gave the same clip used twice two different file ids, so it was+ # described twice and Premiere imported it as two master items — the+ # exact duplication the declare-once rule exists to prevent.+ fid = "file-" + str(file_ids.setdefault(seg["path"],+ len(file_ids) + 1))+ # in/out are the SOURCE window; start/end are the FILM slot. They are+ # different clocks and conflating them is the classic FCP7 XML bug —+ # the film plays, in the wrong order, at the wrong lengths.+ f_in, f_out = _frames(seg["start"], fps), _frames(seg["end"], fps)+ f_s, f_e = _frames(seg["film_start"], fps), _frames(seg["film_end"], fps)+ v_items.append(+ f'<clipitem id="clipitem-{i + 1}">'+ f"<name>{_xml_text(seg['title'])}</name>"+ f"<enabled>TRUE</enabled>"+ f"<duration>{max(1, f_out - f_in)}</duration>"+ f"{_fcp7_rate(fps)}"+ f"<start>{f_s}</start><end>{f_e}</end>"+ f"<in>{f_in}</in><out>{f_out}</out>"+ f"{_fcp7_file(fid, seg, abs_media, fps=fps, declared=declared)}"+ f"<compositemode>normal</compositemode>"+ f"{_fcp7_opacity(seg, fps)}"+ f"</clipitem>")+ if seg["has_audio"]:+ # DISABLED, NOT DELETED. A muted clip whose audio clipitem was+ # simply omitted would arrive in Premiere as a shot that never had+ # sound, and the editor on the far end could not tell a decision+ # from a source without one. `<enabled>FALSE</enabled>` is the+ # timeline's own word for "this is here and it is off", and one+ # click puts it back.+ a_items.append(+ f'<clipitem id="clipitem-a{i + 1}">'+ f"<name>{_xml_text(seg['title'])}</name>"+ f"<enabled>{'FALSE' if seg.get('muted') else 'TRUE'}</enabled>"+ f"<duration>{max(1, f_out - f_in)}</duration>"+ f"{_fcp7_rate(fps)}"+ f"<start>{f_s}</start><end>{f_e}</end>"+ f"<in>{f_in}</in><out>{f_out}</out>"+ f'<file id="{_xml_text(fid)}"/>'+ f"<sourcetrack><mediatype>audio</mediatype>"+ f"<trackindex>1</trackindex></sourcetrack>"+ f"{_fcp7_levels(seg.get('gain'), fps)}"+ f"</clipitem>")+ # ---- V2: the overlay lane ------------------------------------------+ ov_items = []+ for j, o in enumerate(overlays or []):+ if not isinstance(o, dict):+ continue+ src = str(o.get("path") or "")+ if not src or src not in media:+ continue+ abs_media = mdir / media[src]+ fid = "file-" + str(file_ids.setdefault(src, len(file_ids) + 1))+ ofs = _frames(_f(o.get("film_start")), fps)+ ofe = _frames(_f(o.get("film_end")), fps)+ span = max(1, ofe - ofs)+ seg = {"kind": overlay_kind(o), "path": src,+ "title": str(o.get("title") or Path(src).stem),+ "start": _f(o.get("start")), "end": _f(o.get("end")) or (ofe - ofs) / float(fps),+ "film_start": _f(o.get("film_start")), "film_end": _f(o.get("film_end")),+ "w": 0, "h": 0, "has_audio": False,+ "source_duration": _f(o.get("duration")),+ "fx": clip_effects(o)}+ ov_items.append(+ f'<clipitem id="clipitem-ov{j + 1}">'+ f"<name>{_xml_text(seg['title'])}</name>"+ f"<enabled>TRUE</enabled>"+ f"<duration>{span}</duration>"+ f"{_fcp7_rate(fps)}"+ f"<start>{ofs}</start><end>{ofe}</end>"+ f"<in>{_frames(seg['start'], fps)}</in>"+ f"<out>{_frames(seg['start'], fps) + span}</out>"+ f"{_fcp7_file(fid, seg, abs_media, fps=fps, declared=declared)}"+ f"<compositemode>normal</compositemode>"+ f"{_fcp7_opacity(seg, fps)}"+ f"</clipitem>")+ ov_track = f"<track>{''.join(ov_items)}</track>" if ov_items else ""+ music_track = ""+ if audio and audio.get("path"):+ m_abs = mdir / media[str(audio["path"])]+ m_len = _frames(_f(audio.get("duration")) or (total / float(fps)), fps)+ # THE SAME WINDOW THE RENDER USES. An exported project whose music sits+ # where the trim handles did not put it is a project the editor has to+ # re-cut on arrival, which is the opposite of what the folder is for.+ win = music_window(audio)+ m_off = _frames(win["start"], fps)+ m_delay = _frames(win["delay"], fps)+ m_end = (_frames(win["end"], fps) if win["end"] is not None+ else m_off + max(1, total - m_delay))+ music_track = (+ "<track>"+ f'<clipitem id="clipitem-music">'+ f"<name>{_xml_text(m_abs.name)}</name>"+ f"<enabled>TRUE</enabled><duration>{max(1, m_len)}</duration>"+ f"{_fcp7_rate(fps)}"+ f"<start>{m_delay}</start><end>{max(m_delay + 1, total)}</end>"+ f"<in>{m_off}</in><out>{max(m_off + 1, m_end)}</out>"+ f'<file id="file-music">'+ f"<name>{_xml_text(m_abs.name)}</name>"+ f"<pathurl>{_xml_text(_pathurl(m_abs))}</pathurl>"+ f"{_fcp7_rate(fps)}"+ f"<media><audio><channelcount>2</channelcount></audio></media>"+ f"</file>"+ f"<sourcetrack><mediatype>audio</mediatype>"+ f"<trackindex>1</trackindex></sourcetrack>"+ f"</clipitem></track>")+ return (+ '<?xml version="1.0" encoding="UTF-8"?>\n'+ "<!DOCTYPE xmeml>\n"+ '<xmeml version="4">\n'+ '<sequence id="sequence-1">'+ f"<name>{_xml_text(name)}</name>"+ f"<duration>{total}</duration>"+ f"{_fcp7_rate(fps)}"+ "<media>"+ "<video>"+ "<format><samplecharacteristics>"+ f"{_fcp7_rate(fps)}"+ f"<width>{int(width)}</width><height>{int(height)}</height>"+ "<pixelaspectratio>square</pixelaspectratio>"+ "</samplecharacteristics></format>"+ # TWO VIDEO TRACKS NOW. V1 is the picture lane, which the validator+ # still refuses an overlap on. V2 is the OVERLAY lane, and it is the+ # reason a second track stopped describing a film this editor cannot+ # make: an overlay sitting on a clip is not an overlap, it is the+ # feature. Track order is the stacking order — later track, higher+ # layer — so V2 must come second.+ f"<track>{''.join(v_items)}</track>"+ f"{ov_track}"+ "</video>"+ "<audio>"+ f"<track>{''.join(a_items)}</track>"+ f"{music_track}"+ "</audio>"+ "</media>"+ "</sequence>\n"+ "</xmeml>\n")+++def ae_jsx(segments, *, name: str, media: dict, width: int, height: int,+ fps: int = NLE_FPS, audio: dict | None = None,+ overlays: list | None = None) -> str:+ """An ExtendScript that BUILDS the comp, because AE cannot import a timeline.++ It locates its own folder (`File($.fileName).parent`) and imports from the+ `media/` beside it, so the same folder that relinks in Premiere works in AE+ after being moved or handed over.+ """+ lines = [+ "// Phosphene — " + str(name),+ "// After Effects has no timeline-XML import, so this script IS the",+ "// import: run it with File > Scripts > Run Script File…",+ "// It reads the media/ folder sitting next to itself, so move the",+ "// whole folder and it still works.",+ "(function () {",+ ' var here = File($.fileName).parent;',+ " var proj = app.project || app.newProject();",+ " app.beginUndoGroup(" + _jsx_string("Import " + str(name)) + ");",+ " var comp = proj.items.addComp(%s, %d, %d, 1, %s, %d);"+ % (_jsx_string(name), int(width), int(height),+ f"{max([s['film_end'] for s in segments] or [0.0]):.6f}", int(fps)),+ " var lay;",+ " function bring(rel) {",+ " var f = new File(here.fsName + rel);",+ " if (!f.exists) { throw new Error('missing media: ' + f.fsName); }",+ " return proj.importFile(new ImportOptions(f));",+ " }",+ " function bright(layer, v) {",+ " // Brightness & Contrast. AE's Brightness is roughly [-150, 150]",+ " // against a 0-255 pixel; ffmpeg's eq=brightness is an additive",+ " // offset in [-1, 1] against a 0-1 pixel. 0.5 -> 75 is the same",+ " // half-of-half. APPROXIMATE, not a match: AE and ffmpeg do not",+ " // agree on gamma, and the render is the one that is exact.",+ " var fx = layer.property('ADBE Effect Parade')",+ " .addProperty('ADBE Brightness & Contrast 2');",+ " fx.property(1).setValue(v);",+ " }",+ ]+ for i, seg in enumerate(segments):+ ae_b = round(seg["brightness"] * 150.0, 3)+ if seg["kind"] == "slug":+ lines += [+ f" // {i + 1}: black slug",+ " lay = comp.layers.addSolid([0, 0, 0], %s, %d, %d, 1);"+ % (_jsx_string("black"), int(width), int(height)),+ ]+ else:+ rel = "/media/" + media[seg["path"]]+ lines += [+ f" // {i + 1}: {seg['kind']}",+ " lay = comp.layers.add(bring(%s));" % _jsx_string(rel),+ ]+ # startTime is where frame 0 of the SOURCE would sit, so a clip+ # trimmed from 2.0 s starts 2 s before its own in-point. Set it+ # BEFORE in/out or AE clamps the trim to the wrong window. A still+ # has no source window, so its frame 0 is its slot — and leaving+ # startTime at 0 would let AE's default two-second still duration+ # clamp any hold longer than that.+ lines.append(" lay.startTime = %.6f;"+ % (seg["film_start"] - seg["start"]))+ lines += [+ " lay.inPoint = %.6f;" % seg["film_start"],+ " lay.outPoint = %.6f;" % seg["film_end"],+ ]+ if abs(seg["brightness"]) >= 1e-9:+ lines.append(" bright(lay, %s);" % ae_b)+ fx = seg.get("fx") or {}+ f_in, f_out = _f(fx.get("fade_in")), _f(fx.get("fade_out"))+ if f_in > 1e-9 or f_out > 1e-9:+ # OPACITY KEYFRAMES, not a pre-rendered ramp: the editor on the+ # far side gets a fade they can drag, and AE's own timeline is+ # where a fade belongs.+ fs, fe = _f(seg["film_start"]), _f(seg["film_end"])+ pts = []+ if f_in > 1e-9:+ pts += [(fs, 0), (fs + f_in, 100)]+ else:+ pts += [(fs, 100)]+ if f_out > 1e-9:+ pts += [(fe - f_out, 100), (fe, 0)]+ else:+ pts += [(fe, 100)]+ lines.append(" op = lay.property('ADBE Transform Group')"+ ".property('ADBE Opacity');")+ for when, val in pts:+ lines.append(" op.setValueAtTime(%.6f, %d);" % (when, val))+ gain = seg.get("gain") or []+ if len(gain) >= 2:+ # AE'S AUDIO LEVELS ARE dB, so the linear curve is converted here+ # and nowhere else — one conversion, at the one seam that needs it.+ # -96 dB is AE's own floor for silence; log(0) is not a number.+ lines.append(" au = lay.property('ADBE Audio Group')"+ ".property('ADBE Audio Levels');")+ fs = _f(seg["film_start"])+ for t, g in gain:+ db = -96.0 if g <= 1e-6 else max(-96.0, 20.0 * math.log10(g))+ lines.append(" au.setValueAtTime(%.6f, [%.3f, %.3f]);"+ % (fs + t, db, db))+ if seg.get("muted") and seg["kind"] != "slug":+ # The audio SWITCH, which is what AE's timeline calls the same+ # decision — the layer keeps its sound and does not play it.+ lines.append(" lay.audioEnabled = false;")+ # ---- THE OVERLAY LANE, on top ---------------------------------------+ # `comp.layers.add` inserts at index 1, so whatever is added LAST sits+ # highest. Adding the cards after every picture layer is the whole of the+ # stacking order — no index arithmetic, and it cannot drift.+ for j, o in enumerate(overlays or []):+ if not isinstance(o, dict):+ continue+ src = str(o.get("path") or "")+ if not src or src not in media:+ continue+ rel = "/media/" + media[src]+ ofs, ofe = _f(o.get("film_start")), _f(o.get("film_end"))+ lines += [+ f" // overlay {j + 1}: {overlay_kind(o)}",+ " lay = comp.layers.add(bring(%s));" % _jsx_string(rel),+ " lay.startTime = %.6f;" % ofs,+ " lay.inPoint = %.6f;" % ofs,+ " lay.outPoint = %.6f;" % ofe,+ ]+ e = clip_effects(o)+ if e["fade_in"] > 1e-9 or e["fade_out"] > 1e-9:+ pts = []+ if e["fade_in"] > 1e-9:+ pts += [(ofs, 0), (ofs + e["fade_in"], 100)]+ else:+ pts += [(ofs, 100)]+ if e["fade_out"] > 1e-9:+ pts += [(ofe - e["fade_out"], 100), (ofe, 0)]+ else:+ pts += [(ofe, 100)]+ lines.append(" op = lay.property('ADBE Transform Group')"+ ".property('ADBE Opacity');")+ for when, val in pts:+ lines.append(" op.setValueAtTime(%.6f, %d);" % (when, val))+ if audio and audio.get("path"):+ rel = "/media/" + media[str(audio["path"])]+ win = music_window(audio)+ lines += [+ " // the soundtrack, as its own layer and NOT the ducked mix —",+ " // the render's under-mix is not representable here, and stems",+ " // are what an editor wants anyway.",+ " lay = comp.layers.add(bring(%s));" % _jsx_string(rel),+ # startTime is where the track's OWN second zero would sit on the+ # comp: the film second the music starts at, less how far into the+ # track that second is. `+ 0.0` because -0.0 formats as+ # "-0.000000", which is valid ExtendScript and reads like a bug to+ # whoever opens the file.+ " lay.startTime = %.6f;"+ % (win["delay"] - win["start"] + 0.0),+ ]+ if win["delay"] > 1e-6 or win["end"] is not None:+ # Only when the music was actually moved or trimmed — an untouched+ # soundtrack keeps the script it has always produced.+ end_film = (win["delay"] + (win["end"] - win["start"])+ if win["end"] is not None+ else max([s["film_end"] for s in segments] or [0.0]))+ lines += [+ " lay.inPoint = %.6f;" % win["delay"],+ " lay.outPoint = %.6f;" % max(win["delay"] + 1e-3, end_film),+ ]+ lines += [+ " comp.openInViewer();",+ " app.endUndoGroup();",+ "})();",+ "",+ ]+ return "\n".join(lines)+++def export_nle(clips, dest_dir, *, name: str, fps: int = NLE_FPS,+ audio: dict | None = None, probe=None, link=None,+ width: int = 0, height: int = 0,+ overlays: list | None = None) -> dict:+ """Write `<name>_project/` — one XML, one AE script, and the media beside them.++ Returns {"ok", "dir", "xml", "jsx", "clips", "linked", "copied",+ "missing", "width", "height", "duration"}.+ """+ import shutil # noqa: PLC0415, F401+ segs = _nle_segments(clips, probe=probe)+ if not segs:+ raise EditError("there is nothing on the timeline to export")+ root = Path(str(dest_dir)) / f"{_slug(name, 60)}_project"+ media_dir = root / "media"+ media_dir.mkdir(parents=True, exist_ok=True)++ if not width or not height:+ width = max([s["w"] for s in segs] or [0]) or 1024+ height = max([s["h"] for s in segs] or [0]) or 576+ width += width % 2+ height += height % 2++ taken: dict = {}+ media: dict = {}+ linked = copied = 0+ missing: list[str] = []+ ovs = [o for o in (overlays or []) if isinstance(o, dict)+ and str(o.get("path") or "")]+ wanted = [s["path"] for s in segs if s["path"]]+ # The cards travel with the project like every other source, so the folder+ # opens on another machine with the overlay intact.+ wanted += [str(o["path"]) for o in ovs]+ if audio and audio.get("path"):+ wanted.append(str(audio["path"]))+ for src_str in wanted:+ if src_str in media:+ continue+ src = Path(src_str)+ if not src.is_file():+ missing.append(src_str)+ continue+ rel = _nle_media_name(src, taken)+ media[src_str] = rel+ how = _link_or_copy(src, media_dir / rel, link=link)+ linked += (how == "link")+ copied += (how == "copy")+ # A clip whose file has gone cannot be written into the XML — a pathurl to+ # nothing is an offline clip the editor has to hunt for, and silence about+ # it is worse than the gap.+ segs = [s for s in segs if not s["path"] or s["path"] in media]+ a_arg = audio if (audio and str(audio.get("path") or "") in media) else None++ xml_path = root / f"{_slug(name, 60)}.xml"+ jsx_path = root / f"{_slug(name, 60)}_ae.jsx"+ xml_path.write_text(+ fcp7_xml(segs, name=name, media=media, width=width, height=height,+ overlays=ovs,+ base=root, fps=fps, audio=a_arg), encoding="utf-8")+ jsx_path.write_text(+ ae_jsx(segs, name=name, media=media, width=width, height=height,+ overlays=ovs,+ fps=fps, audio=a_arg), encoding="utf-8")+ return {+ "ok": True, "dir": str(root), "xml": str(xml_path),+ "jsx": str(jsx_path), "clips": len(segs),+ "linked": linked, "copied": copied, "missing": missing,+ "media": sorted(media.values()),+ "width": width, "height": height,+ "duration": round(max([s["film_end"] for s in segs] or [0.0]), 3),+ }+++# ===========================================================================+# PART C3 — DRAFTS: the user's own saves, and a backup that never overwrites one+# ===========================================================================+# THE OWNER, AFTER LOSING TWENTY MINUTES TO AN AUTOSAVE HE COULD NOT SEE:+# "the auto-saving function — I think it is not good. It's better that the+# user has the power to manage this feature. You can keep a backup in case+# it's needed... but he should have control over the saving, and only he+# should have that control. Additionally, renaming and access to all the+# drafts he makes are essential. He should be able to start a new draft and+# work on it, as well as copy and paste drafts."+#+# So: SAVE IS THE USER'S VERB. Nothing else writes the document he named.+#+# WHERE THINGS LIVE, AND WHY EDIT.JSON DID NOT MOVE. The ACTIVE draft is+# `edit.json` — the same path the renderer, the exporter, the payload and+# every board on disk already read. Only the INACTIVE drafts sit in+# `drafts/<slug>.json`. That is one copy of any draft, ever: nothing can+# diverge from itself, and a board written before drafts existed becomes a+# board with exactly one draft the first time anybody looks, with no+# migration pass and nothing to half-finish.+#+# THE BACKUP IS A DIFFERENT FILE ON PURPOSE. `history/backup-<slug>.json`+# never touches edit.json and never bumps a revision, so a crash costs the+# user nothing and a working session costs him no surprises. On open, a+# backup newer than the saved draft is an OFFER — see `pending_backup` — and+# applying it is a click, never a side effect.+DRAFT_INDEX_VERSION = 1+DRAFT_NAME_MAX = 60+_BACKUP_PREFIX = "backup-"+++def drafts_dir(board_dir) -> Path:+ return Path(str(board_dir)) / "drafts"+++def _draft_index_path(board_dir) -> Path:+ return drafts_dir(board_dir) / "index.json"+++def _draft_slug(name: str, taken) -> str:+ base = _slug(name, 40) or "draft"+ slug, n = base, 2+ while slug in taken:+ slug = f"{base}-{n}"+ n += 1+ return slug+++def load_draft_index(board_dir) -> dict:+ """The index, MIGRATING a pre-drafts board on the way out.++ A board that has only `edit.json` has exactly one draft and always did —+ it just had no name for it. Naming it here (rather than in a migration+ pass that rewrites files) means the upgrade cannot half-happen: the worst+ case is a board that gets its index written the first time it is read.+ """+ p = _draft_index_path(board_dir)+ idx = None+ if p.is_file():+ try:+ data = json.loads(p.read_text(encoding="utf-8"))+ if isinstance(data, dict) and isinstance(data.get("drafts"), list):+ idx = data+ except (OSError, ValueError):+ idx = None+ if idx is None:+ idx = {"version": DRAFT_INDEX_VERSION, "active": "draft-1",+ "drafts": [{"slug": "draft-1", "name": "Draft 1",+ "created_at": int(time.time())}]}+ rows = [d for d in idx.get("drafts") or []+ if isinstance(d, dict) and d.get("slug")]+ if not rows:+ rows = [{"slug": "draft-1", "name": "Draft 1",+ "created_at": int(time.time())}]+ idx["drafts"] = rows+ if idx.get("active") not in {d["slug"] for d in rows}:+ idx["active"] = rows[0]["slug"]+ idx["version"] = DRAFT_INDEX_VERSION+ return idx+++def _save_draft_index(board_dir, idx: dict) -> Path:+ drafts_dir(board_dir).mkdir(parents=True, exist_ok=True)+ return _atomic_json(_draft_index_path(board_dir), idx, prefix=".drafts-")+++def _draft_file(board_dir, slug: str) -> Path:+ return drafts_dir(board_dir) / f"{_slug(str(slug), 40)}.json"+++def _draft_stats(doc) -> dict:+ if not isinstance(doc, dict):+ return {"clips": None, "duration": None, "revision": None,+ "saved_at": None}+ clips = doc.get("clips")+ return {"clips": len(clips) if isinstance(clips, list) else 0,+ "duration": edit_duration(doc),+ "revision": int(doc.get("revision") or 0),+ "saved_at": (int(doc["updated_at"])+ if isinstance(doc.get("updated_at"), (int, float))+ else None)}+++def _read_json(path: Path):+ try:+ return json.loads(Path(path).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+++def list_drafts(board_dir) -> list[dict]:+ """Every draft this film has, the active one marked, with what it holds."""+ idx = load_draft_index(board_dir)+ out = []+ for d in idx["drafts"]:+ active = (d["slug"] == idx["active"])+ doc = _read_json(edit_path(board_dir) if active+ else _draft_file(board_dir, d["slug"]))+ row = {"slug": d["slug"], "name": d.get("name") or d["slug"],+ "active": active,+ "created_at": d.get("created_at"),+ "exists": doc is not None}+ row.update(_draft_stats(doc))+ out.append(row)+ return out+++def _stash_active(board_dir, idx: dict) -> None:+ """Put the active draft where an inactive one lives. Never loses it."""+ cur = edit_path(board_dir)+ if not cur.is_file():+ return+ doc = _read_json(cur)+ if doc is None:+ return+ drafts_dir(board_dir).mkdir(parents=True, exist_ok=True)+ _atomic_json(_draft_file(board_dir, idx["active"]), doc, prefix=".draft-")+++def create_draft(board_dir, name: str, *, from_current: bool = False) -> dict:+ """A new draft, empty or copied from what is on screen. Becomes active.++ `from_current` is the "work on a variation without risking this one"+ gesture — the whole reason the owner asked for copy-and-paste drafts.+ """+ text = str(name or "").strip()[:DRAFT_NAME_MAX] or "Untitled draft"+ idx = load_draft_index(board_dir)+ slug = _draft_slug(text, {d["slug"] for d in idx["drafts"]})+ # MIGRATED, LIKE EVERY OTHER READ. `validate_edit` refuses any version but+ # the current one and `save_edit` refuses what it complains about, so+ # handing the raw file to save_edit meant copying a draft raised+ # "edit version 1 — this build understands 2" on every board written+ # before EDIT_VERSION went to 2 — which is every board anybody already+ # had. Migration is a read-path job and this is a read.+ current = migrate_edit(_read_json(edit_path(board_dir)) or {}) or {}+ _stash_active(board_dir, idx)+ if from_current and current:+ doc = dict(current)+ else:+ # An EMPTY draft still carries the soundtrack and the beat grid: they+ # are facts about the film, not about the arrangement, and re-pointing+ # at the track for every new idea is work nobody asked for.+ doc = {"version": EDIT_VERSION, "board_id": current.get("board_id", ""),+ "source": "human", "clips": [], "settings": {},+ "audio": current.get("audio"),+ "beats": current.get("beats")}+ doc["revision"] = 0+ return _land_draft(board_dir, idx, slug, text, doc)+++def duplicate_draft(board_dir, slug: str, name: str = "") -> dict:+ """Copy a draft under a new name. The copy becomes active."""+ idx = load_draft_index(board_dir)+ known = {d["slug"]: d for d in idx["drafts"]}+ src = str(slug or idx["active"])+ if src not in known:+ raise EditError("there is no draft by that name")+ doc = _read_json(edit_path(board_dir) if src == idx["active"]+ else _draft_file(board_dir, src))+ if doc is None:+ raise EditError("that draft has nothing in it to copy")+ text = (str(name or "").strip()[:DRAFT_NAME_MAX]+ or f"{known[src].get('name') or src} copy")+ return _land_copy(board_dir, idx, text, migrate_edit(doc))+++def _land_copy(board_dir, idx: dict, text: str, doc: dict) -> dict:+ new_slug = _draft_slug(text, {d["slug"] for d in idx["drafts"]})+ _stash_active(board_dir, idx)+ doc = dict(doc)+ doc["revision"] = 0+ return _land_draft(board_dir, idx, new_slug, text, doc)+++def _land_draft(board_dir, idx: dict, slug: str, text: str, doc: dict) -> dict:+ """Write the new draft's document, THEN point the index at it.++ ORDER IS THE WHOLE FUNCTION. The index used to be saved first, so a+ document `save_edit` refused left the film pointing at a draft that was+ never written: `list_drafts` showed the new name as the ACTIVE one while+ `edit.json` still held the old draft's arrangement, and the client was+ told 400 for an index it could not see had already moved. A write that+ lands and then a pointer that follows it cannot produce that state.++ The archive `save_edit` makes on the way past also lands correctly this+ way round — the outgoing document belongs to the draft that is still+ active, not to the one being created.+ """+ save_edit(board_dir, doc)+ idx["drafts"].append({"slug": slug, "name": text,+ "created_at": int(time.time())})+ idx["active"] = slug+ _save_draft_index(board_dir, idx)+ return {"slug": slug, "name": text}+++def rename_draft(board_dir, slug: str, name: str) -> dict:+ """A NAME CHANGE IS NOT A FILE MOVE. The slug is the identity and it stays+ put, so renaming can never orphan a draft's file or its backup."""+ text = str(name or "").strip()[:DRAFT_NAME_MAX]+ if not text:+ raise EditError("a draft needs a name")+ idx = load_draft_index(board_dir)+ for d in idx["drafts"]:+ if d["slug"] == str(slug):+ d["name"] = text+ _save_draft_index(board_dir, idx)+ return {"slug": d["slug"], "name": text}+ raise EditError("there is no draft by that name")+++def delete_draft(board_dir, slug: str) -> dict:+ """Remove a draft. The LAST one cannot go, and neither can the active one+ without something to land on — an editor with no document is not a state+ this app has, and inventing it here would be inventing a bug."""+ idx = load_draft_index(board_dir)+ rows = idx["drafts"]+ if len(rows) < 2:+ raise EditError("this is the film's only draft")+ target = str(slug)+ if target not in {d["slug"] for d in rows}:+ raise EditError("there is no draft by that name")+ was_active = (idx["active"] == target)+ if was_active:+ # Land on the neighbour FIRST, then drop the file — so a failure+ # halfway leaves a film with a document rather than without one.+ others = [d["slug"] for d in rows if d["slug"] != target]+ activate_draft(board_dir, others[0])+ idx = load_draft_index(board_dir)+ rows = idx["drafts"]+ try:+ _draft_file(board_dir, target).unlink()+ except OSError:+ pass+ try:+ _backup_path(board_dir, target).unlink()+ except OSError:+ pass+ # "Its past saves go with it" — what the panel says when it asks, and now+ # what happens. A draft's history is its own folder, so this is one call+ # rather than a glob nobody can prove is scoped right.+ import shutil # noqa: PLC0415+ shutil.rmtree(history_dir(board_dir, target), ignore_errors=True)+ idx["drafts"] = [d for d in rows if d["slug"] != target]+ _save_draft_index(board_dir, idx)+ return {"active": idx["active"], "deleted": target}+++def activate_draft(board_dir, slug: str) -> dict:+ """Switch which draft `edit.json` is. The outgoing one is stashed first."""+ idx = load_draft_index(board_dir)+ target = str(slug)+ if target not in {d["slug"] for d in idx["drafts"]}:+ raise EditError("there is no draft by that name")+ if target == idx["active"]:+ return {"active": target, "changed": False}+ _stash_active(board_dir, idx)+ doc = _read_json(_draft_file(board_dir, target))+ if doc is None:+ # A draft whose file never landed (created, never saved) opens empty+ # rather than refusing — the alternative is a name in the list that+ # cannot be clicked.+ doc = {"version": EDIT_VERSION, "revision": 0, "source": "human",+ "clips": [], "settings": {}, "audio": None, "beats": None}+ doc = migrate_edit(doc)+ doc["revision"] = int(doc.get("revision") or 0)+ # The document lands BEFORE the pointer moves, for the reason spelled out+ # in `_land_draft`: an index that points at a document which was never+ # written is a film whose active draft holds another draft's arrangement.+ save_edit(board_dir, doc)+ idx["active"] = target+ _save_draft_index(board_dir, idx)+ try:+ _draft_file(board_dir, target).unlink()+ except OSError:+ pass+ return {"active": target, "changed": True}+++# ---- the quiet lane -------------------------------------------------------+def _snapshot_paths(board_dir, slug: str = "") -> list[Path]:+ """Every snapshot of one draft, OLDEST FIRST. The legacy slot counts as one.++ Rule 6: nothing on disk is deleted. A board written before the lane was+ versioned has a single `backup-<draft>.json`, and it is read as the oldest+ snapshot of that draft rather than ignored or thrown away.+ """+ idx_slug = str(slug or load_draft_index(board_dir)["active"])+ hist = history_dir(board_dir, idx_slug)+ # MOVED, NOT READ IN PLACE. A legacy slot left at the root of history/ is+ # invisible to `list_history` and unreachable by `restore_edit`, both of+ # which are scoped to the draft's own folder — so it would have been a+ # snapshot the user could be told about and could not open. Renaming it+ # into the lane makes it a version like any other, and renaming is not+ # deleting: rule 6 holds.+ legacy = _backup_path(board_dir, idx_slug)+ if legacy.is_file():+ try:+ stamp = int(legacy.stat().st_mtime * 1000)+ except OSError:+ stamp = 0+ hist.mkdir(parents=True, exist_ok=True)+ dst = hist / f"{_SNAP_PREFIX}{stamp:013d}-000.json"+ bump = 0+ while dst.exists():+ bump += 1+ dst = hist / f"{_SNAP_PREFIX}{stamp:013d}-{bump:03d}.json"+ try:+ legacy.replace(dst)+ except OSError:+ pass+ out: list[Path] = []+ if hist.is_dir():+ out.extend(sorted(p for p in hist.glob(f"{_SNAP_PREFIX}*.json")+ if p.is_file()))+ return out+++def latest_snapshot(board_dir, slug: str = "") -> tuple[Path, dict] | None:+ """The newest readable snapshot of one draft, or None."""+ for p in reversed(_snapshot_paths(board_dir, slug)):+ doc = _read_json(p)+ if isinstance(doc, dict):+ return p, doc+ return None+++def prune_snapshots(board_dir, *, keep: int = SNAPSHOT_KEEP) -> int:+ """Drop the oldest snapshots past the cap. Losing one is not an event."""+ paths = _snapshot_paths(board_dir)+ gone = 0+ for stale in paths[:max(0, len(paths) - int(keep))]:+ try:+ stale.unlink()+ gone += 1+ except OSError:+ continue+ return gone+++def _backup_path(board_dir, slug: str) -> Path:+ # The crash lane sits at the ROOT of history/, beside the drafts' folders+ # rather than inside one: it is not a past save, and `list_history` walks+ # a draft's folder without needing to know it exists.+ return _history_root(board_dir) / f"{_BACKUP_PREFIX}{_slug(str(slug), 40)}.json"+++def write_backup(board_dir, edit: dict, *, draft: str = "",+ session: str = "") -> Path:+ """Crash insurance for the ACTIVE draft. Writes nothing the user owns.++ Validated like any other document — a backup that cannot be restored is+ not a backup — but it never lands on `edit.json` and never moves a+ revision, so the saved draft on disk is exactly what the user last saved+ and nothing else.++ `draft` IS THE PAYLOAD'S OWN ACCOUNT OF WHERE IT CAME FROM, and it is+ checked rather than trusted. The backup is debounced on the client and the+ server is threaded, so a write composed while draft A was on screen can+ arrive after the user has clicked draft B — and a backup filed under B's+ name is A's arrangement offered back as B's unsaved work, which+ `recover_backup` would then install over B's saved document. A caller that+ names its draft gets refused when it has left; one that names nothing+ keeps the old behaviour.+ """+ # THE SAFETY NET MAY NOT HAVE AN OPINION. A backup that refuses is the one+ # failure this file exists to prevent, so it declines only on the errors+ # that would make the document unrestorable.+ errs = blocking_errors(validate_edit(edit))+ if errs:+ raise EditError("; ".join(e["message"] for e in errs[:3]))+ idx = load_draft_index(board_dir)+ want = str(draft or "").strip()+ if want and want != idx["active"]:+ raise EditError("that backup belongs to a draft you have left")+ # WRITING IS WHAT CLAIMS THE BOARD, and it is the only thing that does.+ # This used to REFUSE a session that did not hold the claim, and the claim+ # was taken by loading the page — so opening the film in a second tab, or+ # in a headless browser, or as an agent, silently stopped the snapshot lane+ # in the tab the person was working in. The refusal is gone; the claim+ # moves to whoever is actually editing.+ if str(session or "").strip():+ try:+ claim_session(board_dir, session)+ except EditError:+ pass+ doc = normalise_edit(edit)+ # AN IDENTICAL SNAPSHOT IS NOT A SNAPSHOT. The lane is 20 files deep, and+ # on the day this was written it took ten of them in fifteen seconds — same+ # revision, same clips, same digest — which is half the net spent on one+ # arrangement and, worse, half the DISTINCT history evicted to hold it. The+ # debounce is doing its job; what it cannot know is that the timer it fired+ # was armed by something that did not change the film. `edit_digest` is the+ # same fingerprint `pending_backup` compares on, so "nothing to snapshot"+ # here means exactly "nothing that lane would have offered you".+ newest = latest_snapshot(board_dir, idx["active"])+ if newest is not None and edit_digest(newest[1]) == edit_digest(doc):+ return newest[0]+ doc["origin"] = "backup"+ doc["backup_of"] = idx["active"]+ doc["backed_up_at"] = int(time.time())+ # The revision `edit.json` stood at when this was composed. Nothing gates+ # on it today — the offer ends when the user ANSWERS it, not when a clock+ # says so — but a file on its own can now say which save it followed.+ doc["backup_revision"] = int((_read_json(edit_path(board_dir)) or {})+ .get("revision") or 0)+ # ONE FILE PER SNAPSHOT. The lane never overwrites and therefore never+ # has to stop: a new snapshot beside the last one cannot destroy work an+ # unanswered offer is holding, which is the entire reason the old single+ # slot had to be guarded and the guard switched the safety net off.+ hist = history_dir(board_dir, idx["active"])+ hist.mkdir(parents=True, exist_ok=True)+ # Named by the clock, and made unique when the clock does not move: two+ # snapshots inside one millisecond are ordinary on a fast machine, and a+ # collision here would be the overwrite this lane exists to make+ # impossible.+ # The counter is ALWAYS present, never appended only on collision: a name+ # that grows a suffix sorts BEFORE the one it collided with ('-' < '.'),+ # so the bumped file would have read as the older of the two and the lane+ # would have handed back the wrong snapshot. Uniform names sort right.+ stamp = int(time.time() * 1000)+ bump = 0+ dst = hist / f"{_SNAP_PREFIX}{stamp:013d}-{bump:03d}.json"+ while dst.exists():+ bump += 1+ dst = hist / f"{_SNAP_PREFIX}{stamp:013d}-{bump:03d}.json"+ out = _atomic_json(dst, doc, prefix=".snap-")+ prune_snapshots(board_dir)+ return out+++def pending_backup(board_dir) -> dict | None:+ """Unsaved work sitting in the crash lane, or None.++ This is an OFFER, never an action: the panel shows what is in it and the+ user decides. Silently applying it would be the autosave he asked us to+ remove, wearing a different name.++ AN OFFER ENDS WHEN THE USER ANSWERS IT — Save deletes the file, Recover+ applies it, Discard drops it. It used to end when a clock said so, and the+ clock was wrong in both directions: `backed_up_at` and `updated_at` are+ whole seconds, so a backup written just BEFORE a save read as newer than+ it; and every write that is not the user's — a draft switch, an+ auto-edit, a restore — moved `updated_at` forward and buried an offer that+ still held the only copy of somebody's afternoon. What is left is the one+ honest reason not to ask: the backup holds nothing the saved draft does+ not already have.+ """+ idx = load_draft_index(board_dir)+ newest = latest_snapshot(board_dir, idx["active"])+ if newest is None:+ return None+ p, doc = newest+ saved = _read_json(edit_path(board_dir)) or {}+ stats = _draft_stats(doc)+ # CONTENT, BY DIGEST. The old test was `json.dumps(clips)` on both sides,+ # and `_sbe_payload` rewrites every clip's `proxy` on the way out — so the+ # client's copy differed from the file in a field the user has never heard+ # of, on any board whose proxies were built after its last save, forever.+ # `edit_digest` compares the arrangement and ignores everything derived.+ if edit_digest(doc) == edit_digest(saved):+ return None+ return {"file": p.name, "at": int(doc.get("backed_up_at") or 0),+ "draft": idx["active"], "clips": stats["clips"],+ "duration": stats["duration"]}+++def recover_backup(board_dir) -> dict:+ """Apply the pending backup, keeping the saved draft it replaces.++ IT RECOVERS ONLY WHAT THE PANEL WOULD HAVE OFFERED. A client can hold a+ stale offer — it saved a second ago, the file is gone, the amber bar is+ still on screen in another tab — and applying that would archive the good+ save and install an older arrangement over it, which is the exact loss the+ backup exists to prevent, arriving through the recovery button.+ """+ idx = load_draft_index(board_dir)+ newest = latest_snapshot(board_dir, idx["active"])+ if newest is None:+ raise EditError("there is no snapshot to restore")+ _, doc = newest+ if pending_backup(board_dir) is None:+ raise EditError("that backup is older than your last save — "+ "everything in it is already in this draft")+ doc = migrate_edit(dict(doc))+ doc.pop("backup_of", None)+ doc.pop("backed_up_at", None)+ doc["origin"] = "manual" # recovering IS the user's decision+ saved = _read_json(edit_path(board_dir))+ if isinstance(saved, dict):+ archive_edit(board_dir, saved)+ prune_history(board_dir)+ doc["revision"] = int(saved.get("revision") or 0)+ # BLOCKING ONLY — the same rule `save_edit` and `write_backup` apply.+ # Using the raw list here meant a WARNING refused the recovery of work+ # that had been perfectly legal to write: `clips_audio_overlap` is in+ # WARNING_CODES, and it is what an ordinary J-cut reports. So a crash+ # over a split edit — the feature this editor exists for — wrote a+ # backup fine and then refused to give it back, permanently, because+ # the offer is never discarded on the failure path and an unanswered+ # offer suppresses further snapshots. Persisting the user's work wins.+ errs = blocking_errors(validate_edit(doc))+ if errs:+ raise EditError("that backup cannot be recovered: "+ + "; ".join(e["message"] for e in errs[:3]))+ save_edit(board_dir, doc)+ discard_backup(board_dir)+ return load_edit(board_dir)+++def discard_backup(board_dir) -> bool:+ """Answer the offer by dropping the newest snapshot. The rest stay.++ A save also calls this, and it means the same thing there: what the chip+ was offering is now in the document, so the chip has nothing to say.+ """+ idx = load_draft_index(board_dir)+ newest = latest_snapshot(board_dir, idx["active"])+ if newest is None:+ return False+ try:+ newest[0].unlink()+ return True+ except OSError:+ return Falsediff --git a/storyboard_planner.py b/storyboard_planner.pyindex c4ef494..4a98c47 100644--- a/storyboard_planner.py+++ b/storyboard_planner.py@@ -544,6 +544,9 @@ def _build_user_prompt(style: str,cast: Sequence[Dict[str, str]],must_include: Sequence[str],+ locations: Sequence[Dict[str, str]] = (),+ screenplay: str = "",+ floor_plan: str = "",) -> str:lines = ["BRIEF", "", "CONCEPT: %s" % concept.strip(), "", "SHOT COUNT: exactly %d shots." % n_shots]if style and style.strip():@@ -584,15 +587,404 @@ def _build_user_prompt(]else:lines += ["", "CAST: none. Every shot sets \"character_id\": null."]+ if locations:+ # The room is injected into the prompt LATER, from the board, for every+ # shot that names it. The model is told about them anyway so it writes+ # shots that belong somewhere, and so it does not spend its own prose+ # re-describing scenery that is about to be appended underneath it.+ lines += ["", "LOCATIONS - the film happens in these places, and ONLY these:"]+ has_views = False+ for loc in locations:+ lines.append(" - %s: %s" % (loc.get("name") or loc.get("id"),+ (loc.get("description") or "").strip()))+ views = [v for v in (loc.get("views") or [])+ if isinstance(v, dict) and v.get("id") and v.get("description")]+ if not views:+ continue+ has_views = True+ lines.append(" VIEWS of %s - which way the camera points. Every shot here"+ " picks ONE, by id:" % (loc.get("name") or loc.get("id")))+ for v in views:+ lines.append(" * %s (%s): %s" % (+ str(v.get("id")).strip(), str(v.get("name") or "").strip(),+ str(v.get("description") or "").strip()))+ lines += [+ " Every shot sets \"location\" to one of the names above, exactly as written.",+ " DO NOT describe the place in the shot description - it is added automatically",+ " from the line above, identically on every shot that names it. Describe the",+ " PEOPLE, the ACTION and the FRAMING only. A shot that re-describes the room in",+ " its own words is how the same room comes back as four different rooms.",+ ]+ if has_views:+ lines += ["", _GEOGRAPHY_LAWS]if must_include:lines += ["", "MUST APPEAR somewhere in the film:"]for m in must_include:lines.append(" - %s" % str(m).strip())+ if floor_plan and floor_plan.strip():+ # WHERE EVERYTHING IS, written once. The views above are derived from+ # this paragraph, and a shot that knows what is behind whom stops+ # inventing a new room every time the camera turns around.+ lines += ["", "THE FLOOR PLAN. This is the space the scene happens in. It is",+ "already decided - do not move anybody, and do not re-describe it in a",+ "shot:", "", floor_plan.strip(), ""]+ if screenplay and screenplay.strip():+ # The scene, written first and handed down. Without this the model is+ # asked to invent structure and coverage in the same breath, and what+ # comes back is a run of equally-weighted moments — the owner's words:+ # "It is not working properly. It's just a succession of shots."+ lines += ["", "THE SCENE. This has already been written. Your job is to SHOOT it,",+ "not to rewrite it. Cover these beats in order, keep every spoken line",+ "word for word, and put each line in the shot where it is spoken:", "",+ screenplay.strip(), "",+ "A beat with no line is a shot with no line. Do not invent dialogue for",+ "it and do not say that someone speaks in it."]lines += ["", "Return the JSON object now. %d shots. Nothing before it, nothing after it."% n_shots]return "\n".join(lines)+_SCREENPLAY_SYSTEM = """\+You are a screenwriter. You write the SCENE, not a shot list. Prose and dialogue only.++Rules:+1. It is ONE continuous scene in ONE place, unless the brief names more. Everyone in it can+ see and hear everyone else. Do not cut to somewhere nobody could hear the last line.+2. Give it a shape: an opening, a turn in the middle, and a button at the end. A run of+ equally-weighted moments is not a scene.+3. WRITE THE ACTUAL LINES. Every line of dialogue is words a person says out loud, in double+ quotes, attributed by name. Never "he explains the situation" — write what he says.+4. Spread the dialogue across the scene. Do not put every line in the first beat.+5. Some beats have no dialogue at all. Those are where the scene breathes; say what the+ person is DOING instead.+6. Keep it short: 8-14 beats, one or two sentences each. This is a 30-60 second scene.++Output plain text, one beat per line, in this form:++ BEAT - <what happens, present tense>+ NAME: "the line, exactly as spoken"++No preamble, no headings, no shot numbers, no camera directions. The camera is not your job.+"""+++def _screenplay_text(resp: Dict[str, Any]) -> str:+ """The scene out of a generate() response, or "" if there is nothing usable.++ Small models like to answer a screenwriting brief with a paragraph of+ preamble ("Sure! Here is the scene:"), and a scene that begins with that+ would be handed to the shot pass as if it were a beat. Keep only the lines+ that look like the form that was asked for, and if none do, return nothing+ and let the plan proceed exactly as it did before this pass existed.+ """+ text = (resp or {}).get("text") or ""+ keep = [ln.rstrip() for ln in text.splitlines()+ if _SCREENPLAY_LINE_RE.match(ln.strip())]+ if len(keep) < 3:+ return ""+ return "\n".join(keep)[:4000]+++# A beat line or an attributed line of dialogue. Anything else is chatter.+_SCREENPLAY_LINE_RE = re.compile(r"^(?:BEAT\b|[A-Z][A-Za-z0-9 _\'-]{0,30}:)")+++def _build_screenplay_prompt(concept: str, n_shots: int, style: str,+ cast: Sequence[Dict[str, str]],+ must_include: Sequence[str],+ locations: Sequence[Dict[str, str]] = ()) -> str:+ lines = ["CONCEPT: %s" % (concept or "").strip(), "",+ "LENGTH: about %d beats." % max(6, min(14, n_shots))]+ if cast:+ lines += ["", "WHO IS IN IT:"]+ for c in cast:+ who = c.get("name") or c.get("id")+ noun = (c.get("subject_noun") or "").strip()+ lines.append(" - %s%s" % (who, (" (%s)" % noun) if noun else ""))+ lines.append(" Use these names in the dialogue attributions.")+ if locations:+ lines += ["", "WHERE:"]+ for loc in locations:+ lines.append(" - %s: %s" % (loc.get("name") or loc.get("id"),+ (loc.get("description") or "").strip()))+ if len(locations) == 1:+ lines.append(" The whole scene happens HERE. Nobody leaves.")+ if must_include:+ lines += ["", "MUST HAPPEN:"]+ for m in must_include:+ lines.append(" - %s" % str(m).strip())+ lines += ["", "Write the scene now."]+ return "\n".join(lines)+++# ======================================================================================+# THE GEOGRAPHY PASS — the screenplay is TIME, this is SPACE+# ======================================================================================+# The owner, after a full day of manual continuity work: "Do you notice all the work I+# had to do to make this scene happen in the same place and have proper angles? ... You+# need to first make a concept of the whole situation. For instance, a man or woman in a+# bar — behind him there is this, behind her there is that. When they sit together, this+# is what you see. So there is continuity between the shots."+#+# A scene is a SPACE before it is a shot list. This pass writes the floor plan ONCE —+# who stands where, what is behind each of them, where the light comes from — and then+# DERIVES the named views of the location from it, so the reverse angle automatically+# excludes what has moved behind the camera and the light lands on the correct side.+# The whole car-wash day was the prototype: carwash/carwash_reverse, the flipped sun,+# the no-car reverse background, the sign living only on the far side — all of it+# hand-built, all of it derivable from one paragraph.+# What the SHOT pass is told once the floor plan exists. Stated in the brief+# rather than in the system prompt because it is only true for a film whose+# locations actually carry views — a plan with none must read exactly as it did+# before this pass existed.+_GEOGRAPHY_LAWS = """\+ GEOGRAPHY - the scene happens in a space, and the space does not move.+ Every shot in a place that has views sets "view" to one of the view ids above, and+ "eyeline" to "left", "right" or "lens".+ "eyeline" is where the person LOOKS as the audience sees it: "right" means their eyes go+ off past the right edge of the frame, "left" past the left edge, "lens" straight down the+ barrel at the audience. Use "lens" only for a piece to camera.+ THE 180-DEGREE RULE. Two people talking keep the same sides of the screen for the whole+ conversation. If he looks frame-RIGHT at her, then in her shot she looks frame-LEFT back+ at him. Two shots that cut between them may NEVER claim the same eyeline - that is the+ cut where the audience watches both of them turn and stare at the same wall.+ A shot on a reverse view must not mention anything that view says is not in it. If the+ view says "no car in frame", the shot has no car in it, in any words.+ Never put a character's own body in the view behind them: what the camera sees over his+ shoulder is HER side of the room, not another copy of him."""+++_GEOGRAPHY_SYSTEM = """\+You are a director blocking a scene. Before a single shot exists you decide where+everything IS, and then you describe the place from each direction the camera will point.++Work in two steps.++STEP 1 - THE FLOOR PLAN. One paragraph, present tense. Say where each person stands or+sits, where the key objects are, and where the light comes from. Say what is BEHIND each+person, because that is what the camera sees when it looks at them. Do not describe shots.++STEP 2 - THE VIEWS. Turn the floor plan into 2 to 4 camera directions and describe what+each one SEES. Rules that are not negotiable:++ * When two people face each other you write AT LEAST an establishing view and its+ REVERSE - the camera turned 180 degrees to look back the other way.+ * A view never contains what is behind the camera in that view. If the establishing+ view holds the car, the reverse view does NOT hold the car - and you SAY SO, in the+ words "no car in frame", for every prominent thing the other views hold. That+ sentence is what stops it being put back later.+ * THE LIGHT FLIPS. A sun raking in from camera LEFT rakes in from camera RIGHT once the+ camera turns 180 degrees. Every view names its side.+ * Never put a person's own body in the view behind them. The view behind HIM is what+ the camera sees over his shoulder, which is HER side of the room, not him.+ * Each view is self-contained: a reader who has only that one sentence must be able to+ picture the frame without the floor plan.++Return ONE JSON object and nothing else:++{"floor_plan": "<the paragraph from step 1>",+ "views": [{"location": "<the location name, exactly as it was given to you>",+ "id": "<short_lowercase_id>",+ "name": "<what it is, in a few words>",+ "light": "camera left" | "camera right",+ "description": "<what this camera sees, one or two sentences>"}]}++No preamble, no headings, nothing before the object and nothing after it.+"""+++def _build_geography_prompt(concept: str, style: str,+ cast: Sequence[Dict[str, str]],+ locations: Sequence[Dict[str, Any]],+ screenplay: str = "") -> str:+ lines = ["CONCEPT: %s" % (concept or "").strip()]+ if style and style.strip():+ lines += ["", "STYLE: %s" % style.strip()]+ if cast:+ lines += ["", "WHO IS IN IT:"]+ for c in cast:+ who = c.get("name") or c.get("id")+ noun = (c.get("subject_noun") or "").strip()+ lines.append(" - %s%s" % (who, (" (%s)" % noun) if noun else ""))+ lines += ["", "THE PLACES - block every one of them, by name:"]+ for loc in locations:+ lines.append(" - %s: %s" % (loc.get("name") or loc.get("id"),+ (loc.get("description") or "").strip()))+ if screenplay and screenplay.strip():+ # The scene, so the blocking serves what actually happens in it — who+ # turns to whom, and therefore which direction has to exist.+ lines += ["", "THE SCENE THAT HAPPENS HERE:", "", screenplay.strip()[:2000]]+ lines += ["", "Write the floor plan and the views now."]+ return "\n".join(lines)+++# A view id is a location id: lowercase, digits, - and _. Kept local so the+# planner does not need storyboard.py imported to slugify one.+_VIEW_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$")+_CAMERA_SIDE_RE = re.compile(r"camera[ -](left|right)", re.IGNORECASE)+MAX_VIEWS_PER_LOCATION = 4+++def _slug_view_id(*candidates: Any) -> str:+ for cand in candidates:+ raw = re.sub(r"[^a-z0-9]+", "_", str(cand or "").strip().lower()).strip("_")[:40]+ if raw and _VIEW_ID_RE.match(raw):+ return raw+ return ""+++def _fold_light(description: str, light: Any) -> str:+ """Make sure the view's own sentence says which side the light rakes from.++ The side is the single most load-bearing word in a reverse angle and the+ model likes to answer it in the `light` field and then forget it in the+ prose that actually reaches the renderer. Folded in only when the sentence+ does not already carry a side of its own.+ """+ desc = (description or "").strip()+ m = _CAMERA_SIDE_RE.search(str(light or ""))+ side = m.group(1).lower() if m else ""+ if not side:+ low = str(light or "").lower()+ side = "left" if "left" in low else "right" if "right" in low else ""+ if not side or _CAMERA_SIDE_RE.search(desc):+ return desc+ return "%s, the light rakes in from camera %s" % (desc.rstrip(" .,;"), side)+++def _geography_plan(resp: Dict[str, Any],+ locations: Sequence[Dict[str, Any]]) -> Tuple[str, Dict[str, List[Dict[str, str]]]]:+ """(floor plan, {location_id: [views]}) out of a generate() response.++ Empty on anything unusable, exactly like `_screenplay_text` — a model that+ answers a blocking brief with a paragraph of enthusiasm must leave the plan+ behaving precisely as it did before this pass existed, not hand chatter+ down as if it were geography.+ """+ obj = next((o for o in _json_dicts((resp or {}).get("text") or "")+ if isinstance(o.get("views"), list)), None)+ if obj is None:+ return "", {}+ floor = str(obj.get("floor_plan") or obj.get("floorplan") or+ obj.get("layout") or "").strip()[:1500]+ raw_views = obj["views"]++ by_name: Dict[str, Dict[str, Any]] = {}+ for loc in locations:+ for key in (loc.get("name"), loc.get("id")):+ if str(key or "").strip():+ by_name[str(key).strip().lower()] = loc++ out: Dict[str, List[Dict[str, str]]] = {}+ for v in raw_views:+ if not isinstance(v, dict):+ continue+ desc = _fold_light(str(v.get("description") or v.get("sees") or "").strip(),+ v.get("light"))+ # A view is a DESCRIPTION. An id with nothing under it composes to the+ # location's own text and pretends coverage exists.+ if len(desc) < 20:+ continue+ want = str(v.get("location") or v.get("place") or "").strip().lower()+ loc = by_name.get(want)+ if loc is None and len(locations) == 1:+ loc = locations[0]+ if loc is None:+ continue+ lid = str(loc.get("id"))+ rows = out.setdefault(lid, [])+ if len(rows) >= MAX_VIEWS_PER_LOCATION:+ continue+ vid = _slug_view_id(v.get("id"), v.get("name"), "view_%d" % (len(rows) + 1))+ if not vid or any(r["id"] == vid for r in rows):+ vid = _slug_view_id("%s_%d" % (vid or "view", len(rows) + 1)) or \+ "view_%d" % (len(rows) + 1)+ if any(r["id"] == vid for r in rows):+ continue+ rows.append({"id": vid,+ "name": str(v.get("name") or v.get("id") or vid).strip()[:80],+ "description": desc[:600]})++ out = {k: v for k, v in out.items() if v}+ if not out:+ return "", {}+ return floor, out+++def _merge_views(locations: Sequence[Dict[str, Any]],+ views: Dict[str, List[Dict[str, str]]]) -> List[Dict[str, Any]]:+ """The board's locations, each carrying the views the floor plan derived.++ Copies rather than mutating: `locations` is the caller's list — on the+ panel it is the user's own Locations box, parsed — and a pass that edits it+ in place would leave the user's places rewritten by a model even on the+ paths where the plan is thrown away.+ """+ merged: List[Dict[str, Any]] = []+ for loc in locations:+ row = dict(loc)+ rows = views.get(str(row.get("id")))+ if rows:+ row["views"] = [dict(r) for r in rows]+ merged.append(row)+ return merged+++# The eyeline vocabulary, and every way a model says it. Anything that does not+# land in here is dropped rather than written onto a shot: `eyeline` outside the+# vocabulary is a hard validator error, and a plan that cannot be rendered is a+# worse outcome than a shot with no eyeline on it.+_EYELINE_WORDS = {+ "left": "left", "frame-left": "left", "frame left": "left",+ "screen-left": "left", "screen left": "left", "camera-left": "left",+ "camera left": "left", "off-frame left": "left", "l": "left",+ "right": "right", "frame-right": "right", "frame right": "right",+ "screen-right": "right", "screen right": "right", "camera-right": "right",+ "camera right": "right", "off-frame right": "right", "r": "right",+ "lens": "lens", "camera": "lens", "to camera": "lens", "at camera": "lens",+ "into the lens": "lens", "down the lens": "lens", "to the lens": "lens",+}+++def _eyeline_key(raw: Any) -> str:+ key = re.sub(r"\s+", " ", str(raw or "").strip().lower()).strip(".,")+ return _EYELINE_WORDS.get(key, "")+++def _apply_geography(shot: Dict[str, Any], raw: Dict[str, Any], loc: Dict[str, Any],+ n: int, warnings: List[str]) -> None:+ """Stamp `view` and `eyeline` onto one shot, matched against the floor plan."""+ views = [v for v in (loc.get("views") or []) if isinstance(v, dict) and v.get("id")]+ if views:+ want = str(raw.get("view") or raw.get("angle") or raw.get("facing") or "").strip().lower()+ hit = next((v for v in views+ if want and want in (str(v.get("id") or "").strip().lower(),+ str(v.get("name") or "").strip().lower())), None)+ if hit is None and want:+ hit = next((v for v in views+ if _slug_view_id(want) == str(v.get("id")).strip().lower()), None)+ if hit is None:+ # UNSPECIFIED COVERAGE IS THE MASTER. A shot that names no view+ # would compose from the location's own neutral sentence, which is+ # the pre-views behaviour and the thing this pass exists to end.+ # The first view is the establishing one by construction.+ hit = views[0]+ warnings.append(+ "shot %d named %sno view of %s — it was put on %r, the establishing view"+ % (n, ("view %r, which is not on the floor plan, so " % want) if want else "",+ loc.get("name") or loc.get("id"), hit.get("id")))+ shot["view"] = str(hit["id"]).strip().lower()++ raw_eye = raw.get("eyeline") or raw.get("eye_line") or raw.get("looking")+ if raw_eye:+ eye = _eyeline_key(raw_eye)+ if eye:+ shot["eyeline"] = eye+ else:+ warnings.append("shot %d asked for eyeline %r, which is not left, right or "+ "lens — the shot carries no eyeline" % (n, str(raw_eye)[:40]))++def _build_repair_prompt(bad_json: str, problems: Sequence[str], n_shots: int) -> str:return "\n".join(["Your previous reply did not pass validation.",@@ -654,7 +1046,7 @@ def _build_shot_feedback_prompt(previous: Dict[str, Any], shot_n: int, note: strdef _shot_to_model_view(shot: Dict[str, Any]) -> Dict[str, Any]:"""The eight creative keys, as the model sees them (drops seeds/modes/engines/etc)."""- return {+ out = {"n": shot.get("n"),"title": shot.get("title", ""),"character_id": shot.get("character_id"),@@ -666,6 +1058,16 @@ def _shot_to_model_view(shot: Dict[str, Any]) -> Dict[str, Any]:"soundscape": shot.get("soundscape", ""),"music": shot.get("music", "N/A"),}+ # WHERE, and WHICH WAY. Only when the shot has them, so a board with no+ # locations shows the model exactly what it always showed. Without these a+ # film-level re-plan came back with the geography stripped — every shot+ # re-coerced onto the establishing view because nothing in the plan the+ # model was shown said which way it had been pointing.+ for key, src in (("location", "location_id"), ("view", "view"),+ ("eyeline", "eyeline")):+ if shot.get(src):+ out[key] = shot[src]+ return outdef _spec_to_model_view(spec: Dict[str, Any]) -> Dict[str, Any]:@@ -777,8 +1179,28 @@ def extract_json_object(text: str) -> Optional[Dict[str, Any]]:output truncated mid-object by the token limit. Returns None only when there is norecoverable object at all."""+ for obj in _json_dicts(text):+ if "shots" in obj or "title" in obj:+ return obj+ # Model returned a bare list of shots under some other key.+ for v in obj.values():+ if isinstance(v, list) and v and isinstance(v[0], dict) and "description" in v[0]:+ return {"title": "", "shots": v}+ return None+++def _json_dicts(text: str) -> Iterable[Dict[str, Any]]:+ """Every JSON object recoverable from a model reply, longest first.++ The recovery half of `extract_json_object`, split out because it is not+ plan-specific and a SECOND pass now needs it. The predicate is not shared+ on purpose: extract_json_object's last resort — "a list of dicts with a+ description under any key must be the shots" — read the geography pass's+ `views` array as a shot list and handed a floor plan to the coercer as a+ film. Two passes, two shapes, one recovery.+ """if not text:- return None+ returnbody = _THINK_RE.sub(" ", text)candidates: List[str] = []@@ -806,13 +1228,7 @@ def extract_json_object(text: str) -> Optional[Dict[str, Any]]:if obj is None:continueif isinstance(obj, dict):- if "shots" in obj or "title" in obj:- return obj- # Model returned a bare list of shots under some other key.- for v in obj.values():- if isinstance(v, list) and v and isinstance(v[0], dict) and "description" in v[0]:- return {"title": "", "shots": v}- return None+ yield obj# --------------------------------------------------------------------------------------@@ -1640,6 +2056,7 @@ def coerce_spec(created_at: Optional[int] = None,allow_hidden_faces: bool = False,storyboard_mod: Any = None,+ locations: Optional[Sequence[Dict[str, Any]]] = None,) -> Tuple[Dict[str, Any], List[str]]:"""Turn whatever the model returned into a schema-correct storyboard.@@ -1649,6 +2066,7 @@ def coerce_spec("""warnings: List[str] = []cast = list(cast or ())+ locs = [l for l in (locations or ()) if isinstance(l, dict) and l.get("id")]if seed_base is None:seed_base = _stable_seed(concept)@@ -1772,6 +2190,26 @@ def coerce_spec("soundscape": sound,"music": music,}+ # Which place this shot happens in. Matched on the NAME the model was+ # given; if it answers with something not on the list, or answers with+ # nothing, a film with exactly ONE location falls back to that one —+ # which is the common case and the one the whole feature is for.+ if locs:+ want = str(s.get("location") or s.get("place") or "").strip().lower()+ hit = next((l for l in locs+ if want and want in (str(l.get("name") or "").lower(),+ str(l.get("id") or "").lower())), None)+ if hit is None and len(locs) == 1:+ hit = locs[0]+ if hit is not None:+ shot["location_id"] = hit["id"]+ # WHICH WAY THE CAMERA FACES, and where the eyes go. Both are+ # matched against the floor plan rather than trusted: an+ # unknown view id is a HARD validator error and an eyeline+ # outside the vocabulary is another, so nothing that did not+ # resolve is ever written onto a shot.+ _apply_geography(shot, s, hit, idx + 1, warnings)+if char:shot["character_id"] = char["id"]shot["trigger"] = char["trigger"]@@ -1817,6 +2255,17 @@ def coerce_spec("policy": default_policy(max_dim),"shots": shots,}+ # THE PLAN CARRIES THE PLACES IT NAMES. Shots have been stamped with+ # `location_id` since locations existed, and the spec they live in never+ # carried `locations` — so `validate_storyboard()` saw a shot pointing at a+ # place the board did not have and returned `unknown_location` for EVERY+ # shot. Every plan with a location in the brief spent its one repair+ # round-trip on a fault no model could fix and came back `invalid_plan`.+ # It survived because the panel keeps its own copy of the locations and+ # patches them onto the board after adoption, so the only visible symptom+ # was planning failing whenever the user filled the Locations box in.+ if locs:+ spec["locations"] = [dict(l) for l in locs]return spec, warnings@@ -2045,6 +2494,9 @@ def plan_film(duration_s: float = 5.0,allow_hidden_faces: Optional[bool] = None,board_id: Optional[str] = None,+ locations: Optional[Iterable[Dict[str, Any]]] = None,+ screenplay: bool = True,+ geography: bool = True,known_character_ids: Optional[Iterable[str]] = None,ref_root: Optional[Any] = None,max_dim: Optional[int] = None,@@ -2078,6 +2530,15 @@ def plan_film(or {"shot": 4, "note": "..."}Per-shot re-rolls replace ONLY that shot; every other shot object iscarried across by reference, so the rest of the plan is byte-stable.+ locations the places the film happens in, as board `locations` rows. They ride+ into the returned spec so the shots that name them validate, and+ they are what the geography pass hangs its views on.+ geography write the FLOOR PLAN before the shots (default on): where everybody+ stands, what is behind them, which side the light comes from — and+ from that, 2-4 named VIEWS per location, so the reverse angle+ excludes what is now behind the camera and the light flips sides.+ Needs at least one location to be spatial about; with none it is+ skipped and the plan behaves as it did before the pass existed.engine "auto" (default) | "h3" | "ltx". Auto = H3 unless the shot is cast.tier per-shot tier, default "draft" — plans are for reviewing, not shipping.allow_hidden_faces@@ -2104,6 +2565,7 @@ def plan_film(n_shots = max(1, int(n_shots))cast = _normalise_cast(characters)must = [str(m).strip() for m in (must_include or ()) if str(m).strip()]+ locs = [l for l in (locations or ()) if isinstance(l, dict) and l.get("id")]fb_mode, fb_shot, fb_note = _parse_feedback(feedback)if fb_mode != "none" and previous is None:previous = feedback.get("previous") if isinstance(feedback, dict) else None@@ -2132,12 +2594,75 @@ def plan_film(elif fb_mode == "film":user = _build_film_feedback_prompt(previous, fb_note, n_shots)else:- user = _build_user_prompt(concept, n_shots, style, cast, must)+ user = _build_user_prompt(concept, n_shots, style, cast, must, locs)owned = session is Nonesess = session or PlannerSession(model_path=model_path, python_exe=python_exe,timeout_s=timeout_s)result: Dict[str, Any] = {}+ pass_warnings: List[str] = []+ scene_text = ""+ floor_plan = ""+ # Hoisted so the name exists on every path — the shot pass reads it below+ # to decide whether the prompt has to be rebuilt.+ _views: Dict[str, List[Dict[str, str]]] = {}+ if screenplay and fb_mode not in ("shot", "film"):+ # PASS ONE: write the scene. Only on a fresh plan — a re-roll already+ # has a scene and rewriting it would move the ground under the shot+ # being fixed.+ try:+ _sp = sess.generate(+ _SCREENPLAY_SYSTEM,+ _build_screenplay_prompt(concept, n_shots, style, cast, must, locs),+ max_tokens=1200, temperature=0.8, seed=seed_base % 100000)+ scene_text = _screenplay_text(_sp)+ except PlannerError:+ # A film with no scene is the behaviour this feature replaced, not a+ # failure worth aborting a plan over.+ scene_text = ""+ if geography and locs and fb_mode not in ("shot", "film"):+ # PASS TWO: block the space. Between the screenplay and the shots+ # because it reads the scene (who turns to whom decides which+ # directions have to exist) and the shots read it (a shot cannot name a+ # view that has not been derived yet). Skipped on a re-roll for the+ # same reason the screenplay is: the other shots are standing on this+ # geography and moving it under them is not a fix.+ #+ # It needs a location to be spatial ABOUT. With none, there is nowhere+ # to hang a view and no board field to carry it, so the pass is not run+ # and the plan behaves exactly as it did before it existed.+ try:+ _gp = sess.generate(+ _GEOGRAPHY_SYSTEM,+ _build_geography_prompt(concept, style, cast, locs, scene_text),+ max_tokens=1400, temperature=0.7, seed=(seed_base + 3) % 100000)+ floor_plan, _views = _geography_plan(_gp, locs)+ except PlannerError:+ floor_plan, _views = "", {}+ if _views:+ locs = _merge_views(locs, _views)+ pass_warnings.append(+ "geography: %d view(s) derived across %d location(s)"+ % (sum(len(v) for v in _views.values()), len(_views)))+ else:+ pass_warnings.append(+ "geography: the model returned no usable floor plan — shots will not "+ "declare views, exactly as before this pass existed")+ # VIEWS COUNT AS A REASON TO REBUILD THE PROMPT. `_geography_plan` derives+ # the floor plan from the model's own optional `floor_plan` key, so a reply+ # that carries views and no plan legitimately returns ("", {...views...}).+ # With the screenplay also empty — routine: `_screenplay_text` returns ""+ # whenever fewer than three lines match the form, and a PlannerError there+ # is deliberately tolerated — `locs` had been REPLACED by the merged list+ # while `user` was still the pre-geography prompt: no view ids in it, no+ # geography laws. The model then named no view, `_apply_geography` found+ # views on the location and no view on any shot, and stamped views[0] on+ # every shot with one warning each. That is the whole film pinned to the+ # establishing angle, which is the pre-views behaviour this pass exists to+ # end — arriving silently, through the pass itself.+ if scene_text or floor_plan or _views:+ user = _build_user_prompt(concept, n_shots, style, cast, must, locs,+ screenplay=scene_text, floor_plan=floor_plan)try:result = _plan_with_session(sess, system=system, user=user, fb_mode=fb_mode, fb_shot=fb_shot,@@ -2146,7 +2671,8 @@ def plan_film(duration_s=duration_s, seed_base=seed_base, max_dim=max_dim,known_ids=known_ids, ref_root=ref_root, temperature=temperature,budget=budget, model_path=model_path, t_start=t_start,- allow_hidden_faces=allow_hidden)+ allow_hidden_faces=allow_hidden, locs=locs,+ pass_warnings=pass_warnings)finally:# The model is gone before this function returns, on every path including an# exception. Peak RSS is only final once the child has been reaped, so the@@ -2161,7 +2687,8 @@ def plan_film(def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, validate, sb,concept, n_shots, style, cast, board_id, engine, tier, duration_s,seed_base, max_dim, known_ids, ref_root, temperature, budget,- model_path, t_start, allow_hidden_faces) -> Dict[str, Any]:+ model_path, t_start, allow_hidden_faces,+ locs=(), pass_warnings=()) -> Dict[str, Any]:"""The generate -> extract -> coerce -> validate -> ONE repair loop.Split out of plan_film() so the `finally:` that releases the model is three lines with@@ -2175,11 +2702,41 @@ def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, validaobj, fb_mode, fb_shot, previous, concept=concept, n_shots=n_shots, style=style,cast=cast, board_id=board_id, engine=engine, tier=tier, duration_s=duration_s,seed_base=seed_base, max_dim=max_dim, sb=sb,- allow_hidden_faces=allow_hidden_faces)+ allow_hidden_faces=allow_hidden_faces, locations=locs)def check(spec):- return list(validate(spec, known_character_ids=known_ids,+ errs = list(validate(spec, known_character_ids=known_ids,ref_root=Path(ref_root) if ref_root else None, max_dim=max_dim))+ # `speech_without_words` is the board's version of L13 and it is a HARD+ # error there, correctly — a hand-authored board that would babble must+ # not reach a render. In here it is premature: this check runs before+ # `_enforce_laws`, which owns speech and can do better than reject —+ # it rewraps a prose-quoted line so the voice switches on, or stages the+ # shot honestly silent. Failing the plan here would spend the one repair+ # round-trip on a fault the next pass was about to fix for free, and+ # then return invalid_plan for it.+ # Dropping it is safe because it is not being waived, only deferred:+ # the panel validates the finished board again before it renders a+ # frame, and by then _enforce_laws has run.+ #+ # Filtered by CODE via the detail validator, not by matching English in+ # `errs` — `validate_storyboard()` returns formatted strings, so an+ # isinstance(dict) filter here silently matched nothing and every one of+ # these deferrals leaked through as an invalid_plan.+ detail = getattr(sb, "validate_storyboard_detail", None)+ if detail is None:+ return errs+ try:+ rows = detail(spec, known_character_ids=known_ids,+ ref_root=Path(ref_root) if ref_root else None, max_dim=max_dim)+ except Exception: # noqa: BLE001+ return errs+ # `dialogue_does_not_fit` is deferred for the same reason: the panel's+ # plan-adoption step FIXES it mechanically (it extends the shot to fit+ # the line via speech_fit_frames) — failing the plan here would spend+ # the repair round-trip on a fault that costs zero to fix.+ _DEFER = {"speech_without_words", "dialogue_does_not_fit"}+ return [r["message"] for r in rows if r.get("code") not in _DEFER]# ---- attempt 1 ------------------------------------------------------------------try:@@ -2229,6 +2786,11 @@ def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, validaexcept PlannerError as exc:warnings.append("repair round failed: %s" % exc)+ # What the passes BEFORE this one had to say, in front of what the shot+ # pass had to say. Prepended here rather than earlier because the repair+ # round replaces `warnings` wholesale with the second draft's list.+ warnings[:0] = list(pass_warnings)+if errs:return _error("invalid_plan",@@ -2259,7 +2821,7 @@ def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, validaobj3, "shot", n, current, concept=concept, n_shots=n_shots, style=style,cast=cast, board_id=board_id, engine=engine, tier=tier,duration_s=duration_s, seed_base=seed_base, max_dim=max_dim, sb=sb,- allow_hidden_faces=allow_hidden_faces)+ allow_hidden_faces=allow_hidden_faces, locations=locs)# A re-roll that breaks the SCHEMA is discarded outright — the law fix is not# worth an invalid plan, and the mechanical fallback can still clean the prose.if check(fixed):@@ -2274,6 +2836,12 @@ def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, validaspec = _enforce_premise(spec, cast, warnings, replan=_replan_one, style=style, sb=sb,premise=_premise)+ # SPACE, after the prose laws have finished rewriting shots. Safe in+ # any order in fact — it reads `eyeline`/`view`/`description` and+ # writes only `eyeline`, which no other law reads and which is composed+ # into the prompt at render time — but it is a scan, not a re-plan, and+ # scanning what the last mutation produced is the only honest place.+ spec = _enforce_geography(spec, locs, warnings)# ---- THE FINAL INVARIANT SCAN ------------------------------------# After the LAST mutation, whichever pass made it. Every pass before# this validated only the condition it owned, so the last repair could@@ -2291,6 +2859,10 @@ def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, valida# optional. Mechanical repair still applies, and what cannot be repaired# is reported the same way a full plan reports it._premise = _premise_species(" ".join([concept or "", style or ""]))+ # A RE-ROLLED SHOT CAN BREAK THE LINE with the neighbours it was cut+ # between — and unlike the prose laws this one costs no model call, so+ # there is no reason for the cheap path to skip it.+ spec = _enforce_geography(spec, locs or (spec.get("locations") or ()), warnings)spec, _degraded = _assert_final_invariants(spec, cast, warnings, style=style, sb=sb, premise=_premise)@@ -2319,6 +2891,131 @@ def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, validareturn spec+# ---- THE GEOGRAPHY LAWS ---------------------------------------------------------------+# Both are WARNING level and neither can fail a plan. A film whose eyelines are+# a little loose is still a film; a film that will not render is not. What they+# do is name the defect in the words the UI already shows, and — where the fix+# is a single discrete field with exactly one other legal value — apply it.++def _shots_in_cut_order(spec: Dict[str, Any]) -> List[Dict[str, Any]]:+ """The shots as the audience meets them. "Adjacent" means adjacent ON SCREEN."""+ rows = [s for s in (spec.get("shots") or ()) if isinstance(s, dict)]+ return sorted(rows, key=lambda s: s.get("n") if isinstance(s.get("n"), int) else 0)+++def _enforce_eyelines(spec: Dict[str, Any], warnings: List[str]) -> Dict[str, Any]:+ """THE 180-DEGREE LINE: a cut between two people reverses the eyeline.++ He looks frame-right at her; she looks frame-LEFT back at him. Two adjacent+ shots of two DIFFERENT characters in the SAME place that both claim the+ same side are the cut where the audience watches both of them turn and+ stare at the same wall — the single most recognisable continuity error in+ the format, and the owner spent a day fixing it by hand.++ Repaired mechanically, which is only defensible because `eyeline` is a+ discrete field with exactly one complement: flipping it cannot damage+ anybody's prose, and the clause it produces is composed at render time+ (`compose_shot_prompt`), so nothing has to be re-assembled. Prose laws get+ a model round trip precisely because they do not have this property.+ """+ shots = _shots_in_cut_order(spec)+ for prev, cur in zip(shots, shots[1:]):+ a, b = prev.get("eyeline"), cur.get("eyeline")+ if a not in ("left", "right") or a != b:+ continue+ ca, cb = prev.get("character_id"), cur.get("character_id")+ if not ca or not cb or ca == cb:+ continue+ if (prev.get("location_id") or "") != (cur.get("location_id") or ""):+ continue+ flip = "right" if b == "left" else "left"+ cur["eyeline"] = flip+ warnings.append(+ "shots %s and %s cut between two people and both looked %s — the 180-degree "+ "line. Shot %s now looks %s, back at them."+ % (prev.get("n"), cur.get("n"), b, cur.get("n"), flip))+ return spec+++# What a view says is NOT in it. "no car in frame", "without the sign".+# The floor plan is asked to write these sentences precisely so this check has+# something exact to stand on.+_ABSENCE_RE = re.compile(r"\b(?:no|without|not)\s+((?:[a-z][a-z'-]{2,}\s+){0,2}[a-z][a-z'-]{2,})",+ re.IGNORECASE)+# Words that carry no object of their own — a view saying "no longer" or "not+# visible" is not naming a thing that must stay off screen.+_ABSENCE_STOP = {+ "longer", "visible", "seen", "shown", "there", "here", "part", "more", "less",+ "camera", "frame", "shot", "view", "side", "screen", "left", "right", "front",+ "behind", "back", "this", "that", "these", "those", "them", "their", "they",+ "anything", "anyone", "nothing", "else", "other", "another", "same", "and",+ "the", "one", "two", "any", "all", "with", "from", "into", "onto", "over",+ "under", "near", "past", "still", "yet", "just", "only", "even", "very",+}+++def _absent_terms(view_desc: str) -> List[str]:+ """The things a view SAYS are not in it: "no car in frame" -> ["car"].++ Only the view's own negations. An earlier draft also inferred absence by+ diffing the content words of the other views, and that is wrong in the case+ the feature exists for: a reverse angle legitimately contains the OTHER+ person and everything they are holding, so every mention of her, her+ sponge, her wheel came back as a violation. The floor plan states absence+ out loud; nothing else is trustworthy enough to warn on.+ """+ out: List[str] = []+ for m in _ABSENCE_RE.finditer(view_desc or ""):+ for word in m.group(1).split():+ w = word.strip(".,;:'\"").lower()+ if len(w) >= 3 and w not in _ABSENCE_STOP and w not in out:+ out.append(w)+ return out+++def _scan_reverse_objects(spec: Dict[str, Any],+ locations: Sequence[Dict[str, Any]]) -> List[Tuple[int, str, str]]:+ """[(shot n, view id, the thing that is behind the camera in it)].++ The car-wash law: the reverse angle exists so the car is not in it, and a+ shot on that view that writes the car back in has undone the only reason+ it was derived.+ """+ by_id = {str(l.get("id")): l for l in (locations or ()) if isinstance(l, dict)}+ out: List[Tuple[int, str, str]] = []+ for s in (spec.get("shots") or ()):+ if not isinstance(s, dict) or not s.get("view"):+ continue+ loc = by_id.get(str(s.get("location_id") or ""))+ view = next((v for v in ((loc or {}).get("views") or ())+ if isinstance(v, dict)+ and str(v.get("id")).strip().lower() == str(s["view"]).strip().lower()),+ None)+ if view is None:+ continue+ text = " ".join([str(s.get("description") or ""), str(s.get("settle") or "")])+ for term in _absent_terms(str(view.get("description") or "")):+ if re.search(r"\b%s(?:e?s)?\b" % re.escape(term), text, re.IGNORECASE):+ out.append((int(s.get("n") or 0), str(s["view"]), term))+ break+ return out+++def _enforce_geography(spec: Dict[str, Any], locations: Sequence[Dict[str, Any]],+ warnings: List[str]) -> Dict[str, Any]:+ """Both laws, in the order that makes the second one's warning readable."""+ spec = _enforce_eyelines(spec, warnings)+ for n, view, term in _scan_reverse_objects(spec, locations):+ # NOT repaired. Cutting a noun out of a sentence leaves prose nobody+ # wrote, and a targeted re-plan is a 20-second round trip spent on a+ # shot the user can re-roll deliberately with this sentence in hand.+ warnings.append(+ "shot %d is on view %r, which says the %s is not in it — and the shot puts "+ "the %s back in frame. Re-roll the shot, or move it to the view that holds "+ "the %s." % (n, view, term, term, term))+ return spec++def _scan_laws(spec: Dict[str, Any],cast: Sequence[Dict[str, str]]) -> List[Tuple[int, List[str]]]:"""Every shot that breaks L12 or L13, as [(shot_n, [reasons])].@@ -2702,13 +3399,14 @@ def _engine_mix(spec: Dict[str, Any]) -> Dict[str, int]:def _coerce_for_mode(obj, fb_mode, fb_shot, previous, *, concept, n_shots, style, cast,board_id, engine, tier, duration_s, seed_base, max_dim, sb,- allow_hidden_faces=False):+ allow_hidden_faces=False, locations=None):"""Coerce a fresh plan, or splice one re-rolled shot into an existing plan."""if fb_mode != "shot":return coerce_spec(obj, concept=concept, n_shots=n_shots, style=style, cast=cast,board_id=board_id, engine=engine, tier=tier,duration_s=duration_s, seed_base=seed_base, max_dim=max_dim,- allow_hidden_faces=allow_hidden_faces, storyboard_mod=sb)+ allow_hidden_faces=allow_hidden_faces, storyboard_mod=sb,+ locations=locations)# Per-shot re-roll: coerce the single returned shot, then splice. Every other shot# object is carried across by reference, so the untouched part of the plan is@@ -2716,7 +3414,8 @@ def _coerce_for_mode(obj, fb_mode, fb_shot, previous, *, concept, n_shots, styleone, warnings = coerce_spec(obj, concept=concept, n_shots=1, style=style, cast=cast,board_id=previous.get("id"), engine=engine, tier=tier,duration_s=duration_s, seed_base=seed_base, max_dim=max_dim,- allow_hidden_faces=allow_hidden_faces, storyboard_mod=sb)+ allow_hidden_faces=allow_hidden_faces, storyboard_mod=sb,+ locations=locations)new_shots = one.get("shots") or []spec = copy.copy(previous)spec["shots"] = list(previous.get("shots") or [])diff --git a/test_caption_counts.py b/test_caption_counts.pynew file mode 100644index 0000000..f737dbd--- /dev/null+++ b/test_caption_counts.py@@ -0,0 +1,135 @@+#!/usr/bin/env python3+"""The auto-captioner must report what it WROTE, not what it was handed.++`caption_with_gemma.py` deliberately does not abort the whole run on one bad+image — it logs an `error` event and moves to the next. That is the right+behaviour and it made the summary a lie: `done` carried `count=len(images)`,+so a dataset where four images failed still printed++ [caption] done - 24 captions in 91.4s++while 20 caption files existed. The four uncaptioned images then trained on+the 3-word `<trigger> man` fallback and nobody was told. Same class as the zip+filter in #61 that accepted 12 of 18 images without a word: a silent loss+under a green summary.++And a run where EVERY image failed still exited 0 and reported `done`, which+is not a finished run by any reading.+"""++import io+import json+import sys+import tempfile+import types+import unittest+from pathlib import Path+from unittest.mock import patch++import caption_with_gemma+++class _FakeProcessor:+ pass+++class _FakeModel:+ config = object()+++def _install_fake_mlx_vlm(fail_on: set[str]) -> dict[str, types.ModuleType]:+ """A stand-in for `mlx_vlm` that fails on the named image basenames."""++ def _load(_path):+ return _FakeModel(), _FakeProcessor()++ def _generate(_model, _processor, _formatted, image, **_kw):+ name = Path(image[0]).name+ if name in fail_on:+ raise RuntimeError("simulated caption failure")+ return f"[VISUAL]: tok, a description of {name}"++ root = types.ModuleType("mlx_vlm")+ root.load = _load+ root.generate = _generate+ prompt_utils = types.ModuleType("mlx_vlm.prompt_utils")+ prompt_utils.apply_chat_template = lambda *a, **k: "PROMPT"+ root.prompt_utils = prompt_utils+ return {"mlx_vlm": root, "mlx_vlm.prompt_utils": prompt_utils}+++class CaptionCountTests(unittest.TestCase):+ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.dataset = Path(self.tmp.name)+ self.images = self.dataset / "images"+ self.images.mkdir()+ for i in range(1, 6):+ (self.images / f"char_{i:03d}.png").write_bytes(b"not really a png")++ def tearDown(self) -> None:+ self.tmp.cleanup()++ def _run(self, fail_on: set[str]) -> tuple[int, list[dict]]:+ stream = io.StringIO()+ argv = [+ "caption_with_gemma",+ "--dataset", str(self.dataset),+ "--trigger", "tok",+ "--gemma-path", str(self.dataset), # any existing dir passes the check+ ]+ with patch.dict(sys.modules, _install_fake_mlx_vlm(fail_on)), \+ patch.object(sys, "argv", argv), \+ patch.object(sys, "stdout", stream):+ code = caption_with_gemma.main()+ events = [+ json.loads(line)+ for line in stream.getvalue().splitlines()+ if line.strip().startswith("{")+ ]+ return code, events++ def _event(self, events: list[dict], name: str) -> dict | None:+ return next((e for e in events if e.get("event") == name), None)++ def test_a_clean_run_counts_every_image(self) -> None:+ code, events = self._run(fail_on=set())+ done = self._event(events, "done")+ self.assertEqual(code, 0)+ self.assertIsNotNone(done)+ self.assertEqual(done["count"], 5)+ self.assertEqual(done["failed"], 0)+ self.assertEqual(done["total"], 5)+ self.assertEqual(len(list((self.dataset / "captions").glob("*.txt"))), 5)++ def test_the_summary_counts_files_written_not_images_seen(self) -> None:+ code, events = self._run(fail_on={"char_002.png", "char_004.png"})+ done = self._event(events, "done")+ on_disk = len(list((self.dataset / "captions").glob("*.txt")))+ self.assertEqual(code, 0)+ self.assertEqual(on_disk, 3)+ self.assertEqual(done["count"], on_disk)+ self.assertEqual(done["failed"], 2)+ self.assertEqual(done["total"], 5)++ def test_every_image_failing_is_not_a_finished_run(self) -> None:+ names = {f"char_{i:03d}.png" for i in range(1, 6)}+ code, events = self._run(fail_on=names)+ self.assertEqual(code, 1)+ self.assertIsNone(self._event(events, "done"))+ errors = [e for e in events if e.get("event") == "error"]+ # One per image, plus the fatal summary.+ self.assertEqual(len(errors), 6)+ self.assertEqual(errors[-1]["count"], 0)+ self.assertEqual(errors[-1]["failed"], 5)+ self.assertIn("no captions were written", errors[-1]["message"])++ def test_a_failed_image_still_lets_the_others_through(self) -> None:+ _, events = self._run(fail_on={"char_003.png"})+ captioned = {e["file"] for e in events if e.get("event") == "progress"}+ self.assertNotIn("char_003.png", captioned)+ self.assertEqual(len(captioned), 4)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_layout_geometry.py b/test_editor_layout_geometry.pynew file mode 100644index 0000000..3181c01--- /dev/null+++ b/test_editor_layout_geometry.py@@ -0,0 +1,310 @@+"""The Editor's layout, measured in a real browser.++WHAT THIS GUARDS. Three defects shipped to the owner's screen inside one+month, and the suite was green through all three: Save resolved to 1554px wide+because the global `button { width: 100% }` rule was never cancelled for+`.primary`, the header wrapped to two rows around it, and the timeline floor+was shorter than the lanes standing in it so the soundtrack was clipped off the+bottom. Not one of those is visible to a test that reads markup or stylesheet+text - the rule that fixes them and the rule that does not are both just+strings in the file. They are only visible to a browser that has laid the page+out.++So `scripts/measure_editor_layout.py` boots a panel from this tree against a+throwaway state directory, drives a headless Chrome over CDP with a websocket+client written in the standard library, opens the Editor, and reads five+numbers off the live DOM at four widths. This file runs it and asserts on+them, one subtest per width, so a failure names the width and the measurement.++NO NEW DEPENDENCY. The script imports nothing outside the standard library -+`test_script_is_stdlib_only` is the guard on that - so nothing here reaches a+Pinokio install. On a machine with no browser the script exits 3 and the+browser test SKIPS; the stdlib and syntax tests still run, so the file is never+completely unguarded.+"""++from __future__ import annotations++import ast+import json+import subprocess+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+SCRIPT = ROOT / "scripts" / "measure_editor_layout.py"++# The panel's own interpreter, which is the one this has to run under: it has+# no selenium, no playwright and no `websockets`, and that is the point.+VENV_PY = ROOT / "ltx-2-mlx" / "env" / "bin" / "python3.11"++NO_BROWSER_EXIT = 3+WIDTHS = ("1920", "1520", "1280", "1100")++SAVE_MIN, SAVE_MAX = 40.0, 200.0+OVERFLOW_TOL = 1.0+++def _python() -> str:+ return str(VENV_PY) if VENV_PY.exists() else sys.executable+++def _browser_present() -> bool:+ """Same search the script does, without importing it."""+ import os+ import shutil++ env = os.environ.get("CHROME_PATH", "").strip()+ if env and Path(env).exists():+ return True+ candidates = (+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ "/Applications/Chromium.app/Contents/MacOS/Chromium",+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",+ )+ if any(Path(c).exists() for c in candidates):+ return True+ return any(shutil.which(n) for n in+ ("google-chrome", "chromium", "chromium-browser"))+++# =============================================================================+# 1. The file itself - runs everywhere, browser or not+# =============================================================================+class ScriptShape(unittest.TestCase):+ def test_script_exists(self):+ self.assertTrue(SCRIPT.is_file(), f"{SCRIPT} is missing")++ def test_script_parses(self):+ """A gate nobody can run is a gate that is not there."""+ src = SCRIPT.read_text(encoding="utf-8")+ compile(src, str(SCRIPT), "exec")++ def test_script_is_stdlib_only(self):+ """THE RULE THAT KEEPS THIS OUT OF THE INSTALL.++ The moment this script imports selenium, playwright or `websockets`,+ running the suite means a pip install into every Pinokio copy of+ Phosphene - and the panel's own python has none of them, so it would+ not even run there. The websocket client is hand-written for exactly+ this reason and this test is what keeps it that way.+ """+ tree = ast.parse(SCRIPT.read_text(encoding="utf-8"), str(SCRIPT))+ allowed = set(sys.stdlib_module_names) | {"__future__"}+ seen: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for a in node.names:+ seen.add(a.name.split(".")[0])+ elif isinstance(node, ast.ImportFrom):+ if node.level: # relative: not a package+ self.fail(f"relative import in {SCRIPT.name}")+ if node.module:+ seen.add(node.module.split(".")[0])+ outside = sorted(seen - allowed)+ self.assertEqual(outside, [],+ f"{SCRIPT.name} imports non-stdlib modules {outside} "+ f"- that would put a pip dependency in the install")++ def test_never_binds_the_owners_port(self):+ """8199 is the live panel. The gate boots its own on an ephemeral one."""+ import re++ src = SCRIPT.read_text(encoding="utf-8")+ self.assertIn("FORBIDDEN_PORTS", src)+ # The only 8199 in the file may be the one it refuses to use.+ for line in src.splitlines():+ if "8199" in line:+ self.assertTrue(+ re.search(r"FORBIDDEN_PORTS\s*=", line),+ f"8199 appears outside the forbidden set: {line.strip()}")+++# =============================================================================+# 2. The measurement - skips when there is no browser+# =============================================================================+class EditorLayoutGeometry(unittest.TestCase):+ """One panel, one Chrome, four widths. Measured once for the whole class."""++ doc: dict | None = None+ skip_why: str | None = None+ fail_why: str | None = None+ returncode: int | None = None++ @classmethod+ def setUpClass(cls):+ if not SCRIPT.is_file():+ cls.skip_why = f"{SCRIPT} is missing"+ return+ if not _browser_present():+ cls.skip_why = ("no Chrome/Chromium/Edge on this machine - set "+ "CHROME_PATH to measure the Editor's layout")+ return+ try:+ proc = subprocess.run(+ [_python(), str(SCRIPT)],+ cwd=str(ROOT), capture_output=True, text=True, timeout=300,+ )+ except subprocess.TimeoutExpired:+ cls.fail_why = "the geometry gate did not finish in 300s"+ return+ if proc.returncode == NO_BROWSER_EXIT:+ cls.skip_why = ("the geometry gate found no browser: "+ + (proc.stderr or "").strip())+ return+ try:+ cls.doc = json.loads(proc.stdout)+ except json.JSONDecodeError:+ cls.doc = None+ cls.fail_why = (f"the gate printed no JSON (exit "+ f"{proc.returncode}). stderr: "+ f"{(proc.stderr or '').strip()[-800:]}")+ return+ cls.returncode = proc.returncode++ def setUp(self):+ if self.skip_why:+ self.skipTest(self.skip_why)+ if self.doc is None:+ self.fail(self.fail_why or "the geometry gate produced no "+ "measurement")++ def _width(self, w: str) -> dict:+ widths = self.doc.get("widths") or {}+ self.assertIn(w, widths,+ f"nothing was measured at {w}px - the gate reported "+ f"{sorted(widths)} and said {self.doc.get('failures')}")+ return widths[w]++ # -- the gate's own verdict -------------------------------------------+ def test_gate_reports_no_failures(self):+ """The whole verdict in one place, so a run that fails says why."""+ self.assertEqual(self.doc.get("failures") or [], [],+ "the Editor's layout is wrong:\n "+ + "\n ".join(self.doc.get("failures") or []))+ self.assertTrue(self.doc.get("ok"))+ # The exit code and the document have to agree, or a red gate could be+ # green in CI simply because nobody read the JSON.+ self.assertEqual(self.returncode, 0,+ f"the gate exited {self.returncode} while reporting "+ f"no failures")++ def test_the_editor_was_actually_open(self):+ """Zeros measured on a closed Editor would be five false passes."""+ for w in WIDTHS:+ with self.subTest(width=w):+ m = self._width(w)+ self.assertTrue(m.get("editor_open"),+ f"{w}: the Editor was not open, so nothing "+ f"measured here means anything")+ self.assertEqual(m.get("missing") or [], [],+ f"{w}: the gate could not find "+ f"{m.get('missing')}")+ self.assertFalse(m.get("stacked"),+ f"{w}: the page was in its stacked (<=900px) "+ f"layout, which is not what is being gated")++ # -- the five measurements --------------------------------------------+ def test_header_is_one_row(self):+ for w in WIDTHS:+ with self.subTest(width=w):+ m = self._width(w)+ self.assertEqual(+ m.get("header_rows"), 1,+ f"{w}: header_rows {m.get('header_rows')} != 1 "+ f"(row centres {m.get('header_row_centres')}, "+ f"children {m.get('header_children')})")++ def test_save_is_a_button_not_a_bar(self):+ """The 1554px defect, measured in the state it appeared in."""+ for w in WIDTHS:+ with self.subTest(width=w):+ m = self._width(w)+ sw = m.get("save_width")+ self.assertIsNotNone(sw, f"{w}: Save was not measured")+ self.assertTrue(+ m.get("save_primary"),+ f"{w}: Save was not in its `.primary` state, which is the "+ f"only state the 1554px defect ever appeared in "+ f"(class {m.get('save_class')!r})")+ self.assertTrue(+ SAVE_MIN <= sw <= SAVE_MAX,+ f"{w}: save_width {sw} outside [{SAVE_MIN:g}, "+ f"{SAVE_MAX:g}] (class {m.get('save_class')!r})")++ def test_column_does_not_scroll_sideways(self):+ for w in WIDTHS:+ with self.subTest(width=w):+ m = self._width(w)+ over = m.get("column_overflow")+ self.assertIsNotNone(over, f"{w}: #edStage was not measured")+ self.assertLessEqual(+ over, OVERFLOW_TOL,+ f"{w}: column_overflow {over} > {OVERFLOW_TOL:g} "+ f"(scrollWidth {m.get('column_scroll_width')} vs "+ f"clientWidth {m.get('column_client_width')})")++ def test_timeline_floor_does_not_clip_its_lanes(self):+ for w in WIDTHS:+ with self.subTest(width=w):+ m = self._width(w)+ clip = m.get("timeline_clip")+ self.assertIsNotNone(clip, f"{w}: #sbeScroll was not measured")+ self.assertLessEqual(+ clip, OVERFLOW_TOL,+ f"{w}: timeline_clip {clip} > {OVERFLOW_TOL:g} - the "+ f"soundtrack lane is cut off (scrollHeight "+ f"{m.get('timeline_scroll_height')} vs clientHeight "+ f"{m.get('timeline_client_height')}, floor "+ f"{m.get('timeline_floor_h')})")++ # -- the draggable affordances ----------------------------------------+ def test_every_draggable_affordance_was_actually_measured(self):+ """A gate that measured nothing would report nothing and pass.++ The verdict on hit sizes and overlaps lands in `failures`, which+ `test_gate_reports_no_failures` already asserts is empty — but an empty+ list is also what an empty timeline produces, and an empty timeline is+ exactly what the seed used to be. So this asserts the rows were THERE:+ both blocks, at both ends of the lane range, with a rectangle for every+ affordance the table names.+ """+ handles = self.doc.get("handles") or {}+ self.assertEqual(sorted(handles), ["ceiling", "floor"],+ f"the gate measured {sorted(handles)}, not both ends "+ f"of the lane range")+ want = {"clip": ("grip_l", "grip_r", "fade_in", "fade_out"),+ "aclip": ("grip_l", "grip_r", "fade_in", "fade_out",+ "level", "kf")}+ for end, m in handles.items():+ for block, names in want.items():+ with self.subTest(end=end, block=block):+ rows = (m.get("blocks") or {}).get(block)+ self.assertTrue(rows, f"{end}: no {block} on screen")+ for n in names:+ self.assertIn(n, rows,+ f"{end}/{block}: {n} was never found, so "+ f"nothing was checked about it")+ self.assertGreater(rows[n]["w"], 0)+ self.assertGreater(rows[n]["h"], 0)+ # ...and the floor really is the floor: the lanes at their bases,+ # not a track that flex has grown in a tall window.+ if end == "floor":+ self.assertEqual(m.get("lane_track"), "64px")+ self.assertEqual(m.get("lane_alane"), "44px")++ def test_stage_never_shows_both_layers(self):+ for w in WIDTHS:+ with self.subTest(width=w):+ m = self._width(w)+ self.assertIs(+ m.get("stage_layers_both_visible"), False,+ f"{w}: the <video> and the still are both visible "+ f"(video opacity {m.get('video_opacity')}, still opacity "+ f"{m.get('still_opacity')})")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_editor_mix.py b/test_editor_mix.pynew file mode 100644index 0000000..51859f8--- /dev/null+++ b/test_editor_mix.py@@ -0,0 +1,824 @@+"""The mix — one definition, read identically by the preview and the render.++WHAT THESE EXIST FOR. The renderer was a second author of the soundtrack's+level, and an invisible one: under `mode: "under"` the ffmpeg graph held every+bed at a hard-coded `volume=0.20` and then pushed it down a further ~11 dB+through a `sidechaincompress` keyed on the clips' own audio. Neither number was+in any document, on any screen, or in the preview — so the one surface the user+checks his work on played a mix the file never had.++ "when you render it, there are some weird manipulations... the volume of+ the music goes low when the dialogue appears. The mix is weird."++`docs/EDITOR_EFFECTS_MODEL.md` already decided the shape of the fix: if the+preview and the render can disagree about a gain, that gain is not in the+model. So the suite below asks the only question that settles it — does the+BROWSER compute the same number as the SERVER, for the same document, at the+same second — and it asks it by running the panel's real JavaScript in node+against the real Python, rather than by grepping either for a promising string.+"""++import json+import math+import re+import subprocess+import tempfile+import unittest+from pathlib import Path++import mlx_ltx_panel as panel+import storyboard_editor as se+from test_storyboard_editor_ui import (FUNCTIONS, NODE, SHIM, extract_function,+ panel_source)++ROOT = Path(__file__).resolve().parent+++# ---------------------------------------------------------------------------+# Running the panel's own client model, for real+# ---------------------------------------------------------------------------+def run_js(body: str) -> dict:+ """Evaluate `body` with every extracted client function in scope.++ The same harness `test_storyboard_editor_ui` uses, and for the same+ reason: `scripts/extract_panel_js.py` RAISES on a renamed function, so a+ client model that quietly drifts away from the server's turns this red+ instead of turning the preview into a liar.+ """+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = panel_source()+ # THE CONSTANTS COME OUT OF THE PANEL, NOT OUT OF A COPY HERE. A shim that+ # restated `SBE_MIX_DUCK_GAIN` would be a third place for one number to+ # live, and this file exists because two was already one too many.+ consts = "\n".join(m + ";" for m in re.findall(+ r"^const SBE_MIX_\w+ = [^;]+", src, re.MULTILINE))+ assert consts, "the panel declares no SBE_MIX_* constants"+ script = (SHIM + consts + "\n"+ + "\n".join(extract_function(n, src) for n in FUNCTIONS)+ + "\nconst out = {};\n" + body+ + "\nprocess.stdout.write(JSON.stringify(out));\n")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = subprocess.run([NODE, str(path)], capture_output=True,+ text=True, timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)+++def _clip(path, film_start, dur, **extra):+ c = {"path": path, "start": 0.0, "end": dur, "source": "human",+ "film_start": film_start, "film_end": film_start + dur}+ c.update(extra)+ return c+++def bed_only():+ """A film whose clips carry NO sound: nothing for the duck to key on."""+ return {"version": 2,+ "clips": [_clip("/x/a.mp4", 0.0, 4.0, has_audio=False),+ _clip("/x/b.mp4", 4.0, 4.0, has_audio=False)],+ "audio": {"path": "/x/song.mp3", "duration": 30.0,+ "mode": "under", "mix": {"bed_gain": 0.5, "duck": True}}}+++def dialogue_only():+ """Sound under every shot, back to back — the duck is on for all of it."""+ return {"version": 2,+ "clips": [_clip("/x/a.mp4", 0.0, 4.0),+ _clip("/x/b.mp4", 4.0, 4.0)],+ "audio": {"path": "/x/song.mp3", "duration": 30.0,+ "mode": "under", "mix": {"bed_gain": 0.5, "duck": True}}}+++def overlapping():+ """Sound, then a hole, then sound: the duck goes down, up, and down."""+ return {"version": 2,+ "clips": [_clip("/x/a.mp4", 0.0, 3.0),+ _clip("/x/b.mp4", 5.0, 3.0, has_audio=False),+ _clip("/x/c.mp4", 8.0, 3.0)],+ "audio": {"path": "/x/song.mp3", "duration": 30.0,+ "mode": "under", "mix": {"bed_gain": 0.8, "duck": True}}}+++def authored():+ """A bed the user has shaped himself. His envelope, nothing else."""+ return {"version": 2,+ "clips": [_clip("/x/a.mp4", 0.0, 4.0),+ _clip("/x/b.mp4", 4.0, 4.0)],+ "audio": {"path": "/x/song.mp3", "duration": 30.0, "mode": "under",+ "mix": {"bed_gain": 0.9, "duck": True},+ "afx": {"fade_in": 1.5, "fade_out": 3.0,+ "points": [[10.0, 0.4], [18.0, 1.0]]}}}+++CASES = {"bed_only": bed_only(), "dialogue_only": dialogue_only(),+ "overlapping": overlapping(), "authored": authored(),+ "default": {"version": 2, "clips": [_clip("/x/a.mp4", 0.0, 4.0)],+ "audio": {"path": "/x/song.mp3", "duration": 30.0,+ "mode": "under"}},+ "moved": {"version": 2,+ "clips": [_clip("/x/a.mp4", 0.0, 6.0)],+ "audio": {"path": "/x/song.mp3", "duration": 30.0,+ "mode": "under", "offset": -2.0,+ "trim_start": 0.0,+ "mix": {"bed_gain": 0.6, "duck": True}}}}++# Where the two are asked. Deliberately not on the breakpoints alone: an+# agreement that only holds at the knots is an agreement about a list, not+# about a curve.+PROBES = [0.0, 0.004, 0.02, 0.5, 2.9, 3.0, 3.2, 3.4, 4.0, 5.0, 7.5, 8.0,+ 10.25, 11.0, 12.0, 15.0, 19.9, 25.0]+++class ThePreviewAndTheRenderComputeTheSameMix(unittest.TestCase):+ """THE HEADLINE INVARIANT. Everything else in this file supports it."""++ @classmethod+ def setUpClass(cls) -> None:+ body = """+const CASES = %s;+const PROBES = %s;+out.curves = {}; out.at = {}; out.len = {}; out.suppressed = {};+for (const [name, edit] of Object.entries(CASES)) {+ // THE FILM'S OWN CLOCK, computed from the same document the server reads —+ // not handed in from a probe the render has never seen. See `sbeBedLen`.+ const dur = sbeFilmDuration(edit.clips);+ out.curves[name] = sbeBedGainPoints(edit.audio, edit.clips, dur);+ out.len[name] = sbeBedLen(edit.audio, dur);+ out.suppressed[name] = sbeBedDuckSuppressed(edit.audio, dur);+ out.at[name] = PROBES.map(t => sbeBedGainAt(edit.audio, edit.clips, dur, t));+}+out.mix = {+ absent: sbeAudioMix({}),+ partial: sbeAudioMix({ mix: { duck: true } }),+ clamped: sbeAudioMix({ mix: { bed_gain: 4 } }),+};+""" % (json.dumps(CASES), json.dumps(PROBES))+ cls.js = run_js(body)++ def test_the_curve_the_browser_draws_is_the_curve_the_render_applies(self):+ for name, edit in CASES.items():+ with self.subTest(case=name):+ self.assertEqual(+ [[round(t, 6), round(g, 6)]+ for t, g in self.js["curves"][name]],+ se.bed_gain_points(edit),+ f"{name}: the client and the server disagree about the bed")++ def test_they_agree_at_every_second_and_not_only_at_the_knots(self):+ for name, edit in CASES.items():+ with self.subTest(case=name):+ want = [se.bed_gain_at(edit, t) for t in PROBES]+ got = [round(v, 6) for v in self.js["at"][name]]+ for t, a, b in zip(PROBES, got, want):+ self.assertAlmostEqual(+ a, b, places=5,+ msg=f"{name} @ {t}s: preview {a} vs render {b}")++ def test_they_agree_about_how_long_the_bed_is(self):+ # The envelope's clock. If these differ, every fade is drawn in one+ # place and rendered in another.+ for name, edit in CASES.items():+ with self.subTest(case=name):+ self.assertAlmostEqual(+ self.js["len"][name],+ se.bed_length(edit["audio"], se.edit_duration(edit)),+ places=5)++ def test_they_agree_about_when_the_duck_stands_down(self):+ for name, edit in CASES.items():+ with self.subTest(case=name):+ self.assertEqual(self.js["suppressed"][name],+ se.bed_duck_suppressed(edit))++ def test_the_accessor_reads_the_same_defaults_on_both_sides(self):+ self.assertEqual(self.js["mix"]["absent"],+ se.audio_mix({}))+ self.assertEqual(self.js["mix"]["partial"],+ se.audio_mix({"mix": {"duck": True}}))+ # Out of range is CLAMPED, not refused: a slider cannot produce this,+ # but a hand-edited document can, and a gain of 4 is a blown mix.+ self.assertEqual(self.js["mix"]["clamped"],+ se.audio_mix({"mix": {"bed_gain": 4}}))+ self.assertEqual(se.audio_mix({"mix": {"bed_gain": 4}})["bed_gain"], 1.0)+++class TheConstantsCannotDrift(unittest.TestCase):+ """A mirrored constant is a mirror, and a mirror is a thing that drifts."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()++ def _js_const(self, name: str) -> float:+ m = re.search(rf"const {name} = ([-\d.]+|true|false);", self.src)+ self.assertIsNotNone(m, f"{name} is not declared in the panel")+ v = m.group(1)+ return {"true": True, "false": False}.get(v, None) or float(v)++ def test_the_client_and_the_server_agree_about_the_mix_constants(self):+ self.assertEqual(self._js_const("SBE_MIX_BED_GAIN"), se.MIX_BED_GAIN)+ self.assertEqual(self._js_const("SBE_MIX_DUCK_GAIN"), se.MIX_DUCK_GAIN)+ self.assertEqual(self._js_const("SBE_MIX_DUCK_ATTACK"),+ se.MIX_DUCK_ATTACK)+ self.assertEqual(self._js_const("SBE_MIX_DUCK_RELEASE"),+ se.MIX_DUCK_RELEASE)+ self.assertIn("const SBE_MIX_DUCK = false;", self.src)+ self.assertIs(se.MIX_DUCK, False)++ def test_the_panel_and_the_model_agree_about_the_ceiling(self):+ # The panel keeps a last-resort literal so it can boot without the+ # editor module — shipping an UNLIMITED mix would be the worse of the+ # two failures — but the value it USES comes from the model.+ self.assertEqual(panel._sb_mix_ceiling(), se.MIX_CEILING)+ self.assertEqual(panel.SB_MIX_CEILING_FALLBACK, se.MIX_CEILING)++ def test_the_duck_depth_is_the_measured_one(self):+ # 11.4 dB is what the gated-tone rig measured for the compressor this+ # replaces (0.02 / 10), and the envelope reproduces that depth rather+ # than a rounder number somebody preferred.+ self.assertAlmostEqual(20 * math.log10(se.MIX_DUCK_GAIN), -11.4,+ places=1)+++class TheRenderAppliesExactlyWhatTheDocumentSays(unittest.TestCase):+ """The other half of the equality: the ffmpeg expression, evaluated."""++ @staticmethod+ def _volume_expr(edit) -> str:+ term = panel._sb_volume_term(se.bed_render_gain(edit))+ m = re.search(r"volume=volume='(.+)':eval=frame,", term)+ return m.group(1) if m else ""++ @staticmethod+ def _eval(expr: str, t: float) -> float:+ """ffmpeg's own expression, evaluated. Not a re-derivation of it.++ The generated grammar is exactly `if(lt(t,X),A,B)` over arithmetic, so+ rewriting `if(` to a strict three-argument call and `lt` to a+ comparison evaluates the STRING the renderer will hand ffmpeg — which+ is the thing under test. Both branches are arithmetic with a divisor+ `_sb_volume_term` has already refused to make zero, so evaluating them+ eagerly is safe.+ """+ return eval(expr.replace("if(", "IF("), # noqa: S307+ {"__builtins__": {}},+ {"IF": lambda c, a, b: a if c else b,+ "lt": lambda a, b: a < b, "t": t})++ def test_the_expression_ffmpeg_gets_is_the_curve_the_preview_played(self):+ for name, edit in CASES.items():+ expr = self._volume_expr(edit)+ if not expr:+ # A unity bed adds NO filter, which is the neutral-is-absent+ # rule: the graph for a film nobody mixed is byte-identical to+ # one from before the mix was a control.+ self.assertEqual(se.bed_gain_points(edit), [], name)+ continue+ delay = se.music_window(edit["audio"])["delay"]+ n = se.bed_length(edit["audio"], se.edit_duration(edit))+ with self.subTest(case=name):+ for t in [p for p in PROBES if p <= n]:+ self.assertAlmostEqual(+ self._eval(expr, t + delay),+ se.bed_gain_at(edit, t), places=5,+ msg=f"{name} @ {t}s on the bed's clock")++ def test_an_authored_envelope_reaches_the_render_exactly(self):+ # The field the graph always read and NOTHING ever set: a fade on the+ # soundtrack was expressible in the model, drawn on the strip, and+ # absent from the file.+ edit = authored()+ expr = self._volume_expr(edit)+ self.assertTrue(expr)+ n = se.bed_length(edit["audio"])+ # The fade-in ramps from silence, the fade-out lands on it, and the+ # authored dip at 10 s is 0.4 of the fader.+ self.assertAlmostEqual(self._eval(expr, 0.0), 0.0, places=5)+ self.assertAlmostEqual(self._eval(expr, n), 0.0, places=5)+ self.assertAlmostEqual(self._eval(expr, 10.0), 0.4 * 0.9, places=4)+ self.assertAlmostEqual(self._eval(expr, 18.0), 1.0 * 0.9, places=4)++ def test_the_render_stops_inventing_a_bed_gain_of_its_own(self):+ graph, _ = panel._sb_film_filtergraph(+ [], 1024, 576, 24, "yuv420p",+ music={"path": "/x/song.mp3", "start": 0.0, "mode": "under"},+ segments=[{"kind": "slug", "input": None, "info": None,+ "window": None, "adjust": None, "duration": 4.0}])+ self.assertNotIn("sidechaincompress", graph)+ self.assertNotIn("volume=0.20", graph)++ def test_a_document_nobody_mixed_builds_the_graph_it_always_did(self):+ edit = {"version": 2, "clips": [_clip("/x/a.mp4", 0.0, 4.0)],+ "audio": {"path": "/x/song.mp3", "duration": 30.0,+ "mode": "replace"}}+ self.assertEqual(se.bed_render_gain(edit), [])+ self.assertEqual(panel._sb_volume_term(se.bed_render_gain(edit)), "")+++class TheDefaultsAreSettledAndTheHealIsOneTime(unittest.TestCase):+ def test_a_new_timeline_plays_the_track_and_leaves_it_alone(self):+ self.assertEqual(se.MIX_BED_GAIN, 1.0)+ self.assertIs(se.MIX_DUCK, False)+ fresh = {"version": 2, "clips": [], "audio": {"path": "/x/s.mp3"}}+ self.assertEqual(se.audio_mix(fresh["audio"]),+ {"bed_gain": 1.0, "duck": False})++ def test_an_existing_under_film_keeps_the_levels_it_was_approved_at(self):+ doc = {"version": 2, "clips": [],+ "audio": {"path": "/x/s.mp3", "mode": "under"}}+ got = se.migrate_edit(doc)+ self.assertEqual(got["audio"]["mix"],+ {"bed_gain": se.MIX_LEGACY_BED_GAIN, "duck": True})+ self.assertEqual(got["mix_repair"], se.MIX_REPAIR_VERSION)+ self.assertTrue(got["repaired_mix"])+ # The old renderer's own number, so the film is the film.+ self.assertEqual(se.MIX_LEGACY_BED_GAIN, 0.2)++ def test_a_replace_film_is_left_completely_alone(self):+ # `replace` never touched the bed — no gain term, no compressor — so+ # stamping one would invent an attenuation that path never had.+ doc = {"version": 2, "clips": [],+ "audio": {"path": "/x/s.mp3", "mode": "replace"}}+ got = se.migrate_edit(doc)+ self.assertNotIn("mix", got["audio"])+ self.assertNotIn("repaired_mix", got)++ def test_a_film_with_no_soundtrack_is_left_alone(self):+ got = se.migrate_edit({"version": 2, "clips": [], "audio": None})+ self.assertIsNone(got["audio"])++ def test_THE_HEAL_NEVER_RUNS_TWICE_OVER_A_DECISION(self):+ # THE DEFECT THE MARKER EXISTS FOR. `normalise_edit` drops a mix that+ # is back at the default, so without the marker a user who switched+ # the duck OFF would have the next READ helpfully put it back — the+ # rival author, wearing a repair's clothes.+ doc = se.migrate_edit({"version": 2, "clips": [],+ "audio": {"path": "/x/s.mp3", "mode": "under"}})+ doc["audio"]["mix"] = {"bed_gain": 1.0, "duck": False}+ saved = se.normalise_edit(doc)+ self.assertNotIn("mix", saved["audio"]) # neutral is absent+ self.assertEqual(saved["mix_repair"], se.MIX_REPAIR_VERSION)+ again = se.migrate_edit(saved)+ self.assertNotIn("mix", again["audio"]) # and it STAYS off++ def test_the_read_does_not_mutate_the_document_it_was_given(self):+ # `pending_backup` compares raw JSON on both sides, so a read that+ # edits its argument in place makes the file and the snapshot differ+ # over a repair neither of them contains — which resurrects the+ # permanent interrogation `docs/EDITOR_SAVE_MODEL.md` exists to kill.+ doc = {"version": 2, "clips": [_clip("/x/a.mp4", 0.0, 4.0)],+ "audio": {"path": "/x/s.mp3", "mode": "under"}}+ before = json.dumps(doc, sort_keys=True)+ se.migrate_edit(doc)+ self.assertEqual(json.dumps(doc, sort_keys=True), before)+ self.assertNotIn("mix", doc["audio"])++ def test_the_marker_is_not_a_content_difference(self):+ # A field the user cannot see may never be the reason they are asked a+ # question — invariant 3 of the save model.+ a = {"version": 2, "clips": [], "audio": {"path": "/x/s.mp3"}}+ b = dict(a, mix_repair=se.MIX_REPAIR_VERSION, repaired_mix=True)+ self.assertEqual(se.edit_digest(a), se.edit_digest(b))++ def test_but_the_mix_ITSELF_is_content(self):+ a = {"version": 2, "clips": [], "audio": {"path": "/x/s.mp3"}}+ b = {"version": 2, "clips": [],+ "audio": {"path": "/x/s.mp3", "mix": {"bed_gain": 0.3}}}+ self.assertNotEqual(se.edit_digest(a), se.edit_digest(b))+++class TheMixSurvivesTheRoundTrip(unittest.TestCase):+ def test_duck_on_and_off_round_trip_through_save_and_load(self):+ import tempfile as _tf+ for duck, gain in ((True, 0.35), (False, 1.0), (True, 1.0),+ (False, 0.5)):+ with self.subTest(duck=duck, gain=gain):+ with _tf.TemporaryDirectory() as d:+ doc = {"version": 2,+ "clips": [_clip("/x/a.mp4", 0.0, 4.0)],+ "audio": {"path": "/x/s.mp3", "duration": 30.0,+ "mode": "under",+ "mix": {"bed_gain": gain, "duck": duck}},+ # The marker rides along so the heal cannot be what+ # answers this question instead of the round trip.+ "mix_repair": se.MIX_REPAIR_VERSION}+ se.save_edit(d, doc)+ back = se.load_edit(d)+ self.assertEqual(se.audio_mix(back["audio"]),+ {"bed_gain": gain, "duck": duck})++ def test_a_bed_envelope_round_trips_through_save_and_load(self):+ import tempfile as _tf+ with _tf.TemporaryDirectory() as d:+ doc = {"version": 2, "clips": [_clip("/x/a.mp4", 0.0, 4.0)],+ "audio": {"path": "/x/s.mp3", "duration": 30.0,+ "mode": "under",+ "afx": {"fade_in": 1.0, "fade_out": 2.0,+ "points": [[12.0, 0.3]]}},+ "mix_repair": se.MIX_REPAIR_VERSION}+ se.save_edit(d, doc)+ back = se.load_edit(d)+ self.assertEqual(back["audio"]["afx"],+ {"fade_in": 1.0, "fade_out": 2.0,+ "points": [[12.0, 0.3]]})++ def test_a_bad_mix_is_refused_with_a_sentence(self):+ for mix, code in (({"bed_gain": "loud"}, "audio_mix_bed_gain"),+ ({"bed_gain": 3}, "audio_mix_bed_gain_range"),+ ({"duck": "yes"}, "audio_mix_duck")):+ doc = {"version": 2, "clips": [],+ "audio": {"path": "/x/s.mp3", "mix": mix}}+ codes = [e["code"] for e in se.validate_edit(doc)]+ self.assertIn(code, codes, mix)+++class ThePrecedenceIsOneCurveAtATime(unittest.TestCase):+ """THE RULE: the user's envelope wins, and the duck stands down."""++ def test_an_authored_envelope_switches_the_auto_duck_off(self):+ edit = authored()+ self.assertTrue(se.audio_mix(edit["audio"])["duck"])+ self.assertTrue(se.bed_duck_suppressed(edit))+ # The curve is the fader times the ENVELOPE, with no duck in it. At+ # 6 s the second clip's sound is playing and the bed does NOT step+ # back: the value is the envelope's own (0.4, held before its first+ # point) times the fader, and 0.269 appears nowhere in it.+ self.assertAlmostEqual(se.bed_gain_at(edit, 6.0), 0.4 * 0.9, places=4)+ with_duck = 0.4 * 0.9 * se.MIX_DUCK_GAIN+ self.assertNotAlmostEqual(se.bed_gain_at(edit, 6.0), with_duck,+ places=4)++ def test_two_curves_are_never_multiplied_together(self):+ # The proof is arithmetic: every value on an authored bed's curve is a+ # value on the envelope times the fader, and the duck's depth (0.269)+ # appears nowhere in it.+ edit = authored()+ n = se.bed_length(edit["audio"])+ env = se.audio_gain_points(edit["audio"], n)+ got = dict(se.bed_gain_points(edit))+ for t, g in env:+ self.assertAlmostEqual(got[t], g * 0.9, places=5)++ def test_the_fader_is_a_scalar_and_composes_with_everything(self):+ edit = dialogue_only()+ edit["audio"]["mix"] = {"bed_gain": 1.0, "duck": True}+ full = se.bed_gain_at(edit, 2.0)+ edit["audio"]["mix"] = {"bed_gain": 0.5, "duck": True}+ half = se.bed_gain_at(edit, 2.0)+ self.assertAlmostEqual(half, full * 0.5, places=5)++ def test_the_duck_is_keyed_on_the_document_and_not_on_the_samples(self):+ # A muted clip and a clip with no audio track contribute NO lane to+ # the render, so neither may duck anything.+ edit = dialogue_only()+ self.assertEqual(se.audible_strips(edit), [[0.0, 8.0]])+ edit["clips"][1]["mute"] = True+ self.assertEqual(se.audible_strips(edit), [[0.0, 4.0]])+ edit["clips"][0]["has_audio"] = False+ self.assertEqual(se.audible_strips(edit), [])++ def test_lines_closer_than_one_release_do_not_pump(self):+ edit = {"version": 2,+ "clips": [_clip("/x/a.mp4", 0.0, 3.0),+ _clip("/x/b.mp4", 3.2, 3.0)],+ "audio": {"path": "/x/s.mp3", "duration": 30.0, "mode": "under",+ "mix": {"duck": True}}}+ # 0.2 s apart, which is inside the 0.4 s release: one window, so the+ # bed does not scramble back up and down between them.+ self.assertEqual(se.audible_strips(edit), [[0.0, 6.2]])+ self.assertAlmostEqual(se.bed_gain_at(edit, 3.1), se.MIX_DUCK_GAIN,+ places=4)++ def test_the_bed_is_at_FULL_level_where_nothing_is_speaking(self):+ edit = overlapping()+ # The hole between 5 s and 8 s, one release after the first window.+ self.assertAlmostEqual(se.bed_gain_at(edit, 6.0), 0.8, places=4)+ # ...and down again under the third shot.+ self.assertAlmostEqual(se.bed_gain_at(edit, 9.0),+ 0.8 * se.MIX_DUCK_GAIN, places=4)+++class TheNLEExportStillShipsStems(unittest.TestCase):+ """An NLE gets raw stems plus automation. That is deliberate."""++ def test_the_soundtrack_clipitem_carries_no_gain_and_no_duck(self):+ edit = dialogue_only()+ xml = se.fcp7_xml(+ [], name="film", media={"/x/song.mp3": "song.mp3"},+ width=1024, height=576, base="/tmp/p", audio=edit["audio"])+ # The bed is there, at its own level, with nothing done to it: the+ # under-mix has no representation in an NLE's timeline, so baking it+ # in would hand an editor a bed they cannot unmix or re-balance.+ self.assertIn('clipitem-music', xml)+ self.assertNotIn("sidechain", xml.lower())+ head, _, _ = xml.partition('clipitem-music')+ tail = xml[len(head):]+ self.assertNotIn("<name>Audio Levels</name>", tail)+ self.assertNotIn("audiolevels", tail.lower())++ def test_the_bed_is_still_placed_at_the_window_the_render_uses(self):+ # Stems undducked is not stems misplaced.+ aud = {"path": "/x/s.mp3", "duration": 30.0, "offset": 0.0,+ "trim_start": 4.0, "mix": {"bed_gain": 0.2, "duck": True}}+ xml = se.fcp7_xml([], name="film", media={"/x/s.mp3": "s.mp3"},+ width=1024, height=576, base="/tmp/p", audio=aud)+ win = se.music_window(aud)+ self.assertGreater(win["start"], 0)+ self.assertIn("clipitem-music", xml)+++# ---------------------------------------------------------------------------+# THE TABLE. One row per SHAPE a document can have, not one per feature.+# ---------------------------------------------------------------------------+# WHY THIS EXISTS ON TOP OF EVERYTHING ABOVE. The mix is two implementations —+# `storyboard_editor.bed_gain_points` and the panel's `sbeBedGainPoints`,+# function for function — and the suite written to keep them together compared+# the five CONSTANTS and four hand-built documents. It never compared the+# ARITHMETIC over the shapes a real edit.json takes, so a divergence lived+# through it: a bed with no `duration` and no `trim_end` made the server's+# `bed_length` return 0, which made its curve EMPTY, which means "no filter" —+# the render played the bed at unity over the dialogue while the browser drew+# it 19.6 dB lower and the preview played what it drew.+#+# So the gate is a TABLE, and the rule for adding to it is "a shape a document+# can have", not "a feature somebody wrote". Both sides are handed the same+# JSON and nothing else — in particular the client is NOT handed the peaks+# probe, because the renderer cannot see peaks.json and a term only one side+# can compute is how the two came apart in the first place.+def _t(clips, audio, **extra):+ doc = {"version": 2, "clips": clips, "audio": audio}+ doc.update(extra)+ return doc+++def _under(**fields):+ a = {"path": "/x/song.mp3", "mode": "under",+ "mix": {"bed_gain": 0.35, "duck": True}}+ a.update(fields)+ return a+++_SPEAKING = [_clip("/x/a.mp4", 0.0, 3.0), _clip("/x/b.mp4", 3.0, 3.0)]++TABLE = {+ # THE MEASURED DEFECT. No length anywhere on the bed: the render used to+ # answer this with an empty curve, which is the bed at FULL level.+ "no_duration": _t(_SPEAKING, _under()),+ # ...and the same hole with the block moved, so the fallback is exercised+ # as "what is left of the film after the bed starts" rather than as "the+ # film's length", which are different numbers the moment offset is not 0.+ "no_duration_late": _t(_SPEAKING, _under(offset=-2.0)),+ "no_duration_head_trim": _t(_SPEAKING, _under(trim_start=4.0)),+ "no_duration_authored": _t(_SPEAKING, _under(+ afx={"fade_in": 0.5, "fade_out": 1.0, "points": [[2.0, 0.6]]})),+ "no_duration_no_clips": _t([], _under()),+ # NO TRIM_END, which is the ordinary document: a bed that plays to the end+ # of the track.+ "no_trim_end": _t(_SPEAKING, _under(duration=30.0)),+ "bed_longer_than_film": _t(_SPEAKING, _under(duration=45.0)),+ "bed_shorter_than_film": _t(_SPEAKING, _under(duration=4.0)),+ "bed_exactly_the_film": _t(_SPEAKING, _under(duration=6.0)),+ # TRIMS: both ends, one end, a handle dragged back out past the end of the+ # track (which is not a trim), and a pair that closes the window entirely.+ "trimmed_both_ends": _t(_SPEAKING, _under(duration=30.0, trim_start=5.0,+ trim_end=20.0)),+ "trim_end_past_the_track": _t(_SPEAKING, _under(duration=30.0,+ trim_end=30.0)),+ "trims_close_the_window": _t(_SPEAKING, _under(duration=30.0,+ trim_start=12.0,+ trim_end=9.0)),+ "moved_negative_offset": _t(_SPEAKING, _under(duration=30.0, offset=-2.5)),+ "moved_positive_offset": _t(_SPEAKING, _under(duration=30.0, offset=3.0)),+ # THE AUTHORED ENVELOPE, which outranks the duck — with and without a+ # stated length, because the fade-out anchors on the bed's LAST second and+ # that is precisely the number the two sides used to disagree about.+ "authored_fades": _t(_SPEAKING, _under(+ duration=30.0, afx={"fade_in": 1.5, "fade_out": 3.0})),+ "authored_points": _t(_SPEAKING, _under(+ duration=30.0, afx={"points": [[2.0, 0.2], [9.0, 1.0]]})),+ "authored_everything": _t(_SPEAKING, _under(+ duration=30.0, mix={"bed_gain": 0.9, "duck": True},+ afx={"fade_in": 1.0, "fade_out": 2.0,+ "points": [[4.0, 0.4], [12.0, 0.8]]})),+ # THE DUCK, ON AND OFF, and the fader on its own.+ "duck_off": _t(_SPEAKING, _under(duration=30.0,+ mix={"bed_gain": 0.35, "duck": False})),+ "duck_on_fader_unity": _t(_SPEAKING, _under(duration=30.0,+ mix={"bed_gain": 1.0,+ "duck": True})),+ "fader_only": _t(_SPEAKING, _under(duration=30.0,+ mix={"bed_gain": 0.5, "duck": False})),+ "fader_at_zero": _t(_SPEAKING, _under(duration=30.0,+ mix={"bed_gain": 0.0, "duck": True})),+ "no_mix_block_at_all": _t(_SPEAKING, {"path": "/x/song.mp3",+ "duration": 30.0, "mode": "under"}),+ # WHAT THE DUCK IS KEYED ON. A muted clip and a clip with no audio track+ # are both silence, and neither may duck anything.+ "one_clip_muted": _t([_clip("/x/a.mp4", 0.0, 3.0),+ _clip("/x/b.mp4", 3.0, 3.0, mute=True)],+ _under(duration=30.0)),+ "all_clips_muted": _t([_clip("/x/a.mp4", 0.0, 3.0, mute=True),+ _clip("/x/b.mp4", 3.0, 3.0, mute=True)],+ _under(duration=30.0)),+ "one_clip_has_no_audio": _t([_clip("/x/a.mp4", 0.0, 3.0, has_audio=False),+ _clip("/x/b.mp4", 3.0, 3.0)],+ _under(duration=30.0)),+ "no_clip_has_audio": _t([_clip("/x/a.mp4", 0.0, 3.0, has_audio=False),+ _clip("/x/b.mp4", 3.0, 3.0, has_audio=False)],+ _under(duration=30.0)),+ "muted_and_silent_and_no_duration": _t(+ [_clip("/x/a.mp4", 0.0, 3.0, mute=True),+ _clip("/x/b.mp4", 3.0, 3.0, has_audio=False)], _under()),+ # HOLES, so the duck goes down, up and down again — and a pair of lines+ # closer together than one release, which must NOT pump.+ "a_hole_between_lines": _t([_clip("/x/a.mp4", 0.0, 3.0),+ _clip("/x/b.mp4", 5.0, 3.0, has_audio=False),+ _clip("/x/c.mp4", 8.0, 3.0)],+ _under(duration=30.0)),+ "lines_inside_one_release": _t([_clip("/x/a.mp4", 0.0, 3.0),+ _clip("/x/b.mp4", 3.2, 3.0)],+ _under(duration=30.0)),+ # A J-CUT: the sound's own window, ahead of its picture.+ "a_j_cut": _t([_clip("/x/a.mp4", 0.0, 3.0),+ _clip("/x/b.mp4", 3.0, 3.0,+ audio={"start": 0.0, "end": 3.0, "film_start": 2.0})],+ _under(duration=30.0)),+ # AND THE DOCUMENTS THAT HAVE NO MIX TO COMPUTE. Both sides must produce+ # the same NOTHING, or a film nobody mixed stops building the graph it+ # always did.+ "replace_mode": _t(_SPEAKING, {"path": "/x/song.mp3", "duration": 30.0,+ "mode": "replace"}),+ "no_soundtrack": _t(_SPEAKING, None),+ "soundtrack_without_a_path": _t(_SPEAKING, {"duration": 30.0,+ "mode": "under"}),+ "an_empty_film": _t([], _under(duration=30.0)),+}++# Asked BETWEEN the knots as well as on them: an agreement that only holds at+# the breakpoints is an agreement about a list, not about a curve.+TABLE_PROBES = [0.0, 0.001, 0.005, 0.01, 0.25, 1.0, 1.9, 2.0, 2.1, 2.9, 3.0,+ 3.05, 3.4, 3.9, 4.0, 5.5, 5.999, 6.0, 6.4, 8.0, 11.0, 15.0,+ 19.999, 20.0, 25.0, 44.0]+++class TheTwoImplementationsAgreeOverEveryShapeOfDocument(unittest.TestCase):+ """THE GATE THE DIVERGENCE GOT PAST. Real node, real Python, one table."""++ @classmethod+ def setUpClass(cls) -> None:+ body = """+const TABLE = %s;+const PROBES = %s;+out.film = {}; out.len = {}; out.curves = {}; out.at = {}; out.suppressed = {};+for (const [name, edit] of Object.entries(TABLE)) {+ const a = edit.audio || {};+ // EVERY INPUT COMES OUT OF THE DOCUMENT. The film's clock is derived here+ // exactly as the server derives it, so neither side is handed a number the+ // other could not have worked out for itself.+ const film = sbeFilmDuration(edit.clips);+ out.film[name] = film;+ out.len[name] = sbeBedLen(a, film);+ out.curves[name] = sbeBedGainPoints(a, edit.clips, film);+ out.suppressed[name] = sbeBedDuckSuppressed(a, film);+ out.at[name] = PROBES.map(t => sbeBedGainAt(a, edit.clips, film, t));+}+""" % (json.dumps(TABLE), json.dumps(TABLE_PROBES))+ cls.js = run_js(body)++ def test_they_agree_about_the_films_own_clock(self):+ # The fallback is only as good as the number it falls back TO.+ for name, edit in TABLE.items():+ with self.subTest(case=name):+ self.assertAlmostEqual(self.js["film"][name],+ se.edit_duration(edit), places=5)++ def test_they_agree_about_how_long_the_bed_is(self):+ for name, edit in TABLE.items():+ with self.subTest(case=name):+ self.assertAlmostEqual(+ self.js["len"][name],+ se.bed_length(edit["audio"], se.edit_duration(edit)),+ places=5)++ def test_THE_CURVES_ARE_IDENTICAL_POINT_FOR_POINT(self):+ for name, edit in TABLE.items():+ with self.subTest(case=name):+ self.assertEqual(+ [[round(t, 6), round(g, 6)]+ for t, g in self.js["curves"][name]],+ se.bed_gain_points(edit),+ f"{name}: the browser and the render disagree about the bed")++ def test_they_agree_at_every_second_and_not_only_at_the_knots(self):+ for name, edit in TABLE.items():+ want = [se.bed_gain_at(edit, t) for t in TABLE_PROBES]+ got = [round(v, 6) for v in self.js["at"][name]]+ with self.subTest(case=name):+ for t, a, b in zip(TABLE_PROBES, got, want):+ self.assertAlmostEqual(+ a, b, places=5,+ msg=f"{name} @ {t}s: preview {a} vs render {b}")++ def test_they_agree_about_when_the_duck_stands_down(self):+ for name, edit in TABLE.items():+ with self.subTest(case=name):+ self.assertEqual(self.js["suppressed"][name],+ se.bed_duck_suppressed(edit))++ def test_THE_FFMPEG_EXPRESSION_IS_THE_CURVE_THE_BROWSER_DREW(self):+ """The other half of the equality, and the one the ear hears.++ Not "the model agrees with the model" but "the string handed to ffmpeg,+ evaluated, is the number the browser drew" — which is what makes this a+ measurement of the render rather than a re-derivation of it.+ """+ ev = TheRenderAppliesExactlyWhatTheDocumentSays()+ for name, edit in TABLE.items():+ expr = ev._volume_expr(edit)+ curve = self.js["curves"][name]+ if not expr:+ # NEUTRAL IS ABSENT: no filter is the honest graph for a bed+ # nobody moved, and both sides have to say so together.+ self.assertEqual(curve, [], name)+ self.assertEqual(se.bed_gain_points(edit), [], name)+ continue+ self.assertTrue(curve, f"{name}: the render filters, the browser "+ f"draws unity — that is the defect")+ delay = se.music_window(edit["audio"])["delay"]+ n = se.bed_length(edit["audio"], se.edit_duration(edit))+ with self.subTest(case=name):+ for t, g in [(t, g) for t, g in curve if t <= n]:+ self.assertAlmostEqual(+ ev._eval(expr, t + delay), g, places=5,+ msg=f"{name} @ {t}s: ffmpeg plays "+ f"{ev._eval(expr, t + delay)}, the browser drew {g}")+++class TheBedWithNoLengthPlaysUNDERTheFilm(unittest.TestCase):+ """The ruling, stated as an assertion rather than as a comment.++ A bed whose document says nothing about how long the track is used to+ render at UNITY under the dialogue — 19.6 dB above what the preview drew —+ because a zero-length bed produced an empty curve and an empty curve means+ no filter. The film is the honest clock for a bed of unknown length: the+ renderer trims the mix to the film anyway.+ """++ @staticmethod+ def _doc(**audio):+ return _t(_SPEAKING, _under(**audio))++ def test_the_render_no_longer_answers_an_unknown_length_with_silence(self):+ edit = self._doc()+ self.assertEqual(se.edit_duration(edit), 6.0)+ self.assertEqual(se.bed_length(edit["audio"], 6.0), 6.0)+ # The measured curve, and it is the one the validator read off the+ # browser: the fader, then the duck's 11.4 dB, held to the last frame.+ self.assertEqual(se.bed_gain_points(edit),+ [[0.0, 0.35], [0.005, 0.09415], [6.0, 0.09415]])++ def test_the_gain_under_a_line_is_the_ducked_one_and_not_full_level(self):+ edit = self._doc()+ self.assertAlmostEqual(se.bed_gain_at(edit, 3.0),+ 0.35 * se.MIX_DUCK_GAIN, places=5)+ # THE SIZE OF THE DEFECT. What the render used to play here was UNITY+ # — the empty curve, which is no filter at all — against the fader+ # times the duck the document asks for. On the rig that found this the+ # 8 kHz bed came out at -30.2 dB where the preview promised -49.8, and+ # the model's own gap is the same order: about 20 dB of soundtrack+ # sitting on top of the dialogue with nothing on screen saying so.+ gap = 20 * math.log10(1.0 / se.bed_gain_at(edit, 3.0))+ self.assertGreater(gap, 19.0)+ self.assertLess(gap, 21.0)++ def test_the_fallback_is_what_is_LEFT_of_the_film_not_its_whole_length(self):+ # A bed that comes in two seconds late is heard for four seconds, and+ # its envelope's clock is those four — otherwise a fade-out dragged+ # onto the corner would land two seconds past the last frame.+ edit = self._doc(offset=-2.0)+ self.assertEqual(se.music_window(edit["audio"])["film_start"], 2.0)+ self.assertEqual(se.bed_length(edit["audio"], 6.0), 4.0)++ def test_a_stated_length_still_wins_over_the_film(self):+ # The film is a FALLBACK, not an override: a document that knows how+ # long its track is renders exactly as it did before this existed.+ edit = self._doc(duration=45.0)+ self.assertEqual(se.bed_length(edit["audio"], 6.0), 45.0)++ def test_a_bed_on_an_empty_film_is_still_nothing(self):+ # No clips, no stated length: there is no clock at all, and inventing+ # one would be worse than the silence.+ edit = _t([], _under())+ self.assertEqual(se.bed_length(edit["audio"], 0.0), 0.0)+ self.assertEqual(se.bed_gain_points(edit), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_generation_profile_override.py b/test_generation_profile_override.pyindex 63e2617..67cf0db 100644--- a/test_generation_profile_override.py+++ b/test_generation_profile_override.py@@ -65,3 +65,28 @@ class GenerationProfileClamp(unittest.TestCase):if __name__ == "__main__":unittest.main()+++class OneCacheHoweverLaunched(unittest.TestCase):+ """The panel defaults HF_HOME to its own cache when the launcher didn't.++ Launched from a bare shell, every mflux/hf subprocess re-downloaded weights+ into ~/.cache/huggingface instead of seeing <install>/cache/HF_HOME — a+ forked cache that twice nearly filled the system volume in one week (the+ second time to 177 MB free, mid-render, with a 20 GB duplicate of+ Qwen-Edit). setdefault, not assignment: an explicit HF_HOME still wins.+ """++ def test_the_default_is_set_before_any_subprocess_can_spawn(self):+ import re+ from pathlib import Path+ src = Path(__file__).with_name("mlx_ltx_panel.py").read_text()+ i = src.index('os.environ.setdefault("HF_HOME"')+ # It must run at import time in the constants block, not inside some+ # handler that a render path may or may not reach.+ self.assertLess(i, src.index("QUEUE_FILE = "))+ # And it must be a setdefault — an assignment would stomp a+ # self-hoster's explicit cache location.+ window = src[i - 400:i]+ self.assertIn("setdefault", src[i:i + 60])+ self.assertNotIn('os.environ["HF_HOME"] =', src)diff --git a/test_geometry_grid.py b/test_geometry_grid.pyindex a8848c8..d79d8b7 100644--- a/test_geometry_grid.py+++ b/test_geometry_grid.py@@ -65,5 +65,69 @@ class TestLtxGeometryGrid(unittest.TestCase):(tier["width"], tier["height"], tier["frames"]))++class ControlsHideWithTheirParents(unittest.TestCase):+ """Reported on Pinokio (fuschichou): the Remix tool row stayed on screen+ on every non-Video surface. #remixSubGroup is a SIBLING of the mode bar,+ not a child — it sits outside #genForm — so hiding #modeGroup left the row+ behind as a stray control on Audio, Train, Storyboard, Editor, Characters+ and Studio."""++ SURFACES = ("train", "audio", "storyboard", "editor", "characters",+ "studio")++ @classmethod+ def setUpClass(cls):+ cls.src = (Path(__file__).resolve().parent / "mlx_ltx_panel.py").read_text()++ def test_the_remix_row_hides_wherever_the_mode_bar_hides(self):+ for wf in self.SURFACES:+ with self.subTest(workflow=wf):+ self.assertIn('body[data-workflow="%s"] #modeGroup,' % wf, self.src)+ self.assertIn('body[data-workflow="%s"] #remixSubGroup,' % wf,+ self.src)++ def test_neither_id_is_ever_listed_without_the_other(self):+ # The rule that keeps the seventh surface from repeating it.+ mode = self.src.count('] #modeGroup,')+ remix = self.src.count('] #remixSubGroup,')+ self.assertEqual(mode, remix)+ self.assertEqual(remix, len(self.SURFACES))+++class TheA2VWarningFollowsTheReports(unittest.TestCase):+ """Issue #46. The four reported datapoints cannot be separated by any+ frames x area constant — 832x480x721 = 287.9 Mpx holds together while+ 1024x576x481 = 283.7 Mpx falls apart, a SMALLER product failing. They+ separate cleanly on PER-FRAME AREA, so the canvas is the lever."""++ @classmethod+ def setUpClass(cls):+ cls.src = (Path(__file__).resolve().parent / "mlx_ltx_panel.py").read_text()++ def test_the_refuted_budget_is_gone(self):+ self.assertNotIn("A2V_PIXEL_BUDGET", self.src)++ def test_the_knee_sits_between_the_clean_and_the_failing_reports(self):+ self.assertIn("const A2V_AREA_KNEE = 0.45e6;", self.src)+ self.assertLess(832 * 480 / 1e6, 0.45) # highest clean: 0.399+ self.assertLess(0.45, 1024 * 576 / 1e6) # lowest failing: 0.590++ def test_a_clean_canvas_is_never_warned_about_in_range(self):+ fn = self.src[self.src.index("function audioStudioDurationChanged"):]+ fn = fn[:fn.index("async function audioStudioEnhancePrompt")]+ self.assertIn("area > A2V_AREA_KNEE && frames > A2V_KNEE_FRAMES", fn)+ # 640x480 at the full 20 s is the render the old rule shouted at.+ self.assertLess(640 * 480, 0.45e6)++ def test_the_copy_names_the_canvas_and_keeps_its_provenance(self):+ fn = self.src[self.src.index("function audioStudioDurationChanged"):]+ fn = fn[:fn.index("async function audioStudioEnhancePrompt")]+ self.assertIn("is the <b>canvas</b>, not the length", fn)+ self.assertIn("field reports, not a limit measured here", fn)+ self.assertIn("issues/46", fn)+ self.assertIn("A2V_KNEE_FRAMES", fn)++if __name__ == "__main__":unittest.main(verbosity=2)diff --git a/test_lora_compat.py b/test_lora_compat.pyindex 3792ea5..4f07e3b 100644--- a/test_lora_compat.py+++ b/test_lora_compat.py@@ -8,9 +8,14 @@ import unittestfrom pathlib import Pathfrom unittest.mock import patch+import lora_compatfrom lora_compat import (+ WEAK_DELTA_RMS,LoraCompatibilityError,inspect_lora_compatibility,+ measure_adapter_effect,+ read_tensor_header,+ validate_adapter_effects,validate_runtime_application,validate_lora_stack,)@@ -201,5 +206,282 @@ class LoraCompatibilityTests(unittest.TestCase):self.assertIn("bad_v2.safetensors", refusal or "")+def _write_adapter(path: Path, modules: dict[str, tuple["np.ndarray", "np.ndarray"]]) -> None:+ """Write a real safetensors file (header + payload) for one adapter."""+ import numpy as np++ header: dict[str, dict] = {}+ blobs: list[bytes] = []+ offset = 0+ for name, (a, b) in modules.items():+ for suffix, array in ((".lora_A.weight", a), (".lora_B.weight", b)):+ raw = np.ascontiguousarray(array, dtype=np.float32).tobytes()+ header[f"{name}{suffix}"] = {+ "dtype": "F32",+ "shape": list(array.shape),+ "data_offsets": [offset, offset + len(raw)],+ }+ blobs.append(raw)+ offset += len(raw)+ encoded = json.dumps(header, separators=(",", ":")).encode("utf-8")+ path.write_bytes(struct.pack("<Q", len(encoded)) + encoded + b"".join(blobs))+++class AdapterEffectTests(unittest.TestCase):+ """A green key tally is not evidence that an adapter can do anything (#62)."""++ def setUp(self) -> None:+ import numpy as np++ self.np = np+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.rng = np.random.default_rng(11)++ def tearDown(self) -> None:+ self.tmp.cleanup()++ def _adapter(self, name: str, b_scale: float, modules: int = 3) -> Path:+ np = self.np+ payload = {}+ for index in range(modules):+ a = self.rng.normal(0, 1 / 64, size=(8, 4096)).astype(np.float32)+ b = (self.rng.normal(0, 1, size=(4096, 8)) * b_scale).astype(np.float32)+ payload[f"diffusion_model.transformer_blocks.{index}.attn1.to_q"] = (a, b)+ path = self.root / name+ _write_adapter(path, payload)+ return path++ def test_frobenius_norm_matches_the_explicit_product(self) -> None:+ """The trace identity must agree with actually forming ``B @ A``."""+ np = self.np+ path = self._adapter("exact.safetensors", b_scale=1e-2, modules=1)+ effect = measure_adapter_effect(path)+ header = read_tensor_header(path)+ module = "diffusion_model.transformer_blocks.0.attn1.to_q"+ with path.open("rb") as fh:+ size = struct.unpack("<Q", fh.read(8))[0]+ base = 8 + size++ def load(key: str):+ info = header[key]+ start, end = info["data_offsets"]+ fh.seek(base + start)+ return np.frombuffer(fh.read(end - start), dtype="<f4").reshape(+ info["shape"]+ )++ delta = load(module + ".lora_B.weight") @ load(module + ".lora_A.weight")+ expected = float(np.linalg.norm(delta)) / (4096 * 4096) ** 0.5+ self.assertAlmostEqual(effect.median_rms, expected, places=7)++ def test_untrained_adapter_is_inert_and_refused(self) -> None:+ path = self._adapter("never_trained.safetensors", b_scale=0.0)+ effect = measure_adapter_effect(path)+ self.assertTrue(effect.inert)+ self.assertEqual(effect.zero_modules, effect.modules)+ with self.assertRaisesRegex(+ LoraCompatibilityError, r"never_trained\.safetensors.*no weight delta"+ ):+ validate_adapter_effects([(str(path), 1.0)])++ def test_weak_adapter_is_reported_but_never_refused(self) -> None:+ """Below the floor is a warning: a light touch is the owner's call."""+ path = self._adapter("barely_trained.safetensors", b_scale=1e-6)+ lines: list[str] = []+ effects = validate_adapter_effects([(str(path), 1.0)], reporter=lines.append)+ self.assertEqual(len(effects), 1)+ self.assertTrue(effects[0].weak)+ self.assertFalse(effects[0].inert)+ self.assertEqual(len(lines), 2)+ self.assertIn("delta_rms median=", lines[0])+ self.assertIn("WARNING", lines[1])++ def test_identity_grade_adapter_passes_clean(self) -> None:+ """Sized to the shipped characters: median rms ~1.4e-03."""+ path = self._adapter("carries_identity.safetensors", b_scale=1.2e-2)+ lines: list[str] = []+ effect = validate_adapter_effects(+ [(str(path), 1.0)], reporter=lines.append+ )[0]+ self.assertFalse(effect.weak)+ self.assertFalse(effect.inert)+ self.assertGreater(effect.median_rms, WEAK_DELTA_RMS)+ self.assertEqual(len(lines), 1)+ self.assertIn("3/3 modules carry a delta", lines[0])++ def test_disabled_adapter_is_not_measured(self) -> None:+ path = self._adapter("switched_off.safetensors", b_scale=0.0)+ lines: list[str] = []+ self.assertEqual(+ validate_adapter_effects([(str(path), 0.0)], reporter=lines.append), []+ )+ self.assertEqual(lines, [])++ def test_training_reports_the_number_and_shouts_when_it_is_low(self) -> None:+ """The trainer's own verdict — the line #62 never got."""+ import io+ import contextlib++ from lora_lab import train_character++ path = self._adapter("weak_v2.safetensors", b_scale=1e-6)+ stream = io.StringIO()+ with patch.object(train_character, "_REAL_STDOUT", stream):+ payload = train_character.report_adapter_strength(path)+ events = [json.loads(line) for line in stream.getvalue().splitlines()]+ kinds = [event["event"] for event in events]+ self.assertEqual(payload["verdict"], "weak")+ self.assertIn("adapter_strength", kinds)+ self.assertIn("warning", kinds)+ warning = next(e for e in events if e["event"] == "warning")+ self.assertEqual(warning["stage"], "verify")+ self.assertIn("weak_v2.safetensors", warning["message"])++ def test_training_verdict_is_ok_for_an_identity_grade_adapter(self) -> None:+ import io++ from lora_lab import train_character++ path = self._adapter("strong_v2.safetensors", b_scale=1.2e-2)+ stream = io.StringIO()+ with patch.object(train_character, "_REAL_STDOUT", stream):+ payload = train_character.report_adapter_strength(path)+ self.assertEqual(payload["verdict"], "ok")+ self.assertEqual(payload["carrying_modules"], payload["modules"])+ self.assertNotIn("warning", stream.getvalue())+++class AdapterCliTests(unittest.TestCase):+ """`python3 lora_compat.py <file>` — the answer without a render.++ #62 cost its reporter days of proving a negative about a file already on+ his disk, and the owner's only way to settle it was to ask for a 500 MB+ upload. The measurement takes about a second, so it has to be reachable+ from a shell on the machine that holds the file.+ """++ def setUp(self) -> None:+ try:+ import numpy+ except ImportError: # pragma: no cover+ self.skipTest("numpy unavailable")+ self.np = numpy+ self.rng = numpy.random.default_rng(11)+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)++ def tearDown(self) -> None:+ self.tmp.cleanup()++ def _adapter(self, name: str, b_scale: float) -> Path:+ np = self.np+ a = self.rng.normal(0, 1 / 64, size=(8, 4096)).astype(np.float32)+ b = (self.rng.normal(0, 1, size=(4096, 8)) * b_scale).astype(np.float32)+ path = self.root / name+ _write_adapter(+ path, {"diffusion_model.transformer_blocks.0.attn1.to_q": (a, b)}+ )+ return path++ def _run(self, *argv: str) -> tuple[int, str]:+ import io++ stream = io.StringIO()+ with patch.object(lora_compat.sys, "stdout", stream):+ code = lora_compat.main(list(argv))+ return code, stream.getvalue()++ def test_identity_grade_adapter_reports_ok_and_exits_zero(self) -> None:+ path = self._adapter("carries_identity.safetensors", b_scale=1.2e-2)+ code, out = self._run(str(path))+ self.assertEqual(code, 0)+ self.assertIn("OK", out)+ self.assertIn("delta_rms median=", out)++ def test_weak_is_reported_and_still_exits_zero(self) -> None:+ """A light touch is the owner's call, so WEAK must not fail the run."""+ path = self._adapter("barely_trained.safetensors", b_scale=1e-6)+ code, out = self._run(str(path))+ self.assertEqual(code, 0)+ self.assertIn("WEAK", out)++ def test_inert_adapter_exits_one(self) -> None:+ path = self._adapter("never_trained.safetensors", b_scale=0.0)+ code, out = self._run(str(path))+ self.assertEqual(code, 1)+ self.assertIn("INERT", out)++ def test_worst_status_across_several_files_decides_the_exit(self) -> None:+ good = self._adapter("good.safetensors", b_scale=1.2e-2)+ dead = self._adapter("dead.safetensors", b_scale=0.0)+ code, out = self._run(str(good), str(dead))+ self.assertEqual(code, 1)+ self.assertIn("good.safetensors", out)+ self.assertIn("dead.safetensors", out)++ def test_a_path_that_does_not_exist_is_the_callers_mistake(self) -> None:+ code, out = self._run(str(self.root / "absent.safetensors"))+ self.assertEqual(code, 2)+ self.assertIn("NOT FOUND", out)++ def test_no_arguments_prints_usage_and_exits_two(self) -> None:+ code, out = self._run()+ self.assertEqual(code, 2)+ self.assertIn("usage:", out)++ def test_help_is_not_an_error(self) -> None:+ code, out = self._run("--help")+ self.assertEqual(code, 0)+ self.assertIn("usage:", out)++ def test_describe_adapter_returns_a_status_not_a_string_to_sniff(self) -> None:+ path = self._adapter("strong.safetensors", b_scale=1.2e-2)+ status, line = lora_compat.describe_adapter(path)+ self.assertEqual(status, "ok")+ self.assertIn("strong.safetensors", line)++++class AGreenTallyIsNotProof(unittest.TestCase):+ """A LoRA can train to completion, write a valid safetensors, load without+ a warning and change NOTHING — the deltas are too small to move the model.+ Every gate said "done"; only the render said otherwise, hours later."""++ def test_the_verdict_rides_out_of_the_sidecar(self):+ import mlx_ltx_panel as panel+ self.assertEqual(panel._adapter_verdict(+ {"adapter_strength": {"verdict": "weak"}}), "weak")+ self.assertEqual(panel._adapter_verdict(+ {"adapter_strength": {"verdict": "ok"}}), "ok")++ def test_a_run_that_never_measured_is_unknown_and_not_weak(self):+ # Silence is not weakness: a chip on every LoRA trained before the+ # trainer measured would be noise nobody could act on.+ import mlx_ltx_panel as panel+ for meta in ({}, {"adapter_strength": None},+ {"adapter_strength": {}}, {"adapter_strength": "yes"}):+ self.assertEqual(panel._adapter_verdict(meta), "unknown")++ def test_the_two_ungraded_presets_say_so_on_the_pill(self):+ # The rank-32 recipe is the one measured on faces. Saying "fast" and+ # letting the user infer "as good, sooner" is the pill doing the lying.+ import mlx_ltx_panel as panel+ self.assertIn("ungraded", panel.TRAIN_PRESETS["quick"]["subtitle"])+ self.assertIn("ungraded", panel.TRAIN_PRESETS["medium"]["subtitle"])+ self.assertNotIn("ungraded", panel.TRAIN_PRESETS["high"]["subtitle"])+ self.assertIn("validated", panel.TRAIN_PRESETS["high"]["subtitle"])++ def test_the_trainer_event_is_read_and_a_weak_run_is_not_a_plain_done(self):+ src = (Path(__file__).resolve().parent / "mlx_ltx_panel.py").read_text()+ self.assertIn('elif evt == "adapter_strength":', src)+ self.assertIn("[train] adapter strength: delta_rms", src)+ self.assertIn("delta_rms_median", src)+ self.assertIn("carrying_modules", src)+ # ...and the job carries the warning rather than reporting success.+ self.assertIn('job["warning"]', src)+ self.assertIn('if train_verdict not in ("ok", "unknown"):', src)++if __name__ == "__main__":unittest.main()diff --git a/test_prompt_enhance_endpoint.py b/test_prompt_enhance_endpoint.pyindex 7b624b1..649f3d6 100644--- a/test_prompt_enhance_endpoint.py+++ b/test_prompt_enhance_endpoint.py@@ -99,7 +99,16 @@ class PromptEnhanceEndpointTest(unittest.TestCase):def test_endpoint_uses_gemma3_and_always_returns_json(self) -> None:# Refuse to interfere with any process already using the requested test# port. Cleanup below only signals the exact Popen PID saved here.+ #+ # SO_REUSEADDR matters here and its absence made this suite flaky: the+ # probe binds PORT, closes it, and the socket sits in TIME_WAIT for+ # ~30 s. Running the suite twice inside that window failed with+ # "Address already in use" and named a port that nothing held —+ # blaming a phantom process for this test's own previous run. The flag+ # permits exactly that case and still refuses a port a LIVE listener+ # owns, which is the check we actually want.probe = socket.socket()+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)try:probe.bind(("127.0.0.1", PORT))except PermissionError as exc:diff --git a/test_stale_process.py b/test_stale_process.pyindex 0de0467..ce84390 100644--- a/test_stale_process.py+++ b/test_stale_process.py@@ -14,20 +14,59 @@ the old code, conclude the update did nothing. Seven hours on a 4.0.9 UI withThe fix is a separate `_BOOT_HEAD_SHA` captured once at process start. Thesetests pin the behaviour AND the trap — `test_polled_state_does_not_defeat_it`is the one that would have caught the original bug.++2026-08-20 — the same bug had survived twice more, in the two places that+mattered most:++ * `_capture_boot_head()` was called from `version_check_loop` ONLY, a thread+ `__main__` starts `if VERSION_CHECK_ENABLED`. With the check disabled the+ boot SHA stayed None for the life of the process, and `disk != boot` is+ False when boot is None. The detector was dead again, for exactly the+ users who had opted out of update nagging.+ * `stale_process` was a BOOLEAN bolted onto a stamp that still read the+ working tree. `local_short` / `local_version` / `local_branch` /+ `local_commit_date` are refreshed from disk by every poll, so the header+ advertised the new build the moment a pull landed — while the old code+ kept serving — and the restart tooltip printed the disk label on BOTH+ sides of "X is on disk but this process loaded Y".++`BuildStampNamesTheRunningCode` is that half of the story."""+import tempfileimport unittest+from pathlib import Pathfrom unittest import mockimport mlx_ltx_panel as panel+_BOOT_FIELDS = ("_BOOT_HEAD_SHA", "_BOOT_VERSION", "_BOOT_BRANCH",+ "_BOOT_COMMIT_DATE")+++def _save_boot():+ return {f: getattr(panel, f) for f in _BOOT_FIELDS}+++def _restore_boot(saved):+ for f, v in saved.items():+ setattr(panel, f, v)+++def _set_boot(sha, version=None, branch="dev", commit_date="2026-01-01"):+ panel._BOOT_HEAD_SHA = sha+ panel._BOOT_VERSION = version+ panel._BOOT_BRANCH = branch+ panel._BOOT_COMMIT_DATE = commit_date++class StaleProcessDetection(unittest.TestCase):def setUp(self):- self._saved = panel._BOOT_HEAD_SHA+ self._saved = _save_boot()def tearDown(self):- panel._BOOT_HEAD_SHA = self._saved+ _restore_boot(self._saved)def test_capture_is_idempotent(self):"""A second call must not re-point the snapshot at whatever is on disk now."""@@ -39,14 +78,14 @@ class StaleProcessDetection(unittest.TestCase):self.assertEqual(panel._BOOT_HEAD_SHA, "aaaa111")def test_stale_when_disk_moved_under_the_process(self):- panel._BOOT_HEAD_SHA = "aaaa111"+ _set_boot("aaaa111")with mock.patch.object(panel, "_git_capture", return_value="bbbb222"):snap = panel.get_version_state()self.assertTrue(snap["stale_process"])self.assertEqual(snap.get("disk_short"), "bbbb222"[:7])def test_not_stale_when_disk_matches_boot(self):- panel._BOOT_HEAD_SHA = "aaaa111"+ _set_boot("aaaa111")with mock.patch.object(panel, "_git_capture", return_value="aaaa111"):snap = panel.get_version_state()self.assertFalse(snap["stale_process"])@@ -58,7 +97,7 @@ class StaleProcessDetection(unittest.TestCase):disk on every remote check, so anything comparing against it reports"not stale" no matter how old the running process is."""- panel._BOOT_HEAD_SHA = "aaaa111"+ _set_boot("aaaa111")with panel._VERSION_LOCK:panel._VERSION_STATE["local_sha"] = "bbbb222" # what a poll would writewith mock.patch.object(panel, "_git_capture", return_value="bbbb222"):@@ -68,11 +107,215 @@ class StaleProcessDetection(unittest.TestCase):def test_missing_git_never_claims_staleness(self):"""No git binary must read as 'fine', not as a permanent restart nag."""- panel._BOOT_HEAD_SHA = "aaaa111"+ _set_boot("aaaa111")with mock.patch.object(panel, "_git_capture", return_value=None):snap = panel.get_version_state()self.assertFalse(snap["stale_process"])++class BuildStampNamesTheRunningCode(unittest.TestCase):+ """The header stamp is how the owner tells which build he is on. It has to+ name the code that is ANSWERING him, not the code sitting in the working+ tree — those differ for exactly as long as a panel goes un-restarted after+ an update, which is the window the whole trust surface exists to cover."""++ def setUp(self):+ self._saved = _save_boot()++ def tearDown(self):+ _restore_boot(self._saved)++ def test_the_boot_snapshot_exists_without_the_poll_thread_ever_running(self):+ """THE regression, second form.++ Importing the module is the only thing that has happened in this+ process — `version_check_loop` has never been started, which is+ precisely the state of an install running with+ PHOSPHENE_DISABLE_VERSION_CHECK=1. The boot SHA must already be+ captured, because `disk != boot` is False when boot is None and the+ stale detector silently dies.+ """+ if not panel._git_capture(["rev-parse", "HEAD"]):+ self.skipTest("not a git checkout — nothing to snapshot")+ self.assertIsNotNone(+ panel._BOOT_HEAD_SHA,+ "boot SHA must be captured at import, not by the version-check "+ "thread — that thread does not start when the update check is off")+ self.assertIsNotNone(panel._BOOT_BRANCH)+ self.assertIsNotNone(panel._BOOT_COMMIT_DATE)++ def test_the_stamp_is_the_boot_build_not_the_tree(self):+ """THE regression, first form. A poll writes disk into _VERSION_STATE+ every 30 minutes; the stamp must not follow it."""+ _set_boot("0ld0ld0" + "0" * 33, version="4.5.0",+ branch="dev", commit_date="2026-08-18")+ with panel._VERSION_LOCK: # what a poll leaves behind+ panel._VERSION_STATE["local_sha"] = "n3wn3wn" + "0" * 33+ panel._VERSION_STATE["local_short"] = "n3wn3wn"+ panel._VERSION_STATE["local_version"] = "4.6.0"+ panel._VERSION_STATE["local_commit_date"] = "2026-08-20"+ with mock.patch.object(panel, "_git_capture",+ return_value="n3wn3wn" + "0" * 33):+ with mock.patch.object(panel, "_read_local_version",+ return_value="4.6.0"):+ snap = panel.get_version_state()+ self.assertEqual(snap["local_short"], "0ld0ld0",+ "the stamp followed the working tree instead of the "+ "code this process loaded")+ self.assertEqual(snap["local_version"], "4.5.0")+ self.assertEqual(snap["local_commit_date"], "2026-08-18")+ self.assertEqual(snap["disk_short"], "n3wn3wn")+ self.assertEqual(snap["disk_version"], "4.6.0")+ self.assertTrue(snap["stale_process"])++ def test_both_builds_are_nameable_when_the_version_label_did_not_move(self):+ """Most fixes land without a VERSION bump, so the two labels read the+ same number. The tooltip that told the owner to restart said+ 'Phosphene 4.6.0 is on disk, but this panel process loaded 4.6.0' —+ an alarm that names nothing. The SHAs have to survive to the payload."""+ _set_boot("0ld0ld0" + "0" * 33, version="4.6.0")+ with mock.patch.object(panel, "_git_capture",+ return_value="n3wn3wn" + "0" * 33):+ with mock.patch.object(panel, "_read_local_version",+ return_value="4.6.0"):+ snap = panel.get_version_state()+ self.assertEqual(snap["local_version"], snap["disk_version"])+ self.assertNotEqual(snap["local_short"], snap["disk_short"])++ def test_disk_fields_are_always_present(self):+ """Not 'only when stale'. A consumer that must check stale_process+ before it may trust disk_short is one that will forget to."""+ _set_boot("aaaa111" + "0" * 33, version="4.6.0")+ with mock.patch.object(panel, "_git_capture",+ return_value="aaaa111" + "0" * 33):+ snap = panel.get_version_state()+ self.assertFalse(snap["stale_process"])+ self.assertEqual(snap["disk_short"], "aaaa111")+ self.assertIn("disk_version", snap)++ def test_a_version_file_edited_under_the_process_does_not_move_the_stamp(self):+ """The VERSION file is read fresh on every poll too."""+ _set_boot("aaaa111" + "0" * 33, version="4.5.0")+ with mock.patch.object(panel, "_git_capture",+ return_value="aaaa111" + "0" * 33):+ with mock.patch.object(panel, "_read_local_version",+ return_value="9.9.9"):+ snap = panel.get_version_state()+ self.assertEqual(snap["local_version"], "4.5.0")+ self.assertEqual(snap["disk_version"], "9.9.9")++ def test_capture_freezes_the_whole_snapshot_together(self):+ """Half a snapshot is worse than none — a fresh branch name beside a+ boot SHA reads as authoritative and is not."""+ saved = _save_boot()+ try:+ panel._BOOT_HEAD_SHA = None+ panel._BOOT_VERSION = None+ panel._BOOT_BRANCH = None+ panel._BOOT_COMMIT_DATE = None+ with mock.patch.object(panel, "_git_capture", return_value="first"):+ with mock.patch.object(panel, "_read_local_version",+ return_value="1.0.0"):+ panel._capture_boot_head()+ with mock.patch.object(panel, "_git_capture", return_value="second"):+ with mock.patch.object(panel, "_read_local_version",+ return_value="2.0.0"):+ panel._capture_boot_head()+ self.assertEqual(panel._BOOT_HEAD_SHA, "first")+ self.assertEqual(panel._BOOT_VERSION, "1.0.0")+ self.assertEqual(panel._BOOT_BRANCH, "first")+ finally:+ _restore_boot(saved)++ def test_a_zip_install_still_freezes_its_version(self):+ """No git, so no SHA — but VERSION ships in the zip and is still a+ property of the code that got loaded."""+ saved = _save_boot()+ try:+ panel._BOOT_HEAD_SHA = None+ panel._BOOT_VERSION = None+ with mock.patch.object(panel, "_git_capture", return_value=None):+ with mock.patch.object(panel, "_read_local_version",+ return_value="4.6.0"):+ panel._capture_boot_head()+ self.assertIsNone(panel._BOOT_HEAD_SHA)+ self.assertEqual(panel._BOOT_VERSION, "4.6.0")+ finally:+ _restore_boot(saved)+++class ThePageAnswersWhichBuildItIs(unittest.TestCase):+ """`c5dc04c` is a real commit from 2026-05-21 that shipped inside the+ served page, in a comment, formatted exactly like the header stamp it+ described: "you're on 3.0.0 · dev · c5dc04c (2026-05-21)". The running+ build appeared nowhere in the page at all. So the page answered "which+ build is this?" with a decoy, confidently, in the right format — the+ 2026-08-19 report. The page carries the true answer now."""++ def test_the_page_names_the_running_build(self):+ stamp = panel.boot_build_stamp()+ page = panel.page()+ self.assertIn('<meta name="phosphene-build"', page)+ if stamp["short"]:+ self.assertIn(stamp["short"], page,+ "the running SHA must appear in the served page")+ if stamp["version"]:+ self.assertIn(stamp["version"], panel.build_stamp_text())++ def test_the_version_pill_ships_no_sha_literal(self):+ """The decoy lived in this function's comments. Nothing in the code+ that RENDERS the stamp may carry a SHA of its own."""+ import re+ page = panel.page()+ start = page.index("function renderVersionPill(")+ end = page.index("\nfunction ", start + 1)+ body = page[start:end]+ found = re.findall(r"(?<![0-9a-zA-Z_#/])[0-9a-f]{7}(?![0-9a-zA-Z_])",+ body)+ self.assertEqual(found, [],+ f"SHA-shaped literals in renderVersionPill: {found}. "+ "A comment there is served to the browser and reads "+ "as the build stamp to anyone searching the page.")++++class ATestPanelCannotImpersonateTheRealOne(unittest.TestCase):+ """A verifying agent runs a second copy against a throwaway state dir so+ it can cut, save and restore without touching the owner's films. An+ abandoned tab of THAT is indistinguishable from his own panel showing a+ stale build — and it cost an evening: he read a test instance as his+ install and reported the app had gone backwards."""++ def test_the_install_serving_its_own_films_is_native(self):+ import mlx_ltx_panel as panel+ with mock.patch.object(panel, "STATE_DIR", panel.ROOT / "state"):+ self.assertTrue(panel._state_dir_is_native())++ def test_a_foreign_state_dir_is_not(self):+ import mlx_ltx_panel as panel+ with tempfile.TemporaryDirectory() as tmp:+ with mock.patch.object(panel, "STATE_DIR", Path(tmp)):+ self.assertFalse(panel._state_dir_is_native())++ def test_the_page_shouts_it_in_the_two_places_a_tab_shows(self):+ # The badge for a tab you are looking at, the TITLE for one you are+ # not — a background tab is a title and a favicon and nothing else.+ import mlx_ltx_panel as panel+ with tempfile.TemporaryDirectory() as tmp:+ with mock.patch.object(panel, "STATE_DIR", Path(tmp)):+ page = panel.page()+ self.assertIn("<title>Phosphene TEST</title>", page)+ self.assertIn("TEST PANEL", page)+ self.assertIn("test-badge", page)++ def test_the_real_install_carries_neither(self):+ import mlx_ltx_panel as panel+ with mock.patch.object(panel, "STATE_DIR", panel.ROOT / "state"):+ page = panel.page()+ self.assertIn("<title>Phosphene</title>", page)+ self.assertNotIn("TEST PANEL", page)++if __name__ == "__main__":unittest.main()diff --git a/test_storyboard.py b/test_storyboard.pyindex dc29707..1a98fd3 100644--- a/test_storyboard.py+++ b/test_storyboard.py@@ -367,6 +367,32 @@ class ValidatorSplit(unittest.TestCase):yield "ref_missing", _board([_shot(1, refs=["/nope/desert.png"])]), {}yield "remix_no_ref", _board([_shot(1, mode="remix")]), {}yield "over_cap", _board([_shot(1)]), {"max_dim": 512}+ loc = sb.new_location("carwash", "The car wash", "a soapy sedan",+ views=[sb.new_view("wide", "Establishing", "the sedan")])+ yield ("unknown_view",+ _board([dict(_shot(1), location_id="carwash", view="reverse")],+ locations=[loc]), {})+ yield ("view_dupe",+ _board([_shot(1)], locations=[sb.new_location(+ "carwash", "The car wash", "a soapy sedan",+ views=[sb.new_view("wide", "A", "the sedan"),+ sb.new_view("wide", "B", "the houses")])]), {})+ yield ("view_bad_id",+ _board([_shot(1)], locations=[sb.new_location(+ "carwash", "The car wash", "a soapy sedan",+ views=[{"id": "Not An Id!", "description": "x"}])]), {})+ yield ("view_empty",+ _board([_shot(1)], locations=[sb.new_location(+ "carwash", "The car wash", "a soapy sedan",+ views=[sb.new_view("wide", "A", " ")])]), {})+ yield ("view_long",+ _board([_shot(1)], locations=[sb.new_location(+ "carwash", "The car wash", "a soapy sedan",+ views=[sb.new_view("wide", "A", "x" * 601)])]), {})+ yield ("views_shape",+ _board([_shot(1)], locations=[dict(sb.new_location(+ "carwash", "The car wash", "a soapy sedan"), views="wide")]), {})+ yield "bad_eyeline", _board([dict(_shot(1), eyeline="frame-left")]), {}def test_detail_and_flat_agree_byte_for_byte(self):for name, board, kw in self._cases():@@ -385,16 +411,20 @@ class ValidatorSplit(unittest.TestCase):"refs_not_list": ["refs_not_list"], "ref_missing": ["ref_missing"],"remix_no_ref": ["remix_needs_ref"],"over_cap": ["over_cap", "over_cap"],+ "unknown_view": ["unknown_view"], "view_dupe": ["view_duplicate"],+ "view_bad_id": ["view_id"], "view_empty": ["view_empty"],+ "view_long": ["view_too_long"], "views_shape": ["views_shape"],+ "bad_eyeline": ["bad_eyeline"],}for name, board, kw in self._cases():codes = [e["code"] for e in sb.validate_storyboard_detail(board, **kw)]self.assertEqual(codes, want[name], f"{name}: {codes}")- def test_all_sixteen_codes_are_reachable(self):+ def test_every_code_is_reachable(self):seen = set()for _, board, kw in self._cases():seen |= {e["code"] for e in sb.validate_storyboard_detail(board, **kw)}- self.assertEqual(len(seen), 16, sorted(seen))+ self.assertEqual(len(seen), 23, sorted(seen))def test_a_non_dict_shot_does_not_raise(self):# It used to: `where` was computed from s.get() before the isinstance check.@@ -441,5 +471,542 @@ class Persistence(unittest.TestCase):self.assertEqual(got["schema"], 1) # never bumped for additive fields+class DialogueFitsTheShot(unittest.TestCase):+ """A line must fit its clock and must close.++ Owner, after the same truncation twice in one day: "when people talk,+ there is a structure to the talk... a beginning and an end. It's not just+ open-ended sentences that get cut." The budget constants are measured: a+ 7-word line in 4.04s delivered; a 20-word line in 7.04s was cut mid-phrase.+ """++ def test_the_line_that_actually_got_cut_is_caught(self):+ # Verbatim from the shot the owner watched truncate.+ p = ("She says slowly and low: 'Update the app. The new timeline "+ "editor is in. Cut your shots, move them around, put music "+ "under your voice.'")+ prob = sb.shot_pacing_problem(p, 7.04)+ self.assertIsNotNone(prob)+ self.assertIn("cut off", prob)++ def test_the_same_line_fits_when_the_shot_is_long_enough(self):+ # SLOW read: 23 words at 1.7 w/s needs ~14.5s — 13.04 was measured to+ # truncate, 15.04 fits.+ p = ("She says slowly and low: 'Update the app. There is a new "+ "timeline editor. Cut your shots. Move them around. Put music "+ "under your voice. That is it.'")+ self.assertIsNotNone(sb.shot_pacing_problem(p, 13.04))+ self.assertIsNone(sb.shot_pacing_problem(p, 15.04))++ def test_a_warm_read_is_budgeted_slower_than_a_bright_one(self):+ # The same 9 words truncate under-the-breath and deliver fine bright:+ # both halves observed on real renders the same day.+ line = "'Update the app. There is a timeline editor now.'"+ self.assertIsNotNone(sb.shot_pacing_problem(+ "She says quietly, almost under her breath: " + line, 5.04))+ self.assertIsNone(sb.shot_pacing_problem(+ "She says brightly and clearly: " + line, 5.04))++ def test_the_lines_that_delivered_fine_still_pass(self):+ for line, dur in [("'Ladies and gentlemen — version four point six.'", 4.04),+ ("'Is it any good?'", 4.04),+ ("'It is buggy. But it works.'", 4.04),+ ("'Ship it.'", 3.04)]:+ self.assertIsNone(sb.shot_pacing_problem("He says: " + line, dur), line)++ def test_a_line_that_trails_off_is_unfinished(self):+ p = "He says: 'And another thing about the update,'"+ prob = sb.shot_pacing_problem(p, 8.04)+ self.assertIsNotNone(prob)+ self.assertIn("never finishes", prob)++ def test_a_silent_shot_has_no_pacing_problem(self):+ self.assertIsNone(sb.shot_pacing_problem(+ "ariatrn scrubs the door with a foam-loaded sponge", 4.04))++ def test_contractions_do_not_end_the_count_early(self):+ # A quote flanked by letters is an apostrophe, not the end of the+ # line — without that rule "There's" stops the counter at word four+ # and every long line after a contraction sails through unfitted.+ spans = sb.spoken_spans("She says: 'There's a new editor and it does "+ "a great many things you will surely enjoy.'")+ self.assertEqual(len(spans), 1)+ self.assertGreater(len(spans[0].split()), 10)++ def test_speech_fit_frames_is_a_legal_frame_count(self):+ for words in (2, 7, 23, 40):+ for slow in (False, True):+ f = sb.speech_fit_frames(words, slow=slow)+ self.assertEqual((f - 1) % 24, 0, f)+ lead = "He says slowly: '" if slow else "He says: '"+ self.assertIsNone(sb.shot_pacing_problem(+ lead + " ".join(["word"] * (words - 1)) + " end.'",+ f / 24.0))++ def test_the_board_validator_blocks_an_overstuffed_shot(self):+ board = _board([dict(_shot(1),+ prompt="He says: 'twenty words of dialogue that "+ "can not possibly be spoken aloud inside "+ "four seconds of screen time at all.'",+ mode="text", character_id=None, trigger=None,+ duration_s=4.0)])+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertIn("dialogue_does_not_fit", codes)+++class TrainedVoiceActuallyLoads(unittest.TestCase):+ """`no_voice` gates the trained voice LoRA, and it was engine-blind.++ The gate read `_HAS_DIALOGUE`, which matches `<d>…</d>` and nothing else,+ under a comment calling itself "a derivation, not a heuristic". True of H3.+ False of LTX, where `_strip_h3_markup` has already turned the tag into+ 'single quotes' before the prompt exists — so the tag was never there,+ `no_voice` was always "on", and the voice LoRA was stripped from every LTX+ character shot with a line in it.++ Confirmed on a real sidecar: `no_voice: true` with a one-entry LoRA stack+ holding only the face. The owner reported it as the characters never using+ their own voices, more than once.+ """+ POLICY = {"quality": "balanced", "width": 1024, "height": 576, "frames": 121}++ def _job(self, prompt):+ return sb.shot_to_job(+ {"n": 1, "mode": "character", "character_id": "bizarrotrn",+ "trigger": "bizarrotrn", "prompt": prompt}, self.POLICY)++ def test_an_ltx_line_in_single_quotes_loads_the_voice(self):+ j = self._job("bizarrotrn announces in a showman's voice: "+ "'Ladies and gentlemen.'")+ self.assertEqual(j["no_voice"], "off")++ def test_an_h3_line_in_a_tag_still_loads_the_voice(self):+ j = self._job("A man says: <d>[English] They said this was impossible.</d>")+ self.assertEqual(j["no_voice"], "off")++ def test_a_silent_shot_still_leaves_the_voice_off(self):+ # The other half of the contract: a voice LoRA loaded onto a shot with+ # nothing to say is the babble this gate exists to prevent.+ j = self._job("ariatrn a woman scrubs the door with a foam-loaded sponge")+ self.assertEqual(j["no_voice"], "on")++ def test_an_empty_tag_is_not_a_line(self):+ self.assertEqual(self._job("A man stands there. <d></d>")["no_voice"], "on")++ def test_the_voice_gate_and_the_speech_law_use_the_SAME_detector(self):+ # If they ever disagree you get one of the two bugs: a mouth with+ # nothing to say, or a line delivered by a stranger's voice.+ for p in ("bizarrotrn says: 'Ship it.'",+ "A man says: <d>[English] Ship it.</d>",+ "ariatrn scrubs the door in silence"):+ speaks_law = sb.shot_speech_problem(p) is None and bool(+ sb._SPOKEN_WORDS_RE.search(p))+ speaks_gate = self._job(p)["no_voice"] == "off"+ self.assertEqual(speaks_law, speaks_gate, p)+++class Wardrobe(unittest.TestCase):+ """The same outfit in every shot, for the same reason as the same room.++ Four shots of one man came back in a navy suit, a navy suit, a period+ collar and a different period collar. "A man in a dark suit" is a different+ suit each time it is re-rolled.+ """+ CAST = [{"id": "bizarrotrn", "trigger": "bizarrotrn",+ "wardrobe": "a loud floral Hawaiian shirt with the collar open"}]++ def test_the_outfit_reaches_the_rendered_prompt(self):+ w = sb.board_wardrobe({"cast": self.CAST})+ got = sb.compose_shot_prompt(+ {"n": 1, "character_id": "bizarrotrn", "trigger": "bizarrotrn",+ "prompt": "a man stands square to the camera"}, {}, w)+ self.assertIn("Hawaiian", got)++ def test_it_lands_on_the_person_before_the_frame_and_the_room(self):+ w = sb.board_wardrobe({"cast": self.CAST})+ locs = {"carwash": {"id": "carwash", "description": "a sunlit driveway"}}+ got = sb.compose_shot_prompt(+ {"n": 1, "character_id": "bizarrotrn", "trigger": "bizarrotrn",+ "location_id": "carwash", "prompt": "a man stands there",+ "framing": "medium shot"}, locs, w)+ self.assertLess(got.index("Hawaiian"), got.index("medium shot"))+ self.assertLess(got.index("medium shot"), got.index("sunlit driveway"))++ def test_a_shot_that_already_says_it_does_not_get_it_twice(self):+ w = sb.board_wardrobe({"cast": self.CAST})+ got = sb.compose_shot_prompt(+ {"n": 1, "character_id": "bizarrotrn", "trigger": "bizarrotrn",+ "prompt": "a loud floral Hawaiian shirt with the collar open, he waves"}, {}, w)+ self.assertEqual(got.lower().count("hawaiian"), 1)++ def test_no_wardrobe_on_the_board_changes_nothing(self):+ shot = {"n": 1, "character_id": "bizarrotrn", "trigger": "bizarrotrn",+ "prompt": "a man stands there"}+ self.assertEqual(sb.compose_shot_prompt(shot, {}, {}),+ sb.compose_shot_prompt(shot, {}))++ def test_it_only_applies_to_the_character_it_belongs_to(self):+ w = sb.board_wardrobe({"cast": self.CAST})+ got = sb.compose_shot_prompt(+ {"n": 1, "character_id": "ariatrn", "trigger": "ariatrn",+ "prompt": "a woman washes a car"}, {}, w)+ self.assertNotIn("Hawaiian", got)++ def test_shot_to_job_carries_it(self):+ w = sb.board_wardrobe({"cast": self.CAST})+ job = sb.shot_to_job(+ {"n": 1, "mode": "character", "character_id": "bizarrotrn",+ "trigger": "bizarrotrn", "prompt": "a man waves"},+ {"quality": "balanced", "width": 1024, "height": 576, "frames": 121},+ wardrobe=w)+ self.assertIn("Hawaiian", job["prompt"])+++class SpeechLawAtBoardLevel(unittest.TestCase):+ """No mouth moves without words, whoever wrote the shot.++ The planner has enforced this since the owner first said "talking+ gibberish". It ran INSIDE the planner, so a hand-authored board walked+ straight past it and the owner reported gibberish a second time. These pin+ the law at the level every shot passes through.++ The BAD strings below are verbatim from the board that actually produced+ the second gibberish clip, and the GOOD ones from the board that fixed it.+ """+ BAD = ("bizarrotrn a man in a dark navy suit sits upright and addresses the camera",+ "ariatrn a woman pushes her wet hair back and announces something to the lens",+ "bizarrotrn a man asks a dry follow-up question",+ "a weary man explains the situation to the room")++ GOOD = ("bizarrotrn announces in a big brassy showman's voice: "+ "'Ladies and gentlemen — version four point six.'",+ "ariatrn says brightly and clearly: 'Update the app. "+ "There is a timeline editor now.'",+ "A man on a dune ridge says: <d>[English] They said this was impossible.</d>")++ SILENT = ("ariatrn scrubs slow circles across the door with a foam-loaded sponge",+ "Tight on a sponge pressed against the panel, foam bulging and water running",+ "bizarrotrn walks to the window and looks out at the rain without a word")++ def test_it_catches_the_prompts_that_actually_babbled(self):+ for p in self.BAD:+ self.assertIsNotNone(sb.shot_speech_problem(p), f"missed: {p!r}")++ def test_a_written_line_passes_in_either_wrapper(self):+ # H3 keeps <d>...</d>; LTX has already been converted to single quotes+ # by the time the prompt is on a board. Both are "the words are there".+ for p in self.GOOD:+ self.assertIsNone(sb.shot_speech_problem(p), f"false positive: {p!r}")++ def test_an_honestly_silent_shot_is_not_flagged(self):+ for p in self.SILENT:+ self.assertIsNone(sb.shot_speech_problem(p), f"false positive: {p!r}")++ def test_a_briefing_room_is_a_room(self):+ # The planner's version of this law paid for this false positive once+ # already, firing three times on "a dimly lit briefing room".+ self.assertIsNone(sb.shot_speech_problem(+ "a dimly lit briefing room, empty chairs, a map still on the table"))++ def test_gesturing_is_not_speaking(self):+ # Under-reach on purpose. A shot can hand over with a look and stay+ # silent, and this check blocks renders — it may not guess.+ self.assertIsNone(sb.shot_speech_problem(+ "bizarrotrn turns and gestures to someone off-screen, one eyebrow raised"))++ def test_the_validator_blocks_a_board_that_would_babble(self):+ board = _board([dict(_shot(1), prompt="bizarrotrn addresses the camera",+ mode="text", character_id=None, trigger=None)])+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertIn("speech_without_words", codes)++ def test_the_error_says_what_to_do_about_it(self):+ board = _board([dict(_shot(1), prompt="bizarrotrn addresses the camera",+ mode="text", character_id=None, trigger=None)])+ msg = next(e["message"] for e in sb.validate_storyboard_detail(board)+ if e["code"] == "speech_without_words")+ self.assertIn("Write the line", msg)+++class Locations(unittest.TestCase):+ """The same room in every shot that claims to be in it.++ Four Bizarro shots that each said "dim room, cinematic close-up" rendered+ as four different rooms — one of them a vintage parlour with no monitors in+ it at all, with the collar changing between them. Nobody wrote a+ contradiction; the shots simply never agreed, and what a prompt leaves+ unstated gets re-rolled per shot.+ """+ LOC = {"id": "study", "name": "The study",+ "description": "a dark oak-panelled study, three curved monitors "+ "glowing cold blue, a brass desk lamp"}++ def test_the_location_reaches_the_rendered_prompt(self):+ shot = {"n": 1, "trigger": "bizarrotrn", "prompt": "speaks to camera",+ "location_id": "study"}+ got = sb.compose_shot_prompt(shot, {"study": self.LOC})+ self.assertIn("oak-panelled", got)+ self.assertTrue(got.startswith("bizarrotrn speaks to camera"),+ "subject and action come first; the room is appended")++ def test_the_framing_lands_between_the_action_and_the_room(self):+ # Order is not cosmetic: leading with scenery buries the action.+ shot = {"n": 1, "trigger": "x", "prompt": "leans on the car",+ "framing": "wide shot, full body, clear space around her",+ "location_id": "study"}+ got = sb.compose_shot_prompt(shot, {"study": self.LOC})+ self.assertLess(got.index("leans on the car"), got.index("wide shot"))+ self.assertLess(got.index("wide shot"), got.index("oak-panelled"))++ def test_a_shot_with_no_location_is_completely_unchanged(self):+ # Every board written before locations existed has none.+ shot = {"n": 1, "trigger": "x", "prompt": "does a thing"}+ self.assertEqual(sb.compose_shot_prompt(shot, {}), "x does a thing")+ self.assertEqual(sb.compose_shot_prompt(shot, None), "x does a thing")++ def test_shot_to_job_injects_it_because_that_is_the_only_choke_point(self):+ # Every render path goes through shot_to_job. Composing at the call+ # sites instead would give each of them its own chance to forget.+ shot = {"n": 1, "mode": "character", "trigger": "bizarrotrn",+ "prompt": "speaks", "location_id": "study",+ "framing": "medium close-up"}+ job = sb.shot_to_job(shot, {"quality": "balanced", "width": 1024,+ "height": 576, "frames": 121},+ locations={"study": self.LOC})+ self.assertIn("oak-panelled", job["prompt"])+ self.assertIn("medium close-up", job["prompt"])+ self.assertIn("bizarrotrn", job["prompt"])++ def test_a_shot_naming_a_location_the_board_lacks_is_an_error(self):+ # It would render with NO room injected and look exactly like a shot+ # that never claimed one — the continuity failure arriving silently.+ board = _board([dict(_shot(1), location_id="nowhere")])+ board["locations"] = [self.LOC]+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertIn("unknown_location", codes)++ def test_a_location_with_no_description_is_an_error(self):+ board = _board([_shot(1)])+ board["locations"] = [{"id": "study", "name": "The study", "description": " "}]+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertIn("location_empty", codes)++ def test_duplicate_and_malformed_location_ids_are_caught(self):+ board = _board([_shot(1)])+ board["locations"] = [self.LOC, dict(self.LOC), {"id": "Not An Id!", "description": "x"}]+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertIn("location_duplicate", codes)+ self.assertIn("location_id", codes)++ def test_a_board_with_locations_still_validates(self):+ board = _board([dict(_shot(1), location_id="study")])+ board["locations"] = [self.LOC]+ self.assertEqual(sb.validate_storyboard(board), [])+++class LocationViews(unittest.TestCase):+ """THE CAR WASH — the acceptance benchmark, on the deterministic half.++ A whole day of manual continuity work on `sb_carwash` produced exactly one+ paragraph of floor plan: a man presents at a soapy car, a woman washes it,+ houses across the street, a low sun. From that paragraph the establishing+ angle and the reverse angle are DERIVABLE, and the two things that make the+ cut work are the two things a single location description cannot express —+ the reverse does not contain the car, and the sun that raked in from camera+ LEFT rakes in from camera RIGHT once the camera turns 180 degrees.++ The floor plan itself is a model's job. Everything below it — which+ description reaches the prompt, which side the eyes go, what happens to a+ board that has no views at all — is arithmetic, and this is where it is+ pinned.+ """+ CARWASH = sb.new_location(+ "carwash", "The car wash",+ "a suburban driveway on a bright afternoon",+ views=[+ sb.new_view("establishing", "Establishing — facing the driveway",+ "a soapy blue sedan on the driveway, a woman crouched at the "+ "front wheel with a sponge, the low sun raking in from camera "+ "left"),+ sb.new_view("reverse", "Reverse — facing the street",+ "the row of low houses across the street, a hand-painted sign "+ "on the far verge, no car in frame, the low sun raking in from "+ "camera right"),+ ])+ LOCS = {"carwash": CARWASH}++ def _shot(self, view, **kw):+ s = {"n": 1, "trigger": "bizarrotrn", "prompt": "throws both arms wide",+ "location_id": "carwash", "view": view}+ s.update(kw)+ return s++ # ---- the benchmark ------------------------------------------------------+ def test_the_establishing_view_has_the_car_and_the_woman(self):+ got = sb.compose_shot_prompt(self._shot("establishing"), self.LOCS)+ self.assertIn("soapy blue sedan", got)+ self.assertIn("woman", got)+ self.assertIn("camera left", got)++ def test_the_reverse_view_has_the_houses_and_no_car(self):+ got = sb.compose_shot_prompt(self._shot("reverse"), self.LOCS)+ self.assertIn("houses across the street", got)+ self.assertNotIn("soapy blue sedan", got)+ self.assertNotIn("driveway", got)++ def test_the_light_flips_sides_at_180_degrees(self):+ # Measured on the real cut: a camera-left sun is a camera-right sun+ # turned around. Both descriptions carry it, and neither carries both.+ front = sb.compose_shot_prompt(self._shot("establishing"), self.LOCS)+ back = sb.compose_shot_prompt(self._shot("reverse"), self.LOCS)+ self.assertIn("camera left", front)+ self.assertNotIn("camera right", front)+ self.assertIn("camera right", back)+ self.assertNotIn("camera left", back)++ def test_the_eyeline_pair_is_complementary(self):+ him = sb.compose_shot_prompt(+ self._shot("establishing", eyeline="right", pronoun="he"), self.LOCS)+ her = sb.compose_shot_prompt(+ dict(self._shot("reverse", eyeline="left", pronoun="she"),+ trigger="ariatrn", prompt="keeps scrubbing"), self.LOCS)+ self.assertIn("his eyes fixed past the right edge of frame", him)+ self.assertIn("her eyes fixed past the left edge of frame", her)+ self.assertEqual(sb.eyeline_complement("right"), "left")+ self.assertEqual(sb.eyeline_complement("left"), "right")+ self.assertEqual(sb.eyeline_complement("lens"), "")++ # ---- the composition contract ------------------------------------------+ def test_the_eyeline_lands_with_the_framing_not_with_the_room(self):+ # Where a person looks is a fact about the FRAME. Behind the scenery it+ # reads as a note about the street.+ got = sb.compose_shot_prompt(+ self._shot("establishing", framing="medium close-up", eyeline="right"),+ self.LOCS)+ self.assertLess(got.index("throws both arms wide"), got.index("medium close-up"))+ self.assertLess(got.index("medium close-up"), got.index("eyes fixed"))+ self.assertLess(got.index("eyes fixed"), got.index("soapy blue sedan"))++ def test_looking_down_the_lens_says_nothing(self):+ # These models point a piece to camera at the lens unprompted; a+ # sentence ordering it buys a stiffer performance for nothing.+ got = sb.compose_shot_prompt(self._shot("establishing", eyeline="lens"), self.LOCS)+ self.assertNotIn("eyes fixed", got)+ self.assertEqual(sb.eyeline_clause("lens"), "")+ self.assertEqual(sb.eyeline_clause(None), "")++ def test_an_eyeline_with_no_pronoun_is_still_renderable(self):+ self.assertEqual(sb.eyeline_clause("left"), "eyes fixed past the left edge of frame")++ # ---- back-compat: a location with no views is exactly what it was -------+ def test_a_location_with_no_views_behaves_as_it_always_did(self):+ loc = sb.new_location("study", "The study", "a dark oak-panelled study")+ self.assertNotIn("views", loc)+ shot = {"n": 1, "trigger": "x", "prompt": "speaks", "location_id": "study"}+ self.assertEqual(sb.compose_shot_prompt(shot, {"study": loc}),+ "x speaks, a dark oak-panelled study")++ def test_a_shot_that_names_no_view_gets_the_location_description(self):+ shot = {"n": 1, "trigger": "x", "prompt": "speaks", "location_id": "carwash"}+ got = sb.compose_shot_prompt(shot, self.LOCS)+ self.assertIn("suburban driveway on a bright afternoon", got)+ self.assertNotIn("soapy blue sedan", got)++ def test_a_view_with_no_description_falls_back_rather_than_vanishing(self):+ # The validator calls this out (view_empty); compose still has to+ # produce a prompt, and a prompt with no place at all is worse.+ loc = sb.new_location("x", "X", "a place", views=[{"id": "v", "description": ""}])+ shot = {"n": 1, "trigger": "t", "prompt": "does a thing",+ "location_id": "x", "view": "v"}+ self.assertIn("a place", sb.compose_shot_prompt(shot, {"x": loc}))++ # ---- the render choke point --------------------------------------------+ def test_shot_to_job_carries_the_view_and_the_eyeline(self):+ shot = {"n": 1, "mode": "character", "trigger": "bizarrotrn",+ "prompt": "throws both arms wide", "location_id": "carwash",+ "view": "reverse", "eyeline": "right", "pronoun": "he"}+ job = sb.shot_to_job(shot, {"quality": "balanced", "width": 1024,+ "height": 576, "frames": 121},+ locations=self.LOCS)+ self.assertIn("houses across the street", job["prompt"])+ self.assertIn("his eyes fixed past the right edge of frame", job["prompt"])+ self.assertNotIn("soapy blue sedan", job["prompt"])++ # ---- the schema ---------------------------------------------------------+ def test_helpers_read_the_shape_the_planner_writes(self):+ self.assertEqual(sorted(sb.location_views(self.CARWASH)),+ ["establishing", "reverse"])+ self.assertEqual(sb.location_views(None), {})+ self.assertEqual(sb.location_views({"id": "x"}), {})+ self.assertEqual(+ sb.shot_view(self._shot("reverse"), self.LOCS)["name"],+ "Reverse — facing the street")+ self.assertIsNone(sb.shot_view(self._shot("nope"), self.LOCS))+ self.assertIsNone(sb.shot_view({"n": 1}, self.LOCS))++ def test_a_board_with_views_still_validates(self):+ board = _board([dict(_shot(1), location_id="carwash", view="reverse",+ eyeline="left")], locations=[self.CARWASH])+ self.assertEqual(sb.validate_storyboard(board), [])++ def test_every_eyeline_in_the_vocabulary_is_legal(self):+ for eye in sb.EYELINES:+ board = _board([dict(_shot(1), eyeline=eye)])+ self.assertEqual(sb.validate_storyboard(board), [], eye)++ def test_a_view_on_a_shot_with_no_location_is_an_error(self):+ board = _board([dict(_shot(1), view="reverse")], locations=[self.CARWASH])+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertIn("unknown_view", codes)++ def test_the_error_names_the_views_that_do_exist(self):+ board = _board([dict(_shot(1), location_id="carwash", view="behind")],+ locations=[self.CARWASH])+ row = next(e for e in sb.validate_storyboard_detail(board)+ if e["code"] == "unknown_view")+ self.assertEqual(row["data"]["known"], ["establishing", "reverse"])+ self.assertEqual(row["field"], "view")++ # ---- adoption: the plan's views onto the user's own locations ----------+ def test_the_plans_views_land_on_the_users_own_words(self):+ # The board row is the Locations box, typed by a human. Only `views`+ # comes from the model.+ mine = [sb.new_location("carwash", "The car wash", "MY OWN WORDS")]+ merged = sb.merge_location_views(mine, [self.CARWASH])+ self.assertEqual(merged[0]["description"], "MY OWN WORDS")+ self.assertEqual([v["id"] for v in merged[0]["views"]],+ ["establishing", "reverse"])+ self.assertNotIn("views", mine[0], "the board's own list was mutated")++ def test_a_plan_with_no_views_does_not_strip_the_ones_on_the_board(self):+ # A re-plan with geography off, or one whose floor plan came back as+ # chatter. The shots still name these views and an unknown view id is+ # a hard error.+ merged = sb.merge_location_views(+ [self.CARWASH], [sb.new_location("carwash", "The car wash", "x")])+ self.assertEqual([v["id"] for v in merged[0]["views"]],+ ["establishing", "reverse"])++ def test_a_location_the_board_lacks_is_appended_not_dropped(self):+ merged = sb.merge_location_views([], [self.CARWASH])+ self.assertEqual([l["id"] for l in merged], ["carwash"])++ def test_merging_nothing_into_nothing_is_empty(self):+ self.assertEqual(sb.merge_location_views(None, None), [])+ self.assertEqual(sb.merge_location_views([{"name": "no id"}], None), [])++ def test_a_broken_view_is_reported_once_not_on_every_shot(self):+ # A view whose description is empty is still a view that EXISTS. Adding+ # `unknown_view` to every shot that names it buries the one line worth+ # reading under the shot list.+ loc = sb.new_location("x", "X", "a place",+ views=[sb.new_view("v", "V", " ")])+ board = _board([dict(_shot(1), location_id="x", view="v"),+ dict(_shot(2), location_id="x", view="v")],+ locations=[loc])+ codes = [e["code"] for e in sb.validate_storyboard_detail(board)]+ self.assertEqual(codes, ["view_empty"])++if __name__ == "__main__":unittest.main()diff --git a/test_storyboard_assembly.py b/test_storyboard_assembly.pynew file mode 100644index 0000000..80bbaac--- /dev/null+++ b/test_storyboard_assembly.py@@ -0,0 +1,1919 @@+#!/usr/bin/env python3+"""Tests for the storyboard EXPORT: the folder, the manifest, and the film.++Two things are locked here.++1. **Assembly.** A film's shots are not uniform — the draft pass writes+ 640x448, delivery writes 1024x576, H3's export lands 768x448 or 1280x720,+ LTX carries 48 kHz sound and H3 carries 32 kHz, and a character test may+ carry none at all. A bare concat DEMUXER either refuses that or writes a+ file that plays the first shot and garbles the rest, so the panel builds a+ concat FILTER graph that normalises every segment first. These tests assert+ the graph, not a happy-path smoke render.++2. **Stop.** Pressing Stop must cancel the shot that is RENDERING, not only the+ ones still queued, and it must do it through the panel's one existing+ job-cancel path without touching anybody else's job.++No GPU, no weights, no model download. Everything that shells out is either+mocked or gated on a real ffmpeg being present (the two fixture clips are+lavfi test patterns, a fraction of a second each).++Run: python3 -m unittest test_storyboard_assembly+"""++from __future__ import annotations++import hashlib+import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402+import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402++NODE = shutil.which("node")+++def _probe(w, h, duration, *, audio=True, rate=48000) -> dict:+ return {"w": w, "h": h, "duration": duration,+ "has_audio": audio, "sample_rate": rate if audio else 0}+++def _clip(n, path, **kw):+ s = {"n": n, "mode": "text", "engine": "ltx", "prompt": f"shot {n} happens",+ "duration_s": 5.0, "seed": 1000 + n, "refs": [], "status": "done",+ "draft_output": str(path)}+ s.update(kw)+ return s+++def _board(shots, **kw) -> dict:+ b = {"schema": 1, "id": "sb_assembly_test", "title": "The Long Walk",+ "created_at": 1_700_000_000, "shots": shots, "policy": {}, "cast": []}+ b.update(kw)+ return b+++def _sha(p: Path) -> str:+ return hashlib.sha256(Path(p).read_bytes()).hexdigest()+++def _write_fake_clip(p: Path, body: bytes = b"not really an mp4") -> Path:+ p.write_bytes(body)+ return p+++# =============================================================================+# The filter graph — the mixed-geometry problem itself+# =============================================================================+class FilterGraph(unittest.TestCase):+ MIXED = [+ ("draft.mp4", _probe(640, 448, 3.041667)), # LTX draft+ ("delivery.mp4", _probe(1024, 576, 5.041667)), # LTX delivery+ ("h3.mp4", _probe(768, 448, 5.125, rate=32000)), # H3, 32 kHz+ ("silent.mp4", _probe(1024, 576, 2.0, audio=False)), # no sound+ ]++ def graph(self, probes=None, w=1024, h=576, rate=48000, pix="yuv420p",+ **kw):+ g, label = panel._sb_film_filtergraph(probes or self.MIXED, w, h, rate,+ pix, **kw)+ return g, label++ def test_every_segment_is_scaled_and_padded_to_one_geometry(self):+ g, _ = self.graph()+ for idx in range(len(self.MIXED)):+ self.assertIn(+ f"[{idx}:v]fps=24,scale=1024:576:"+ f"force_original_aspect_ratio=decrease,"+ f"pad=1024:576:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p"+ f"[v{idx}]", g)++ def test_no_shot_is_ever_cropped_or_stretched(self):+ # force_original_aspect_ratio=decrease + pad is the "bars, never crop"+ # recipe; `crop` and force_original_aspect_ratio=increase are the two+ # ways to silently lose picture, and neither may appear.+ g, _ = self.graph()+ self.assertNotIn("crop", g)+ self.assertNotIn("force_original_aspect_ratio=increase", g)+ # setsar=1 or a 4:3-flagged source skews the whole cut.+ self.assertEqual(g.count("setsar=1"), len(self.MIXED))++ def test_one_frame_rate_for_the_whole_film(self):+ g, _ = self.graph()+ self.assertEqual(g.count(f"fps={panel.FPS}"), len(self.MIXED))++ def test_pixel_format_is_uniform_and_comes_from_the_settings(self):+ # concat negotiates ONE pixel format across its inputs; making that+ # format the one the encode was going to write anyway avoids a second+ # conversion and keeps the film inside the codec gate's contract.+ g, _ = self.graph(pix="yuv444p")+ self.assertEqual(g.count("format=yuv444p"), len(self.MIXED))+ self.assertNotIn("format=yuv420p", g)++ def test_a_silent_clip_gets_synthesised_silence(self):+ # THE failure this exists for: an uneven audio-stream count and ffmpeg+ # refuses to build the graph at all.+ g, _ = self.graph()+ self.assertIn(+ "anullsrc=channel_layout=stereo:sample_rate=48000:d=2.000000[a3]", g)++ def test_every_segment_has_exactly_one_audio_pad(self):+ g, _ = self.graph()+ for idx in range(len(self.MIXED)):+ self.assertEqual(g.count(f"[a{idx}]"), 2, # produced once, consumed once+ f"segment {idx}")++ def test_real_audio_is_resampled_to_the_films_one_rate(self):+ g, _ = self.graph(rate=48000)+ # The 32 kHz H3 track is segment 2 and must be brought to 48 kHz, not+ # left to fight the LTX segments inside concat.+ self.assertIn("[2:a]aresample=48000,", g)+ self.assertEqual(g.count("aresample=48000"), 3) # the three sounded clips++ def test_audio_is_padded_and_trimmed_to_the_PICTURE_length(self):+ # An H3 clip's AAC track runs ~42 ms past its last frame. Believing the+ # container would drift the sound further behind the picture with every+ # shot, so each segment's audio is pinned to its VIDEO duration.+ g, _ = self.graph()+ self.assertIn("apad,atrim=0:5.125000,asetpts=PTS-STARTPTS[a2]", g)++ def test_concat_is_the_filter_not_the_demuxer(self):+ g, _ = self.graph()+ self.assertIn("concat=n=4:v=1:a=1[vcat][aout]", g)++ def test_bt709_tagging_rides_the_same_helper_as_every_other_export(self):+ with mock.patch.object(panel, "bt709_vf", return_value="setparams=x"):+ g, label = self.graph()+ self.assertEqual(label, "[vout]")+ self.assertTrue(g.endswith("[vcat]setparams=x[vout]"))++ def test_an_ffmpeg_without_setparams_still_produces_a_valid_graph(self):+ with mock.patch.object(panel, "bt709_vf", return_value=""):+ g, label = self.graph()+ self.assertEqual(label, "[vcat]")+ self.assertTrue(g.endswith("concat=n=4:v=1:a=1[vcat][aout]"))++ def test_a_single_clip_is_still_a_film(self):+ g, _ = self.graph(probes=self.MIXED[:1])+ self.assertIn("concat=n=1:v=1:a=1", g)+++# =============================================================================+# The auto-edit — trimming and a soundtrack, in the SAME filtergraph pass+# =============================================================================+class AutoEditGraph(unittest.TestCase):+ """The opt-in path. Two properties matter more than any other: the default+ graph must be untouched, and the trim must happen HERE rather than in a+ second ffmpeg run that would decode and re-encode every shot twice."""++ PROBES = [+ (Path("/x/S01.mp4"), _probe(1920, 1080, 10.125)),+ (Path("/x/S02.mp4"), _probe(1024, 576, 5.167)),+ (Path("/x/S03.mp4"), _probe(1024, 576, 5.167, audio=False)),+ ]+ PLAN = [+ {"path": "/x/S01.mp4", "start": 0.5, "end": 5.25},+ {"path": "/x/S02.mp4", "start": 0.75, "end": 3.0},+ {"path": "/x/S03.mp4", "start": 1.0, "end": 3.5},+ ]++ def graph(self, probes=None, **kw):+ return panel._sb_film_filtergraph(probes or self.PROBES, 1920, 1080,+ 48000, "yuv420p", **kw)++ # ---- the default cannot move -----------------------------------------+ def test_no_plan_and_no_music_is_byte_identical_to_the_old_graph(self):+ # The literal below is the graph as it was BEFORE the auto-editor+ # existed. If this test has to be edited, the default export changed,+ # and that is exactly the thing that must not happen by accident.+ expected = (+ "[0:v]fps=24,scale=1920:1080:force_original_aspect_ratio=decrease,"+ "pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p[v0];"+ "[0:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,"+ "apad,atrim=0:10.125000,asetpts=PTS-STARTPTS[a0];"+ "[1:v]fps=24,scale=1920:1080:force_original_aspect_ratio=decrease,"+ "pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p[v1];"+ "[1:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,"+ "apad,atrim=0:5.167000,asetpts=PTS-STARTPTS[a1];"+ "[2:v]fps=24,scale=1920:1080:force_original_aspect_ratio=decrease,"+ "pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p[v2];"+ "anullsrc=channel_layout=stereo:sample_rate=48000:d=5.167000[a2];"+ "[v0][a0][v1][a1][v2][a2]concat=n=3:v=1:a=1[vcat][aout]")+ with mock.patch.object(panel, "bt709_vf", return_value=""):+ g, label = self.graph()+ self.assertEqual(g, expected)+ self.assertEqual(label, "[vcat]")+ # ...and passing the arguments as None must be the same thing.+ self.assertEqual(self.graph(cuts=None, music=None)[0], expected)+ self.assertEqual(self.graph(cuts={}, music=None)[0], expected)++ # ---- trimming ---------------------------------------------------------+ def test_each_segment_is_trimmed_to_its_own_window(self):+ g, _ = self.graph(cuts=panel._sb_cut_index(self.PLAN))+ self.assertIn("[0:v]trim=start=0.500000:end=5.250000,"+ "setpts=PTS-STARTPTS,fps=24,", g)+ self.assertIn("[1:v]trim=start=0.750000:end=3.000000,"+ "setpts=PTS-STARTPTS,fps=24,", g)++ def test_the_trim_comes_BEFORE_the_rate_and_scale_conversions(self):+ # trim works on SOURCE timestamps. Put it after `fps` and the window+ # you asked for is not the window you get.+ g, _ = self.graph(cuts=panel._sb_cut_index(self.PLAN))+ for idx in range(3):+ chain = next(c for c in g.split(";") if c.startswith(f"[{idx}:v]"))+ self.assertLess(chain.index("trim=start"), chain.index("fps="))+ self.assertLess(chain.index("setpts=PTS-STARTPTS"),+ chain.index("scale="))++ def test_the_audio_is_trimmed_to_the_same_window_and_pinned_to_it(self):+ g, _ = self.graph(cuts=panel._sb_cut_index(self.PLAN))+ self.assertIn("[1:a]atrim=start=0.750000:end=3.000000,"+ "asetpts=PTS-STARTPTS,aresample=48000,", g)+ # the pad/trim tail still pins the sound to the PICTURE's new length+ self.assertIn("apad,atrim=0:2.250000,asetpts=PTS-STARTPTS[a1]", g)++ def test_a_silent_clip_gets_silence_of_the_TRIMMED_length(self):+ g, _ = self.graph(cuts=panel._sb_cut_index(self.PLAN))+ self.assertIn("sample_rate=48000:d=2.500000[a2]", g)+ self.assertNotIn("d=5.167000", g)++ def test_a_clip_with_no_plan_entry_plays_whole(self):+ # A plan can be partial. The clips it does not mention are not+ # silently dropped and not silently trimmed to zero.+ cuts = panel._sb_cut_index(self.PLAN[:1])+ g, _ = self.graph(cuts=cuts)+ self.assertIn("[0:v]trim=start=0.500000", g)+ self.assertIn("[1:v]fps=24,", g)+ self.assertIn("apad,atrim=0:5.167000,asetpts=PTS-STARTPTS[a1]", g)++ def test_a_window_longer_than_its_clip_cannot_stretch_the_segment(self):+ cuts = panel._sb_cut_index([{"path": "/x/S02.mp4",+ "start": 0.0, "end": 99.0}])+ g, _ = self.graph(cuts=cuts)+ self.assertIn("apad,atrim=0:5.167000,asetpts=PTS-STARTPTS[a1]", g)++ def test_the_plan_is_matched_by_PATH_not_by_position(self):+ # _sb_assemble_film drops clips ffprobe cannot read. A positional plan+ # would then apply shot 2's window to shot 3 — silently, and only when+ # a file is broken.+ idx = panel._sb_cut_index(self.PLAN)+ self.assertEqual(sorted(idx), ["/x/S01.mp4", "/x/S02.mp4",+ "/x/S03.mp4"])+ short = [self.PROBES[0], self.PROBES[2]] # S02 unreadable+ g, _ = panel._sb_film_filtergraph(short, 1920, 1080, 48000,+ "yuv420p", cuts=idx)+ self.assertIn("[1:v]trim=start=1.000000:end=3.500000", g)++ def test_a_malformed_plan_entry_is_ignored_rather_than_fatal(self):+ idx = panel._sb_cut_index([+ {"path": "/x/S01.mp4", "start": 1.0, "end": 2.0},+ {"path": "/x/S02.mp4", "start": 3.0, "end": 3.0}, # zero length+ {"path": "/x/S03.mp4", "start": "nope", "end": 4.0},+ {"start": 0.0, "end": 1.0}, # no path+ "not a dict",+ ])+ self.assertEqual(list(idx), ["/x/S01.mp4"])+ self.assertEqual(panel._sb_cut_index(None), {})+ self.assertEqual(panel._sb_cut_index([]), {})++ # ---- the soundtrack ---------------------------------------------------+ def test_music_replaces_the_clip_audio_entirely(self):+ g, _ = self.graph(cuts=panel._sb_cut_index(self.PLAN),+ music={"path": "/x/song.mp3", "start": 0.0})+ self.assertIn("concat=n=3:v=1:a=0[vcat]", g)+ for idx in range(3):+ self.assertNotIn(f"[a{idx}]", g)+ self.assertNotIn("anullsrc", g)++ def test_the_music_is_trimmed_to_the_length_of_the_CUT(self):+ # 4.75 + 2.25 + 2.5 = 9.5 s of film, not 20.459 s of source clips.+ g, _ = self.graph(cuts=panel._sb_cut_index(self.PLAN),+ music={"path": "/x/song.mp3", "start": 0.0})+ self.assertIn("[3:a]atrim=start=0.000000,asetpts=PTS-STARTPTS,"+ "aresample=48000,", g)+ self.assertIn("apad,atrim=0:9.500000,asetpts=PTS-STARTPTS[aout]", g)++ def test_music_without_a_plan_still_lays_under_the_whole_clips(self):+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0})+ self.assertIn("apad,atrim=0:20.459000,asetpts=PTS-STARTPTS[aout]", g)++ # ---- the soundtrack, mode `under` -------------------------------------+ # `replace` silences the clips. That is right for a beat-cut music video+ # and catastrophic for anything with a voice in it: attaching a bed to a+ # dialogue film deleted the performance. These pin the other mode.+ def test_under_keeps_the_clip_audio_instead_of_dropping_it(self):+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "under"})+ self.assertIn("concat=n=3:v=1:a=1[vcat][acat]", g)+ for idx in range(3):+ self.assertIn(f"[a{idx}]", g) # every segment still has sound++ def test_under_applies_no_gain_the_document_did_not_ask_for(self):+ # THE DEFECT THIS PINS. The graph used to hold every `under` bed at a+ # hard-coded 0.20 and then duck it through `sidechaincompress`, neither+ # of them in any document and neither of them in the preview — so the+ # render invented a mix the Editor never played. A bed with no curve+ # now gets no filter at all, exactly like a clip with no envelope.+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "under"})+ self.assertNotIn("sidechaincompress", g)+ self.assertNotIn("volume=0.20", g)+ self.assertIn("asetpts=PTS-STARTPTS[bed]", g)++ def test_under_mixes_the_dialogue_and_the_bed_directly(self):+ # No `asplit` either: it existed only to feed the compressor's key.+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "under"})+ self.assertNotIn("asplit", g)+ self.assertIn("[acat][bed]amix=", g)++ def test_under_carries_the_documents_own_bed_curve(self):+ # The one field the graph always read and nothing ever set. A fade on+ # the soundtrack was expressible in the model, drawn on the strip, and+ # absent from the file.+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "under",+ "gain": [[0.0, 1.0], [4.0, 0.25]]})+ self.assertIn("volume=volume='", g)+ self.assertIn("eval=frame", g)+ self.assertIn("[bed]", g)++ def test_replace_carries_the_bed_curve_too(self):+ # "Fade the music out under the last shot" is the same request whether+ # or not the clips kept their own sound.+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "gain": [[0.0, 1.0], [4.0, 0.0]]})+ self.assertIn("volume=volume='", g)+ self.assertIn("[aout]", g)++ def test_under_does_not_let_amix_rescale_the_mix(self):+ # normalize=0: amix otherwise halves both inputs to protect a headroom+ # budget the bed gain has already set deliberately.+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "under"})+ self.assertIn("normalize=0", g)+ self.assertIn("duration=first", g)++ def test_under_puts_a_ceiling_on_the_sum(self):+ # normalize=0 means nothing is protecting the sum, and hot engine+ # dialogue plus a bed peaked the first under-mix film at 1.31 with 1341+ # hard-clipped samples. The ceiling is the last thing before [aout].+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "under"})+ self.assertIn(f"asoftclip=type=tanh:threshold={panel._sb_mix_ceiling():g}[aout]", g)++ def test_the_ceiling_is_not_alimiter(self):+ # alimiter is the filter this obviously wants and it is a NO-OP on+ # float samples in this ffmpeg: measured on the real mix, in 1.3075 ->+ # out 1.3075, unchanged by level=disabled or by an aformat to s16 on+ # either side. It fails silently and the failure is audible, so the+ # name is banned here rather than left as an inviting "cleanup".+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "under"})+ self.assertNotIn("alimiter", g)++ def test_replace_is_still_the_default_when_no_mode_is_given(self):+ # Every existing caller passes no mode and must keep the old graph.+ without = self.graph(music={"path": "/x/song.mp3", "start": 0.0})[0]+ explicit = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "replace"})[0]+ self.assertEqual(without, explicit)+ self.assertNotIn("sidechaincompress", without)++ def test_an_unknown_mode_falls_back_to_replace_rather_than_breaking(self):+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "sidechain-please"})+ self.assertNotIn("sidechaincompress", g)+ self.assertIn("concat=n=3:v=1:a=0[vcat]", g)++ # ---- the soundtrack, as an object (Wave 4) ----------------------------+ def test_a_trimmed_soundtrack_stops_where_the_trim_says(self):+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 4.0,+ "end": 12.0})+ self.assertIn("[3:a]atrim=start=4.000000:end=12.000000,"+ "asetpts=PTS-STARTPTS,aresample=48000,", g)++ def test_a_delayed_soundtrack_arrives_late_and_in_both_channels(self):+ # adelay and not a longer atrim: silence in front of a track is not a+ # property of the track. `all=1` because the default delays the FIRST+ # channel only — a bed that arrives in the left speaker.+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 0.0,+ "delay": 2.5})+ self.assertIn("[3:a]atrim=start=0.000000,asetpts=PTS-STARTPTS,"+ "adelay=delays=2500:all=1,aresample=48000,", g)++ def test_the_trim_and_the_delay_survive_the_under_mix(self):+ # The duck and the ceiling are what `under` is for; a music object+ # that only worked in `replace` would be half a feature.+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 1.0,+ "end": 9.0, "delay": 3.0, "mode": "under"})+ self.assertIn("[3:a]atrim=start=1.000000:end=9.000000,"+ "asetpts=PTS-STARTPTS,adelay=delays=3000:all=1,", g)+ self.assertIn("[acat][bed]amix=", g)+ self.assertIn(f"asoftclip=type=tanh:threshold={panel._sb_mix_ceiling():g}[aout]", g)++ def test_an_untouched_soundtrack_builds_the_graph_it_always_did(self):+ # The whole safety of Wave 4's schema: absent trims, no delay, and the+ # string is character-for-character the one every film so far used.+ plain = self.graph(music={"path": "/x/song.mp3", "start": 0.0})[0]+ for extra in ({"end": None, "delay": 0.0},+ {"end": None}, {"delay": 0}):+ with self.subTest(extra=extra):+ self.assertEqual(+ self.graph(music=dict({"path": "/x/song.mp3",+ "start": 0.0}, **extra))[0], plain)+ self.assertNotIn("adelay", plain)+ self.assertNotIn(":end=", plain)++ def test_an_end_that_is_not_after_the_start_is_ignored(self):+ # A window the trims closed is not a zero-length atrim ffmpeg refuses.+ g, _ = self.graph(music={"path": "/x/song.mp3", "start": 5.0,+ "end": 5.0})+ self.assertIn("[3:a]atrim=start=5.000000,asetpts", g)+ self.assertNotIn(":end=", g)++ # ---- J-cuts and L-cuts (Wave 4) --------------------------------------+ # "You can edit dialogue in a way that you hear her voice while you're+ # seeing him... I need to be able to leave some of the audio and drag only+ # the image."+ def _split_segs(self, delta=-1.0, alen=None):+ probe = {"w": 1920, "h": 1080, "duration": 8.0,+ "sample_rate": 48000, "has_audio": True}+ with mock.patch.object(panel, "_sb_probe_clip", return_value=probe):+ segs, _unread, _inputs = panel._sb_timeline_segments([+ {"path": "/x/a.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0},+ {"path": "/x/b.mp4", "start": 0.0, "end": 4.0,+ "film_start": 4.0,+ "audio": {"start": 0.0, "end": alen if alen else 4.0,+ "film_start": 4.0 + delta}},+ ])+ return segs++ def test_nothing_unlinked_builds_the_graph_it_always_did(self):+ # The safety the whole schema rests on: absent means linked.+ plan = panel._sb_split_audio_plan(+ [{"kind": "video", "info": {"has_audio": True, "duration": 4.0},+ "window": {"start": 0.0, "end": 4.0}}])+ self.assertFalse(plan["split"])++ def test_an_unlinked_clip_puts_its_sound_at_its_own_offset(self):+ plan = panel._sb_split_audio_plan([+ {"kind": "video", "info": {"has_audio": True, "duration": 4.0},+ "window": {"start": 0.0, "end": 4.0}},+ {"kind": "video", "info": {"has_audio": True, "duration": 4.0},+ "window": {"start": 0.0, "end": 4.0},+ "audio": {"start": 0.0, "end": 4.0, "delta": -1.0}},+ ])+ self.assertTrue(plan["split"])+ self.assertEqual(plan["total"], 8.0)+ # The J-cut: clip 2's sound leads its picture in by a second, so the+ # first clip's sound is trimmed to make room — one lane, still.+ lanes = {L["idx"]: L for L in plan["lanes"]}+ self.assertEqual(lanes[1]["at"], 3.0)+ self.assertEqual(lanes[0]["at"], 0.0)+ self.assertAlmostEqual(lanes[0]["len"], 3.0, places=6)++ def test_the_offset_is_a_delta_so_a_closed_gap_cannot_desync_it(self):+ # The assembler concatenates; an absolute film second taken from the+ # editor's clock would put the sound where the picture used to be.+ plan = panel._sb_split_audio_plan([+ {"kind": "slug", "duration": 2.0},+ {"kind": "video", "info": {"has_audio": True, "duration": 4.0},+ "window": {"start": 0.0, "end": 4.0},+ "audio": {"start": 1.0, "end": 4.0, "delta": 1.0}},+ ])+ lane = plan["lanes"][0]+ self.assertEqual(lane["at"], 3.0) # 2s of slug + 1s of delta+ self.assertEqual([lane["start"], lane["end"]], [1.0, 4.0])++ def test_a_j_cut_on_the_first_clip_has_nowhere_to_lead_from(self):+ plan = panel._sb_split_audio_plan([+ {"kind": "video", "info": {"has_audio": True, "duration": 4.0},+ "window": {"start": 0.0, "end": 4.0},+ "audio": {"start": 0.0, "end": 4.0, "delta": -2.0}},+ ])+ lane = plan["lanes"][0]+ self.assertEqual(lane["at"], 0.0)+ self.assertEqual(lane["start"], 2.0) # the head is cut, not shifted++ def test_an_l_cut_past_the_last_frame_is_cut_to_the_film(self):+ plan = panel._sb_split_audio_plan([+ {"kind": "video", "info": {"has_audio": True, "duration": 8.0},+ "window": {"start": 0.0, "end": 4.0},+ "audio": {"start": 0.0, "end": 8.0, "delta": 0.0}},+ ])+ self.assertEqual(plan["total"], 4.0)+ self.assertEqual(plan["lanes"][0]["len"], 4.0)++ def test_the_split_graph_is_one_audio_lane_of_sound_and_silence(self):+ chains = panel._sb_split_audio_chains(+ [{"idx": 0, "start": 0.0, "end": 2.0, "at": 1.0, "len": 2.0}],+ 5.0, 48000, "[aout]")+ g = ";".join(chains)+ # concat and NOT amix: concat cannot sum, so this graph is incapable+ # of becoming the mixer the refuse list bans.+ self.assertIn("concat=n=3:v=0:a=1[aout]", g)+ self.assertNotIn("amix", g)+ self.assertIn("anullsrc=channel_layout=stereo:sample_rate=48000:d=1.000000", g)+ self.assertIn("d=2.000000", g) # the tail silence++ def test_a_split_film_still_mixes_the_music_and_keeps_its_ceiling(self):+ # The two things the whole mix rests on, and the two a restructure+ # would quietly drop. The bed carries its own curve; the ceiling is+ # the safety net on the sum and belongs to no document.+ segs = self._split_segs()+ g, _ = self.graph(segments=segs,+ music={"path": "/x/song.mp3", "start": 0.0,+ "mode": "under",+ "gain": [[0.0, 0.4], [3.0, 0.4]]})+ self.assertIn("concat=n=2:v=1:a=0[vcat]", g)+ self.assertIn(":v=0:a=1[acat]", g)+ self.assertIn("[acat][bed]amix=", g)+ self.assertIn("volume=volume='", g)+ self.assertIn(f"asoftclip=type=tanh:threshold={panel._sb_mix_ceiling():g}[aout]", g)++ def test_the_sound_is_padded_to_its_own_length_not_the_pictures(self):+ segs = self._split_segs(delta=-1.0, alen=2.0)+ g, _ = self.graph(segments=segs)+ self.assertIn("apad,atrim=0:2.000000,asetpts=PTS-STARTPTS[a1]", g)++ def test_segment_index_is_still_not_input_index_when_split(self):+ # The trap SegmentIndexIsNotInputIndex exists for: a slug consumes no+ # -i, so the soundtrack's index is the INPUT count, and a split lane+ # addresses its clip by SEGMENT index.+ probe = {"w": 1920, "h": 1080, "duration": 8.0,+ "sample_rate": 48000, "has_audio": True}+ with mock.patch.object(panel, "_sb_probe_clip", return_value=probe):+ segs, unreadable, inputs = panel._sb_timeline_segments([+ {"kind": "slug", "start": 0.0, "end": 2.0, "film_start": 0.0},+ {"path": "/x/b.mp4", "start": 0.0, "end": 4.0,+ "film_start": 2.0,+ "audio": {"start": 0.0, "end": 4.0, "film_start": 1.0}},+ ])+ self.assertEqual(segs[0]["input"], None)+ self.assertEqual(segs[1]["input"], 0)+ self.assertEqual(len(inputs), 1)+ self.assertEqual(segs[1]["audio"]["delta"], -1.0)++ def test_bt709_still_rides_the_same_helper_when_auto_edited(self):+ with mock.patch.object(panel, "bt709_vf", return_value="setparams=x"):+ g, label = self.graph(cuts=panel._sb_cut_index(self.PLAN),+ music={"path": "/x/song.mp3", "start": 0.0})+ self.assertEqual(label, "[vout]")+ self.assertIn("[vcat]setparams=x[vout]", g)+++# =============================================================================+# _sb_assemble_film — target geometry, argv, and failure that stays contained+# =============================================================================+class AssembleFilm(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)+ self.addCleanup(self.tmp.cleanup)++ def _run(self, probes, *, ffmpeg_side_effect=None, pix="yuv420p", crf="18"):+ """Assemble with ffprobe + ffmpeg mocked. Returns (result, argv)."""+ clips = []+ for i, _ in enumerate(probes):+ clips.append(_write_fake_clip(self.dir / f"S{i:02d}.mp4"))+ seen = {}++ def fake_probe(path):+ return dict(probes[clips.index(Path(path))])++ def fake_ffmpeg(cmd, label):+ seen["cmd"] = list(cmd)+ if ffmpeg_side_effect:+ raise ffmpeg_side_effect+ Path(cmd[-1]).write_bytes(b"film")+ return "", ""++ with mock.patch.object(panel, "_sb_probe_clip", side_effect=fake_probe), \+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \+ mock.patch.object(panel, "output_codec_settings",+ return_value={"preset": "standard",+ "pix_fmt": pix, "crf": crf}):+ res = panel._sb_assemble_film(clips, self.dir / "film.mp4")+ return res, seen.get("cmd", [])++ def test_target_geometry_is_the_largest_picture_in_the_cut(self):+ res, cmd = self._run([_probe(640, 448, 3.0),+ _probe(1024, 576, 5.0),+ _probe(768, 448, 5.0)])+ self.assertTrue(res["ok"])+ self.assertEqual((res["width"], res["height"]), (1024, 576))+ # Widest and tallest can come from DIFFERENT clips; the canvas takes+ # both so nothing is ever scaled down.+ res, _ = self._run([_probe(1280, 448, 3.0), _probe(640, 720, 5.0)])+ self.assertEqual((res["width"], res["height"]), (1280, 720))++ def test_odd_dimensions_are_rounded_up_to_even(self):+ # H.264 4:2:0 has no odd-dimension form; an odd canvas is a hard+ # encoder error at the very end of a long export.+ res, _ = self._run([_probe(641, 449, 3.0)])+ self.assertEqual((res["width"], res["height"]), (642, 450))++ def test_sample_rate_is_the_highest_present_not_a_guess(self):+ res, cmd = self._run([_probe(640, 448, 3.0, rate=32000),+ _probe(640, 448, 3.0, rate=48000)])+ self.assertEqual(res["sample_rate"], 48000)+ self.assertEqual(cmd[cmd.index("-ar") + 1], "48000")++ def test_an_all_silent_film_falls_back_to_the_default_rate(self):+ res, _ = self._run([_probe(640, 448, 3.0, audio=False)])+ self.assertEqual(res["sample_rate"], panel._SB_FILM_SAMPLE_RATE)++ def test_the_encode_uses_the_panels_own_output_settings(self):+ _, cmd = self._run([_probe(640, 448, 3.0)], pix="yuv444p", crf="0")+ self.assertEqual(cmd[cmd.index("-pix_fmt") + 1], "yuv444p")+ self.assertEqual(cmd[cmd.index("-crf") + 1], "0")+ self.assertEqual(cmd[cmd.index("-c:v") + 1], "libx264")++ def test_faststart_and_bt709_are_present(self):+ _, cmd = self._run([_probe(640, 448, 3.0)])+ self.assertIn("+faststart", cmd)+ self.assertEqual(cmd[cmd.index("-movflags") + 1], "+faststart")+ for flag in panel.BT709_FLAGS:+ self.assertIn(flag, cmd)++ def test_argv_is_a_list_of_arguments_never_a_shell_string(self):+ _, cmd = self._run([_probe(640, 448, 3.0), _probe(640, 448, 3.0)])+ self.assertIsInstance(cmd, list)+ self.assertTrue(all(isinstance(a, str) for a in cmd))+ self.assertEqual(cmd.count("-i"), 2)++ def test_duration_reported_is_the_sum_of_the_included_clips(self):+ res, _ = self._run([_probe(640, 448, 3.041667),+ _probe(640, 448, 5.125)])+ self.assertAlmostEqual(res["duration"], 8.167, places=3)++ def test_an_unreadable_clip_is_dropped_from_the_cut_not_fatal(self):+ clips = [_write_fake_clip(self.dir / "good.mp4"),+ _write_fake_clip(self.dir / "torn.mp4")]+ with mock.patch.object(panel, "_sb_probe_clip",+ side_effect=[_probe(640, 448, 3.0), None]), \+ mock.patch.object(panel, "run_ffmpeg_tracked",+ side_effect=lambda c, l: (Path(c[-1])+ .write_bytes(b"f"), ("", ""))[1]), \+ mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "18"}):+ res = panel._sb_assemble_film(clips, self.dir / "film.mp4")+ self.assertTrue(res["ok"])+ self.assertEqual(res["clips"], 1)+ self.assertEqual(res["unreadable"], ["torn.mp4"])++ def test_nothing_readable_is_an_honest_refusal(self):+ clips = [_write_fake_clip(self.dir / "torn.mp4")]+ with mock.patch.object(panel, "_sb_probe_clip", return_value=None):+ res = panel._sb_assemble_film(clips, self.dir / "film.mp4")+ self.assertFalse(res["ok"])+ self.assertIn("ffprobe", res["error"])++ def test_no_clips_at_all_is_an_honest_refusal(self):+ res = panel._sb_assemble_film([], self.dir / "film.mp4")+ self.assertFalse(res["ok"])++ def test_a_failed_encode_leaves_no_half_written_film_behind(self):+ target = self.dir / "film.mp4"++ def half_write(cmd, label):+ Path(cmd[-1]).write_bytes(b"half a film")+ raise RuntimeError("storyboard film exited with code 1")++ clips = [_write_fake_clip(self.dir / "a.mp4")]+ with mock.patch.object(panel, "_sb_probe_clip",+ return_value=_probe(640, 448, 3.0)), \+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=half_write), \+ mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "18"}):+ res = panel._sb_assemble_film(clips, target)+ self.assertFalse(res["ok"])+ self.assertIn("exited with code 1", res["error"])+ self.assertFalse(target.exists(), "a half-written mp4 looks finished in Finder")++ # ---- the auto-edit, at the assembler's own seam ----------------------+ def _run_planned(self, probes, plan, music=None):+ clips = [_write_fake_clip(self.dir / f"S{i:02d}.mp4")+ for i in range(len(probes))]+ for entry, clip in zip(plan, clips):+ entry["path"] = str(clip)+ seen = {}++ def fake_probe(path):+ p = Path(path)+ if music and str(p) == str(music):+ return None+ return dict(probes[clips.index(p)])++ def fake_ffmpeg(cmd, label):+ seen["cmd"] = list(cmd)+ Path(cmd[-1]).write_bytes(b"film")+ return "", ""++ with mock.patch.object(panel, "_sb_probe_clip", side_effect=fake_probe), \+ mock.patch.object(panel, "_sb_probe_audio_rate", return_value=44100), \+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \+ mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "18"}):+ res = panel._sb_assemble_film(clips, self.dir / "film.mp4",+ plan=plan, music=music)+ return res, seen.get("cmd", []), clips++ def test_the_reported_duration_is_the_CUT_not_the_source(self):+ res, _, _ = self._run_planned(+ [_probe(1024, 576, 10.125), _probe(1024, 576, 5.167)],+ [{"start": 1.0, "end": 5.0}, {"start": 0.5, "end": 3.0}])+ self.assertTrue(res["ok"])+ self.assertAlmostEqual(res["duration"], 6.5, places=3)+ self.assertTrue(res["trimmed"])+ self.assertFalse(res["music"])++ def test_a_soundtrack_is_one_extra_input_at_the_end(self):+ song = self.dir / "song.mp3"+ song.write_bytes(b"mp3")+ res, cmd, clips = self._run_planned(+ [_probe(1024, 576, 5.167)], [{"start": 0.0, "end": 4.0}],+ music=song)+ self.assertEqual(cmd.count("-i"), 2)+ self.assertEqual(cmd[cmd.index("-i", cmd.index(str(clips[0]))) + 1],+ str(song))+ self.assertTrue(res["music"])++ def test_the_soundtracks_sample_rate_wins_over_the_clips(self):+ # 44.1 kHz song under 32 kHz H3 clips: resampling the song DOWN to a+ # rate no longer present in the film is a loss for nothing.+ song = self.dir / "song.mp3"+ song.write_bytes(b"mp3")+ res, cmd, _ = self._run_planned(+ [_probe(1024, 576, 5.167, rate=32000)],+ [{"start": 0.0, "end": 4.0}], music=song)+ self.assertEqual(res["sample_rate"], 44100)+ self.assertEqual(cmd[cmd.index("-ar") + 1], "44100")++ def test_source_geometry_still_decides_the_canvas_when_auto_edited(self):+ res, _, _ = self._run_planned(+ [_probe(640, 448, 5.0), _probe(1024, 576, 5.0)],+ [{"start": 0.0, "end": 2.0}, {"start": 1.0, "end": 4.0}])+ self.assertEqual((res["width"], res["height"]), (1024, 576))++ def test_an_unreadable_clip_does_not_shift_everyone_elses_window(self):+ clips = [_write_fake_clip(self.dir / n)+ for n in ("a.mp4", "torn.mp4", "c.mp4")]+ plan = [{"path": str(clips[0]), "start": 0.0, "end": 2.0},+ {"path": str(clips[1]), "start": 0.0, "end": 2.0},+ {"path": str(clips[2]), "start": 3.0, "end": 4.0}]+ seen = {}++ def fake_ffmpeg(cmd, label):+ seen["graph"] = cmd[cmd.index("-filter_complex") + 1]+ Path(cmd[-1]).write_bytes(b"film")+ return "", ""++ with mock.patch.object(panel, "_sb_probe_clip",+ side_effect=[_probe(640, 448, 5.0), None,+ _probe(640, 448, 5.0)]), \+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \+ mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "18"}):+ res = panel._sb_assemble_film(clips, self.dir / "film.mp4",+ plan=plan)+ self.assertEqual(res["clips"], 2)+ # c.mp4 became input 1 — it must still get ITS window, 3.0-4.0.+ self.assertIn("[1:v]trim=start=3.000000:end=4.000000", seen["graph"])+ self.assertAlmostEqual(res["duration"], 3.0, places=3)++ def test_a_clean_exit_that_wrote_nothing_is_still_a_failure(self):+ clips = [_write_fake_clip(self.dir / "a.mp4")]+ with mock.patch.object(panel, "_sb_probe_clip",+ return_value=_probe(640, 448, 3.0)), \+ mock.patch.object(panel, "run_ffmpeg_tracked", return_value=("", "")), \+ mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "18"}):+ res = panel._sb_assemble_film(clips, self.dir / "film.mp4")+ self.assertFalse(res["ok"])+ self.assertIn("no film", res["error"])+++# =============================================================================+# _sb_probe_clip — the only thing that decides a clip is usable+# =============================================================================+class ProbeClip(unittest.TestCase):+ LTX = {"streams": [{"codec_type": "video", "width": 1024, "height": 576,+ "duration": "3.041667"},+ {"codec_type": "audio", "sample_rate": "48000",+ "duration": "3.010000"}],+ "format": {"duration": "3.041667"}}+ SILENT = {"streams": [{"codec_type": "video", "width": 640, "height": 448,+ "duration": "2.000000"}],+ "format": {"duration": "2.000000"}}+ NO_STREAM_DURATION = {"streams": [{"codec_type": "video", "width": 800,+ "height": 600}],+ "format": {"duration": "4.5"}}++ def _probe(self, payload, rc=0):+ proc = subprocess.CompletedProcess([], rc, json.dumps(payload), "")+ with mock.patch.object(panel.subprocess, "run", return_value=proc):+ return panel._sb_probe_clip("/nope/clip.mp4")++ def test_reads_geometry_duration_and_audio(self):+ got = self._probe(self.LTX)+ self.assertEqual(got, {"w": 1024, "h": 576, "duration": 3.041667,+ "has_audio": True, "sample_rate": 48000})++ def test_a_silent_clip_is_valid_with_has_audio_false(self):+ got = self._probe(self.SILENT)+ self.assertFalse(got["has_audio"])+ self.assertEqual(got["sample_rate"], 0)++ def test_duration_prefers_the_video_stream_over_the_container(self):+ h3 = {"streams": [{"codec_type": "video", "width": 768, "height": 448,+ "duration": "5.125000"},+ {"codec_type": "audio", "sample_rate": "32000"}],+ "format": {"duration": "5.167000"}}+ self.assertEqual(self._probe(h3)["duration"], 5.125)++ def test_container_duration_is_the_fallback(self):+ self.assertEqual(self._probe(self.NO_STREAM_DURATION)["duration"], 4.5)++ def test_unreadable_inputs_return_None_rather_than_raising(self):+ self.assertIsNone(self._probe({}, rc=1))+ self.assertIsNone(self._probe({"streams": []}))+ self.assertIsNone(self._probe({"streams": [{"codec_type": "audio"}]}))+ with mock.patch.object(panel.subprocess, "run",+ side_effect=OSError("no ffprobe")):+ self.assertIsNone(panel._sb_probe_clip("/nope/clip.mp4"))+ proc = subprocess.CompletedProcess([], 0, "not json at all", "")+ with mock.patch.object(panel.subprocess, "run", return_value=proc):+ self.assertIsNone(panel._sb_probe_clip("/nope/clip.mp4"))+++# =============================================================================+# _sb_export — selection, ordering, and a failure that stays contained+# =============================================================================+class ExportSelection(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.addCleanup(self.tmp.cleanup)+ self.src = self.root / "gallery"+ self.src.mkdir()+ self._patch = mock.patch.object(panel, "OUTPUT", self.root / "out")+ self._patch.start()+ self.addCleanup(self._patch.stop)++ def clip(self, name: str) -> Path:+ return _write_fake_clip(self.src / name, name.encode() * 64)++ def export(self, board, film=None):+ """Run the real _sb_export with the assembler mocked. -> (res, clips)."""+ seen = {}++ def fake_assemble(clips, out):+ seen["clips"] = [Path(c) for c in clips]+ seen["out"] = Path(out)+ if film is None:+ Path(out).write_bytes(b"film")+ return {"ok": True, "path": str(out), "clips": len(clips),+ "width": 1024, "height": 576, "sample_rate": 48000,+ "duration": 10.0, "unreadable": []}+ return film++ with mock.patch.object(panel, "_sb_assemble_film", side_effect=fake_assemble):+ res = panel._sb_export(board)+ return res, seen++ def test_shots_reach_the_film_in_n_order_however_the_board_stores_them(self):+ a, b, c = self.clip("a.mp4"), self.clip("b.mp4"), self.clip("c.mp4")+ board = _board([_clip(3, c), _clip(1, a), _clip(2, b)])+ res, seen = self.export(board)+ self.assertEqual([p.name for p in seen["clips"]],+ ["S01_shot-1-happens.mp4", "S02_shot-2-happens.mp4",+ "S03_shot-3-happens.mp4"])+ self.assertEqual(res["files"], [p.name for p in seen["clips"]])++ def test_skipped_shots_are_excluded_from_the_film_and_the_folder(self):+ a, b = self.clip("a.mp4"), self.clip("b.mp4")+ board = _board([_clip(1, a), _clip(2, b, status="skipped")])+ res, seen = self.export(board)+ self.assertEqual(len(seen["clips"]), 1)+ self.assertEqual(seen["clips"][0].name, "S01_shot-1-happens.mp4")+ md = (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8")+ self.assertIn("## Cut", md)+ self.assertIn("**S02**", md)++ def test_a_shot_whose_file_is_gone_is_excluded_from_the_film(self):+ a = self.clip("a.mp4")+ board = _board([_clip(1, a),+ _clip(2, self.src / "vanished.mp4"),+ _clip(3, "")])+ _res, seen = self.export(board)+ self.assertEqual([p.name for p in seen["clips"]],+ ["S01_shot-1-happens.mp4"])++ def test_the_film_is_built_from_the_copies_the_loop_just_made(self):+ # One selection, not two: whatever is in the folder is what is in the+ # film, and the assembler never reads the gallery.+ a = self.clip("a.mp4")+ res, seen = self.export(_board([_clip(1, a)]))+ self.assertEqual(seen["clips"][0].parent, Path(res["dir"]))+ self.assertTrue(seen["clips"][0].is_file())++ def test_delivery_beats_draft_exactly_as_the_copy_loop_decides(self):+ d, f = self.clip("draft.mp4"), self.clip("final.mp4")+ board = _board([_clip(1, d, final_output=str(f))])+ res, seen = self.export(board)+ self.assertEqual(_sha(seen["clips"][0]), _sha(f))+ self.assertIn("| delivery |",+ (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8"))++ def test_source_clips_are_never_modified_or_moved(self):+ a, b = self.clip("a.mp4"), self.clip("b.mp4")+ before = {p: _sha(p) for p in (a, b)}+ self.export(_board([_clip(1, a), _clip(2, b)]))+ for p, digest in before.items():+ self.assertTrue(p.is_file(), f"{p.name} was moved")+ self.assertEqual(_sha(p), digest, f"{p.name} was modified")++ def test_the_film_is_named_after_the_board_and_returned(self):+ a = self.clip("a.mp4")+ res, seen = self.export(_board([_clip(1, a)], title="The Long Walk"))+ self.assertEqual(seen["out"].name, "the-long-walk_film.mp4")+ self.assertEqual(res["film_name"], "the-long-walk_film.mp4")+ self.assertEqual(res["film"], str(seen["out"]))+ self.assertIsNone(res["film_error"])++ def test_the_film_is_listed_in_the_markdown(self):+ a = self.clip("a.mp4")+ res, _ = self.export(_board([_clip(1, a)]))+ md = (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8")+ self.assertIn("**Film:**", md)+ self.assertIn("the-long-walk_film.mp4", md)+ self.assertIn("1024×576", md)++ def test_the_film_is_not_listed_among_the_clips(self):+ a = self.clip("a.mp4")+ res, _ = self.export(_board([_clip(1, a)]))+ self.assertNotIn("the-long-walk_film.mp4", res["files"])++ # ---- the failure contract ------------------------------------------+ def test_a_failed_assembly_still_produces_the_folder_and_the_manifest(self):+ a, b = self.clip("a.mp4"), self.clip("b.mp4")+ res, _ = self.export(_board([_clip(1, a), _clip(2, b)]),+ film={"ok": False, "error": "ffmpeg is not installed"})+ self.assertTrue(res["ok"])+ dest = Path(res["dir"])+ self.assertTrue(dest.is_dir())+ self.assertEqual(len(res["files"]), 2)+ for name in res["files"]:+ self.assertTrue((dest / name).is_file())+ self.assertTrue((dest / "storyboard.md").is_file())+ self.assertEqual(json.loads((dest / "storyboard.json")+ .read_text(encoding="utf-8"))["title"],+ "The Long Walk")++ def test_a_failed_assembly_is_reported_honestly_not_swallowed(self):+ a = self.clip("a.mp4")+ res, _ = self.export(_board([_clip(1, a)]),+ film={"ok": False, "error": "ffmpeg is not installed"})+ self.assertIsNone(res["film"])+ self.assertIsNone(res["film_name"])+ self.assertEqual(res["film_error"], "ffmpeg is not installed")+ md = (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8")+ self.assertIn("not assembled", md)+ self.assertIn("ffmpeg is not installed", md)++ def test_an_assembler_that_RAISES_still_leaves_the_export_intact(self):+ a = self.clip("a.mp4")+ with mock.patch.object(panel, "_sb_assemble_film",+ side_effect=OSError("disk went away")):+ res = panel._sb_export(_board([_clip(1, a)]))+ self.assertTrue(res["ok"])+ self.assertEqual(len(res["files"]), 1)+ self.assertIn("disk went away", res["film_error"])+ self.assertTrue((Path(res["dir"]) / "storyboard.md").is_file())++ def test_a_board_with_nothing_renderable_exports_without_a_film(self):+ board = _board([_clip(1, self.src / "vanished.mp4")])+ with mock.patch.object(panel, "_sb_assemble_film") as m:+ res = panel._sb_export(board)+ m.assert_not_called()+ self.assertTrue(res["ok"])+ self.assertEqual(res["files"], [])+ self.assertIsNone(res["film"])+ self.assertIn("no shots", res["film_error"])++ # ---- the auto-edit is OPT-IN -----------------------------------------+ def test_by_default_the_export_never_even_asks_for_a_plan(self):+ a = self.clip("a.mp4")+ with mock.patch.object(panel, "_sb_plan_auto_edit") as planner, \+ mock.patch.object(panel, "_sb_assemble_film") as asm:+ asm.return_value = {"ok": True, "path": "/x/f.mp4", "clips": 1,+ "width": 640, "height": 448,+ "sample_rate": 48000, "duration": 3.0,+ "unreadable": []}+ res = panel._sb_export(_board([_clip(1, a)]))+ planner.assert_not_called()+ # and the assembler is called EXACTLY as it was before the auto-editor+ # existed — two positional arguments, no keywords.+ self.assertEqual(len(asm.call_args.args), 2)+ self.assertEqual(asm.call_args.kwargs, {})+ self.assertFalse(res["auto_edit"])+ self.assertNotIn("Auto-edited",+ (Path(res["dir"]) / "storyboard.md")+ .read_text(encoding="utf-8"))++ def test_auto_edit_true_plans_and_hands_the_plan_to_the_assembler(self):+ a = self.clip("a.mp4")+ plan = [{"path": "x", "start": 0.0, "end": 2.0, "n": 1,+ "duration": 2.0, "film_start": 0.0, "film_end": 2.0,+ "snap": {"kind": "downbeat", "shift_ms": -12.0},+ "window": {"reason": "because"}, "notes": []}]+ with mock.patch.object(panel, "_sb_plan_auto_edit",+ return_value=(plan, "auto-edit: 1 shots")), \+ mock.patch.object(panel, "_sb_assemble_film") as asm:+ asm.return_value = {"ok": True, "path": "/x/f.mp4", "clips": 1,+ "width": 640, "height": 448,+ "sample_rate": 48000, "duration": 2.0,+ "unreadable": []}+ res = panel._sb_export(_board([_clip(1, a)]), auto_edit=True,+ music="/x/song.mp3", target_seconds=60.0)+ self.assertIs(asm.call_args.kwargs["plan"], plan)+ self.assertEqual(asm.call_args.kwargs["music"], "/x/song.mp3")+ self.assertTrue(res["auto_edit"])+ md = (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8")+ self.assertIn("## The edit", md)+ self.assertIn("1 of 1 cuts landed on the beat", md)+ self.assertIn("because", md)+ self.assertEqual(json.loads((Path(res["dir"]) / "storyboard_edit.json")+ .read_text(encoding="utf-8")), plan)++ def test_an_auto_edit_that_cannot_run_falls_back_to_whole_clips(self):+ # A missing or broken storyboard_edit.py costs you the auto-edit, not+ # the export — and it says so in the manifest.+ a = self.clip("a.mp4")+ with mock.patch.object(panel, "_sb_plan_auto_edit",+ return_value=(None, "auto-edit unavailable "+ "(ImportError: no numpy)")), \+ mock.patch.object(panel, "_sb_assemble_film") as asm:+ asm.return_value = {"ok": True, "path": "/x/f.mp4", "clips": 1,+ "width": 640, "height": 448,+ "sample_rate": 48000, "duration": 5.0,+ "unreadable": []}+ res = panel._sb_export(_board([_clip(1, a)]), auto_edit=True)+ self.assertEqual(asm.call_args.kwargs, {}) # the old call, exactly+ self.assertTrue(res["ok"])+ self.assertFalse(res["auto_edit"])+ md = (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8")+ self.assertIn("Whole clips", md)+ self.assertIn("no numpy", md)++ def test_a_planner_that_raises_is_caught_at_the_seam(self):+ with mock.patch.dict("sys.modules", {"storyboard_edit": None}):+ plan, note = panel._sb_plan_auto_edit(["/x/a.mp4"])+ self.assertIsNone(plan)+ self.assertIn("auto-edit unavailable", note)++ def test_unreadable_clips_are_named_in_the_markdown(self):+ a = self.clip("a.mp4")+ res, _ = self.export(_board([_clip(1, a)]),+ film={"ok": True, "path": "/x/f.mp4", "clips": 1,+ "width": 640, "height": 448,+ "sample_rate": 48000, "duration": 3.0,+ "unreadable": ["S02_torn.mp4"]})+ md = (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8")+ self.assertIn("S02_torn.mp4", md)+++# =============================================================================+# Stop — the shot in flight is cancelled, through the panel's own path+# =============================================================================+# =============================================================================+# ONE ASSEMBLER — Export renders the CUT when there is one+# =============================================================================+class ExportDelegatesToTheTimeline(unittest.TestCase):+ """Two buttons that both said "make the film" made two different films.++ Export wrote `<slug>_film.mp4` from a second auto-editor over its own+ copies; the Editor's Render wrote `<slug>_timeline.mp4` from the cut, with+ the soundtrack. Same folder, same board, different files — and the Film+ screen could only tell them apart by a chip naming the button you pressed.+ Now: one name, and the human's arrangement wins whenever there is one.+ """++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.addCleanup(self.tmp.cleanup)+ self.state = self.root / "state"+ self.out = self.root / "out"+ self.state.mkdir()+ self.src = self.root / "gallery"+ self.src.mkdir()+ for pt in (mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None)):+ pt.start()+ self.addCleanup(pt.stop)+ self.a = _write_fake_clip(self.src / "a.mp4", b"a" * 64)+ self.b = _write_fake_clip(self.src / "b.mp4", b"b" * 64)+ self.board = _board([_clip(1, self.a), _clip(2, self.b)],+ id="sb_one_assembler")+ storyboard.save_storyboard(self.state, self.board)+ self.bdir = storyboard.board_dir(self.state, "sb_one_assembler")++ def save_edit(self, audio=None):+ import storyboard_editor as sedit+ clips = [sedit.new_clip(self.a, 1.0, 3.0, 0.0),+ sedit.new_clip(self.b, 0.5, 2.5, 2.0)]+ sedit.save_edit(self.bdir, {"version": sedit.EDIT_VERSION,+ "board_id": "sb_one_assembler",+ "revision": 0, "source": "human",+ "audio": audio, "beats": None,+ "clips": clips, "settings": {}})++ def export(self, **kw):+ seen = {}++ def fake_assemble(clips, out, **akw):+ seen["clips"] = [Path(c) for c in clips]+ seen["out"] = Path(out)+ seen.update(akw)+ Path(out).write_bytes(b"film")+ return {"ok": True, "path": str(out), "clips": len(clips),+ "width": 1024, "height": 576, "sample_rate": 48000,+ "duration": 10.0, "unreadable": []}++ board = storyboard.load_storyboard(self.state, "sb_one_assembler")+ with mock.patch.object(panel, "_sb_assemble_film",+ side_effect=fake_assemble):+ res = panel._sb_export(board, **kw)+ return res, seen++ def test_with_no_timeline_export_is_exactly_what_it_always_was(self):+ res, seen = self.export()+ self.assertTrue(res["ok"])+ # The copies in the folder, whole, in `n` order — the old behaviour.+ self.assertEqual([p.name for p in seen["clips"]],+ ["S01_shot-1-happens.mp4", "S02_shot-2-happens.mp4"])+ self.assertIsNone(seen.get("plan"))+ self.assertEqual(seen["out"].name, "the-long-walk_film.mp4")++ def test_with_a_timeline_export_renders_the_CUT(self):+ self.save_edit()+ res, seen = self.export()+ self.assertTrue(res["ok"])+ # The SOURCES, not the copies — the cut points at the gallery files,+ # and the plan carries the windows the human trimmed.+ self.assertEqual([p.name for p in seen["clips"]], ["a.mp4", "b.mp4"])+ # `timeline=`, not `plan=` (Wave 2). A cut list is the only shape that+ # can hold a slug — which has no path and therefore cannot appear in+ # the `clips` argument at all — so the timeline door stopped passing a+ # plan the moment black became a kind of clip.+ self.assertIsNone(seen.get("plan"))+ plan = seen["timeline"]+ self.assertEqual(len(plan), 2)+ self.assertAlmostEqual(plan[0]["start"], 1.0)+ self.assertAlmostEqual(plan[0]["end"], 3.0)+ self.assertAlmostEqual(plan[1]["film_start"], 2.0)++ def test_both_doors_write_the_same_name(self):+ # The whole "two films in one folder" finding, in one assertion.+ self.save_edit()+ _res, seen = self.export()+ self.assertEqual(seen["out"].name, panel._sb_film_name(self.board))+ self.assertEqual(seen["out"].name, "the-long-walk_film.mp4")+ self.assertNotIn("_timeline", seen["out"].name)++ def test_the_soundtrack_reaches_the_film_from_either_door(self):+ # Export posted `id` and nothing else, so a film scored in the Editor+ # came out of this door silent.+ track = self.src / "bed.wav"+ track.write_bytes(b"RIFF")+ self.save_edit(audio={"path": str(track), "offset": 0.0,+ "mode": "under"})+ _res, seen = self.export()+ self.assertEqual(seen["music"], str(track))+ self.assertEqual(seen["music_mode"], "under")++ def test_an_explicit_music_mode_beats_the_edits_own(self):+ track = self.src / "bed.wav"+ track.write_bytes(b"RIFF")+ self.save_edit(audio={"path": str(track), "offset": 0.0,+ "mode": "under"})+ _res, seen = self.export(music_mode="replace")+ self.assertEqual(seen["music_mode"], "replace")++ def test_the_manifest_says_the_film_came_from_the_timeline(self):+ self.save_edit()+ res, _ = self.export()+ md = (Path(res["dir"]) / "storyboard.md").read_text(encoding="utf-8")+ self.assertIn("Assembled from the timeline in the Editor", md)+ # The folder and the shot list are unchanged — only who assembled the+ # film changed.+ self.assertEqual(len(res["files"]), 2)+ self.assertIn("| # | file | length | seed | pass | prompt |", md)++ def test_an_empty_timeline_does_not_hijack_the_export(self):+ import storyboard_editor as sedit+ sedit.save_edit(self.bdir, {"version": sedit.EDIT_VERSION,+ "board_id": "sb_one_assembler",+ "revision": 0, "source": "auto",+ "audio": None, "beats": None,+ "clips": [], "settings": {}})+ _res, seen = self.export()+ self.assertEqual([p.name for p in seen["clips"]],+ ["S01_shot-1-happens.mp4", "S02_shot-2-happens.mp4"])+++class StopCancelsTheRunningShot(unittest.TestCase):+ def _cancel(self, current, ids):+ with mock.patch.dict(panel.STATE, {"current": current}, clear=False), \+ mock.patch.object(panel, "stop_current_job") as killer:+ got = panel._sb_cancel_running_shot(ids)+ return got, killer++ def test_the_running_shot_of_THIS_film_is_cancelled(self):+ got, killer = self._cancel({"id": "j-abc-001"}, {"j-abc-001", "j-abc-002"})+ self.assertEqual(got, "j-abc-001")+ killer.assert_called_once_with()++ def test_it_reuses_the_panels_cancel_path_instead_of_inventing_one(self):+ # stop_current_job() is what POST /stop calls; it is what sets+ # cancel_requested, and therefore what makes the job land as+ # "cancelled" (a state _sb_reconcile already folds onto the shot)+ # rather than "failed". A second, storyboard-only kill would skip that+ # flag and every process group stop_current_job knows about, so the+ # function must contain no killing of its own.+ import inspect # noqa: PLC0415+ src = inspect.getsource(panel._sb_cancel_running_shot)+ self.assertIn("stop_current_job()", src)+ for invented in ("killpg", "HELPER.kill", "SIGTERM", "SIGKILL",+ "terminate("):+ self.assertNotIn(invented, src,+ "Stop must not grow a second cancellation path")++ def test_another_features_job_is_never_collateral(self):+ got, killer = self._cancel({"id": "j-image-999"}, {"j-abc-001"})+ self.assertIsNone(got)+ killer.assert_not_called()++ def test_nothing_running_means_nothing_killed(self):+ for current in (None, {}, {"id": None}):+ got, killer = self._cancel(current, {"j-abc-001"})+ self.assertIsNone(got)+ killer.assert_not_called()++ def test_a_film_with_no_job_ids_kills_nothing(self):+ for ids in (set(), None, []):+ got, killer = self._cancel({"id": "j-abc-001"}, ids)+ self.assertIsNone(got)+ killer.assert_not_called()++ def test_a_cancelled_job_lands_in_a_state_the_reconciler_understands(self):+ # The worker writes status="cancelled" when cancel_requested is set+ # (see the run_job except branch). _sb_reconcile must already fold+ # that onto the shot — this is the contract Stop now depends on.+ shot = {"n": 1, "draft_job_id": "j-1", "status": "rendering"}+ board = {"shots": [shot]}+ with mock.patch.object(panel, "_sb_job_index",+ return_value={"j-1": {"status": "cancelled",+ "output_path": None,+ "error": "Job cancelled."}}):+ changed = panel._sb_reconcile(board)+ self.assertTrue(changed)+ self.assertEqual(shot["status"], "failed")+ self.assertEqual(shot["error"], "Job cancelled.")+++# =============================================================================+# End-to-end with a REAL ffmpeg — two lavfi patterns, no GPU, no weights+# =============================================================================[email protected](Path(panel.FFMPEG).is_file() and Path(panel.FFPROBE).is_file(),+ "needs a real ffmpeg + ffprobe")+class RealAssembly(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)+ self.addCleanup(self.tmp.cleanup)++ def _make(self, name, w, h, seconds, *, audio_rate=None):+ out = self.dir / name+ cmd = [str(panel.FFMPEG), "-y", "-f", "lavfi",+ "-i", f"testsrc=size={w}x{h}:rate=24:duration={seconds}"]+ if audio_rate:+ cmd += ["-f", "lavfi",+ "-i", f"sine=frequency=440:sample_rate={audio_rate}:"+ f"duration={seconds}"]+ cmd += ["-c:v", "libx264", "-pix_fmt", "yuv420p"]+ if audio_rate:+ cmd += ["-c:a", "aac", "-shortest"]+ cmd += [str(out)]+ subprocess.run(cmd, capture_output=True, check=True, timeout=120)+ return out++ def test_mixed_geometry_and_a_silent_clip_join_into_one_film(self):+ loud = self._make("loud.mp4", 320, 240, 1, audio_rate=44100)+ silent = self._make("silent.mp4", 640, 360, 2)+ before = {p: _sha(p) for p in (loud, silent)}++ with mock.patch.object(panel, "output_codec_settings",+ return_value={"preset": "standard",+ "pix_fmt": "yuv420p", "crf": "23"}):+ res = panel._sb_assemble_film([loud, silent], self.dir / "film.mp4")++ self.assertTrue(res["ok"], res.get("error"))+ self.assertEqual((res["width"], res["height"]), (640, 360))++ film = Path(res["path"])+ probe = json.loads(subprocess.run(+ [str(panel.FFPROBE), "-v", "error", "-show_entries",+ "stream=codec_type,width,height,pix_fmt,nb_frames:format=duration",+ "-of", "json", str(film)],+ capture_output=True, text=True, timeout=60).stdout)+ streams = probe["streams"]+ self.assertEqual(sum(1 for s in streams if s["codec_type"] == "video"), 1)+ self.assertEqual(sum(1 for s in streams if s["codec_type"] == "audio"), 1)+ video = next(s for s in streams if s["codec_type"] == "video")+ self.assertEqual((video["width"], video["height"]), (640, 360))+ self.assertEqual(video["pix_fmt"], "yuv420p")+ # ~3 s = the two clips end to end, not one of them and not both halves.+ self.assertAlmostEqual(float(probe["format"]["duration"]),+ res["duration"], delta=0.15)+ self.assertAlmostEqual(int(video["nb_frames"]),+ res["duration"] * panel.FPS, delta=2)++ # +faststart, via the release gate's own box walk.+ import scripts.check_output_codec as gate # noqa: PLC0415+ self.assertIs(gate.has_faststart(film), True)++ for p, digest in before.items():+ self.assertEqual(_sha(p), digest, f"{p.name} was modified")++ def _probe_json(self, path, entries):+ return json.loads(subprocess.run(+ [str(panel.FFPROBE), "-v", "error", "-show_entries", entries,+ "-of", "json", str(path)],+ capture_output=True, text=True, timeout=60).stdout)++ def test_a_planned_cut_really_is_only_the_windows_that_were_chosen(self):+ a = self._make("a.mp4", 320, 240, 4, audio_rate=48000)+ b = self._make("b.mp4", 320, 240, 4, audio_rate=48000)+ plan = [{"path": str(a), "start": 0.5, "end": 2.0},+ {"path": str(b), "start": 1.0, "end": 2.0}]+ before = {p: _sha(p) for p in (a, b)}++ with mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "23"}):+ res = panel._sb_assemble_film([a, b], self.dir / "cut.mp4",+ plan=plan)+ self.assertTrue(res["ok"], res.get("error"))+ self.assertAlmostEqual(res["duration"], 2.5, places=3)+ probe = self._probe_json(res["path"],+ "stream=codec_type,nb_frames:format=duration")+ # 2.5 s, not the 8 s the two source clips hold.+ self.assertAlmostEqual(float(probe["format"]["duration"]), 2.5,+ delta=0.12)+ video = next(s for s in probe["streams"] if s["codec_type"] == "video")+ self.assertAlmostEqual(int(video["nb_frames"]), 2.5 * panel.FPS,+ delta=2)+ for p, digest in before.items():+ self.assertEqual(_sha(p), digest, f"{p.name} was modified")++ def test_the_trim_takes_the_window_it_was_asked_for_frame_for_frame(self):+ # `testsrc` writes its own frame counter into the picture, so "did the+ # trim start where the plan said" is answerable by comparing pixels+ # rather than by trusting the container's duration.+ src = self._make("counter.mp4", 320, 240, 5)+ plan = [{"path": str(src), "start": 2.0, "end": 4.0}]+ with mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "23"}):+ res = panel._sb_assemble_film([src], self.dir / "trim.mp4",+ plan=plan)+ self.assertTrue(res["ok"], res.get("error"))++ def grab(path, t):+ out = subprocess.run(+ [str(panel.FFMPEG), "-v", "error", "-ss", f"{t:.3f}",+ "-i", str(path), "-frames:v", "1", "-vf",+ "scale=64:48,format=gray", "-f", "rawvideo",+ "-pix_fmt", "gray", "-"],+ capture_output=True, timeout=60).stdout+ return bytearray(out[:64 * 48])++ def diff(x, y):+ return sum(abs(p - q) for p, q in zip(x, y)) / max(1, len(x))++ # Where in the SOURCE does the film's half-second mark come from? Scan+ # the whole source and take the best match — an absolute threshold+ # would only be measuring how fast `testsrc` moves.+ film_at_0_5 = grab(res["path"], 0.5)+ scan = [(diff(film_at_0_5, grab(src, k / panel.FPS)), k / panel.FPS)+ for k in range(0, 5 * panel.FPS)]+ best = min(scan)[1]+ self.assertAlmostEqual(best, 2.5, delta=2.5 / panel.FPS,+ msg=f"the trim landed at {best:.3f}s, not 2.5s")+ # ...and 0.5 s into the SOURCE is emphatically not the answer.+ self.assertLess(min(scan)[0], diff(film_at_0_5, grab(src, 0.5)))++ def test_a_soundtrack_replaces_the_clip_audio_end_to_end(self):+ clip = self._make("loud.mp4", 320, 240, 4, audio_rate=48000)+ song = self.dir / "song.wav"+ subprocess.run(+ [str(panel.FFMPEG), "-y", "-f", "lavfi",+ "-i", "sine=frequency=110:sample_rate=44100:duration=10",+ str(song)], capture_output=True, check=True, timeout=120)+ plan = [{"path": str(clip), "start": 0.0, "end": 2.0}]+ with mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "23"}):+ res = panel._sb_assemble_film([clip], self.dir / "scored.mp4",+ plan=plan, music=song)+ self.assertTrue(res["ok"], res.get("error"))+ self.assertEqual(res["sample_rate"], 44100)+ probe = self._probe_json(res["path"],+ "stream=codec_type,sample_rate:format=duration")+ audio = next(s for s in probe["streams"] if s["codec_type"] == "audio")+ self.assertEqual(audio["sample_rate"], "44100")+ # The film is 2 s long even though the song is 10 s: the soundtrack is+ # trimmed to the CUT, never the other way round.+ self.assertAlmostEqual(float(probe["format"]["duration"]), 2.0,+ delta=0.12)+++# =============================================================================+# The Export button itself — the real sbExport(), run in node+# =============================================================================+SB_EXPORT_SHIM = r"""+const CALLS = { toasts: [], fetches: [], states: [], landed: [] };+function node() {+ return { textContent: 'Export', disabled: false, dataset: {}, onclick: null };+}+const BTN = node();+function sbEl(id) { return BTN; }+const SB = { id: 'sb_1' };+function phosToast(msg, opts) { CALLS.toasts.push({ msg: String(msg), opts: opts || {} }); }+// Where a successful export now ENDS: on the film it made. Stubbed, because+// what is under test here is that the export goes there at all — the screen+// itself is locked by test_storyboard_film.py.+function sbFilmOpen(opts) { CALLS.landed.push(opts || {}); }+class URLSearchParams { constructor() { this.v = {}; } set(k, x) { this.v[k] = x; } }+let RESPONSE = null;+async function fetch(url) {+ CALLS.fetches.push(url);+ // Snapshot the button WHILE the request is in flight — this is the state a+ // second, impatient click would meet.+ CALLS.states.push({ busy: BTN.dataset.busy, disabled: BTN.disabled,+ label: BTN.textContent });+ return { json: async () => RESPONSE };+}+__SB_EXPORT__+async function main() {+ RESPONSE = JSON.parse(process.argv[2]);+ await sbExport();+ console.log(JSON.stringify({ toasts: CALLS.toasts, fetches: CALLS.fetches,+ states: CALLS.states, landed: CALLS.landed,+ after: { busy: BTN.dataset.busy,+ disabled: BTN.disabled,+ label: BTN.textContent } }));+}+main();+"""++[email protected](NODE, "needs node")+class ExportButton(unittest.TestCase):+ """The real client function, executed — not grepped."""++ @classmethod+ def setUpClass(cls):+ cls.script = SB_EXPORT_SHIM.replace("__SB_EXPORT__",+ extract_function("sbExport"))++ def run_export(self, response: dict) -> dict:+ with tempfile.TemporaryDirectory() as tmp:+ js = Path(tmp) / "sbexport.mjs"+ js.write_text(self.script, encoding="utf-8")+ proc = subprocess.run([NODE, str(js), json.dumps(response)],+ capture_output=True, text=True, timeout=60)+ self.assertEqual(proc.returncode, 0, proc.stderr)+ return json.loads(proc.stdout.strip().splitlines()[-1])++ OK = {"ok": True, "dir": "/out/sb", "files": ["S01.mp4", "S02.mp4"],+ "film": "/out/sb/x_film.mp4", "film_name": "x_film.mp4",+ "film_error": None, "film_duration": 22.375}+ NO_FILM = {"ok": True, "dir": "/out/sb", "files": ["S01.mp4"],+ "film": None, "film_name": None,+ "film_error": "ffmpeg is not installed", "film_duration": None}++ def test_a_finished_film_is_named_in_the_success_toast(self):+ got = self.run_export(self.OK)+ self.assertEqual(len(got["toasts"]), 1)+ toast = got["toasts"][0]+ self.assertEqual(toast["opts"]["kind"], "success")+ self.assertIn("x_film.mp4", toast["msg"])+ self.assertIn("22 s", toast["msg"])++ def test_a_failed_assembly_is_a_note_on_a_successful_export(self):+ # NOT a danger toast and NOT a silent success: the folder really did+ # land, and the reason the film didn't has to reach the user.+ got = self.run_export(self.NO_FILM)+ toast = got["toasts"][0]+ self.assertNotEqual(toast["opts"].get("kind"), "danger")+ self.assertIn("could not be assembled", toast["msg"])+ self.assertIn("ffmpeg is not installed", toast["msg"])+ self.assertIn("Exported 1 clips", toast["msg"])++ def test_the_button_is_held_shut_while_the_encode_runs(self):+ # Export was instant before it also encoded a film; a second click+ # would start a second ffmpeg writing the same file.+ got = self.run_export(self.OK)+ inflight = got["states"][0]+ self.assertEqual(inflight["busy"], "1")+ self.assertTrue(inflight["disabled"])+ self.assertEqual(inflight["label"], "Assembling…")++ def test_the_button_is_released_even_when_the_request_fails(self):+ got = self.run_export({"ok": False, "error": "boom"})+ self.assertFalse(got["after"]["disabled"])+ self.assertNotEqual(got["after"]["busy"], "1")+ self.assertEqual(got["toasts"][0]["opts"]["kind"], "danger")++ def test_a_successful_export_ENDS_ON_THE_FILM_IT_MADE(self):+ # A toast that fades is what made the finished film invisible: the+ # panel wrote a film, said so for eight seconds, and left the user on a+ # list of individual shots wondering which one was the movie.+ got = self.run_export(self.OK)+ self.assertEqual(got["landed"], [{"focus": "x_film.mp4"}])++ def test_an_export_with_no_film_does_not_send_you_to_a_film_screen(self):+ got = self.run_export(self.NO_FILM)+ self.assertEqual(got["landed"], [])+++if __name__ == "__main__":+ unittest.main()+++class ImportShotsBetweenFilms(unittest.TestCase):+ """A board is a timeline one-to-one, and coverage is not.++ Owner, holding a film in one board and its B-roll in another: "can you make+ a project with all the clips? … If you create two different project+ timelines, how can you storyboard? How can you move from one to the other?"+ Before this there was no answer but rendering them again.+ """++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)+ self.clips = []+ for i in range(3):+ p = self.root / f"c{i}.mp4"+ p.write_bytes(b"x")+ self.clips.append(str(p))++ def _board(self, bid, shots, **kw):+ b = {"id": bid, "title": bid, "shots": shots}+ b.update(kw)+ return b++ def _shot(self, n, path=None, **kw):+ s = {"n": n, "title": f"shot {n}", "mode": "text", "status": "done"}+ if path:+ s["final_output"] = path+ s.update(kw)+ return s++ def test_rendered_shots_come_across_and_are_renumbered(self):+ dst = self._board("a", [self._shot(1, self.clips[0])])+ src = self._board("b", [self._shot(1, self.clips[1]),+ self._shot(2, self.clips[2])])+ got, skipped = panel._sb_import_shots(dst, src)+ self.assertEqual([g["n"] for g in got], [2, 3])+ self.assertEqual(len(dst["shots"]), 3)+ self.assertEqual(skipped, [])++ def test_the_clip_is_referenced_not_copied(self):+ # An import must cost a JSON edit and no render time.+ dst = self._board("a", [])+ src = self._board("b", [self._shot(1, self.clips[0])])+ panel._sb_import_shots(dst, src)+ self.assertEqual(dst["shots"][0]["final_output"], self.clips[0])++ def test_provenance_stays_on_the_shot(self):+ # Otherwise an imported clip is indistinguishable from one this film+ # planned, and a re-plan silently rewrites somebody else's shot.+ dst = self._board("a", [])+ src = self._board("b", [self._shot(1, self.clips[0])], title="B-roll")+ panel._sb_import_shots(dst, src)+ self.assertEqual(dst["shots"][0]["imported_from"],+ {"board": "b", "n": 1, "title": "B-roll"})++ def test_a_shot_that_never_rendered_is_skipped_not_imported(self):+ dst = self._board("a", [])+ src = self._board("b", [self._shot(1), self._shot(2, self.clips[0])])+ got, skipped = panel._sb_import_shots(dst, src)+ self.assertEqual(len(got), 1)+ self.assertEqual(skipped, [{"n": 1, "why": "not rendered yet"}])++ def test_importing_twice_does_not_duplicate(self):+ dst = self._board("a", [])+ src = self._board("b", [self._shot(1, self.clips[0])])+ panel._sb_import_shots(dst, src)+ got, skipped = panel._sb_import_shots(dst, src)+ self.assertEqual(got, [])+ self.assertEqual(skipped, [{"n": 1, "why": "already here"}])+ self.assertEqual(len(dst["shots"]), 1)++ def test_only_selects_a_subset(self):+ dst = self._board("a", [])+ src = self._board("b", [self._shot(1, self.clips[0]),+ self._shot(2, self.clips[1]),+ self._shot(3, self.clips[2])])+ got, _ = panel._sb_import_shots(dst, src, only={2})+ self.assertEqual(len(got), 1)+ self.assertEqual(dst["shots"][0]["final_output"], self.clips[1])++ def test_the_location_comes_with_the_shot(self):+ # An imported shot pointing at a location this board has never heard of+ # is `unknown_location`, which correctly refuses to render — turning a+ # successful import into an unrenderable film.+ loc = {"id": "carwash", "name": "The car wash", "description": "a driveway"}+ dst = self._board("a", [], locations=[])+ src = self._board("b", [self._shot(1, self.clips[0], location_id="carwash")],+ locations=[loc])+ panel._sb_import_shots(dst, src)+ self.assertIn("carwash", [l["id"] for l in dst["locations"]])++ def test_a_location_already_present_is_not_duplicated(self):+ loc = {"id": "carwash", "name": "The car wash", "description": "a driveway"}+ dst = self._board("a", [], locations=[dict(loc)])+ src = self._board("b", [self._shot(1, self.clips[0])], locations=[loc])+ panel._sb_import_shots(dst, src)+ self.assertEqual(len(dst["locations"]), 1)++ def test_the_cast_comes_too_so_wardrobe_survives(self):+ cast = [{"id": "ariatrn", "trigger": "ariatrn", "wardrobe": "a red bikini"}]+ dst = self._board("a", [], cast=[])+ src = self._board("b", [self._shot(1, self.clips[0])], cast=cast)+ panel._sb_import_shots(dst, src)+ self.assertEqual(dst["cast"][0]["wardrobe"], "a red bikini")+++# =============================================================================+# WAVE 2 — stills, slugs, brightness, and the input-index refactor+# =============================================================================+class SegmentIndexIsNotInputIndex(unittest.TestCase):+ """The refactor the two new kinds cost, pinned in both directions.++ Until a clip could be black, segment index WAS ffmpeg input index: one+ `-i` per probe, in probe order, and the soundtrack addressed as+ `len(probes)`. A slug consumes NO input (`color=` is a source filter); a+ still consumes one, but through `-loop 1 -framerate F -t D` and never+ through ffprobe. So every input after the first slug shifts, and a film+ whose sound is one shot late is what a wrong answer here looks like.+ """++ TIMELINE = [+ {"path": "/x/a.mp4", "start": 0.0, "end": 2.0, "film_start": 0.0},+ {"path": None, "kind": "slug", "start": 0.0, "end": 1.5,+ "film_start": 2.0},+ {"path": "/x/card.png", "kind": "still", "start": 0.0, "end": 3.0,+ "film_start": 3.5},+ {"path": "/x/b.mp4", "start": 1.0, "end": 4.0, "film_start": 6.5},+ ]++ def segments(self, timeline=None):+ with mock.patch.object(panel, "_sb_probe_clip",+ side_effect=lambda p: _probe(1024, 576, 10.0)), \+ mock.patch.object(panel, "_sb_probe_still",+ side_effect=lambda p: {"w": 1920, "h": 1080,+ "duration": 0.0,+ "has_audio": False,+ "sample_rate": 0}):+ return panel._sb_timeline_segments(timeline or self.TIMELINE)++ def test_only_the_segments_with_a_file_get_an_input_index(self):+ segs, unreadable, inputs = self.segments()+ self.assertEqual([s["kind"] for s in segs],+ ["video", "slug", "still", "video"])+ # THE ASSERTION THIS CLASS EXISTS FOR: the slug is None, and the two+ # segments after it are 1 and 2, not 2 and 3.+ self.assertEqual([s["input"] for s in segs], [0, None, 1, 2])+ self.assertEqual(len(inputs), 3)+ self.assertEqual(unreadable, [])++ def test_a_still_is_looped_to_its_slot_and_a_slug_is_not_an_input(self):+ _segs, _unreadable, inputs = self.segments()+ self.assertEqual(inputs[0], ["-i", "/x/a.mp4"])+ # `-loop 1` WITHOUT `-t` runs until the disk is full.+ self.assertEqual(inputs[1], ["-loop", "1", "-framerate", str(panel.FPS),+ "-t", "3.000000", "-i", "/x/card.png"])+ self.assertEqual(inputs[2], ["-i", "/x/b.mp4"])+ self.assertNotIn(["-i", None], inputs)++ def test_the_graph_addresses_the_inputs_the_argv_will_actually_pass(self):+ segs, _u, inputs = self.segments()+ g, _label = panel._sb_film_filtergraph(+ [], 1920, 1080, 48000, "yuv420p", segments=segs)+ self.assertIn("[0:v]trim=start=0.000000:end=2.000000", g)+ self.assertIn("color=c=black:s=1920x1080", g)+ self.assertIn("[1:v]trim=0:3.000000", g) # the still, not [2:v]+ self.assertIn("[2:v]trim=start=1.000000:end=4.000000", g)+ # Four segments, three inputs. Both numbers appear, and they differ.+ self.assertIn("concat=n=4:v=1:a=1[vcat][aout]", g)+ self.assertEqual(len(inputs), 3)++ def test_the_soundtrack_is_the_input_after_the_last_one_that_exists(self):+ segs, _u, inputs = self.segments()+ for mode in ("replace", "under"):+ g, _l = panel._sb_film_filtergraph(+ [], 1920, 1080, 48000, "yuv420p", segments=segs,+ music={"path": "/x/song.mp3", "start": 0.0, "mode": mode})+ # THREE inputs, so the music is [3:a] — not [4:a], which is what+ # counting segments instead of inputs would have produced.+ self.assertIn("[3:a]atrim=start=0.000000", g, mode)+ self.assertNotIn("[4:a]atrim", g, mode)+ self.assertEqual(len(inputs), 3)++ def test_an_unreadable_still_is_dropped_and_the_indices_close_up(self):+ with mock.patch.object(panel, "_sb_probe_clip",+ side_effect=lambda p: _probe(1024, 576, 10.0)), \+ mock.patch.object(panel, "_sb_probe_still", return_value=None):+ segs, unreadable, inputs = panel._sb_timeline_segments(self.TIMELINE)+ self.assertEqual(unreadable, ["card.png"])+ self.assertEqual([s["kind"] for s in segs], ["video", "slug", "video"])+ self.assertEqual([s["input"] for s in segs], [0, None, 1])+ self.assertEqual(len(inputs), 2)++ def test_a_slug_needs_no_probe_at_all(self):+ # No file, no ffprobe, no proxy — the cheapest of the three kinds is+ # also the one that forced the refactor.+ with mock.patch.object(panel, "_sb_probe_clip") as pc, \+ mock.patch.object(panel, "_sb_probe_still") as ps:+ segs, _u, inputs = panel._sb_timeline_segments(+ [{"path": None, "kind": "slug", "start": 0.0, "end": 2.0,+ "film_start": 0.0}])+ pc.assert_not_called()+ ps.assert_not_called()+ self.assertEqual(inputs, [])+ self.assertEqual(segs[0]["input"], None)+ self.assertEqual(segs[0]["duration"], 2.0)+++class StillsAndSlugsInTheGraph(unittest.TestCase):+ def graph(self, segments, **kw):+ return panel._sb_film_filtergraph([], 1024, 576, 48000, "yuv420p",+ segments=segments, **kw)[0]++ def slug(self, dur=2.0, **kw):+ return dict({"kind": "slug", "input": None, "info": None,+ "window": None, "adjust": None, "duration": dur}, **kw)++ def still(self, dur=3.0, inp=0, **kw):+ return dict({"kind": "still", "input": inp,+ "info": {"w": 1920, "h": 1080, "duration": 0.0,+ "has_audio": False, "sample_rate": 0},+ "window": None, "adjust": None, "duration": dur}, **kw)++ def test_a_slug_is_a_colour_source_at_the_films_own_geometry(self):+ g = self.graph([self.slug(2.0)])+ self.assertIn("color=c=black:s=1024x576:r=24:d=2.000000,"+ "setsar=1,format=yuv420p[v0]", g)+ # No scale, no pad: `color` already emits the target size, so both+ # would be filters that do nothing to every frame of the slug.+ self.assertNotIn("scale=1024:576", g)++ def test_a_slug_is_silent_by_construction_not_by_accident(self):+ # An uneven audio-stream count and ffmpeg refuses to build the graph.+ g = self.graph([self.slug(2.0)])+ self.assertIn("anullsrc=channel_layout=stereo:sample_rate=48000:"+ "d=2.000000[a0]", g)+ self.assertIn("concat=n=1:v=1:a=1", g)++ def test_a_still_gets_the_same_normalisation_every_other_segment_gets(self):+ g = self.graph([self.still(3.0)])+ self.assertIn("[0:v]trim=0:3.000000,setpts=PTS-STARTPTS,fps=24,"+ "scale=1024:576:force_original_aspect_ratio=decrease,"+ "pad=1024:576:(ow-iw)/2:(oh-ih)/2,setsar=1,"+ "format=yuv420p[v0]", g)+ self.assertIn("anullsrc=channel_layout=stereo:sample_rate=48000:"+ "d=3.000000[a0]", g)++ def test_a_film_of_nothing_but_black_still_assembles(self):+ g = self.graph([self.slug(1.0), self.slug(2.0)])+ self.assertIn("concat=n=2:v=1:a=1[vcat][aout]", g)+ self.assertEqual(g.count("color=c=black"), 2)++ def test_the_under_mix_path_is_untouched_by_the_new_kinds(self):+ # There are tests pinning this mix and there is a measured reason for+ # every term in it. A slug in the timeline must not change one.+ segs = [self.still(3.0), self.slug(1.0)]+ g = self.graph(segs, music={"path": "/x/s.mp3", "start": 0.0,+ "mode": "under",+ "gain": [[0.0, 0.2], [4.0, 0.2]]})+ self.assertIn("[bed]", g)+ self.assertIn("volume=volume='", g)+ self.assertIn("[acat][bed]amix=inputs=2:duration=first:"+ "dropout_transition=0:"+ f"normalize=0,asoftclip=type=tanh:"+ f"threshold={panel._sb_mix_ceiling():g}[aout]", g)+ # `under` keeps the segments' own audio, so the silence they carry is+ # what the bed ducks against — the bed must not become the only sound.+ self.assertIn("[v0][a0][v1][a1]concat=n=2:v=1:a=1[vcat][acat]", g)++ def test_music_replace_still_drops_every_segments_audio(self):+ g = self.graph([self.still(3.0), self.slug(1.0)],+ music={"path": "/x/s.mp3", "start": 0.0,+ "mode": "replace"})+ self.assertIn("concat=n=2:v=1:a=0[vcat]", g)+ self.assertNotIn("anullsrc", g)+ self.assertIn("[1:a]atrim=start=0.000000", g) # one input: the still+++class BrightnessIsOneTermOrNoTerm(unittest.TestCase):+ PROBES = [(Path("/x/S01.mp4"), _probe(1024, 576, 5.0)),+ (Path("/x/S02.mp4"), _probe(1024, 576, 5.0))]++ def test_a_neutral_clip_adds_no_filter_at_all(self):+ # NOT `eq=brightness=0.000000`. That would change the graph of every+ # film ever exported in order to express nothing, and would break the+ # byte-for-byte default this suite pins two classes up.+ for adjust in (None, {}, {"brightness": 0}, {"brightness": 0.0},+ {"brightness": "nonsense"}, {"brightness": None},+ "not a dict"):+ self.assertEqual(panel._sb_brightness_term(adjust), "",+ repr(adjust))++ def test_a_graded_clip_gets_one_eq_term_before_the_format(self):+ self.assertEqual(panel._sb_brightness_term({"brightness": 0.25}),+ "eq=brightness=0.250000,")+ self.assertEqual(panel._sb_brightness_term({"brightness": -0.125}),+ "eq=brightness=-0.125000,")++ def test_the_term_is_clamped_to_what_the_validator_allows(self):+ self.assertEqual(panel._sb_brightness_term({"brightness": 9}),+ "eq=brightness=0.500000,")+ self.assertEqual(panel._sb_brightness_term({"brightness": -9}),+ "eq=brightness=-0.500000,")++ def test_the_grade_lands_in_the_segment_it_belongs_to(self):+ cuts = panel._sb_cut_index([+ {"path": "/x/S01.mp4", "start": 0.0, "end": 2.0,+ "adjust": {"brightness": 0.2}},+ {"path": "/x/S02.mp4", "start": 0.0, "end": 2.0},+ ])+ g, _l = panel._sb_film_filtergraph(self.PROBES, 1024, 576, 48000,+ "yuv420p", cuts=cuts)+ self.assertIn("setsar=1,eq=brightness=0.200000,format=yuv420p[v0]", g)+ self.assertIn("setsar=1,format=yuv420p[v1]", g)+ self.assertEqual(g.count("eq=brightness"), 1)++ def test_one_source_used_twice_can_be_graded_two_different_ways(self):+ # The cut index has been list-per-path since repeats were possible;+ # what it never carried was anything to differ ABOUT.+ cuts = panel._sb_cut_index([+ {"path": "/x/S01.mp4", "start": 0.0, "end": 2.0,+ "adjust": {"brightness": -0.3}},+ {"path": "/x/S01.mp4", "start": 3.0, "end": 4.0,+ "adjust": {"brightness": 0.4}},+ ])+ probes = [(Path("/x/S01.mp4"), _probe(1024, 576, 5.0))] * 2+ g, _l = panel._sb_film_filtergraph(probes, 1024, 576, 48000,+ "yuv420p", cuts=cuts)+ self.assertIn("eq=brightness=-0.300000,format=yuv420p[v0]", g)+ self.assertIn("eq=brightness=0.400000,format=yuv420p[v1]", g)++ def test_the_cut_index_is_unchanged_for_a_plan_that_says_nothing_new(self):+ # A plan of plain trims must build the identical index it always did,+ # or every existing export changes for no reason.+ idx = panel._sb_cut_index([{"path": "/x/S01.mp4", "start": 1.0,+ "end": 2.0}])+ self.assertEqual(idx, {"/x/S01.mp4": [{"start": 1.0, "end": 2.0}]})++ def test_a_graded_still_and_a_graded_slug_carry_the_term_too(self):+ segs = [+ {"kind": "still", "input": 0,+ "info": {"w": 1024, "h": 576, "duration": 0.0,+ "has_audio": False, "sample_rate": 0},+ "window": None, "adjust": {"brightness": 0.1}, "duration": 2.0},+ {"kind": "slug", "input": None, "info": None, "window": None,+ "adjust": {"brightness": 0.5}, "duration": 1.0},+ ]+ g, _l = panel._sb_film_filtergraph([], 1024, 576, 48000, "yuv420p",+ segments=segs)+ self.assertIn("setsar=1,eq=brightness=0.100000,format=yuv420p[v0]", g)+ self.assertIn("setsar=1,eq=brightness=0.500000,format=yuv420p[v1]", g)diff --git a/test_storyboard_edit.py b/test_storyboard_edit.pynew file mode 100644index 0000000..046d9dd--- /dev/null+++ b/test_storyboard_edit.py@@ -0,0 +1,579 @@+#!/usr/bin/env python3+"""Tests for the auto-editor: which window, where the beats, and the plan.++Three things are locked here.++1. **The window search.** A generated clip is not uniformly good, and the whole+ point of `best_window()` is to prefer the part that is. These tests feed it+ SYNTHETIC frame stacks with a known answer — a sharp middle and a soft tail,+ a frozen stretch, a blown-out ending — and assert it finds the answer, that+ the head/tail prior only breaks ties, and that two identical calls produce+ identical dicts.++2. **The beat grid.** A click track written by `wave` at a known tempo is the+ only honest way to test a tempo estimator without shipping a reference+ implementation to disagree with. The assertions are the numbers that matter:+ BPM within a fraction of a beat, downbeats on the accents.++3. **The plan.** `min_shot` is never violated, snapping never invents a cut+ that the shot length forbids, the order is the order given, the total lands+ near the target, and the same inputs give the same plan.++No GPU, no weights, no model download, and nothing longer than a few seconds+of synthesised audio. The only external process is ffmpeg, and only where a+real decode is the thing being tested.++Run: python3 -m unittest test_storyboard_edit+"""++from __future__ import annotations++import json+import math+import struct+import subprocess+import tempfile+import unittest+import wave+from pathlib import Path+from unittest import mock++import numpy as np++import storyboard_edit as se++ROOT = Path(__file__).resolve().parent+HAVE_FFMPEG = Path(se.FFMPEG).is_file() and Path(se.FFPROBE).is_file()+++# ---------------------------------------------------------------------------+# Synthetic footage. `amp` drives sharpness (contrast of a fixed noise+# pattern), `dc` drives both brightness and — through its frame-to-frame+# change — motion. Nothing here is random at call time: one seeded pattern,+# reused, so the whole suite is reproducible.+# ---------------------------------------------------------------------------+PATTERN = (np.random.default_rng(20260815).integers(0, 256, size=(36, 64))+ .astype(np.float32) - 128.0) / 128.0+++def synth(amp: list[float], dc: list[float]) -> np.ndarray:+ frames = [np.clip(d + 60.0 * a * PATTERN, 0, 255) for a, d in zip(amp, dc)]+ return np.stack(frames).astype(np.uint8)+++def probe(duration: float, w: int = 640, h: int = 360) -> dict:+ return {"w": w, "h": h, "duration": duration, "fps": 24.0,+ "has_audio": True, "sample_rate": 48000}+++def window(frames: np.ndarray, want: float, duration: float | None = None,+ **kw) -> dict:+ n = frames.shape[0]+ dur = duration if duration is not None else n / se.ANALYSIS_FPS+ with mock.patch.object(se, "_decode_grey", return_value=frames):+ return se.best_window("/nope/clip.mp4", want, probe=probe(dur), **kw)+++# =============================================================================+# The scoring primitives+# =============================================================================+class ScoreShapes(unittest.TestCase):+ def test_motion_is_a_band_not_a_maximum(self):+ # THE reason this is not "more movement is better": a frozen window is+ # dead footage and a thrashing one is the model breaking up.+ self.assertEqual(se._motion_score(0.0), 0.0)+ self.assertEqual(se._motion_score(se.MOTION_DEAD), 0.0)+ self.assertEqual(se._motion_score(se.MOTION_LOW), 1.0)+ self.assertEqual(se._motion_score(se.MOTION_HIGH), 1.0)+ self.assertEqual(se._motion_score(se.MOTION_THRASH), 0.0)+ self.assertEqual(se._motion_score(999.0), 0.0)+ # and it really does ramp, in both directions+ mid_low = se._motion_score((se.MOTION_DEAD + se.MOTION_LOW) / 2)+ mid_high = se._motion_score((se.MOTION_HIGH + se.MOTION_THRASH) / 2)+ for v in (mid_low, mid_high):+ self.assertGreater(v, 0.0)+ self.assertLess(v, 1.0)++ def test_luma_rejects_both_ends(self):+ self.assertEqual(se._luma_score(0.0), 0.0)+ self.assertEqual(se._luma_score(255.0), 0.0)+ self.assertEqual(se._luma_score(128.0), 1.0)+ self.assertGreater(se._luma_score(se.LUMA_GOOD_LO), 0.99)++ def test_ramp_handles_a_zero_width_ramp(self):+ self.assertEqual(se._ramp(5.0, 3.0, 3.0), 1.0)+ self.assertEqual(se._ramp(1.0, 3.0, 3.0), 0.0)+++# =============================================================================+# best_window+# =============================================================================+class BestWindow(unittest.TestCase):+ def test_it_finds_the_sharp_middle_of_a_clip_that_softens(self):+ # The documented failure mode of generated video: soft head, good+ # middle, degrading tail. 8 s at 4 fps.+ amp = ([0.35] * 4) + ([1.0] * 16) + ([0.30] * 12)+ dc = [110.0 + 2.0 * (i % 2) for i in range(32)]+ got = window(synth(amp, dc), 4.0)+ self.assertAlmostEqual(got["end"] - got["start"], 4.0, places=6)+ self.assertGreaterEqual(got["start"], 0.75)+ self.assertLessEqual(got["end"], 5.5)+ self.assertIn("sharpness", got["reason"])++ def test_a_frozen_stretch_loses_to_a_moving_one(self):+ # Same sharpness throughout; the only difference is that the first six+ # seconds do not move at all. A four-second window fits entirely+ # inside either half, so there is no excuse for straddling.+ amp = [1.0] * 48+ dc = [110.0] * 24 + [110.0 + 4.0 * (i % 2) for i in range(24)]+ got = window(synth(amp, dc), 4.0)+ self.assertGreaterEqual(got["start"], 5.0, "picked the frozen half")+ self.assertEqual(got["components"]["stability"], 1.0)++ def test_a_blown_out_tail_is_vetoed_not_merely_marked_down(self):+ # The real bug class: a render that washes to white in its last+ # seconds. No window may include it.+ amp = [0.5] * 20 + [0.05] * 12+ dc = [110.0 + 3.0 * (i % 2) for i in range(20)] + [252.0] * 12+ got = window(synth(amp, dc), 3.0)+ self.assertLessEqual(got["end"], 5.0)+ self.assertTrue(got["usable"])++ def test_every_window_blown_is_reported_as_unusable(self):+ frames = synth([0.05] * 24, [251.0] * 24)+ got = window(frames, 3.0)+ self.assertFalse(got["usable"])+ self.assertIn("luma check", got["reason"])++ def test_a_black_clip_is_rejected_too(self):+ frames = synth([0.05] * 24, [3.0] * 24)+ self.assertFalse(window(frames, 3.0)["usable"])++ def test_the_positional_prior_breaks_a_tie_away_from_both_guards(self):+ # Uniform footage: nothing in the pixels prefers any position, so the+ # head and tail guards are the only thing left. The winner must clear+ # BOTH guard zones, and among the windows that do, it must be the+ # earliest — determinism, not taste.+ frames = synth([1.0] * 24, [110.0 + 3.0 * (i % 2) for i in range(24)])+ got = window(frames, 4.0)+ self.assertEqual(got["components"]["penalty"], 0.0)+ self.assertGreaterEqual(got["start"], se.HEAD_GUARD_S)+ self.assertLessEqual(got["end"], got["duration"] - se.TAIL_GUARD_S)+ self.assertEqual(got["start"], 0.5) # first sample past 0.30+ # ...and it is a PRIOR, so turning it off changes the answer's basis+ # rather than crashing.+ off = window(frames, 4.0, head_weight=0.0, tail_weight=0.0)+ self.assertEqual(off["components"]["penalty"], 0.0)+ self.assertEqual(off["start"], 0.0)++ def test_a_bigger_tail_guard_pushes_the_window_earlier(self):+ frames = synth([1.0] * 40, [110.0 + 3.0 * (i % 2) for i in range(40)])+ near = window(frames, 4.0, tail_guard=0.5, tail_weight=0.25)+ far = window(frames, 4.0, tail_guard=5.0, tail_weight=0.25)+ self.assertLessEqual(far["start"], near["start"])++ def test_the_window_is_exactly_as_long_as_asked(self):+ frames = synth([1.0] * 40, [110.0 + 3.0 * (i % 2) for i in range(40)])+ for want in (1.0, 2.5, 3.75, 7.0):+ got = window(frames, want)+ self.assertAlmostEqual(got["end"] - got["start"], want, places=6)+ self.assertGreaterEqual(got["start"], 0.0)+ self.assertLessEqual(got["end"], got["duration"] + 1e-9)++ def test_asking_for_the_whole_clip_or_more_returns_the_whole_clip(self):+ frames = synth([1.0] * 20, [110.0] * 20)+ for want in (5.0, 9.0):+ got = window(frames, want, duration=5.0)+ self.assertEqual((got["start"], got["end"]), (0.0, 5.0))+ self.assertTrue(got["forced"])+ self.assertIn("nothing to choose", got["reason"])+ # It is still SCORED — a forced window is not a scoreless one.+ self.assertIn("stability", got["components"])++ def test_per_second_diagnostics_are_returned_for_a_human(self):+ frames = synth([1.0] * 24, [110.0] * 24)+ got = window(frames, 2.0)+ self.assertEqual(len(got["per_second"]), 6)+ for row in got["per_second"]:+ for key in ("t", "sharpness", "motion", "luma", "crushed", "blown"):+ self.assertIn(key, row)++ def test_it_is_deterministic(self):+ frames = synth([0.4, 1.0] * 16, [110.0 + 2.0 * (i % 3) for i in range(32)])+ a = window(frames, 3.0)+ b = window(frames, 3.0)+ self.assertEqual(json.dumps(a, sort_keys=True),+ json.dumps(b, sort_keys=True))++ def test_a_flat_clip_says_sharpness_did_not_decide(self):+ frames = synth([1.0] * 24, [110.0] * 24)+ got = window(frames, 2.0)+ self.assertIn("sharpness was flat", got["reason"])++ def test_an_unprobeable_clip_is_an_honest_error(self):+ with mock.patch.object(se, "probe_media", return_value=None):+ with self.assertRaises(RuntimeError):+ se.best_window("/nope/clip.mp4", 2.0)+++# =============================================================================+# snap + the planner's constrained variant+# =============================================================================+class Snap(unittest.TestCase):+ BEATS = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5]++ def test_it_moves_to_the_nearest_beat_inside_the_tolerance(self):+ self.assertEqual(se.snap(1.05, self.BEATS, 0.2), 1.0)+ self.assertEqual(se.snap(1.45, self.BEATS, 0.2), 1.5)++ def test_it_leaves_the_time_alone_outside_the_tolerance(self):+ self.assertEqual(se.snap(1.25, self.BEATS, 0.1), 1.25)+ self.assertEqual(se.snap(1.25, self.BEATS, 0.0), 1.25)+ self.assertEqual(se.snap(1.25, [], 5.0), 1.25)+ self.assertEqual(se.snap(1.25, None, 5.0), 1.25)++ def test_an_exact_midpoint_takes_the_earlier_beat(self):+ # Determinism, not musicality: a tie has to resolve the same way every+ # run or the plan is not reproducible.+ self.assertEqual(se.snap(1.25, self.BEATS, 0.5), 1.0)++ def test_the_tolerance_is_inclusive_of_its_own_edge(self):+ self.assertEqual(se.snap(1.2, self.BEATS, 0.2), 1.0)++ def test_constrained_snapping_refuses_a_cut_the_shot_cannot_reach(self):+ # The nearest beat is 2.0 but the shot may not run past 1.6, so the+ # answer is the best REACHABLE beat, not "no beat".+ self.assertEqual(se._snap_in_range(1.9, self.BEATS, 0.5, 0.0, 1.6), 1.5)+ self.assertIsNone(se._snap_in_range(1.9, self.BEATS, 0.1, 0.0, 1.6))+ self.assertIsNone(se._snap_in_range(1.9, [], 0.5, 0.0, 1.6))+ self.assertIsNone(se._snap_in_range(1.9, self.BEATS, 0.5, 2.0, 1.0))+++class Balance(unittest.TestCase):+ def test_it_hits_the_target_when_the_material_allows(self):+ got = se._balance([10.0] * 5, 30.0, 1.5)+ self.assertAlmostEqual(sum(got), 30.0, places=4)++ def test_no_clip_is_asked_for_more_than_it_has(self):+ avail = [2.0, 10.0, 3.0]+ got = se._balance(avail, 30.0, 1.5)+ for a, g in zip(avail, got):+ self.assertLessEqual(g, a + 1e-9)++ def test_a_target_the_material_cannot_reach_is_capped_not_faked(self):+ got = se._balance([2.0, 2.0], 60.0, 1.5)+ self.assertAlmostEqual(sum(got), 4.0, places=6)++ def test_it_terminates_on_degenerate_input(self):+ self.assertEqual(se._balance([], 10.0, 1.5), [])+ self.assertEqual(len(se._balance([5.0], 0.0, 1.5)), 1)+++# =============================================================================+# beat_map, against a click track with a known tempo+# =============================================================================+def click_track(path: Path, bpm: float, seconds: float, *, sr: int = 22050,+ meter: int = 4, accent: float = 1.0) -> Path:+ """A 4/4 click at a known tempo. Every beat is a short decaying burst;+ beat one is louder. Written with the stdlib so the fixture cannot drift+ with an ffmpeg version."""+ n = int(seconds * sr)+ buf = np.zeros(n, dtype=np.float64)+ period = 60.0 / bpm+ tick = np.exp(-np.arange(int(0.03 * sr)) / (0.004 * sr))+ tone = np.sin(2 * math.pi * 1800 * np.arange(tick.size) / sr) * tick+ k = 0+ while True:+ t = k * period+ i = int(round(t * sr))+ if i + tone.size >= n:+ break+ buf[i:i + tone.size] += tone * (accent if k % meter == 0 else 0.45)+ k += 1+ buf = np.clip(buf, -1.0, 1.0)+ with wave.open(str(path), "wb") as w:+ w.setnchannels(1)+ w.setsampwidth(2)+ w.setframerate(sr)+ w.writeframes(struct.pack(f"<{n}h", *(buf * 30000).astype(np.int16)))+ return path++[email protected](HAVE_FFMPEG, "needs a real ffmpeg")+class BeatMap(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.tmp = tempfile.TemporaryDirectory()+ cls.dir = Path(cls.tmp.name)+ cls.click = click_track(cls.dir / "click125.wav", 125.0, 40.0)+ cls.map = se.beat_map(cls.click)++ @classmethod+ def tearDownClass(cls):+ cls.tmp.cleanup()++ def test_it_recovers_the_tempo_it_was_given(self):+ # Half a BPM at 125 is 1.6 ms per beat — over a 40 s track that is a+ # third of a beat of accumulated drift, which is the real tolerance.+ self.assertAlmostEqual(self.map["bpm"], 125.0, delta=0.5)++ def test_the_beats_are_where_the_clicks_are(self):+ period = 60.0 / 125.0+ for b in self.map["beats"][:40]:+ self.assertLess(abs(b - round(b / period) * period), 0.02,+ f"beat at {b:.3f}s is not on the click grid")++ def test_downbeats_are_every_fourth_beat_and_land_on_the_accent(self):+ beats, downs = self.map["beats"], self.map["downbeats"]+ self.assertEqual(self.map["meter"], 4)+ self.assertEqual(len(downs), len(beats[self.map["diagnostics"]+ ["downbeat_offset"]::4]))+ period = 60.0 / 125.0+ for d in downs[:8]:+ self.assertLess(abs(d - round(d / (4 * period)) * 4 * period), 0.03,+ f"downbeat at {d:.3f}s is not on an accent")++ def test_a_click_track_is_high_confidence_and_tightly_locked(self):+ self.assertGreater(self.map["confidence"], 0.6)+ self.assertLess(self.map["diagnostics"]["grid_lock_ms"], 25.0)+ self.assertGreater(self.map["diagnostics"]["pulse_ratio"], 2.0)++ def test_it_is_deterministic(self):+ again = se.beat_map(self.click)+ self.assertEqual(again["bpm"], self.map["bpm"])+ self.assertEqual(again["beats"], self.map["beats"])+ self.assertEqual(again["downbeats"], self.map["downbeats"])++ def test_a_span_limits_both_the_fit_and_the_beats(self):+ part = se.beat_map(self.click, span=(10.0, 25.0))+ self.assertAlmostEqual(part["bpm"], 125.0, delta=0.8)+ self.assertGreaterEqual(min(part["beats"]), 9.99)+ self.assertLessEqual(max(part["beats"]), 25.01)+ self.assertEqual(part["span"], [10.0, 25.0])++ def test_noise_is_not_reported_as_a_confident_tempo(self):+ rng = np.random.default_rng(7)+ n = 22050 * 20+ noise = (rng.standard_normal(n) * 3000).astype(np.int16)+ p = self.dir / "noise.wav"+ with wave.open(str(p), "wb") as w:+ w.setnchannels(1)+ w.setsampwidth(2)+ w.setframerate(22050)+ w.writeframes(noise.tobytes())+ got = se.beat_map(p)+ self.assertLess(got["confidence"], self.map["confidence"],+ "white noise must not look as beat-like as a click track")++ def test_the_span_helper_is_the_one_definition_of_the_fit_window(self):+ self.assertIsNone(se.audio_span_for(None))+ self.assertIsNone(se.audio_span_for(0))+ self.assertEqual(se.audio_span_for(60.0), (0.0, 100.0))+++# =============================================================================+# plan_cut+# =============================================================================+def fake_map(bpm: float = 120.0, phase: float = 0.0, seconds: float = 120.0,+ meter: int = 4) -> dict:+ period = 60.0 / bpm+ beats = [round(phase + k * period, 6)+ for k in range(int((seconds - phase) / period) + 1)]+ return {"bpm": bpm, "period": period, "phase": phase, "meter": meter,+ "beats": beats, "downbeats": beats[::meter], "confidence": 0.9,+ "span": [0.0, seconds], "duration": seconds, "diagnostics": {}}+++class PlanCut(unittest.TestCase):+ """The planner, with the window search stubbed out — this suite is about+ lengths, boundaries and order, and a real decode would only make it slow+ and dependent on footage."""++ def setUp(self):+ def fake_window(path, want, *, probe=None, **kw):+ return {"path": str(path), "start": 0.25,+ "end": round(0.25 + want, 6), "score": 0.5,+ "usable": True, "reason": "stub", "components": {},+ "runner_up": None, "per_second": [],+ "duration": probe["duration"], "forced": False,+ "candidates": 3}+ self.patch = mock.patch.object(se, "best_window",+ side_effect=fake_window)+ self.patch.start()+ self.addCleanup(self.patch.stop)++ def plan(self, durations, **kw):+ probes = {f"/c/{i}.mp4": probe(d) for i, d in enumerate(durations)}+ return se.plan_cut(list(probes), probes=probes, **kw)++ def test_the_order_given_is_the_order_planned(self):+ got = self.plan([6.0, 6.0, 6.0])+ self.assertEqual([p["path"] for p in got],+ ["/c/0.mp4", "/c/1.mp4", "/c/2.mp4"])+ self.assertEqual([p["n"] for p in got], [1, 2, 3])++ def test_shots_are_laid_end_to_end_with_no_gap(self):+ got = self.plan([6.0] * 4, audio=fake_map(), target_seconds=16.0)+ self.assertEqual(got[0]["film_start"], 0.0)+ for a, b in zip(got, got[1:]):+ self.assertAlmostEqual(a["film_end"], b["film_start"], places=6)+ self.assertAlmostEqual(a["film_end"] - a["film_start"],+ a["duration"], places=6)++ def test_min_shot_is_never_violated(self):+ got = self.plan([10.0] * 8, audio=fake_map(bpm=140.0),+ target_seconds=12.0, min_shot=2.0)+ for p in got:+ self.assertGreaterEqual(p["duration"], 2.0 - 1e-9,+ f"shot {p['n']} is {p['duration']}s")++ def test_a_source_shorter_than_min_shot_is_used_whole_and_flagged(self):+ got = self.plan([0.8, 6.0], min_shot=1.5)+ self.assertAlmostEqual(got[0]["duration"], 0.8, places=6)+ self.assertTrue(any("shorter than" in n for n in got[0]["notes"]))++ def test_max_shot_caps_every_shot(self):+ got = self.plan([20.0] * 3, max_shot=4.0)+ for p in got:+ self.assertLessEqual(p["duration"], 4.0 + 1e-9)++ def test_the_total_lands_near_the_target(self):+ got = self.plan([8.0] * 6, audio=fake_map(), target_seconds=24.0)+ self.assertAlmostEqual(se.plan_total(got), 24.0, delta=1.0)++ def test_a_target_the_material_cannot_reach_is_not_faked(self):+ got = self.plan([2.0] * 3, target_seconds=60.0)+ self.assertAlmostEqual(se.plan_total(got), 6.0, places=6)++ def test_every_cut_lands_on_the_grid_and_says_which(self):+ bm = fake_map(bpm=120.0, phase=0.13)+ got = self.plan([8.0] * 5, audio=bm, target_seconds=20.0)+ for p in got:+ self.assertIn(p["snap"]["kind"], ("downbeat", "beat", "none"))+ if p["snap"]["kind"] == "downbeat":+ self.assertTrue(any(abs(p["film_end"] - d) < 1e-6+ for d in bm["downbeats"]))+ elif p["snap"]["kind"] == "beat":+ self.assertTrue(any(abs(p["film_end"] - b) < 1e-6+ for b in bm["beats"]))++ def test_the_shift_is_reported_in_milliseconds_with_a_sign(self):+ got = self.plan([8.0] * 4, audio=fake_map(phase=0.21),+ target_seconds=18.0)+ for p in got:+ self.assertAlmostEqual(+ p["snap"]["shift_ms"],+ (p["snap"]["landed"] - p["snap"]["wanted"]) * 1000.0, places=3)++ def test_without_music_nothing_is_snapped(self):+ got = self.plan([6.0] * 3, target_seconds=12.0)+ for p in got:+ self.assertEqual(p["snap"]["kind"], "none")+ self.assertEqual(p["snap"]["shift_ms"], 0.0)++ def test_a_grid_below_min_confidence_is_refused_out_loud(self):+ bm = fake_map()+ bm["confidence"] = 0.2+ got = self.plan([6.0] * 3, audio=bm, target_seconds=12.0,+ min_confidence=0.6)+ for p in got:+ self.assertEqual(p["snap"]["kind"], "none")+ self.assertTrue(any("below the" in n for n in got[0]["notes"]))++ def test_the_window_never_runs_past_the_end_of_its_source(self):+ got = self.plan([3.0, 3.0], audio=fake_map(), target_seconds=6.0)+ for p in got:+ self.assertLessEqual(p["end"], p["window"]["source_duration"] + 1e-6)+ self.assertGreaterEqual(p["start"], 0.0)+ self.assertAlmostEqual(p["end"] - p["start"], p["duration"],+ places=6)++ def test_it_is_deterministic(self):+ a = self.plan([6.0, 9.0, 4.0], audio=fake_map(phase=0.07),+ target_seconds=15.0)+ b = self.plan([6.0, 9.0, 4.0], audio=fake_map(phase=0.07),+ target_seconds=15.0)+ self.assertEqual(json.dumps(a, sort_keys=True),+ json.dumps(b, sort_keys=True))++ def test_an_empty_list_plans_nothing_rather_than_raising(self):+ self.assertEqual(se.plan_cut([]), [])++ def test_a_clip_that_cannot_be_probed_is_an_honest_error(self):+ with mock.patch.object(se, "probe_media", return_value=None):+ with self.assertRaises(RuntimeError):+ se.plan_cut(["/nope/clip.mp4"])++ def test_the_plan_formats_as_something_a_human_can_read(self):+ got = self.plan([6.0] * 3, audio=fake_map(), target_seconds=12.0)+ text = se.format_plan(got, fake_map())+ self.assertIn("3 shots", text)+ self.assertIn("BPM", text)+ for p in got:+ self.assertIn(Path(p["path"]).name, text)+++# =============================================================================+# The real decode paths, on fixtures ffmpeg makes in a fraction of a second+# =============================================================================[email protected](HAVE_FFMPEG, "needs a real ffmpeg")+class RealDecode(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)+ self.addCleanup(self.tmp.cleanup)++ def make(self, name, w, h, seconds) -> Path:+ out = self.dir / name+ subprocess.run(+ [str(se.FFMPEG), "-y", "-f", "lavfi",+ "-i", f"testsrc=size={w}x{h}:rate=24:duration={seconds}",+ "-c:v", "libx264", "-pix_fmt", "yuv420p", str(out)],+ capture_output=True, check=True, timeout=120)+ return out++ def test_probe_reads_a_real_clip(self):+ p = self.make("a.mp4", 320, 240, 2)+ got = se.probe_media(p)+ self.assertEqual((got["w"], got["h"]), (320, 240))+ self.assertAlmostEqual(got["duration"], 2.0, delta=0.1)+ self.assertFalse(got["has_audio"])++ def test_probe_reads_an_AUDIO_ONLY_file(self):+ # An mp3 has no video stream; the clip probe answers None for that and+ # is right to. This one must not.+ wav = click_track(self.dir / "click.wav", 120.0, 4.0)+ got = se.probe_media(wav)+ self.assertIsNotNone(got)+ self.assertTrue(got["has_audio"])+ self.assertEqual(got["sample_rate"], 22050)++ def test_probe_returns_None_for_something_that_is_not_media(self):+ junk = self.dir / "junk.mp4"+ junk.write_bytes(b"not an mp4 at all")+ self.assertIsNone(se.probe_media(junk))++ def test_the_analysis_decode_samples_rather_than_decoding_everything(self):+ p = self.make("b.mp4", 640, 360, 3)+ frames = se._decode_grey(p, 320, 180, 4.0)+ self.assertEqual(frames.shape[1:], (180, 320))+ self.assertAlmostEqual(frames.shape[0], 12, delta=1) # 3 s at 4 fps+ self.assertEqual(frames.dtype, np.uint8)++ def test_best_window_runs_end_to_end_on_a_real_clip(self):+ p = self.make("c.mp4", 320, 240, 4)+ got = se.best_window(p, 2.0)+ self.assertAlmostEqual(got["end"] - got["start"], 2.0, places=6)+ self.assertGreaterEqual(got["start"], 0.0)+ self.assertLessEqual(got["end"], 4.05)+ self.assertTrue(got["per_second"])++ def test_a_clip_that_cannot_be_decoded_raises_rather_than_guessing(self):+ junk = self.dir / "junk2.mp4"+ junk.write_bytes(b"still not an mp4")+ with self.assertRaises(RuntimeError):+ se._decode_grey(junk, 32, 32, 4.0)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_editor_api.py b/test_storyboard_editor_api.pynew file mode 100644index 0000000..580e27f--- /dev/null+++ b/test_storyboard_editor_api.py@@ -0,0 +1,5298 @@+#!/usr/bin/env python3+"""Tests for the TIMELINE EDITOR's server: proxies, peaks, edit.json, routes.++Four things are locked here, and every one of them is a thing that would fail+silently if it broke.++1. **The proxy recipe.** All-intra or nothing. Our rendered clips are a single+ GOP — one keyframe for the whole clip — so a browser seeking into a source+ clip decodes from frame zero (235 ms median / 1266 ms p90 in Chrome; 3.5 ms+ against a proxy). Lose `-g 1` and the timeline still "works": it just+ becomes unusable, with no error anywhere. So the flags are asserted, by+ name, in the argv.++2. **One source used twice.** The whole reason `edit.json` is a separate file+ from `storyboard.json`. The cut index used to be a path->one-window map,+ which collapsed both uses of a repeated shot onto the last window — a+ silent wrong film. It is a list per path now, consumed in order.++3. **A bad edit never lands on a good one.** Validation runs before the write,+ the write is atomic, and the failure returns every problem at once instead+ of the first.++4. **The make_job allowlist.** `edit/generate` builds a shot and enqueues it+ through the panel's ordinary lane. A form field make_job does not name is+ dropped in silence — the known trap in this codebase — so the test enqueues+ for real and reads the params back off the queued job.++No GPU, no weights, no model download, no network. ffmpeg is only ever invoked+as an argv assertion or a mock.++Run: python3 -m unittest test_storyboard_editor_api+"""++from __future__ import annotations++import json+import re+import shutil+import subprocess+import sys+import tempfile+import threading+import unittest+import xml.etree.ElementTree as ET+from pathlib import Path+from unittest import mock+from urllib.parse import urlparse++import numpy as np++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+import storyboard_editor as sedit # noqa: E402+++# =============================================================================+# helpers+# =============================================================================+def _clip(path, start, end, film_start, **kw) -> dict:+ return sedit.new_clip(path, start, end, film_start, **kw)+++def _edit(clips, **kw) -> dict:+ doc = {"version": sedit.EDIT_VERSION, "board_id": "sb_t", "revision": 0,+ "source": "auto",+ "audio": None, "beats": None, "clips": clips, "settings": {}}+ doc.update(kw)+ return doc+++def _board(clips, bid="sb_t", title="A Film") -> dict:+ return {"schema": 1, "id": bid, "title": title, "created_at": 1_700_000_000,+ "policy": storyboard.default_policy(), "cast": [], "engine_mode": "ltx",+ "shots": [+ {"n": i + 1, "title": f"shot {i + 1}", "mode": "text",+ "engine": "ltx", "prompt": f"shot {i + 1} happens",+ "duration_s": 5.0, "seed": 100 + i, "refs": [],+ "status": "done", "draft_output": str(p)}+ for i, p in enumerate(clips)]}+++class FakeHandler:+ """Just enough of `Handler` for the two dispatch methods under test.++ Deliberately not a real `BaseHTTPRequestHandler`: these routes are pure+ functions of (query, disk, queue) and a socket would only add ways for the+ test to be flaky.+ """++ def __init__(self):+ self.status = None+ self.payload = None+ self.error = None+ self.served = None+ # WHAT THE DISPATCHER IS TOLD, which is a different thing from what+ # was written. This used to be discarded, so the one branch that+ # answered a request and then reported it unhandled — writing a second+ # complete 404 response onto the same socket — was invisible to 250+ # green tests.+ self.handled = None++ def _json(self, payload, status: int = 200):+ self.payload, self.status = payload, status++ def send_error(self, code, *a):+ self.error, self.status = code, code++ def _serve_video_with_range(self, path):+ self.served = Path(path)++ # the two methods under test, bound to this stand-in+ def get(self, url: str):+ self.handled = panel.Handler._storyboard_edit_get(self, urlparse(url))+ return self++ def post(self, action: str, form: dict | None = None, body: str = ""):+ panel.Handler._storyboard_post(self, action, body, form or {})+ return self+++class EditorCase(unittest.TestCase):+ """A scratch STATE_DIR with one board, patched over the module globals."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.state = self.root / "state"+ self.out = self.root / "outputs"+ self.state.mkdir()+ self.out.mkdir()+ self.clips = []+ for i in range(3):+ p = self.root / f"S{i + 1:02d}.mp4"+ p.write_bytes(b"x" * (1000 + i))+ self.clips.append(p)+ self.board = _board(self.clips)+ self._patches = [+ mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "push", lambda *a, **k: None),+ ]+ for p in self._patches:+ p.start()+ storyboard.save_storyboard(self.state, self.board)+ self.bdir = storyboard.board_dir(self.state, "sb_t")+ panel._SBE_JOBS.clear()++ def tearDown(self):+ for p in reversed(self._patches):+ p.stop()+ panel._SBE_JOBS.clear()+ self.tmp.cleanup()+++# =============================================================================+# 1. The proxy recipe — the measurement this whole feature stands on+# =============================================================================+class ProxyRecipe(unittest.TestCase):+ def cmd(self, **kw) -> list[str]:+ return sedit.proxy_cmd("/bin/ffmpeg", "/x/S01.mp4", "/y/p.mp4", **kw)++ def test_every_frame_is_a_keyframe(self):+ # THE flag. Without it a proxy is a single GOP exactly like its source+ # and the 235 ms seek is unchanged — the feature looks built and is not.+ c = self.cmd()+ self.assertEqual(c[c.index("-g") + 1], "1")+ # libx264 will make its own GOP decisions regardless of -g unless both+ # of these say otherwise.+ self.assertEqual(c[c.index("-keyint_min") + 1], "1")+ self.assertEqual(c[c.index("-sc_threshold") + 1], "0")++ def test_no_b_frames(self):+ # Display order == decode order, so a backwards scrub does not re-read+ # a pyramid to show one frame.+ self.assertEqual(self.cmd()[self.cmd().index("-bf") + 1], "0")++ def test_carries_audio(self):+ # Recipe v2. The old recipe dropped audio on the reasoning that "the+ # timeline's sound is the soundtrack" — true for a music video, wrong+ # for a dialogue film, where a silent preview cannot tell you whether a+ # cut lands on the line or halfway through the word.+ c = self.cmd()+ self.assertNotIn("-an", c)+ self.assertIn("0:a:0?", c) # OPTIONAL: a silent clip still proxies+ self.assertEqual(c[c.index("-c:a") + 1], "aac")+ self.assertEqual(c[c.index("-b:a") + 1], sedit.PROXY_ABITRATE)++ def test_audio_mapping_is_optional_so_silent_clips_still_build(self):+ # Without the trailing '?', a clip with no audio track fails the whole+ # prepare instead of producing a picture-only proxy.+ self.assertIn("0:a:0?", self.cmd())+ self.assertNotIn("0:a:0", [x for x in self.cmd() if x == "0:a:0"])++ def test_recipe_version_moved_so_silent_proxies_rebuild(self):+ # The version is inside the content hash, so bumping it invalidates+ # every proxy built by the old recipe exactly once.+ self.assertGreaterEqual(sedit.PROXY_RECIPE_VERSION, 2)++ def test_scaled_to_the_requested_width_with_an_even_height(self):+ vf = self.cmd(width=480)[self.cmd().index("-vf") + 1]+ self.assertEqual(vf, "scale='min(480,iw)':-2:flags=bicubic")++ def test_the_proxy_never_upscales_its_source(self):+ # The width is a CEILING, not a target. Engine output is commonly 1024+ # wide; a flat `scale=1280` would spend bytes and encode time inventing+ # detail that is not in the source and look no better for it.+ vf = self.cmd()[self.cmd().index("-vf") + 1]+ self.assertIn(f"min({sedit.PROXY_WIDTH},iw)", vf)++ def test_the_default_width_is_big_enough_to_watch(self):+ # 640 was chosen for seek speed and produced a preview upscaled >2x on a+ # normal window — reported as "the quality is pretty bad". All-intra is+ # what makes seeking fast, not the pixel count.+ self.assertGreaterEqual(sedit.PROXY_WIDTH, 1024)++ def test_faststart_so_the_browser_gets_the_moov_atom_first(self):+ c = self.cmd()+ self.assertEqual(c[c.index("-movflags") + 1], "+faststart")++ def test_argv_is_a_list_never_a_shell_string(self):+ self.assertTrue(all(isinstance(a, str) for a in self.cmd()))+ self.assertNotIn(" ", self.cmd()[0])+++class ProxyAddressing(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.src = self.root / "S01.mp4"+ self.src.write_bytes(b"a" * 100)++ def tearDown(self):+ self.tmp.cleanup()++ def test_the_same_file_gets_the_same_name(self):+ self.assertEqual(sedit.proxy_name(self.src), sedit.proxy_name(self.src))++ def test_a_rewritten_source_gets_a_different_name(self):+ before = sedit.proxy_name(self.src)+ self.src.write_bytes(b"b" * 250) # different size AND mtime+ self.assertNotEqual(before, sedit.proxy_name(self.src))++ def test_two_sources_sharing_a_basename_do_not_collide(self):+ other = self.root / "sub"+ other.mkdir()+ twin = other / "S01.mp4"+ twin.write_bytes(b"a" * 100)+ self.assertNotEqual(sedit.proxy_name(self.src), sedit.proxy_name(twin))++ def test_changing_the_recipe_invalidates_every_proxy_exactly_once(self):+ before = sedit.proxy_name(self.src)+ with mock.patch.object(sedit, "PROXY_RECIPE_VERSION", 99):+ self.assertNotEqual(before, sedit.proxy_name(self.src))++ def test_a_missing_source_still_plans(self):+ # ffmpeg produces the honest error; the planner must not raise first.+ self.assertTrue(sedit.proxy_name(self.root / "gone.mp4").endswith(".mp4"))++ def test_a_repeated_clip_builds_ONE_proxy(self):+ plan = sedit.plan_proxies([{"path": str(self.src)},+ {"path": str(self.src)}], self.root)+ self.assertEqual(len(plan["build"]), 1)++ def test_an_existing_proxy_is_reused_not_rebuilt(self):+ d = sedit.proxy_dir(self.root)+ d.mkdir()+ (d / sedit.proxy_name(self.src)).write_bytes(b"proxy")+ plan = sedit.plan_proxies([{"path": str(self.src)}], self.root)+ self.assertEqual(plan["build"], [])+ self.assertEqual(len(plan["reuse"]), 1)++ def test_a_proxy_nothing_points_at_is_stale(self):+ d = sedit.proxy_dir(self.root)+ d.mkdir()+ junk = d / "orphan_deadbeef1234.mp4"+ junk.write_bytes(b"junk")+ plan = sedit.plan_proxies([{"path": str(self.src)}], self.root)+ self.assertEqual(plan["stale"], [junk])+ self.assertEqual(sedit.prune_proxies(plan["stale"]), 1)+ self.assertFalse(junk.exists())++ def test_pruning_never_raises_on_a_file_that_is_already_gone(self):+ self.assertEqual(sedit.prune_proxies([self.root / "nope.mp4"]), 0)+++# =============================================================================+# 2. Peaks — server-side, because the client alternative is 100 MB of RAM+# =============================================================================+class Peaks(unittest.TestCase):+ SR = 22050++ def pcm(self, seconds=5.0):+ t = np.arange(int(self.SR * seconds)) / self.SR+ return (0.8 * np.sin(2 * np.pi * 220 * t)).astype(np.float32)++ def peaks(self, **kw):+ return sedit.compute_peaks(+ "/x/song.mp3", decoder=lambda p, sr: self.pcm(), **kw)++ def test_min_and_max_are_interleaved_and_min_never_exceeds_max(self):+ p = self.peaks()+ vals = p["peaks"]+ self.assertEqual(len(vals), p["count"] * 2)+ for i in range(0, len(vals), 2):+ self.assertLessEqual(vals[i], vals[i + 1])++ def test_values_are_small_integers_not_floats(self):+ p = self.peaks()+ self.assertTrue(all(isinstance(v, int) for v in p["peaks"]))+ self.assertLessEqual(max(abs(v) for v in p["peaks"]), sedit.PEAKS_SCALE)++ def test_a_full_scale_signal_reaches_the_top_of_the_scale(self):+ p = sedit.compute_peaks("/x/s.wav",+ decoder=lambda a, b: np.ones(22050, "float32"))+ self.assertEqual(max(p["peaks"]), sedit.PEAKS_SCALE)++ def test_the_bucket_rate_is_what_was_asked_for(self):+ p = self.peaks(buckets_per_second=50)+ self.assertAlmostEqual(p["buckets_per_second"], 50.0, delta=0.5)+ self.assertAlmostEqual(p["count"], 250, delta=2)++ def test_silence_is_not_an_error(self):+ p = sedit.compute_peaks("/x/s.wav",+ decoder=lambda a, b: np.zeros(22050, "float32"))+ self.assertEqual(set(p["peaks"]), {0})++ def test_an_empty_decode_is_an_honest_refusal(self):+ with self.assertRaises(sedit.EditError):+ sedit.compute_peaks("/x/s.wav",+ decoder=lambda a, b: np.zeros(0, "float32"))++ def test_the_file_on_disk_is_compact_not_pretty(self):+ # indent=2 puts every one of ~96,000 integers on its own line and+ # doubles the file. Measured: 795 KB pretty vs 345 KB compact on the+ # real 479 s track.+ with tempfile.TemporaryDirectory() as d:+ sedit.save_peaks(Path(d), self.peaks())+ text = sedit.peaks_path(Path(d)).read_text()+ self.assertNotIn("\n", text.strip())+ self.assertLess(len(text), 5.0 * 1024 * self.peaks()["duration"])++ def test_it_round_trips_through_disk(self):+ with tempfile.TemporaryDirectory() as d:+ p = self.peaks()+ sedit.save_peaks(Path(d), p)+ self.assertEqual(sedit.load_peaks(Path(d))["peaks"], p["peaks"])++ def test_a_missing_or_corrupt_peaks_file_reads_as_None(self):+ with tempfile.TemporaryDirectory() as d:+ self.assertIsNone(sedit.load_peaks(Path(d)))+ sedit.peaks_path(Path(d)).write_text("{not json")+ self.assertIsNone(sedit.load_peaks(Path(d)))+++# =============================================================================+# 3. edit.json — the arrangement, and everything that must not corrupt it+# =============================================================================+class EditSchema(unittest.TestCase):+ def test_a_clean_edit_validates(self):+ e = _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0),+ _clip("/x/b.mp4", 1.0, 4.0, 3.0)])+ self.assertEqual(sedit.validate_edit(e), [])++ def test_film_slot_and_source_window_must_be_the_same_length(self):+ c = _clip("/x/a.mp4", 0.0, 3.0, 0.0)+ c["film_end"] = 9.0 # 3 s of clip in a 9 s slot+ errs = sedit.validate_edit(_edit([c]))+ self.assertEqual([e["code"] for e in errs], ["clip_length_mismatch"])++ def test_a_window_past_the_end_of_its_source_is_refused(self):+ c = _clip("/x/a.mp4", 8.0, 12.0, 0.0, duration=10.0)+ self.assertIn("clip_past_the_end",+ [e["code"] for e in sedit.validate_edit(_edit([c]))])++ def test_overlapping_clips_are_an_error(self):+ # One video track can only play one of them; a concat would silently+ # pick whichever came first.+ e = _edit([_clip("/x/a.mp4", 0.0, 4.0, 0.0),+ _clip("/x/b.mp4", 0.0, 4.0, 2.0)])+ self.assertIn("clips_overlap",+ [x["code"] for x in sedit.validate_edit(e)])++ def test_the_soundtrack_mode_is_checked_because_one_value_deletes_dialogue(self):+ # `replace` silences every line in the film. A typo must not fall+ # through to it, and the two good values must both survive the round+ # trip — reopening a film that was mixed `under` and silently+ # re-arming `replace` is the same bug arriving later.+ for mode in ("under", "replace"):+ e = _edit([_clip("/x/a.mp4", 0.0, 4.0, 0.0)])+ e["audio"] = {"path": "/x/song.wav", "offset": 0.0, "mode": mode}+ self.assertEqual(sedit.validate_edit(e), [], f"{mode} should be valid")+ e = _edit([_clip("/x/a.mp4", 0.0, 4.0, 0.0)])+ e["audio"] = {"path": "/x/song.wav", "offset": 0.0, "mode": "duck"}+ self.assertIn("audio_mode", [x["code"] for x in sedit.validate_edit(e)])++ def test_a_soundtrack_with_no_mode_is_still_valid(self):+ # Every edit.json written before the mode existed has no mode.+ e = _edit([_clip("/x/a.mp4", 0.0, 4.0, 0.0)])+ e["audio"] = {"path": "/x/song.wav", "offset": 0.0}+ self.assertEqual(sedit.validate_edit(e), [])++ def test_clips_that_merely_TOUCH_are_not_an_overlap(self):+ e = _edit([_clip("/x/a.mp4", 0.0, 4.0, 0.0),+ _clip("/x/b.mp4", 0.0, 4.0, 4.0)])+ self.assertEqual(sedit.validate_edit(e), [])++ def test_a_GAP_is_not_an_error(self):+ # It is the hole somebody is about to generate a shot into. Refusing to+ # save it would make the feature impossible.+ e = _edit([_clip("/x/a.mp4", 0.0, 4.0, 0.0),+ _clip("/x/b.mp4", 0.0, 4.0, 10.0)])+ self.assertEqual(sedit.validate_edit(e), [])+ gaps = sedit.edit_gaps(e)+ self.assertEqual(len(gaps), 1)+ self.assertAlmostEqual(gaps[0]["duration"], 6.0)+ self.assertEqual(gaps[0]["after"], 0)++ def test_a_gap_at_the_head_of_the_film_is_reported_as_after_minus_one(self):+ gaps = sedit.edit_gaps(_edit([_clip("/x/a.mp4", 0.0, 2.0, 5.0)]))+ self.assertEqual(gaps[0]["after"], -1)++ def test_the_same_source_twice_is_LEGAL_and_is_the_point(self):+ e = _edit([_clip("/x/a.mp4", 0.0, 2.0, 0.0),+ _clip("/x/a.mp4", 6.0, 8.0, 2.0)])+ self.assertEqual(sedit.validate_edit(e), [])+ cuts = sedit.edit_to_cuts(e)+ self.assertEqual([(c["start"], c["end"]) for c in cuts],+ [(0.0, 2.0), (6.0, 8.0)])++ def test_a_proxy_that_escapes_the_board_folder_is_refused(self):+ for bad in ("/etc/passwd", "../../secrets.mp4"):+ c = _clip("/x/a.mp4", 0.0, 2.0, 0.0, proxy=bad)+ self.assertIn("clip_proxy_escapes",+ [e["code"] for e in sedit.validate_edit(_edit([c]))],+ bad)++ def test_every_broken_clip_is_reported_not_just_the_first(self):+ e = _edit([_clip("/x/a.mp4", 0.0, 0.0, 0.0),+ dict(_clip("/x/b.mp4", 0.0, 2.0, 5.0), source="sideways"),+ dict(_clip("/x/c.mp4", 0.0, 2.0, 9.0), locked="yes")])+ codes = {e2["code"] for e2 in sedit.validate_edit(e)}+ self.assertEqual(codes, {"clip_window", "clip_film_window",+ "clip_source", "clip_locked"})++ def test_a_wrong_version_is_refused(self):+ self.assertIn("version",+ [e["code"] for e in sedit.validate_edit(_edit([], version=7))])++ def test_junk_is_refused_rather_than_crashing(self):+ for junk in (None, [], "edit", 3):+ self.assertTrue(sedit.validate_edit(junk))++ def test_normalise_sorts_by_film_position_and_never_moves_a_cut(self):+ e = _edit([_clip("/x/b.mp4", 1.0, 3.0, 8.0),+ _clip("/x/a.mp4", 0.0, 2.0, 0.0)])+ n = sedit.normalise_edit(e)+ self.assertEqual([c["path"] for c in n["clips"]],+ ["/x/a.mp4", "/x/b.mp4"])+ self.assertEqual(n["clips"][1]["start"], 1.0) # untouched+ self.assertEqual(n["duration"], 10.0) # 8.0 + a 2 s clip++ def test_new_clip_derives_the_film_slot_rather_than_taking_it_twice(self):+ c = sedit.new_clip("/x/a.mp4", 2.0, 5.5, 10.0)+ self.assertEqual(c["film_end"], 13.5)+++class EditPersistence(EditorCase):+ def test_a_malformed_edit_never_lands_on_a_good_one(self):+ good = _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)])+ sedit.save_edit(self.bdir, good)+ before = sedit.edit_path(self.bdir).read_text()+ bad = _edit([_clip("/x/a.mp4", 5.0, 1.0, 0.0)])+ with self.assertRaises(sedit.EditError):+ sedit.save_edit(self.bdir, bad)+ self.assertEqual(sedit.edit_path(self.bdir).read_text(), before)++ def test_the_write_is_atomic_and_leaves_no_temp_files(self):+ sedit.save_edit(self.bdir, _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)]))+ leftovers = [p.name for p in self.bdir.iterdir()+ if p.name.startswith(".edit-")]+ self.assertEqual(leftovers, [])++ def test_the_revision_counts_up_on_every_save(self):+ e = _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)])+ sedit.save_edit(self.bdir, e)+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 1)+ sedit.save_edit(self.bdir, sedit.load_edit(self.bdir))+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 2)++ def test_a_corrupt_edit_raises_rather_than_pretending_there_is_none(self):+ sedit.edit_path(self.bdir).write_text("{ half a fi")+ with self.assertRaises(sedit.EditError):+ sedit.load_edit(self.bdir)++ def test_no_edit_at_all_is_None_not_an_error(self):+ self.assertIsNone(sedit.load_edit(self.bdir))++ def test_a_human_edit_survives_a_full_round_trip(self):+ auto = sedit.edit_from_plan(+ [{"n": 1, "path": "/x/a.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0, "film_end": 4.0,+ "snap": {"kind": "downbeat", "shift_ms": 12.0},+ "window": {"score": 0.8, "reason": "because", "usable": True,+ "source_duration": 10.0},+ "notes": []}],+ board_id="sb_t")+ self.assertEqual(auto["clips"][0]["source"], "auto")+ sedit.save_edit(self.bdir, auto)+ human = sedit.load_edit(self.bdir)+ human["clips"][0]["start"] = 1.0+ human["clips"][0]["end"] = 5.0+ human["clips"][0]["source"] = "human"+ human["clips"][0]["locked"] = True+ sedit.save_edit(self.bdir, human)+ back = sedit.load_edit(self.bdir)+ self.assertEqual(back["clips"][0]["source"], "human")+ self.assertTrue(back["clips"][0]["locked"])+ self.assertEqual(back["clips"][0]["start"], 1.0)+ self.assertEqual(sedit.edit_to_cuts(back),+ [{"path": "/x/a.mp4", "start": 1.0, "end": 5.0,+ "film_start": 0.0}])++ def test_the_analysis_rides_along_so_the_UI_can_say_why(self):+ auto = sedit.edit_from_plan(+ [{"n": 1, "path": "/x/a.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0, "film_end": 4.0,+ "snap": {"kind": "beat", "shift_ms": -30.0},+ "window": {"score": 0.42, "reason": "sharpness 0.9",+ "usable": True, "source_duration": 10.0},+ "notes": ["a note"]}])+ a = auto["clips"][0]["analysis"]+ self.assertEqual(a["snap"]["kind"], "beat")+ self.assertEqual(a["reason"], "sharpness 0.9")+ self.assertEqual(a["notes"], ["a note"])++ def test_the_beat_grid_is_slimmed_but_the_grid_itself_survives(self):+ fat = {"bpm": 126.0, "period": 0.476, "phase": 0.1, "meter": 4,+ "confidence": 0.7, "span": [0, 60],+ "beats": [0.1, 0.6], "downbeats": [0.1],+ "diagnostics": {"grid_lock_ms": 9.0, "tempo_drift_bpm": 0.2,+ "runners_up": [{"bpm": 63.0}] * 3,+ "n_onsets": 400}}+ slim = sedit.edit_from_plan([], beats=fat)["beats"]+ self.assertEqual(slim["beats"], [0.1, 0.6])+ self.assertEqual(slim["grid_lock_ms"], 9.0)+ self.assertNotIn("runners_up", slim)+++# =============================================================================+# 4. A shot used twice must actually RENDER twice+# =============================================================================+class RepeatedShots(unittest.TestCase):+ PROBES = [+ (Path("/x/A.mp4"), {"w": 1024, "h": 576, "duration": 10.0,+ "has_audio": True, "sample_rate": 48000}),+ (Path("/x/A.mp4"), {"w": 1024, "h": 576, "duration": 10.0,+ "has_audio": True, "sample_rate": 48000}),+ (Path("/x/B.mp4"), {"w": 1024, "h": 576, "duration": 10.0,+ "has_audio": True, "sample_rate": 48000}),+ ]+ PLAN = [{"path": "/x/A.mp4", "start": 0.0, "end": 2.0},+ {"path": "/x/A.mp4", "start": 7.0, "end": 9.0},+ {"path": "/x/B.mp4", "start": 1.0, "end": 4.0}]++ def test_the_index_keeps_every_occurrence(self):+ idx = panel._sb_cut_index(self.PLAN)+ self.assertEqual(len(idx["/x/A.mp4"]), 2)+ self.assertEqual(idx["/x/A.mp4"][1]["start"], 7.0)++ def test_each_use_gets_its_OWN_window_in_the_graph(self):+ g, _ = panel._sb_film_filtergraph(+ self.PROBES, 1024, 576, 48000, "yuv420p",+ cuts=panel._sb_cut_index(self.PLAN))+ self.assertIn("[0:v]trim=start=0.000000:end=2.000000", g)+ self.assertIn("[1:v]trim=start=7.000000:end=9.000000", g)+ self.assertIn("[2:v]trim=start=1.000000:end=4.000000", g)++ def test_a_hand_built_single_window_dict_still_works(self):+ # The pre-editor shape. Nothing that passed a dict may break.+ g, _ = panel._sb_film_filtergraph(+ self.PROBES[:1], 1024, 576, 48000, "yuv420p",+ cuts={"/x/A.mp4": {"start": 1.0, "end": 2.0}})+ self.assertIn("[0:v]trim=start=1.000000:end=2.000000", g)++ def test_windows_are_consumed_in_order_and_then_the_clip_plays_whole(self):+ w = panel._sb_segment_windows(self.PROBES + [self.PROBES[0]],+ panel._sb_cut_index(self.PLAN))+ self.assertEqual([x["start"] if x else None for x in w],+ [0.0, 7.0, 1.0, None])++ def test_an_unreadable_clip_still_cannot_shift_anyone_elses_window(self):+ # The property the path-keying exists for, preserved through the+ # change to a list.+ idx = panel._sb_cut_index(self.PLAN)+ g, _ = panel._sb_film_filtergraph(+ [self.PROBES[0], self.PROBES[2]], 1024, 576, 48000, "yuv420p",+ cuts=idx)+ self.assertIn("[1:v]trim=start=1.000000:end=4.000000", g)+++# =============================================================================+# 5. The routes+# =============================================================================+class ReadRoutes(EditorCase):+ def test_every_read_route_tells_the_dispatcher_it_answered(self):+ # do_GET reads the return value as "did anybody serve this" and falls+ # through to send_error(404) when it is false. The uploads branch+ # ended in a bare `return`, so a request that had already been+ # answered in full — status, headers, Content-Length and body on the+ # wire — got a second complete 404 response written behind it. It is+ # survivable only because this handler never sets protocol_version;+ # with keep-alive those bytes become the head of the next response.+ sedit.save_edit(self.bdir, _edit([])) # so `edit` reads rather than cuts+ for url in ("/storyboard/edit?id=sb_t",+ "/storyboard/edit/status?id=sb_t",+ "/storyboard/edit/peaks?id=sb_t",+ "/storyboard/edit/uploads",+ "/storyboard/edit/drafts?id=sb_t",+ "/storyboard/edit/versions?id=sb_t"):+ self.assertIs(FakeHandler().get(url).handled, True, url)+ # ...and a path this method does not own says so, exactly once.+ self.assertIs(FakeHandler().get("/outputs").handled, False)++ def test_the_drafts_and_versions_routes_check_the_film_exists(self):+ # Every other editor route opens with a load that 404s an unknown id;+ # these two built a board path straight out of the query string, and+ # `storyboard.board_dir` does no sanitising at all.+ for url in ("/storyboard/edit/drafts?id=nope",+ "/storyboard/edit/versions?id=nope",+ "/storyboard/edit/drafts?id=../../..",+ "/storyboard/edit/versions?id=../../.."):+ h = FakeHandler().get(url)+ self.assertEqual(h.status, 404, url)+ self.assertFalse(h.payload["ok"], url)++ def test_GET_edit_auto_generates_once_and_then_reads_from_disk(self):+ plan = [{"n": i + 1, "path": str(p), "start": 0.0, "end": 3.0,+ "film_start": i * 3.0, "film_end": (i + 1) * 3.0,+ "snap": {"kind": "none", "shift_ms": 0.0},+ "window": {"score": 0.5, "reason": "r", "usable": True,+ "source_duration": 5.0},+ "notes": []}+ for i, p in enumerate(self.clips)]+ with mock.patch("storyboard_edit.plan_cut", return_value=plan) as pc:+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertTrue(h.payload["ok"])+ self.assertTrue(h.payload["generated"])+ self.assertEqual(len(h.payload["edit"]["clips"]), 3)+ h2 = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertFalse(h2.payload["generated"])+ self.assertEqual(pc.call_count, 1) # not re-analysed++ def test_GET_edit_on_an_unknown_board_is_a_404(self):+ h = FakeHandler().get("/storyboard/edit?id=nope")+ self.assertEqual(h.status, 404)++ def test_GET_edit_on_a_CORRUPT_edit_refuses_rather_than_replacing_it(self):+ sedit.edit_path(self.bdir).write_text("{ broken")+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.status, 500)+ self.assertTrue(h.payload["corrupt"])+ self.assertEqual(sedit.edit_path(self.bdir).read_text(), "{ broken")++ def test_the_payload_carries_the_gaps_and_the_unplaced_clips(self):+ sedit.save_edit(self.bdir, _edit(+ [_clip(str(self.clips[0]), 0.0, 2.0, 0.0),+ _clip(str(self.clips[1]), 0.0, 2.0, 6.0)]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(len(h.payload["gaps"]), 1)+ self.assertEqual([u["path"] for u in h.payload["unplaced"]],+ [str(self.clips[2])])+ self.assertEqual(h.payload["duration"], 8.0)++ def test_the_proxy_pointer_is_refreshed_on_every_read(self):+ d = sedit.proxy_dir(self.bdir)+ d.mkdir(parents=True)+ name = sedit.proxy_name(self.clips[0])+ (d / name).write_bytes(b"proxy")+ sedit.save_edit(self.bdir, _edit(+ [_clip(str(self.clips[0]), 0.0, 2.0, 0.0)]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.payload["edit"]["clips"][0]["proxy"],+ f"proxy/{name}")+ (d / name).unlink()+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertIsNone(h.payload["edit"]["clips"][0]["proxy"])++ def test_GET_peaks_is_404_before_prepare_and_the_data_after(self):+ h = FakeHandler().get("/storyboard/edit/peaks?id=sb_t")+ self.assertEqual(h.status, 404)+ sedit.save_peaks(self.bdir, {"version": 1, "count": 2,+ "peaks": [-3, 4, -5, 6]})+ h = FakeHandler().get("/storyboard/edit/peaks?id=sb_t")+ self.assertEqual(h.payload["peaks"], [-3, 4, -5, 6])++ def test_GET_status_answers_even_before_a_prepare_has_ever_run(self):+ h = FakeHandler().get("/storyboard/edit/status?id=sb_t")+ self.assertEqual(h.payload, {"ok": True, "id": "sb_t", "prepare": {}})++ def test_a_proxy_is_served_through_the_RANGE_path(self):+ # Safari will not seek a <video> whose server answers a plain 200, so+ # serving these any other way undoes the reason proxies exist.+ d = sedit.proxy_dir(self.bdir)+ d.mkdir(parents=True)+ (d / "a_1234.mp4").write_bytes(b"proxy bytes")+ h = FakeHandler().get("/storyboard/edit/proxy?id=sb_t&name=a_1234.mp4")+ self.assertEqual(h.served, (d / "a_1234.mp4").resolve())++ def test_a_proxy_name_cannot_escape_the_board_folder(self):+ for name in ("../../../../etc/passwd", "..%2Fx.mp4", "/etc/hosts",+ "sub/dir.mp4", "", "x.mp4x"):+ h = FakeHandler().get(+ f"/storyboard/edit/proxy?id=sb_t&name={name}")+ self.assertIn(h.status, (400, 404), name)+ self.assertIsNone(h.served, name)++ def test_a_non_editor_path_is_not_claimed(self):+ h = FakeHandler()+ self.assertFalse(+ panel.Handler._storyboard_edit_get(h, urlparse("/storyboard/list")))+++class TheCompareAndSwapItself(EditorCase):+ """`save_edit(expect=…)` — the guard, at the place the write happens."""++ def _one(self, clip):+ return _edit([_clip(str(clip), 0.0, 2.0, 0.0)])++ def test_a_matching_expectation_writes_and_bumps_from_the_disk(self):+ sedit.save_edit(self.bdir, self._one(self.clips[0]))+ sedit.save_edit(self.bdir, self._one(self.clips[1]), expect=1)+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 2)++ def test_a_stale_expectation_raises_and_writes_NOTHING(self):+ sedit.save_edit(self.bdir, self._one(self.clips[0]))+ sedit.save_edit(self.bdir, sedit.load_edit(self.bdir))+ self.assertEqual(sedit.on_disk_revision(self.bdir), 2)+ with self.assertRaises(sedit.EditConflict) as caught:+ sedit.save_edit(self.bdir, self._one(self.clips[1]), expect=1)+ self.assertEqual(caught.exception.revision, 2)+ got = sedit.load_edit(self.bdir)+ self.assertEqual(got["revision"], 2)+ self.assertEqual(got["clips"][0]["path"], str(self.clips[0]))++ def test_a_conflict_IS_an_edit_error_so_old_callers_still_refuse(self):+ # Every `except EditError` around a save still stops the write and+ # still has a sentence to show. Nobody has to learn a new exception+ # to stay correct.+ self.assertTrue(issubclass(sedit.EditConflict, sedit.EditError))++ def test_expecting_a_revision_on_an_empty_board_is_zero(self):+ sedit.save_edit(self.bdir, self._one(self.clips[0]), expect=0)+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 1)++ def test_the_raw_revision_read_matches_what_load_edit_reports(self):+ self.assertEqual(sedit.on_disk_revision(self.bdir), 0)+ for want in (1, 2, 3):+ sedit.save_edit(self.bdir, sedit.load_edit(self.bdir)+ or self._one(self.clips[0]))+ self.assertEqual(sedit.on_disk_revision(self.bdir), want)+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], want)++ def test_the_lock_is_PER_BOARD_and_not_one_queue_for_the_whole_panel(self):+ # Two people cutting two films have nothing to say to each other.+ other = self.state / "boards" / "sb_other"+ other.mkdir(parents=True, exist_ok=True)+ self.assertIs(sedit.board_write_lock(self.bdir),+ sedit.board_write_lock(self.bdir))+ self.assertIsNot(sedit.board_write_lock(self.bdir),+ sedit.board_write_lock(other))+ # ...and holding one must not block the other, or a slow save on one+ # film would stall every other tab in the panel.+ done = threading.Event()++ def other_board():+ with sedit.board_write_lock(other):+ done.set()++ with sedit.board_write_lock(self.bdir):+ t = threading.Thread(target=other_board, daemon=True)+ t.start()+ self.assertTrue(done.wait(timeout=5),+ "an unrelated board queued behind this one")+ t.join(timeout=5)+++class WriteRoutes(EditorCase):+ def test_save_persists_and_answers_with_the_full_payload(self):+ e = _edit([_clip(str(self.clips[0]), 0.0, 2.0, 0.0)])+ h = FakeHandler().post("edit/save", {},+ json.dumps({"id": "sb_t", "edit": e}))+ self.assertTrue(h.payload["ok"])+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 1)+ self.assertEqual(h.payload["duration"], 2.0)++ def test_save_returns_EVERY_error_and_writes_nothing(self):+ good = _edit([_clip(str(self.clips[0]), 0.0, 2.0, 0.0)])+ sedit.save_edit(self.bdir, good)+ bad = _edit([_clip("/x/a.mp4", 4.0, 1.0, 0.0),+ dict(_clip("/x/b.mp4", 0.0, 2.0, 5.0), source="nope")])+ h = FakeHandler().post("edit/save", {},+ json.dumps({"id": "sb_t", "edit": bad}))+ self.assertEqual(h.status, 400)+ self.assertEqual({e["code"] for e in h.payload["errors"]},+ {"clip_window", "clip_film_window", "clip_source"})+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 1)++ def test_a_stale_tab_cannot_wind_the_revision_backwards(self):+ e = _edit([_clip(str(self.clips[0]), 0.0, 2.0, 0.0)])+ for _ in range(3):+ sedit.save_edit(self.bdir, sedit.load_edit(self.bdir) or e)+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 3)+ stale = _edit([_clip(str(self.clips[0]), 0.0, 2.0, 0.0)], revision=0)+ FakeHandler().post("edit/save", {},+ json.dumps({"id": "sb_t", "edit": stale}))+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 4)++ def test_expect_revision_turns_a_silent_overwrite_into_a_409(self):+ sedit.save_edit(self.bdir, _edit([_clip(str(self.clips[0]),+ 0.0, 2.0, 0.0)]))+ body = json.dumps({"id": "sb_t", "expect_revision": 0,+ "edit": _edit([_clip(str(self.clips[1]),+ 0.0, 2.0, 0.0)])})+ h = FakeHandler().post("edit/save", {}, body)+ self.assertEqual(h.status, 409)+ self.assertTrue(h.payload["conflict"])+ self.assertEqual(h.payload["revision"], 1)+ # ...and the other tab's arrangement is untouched+ self.assertEqual(sedit.load_edit(self.bdir)["clips"][0]["path"],+ str(self.clips[0]))++ # -- THE RACE, and it is the one the guard above could not catch --------+ # `expect_revision` is a compare-and-swap whose compare and whose swap+ # used to be in different critical sections. The panel is a+ # ThreadingHTTPServer, so two tabs whose debounces landed together both+ # read revision 7, both compared 7 == 7, and both wrote. Both got HTTP+ # 200 and one arrangement was gone — recoverable only from history/ and+ # only by somebody who knew to look.+ def _race(self, expect, gate_after=2):+ """Two tabs, both held past the read-and-compare, then released."""+ gate = threading.Barrier(gate_after, timeout=20)+ real = sedit.validate_edit+ held = set()+ held_lock = threading.Lock()++ def gated(doc):+ out = real(doc)+ # ONLY THE FIRST CALL ON EACH THREAD, which is the handler's own+ # check. `save_edit` validates again on its way in, and waiting+ # there would be waiting for a partner that has already gone past.+ tid = threading.get_ident()+ with held_lock:+ first = tid not in held+ held.add(tid)+ if first:+ gate.wait()+ return out++ got = {}++ def tab(name, clip):+ body = json.dumps(+ {"id": "sb_t", "edit": _edit([_clip(str(clip), 0.0, 2.0, 0.0)]),+ **({} if expect is None else {"expect_revision": expect})})+ got[name] = FakeHandler().post("edit/save", {}, body)++ with mock.patch.object(sedit, "validate_edit", gated):+ ts = [threading.Thread(target=tab, args=(n, c), daemon=True)+ for n, c in (("a", self.clips[1]), ("b", self.clips[2]))]+ for t in ts:+ t.start()+ for t in ts:+ t.join(timeout=25)+ for t in ts:+ self.assertFalse(t.is_alive(), "a save thread never returned")+ return got++ def test_TWO_TABS_SAVING_AT_ONCE_CANNOT_BOTH_BE_TOLD_THEY_WON(self):+ sedit.save_edit(self.bdir, _edit([_clip(str(self.clips[0]),+ 0.0, 2.0, 0.0)]))+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 1)+ got = self._race(expect=1)+ codes = sorted((got["a"].status or 200, got["b"].status or 200))+ self.assertEqual(codes, [200, 409],+ "both tabs were told they won — the write race is "+ "back and one arrangement was overwritten in silence")+ loser = got["a"] if (got["a"].status == 409) else got["b"]+ winner = got["b"] if loser is got["a"] else got["a"]+ # THE LOSER GETS THE SAME HONEST 409 THE SEQUENTIAL CASE PRODUCES —+ # the body the client already knows how to answer, naming the+ # revision it was overtaken by.+ self.assertTrue(loser.payload["conflict"])+ self.assertEqual(loser.payload["revision"], 2)+ self.assertIn("moved on without you", loser.payload["error"])+ self.assertFalse(loser.payload["ok"])+ self.assertTrue(winner.payload["ok"])+ # ...and the file holds exactly one of the two arrangements, at one+ # revision, rather than a bump per writer.+ on_disk = sedit.load_edit(self.bdir)+ self.assertEqual(on_disk["revision"], 2)+ self.assertEqual(on_disk["clips"][0]["path"],+ winner.payload["edit"]["clips"][0]["path"])++ def test_the_loser_did_not_lose_the_revision_counter_as_well(self):+ # A refused write must leave the counter where the WINNER put it: a+ # second bump would make the next legitimate save look stale.+ sedit.save_edit(self.bdir, _edit([_clip(str(self.clips[0]),+ 0.0, 2.0, 0.0)]))+ self._race(expect=1)+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 2)++ def test_an_absent_guard_is_still_last_write_wins_and_says_so(self):+ # THE DECISION: accepted, and logged. The client deliberately sends no+ # `expect_revision` for "Keep mine" — a user looking at a conflict and+ # choosing to overwrite — so refusing an unguarded save would strand+ # the arrangement on screen with no button that could answer.+ sedit.save_edit(self.bdir, _edit([_clip(str(self.clips[0]),+ 0.0, 2.0, 0.0)]))+ lines = []+ with mock.patch.object(panel, "push", lambda s: lines.append(s)):+ got = self._race(expect=None)+ self.assertEqual([got["a"].status, got["b"].status], [200, 200])+ self.assertTrue(got["a"].payload["ok"] and got["b"].payload["ok"])+ # AND THIS IS WHAT LAST-WRITE-WINS COSTS, stated rather than hidden:+ # both tabs read revision 1, both wrote 2, and only one arrangement+ # survives. That is the deal "Keep mine" asks for — the difference is+ # that the log now names it and the loser is in history/.+ self.assertEqual(sedit.load_edit(self.bdir)["revision"], 2)+ unguarded = [ln for ln in lines if "unguarded save" in ln]+ self.assertEqual(len(unguarded), 2, lines)+ self.assertIn("last write wins", unguarded[0])++ def test_save_refuses_junk_bodies_politely(self):+ self.assertEqual(FakeHandler().post("edit/save", {}, "{oops").status, 400)+ self.assertEqual(+ FakeHandler().post("edit/save", {},+ json.dumps({"id": "sb_t"})).status, 400)++ def test_prepare_starts_a_job_and_refuses_a_second_one(self):+ started = []++ def fake_thread(bid, music, target):+ started.append((bid, music, target))++ with mock.patch.object(panel, "_sbe_prepare_thread", fake_thread):+ h = FakeHandler().post("edit/prepare", {"id": "sb_t"})+ self.assertEqual(h.status, 202)+ self.assertEqual(started, [("sb_t", None, None)])+ # the fake thread never finished the job, so the slot is still held+ h = FakeHandler().post("edit/prepare", {"id": "sb_t"})+ self.assertEqual(h.status, 409)+ self.assertTrue(h.payload["busy"])++ def test_prepare_refuses_a_soundtrack_that_is_not_there(self):+ h = FakeHandler().post("edit/prepare",+ {"id": "sb_t", "music": "/x/nope.mp3"})+ self.assertEqual(h.status, 400)++ def test_cancel_sets_the_flag_the_build_loop_reads(self):+ with mock.patch.object(panel, "_sbe_prepare_thread",+ lambda *a: None):+ FakeHandler().post("edit/prepare", {"id": "sb_t"})+ FakeHandler().post("edit/cancel", {"id": "sb_t"})+ self.assertTrue(panel._sbe_cancelled("sb_t"))++ def test_auto_rebuilds_the_arrangement_ON_PURPOSE(self):+ human = _edit([_clip(str(self.clips[0]), 1.0, 2.0, 0.0,+ source="human")])+ sedit.save_edit(self.bdir, human)+ plan = [{"n": 1, "path": str(self.clips[0]), "start": 0.0, "end": 3.0,+ "film_start": 0.0, "film_end": 3.0,+ "snap": {"kind": "none", "shift_ms": 0.0},+ "window": {"score": 0.5, "reason": "r", "usable": True,+ "source_duration": 5.0},+ "notes": []}]+ with mock.patch("storyboard_edit.plan_cut", return_value=plan):+ h = FakeHandler().post("edit/auto", {"id": "sb_t"})+ self.assertTrue(h.payload["ok"])+ back = sedit.load_edit(self.bdir)+ self.assertEqual(back["clips"][0]["source"], "auto")+ self.assertEqual(back["clips"][0]["end"], 3.0)+ self.assertEqual(back["revision"], 2) # continues the history+++class RenderRoute(EditorCase):+ def edit_with(self, clips):+ sedit.save_edit(self.bdir, _edit(clips))++ def test_the_render_uses_the_EXISTING_assembler_with_the_edits_cuts(self):+ self.edit_with([_clip(str(self.clips[0]), 0.0, 2.0, 0.0),+ _clip(str(self.clips[0]), 5.0, 7.0, 2.0),+ _clip(str(self.clips[1]), 1.0, 3.0, 4.0)])+ with mock.patch.object(panel, "_sb_assemble_film",+ return_value={"ok": True, "clips": 3}) as af:+ h = FakeHandler().post("edit/render", {"id": "sb_t"})+ self.assertTrue(h.payload["ok"])+ args, kw = af.call_args+ # one entry PER TIMELINE CLIP, repeats included, in film order+ self.assertEqual(args[0], [str(self.clips[0]), str(self.clips[0]),+ str(self.clips[1])])+ # `timeline=`, not `plan=`. Same list, same order, same windows — but+ # the argument that can also carry a kind, because a slug has no path+ # and so cannot be described by args[0] at all.+ self.assertIsNone(kw.get("plan"))+ self.assertEqual([(c["start"], c["end"]) for c in kw["timeline"]],+ [(0.0, 2.0), (5.0, 7.0), (1.0, 3.0)])++ def test_the_soundtrack_and_its_offset_ride_to_the_assembler(self):+ song = self.root / "song.mp3"+ song.write_bytes(b"mp3")+ sedit.save_edit(self.bdir, _edit(+ [_clip(str(self.clips[0]), 0.0, 2.0, 0.0)],+ audio={"path": str(song), "offset": 12.5}))+ with mock.patch.object(panel, "_sb_assemble_film",+ return_value={"ok": True}) as af:+ FakeHandler().post("edit/render", {"id": "sb_t"})+ self.assertEqual(af.call_args.kwargs["music"], str(song))+ self.assertEqual(af.call_args.kwargs["music_start"], 12.5)++ def test_gaps_are_DISCLOSED_because_the_concat_closes_them(self):+ self.edit_with([_clip(str(self.clips[0]), 0.0, 2.0, 0.0),+ _clip(str(self.clips[1]), 0.0, 2.0, 7.0)])+ with mock.patch.object(panel, "_sb_assemble_film",+ return_value={"ok": True, "duration": 4.0}):+ h = FakeHandler().post("edit/render", {"id": "sb_t"})+ self.assertEqual(len(h.payload["gaps"]), 1)+ self.assertIn("closed by the concatenation", h.payload["gaps_note"])+ self.assertEqual(h.payload["timeline_duration"], 9.0)++ def test_an_empty_timeline_is_an_honest_refusal(self):+ self.edit_with([])+ h = FakeHandler().post("edit/render", {"id": "sb_t"})+ self.assertEqual(h.status, 400)++ def test_no_edit_at_all_says_so(self):+ self.assertEqual(FakeHandler().post("edit/render",+ {"id": "sb_t"}).status, 404)++ def test_the_output_name_cannot_escape_the_export_folder(self):+ self.edit_with([_clip(str(self.clips[0]), 0.0, 2.0, 0.0)])+ h = FakeHandler().post("edit/render",+ {"id": "sb_t", "out": "../../evil.mp4"})+ self.assertEqual(h.status, 400)++ def test_a_failed_assembly_is_a_500_carrying_the_reason(self):+ self.edit_with([_clip(str(self.clips[0]), 0.0, 2.0, 0.0)])+ with mock.patch.object(panel, "_sb_assemble_film",+ return_value={"ok": False, "error": "boom"}):+ h = FakeHandler().post("edit/render", {"id": "sb_t"})+ self.assertEqual(h.status, 500)+ self.assertEqual(h.payload["error"], "boom")+++class GenerateIntoAGap(EditorCase):+ """The make_job allowlist trap, checked against the real queue."""++ def setUp(self):+ super().setUp()+ self._q = mock.patch.dict(panel.STATE, {"queue": [], "history": [],+ "current": None}, clear=False)+ self._q.start()+ self._pq = mock.patch.object(panel, "persist_queue", lambda: None)+ self._pq.start()++ def tearDown(self):+ self._pq.stop()+ self._q.stop()+ super().tearDown()++ def gen(self, **form):+ f = {"id": "sb_t", "prompt": "a slow push in on the gate",+ "duration": "5", "film_start": "12.5"}+ f.update(form)+ return FakeHandler().post("edit/generate", f)++ def test_it_enqueues_through_the_panels_ONE_queue(self):+ h = self.gen()+ self.assertEqual(h.status, 202)+ self.assertEqual(len(panel.STATE["queue"]), 1)+ self.assertEqual(panel.STATE["queue"][0]["id"], h.payload["job_id"])++ def test_the_fields_SURVIVE_make_jobs_allowlist(self):+ # The trap: a form field make_job does not name is dropped in silence,+ # so a control can look wired and do nothing. This asserts against the+ # params actually stamped onto the queued job — not against the form.+ h = self.gen(prompt="the gate opens onto white light", duration="3")+ p = panel.STATE["queue"][0]["params"]+ self.assertEqual(p["prompt"], "the gate opens onto white light")+ self.assertEqual(p["mode"], "t2v")+ self.assertEqual(p["engine"], "ltx")+ self.assertEqual(p["frames"], storyboard.ltx_frames_for(3.0))+ self.assertEqual(p["session_tag"], f"sb:sb_t#{h.payload['n']}")+ self.assertEqual(p["label"], f"S{h.payload['n']:02d} · A Film")+ self.assertFalse(p["enhance"]) # never re-write a planned prompt+ self.assertFalse(p["open_when_done"]) # no QuickTime window per shot+ # ...and the endpoint REPORTS what landed, so a client sees it too.+ self.assertEqual(h.payload["params"]["prompt"], p["prompt"])+ self.assertEqual(h.payload["params"]["frames"], p["frames"])++ def test_the_duration_control_actually_changes_the_render(self):+ self.gen(duration="3")+ short = panel.STATE["queue"][0]["params"]["frames"]+ self.gen(duration="8")+ long = panel.STATE["queue"][1]["params"]["frames"]+ self.assertLess(short, long)++ def test_the_slot_is_remembered_on_the_board(self):+ h = self.gen(film_start="21.25")+ board = storyboard.load_storyboard(self.state, "sb_t")+ shot = board["shots"][-1]+ self.assertEqual(shot["edit_slot"],+ {"film_start": 21.25, "duration": 5.0})+ self.assertEqual(shot["draft_job_id"], h.payload["job_id"])+ self.assertEqual(shot["status"], "queued")++ def test_the_new_shot_shows_up_as_UNPLACED_never_auto_inserted(self):+ # The arrangement belongs to the human. A server that appends to it+ # moves their cuts.+ sedit.save_edit(self.bdir, _edit(+ [_clip(str(self.clips[0]), 0.0, 2.0, 0.0)]))+ self.gen()+ board = storyboard.load_storyboard(self.state, "sb_t")+ landed = self.root / "generated.mp4"+ landed.write_bytes(b"clip")+ board["shots"][-1]["draft_output"] = str(landed)+ board["shots"][-1]["status"] = "done"+ storyboard.save_storyboard(self.state, board)+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(len(h.payload["edit"]["clips"]), 1)+ slots = [u["slot"] for u in h.payload["unplaced"]+ if u["path"] == str(landed)]+ self.assertEqual(slots, [{"film_start": 12.5, "duration": 5.0}])++ def test_an_empty_prompt_is_refused_before_anything_is_written(self):+ h = self.gen(prompt="")+ self.assertEqual(h.status, 400)+ self.assertEqual(panel.STATE["queue"], [])+ self.assertEqual(+ len(storyboard.load_storyboard(self.state, "sb_t")["shots"]), 3)++ def test_an_impossible_duration_is_refused(self):+ for d in ("0", "-4", "600"):+ self.assertEqual(self.gen(duration=d).status, 400, d)+ self.assertEqual(panel.STATE["queue"], [])++ def test_an_uninstalled_character_is_refused_rather_than_rendering_a_stranger(self):+ with mock.patch.object(panel, "_sb_known_character_ids",+ return_value=["aria"]):+ h = self.gen(character_id="ghost")+ self.assertEqual(h.status, 400)+ self.assertEqual(panel.STATE["queue"], [])+ # ...and the board is not left carrying a shot that cannot render.+ self.assertEqual(+ len(storyboard.load_storyboard(self.state, "sb_t")["shots"]), 3)++ def test_an_INSTALLED_character_queues_with_its_face_lora_and_trigger(self):+ # Machine-independent: the character library is mocked, because a test+ # that only passes on a Mac with `aria` trained is not a test.+ face = self.root / "aria.safetensors"+ face.write_bytes(b"lora")+ rec = {"id": "aria", "trigger": "ariatrn",+ "face_lora_path": str(face), "audio_lora_path": None}+ compat = {"ltx_compatible": True, "ltx_compat_reason": "",+ "ltx_fusion_tally": None}+ with mock.patch.object(panel, "_sb_known_character_ids",+ return_value=["aria"]), \+ mock.patch.object(panel, "list_characters", return_value=[rec]), \+ mock.patch.object(panel, "_ltx_lora_compatibility",+ return_value=compat):+ h = self.gen(character_id="aria", trigger="ariatrn",+ prompt="ariatrn walks through the gate")+ self.assertEqual(h.status, 202)+ p = panel.STATE["queue"][0]["params"]+ self.assertEqual(p["character_id"], "aria")+ self.assertIn("ariatrn", p["prompt"]) # the trigger, mechanically+ self.assertTrue(p["loras"]) # the face actually loads+ # The pass quality was translated into the character vocabulary on the+ # way through, or this request would have been refused outright.+ self.assertIsNotNone(panel.resolve_character_quality(+ storyboard.CHARACTER_QUALITY_FOR_PASS[+ self.board["policy"]["draft"]["quality"]],+ panel.ACTIVE_MODEL_VERSION))++ def test_the_final_pass_uses_the_boards_delivery_policy(self):+ h = self.gen(**{"pass": "final"})+ p = panel.STATE["queue"][0]["params"]+ policy = self.board["policy"]["final"]+ self.assertEqual((p["width"], p["height"]),+ (policy["width"], policy["height"]))+ board = storyboard.load_storyboard(self.state, "sb_t")+ self.assertEqual(board["shots"][-1]["final_job_id"], h.payload["job_id"])+++class PrepareRun(EditorCase):+ """The build loop itself — with ffmpeg mocked, but every decision real."""++ def run_prepare(self, music=None, fail=(), cancel_after=None):+ calls = []++ def fake_ffmpeg(cmd, label):+ calls.append(cmd)+ dest = Path(cmd[-1])+ if dest.name in fail:+ raise RuntimeError("ffmpeg said no")+ dest.write_bytes(b"proxy")+ if cancel_after is not None and len(calls) >= cancel_after:+ panel._SBE_JOBS["sb_t"]["cancel"] = True+ return "", ""++ panel._SBE_JOBS["sb_t"] = {"id": "sb_t", "state": "running",+ "cancel": False}+ with mock.patch.object(panel, "run_ffmpeg_tracked", fake_ffmpeg):+ panel._sbe_prepare_inner("sb_t", music, None)+ return calls, panel._sbe_job_state("sb_t")++ def test_it_builds_one_proxy_per_clip_and_reports_progress(self):+ calls, st = self.run_prepare()+ self.assertEqual(len(calls), 3)+ self.assertEqual(st["state"], "done")+ self.assertEqual((st["built"], st["total"], st["done"]), (3, 3, 3))+ self.assertEqual(len(list(sedit.proxy_dir(self.bdir).glob("*.mp4"))), 3)++ def test_a_second_run_rebuilds_NOTHING(self):+ self.run_prepare()+ calls, st = self.run_prepare()+ self.assertEqual(calls, [])+ self.assertEqual((st["built"], st["reused"]), (0, 3))++ def test_one_broken_clip_does_not_cost_the_others_their_timeline(self):+ name = sedit.proxy_name(self.clips[1])+ calls, st = self.run_prepare(fail={name})+ self.assertEqual(st["built"], 2)+ self.assertEqual(len(st["failed"]), 1)+ self.assertEqual(st["state"], "done")+ # ...and no half-written proxy is left claiming to be one+ self.assertFalse((sedit.proxy_dir(self.bdir) / name).exists())++ def test_a_proxy_for_a_shot_that_is_gone_is_pruned(self):+ self.run_prepare()+ board = storyboard.load_storyboard(self.state, "sb_t")+ board["shots"] = board["shots"][:2]+ storyboard.save_storyboard(self.state, board)+ _calls, st = self.run_prepare()+ self.assertEqual(st["pruned"], 1)+ self.assertEqual(len(list(sedit.proxy_dir(self.bdir).glob("*.mp4"))), 2)++ def test_cancel_stops_the_loop_between_clips(self):+ calls, st = self.run_prepare(cancel_after=1)+ self.assertEqual(len(calls), 1)+ self.assertEqual(st["state"], "cancelled")++ def test_the_soundtrack_produces_peaks_and_a_grid(self):+ song = self.root / "song.mp3"+ song.write_bytes(b"mp3")+ fake_beats = {"bpm": 126.0, "period": 0.4762, "phase": 0.1, "meter": 4,+ "confidence": 0.8, "span": [0, 60], "beats": [0.1, 0.6],+ "downbeats": [0.1], "diagnostics": {}}+ with mock.patch("storyboard_edit._decode_pcm",+ return_value=np.zeros(22050, "float32")), \+ mock.patch("storyboard_edit.beat_map", return_value=fake_beats):+ _calls, st = self.run_prepare(music=str(song))+ self.assertEqual(st["peaks"]["count"], 100)+ self.assertEqual(st["beats"]["bpm"], 126.0)+ self.assertTrue(sedit.peaks_path(self.bdir).is_file())+ # cached, so `GET /storyboard/edit` does not re-run the tracker+ cache = json.loads((self.bdir / "edit_prepare.json").read_text())+ self.assertEqual(cache["music"], str(song))+ self.assertEqual(cache["beats"]["bpm"], 126.0)++ def test_a_soundtrack_that_cannot_be_read_does_not_lose_the_proxies(self):+ song = self.root / "song.mp3"+ song.write_bytes(b"mp3")+ with mock.patch("storyboard_edit._decode_pcm",+ side_effect=RuntimeError("no audio")):+ _calls, st = self.run_prepare(music=str(song))+ self.assertEqual(st["state"], "done")+ self.assertEqual(st["built"], 3)+ # BOTH halves are reported. Folding them into one string meant the+ # tracker's failure silently overwrote the waveform's.+ self.assertIn("waveform failed", st["peaks_error"])+ self.assertIn("beat tracking failed", st["beats_error"])+ self.assertIn("waveform failed", st["music_error"])++ def test_a_thread_that_dies_leaves_a_job_the_client_can_SEE_die(self):+ # A vanished thread leaves "running" on the poll forever, which reads+ # as a hang — the worst of the available failures.+ panel._SBE_JOBS["sb_t"] = {"id": "sb_t", "state": "running",+ "cancel": False}+ with mock.patch.object(panel, "_sbe_prepare_inner",+ side_effect=RuntimeError("kaboom")):+ panel._sbe_prepare_thread("sb_t", None, None)+ st = panel._sbe_job_state("sb_t")+ self.assertEqual(st["state"], "failed")+ self.assertIn("kaboom", st["error"])+++# =============================================================================+# 6. A cast shot must be ENQUEUEABLE — found by building `edit/generate`+# =============================================================================+class CharacterQualityContract(unittest.TestCase):+ """`make_job` speaks a different quality vocabulary for character jobs.++ Found while wiring `edit/generate`: a shot with a `character_id` and the+ DEFAULT board policy raised `CharacterRequestError("character quality must+ be draft, pro, high or high720")` — because the pass policy says "quick" /+ "standard" and `resolve_character_quality()` accepts only the four+ character tokens. `_sb_render_thread` catches that and marks the shot+ failed, so every cast shot in every film failed to queue, both passes, with+ that sentence as the only clue.++ `shot_to_job` translates now. These tests pin the translation against the+ panel's own resolver, so the table cannot drift away from the thing it+ is a table OF.+ """++ def job_form(self, quality: str, character=True) -> dict:+ shot = {"n": 1, "mode": "character" if character else "text",+ "engine": "ltx", "prompt": "trig walks through the gate",+ "duration_s": 5.0, "seed": 7, "refs": [], "status": "pending"}+ if character:+ shot["character_id"] = "trig"+ shot["trigger"] = "trig"+ return storyboard.shot_to_job(+ shot, {"quality": quality, "width": 1024, "height": 576,+ "frames": 121}, h3_available=False)++ def test_every_pass_quality_maps_to_something_make_job_ACCEPTS(self):+ for q in ("quick", "balanced", "standard", "high", "high_720p"):+ token = self.job_form(q)["quality"]+ self.assertIsNotNone(+ panel.resolve_character_quality(token, panel.ACTIVE_MODEL_VERSION),+ f"pass quality {q!r} -> {token!r} is not a character quality")++ def test_the_default_board_policy_produces_a_queueable_cast_shot(self):+ # The exact pair `_sb_policy_for` hands `_sb_render_thread`.+ for pass_name in ("draft", "final"):+ q = storyboard.DEFAULT_POLICY[pass_name]["quality"]+ self.assertIn(self.job_form(q)["quality"],+ ("draft", "pro", "high", "high720"), pass_name)++ def test_an_unknown_quality_lands_on_the_validated_recipe(self):+ self.assertEqual(self.job_form("something_new")["quality"], "pro")++ def test_a_shot_with_no_character_keeps_the_passes_own_quality(self):+ self.assertEqual(self.job_form("quick", character=False)["quality"],+ "quick")+ self.assertEqual(self.job_form("standard", character=False)["quality"],+ "standard")++ def test_the_draft_pass_stays_SMALLER_than_the_delivery_pass(self):+ # The translation must not collapse the two passes into one recipe —+ # the whole point of a draft is that it is cheaper.+ cells = [panel.resolve_character_quality(+ self.job_form(storyboard.DEFAULT_POLICY[p]["quality"])["quality"],+ panel.ACTIVE_MODEL_VERSION) for p in ("draft", "final")]+ self.assertLess(cells[0]["width"] * cells[0]["height"],+ cells[1]["width"] * cells[1]["height"])+++# =============================================================================+# THE MEDIA POOL — one verb, three sources, and a proxy before the clip lands+# =============================================================================+class AddClipRoute(EditorCase):+ """`POST /storyboard/edit/add-clip` — what replaced a window.prompt().++ Until Wave 1 the only way to bring a clip into a cut was a native text box+ asking for the NUMBER of a film, and the generations gallery — every clip+ the panel has ever made — was unreachable from the editor entirely. This+ route is the whole of the answer: a path in, a proxied clip out.+ """++ def setUp(self):+ super().setUp()+ # A clip in the gallery that belongs to no board — the case the pool+ # exists for.+ self.loose = self.out / "a_loose_render.mp4"+ self.loose.write_bytes(b"y" * 2048)++ def add(self, **form):+ built = []++ def fake_ffmpeg(cmd, label):+ built.append(cmd)+ Path(cmd[-1]).write_bytes(b"proxy")+ return "", ""++ with mock.patch.object(panel, "run_ffmpeg_tracked", fake_ffmpeg), \+ mock.patch("storyboard_edit.probe_media",+ return_value={"duration": 7.5}):+ h = FakeHandler().post("edit/add-clip", form)+ return h, built++ def test_a_gallery_clip_arrives_with_its_proxy_already_built(self):+ # THE POINT OF THE ROUTE. A clip placed without a proxy scrubs at+ # source speed — 235 ms a seek, measured — which reads as the editor+ # being broken rather than as a missing build step.+ h, built = self.add(id="sb_t", path=str(self.loose))+ self.assertEqual(h.status, 200)+ self.assertTrue(h.payload["ok"])+ clip = h.payload["clip"]+ self.assertEqual(clip["path"], str(self.loose))+ self.assertEqual(clip["duration_s"], 7.5)+ self.assertTrue(clip["proxy"].startswith("proxy/"))+ self.assertEqual(len(built), 1)+ self.assertTrue((sedit.proxy_dir(self.bdir) /+ Path(clip["proxy"]).name).is_file())++ def test_a_proxy_that_already_exists_is_not_built_again(self):+ self.add(id="sb_t", path=str(self.loose))+ h, built = self.add(id="sb_t", path=str(self.loose))+ self.assertTrue(h.payload["ok"])+ self.assertEqual(built, [])+ self.assertEqual(h.payload["proxy"]["reused"], 1)++ def test_it_prunes_nothing(self):+ # The full Prepare re-plans the WHOLE board and deletes every proxy no+ # live clip points at. Scoping matters: adding one clip must not cost+ # the timeline the proxies of clips the board does not know about.+ d = sedit.proxy_dir(self.bdir)+ d.mkdir(parents=True, exist_ok=True)+ keeper = d / "someone-elses-proxy.mp4"+ keeper.write_bytes(b"proxy")+ self.add(id="sb_t", path=str(self.loose))+ self.assertTrue(keeper.is_file())++ def test_a_path_outside_the_panels_own_outputs_is_refused(self):+ # `path` comes off a request. Anything not under OUTPUT or STATE_DIR+ # is refused HERE, rather than at the ffmpeg that would read it.+ outsider = self.root / "not_an_output.mp4"+ outsider.write_bytes(b"z")+ h, built = self.add(id="sb_t", path=str(outsider))+ self.assertEqual(h.status, 400)+ self.assertFalse(h.payload["ok"])+ self.assertEqual(built, [])++ def test_a_path_that_is_not_a_file_is_refused(self):+ h, _ = self.add(id="sb_t", path=str(self.out / "ghost.mp4"))+ self.assertEqual(h.status, 400)++ def test_a_clip_from_another_film_is_imported_then_proxied(self):+ # The `only=` subset param the server has always supported and no+ # screen could reach. The clip is REFERENCED, never copied.+ other = self.out / "other_film_s01.mp4"+ other.write_bytes(b"w" * 900)+ src = _board([other], bid="sb_other", title="B-roll")+ storyboard.save_storyboard(self.state, src)+ h, built = self.add(id="sb_t", **{"from": "sb_other", "only": "1"})+ self.assertTrue(h.payload["ok"])+ self.assertEqual(h.payload["clip"]["path"], str(other))+ self.assertEqual(len(built), 1)+ # …and the board it landed on now carries the shot, with provenance.+ board = storyboard.load_storyboard(self.state, "sb_t")+ got = [s for s in board["shots"] if s.get("draft_output") == str(other)]+ self.assertEqual(len(got), 1)+ self.assertEqual(got[0]["imported_from"]["board"], "sb_other")+ self.assertEqual(h.payload["clip"]["n"], got[0]["n"])+ # The file itself was not copied anywhere.+ self.assertFalse((self.bdir / other.name).exists())++ def test_importing_from_a_film_that_is_rendering_is_refused_not_raced(self):+ other = self.out / "busy_s01.mp4"+ other.write_bytes(b"w")+ storyboard.save_storyboard(self.state,+ _board([other], bid="sb_other"))+ panel._SB_RENDERS["sb_t"] = {"stop": False}+ try:+ h, built = self.add(id="sb_t", **{"from": "sb_other", "only": "1"})+ finally:+ panel._SB_RENDERS.pop("sb_t", None)+ self.assertEqual(h.status, 409)+ self.assertEqual(built, [])++ def test_the_pool_is_on_the_payload_with_what_is_already_on_the_track(self):+ # The pool shows placed clips too — marked — so putting one on twice+ # is a choice and not an accident.+ edit = _edit([_clip(self.clips[0], 0, 4, 0)])+ sedit.save_edit(self.bdir, edit)+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ pool = h.payload["clips"]+ self.assertEqual(len(pool), 3)+ self.assertEqual([c["placed"] for c in pool], [True, False, False])++ def test_a_timeline_only_clips_proxy_is_reported_not_dropped(self):+ # The map used to be built from BOARD shots alone, so a clip added+ # from the pool got `proxy: null` in the payload while its freshly+ # built proxy sat on disk — and the player fell back to the source.+ self.add(id="sb_t", path=str(self.loose))+ edit = _edit([_clip(self.loose, 0, 4, 0)])+ sedit.save_edit(self.bdir, edit)+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ clip = h.payload["edit"]["clips"][0]+ self.assertTrue(str(clip["proxy"]).startswith("proxy/"))+++# =============================================================================+# RELINK — the drafts a delivery pass left behind+# =============================================================================+class RelinkDraftToDelivery(EditorCase):+ """The live bug: "Finish keepers" made files the film never used.++ `_sbe_board_clips` picks delivery over draft — but `edit.json` freezes the+ path at the moment of the cut and nothing ever rewrote it, so a delivery+ pass produced full-size renders that the timeline went on ignoring, and+ the next Prepare pruned their proxies for good measure.+ """++ def deliver(self, n: int, name: str) -> Path:+ final = self.out / name+ final.write_bytes(b"final" * 100)+ board = storyboard.load_storyboard(self.state, "sb_t")+ for sh in board["shots"]:+ if sh["n"] == n:+ sh["final_output"] = str(final)+ storyboard.save_storyboard(self.state, board)+ return final++ def test_a_draft_on_the_timeline_with_a_delivery_on_disk_is_flagged(self):+ final = self.deliver(1, "S01_final.mp4")+ sedit.save_edit(self.bdir, _edit([_clip(self.clips[0], 0, 4, 0)]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ rows = h.payload["relink"]+ self.assertEqual(len(rows), 1)+ self.assertEqual(rows[0]["path"], str(self.clips[0]))+ self.assertEqual(rows[0]["to"], str(final))+ self.assertEqual(rows[0]["n"], 1)++ def test_nothing_is_flagged_when_the_delivery_file_is_gone(self):+ final = self.deliver(1, "S01_final.mp4")+ final.unlink()+ sedit.save_edit(self.bdir, _edit([_clip(self.clips[0], 0, 4, 0)]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.payload["relink"], [])++ def test_a_timeline_already_on_the_delivery_is_not_flagged(self):+ final = self.deliver(1, "S01_final.mp4")+ sedit.save_edit(self.bdir, _edit([_clip(final, 0, 4, 0)]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.payload["relink"], [])++ def test_it_is_never_applied_without_being_asked(self):+ # The arrangement is the human's — the rule `_sbe_payload` already+ # states about `unplaced`, applied to paths.+ self.deliver(1, "S01_final.mp4")+ sedit.save_edit(self.bdir, _edit([_clip(self.clips[0], 0, 4, 0)]))+ FakeHandler().get("/storyboard/edit?id=sb_t")+ on_disk = sedit.load_edit(self.bdir)+ self.assertEqual(on_disk["clips"][0]["path"], str(self.clips[0]))++ def test_the_button_rewrites_the_paths_and_keeps_the_cuts(self):+ final = self.deliver(2, "S02_final.mp4")+ sedit.save_edit(self.bdir, _edit([+ _clip(self.clips[0], 0, 4, 0),+ _clip(self.clips[1], 1.5, 5.5, 4)]))+ built = []++ def fake_ffmpeg(cmd, label):+ built.append(cmd)+ Path(cmd[-1]).write_bytes(b"proxy")+ return "", ""++ with mock.patch.object(panel, "run_ffmpeg_tracked", fake_ffmpeg):+ h = FakeHandler().post("edit/relink", {"id": "sb_t"})+ self.assertTrue(h.payload["ok"])+ self.assertEqual(h.payload["relinked"], 1)+ clips = sedit.load_edit(self.bdir)["clips"]+ self.assertEqual(clips[0]["path"], str(self.clips[0])) # untouched+ self.assertEqual(clips[1]["path"], str(final)) # relinked+ # SAME CUTS. Only the files change — the window and the slot on the+ # film are exactly what the human left there.+ self.assertAlmostEqual(clips[1]["start"], 1.5)+ self.assertAlmostEqual(clips[1]["end"], 5.5)+ self.assertAlmostEqual(clips[1]["film_start"], 4.0)+ self.assertAlmostEqual(clips[1]["film_end"], 8.0)+ # …and the delivery's proxy is built before the answer goes out, so+ # the timeline that comes back is scrubbable.+ self.assertEqual(len(built), 1)+ self.assertEqual(Path(built[0][-1]).name, sedit.proxy_name(final))+ self.assertEqual(h.payload["relink"], [])++ def test_relinking_nothing_is_not_an_error(self):+ sedit.save_edit(self.bdir, _edit([_clip(self.clips[0], 0, 4, 0)]))+ h = FakeHandler().post("edit/relink", {"id": "sb_t"})+ self.assertTrue(h.payload["ok"])+ self.assertEqual(h.payload["relink"], [])++ def test_relinking_without_a_timeline_says_so(self):+ h = FakeHandler().post("edit/relink", {"id": "sb_t"})+ self.assertEqual(h.status, 404)+++class UnknownActions(EditorCase):+ def test_an_unknown_editor_action_is_a_404_not_a_500(self):+ h = FakeHandler().post("edit/nonsense", {"id": "sb_t"})+ self.assertEqual(h.status, 404)++ def test_a_missing_editor_module_is_a_503_not_a_dead_panel(self):+ with mock.patch.object(panel, "_sbe_import",+ side_effect=ImportError("no module")):+ self.assertEqual(FakeHandler().post("edit/save", {}, "{}").status,+ 503)+ self.assertEqual(FakeHandler().get("/storyboard/edit?id=sb_t")+ .status, 503)+++# =============================================================================+# WAVE 2 — the three kinds, the version bump, and the project folder+# =============================================================================+class KindsAndAdjustments(unittest.TestCase):+ """`clip.kind` and `clip.adjust`, and what the validator will not take."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.img = self.root / "card.png"+ self.img.write_bytes(b"\x89PNG\r\n\x1a\n" + b"0" * 40)++ def tearDown(self):+ self.tmp.cleanup()++ def still(self, **kw):+ return dict({"id": "s", "kind": "still", "path": str(self.img),+ "start": 0, "end": 0, "film_start": 0.0,+ "film_end": 3.0, "source": "human", "locked": False}, **kw)++ def slug(self, **kw):+ return dict({"id": "k", "kind": "slug", "path": None,+ "start": 0, "end": 0, "film_start": 0.0,+ "film_end": 2.0, "source": "human", "locked": False}, **kw)++ def codes(self, clips):+ return [e["code"] for e in sedit.validate_edit(_edit(clips))]++ # ---- kind ------------------------------------------------------------+ def test_an_absent_kind_is_a_video_which_is_the_whole_migration(self):+ self.assertEqual(sedit.clip_kind({}), "video")+ self.assertEqual(sedit.clip_kind({"kind": "still"}), "still")+ self.assertEqual(sedit.clip_kind({"kind": "SLUG"}), "slug")+ self.assertEqual(sedit.clip_kind({"kind": "banana"}), "video")+ self.assertEqual(sedit.clip_kind(None), "video")++ def test_a_kind_the_build_does_not_know_is_refused_by_name(self):+ self.assertEqual(self.codes([self.still(kind="dissolve")]),+ ["clip_kind"])++ def test_a_still_needs_an_image_that_is_actually_there(self):+ self.assertEqual(self.codes([self.still()]), [])+ gone = self.still(path=str(self.root / "nope.png"))+ self.assertEqual(self.codes([gone]), ["still_missing"])+ self.assertEqual(self.codes([self.still(path="")]), ["clip_path"])++ def test_a_still_needs_a_duration_and_that_is_its_slot(self):+ self.assertEqual(self.codes([self.still(film_end=0.0)]),+ ["clip_film_window"])++ def test_a_slug_needs_only_a_duration_and_never_a_path(self):+ self.assertEqual(self.codes([self.slug()]), [])+ self.assertEqual(self.codes([self.slug(film_end=0.0)]),+ ["clip_film_window"])++ def test_the_1x_rule_does_not_apply_to_a_synthesised_window(self):+ # A video whose window and slot disagree is refused, and must stay+ # refused. A still and a slug have their window SYNTHESISED from the+ # slot by normalise_edit, so policing it would refuse the document for+ # a number the server itself wrote.+ bad_video = _clip("/x/a.mp4", 0.0, 2.0, 0.0)+ bad_video["film_end"] = 5.0+ self.assertIn("clip_length_mismatch", self.codes([bad_video]))+ self.assertEqual(self.codes([self.still(end=0, film_end=9.0)]), [])+ self.assertEqual(self.codes([self.slug(end=0, film_end=9.0)]), [])+ # …and a still is never "past the end" of a source it does not have.+ self.assertEqual(self.codes([self.still(duration=0.5, film_end=9.0)]),+ [])++ def test_normalise_synthesises_the_window_and_clears_the_source_clock(self):+ doc = sedit.normalise_edit(_edit([self.still(film_start=2.0,+ film_end=5.5,+ duration=99),+ self.slug(film_start=5.5,+ film_end=7.0)]))+ still, slug = doc["clips"]+ self.assertEqual((still["start"], still["end"]), (0.0, 3.5))+ self.assertIsNone(still["duration"])+ self.assertEqual((slug["start"], slug["end"]), (0.0, 1.5))+ self.assertIsNone(slug["path"])+ self.assertIsNone(slug["proxy"])++ def test_a_video_clip_never_grows_a_kind_field_on_disk(self):+ # Stamping "video" on every clip would rewrite every edit.json on the+ # machine to say the thing its absence already says.+ doc = sedit.normalise_edit(_edit([_clip("/x/a.mp4", 0.0, 2.0, 0.0)]))+ self.assertNotIn("kind", doc["clips"][0])++ # ---- adjust ----------------------------------------------------------+ def test_brightness_is_refused_outside_the_clamp(self):+ c = _clip("/x/a.mp4", 0.0, 2.0, 0.0)+ self.assertEqual(self.codes([dict(c, adjust={"brightness": 0.5})]), [])+ self.assertEqual(self.codes([dict(c, adjust={"brightness": -0.5})]), [])+ self.assertEqual(self.codes([dict(c, adjust={"brightness": 0.51})]),+ ["clip_brightness_range"])+ self.assertEqual(self.codes([dict(c, adjust={"brightness": -9})]),+ ["clip_brightness_range"])+ self.assertEqual(self.codes([dict(c, adjust={"brightness": "dark"})]),+ ["clip_brightness"])+ self.assertEqual(self.codes([dict(c, adjust={"brightness": True})]),+ ["clip_brightness"])+ self.assertEqual(self.codes([dict(c, adjust="dark")]), ["clip_adjust"])++ def test_a_neutral_grade_is_dropped_rather_than_written(self):+ # An untouched edit.json and one whose slider went out and came back+ # must be the same document.+ doc = sedit.normalise_edit(_edit([+ dict(_clip("/x/a.mp4", 0.0, 2.0, 0.0), adjust={"brightness": 0.0}),+ dict(_clip("/x/b.mp4", 0.0, 2.0, 2.0), adjust={"brightness": 0.2}),+ ]))+ self.assertNotIn("adjust", doc["clips"][0])+ self.assertEqual(doc["clips"][1]["adjust"], {"brightness": 0.2})++ def test_the_cut_list_carries_the_kinds_and_nothing_it_need_not(self):+ doc = sedit.normalise_edit(_edit([+ dict(_clip("/x/a.mp4", 1.0, 3.0, 0.0), adjust={"brightness": 0.2}),+ self.still(film_start=2.0, film_end=5.0),+ self.slug(film_start=5.0, film_end=6.0),+ ]))+ cuts = sedit.edit_to_cuts(doc)+ self.assertEqual([c.get("kind") for c in cuts],+ [None, "still", "slug"])+ self.assertEqual(cuts[0]["adjust"], {"brightness": 0.2})+ self.assertNotIn("adjust", cuts[1])+ self.assertIsNone(cuts[2]["path"])+ # A slug is emitted, not skipped — the old edit_to_cuts dropped every+ # pathless entry, which is exactly what black looks like.+ self.assertEqual((cuts[2]["start"], cuts[2]["end"]), (0.0, 1.0))++ def test_a_still_and_a_slug_are_never_proxy_work(self):+ # A slug has no file; a still is one frame a browser paints from an+ # <img>. Planning a proxy for either builds an mp4 nothing will play+ # and puts a name in `wanted` that the prune then has to keep.+ plan = sedit.plan_proxies([+ {"path": "/x/a.mp4"},+ {"path": str(self.img), "kind": "still"},+ {"path": None, "kind": "slug"},+ ], self.root)+ self.assertEqual([Path(r["path"]).name+ for r in plan["build"] + plan["reuse"]], ["a.mp4"])+++class TheVersionBumpAndItsMigration(unittest.TestCase):+ """EDIT_VERSION 2 refuses old builds — WITHOUT refusing old documents."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.bdir = Path(self.tmp.name)++ def tearDown(self):+ self.tmp.cleanup()++ def v1(self) -> dict:+ return {"version": 1, "board_id": "sb_t", "revision": 3,+ "source": "human", "audio": None, "beats": None, "settings": {},+ "clips": [{"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 2.0, "film_start": 0.0,+ "film_end": 2.0, "source": "auto",+ "locked": False}]}++ def test_a_version_1_document_on_disk_loads_clean(self):+ # THE TRAP THE AUDIT NAMED. validate_edit hard-refuses any version but+ # the current one and save_edit refuses to write anything it+ # complained about — so a bump with no read-path upgrade would not+ # have refused old BUILDS, it would have refused every timeline+ # anybody already had, on their own machine.+ sedit.edit_path(self.bdir).write_text(json.dumps(self.v1()))+ doc = sedit.load_edit(self.bdir)+ self.assertEqual(doc["version"], sedit.EDIT_VERSION)+ self.assertEqual(doc["migrated_from"], 1)+ self.assertEqual(sedit.validate_edit(doc), [])+ # The clips are untouched: absent already MEANS video, so there is+ # nothing to rewrite and nothing that can half-fail.+ self.assertNotIn("kind", doc["clips"][0])+ self.assertEqual(doc["revision"], 3)++ def test_a_migrated_document_saves_and_reloads(self):+ sedit.edit_path(self.bdir).write_text(json.dumps(self.v1()))+ sedit.save_edit(self.bdir, sedit.load_edit(self.bdir))+ back = sedit.load_edit(self.bdir)+ self.assertEqual(back["version"], 2)+ self.assertEqual(back["revision"], 4)++ def test_a_document_from_the_future_is_refused_not_pretended_about(self):+ future = dict(self.v1(), version=99)+ self.assertEqual(sedit.migrate_edit(future)["version"], 99)+ self.assertEqual([e["code"] for e in sedit.validate_edit(future)],+ ["version"])++ def test_the_bump_is_what_stops_an_old_build_rendering_a_new_film(self):+ # An older Phosphene reading a slugged timeline must stop loudly. The+ # alternative is edit_to_cuts skipping every pathless clip and the+ # whole film sliding off the beats it was cut to, silently.+ self.assertEqual(sedit.EDIT_VERSION, 2)+ self.assertEqual([e["code"] for e in+ sedit.validate_edit(dict(self.v1(), version=1))],+ ["version"])+++class NleProjectExport(unittest.TestCase):+ """`<film>_project/` — the film as a project somebody else's editor opens."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.mp4 = self.root / "a shot's take.mp4"+ self.mp4.write_bytes(b"v" * 64)+ self.png = self.root / "card.png"+ self.png.write_bytes(b"i" * 64)+ self.mp3 = self.root / "the track.mp3"+ self.mp3.write_bytes(b"m" * 64)++ def tearDown(self):+ self.tmp.cleanup()++ def probe(self, p):+ return {"w": 1024, "h": 576, "duration": 10.0,+ "has_audio": str(p).endswith(".mp4")}++ def clips(self):+ return [+ {"id": "1", "path": str(self.mp4), "title": "Open",+ "start": 1.0, "end": 3.0, "film_start": 0.0, "film_end": 2.0,+ "adjust": {"brightness": 0.25}},+ {"id": "2", "kind": "still", "path": str(self.png), "title": "Card",+ "start": 0.0, "end": 1.5, "film_start": 2.0, "film_end": 3.5},+ {"id": "3", "kind": "slug", "path": None,+ "start": 0.0, "end": 1.0, "film_start": 3.5, "film_end": 4.5},+ {"id": "4", "path": str(self.mp4), "title": "Close",+ "start": 4.0, "end": 6.0, "film_start": 4.5, "film_end": 6.5},+ ]++ _NOTHING = object()++ def export(self, **kw):+ clips = kw.pop("clips", self._NOTHING)+ return sedit.export_nle(+ self.clips() if clips is self._NOTHING else clips, self.root,+ name=kw.pop("name", "the long walk_film"), probe=self.probe, **kw)++ def seq(self, res):+ return ET.parse(res["xml"]).getroot().find("sequence")++ # ---- the folder ------------------------------------------------------+ def test_the_folder_holds_the_xml_the_script_and_the_media(self):+ res = self.export()+ d = Path(res["dir"])+ self.assertTrue(d.is_dir())+ self.assertEqual(d.name, "the-long-walk-film_project")+ self.assertTrue(Path(res["xml"]).is_file())+ self.assertTrue(Path(res["jsx"]).is_file())+ self.assertEqual(sorted(p.name for p in (d / "media").iterdir()),+ ["a shot's take.mp4", "card.png"])++ def test_the_media_is_hardlinked_so_a_30_shot_film_costs_nothing(self):+ res = self.export()+ self.assertEqual((res["linked"], res["copied"]), (2, 0))+ linked = Path(res["dir"]) / "media" / "a shot's take.mp4"+ self.assertEqual(linked.stat().st_ino, self.mp4.stat().st_ino)+ # The same source used twice is ONE file in media/.+ self.assertEqual(len(res["media"]), 2)++ def test_a_cross_device_export_copies_rather_than_refusing(self):+ # os.link raises EXDEV across filesystems, and an export that refuses+ # to happen is worse than an export that costs disk.+ def no_link(_a, _b):+ raise OSError(18, "Cross-device link")++ res = self.export(link=no_link)+ self.assertEqual((res["linked"], res["copied"]), (0, 2))+ copy = Path(res["dir"]) / "media" / "card.png"+ self.assertTrue(copy.is_file())+ self.assertNotEqual(copy.stat().st_ino, self.png.stat().st_ino)+ self.assertEqual(copy.read_bytes(), self.png.read_bytes())++ def test_a_soundtrack_rides_along_into_media(self):+ res = self.export(audio={"path": str(self.mp3), "offset": 2.0,+ "duration": 60.0})+ self.assertIn("the track.mp3", res["media"])+ self.assertTrue((Path(res["dir"]) / "media" / "the track.mp3").is_file())++ def test_a_file_that_has_gone_is_left_out_and_said_so(self):+ clips = self.clips()+ clips[0]["path"] = str(self.root / "vanished.mp4")+ res = self.export(clips=clips)+ self.assertEqual([Path(m).name for m in res["missing"]],+ ["vanished.mp4"])+ names = [c.findtext("name")+ for c in self.seq(res).iter("clipitem")]+ self.assertNotIn("Open", names)++ # ---- the XML ---------------------------------------------------------+ def test_it_is_the_one_xml_both_premiere_and_resolve_import(self):+ root = ET.parse(self.export()["xml"]).getroot()+ self.assertEqual(root.tag, "xmeml")+ self.assertEqual(root.get("version"), "4")++ def test_the_sequence_runs_at_24_and_is_not_ntsc(self):+ # ntsc TRUE reads timebase 24 as 23.976 and every cut past the first+ # drifts a frame per thousand.+ seq = self.seq(self.export())+ rate = seq.find("rate")+ self.assertEqual(rate.findtext("timebase"), "24")+ self.assertEqual(rate.findtext("ntsc"), "FALSE")+ self.assertEqual(seq.findtext("duration"), "156") # 6.5 s at 24 fps++ def test_one_video_track_because_the_validator_allows_no_other(self):+ seq = self.seq(self.export())+ self.assertEqual(len(seq.findall("media/video/track")), 1)++ def test_a_slug_is_a_gap_not_a_generator(self):+ # Generator effect ids differ between the two NLEs, so "one XML for+ # both" would have quietly become "one XML for one of them". A gap+ # reads as black in every editor ever made.+ items = self.seq(self.export()).findall("media/video/track/clipitem")+ self.assertEqual([i.findtext("name") for i in items],+ ["Open", "Card", "Close"])+ # 3.5 s to 4.5 s is simply nobody's slot.+ self.assertEqual([(i.findtext("start"), i.findtext("end"))+ for i in items],+ [("0", "48"), ("48", "84"), ("108", "156")])+ self.assertNotIn("generatoritem", ET.tostring(self.seq(self.export()),+ encoding="unicode"))++ def test_in_and_out_are_the_source_window_start_and_end_are_the_slot(self):+ # Two different clocks. Conflating them is the classic FCP7 XML bug:+ # the film plays, in the wrong order, at the wrong lengths.+ items = self.seq(self.export()).findall("media/video/track/clipitem")+ self.assertEqual((items[0].findtext("in"), items[0].findtext("out")),+ ("24", "72")) # 1.0-3.0 s of the source+ self.assertEqual((items[0].findtext("start"), items[0].findtext("end")),+ ("0", "48")) # 0.0-2.0 s of the film+ self.assertEqual((items[2].findtext("in"), items[2].findtext("out")),+ ("96", "144")) # 4.0-6.0 s of the same source++ def test_a_still_is_held_for_its_slot(self):+ card = self.seq(self.export()).findall(+ "media/video/track/clipitem")[1]+ self.assertEqual((card.findtext("in"), card.findtext("out")),+ ("0", "36")) # 1.5 s of hold+ self.assertEqual((card.findtext("start"), card.findtext("end")),+ ("48", "84"))++ def test_a_file_is_described_once_and_referenced_by_id_after(self):+ # Re-describing it makes Premiere import the same clip several times+ # as several master items.+ seq = self.seq(self.export())+ full = [f for f in seq.iter("file") if f.find("pathurl") is not None]+ self.assertEqual(len(full), 2) # the mp4 and the png, once each+ self.assertEqual(sorted(f.get("id") for f in full),+ ["file-1", "file-2"])+ # THE ID IS THE SOURCE'S, NOT THE SEGMENT'S. The same mp4 in two slots+ # is one master item pointed at four times — twice on the video track,+ # twice on A1 — not two imports of the same file.+ ids = [f.get("id") for f in seq.iter("file")]+ self.assertEqual(ids.count("file-1"), 4)+ self.assertEqual(sorted(set(ids)), ["file-1", "file-2"])++ def test_the_pathurls_are_absolute_into_the_projects_own_media(self):+ # Absolute-into-media/ is the pair that works: it opens instantly here,+ # and when the folder is handed over both importers fall back to+ # matching by NAME inside the project's own directory.+ res = self.export()+ urls = [f.findtext("pathurl") for f in self.seq(res).iter("file")+ if f.findtext("pathurl")]+ for u in urls:+ self.assertTrue(u.startswith("file://localhost/"), u)+ self.assertIn("/the-long-walk-film_project/media/", u)+ # Spaces and quotes are percent-encoded — an un-encoded space makes+ # the pathurl unparseable and the clip imports offline, silently.+ self.assertTrue(any("a%20shot%27s%20take.mp4" in u for u in urls))+ self.assertFalse(any(" " in u for u in urls))++ def test_the_audio_comes_out_as_stems_not_the_ducked_mix(self):+ # The render's sidechained under-mix has no representation in an NLE+ # timeline, so baking it in would hand an editor a bed they cannot+ # unmix. A1 is the clips' own sound; A2 is the soundtrack.+ seq = self.seq(self.export(audio={"path": str(self.mp3),+ "offset": 2.0, "duration": 60.0}))+ tracks = seq.findall("media/audio/track")+ self.assertEqual(len(tracks), 2)+ self.assertEqual([i.findtext("name") for i in tracks[0]],+ ["Open", "Close"]) # the still is silent+ self.assertEqual(len(tracks[1].findall("clipitem")), 1)+ self.assertEqual(tracks[1].find("clipitem").findtext("name"),+ "the track.mp3")+ # The offset is where in the TRACK the film begins.+ self.assertEqual(tracks[1].find("clipitem").findtext("in"), "48")++ def test_a_title_with_an_ampersand_does_not_break_the_document(self):+ clips = self.clips()+ clips[0]["title"] = 'Salt & <Pepper> "1"'+ res = self.export(clips=clips)+ names = [i.findtext("name")+ for i in self.seq(res).findall("media/video/track/clipitem")]+ self.assertEqual(names[0], 'Salt & <Pepper> "1"')++ # ---- the After Effects script ---------------------------------------+ def test_the_script_finds_its_own_folder_so_it_survives_a_move(self):+ jsx = Path(self.export()["jsx"]).read_text()+ self.assertIn("File($.fileName).parent", jsx)+ self.assertIn("here.fsName +", jsx)+ self.assertIn("proj.items.addComp", jsx)++ def test_a_slug_becomes_a_real_black_solid_in_after_effects(self):+ # AE has no ambiguity about a colour source, so it gets the real+ # thing rather than the gap the XML uses.+ jsx = Path(self.export()["jsx"]).read_text()+ self.assertIn("comp.layers.addSolid([0, 0, 0]", jsx)+ self.assertIn("lay.inPoint = 3.500000;", jsx)+ self.assertIn("lay.outPoint = 4.500000;", jsx)++ def test_brightness_maps_to_the_ae_effect_and_says_it_is_approximate(self):+ jsx = Path(self.export()["jsx"]).read_text()+ self.assertIn("ADBE Brightness & Contrast 2", jsx)+ self.assertIn("bright(lay, 37.5);", jsx) # 0.25 of +/-0.5 -> +/-75+ self.assertIn("APPROXIMATE", jsx)+ # Only the graded clip gets one.+ self.assertEqual(jsx.count("bright(lay,"), 1)++ def test_a_trimmed_clip_starts_before_its_own_in_point(self):+ # startTime is where frame 0 of the SOURCE would sit. Setting it after+ # in/out makes AE clamp the trim to the wrong window.+ jsx = Path(self.export()["jsx"]).read_text()+ self.assertIn("lay.startTime = -1.000000;", jsx) # 0.0 film - 1.0 src+ self.assertLess(jsx.index("lay.startTime = -1.000000;"),+ jsx.index("lay.inPoint = 0.000000;"))++ def test_a_path_with_a_quote_and_a_space_stays_one_string_literal(self):+ # A backslash escapes the quote after it, a quote ends the literal,+ # and a newline in a filename (legal on macOS) makes the whole script+ # a syntax error.+ self.assertEqual(sedit._jsx_string('a "b" c'), '"a \\"b\\" c"')+ self.assertEqual(sedit._jsx_string("back\\slash"),+ '"back\\\\slash"')+ self.assertEqual(sedit._jsx_string("two\nlines"), '"two\\nlines"')+ jsx = Path(self.export()["jsx"]).read_text()+ self.assertIn('bring("/media/a shot\'s take.mp4")', jsx)++ def test_an_empty_timeline_is_refused_rather_than_written_empty(self):+ with self.assertRaises(sedit.EditError):+ self.export(clips=[])+++class NleExportRoute(EditorCase):+ """`POST /storyboard/edit/export-nle`, and the reveal that follows it."""++ def setUp(self):+ super().setUp()+ sedit.save_edit(self.bdir, _edit([+ _clip(str(self.clips[0]), 0.0, 2.0, 0.0),+ {"id": "k", "kind": "slug", "path": None, "start": 0, "end": 0,+ "film_start": 2.0, "film_end": 3.0, "source": "human",+ "locked": False},+ ]))++ def test_the_route_writes_the_folder_next_to_the_film(self):+ with mock.patch.object(panel, "_sb_probe_clip",+ return_value={"w": 1024, "h": 576,+ "duration": 9.0,+ "has_audio": True,+ "sample_rate": 48000}):+ h = FakeHandler().post("edit/export-nle", {"id": "sb_t"})+ self.assertEqual(h.status, 200)+ self.assertTrue(h.payload["ok"])+ d = Path(h.payload["dir"])+ self.assertTrue(d.is_dir())+ self.assertEqual(d.parent, panel._sb_film_dir(self.board))+ self.assertEqual(h.payload["clips"], 2) # the slug counts+ self.assertTrue(Path(h.payload["xml"]).is_file())+ self.assertTrue(Path(h.payload["jsx"]).is_file())++ def test_a_still_is_probed_by_the_probe_that_accepts_an_image(self):+ # `_sb_probe_clip` refuses anything with no duration — correct for a+ # shot, and exactly what an image is.+ img = self.out / "card.png"+ img.write_bytes(b"i" * 32)+ sedit.save_edit(self.bdir, _edit([+ {"id": "s", "kind": "still", "path": str(img), "start": 0,+ "end": 0, "film_start": 0.0, "film_end": 3.0, "source": "human",+ "locked": False}]))+ with mock.patch.object(panel, "_sb_probe_clip", return_value=None), mock.patch.object(panel, "_sb_probe_still",+ return_value={"w": 1920, "h": 1080,+ "duration": 0.0,+ "has_audio": False,+ "sample_rate": 0}) as ps:+ h = FakeHandler().post("edit/export-nle", {"id": "sb_t"})+ self.assertTrue(h.payload["ok"])+ ps.assert_called()+ self.assertEqual((h.payload["width"], h.payload["height"]),+ (1920, 1080))++ def test_a_board_with_no_timeline_is_a_404_not_an_empty_folder(self):+ sedit.edit_path(self.bdir).unlink()+ h = FakeHandler().post("edit/export-nle", {"id": "sb_t"})+ self.assertEqual(h.status, 404)+ self.assertFalse(h.payload["ok"])++ def test_reveal_computes_its_own_path_from_the_board_id_alone(self):+ # The client sends nothing but the board id, so this can never become+ # an argument to `open` pointing outside the board's folder.+ with mock.patch.object(panel, "_sb_probe_clip",+ return_value={"w": 1024, "h": 576,+ "duration": 9.0,+ "has_audio": True,+ "sample_rate": 48000}):+ FakeHandler().post("edit/export-nle", {"id": "sb_t"})+ with mock.patch.object(panel.subprocess, "Popen") as popen:+ h = FakeHandler().post("edit/reveal",+ {"id": "sb_t", "what": "project"})+ self.assertTrue(h.payload["ok"])+ cmd = popen.call_args[0][0]+ self.assertEqual(cmd[0], "open")+ self.assertTrue(cmd[1].endswith("_project"))+ self.assertTrue(Path(cmd[1]).is_dir())+++++class EverySaveKeepsItsPredecessor(unittest.TestCase):+ """No arrangement is ever only-overwritten again.++ The owner, after a crash-heavy day: "There was a version I was working on+ that was better than this one. Is it lost?" It was. The editor held one+ save per film and the undo stack dies with the tab, so editing past a good+ arrangement destroyed it silently.+ """++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.d = Path(self.tmp.name)++ def _edit(self, rev=0):+ return {"version": sedit.EDIT_VERSION, "board_id": "b", "revision": rev,+ "source": "manual", "audio": None, "beats": None, "settings": {},+ "clips": [{"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 2.0, "film_start": 0.0,+ "film_end": 2.0, "source": "human", "locked": False}]}++ def test_the_outgoing_save_lands_in_history(self):+ sedit.save_edit(self.d, self._edit()) # rev 1 on disk+ sedit.save_edit(self.d, sedit.load_edit(self.d)) # rev 2; rev 1 -> history+ # A save the user pressed lands in the MANUAL lane, which the prune+ # never walks — "so the user can go back and see the manual saves".+ hist = sorted(sedit.history_dir(self.d).glob("save-r*.json"))+ self.assertEqual(len(hist), 1)+ old = json.loads(hist[0].read_text())+ self.assertEqual(old["revision"], 1)+ self.assertEqual(old["origin"], "manual")+ self.assertEqual(list(sedit.history_dir(self.d).glob("edit-r*.json")), [])++ def test_the_automatic_lane_is_capped(self):+ e = self._edit()+ sedit.save_edit(self.d, e, origin="auto")+ for _ in range(sedit.EDIT_HISTORY_KEEP + 10):+ sedit.save_edit(self.d, sedit.load_edit(self.d), origin="auto")+ hist = list(sedit.history_dir(self.d).glob("edit-r*.json"))+ self.assertLessEqual(len(hist), sedit.EDIT_HISTORY_KEEP)++ def test_the_users_own_saves_are_never_pruned(self):+ # The lane the prune must not be able to reach: fifty debounced+ # snapshots would otherwise delete an afternoon of decisions.+ sedit.save_edit(self.d, self._edit())+ for _ in range(sedit.EDIT_HISTORY_KEEP + 20):+ sedit.save_edit(self.d, sedit.load_edit(self.d))+ mine = list(sedit.history_dir(self.d).glob("save-r*.json"))+ self.assertGreater(len(mine), sedit.EDIT_HISTORY_KEEP)+ rows = sedit.list_history(self.d)+ self.assertTrue(all(r["manual"] for r in rows))+ self.assertTrue(all(r["origin"] == "manual" for r in rows))++ def test_a_failing_history_write_never_blocks_the_save(self):+ sedit.save_edit(self.d, self._edit())+ # a FILE named history blocks mkdir — the save must still land+ (self.d / "history").write_text("not a directory") if not (self.d / "history").exists() else None+ import shutil+ shutil.rmtree(self.d / "history", ignore_errors=True)+ (self.d / "history").write_text("not a directory")+ out = sedit.save_edit(self.d, sedit.load_edit(self.d))+ self.assertTrue(out.is_file())+ self.assertEqual(sedit.load_edit(self.d)["revision"], 2)+++class TheSoundtrackIsAnObject(unittest.TestCase):+ """Wave 4 — `offset` + `trim_start` + `trim_end`, and the one function+ that turns them into what ffmpeg is told.++ The owner, cutting: the music must drag "back and forth however you want"+ and trim at both ends, "features similar to what you did with the clips".+ Everything here is the arithmetic behind that, and the promise that a+ timeline written before today still means exactly what it meant.+ """++ def test_an_untouched_track_asks_for_nothing(self):+ w = sedit.music_window({"path": "/x/s.wav", "offset": 0,+ "duration": 60})+ self.assertEqual([w["start"], w["end"], w["delay"]], [0.0, None, 0.0])++ def test_a_positive_offset_is_still_a_head_trim(self):+ # Its meaning predates the editor and every edit.json on disk relies+ # on it: the TRACK second that plays at film zero.+ w = sedit.music_window({"offset": 5, "duration": 60})+ self.assertEqual([w["start"], w["delay"]], [5.0, 0.0])++ def test_a_negative_offset_delays_the_music_into_the_film(self):+ w = sedit.music_window({"offset": -4, "duration": 60})+ self.assertEqual([w["start"], w["delay"]], [0.0, 4.0])++ def test_a_head_trim_becomes_silence_in_front_not_a_ripple(self):+ # Trimming the music's left edge must not slide the rest of the track+ # earlier — music does not ripple.+ w = sedit.music_window({"offset": 0, "trim_start": 8, "duration": 60})+ self.assertEqual([w["start"], w["delay"]], [8.0, 8.0])++ def test_a_tail_trim_is_a_track_second(self):+ w = sedit.music_window({"offset": 0, "trim_start": 8, "trim_end": 20,+ "duration": 60})+ self.assertEqual([w["start"], w["end"], w["delay"]], [8.0, 20.0, 8.0])++ def test_a_trim_past_the_end_of_the_track_is_no_trim(self):+ w = sedit.music_window({"offset": 0, "trim_end": 99, "duration": 60})+ self.assertIsNone(w["end"])++ def test_a_window_the_trims_closed_is_no_window(self):+ # Not a zero-length atrim, which ffmpeg refuses outright.+ w = sedit.music_window({"offset": 30, "trim_end": 20, "duration": 60})+ self.assertIsNone(w["end"])++ def test_the_offset_and_a_head_trim_do_not_add_up(self):+ # They are the same gesture from two directions; whichever cuts more+ # wins, and neither is applied twice.+ w = sedit.music_window({"offset": 5, "trim_start": 9, "duration": 60})+ self.assertEqual([w["start"], w["delay"]], [9.0, 4.0])+ w = sedit.music_window({"offset": 9, "trim_start": 5, "duration": 60})+ self.assertEqual([w["start"], w["delay"]], [9.0, 0.0])++ # ---- what the validator will and will not take -----------------------+ def test_the_trims_are_optional_so_every_old_document_is_valid(self):+ e = _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)],+ audio={"path": "/x/s.wav", "offset": 0, "mode": "under"})+ self.assertEqual(sedit.validate_edit(e), [])++ def test_a_negative_offset_is_legal_and_a_negative_trim_is_not(self):+ ok = _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)],+ audio={"path": "/x/s.wav", "offset": -4})+ self.assertEqual(sedit.validate_edit(ok), [])+ bad = _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)],+ audio={"path": "/x/s.wav", "offset": 0, "trim_start": -1})+ self.assertIn("audio_trim_start_range",+ [e["code"] for e in sedit.validate_edit(bad)])++ def test_a_trim_window_that_closes_is_refused_on_the_way_in(self):+ bad = _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)],+ audio={"path": "/x/s.wav", "trim_start": 9,+ "trim_end": 4})+ self.assertIn("audio_trim_window",+ [e["code"] for e in sedit.validate_edit(bad)])++ def test_a_non_numeric_offset_is_refused(self):+ bad = _edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)],+ audio={"path": "/x/s.wav", "offset": "later"})+ self.assertIn("audio_offset",+ [e["code"] for e in sedit.validate_edit(bad)])++ # ---- neutral is absent, the same rule `adjust` follows ---------------+ def test_dragging_a_trim_back_to_the_edge_leaves_no_trace(self):+ doc = sedit.normalise_edit(_edit(+ [_clip("/x/a.mp4", 0.0, 3.0, 0.0)],+ audio={"path": "/x/s.wav", "offset": 0, "duration": 60,+ "trim_start": 0, "trim_end": 60}))+ self.assertNotIn("trim_start", doc["audio"])+ self.assertNotIn("trim_end", doc["audio"])++ def test_a_real_trim_survives_the_round_trip(self):+ doc = sedit.normalise_edit(_edit(+ [_clip("/x/a.mp4", 0.0, 3.0, 0.0)],+ audio={"path": "/x/s.wav", "offset": -2.5, "duration": 60,+ "trim_start": 4, "trim_end": 30}))+ self.assertEqual(doc["audio"]["offset"], -2.5)+ self.assertEqual(doc["audio"]["trim_start"], 4.0)+ self.assertEqual(doc["audio"]["trim_end"], 30.0)++ def test_no_soundtrack_still_normalises(self):+ doc = sedit.normalise_edit(_edit([_clip("/x/a.mp4", 0.0, 3.0, 0.0)]))+ self.assertIsNone(doc["audio"])++ def test_the_version_does_not_move_for_an_optional_field(self):+ # A bump would refuse every timeline anybody already has. Absent means+ # untrimmed, which is what absence already meant.+ self.assertEqual(sedit.EDIT_VERSION, 2)+++class HistoryAndVersions(unittest.TestCase):+ """Wave 4 — a named version the prune cannot take, and a way back to it."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.d = Path(self.tmp.name)++ def _doc(self, rev=0, n=1):+ return {"version": sedit.EDIT_VERSION, "board_id": "b", "revision": rev,+ "source": "manual", "audio": None, "beats": None,+ "settings": {},+ "clips": [{"id": f"c{i}", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 2.0, "film_start": 2.0 * i,+ "film_end": 2.0 * (i + 1), "source": "human",+ "locked": False} for i in range(n)]}++ # ---- naming one -----------------------------------------------------+ def test_a_named_version_lands_under_its_own_prefix(self):+ sedit.save_edit(self.d, self._doc())+ dst = sedit.archive_edit(self.d, sedit.load_edit(self.d), "the good one")+ self.assertTrue(dst.name.startswith("keep-r"))+ self.assertIn("the-good-one", dst.name)+ self.assertEqual(json.loads(dst.read_text())["label"], "the good one")++ def test_naming_a_version_does_not_move_the_revision(self):+ sedit.save_edit(self.d, self._doc())+ before = sedit.load_edit(self.d)["revision"]+ sedit.archive_edit(self.d, sedit.load_edit(self.d), "keeper")+ self.assertEqual(sedit.load_edit(self.d)["revision"], before)++ def test_the_prune_never_takes_a_named_version(self):+ sedit.save_edit(self.d, self._doc())+ sedit.archive_edit(self.d, sedit.load_edit(self.d), "keeper")+ for _ in range(sedit.EDIT_HISTORY_KEEP + 20):+ sedit.save_edit(self.d, sedit.load_edit(self.d))+ kept = list(sedit.history_dir(self.d).glob("keep-r*.json"))+ auto = list(sedit.history_dir(self.d).glob("edit-r*.json"))+ self.assertEqual(len(kept), 1)+ self.assertLessEqual(len(auto), sedit.EDIT_HISTORY_KEEP)++ def test_archiving_the_same_revision_twice_is_not_two_files(self):+ sedit.save_edit(self.d, self._doc())+ doc = sedit.load_edit(self.d)+ self.assertIsNotNone(sedit.archive_edit(self.d, doc, "one"))+ self.assertIsNone(sedit.archive_edit(self.d, doc, "one"))++ # ---- listing --------------------------------------------------------+ def test_the_listing_is_newest_first_and_says_what_it_would_restore(self):+ sedit.save_edit(self.d, self._doc(n=1))+ sedit.save_edit(self.d, self._doc(rev=1, n=3))+ rows = sedit.list_history(self.d)+ self.assertTrue(rows)+ self.assertEqual(rows[0]["clips"], 1) # the rev-1 doc, archived last+ self.assertEqual(rows[0]["duration"], 2.0)+ self.assertFalse(rows[0]["kept"])++ def test_an_unreadable_entry_is_reported_and_not_swallowed(self):+ # A file that vanishes from the list is indistinguishable from one that+ # was never written, and the point of the folder is seeing what is left.+ sedit.history_dir(self.d).mkdir(parents=True, exist_ok=True)+ (sedit.history_dir(self.d) / "edit-r00007.json").write_text("{ broken")+ rows = sedit.list_history(self.d)+ self.assertEqual(len(rows), 1)+ self.assertFalse(rows[0]["readable"])++ def test_no_history_is_an_empty_list_not_an_error(self):+ self.assertEqual(sedit.list_history(self.d), [])++ # ---- restoring ------------------------------------------------------+ def test_restore_puts_the_arrangement_back(self):+ sedit.save_edit(self.d, self._doc(n=3)) # rev 1: three clips+ sedit.save_edit(self.d, self._doc(rev=1, n=1)) # rev 2: one clip+ old = [r for r in sedit.list_history(self.d) if r["clips"] == 3][0]+ doc = sedit.restore_edit(self.d, old["file"])+ self.assertEqual(len(doc["clips"]), 3)++ def test_restore_keeps_what_it_replaced(self):+ sedit.save_edit(self.d, self._doc(n=3))+ sedit.save_edit(self.d, self._doc(rev=1, n=1))+ old = [r for r in sedit.list_history(self.d) if r["clips"] == 3][0]+ sedit.restore_edit(self.d, old["file"])+ # the one-clip arrangement it overwrote is still in the folder+ self.assertTrue(any(r["clips"] == 1 for r in sedit.list_history(self.d)))++ def test_restore_moves_the_revision_forward_never_back(self):+ sedit.save_edit(self.d, self._doc(n=3))+ sedit.save_edit(self.d, self._doc(rev=1, n=1))+ now = sedit.load_edit(self.d)["revision"]+ old = [r for r in sedit.list_history(self.d) if r["clips"] == 3][0]+ doc = sedit.restore_edit(self.d, old["file"])+ self.assertEqual(doc["revision"], now + 1)++ def test_restore_migrates_a_version_written_by_an_older_build(self):+ sedit.save_edit(self.d, self._doc())+ hist = sedit.history_dir(self.d)+ hist.mkdir(parents=True, exist_ok=True)+ v1 = dict(self._doc(rev=4, n=2), version=1)+ (hist / "keep-r00004-old.json").write_text(json.dumps(v1))+ doc = sedit.restore_edit(self.d, "keep-r00004-old.json")+ self.assertEqual(doc["version"], sedit.EDIT_VERSION)+ self.assertEqual(len(doc["clips"]), 2)++ def test_the_label_does_not_ride_back_into_the_live_document(self):+ sedit.save_edit(self.d, self._doc())+ sedit.archive_edit(self.d, sedit.load_edit(self.d), "keeper")+ name = [r["file"] for r in sedit.list_history(self.d) if r["kept"]][0]+ doc = sedit.restore_edit(self.d, name)+ self.assertNotIn("label", doc)+ self.assertNotIn("archived_at", doc)++ def test_a_name_that_leaves_the_folder_is_refused(self):+ sedit.save_edit(self.d, self._doc())+ for bad in ("../edit.json", "/etc/passwd", "sub/x.json", "", "x.txt"):+ with self.subTest(bad=bad):+ with self.assertRaises(sedit.EditError):+ sedit.restore_edit(self.d, bad)++ def test_restoring_something_that_is_not_there_is_an_error(self):+ with self.assertRaises(sedit.EditError):+ sedit.restore_edit(self.d, "keep-r09999-nope.json")+++class VersionRoutes(EditorCase):+ """The three seams the panel exposes for it."""++ def _prime(self):+ clips = [self.out / "a.mp4"]+ for c in clips:+ c.write_bytes(b"0" * 32)+ board = _board(clips)+ storyboard.save_storyboard(self.state, board)+ bdir = self.state / "storyboards" / board["id"]+ sedit.save_edit(bdir, _edit([_clip(str(clips[0]), 0.0, 2.0, 0.0)]))+ return board, bdir++ def test_versions_lists_and_version_keeps(self):+ board, bdir = self._prime()+ h = FakeHandler().post("edit/version", {"id": board["id"],+ "label": "first pass"})+ self.assertTrue(h.payload["ok"])+ self.assertTrue(h.payload["file"].startswith("keep-r"))+ g = FakeHandler().get("/storyboard/edit/versions?id=" + board["id"])+ self.assertTrue(g.payload["ok"])+ self.assertEqual(g.payload["keep"], sedit.EDIT_HISTORY_KEEP)+ self.assertTrue(any(v["label"] == "first pass"+ for v in g.payload["versions"]))++ def test_a_version_needs_a_name(self):+ board, _ = self._prime()+ h = FakeHandler().post("edit/version", {"id": board["id"], "label": " "})+ self.assertFalse(h.payload["ok"])+ self.assertEqual(h.status, 400)++ def test_restore_answers_with_the_whole_payload(self):+ board, bdir = self._prime()+ sedit.save_edit(bdir, _edit([])) # wipe it, on purpose+ old = [v for v in sedit.list_history(bdir) if v["clips"] == 1][0]+ h = FakeHandler().post("edit/restore", {"id": board["id"],+ "file": old["file"]})+ self.assertTrue(h.payload["ok"])+ self.assertEqual(len(h.payload["edit"]["clips"]), 1)+ self.assertIn("versions", h.payload)+ self.assertIn("proxy_url", h.payload) # the full read shape++ def test_restore_is_refused_while_the_film_is_rendering(self):+ board, bdir = self._prime()+ sedit.save_edit(bdir, sedit.load_edit(bdir)) # one entry in history+ old = sedit.list_history(bdir)[0]+ with mock.patch.dict(panel._SB_RENDERS,+ {board["id"]: {"stop": False}}, clear=False):+ h = FakeHandler().post("edit/restore", {"id": board["id"],+ "file": old["file"]})+ self.assertFalse(h.payload["ok"])+ self.assertEqual(h.status, 409)+ self.assertTrue(h.payload["busy"])++ def test_a_restore_that_escapes_the_folder_is_a_400(self):+ board, _ = self._prime()+ h = FakeHandler().post("edit/restore", {"id": board["id"],+ "file": "../edit.json"})+ self.assertFalse(h.payload["ok"])+ self.assertEqual(h.status, 400)+++class UploadIntoThePool(unittest.TestCase):+ """Wave 4 — "you cannot upload your own images and insert them into the+ timeline". Where the bytes land is the whole design."""++ IMAGES = {".png", ".jpg", ".jpeg", ".webp"}+ VIDEOS = {".mp4", ".mov", ".m4v", ".webm"}++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)+ self.up = self.root / "panel_uploads"+ self.out = self.root / "outputs"+ self.up.mkdir()+ self.out.mkdir()+ self._patches = [+ mock.patch.object(panel, "UPLOADS", self.up),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "STATE_DIR", self.root / "state"),+ mock.patch.object(panel, "push", lambda *a, **k: None),+ ]+ for q in self._patches:+ q.start()+ self.addCleanup(lambda: [q.stop() for q in reversed(self._patches)])++ def accept(self, name, data=b"bytes"):+ return panel._sbe_accept_upload(name, data, images=self.IMAGES,+ videos=self.VIDEOS)++ def test_a_picture_lands_where_the_gallery_already_looks(self):+ # list_outputs walks UPLOADS/library/manual — so the still turns up in+ # the Images source by itself, with no second listing to keep in sync.+ with mock.patch.object(panel, "_sb_probe_still",+ return_value={"w": 1024, "h": 576}):+ r = self.accept("Title Card.png")+ self.assertTrue(r["ok"])+ self.assertEqual(r["kind"], "still")+ self.assertIn("library/manual", r["path"])+ self.assertTrue(Path(r["path"]).is_file())++ def test_a_clip_is_kept_out_of_the_renders_folder(self):+ # OUTPUT means "the panel made this". A phone clip did not.+ with mock.patch.object(panel, "_sb_probe_clip",+ return_value={"w": 1920, "h": 1080,+ "duration": 7.5,+ "sample_rate": 48000,+ "has_audio": True}):+ r = self.accept("IMG_2213.mov")+ self.assertTrue(r["ok"])+ self.assertEqual(r["kind"], "video")+ self.assertEqual(r["duration_s"], 7.5)+ self.assertEqual(Path(r["path"]).parent, self.up / "timeline")+ self.assertEqual(list(self.out.iterdir()), [])++ def test_both_roots_are_ones_the_timeline_may_already_read(self):+ # The containment rule is not widened for uploads — they land inside+ # what it already allows.+ with mock.patch.object(panel, "_sb_probe_still",+ return_value={"w": 8, "h": 8}):+ img = self.accept("a.png")["path"]+ with mock.patch.object(panel, "_sb_probe_clip",+ return_value={"w": 8, "h": 8, "duration": 1.0,+ "sample_rate": 0, "has_audio": False}):+ vid = self.accept("b.mp4")["path"]+ self.assertTrue(panel._sbe_pool_path_ok(img))+ self.assertTrue(panel._sbe_pool_path_ok(vid))++ def test_a_file_that_is_not_what_it_claims_is_refused_and_deleted(self):+ # A broken .png would otherwise sit in the pool looking fine and fail+ # at the render hours later, with the upload long forgotten.+ with mock.patch.object(panel, "_sb_probe_still", return_value=None):+ r = self.accept("not-really.png")+ self.assertFalse(r["ok"])+ self.assertEqual(r["status"], 400)+ lib = self.up / "library" / "manual"+ self.assertFalse(any(p.is_file() for p in lib.rglob("*")))++ def test_an_extension_nobody_asked_for_is_refused_before_it_is_written(self):+ for name in ("payload.exe", "notes.txt", "archive.zip", "noextension"):+ with self.subTest(name=name):+ r = self.accept(name)+ self.assertFalse(r["ok"])+ self.assertEqual(r["status"], 400)+ self.assertFalse(any(p.is_file() for p in self.up.rglob("*")))++ def test_a_name_that_tries_to_walk_out_cannot(self):+ with mock.patch.object(panel, "_sb_probe_still",+ return_value={"w": 8, "h": 8}):+ r = self.accept("../../../../etc/evil.png")+ self.assertTrue(r["ok"])+ # basename only, then sanitised — it lands in the library like any other+ self.assertTrue(Path(r["path"]).resolve().is_relative_to(self.up.resolve()))+ self.assertNotIn("..", Path(r["path"]).name)++ def test_the_uploads_listing_hides_our_own_bookkeeping(self):+ (self.up / "timeline").mkdir(parents=True)+ (self.up / "timeline" / "1787000000000_IMG_2213.mov").write_bytes(b"x")+ (self.up / "timeline" / "notes.txt").write_bytes(b"x")+ h = FakeHandler().get("/storyboard/edit/uploads")+ self.assertTrue(h.payload["ok"])+ self.assertEqual([u["name"] for u in h.payload["uploads"]],+ ["IMG_2213.mov"])++ def test_no_uploads_folder_is_an_empty_list_not_an_error(self):+ h = FakeHandler().get("/storyboard/edit/uploads")+ self.assertTrue(h.payload["ok"])+ self.assertEqual(h.payload["uploads"], [])+++class DraftsAreTheUsersOwn(unittest.TestCase):+ """"He should have control over the saving, and only he should have that+ control... renaming and access to all the drafts he makes are essential."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.d = Path(self.tmp.name)++ def _doc(self, n=1, rev=0):+ return {"version": sedit.EDIT_VERSION, "board_id": "b", "revision": rev,+ "source": "human", "audio": None, "beats": None, "settings": {},+ "clips": [{"id": f"c{i}", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 2.0, "film_start": 2.0 * i,+ "film_end": 2.0 * (i + 1), "source": "human",+ "locked": False} for i in range(n)]}++ def _save(self, n=1):+ """A save that carries the counter forward, the way the route does.++ `revision` is the server's, read off disk — a fresh document at 0+ every time would make two consecutive saves land on the same archive+ name, which is the collision these tests are about.+ """+ doc = self._doc(n=n)+ doc["revision"] = int((sedit._read_json(sedit.edit_path(self.d)) or {})+ .get("revision") or 0)+ return sedit.save_edit(self.d, doc)++ # ---- migration -------------------------------------------------------+ def test_a_board_written_before_drafts_has_exactly_one(self):+ # No migration pass, nothing to half-finish: the file it already has+ # IS the draft, and looking is what names it.+ sedit.save_edit(self.d, self._doc(n=3))+ rows = sedit.list_drafts(self.d)+ self.assertEqual(len(rows), 1)+ self.assertTrue(rows[0]["active"])+ self.assertEqual(rows[0]["clips"], 3)+ self.assertEqual(rows[0]["name"], "Draft 1")++ def test_the_active_draft_is_edit_json_and_nothing_shadows_it(self):+ # One copy of any draft, ever — the active one lives where every+ # existing reader already looks.+ sedit.save_edit(self.d, self._doc())+ sedit.list_drafts(self.d)+ self.assertFalse((sedit.drafts_dir(self.d) / "draft-1.json").exists())++ # ---- the verbs -------------------------------------------------------+ def test_a_new_draft_from_current_copies_the_cut(self):+ sedit.save_edit(self.d, self._doc(n=4))+ out = sedit.create_draft(self.d, "variation", from_current=True)+ self.assertEqual(out["name"], "variation")+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 4)+ # ...and the one it came from is still whole, in its own file.+ stashed = json.loads((sedit.drafts_dir(self.d) / "draft-1.json").read_text())+ self.assertEqual(len(stashed["clips"]), 4)++ def test_an_empty_draft_keeps_the_soundtrack(self):+ # The track is a fact about the film, not about the arrangement.+ doc = self._doc(n=2)+ doc["audio"] = {"path": "/x/s.wav", "offset": 0, "mode": "under"}+ sedit.save_edit(self.d, doc)+ sedit.create_draft(self.d, "from scratch")+ fresh = sedit.load_edit(self.d)+ self.assertEqual(fresh["clips"], [])+ self.assertEqual(fresh["audio"]["path"], "/x/s.wav")++ def test_switching_drafts_never_loses_the_one_being_left(self):+ sedit.save_edit(self.d, self._doc(n=5))+ sedit.create_draft(self.d, "second")+ sedit.save_edit(self.d, dict(sedit.load_edit(self.d), clips=[]))+ sedit.activate_draft(self.d, "draft-1")+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 5)+ sedit.activate_draft(self.d, "second")+ self.assertEqual(sedit.load_edit(self.d)["clips"], [])++ def test_duplicate_lands_on_the_copy(self):+ sedit.save_edit(self.d, self._doc(n=2))+ out = sedit.duplicate_draft(self.d, "draft-1", "take two")+ rows = {r["slug"]: r for r in sedit.list_drafts(self.d)}+ self.assertTrue(rows[out["slug"]]["active"])+ self.assertEqual(rows[out["slug"]]["clips"], 2)+ self.assertEqual(len(rows), 2)++ def test_renaming_does_not_move_a_file(self):+ # The slug is the identity, so a rename can never orphan a draft's+ # file or its backup.+ sedit.save_edit(self.d, self._doc())+ sedit.create_draft(self.d, "b roll")+ before = sorted(p.name for p in sedit.drafts_dir(self.d).iterdir())+ sedit.rename_draft(self.d, "b-roll", "the good b roll")+ after = sorted(p.name for p in sedit.drafts_dir(self.d).iterdir())+ self.assertEqual(before, after)+ names = [r["name"] for r in sedit.list_drafts(self.d)]+ self.assertIn("the good b roll", names)++ def test_the_last_draft_cannot_be_deleted(self):+ # An editor with no document is not a state this app has.+ sedit.save_edit(self.d, self._doc())+ with self.assertRaises(sedit.EditError):+ sedit.delete_draft(self.d, "draft-1")++ def test_deleting_the_active_draft_lands_on_a_neighbour_first(self):+ sedit.save_edit(self.d, self._doc(n=3))+ sedit.create_draft(self.d, "scratch")+ sedit.delete_draft(self.d, "scratch")+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 3)+ self.assertEqual([r["slug"] for r in sedit.list_drafts(self.d)], ["draft-1"])++ def _make_v1_on_disk(self):+ """The state every board written before EDIT_VERSION 2 is still in.++ Migration is READ-path only, so `edit.json` stays v1 on disk until its+ next save — which for a board somebody opens and immediately copies a+ draft from is never.+ """+ sedit.save_edit(self.d, self._doc(n=3))+ p = sedit.edit_path(self.d)+ doc = json.loads(p.read_text())+ doc["version"] = 1+ for c in doc["clips"]:+ c.pop("kind", None)+ p.write_text(json.dumps(doc))+ return doc++ def test_a_draft_can_be_copied_from_a_board_written_before_v2(self):+ self._make_v1_on_disk()+ out = sedit.create_draft(self.d, "take two", from_current=True)+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 3)+ self.assertEqual(sedit.load_draft_index(self.d)["active"], out["slug"])++ def test_duplicate_works_on_a_board_written_before_v2(self):+ self._make_v1_on_disk()+ out = sedit.duplicate_draft(self.d, "draft-1")+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 3)+ self.assertEqual(sedit.load_draft_index(self.d)["active"], out["slug"])++ def test_an_empty_draft_off_a_v1_board_carries_its_soundtrack(self):+ self._make_v1_on_disk()+ sedit.create_draft(self.d, "empty one")+ self.assertEqual(sedit.load_edit(self.d)["clips"], [])++ def test_a_refused_draft_never_moves_the_active_pointer(self):+ # The compound failure: the index was written BEFORE the document, so+ # a save the validator refused left `list_drafts` reporting the new+ # name as active while `edit.json` still held the old draft's cut.+ sedit.save_edit(self.d, self._doc(n=3))+ with mock.patch.object(sedit, "save_edit",+ side_effect=sedit.EditError("nope")):+ with self.assertRaises(sedit.EditError):+ sedit.create_draft(self.d, "doomed", from_current=True)+ idx = sedit.load_draft_index(self.d)+ self.assertEqual(idx["active"], "draft-1")+ self.assertEqual([d["slug"] for d in idx["drafts"]], ["draft-1"])+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 3)++ def test_a_refused_activate_leaves_the_film_on_the_draft_it_was_on(self):+ sedit.save_edit(self.d, self._doc(n=3))+ sedit.create_draft(self.d, "other")+ with mock.patch.object(sedit, "save_edit",+ side_effect=sedit.EditError("nope")):+ with self.assertRaises(sedit.EditError):+ sedit.activate_draft(self.d, "draft-1")+ self.assertEqual(sedit.load_draft_index(self.d)["active"], "other")++ def test_two_drafts_with_one_name_get_two_slugs(self):+ sedit.save_edit(self.d, self._doc())+ a = sedit.create_draft(self.d, "take")+ b = sedit.create_draft(self.d, "take")+ self.assertNotEqual(a["slug"], b["slug"])++ # ---- history belongs to a draft --------------------------------------+ def test_two_drafts_do_not_share_one_history(self):+ # THE COLLISION: entries were named by revision alone in one folder+ # per BOARD, while every new draft restarts its revision at zero. So+ # draft B's rev 1 collided with draft A's, archive_edit dropped it+ # silently, and the picker shown while B was open listed A's saves.+ self._save(n=1)+ self._save(n=2) # rev 1 -> draft-1's+ sedit.create_draft(self.d, "take two")+ self._save(n=7)+ self._save(n=8) # -> take-two's own+ self.assertIn(7, [r["clips"] for r in sedit.list_history(self.d)])+ self.assertNotIn(1, [r["clips"] for r in sedit.list_history(self.d)])+ sedit.activate_draft(self.d, "draft-1")+ # Draft 1's own two: the save it made, and the cut it was holding when+ # the second draft was branched off it. Neither of the other draft's.+ self.assertEqual([r["clips"] for r in sedit.list_history(self.d)], [2, 1])++ def test_restore_refuses_a_version_belonging_to_another_draft(self):+ self._save(n=1)+ sedit.archive_edit(self.d, sedit.load_edit(self.d), "almost final")+ theirs = [r["file"] for r in sedit.list_history(self.d) if r["kept"]][0]+ sedit.create_draft(self.d, "take two")+ self._save(n=7)+ with self.assertRaises(sedit.EditError):+ sedit.restore_edit(self.d, theirs)+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 7)+ # ...and it is still there for the draft it belongs to.+ sedit.activate_draft(self.d, "draft-1")+ self.assertEqual(len(sedit.restore_edit(self.d, theirs)["clips"]), 1)++ def test_deleting_a_draft_takes_its_past_saves_with_it(self):+ # What the panel says when it asks, made true.+ sedit.save_edit(self.d, self._doc(n=1))+ sedit.create_draft(self.d, "scratch")+ sedit.save_edit(self.d, self._doc(n=4))+ sedit.save_edit(self.d, self._doc(n=5))+ self.assertTrue(sedit.history_dir(self.d, "scratch").is_dir())+ sedit.delete_draft(self.d, "scratch")+ self.assertFalse(sedit.history_dir(self.d, "scratch").exists())+ self.assertTrue(sedit.history_dir(self.d, "draft-1").exists()+ or not sedit.list_history(self.d))++ def test_history_written_before_drafts_is_folded_into_the_first_draft(self):+ # A board that already has fifty saves must not lose them to a folder+ # nothing lists any more.+ sedit.save_edit(self.d, self._doc(n=1))+ sedit.save_edit(self.d, self._doc(n=2))+ home = sedit.history_dir(self.d, "draft-1")+ root = self.d / "history"+ for p in list(home.glob("*.json")):+ p.replace(root / p.name) # put it back the old way+ home.rmdir()+ rows = sedit.list_history(self.d)+ self.assertEqual([r["clips"] for r in rows], [1])+ self.assertTrue((sedit.history_dir(self.d, "draft-1")+ / rows[0]["file"]).is_file())++ def test_an_interrupted_atomic_write_is_not_a_version(self):+ # pathlib's glob returns dotfiles and `_atomic_json` writes its temp+ # beside the target, so a crash mid-write used to leave a clickable+ # row with no name and revision None.+ sedit.save_edit(self.d, self._doc(n=1))+ sedit.save_edit(self.d, self._doc(n=2))+ hist = sedit.history_dir(self.d)+ (hist / ".edit-abcdef.json").write_text('{"version": 2}')+ self.assertEqual(len(sedit.list_history(self.d)), 1)+ with self.assertRaises(sedit.EditError):+ sedit.restore_edit(self.d, ".edit-abcdef.json")++ # ---- the quiet lane --------------------------------------------------+ def test_a_backup_never_touches_the_saved_draft(self):+ sedit.save_edit(self.d, self._doc(n=2))+ saved = sedit.load_edit(self.d)+ sedit.write_backup(self.d, dict(self._doc(n=7), revision=saved["revision"]))+ after = sedit.load_edit(self.d)+ self.assertEqual(len(after["clips"]), 2)+ self.assertEqual(after["revision"], saved["revision"])++ def test_a_newer_backup_is_offered_not_applied(self):+ sedit.save_edit(self.d, self._doc(n=2))+ sedit.write_backup(self.d, self._doc(n=6))+ offer = sedit.pending_backup(self.d)+ self.assertIsNotNone(offer)+ self.assertEqual(offer["clips"], 6)+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 2) # untouched++ def test_a_backup_of_what_is_already_saved_is_not_a_nag(self):+ sedit.save_edit(self.d, self._doc(n=2))+ sedit.write_backup(self.d, sedit.load_edit(self.d))+ self.assertIsNone(sedit.pending_backup(self.d))++ def test_recovering_keeps_the_draft_it_replaces(self):+ sedit.save_edit(self.d, self._doc(n=2))+ sedit.write_backup(self.d, self._doc(n=6))+ doc = sedit.recover_backup(self.d)+ self.assertEqual(len(doc["clips"]), 6)+ self.assertTrue(any(r["clips"] == 2 for r in sedit.list_history(self.d)))+ # ...and the offer is spent, not left to be made again.+ self.assertIsNone(sedit.pending_backup(self.d))++ def test_the_backup_is_not_listed_as_a_past_save(self):+ # "Recover" and "Restore" mean two different things; side by side in+ # one list they would read as one.+ sedit.save_edit(self.d, self._doc())+ sedit.write_backup(self.d, self._doc(n=3))+ self.assertFalse(any(r["file"].startswith("backup-")+ for r in sedit.list_history(self.d)))++ def test_each_draft_has_its_own_backup(self):+ sedit.save_edit(self.d, self._doc(n=2))+ sedit.write_backup(self.d, self._doc(n=9))+ sedit.create_draft(self.d, "other")+ self.assertIsNone(sedit.pending_backup(self.d)) # not this draft's+ sedit.activate_draft(self.d, "draft-1")+ self.assertIsNotNone(sedit.pending_backup(self.d))++ def test_an_offer_survives_everything_that_is_not_the_user_answering(self):+ # THE TWENTY MINUTES, THE SECOND TIME. The offer used to be suppressed+ # by a wall clock: `backed_up_at < updated_at` and it was gone. But+ # `updated_at` moves on every write, and three of them are not the+ # user's — a draft switch, an auto-edit, a restore — so unsaved work+ # that had only ever reached the crash lane became unreachable while+ # the file sat on disk holding the only copy of it.+ sedit.save_edit(self.d, self._doc(n=2))+ sedit.write_backup(self.d, self._doc(n=9))+ p = sedit.latest_snapshot(self.d)[0]+ doc = json.loads(p.read_text())+ doc["backed_up_at"] = 1 # as old as the clock can make it+ p.write_text(json.dumps(doc))+ sedit.create_draft(self.d, "other")+ sedit.activate_draft(self.d, "draft-1")+ sedit.save_edit(self.d, self._doc(n=2), origin="auto")+ offer = sedit.pending_backup(self.d)+ self.assertIsNotNone(offer)+ self.assertEqual(offer["clips"], 9)++ def test_the_backup_records_the_revision_it_followed(self):+ sedit.save_edit(self.d, self._doc(n=2))+ rev = sedit.load_edit(self.d)["revision"]+ sedit.write_backup(self.d, self._doc(n=9))+ doc = sedit.latest_snapshot(self.d)[1]+ self.assertEqual(doc["backup_revision"], rev)++ def test_a_backup_composed_on_a_draft_the_user_has_left_is_refused(self):+ # The client debounces this write and the server is threaded, so a+ # backup composed while draft A was on screen can arrive after the+ # user clicked draft B. Filed under B, it is A's arrangement offered+ # back as B's unsaved work — and recovering it would install A's cut+ # over B's saved document.+ sedit.save_edit(self.d, self._doc(n=2))+ sedit.create_draft(self.d, "other")+ with self.assertRaises(sedit.EditError):+ sedit.write_backup(self.d, self._doc(n=9), draft="draft-1")+ self.assertIsNone(sedit.pending_backup(self.d))+ # ...and a caller that names the draft it IS on is written normally.+ sedit.write_backup(self.d, self._doc(n=9), draft="other")+ self.assertIsNotNone(sedit.pending_backup(self.d))++ def test_recover_refuses_a_backup_the_save_has_already_answered(self):+ # A client can hold a stale offer — it saved a second ago and the+ # amber bar is still on screen in another tab. Applying that would+ # archive the good save and install an older arrangement over it.+ sedit.save_edit(self.d, self._doc(n=2))+ sedit.write_backup(self.d, self._doc(n=6))+ sedit.save_edit(self.d, self._doc(n=6)) # the user saved it+ with self.assertRaises(sedit.EditError):+ sedit.recover_backup(self.d)+ self.assertEqual(len(sedit.load_edit(self.d)["clips"]), 6)+++class DraftRoutes(EditorCase):+ def _prime(self):+ clip = self.out / "a.mp4"+ clip.write_bytes(b"0" * 32)+ board = _board([clip])+ storyboard.save_storyboard(self.state, board)+ bdir = self.state / "storyboards" / board["id"]+ sedit.save_edit(bdir, _edit([_clip(str(clip), 0.0, 2.0, 0.0)]))+ return board, bdir++ def test_the_read_payload_carries_the_drafts_and_any_offer(self):+ board, _ = self._prime()+ h = FakeHandler().get("/storyboard/edit?id=" + board["id"])+ self.assertIn("drafts", h.payload)+ self.assertEqual(h.payload["active_draft"], "draft-1")+ self.assertIsNone(h.payload["backup"])++ def test_one_route_serves_every_draft_verb(self):+ board, bdir = self._prime()+ h = FakeHandler().post("edit/draft", {"id": board["id"], "op": "new",+ "name": "variation",+ "from": "current"})+ self.assertTrue(h.payload["ok"])+ self.assertEqual(h.payload["draft"]["name"], "variation")+ self.assertEqual(h.payload["active_draft"], h.payload["draft"]["slug"])+ h = FakeHandler().post("edit/draft", {"id": board["id"], "op": "rename",+ "slug": "variation",+ "name": "the good one"})+ self.assertTrue(h.payload["ok"])+ h = FakeHandler().post("edit/draft", {"id": board["id"],+ "op": "activate",+ "slug": "draft-1"})+ self.assertTrue(h.payload["ok"])+ self.assertEqual(h.payload["active_draft"], "draft-1")++ def test_an_unknown_draft_verb_is_refused(self):+ board, _ = self._prime()+ h = FakeHandler().post("edit/draft", {"id": board["id"], "op": "yolo"})+ self.assertFalse(h.payload["ok"])+ self.assertEqual(h.status, 400)++ def test_changing_drafts_is_refused_while_the_film_renders(self):+ board, _ = self._prime()+ with mock.patch.dict(panel._SB_RENDERS,+ {board["id"]: {"stop": False}}, clear=False):+ h = FakeHandler().post("edit/draft", {"id": board["id"],+ "op": "activate",+ "slug": "draft-1"})+ self.assertEqual(h.status, 409)+ self.assertTrue(h.payload["busy"])++ def test_the_backup_route_writes_no_revision(self):+ board, bdir = self._prime()+ before = sedit.load_edit(bdir)["revision"]+ payload = {"id": board["id"], "edit": _edit([])}+ h = FakeHandler().post("edit/backup", None, json.dumps(payload))+ self.assertTrue(h.payload["ok"])+ after = sedit.load_edit(bdir)+ self.assertEqual(after["revision"], before)+ self.assertEqual(len(after["clips"]), 1) # the draft is untouched++ def test_recover_answers_with_the_whole_payload(self):+ board, bdir = self._prime()+ sedit.write_backup(bdir, _edit([]))+ h = FakeHandler().post("edit/recover", {"id": board["id"]})+ self.assertTrue(h.payload["ok"])+ self.assertEqual(h.payload["edit"]["clips"], [])+ self.assertIn("proxy_url", h.payload)++ def test_saving_answers_the_offer_and_takes_the_file_with_it(self):+ # A SAVE IS THE USER ANSWERING. Left behind, the file kept the amber+ # bar on screen over a saved film, armed a Recover button that would+ # have reverted the save, and — because write_backup refuses to+ # overwrite an unanswered offer — killed the crash lane for the rest+ # of the session, at which point the watchdog started calling a+ # healthy panel broken.+ board, bdir = self._prime()+ sedit.write_backup(bdir, _edit([]))+ self.assertIsNotNone(sedit.pending_backup(bdir))+ payload = {"id": board["id"], "edit": sedit.load_edit(bdir)}+ h = FakeHandler().post("edit/save", None, json.dumps(payload))+ self.assertTrue(h.payload["ok"])+ self.assertIsNone(sedit.pending_backup(bdir))+ self.assertIsNone(h.payload["backup"])+ self.assertIsNone(sedit.latest_snapshot(bdir))+ # ...and the lane is usable again on the very next write.+ sedit.write_backup(bdir, _edit([]), draft="draft-1")++ def test_the_save_payload_carries_the_drafts_it_just_changed(self):+ board, bdir = self._prime()+ payload = {"id": board["id"], "edit": sedit.load_edit(bdir)}+ h = FakeHandler().post("edit/save", None, json.dumps(payload))+ rows = h.payload["drafts"]+ self.assertEqual([r["slug"] for r in rows], ["draft-1"])+ self.assertEqual(rows[0]["revision"], sedit.load_edit(bdir)["revision"])++ def test_discard_takes_the_offer_away(self):+ board, bdir = self._prime()+ sedit.write_backup(bdir, _edit([]))+ self.assertIsNotNone(sedit.pending_backup(bdir))+ h = FakeHandler().post("edit/discard-backup", {"id": board["id"]})+ self.assertTrue(h.payload["ok"])+ self.assertIsNone(sedit.pending_backup(bdir))+++class AnUploadedPictureIsAStill(unittest.TestCase):+ """Hit live: a PNG uploaded and dragged onto the track landed with no+ `kind`, so clip_kind() called it a video, the client asked /file instead+ of /image, a <video> was handed a PNG and the preview went black — with+ nothing on screen to say why."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)+ self.state = self.root / "state"+ self.out = self.root / "outputs"+ self.up = self.root / "panel_uploads"+ for d in (self.state, self.out, self.up):+ d.mkdir()+ self.img = self.up / "library" / "manual" / "20260818" / "uploads"+ self.img.mkdir(parents=True)+ self.png = self.img / "1787_title_card.png"+ self.png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"0" * 64)+ self._p = [mock.patch.object(panel, "STATE_DIR", self.state),+ mock.patch.object(panel, "OUTPUT", self.out),+ mock.patch.object(panel, "UPLOADS", self.up),+ mock.patch.object(panel, "push", lambda *a, **k: None)]+ for q in self._p:+ q.start()+ self.addCleanup(lambda: [q.stop() for q in reversed(self._p)])+ self.board = _board([self.out / "a.mp4"])+ (self.out / "a.mp4").write_bytes(b"0" * 16)+ storyboard.save_storyboard(self.state, self.board)++ def test_the_server_calls_a_png_a_still_even_when_nobody_said_so(self):+ # This is the exact request the drag sent: a path, a title, no kind.+ with mock.patch.object(panel, "_sb_probe_still",+ return_value={"w": 1024, "h": 576}):+ h = FakeHandler().post("edit/add-clip",+ {"id": self.board["id"],+ "path": str(self.png),+ "title": "title card"})+ self.assertTrue(h.payload["ok"], h.payload)+ self.assertEqual(h.payload["clip"]["kind"], "still")+ self.assertIsNone(h.payload["clip"]["proxy"])++ def test_every_picture_extension_the_exporter_knows_is_covered(self):+ for sfx in sedit._STILL_SUFFIXES:+ with self.subTest(sfx=sfx):+ f = self.img / ("card" + sfx)+ f.write_bytes(b"0" * 32)+ with mock.patch.object(panel, "_sb_probe_still",+ return_value={"w": 8, "h": 8}):+ h = FakeHandler().post("edit/add-clip",+ {"id": self.board["id"],+ "path": str(f)})+ self.assertEqual(h.payload["clip"]["kind"], "still")++ def test_a_still_that_lands_this_way_is_a_valid_document(self):+ # The end of the bug: a clip whose kind survives into edit.json and+ # whose window is the slot, not a source clock it does not have.+ c = sedit.new_clip(str(self.png), 0.0, 3.0, 0.0, kind="still",+ source="human")+ doc = sedit.normalise_edit(_edit([c]))+ self.assertEqual(doc["clips"][0]["kind"], "still")+ self.assertIsNone(doc["clips"][0]["duration"])+ self.assertEqual(sedit.validate_edit(doc), [])++ def test_a_video_is_still_a_video(self):+ # The suffix test must not reach past pictures.+ mp4 = self.up / "timeline" / "clip.mp4"+ mp4.parent.mkdir(parents=True)+ mp4.write_bytes(b"0" * 32)+ with mock.patch.object(panel, "_sbe_proxy_now",+ return_value={"built": 1, "reused": 0, "failed": []}), \+ mock.patch("storyboard_edit.probe_media",+ return_value={"duration": 4.0}):+ h = FakeHandler().post("edit/add-clip",+ {"id": self.board["id"], "path": str(mp4)})+ self.assertTrue(h.payload["ok"], h.payload)+ self.assertNotEqual(h.payload["clip"].get("kind"), "still")+++class SplitEdits(unittest.TestCase):+ """J-cuts and L-cuts: `clip.audio`, and the promise that absent means+ linked so no document written before tonight has to change."""++ def _clip(self, **kw):+ return dict({"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 4.0, "film_start": 0.0,+ "film_end": 4.0, "source": "human", "locked": False,+ "duration": 10.0}, **kw)++ def test_absent_means_linked_and_that_is_the_migration(self):+ w = sedit.clip_audio(self._clip())+ self.assertEqual([w["start"], w["end"], w["film_start"]], [0.0, 4.0, 0.0])+ self.assertTrue(w["linked"])+ self.assertEqual(sedit.EDIT_VERSION, 2)++ def test_an_l_cut_leaves_the_sound_running_under_the_neighbour(self):+ w = sedit.clip_audio(self._clip(+ audio={"start": 0.0, "end": 6.0, "film_start": 0.0}))+ self.assertEqual(w["end"], 6.0)+ self.assertFalse(w["linked"])++ def test_a_j_cut_leads_the_sound_in_before_the_picture(self):+ w = sedit.clip_audio(self._clip(+ film_start=4.0, film_end=8.0,+ audio={"start": 0.0, "end": 4.0, "film_start": 3.0}))+ self.assertEqual(w["film_start"], 3.0)+ self.assertFalse(w["linked"])++ def test_the_field_itself_is_the_switch(self):+ # Deriving "linked" from equality looked tidier and was wrong in the+ # one case that matters: unlinking writes the window the clip already+ # had, so a just-unlinked clip read as linked and refused to be+ # dragged. Presence decides; the toggle adds or deletes.+ c = self._clip(audio={"start": 0.0, "end": 4.0, "film_start": 0.0})+ self.assertFalse(sedit.clip_audio(c)["linked"])+ doc = sedit.normalise_edit(_edit([c]))+ self.assertIn("audio", doc["clips"][0])+ self.assertTrue(sedit.clip_audio(self._clip())["linked"])++ def test_a_real_split_survives_the_round_trip(self):+ doc = sedit.normalise_edit(_edit([self._clip(+ audio={"start": 0.5, "end": 4.0, "film_start": 0.5})]))+ self.assertEqual(doc["clips"][0]["audio"],+ {"start": 0.5, "end": 4.0, "film_start": 0.5})+ self.assertEqual(sedit.validate_edit(doc), [])++ def test_only_a_video_clip_has_sound_to_unlink(self):+ c = {"id": "s", "kind": "slug", "path": None, "start": 0.0, "end": 2.0,+ "film_start": 0.0, "film_end": 2.0, "source": "human",+ "locked": False, "audio": {"start": 0, "end": 1, "film_start": 0}}+ self.assertIn("clip_audio_kind",+ [e["code"] for e in sedit.validate_edit(_edit([c]))])+ # ...and normalise takes it off rather than leaving a document that+ # cannot be saved.+ self.assertNotIn("audio", sedit.normalise_edit(_edit([c]))["clips"][0])++ def test_a_backwards_sound_window_is_refused(self):+ c = self._clip(audio={"start": 3.0, "end": 1.0, "film_start": 0.0})+ self.assertIn("clip_audio_window",+ [e["code"] for e in sedit.validate_edit(_edit([c]))])++ def test_sound_past_the_end_of_its_source_is_refused(self):+ c = self._clip(duration=5.0,+ audio={"start": 0.0, "end": 9.0, "film_start": 0.0})+ self.assertIn("clip_audio_past_the_end",+ [e["code"] for e in sedit.validate_edit(_edit([c]))])++ def test_two_clips_sound_may_not_overlap_either(self):+ # This is what keeps a split edit from becoming the multi-track mixer+ # the refuse list bans: one lane, still.+ a = self._clip(id="a", audio={"start": 0.0, "end": 6.0,+ "film_start": 0.0})+ b = self._clip(id="b", film_start=4.0, film_end=8.0)+ codes = [e["code"] for e in sedit.validate_edit(_edit([a, b]))]+ self.assertIn("clips_audio_overlap", codes)+ self.assertNotIn("clips_overlap", codes) # the pictures are fine++ def test_the_cut_list_says_nothing_when_nothing_is_split(self):+ # A plan of ordinary cuts must produce the identical list it always+ # did, or every film ever exported renders a different graph.+ cuts = sedit.edit_to_cuts(_edit([self._clip()]))+ self.assertNotIn("audio", cuts[0])++ def test_the_cut_list_carries_the_window_when_it_is_split(self):+ cuts = sedit.edit_to_cuts(_edit([self._clip(+ audio={"start": 0.0, "end": 4.0, "film_start": 1.0})]))+ self.assertEqual(cuts[0]["audio"],+ {"start": 0.0, "end": 4.0, "film_start": 1.0})+++class TheSyncFlag(unittest.TestCase):+ """How far an unlinked pair has come apart, and where it goes back to.++ The sibling of `edit_gaps` and information for the same reason: a J-cut IS+ a deliberate drift, so this can never be an error. What it can be is+ VISIBLE. The owner unlinked a clip, moved the picture, and had no way to+ read how far the two had separated or to put them back — "it is actually+ getting the audio out of sync... what should happen is that I only cut the+ video and left the sound in place."+ """++ def _clip(self, **kw):+ return dict({"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 4.0, "film_start": 0.0,+ "film_end": 4.0, "source": "human", "locked": False,+ "duration": 10.0}, **kw)++ def test_a_linked_clip_cannot_drift(self):+ self.assertEqual(sedit.clip_audio_drift(self._clip()), 0.0)++ def test_an_unlinked_strip_that_never_moved_reads_zero(self):+ c = self._clip(audio={"start": 0.0, "end": 4.0, "film_start": 0.0})+ self.assertEqual(sedit.clip_audio_drift(c), 0.0)++ def test_late_is_positive_and_early_is_negative(self):+ # The picture moved to film 6 and the sound stayed at 4: the sound runs+ # two seconds AHEAD of the frame it was recorded with.+ early = self._clip(film_start=6.0, film_end=10.0,+ audio={"start": 0.0, "end": 4.0, "film_start": 4.0})+ self.assertEqual(sedit.clip_audio_drift(early), -2.0)+ late = self._clip(audio={"start": 0.0, "end": 4.0, "film_start": 2.0})+ self.assertEqual(sedit.clip_audio_drift(late), 2.0)++ def test_a_head_trim_on_both_halves_is_not_a_drift(self):+ # Trimming the picture's head moves the in-point and the slot together,+ # and trimming the sound's head does the same to the strip. Neither+ # changes what plays when, so neither is out of sync.+ c = self._clip(start=1.0, film_start=1.0,+ audio={"start": 2.0, "end": 4.0, "film_start": 2.0})+ self.assertEqual(sedit.clip_audio_drift(c), 0.0)++ def test_resync_keeps_the_in_point_and_moves_the_strip(self):+ # Rematching is not un-trimming: a sound shortened to start a second+ # into the take lands a second after the picture does.+ c = self._clip(film_start=5.0, film_end=9.0,+ audio={"start": 1.0, "end": 4.0, "film_start": 1.0})+ self.assertEqual(sedit.clip_audio_resync(c), 6.0)+ fixed = dict(c, audio=dict(c["audio"], film_start=6.0))+ self.assertEqual(sedit.clip_audio_drift(fixed), 0.0)+ self.assertEqual(sedit.validate_edit(_edit([fixed])), [])++ def test_the_flag_list_names_only_the_pairs_that_are_out(self):+ ok = self._clip(id="ok", audio={"start": 0.0, "end": 4.0,+ "film_start": 0.0})+ linked = self._clip(id="linked", film_start=4.0, film_end=8.0)+ out = self._clip(id="out", film_start=8.0, film_end=12.0,+ audio={"start": 0.0, "end": 4.0, "film_start": 9.5})+ flags = sedit.edit_sync_flags(_edit([ok, linked, out]))+ self.assertEqual([f["id"] for f in flags], ["out"])+ self.assertEqual(flags[0]["drift"], 1.5)+ self.assertEqual(flags[0]["resync_to"], 8.0)+ self.assertEqual(flags[0]["where"], 2)++ def test_half_a_frame_is_not_a_drift(self):+ # Every window on the timeline is rounded to a microsecond, so an+ # exact-zero test would flag a strip one float away from home.+ near = self._clip(audio={"start": 0.0, "end": 4.0,+ "film_start": 1.0 / 96.0})+ self.assertEqual(sedit.edit_sync_flags(_edit([near])), [])+ past = self._clip(audio={"start": 0.0, "end": 4.0,+ "film_start": 1.0 / 12.0})+ self.assertEqual(len(sedit.edit_sync_flags(_edit([past]))), 1)++ def test_a_drifted_pair_is_still_a_VALID_document(self):+ # A J-cut is a deliberate drift. Refusing to save one would refuse the+ # feature.+ out = self._clip(film_start=8.0, film_end=12.0,+ audio={"start": 0.0, "end": 4.0, "film_start": 9.5})+ self.assertEqual(sedit.validate_edit(_edit([out])), [])+++class LinkingFreezesTheOffset(unittest.TestCase):+ """`audio.linked` — split, but travelling with its picture.++ Re-linking used to DELETE the field, which snapped the sound back under+ the picture and threw away the J-cut the moment it was made. So the owner+ reached for LOCK instead, and a locked clip refuses every drag with a+ forbidden cursor and no grips — the editor looked broken. Re-linking now+ freezes the relationship: "You just drag it, and the sound below stays,+ and then you can lock it and move it, and then the sound starts before the+ clip starts."+ """++ def _clip(self, **kw):+ return dict({"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 4.0, "film_start": 6.0,+ "film_end": 10.0, "source": "human", "locked": False,+ "duration": 10.0}, **kw)++ def _coupled(self, **kw):+ return self._clip(audio={"start": 0.0, "end": 4.0, "film_start": 4.0,+ "linked": True}, **kw)++ def test_a_coupled_strip_reads_as_linked_AND_split(self):+ w = sedit.clip_audio(self._coupled())+ self.assertTrue(w["linked"]) # cannot be dragged on its own+ self.assertTrue(w["coupled"])+ self.assertTrue(w["split"]) # ...but the window is its own+ self.assertEqual([w["start"], w["end"], w["film_start"]],+ [0.0, 4.0, 4.0])++ def test_the_offset_is_real_and_is_reported(self):+ self.assertEqual(sedit.clip_audio_drift(self._coupled()), -2.0)+ self.assertEqual(sedit.clip_audio_resync(self._coupled()), 6.0)++ def test_a_coupled_pair_is_never_a_sync_FLAG(self):+ # Its offset is the relationship the user froze and the two travel+ # together, so flagging it would put a permanent warning on every+ # J-cut in the film.+ self.assertEqual(sedit.edit_sync_flags(_edit([self._coupled()])), [])+ free = self._clip(audio={"start": 0.0, "end": 4.0, "film_start": 4.0})+ self.assertEqual(len(sedit.edit_sync_flags(_edit([free]))), 1)++ def test_the_flag_survives_the_round_trip_and_only_when_true(self):+ doc = sedit.normalise_edit(_edit([self._coupled()]))+ self.assertEqual(doc["clips"][0]["audio"],+ {"start": 0.0, "end": 4.0, "film_start": 4.0,+ "linked": True})+ self.assertEqual(sedit.validate_edit(doc), [])+ # A FREE strip is byte-identical to what every edit.json on disk+ # already carries — the flag is written only when it says something.+ free = sedit.normalise_edit(_edit([+ self._clip(audio={"start": 0.0, "end": 4.0, "film_start": 4.0})]))+ self.assertEqual(free["clips"][0]["audio"],+ {"start": 0.0, "end": 4.0, "film_start": 4.0})++ def test_a_non_boolean_flag_is_refused(self):+ c = self._clip(audio={"start": 0.0, "end": 4.0, "film_start": 4.0,+ "linked": "yes"})+ self.assertIn("clip_audio_linked",+ [e["code"] for e in sedit.validate_edit(_edit([c]))])++ def test_the_cut_list_carries_a_coupled_window_too(self):+ # An assembler that ignored it would render the sound back under the+ # picture — the J-cut would exist in the timeline and not in the film.+ cuts = sedit.edit_to_cuts(_edit([self._coupled()]))+ self.assertEqual(cuts[0]["audio"],+ {"start": 0.0, "end": 4.0, "film_start": 4.0})+ # ...and an ordinary clip still says nothing at all.+ plain = sedit.edit_to_cuts(_edit([self._clip()]))+ self.assertNotIn("audio", plain[0])+++ENDCARD = Path("/Users/salo/pinokio/api/phosphene-dev.git/mlx_outputs/"+ "endcard_phosphene_46_overlay_A.png")+PULLOUT = Path("/Users/salo/pinokio/api/phosphene-dev.git/mlx_outputs/"+ "h3_pullout_ending_turbo_aria.mp4")+++class TheSoundsEnvelope(unittest.TestCase):+ """"Fading and fade-out with keyframes should be very simple and intuitive+ for the sound as well."++ BOTH, FROM ONE MODEL. `fade_in`/`fade_out` are the simple case and the only+ thing the corner handles touch; `points` are the control case.+ `audio_gain_points()` folds them into ONE breakpoint curve, and the+ preview, the render and the export all read that — so the simple case+ never has to discover keyframes and a keyframed envelope never has to be+ re-expressed.+ """++ def _clip(self, **kw):+ return dict({"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 4.0, "film_start": 0.0,+ "film_end": 4.0, "source": "human", "locked": False,+ "duration": 10.0}, **kw)++ def test_a_flat_unity_curve_is_no_curve_at_all(self):+ # Saying "the volume is 1 the whole way" would put a filter in every+ # graph to express nothing.+ self.assertEqual(sedit.audio_gain_points({}, 4.0), [])+ self.assertEqual(sedit.audio_gain_at({}, 4.0, 2.0), 1.0)++ def test_the_simple_case_is_two_ramps(self):+ c = self._clip(afx={"fade_in": 1.0, "fade_out": 0.5})+ self.assertEqual(sedit.audio_gain_points(c, 4.0),+ [[0.0, 0.0], [1.0, 1.0], [3.5, 1.0], [4.0, 0.0]])+ self.assertEqual(sedit.audio_gain_at(c, 4.0, 0.5), 0.5)++ def test_keyframes_are_the_same_curve_by_another_door(self):+ c = self._clip(afx={"points": [[1.0, 0.3], [2.0, 1.0]]})+ self.assertEqual(sedit.audio_gain_points(c, 4.0),+ [[0.0, 0.3], [1.0, 0.3], [2.0, 1.0], [4.0, 1.0]])+ self.assertAlmostEqual(sedit.audio_gain_at(c, 4.0, 1.5), 0.65, places=3)++ def test_a_fade_and_a_keyframed_level_COMPOSE(self):+ # Not one overriding the other: the fade multiplies the point curve,+ # which is what makes "fade in to a 25% bed" a thing you can say.+ c = self._clip(afx={"fade_in": 1.0, "points": [[2.0, 0.25]]})+ curve = sedit.audio_gain_points(c, 4.0)+ self.assertEqual(curve[0], [0.0, 0.0])+ self.assertEqual(curve[1], [1.0, 0.25])+ self.assertEqual(curve[-1][1], 0.25)++ def test_the_clamp_and_the_bounds(self):+ c = self._clip(afx={"fade_in": 9.0, "fade_out": 9.0})+ e = sedit.audio_effects(c, 4.0)+ self.assertEqual([e["fade_in"], e["fade_out"]], [2.0, 2.0])+ loud = self._clip(afx={"points": [[1.0, 5.0], [2.0, -3.0]]})+ pts = sedit.audio_effects(loud, 4.0)["points"]+ self.assertEqual([p[1] for p in pts], [1.0, 0.0])++ def test_t_is_STRIP_relative_so_a_j_cut_does_not_drag_the_points(self):+ # The strip is 4 s of source wherever it sits on the film; a point at+ # 1.0 is one second into the SOUND, and sliding the J-cut must not+ # move it.+ early = self._clip(film_start=10.0, film_end=14.0,+ audio={"start": 0.0, "end": 4.0, "film_start": 9.5},+ afx={"points": [[1.0, 0.5]]})+ late = dict(early, audio={"start": 0.0, "end": 4.0, "film_start": 11.0})+ self.assertEqual(sedit.audio_gain_points(early, 4.0),+ sedit.audio_gain_points(late, 4.0))++ def test_it_saves_reloads_and_reaches_the_cut_list(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, _edit([self._clip(+ afx={"fade_in": 1.0, "points": [[2.0, 0.5]]})]))+ got = sedit.load_edit(bdir)+ self.assertEqual(got["clips"][0]["afx"],+ {"fade_in": 1.0, "points": [[2.0, 0.5]]})+ self.assertEqual(sedit.validate_edit(got), [])+ cuts = sedit.edit_to_cuts(got)+ self.assertTrue(cuts[0]["gain"])+ # ...and neutral is absent.+ doc = sedit.normalise_edit(_edit([self._clip(afx={"fade_in": 0.0})]))+ self.assertNotIn("afx", doc["clips"][0])++ def test_a_nonsense_envelope_is_refused(self):+ codes = [e["code"] for e in sedit.validate_edit(+ _edit([self._clip(afx={"fade_in": -1})]))]+ self.assertIn("clip_afade_in_range", codes)+ codes = [e["code"] for e in sedit.validate_edit(+ _edit([self._clip(afx={"points": [[1.0]]})]))]+ self.assertIn("clip_afx_point", codes)++ # ---- output 2: the render -----------------------------------------+ def test_the_volume_expression_is_the_curve(self):+ curve = sedit.audio_gain_points(+ self._clip(afx={"fade_in": 1.0, "fade_out": 0.5}), 4.0)+ term = panel._sb_volume_term(curve)+ self.assertIn("eval=frame", term)+ self.assertIn("lt(t,1.000000)", term)+ self.assertIn("lt(t,3.500000)", term)+ # `eval=frame` or ffmpeg evaluates once at init and the envelope+ # becomes a constant.+ self.assertEqual(panel._sb_volume_term([]), "")+ self.assertEqual(panel._sb_volume_term([[0.0, 1.0]]), "")++ def test_an_unshaped_sound_builds_the_chain_it_always_did(self):+ info = {"has_audio": True, "duration": 10.0, "w": 1024, "h": 576,+ "sample_rate": 48000}+ seg = {"kind": "video", "input": 0, "info": dict(info),+ "window": {"start": 0.0, "end": 4.0}, "adjust": None,+ "duration": 4.0, "path": "/x/a.mp4"}+ plain, _ = panel._sb_film_filtergraph([], 1024, 576, 48000, "yuv420p",+ segments=[dict(seg)])+ self.assertNotIn("volume=", plain)+ self.assertNotIn("anull", plain)+ shaped, _ = panel._sb_film_filtergraph(+ [], 1024, 576, 48000, "yuv420p",+ segments=[dict(seg, gain=[[0.0, 0.0], [1.0, 1.0]])])+ self.assertIn("volume=volume=", shaped)++ # ---- output 3: the export ------------------------------------------+ def test_fcp7_gets_linear_level_keyframes(self):+ probe = lambda p: {"w": 1024, "h": 576, "duration": 10.0,+ "has_audio": True}+ rows = sedit._nle_segments(+ [self._clip(afx={"fade_in": 1.0, "fade_out": 0.5})], probe=probe)+ self.assertEqual(rows[0]["gain"],+ [[0.0, 0.0], [1.0, 1.0], [3.5, 1.0], [4.0, 0.0]])+ xml = sedit.fcp7_xml(rows, name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576, base="/tmp/p")+ self.assertIn("<name>Audio Levels</name>", xml)+ root = ET.fromstring(xml)+ lv = [e for e in root.iter("effect")+ if e.find("name") is not None+ and e.find("name").text == "Audio Levels"]+ keys = [(int(k.find("when").text), float(k.find("value").text))+ for k in lv[0].iter("keyframe")]+ # Linear, with 1.0 as unity — the same number the render uses, so+ # there is nothing to get wrong between them.+ self.assertEqual(keys, [(0, 0.0), (24, 1.0), (84, 1.0), (96, 0.0)])++ def test_after_effects_gets_the_same_curve_in_dB(self):+ probe = lambda p: {"w": 1024, "h": 576, "duration": 10.0,+ "has_audio": True}+ rows = sedit._nle_segments(+ [self._clip(afx={"fade_in": 1.0})], probe=probe)+ jsx = sedit.ae_jsx(rows, name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576)+ self.assertIn("ADBE Audio Levels", jsx)+ # AE's unit is dB, so the conversion happens at that ONE seam:+ # unity is 0 dB and silence is AE's own -96 floor, because log(0) is+ # not a number.+ self.assertIn("au.setValueAtTime(0.000000, [-96.000, -96.000]);", jsx)+ self.assertIn("au.setValueAtTime(1.000000, [0.000, 0.000]);", jsx)++ def test_the_three_outputs_agree_on_the_breakpoints(self):+ probe = lambda p: {"w": 1024, "h": 576, "duration": 10.0,+ "has_audio": True}+ c = self._clip(afx={"fade_in": 1.0, "fade_out": 0.5})+ curve = sedit.audio_gain_points(c, 4.0)+ rows = sedit._nle_segments([c], probe=probe)+ xml = sedit.fcp7_xml(rows, name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576, base="/tmp/p")+ root = ET.fromstring(xml)+ lv = [e for e in root.iter("effect")+ if e.find("name") is not None+ and e.find("name").text == "Audio Levels"][0]+ fcp = [round(int(k.find("when").text) / 24.0, 3) for k in lv.iter("keyframe")]+ jsx = sedit.ae_jsx(rows, name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576)+ ae = [round(float(m), 3) for m in re.findall(+ r"au\.setValueAtTime\(([\d.]+), \[", jsx)]+ self.assertEqual(fcp, [round(t, 3) for t, _ in curve])+ self.assertEqual(ae, fcp)+ term = panel._sb_volume_term(curve)+ for t, _ in curve[1:]:+ self.assertIn(f"lt(t,{t:.6f})", term)+++class TheOverlayLane(unittest.TestCase):+ """A SECOND video track, above the picture — and the real endcard.++ Tested with his actual asset: 1536x832 RGBA authored at 2x the frame+ aspect of a 768x416 pull-out, so the default full-frame fit DOWNSCALES it.+ A scale that drops the alpha channel delivers a black rectangle where the+ transparency was, and that is the failure this lane exists to avoid.+ """++ def _board(self, **ovkw):+ clip = {"id": "c1", "path": str(PULLOUT), "proxy": None, "start": 0.0,+ "end": 6.0, "film_start": 0.0, "film_end": 6.0,+ "source": "human", "locked": False, "duration": 10.12}+ ov = dict({"id": "o1", "kind": "still", "path": str(ENDCARD),+ "start": 0.0, "end": 3.0, "film_start": 3.0,+ "film_end": 6.0, "source": "human", "locked": False},+ **ovkw)+ doc = _edit([clip])+ doc["overlays"] = [ov]+ return doc++ def test_the_asset_is_what_it_claims_to_be(self):+ # The doctrine is to test with the real thing, so the test says what+ # the real thing is: if the card stops being RGBA this fails here+ # rather than three assertions later.+ if not ENDCARD.is_file():+ raise unittest.SkipTest("endcard asset not present")+ out = subprocess.run(+ ["ffprobe", "-v", "error", "-show_entries",+ "stream=width,height,pix_fmt", "-of", "csv=p=0", str(ENDCARD)],+ capture_output=True, text=True).stdout.strip()+ self.assertEqual(out, "1536,832,rgba")++ def test_an_absent_lane_is_an_absent_key(self):+ doc = sedit.normalise_edit(_edit([]))+ self.assertNotIn("overlays", doc)+ self.assertEqual(sedit.overlay_items(doc), [])++ def test_a_still_is_its_slot(self):+ doc = sedit.normalise_edit(self._board())+ o = doc["overlays"][0]+ self.assertEqual([o["start"], o["end"]], [0.0, 3.0])+ self.assertIsNone(o["duration"])+ self.assertEqual(sedit.validate_edit(doc), [])++ def test_an_overlay_over_a_clip_is_NOT_an_overlap(self):+ # The picture lane may not overlap itself; a card sitting ON a picture+ # is the feature, which is why the lane is its own list.+ self.assertEqual(sedit.validate_edit(sedit.normalise_edit(self._board())), [])++ def test_but_two_cards_at_once_are(self):+ doc = self._board()+ doc["overlays"].append(dict(doc["overlays"][0], id="o2",+ film_start=4.0, film_end=7.0))+ self.assertIn("overlays_overlap",+ [e["code"] for e in sedit.validate_edit(doc)])++ def test_the_lane_saves_and_reloads(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._board(fx={"fade_in": 1.0}))+ got = sedit.load_edit(bdir)+ self.assertEqual(len(got["overlays"]), 1)+ self.assertEqual(got["overlays"][0]["fx"], {"fade_in": 1.0})+ self.assertEqual(sedit.validate_edit(got), [])++ # ---- the same accessor as a clip: the foundation paying off --------+ def test_an_overlay_gets_its_fades_from_clip_effects(self):+ o = sedit.normalise_edit(self._board(fx={"fade_in": 1.0}))["overlays"][0]+ self.assertEqual(sedit.clip_effects(o)["fade_in"], 1.0)+ # ...and the SAME clamp: a fade cannot outrun the card.+ wide = sedit.normalise_edit(+ self._board(fx={"fade_in": 9.0}))["overlays"][0]+ self.assertEqual(sedit.clip_effects(wide)["fade_in"], 3.0)++ # ---- output 2: the render -----------------------------------------+ def test_the_graph_keeps_the_alpha_on_BOTH_sides_of_the_scale(self):+ ov = [{"kind": "still", "path": str(ENDCARD), "film_start": 3.0,+ "film_end": 6.0, "fx": {"fade_in": 1.0}}]+ g, _ = panel._sb_film_filtergraph(+ [], 768, 416, 48000, "yuv420p",+ segments=[{"kind": "video", "input": 0,+ "info": {"has_audio": True, "duration": 10.0, "w": 768,+ "h": 416, "sample_rate": 48000},+ "window": {"start": 0.0, "end": 6.0}, "adjust": None,+ "duration": 6.0, "path": str(PULLOUT)}],+ overlays=ov, overlay_base=1)+ chain = [c for c in g.split(";") if c.startswith("[1:v]")][0]+ # Once so what enters the scaler carries alpha, once because a scaler+ # is free to pick an output format that does not.+ self.assertEqual(chain.count("format=rgba"), 2)+ self.assertLess(chain.index("format=rgba"), chain.index("scale="))+ self.assertLess(chain.index("scale="), chain.rindex("format=rgba"))+ # A fade on the overlay lane ramps ALPHA, not toward black — fading to+ # black would paint a black card over the picture.+ self.assertIn("fade=t=in:st=0:d=1.000000:alpha=1", chain)+ self.assertIn("setpts=PTS+3.000000/TB", chain)+ ovl = [c for c in g.split(";") if "overlay=" in c][0]+ self.assertIn("enable='between(t,3.000000,6.000000)'", ovl)+ self.assertIn("repeatlast=0", ovl)++ def test_a_card_that_outlives_the_picture_composites_over_black(self):+ g, _ = panel._sb_film_filtergraph(+ [], 768, 416, 48000, "yuv420p",+ segments=[{"kind": "video", "input": 0,+ "info": {"has_audio": True, "duration": 10.0, "w": 768,+ "h": 416, "sample_rate": 48000},+ "window": {"start": 0.0, "end": 4.0}, "adjust": None,+ "duration": 4.0, "path": str(PULLOUT)}],+ overlays=[{"kind": "still", "path": str(ENDCARD),+ "film_start": 3.0, "film_end": 7.0}],+ overlay_base=1)+ self.assertIn("tpad=stop_mode=add:stop_duration=3.000000:color=black", g)++ def test_no_overlay_builds_the_graph_it_always_did(self):+ seg = {"kind": "video", "input": 0,+ "info": {"has_audio": True, "duration": 10.0, "w": 768,+ "h": 416, "sample_rate": 48000},+ "window": {"start": 0.0, "end": 4.0}, "adjust": None,+ "duration": 4.0, "path": str(PULLOUT)}+ g, lbl = panel._sb_film_filtergraph([], 768, 416, 48000, "yuv420p",+ segments=[seg])+ self.assertNotIn("overlay=", g)+ self.assertNotIn("tpad", g)++ # ---- output 3: the export -----------------------------------------+ def test_fcp7_puts_the_card_on_V2_above_the_picture(self):+ probe = lambda p: {"w": 768, "h": 416, "duration": 10.12,+ "has_audio": True}+ doc = sedit.normalise_edit(self._board(fx={"fade_in": 1.0}))+ rows = sedit._nle_segments(doc["clips"], probe=probe)+ media = {str(PULLOUT): "pullout.mp4", str(ENDCARD): "card.png"}+ xml = sedit.fcp7_xml(rows, name="c", media=media, width=768,+ height=416, base="/tmp/p",+ overlays=doc["overlays"])+ root = ET.fromstring(xml)+ seq = root if root.tag == "sequence" else root.find("sequence")+ tracks = seq.find("./media/video").findall("track")+ self.assertEqual(len(tracks), 2) # V1 picture, V2 overlay+ self.assertEqual([ci.find("name").text+ for ci in tracks[1].findall("clipitem")],+ ["endcard_phosphene_46_overlay_A"])+ keys = [(int(k.find("when").text), float(k.find("value").text))+ for k in tracks[1].iter("keyframe")]+ self.assertEqual(keys[:2], [(0, 0.0), (24, 100.0)]) # 1 s at 24 fps++ def test_after_effects_puts_the_card_on_top(self):+ probe = lambda p: {"w": 768, "h": 416, "duration": 10.12,+ "has_audio": True}+ doc = sedit.normalise_edit(self._board(fx={"fade_in": 1.0}))+ rows = sedit._nle_segments(doc["clips"], probe=probe)+ media = {str(PULLOUT): "pullout.mp4", str(ENDCARD): "card.png"}+ jsx = sedit.ae_jsx(rows, name="c", media=media, width=768, height=416,+ overlays=doc["overlays"])+ # `comp.layers.add` inserts at index 1, so whatever is added LAST sits+ # highest: the card must come after every picture layer.+ self.assertLess(jsx.index("pullout.mp4"), jsx.index("card.png"))+ self.assertIn("op.setValueAtTime(3.000000, 0);", jsx)+ self.assertIn("op.setValueAtTime(4.000000, 100);", jsx)++ def test_the_three_outputs_agree_on_the_overlays_fade(self):+ probe = lambda p: {"w": 768, "h": 416, "duration": 10.12,+ "has_audio": True}+ doc = sedit.normalise_edit(self._board(fx={"fade_in": 1.0}))+ o = doc["overlays"][0]+ media = {str(PULLOUT): "pullout.mp4", str(ENDCARD): "card.png"}+ rows = sedit._nle_segments(doc["clips"], probe=probe)+ xml = sedit.fcp7_xml(rows, name="c", media=media, width=768,+ height=416, base="/tmp/p", overlays=[o])+ root = ET.fromstring(xml)+ seq = root if root.tag == "sequence" else root.find("sequence")+ v2 = seq.find("./media/video").findall("track")[1]+ fcp_in = [int(k.find("when").text) / 24.0 for k in v2.iter("keyframe")][:2]+ jsx = sedit.ae_jsx(rows, name="c", media=media, width=768, height=416,+ overlays=[o])+ ae = [float(m) for m in re.findall(+ r"op\.setValueAtTime\(([\d.]+), \d+\);", jsx)][:2]+ # FCP7 counts from the clipitem's own head; AE from the film clock.+ self.assertEqual(round(fcp_in[1] - fcp_in[0], 3),+ round(ae[1] - ae[0], 3))+ term = panel._sb_fade_term(o.get("fx"), 3.0, alpha=True)+ self.assertIn("d=1.000000", term) # the same ramp length, again+++class TheOverlayRendersWithItsAlpha(unittest.TestCase):+ """The failure mode, tested by actually rendering it.++ A card that arrives as a black rectangle instead of transparency is the+ thing this lane must never do, and no amount of reading the filter string+ proves it did not. So: composite the real endcard over a KNOWN solid base+ and count the pixels that still show the base through it.+ """++ def test_the_real_endcard_downscales_with_its_transparency_intact(self):+ if not ENDCARD.is_file() or not shutil.which("ffmpeg"):+ raise unittest.SkipTest("endcard or ffmpeg not present")+ with tempfile.TemporaryDirectory() as d:+ out = Path(d) / "frame.png"+ # The EXACT chain the panel builds, over solid red.+ chain = ("[1:v]format=rgba,scale=768:416:flags=lanczos,"+ "format=rgba,setsar=1,setpts=PTS+0/TB[ov0];"+ "[0:v][ov0]overlay=0:0:eof_action=pass:repeatlast=0:"+ "enable='between(t,0,2)'[vout]")+ subprocess.run(+ ["ffmpeg", "-v", "error", "-f", "lavfi",+ "-i", "color=c=red:s=768x416:r=24:d=2",+ "-loop", "1", "-framerate", "24", "-t", "2", "-i", str(ENDCARD),+ "-filter_complex", chain, "-map", "[vout]", "-frames:v", "1",+ "-y", str(out)], check=True, capture_output=True)+ raw = subprocess.run(+ ["ffmpeg", "-v", "error", "-i", str(out), "-f", "rawvideo",+ "-pix_fmt", "rgb24", "-"], capture_output=True).stdout+ a = np.frombuffer(raw, np.uint8).reshape(416, 768, 3).astype(int)+ through = ((a[:, :, 0] > 200) & (a[:, :, 1] < 60)+ & (a[:, :, 2] < 60)).mean()+ black = (a.sum(axis=2) < 24).mean()+ # If alpha were dropped the card's transparent region would render+ # BLACK and cover the base entirely.+ self.assertGreater(through, 0.5,+ "the base is not visible through the card")+ self.assertLess(black, 0.05, "the card arrived as a black box")+++class AReadMayNotDisarmTheNet(EditorCase):+ """The owner lost unsaved work because somebody else OPENED his film.++ A page LOAD claimed the board; the tab he was cutting in was answered+ `stale_session` on its next snapshot and stopped writing for seven hours.+ Two rules come out of that and both are asserted here: a read claims+ nothing, and the lane refuses nobody.+ """++ def _doc(self, end=4.0):+ return _edit([dict(_clip("/x/a.mp4", 0.0, end, 0.0), id="c1")])++ def setUp(self):+ super().setUp()+ # A document on disk, so the GET reads rather than auto-cutting a+ # board whose clips are stub bytes ffprobe cannot read.+ sedit.save_edit(self.bdir, self._doc(), origin="human")++ def test_a_read_claims_nothing(self):+ h = FakeHandler().get("/storyboard/edit?id=sb_t&session=ssREADER")+ self.assertTrue(h.payload.get("ok", True))+ self.assertEqual(sedit.current_session(self.bdir)["token"], "",+ "a page load took the claim")++ def test_a_write_claims_the_board(self):+ sedit.write_backup(self.bdir, self._doc(), session="ssEDITOR")+ self.assertEqual(sedit.current_session(self.bdir)["token"], "ssEDITOR")++ def test_a_passive_load_does_not_stop_the_editing_tabs_snapshots(self):+ # The exact sequence that cost him the afternoon.+ sedit.write_backup(self.bdir, self._doc(4.0), session="ssEDITOR")+ FakeHandler().get("/storyboard/edit?id=sb_t&session=ssPASSIVEVIEWER")+ before = len(sedit.list_history(self.bdir))+ sedit.write_backup(self.bdir, self._doc(5.0), session="ssEDITOR")+ sedit.write_backup(self.bdir, self._doc(6.0), session="ssEDITOR")+ self.assertEqual(len(sedit.list_history(self.bdir)), before + 2,+ "the snapshot lane went quiet after a passive load")++ def test_even_a_genuinely_older_tab_is_never_refused(self):+ # The lane is ONE FILE PER SNAPSHOT and never overwrites, so the+ # failure the token was introduced for cannot recur — and a snapshot+ # from any tab can only ever ADD a way back. Refusing one removes one.+ sedit.write_backup(self.bdir, self._doc(4.0), session="ssNEW")+ n = len(sedit.list_history(self.bdir))+ sedit.write_backup(self.bdir, self._doc(9.0), session="ssOLD")+ self.assertEqual(len(sedit.list_history(self.bdir)), n + 1)++ def test_the_claim_follows_the_last_EDITOR_not_the_last_loader(self):+ sedit.write_backup(self.bdir, self._doc(4.0), session="ssA")+ FakeHandler().get("/storyboard/edit?id=sb_t&session=ssB")+ self.assertEqual(sedit.current_session(self.bdir)["token"], "ssA")+ sedit.write_backup(self.bdir, self._doc(5.0), session="ssB")+ self.assertEqual(sedit.current_session(self.bdir)["token"], "ssB")++ def test_the_route_reports_who_holds_the_claim_so_a_tab_can_say_so(self):+ sedit.write_backup(self.bdir, self._doc(), session="ssA")+ h = FakeHandler().post("edit/backup", body=json.dumps(+ {"id": "sb_t", "session": "ssB", "draft": "",+ "edit": self._doc(7.0)}))+ self.assertTrue(h.payload["ok"])+ self.assertEqual(h.payload["session"]["token"], "ssB")+ # ...and never with a refusal.+ self.assertNotIn("stale_session", h.payload)+++class AnIdenticalSnapshotIsNotASnapshot(EditorCase):+ """Ten files in fifteen seconds, same revision, same clips, same digest —+ half of a twenty-deep net spent on one arrangement, and half the DISTINCT+ history evicted to hold it."""++ def _doc(self, end=4.0):+ return _edit([dict(_clip("/x/a.mp4", 0.0, end, 0.0), id="c1")])++ def test_a_burst_of_identical_writes_leaves_one_file(self):+ for _ in range(10):+ sedit.write_backup(self.bdir, self._doc(4.0), session="ssA")+ self.assertEqual(len(sedit.list_history(self.bdir)), 1)++ def test_a_real_change_still_lands(self):+ for end in (4.0, 5.0, 6.0):+ sedit.write_backup(self.bdir, self._doc(end), session="ssA")+ self.assertEqual(len(sedit.list_history(self.bdir)), 3)++ def test_the_dedupe_uses_the_SAME_fingerprint_the_offer_compares_on(self):+ # A derived field the user has never heard of may not be the reason a+ # snapshot is written OR the reason they are asked a question.+ a = self._doc(4.0)+ sedit.write_backup(self.bdir, a, session="ssA")+ b = dict(a)+ b["clips"] = [dict(a["clips"][0], proxy="rebuilt.mp4")]+ sedit.write_backup(self.bdir, b, session="ssA")+ self.assertEqual(len(sedit.list_history(self.bdir)), 1)+++class AHoleShorterThanAFrame(unittest.TestCase):+ """"A black frame that flashes for a microsecond... I tried to drag them+ close and whatever."++ The second half is the defect. Measured on the sequence that produced the+ report, at 24 fps: three holes of 20.94 ms, 15.84 ms and 4.00 ms — 0.503,+ 0.380 and 0.096 of a frame. Too small to see at any zoom, too small for a+ pixel to address, and the stage paints black wherever no clip is playing.+ """++ FRAME = 1.0 / 24.0++ def _doc(self, *gaps, **kw):+ """A film of 4-second clips separated by the gaps given, in seconds."""+ clips, at = [], 0.0+ for i, g in enumerate((0.0,) + gaps):+ at += g+ clips.append(dict(_clip(f"/x/{i}.mp4", 0.0, 4.0, at), id=f"c{i}",+ film_end=round(at + 4.0, 6)))+ at += 4.0+ return _edit(clips, **kw)++ def test_his_three_holes_all_close(self):+ doc = self._doc(0.02094, 0.01584, 0.004)+ closed = sedit.heal_subframe_gaps(doc)+ self.assertEqual(len(closed), 3)+ self.assertEqual([round(c["frames"], 3) for c in closed],+ [0.503, 0.380, 0.096])+ self.assertEqual([(c["film_start"], c["film_end"]) for c in doc["clips"]],+ [(0.0, 4.0), (4.0, 8.0), (8.0, 12.0), (12.0, 16.0)])+ self.assertEqual(sedit.edit_gaps(doc), [])++ def test_the_heal_happens_on_READ_so_an_old_film_fixes_itself_on_open(self):+ healed = sedit.migrate_edit(self._doc(0.02094))+ self.assertEqual(healed["clips"][1]["film_start"], 4.0)+ self.assertEqual(len(healed["healed_subframe_gaps"]), 1)++ def test_the_read_does_not_mutate_the_document_it_was_given(self):+ # `migrate_edit` is a read-path upgrade, and the backup lane compares+ # RAW json on both sides — a read that edited its input in place would+ # make the saved file and the snapshot differ over a repair neither of+ # them contains, which is the interrogation the save model exists to+ # stop.+ raw = self._doc(0.02094)+ sedit.migrate_edit(raw)+ self.assertEqual(raw["clips"][1]["film_start"], 4.02094)++ def test_it_is_idempotent_and_the_record_does_not_survive_a_clean_read(self):+ # "Fixes itself on open" and "drifts a little every open" look+ # identical from one screenshot.+ once = sedit.migrate_edit(self._doc(0.02094, 0.01584, 0.004))+ twice = sedit.migrate_edit(once)+ self.assertEqual([(c["film_start"], c["film_end"]) for c in twice["clips"]],+ [(c["film_start"], c["film_end"]) for c in once["clips"]])+ # ...and the second read announces nothing, because it closed nothing.+ self.assertNotIn("healed_subframe_gaps", twice)++ def test_a_gap_somebody_can_SEE_is_never_touched(self):+ # The false positive to avoid: a black slug the user placed on purpose.+ for gap in (self.FRAME, 0.5, 6.0):+ with self.subTest(gap=gap):+ doc = self._doc(gap)+ self.assertEqual(sedit.heal_subframe_gaps(doc), [])+ self.assertAlmostEqual(doc["clips"][1]["film_start"],+ 4.0 + gap, places=6)+ # ...and it is not snapped to the frame grid either. 1.8 s is 43.2+ # frames; moving it 8 ms to sit on 43 would rewrite a number the user+ # chose to buy a property nothing reads.+ doc = self._doc(1.8)+ sedit.heal_subframe_gaps(doc)+ self.assertEqual(doc["clips"][1]["film_start"], 5.8)++ def test_an_unlinked_strip_keeps_its_offset_through_a_heal(self):+ doc = self._doc(0.02094)+ doc["clips"][1]["audio"] = {"split": True, "start": 0.5, "end": 4.5,+ "film_start": 3.52094}+ drift = sedit.clip_audio_drift(doc["clips"][1])+ sedit.heal_subframe_gaps(doc)+ self.assertAlmostEqual(sedit.clip_audio_drift(doc["clips"][1]),+ drift, places=6)+ # The strip moved by the SAME delta as its picture, not by nothing.+ self.assertAlmostEqual(doc["clips"][1]["audio"]["film_start"], 3.5,+ places=6)++ def test_a_locked_clip_is_an_anchor_and_does_not_move(self):+ doc = self._doc(0.02094, 0.004)+ doc["clips"][1]["locked"] = True+ sedit.heal_subframe_gaps(doc)+ # The pin holds: honouring it by breaking it is not honouring it.+ self.assertEqual(doc["clips"][1]["film_start"], 4.02094)+ # ...and the hole after the anchor is measured from where it actually+ # is, so nothing downstream inherits a shift the anchor did not take.+ self.assertEqual(doc["clips"][2]["film_start"], 8.02094)++ def test_the_hole_counter_stops_lying(self):+ doc = self._doc(0.02094, 0.01584, 0.004)+ # WHAT THE HEADER SAID: one hole, because the threshold was the literal+ # 1/48 and two of the three were under it.+ self.assertEqual(len(sedit.edit_gaps(doc, tolerance=1.0 / 48.0)), 1)+ self.assertEqual(len(sedit.edit_gaps(doc, tolerance=1e-9)), 3)+ # WHAT IT SAYS NOW: nothing, because there is nothing left to report.+ self.assertEqual(sedit.edit_gaps(sedit.migrate_edit(doc)), [])++ def test_the_threshold_follows_the_sequences_rate(self):+ # 1/48 is half a frame at 24 fps and the wrong number at any other.+ doc = self._doc(0.03, fps=12) # 0.36 of a frame+ self.assertEqual(sedit.frame_seconds(doc), 1.0 / 12.0)+ self.assertEqual(sedit.edit_gaps(doc), [])+ self.assertEqual(len(sedit.heal_subframe_gaps(doc)), 1)++ def test_the_render_and_the_timeline_now_agree_on_the_length(self):+ """Where the black frame came from, and where it did not.++ The assembler consumes `start`/`end` per clip and CONCATENATES, so a+ hole never reached ffmpeg at all — the rendered film was already the+ healed length. The PREVIEW is the half that painted black in it. The+ two therefore disagreed by exactly the hole, silently, and healing is+ what makes the number on the header the number that comes out.+ """+ doc = self._doc(0.02094, 0.01584, 0.004)+ rendered = sum(c["end"] - c["start"] for c in sedit.edit_to_cuts(doc))+ self.assertAlmostEqual(sedit.edit_duration(doc) - rendered, 0.04078,+ places=5)+ healed = sedit.migrate_edit(doc)+ self.assertAlmostEqual(sedit.edit_duration(healed), rendered, places=6)+++# =============================================================================+# An overlay that arrives on a black plate+# =============================================================================+# "If the picture comes in a format that doesn't work, automatically make it+# work." The reported failure: a card generated elsewhere HAS an alpha channel,+# so it looks transparent, but the artwork sits on an opaque black backdrop —+# the alpha over the neon burst is a FILLED DISC, so the black between the rays+# is declared opaque and the lane composited it over the sky.+#+# The fixtures are BUILT HERE rather than read off this machine, so the gate+# runs on a fresh install and so the population the detector must refuse is+# visible in the test rather than implied by it. The real reported card is+# asserted too, when it happens to be present.+PLATE_CARD = Path("/Users/salo/pinokio/api/phosphene-dev.git/panel_uploads/"+ "library/manual/20260820/uploads/"+ "1787241298782_ChatGPT_Image_Aug_20_2026_06_54_48_PM.png")+++def _burst(h, w):+ """Neon dashes on a smooth dark backdrop, inside a disc. Returns+ (rgb, disc, ink) — the same picture, mattted two different ways below."""+ cx, cy, r = w * 0.5, h * 0.5, min(w, h) * 0.44+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)+ rad = np.hypot(xx - cx, yy - cy)+ ang = np.arctan2(yy - cy, xx - cx)+ disc = rad <= r+ ink = disc & (np.cos(ang * 28.0) > 0.35) & (rad > r * 0.30) & (rad < r * 0.92)+ rgb = np.zeros((h, w, 3), np.float32)+ back = np.clip(18.0 - rad / r * 10.0, 0.0, 255.0) # a smooth backdrop+ rgb[disc] = np.stack([back * 0.6, back * 0.3, back], -1)[disc]+ hot = np.stack([np.full((h, w), 255.0),+ 60.0 + 120.0 * np.cos(ang * 5.0),+ np.full((h, w), 235.0)], -1) # ...and saturated ink+ rgb[ink] = hot[ink]+ return rgb, disc, ink+++def _rgba(path, rgb, alpha):+ from PIL import Image # noqa: PLC0415+ out = np.concatenate([rgb, alpha[..., None]], -1)+ Image.fromarray(np.rint(out).astype(np.uint8), "RGBA").save(path)+++def _photoish(h, w, seed=7, scale=1.0):+ rng = np.random.default_rng(seed)+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)+ lum = np.clip(((90 + 70 * np.sin(xx / 40.0) * np.cos(yy / 31.0)+ + 50 * np.sin((xx + yy) / 17.0))+ + rng.normal(0.0, 9.0, (h, w))) * scale, 0, 255)+ return np.stack([lum, lum * 0.92, lum * 0.86], -1).astype(np.float32)+++def _ellipse(h, w):+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)+ inside = (((xx - w / 2) / (w * 0.34)) ** 2+ + ((yy - h / 2) / (h * 0.45)) ** 2) <= 1.0+ return np.where(inside, 255.0, 0.0)+++class AnOverlayThatArrivesOnABlackPlate(unittest.TestCase):+ """The detector, the key, and the identity the key stands on."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.d = Path(self.tmp.name)++ def tearDown(self):+ self.tmp.cleanup()++ # ---- the fixtures, as files -------------------------------------------+ def plate(self, name="plate.png", h=440, w=800):+ """The reported shape: a FILLED matte over art drawn on black."""+ rgb, disc, _ = _burst(h, w)+ p = self.d / name+ _rgba(p, rgb, np.where(disc, 255.0, 0.0))+ return p++ def honest(self, name="honest.png", h=440, w=800):+ """The same art with a matte that hugs the ink."""+ rgb, _, ink = _burst(h, w)+ rgb[~ink] = 0.0+ p = self.d / name+ _rgba(p, rgb, np.where(ink, 255.0, 0.0))+ return p++ def photo(self, name="photo.jpg"):+ from PIL import Image # noqa: PLC0415+ p = self.d / name+ Image.fromarray(np.rint(_photoish(440, 800)).astype(np.uint8),+ "RGB").save(p)+ return p++ def matted_photo(self, name="cutout.png", scale=1.0):+ p = self.d / name+ _rgba(p, _photoish(440, 800, scale=scale), _ellipse(440, 800))+ return p++ def black_ink(self, name="ink.png"):+ a = np.zeros((440, 800), np.float32)+ for i in range(6):+ a[120:320, 60 + i * 125: 150 + i * 125] = 255.0+ p = self.d / name+ _rgba(p, np.zeros((440, 800, 3), np.float32), a)+ return p++ # ---- detection --------------------------------------------------------+ def test_a_filled_matte_over_art_on_black_is_detected(self):+ r = panel._sbe_plate_report(self.plate())+ self.assertTrue(r["plate"], r)+ # The clauses, by name, so a threshold that drifts says which one.+ self.assertGreaterEqual(r["clear_share"], panel.SBE_PLATE_CLEAR_MIN)+ self.assertGreaterEqual(r["opaque_share"], panel.SBE_PLATE_OPAQUE_MIN)+ self.assertGreaterEqual(r["dark_share"], panel.SBE_PLATE_DARK_SHARE_MIN)+ self.assertGreaterEqual(r["hot_share"], panel.SBE_PLATE_HOT_SHARE_MIN)+ self.assertLessEqual(r["flat"], panel.SBE_PLATE_FLAT_MAX)+ self.assertGreaterEqual(r["ink_kept"], panel.SBE_PLATE_INK_MIN)++ def test_a_photograph_can_never_be_reached_by_any_of_the_maths(self):+ # THE GUARANTEE THAT MATTERS. A file with no alpha channel never+ # claimed transparency, so it is refused before a single pixel is+ # weighed — no threshold can ever let a plain photo through.+ r = panel._sbe_plate_report(self.photo())+ self.assertFalse(r["plate"])+ self.assertEqual(r["why"], "no alpha channel")++ def test_a_photograph_matted_into_an_overlay_is_left_alone(self):+ for scale, tag in ((1.0, "as shot"), (0.22, "darkened")):+ with self.subTest(tag):+ r = panel._sbe_plate_report(+ self.matted_photo(f"cut_{tag.replace(' ', '_')}.png", scale))+ self.assertFalse(r["plate"], r)++ def test_a_card_with_a_matte_that_hugs_its_ink_is_left_alone(self):+ r = panel._sbe_plate_report(self.honest())+ self.assertFalse(r["plate"], r)++ def test_black_artwork_on_transparency_is_left_alone(self):+ r = panel._sbe_plate_report(self.black_ink())+ self.assertFalse(r["plate"], r)++ def test_a_design_that_keying_would_erase_is_refused_by_the_safety_net(self):+ # A CLAUSE THAT DOES NOT CARE WHICH POPULATION THE FILE IS IN. This+ # fixture is a black plate with saturated ink on it — it passes the+ # transparency, backdrop, flatness and saturation clauses — but the+ # ink is a sixth of the plate, so keying would hand back a hole where+ # a card was. `ink_kept` is the only thing that refuses it.+ h, w = 440, 800+ rgb = np.zeros((h, w, 3), np.float32)+ a = np.zeros((h, w), np.float32)+ a[40:400, 40:760] = 255.0 # the plate+ rgb[40:400, 40:760] = np.array([6.0, 3.0, 9.0], np.float32)+ rgb[170:270, 100:700] = np.array([255.0, 90.0, 240.0], np.float32)+ p = self.d / "tiny_logo.png"+ _rgba(p, rgb, a)+ r = panel._sbe_plate_report(p)+ self.assertGreaterEqual(r["hot_share"], panel.SBE_PLATE_HOT_SHARE_MIN)+ self.assertLessEqual(r["flat"], panel.SBE_PLATE_FLAT_MAX)+ self.assertFalse(r["plate"])+ self.assertEqual(r["why"], "keying it would erase the picture")+ self.assertLess(r["ink_kept"], panel.SBE_PLATE_INK_MIN)++ def test_the_reported_card_itself(self):+ if not PLATE_CARD.is_file():+ raise unittest.SkipTest("the reported card is not on this machine")+ r = panel._sbe_plate_report(PLATE_CARD)+ self.assertTrue(r["plate"], r)+ # The numbers in the comment block above `_sbe_plate_report`.+ self.assertAlmostEqual(r["clear_share"], 0.433, places=2)+ self.assertAlmostEqual(r["opaque_share"], 0.412, places=2)+ self.assertAlmostEqual(r["hot_share"], 0.272, places=2)++ def test_a_genuinely_transparent_card_on_this_machine_is_left_alone(self):+ if not ENDCARD.is_file():+ raise unittest.SkipTest("endcard not present")+ self.assertFalse(panel._sbe_plate_report(ENDCARD)["plate"])++ # ---- keying -----------------------------------------------------------+ def test_the_original_is_never_modified(self):+ import hashlib # noqa: PLC0415+ p = self.plate()+ before = hashlib.sha256(p.read_bytes()).hexdigest()+ made = panel._sbe_key_plate(p)+ self.assertTrue(made["ok"])+ self.assertNotEqual(Path(made["path"]), p)+ self.assertEqual(Path(made["path"]).parent, p.parent)+ self.assertEqual(hashlib.sha256(p.read_bytes()).hexdigest(), before)++ def test_the_derivative_is_the_original_over_black(self):+ """The identity the whole transform stands on.++ `a'·C' = a·(m/255) · C·(255/m) = a·C`, so compositing the derivative+ over black reproduces the source to within 8-bit rounding — and+ everywhere the backdrop was, the background now shows through instead.+ """+ from PIL import Image # noqa: PLC0415+ p = self.plate()+ k = Path(panel._sbe_key_plate(p)["path"])+ o = np.asarray(Image.open(p).convert("RGBA"), np.float32)+ d = np.asarray(Image.open(k).convert("RGBA"), np.float32)+ over_black = lambda x: x[..., :3] * (x[..., 3:] / 255.0) # noqa: E731+ self.assertLess(np.abs(over_black(o) - over_black(d)).max(), 1.5)+ # ...and the plate is gone: nothing is opaque-and-black any more.+ # Measured under a NEUTRAL name so it is the PIXELS that refuse a+ # second key, not the `.keyed.png` shortcut.+ neutral = self.d / "second_pass.png"+ neutral.write_bytes(k.read_bytes())+ r = panel._sbe_plate_report(neutral)+ self.assertEqual(r["dark_share"], 0.0)+ self.assertFalse(r["plate"])++ def test_keying_is_idempotent(self):+ p = self.plate()+ k = Path(panel._sbe_key_plate(p)["path"])+ self.assertFalse(panel._sbe_plate_report(k)["plate"])+ self.assertEqual(panel._sbe_plate_report(k)["why"], "already keyed")+ # ...and asking twice reuses the file rather than making a second one.+ self.assertTrue(panel._sbe_key_plate(p)["reused"])+ self.assertEqual(len(list(self.d.glob("*.png"))), 2)++ def test_it_composites_with_NO_BLACK_over_a_known_background(self):+ """Measured in pixels, through the chain the panel actually builds.++ Reading the filter string proves nothing — the plated card and the+ keyed one produce the same filtergraph. So: render both over the same+ solid base and count.+ """+ if not shutil.which("ffmpeg"):+ raise unittest.SkipTest("ffmpeg not present")+ p = self.plate()+ k = Path(panel._sbe_key_plate(p)["path"])++ def black_share(card: Path) -> float:+ out = self.d / (card.stem + "_frame.png")+ chain = ("[1:v]format=rgba,scale=768:416:flags=lanczos,"+ "format=rgba,setsar=1,setpts=PTS+0/TB[ov0];"+ "[0:v][ov0]overlay=0:0:eof_action=pass:repeatlast=0:"+ "enable='between(t,0,2)'[vout]")+ subprocess.run(+ ["ffmpeg", "-v", "error", "-f", "lavfi",+ "-i", "color=c=0x5A96DC:s=768x416:r=24:d=2",+ "-loop", "1", "-framerate", "24", "-t", "2", "-i", str(card),+ "-filter_complex", chain, "-map", "[vout]", "-frames:v", "1",+ "-y", str(out)], check=True, capture_output=True)+ raw = subprocess.run(+ ["ffmpeg", "-v", "error", "-i", str(out), "-f", "rawvideo",+ "-pix_fmt", "rgb24", "-"], capture_output=True).stdout+ a = np.frombuffer(raw, np.uint8).reshape(416, 768, 3).astype(int)+ return float((a.max(axis=2) < 40).mean())++ self.assertGreater(black_share(p), 0.01,+ "the fixture is not reproducing the reported bug")+ self.assertEqual(black_share(k), 0.0,+ "the keyed card still puts black over the picture")+++class TheOverlayKeyRoute(EditorCase):+ """`POST /storyboard/edit/overlay-key` — the one seam the client uses."""++ def _plate(self, name="plate.png"):+ rgb, disc, _ = _burst(440, 800)+ p = self.out / name+ _rgba(p, rgb, np.where(disc, 255.0, 0.0))+ return p++ def test_a_plate_comes_back_as_a_derivative(self):+ p = self._plate()+ r = FakeHandler().post("edit/overlay-key", {"path": str(p)}).payload+ self.assertTrue(r["ok"])+ self.assertTrue(r["keyed"])+ self.assertNotEqual(r["path"], str(p))+ self.assertEqual(r["original"], str(p))+ self.assertTrue(Path(r["path"]).is_file())+ # The measurement travels with the answer, so a false negative in the+ # field can be diagnosed from the response.+ self.assertIn("hot_share", r["measured"])++ def test_an_honest_card_comes_back_untouched(self):+ rgb, _, ink = _burst(440, 800)+ rgb[~ink] = 0.0+ p = self.out / "honest.png"+ _rgba(p, rgb, np.where(ink, 255.0, 0.0))+ r = FakeHandler().post("edit/overlay-key", {"path": str(p)}).payload+ self.assertTrue(r["ok"])+ self.assertFalse(r["keyed"])+ self.assertEqual(r["path"], str(p))+ self.assertFalse(list(self.out.glob("*keyed*")))++ def test_a_path_outside_the_panels_own_folders_is_refused(self):+ h = FakeHandler().post("edit/overlay-key", {"path": "/etc/hosts"})+ self.assertEqual(h.status, 400)+ self.assertFalse(h.payload["ok"])++ def test_the_render_and_the_export_receive_the_SAME_file(self):+ """Parity is by construction: one path, three consumers."""+ p = self._plate()+ r = FakeHandler().post("edit/overlay-key", {"path": str(p)}).payload+ kept = r["path"]+ ov = [{"id": "o1", "kind": "still", "path": kept, "start": 0.0,+ "end": 2.0, "film_start": 1.0, "film_end": 3.0}]+ graph, _ = panel._sb_film_filtergraph(+ [], 768, 416, 48000, "yuv420p",+ segments=[{"kind": "video", "input": 0,+ "info": {"has_audio": True, "duration": 10.0, "w": 768,+ "h": 416, "sample_rate": 48000},+ "window": {"start": 0.0, "end": 4.0}, "adjust": None,+ "duration": 4.0, "path": "/x/a.mp4"}],+ overlays=ov, overlay_base=1)+ # The overlay stream ffmpeg is handed is input 1 — the derivative.+ self.assertIn("[1:v]format=rgba", graph)+ self.assertIn("overlay=0:0", graph)+ xml = sedit.fcp7_xml(+ [{"kind": "video", "path": "/x/a.mp4", "title": "a", "start": 0.0,+ "end": 4.0, "film_start": 0.0, "film_end": 4.0, "w": 768,+ "h": 416, "has_audio": True, "source_duration": 4.0}],+ name="f", media={"/x/a.mp4": "a.mp4", kept: Path(kept).name},+ width=768, height=416, base=str(self.out), overlays=ov)+ # The NLE is handed the derivative by name, on its own V2 track — the+ # same file the stage previewed and the same file ffmpeg composited.+ self.assertIn(Path(kept).stem, xml)+ self.assertEqual(len(ET.fromstring(xml).findall(".//video/track")), 2)+++class AThumbnailKeepsItsTransparency(unittest.TestCase):+ """The preview half of the same bug, and it was the louder half.++ The overlay's stage layer asks `/image?w=1280`, which resizes through+ `_ensure_thumbnail` — and that used to `convert("RGB")` and save JPEG+ unconditionally. Every card wider than the requested width was previewed+ as a solid rectangle of its own background colour while the ffmpeg render+ composited the very same file correctly. A stage that disagrees with the+ render is worse than no overlay lane.+ """++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.d = Path(self.tmp.name)+ self._p = mock.patch.object(panel, "_THUMBCACHE", self.d / "cache")+ self._p.start()++ def tearDown(self):+ self._p.stop()+ self.tmp.cleanup()++ def test_a_transparent_source_resizes_with_its_alpha(self):+ from PIL import Image # noqa: PLC0415+ rgb, _, ink = _burst(900, 1600)+ rgb[~ink] = 0.0+ src = self.d / "card.png"+ _rgba(src, rgb, np.where(ink, 255.0, 0.0))+ out = panel._ensure_thumbnail(src, 640)+ with Image.open(out) as im:+ self.assertIn("A", im.getbands(),+ "the thumbnail dropped the alpha channel")+ self.assertLess(np.asarray(im.convert("RGBA"))[..., 3].mean(), 200,+ "every pixel came back opaque")++ def test_an_opaque_source_is_still_a_jpeg(self):+ from PIL import Image # noqa: PLC0415+ src = self.d / "photo.png"+ Image.fromarray(np.rint(_photoish(900, 1600)).astype(np.uint8),+ "RGB").save(src)+ out = panel._ensure_thumbnail(src, 640)+ self.assertEqual(out.suffix, ".jpg")+++class TheImagesTabSeesTheOutputsFolder(unittest.TestCase):+ """The pool's Images tab reads `/outputs`, and `/outputs` used to walk the+ image library only — so a card rendered or delivered into `mlx_outputs/`+ was invisible in the one list that turns a still into an overlay."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.d = Path(self.tmp.name)+ (self.d / "outputs").mkdir()+ (self.d / "uploads").mkdir()+ self._patches = [+ mock.patch.object(panel, "OUTPUT", self.d / "outputs"),+ mock.patch.object(panel, "UPLOADS", self.d / "uploads"),+ mock.patch.object(panel, "HIDDEN_PATHS", set()),+ mock.patch.dict(panel.STATE, {"current": None, "history": []}),+ ]+ for p in self._patches:+ p.start()++ def tearDown(self):+ for p in reversed(self._patches):+ p.stop()+ self.tmp.cleanup()++ def _png(self, name):+ from PIL import Image # noqa: PLC0415+ p = self.d / "outputs" / name+ Image.new("RGBA", (8, 8), (255, 0, 0, 255)).save(p)+ import os # noqa: PLC0415+ os.utime(p, (1_700_000_000, 1_700_000_000))+ return p++ def test_a_picture_in_the_outputs_folder_reaches_the_gallery(self):+ p = self._png("endcard.png")+ rows = panel.list_outputs(limit=0)+ got = [r for r in rows if r["path"] == str(p)]+ self.assertEqual(len(got), 1, "the outputs image never appeared")+ self.assertEqual(got[0]["kind"], "image")+ # ...and it is addressable by the route the pool paints it with.+ self.assertTrue(got[0]["url"].startswith("/image?"))++ def test_a_working_subfolder_is_NOT_a_gallery(self):+ # Proxies, per-film project folders and report intermediates live under+ # OUTPUT and are not outputs. The video scan is root-only; so is this.+ sub = self.d / "outputs" / "storyboards"+ sub.mkdir()+ from PIL import Image # noqa: PLC0415+ Image.new("RGB", (8, 8)).save(sub / "proxy_frame.png")+ rows = panel.list_outputs(limit=0)+ self.assertFalse([r for r in rows if "proxy_frame" in r["path"]])+++class TheEffectsModel(unittest.TestCase):+ """docs/EDITOR_EFFECTS_MODEL.md — the base, and its first citizen.++ "Just set the base to have effects somewhere, and then we will find a way+ to better integrate them." The rule that decides what ships: an effect+ that cannot be honestly expressed in ALL THREE outputs does not ship.+ """++ def _clip(self, **kw):+ return dict({"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 4.0, "film_start": 0.0,+ "film_end": 4.0, "source": "human", "locked": False,+ "duration": 10.0}, **kw)++ def test_absent_means_no_effect_and_no_version_bump(self):+ e = sedit.clip_effects(self._clip())+ self.assertEqual([e["fade_in"], e["fade_out"], e["brightness"]],+ [0.0, 0.0, 0.0])+ self.assertEqual(sedit.EDIT_VERSION, 2)++ def test_ONE_accessor_whatever_the_storage(self):+ # Brightness is the legacy citizen and stays at `adjust.brightness`;+ # fades live in `fx`. A consumer never has to know that.+ c = self._clip(fx={"fade_in": 0.5}, adjust={"brightness": 0.25})+ e = sedit.clip_effects(c)+ self.assertEqual(e["fade_in"], 0.5)+ self.assertEqual(e["brightness"], 0.25)++ def test_the_clamp_lives_in_the_model_so_every_output_gets_legal_numbers(self):+ # Two fades that crossed would ask ffmpeg for an opacity that is two+ # things at once and hand the NLEs keyframes out of order.+ e = sedit.clip_effects(self._clip(fx={"fade_in": 3.0, "fade_out": 3.0}))+ self.assertEqual(e["fade_in"], 2.0)+ self.assertEqual(e["fade_out"], 2.0)+ self.assertLessEqual(e["fade_in"] + e["fade_out"], 4.0)+ # ...and it is proportional, not a truncation of one of them.+ e2 = sedit.clip_effects(self._clip(fx={"fade_in": 3.0, "fade_out": 1.0}))+ self.assertGreater(e2["fade_in"], e2["fade_out"])+ self.assertAlmostEqual(e2["fade_in"] + e2["fade_out"], 4.0, places=6)++ def test_neutral_is_absent_on_the_way_to_disk(self):+ doc = sedit.normalise_edit(_edit([self._clip(fx={"fade_in": 0.0})]))+ self.assertNotIn("fx", doc["clips"][0])+ doc = sedit.normalise_edit(_edit([self._clip(fx={"fade_in": 0.5})]))+ self.assertEqual(doc["clips"][0]["fx"], {"fade_in": 0.5})+ # ...and what lands on disk is already CLAMPED, so all three outputs+ # read the same legal numbers.+ doc = sedit.normalise_edit(_edit([self._clip(fx={"fade_in": 9.0})]))+ self.assertEqual(doc["clips"][0]["fx"], {"fade_in": 4.0})++ def test_a_negative_or_nonsense_fade_is_refused(self):+ for fx in ({"fade_in": -1}, {"fade_in": "half"}):+ codes = [e["code"] for e in+ sedit.validate_edit(_edit([self._clip(fx=fx)]))]+ self.assertTrue(any(c.startswith("clip_fade") for c in codes), fx)+ self.assertIn("clip_fx", [e["code"] for e in+ sedit.validate_edit(_edit([self._clip(fx=7)]))])++ def test_a_fade_saves_and_reloads(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, _edit([self._clip(fx={"fade_in": 0.5,+ "fade_out": 1.0})]))+ got = sedit.load_edit(bdir)+ self.assertEqual(got["clips"][0]["fx"],+ {"fade_in": 0.5, "fade_out": 1.0})+ self.assertEqual(sedit.validate_edit(got), [])++ # ---- output 2: the render ----------------------------------------+ def test_the_cut_list_and_the_graph_carry_it(self):+ cuts = sedit.edit_to_cuts(_edit([self._clip(fx={"fade_in": 0.5,+ "fade_out": 1.0})]))+ self.assertEqual(cuts[0]["fx"], {"fade_in": 0.5, "fade_out": 1.0})+ # ...and an unfaded clip says nothing at all, so every film ever+ # exported builds the identical graph.+ self.assertNotIn("fx", sedit.edit_to_cuts(_edit([self._clip()]))[0])++ def test_the_fade_filter_runs_on_the_SEGMENTS_own_timeline(self):+ # After trim+setpts, so `st=0` is this clip's first frame whatever+ # window it plays: fades compose with trims without either knowing+ # about the other.+ term = panel._sb_fade_term({"fade_in": 0.5, "fade_out": 1.0}, 4.0)+ self.assertIn("fade=t=in:st=0:d=0.500000,", term)+ self.assertIn("fade=t=out:st=3.000000:d=1.000000,", term)+ self.assertEqual(panel._sb_fade_term(None, 4.0), "")+ self.assertEqual(panel._sb_fade_term({}, 4.0), "")++ def test_an_unfaded_film_builds_the_graph_it_always_did(self):+ info = {"has_audio": True, "duration": 10.0, "w": 1024, "h": 576,+ "sample_rate": 48000}+ seg = {"kind": "video", "input": 0, "info": dict(info),+ "window": {"start": 0.0, "end": 4.0}, "adjust": None,+ "duration": 4.0, "path": "/x/a.mp4"}+ plain, _ = panel._sb_film_filtergraph([], 1024, 576, 48000, "yuv420p",+ segments=[dict(seg)])+ self.assertNotIn("fade=", plain)+ faded, _ = panel._sb_film_filtergraph(+ [], 1024, 576, 48000, "yuv420p",+ segments=[dict(seg, fx={"fade_in": 0.5})])+ self.assertIn("fade=t=in:st=0:d=0.500000", faded)++ # ---- output 3: the export ----------------------------------------+ def _rows(self, **fx):+ return [{"kind": "video", "path": "/x/a.mp4", "title": "shot",+ "start": 0.0, "end": 4.0, "film_start": 0.0, "film_end": 4.0,+ "brightness": 0.0, "w": 1024, "h": 576, "has_audio": True,+ "muted": False, "source_duration": 10.0,+ "fx": dict({"fade_in": 0.0, "fade_out": 0.0}, **fx)}]++ def test_fcp7_gets_real_opacity_keyframes(self):+ # NOBODY RECEIVES BAKED PIXELS: the decision travels, not just its+ # result, so the editor downstream can drag the fade.+ xml = sedit.fcp7_xml(self._rows(fade_in=0.5, fade_out=1.0), name="f",+ media={"/x/a.mp4": "a.mp4"}, width=1024,+ height=576, base="/tmp/p")+ root = ET.fromstring(xml)+ keys = [(int(k.find("when").text), float(k.find("value").text))+ for k in root.iter("keyframe")]+ self.assertEqual(keys, [(0, 0.0), (12, 100.0), (72, 100.0), (96, 0.0)])+ self.assertIn("<name>Opacity</name>", xml)+ # An unfaded clip carries no filter at all.+ plain = sedit.fcp7_xml(self._rows(), name="f",+ media={"/x/a.mp4": "a.mp4"}, width=1024,+ height=576, base="/tmp/p")+ self.assertNotIn("<name>Opacity</name>", plain)++ def test_after_effects_gets_the_same_decision_in_its_own_idiom(self):+ jsx = sedit.ae_jsx(self._rows(fade_in=0.5, fade_out=1.0), name="f",+ media={"/x/a.mp4": "a.mp4"}, width=1024, height=576)+ self.assertIn("ADBE Opacity", jsx)+ for line in ("op.setValueAtTime(0.000000, 0);",+ "op.setValueAtTime(0.500000, 100);",+ "op.setValueAtTime(3.000000, 100);",+ "op.setValueAtTime(4.000000, 0);"):+ self.assertIn(line, jsx)+ self.assertNotIn("ADBE Opacity", sedit.ae_jsx(+ self._rows(), name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576))++ def test_the_three_outputs_agree_on_WHERE_the_ramps_are(self):+ # The equivalence the model exists to guarantee: one clamped pair of+ # numbers, three idioms, the same two ramps in the same two places.+ rows = self._rows(fade_in=0.5, fade_out=1.0)+ xml = sedit.fcp7_xml(rows, name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576, base="/tmp/p")+ root = ET.fromstring(xml)+ keys = [(int(k.find("when").text) / 24.0, float(k.find("value").text))+ for k in root.iter("keyframe")]+ jsx = sedit.ae_jsx(rows, name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576)+ ae = [(float(m[0]), float(m[1])) for m in re.findall(+ r"op\.setValueAtTime\(([\d.]+), (\d+)\);", jsx)]+ self.assertEqual([round(t, 3) for t, _ in keys],+ [round(t, 3) for t, _ in ae])+ self.assertEqual([v for _, v in keys], [v for _, v in ae])+ term = panel._sb_fade_term(rows[0]["fx"], 4.0)+ self.assertIn("d=0.500000", term) # the in-ramp, same length+ self.assertIn("st=3.000000", term) # the out-ramp, same place+++class TheSameTakeTwiceIsOrdinaryEditing(unittest.TestCase):+ """sb_carwash rev 97, and the repair that would have eaten it.++ "I wanted it a little before her showing up, and I cut it that way. But no+ matter what I do, this is always out, even if I started with the full+ clip."++ Two uses of one take: the first is the whole thing with no strip of its+ own, the second is trimmed 0.42 s off the head with a strip that reaches+ back to cover it. That is a J-cut, and it is the most ordinary edit this+ feature exists to make.+ """++ def _board(self):+ src = "/x/carwash_15_buggy_but_it_works__warm.mp4"+ five = {"id": "c5", "path": src, "proxy": None, "start": 0.0,+ "end": 4.042, "film_start": 25.99, "film_end": 30.032,+ "source": "human", "locked": False, "duration": 4.042}+ six = {"id": "c6", "path": src, "proxy": None, "start": 0.42,+ "end": 4.042, "film_start": 30.77, "film_end": 34.392,+ "source": "human", "locked": False, "duration": 4.042,+ "audio": {"start": 0.0, "end": 4.042, "film_start": 30.35}}+ return _edit([five, six])++ def test_the_repair_does_not_touch_it(self):+ doc = self._board()+ self.assertEqual(sedit.repair_audio_overlaps(doc), 0)+ self.assertEqual(doc["clips"][1]["audio"],+ {"start": 0.0, "end": 4.042, "film_start": 30.35})+ self.assertNotIn("audio", doc["clips"][0])++ def test_his_j_cut_reads_as_IN_SYNC(self):+ # He trimmed 0.42 s off the picture head and left the sound reaching+ # back, so the same source second still plays at the same film second.+ six = self._board()["clips"][1]+ self.assertEqual(sedit.clip_audio_drift(six), 0.0)+ self.assertEqual(sedit.edit_sync_flags(self._board()), [])++ def test_load_save_load_is_byte_stable(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._board())+ first = sedit.load_edit(bdir)+ clips_a = json.dumps(first["clips"], sort_keys=True)+ sedit.save_edit(bdir, dict(first))+ second = sedit.load_edit(bdir)+ self.assertEqual(json.dumps(second["clips"], sort_keys=True), clips_a)+ self.assertEqual(second["clips"][1]["audio"],+ {"start": 0.0, "end": 4.042, "film_start": 30.35})+ # ...and a third pass changes nothing either.+ sedit.save_edit(bdir, dict(second))+ self.assertEqual(json.dumps(sedit.load_edit(bdir)["clips"],+ sort_keys=True), clips_a)+++class TheRepairIsAOneTimeMigration(unittest.TestCase):+ """A repair that runs on every read is a rival author.++ That is the thing the save-model ruling abolished, and it applies to our+ own migrations too: wrong once means wrong forever, invisibly, on every+ load of that film.+ """++ def _legacy(self):+ aud = {"start": 0.0, "end": 4.0, "film_start": 4.0}+ a = {"id": "a", "path": "/x/s.mp4", "proxy": None, "start": 0.0,+ "end": 2.0, "film_start": 4.0, "film_end": 6.0, "source": "human",+ "locked": False, "duration": 10.0, "audio": dict(aud)}+ b = {"id": "b", "path": "/x/s.mp4", "proxy": None, "start": 2.0,+ "end": 4.0, "film_start": 6.0, "film_end": 8.0, "source": "human",+ "locked": False, "duration": 10.0, "audio": dict(aud)}+ return _edit([a, b])++ def test_the_true_artifact_still_repairs_exactly_once(self):+ doc = sedit.migrate_edit(self._legacy())+ self.assertTrue(doc.get("repaired_audio_overlaps"))+ self.assertEqual(doc["audio_repair"], sedit.AUDIO_REPAIR_VERSION)+ self.assertEqual(doc["clips"][0]["audio"],+ {"start": 0.0, "end": 2.0, "film_start": 4.0})+ self.assertEqual(doc["clips"][1]["audio"],+ {"start": 2.0, "end": 4.0, "film_start": 6.0})++ def test_THE_REPAIR_DOES_NOT_REACH_BACK_INTO_THE_CALLERS_DOCUMENT(self):+ # `migrate_edit` shallow-copied the document and then let+ # `repair_audio_overlaps` write `clip["audio"]` — on clip dicts still+ # shared with the caller. `pending_backup` compares raw JSON on both+ # sides, so a read that edits its argument makes the file and the+ # snapshot differ over a repair neither of them contains: the+ # permanent interrogation docs/EDITOR_SAVE_MODEL.md exists to kill,+ # one level deeper than the mix stamp's own guard was looking.+ doc = self._legacy()+ before = json.dumps(doc, sort_keys=True)+ got = sedit.migrate_edit(doc)+ self.assertTrue(got.get("repaired_audio_overlaps"),+ "the fixture stopped triggering the repair")+ self.assertEqual(json.dumps(doc, sort_keys=True), before)+ self.assertEqual(doc["clips"][0]["audio"],+ {"start": 0.0, "end": 4.0, "film_start": 4.0})+ self.assertIsNot(got["clips"][0], doc["clips"][0])++ def test_the_marker_prevents_a_second_pass(self):+ stamped = dict(self._legacy(), audio_repair=sedit.AUDIO_REPAIR_VERSION)+ before = json.dumps(stamped["clips"], sort_keys=True)+ got = sedit.migrate_edit(stamped)+ self.assertEqual(json.dumps(got["clips"], sort_keys=True), before)+ self.assertNotIn("repaired_audio_overlaps", got)++ def test_a_repaired_board_is_never_examined_again(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, sedit.migrate_edit(self._legacy()))+ once = json.dumps(sedit.load_edit(bdir)["clips"], sort_keys=True)+ for _ in range(3):+ self.assertEqual(+ json.dumps(sedit.load_edit(bdir)["clips"], sort_keys=True),+ once)++ def test_the_marker_is_bookkeeping_and_not_content(self):+ a = self._board_like()+ b = dict(a, audio_repair=sedit.AUDIO_REPAIR_VERSION)+ self.assertEqual(sedit.edit_digest(a), sedit.edit_digest(b))++ def _board_like(self):+ return _edit([{"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 2.0, "film_start": 0.0,+ "film_end": 2.0, "source": "human", "locked": False,+ "duration": 10.0}])+++class TheSaveModel(unittest.TestCase):+ """The owner's architecture ruling, as a gate. docs/EDITOR_SAVE_MODEL.md.++ "Either the autosave is something on the side that you can always go and+ check the older versions... it only saves the real saves that are manually+ saved and named by the author... It's intertwined in a way that is causing+ a lot of problems."++ The last sentence is the defect: two writers of record and no rule about+ which one won.+ """++ def _doc(self, **kw):+ c = dict({"id": "a", "path": "/x/a.mp4", "proxy": None, "start": 0.0,+ "end": 4.0, "film_start": 0.0, "film_end": 4.0,+ "source": "human", "locked": False, "duration": 10.0},+ **kw)+ return _edit([c])++ # ---- rule 4: content-equal shows NOTHING --------------------------+ def test_a_rewritten_proxy_pointer_is_not_a_content_difference(self):+ # THE BUG. `_sbe_payload` rewrites every clip's `proxy` on the way out,+ # deliberately, so a proxy built after the last save becomes visible+ # without a re-save. The old comparison was `json.dumps(clips)`, so the+ # client's copy differed from the file in a field the user has never+ # heard of — on any board whose proxies were built after its last save,+ # forever.+ a = self._doc(proxy="proxy/a_d83ae3ddf0b5.mp4")+ b = self._doc(proxy=None)+ self.assertEqual(sedit.edit_digest(a), sedit.edit_digest(b))++ def test_neither_is_a_revision_a_timestamp_or_an_origin(self):+ a = dict(self._doc(), revision=93, updated_at=111, origin="auto")+ b = dict(self._doc(), revision=94, updated_at=222, origin="manual")+ self.assertEqual(sedit.edit_digest(a), sedit.edit_digest(b))++ def test_but_a_REAL_edit_is(self):+ for kw in ({"end": 3.5}, {"film_start": 1.0}, {"locked": True},+ {"mute": True},+ {"audio": {"start": 0.0, "end": 4.0, "film_start": 1.0}},+ {"adjust": {"brightness": 0.2}}):+ self.assertNotEqual(sedit.edit_digest(self._doc()),+ sedit.edit_digest(self._doc(**kw)), kw)+ # ...and so is the soundtrack, and the beats.+ self.assertNotEqual(+ sedit.edit_digest(self._doc()),+ sedit.edit_digest(dict(self._doc(),+ audio={"path": "/t.wav", "offset": 0})))++ def test_a_content_equal_snapshot_raises_no_offer_at_all(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._doc())+ # what the CLIENT holds: the same film with proxies filled in+ sedit.write_backup(bdir, self._doc(proxy="proxy/a_abc123.mp4"))+ self.assertIsNone(sedit.pending_backup(bdir))++ def test_a_real_difference_still_raises_one(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._doc())+ sedit.write_backup(bdir, self._doc(end=3.0, film_end=3.0))+ offer = sedit.pending_backup(bdir)+ self.assertIsNotNone(offer)+ self.assertEqual(offer["clips"], 1)++ # ---- rule 1: loading always gives the last manual save ------------+ def test_loading_a_draft_ALWAYS_gives_the_last_manual_save(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._doc()) # rev 1+ sedit.write_backup(bdir, self._doc(end=2.0, film_end=2.0))+ got = sedit.load_edit(bdir)+ self.assertEqual(got["revision"], 1)+ self.assertEqual(got["clips"][0]["end"], 4.0) # NOT the snapshot+ # ...and the snapshot is still there to be looked at.+ self.assertIsNotNone(sedit.pending_backup(bdir))++ # ---- rule 5: a superseded session writes nothing ------------------+ def test_an_unclaimed_board_refuses_nobody(self):+ # Every board written before this existed, plus every agent and script+ # posting to the routes with no tab to claim one.+ with tempfile.TemporaryDirectory() as d:+ self.assertTrue(sedit.session_is_current(Path(d), ""))+ self.assertTrue(sedit.session_is_current(Path(d), "anything"))++ def test_the_newest_loader_owns_the_lane_and_the_older_tab_is_refused(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._doc())+ sedit.claim_session(bdir, "tab-one")+ self.assertTrue(sedit.session_is_current(bdir, "tab-one"))+ sedit.claim_session(bdir, "tab-two") # a reload+ self.assertFalse(sedit.session_is_current(bdir, "tab-one"))+ self.assertTrue(sedit.session_is_current(bdir, "tab-two"))++ def test_a_snapshot_from_ANY_tab_is_kept(self):+ """Invariant 4 was "a snapshot from a superseded session is refused",+ and it was written for a lane with ONE slot per draft, where a stale+ tab's write destroyed the newer content in it.++ That lane is gone — one file per snapshot, pruned, never overwritten —+ and the invariant outlived its reason. What it did instead was cost the+ owner an afternoon: the claim was taken by LOADING, so a passive page+ load in another browser refused the tab he was cutting in, and it+ stopped writing snapshots for seven hours without saying so.++ The rule now: the lane refuses nobody. A snapshot from any tab costs+ one file and can only ever ADD a way back; refusing one can only ever+ remove one. Which tab is editing is still recorded — as something a+ person can be TOLD, never as a reason to stop protecting them.+ """+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._doc())+ sedit.write_backup(bdir, self._doc(end=3.0, film_end=3.0),+ session="old")+ sedit.claim_session(bdir, "new") # another tab+ sedit.write_backup(bdir, self._doc(end=1.0, film_end=1.0),+ session="old")+ # BOTH are on disk, and the older tab's work is one of them.+ self.assertEqual(len(sedit.list_history(bdir)), 2)+ self.assertIsNotNone(sedit.pending_backup(bdir))++ # ---- rule 3: restore can never lose anything ----------------------+ def _save(self, bdir, doc):+ """What the route does: the revision is the SERVER's, from disk."""+ cur = sedit.load_edit(bdir) or {}+ doc = dict(doc, revision=int(cur.get("revision") or 0))+ sedit.save_edit(bdir, doc)++ def test_restore_archives_the_current_document_first(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ self._save(bdir, self._doc()) # rev 1+ self._save(bdir, self._doc(end=2.0, film_end=2.0)) # rev 2+ rows = sedit.list_history(bdir)+ self.assertTrue(rows)+ before = {r["file"] for r in rows}+ sedit.restore_edit(bdir, rows[-1]["file"])+ after = {r["file"] for r in sedit.list_history(bdir)}+ # The document that was on screen when Restore was pressed is now+ # itself a version — restoring by mistake loses nothing.+ self.assertTrue(after - before)+ self.assertGreater(sedit.load_edit(bdir)["revision"], 2)++ # ---- rule 2: the lane is versioned, bounded, and never stops ------+ def test_a_new_snapshot_never_destroys_the_last_one(self):+ # The single slot is why the client carried "if there is an offer, do+ # not write" — which switched the safety net off for the rest of the+ # session the moment a chip appeared and nobody dismissed it.+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ self._save(bdir, self._doc())+ sedit.write_backup(bdir, self._doc(end=3.0, film_end=3.0))+ first = sedit.latest_snapshot(bdir)[0]+ sedit.write_backup(bdir, self._doc(end=2.0, film_end=2.0))+ second = sedit.latest_snapshot(bdir)[0]+ self.assertNotEqual(first, second)+ self.assertTrue(first.is_file()) # the older one survives+ self.assertEqual(sedit.pending_backup(bdir)["duration"], 2.0)++ def test_the_lane_is_bounded(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ self._save(bdir, self._doc())+ for i in range(sedit.SNAPSHOT_KEEP + 6):+ sedit.write_backup(bdir, self._doc(end=4.0 - i * 0.01,+ film_end=4.0 - i * 0.01))+ self.assertLessEqual(len(sedit._snapshot_paths(bdir)),+ sedit.SNAPSHOT_KEEP)++ def test_snapshots_are_listed_in_the_versions_browser_and_marked(self):+ # Rule 3: manual saves, named versions and snapshots together, and+ # visually distinct.+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ self._save(bdir, self._doc())+ self._save(bdir, self._doc(end=3.0, film_end=3.0))+ sedit.write_backup(bdir, self._doc(end=2.0, film_end=2.0))+ rows = sedit.list_history(bdir)+ snaps = [r for r in rows if r["snapshot"]]+ saves = [r for r in rows if r["manual"]]+ self.assertEqual(len(snaps), 1)+ self.assertTrue(saves)+ self.assertFalse(snaps[0]["manual"])+ # ...and one is restorable like any other version.+ sedit.restore_edit(bdir, snaps[0]["file"])+ self.assertEqual(sedit.load_edit(bdir)["clips"][0]["end"], 2.0)++ def test_a_legacy_single_slot_board_migrates_losslessly(self):+ # Rule 6: nothing on disk is deleted. A board written before the lane+ # was versioned is read, not ignored.+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ self._save(bdir, self._doc())+ legacy = sedit._backup_path(bdir, "draft-1")+ legacy.parent.mkdir(parents=True, exist_ok=True)+ legacy.write_text(json.dumps(sedit.normalise_edit(+ self._doc(end=1.5, film_end=1.5))))+ got = sedit.latest_snapshot(bdir)+ self.assertIsNotNone(got)+ # MOVED into the lane, not read where it lay: a file at the root+ # of history/ is invisible to the versions list and unreachable by+ # restore, so it would have been a snapshot the user could be told+ # about and could not open.+ self.assertFalse(legacy.exists())+ self.assertTrue(got[0].name.startswith("snap-"))+ self.assertEqual(sedit.pending_backup(bdir)["duration"], 1.5)+ rows = sedit.list_history(bdir)+ self.assertIn(got[0].name, [r["file"] for r in rows])+ sedit.restore_edit(bdir, got[0].name) # and it opens+ self.assertEqual(sedit.load_edit(bdir)["clips"][0]["end"], 1.5)++ # ---- rule 2: the side archive never has an opinion ----------------+ def test_the_snapshot_lane_takes_anything_a_manual_save_would(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ # An overlapping J-cut: a WARNING, and neither writer may refuse.+ doc = _edit([+ dict(self._doc()["clips"][0], id="a"),+ {"id": "b", "path": "/x/b.mp4", "proxy": None, "start": 0.0,+ "end": 4.0, "film_start": 4.0, "film_end": 8.0,+ "source": "human", "locked": False, "duration": 10.0,+ "audio": {"start": 0.0, "end": 4.0, "film_start": 3.75}}])+ sedit.save_edit(bdir, doc)+ sedit.write_backup(bdir, doc) # neither raises++ # ---- rule 7: a cache may not outlive its subject ------------------+ def test_peaks_are_invalidated_when_the_soundtrack_changes(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_peaks(bdir, {"version": 1, "path": "/music/old.wav",+ "duration": 44.99, "peaks": [], "count": 0,+ "scale": 127, "buckets_per_second": 100})+ self.assertIsNotNone(sedit.load_peaks(bdir))+ self.assertIsNotNone(sedit.load_peaks(bdir, path="/music/old.wav"))+ # The strip read "44.99s" under a different file for exactly this+ # reason: nothing compared the cache to its subject.+ self.assertIsNone(sedit.load_peaks(bdir, path="/music/new.wav"))++ def test_the_same_file_spelled_two_ways_is_NOT_a_change(self):+ # `mlx_outputs/` is a symlink into Pinokio's shared drive, so the very+ # same soundtrack is spelled two ways depending on which side wrote it+ # down. A raw string compare would have blanked the waveform on boards+ # where nothing had changed — the invalidation fix arriving as a worse+ # bug than the one it fixed. Caught on the live test panel.+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ real = bdir / "track.wav"+ real.write_bytes(b"x")+ link = bdir / "via-a-link.wav"+ try:+ link.symlink_to(real)+ except OSError:+ raise unittest.SkipTest("no symlinks here")+ sedit.save_peaks(bdir, {"version": 1, "path": str(real),+ "duration": 12.0, "peaks": [], "count": 0,+ "scale": 127, "buckets_per_second": 100})+ self.assertIsNotNone(sedit.load_peaks(bdir, path=str(link)))+ self.assertIsNone(sedit.load_peaks(bdir, path=str(bdir / "no.wav")))+++class MutingAClipsOwnSound(unittest.TestCase):+ """`clip.mute` — one additive flag, three outputs, one meaning.++ "We should have an option to mute the clip sound." The H3 shot with wind+ baked in under the line, on a cut where the music is meant to carry it.+ """++ def _clip(self, **kw):+ return dict({"id": "a", "path": "/x/a.mp4", "proxy": None,+ "start": 0.0, "end": 4.0, "film_start": 0.0,+ "film_end": 4.0, "source": "human", "locked": False,+ "duration": 10.0}, **kw)++ def test_absent_is_audible_and_no_document_is_rewritten(self):+ self.assertFalse(sedit.clip_muted(self._clip()))+ self.assertTrue(sedit.clip_muted(self._clip(mute=True)))+ self.assertEqual(sedit.EDIT_VERSION, 2)++ def test_mute_save_reload_still_muted(self):+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, _edit([self._clip(mute=True)]))+ got = sedit.load_edit(bdir)+ self.assertTrue(got["clips"][0]["mute"])+ self.assertTrue(sedit.clip_muted(got["clips"][0]))+ self.assertEqual(sedit.validate_edit(got), [])+ # ...and unmuting leaves a document identical to one never muted.+ sedit.save_edit(bdir, _edit([self._clip()]))+ self.assertNotIn("mute", sedit.load_edit(bdir)["clips"][0])++ def test_the_flag_is_only_written_when_it_says_something(self):+ doc = sedit.normalise_edit(_edit([self._clip(mute=False)]))+ self.assertNotIn("mute", doc["clips"][0])+ slug = {"id": "s", "kind": "slug", "path": None, "start": 0.0,+ "end": 2.0, "film_start": 0.0, "film_end": 2.0,+ "source": "human", "locked": False, "mute": True}+ self.assertIn("clip_mute_kind",+ [e["code"] for e in sedit.validate_edit(_edit([slug]))])+ self.assertNotIn("mute", sedit.normalise_edit(_edit([slug]))["clips"][0])+ bad = self._clip(mute="yes")+ self.assertIn("clip_mute",+ [e["code"] for e in sedit.validate_edit(_edit([bad]))])++ def test_mute_and_unlink_compose(self):+ c = self._clip(mute=True, film_start=4.0, film_end=8.0,+ audio={"start": 0.0, "end": 4.0, "film_start": 3.0})+ self.assertTrue(sedit.clip_muted(c))+ w = sedit.clip_audio(c)+ self.assertTrue(w["split"]) # the strip stays put+ self.assertEqual(w["film_start"], 3.0)+ cuts = sedit.edit_to_cuts(_edit([c]))+ self.assertTrue(cuts[0]["mute"])+ self.assertEqual(cuts[0]["audio"]["film_start"], 3.0)++ def test_the_cut_list_says_nothing_when_nothing_is_muted(self):+ self.assertNotIn("mute", sedit.edit_to_cuts(_edit([self._clip()]))[0])+++class TheRenderMixIsActuallySilent(unittest.TestCase):+ """Mute is expressed as the ABSENCE of an audio lane.++ The film's sound is `concat` of lanes and `anullsrc` hushes laid end to+ end, so "do not play this clip" is a row that is not there — no volume+ filter, no mixer, nothing that could sum.+ """++ def _segs(self, mute_second: bool):+ info = {"has_audio": True, "duration": 10.0, "w": 1024, "h": 576,+ "sample_rate": 48000}+ segs = []+ for i, name in enumerate(("a", "b")):+ sg = {"kind": "video", "input": i, "info": dict(info),+ "window": {"start": 0.0, "end": 4.0}, "adjust": None,+ "duration": 4.0, "path": f"/x/{name}.mp4"}+ if mute_second and i == 1:+ sg["mute"] = True+ segs.append(sg)+ return segs++ def test_an_unmuted_film_builds_the_graph_it_always_did(self):+ plan = panel._sb_split_audio_plan(self._segs(False))+ self.assertFalse(plan["split"])+ self.assertEqual([L["idx"] for L in plan["lanes"]], [0, 1])++ def test_a_muted_clip_contributes_no_lane_and_forces_the_split_path(self):+ plan = panel._sb_split_audio_plan(self._segs(True))+ # Without the split flag the graph would take the plain+ # `concat ... a=1` branch and play the audio just switched off.+ self.assertTrue(plan["split"])+ self.assertEqual([L["idx"] for L in plan["lanes"]], [0])++ def test_the_muted_seconds_come_out_as_REAL_silence(self):+ plan = panel._sb_split_audio_plan(self._segs(True))+ chains = panel._sb_split_audio_chains(plan["lanes"], plan["total"],+ 48000, "[aout]")+ graph = ";".join(chains)+ self.assertIn("[a0]", graph)+ self.assertNotIn("[a1]", graph) # the muted clip is not in it+ # ...and its slot is an honest anullsrc of exactly its length, not an+ # input that happens to be quiet.+ self.assertIn("anullsrc=channel_layout=stereo:sample_rate=48000:"+ "d=4.000000", graph)+ self.assertIn("concat=n=2:v=0:a=1[aout]", graph)++ def test_the_flag_reaches_the_segments_from_the_timeline(self):+ entry = {"path": "/x/a.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0, "mute": True}+ win = panel._sb_cut_index([entry])["/x/a.mp4"][0]+ self.assertTrue(win["mute"])+++class TheExportDisablesTheTrackRatherThanDroppingIt(unittest.TestCase):+ """An editor on the far end must be able to see the decision and undo it."""++ def _segs(self, muted: bool):+ return [{"kind": "video", "path": "/x/a.mp4", "title": "shot one",+ "start": 0.0, "end": 4.0, "film_start": 0.0, "film_end": 4.0,+ "brightness": 0.0, "w": 1024, "h": 576, "has_audio": True,+ "muted": muted, "source_duration": 10.0}]++ def test_the_fcp7_audio_clipitem_is_present_and_DISABLED(self):+ on = sedit.fcp7_xml(self._segs(False), name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576, base="/tmp/p")+ off = sedit.fcp7_xml(self._segs(True), name="f", media={"/x/a.mp4": "a.mp4"},+ width=1024, height=576, base="/tmp/p")+ # The clipitem exists in BOTH — omitting it would arrive as a shot that+ # never had sound, and no editor could tell a decision from a source.+ self.assertIn('id="clipitem-a1"', on)+ self.assertIn('id="clipitem-a1"', off)+ self.assertEqual(on.count("<enabled>TRUE</enabled>"),+ off.count("<enabled>TRUE</enabled>") + 1)+ self.assertIn("<enabled>FALSE</enabled>", off)+ self.assertNotIn("<enabled>FALSE</enabled>", on)+ # ...and the PICTURE is untouched either way.+ self.assertIn('id="clipitem-1"', off)++ def test_the_after_effects_layer_keeps_its_sound_and_does_not_play_it(self):+ on = sedit.ae_jsx(self._segs(False), name="f",+ media={"/x/a.mp4": "a.mp4"}, width=1024, height=576)+ off = sedit.ae_jsx(self._segs(True), name="f",+ media={"/x/a.mp4": "a.mp4"}, width=1024, height=576)+ self.assertNotIn("audioEnabled", on)+ self.assertIn("lay.audioEnabled = false;", off)++ def test_the_flag_reaches_the_export_from_the_document(self):+ rows = sedit._nle_segments([+ {"id": "a", "path": "/x/a.mp4", "start": 0.0, "end": 4.0,+ "film_start": 0.0, "film_end": 4.0, "source": "human",+ "locked": False, "duration": 10.0, "mute": True}])+ self.assertTrue(rows[0]["muted"])+++class SavingIsNeverBlockedByOverlappingSound(unittest.TestCase):+ """The afternoon this cost, as a gate.++ `clips_audio_overlap` was an ERROR, and every writer of this document —+ Save, the autosave and the crash backup alike — refuses on any error. So+ the moment a J-cut pulled one line a quarter of a second under the outgoing+ shot, the board became unsaveable AND unbackupable, with a red "SAVING IS+ FAILING" banner over work that could not be stored anywhere. His exact+ report: "the sound of clips 1 and 2 overlaps (0.000-3.354s and+ 3.102-8.143s)".+ """++ def _pair(self, lead=0.25):+ a = {"id": "a", "path": "/x/a.mp4", "proxy": None, "start": 0.0,+ "end": 3.354, "film_start": 0.0, "film_end": 3.354,+ "source": "human", "locked": False, "duration": 10.0}+ b = {"id": "b", "path": "/x/b.mp4", "proxy": None, "start": 0.0,+ "end": 5.041, "film_start": 3.354, "film_end": 8.395,+ "source": "human", "locked": False, "duration": 10.0,+ "audio": {"start": 0.0, "end": 5.041,+ "film_start": round(3.354 - lead, 6)}}+ return _edit([a, b])++ def test_a_quarter_second_j_cut_is_a_WARNING_not_an_error(self):+ errs = sedit.validate_edit(self._pair())+ self.assertEqual([e["code"] for e in errs], ["clips_audio_overlap"])+ self.assertEqual(errs[0].get("severity"), "warning")+ self.assertEqual(sedit.blocking_errors(errs), [])++ def test_a_real_defect_still_blocks(self):+ broken = self._pair()+ broken["clips"][0]["end"] = -1.0+ self.assertTrue(sedit.blocking_errors(sedit.validate_edit(broken)))++ def test_save_and_backup_both_write_it(self):+ import tempfile+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._pair()) # must not raise+ got = sedit.load_edit(bdir)+ self.assertEqual(got["revision"], 1)+ self.assertEqual(got["clips"][1]["audio"]["film_start"], 3.104)+ sedit.write_backup(bdir, self._pair(lead=0.5)) # nor this+ self.assertIsNotNone(sedit.pending_backup(bdir))++ # ---- ...AND EVERY READER MUST GIVE IT BACK -------------------------+ # The severity split was applied to the two WRITERS and stopped there.+ # `recover_backup` and `restore_edit` kept refusing on the raw list, so+ # the work went to disk and could not come off it again: a crash over a+ # J-cut wrote a backup and then answered "Recover it" with the user's own+ # edit quoted back as the reason it was refused. Nothing discards the+ # offer on that path, and while an offer is unanswered the client stops+ # taking new snapshots — so the one failure disarmed the safety net for+ # the rest of the session. Caught by the v4.6.0 release gate.++ def test_a_crash_backup_holding_a_j_cut_can_be_RECOVERED(self):+ import tempfile+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, _edit([self._pair()["clips"][0]]))+ sedit.write_backup(bdir, self._pair())+ got = sedit.recover_backup(bdir) # must not raise+ self.assertEqual(len(got["clips"]), 2)+ self.assertIsNone(sedit.pending_backup(bdir))++ def test_a_history_version_holding_a_j_cut_can_be_RESTORED(self):+ import tempfile+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, self._pair()) # J-cut -> edit.json+ sedit.save_edit(bdir, _edit([self._pair()["clips"][0]]))+ rows = sedit.list_history(bdir)+ self.assertTrue(rows)+ got = sedit.restore_edit(bdir, rows[0]["file"]) # must not raise+ self.assertEqual(len(got["clips"]), 2)++ def test_a_genuinely_broken_version_is_STILL_refused(self):+ # The relaxation is scoped to WARNING_CODES and nothing else: a+ # history entry that would not validate as a document must still be+ # refused, or this fix would have traded one bug for a worse one.+ import tempfile+ broken = self._pair()+ broken["clips"][0]["end"] = -1.0+ self.assertTrue(sedit.blocking_errors(sedit.validate_edit(broken)))+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.save_edit(bdir, _edit([self._pair()["clips"][0]]))+ hist = sedit.history_dir(bdir)+ hist.mkdir(parents=True, exist_ok=True)+ (hist / "save-r00009.json").write_text(json.dumps(broken))+ with self.assertRaises(sedit.EditError):+ sedit.restore_edit(bdir, "save-r00009.json")+++class TheDuplicatedStripArtifactIsRepairedOnLoad(unittest.TestCase):+ """A board split before the J-cut fix carries two strips claiming the same+ seconds of the same take. It was legal when it was written and became+ unsaveable the day the overlap rule arrived — a migration problem wearing a+ validation error's clothes."""++ def _legacy(self):+ # What the old `sbeSplitAt` produced: a deep copy of `audio` on both+ # halves of the split.+ aud = {"start": 0.0, "end": 4.0, "film_start": 4.0}+ a = {"id": "a", "path": "/x/s.mp4", "proxy": None, "start": 0.0,+ "end": 2.0, "film_start": 4.0, "film_end": 6.0, "source": "human",+ "locked": False, "duration": 10.0, "audio": dict(aud)}+ b = {"id": "b", "path": "/x/s.mp4", "proxy": None, "start": 2.0,+ "end": 4.0, "film_start": 6.0, "film_end": 8.0, "source": "human",+ "locked": False, "duration": 10.0, "audio": dict(aud)}+ return _edit([a, b])++ def test_the_two_halves_are_re_cut_in_their_shared_source_clock(self):+ doc = self._legacy()+ self.assertEqual(sedit.repair_audio_overlaps(doc), 1)+ a, b = doc["clips"]+ self.assertEqual(a["audio"], {"start": 0.0, "end": 2.0,+ "film_start": 4.0})+ self.assertEqual(b["audio"], {"start": 2.0, "end": 4.0,+ "film_start": 6.0})+ # ...and the document it produces has nothing left to warn about.+ self.assertEqual(sedit.validate_edit(doc), [])++ def test_it_happens_on_the_way_IN_so_a_legacy_board_just_opens(self):+ import tempfile+ with tempfile.TemporaryDirectory() as d:+ bdir = Path(d)+ sedit.edit_path(bdir).write_text(json.dumps(self._legacy()))+ got = sedit.load_edit(bdir)+ self.assertTrue(got.get("repaired_audio_overlaps"))+ self.assertEqual(sedit.validate_edit(got), [])+ sedit.save_edit(bdir, got)++ def test_a_DELIBERATE_overlap_is_left_exactly_where_he_put_it(self):+ # A J-cut that merely overlaps its neighbour is a decision, not a+ # defect: the two strips play different seconds of different takes.+ a = {"id": "a", "path": "/x/a.mp4", "proxy": None, "start": 0.0,+ "end": 4.0, "film_start": 0.0, "film_end": 4.0, "source": "human",+ "locked": False, "duration": 10.0}+ b = {"id": "b", "path": "/x/b.mp4", "proxy": None, "start": 0.0,+ "end": 4.0, "film_start": 4.0, "film_end": 8.0, "source": "human",+ "locked": False, "duration": 10.0,+ "audio": {"start": 0.0, "end": 4.0, "film_start": 3.75}}+ doc = _edit([a, b])+ self.assertEqual(sedit.repair_audio_overlaps(doc), 0)+ self.assertEqual(doc["clips"][1]["audio"]["film_start"], 3.75)+++class TheSaveRouteAnswersWithWarnings(EditorCase):++ def test_an_overlapping_j_cut_saves_and_the_note_rides_back(self):+ a = _clip(str(self.clips[0]), 0.0, 2.0, 0.0)+ a["duration"] = 10.0+ b = _clip(str(self.clips[1]), 0.0, 2.0, 2.0)+ b["duration"] = 10.0+ b["audio"] = {"start": 0.0, "end": 2.0, "film_start": 1.75}+ h = FakeHandler().post("edit/save", {},+ json.dumps({"id": "sb_t",+ "edit": _edit([a, b])}))+ self.assertEqual(h.status, 200)+ self.assertTrue(h.payload["ok"])+ self.assertEqual([w["code"] for w in h.payload["warnings"]],+ ["clips_audio_overlap"])+ self.assertEqual(h.payload["edit"]["revision"], 1)+++class TheReadRouteReportsTheSyncFlags(EditorCase):+ """The panel cannot flag what the server does not say."""++ def test_the_payload_carries_the_sync_flags_beside_the_gaps(self):+ c = _clip(str(self.clips[0]), 0.0, 2.0, 0.0)+ c["duration"] = 10.0+ c["audio"] = {"start": 0.0, "end": 2.0, "film_start": 1.25}+ sedit.save_edit(self.bdir, _edit([c]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.status, 200)+ self.assertEqual(len(h.payload["sync"]), 1)+ self.assertEqual(h.payload["sync"][0]["drift"], 1.25)+ self.assertEqual(h.payload["sync"][0]["resync_to"], 0.0)++ def test_an_ordinary_film_reports_an_empty_list(self):+ sedit.save_edit(self.bdir, _edit(+ [_clip(str(self.clips[0]), 0.0, 2.0, 0.0)]))+ h = FakeHandler().get("/storyboard/edit?id=sb_t")+ self.assertEqual(h.payload["sync"], [])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_editor_ui.py b/test_storyboard_editor_ui.pynew file mode 100644index 0000000..3d69b22--- /dev/null+++ b/test_storyboard_editor_ui.py@@ -0,0 +1,6314 @@+#!/usr/bin/env python3+"""Executable UI contract for the timeline editor's CLIENT.++`test_storyboard_editor_api.py` locks the server: proxies, peaks, `edit.json`,+the eight routes. This locks the other half — the half that actually decides+where a cut lands, because the maths that moves a clip lives in the browser.++The panel ships its client inside `mlx_ltx_panel.py` as a string, so a test that+"covers" it by grepping for function names would pass while every drag was off+by a frame. This extracts the REAL functions and RUNS them in node, exactly the+way `test_stage_live_preview.py` and the character round-trip gate do. If the+drag maths changes, this fails; if a function is renamed, extraction raises+rather than quietly reducing coverage back to grepping.++What is locked here:+ * peaks decode — interleaved int16 over `scale`, count clamped to the array+ * the beat grid is never extrapolated past the fitted `span`+ * snap catches a beat inside the tolerance and NOTHING outside it, and the+ override is a straight bypass+ * move / trim / ripple / split, including the 1x invariant the server refuses+ an edit for breaking, and the refusal to touch a locked clip+ * undo/redo+ * the save payload's shape, including `expect_revision` and the stripping of+ client-only bookkeeping+ * a 409 leaves the arrangement on screen+ * validation errors map back onto the clip that caused them+"""+from __future__ import annotations++import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import (extract_element, extract_function, # noqa: E402+ panel_source)+++def panel_html_render() -> str:+ """The page as the browser is handed it, tokens replaced."""+ import mlx_ltx_panel as _p # noqa: PLC0415+ return (_p.HTML.replace("__SEQCAP__", _p.SEQ_NOUN_CAP)+ .replace("__SEQS__", _p.SEQ_NOUN_PL)+ .replace("__SEQ__", _p.SEQ_NOUN))++NODE = shutil.which("node")++# The model functions are pure — arrays in, arrays out. The four that are not+# (sbeSave, sbeMutate, sbeUndo, sbeRedo) reach for exactly four collaborators,+# and those are stubbed below rather than extracted, so a failure here is a+# failure of the thing under test.+FUNCTIONS = (+ "sbeNum", "sbeRound", "sbeFps", "sbeGridGap", "sbeLen",+ "sbePaintProtected",+ "sbeAdoptGaps", "sbeLayout",+ "sbeFilmDuration", "sbeClipAt", "sbeHoles", "sbeBeatGrid",+ "sbeGridIsAGuess", "sbeSnapTime", "sbeById", "sbeMoveTo", "sbeTrim",+ "sbeRippleDelete", "sbeSplitAt", "sbeNewId", "sbePlaceUnplaced",+ "sbeCleanClip", "sbeSaveBody", "sbeErrorsByClip", "sbeDecodePeaks",+ "sbeFmtTime", "sbeMutate", "sbeUndo", "sbeRedo", "sbeSave",+ # Wave 2 — kinds, the one adjustment, and the drop maths.+ "sbeKind", "sbeBright", "sbeBrightnessCss", "sbeSetBrightness",+ "sbeDropIndex", "sbeInsertAt", "sbeReorderTo",+ # Wave 3 — the two sliders and the two monitors. Pure by design: "zoom+ # keeps the playhead still", "the slider's floor fits the whole film" and+ # "the monitor row fills the width" are all invariants nobody can check by+ # eye and everybody notices when they break.+ "sbeZoomFitPps", "sbeZoomFromSlider", "sbeZoomToSlider", "sbeZoomAnchor",+ "sbeZoomScroll", "sbeFollowScroll", "sbeMonitorFit",+ # The third slider nobody called a slider: the timeline's own top edge.+ # Where a dragged pixel lands is the whole feature and the one thing that+ # cannot be checked by looking at it.+ "sbeTlClamp", "sbeLaneHeights", "sbeTlPrefRead", "sbeTlPrefWrite",+ # The level line's geometry, which three gestures now share instead of+ # each carrying a copy of a 20px band.+ "sbeStripY", "sbeStripGain", "sbeStripEditable", "sbeKeysLegend",+ # ...and the span of it that the two corner handles have NOT taken. Pure+ # arithmetic on a polyline, which is the only part of "no pixel belongs to+ # two controls" that can be checked without a browser.+ "sbeLvlHitPath",+ # The two stage layers, and the painter that grades them. Opacity is the+ # ramp AND the layer switch, which is how a fade came to paint black over+ # a perfectly loaded video.+ "sbeFadePaint", "sbeOvPaint",+ # Wave 4 — the soundtrack as an object, and a timeline that does not end+ # where the clips do. Every one of these is arithmetic somebody would+ # otherwise have to check by dragging a strip and squinting.+ "sbeMusicWindow", "sbeMusicEdit", "sbeMusicSnaps", "sbeSnapToList",+ "sbeSpan", "sbeSnapshot", "sbeRestore",+ # Wave 4 — the versions picker's wording, which is the whole of what it+ # tells you about a file you are about to restore over your work.+ "sbeAgo", "sbeVersionLine",+ # J-cuts and L-cuts: the sound's own window.+ "sbeClipAudio", "sbeAudioField", "sbeSetAudioLink", "sbeAudioEdit",+ # ...and the pair, which is the half that was missing: how far the two have+ # come apart, what carries a strip through somebody else's ripple, and the+ # one click that puts it back.+ "sbeClipMuted", "sbeSetClipMute",+ # The preview's strip player: who owns a clip's sound, and which strips+ # are audible at a given film second.+ "sbeStripOwned", "sbePictureCarriesSound", "sbeStripsAt",+ # The effects model and its first citizen.+ "sbeClipLen", "sbeFx", "sbeFadeOpacityAt", "sbeSetFade",+ # "Did the film actually change?" — the question every track drag has to+ # answer on pointerup, and the one that has now twice silently discarded a+ # real edit because its list of fields was short.+ "sbeDragFingerprint",+ # The overlay lane — a second video track, above the picture.+ # The sound's envelope: fades and keyframes, one curve.+ "sbeAfx", "sbeLerpGain", "sbeGainPoints", "sbeGainAt", "sbeSetAudioFade",+ # Waveforms, keyframes, and the strip you can delete.+ "sbeWaveSlice", "sbeAfxWrite", "sbeAddKeyframe", "sbeMoveKeyframe",+ "sbeDeleteKeyframe", "sbeDeleteStrip",+ # THE MIX. The bed's level, and what happens to it under a line. Every one+ # of these is a mirror of a Python function of the same shape, and the+ # whole feature is that the two agree: the render used to hold the bed at+ # a hard-coded 0.20 and duck it through a compressor while the preview+ # applied neither, so the surface the user checks his work on played a mix+ # the file never had. These are the functions that make the two one.+ "sbeAudioMix", "sbeBedLen", "sbeAudibleStrips", "sbeDuckGainAt",+ "sbeBedDuckPoints", "sbeBedDuckSuppressed", "sbeBedGainPoints",+ "sbeBedGainAt", "sbeMixWrite", "sbeBedAfxWrite", "sbeSetBedFade",+ "sbeBedPointsWrite", "sbeBedAddKeyframe", "sbeBedMoveKeyframe",+ "sbeBedDeleteKeyframe",+ "sbeOvKind", "sbeOvAt", "sbeOvById", "sbeOvFits", "sbeOvMove", "sbeOvTrim",+ "sbeOvAdd", "sbeOvDelete", "sbeOvSetPath",+ "sbeAudioDrift", "sbeAudioInSync", "sbeAudioIsThePicture",+ "sbeDriftLabel", "sbeSyncBadge",+ "sbeSyncMark", "sbeSyncCarry", "sbeResyncAudio",+ # The save that cannot be dropped, and the failure that cannot be missed.+ "sbeSaveInner", "sbeSaveAlarm", "sbeSaveAlarmClear", "sbeQueueSave",+ # The crash lane itself, so save → backup → recovery can be DRIVEN rather+ # than grepped for the presence of its guards.+ "sbeBackup", "sbeDraftOp", "sbeNameMode",+ # THE ONE NOTICE SURFACE. Four blocks that are not mutually exclusive used+ # to stack; this decides which is open and which is a chip.+ "sbePaintNotices", "sbeNoticeOpen", "sbeNoticeClick", "sbeNoticeLater",+ "sbeErrsToggle",+)++SHIM = r"""+'use strict';+// The four collaborators the mutating functions reach for. Stubs, not+// extractions: this gate is about the arrangement, not the paint.+const painted = [];+const states = [];+const toasts = [];+const saves = [];+function sbePaint() { painted.push(1); }+function sbePaintHead() {}+function sbePaintTrack() {}+function sbePaintChrome() {}+function sbeSetState(t, k) { states.push([t, k]); }+// The two the SAVE path repaints: a save answers the recovery offer, and the+// drafts rows carry the clip count it just changed.+const recoveryPaints = [];+const draftPaints = [];+function sbePaintRecovery() { recoveryPaints.push(SBE.backup); }+function sbePaintDraft() { draftPaints.push((SBE.drafts || []).length); }+// The draft switch reaches this now that the snapshot lane no longer refuses+// while an offer is open. Stubbed: this gate is about the arrangement, not+// about re-adopting a server payload.+const adopted = [];+function sbeAdopt(r, quiet) { adopted.push(r); }+async function sbeVersionsLoad() { return null; }+function sbeVersionsPaint() {}+function sbeRenderErrors(e) { lastErrors = e; }+function phosToast(m, o) { toasts.push(String(m)); }+function escapeHtml(s) { return String(s || ''); }+let lastErrors = null;+const SBE_MIN_CLIP = 0.2;+const SBE_UNDO_MAX = 80;+const SBE_SNAP_PX = 9;+const SBE_GUESS_CONFIDENCE = 0.4;+const SBE_BRIGHT_MAX = 0.5;+const SBE_STILL_SECONDS = 3.0;+// Wave 3. Keep these equal to the panel's — a drifted constant here is a gate+// that passes while the browser does something else.+const SBE_TL_PAD = 24;+// The timeline's floor, its ceiling and the lanes between them. Both ends are+// the SUM of the lanes; `test_the_height_floor_is_the_sum_of_its_lanes` reads+// them back out of the panel and refuses a lane that was added without moving+// them, which is precisely how the box came to be 30px short of its contents.+const SBE_TL_CHROME = 32;+const SBE_LANES = [+ { key: 'ov', base: 32, cap: 56, share: 0.08 },+ { key: 'track', base: 64, cap: 120, share: 0.14 },+ { key: 'alane', base: 44, cap: 190, share: 0.44 },+ { key: 'wave', base: 108, cap: 240, share: 0.34 },+];+const SBE_TL_MIN_H = 280;+const SBE_TL_MAX_H = 638;+const SBE_TL_STEP = 12;+const SBE_TL_STEP_BIG = 40;+const SBE_LVL_PAD = 8;+const SBE_LVL_GRAB = 12;+// The corner handles' footprint, mirrored from the panel exactly as the lane+// table above is. The BROWSER is what catches a drift between these and the+// stylesheet — `scripts/measure_editor_layout.py` measures the three+// rectangles in a laid-out page — but the clipping arithmetic is pure and is+// checked here.+const SBE_AGRIP_W = 7;+const SBE_GRIP_SKIRT = 3;+const SBE_FADE_HIT = 22;+const SBE_LVL_CLEAR = SBE_AGRIP_W + SBE_GRIP_SKIRT + SBE_FADE_HIT + 1;+const SBE_LVL_MIN_SPAN = 12;+const SBE_PPS_MAX = 200;+const SBE_PPS_FLOOR = 0.5;+const SBE_ZOOM_TICKS = 1000;+const SBE_MON_GAP = 12;+const SBE_MON_MIN_H = 120;+const SBE_MON_RATIO = 2 / 3;+const SBE_MON_RATIO_MAX = 1;+const SBE_RAIL_MIN = 200;+const SBE_RAIL_MAX = 380;+// Wave 4 — the slack past the last frame, and the soundtrack's floor.+const SBE_SLACK_MIN = 3;+const SBE_SLACK_MAX = 15;+const SBE_SLACK_RATIO = 0.15;+const SBE_SPAN_MIN = 10;+const SBE_MIN_MUSIC = 0.5;+// The watchdog's grace, and the same threshold the protected chip goes cold+// on. Keep equal to the panel's — a test below reads both.+const SBE_SAVE_GRACE_MS = 12000;+// Half a frame at 24 fps — the same number TOUCH_TOLERANCE uses on the server.+const SBE_SYNC_TOL = 1 / 48;+// Urgency order for the notice surface. Keep equal to the panel's.+const SBE_NOTICE_ORDER = ['sbeConflict', 'sbeAlarm', 'sbeErrors', 'sbeRecover',+ 'sbeKeyed'];+function stubEl(id, hidden) {+ const cls = new Set();+ const attrs = {};+ return {+ id: id, hidden: !!hidden, textContent: '', innerHTML: '', dataset: {},+ // `style` is a plain bag, which is enough to answer the only question+ // this gate asks: WHAT DID THE PAINTER WRITE INLINE. An inline value beats+ // the stylesheet, so an inline value on a layer the stylesheet is trying+ // to hide is the whole of the bug.+ style: {},+ setAttribute: (k, v) => { attrs[k] = String(v); },+ getAttribute: (k) => (k in attrs ? attrs[k] : null),+ classList: {+ add: (c) => cls.add(c), remove: (c) => cls.delete(c),+ contains: (c) => cls.has(c),+ toggle: (c, on) => { if (on) cls.add(c); else cls.delete(c); return cls.has(c); },+ },+ _cls: cls,+ };+}+const els = {+ sbeConflict: stubEl('sbeConflict', true),+ sbeConflictText: stubEl('sbeConflictText'),+ sbeErrors: stubEl('sbeErrors', true),+ sbeAlarm: stubEl('sbeAlarm', true),+ sbeAlarmWhy: stubEl('sbeAlarmWhy'),+ sbeProtected: stubEl('sbeProtected', true),+ sbeRecover: stubEl('sbeRecover', true),+ sbeKeyed: stubEl('sbeKeyed', true),+ sbeKeyedWhat: stubEl('sbeKeyedWhat'),+ sbeRecoverWhat: stubEl('sbeRecoverWhat'),+ sbeNotices: stubEl('sbeNotices', true),+};+function sbeEl(id) { return els[id] || (els[id] = stubEl(id, false)); }+// Which notices are currently chips, in the surface's own order.+const foldedNotices = () => ['sbeConflict', 'sbeAlarm', 'sbeErrors', 'sbeRecover',+ 'sbeKeyed']+ .filter(id => (sbeEl(id)._cls || new Set()).has('is-folded'));+// The view preferences' actual home. A Map with the two methods the panel+// uses, so "it survives a reload" is a thing this gate can DRIVE rather than+// a thing it hopes about: read → drag → write → read again.+const STORE = new Map();+global.localStorage = {+ getItem: (k) => (STORE.has(k) ? STORE.get(k) : null),+ setItem: (k, v) => { STORE.set(k, String(v)); },+ removeItem: (k) => { STORE.delete(k); },+};+const saveTimers = [];+global.setTimeout = ((real) => function (fn, ms) {+ saveTimers.push(ms);+ return real(fn, ms);+})(global.setTimeout);+const SBE = {+ open: true, id: 'sb_t', edit: {}, clips: [], audio: null, beats: null,+ savePending: false, dirtyAt: 0, saveFailed: '',+ peaks: null, unplaced: [], prepare: {}, proxyUrl: '', revision: 0,+ dirty: false, saving: false, conflict: 0, sel: '', playhead: 0,+ playing: false, curId: '', pps: 40, undo: [], redo: [], errors: {},+ sentOrder: [], timer: null, saveTimer: null, raf: 0, drag: null,+ backup: null, drafts: [], activeDraft: 'draft-1', backingUp: false,+ backedUpAt: 0, noticeLead: '', backupHidden: false, errsOpen: false,+ // The timeline's height: the preference, what the window could give it, and+ // the ceiling the monitors impose.+ tlH: SBE_TL_MIN_H, tlNow: SBE_TL_MIN_H, tlMax: SBE_TL_MAX_H, tlDrag: null,+};+// One fetch stub, scripted per case.+let FETCHES = [];+let NEXT = null;+global.fetch = async (url, opts) => {+ FETCHES.push({ url, body: opts && opts.body });+ const r = NEXT;+ return { ok: r.status < 400, status: r.status, json: async () => r.body };+};+global.setTimeout = global.setTimeout;+function clip(o) {+ return Object.assign({+ id: o.id, path: o.path || ('/o/' + o.id + '.mp4'), proxy: null,+ start: 0, end: 2, film_start: 0, film_end: 2, source: 'auto',+ locked: false, duration: 10,+ }, o);+}+function lay(cs) { sbeAdoptGaps(cs); sbeLayout(cs); return cs; }+function shape(cs) {+ return cs.map(c => [c.id, +c.start.toFixed(3), +c.end.toFixed(3),+ +c.film_start.toFixed(3), +c.film_end.toFixed(3)]);+}+// The invariant the server refuses an edit for breaking: the source window and+// the film slot are the same length, because nothing plays at anything but 1x.+function lengthsAgree(cs) {+ return cs.every(c => Math.abs((c.end - c.start) - (c.film_end - c.film_start)) <= 0.002);+}+function overlaps(cs) {+ const s = cs.slice().sort((a, b) => a.film_start - b.film_start);+ for (let i = 1; i < s.length; i++) {+ if (s[i].film_start < s[i - 1].film_end - 1 / 48) return true;+ }+ return false;+}+"""++BODY = r"""+const out = {};++// ---- peaks ---------------------------------------------------------------+out.peaks = sbeDecodePeaks({+ version: 1, count: 3, scale: 127, buckets_per_second: 100, duration: 0.03,+ peaks: [-127, 127, 0, 64, -32, 32],+});+out.peaksJunk = sbeDecodePeaks({ scale: 0, count: 99, peaks: [-10, 10] });+out.peaksNone = sbeDecodePeaks(null);++// ---- beat grid -----------------------------------------------------------+const beats = {+ bpm: 120, period: 0.5, phase: 0, meter: 4, confidence: 0.71,+ span: [0, 4], beats: [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4],+ downbeats: [0, 2, 4],+};+out.grid = sbeBeatGrid(beats, 0, 10, 0).map(b => [b.t, b.down]);+// The fit stops at 4 s. A film that runs to 30 s gets NO line past the span —+// beat_map refuses to extrapolate and so does the client.+out.gridPastSpan = sbeBeatGrid(beats, 4.01, 30, 0).length;+out.gridWindow = sbeBeatGrid(beats, 1, 2, 0).map(b => b.t);+out.gridOffset = sbeBeatGrid(beats, -2, 10, 1).map(b => b.t);+out.guess = sbeGridIsAGuess(beats);+out.guessLow = sbeGridIsAGuess(Object.assign({}, beats, { confidence: 0.31 }));++// ---- snap ----------------------------------------------------------------+out.snapCatches = sbeSnapTime(1.44, beats, 0.1, true, 0);+out.snapLeaves = sbeSnapTime(1.2, beats, 0.1, true, 0);+out.snapOff = sbeSnapTime(1.44, beats, 0.1, false, 0);+out.snapPrefersDownbeat = sbeSnapTime(2.0001, beats, 0.6, true, 0);+out.snapPastSpan = sbeSnapTime(9.9, beats, 0.6, true, 0);++// ---- layout --------------------------------------------------------------+let cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 }),+ clip({ id: 'c', end: 1.5 })].map((c, i) => c));+// adoptGaps read film_start from the incoming doc; these three arrived stacked+// at 0, so the layout packs them in array order.+out.packed = shape(cs);+out.packedLengths = lengthsAgree(cs);++// A hole survives a round trip through adopt + layout — gaps are legal, and an+// editor that quietly closed them would make "generate into a gap" impossible.+let holed = [clip({ id: 'a', end: 2, film_start: 0, film_end: 2 }),+ clip({ id: 'b', end: 3, film_start: 5, film_end: 8 })];+lay(holed);+out.holeKept = shape(holed);+out.holes = sbeHoles(holed).map(g => [g.film_start, g.film_end, g.duration]);+out.duration = sbeFilmDuration(holed);+out.clipAt = (sbeClipAt(holed, 6) || {}).id;+out.clipInHole = sbeClipAt(holed, 3);++// ---- move ----------------------------------------------------------------+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 }), clip({ id: 'c', end: 1.5 })]);+let r = sbeMoveTo(cs, 'c', 0);+out.moveToHead = shape(r.clips);+out.moveMarksHuman = sbeById(r.clips, 'c').source;+out.moveLengths = lengthsAgree(r.clips);+out.moveNoOverlap = !overlaps(r.clips);++cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);+r = sbeMoveTo(cs, 'b', 6); // dropped into open air: the hole is kept+out.moveOpensHole = shape(r.clips);++cs = lay([clip({ id: 'a', end: 2, locked: true }), clip({ id: 'b', end: 3 })]);+r = sbeMoveTo(cs, 'a', 9);+out.moveLocked = { ok: r.ok, why: r.why, shape: shape(r.clips) };++// A locked clip is an ANCHOR: the flow goes around it, never through it.+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'L', end: 2, film_start: 3, film_end: 5, locked: true }),+ clip({ id: 'b', end: 4 })]);+out.anchored = shape(cs);+out.anchoredNoOverlap = !overlaps(cs);++// ---- trim ----------------------------------------------------------------+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);+sbeTrim(cs, 'a', 'r', 1.25); // right handle: length changes, tail ripples+out.trimRight = shape(cs);+out.trimRightLengths = lengthsAgree(cs);++cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);+sbeTrim(cs, 'b', 'l', 2.5); // left handle: in-point moves, tail stays put+out.trimLeft = shape(cs);+out.trimLeftLengths = lengthsAgree(cs);++cs = lay([clip({ id: 'a', end: 2, duration: 2.4 })]);+sbeTrim(cs, 'a', 'r', 99); // cannot pull past the end of the source+out.trimClampedToSource = shape(cs);+cs = lay([clip({ id: 'a', end: 2 })]);+sbeTrim(cs, 'a', 'l', 99); // nor collapse the clip to nothing+out.trimClampedToMin = shape(cs);+cs = lay([clip({ id: 'a', end: 2, locked: true })]);+out.trimLocked = sbeTrim(cs, 'a', 'r', 1).why;++// ---- ripple + split ------------------------------------------------------+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 }), clip({ id: 'c', end: 1.5 })]);+r = sbeRippleDelete(cs, 'b');+out.ripple = shape(r.clips);+out.rippleLengths = lengthsAgree(r.clips);+cs = lay([clip({ id: 'a', end: 2, locked: true })]);+out.rippleLocked = sbeRippleDelete(cs, 'a').why;++cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);+r = sbeSplitAt(cs, 1.2, 'a2');+out.split = shape(r.clips);+out.splitLengths = lengthsAgree(r.clips);+out.splitHuman = r.clips.map(c => c.source);+out.splitTooClose = sbeSplitAt(lay([clip({ id: 'a', end: 2 })]), 0.05).ok;+out.splitInHole = sbeSplitAt(holed, 3.5).ok;++// ---- place an unplaced clip ---------------------------------------------+cs = lay([clip({ id: 'a', end: 2, film_start: 0, film_end: 2 }),+ clip({ id: 'b', end: 2, film_start: 6, film_end: 8 })]);+r = sbePlaceUnplaced(cs, { path: '/o/new.mp4', duration_s: 3, n: 9, title: 'new',+ slot: { film_start: 2.5, duration: 3 } }, 2.5);+out.placed = r.clips.map(c => [c.path, c.film_start, c.film_end, c.source]);+out.placedNoOverlap = !overlaps(r.clips);+// A shot generated for a hole must not push the film that follows it: the+// cuts after the hole are on beats they were chosen for.+cs = lay([clip({ id: 'a', end: 2, film_start: 0, film_end: 2 }),+ clip({ id: 'b', end: 2, film_start: 9, film_end: 11 })]);+r = sbePlaceUnplaced(cs, { path: '/o/fill.mp4', duration_s: 3,+ slot: { film_start: 3, duration: 3 } }, 3);+out.filled = r.clips.map(c => [c.path.split('/').pop(), c.film_start, c.film_end]);+// ...but when the new clip is too long for the hole, the tail rides along+// rather than overlapping.+cs = lay([clip({ id: 'a', end: 2, film_start: 0, film_end: 2 }),+ clip({ id: 'b', end: 2, film_start: 5, film_end: 7 })]);+r = sbePlaceUnplaced(cs, { path: '/o/big.mp4', duration_s: 4,+ slot: { film_start: 2, duration: 4 } }, 2);+out.overfilled = r.clips.map(c => [c.path.split('/').pop(), c.film_start, c.film_end]);+out.overfilledNoOverlap = !overlaps(r.clips);++// ---- undo / redo ---------------------------------------------------------+SBE.clips = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);+SBE.undo = []; SBE.redo = []; SBE.dirty = false;+sbeMutate(x => sbeRippleDelete(x, 'a'));+out.afterMutate = shape(SBE.clips);+out.dirtyAfterMutate = SBE.dirty;+sbeUndo();+out.afterUndo = shape(SBE.clips);+sbeRedo();+out.afterRedo = shape(SBE.clips);+sbeUndo(); sbeUndo(); // one step of history, two presses+out.undoFloor = shape(SBE.clips);+// A refused mutation writes NO undo step — otherwise ⌘Z would undo nothing.+SBE.clips = lay([clip({ id: 'a', end: 2, locked: true })]);+SBE.undo = []; SBE.redo = [];+sbeMutate(x => sbeRippleDelete(x, 'a'));+out.refusedNoUndo = SBE.undo.length;++// ---- save payload --------------------------------------------------------+const body = sbeSaveBody({+ id: 'sb_t', expect: 4,+ edit: { version: 1, revision: 4, audio: { path: '/m.wav' }, beats: beats,+ settings: { min_shot: 1.5 } },+ clips: lay([clip({ id: 'a', end: 2, source: 'human' })]),+});+out.saveBody = body;+out.saveStrippedPrivate = Object.keys(body.edit.clips[0]).filter(k => k.charAt(0) === '_');+out.saveNoExpect = sbeSaveBody({ id: 'x', edit: {}, clips: [], expect: null });++// ---- errors map onto clips ----------------------------------------------+out.errMap = sbeErrorsByClip(+ [{ code: 'clip_window', where: 1, message: 'clip 2: end must be after start' },+ { code: 'version', where: null, message: 'edit version 9' }],+ ['a', 'b']);++// ---- 409, and the arrangement that survives it --------------------------+SBE.clips = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);+SBE.dirty = true; SBE.revision = 3; SBE.saving = false; SBE.open = true;+NEXT = { status: 409, body: { ok: false, conflict: true, revision: 7,+ error: 'this timeline moved on without you' } };+out.saveConflict = await sbeSave(true);+out.afterConflict = {+ clips: shape(SBE.clips), dirty: SBE.dirty, conflict: SBE.conflict,+ revision: SBE.revision, banner: !els.sbeConflict.hidden,+};+// "Keep mine" re-sends WITHOUT expect_revision — the only way to overwrite, and+// only because a human asked for it in as many words.+FETCHES = [];+NEXT = { status: 200, body: { ok: true, edit: { revision: 8, clips: [] }, unplaced: [] } };+out.forced = await sbeSave(true, true);+out.forcedBody = JSON.parse(FETCHES[0].body);+out.afterForced = { revision: SBE.revision, dirty: SBE.dirty };++// A 400 keeps the work AND says which clip is wrong.+SBE.clips = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 })]);+SBE.dirty = true; SBE.conflict = 0;+NEXT = { status: 400, body: { ok: false, error: 'clip 2: no path',+ errors: [{ code: 'clip_path', where: 1, message: 'clip 2: no path' }] } };+out.saveInvalid = await sbeSave(true);+out.afterInvalid = {+ clips: shape(SBE.clips), dirty: SBE.dirty,+ flagged: Object.keys(SBE.errors.byId || {}),+};++// A good save keeps the clips ON SCREEN — the server's normalised copy of the+// document is adopted, its clip array is not, because the user may have moved+// something while the request was in flight.+SBE.clips = lay([clip({ id: 'a', end: 2 })]);+SBE.dirty = true; SBE.revision = 8;+NEXT = { status: 200, body: { ok: true, edit: { revision: 9, clips: [{ id: 'z' }] },+ unplaced: [{ path: '/o/z.mp4' }] } };+out.saveOk = await sbeSave(true);+out.afterOk = { clips: shape(SBE.clips), dirty: SBE.dirty, revision: SBE.revision,+ unplaced: SBE.unplaced.length };++out.fmt = [sbeFmtTime(0), sbeFmtTime(9.5), sbeFmtTime(75.25)];++// =========================================================================+// WAVE 2 — the three kinds, one adjustment, and the drop maths+// =========================================================================++// ---- kind: absent is video, and that IS the v1 migration -----------------+out.kinds = [sbeKind({}), sbeKind({ kind: 'still' }), sbeKind({ kind: 'slug' }),+ sbeKind({ kind: 'nonsense' }), sbeKind(null)];++// ---- brightness: clamped, and neutral means ABSENT -----------------------+out.bright = [sbeBright({}), sbeBright({ adjust: {} }),+ sbeBright({ adjust: { brightness: 0.2 } }),+ sbeBright({ adjust: { brightness: 9 } }),+ sbeBright({ adjust: { brightness: -9 } }),+ sbeBright({ adjust: { brightness: 'x' } })];+// CSS brightness() is multiplicative, ffmpeg's eq is additive; matched at+// mid-grey, which is where a person judges exposure.+out.brightCss = [sbeBrightnessCss(0), sbeBrightnessCss(0.25),+ sbeBrightnessCss(0.5), sbeBrightnessCss(-0.5),+ sbeBrightnessCss(-9)];+out.brightCssMidGrey = [0.5 + 0.25, 0.5 * sbeBrightnessCss(0.25)];++cs = lay([clip({ id: 'a', end: 2 })]);+out.setBrightOk = sbeSetBrightness(cs, 'a', 0.3).ok;+out.setBrightValue = sbeBright(sbeById(cs, 'a'));+out.setBrightHuman = sbeById(cs, 'a').source;+out.setBrightClamped = (sbeSetBrightness(cs, 'a', 4), sbeBright(sbeById(cs, 'a')));+// Back to zero leaves NO adjust key at all — an untouched clip and a clip+// dragged back to neutral must serialise identically.+sbeSetBrightness(cs, 'a', 0);+out.setBrightCleared = ('adjust' in sbeById(cs, 'a'));+out.setBrightNoop = sbeSetBrightness(cs, 'a', 0).ok;+out.setBrightGone = sbeSetBrightness(cs, 'zz', 0.2).why;++// ---- the save payload carries the kinds, synthesised the server's way ----+const kindBody = sbeSaveBody({+ id: 'sb_t', expect: null, edit: { version: 2 },+ clips: lay([+ clip({ id: 'v', end: 2, adjust: { brightness: 0.25 } }),+ clip({ id: 's', kind: 'still', path: '/img/card.png', end: 3, duration: 99 }),+ clip({ id: 'k', kind: 'slug', path: null, end: 1.5, adjust: { brightness: 0 } }),+ ]),+});+out.kindPayload = kindBody.edit.clips.map(c => ({+ id: c.id, kind: c.kind, path: c.path, start: c.start, end: c.end,+ dur: c.duration, adjust: c.adjust,+}));++// ---- where a drop lands: the midpoint rule ------------------------------+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 2 }),+ clip({ id: 'c', end: 2 })]);+out.dropIdx = [sbeDropIndex(cs, 0), sbeDropIndex(cs, 0.9), sbeDropIndex(cs, 1.1),+ sbeDropIndex(cs, 2.9), sbeDropIndex(cs, 3.1), sbeDropIndex(cs, 99)];+out.dropIdxEmpty = sbeDropIndex([], 5);++// ---- insert RIPPLES (unlike filling a hole, which must not) -------------+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 2 })]);+r = sbeInsertAt(cs, { path: '/o/n.mp4', duration_s: 1, title: 'n' }, 2.1);+out.insertRipple = r.clips.map(c => [c.id === r.added.id ? 'NEW' : c.id,+ c.film_start, c.film_end]);+out.insertLengths = lengthsAgree(r.clips);+out.insertNoOverlap = !overlaps(r.clips);+out.insertHuman = r.added.source;++// A slug has no path and no source duration, and gets both right.+cs = lay([clip({ id: 'a', end: 2 })]);+r = sbeInsertAt(cs, { kind: 'slug', title: 'black', duration_s: 2.5 }, 99);+out.insertSlug = { kind: r.added.kind, path: r.added.path, dur: r.added.duration,+ len: sbeRound(sbeLen(r.added)),+ at: [r.added.film_start, r.added.film_end] };+out.insertSlugNoOverlap = !overlaps(r.clips);+r = sbeInsertAt(lay([clip({ id: 'a', end: 2 })]),+ { kind: 'still', path: '/img/c.png', duration_s: 3 }, 0);+out.insertStill = { kind: r.added.kind, path: r.added.path, dur: r.added.duration,+ index: r.index, at: [r.added.film_start, r.added.film_end] };++// A still is resized by the SAME trim machinery every other block uses, and+// nothing clamps it, because it has no source clock to run out of.+cs = lay([r.added, clip({ id: 'a', end: 2 })]);+sbeTrim(cs, r.added.id, 'r', 9);+out.stillStretched = sbeRound(sbeLen(sbeById(cs, r.added.id)));++// ---- reorder: closes the hole it leaves, opens none where it lands -------+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 3 }),+ clip({ id: 'c', end: 1 })]);+r = sbeReorderTo(cs, 'c', 0);+out.reorder = shape(r.clips);+out.reorderIds = r.clips.map(c => c.id);+out.reorderLengths = lengthsAgree(r.clips);+out.reorderNoOverlap = !overlaps(r.clips);+out.reorderKeepsLength = sbeFilmDuration(r.clips);+out.reorderHuman = sbeById(r.clips, 'c').source;+out.reorderLocked = sbeReorderTo(lay([clip({ id: 'a', end: 2, locked: true })]),+ 'a', 9).why;+out.reorderGone = sbeReorderTo(cs, 'nope', 0).why;+// Contrast with a MOVE, which leaves the hole behind — both verbs exist and+// this is the difference between them.+cs = lay([clip({ id: 'a', end: 2 }), clip({ id: 'b', end: 2 }),+ clip({ id: 'c', end: 2 })]);+out.moveLeavesAHole = sbeMoveTo(cs, 'a', 9).clips.map(c => [c.id, c.film_start]);++// ---- WAVE 3: the two sliders ---------------------------------------------+// The owner's film, measured: 71.583338s in a 1108px-wide scroller.+const FILM = 71.583338;+const VIEW = 1108;+out.fit = sbeZoomFitPps(FILM, VIEW);+// At the fit scale the whole film is inside the box — that is what makes the+// slider's left end mean "all of it". sbePaint pads the inner by SBE_TL_PAD.+out.fitWidth = Math.max(320, Math.ceil(FILM * out.fit) + SBE_TL_PAD);+out.fitFitsTheBox = out.fitWidth <= VIEW + 1;+// sbeSpan() never returns less than 1, so this is the shortest film the fit+// is ever asked about — and it is still a number, not an infinity.+out.fitEmptyFilm = sbeZoomFitPps(1, VIEW);+// A box with no width yet (the tab has never been painted) must not produce+// a zero or a NaN that would then be stored as SBE.pps.+out.fitNarrow = sbeZoomFitPps(FILM, 0);++// The slider is logarithmic and round-trips.+out.sliderEnds = [sbeZoomFromSlider(0, 15.14, 200), sbeZoomFromSlider(1000, 15.14, 200)];+out.sliderRound = [0, 250, 500, 750, 1000].map(v =>+ sbeZoomToSlider(sbeZoomFromSlider(v, 15.14, 200), 15.14, 200));+out.sliderClamps = [sbeZoomToSlider(1, 15.14, 200), sbeZoomToSlider(9999, 15.14, 200)];+// Linear would put the whole useful range in the first fifth of the travel.+out.sliderMidIsNotArithmeticMean = sbeZoomFromSlider(500, 15.14, 200);++// ZOOM KEEPS THE PLAYHEAD STILL. The head is at 36s, the view is scrolled so+// it sits 400px in; after a zoom it must still sit 400px in.+let anchor = sbeZoomAnchor(36, 36 * 42 - 400, VIEW, 42);+out.anchorOnPlayhead = [Math.round(anchor.t * 1000) / 1000, Math.round(anchor.px)];+out.zoomHoldsThePlayhead = Math.round(36 * 96 - sbeZoomScroll(anchor, 96, 1e9));+// Off screen, it holds the middle of the view instead — there is no frame on+// screen to anchor on, and lurching to one that is not visible is worse.+anchor = sbeZoomAnchor(2, 30000, VIEW, 42);+out.anchorFallsBackToTheMiddle = [Math.round(anchor.t * 100) / 100, Math.round(anchor.px)];+// alt + wheel names its own anchor: the film time under the pointer.+anchor = sbeZoomAnchor(36, 1000, VIEW, 42, 30);+out.anchorExplicit = [anchor.t, Math.round(anchor.px)];+// The scroll is clamped to what there is: no negative scroll at the head of+// the film, no scrolling past the end.+out.zoomScrollClamps = [sbeZoomScroll({ t: 0, px: 400 }, 42, 5000),+ sbeZoomScroll({ t: 1000, px: 0 }, 42, 5000)];++// ---- WAVE 3: follow, which PAGES rather than chases ----------------------+// On screen: the view does not move at all. This is the early return that+// keeps the follow from writing scrollLeft sixty times a second.+out.followStaysPut = sbeFollowScroll(500, 0, VIEW, 4000);+// Crossed the right edge: ONE jump, and the head lands near the left of the+// new screenful rather than in the middle of it.+out.followPages = sbeFollowScroll(1680, 0, VIEW, 4000);+out.followLead = 1680 - out.followPages;+// The frame after that, the head is on screen again and nothing moves.+out.followSettles = sbeFollowScroll(1700, out.followPages, VIEW, 4000);+out.followSettled = out.followSettles === out.followPages;+// Seeking backwards out of view pages the other way, and both ends clamp.+out.followBack = sbeFollowScroll(100, 3000, VIEW, 4000);+out.followClampsHead = sbeFollowScroll(-50, 3000, VIEW, 4000);+out.followClampsTail = sbeFollowScroll(99999, 0, VIEW, 4000);++// ---- WAVE 3: the monitor row ---------------------------------------------+// Both measured live, in the Editor's own tab, with the carwash film open.+const A = 16 / 9;+const near = (a, b) => Math.abs(a - b) <= 1.5;+// 1440x900: the column is 1110px wide and 307px of height are free.+let fit = sbeMonitorFit(1110, 307);+out.fit1440 = {+ fills: near(fit.total, 1110),+ prog: [Math.round(fit.progW), Math.round(fit.progH)],+ src: [Math.round(fit.srcW), Math.round(fit.srcH)],+ rail: Math.round(fit.rail),+ progAspect: Math.round(fit.progW / fit.progH * 1000) / 1000,+ srcAspect: Math.round(fit.srcW / fit.srcH * 1000) / 1000,+ split: Math.round(fit.srcW / (fit.srcW + fit.progW) * 100),+ programIsBigger: fit.progW > fit.srcW,+ withinBudget: fit.progH <= 307 + 0.5,+};+// 1900x1000: 1570px wide, 446px free. Same shape, bigger.+fit = sbeMonitorFit(1570, 446);+out.fit1900 = {+ fills: near(fit.total, 1570),+ prog: [Math.round(fit.progW), Math.round(fit.progH)],+ src: [Math.round(fit.srcW), Math.round(fit.srcH)],+ rail: Math.round(fit.rail),+ split: Math.round(fit.srcW / (fit.srcW + fit.progW) * 100),+ programIsBigger: fit.progW > fit.srcW,+ withinBudget: fit.progH <= 446 + 0.5,+};+// A TALL, NARROW WINDOW. The width runs out first, so the pair takes the+// width-derived height at exactly 40/60 and the leftover HEIGHT is left for+// the timeline to absorb — the row never eats more than it can fill.+fit = sbeMonitorFit(1110, 900);+out.fitTall = {+ fills: near(fit.total, 1110), ratio: Math.round(fit.ratio * 1000) / 1000,+ progH: Math.round(fit.progH), leftoverHeight: Math.round(900 - fit.progH),+ rail: Math.round(fit.rail),+};+// A VERY SHORT WINDOW. The source widens to keep the row full, and stops at+// equal monitors: the program is the one being cut and never becomes the+// smaller of the two.+fit = sbeMonitorFit(1900, 180);+out.fitShort = {+ ratio: Math.round(fit.ratio * 1000) / 1000,+ programIsBigger: fit.progW >= fit.srcW,+ rail: Math.round(fit.rail),+};+// The floor: a budget of nothing still leaves a picture worth the name.+fit = sbeMonitorFit(1110, 0);+out.fitFloor = Math.round(fit.progH);+// The rail is leftover, never a panel of its own: clamped at both ends.+out.railClamps = [Math.round(sbeMonitorFit(3000, 200).rail),+ Math.round(sbeMonitorFit(700, 200).rail)];++// ---- Wave 4: the soundtrack is an object ---------------------------------+const MUS = (o) => Object.assign({ path: '/o/track.wav', duration: 60 }, o);+let mw = sbeMusicWindow(MUS({ offset: 0 }), 60);+out.musicPlain = [mw.head, mw.tail, mw.film_start, mw.film_end, mw.trimmed];+// A POSITIVE OFFSET IS A HEAD TRIM: track second 5 plays at film 0, so the+// block still starts at film 0 and ends five seconds earlier than the track.+mw = sbeMusicWindow(MUS({ offset: 5 }), 60);+out.musicOffsetIn = [mw.head, mw.film_start, mw.film_end];+// A NEGATIVE OFFSET IS THE DIRECTION THE OLD CLAMP MADE UNREACHABLE: the+// music starts four seconds INTO the film, from its own first second.+mw = sbeMusicWindow(MUS({ offset: -4 }), 60);+out.musicOffsetOut = [mw.head, mw.film_start, mw.film_end];+// Trims are track seconds, and a head trim does NOT slide the rest earlier.+mw = sbeMusicWindow(MUS({ offset: 0, trim_start: 10, trim_end: 20 }), 60);+out.musicTrimmed = [mw.head, mw.tail, mw.film_start, mw.film_end, mw.trimmed];+// Absent trims, an absent duration, an absent audio: no block, no crash.+out.musicNone = (() => { const w = sbeMusicWindow(null, 0); return [w.duration, w.tail]; })();++// DRAG. Moving writes the offset and NOTHING else — the window into the track+// is what a move must not touch.+let ed = sbeMusicEdit(MUS({ offset: 0, trim_start: 10, trim_end: 20 }), 'move', 7, 60);+out.musicMove = [ed.offset, ed.trim_start, ed.trim_end];+out.musicMoveLands = sbeMusicWindow(MUS(ed), 60).film_start;+// Dragging it back to the head of the film.+ed = sbeMusicEdit(MUS({ offset: -8 }), 'move', 0, 60);+out.musicMoveHome = ed.offset;+// TRIM LEFT: a new in-point, and the rest of the track stays where it was.+ed = sbeMusicEdit(MUS({ offset: 0 }), 'trimL', 12, 60);+out.musicTrimL = [ed.offset, ed.trim_start, ed.trim_end];+out.musicTrimLKeepsPlace = sbeMusicWindow(MUS(ed), 60).film_start;+// ...and it can never cross its own out-point, or go before the track starts.+ed = sbeMusicEdit(MUS({ offset: 0, trim_end: 6 }), 'trimL', 99, 60);+out.musicTrimLClamped = ed.trim_start;+ed = sbeMusicEdit(MUS({ offset: 0, trim_start: 20 }), 'trimL', 0, 60);+out.musicTrimLFloor = ed.trim_start;+// TRIM RIGHT: bounded by the track's own length and by the in-point.+ed = sbeMusicEdit(MUS({ offset: 0 }), 'trimR', 42, 60);+out.musicTrimR = ed.trim_end;+ed = sbeMusicEdit(MUS({ offset: 0 }), 'trimR', 999, 60);+out.musicTrimRClamped = ed.trim_end;+ed = sbeMusicEdit(MUS({ offset: 0, trim_start: 30 }), 'trimR', 0, 60);+out.musicTrimRFloor = ed.trim_end;++// THE EDGES SNAP TO CUTS, NOT TO BEATS — the grid is derived from this track+// at this offset, so snapping the music to it would be circular.+out.musicSnaps = sbeMusicSnaps(lay([clip({ id: 'a' }), clip({ id: 'b' })]));+out.musicSnapCatches = sbeSnapToList(2.04, [0, 2, 4], 0.2, true);+out.musicSnapIgnoresFar = sbeSnapToList(3.0, [0, 2, 4], 0.2, true);+out.musicSnapOverride = sbeSnapToList(2.04, [0, 2, 4], 0.2, false);++// ---- Wave 4: the timeline does not end where the clips end ---------------+SBE.clips = lay([clip({ id: 'a' }), clip({ id: 'b' })]); // 4 s of film+SBE.audio = null; SBE.peaks = null;+out.spanShortFilm = sbeSpan();+// An EMPTY timeline still has a ruler worth reading.+SBE.clips = [];+out.spanEmpty = sbeSpan();+// The music past the last clip drags the scroller out with it.+SBE.clips = lay([clip({ id: 'a' }), clip({ id: 'b' })]);+SBE.audio = { path: '/o/track.wav', duration: 30, offset: -20 };+out.spanFollowsMusic = sbeSpan();+// ...and the slack is capped, so a long film does not open on a minute of+// nothing.+SBE.audio = null;+SBE.clips = lay([clip({ id: 'a', start: 0, end: 300, duration: 400 })]);+out.spanLongFilm = sbeSpan();+SBE.clips = []; SBE.audio = null;++// ---- Wave 4: one undo step, whatever moved -------------------------------+SBE.clips = lay([clip({ id: 'a' })]);+SBE.edit = { audio: { path: '/o/track.wav', offset: 0, duration: 60 } };+SBE.audio = SBE.edit.audio;+const snap = sbeSnapshot();+SBE.edit.audio = { path: '/o/track.wav', offset: -6, duration: 60 };+SBE.audio = SBE.edit.audio;+sbeRestore(snap);+out.undoRestoresMusic = SBE.audio.offset;+// The legacy shape — a bare array of clips — is still accepted, because a+// clip drag takes its own snapshot and has no audio to carry.+sbeRestore(JSON.stringify([clip({ id: 'z' })]));+out.undoLegacyShape = [SBE.clips.length, SBE.clips[0].id, SBE.audio.offset];+SBE.clips = []; SBE.edit = {}; SBE.audio = null;++// ---- Wave 4: the versions picker's wording -------------------------------+const NOW = 1000000;+out.ago = [sbeAgo(NOW - 5, NOW), sbeAgo(NOW - 300, NOW),+ sbeAgo(NOW - 7200, NOW), sbeAgo(NOW - 400000, NOW),+ sbeAgo(0, NOW)];+out.lineAuto = sbeVersionLine(+ { file: 'edit-r00007.json', label: '', revision: 7, clips: 9,+ duration: 39.71, archived_at: NOW - 300, kept: false, readable: true }, NOW);+out.lineKept = sbeVersionLine(+ { file: 'keep-r00007-good.json', label: 'the good one', revision: 7,+ clips: 1, duration: 2, archived_at: NOW - 60, kept: true,+ readable: true }, NOW);+// AN UNREADABLE FILE IS STILL A ROW. It vanishing would be indistinguishable+// from never having been written.+out.lineBad = sbeVersionLine(+ { file: 'edit-r00001.json', revision: null, clips: null, duration: null,+ archived_at: NOW - 10, kept: false, readable: false }, NOW);+// THE FALLBACK FOLLOWS THE LANE. An unnamed row in the lane headed YOUR SAVES+// OF THIS DRAFT is a save the user pressed, and calling it "autosave" is the+// one word that means it was not.+out.lineMine = sbeVersionLine(+ { file: 'save-r00091.json', label: '', revision: 91, clips: 9,+ duration: 46.7, archived_at: NOW - 20, kept: false, manual: true,+ readable: true }, NOW);++// ---- THE SAVE THAT CANNOT BE DROPPED, AND THE FAILURE THAT SCREAMS -------+// The owner cut for twenty minutes against a timeline nothing was writing.+// Everything below is that incident, turned into arithmetic.+SBE.clips = lay([clip({ id: 'a' })]);+SBE.edit = { clips: SBE.clips }; SBE.audio = null;+SBE.dirty = false; SBE.conflict = 0; SBE.saving = false;+SBE.savePending = false; SBE.dirtyAt = 0; SBE.saveFailed = '';+SBE.saveTimer = null; SBE.revision = 1; SBE.sel = '';+els.sbeAlarm = { hidden: true };+els.sbeAlarmWhy = { textContent: '' };++// A SAVE ARRIVING MID-FLIGHT IS REMEMBERED, NOT THROWN AWAY. This is the+// dropped-save bug: `if (SBE.saving) return` left dirty true with no timer+// pending, so that edit was never written again.+SBE.saving = true;+await sbeSave(true);+out.midFlightRemembered = SBE.savePending;+SBE.savePending = false;+await sbeSave(false); // the BUTTON, not the debounce+out.midFlightRemembersASave = SBE.savePending;+SBE.saving = false; SBE.savePending = false;++// THE FLAG CANNOT STICK. A throw between "saving = true" and the fetch used+// to wedge the editor for the rest of the session, silently.+const realBody = sbeSaveBody;+sbeSaveBody = () => { throw new Error('boom'); };+SBE.dirty = true;+await sbeSave(true);+sbeSaveBody = realBody;+out.flagClearedAfterThrow = SBE.saving;+out.throwRaisesAlarm = [!!SBE.saveFailed, els.sbeAlarm.hidden,+ (states[states.length - 1] || [])[1]];++// A QUIET AUTOSAVE THAT FAILS IS STILL LOUD. `if (!quiet)` is what made the+// twenty minutes possible.+SBE.saveFailed = ''; els.sbeAlarm.hidden = true;+SBE.dirty = true; SBE.saving = false;+NEXT = { status: 500, body: { ok: false, error: 'disk is full' } };+await sbeSave(true);+out.quietFailureIsLoud = [!!SBE.saveFailed, els.sbeAlarm.hidden,+ els.sbeAlarmWhy.textContent,+ (states[states.length - 1] || [])[1]];++// A CONFLICT IS A FAILURE TO STORE, not a note.+SBE.saveFailed = ''; els.sbeAlarm.hidden = true; SBE.dirty = true;+NEXT = { status: 409, body: { ok: false, conflict: true, revision: 9 } };+await sbeSave(true);+out.conflictIsLoud = [!!SBE.saveFailed, els.sbeAlarm.hidden];++// ...and a save that LANDS takes the alarm down with it and stops the clock.+SBE.conflict = 0; SBE.dirty = true; SBE.dirtyAt = 1;+NEXT = { status: 200, body: { ok: true, edit: { revision: 12, clips: [] } } };+await sbeSave(true);+out.successClearsAlarm = [!!SBE.saveFailed, els.sbeAlarm.hidden, SBE.dirtyAt,+ SBE.dirty, (states[states.length - 1] || [])[1]];+SBE.dirty = false; SBE.dirtyAt = 0; SBE.saveFailed = '';++// ---- THE CRASH LANE, DRIVEN AS A SEQUENCE --------------------------------+// save → backup → recovery, in that ORDER. Every defect this lane has had+// lived between two of those steps rather than inside any one of them, and a+// suite that only asserts each guard exists is exactly blind to that: the+// guard that refuses to overwrite an unanswered offer was correct, and it+// killed the whole lane for the session because nothing ever answered.+SBE.backup = { at: 1, clips: 3, duration: 6 };+SBE.backedUpAt = 0; SBE.dirty = true;+FETCHES = [];+NEXT = { status: 200, body: { ok: true } };+// THE LANE NEVER STOPS. It used to refuse while an offer was unanswered,+// because there was one backup file per draft and a new write would have+// destroyed the work the offer held. The lane is versioned now, so there is+// nothing left to guard — and a chip nobody dismissed no longer switches the+// safety net off for the rest of the session.+NEXT = { status: 200, body: { ok: true } };+out.backupWritesEvenWithAnOfferOpen = [!!(await sbeBackup(true)),+ FETCHES.length, SBE.backedUpAt > 0];+// Save IS the answer. The server drops the file and hands back a payload with+// no offer in it; the client follows the server rather than deciding.+SBE.dirty = true; SBE.dirtyAt = 5;+const paintsBefore = recoveryPaints.length;+NEXT = { status: 200, body: { ok: true, edit: { revision: 13, clips: [] },+ backup: null,+ drafts: [{ slug: 'draft-1', name: 'Draft 1',+ active: true, clips: 1 }] } };+await sbeSave(true);+out.saveAnswersTheOffer = [SBE.backup, recoveryPaints.length > paintsBefore,+ (SBE.drafts || []).length];+// ...and the lane is alive again: the very next backup actually WRITES.+SBE.dirty = true;+FETCHES = [];+NEXT = { status: 200, body: { ok: true } };+out.backupLivesAfterASave = [!!(await sbeBackup(true)), FETCHES.length,+ SBE.backedUpAt > 0];+out.backupNamesItsDraft = JSON.parse(FETCHES[0].body || '{}').draft;+// A backup that does not land is the safety net gone, and only the alarm says so.+SBE.dirty = true;+NEXT = { status: 500, body: { ok: false, error: 'disk is full' } };+out.backupFailureIsLoud = [await sbeBackup(true), !!SBE.saveFailed];+SBE.saveFailed = ''; els.sbeAlarm.hidden = true;+SBE.dirty = false; SBE.dirtyAt = 0; SBE.backup = null; SBE.drafts = [];++// ---- J-cuts and L-cuts ---------------------------------------------------+const AC = () => lay([clip({ id: 'a', start: 0, end: 4, duration: 10 }),+ clip({ id: 'b', start: 0, end: 4, duration: 10 })]);+let ac = AC();+out.audioLinkedByDefault = (() => {+ const w = sbeClipAudio(ac[1]);+ return [w.start, w.end, w.film_start, w.linked];+})();+// UNLINKING IS NOT AN EDIT. It writes the window the clip already had.+let acr = sbeSetAudioLink(ac, 'b', false);+out.unlinkWritesTheSameWindow = [acr.ok, JSON.stringify(sbeById(acr.clips, 'b').audio)];+// ...and re-linking removes the field entirely.+out.relinkRemovesTheField = sbeById(sbeSetAudioLink(acr.clips, 'b', true).clips, 'b').audio || null;+// A LINKED CLIP REFUSES TO BE DRAGGED — the accident the default prevents.+out.linkedRefusesTheDrag = (() => {+ const q = sbeAudioEdit(AC(), 'b', 'move', 2);+ return [q.ok, q.why];+})();+// THE J-CUT: her voice starts a second before we see her, and the PICTURE+// does not move.+ac = sbeSetAudioLink(AC(), 'b', false).clips;+let j = sbeAudioEdit(ac, 'b', 'move', 3);+out.jCut = [j.ok, sbeById(j.clips, 'b').audio.film_start,+ sbeById(j.clips, 'b').film_start,+ sbeById(j.clips, 'b').audio.start];+// THE L-CUT: his line runs on under her picture — the tail is extended+// within the source it came from.+let l = sbeAudioEdit(sbeSetAudioLink(AC(), 'a', false).clips, 'a', 'trimR', 6);+out.lCut = [l.ok, sbeById(l.clips, 'a').audio.end,+ sbeById(l.clips, 'a').end, sbeById(l.clips, 'a').film_end];+// ...and it cannot run past the source clip.+let over = sbeAudioEdit(sbeSetAudioLink(AC(), 'a', false).clips, 'a', 'trimR', 99);+out.lCutClamped = sbeById(over.clips, 'a').audio.end;+// A HEAD TRIM MOVES THE IN-POINT AND LEAVES THE REST WHERE IT IS.+let h = sbeAudioEdit(sbeSetAudioLink(AC(), 'b', false).clips, 'b', 'trimL', 5);+out.headTrim = [sbeById(h.clips, 'b').audio.start,+ sbeById(h.clips, 'b').audio.film_start,+ sbeById(h.clips, 'b').start];+// A LOCKED CLIP'S SOUND IS LOCKED TOO.+let lk = sbeSetAudioLink(AC(), 'b', false).clips;+sbeById(lk, 'b').locked = true;+out.lockedRefuses = sbeAudioEdit(lk, 'b', 'move', 2).ok;+// A STILL HAS NO SOUND TO UNLINK.+out.stillRefuses = (() => {+ const cs = lay([clip({ id: 's', kind: 'still' })]);+ const q = sbeSetAudioLink(cs, 's', false);+ return [q.ok, q.why];+})();++// ---- WAVEFORMS, KEYFRAMES, AND DELETING HALF A CLIP ---------------------+// A synthetic take: one bucket per 10th of a second, a ramp so every slice is+// distinguishable from every other.+const PEAKS = (() => {+ const n = 100, arr = [];+ for (let i = 0; i < n; i++) { arr.push(-i, i); }+ return { version: 1, count: n, scale: 100, buckets_per_second: 10,+ duration: 10, peaks: arr };+})();+// THE STRIP'S OWN SOURCE WINDOW, never the picture's.+out.waveSliceIsTheStripsWindow = [+ sbeWaveSlice(PEAKS, 0, 1, 2).map(p => p.map(x => +x.toFixed(2))),+ sbeWaveSlice(PEAKS, 5, 6, 2).map(p => p.map(x => +x.toFixed(2))),+];+out.waveSliceHandlesZoomOut = sbeWaveSlice(PEAKS, 0, 10, 1)+ .map(p => p.map(x => +x.toFixed(2)));+out.waveSliceNoPeaksIsEmpty = sbeWaveSlice(null, 0, 1, 4).length;++const SND2 = () => sbeSetAudioLink(+ lay([clip({ id: 'a', start: 0, end: 4, duration: 10 })]), 'a', false).clips;+out.kfAdd = (() => {+ const cs = sbeAddKeyframe(SND2(), 'a', 2.0, 0.4).clips;+ return JSON.stringify(sbeById(cs, 'a').afx);+})();+out.kfNoTwoOnOneSecond = (() => {+ const cs = sbeAddKeyframe(SND2(), 'a', 2.0, 0.4).clips;+ const q = sbeAddKeyframe(cs, 'a', 2.0005, 0.9);+ return [q.ok, q.why];+})();+out.kfMoveAndSort = (() => {+ let cs = sbeAddKeyframe(SND2(), 'a', 1.0, 0.5).clips;+ cs = sbeAddKeyframe(cs, 'a', 3.0, 0.2).clips;+ cs = sbeMoveKeyframe(cs, 'a', 0, 3.5, 0.9).clips; // past its neighbour+ return JSON.stringify(sbeById(cs, 'a').afx.points);+})();+out.kfMoveClamps = (() => {+ let cs = sbeAddKeyframe(SND2(), 'a', 1.0, 0.5).clips;+ cs = sbeMoveKeyframe(cs, 'a', 0, 99, 9).clips;+ return JSON.stringify(sbeById(cs, 'a').afx.points);+})();+out.kfDeleteLeavesNoTrace = (() => {+ let cs = sbeAddKeyframe(SND2(), 'a', 2.0, 0.4).clips;+ cs = sbeDeleteKeyframe(cs, 'a', 0).clips;+ return sbeById(cs, 'a').afx === undefined;+})();+out.kfDeleteKeepsAFade = (() => {+ let cs = sbeSetAudioFade(SND2(), 'a', 'in', 1.0).clips;+ cs = sbeAddKeyframe(cs, 'a', 2.0, 0.4).clips;+ cs = sbeDeleteKeyframe(cs, 'a', 0).clips;+ return JSON.stringify(sbeById(cs, 'a').afx);+})();+out.kfLocked = sbeAddKeyframe(+ lay([clip({ id: 'a', end: 4, locked: true })]), 'a', 1, 0.5).why;++// DELETE THE STRIP: the picture keeps playing, silent, and does not move.+out.deleteStrip = (() => {+ let cs = sbeAudioEdit(SND2(), 'a', 'move', 1.0).clips; // a J-cut first+ const wasFilm = [sbeById(cs, 'a').film_start, sbeById(cs, 'a').film_end];+ const r = sbeDeleteStrip(cs, 'a');+ const c = sbeById(r.clips, 'a');+ return [r.ok, c.audio === undefined, !!c.mute, sbeClipMuted(c),+ [c.film_start, c.film_end], wasFilm];+})();+out.deleteStripIsNotARipple = (() => {+ let cs = sbeSetAudioLink(lay([clip({ id: 'a', end: 2 }),+ clip({ id: 'b', end: 3 })]), 'a', false).clips;+ const before = cs.map(c => [c.id, c.film_start, c.film_end]);+ const r = sbeDeleteStrip(cs, 'a');+ return [JSON.stringify(before),+ JSON.stringify(r.clips.map(c => [c.id, c.film_start, c.film_end]))];+})();+out.deleteStripTwiceIsRefused = (() => {+ const cs = sbeDeleteStrip(SND2(), 'a').clips;+ const q = sbeDeleteStrip(cs, 'a');+ return [q.ok, q.why];+})();++// ---- THE SOUND'S ENVELOPE -----------------------------------------------+const SND = () => sbeSetAudioLink(+ lay([clip({ id: 'a', start: 0, end: 4, duration: 10 })]), 'a', false).clips;+out.afxFlatIsNothing = [sbeGainPoints({}, 4).length, sbeGainAt({}, 4, 2)];+out.afxSimpleCase = sbeGainPoints({ afx: { fade_in: 1, fade_out: 0.5 } }, 4);+out.afxKeyframes = sbeGainPoints({ afx: { points: [[1, 0.3], [2, 1]] } }, 4);+out.afxCompose = sbeGainPoints({ afx: { fade_in: 1, points: [[2, 0.25]] } }, 4);+out.afxGainAt = [0, 0.5, 1, 2, 3.75, 4]+ .map(t => sbeGainAt({ afx: { fade_in: 1, fade_out: 0.5 } }, 4, t));+out.afxClamp = (() => {+ const e = sbeAfx({ afx: { fade_in: 9, fade_out: 9 } }, 4);+ return [e.fade_in, e.fade_out];+})();+// THE SAME GESTURE THE PICTURE HAS, so the muscle memory transfers.+out.afxSet = (() => {+ let cs = sbeSetAudioFade(SND(), 'a', 'in', 1.0).clips;+ const on = JSON.stringify(sbeById(cs, 'a').afx);+ cs = sbeSetAudioFade(cs, 'a', 'in', 0).clips;+ return [on, sbeById(cs, 'a').afx === undefined, sbeById(cs, 'a').source];+})();+out.afxSetClampsToTheStrip = (() => {+ const cs = sbeSetAudioFade(SND(), 'a', 'in', 99).clips;+ return sbeAfx(sbeById(cs, 'a'), sbeClipAudio(sbeById(cs, 'a')).len).fade_in;+})();+out.afxLocked = sbeSetAudioFade(+ lay([clip({ id: 'a', end: 4, locked: true })]), 'a', 'in', 1).why;++// ---- THE OVERLAY LANE ---------------------------------------------------+// A second video track. Cards do NOT ripple: one is placed where somebody+// wants it in the finished sequence, so moving one moves one.+const CARD = () => [{ id: 'o1', kind: 'still', path: '/x/endcard.png',+ start: 0, end: 3, film_start: 3, film_end: 6,+ source: 'human', locked: false }];+out.ovKind = [sbeOvKind({ path: '/x/a.png' }), sbeOvKind({ path: '/x/a.mp4' }),+ sbeOvKind({ kind: 'video', path: '/x/a.png' })];+out.ovAt = [!!sbeOvAt(CARD(), 2.9), !!sbeOvAt(CARD(), 3.0),+ !!sbeOvAt(CARD(), 5.9), !!sbeOvAt(CARD(), 6.0)];+// MOVING ONE MOVES ONE, and a still is its slot.+out.ovMove = (() => {+ const r = sbeOvMove(CARD(), 'o1', 10);+ const o = sbeOvById(r.overlays, 'o1');+ return [r.ok, o.film_start, o.film_end, o.start, o.end, o.source];+})();+// ONE LANE: a move onto another card is refused, not stacked.+out.ovNoStacking = (() => {+ const two = CARD().concat([{ id: 'o2', kind: 'still', path: '/x/b.png',+ start: 0, end: 2, film_start: 8, film_end: 10 }]);+ const q = sbeOvMove(two, 'o1', 8.5);+ return [q.ok, q.why];+})();+// TRIMMING changes only its own window — the picture beneath is not consulted.+out.ovTrim = (() => {+ let cs = sbeOvTrim(CARD(), 'o1', 'r', 8).overlays;+ const a = sbeOvById(cs, 'o1');+ cs = sbeOvTrim(cs, 'o1', 'l', 4).overlays;+ const b = sbeOvById(cs, 'o1');+ return [[a.film_end, a.end], [b.film_start, b.film_end, b.end]];+})();+// ADDING lands somewhere free rather than refusing.+out.ovAddSlidesPastAnother = (() => {+ const r = sbeOvAdd(CARD(), { path: '/x/b.png', duration_s: 2 }, 4);+ const o = r.added;+ return [r.ok, o.film_start, o.film_end, o.kind];+})();+// DELETE IS NOT A RIPPLE: the other card does not move.+out.ovDeleteMovesNothing = (() => {+ const two = CARD().concat([{ id: 'o2', kind: 'still', path: '/x/b.png',+ start: 0, end: 2, film_start: 8, film_end: 10 }]);+ const r = sbeOvDelete(two, 'o1');+ return [r.ok, r.overlays.length, sbeOvById(r.overlays, 'o2').film_start];+})();+// THE SAME EFFECTS ACCESSOR a clip uses — the foundation paying off.+out.ovFades = (() => {+ const o = Object.assign({}, CARD()[0], { fx: { fade_in: 1.0 } });+ return [sbeFx(o).fade_in,+ [3, 3.5, 4, 5].map(t => sbeFadeOpacityAt(o, t))];+})();+out.ovFadeClamp = (() => {+ const o = Object.assign({}, CARD()[0], { fx: { fade_in: 9 } });+ return sbeFx(o).fade_in;+})();+// "KEEP ORIGINAL" IS A POINTER SWAP, and nothing else about the card moves —+// the original file was never modified, so undoing the auto-key is one field.+out.ovKeepOriginal = (() => {+ const keyed = CARD().map(o => Object.assign({}, o, { path: '/x/a.keyed.png' }));+ const r = sbeOvSetPath(keyed, 'o1', '/x/a.png');+ const o = sbeOvById(r.overlays, 'o1');+ return [r.ok, o.path, o.film_start, o.film_end,+ // the array it was given is not mutated — undo depends on that+ sbeOvById(keyed, 'o1').path];+})();+out.ovKeepOriginalOnAGoneCard = (() => {+ const r = sbeOvSetPath(CARD(), 'nope', '/x/a.png');+ return [r.ok, r.why];+})();++// ---- A HOLE SHORTER THAN A FRAME ---------------------------------------+// "A black frame that flashes for a microsecond... I tried to drag them close+// and whatever." His three holes were 0.503, 0.380 and 0.096 of a frame.+const HOLED = () => [+ clip({ id: 'a', start: 0, end: 4, film_start: 0, film_end: 4 }),+ clip({ id: 'b', start: 0, end: 4, film_start: 4.02094, film_end: 8.02094 }),+ clip({ id: 'c', start: 0, end: 4, film_start: 8.03678, film_end: 12.03678 }),+ clip({ id: 'd', start: 0, end: 4, film_start: 12.04078, film_end: 16.04078 }),+];+out.gridGapCollapsesSubFrameOnly = [+ sbeGridGap(0.02094), sbeGridGap(0.01584), sbeGridGap(0.004),+ sbeGridGap(1 / 24), sbeGridGap(0.5), sbeGridGap(1.8),+];+out.holedFilmLaysOutContiguous = (() => {+ const cs = lay(HOLED());+ return [shape(cs), sbeHoles(cs).length, lengthsAgree(cs)];+})();+// A DRAG CANNOT REOPEN ONE. `sbeLayout` quantises the gap a gesture produced,+// so there is no pixel that lands a third of a frame away from the cut.+out.dragCannotOpenASubFrameHole = (() => {+ const cs = lay(HOLED());+ const r = sbeMoveTo(cs, 'b', 4.017);+ const o = sbeById(r.clips, 'b');+ return [r.ok, o.film_start, sbeHoles(r.clips).length];+})();+// ...but a hole somebody can SEE survives a drag untouched.+out.dragKeepsAGapYouCanSee = (() => {+ const cs = lay(HOLED());+ const r = sbeMoveTo(cs, 'b', 6.5);+ return [sbeById(r.clips, 'b').film_start, sbeHoles(r.clips).length];+})();+// THE HEAL CARRIES THE SOUND. Closing a hole is not the user sliding a+// picture, so an unlinked strip travels with it and the J-cut is unchanged.+out.adoptCarriesTheUnlinkedStrip = (() => {+ const cs = HOLED();+ cs[1].audio = { split: true, start: 0.5, end: 4.5, film_start: 3.52094 };+ const before = sbeAudioDrift(cs[1]);+ lay(cs);+ return [+before.toFixed(6), +sbeAudioDrift(cs[1]).toFixed(6),+ +cs[1].audio.film_start.toFixed(6)];+})();+// THE COUNTER STOPS LYING. The old threshold was the literal 1/48 — half a+// frame at 24 fps and the wrong number at any other — and two of his three+// holes were under it, which is why the header read "1 hole".+out.holeCounterOnHisFilm = (() => {+ return [sbeHoles(HOLED(), 1 / 48).length, sbeHoles(HOLED(), 1e-9).length,+ sbeHoles(lay(HOLED())).length];+})();++// ---- THE NET'S OWN STATE ------------------------------------------------+out.protectedChip = (() => {+ const read = () => ({ text: sbeEl('sbeProtected').textContent,+ cold: sbeEl('sbeProtected').classList.contains('is-cold') });+ const was = { open: SBE.open, id: SBE.id, dirty: SBE.dirty,+ dirtyAt: SBE.dirtyAt, backedUpAt: SBE.backedUpAt };+ SBE.open = true; SBE.id = 'sb_t'; SBE.otherEditor = '';+ SBE.dirty = true; SBE.dirtyAt = Date.now();+ SBE.backedUpAt = Date.now() - 3000; sbePaintProtected(); const fresh = read();+ SBE.backedUpAt = Date.now() - 40000; sbePaintProtected(); const cold = read();+ SBE.backedUpAt = 0; sbePaintProtected(); const never = read();+ Object.assign(SBE, was);+ return [fresh, cold, never];+})();++// ---- THE EFFECTS MODEL --------------------------------------------------+const FADED = () => lay([clip({ id: 'a', start: 0, end: 4, duration: 10,+ fx: { fade_in: 0.5, fade_out: 1.0 } })]);+out.fxAbsentIsNothing = (() => {+ const e = sbeFx(clip({ id: 'z', end: 4 }));+ return [e.fade_in, e.fade_out, e.brightness];+})();+out.fxOneAccessor = (() => {+ const e = sbeFx(clip({ id: 'a', end: 4, fx: { fade_in: 0.5 },+ adjust: { brightness: 0.25 } }));+ return [e.fade_in, e.brightness];+})();+// THE SAME CLAMP THE SERVER APPLIES, and proportional rather than truncating.+out.fxClamp = (() => {+ const both = sbeFx(clip({ id: 'a', end: 4, film_end: 4,+ fx: { fade_in: 3, fade_out: 3 } }));+ const lop = sbeFx(clip({ id: 'a', end: 4, film_end: 4,+ fx: { fade_in: 3, fade_out: 1 } }));+ return [[both.fade_in, both.fade_out],+ [sbeRound(lop.fade_in + lop.fade_out), lop.fade_in > lop.fade_out]];+})();+// A VALUE PER FRAME, not a CSS transition: a scrub shows what is true at the+// second it landed on.+out.fxOpacityRamp = (() => {+ const c = sbeById(FADED(), 'a');+ return [0, 0.25, 0.5, 2, 3, 3.5, 4].map(t => sbeFadeOpacityAt(c, t));+})();+out.fxNoFadeIsAlwaysOpaque = (() => {+ const c = sbeById(lay([clip({ id: 'a', end: 4 })]), 'a');+ return [sbeFadeOpacityAt(c, 0), sbeFadeOpacityAt(c, 2)];+})();+// SETTING one, and NEUTRAL IS ABSENT on the way back out.+out.fxSet = (() => {+ let cs = FADED();+ cs = sbeSetFade(cs, 'a', 'out', 0).clips;+ const afterClear = JSON.stringify(sbeById(cs, 'a').fx);+ cs = sbeSetFade(cs, 'a', 'in', 0).clips;+ return [afterClear, sbeById(cs, 'a').fx === undefined,+ sbeById(cs, 'a').source];+})();+out.fxSetClamps = (() => {+ const cs = sbeSetFade(FADED(), 'a', 'in', 99).clips;+ return sbeFx(sbeById(cs, 'a')).fade_in;+})();+out.fxLockedRefuses = sbeSetFade(+ lay([clip({ id: 'a', end: 4, locked: true })]), 'a', 'in', 1).why;+out.fxReachesTheSavePayload = (() => {+ const c = sbeCleanClip(sbeById(FADED(), 'a'));+ return JSON.stringify(c.fx);+})();++// ---- THE PREVIEW PLAYS WHAT THE DOCUMENT SAYS ---------------------------+// HIS ARRANGEMENT, rev 97. One take twice: clip 5 whole at film 25.99, clip 6+// trimmed 0.42 s off the head at film 30.77 with its strip reaching back to+// 30.35. The J-cut was correct on disk, in the render and in the export, and+// inaudible in the one place he checks his work.+const JCUT = () => [+ {id:'c5', path:'/x/w.mp4', proxy:null, start:0.0, end:4.042, film_start:25.99,+ film_end:30.032, source:'human', locked:false, duration:4.042},+ {id:'c6', path:'/x/w.mp4', proxy:null, start:0.42, end:4.042, film_start:30.77,+ film_end:34.392, source:'human', locked:false, duration:4.042,+ audio:{start:0.0, end:4.042, film_start:30.35}}];++// WHO OWNS THE SOUND. Exactly one of the two, never both.+out.stripOwnership = (() => {+ const cs = JCUT();+ const plain = cs[0], split = cs[1];+ const muted = Object.assign({}, split, { mute: true });+ const still = { id: 's', kind: 'still', path: '/x/a.png', start: 0, end: 2,+ film_start: 0, film_end: 2 };+ return {+ plain: [sbeStripOwned(plain), sbePictureCarriesSound(plain)],+ split: [sbeStripOwned(split), sbePictureCarriesSound(split)],+ muted: [sbeStripOwned(muted), sbePictureCarriesSound(muted)],+ still: [sbeStripOwned(still), sbePictureCarriesSound(still)],+ };+})();++// THE J-CUT IS AUDIBLE BEFORE THE PICTURE CUTS. 29.5 -> 31.5 across the cut.+out.stripAcrossHisCut = (() => {+ const cs = JCUT();+ const at = t => sbeStripsAt(cs, t).map(x => [x.id, x.at]);+ return {+ before: at(29.5), // his line has not started yet+ lead: at(30.4), // ...it starts at 30.35, under the outgoing shot+ edge: at(30.76), // still ahead of the picture+ after: at(31.0), // and continuous across the cut at 30.77+ late: at(34.3),+ ended: at(34.4), // 30.35 + 4.042 = 34.392+ };+})();++// THE MAPPING. Film second -> SOURCE second, and it is the strip's own clock.+out.stripMapping = (() => {+ const cs = JCUT();+ const one = t => (sbeStripsAt(cs, t)[0] || {}).at;+ return [one(30.35), one(30.77), one(31.35), one(34.39)];+})();++// TWO STRIPS AT ONCE. An L-cut runs the outgoing sound under the incoming+// picture, so both are audible and the player gives each a voice.+out.stripOverlap = (() => {+ const cs = [+ {id:'a', path:'/x/a.mp4', start:0, end:4, film_start:0, film_end:4,+ duration:10, audio:{start:0, end:6, film_start:0}}, // L-cut tail+ {id:'b', path:'/x/b.mp4', start:0, end:4, film_start:4, film_end:8,+ duration:10, audio:{start:0, end:4, film_start:3.5}}]; // J-cut head+ return {+ both: sbeStripsAt(cs, 4.5).map(x => [x.id, x.at]),+ onlyA: sbeStripsAt(cs, 2.0).map(x => x.id),+ onlyB: sbeStripsAt(cs, 6.5).map(x => x.id),+ };+})();++// A MUTED STRIP IS SILENT, and it is silent by not being there at all.+out.stripMuted = (() => {+ const cs = JCUT();+ cs[1] = Object.assign({}, cs[1], { mute: true });+ return [sbeStripsAt(cs, 30.4).length, sbeStripsAt(cs, 31.0).length];+})();++// A COUPLED pair is a strip too: it travels with its picture at a frozen+// offset, and the player is what makes that offset audible.+out.stripCoupled = (() => {+ const cs = [{id:'a', path:'/x/a.mp4', start:0, end:4, film_start:6,+ film_end:10, duration:10,+ audio:{start:0, end:4, film_start:4, linked:true}}];+ return [sbeStripOwned(cs[0]), sbeStripsAt(cs, 4.5).map(x => [x.id, x.at])];+})();++// AN ORDINARY CLIP IS NOT THE PLAYER'S BUSINESS — no strip, no voice, and the+// picture element goes on carrying its own sound as it always did.+out.stripIgnoresOrdinary = sbeStripsAt(lay([clip({id:'z', end:4})]), 1.0).length;++// ---- THE LOAD PATH REWRITES NOTHING -------------------------------------+// sb_carwash rev 97: one take used twice, the first whole with no strip of its+// own, the second trimmed 0.42 s off the head with a strip reaching back to+// cover it. The client must hand back exactly what the disk gave it — there is+// no load-time repair here, and there must never be one.+out.loadRewritesNothing = (() => {+ const disk = [+ {id:'c5', path:'/x/w.mp4', proxy:null, start:0.0, end:4.042, film_start:25.99,+ film_end:30.032, source:'human', locked:false, duration:4.042},+ {id:'c6', path:'/x/w.mp4', proxy:null, start:0.42, end:4.042, film_start:30.77,+ film_end:34.392, source:'human', locked:false, duration:4.042,+ audio:{start:0.0, end:4.042, film_start:30.35}}];+ const before = JSON.stringify(disk);+ const clips = sbeAdoptGaps(disk.map(c => Object.assign({}, c)));+ sbeLayout(clips);+ const saved = clips.map(sbeCleanClip);+ return {+ audioUntouched: JSON.stringify(sbeById(clips, 'c6').audio),+ firstHasNoStrip: sbeById(clips, 'c5').audio === undefined,+ drift: [sbeAudioDrift(sbeById(clips, 'c5')), sbeAudioDrift(sbeById(clips, 'c6'))],+ roundTrips: JSON.stringify(saved.map(c => [c.id, c.film_start, c.film_end,+ c.start, c.end, c.audio || null])),+ diskWasNotMutated: JSON.stringify(disk) === before,+ };+})();++// ---- MUTE: the clip's own sound, switched off ---------------------------+// "We should have an option to mute the clip sound." An H3 shot arrives with+// baked-in wind under the line, and on a music cut that is noise to remove.+out.muteAbsentIsAudible = sbeClipMuted(clip({ id: 'm' }));+out.muteWritesTheFlag = (() => {+ const cs = lay([clip({ id: 'a', start: 0, end: 4, duration: 10 })]);+ const q = sbeSetClipMute(cs, 'a', true);+ return [q.ok, sbeById(q.clips, 'a').mute, sbeClipMuted(sbeById(q.clips, 'a')),+ sbeById(q.clips, 'a').source];+})();+// UNMUTE RESTORES EXACTLY WHAT WAS THERE: the field goes, so the document is+// identical to one that was never muted.+out.muteUnmuteLeavesNoTrace = (() => {+ let cs = lay([clip({ id: 'a', start: 0, end: 4, duration: 10 })]);+ // `source` legitimately becomes 'human' — the user touched this clip — so+ // the comparison is of everything the mute could have left behind.+ const shape = x => { const o = sbeCleanClip(x); delete o.source; return JSON.stringify(o); };+ const was = shape(sbeById(cs, 'a'));+ cs = sbeSetClipMute(cs, 'a', true).clips;+ cs = sbeSetClipMute(cs, 'a', false).clips;+ return [was === shape(sbeById(cs, 'a')),+ sbeById(cs, 'a').mute === undefined];+})();+// MUTE AND UNLINK ARE INDEPENDENT, in both directions.+out.muteComposesWithUnlink = (() => {+ let cs = lay([clip({ id: 'a', start: 0, end: 4, duration: 10 }),+ clip({ id: 'b', start: 0, end: 4, duration: 10 })]);+ cs = sbeSetAudioLink(cs, 'b', false).clips;+ cs = sbeAudioEdit(cs, 'b', 'move', 2).clips; // a J-cut+ cs = sbeSetClipMute(cs, 'b', true).clips; // ...then mute it+ const c = sbeById(cs, 'b');+ const w = sbeClipAudio(c);+ const after = { muted: sbeClipMuted(c), split: w.split,+ snd: [w.film_start, sbeRound(w.film_start + w.len)] };+ // ...and muting first, then unlinking, reaches the same place.+ let d = sbeSetClipMute(lay([clip({ id: 'z', start: 0, end: 4, duration: 10 })]),+ 'z', true).clips;+ d = sbeSetAudioLink(d, 'z', false).clips;+ return [after, sbeClipMuted(sbeById(d, 'z')),+ sbeClipAudio(sbeById(d, 'z')).split];+})();+// A CLIP WHOSE FILE HAS NO AUDIO HAS NOTHING TO SWITCH OFF.+out.muteRefusesASilentSource = (() => {+ const cs = lay([clip({ id: 'a', has_audio: false })]);+ const q = sbeSetClipMute(cs, 'a', true);+ return [q.ok, q.why];+})();+out.muteRefusesAStill = sbeSetClipMute(lay([clip({ id: 's', kind: 'still' })]),+ 's', true).why;+// UNDO WALKS IT BACK, because it goes through the one lane every edit does.+out.muteIsUndoable = (() => {+ SBE.clips = lay([clip({ id: 'a', start: 0, end: 4, duration: 10 })]);+ SBE.undo = []; SBE.redo = [];+ sbeMutate(cs => sbeSetClipMute(cs, 'a', true));+ const on = sbeClipMuted(sbeById(SBE.clips, 'a'));+ sbeUndo();+ const off = sbeClipMuted(sbeById(SBE.clips, 'a'));+ sbeRedo();+ return [on, off, sbeClipMuted(sbeById(SBE.clips, 'a'))];+})();+// IT REACHES DISK. `sbeCleanClip` is the save payload's own shape.+out.muteSurvivesTheSavePayload = (() => {+ const cs = sbeSetClipMute(lay([clip({ id: 'a', start: 0, end: 4, duration: 10 })]),+ 'a', true).clips;+ return sbeCleanClip(sbeById(cs, 'a')).mute;+})();++// ---- the ONE notice surface ---------------------------------------------+// Four full-width blocks in the same column, and they are NOT mutually+// exclusive: the day the overlap rule refused a J-cut he had three of them on+// screen at once, the timeline pushed off the bottom, and the sentence that+// mattered was the third one down.+function noticeState(open, lead) {+ // An earlier case swaps a bare object over one of these; give them all a+ // classList back so the fold is observable rather than skipped.+ for (const id of SBE_NOTICE_ORDER) {+ if (!els[id] || !els[id].classList) els[id] = stubEl(id, true);+ }+ // The snapshot offer is the one QUIET notice: a chip even when alone.+ els.sbeRecover.dataset = { quiet: '1' };+ els.sbeKeyed.dataset = { quiet: '1' };+ for (const id of SBE_NOTICE_ORDER) sbeEl(id).hidden = open.indexOf(id) < 0;+ SBE.noticeLead = lead || '';+ const got = sbePaintNotices();+ return { lead: got, folded: foldedNotices(),+ wrapHidden: sbeEl('sbeNotices').hidden };+}+out.noticeNothingIsNoSurface = noticeState([]);+// A LONE NOTICE IS NEVER A CHIP — folding the only thing on screen would hide+// the sentence to save room nothing is asking for.+out.noticeAloneIsOpen = noticeState(['sbeAlarm']);+// ...but the SNAPSHOT offer is quiet: a chip even when it is the only notice,+// because it is an invitation to look and never a question to answer.+out.noticeQuietIsAlwaysAChip = noticeState(['sbeRecover']);+// The auto-key receipt is the second quiet citizen, and the least urgent thing+// on the screen: it reports something that ALREADY WORKED, so a save that is+// failing takes the width and the receipt sits beside it as a chip.+out.noticeKeyedAloneIsAChip = noticeState(['sbeKeyed']);+out.noticeKeyedNeverOutranksTheAlarm = noticeState(['sbeKeyed', 'sbeAlarm']);+out.noticeKeyedIsLastOfAll =+ noticeState(['sbeKeyed', 'sbeRecover', 'sbeErrors', 'sbeAlarm', 'sbeConflict']);+// Urgency order, and it is not the DOM order: the recovery offer is a+// question about last session and waits behind all three of the others.+out.noticeUrgencyOrder = noticeState(['sbeRecover', 'sbeErrors', 'sbeAlarm']);+out.noticeConflictWinsEverything =+ noticeState(['sbeRecover', 'sbeErrors', 'sbeAlarm', 'sbeConflict']);+// ...and the user overrides it by clicking a chip.+out.noticeClickOpensAChip = (() => {+ noticeState(['sbeAlarm', 'sbeRecover']);+ sbeNoticeOpen('sbeRecover');+ return { lead: SBE.noticeLead, folded: foldedNotices() };+})();+// A lead that goes away hands the surface back to urgency order rather than+// leaving every notice folded behind a chip nobody can see.+out.noticeLeadThatClosesReleases = (() => {+ noticeState(['sbeAlarm', 'sbeRecover'], 'sbeRecover');+ return noticeState(['sbeAlarm']);+})();+// "LATER" IS NOT "DISCARD". Discard deletes the backup, so it was never the+// button for "not now" — and with no third option the bar sat across the top+// of the film for the rest of the session.+out.noticeLaterHidesAndKeeps = (() => {+ SBE.backup = { at: 1, clips: 3, duration: 4 };+ SBE.backupHidden = false;+ sbeEl('sbeRecover').hidden = false;+ sbeNoticeLater();+ // The flag is what `sbePaintRecovery` reads on every repaint; the backup+ // FILE and the offer object are both untouched, which is the whole point.+ return [SBE.backupHidden, !!SBE.backup];+})();+SBE.backup = null; SBE.backupHidden = false;+sbeEl('sbeRecover').hidden = true; sbeEl('sbeAlarm').hidden = true;+sbeEl('sbeErrors').hidden = true; sbeEl('sbeConflict').hidden = true;+sbePaintNotices();++// ---- the PAIR: unlink, cut the picture, put it back ----------------------+// The owner, mid-film: "instead of allowing me to remove or move what video is+// visible while leaving the sound intact and then rematching it, it is actually+// getting the audio out of sync... what should happen is that I only cut the+// video and left the sound in place."+//+// Three butt-joined shots, each a full 4 s of its own 10 s take. Every case+// below reports the same four things — where the picture sits on the film, what+// it plays, where the SOUND sits, what IT plays — because "in sync" is a+// statement about the pair and not about either half.+const PAIR = () => lay([clip({ id: 'a', start: 0, end: 4, duration: 10 }),+ clip({ id: 'b', start: 0, end: 4, duration: 10 }),+ clip({ id: 'c', start: 0, end: 4, duration: 10 })]);+function aState(cs, id) {+ const c = sbeById(cs, id);+ const w = sbeClipAudio(c);+ return {+ vid: [sbeRound(c.film_start), sbeRound(c.film_end)],+ vsrc: [sbeRound(c.start), sbeRound(c.end)],+ snd: [w.film_start, sbeRound(w.film_start + w.len)],+ ssrc: [w.start, w.end],+ drift: sbeAudioDrift(c), linked: w.linked, coupled: w.coupled,+ split: w.split,+ };+}+const unlink = (cs, ids) => ids.reduce((x, id) => sbeSetAudioLink(x, id, false).clips, cs);++// 1. UNLINKING ANCHORS THE STRIP WHERE THE CLIP ALREADY IS, and nothing moves.+out.pairUnlink = aState(unlink(PAIR(), ['b']), 'b');++// 2. TRIMMING THE HEAD. The in-point and the slot move together, so the frames+// that remain still play at the film second they always did — the sound is+// not touched and does not have to be.+out.pairTrimHead = (() => {+ const cs = unlink(PAIR(), ['b']);+ sbeTrim(cs, 'b', 'l', 5);+ return [aState(cs, 'b'), aState(cs, 'c')];+})();++// 3. TRIMMING THE TAIL of the shot BEFORE it. The picture after a ripple is+// rigidly translated, so its sound goes with it: this is the case that was+// silently coming apart, three shots away from the handle being dragged.+out.pairTrimTailRipples = (() => {+ const cs = unlink(PAIR(), ['c']);+ sbeTrim(cs, 'a', 'r', 3);+ return [aState(cs, 'a'), aState(cs, 'c')];+})();++// 4. MOVING THE PICTURE BY HAND. The one gesture whose whole point is to leave+// the sound behind — and the clip NEXT to it still rides along.+out.pairMove = (() => {+ const cs = sbeMoveTo(unlink(PAIR(), ['b', 'c']), 'b', 6).clips;+ return [aState(cs, 'b'), aState(cs, 'c')];+})();++// 5. THE REMATCH. One call puts the strip back under the frame it came from,+// and leaves it unlinked so it can be moved again.+out.pairResync = (() => {+ const cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;+ const r = sbeResyncAudio(cs, 'b');+ return [r.ok, aState(r.clips, 'b')];+})();+// ...and it is a RE-MATCH, not an un-trim: a sound trimmed to a later in-point+// keeps that in-point and lands where THAT second plays.+out.pairResyncKeepsTheTrim = (() => {+ let cs = unlink(PAIR(), ['a']);+ cs = sbeAudioEdit(cs, 'a', 'trimL', 1).clips; // in-point 1 s into the take+ cs = sbeMoveTo(cs, 'a', 5).clips;+ const r = sbeResyncAudio(cs, 'a');+ return [r.ok, aState(r.clips, 'a')];+})();+out.pairResyncRefusesWhenAlreadyThere = (() => {+ const q = sbeResyncAudio(unlink(PAIR(), ['b']), 'b');+ return [q.ok, q.why];+})();+out.pairResyncRefusesALinkedClip = (() => {+ const q = sbeResyncAudio(PAIR(), 'b');+ return [q.ok, q.why];+})();++// 6. SPLIT. One strip becomes two that butt-join — never two claiming the same+// seconds, which is what the deep copy used to produce and what the server+// refuses as `clips_audio_overlap`.+out.pairSplit = (() => {+ const r = sbeSplitAt(unlink(PAIR(), ['b']), 6, 'b2');+ return [r.ok, aState(r.clips, 'b'), aState(r.clips, 'b2')];+})();+// A split of a DRIFTED pair keeps the drift on both halves — the cut is+// expressed in the source clock the two halves share.+out.pairSplitKeepsTheDrift = (() => {+ const cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;+ const r = sbeSplitAt(cs, 8, 'b2');+ return [r.ok, aState(r.clips, 'b').drift, aState(r.clips, 'b2').drift,+ aState(r.clips, 'b').snd, aState(r.clips, 'b2').snd];+})();+// ...and a cut the strip does not reach is an honest no, because "this half has+// no sound" is a state the document cannot express: an absent `audio` means+// LINKED, which would invent sound the film never had.+out.pairSplitOutsideTheStrip = (() => {+ let cs = unlink(PAIR(), ['a']);+ cs = sbeAudioEdit(cs, 'a', 'trimL', 2).clips; // the strip now plays 2→4+ const q = sbeSplitAt(cs, 1, 'a2');+ return [q.ok, q.why, aState(cs, 'a').ssrc];+})();++// 7. RIPPLE DELETE pulls the film up, sound included.+out.pairRippleDelete = (() => {+ const cs = sbeRippleDelete(unlink(PAIR(), ['c']), 'b').clips;+ return aState(cs, 'c');+})();++// 8. RE-LINK FREEZES THE OFFSET INSTEAD OF THROWING IT AWAY. Deleting the+// field snapped the sound back under the picture, so the one button that+// said "link" destroyed the J-cut the moment it was made — which is why the+// owner reached for LOCK, and why the clip then refused every drag.+out.pairRelinkFreezesTheOffset = (() => {+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;+ cs = sbeSetAudioLink(cs, 'b', true).clips;+ return [aState(cs, 'b'), sbeById(cs, 'b').audio.linked === true];+})();+// ...and an IN-SYNC re-link still removes the field outright, so a split+// somebody tried and undid leaves a document identical to one that never had+// it.+out.pairRelinkInSyncRemovesTheField = (() => {+ const cs = sbeSetAudioLink(unlink(PAIR(), ['b']), 'b', true).clips;+ return [sbeById(cs, 'b').audio === undefined, aState(cs, 'b')];+})();+// A COUPLED pair travels together: the gesture that moves the picture moves+// the sound, offset intact. This is the "lock it and move it" he described.+out.pairCoupledTravels = (() => {+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips; // -2 s J-cut+ cs = sbeSetAudioLink(cs, 'b', true).clips; // freeze it+ cs = sbeMoveTo(cs, 'b', 10).clips; // now move the pair+ const s = aState(cs, 'b');+ const t = sbeTrim(cs, 'b', 'r', sbeById(cs, 'b').film_end - 1);+ return [s, aState(cs, 'b').drift, t.ok];+})();+// ...and it cannot be dragged on its own any more, which is what "linked"+// has always meant.+out.pairCoupledStripRefusesTheDrag = (() => {+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;+ cs = sbeSetAudioLink(cs, 'b', true).clips;+ const q = sbeAudioEdit(cs, 'b', 'move', 2);+ return [q.ok, q.why];+})();+// THE TOGGLE ROUND TRIP, which is what he actually did: unlink, trim, link,+// move, unlink again. Both halves stay editable and the offset survives every+// step.+out.pairToggleRoundTrip = (() => {+ const seen = [];+ let cs = unlink(PAIR(), ['b']);+ const t1 = sbeTrim(cs, 'b', 'r', 7); // tail, unlinked+ seen.push([t1.ok, aState(cs, 'b').drift]);+ cs = sbeAudioEdit(cs, 'b', 'move', 2.5).clips; // build the J-cut+ seen.push(aState(cs, 'b').drift);+ cs = sbeSetAudioLink(cs, 'b', true).clips; // "lock" it+ seen.push([aState(cs, 'b').drift, aState(cs, 'b').coupled]);+ cs = sbeMoveTo(cs, 'b', 9).clips; // move the pair+ seen.push([aState(cs, 'b').drift, aState(cs, 'b').snd]);+ const t2 = sbeTrim(cs, 'b', 'l', 9.5); // head, coupled+ seen.push([t2.ok, aState(cs, 'b').drift]);+ cs = sbeSetAudioLink(cs, 'b', false).clips; // unlink again+ seen.push([aState(cs, 'b').drift, aState(cs, 'b').coupled,+ aState(cs, 'b').linked]);+ const t3 = sbeTrim(cs, 'b', 'r', sbeById(cs, 'b').film_end - 0.5);+ seen.push([t3.ok, aState(cs, 'b').drift]);+ return seen;+})();+// THE SCENARIO HE DESCRIBED, START TO FINISH. "I clip a little from the+// visuals and then move all together to fill the gap. So you start hearing+// the character before you see it." Trim the head off shot 2, which opens a+// gap and leaves the sound reaching back into shot 1; freeze that; then drag+// the pair left to close the gap and check that BOTH halves moved by the same+// amount and the sound still leads the picture.+out.pairHisScenario = (() => {+ let cs = unlink(PAIR(), ['b']);+ sbeTrim(cs, 'b', 'l', 5); // a little off the visuals+ const afterTrim = aState(cs, 'b'); // picture 5-8, sound 4-8+ cs = sbeSetAudioLink(cs, 'b', true).clips; // "lock" the two together+ const frozen = aState(cs, 'b');+ cs = sbeMoveTo(cs, 'b', 4).clips; // move all together, gap closed+ const moved = aState(cs, 'b');+ return {+ trimOpensTheGap: [afterTrim.vid, afterTrim.snd, afterTrim.drift],+ frozen: [frozen.coupled, frozen.drift],+ moved: [moved.vid, moved.snd, moved.drift],+ videoDelta: sbeRound(moved.vid[0] - frozen.vid[0]),+ soundDelta: sbeRound(moved.snd[0] - frozen.snd[0]),+ soundLeadsBy: sbeRound(moved.vid[0] - moved.snd[0]),+ };+})();++// A COUPLED pair is not a drift and is never flagged — its offset is the+// relationship the user froze.+out.pairCoupledIsNotFlagged = (() => {+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;+ const free = sbeSyncBadge(sbeById(cs, 'b')).length > 0;+ cs = sbeSetAudioLink(cs, 'b', true).clips;+ return [free, sbeSyncBadge(sbeById(cs, 'b')).length > 0,+ aState(cs, 'b').drift];+})();+// ...but Resync still reaches it, and a rematched couple has nothing left to+// say, so the field goes.+out.pairResyncACouple = (() => {+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;+ cs = sbeSetAudioLink(cs, 'b', true).clips;+ const r = sbeResyncAudio(cs, 'b');+ return [r.ok, sbeById(r.clips, 'b').audio === undefined, aState(r.clips, 'b')];+})();+// A COUPLED pair splits into two coupled pairs.+out.pairSplitACouple = (() => {+ let cs = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips;+ cs = sbeSetAudioLink(cs, 'b', true).clips;+ const r = sbeSplitAt(cs, 8, 'b2');+ return [r.ok, aState(r.clips, 'b'), aState(r.clips, 'b2')];+})();++// 9. A HEAD TRIM MAY NOT SLIP THE PICTURE INSIDE ITS OWN SLOT. The lead gap+// used to clamp at zero on its own, so pulling the head open with no room+// moved the in-point while the slot stood still: the tail rippled the wrong+// way and an unlinked sound was left describing a frame that had moved.+out.pairHeadTrimCannotSlip = (() => {+ const cs = unlink(lay([clip({ id: 'a', start: 0, end: 2, duration: 10 }),+ clip({ id: 'b', start: 2, end: 5, film_start: 3,+ film_end: 6, duration: 10 })]), ['b']);+ const q = sbeTrim(cs, 'b', 'l', 1); // 2 s of head wanted, 1 s of room+ return [q.ok, aState(cs, 'b')];+})();+out.pairHeadTrimUsesTheRoomItHas = (() => {+ const cs = unlink(lay([clip({ id: 'a', start: 0, end: 2, duration: 10 }),+ clip({ id: 'b', start: 2, end: 5, film_start: 3,+ film_end: 6, duration: 10 })]), ['b']);+ sbeTrim(cs, 'b', 'l', 2.5); // half the gap+ return aState(cs, 'b');+})();+// ...and against a neighbour there is no room at all, so the handle refuses+// rather than growing the clip out of its far end.+out.pairHeadTrimAgainstANeighbour = (() => {+ const cs = unlink(PAIR(), ['b']);+ const q = sbeTrim(cs, 'b', 'l', 3);+ return [q.ok, q.why, aState(cs, 'b')];+})();++// 10. THE FLAG'S ARITHMETIC. Positive is LATE, the tolerance is half a frame,+// and the label is what both halves print.+out.pairDriftSigns = (() => {+ const early = sbeMoveTo(unlink(PAIR(), ['b']), 'b', 6).clips; // sound early+ const late = sbeAudioEdit(unlink(PAIR(), ['b']), 'b', 'move', 6).clips;+ return [sbeAudioDrift(sbeById(early, 'b')), sbeAudioDrift(sbeById(late, 'b')),+ sbeDriftLabel(sbeAudioDrift(sbeById(early, 'b'))),+ sbeDriftLabel(sbeAudioDrift(sbeById(late, 'b')))];+})();+out.pairInSyncTolerance = (() => {+ const cs = unlink(PAIR(), ['b']);+ const near = sbeAudioEdit(cs, 'b', 'move', 4 + 1 / 96).clips;+ const past = sbeAudioEdit(cs, 'b', 'move', 4 + 1 / 12).clips;+ return [sbeAudioInSync(sbeById(cs, 'b')), sbeAudioInSync(sbeById(near, 'b')),+ sbeAudioInSync(sbeById(past, 'b')),+ sbeAudioInSync(sbeById(PAIR(), 'b'))];+})();+// A LINKED clip is never carried and never flagged: it has no field to write,+// and writing one would unlink it behind the user's back.+out.pairCarryLeavesLinkedAlone = (() => {+ const cs = PAIR();+ sbeTrim(cs, 'a', 'r', 3);+ return [sbeById(cs, 'c').audio === undefined, aState(cs, 'c').drift];+})();++// ---- the boundaries, and a drag as the STREAM of events it really is -----+// Everything above trims INSIDE the source and calls each edit once. Both of+// tonight's arithmetic bugs lived on the other side of exactly those two+// lines.+//+// ASKING FOR MORE HEAD THAN THE TAKE HAS. `start` clamped at the top of the+// source while `film` kept sliding, so the strip's out-point moved left — an+// L-cut that silently shortened the line it was keeping.+out.headTrimPastTheSource = (() => {+ const cs = sbeSetAudioLink(lay([clip({ id: 'a', start: 0, end: 2, duration: 10 }),+ clip({ id: 'b', start: 0.5, end: 2, duration: 10 })]),+ 'b', false).clips;+ const was = sbeClipAudio(sbeById(cs, 'b'));+ const q = sbeAudioEdit(cs, 'b', 'trimL', 1.0);+ const now = sbeClipAudio(sbeById(q.clips, 'b'));+ const far = sbeClipAudio(sbeById(sbeAudioEdit(cs, 'b', 'trimL', 0).clips, 'b'));+ return { wasOut: sbeRound(was.film_start + was.len),+ outAt1: sbeRound(now.film_start + now.len),+ outAt0: sbeRound(far.film_start + far.len),+ start1: now.start, start0: far.start };+})();++// A DRAG IS N POINTERMOVES, NOT ONE. sbeOnMusicMove re-reads the already+// mutated object every event while `want` comes off a fixed anchor, so an+// edit that folds the previous offset back into its answer composes+// differently depending on how fast the mouse was going.+out.musicDragIsFrameRateIndependent = (() => {+ const drive = (audio, steps) => {+ let a = Object.assign({}, audio);+ for (let i = 1; i <= steps; i++) {+ const want = 6 * (i / steps); // same gesture, more events+ a = Object.assign({}, a, sbeMusicEdit(a, 'move', want, 180));+ }+ return sbeMusicWindow(a, 180).film_start;+ };+ const base = { path: '/o/t.wav', duration: 180 };+ return {+ zeroOne: drive(Object.assign({ offset: 0 }, base), 1),+ zeroSix: drive(Object.assign({ offset: 0 }, base), 6),+ headOne: drive(Object.assign({ offset: 10 }, base), 1),+ headSix: drive(Object.assign({ offset: 10 }, base), 6),+ trimSix: drive(Object.assign({ offset: 0, trim_start: 10 }, base), 6),+ };+})();+// ...and a drag that lands where the block already was writes the SAME+// object, so sbeOnMusicUp's changed-test cannot mark a film dirty for a+// gesture nobody can see.+out.musicDragNowhereChangesNothing = (() => {+ const a = { path: '/o/t.wav', duration: 180, offset: 10, trim_start: 10 };+ const at = sbeMusicWindow(a, 180).film_start;+ const q = sbeMusicEdit(a, 'move', at, 180);+ return [q.offset, a.offset, q.trim_start];+})();++// ---- the draft switch, DRIVEN through its refusal ------------------------+// `sbeDraftOp`'s return value is the whole guard: the comment above its+// backup call states the invariant, and the call used to be awaited and+// discarded. With an unanswered offer on screen the backup cannot write, so+// the switch must refuse and nothing may leave the panel.+out.draftSwitchRefusesWhenTheBackupCannotWrite = await (async () => {+ // A REAL write failure, not an unanswered offer: the snapshot POST fails,+ // so the work on screen has nowhere to go and the switch must not proceed.+ SBE.backup = null;+ SBE.dirty = true; SBE.conflict = 0;+ FETCHES = [];+ NEXT = { status: 500, body: { ok: false, error: 'disk is full' } };+ const got = await sbeDraftOp('activate', { slug: 'take-two' });+ const out2 = [got, FETCHES.length, SBE.dirty,+ (toasts[toasts.length - 1] || '').slice(0, 34)];+ SBE.backup = null; SBE.dirty = false; SBE.saveFailed = '';+ els.sbeAlarm.hidden = true;+ return out2;+})();++// ---- undo reads the timeline, not the document --------------------------+// A soundtrack discovered from peaks.json is on the timeline before the+// arrangement was ever cut to it, so a snapshot of `SBE.edit.audio` carried+// null and the first ⌘Z of any clip edit deleted the track.+out.undoKeepsADiscoveredTrack = (() => {+ SBE.clips = lay([clip({ id: 'a' }), clip({ id: 'b' })]);+ SBE.edit = { clips: SBE.clips }; // never auto-edited+ SBE.audio = { path: '/state/track.mp3', offset: 0, peaks: 'peaks.json',+ duration: 180 };+ SBE.undo = []; SBE.redo = []; SBE.dirty = false;+ sbeMutate(cs => sbeTrim(cs, 'a', 'r', 1.5));+ sbeUndo();+ const kept = SBE.audio && SBE.audio.path;+ sbeRedo();+ const after = SBE.audio && SBE.audio.path;+ return [kept || null, after || null, SBE.edit.audio || null];+})();+SBE.clips = []; SBE.edit = {}; SBE.audio = null; SBE.undo = []; SBE.redo = [];+SBE.dirty = false;++// ---- the timeline's own top edge ----------------------------------------+// The clamps, where a dragged pixel lands, and the fact that it survives a+// reload without ever touching the document.+const laneSum = (L) => SBE_TL_CHROME + L.ov + L.track + L.alane + L.wave;+out.tlClamp = {+ under: sbeTlClamp(10, 600),+ over: sbeTlClamp(9000, 600),+ exact: sbeTlClamp(400, 600),+ // A window that has nothing to give pins the handle at the floor rather+ // than handing the monitors a negative height.+ noRoom: sbeTlClamp(400, 0),+ // Nobody may ask for more than the lanes can use, whatever they measured.+ ceiling: sbeTlClamp(9000, 99999),+ junk: sbeTlClamp('kittens', 600),+};+out.lanesAtFloor = sbeLaneHeights(SBE_TL_MIN_H);+out.lanesAtCeiling = sbeLaneHeights(SBE_TL_MAX_H);+out.lanesMid = sbeLaneHeights(SBE_TL_MIN_H + 100);+// EVERY PIXEL IS SPENT: the four lanes plus the box's own chrome are the+// height that was asked for, at the floor, in the middle and at the top.+out.laneSums = [laneSum(out.lanesAtFloor) - SBE_TL_MIN_H,+ laneSum(out.lanesMid) - (SBE_TL_MIN_H + 100),+ laneSum(out.lanesAtCeiling) - SBE_TL_MAX_H];+// Where 100px of drag went, lane by lane.+out.laneGain = {+ ov: out.lanesMid.ov - out.lanesAtFloor.ov,+ track: out.lanesMid.track - out.lanesAtFloor.track,+ alane: out.lanesMid.alane - out.lanesAtFloor.alane,+ wave: out.lanesMid.wave - out.lanesAtFloor.wave,+};+// The picture track caps at 240 long before the sound lanes do; what it+// cannot take has to be OFFERED AGAIN, not dropped on the floor.+out.lanesPastTheTrackCap = sbeLaneHeights(SBE_TL_MIN_H + 340);+out.laneRedistributed = laneSum(out.lanesPastTheTrackCap) - (SBE_TL_MIN_H + 340);+// The ruler never grows: it is a scale, not a surface.+out.rulerFixed = [out.lanesAtFloor.ruler, out.lanesAtCeiling.ruler];++out.tlPref = (() => {+ const seen = {};+ STORE.clear();+ seen.fresh = sbeTlPrefRead(); // nothing stored yet+ sbeTlPrefWrite(392);+ seen.stored = STORE.get('phos_sbe_tl_h');+ seen.restored = sbeTlPrefRead(); // ...as a new tab would read it+ STORE.set('phos_sbe_tl_h', '99999');+ seen.absurd = sbeTlPrefRead();+ STORE.set('phos_sbe_tl_h', 'not-a-height');+ seen.junk = sbeTlPrefRead();+ seen.keys = [...STORE.keys()];+ STORE.clear();+ return seen;+})();+// AND IT IS NOT IN THE DOCUMENT. The save payload is the whole of what the+// server is told; a window height in there would bump the revision on a drag.+out.tlIsNotInTheSave = (() => {+ SBE.tlH = 480; SBE.tlNow = 480;+ const body = JSON.stringify(sbeSaveBody(Object.assign({}, SBE, {+ id: 'sb_t', edit: {}, clips: lay([clip({ id: 'a' })]), expect: 3,+ })));+ SBE.tlH = SBE_TL_MIN_H; SBE.tlNow = SBE_TL_MIN_H;+ return [body.indexOf('tlH'), body.indexOf('480'), body.indexOf('tl_h')];+})();++// ---- the level line, and the heights it has to survive -------------------+// THE 20PX BAND MUST NOT COME BACK. The gain a pointer means is derived from+// the strip's own height, so the round trip has to close at every height the+// share table can produce — not just the one somebody had on screen.+const stripHs = [SBE_TL_MIN_H, SBE_TL_MIN_H + 80, SBE_TL_MIN_H + 180,+ SBE_TL_MAX_H].map(h => sbeLaneHeights(h).alane - 7);+out.stripHeights = stripHs;+out.lvlRoundTrip = (() => {+ const bad = [];+ for (const H of stripHs) {+ for (const g of [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1]) {+ const back = sbeStripGain(200 + sbeStripY(g, H), 200, H);+ if (Math.abs(back - g) > 1e-9) bad.push([H, g, back]);+ }+ }+ return bad;+})();+// The two ends mean what they say at every height: the top of the strip is+// unity and the bottom is silence.+out.lvlEnds = stripHs.map(H => [sbeStripGain(200, 200, H),+ sbeStripGain(200 + H, 200, H)]);+// ...and the middle is NOT hard-coded: at a tall strip, half way down is half.+out.lvlMid = stripHs.map(H => +sbeStripGain(200 + H / 2, 200, H).toFixed(3));+// THE HEADROOM, at the shortest strip the share table can produce. Unity has+// to sit far enough down that the whole 14px target is inside the box —+// "maybe you should put the orange line a little lower so it feels more+// draggable" was a line drawn ON the top edge with most of its target clipped+// away outside it.+out.lvlUnityY = stripHs.map(H => +sbeStripY(1, H).toFixed(2));+out.lvlSilenceGap = stripHs.map(H => +(H - sbeStripY(0, H)).toFixed(2));+// ---- the span of the line the corner handles have NOT taken ---------------+// A flat line across a 400-unit strip: the target starts and ends clear of+// both 22px handles, and its y is the line's own y.+out.lvlHitFlat = sbeLvlHitPath([[0, 1], [4, 1]],+ t => (t / 4) * 400, g => sbeStripY(g, 40),+ SBE_LVL_CLEAR, 400 - SBE_LVL_CLEAR);+// ...and a sloped one, so the cut lands ON the line rather than on a chord+// between whole points: gain 1 -> 0 across the strip, so at x=33 of 400 the+// gain is 1 - 33/400 and the y is that gain's y.+out.lvlHitSloped = sbeLvlHitPath([[0, 1], [4, 0]],+ t => (t / 4) * 400, g => sbeStripY(g, 40),+ SBE_LVL_CLEAR, 400 - SBE_LVL_CLEAR);+out.lvlHitSlopedWant = [+sbeStripY(1 - SBE_LVL_CLEAR / 400, 40).toFixed(2),+ +sbeStripY(SBE_LVL_CLEAR / 400, 40).toFixed(2)];+// A strip with no room between the handles is offered NO target at all: an+// 8px stub of a control is worse than none, and the inspector is the route+// that never depends on width.+out.lvlHitNarrow = sbeLvlHitPath([[0, 1], [4, 1]],+ t => (t / 4) * 70, g => sbeStripY(g, 40),+ SBE_LVL_CLEAR, 70 - SBE_LVL_CLEAR);+// Segments entirely inside a handle's column are dropped, not clamped onto its+// edge — a target that ran to x=0 would be back under the fade handle.+out.lvlHitPoints = sbeLvlHitPath([[0, 1], [0.2, 0.5], [3.8, 0.5], [4, 1]],+ t => (t / 4) * 400, g => sbeStripY(g, 40),+ SBE_LVL_CLEAR, 400 - SBE_LVL_CLEAR);++// ---- "DID THE FILM ACTUALLY CHANGE?" -------------------------------------+// The question `sbeOnTrackUp` asks on every drag, and the one that has twice+// answered "no" over an edit somebody had just made. Every mode that writes a+// field is driven here, so a new mode is checked against the list rather than+// against whichever gesture the list was last written for.+out.dragFp = (() => {+ const base = () => [clip({ id: 'a', end: 4, film_end: 4 }),+ clip({ id: 'b', start: 0, end: 4, film_start: 4, film_end: 8 })];+ const fp = cs => sbeDragFingerprint(cs);+ const moved = (mut) => { const cs = base(); const out2 = mut(cs); return fp(base()) !== fp(out2 || cs); };+ return {+ // Nothing moved: the snapshot is restored and no revision is burned.+ still: fp(base()) === fp(base()),+ // A FADE IS AN EDIT. `mode: 'fade'` writes `fx` and nothing else, so with+ // `fx` off the list the ramp was dragged, painted, and thrown away on+ // pointerup — which is the second half of "I'm not being able to do it".+ fade: moved(cs => sbeSetFade(cs, 'a', 'in', 0.75).clips),+ fadeOut: moved(cs => sbeSetFade(cs, 'a', 'out', 0.4).clips),+ // ...and the three that were already on it stay on it.+ trim: moved(cs => { sbeTrim(cs, 'a', 'r', 3); }),+ move: moved(cs => sbeMoveTo(cs, 'b', 5).clips),+ sound: moved(cs => { cs[0].audio = { start: 0, end: 4, film_start: 0.5 }; }),+ };+})();+// Which strips may be shaped at all — the rule the line, the ghost, the click+// and the inspector all now ask the same way.+out.editable = (() => {+ const mk = o => Object.assign(clip({ id: 'e', end: 3 }), o);+ return {+ linked: sbeStripEditable(mk({ audio: { start: 0, end: 3, film_start: 0, linked: true } })),+ unlinked: sbeStripEditable(mk({ audio: { start: 0, end: 3, film_start: 0, linked: false } })),+ locked: sbeStripEditable(mk({ locked: true, audio: { start: 0, end: 3, film_start: 0, linked: false } })),+ silent: sbeStripEditable(mk({ has_audio: false, audio: { start: 0, end: 3, film_start: 0, linked: false } })),+ nothing: sbeStripEditable(null),+ };+})();+out.legend = sbeKeysLegend();++// ---- the stage's two layers ---------------------------------------------+// OPACITY IS ALSO THE LAYER SWITCH: `.sbe-stage video` and `.sbe-stage+// img.sbe-still` are opacity:0 until one of them wins `.is-on`. A painter that+// writes the ramp onto BOTH turns the hidden one on, and the still — last in+// the stage, backed with #000 — paints a black rectangle over the video. The+// owner reported it as "videos are not loading"; they were loading fine.+out.stage = (() => {+ const V = sbeEl('sbeVideo'), I = sbeEl('sbeStill');+ const SRC = sbeEl('sbeSrcVideo'), SRCI = sbeEl('sbeSrcStill');+ const on = (el) => { V._cls.delete('is-on'); I._cls.delete('is-on');+ if (el) el._cls.add('is-on'); };+ const snap = () => [V.style.opacity, I.style.opacity];+ // One clip, 0-4s on the film, with a one-second fade in.+ let cs = lay([clip({ id: 'a', end: 4 })]);+ const r = sbeSetFade(cs, 'a', 'in', 1);+ SBE.clips = r.ok ? r.clips : cs;+ SBE.curId = 'a';+ const seen = {};+ // 1. the VIDEO is the layer that is showing, half way through the fade+ on(V); SBE.playhead = 0.5; sbeFadePaint();+ seen.videoOnInFade = snap();+ // 2. ...and the STILL is, at the same instant+ on(I); sbeFadePaint();+ seen.stillOnInFade = snap();+ // 3. THE TRANSITION, which is the one that leaves a ghost: the layer that+ // was carrying a ramp has to be handed back to the stylesheet when it+ // stops being the layer that is showing.+ seen.videoAfterHandover = V.style.opacity;+ // 4. past the fade, the on layer is fully up+ on(V); SBE.playhead = 2; sbeFadePaint();+ seen.outsideFade = snap();+ // 5. nothing at the playhead at all+ SBE.clips = []; SBE.curId = ''; SBE.playhead = 9; sbeFadePaint();+ seen.noClip = snap();+ // 6. neither layer showing — nothing may be written to either+ on(null); sbeFadePaint();+ seen.neitherOn = snap();+ // 7. the SOURCE monitor's layers are not this painter's business+ seen.sourceUntouched = [SRC.style.opacity === undefined,+ SRCI.style.opacity === undefined];+ SBE.clips = []; SBE.curId = ''; SBE.playhead = 0;+ return seen;+})();++// The sibling layer, for contrast: the overlay's switch is DISPLAY, so its+// opacity is free to be a ramp and nothing it writes can turn it on.+out.overlayLayer = (() => {+ const el = sbeEl('sbeOvLayer');+ SBE.overlays = [{ id: 'o1', path: '/o/card.png', film_start: 0, film_end: 4,+ fx: { fade_in: 1 } }];+ SBE.playhead = 0.5;+ sbeOvPaint();+ const during = [el.style.opacity, el._cls.has('is-on')];+ SBE.overlays = [];+ sbeOvPaint();+ const after = [el.style.opacity, el._cls.has('is-on')];+ SBE.playhead = 0;+ return { during: during, after: after };+})();++process.stdout.write(JSON.stringify(out));+"""+++def run_contract() -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ source = panel_source()+ script = (SHIM+ + "\n".join(extract_function(n, source) for n in FUNCTIONS)+ + "\n(async () => {\n" + BODY + "\n})();\n")+ 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 TimelineClient(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()++ # ---- the waveform ----------------------------------------------------+ def test_peaks_decode_interleaved_int16_over_the_scale(self):+ p = self.r["peaks"]+ self.assertEqual(p["count"], 3)+ self.assertEqual([round(v, 4) for v in p["lo"]], [-1.0, 0.0, -0.252])+ self.assertEqual([round(v, 4) for v in p["hi"]], [1.0, 0.5039, 0.252])+ self.assertEqual(p["rate"], 100)++ def test_a_peaks_file_that_lies_about_its_count_does_not_read_off_the_end(self):+ self.assertEqual(self.r["peaksJunk"]["count"], 1)+ self.assertIsNone(self.r["peaksNone"])++ # ---- the beat grid ---------------------------------------------------+ def test_the_grid_carries_beats_and_marks_downbeats(self):+ self.assertEqual(self.r["grid"][:3],+ [[0, True], [0.5, False], [1, False]])+ self.assertIn([2, True], self.r["grid"])+ self.assertEqual(len(self.r["grid"]), 9)++ def test_the_grid_is_NEVER_extrapolated_past_the_fitted_span(self):+ # beat_map fits ONE tempo across a span because real tracks drift.+ # A line past that span is a confident wrong answer, so there is none.+ self.assertEqual(self.r["gridPastSpan"], 0)++ def test_the_grid_is_clipped_to_the_window_being_drawn(self):+ self.assertEqual(self.r["gridWindow"], [1, 1.5, 2])++ def test_an_audio_offset_shifts_the_grid_into_film_time(self):+ self.assertEqual(self.r["gridOffset"][0], -1)++ def test_a_weak_grid_is_flagged_as_a_guess(self):+ self.assertFalse(self.r["guess"])+ self.assertTrue(self.r["guessLow"])++ # ---- snap ------------------------------------------------------------+ def test_snap_catches_a_beat_inside_the_tolerance(self):+ self.assertEqual(self.r["snapCatches"], 1.5)++ def test_snap_leaves_a_time_that_is_not_near_a_beat_alone(self):+ self.assertEqual(self.r["snapLeaves"], 1.2)++ def test_the_override_is_a_straight_bypass(self):+ self.assertEqual(self.r["snapOff"], 1.44)++ def test_a_downbeat_wins_a_tie(self):+ self.assertEqual(self.r["snapPrefersDownbeat"], 2)++ def test_snap_past_the_span_is_a_no_op_not_an_invented_beat(self):+ self.assertEqual(self.r["snapPastSpan"], 9.9)++ # ---- layout ----------------------------------------------------------+ def test_the_film_slot_is_derived_from_the_source_window_every_time(self):+ self.assertTrue(self.r["packedLengths"])+ self.assertEqual(self.r["packed"],+ [["a", 0, 2, 0, 2], ["b", 0, 3, 2, 5], ["c", 0, 1.5, 5, 6.5]])++ def test_a_hole_survives_the_round_trip(self):+ self.assertEqual(self.r["holeKept"],+ [["a", 0, 2, 0, 2], ["b", 0, 3, 5, 8]])+ self.assertEqual(self.r["holes"], [[2, 5, 3]])+ self.assertEqual(self.r["duration"], 8)++ def test_clip_lookup_answers_honestly_over_a_hole(self):+ self.assertEqual(self.r["clipAt"], "b")+ self.assertIsNone(self.r["clipInHole"])++ # ---- move ------------------------------------------------------------+ def test_a_move_reorders_and_everything_after_it_slides(self):+ self.assertEqual(self.r["moveToHead"],+ [["c", 0, 1.5, 0, 1.5], ["a", 0, 2, 1.5, 3.5],+ ["b", 0, 3, 3.5, 6.5]])+ self.assertTrue(self.r["moveLengths"])+ self.assertTrue(self.r["moveNoOverlap"])++ def test_a_moved_clip_is_stamped_human(self):+ # The server keeps the other end of this promise: a re-plan can leave a+ # human's cut alone precisely because it is labelled.+ self.assertEqual(self.r["moveMarksHuman"], "human")++ def test_a_clip_dropped_into_open_air_keeps_the_hole_it_opened(self):+ self.assertEqual(self.r["moveOpensHole"],+ [["a", 0, 2, 0, 2], ["b", 0, 3, 6, 9]])++ def test_a_locked_clip_refuses_to_move(self):+ self.assertFalse(self.r["moveLocked"]["ok"])+ self.assertEqual(self.r["moveLocked"]["why"], "locked")+ self.assertEqual(self.r["moveLocked"]["shape"][0], ["a", 0, 2, 0, 2])++ def test_the_flow_goes_AROUND_a_locked_clip_never_through_it(self):+ self.assertEqual(self.r["anchored"],+ [["a", 0, 2, 0, 2], ["L", 0, 2, 3, 5], ["b", 0, 4, 5, 9]])+ self.assertTrue(self.r["anchoredNoOverlap"])++ # ---- trim ------------------------------------------------------------+ def test_the_right_handle_changes_the_length_and_ripples_the_tail(self):+ self.assertEqual(self.r["trimRight"],+ [["a", 0, 1.25, 0, 1.25], ["b", 0, 3, 1.25, 4.25]])+ self.assertTrue(self.r["trimRightLengths"])++ def test_the_left_handle_moves_the_in_point_and_leaves_the_tail_alone(self):+ self.assertEqual(self.r["trimLeft"],+ [["a", 0, 2, 0, 2], ["b", 0.5, 3, 2.5, 5]])+ self.assertTrue(self.r["trimLeftLengths"])++ def test_a_trim_cannot_run_past_the_end_of_its_source(self):+ self.assertEqual(self.r["trimClampedToSource"], [["a", 0, 2.4, 0, 2.4]])++ def test_a_trim_cannot_collapse_a_clip_to_nothing(self):+ self.assertEqual(self.r["trimClampedToMin"], [["a", 1.8, 2, 1.8, 2]])++ def test_a_locked_clip_refuses_to_trim(self):+ self.assertEqual(self.r["trimLocked"], "locked")++ # ---- ripple + split --------------------------------------------------+ def test_ripple_delete_pulls_everything_after_it_up(self):+ self.assertEqual(self.r["ripple"],+ [["a", 0, 2, 0, 2], ["c", 0, 1.5, 2, 3.5]])+ self.assertTrue(self.r["rippleLengths"])++ def test_a_locked_clip_refuses_to_be_deleted(self):+ self.assertEqual(self.r["rippleLocked"], "locked")++ def test_split_makes_two_clips_that_still_add_up(self):+ self.assertEqual(self.r["split"],+ [["a", 0, 1.2, 0, 1.2], ["a2", 1.2, 2, 1.2, 2],+ ["b", 0, 3, 2, 5]])+ self.assertTrue(self.r["splitLengths"])+ self.assertEqual(self.r["splitHuman"], ["human", "human", "auto"])++ def test_split_refuses_where_it_would_make_a_blink(self):+ self.assertFalse(self.r["splitTooClose"])++ def test_split_over_a_hole_is_an_honest_no(self):+ self.assertFalse(self.r["splitInHole"])++ # ---- placing ---------------------------------------------------------+ def test_a_generated_clip_lands_in_the_hole_it_was_ordered_for(self):+ self.assertEqual(self.r["placed"][1],+ ["/o/new.mp4", 2.5, 5.5, "human"])+ self.assertTrue(self.r["placedNoOverlap"])++ def test_filling_a_hole_does_NOT_move_the_film_after_it(self):+ # Every other operation ripples. This one must not: the shot was+ # generated for this slot so the cuts around it stay on their beats.+ self.assertEqual(self.r["filled"],+ [["a.mp4", 0, 2], ["fill.mp4", 3, 6], ["b.mp4", 9, 11]])++ def test_a_clip_too_long_for_its_hole_pushes_rather_than_overlaps(self):+ self.assertEqual(self.r["overfilled"],+ [["a.mp4", 0, 2], ["big.mp4", 2, 6], ["b.mp4", 6, 8]])+ self.assertTrue(self.r["overfilledNoOverlap"])++ # ---- undo ------------------------------------------------------------+ def test_undo_and_redo_walk_the_arrangement_back_and_forward(self):+ self.assertEqual([c[0] for c in self.r["afterMutate"]], ["b"])+ self.assertEqual([c[0] for c in self.r["afterUndo"]], ["a", "b"])+ self.assertEqual([c[0] for c in self.r["afterRedo"]], ["b"])+ self.assertEqual([c[0] for c in self.r["undoFloor"]], ["a", "b"])+ self.assertTrue(self.r["dirtyAfterMutate"])++ def test_a_refused_edit_writes_no_undo_step(self):+ self.assertEqual(self.r["refusedNoUndo"], 0)++ # ---- save ------------------------------------------------------------+ def test_the_save_body_is_the_shape_the_route_documents(self):+ b = self.r["saveBody"]+ self.assertEqual(sorted(b.keys()), ["edit", "expect_revision", "id"])+ self.assertEqual(b["expect_revision"], 4)+ self.assertEqual(b["edit"]["board_id"], "sb_t")+ self.assertEqual(b["edit"]["clips"][0]["source"], "human")+ self.assertEqual(b["edit"]["beats"]["bpm"], 120)++ def test_client_only_bookkeeping_never_reaches_disk(self):+ self.assertEqual(self.r["saveStrippedPrivate"], [])++ def test_expect_revision_is_omitted_rather_than_sent_as_null(self):+ self.assertNotIn("expect_revision", self.r["saveNoExpect"])++ def test_every_error_is_pinned_to_the_clip_that_caused_it(self):+ m = self.r["errMap"]+ self.assertEqual(list(m["byId"].keys()), ["b"])+ self.assertEqual(m["byId"]["b"][0]["code"], "clip_window")+ self.assertEqual(m["doc"][0]["code"], "version")++ def test_a_409_keeps_the_arrangement_and_says_who_won(self):+ self.assertFalse(self.r["saveConflict"])+ a = self.r["afterConflict"]+ self.assertEqual([c[0] for c in a["clips"]], ["a", "b"])+ self.assertTrue(a["dirty"]) # still unsaved, still on screen+ self.assertEqual(a["conflict"], 7)+ self.assertEqual(a["revision"], 3) # NOT quietly advanced+ self.assertTrue(a["banner"])++ def test_keep_mine_is_the_only_path_that_drops_expect_revision(self):+ self.assertTrue(self.r["forced"])+ self.assertNotIn("expect_revision", self.r["forcedBody"])+ self.assertEqual(self.r["afterForced"]["revision"], 8)+ self.assertFalse(self.r["afterForced"]["dirty"])++ def test_a_400_keeps_the_work_and_flags_the_clip(self):+ self.assertFalse(self.r["saveInvalid"])+ a = self.r["afterInvalid"]+ self.assertEqual([c[0] for c in a["clips"]], ["a", "b"])+ self.assertTrue(a["dirty"])+ self.assertEqual(a["flagged"], ["b"])++ def test_a_good_save_never_replaces_the_clips_under_the_users_hands(self):+ self.assertTrue(self.r["saveOk"])+ a = self.r["afterOk"]+ self.assertEqual([c[0] for c in a["clips"]], ["a"])+ self.assertFalse(a["dirty"])+ self.assertEqual(a["revision"], 9)+ self.assertEqual(a["unplaced"], 1)++ def test_times_are_printed_the_way_a_person_reads_them(self):+ self.assertEqual(self.r["fmt"], ["0:00.00", "0:09.50", "1:15.25"])++ # ---- WAVE 2: the three kinds -----------------------------------------+ def test_an_absent_kind_is_a_video_and_nonsense_is_too(self):+ # This is the whole v1 migration, on the client. Every clip in every+ # edit.json written before today has no `kind`; reading the default+ # rather than stamping it is what makes those documents correct the+ # moment they load, with nothing rewritten.+ self.assertEqual(self.r["kinds"],+ ["video", "still", "slug", "video", "video"])++ def test_brightness_is_clamped_on_the_way_out_of_a_clip(self):+ # The same clamp the validator enforces on the way in. A slider that+ # could ask for a value the server refuses is a slider that produces a+ # red error box instead of a picture.+ self.assertEqual(self.r["bright"], [0, 0, 0.2, 0.5, -0.5, 0])++ def test_the_css_preview_matches_ffmpeg_at_mid_grey(self):+ # ffmpeg's eq=brightness is ADDITIVE; CSS brightness() is+ # MULTIPLICATIVE, and CSS has no additive form. They are matched where+ # a person judges exposure — mid-grey — and the drift at the ends is+ # why the strip says the preview is approximate.+ self.assertEqual(self.r["brightCss"], [1, 1.5, 2, 0, 0])+ lo, hi = self.r["brightCssMidGrey"]+ self.assertAlmostEqual(lo, hi, places=6)++ def test_setting_brightness_back_to_zero_removes_the_field(self):+ self.assertTrue(self.r["setBrightOk"])+ self.assertEqual(self.r["setBrightValue"], 0.3)+ self.assertEqual(self.r["setBrightHuman"], "human")+ self.assertEqual(self.r["setBrightClamped"], 0.5)+ # NEUTRAL IS ABSENT, exactly as normalise_edit writes it. Otherwise+ # every clip anybody ever selected carries a dead field forever.+ self.assertFalse(self.r["setBrightCleared"])+ self.assertFalse(self.r["setBrightNoop"]) # no undo step for a no-op+ self.assertEqual(self.r["setBrightGone"], "gone")++ def test_the_save_payload_synthesises_a_still_and_a_slug_the_servers_way(self):+ v, still, slug = self.r["kindPayload"]+ # A video keeps its window, its source duration and its grade, and+ # carries NO kind — absent is video, on the wire as well as on disk.+ self.assertNotIn("kind", v)+ self.assertEqual(v["adjust"], {"brightness": 0.25})+ self.assertEqual(v["dur"], 10)+ # A still is its slot: start 0, end = the hold, no source duration to+ # clamp the trim that is the only way to change it.+ self.assertEqual(still["kind"], "still")+ self.assertEqual((still["start"], still["end"]), (0, 3))+ self.assertIsNone(still["dur"])+ # A slug has no file at all, and a neutral grade is dropped.+ self.assertEqual(slug["kind"], "slug")+ self.assertIsNone(slug["path"])+ self.assertEqual((slug["start"], slug["end"]), (0, 1.5))+ self.assertNotIn("adjust", slug)++ # ---- WAVE 2: the drop maths ------------------------------------------+ def test_a_drop_lands_by_the_midpoint_rule(self):+ # Left half of a clip means before it, right half means after — the+ # rule every NLE uses, and the only reading that makes a drop exactly+ # on a boundary unambiguous.+ self.assertEqual(self.r["dropIdx"], [0, 0, 1, 1, 2, 3])+ self.assertEqual(self.r["dropIdxEmpty"], 0)++ def test_inserting_ripples_the_film_but_filling_a_hole_does_not(self):+ # Both behaviours are right and they are different verbs. A shot+ # generated for a hole must not move the cuts around it; a clip+ # dropped BETWEEN two others must, or the drop silently overwrites+ # whatever it landed on.+ self.assertEqual(self.r["insertRipple"],+ [["a", 0, 2], ["NEW", 2, 3], ["b", 3, 5]])+ self.assertTrue(self.r["insertLengths"])+ self.assertTrue(self.r["insertNoOverlap"])+ self.assertEqual(self.r["insertHuman"], "human")+ # …and the un-rippled counterpart is still un-rippled.+ self.assertEqual(self.r["filled"],+ [["a.mp4", 0, 2], ["fill.mp4", 3, 6], ["b.mp4", 9, 11]])++ def test_a_slug_arrives_with_no_path_and_no_source_duration(self):+ slug = self.r["insertSlug"]+ self.assertEqual(slug["kind"], "slug")+ self.assertIsNone(slug["path"])+ self.assertIsNone(slug["dur"]) # nothing for the trim to clamp to+ self.assertEqual(slug["len"], 2.5)+ self.assertTrue(self.r["insertSlugNoOverlap"])++ def test_a_still_is_resized_by_the_ordinary_trim_handles(self):+ still = self.r["insertStill"]+ self.assertEqual(still["kind"], "still")+ self.assertIsNone(still["dur"])+ self.assertEqual(still["at"], [0, 3])+ # No source clock means nothing to run out of: dragging the handle to+ # 9 s gives 9 s, where a video would have clamped at its own length.+ self.assertEqual(self.r["stillStretched"], 9)++ # ---- WAVE 2: reorder --------------------------------------------------+ def test_reorder_closes_the_hole_it_leaves_and_keeps_the_films_length(self):+ self.assertEqual(self.r["reorderIds"], ["c", "a", "b"])+ self.assertEqual(self.r["reorder"],+ [["c", 0, 1, 0, 1], ["a", 0, 2, 1, 3],+ ["b", 0, 3, 3, 6]])+ self.assertTrue(self.r["reorderLengths"])+ self.assertTrue(self.r["reorderNoOverlap"])+ self.assertEqual(self.r["reorderKeepsLength"], 6)+ self.assertEqual(self.r["reorderHuman"], "human")++ def test_reorder_refuses_a_locked_clip_and_a_missing_one(self):+ self.assertEqual(self.r["reorderLocked"], "locked")+ self.assertEqual(self.r["reorderGone"], "gone")++ def test_move_and_reorder_are_different_verbs_on_purpose(self):+ # A move puts a clip at a TIME and leaves a hole behind it — which is+ # the hole the generate control fills. A reorder puts it at a POSITION+ # and closes that hole. Shift picks; neither can be inferred.+ self.assertEqual(self.r["moveLeavesAHole"], [["b", 0], ["c", 2], ["a", 9]])++ # ---- the zoom slider's floor ----------------------------------------+ def test_the_zoom_floor_puts_the_WHOLE_film_in_the_window(self):+ # The defect this is the gate for: "when you get to the 36 seconds,+ # you cannot scroll." At 42 px/sec the owner's 71.6s film drew a+ # 3031px inner inside a 1108px box. The slider's left end is now+ # whatever px/sec makes that inner fit, so "all of it" is always one+ # drag away — and it is computed from the LIVE box, not a constant.+ self.assertAlmostEqual(self.r["fit"], 15.1432, places=3)+ self.assertTrue(self.r["fitFitsTheBox"])+ self.assertLessEqual(self.r["fitWidth"], 1108)++ def test_the_fit_survives_an_empty_film_and_an_unpainted_box(self):+ # Both of these are real states: a document with no clips, and the+ # first paint before the column has a width. Neither may produce a+ # zero, an infinity or a NaN, because the result is stored in SBE.pps+ # and every pixel on the track is multiplied by it.+ self.assertAlmostEqual(self.r["fitEmptyFilm"], 1084.0, places=1)+ self.assertGreater(self.r["fitNarrow"], 0)+ self.assertLess(self.r["fitNarrow"], 2)++ def test_the_slider_is_logarithmic_and_round_trips(self):+ lo, hi = self.r["sliderEnds"]+ self.assertAlmostEqual(lo, 15.14, places=2) # the fit+ self.assertAlmostEqual(hi, 200.0, places=2) # the ladder's top+ self.assertEqual(self.r["sliderRound"], [0, 250, 500, 750, 1000])+ self.assertEqual(self.r["sliderClamps"], [0, 1000])+ # Linear would put the whole useful range in the first fifth of the+ # travel: the arithmetic midpoint is 107 px/sec, the geometric one 55.+ self.assertLess(self.r["sliderMidIsNotArithmeticMean"], 80)++ # ---- zoom keeps the picture still ------------------------------------+ def test_zooming_holds_the_playhead_exactly_where_it_was(self):+ # The one thing nobody can check by eye and everybody notices: after+ # a zoom the frame you were looking at is under the same pixel.+ self.assertEqual(self.r["anchorOnPlayhead"], [36, 400])+ self.assertEqual(self.r["zoomHoldsThePlayhead"], 400)++ def test_a_playhead_off_screen_anchors_on_the_middle_of_the_view(self):+ # There is no frame on screen to hold, and lurching to one that is not+ # visible is worse than holding what the user is looking at.+ t, px = self.r["anchorFallsBackToTheMiddle"]+ self.assertAlmostEqual(t, 727.48, places=1)+ self.assertEqual(px, 554) # half of 1108++ def test_alt_wheel_anchors_on_the_time_under_the_pointer(self):+ self.assertEqual(self.r["anchorExplicit"][0], 30)++ def test_the_zoom_scroll_is_clamped_to_what_there_is_to_scroll(self):+ self.assertEqual(self.r["zoomScrollClamps"], [0, 5000])++ # ---- follow PAGES, it does not chase ---------------------------------+ def test_the_view_does_not_move_while_the_playhead_is_on_screen(self):+ # This early return is what stops the follow writing scrollLeft sixty+ # times a second and fighting the user's own panning.+ self.assertEqual(self.r["followStaysPut"], 0)++ def test_crossing_the_right_edge_pages_forward_ONCE(self):+ # Resolve's behaviour: one jump, the head lands near the left of a+ # fresh screenful, and the next frame moves nothing.+ self.assertAlmostEqual(self.r["followPages"], 1547.04, places=1)+ self.assertAlmostEqual(self.r["followLead"], 133.0, places=0)+ self.assertTrue(self.r["followSettled"])++ def test_the_follow_clamps_at_both_ends_of_the_film(self):+ self.assertEqual(self.r["followBack"], 0)+ self.assertEqual(self.r["followClampsHead"], 0)+ self.assertEqual(self.r["followClampsTail"], 4000)++ # ---- the monitor row -------------------------------------------------+ def test_the_two_monitors_fill_the_width_at_1440x900(self):+ # MEASURED, not assumed: 1110px of column and 307px of free height,+ # read off the Editor's own tab with the carwash film open. The whole+ # point of this pass is that the row leaves no black gutter, so the+ # first assertion is that the parts add up to the whole.+ f = self.r["fit1440"]+ self.assertTrue(f["fills"])+ self.assertEqual(f["prog"], [524, 295])+ self.assertEqual(f["src"], [350, 197])+ self.assertEqual(f["rail"], 212)+ self.assertEqual(f["progAspect"], 1.778)+ self.assertEqual(f["srcAspect"], 1.778)+ self.assertEqual(f["split"], 40)+ self.assertTrue(f["programIsBigger"])+ self.assertTrue(f["withinBudget"])++ def test_the_two_monitors_fill_the_width_at_1900x1000(self):+ f = self.r["fit1900"]+ self.assertTrue(f["fills"])+ self.assertEqual(f["split"], 40)+ self.assertTrue(f["programIsBigger"])+ self.assertTrue(f["withinBudget"])+ self.assertGreaterEqual(f["rail"], 200)+ self.assertLessEqual(f["rail"], 380)++ def test_a_tall_window_gives_the_leftover_HEIGHT_to_the_timeline(self):+ # When the width binds first the pair takes the width-derived height+ # at exactly 40/60 and stops. What is left over vertically is the+ # track's — `.sbe-tl` is the one row with flex-grow — which is why a+ # tall window gets a taller track instead of a dead band under the+ # sticky action bar.+ f = self.r["fitTall"]+ self.assertTrue(f["fills"])+ self.assertAlmostEqual(f["ratio"], 0.667, places=2)+ self.assertGreater(f["leftoverHeight"], 100)++ def test_a_short_window_widens_the_SOURCE_and_never_past_the_program(self):+ # Filling the row matters more than the exact split — a symmetric+ # black gutter is the bug — but the program is the thing being cut+ # and never becomes the smaller of the two.+ f = self.r["fitShort"]+ self.assertLessEqual(f["ratio"], 1.0)+ self.assertTrue(f["programIsBigger"])++ def test_the_picture_has_a_floor_and_the_rail_has_both(self):+ self.assertEqual(self.r["fitFloor"], 120)+ self.assertEqual(self.r["railClamps"][0], 380) # never a second sidebar+ self.assertGreaterEqual(self.r["railClamps"][1], 200) # never a slot+++class TimelineMusic(unittest.TestCase):+ """Wave 4 — the soundtrack is a first-class object on the timeline."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()++ def test_an_untrimmed_track_is_the_whole_track_at_film_zero(self):+ head, tail, fs, fe, trimmed = self.r["musicPlain"]+ self.assertEqual([head, tail, fs, fe], [0, 60, 0, 60])+ self.assertFalse(trimmed)++ def test_a_positive_offset_is_a_head_trim(self):+ # It has meant "the track second that plays at film 0" since before+ # the editor existed, and every edit.json on disk relies on that.+ self.assertEqual(self.r["musicOffsetIn"], [5, 0, 55])++ def test_a_negative_offset_starts_the_music_inside_the_film(self):+ # The direction the old `max(0, …)` clamp made unreachable, and half+ # of "back and forth however you want".+ self.assertEqual(self.r["musicOffsetOut"], [0, 4, 64])++ def test_trims_are_track_seconds_and_a_head_trim_does_not_ripple(self):+ head, tail, fs, fe, trimmed = self.r["musicTrimmed"]+ self.assertEqual([head, tail, fs, fe], [10, 20, 10, 20])+ self.assertTrue(trimmed)++ def test_no_soundtrack_is_not_a_crash(self):+ self.assertEqual(self.r["musicNone"], [0, None])++ def test_a_move_writes_the_offset_and_leaves_the_window_alone(self):+ offset, ts, te = self.r["musicMove"]+ self.assertEqual([ts, te], [10, 20])+ self.assertEqual(offset, 3) # head 10 landing at film 7+ self.assertEqual(self.r["musicMoveLands"], 7)+ self.assertEqual(self.r["musicMoveHome"], 0)++ def test_trimming_the_left_edge_leaves_the_rest_where_it_was(self):+ offset, ts, te = self.r["musicTrimL"]+ self.assertEqual([offset, ts, te], [0, 12, None])+ # The seconds a head trim removes come back as silence in front — the+ # music that is left does NOT slide earlier.+ self.assertEqual(self.r["musicTrimLKeepsPlace"], 12)++ def test_neither_edge_can_cross_the_other_or_the_track(self):+ self.assertAlmostEqual(self.r["musicTrimLClamped"], 5.5, places=6)+ self.assertEqual(self.r["musicTrimLFloor"], 0)+ self.assertEqual(self.r["musicTrimR"], 42)+ self.assertEqual(self.r["musicTrimRClamped"], 60)+ self.assertAlmostEqual(self.r["musicTrimRFloor"], 30.5, places=6)++ def test_the_music_snaps_to_the_cuts_and_never_to_its_own_beat_grid(self):+ self.assertEqual(self.r["musicSnaps"], [0, 0, 2, 2, 4])+ self.assertEqual(self.r["musicSnapCatches"], 2)+ self.assertEqual(self.r["musicSnapIgnoresFar"], 3)+ self.assertEqual(self.r["musicSnapOverride"], 2.04)++ # ---- the scroller ----------------------------------------------------+ def test_the_timeline_runs_past_the_last_frame(self):+ # 4 s of film, so the slack is the 3 s floor — but the span floor for+ # a nearly-empty timeline wins, and either way there is track out+ # past the final cut to drag the music onto.+ self.assertGreater(self.r["spanShortFilm"], 4)+ self.assertGreaterEqual(self.r["spanShortFilm"], 10)++ def test_an_empty_timeline_still_has_a_ruler(self):+ self.assertEqual(self.r["spanEmpty"], 10)++ def test_music_placed_past_the_clips_extends_the_scroller(self):+ # 30 s of track starting 20 s into a 4 s film ends at 50 s, and the+ # timeline has to reach it or it could never have been dragged there.+ self.assertGreaterEqual(self.r["spanFollowsMusic"], 50)++ def test_the_slack_is_capped(self):+ # 300 s of film: 15 % would be 45 s of empty track on open.+ self.assertEqual(self.r["spanLongFilm"], 315)++ def test_undo_carries_the_music_and_still_accepts_the_old_shape(self):+ self.assertEqual(self.r["undoRestoresMusic"], 0)+ n, first, offset = self.r["undoLegacyShape"]+ self.assertEqual([n, first], [1, "z"])+ self.assertEqual(offset, 0) # a clip snapshot leaves audio++ def test_one_undo_does_not_delete_a_soundtrack_nobody_edited(self):+ # `sbeFetchPeaks` fills SBE.audio and deliberately does NOT touch the+ # document, so on a film that was Prepared but never auto-edited the+ # snapshot carried null — and one ⌘Z of any clip edit hid the music+ # block, silenced the preview bed, and put the same null on the redo+ # stack so redo could not undo the undo.+ kept, after, doc = self.r["undoKeepsADiscoveredTrack"]+ self.assertEqual(kept, "/state/track.mp3")+ self.assertEqual(after, "/state/track.mp3")+ # ...and it is still not in the document: an undo must not be what+ # saves a soundtrack the arrangement was never cut to.+ self.assertIsNone(doc)++ def test_a_music_drag_lands_in_the_same_place_however_fast_the_mouse_is(self):+ # `out.offset = head - want` folded the PREVIOUS offset back into its+ # own answer, and a pointermove stream re-reads the mutated object+ # every event. On a positive-offset document the same six-second drag+ # landed at film 6 as six events and did not move the block at all as+ # one.+ d = self.r["musicDragIsFrameRateIndependent"]+ for key in ("zeroOne", "zeroSix", "headOne", "headSix", "trimSix"):+ self.assertAlmostEqual(d[key], 6, places=6, msg=key)++ def test_a_drag_that_moves_nothing_writes_nothing(self):+ # sbeOnMusicUp decides "did anything change" by comparing the three+ # fields, and `offset` used to change even when the block did not — so+ # a nudge that ended where it started marked the film dirty, burned an+ # undo step and queued a write.+ got, was, ts = self.r["musicDragNowhereChangesNothing"]+ self.assertEqual(got, was)+ self.assertEqual(ts, 10)+++class SavingCannotFailQuietly(unittest.TestCase):+ """The twenty minutes the owner lost, as a gate.++ edit.json sat frozen on disk while he kept cutting, and the only thing on+ screen that knew was a small grey chip reading "not saved". Two defects+ made it possible — a save that arrived mid-flight was DROPPED, and the+ in-flight flag could stick after a throw — and one made it survivable for+ twenty minutes: the autosave's failure branch was silent by design.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_a_save_that_arrives_mid_flight_is_remembered(self):+ # ...AS THE KIND OF WRITE IT WAS. `sbeQueueSave` no longer saves — it+ # schedules a crash backup — so remembering the dropped save as a bare+ # `true` and re-queuing through that lane turned the second of two+ # rapid Save presses into a backup write, with edit.json left at the+ # older revision and the alarm reading clear.+ self.assertEqual(self.r["midFlightRemembered"], "backup")+ self.assertEqual(self.r["midFlightRemembersASave"], "save")+ fn = extract_function("sbeSave", self.src)+ self.assertIn("finally", fn)+ self.assertIn("if (again === 'save') sbeSave(quiet, force);", fn)++ def test_the_in_flight_flag_cannot_stick_after_a_throw(self):+ self.assertFalse(self.r["flagClearedAfterThrow"])+ raised, hidden, kind = self.r["throwRaisesAlarm"]+ self.assertTrue(raised)+ self.assertFalse(hidden)+ self.assertEqual(kind, "alarm")++ def test_a_failing_autosave_is_loud_even_though_nobody_asked(self):+ raised, hidden, why, kind = self.r["quietFailureIsLoud"]+ self.assertTrue(raised)+ self.assertFalse(hidden)+ self.assertIn("disk is full", why)+ self.assertEqual(kind, "alarm")++ def test_a_conflict_is_a_failure_to_store_and_says_so(self):+ raised, hidden = self.r["conflictIsLoud"]+ self.assertTrue(raised)+ self.assertFalse(hidden)++ def test_a_save_that_lands_takes_the_alarm_down(self):+ raised, hidden, dirty_at, dirty, kind = self.r["successClearsAlarm"]+ self.assertFalse(raised)+ self.assertTrue(hidden)+ self.assertEqual(dirty_at, 0)+ self.assertFalse(dirty)+ self.assertEqual(kind, "saved")++ # ---- the crash lane, as a sequence -----------------------------------+ def test_the_lane_keeps_writing_while_an_offer_is_open(self):+ # It used to refuse: one backup file per draft, so a new write would+ # have destroyed the work the offer held. The cure was worse — a chip+ # nobody dismissed switched the safety net off for the rest of the+ # session, silently. The lane is versioned now (one file per snapshot,+ # pruned), so a new snapshot cannot eat an old one.+ wrote, fetches, stamped = self.r["backupWritesEvenWithAnOfferOpen"]+ self.assertTrue(wrote)+ self.assertEqual(fetches, 1)+ self.assertTrue(stamped)++ def test_a_save_answers_the_offer_and_repaints_the_bar(self):+ # THE BUG THIS IS FOR: the ok branch cleared `dirty` and the alarm and+ # left `SBE.backup` set, so the amber bar stayed on screen over a saved+ # film with a "Recover it" button that would have reverted the save.+ backup, repainted, drafts = self.r["saveAnswersTheOffer"]+ self.assertIsNone(backup)+ self.assertTrue(repainted)+ self.assertEqual(drafts, 1) # ...and the drafts rows are refreshed++ def test_the_backup_lane_is_alive_again_after_a_save(self):+ # The compound failure: with the offer never answered, every later+ # backup no-opped, `backedUpAt` stayed 0, and the twelve-second+ # watchdog raised the red NOT SAVED alarm on a healthy panel.+ wrote, fetches, stamped = self.r["backupLivesAfterASave"]+ self.assertTrue(wrote)+ self.assertEqual(fetches, 1)+ self.assertTrue(stamped)++ def test_the_backup_says_which_draft_it_was_composed_from(self):+ self.assertEqual(self.r["backupNamesItsDraft"], "draft-1")++ def test_a_backup_that_does_not_land_raises_the_alarm(self):+ wrote, raised = self.r["backupFailureIsLoud"]+ self.assertFalse(wrote)+ self.assertTrue(raised)++ def test_an_autoplay_refusal_never_becomes_a_stored_preference(self):+ # The second way the Editor could go permanently silent: Chrome+ # declines an unmuted play(), the editor mutes itself so the picture+ # still runs (right call) — and then WROTE that to localStorage, so one+ # refusal silenced clips AND soundtrack across every later reload.+ fn = extract_function("sbeSetMute", self.src)+ self.assertIn("remember !== false", fn)+ self.assertIn("localStorage.setItem('sbeMuted'", fn)+ for site in ("sbePlay", "sbeSrcPlay"):+ body = extract_function(site, self.src)+ if "browser blocked sound" not in body:+ continue+ self.assertIn("'browser blocked sound — click \u1f50a to unmute'"+ .replace("\u1f50a", "\U0001f50a"), body + body)+ # Neither refusal site may persist it.+ self.assertEqual(self.src.count(+ "sbeSetMute(true, 'browser blocked sound — click \U0001f50a to unmute')"), 0)+ self.assertEqual(self.src.count(+ "sbeSetMute(true, 'browser blocked sound — click \U0001f50a to unmute', false)"), 2)+ # ...and it says so where somebody will see it, not in a 10.5px line.+ self.assertIn("phosToast", fn)+ self.assertIn("Your setting has not been changed", fn)++ def test_the_speaker_button_is_the_way_back_from_a_refusal(self):+ # Pressing it IS the user gesture the browser was waiting for, so the+ # recovery path restarts the picture and the bed rather than only+ # flipping a flag.+ fn = extract_function("sbeUnmuteFromRefusal", self.src)+ self.assertIn("sbeSetMute(false)", fn)+ self.assertIn("sbeMusicPlay()", fn)+ self.assertIn("sbeUnmuteFromRefusal()", self.src)++ def test_the_banner_says_the_one_sentence_that_matters(self):+ el = self.src[self.src.index('id="sbeAlarm"'):]+ el = el[:el.index("</div>")]+ self.assertIn("SAVING IS FAILING", el)+ self.assertIn("your changes are not being stored", el)+ self.assertIn("Try again", el)++ def test_the_tick_notices_work_that_is_not_reaching_the_disk(self):+ fn = extract_function("sbeTick", self.src)+ # Re-queue a dropped save, and raise the alarm past the grace — BEFORE+ # any of the early returns this function is full of.+ self.assertLess(fn.index("SBE.dirty && !SBE.conflict"),+ fn.index("SBE.prepare || {}"))+ self.assertIn("sbeQueueSave()", fn)+ self.assertIn("SBE_SAVE_GRACE_MS", fn)+++class SplitEditsInTheBrowser(unittest.TestCase):+ """"I need to be able to leave some of the audio and drag only the image."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_a_clip_carries_its_own_sound_until_somebody_says_otherwise(self):+ start, end, film, linked = self.r["audioLinkedByDefault"]+ self.assertEqual([start, end, film], [0, 4, 4])+ self.assertTrue(linked)++ def test_unlinking_writes_the_window_the_clip_already_had(self):+ ok, payload = self.r["unlinkWritesTheSameWindow"]+ self.assertTrue(ok)+ self.assertEqual(json.loads(payload),+ {"start": 0, "end": 4, "film_start": 4})+ # ...and re-linking leaves no trace, so the document is identical to+ # one that was never split.+ self.assertIsNone(self.r["relinkRemovesTheField"])++ def test_a_linked_strip_cannot_be_dragged_by_accident(self):+ ok, why = self.r["linkedRefusesTheDrag"]+ self.assertFalse(ok)+ self.assertIn("unlink", why)++ def test_the_j_cut_moves_the_sound_and_not_the_picture(self):+ ok, audio_at, film_at, src_in = self.r["jCut"]+ self.assertTrue(ok)+ self.assertEqual(audio_at, 3) # her voice arrives a second early+ self.assertEqual(film_at, 4) # ...and her picture does not move+ self.assertEqual(src_in, 0) # nor does the window into her file++ def test_the_l_cut_runs_the_sound_on_under_the_next_picture(self):+ ok, audio_end, video_end, film_end = self.r["lCut"]+ self.assertTrue(ok)+ self.assertEqual(audio_end, 6) # two more seconds of his line+ self.assertEqual(video_end, 4) # his picture is untouched+ self.assertEqual(film_end, 4)+ # ...and it cannot invent audio the source does not have.+ self.assertEqual(self.r["lCutClamped"], 10)++ def test_a_head_trim_leaves_the_rest_where_it_was(self):+ src_in, film_at, video_in = self.r["headTrim"]+ self.assertEqual(src_in, 1) # one second later into the file+ self.assertEqual(film_at, 5) # ...landing one second later+ self.assertEqual(video_in, 0) # the picture's window is untouched++ def test_a_head_trim_past_the_source_never_moves_the_out_point(self):+ # The one boundary every audio case above stays inside. `start`+ # clamped at 0 while `film` applied the full, unclamped delta, so+ # pulling the sound's head back further than the take allows dragged+ # the strip's right edge left with it — the L-cut you were keeping,+ # quietly shortened.+ q = self.r["headTrimPastTheSource"]+ self.assertAlmostEqual(q["outAt1"], q["wasOut"], places=6)+ self.assertAlmostEqual(q["outAt0"], q["wasOut"], places=6)+ # ...and the in-point stops at the head of the source, as it must.+ self.assertEqual(q["start1"], 0)+ self.assertEqual(q["start0"], 0)++ def test_a_locked_clip_and_a_still_both_refuse(self):+ self.assertFalse(self.r["lockedRefuses"])+ ok, why = self.r["stillRefuses"]+ self.assertFalse(ok)+ self.assertIn("video clip", why)++ def test_the_three_layers_are_in_the_owners_order(self):+ inner = self.src[self.src.index('id="sbeInner"'):]+ inner = inner[:inner.index('id="sbeHead"')]+ for a, b in (("sbeRuler", "sbeTrack"), ("sbeTrack", "sbeAudioLane"),+ ("sbeAudioLane", "sbeWave")):+ self.assertLess(inner.index('id="%s"' % a),+ inner.index('id="%s"' % b))++ def test_the_toggle_is_offered_on_a_video_clip_and_only_there(self):+ fn = extract_function("sbePaintInspector", self.src)+ self.assertIn("sbeToggleAudioLink()", fn)+ self.assertIn("kind === 'video'", fn)+ self.assertIn("Unlink sound", fn)++ def test_the_height_floor_is_the_sum_of_its_lanes(self):+ # sbeFitMonitors budgets the monitors against this constant, so a lane+ # added without moving it steals the difference from the picture — and+ # that is not hypothetical: the floor was 190, itemised in a comment+ # that predated the overlay lane, so the box spent three releases 30px+ # shorter than its own contents with `overflow-y: hidden` over the+ # difference. The bottom of the soundtrack was drawn where nobody+ # could see it. Both ends are now COMPUTED here rather than matched as+ # strings, so a fifth lane turns this red instead of clipping.+ chrome = int(re.search(r"const SBE_TL_CHROME = (\d+);",+ self.src).group(1))+ lanes = re.findall(+ r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*(\d+), share: ([\d.]+) \}",+ self.src)+ self.assertEqual([l[0] for l in lanes], ["ov", "track", "alane", "wave"])+ floor = int(re.search(r"const SBE_TL_MIN_H = (\d+);", self.src).group(1))+ ceil_ = int(re.search(r"const SBE_TL_MAX_H = (\d+);", self.src).group(1))+ self.assertEqual(floor, chrome + sum(int(l[1]) for l in lanes))+ self.assertEqual(ceil_, chrome + sum(int(l[2]) for l in lanes))+ # And the CSS fallback — what the page shows for the frame before the+ # JS runs — is the same number.+ self.assertIn("min-height: var(--sbe-tl-h, %dpx);" % floor, self.src)+ # Every lane's CSS fallback is its base, and the picture's max-height+ # is its cap. If those disagree with the table, flex fights the+ # distribution and the pixels go somewhere nobody chose.+ base = dict((l[0], l[1]) for l in lanes)+ cap = dict((l[0], l[2]) for l in lanes)+ self.assertIn("var(--sbe-ov-h, %spx)" % base["ov"], self.src)+ self.assertIn("var(--sbe-track-h, %spx); max-height: %spx;"+ % (base["track"], cap["track"]), self.src)+ self.assertIn("var(--sbe-alane-h, %spx)" % base["alane"], self.src)+ self.assertIn("var(--sbe-wave-h, %spx)" % base["wave"], self.src)++ def test_the_dragged_height_goes_where_the_owner_asked_for_it(self):+ # "...enabling expansion in case you have some sound editing in+ # there." Shares, not proportions: scaling every lane by the same+ # factor would give the picture track 41% of the drag and the sound+ # strip 14%, which is the opposite of the sentence above.+ lanes = dict((m[0], float(m[3])) for m in re.findall(+ r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*(\d+), share: ([\d.]+) \}",+ self.src))+ self.assertAlmostEqual(sum(lanes.values()), 1.0, places=6)+ self.assertGreaterEqual(lanes["alane"] + lanes["wave"], 0.75)+ self.assertGreater(lanes["alane"], lanes["track"])+ # "They don't need to be this big": after the rebalance the picture+ # takes the SMALLEST share of a dragged pixel bar the overlay strip.+ self.assertLess(lanes["track"], lanes["wave"])+++class ThePanelsClientPARSES(unittest.TestCase):+ """The whole script, as one file, through a real parser.++ Every other gate in this suite EXTRACTS the function it is about and runs+ that. So a stray paren three characters outside any function body — one too+ many closing an `escapeHtml(` argument — left 250 client tests green while+ the served page threw `SyntaxError: Unexpected token ')'` on load, `SBE`+ was never defined, and the Editor did not exist in the browser at all. The+ per-function harness is structurally incapable of seeing that: it never+ concatenates the file the browser is handed.++ This does. It is the cheapest test in the suite and it is the only one that+ fails when the panel is unopenable.+ """++ def test_the_served_script_parses_as_javascript(self):+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = panel_source()+ m = re.search(r'HTML = r"""(.*?)"""', src, re.S)+ self.assertIsNotNone(m, "the panel's HTML template moved")+ blocks = re.findall(r"<script>(.*?)</script>", m.group(1), re.S)+ self.assertTrue(blocks, "no <script> block found in the panel HTML")+ for i, js in enumerate(blocks):+ with tempfile.NamedTemporaryFile("w", suffix=".js",+ delete=False) as fh:+ fh.write(js)+ path = Path(fh.name)+ try:+ r = subprocess.run([NODE, "--check", str(path)],+ capture_output=True, text=True, timeout=60)+ self.assertEqual(r.returncode, 0,+ "script block %d does not parse:\n%s"+ % (i, r.stderr))+ finally:+ path.unlink(missing_ok=True)+++class TheNounIsSingleSourced(unittest.TestCase):+ """"These are not films... something less bad than film."++ One noun, three forms, replaced at serve time — so changing his mind again+ costs one line and nothing else.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()++ def test_there_is_exactly_one_place_to_change_it(self):+ self.assertIn('SEQ_NOUN = "sequence"', self.src)+ self.assertIn('SEQ_NOUN_PL = "sequences"', self.src)+ self.assertIn('SEQ_NOUN_CAP = "Sequence"', self.src)+ # ...and the template is what carries it, not 30 hardcoded strings.+ self.assertIn('.replace("__SEQ__", SEQ_NOUN)', self.src)+ self.assertIn('.replace("__SEQS__", SEQ_NOUN_PL)', self.src)+ self.assertIn('.replace("__SEQCAP__", SEQ_NOUN_CAP)', self.src)++ def test_the_longest_token_is_replaced_first(self):+ # `__SEQ__` is a prefix of neither, but `__SEQS__` and `__SEQCAP__`+ # both START with `__SEQ`, so replacing the short one first would+ # leave "sequenceS__" and "sequenceCAP__" on the screen.+ order = [self.src.index('.replace("__SEQCAP__"'),+ self.src.index('.replace("__SEQS__"'),+ self.src.index('.replace("__SEQ__", SEQ_NOUN)')]+ self.assertEqual(order, sorted(order))++ def test_the_editor_surface_carries_no_bare_film_noun(self):+ # The Editor's own markup: the pool tabs, the empty state, the+ # inspector summary. Internal field names are exempt by construction —+ # they are the schema, and a label is not worth a data migration.+ # The strings the owner named, by name. A slice-scan would be broader+ # and would also catch the STORYBOARD tab, where "Film" means the+ # finished render — a different noun for a different thing, and not+ # what he asked to rename.+ for gone in ('data-src="film">This film<',+ 'data-src="other">Other films<',+ "' of film'",+ 'title="This film\'s shots, other films\' clips',+ 'Every draft this film has',+ "'Open a film first"):+ self.assertNotIn(gone, self.src, gone)+ for now in ('>This __SEQCAP__<', '>Other __SEQS__<',+ "' of the __SEQ__'", "'Open a __SEQ__ first"):+ self.assertIn(now, self.src, now)++ def test_no_token_survives_into_the_served_page(self):+ # The badge is concatenated in Python AFTER the template pass, so a+ # token there is a token the user reads. It uses the constant instead.+ import re as _re+ page = panel_html_render()+ self.assertEqual(_re.findall(r"__SEQ\w*", page), [])+ self.assertIn("This Sequence", page)+ self.assertIn("Other sequences", page)++ def test_the_schema_words_are_untouched(self):+ for keep in ("film_start", "film_end", "sbeFilmDuration"):+ self.assertIn(keep, self.src, keep)+++class TheStripIsAnEditingSurface(unittest.TestCase):+ """Waveforms, a level line with keyframes, and half a clip you can delete."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_the_waveform_is_the_STRIPS_window_not_the_pictures(self):+ # Two different source windows must draw two different slices, or a+ # trimmed strip and a J-cut both show the wrong seconds.+ first, later = self.r["waveSliceIsTheStripsWindow"]+ self.assertNotEqual(first, later)+ self.assertEqual(first, [[-0.04, 0.04], [-0.09, 0.09]])+ self.assertEqual(later, [[-0.54, 0.54], [-0.59, 0.59]])++ def test_one_column_over_many_buckets_takes_the_extremes(self):+ # Otherwise a quiet frame in the middle of a loud second draws a hole+ # that is not there.+ self.assertEqual(self.r["waveSliceHandlesZoomOut"], [[-0.99, 0.99]])+ self.assertEqual(self.r["waveSliceNoPeaksIsEmpty"], 0)++ def test_one_waveform_per_SOURCE_asked_for_once(self):+ fn = extract_function("sbeWaveWant", self.src)+ self.assertIn("SBE.clipPeaks", fn)+ self.assertIn("hasOwnProperty", fn) # asked once, cached forever+ # A take with no audio is a FACT, remembered as false so the lane+ # never asks again.+ self.assertIn("false", fn)+ self.assertIn("clip-peaks", fn)++ def test_a_point_is_added_moved_and_deleted(self):+ self.assertEqual(json.loads(self.r["kfAdd"]), {"points": [[2, 0.4]]})+ self.assertEqual(json.loads(self.r["kfMoveAndSort"]),+ [[3, 0.2], [3.5, 0.9]]) # re-sorted past its neighbour+ self.assertEqual(json.loads(self.r["kfMoveClamps"]), [[4, 1]])+ self.assertTrue(self.r["kfDeleteLeavesNoTrace"])+ self.assertEqual(json.loads(self.r["kfDeleteKeepsAFade"]),+ {"fade_in": 1})+ self.assertEqual(self.r["kfLocked"], "locked")++ def test_two_points_on_one_second_are_refused(self):+ # A discontinuity the envelope cannot express and the NLEs would+ # import out of order.+ ok, why = self.r["kfNoTwoOnOneSecond"]+ self.assertFalse(ok)+ self.assertIn("already a point", why)++ def test_the_gesture_precedence_on_the_strip_is_written_down(self):+ down = extract_function("sbeOnAudioDown", self.src)+ # sync flag -> corner handle -> keyframe dot -> grips -> body+ self.assertLess(down.index(".sbe-sync"), down.index(".sbe-kf"))+ self.assertLess(down.index(".sbe-kf"), down.index(".sbe-fade-h"))+ self.assertLess(down.index(".sbe-fade-h"), down.rindex(".sbe-aclip'"))+ # SHIFT-CLICK deletes: a modifier rather than a second affordance+ # drawn on a 6px target.+ self.assertIn("ev.shiftKey", down)+ self.assertIn("sbeDeleteKeyframe", down)+ # DOUBLE-CLICK adds, so plain drag stays "move the strip".+ dbl = extract_function("sbeOnAudioDbl", self.src)+ self.assertIn("sbeAddKeyframe", dbl)+ self.assertIn(".sbe-kf", dbl) # not on top of a point+ self.assertIn(".sbe-fade-h", dbl) # nor on a corner+ self.assertIn("dblclick", self.src)++ def test_deleting_the_strip_leaves_the_picture_playing_silent(self):+ # "You cannot unlock the clip and delete the upper part, nor delete+ # the lower part of the sound."+ ok, no_audio, flagged, reads_muted, after, before = \+ self.r["deleteStrip"]+ self.assertTrue(ok)+ self.assertTrue(no_audio)+ # Absent `audio` alone would mean LINKED — the clip's own sound would+ # play again, the opposite of what was asked for. The mute is what+ # makes the silence real in all three outputs.+ self.assertTrue(flagged)+ self.assertTrue(reads_muted)+ self.assertEqual(after, before) # the picture does not move+ self.assertEqual(after, [0, 4])++ def test_deleting_the_strip_is_not_a_ripple(self):+ before, after = self.r["deleteStripIsNotARipple"]+ self.assertEqual(before, after)++ def test_a_clip_that_is_already_silent_says_so(self):+ ok, why = self.r["deleteStripTwiceIsRefused"]+ self.assertFalse(ok)+ self.assertIn("already silent", why)++ def test_the_verb_is_offered_only_once_the_halves_are_separate(self):+ # On a linked clip "delete the sound" and "mute" would be the same+ # button twice.+ fn = extract_function("sbePaintInspector", self.src)+ self.assertIn("sbeDeleteStripSel()", fn)+ i = fn.index("sbeDeleteStripSel()")+ self.assertIn("sbeClipAudio(c).split", fn[max(0, i - 400):i])++ def test_the_overlay_lane_teaches_itself(self):+ # An empty lane is a sentence, not a blank — the convention the track+ # and the four pool sources already follow.+ fn = extract_function("sbePaintOverlays", self.src)+ self.assertIn("sbe-track-empty", fn)+ self.assertIn("drop a still here", fn)+ self.assertIn("media pool", fn)+++class TheSoundsEnvelopeOnTheClient(unittest.TestCase):+ """The preview has to move the same number the render and export do."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_a_flat_unity_curve_is_no_curve(self):+ self.assertEqual(self.r["afxFlatIsNothing"], [0, 1])++ def test_the_client_curve_is_the_servers_curve(self):+ # Byte-for-byte the same breakpoints the API suite pins for the same+ # inputs — two implementations of one model is how they drift.+ self.assertEqual(self.r["afxSimpleCase"],+ [[0, 0], [1, 1], [3.5, 1], [4, 0]])+ self.assertEqual(self.r["afxKeyframes"],+ [[0, 0.3], [1, 0.3], [2, 1], [4, 1]])+ self.assertEqual(self.r["afxCompose"],+ [[0, 0], [1, 0.25], [2, 0.25], [4, 0.25]])+ self.assertEqual(self.r["afxClamp"], [2, 2])++ def test_the_gain_at_a_second_is_the_previews_answer(self):+ self.assertEqual(self.r["afxGainAt"], [0, 0.5, 1, 1, 0.5, 0])++ def test_setting_a_sound_fade_and_clearing_it(self):+ on, gone, source = self.r["afxSet"]+ self.assertEqual(json.loads(on), {"fade_in": 1})+ self.assertTrue(gone) # neutral is absent+ self.assertEqual(source, "human")+ self.assertEqual(self.r["afxSetClampsToTheStrip"], 4)+ self.assertEqual(self.r["afxLocked"], "locked")++ def test_the_strip_player_moves_the_gain(self):+ fn = extract_function("sbeStripSync", self.src)+ self.assertIn("sbeGainAt(c2, win.len, w.at - win.start)", fn)+ # STRIP-relative, which is the envelope's own clock: a J-cut that+ # slides its sound must not drag the ramp with it.+ self.assertIn("w.at - win.start", fn)++ def test_the_bed_plays_the_WHOLE_mix_and_not_just_its_envelope(self):+ # The preview used to read the bed's `afx` and nothing else, while the+ # render held the bed at a hard-coded 0.20 and ducked it against the+ # dialogue. `sbeBedGainAt` is the one function both sides now read.+ fn = extract_function("sbeMusicSync", self.src)+ self.assertIn("a.volume = sbeBedGainAt(", fn)+ # ON THE BED'S OWN CLOCK — the played window, not the track — so a+ # soundtrack that was trimmed or dragged does not slide its own fade.+ self.assertIn("SBE.playhead - bw.film_start", fn)++ def test_the_strip_grows_the_SAME_corner_handle_the_picture_has(self):+ self.assertIn('data-afade="in"', self.src)+ self.assertIn('data-afade="out"', self.src)+ lane = extract_function("sbePaintAudioLane", self.src)+ self.assertIn("sbeAudioFadeMarks(c, w)", lane)++ def test_the_gesture_precedence_is_the_same_on_both_lanes(self):+ # The corner handle sits over the left grip's hit area, so it is+ # tested FIRST — one rule for both lanes, or the strip behaves+ # differently from the block above it for no reason a user could name.+ down = extract_function("sbeOnAudioDown", self.src)+ self.assertIn(".sbe-fade-h", down)+ # rindex: the strip BODY is the last thing tested, after the flag, the+ # keyframe dot and the corner handle — most specific gesture first.+ self.assertLess(down.index(".sbe-fade-h"), down.rindex(".sbe-aclip"))+ move = extract_function("sbeOnAudioMove", self.src)+ self.assertIn("d.mode === 'afade'", move)+ # ...and it resolves before the strip's own move/trim maths.+ self.assertLess(move.index("'afade'"), move.index("sbeAudioEdit"))++ def test_the_inspector_separates_picture_fades_from_sound_fades(self):+ fn = extract_function("sbePaintInspector", self.src)+ # THREE sections, which is what the effects model documents. The+ # sound's ramps live inside Sound rather than under a fourth heading:+ # two adjacent headings both saying "sound" pushed the inspector past+ # 460px in the rail.+ self.assertIn("sect('Effects'", fn)+ self.assertNotIn("sect('Sound fades'", fn)+ self.assertIn("sbeAudioFadeCommit", fn)+ sound = fn[fn.index("sect('Sound'"):fn.index("sect('Effects'")]+ self.assertIn("sbeAudioFadeCommit", sound)+++class TheOverlayLaneOnTheClient(unittest.TestCase):+ """A second video track, above the picture. His endcard's lane."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_a_png_is_a_card_and_an_mp4_is_a_clip(self):+ self.assertEqual(self.r["ovKind"], ["still", "video", "video"])++ def test_a_card_covers_its_own_window_and_no_more(self):+ self.assertEqual(self.r["ovAt"], [False, True, True, False])++ def test_moving_one_moves_ONE_and_a_still_is_its_slot(self):+ ok, fs, fe, st, en, source = self.r["ovMove"]+ self.assertTrue(ok)+ self.assertEqual([fs, fe], [10, 13])+ self.assertEqual([st, en], [0, 3]) # the still follows its slot+ self.assertEqual(source, "human")++ def test_one_lane_means_no_stacking(self):+ ok, why = self.r["ovNoStacking"]+ self.assertFalse(ok)+ self.assertIn("already there", why)++ def test_trimming_changes_only_its_own_window(self):+ right, left = self.r["ovTrim"]+ self.assertEqual(right, [8, 5]) # end moved, length followed+ self.assertEqual(left, [4, 8, 4])++ def test_adding_lands_somewhere_free(self):+ ok, fs, fe, kind = self.r["ovAddSlidesPastAnother"]+ self.assertTrue(ok)+ self.assertEqual([fs, fe], [6, 8]) # pushed past the card at 3–6+ self.assertEqual(kind, "still")++ def test_removing_a_card_is_not_a_ripple(self):+ # The lane is a set of placements, not a queue: nothing else moves.+ ok, left, other_at = self.r["ovDeleteMovesNothing"]+ self.assertTrue(ok)+ self.assertEqual(left, 1)+ self.assertEqual(other_at, 8)++ def test_a_card_takes_its_fades_from_the_SAME_accessor(self):+ # The proof the effects foundation was worth building: an overlay is+ # not a second fade implementation.+ fade_in, ramp = self.r["ovFades"]+ self.assertEqual(fade_in, 1.0)+ self.assertEqual(ramp, [0, 0.5, 1, 1])+ self.assertEqual(self.r["ovFadeClamp"], 3) # cannot outrun the card++ def test_the_lane_is_drawn_above_the_picture_track(self):+ # Lane order on screen is stacking order in the sequence.+ html = self.src[self.src.index('id="sbeInner"'):]+ self.assertLess(html.index('id="sbeOverlayLane"'),+ html.index('id="sbeTrack"'))+ self.assertIn("sbePaintOverlays()", extract_function("sbePaint", self.src))++ def test_the_stage_carries_its_own_opacity(self):+ fn = extract_function("sbeOvPaint", self.src)+ self.assertIn("sbeFadeOpacityAt(o, now)", fn)+ self.assertIn("sbeOvAt(SBE.overlays, now)", fn)+ self.assertIn("sbeOvPaint();", extract_function("sbeFrame", self.src))+ # BEFORE the picture's early returns. A card may outlive the last shot,+ # and `sbeShowFrameAt` returns early on "nothing plays here" — which+ # left the card stuck on screen at full opacity past its own end.+ show = extract_function("sbeShowFrameAt", self.src)+ self.assertIn("sbeOvPaint(t);", show)+ self.assertLess(show.index("sbeOvPaint(t);"),+ show.index("nothing plays here"))++ def test_the_lane_travels_with_the_document_and_the_undo_stack(self):+ self.assertIn("edit.overlays", extract_function("sbeSaveBody", self.src))+ self.assertIn("SBE.overlays", extract_function("sbeAdopt", self.src))+ snap = extract_function("sbeSnapshot", self.src)+ self.assertIn("overlays: SBE.overlays", snap)+ # An older snapshot carries no lane, and restoring `undefined` over a+ # live one would delete a card nobody asked to remove.+ rest = extract_function("sbeRestore", self.src)+ self.assertIn("s.overlays !== undefined", rest)++ def test_an_image_in_the_pool_can_become_a_card(self):+ self.assertIn("edPoolOverlay(", self.src)+ self.assertIn("ed-pool-ov", self.src)+ fn = extract_function("edPoolOverlay", self.src)+ self.assertIn("sbeOvAddAt", fn)+ self.assertIn("SBE.playhead", fn)+++class AHoleShorterThanAFrameOnTheClient(unittest.TestCase):+ """The client half of the black-frame report. The server heals what is+ already on disk; this is what stops a gesture from making another one."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_under_a_frame_is_no_gap_and_anything_larger_is_untouched(self):+ got = self.r["gridGapCollapsesSubFrameOnly"]+ self.assertEqual(got[:3], [0, 0, 0])+ # NOT `round(gap / frame)`: his 0.503-frame hole would round UP to a+ # whole frame of black, which is the same bug one frame louder.+ self.assertAlmostEqual(got[3], 1 / 24, places=6)+ self.assertEqual(got[4:], [0.5, 1.8])++ def test_his_film_lays_out_with_the_cuts_touching(self):+ shape, holes, lengths = self.r["holedFilmLaysOutContiguous"]+ self.assertEqual([row[3] for row in shape], [0, 4, 8, 12])+ self.assertEqual(holes, 0)+ # ...without breaking the invariant the server refuses an edit for.+ self.assertTrue(lengths)++ def test_a_drag_cannot_open_one(self):+ ok, film_start, holes = self.r["dragCannotOpenASubFrameHole"]+ self.assertTrue(ok)+ self.assertEqual(film_start, 4)+ self.assertEqual(holes, 0)++ def test_a_gap_you_can_see_survives_a_drag(self):+ film_start, holes = self.r["dragKeepsAGapYouCanSee"]+ self.assertEqual(film_start, 6.5)+ self.assertEqual(holes, 1)++ def test_the_heal_carries_the_unlinked_strip(self):+ before, after, anchor = self.r["adoptCarriesTheUnlinkedStrip"]+ self.assertEqual(before, after)+ self.assertEqual(anchor, 3.5)++ def test_the_hole_counter_stops_lying(self):+ old, truth, now = self.r["holeCounterOnHisFilm"]+ # What the header said, what was actually there, and what is left.+ self.assertEqual([old, truth, now], [1, 3, 0])++ def test_the_threshold_is_derived_from_the_rate_not_written_as_1_48(self):+ fn = extract_function("sbeHoles", self.src)+ self.assertIn("sbeFps()", fn)+ self.assertNotIn("1 / 48", fn)+++class ACardOnABlackPlateIsFixedOnTheWayIn(unittest.TestCase):+ """"If the picture comes in a format that doesn't work, automatically make+ it work" — and then say so, quietly, with the original one click away.++ The server half is in `test_storyboard_editor_api`. This is the half that+ decides WHICH LANE it happens on, whether the receipt can push the timeline+ down the screen, and whether "Keep original" actually restores anything.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_it_happens_on_the_way_to_the_OVERLAY_lane_and_nowhere_else(self):+ # A still on the PICTURE lane legitimately keeps its black — it is the+ # whole frame there. So the call sits in the overlay verb, and the+ # pool's ordinary add never learns about it.+ fn = extract_function("edPoolOverlay", self.src)+ self.assertIn("/storyboard/edit/overlay-key", fn)+ self.assertTrue(fn.lstrip().startswith("async "),+ "the key has to be awaited before the card is placed")+ self.assertNotIn("overlay-key", extract_function("edPoolAdd", self.src))++ def test_it_posts_the_body_the_panel_can_actually_read(self):+ # MEASURED IN A BROWSER, not reasoned about. `_storyboard_post` parses+ # urlencoded bodies; a `FormData` sends multipart and arrives as an+ # empty form, so the route answered "that image is not in this panel's+ # outputs" about a file sitting in the outputs folder and the card went+ # on the lane still plated. Twenty green unit tests did not see it,+ # because the fake handler is handed the form dict directly.+ fn = extract_function("edPoolOverlay", self.src)+ self.assertIn("new URLSearchParams()", fn)+ self.assertNotIn("new FormData", fn)+ # ...which is the same shape the pool's other verb uses.+ self.assertIn("new URLSearchParams()",+ extract_function("edPoolAdd", self.src))++ def test_a_card_that_could_not_be_measured_is_still_placed(self):+ # A panel that cannot answer must not cost the user their card.+ fn = extract_function("edPoolOverlay", self.src)+ self.assertIn("catch", fn)+ self.assertLess(fn.index("catch"), fn.index("sbeOvAddAt"))++ def test_the_receipt_is_a_quiet_chip_in_the_ONE_notice_surface(self):+ el = extract_element("sbeKeyed", self.src)+ self.assertIn('data-quiet="1"', el)+ self.assertIn('data-short="Black background removed"', el)+ # The sentence and the way back, in the markup a gate can read.+ body = self.src[self.src.index('id="sbeKeyed"'):]+ body = body[:body.index("</div>")]+ self.assertIn("Black background removed", body)+ self.assertIn("Keep original", body)+ self.assertIn("sbeKeyedKeepOriginal()", body)+ # Inside the container, so it can never become a fifth stacked banner.+ wrap = self.src[self.src.index('id="sbeNotices"'):]+ self.assertLess(wrap.index('id="sbeKeyed"'), wrap.index("sbe-vers"))++ def test_it_is_the_LEAST_urgent_thing_on_the_screen(self):+ # It reports something that already worked. A save that is failing+ # outranks it, always.+ order = self.src[self.src.index("const SBE_NOTICE_ORDER"):]+ order = order[:order.index("]")]+ self.assertIn("'sbeKeyed'", order)+ self.assertGreater(order.index("'sbeKeyed'"), order.index("'sbeAlarm'"))+ self.assertGreater(order.index("'sbeKeyed'"), order.index("'sbeErrors'"))++ def test_the_gates_copy_of_the_urgency_order_is_the_panels(self):+ # This constant is duplicated into the harness above. It was a comment+ # asking to be kept equal and nothing that checked — so a notice added+ # to the panel was silently uncovered here.+ panel_list = re.search(+ r"const SBE_NOTICE_ORDER = (\[[^\]]*\])", self.src).group(1)+ mine = re.search(r"const SBE_NOTICE_ORDER = (\[[^\]]*\])", SHIM).group(1)+ norm = lambda s: re.findall(r"'([a-zA-Z]+)'", s) # noqa: E731+ self.assertEqual(norm(panel_list), norm(mine))++ def test_keep_original_restores_the_file_that_was_never_touched(self):+ ok, path, fs, fe, untouched = self.r["ovKeepOriginal"]+ self.assertTrue(ok)+ self.assertEqual(path, "/x/a.png")+ # Only the pointer moved: the card keeps its place and its length.+ self.assertEqual([fs, fe], [3, 6])+ # ...and the input array is left alone, which is what undo walks back.+ self.assertEqual(untouched, "/x/a.keyed.png")++ def test_keep_original_on_a_card_that_is_gone_changes_nothing(self):+ self.assertEqual(self.r["ovKeepOriginalOnAGoneCard"], [False, "gone"])++ def test_keep_original_is_an_ordinary_undoable_edit(self):+ fn = extract_function("sbeKeyedKeepOriginal", self.src)+ self.assertIn("sbeOvMutate", fn)+ # Not a private path around the door every other lane edit goes through.+ self.assertNotIn("SBE.overlays =", fn)++ def test_the_add_hands_back_the_row_it_added(self):+ # The receipt needs the id to be able to undo it, and guessing which+ # row is new is how the wrong card gets reverted.+ self.assertIn("return res.added", extract_function("sbeOvAddAt", self.src))++ def test_a_load_clears_a_receipt_that_no_longer_points_at_anything(self):+ self.assertIn("sbeKeyedDismiss", extract_function("sbeAdopt", self.src))++ def test_the_receipt_alone_is_still_a_chip(self):+ got = self.r["noticeKeyedAloneIsAChip"]+ self.assertEqual(got["folded"], ["sbeKeyed"])+ self.assertFalse(got["wrapHidden"])++ def test_a_failing_save_takes_the_width_and_the_receipt_sits_beside_it(self):+ got = self.r["noticeKeyedNeverOutranksTheAlarm"]+ self.assertEqual(got["lead"], "sbeAlarm")+ self.assertEqual(got["folded"], ["sbeKeyed"])++ def test_with_everything_open_the_receipt_is_last(self):+ got = self.r["noticeKeyedIsLastOfAll"]+ self.assertEqual(got["lead"], "sbeConflict")+ # Every other notice folds too — the surface is ONE ROW, and adding a+ # fifth citizen to it must not make it a stack. Measured in a browser+ # at 1920: the timeline sits at the same y with one chip open as with+ # two, and the surface costs 39px either way.+ self.assertEqual(got["folded"],+ ["sbeAlarm", "sbeErrors", "sbeRecover", "sbeKeyed"])+++class TheEffectsModelOnTheClient(unittest.TestCase):+ """docs/EDITOR_EFFECTS_MODEL.md, client side — and the inspector it asked+ for: "just set the base to have effects somewhere"."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_absent_means_no_effect(self):+ self.assertEqual(self.r["fxAbsentIsNothing"], [0, 0, 0])++ def test_one_accessor_whatever_the_storage(self):+ # Fades live in `fx`; brightness stays where history put it. A+ # consumer never has to know that.+ self.assertEqual(self.r["fxOneAccessor"], [0.5, 0.25])++ def test_the_client_clamps_exactly_as_the_server_does(self):+ both, lopsided = self.r["fxClamp"]+ self.assertEqual(both, [2, 2])+ total, in_is_bigger = lopsided+ self.assertEqual(total, 4)+ self.assertTrue(in_is_bigger) # proportional, not truncated++ def test_the_preview_opacity_is_a_value_per_frame(self):+ # A 4 s clip, 0.5 s in and 1.0 s out. A scrub must show what is TRUE+ # at the second it landed on, not an animation that started on arrival.+ self.assertEqual(self.r["fxOpacityRamp"], [0, 0.5, 1, 1, 1, 0.5, 0])+ self.assertEqual(self.r["fxNoFadeIsAlwaysOpaque"], [1, 1])++ def test_clearing_a_fade_leaves_no_trace(self):+ after_clear, gone, source = self.r["fxSet"]+ self.assertEqual(json.loads(after_clear), {"fade_in": 0.5})+ self.assertTrue(gone) # both cleared: no `fx` at all+ self.assertEqual(source, "human")++ def test_setting_one_clamps_against_the_other(self):+ self.assertEqual(self.r["fxSetClamps"], 3.2) # 3.2 + 0.8 = the length++ def test_a_locked_clip_refuses(self):+ self.assertEqual(self.r["fxLockedRefuses"], "locked")++ def test_it_reaches_the_save_payload(self):+ self.assertEqual(json.loads(self.r["fxReachesTheSavePayload"]),+ {"fade_in": 0.5, "fade_out": 1})++ def test_the_inspector_has_three_sections_and_effects_holds_brightness(self):+ # The reorganization IS the request: brightness was floating in the+ # middle of a flat run of buttons.+ fn = extract_function("sbePaintInspector", self.src)+ for name in ("'Clip'", "'Sound'", "'Effects'"):+ self.assertIn("sect(" + name, fn, name)+ eff = fn[fn.index("sect('Effects'"):]+ self.assertIn("adjust", eff) # brightness lives here+ self.assertIn("fadeRow('in'", eff)+ self.assertIn("fadeRow('out'", eff)+ # ...and the sections are real markup a gate can read.+ self.assertIn(".sbe-sect-h", self.src)++ def test_intuitive_first_precise_second(self):+ # The corner handle is how a fade is set in every NLE ever made; the+ # numeric field beside it is the exact second.+ self.assertIn('data-fade="in"', self.src)+ self.assertIn('data-fade="out"', self.src)+ self.assertIn(".sbe-fade-h", self.src)+ down = extract_function("sbeOnTrackDown", self.src)+ self.assertIn(".sbe-fade-h", down)+ # The handle is checked BEFORE the grips: it sits over the left grip's+ # hit area, and a fade drag is the more specific gesture.+ self.assertLess(down.index(".sbe-fade-h"), down.index(".sbe-grip"))+ move = extract_function("sbeOnTrackMove", self.src)+ self.assertIn("d.mode === 'fade'", move)+ self.assertIn("sbeSetFade", move)+ self.assertIn("sbeFadeCommit", extract_function("sbePaintInspector", self.src))++ def test_the_preview_paints_the_ramp_from_the_playhead(self):+ self.assertIn("sbeFadePaint();", extract_function("sbeFrame", self.src))+ self.assertIn("sbeFadePaint(t);",+ extract_function("sbeShowFrameAt", self.src))+ fn = extract_function("sbeFadePaint", self.src)+ self.assertIn("sbeFadeOpacityAt", fn)+ self.assertIn("style.opacity", fn)+ # THE CLIP AT THE PLAYHEAD, not `curId` — that is the transport's own+ # bookkeeping and is only current while something plays, so a SCRUB+ # read the stale clip or none at all. Caught on the test panel: the+ # stage stayed fully opaque while the playhead sat inside a ramp.+ self.assertIn("sbeClipAt(SBE.clips, now)", fn)+ self.assertLess(fn.index("sbeClipAt"), fn.index("SBE.curId"))++ def test_the_block_draws_the_ramps_it_has(self):+ self.assertIn("sbeFadeMarks(c)", extract_function("sbePaintTrack", self.src))+ self.assertIn(".sbe-cl-fade", self.src)+++class ThePreviewPlaysWhatTheDocumentSays(unittest.TestCase):+ """The J-cut was inaudible, and that was the whole complaint.++ The transport plays ONE <video> at a time and enters each clip at its+ picture boundary, so a clip's sound always landed with its picture no+ matter where its strip sat. Correct on disk, correct in the render's+ concat lanes, correct in the NLE export — and missing from the one place+ the user checks his work: "no matter what I do, this is always out."+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_exactly_one_thing_carries_a_clips_sound(self):+ # Both would play the same seconds twice, a beat apart.+ got = self.r["stripOwnership"]+ self.assertEqual(got["plain"], [False, True]) # the picture element+ self.assertEqual(got["split"], [True, False]) # the strip player+ self.assertEqual(got["muted"], [False, False]) # neither+ self.assertEqual(got["still"], [False, False]) # nothing to play++ def test_HIS_j_cut_is_audible_before_the_picture_arrives(self):+ # rev 97: strip at film 30.35, picture cut at 30.77.+ got = self.r["stripAcrossHisCut"]+ self.assertEqual(got["before"], []) # 29.5: not yet+ self.assertEqual(got["lead"], [["c6", 0.05]]) # 30.4: his line+ self.assertEqual(got["edge"], [["c6", 0.41]]) # 30.76: still early+ self.assertEqual(got["after"], [["c6", 0.65]]) # 31.0: across it+ self.assertEqual(got["late"], [["c6", 3.95]])+ self.assertEqual(got["ended"], []) # 34.392 and done++ def test_the_sound_and_the_picture_MEET_at_the_cut(self):+ # At film 30.77 the strip is at source 0.42 — which is exactly clip+ # 6's picture in-point. That is what makes his edit sync rather than+ # merely early, and it is the arithmetic the whole feature turns on.+ self.assertEqual(self.r["stripMapping"], [0, 0.42, 1, 4.04])++ def test_two_strips_sound_at_once_across_a_cut(self):+ # An L-cut tail and a J-cut head overlap by construction. The render's+ # concat lane resolves that by trimming the outgoing tail; the preview+ # sums them, which is what the person cutting needs to hear.+ got = self.r["stripOverlap"]+ self.assertEqual(got["both"], [["a", 4.5], ["b", 1]])+ self.assertEqual(got["onlyA"], ["a"])+ self.assertEqual(got["onlyB"], ["b"])+ # ...and the pool has a voice for each, with one spare.+ self.assertIn("const SBE_STRIP_VOICES = 3;", self.src)++ def test_a_muted_strip_is_silent_by_not_being_there(self):+ self.assertEqual(self.r["stripMuted"], [0, 0])++ def test_a_coupled_pair_is_played_at_its_frozen_offset(self):+ owned, at = self.r["stripCoupled"]+ self.assertTrue(owned)+ self.assertEqual(at, [["a", 0.5]])++ def test_an_ordinary_clip_is_not_the_players_business(self):+ self.assertEqual(self.r["stripIgnoresOrdinary"], 0)++ def test_the_picture_element_yields_whenever_a_strip_exists(self):+ fn = extract_function("sbeLoadInto", self.src)+ self.assertIn("!sbePictureCarriesSound(c)", fn)++ def test_the_player_is_driven_by_the_playhead_from_every_door(self):+ # Every frame while playing (a strip starts on its own clock, not at+ # the cuts), forced on a seek and on play, stopped on stop, and+ # re-synced after any edit — sbePaint is where every mutation, undo,+ # redo and adopt lands.+ self.assertIn("sbeStripSync();", extract_function("sbeFrame", self.src))+ self.assertIn("sbeStripSync(true);", extract_function("sbePlay", self.src))+ self.assertIn("sbeStripSync(true);", extract_function("sbeSeek", self.src))+ self.assertIn("sbeStripStop();", extract_function("sbeStop", self.src))+ self.assertIn("sbeStripSync();", extract_function("sbePaint", self.src))++ def test_a_seek_re_seeks_rather_than_tolerating_slip(self):+ fn = extract_function("sbeStripSync", self.src)+ self.assertIn("SBE_STRIP_SLIP", fn)+ self.assertIn("fresh || force", fn)+ # A voice is released BEFORE any is claimed, or an overlap of two+ # finds the pool full of yesterday's clips.+ # rindex: the FIRST `for (const w of want)` builds the live map; the+ # CLAIM loop is the last one, and that is the one release must precede.+ self.assertLess(fn.index("for (const a of pool)"),+ fn.rindex("for (const w of want)"))+ # ...and the global mute reaches it.+ self.assertIn("a.muted = !!SBE.muted;", fn)+++class TheLoadPathRewritesNothing(unittest.TestCase):+ """sb_carwash rev 97, on the client side.++ His symptom was the loaded board differing from disk, so the load path is+ the first suspect. It is byte-stable, there is no client-side repair, and+ this is the gate that keeps it that way.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_the_strip_survives_adopt_and_layout_untouched(self):+ got = self.r["loadRewritesNothing"]+ self.assertEqual(json.loads(got["audioUntouched"]),+ {"start": 0.0, "end": 4.042, "film_start": 30.35})+ self.assertTrue(got["firstHasNoStrip"])+ self.assertTrue(got["diskWasNotMutated"])++ def test_his_j_cut_reads_as_in_sync_on_the_client_too(self):+ # He trimmed 0.42 s off the picture head and left the sound reaching+ # back, so the same source second still plays at the same film second.+ self.assertEqual(self.r["loadRewritesNothing"]["drift"], [0, 0])++ def test_the_save_payload_is_what_the_disk_gave_it(self):+ rows = json.loads(self.r["loadRewritesNothing"]["roundTrips"])+ self.assertEqual(rows[0][:5], ["c5", 25.99, 30.032, 0, 4.042])+ self.assertIsNone(rows[0][5])+ self.assertEqual(rows[1][:5], ["c6", 30.77, 34.392, 0.42, 4.042])+ self.assertEqual(rows[1][5],+ {"start": 0.0, "end": 4.042, "film_start": 30.35})++ def test_there_is_no_client_side_repair_to_gate(self):+ # The server's legacy repair is a one-time, marker-gated migration.+ # The client has no mirror of it, and adding one would put a second+ # author back inside the load path.+ for name in ("sbeAdopt", "sbeAdoptGaps", "sbeLayout"):+ fn = extract_function(name, self.src)+ self.assertNotIn("repair", fn.lower(), name)+++class MutingAClipsOwnSound(unittest.TestCase):+ """"We should have an option to mute the clip sound."++ An H3 shot arrives with baked-in wind and ambience under the line, and on a+ music cut that is not a performance to be balanced — it is noise to remove+ so the track can carry the moment.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_absent_is_audible_and_that_is_the_migration(self):+ self.assertFalse(self.r["muteAbsentIsAudible"])++ def test_the_toggle_writes_one_flag_and_stamps_the_clip_human(self):+ ok, flag, reads, source = self.r["muteWritesTheFlag"]+ self.assertTrue(ok)+ self.assertTrue(flag)+ self.assertTrue(reads)+ self.assertEqual(source, "human")++ def test_unmute_restores_exactly_what_was_there(self):+ same, gone = self.r["muteUnmuteLeavesNoTrace"]+ self.assertTrue(same)+ self.assertTrue(gone)++ def test_mute_and_unlink_are_independent_in_both_directions(self):+ after, muted_then_unlinked, split = self.r["muteComposesWithUnlink"]+ # A J-cut that is then muted keeps its strip exactly where it was put:+ # `mute` describes the sound WHEREVER its strip happens to be.+ self.assertTrue(after["muted"])+ self.assertTrue(after["split"])+ self.assertEqual(after["snd"], [2, 6])+ # ...and muting first, then unlinking, reaches the same place.+ self.assertTrue(muted_then_unlinked)+ self.assertTrue(split)++ def test_there_must_be_something_to_switch_off(self):+ ok, why = self.r["muteRefusesASilentSource"]+ self.assertFalse(ok)+ self.assertIn("no sound of its own", why)+ self.assertIn("video clip", self.r["muteRefusesAStill"])++ def test_undo_walks_it_back_and_redo_puts_it_on(self):+ on, off, again = self.r["muteIsUndoable"]+ self.assertEqual([on, off, again], [True, False, True])++ def test_it_reaches_the_save_payload(self):+ self.assertTrue(self.r["muteSurvivesTheSavePayload"])++ def test_the_strip_stays_and_says_muted(self):+ # The decision has to be visible and reversible in the place it was+ # made, so the strip is struck through rather than removed.+ fn = extract_function("sbePaintAudioLane", self.src)+ self.assertIn("sbeClipMuted(c)", fn)+ self.assertIn("is-silenced", fn)+ self.assertIn("MUTED", fn)+ self.assertIn(".sbe-aclip.is-silenced", self.src)+ # ...and it is NOT the same state as a file with no audio track.+ self.assertIn(".sbe-aclip.is-mute", self.src)++ def test_the_inspector_offers_it_on_any_video_clip_with_sound(self):+ fn = extract_function("sbePaintInspector", self.src)+ self.assertIn("sbeToggleClipMute()", fn)+ self.assertIn("Mute sound", fn)+ self.assertIn("Unmute sound", fn)+ self.assertIn("c.has_audio !== false", fn)++ def test_the_PREVIEW_is_the_third_output_and_agrees(self):+ # The render drops the clip's lane and the export disables its audio+ # track; the preview has to agree, or the one place the user checks his+ # work is the one place the decision does not exist.+ fn = extract_function("sbeLoadInto", self.src)+ # Muting now goes through the ownership helper, because a muted clip+ # and a clip whose sound the STRIP PLAYER owns both mean the same+ # thing to the picture element: not yours.+ self.assertIn("!!SBE.muted || !sbePictureCarriesSound(c)", fn)+ self.assertIn("sbeClipMuted(c)",+ extract_function("sbePictureCarriesSound", self.src))+++class ThePassiveViewerThatDisarmedTheNet(unittest.TestCase):+ """The owner lost unsaved work because somebody else OPENED his film.++ Seven hours of snapshots stopped and nothing on screen said so. The chain,+ each link measured on the code as it was:++ 1. `GET /storyboard/edit?...&session=T` claimed the board unconditionally,+ so a page LOAD took the claim — a second window, a headless browser,+ an agent reading the board, a preview.+ 2. The tab he was cutting in got 409 `stale_session` on its next+ snapshot and set `SBE.superseded = true`, permanently.+ 3. `sbeQueueSave` returned on that flag BEFORE the line that sets+ `SBE.dirtyAt`, so the timestamp froze at its last pre-supersede value+ while `SBE.backedUpAt` stayed AHEAD of it.+ 4. The 12-second watchdog gates on `backedUpAt < dirtyAt`. With the pair+ frozen that way it read "this work is backed up" forever, so the one+ thing built to catch a dead net could never fire.+ 5. The single 9-second toast expired and the state line it set was+ overwritten by the very next edit. The tab looked completely normal.++ Rule 5 of the ruling is still honoured — a second tab is not a second+ opinion — but it is honoured by TELLING, never by stopping.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()++ def test_a_read_claims_nothing(self):+ # The whole outage in one line: opening a film is not editing it.+ get = panel_source()+ head = get[get.index("def _storyboard_edit_get"):]+ head = head[:head.index("def _storyboard_post")]+ self.assertNotIn("claim_session", head)+ self.assertIn("A READ CLAIMS NOTHING", head)++ def test_writing_is_what_claims_the_board(self):+ src = (ROOT / "storyboard_editor.py").read_text()+ fn = src[src.index("def write_backup("):]+ fn = fn[:fn.index("\ndef ", 10)]+ self.assertIn("claim_session(board_dir, session)", fn)+ # ...and it does not refuse anybody.+ self.assertNotIn("raise EditError(\"this film is open in a newer", fn)++ def test_there_is_no_flag_that_can_switch_the_writer_off(self):+ self.assertNotIn("superseded: false", self.src)+ self.assertNotIn("SBE.superseded = true", self.src)+ queue = extract_function("sbeQueueSave", self.src)+ self.assertNotIn("return;", queue.split("SBE.dirtyAt")[0])++ def test_the_watchdogs_clock_is_armed_before_any_early_return(self):+ # Link 3. `dirtyAt` must be the FIRST thing the queue does, so no guard+ # added later can starve the watchdog the way `superseded` did.+ queue = extract_function("sbeQueueSave", self.src)+ body = queue[queue.index("{") + 1:]+ self.assertLess(body.index("SBE.dirtyAt = Date.now()"),+ body.index("setTimeout"))+ for line in body.split("\n"):+ stripped = line.strip()+ if stripped.startswith("//") or not stripped:+ continue+ self.assertIn("dirtyAt", stripped)+ break++ def test_a_refused_snapshot_raises_the_alarm_like_any_other_failure(self):+ backup = extract_function("sbeBackup", self.src)+ # `stale_session` used to be intercepted as a non-failure ABOVE the+ # alarm. There is no interception left: every path that does not write+ # reaches the same sentence.+ self.assertNotIn("if (r && r.stale_session)", backup)+ self.assertIn("sbeSaveAlarm(", backup)+ self.assertNotIn("older session", backup)++ def test_the_alarm_is_the_persistent_kind_not_a_toast(self):+ # Link 5. A toast expires and a state string is overwritten by the next+ # edit; the alarm stays up until a write actually lands.+ alarm = extract_function("sbeSaveAlarm", self.src)+ self.assertNotIn("phosToast", alarm)+ clear = extract_function("sbeSaveAlarmClear", self.src)+ self.assertTrue(clear)++ def test_a_second_editor_is_information_and_nothing_more(self):+ backup = extract_function("sbeBackup", self.src)+ self.assertIn("SBE.otherEditor", backup)+ paint = extract_function("sbePaintProtected", self.src)+ self.assertIn("also open elsewhere", paint)+++class TheNetSaysWhenItLastCaughtYou(unittest.TestCase):+ """There was no way — for the user OR for anybody helping him — to see+ that the snapshot lane had gone quiet. It was inferred from a directory+ listing, after the loss."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_it_says_how_long_ago_in_the_place_people_already_look(self):+ self.assertIn('id="sbeProtected"', self.src)+ self.assertLess(self.src.index('id="sbeState"'),+ self.src.index('id="sbeProtected"'))++ def test_fresh_reads_as_protected_and_stale_reads_as_NOT(self):+ fresh, cold, never = self.r["protectedChip"]+ self.assertIn("protected", fresh["text"])+ self.assertFalse(fresh["cold"])+ # Past the watchdog's own grace, the chip goes cold on the SAME+ # threshold the banner alarms on — two indicators that can disagree+ # are one indicator and one bug.+ self.assertIn("NOT PROTECTED", cold["text"])+ self.assertTrue(cold["cold"])+ self.assertIn("not backed up yet", never["text"])++ def test_cold_is_stated_against_the_last_SUCCESSFUL_write(self):+ # Not against `dirtyAt`: the outage froze that pair in a way that read+ # "protected" for seven hours. How long ago the net actually caught+ # this tab cannot be faked by a stuck flag.+ fn = extract_function("sbePaintProtected", self.src)+ self.assertIn("SBE.backedUpAt", fn)+ cold = fn[fn.index("const cold"):]+ cold = cold[:cold.index(";")]+ self.assertNotIn("dirtyAt", cold)+++class OneNoticeSurface(unittest.TestCase):+ """Four full-width banners in one column, and they are not mutually+ exclusive.++ Conflict, the save alarm, the validation list and the recovery offer each+ took the full width and stacked. The day the overlap rule refused a J-cut+ the owner had three of them up at once — the timeline pushed off the bottom+ of the screen, and the sentence that mattered was the third one down. They+ still exist as themselves; the surface decides which one is OPEN and folds+ the rest to a chip.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_no_notice_is_no_surface_at_all(self):+ self.assertTrue(self.r["noticeNothingIsNoSurface"]["wrapHidden"])++ def test_a_lone_notice_is_never_a_chip(self):+ # Folding the only thing on screen would hide the sentence to save+ # room nothing else is asking for.+ got = self.r["noticeAloneIsOpen"]+ self.assertEqual(got["lead"], "sbeAlarm")+ self.assertEqual(got["folded"], [])+ self.assertFalse(got["wrapHidden"])++ def test_the_snapshot_offer_is_a_chip_even_when_it_is_alone(self):+ # NO RECOVERY WALL. It was a full-width bar with a primary button,+ # asking a question that had to be answered before the film could be+ # worked on. It is an invitation to go and look.+ got = self.r["noticeQuietIsAlwaysAChip"]+ self.assertEqual(got["folded"], ["sbeRecover"])+ self.assertFalse(got["wrapHidden"])+ self.assertIn('data-quiet="1"', self.src)+ # ...and it points at the place versions live rather than acting.+ el = self.src[self.src.index('id="sbeRecover"'):]+ el = el[:el.index("</div>")]+ self.assertIn("sbeVersionsOpen()", el)+ self.assertNotIn('class="primary"', el)++ def test_urgency_decides_and_it_is_not_the_dom_order(self):+ # The recovery offer is a question about last session; it waits behind+ # every notice that is about the file in front of you.+ got = self.r["noticeUrgencyOrder"]+ self.assertEqual(got["lead"], "sbeAlarm")+ self.assertEqual(got["folded"], ["sbeErrors", "sbeRecover"])++ def test_a_conflict_outranks_everything(self):+ got = self.r["noticeConflictWinsEverything"]+ self.assertEqual(got["lead"], "sbeConflict")+ self.assertEqual(got["folded"], ["sbeAlarm", "sbeErrors", "sbeRecover"])++ def test_clicking_a_chip_opens_it(self):+ got = self.r["noticeClickOpensAChip"]+ self.assertEqual(got["lead"], "sbeRecover")+ self.assertEqual(got["folded"], ["sbeAlarm"])+ # ...and the handler is bound on the CONTAINER, so it survives every+ # repaint of the children and needs no rebinding anywhere.+ self.assertIn('onclick="sbeNoticeClick(event)"', self.src)+ self.assertIn(".is-folded", extract_function("sbeNoticeClick", self.src))++ def test_a_lead_that_closes_hands_the_surface_back(self):+ # Otherwise the override outlives its notice and the next one to open+ # arrives folded behind a chip nobody is looking for.+ got = self.r["noticeLeadThatClosesReleases"]+ self.assertEqual(got["lead"], "sbeAlarm")+ self.assertEqual(got["folded"], [])++ def test_later_is_not_discard(self):+ # Discard DELETES the backup, so it was never the button for "not+ # now" — and with no third option the bar sat across the top of the+ # film for the rest of the session over a question the user was not+ # ready to answer.+ hidden, kept = self.r["noticeLaterHidesAndKeeps"]+ self.assertTrue(hidden)+ self.assertTrue(kept)+ self.assertIn("!!SBE.backupHidden",+ extract_function("sbePaintRecovery", self.src))+ # A NEW offer is not the one that was dismissed.+ self.assertIn("SBE.backupHidden = false", self.src)++ def test_the_validation_list_shows_one_line_and_folds_the_rest(self):+ # Nine clips failing the same rule printed nine copies of the same+ # sentence and pushed the timeline off the screen.+ fn = extract_function("sbeRenderErrors", self.src)+ self.assertIn("SBE.errsOpen", fn)+ self.assertIn("more", fn)+ self.assertIn("sbeErrsToggle()", fn)++ def test_every_banner_still_says_its_own_sentence(self):+ # The surface is CSS and a class, never a rewrite: folding may not be+ # the reason a message stops existing.+ for marker in ("SAVING IS FAILING", "Unsaved snapshot",+ "The timeline was not saved.", "Load theirs", "Keep mine",+ "Restore it", "Discard", "Later", "Open Versions"):+ self.assertTrue(marker in self.src, marker)+ for el_id in ("sbeConflict", "sbeAlarm", "sbeErrors", "sbeRecover"):+ self.assertIn('id="%s"' % el_id, self.src)+ self.assertIn('data-short=', self.src)+++class TheSoundStaysWhereItWasPut(unittest.TestCase):+ """The other half of the J-cut: what happens to the strip AFTERWARDS.++ `audio.film_start` is an absolute film anchor and `sbeLayout` re-derives the+ film position of every clip from the running total of the lead gaps — the+ PICTURE's position and nothing else. So a right trim, a move, a ripple+ delete, an insert or a reorder slid everything downstream while every+ unlinked strip stood still, and a split edit made three shots earlier came+ apart without anybody touching it. Measured on the code as it was:++ trim the tail of shot 1 → shot 3 is +1.00s out+ move shot 2 by hand → shot 3 is -2.00s out+ ripple-delete shot 2 → shot 3 is +4.00s out+ split an unlinked clip → BOTH halves carry {0,4}@4 — one strip+ duplicated, which the server refuses as+ `clips_audio_overlap`+ head-trim with no room → the picture slips inside its own slot and+ takes its own sound out by -1.00s++ The owner, cutting his film: "instead of allowing me to remove or move what+ video is visible while leaving the sound intact and then rematching it, it+ is actually getting the audio out of sync."+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_unlinking_leaves_the_pair_exactly_where_it_was(self):+ s = self.r["pairUnlink"]+ self.assertEqual(s["vid"], [4, 8])+ self.assertEqual(s["snd"], [4, 8])+ self.assertEqual(s["ssrc"], [0, 4])+ self.assertEqual(s["drift"], 0)+ self.assertFalse(s["linked"])++ def test_a_head_trim_does_not_move_the_sound_and_does_not_have_to(self):+ # The in-point and the slot move together, so the frames that remain+ # play at the film second they always did. The seconds of picture that+ # went away leave the sound reaching a second early — a J-cut for free+ # — and the pair is still IN SYNC, which is the whole claim.+ b, c = self.r["pairTrimHead"]+ self.assertEqual(b["vid"], [5, 8])+ self.assertEqual(b["vsrc"], [1, 4])+ self.assertEqual(b["snd"], [4, 8]) # not touched+ self.assertEqual(b["ssrc"], [0, 4]) # not re-windowed+ self.assertEqual(b["drift"], 0)+ # ...and a head trim ripples nothing, so the shot after it is untouched.+ self.assertEqual(c["vid"], [8, 12])++ def test_a_tail_trim_carries_the_sound_of_everything_it_ripples(self):+ # Shot 1 loses a second; shot 3's picture is rigidly translated back by+ # that second and its unlinked sound goes with it. This is the case the+ # owner was hitting from three shots away.+ a, c = self.r["pairTrimTailRipples"]+ self.assertEqual(a["vid"], [0, 3])+ self.assertEqual(c["vid"], [7, 11])+ self.assertEqual(c["snd"], [7, 11]) # was [8, 12] before the fix+ self.assertEqual(c["ssrc"], [0, 4]) # the window is never rewritten+ self.assertEqual(c["drift"], 0)++ def test_moving_a_picture_by_hand_leaves_ITS_OWN_sound_behind(self):+ # The one gesture whose point is to break the pair — and the flag says+ # by how much rather than pretending it did not happen.+ b, c = self.r["pairMove"]+ self.assertEqual(b["vid"], [6, 10])+ self.assertEqual(b["snd"], [4, 8]) # never silently dragged+ self.assertEqual(b["drift"], -2) # the sound now runs early+ # ...while the shot the move pushed keeps its own pair together.+ self.assertEqual(c["vid"], [10, 14])+ self.assertEqual(c["snd"], [10, 14]) # was [8, 12] before the fix+ self.assertEqual(c["drift"], 0)++ def test_ripple_delete_pulls_the_sound_up_with_the_picture(self):+ s = self.r["pairRippleDelete"]+ self.assertEqual(s["vid"], [4, 8])+ self.assertEqual(s["snd"], [4, 8]) # was [8, 12] before the fix+ self.assertEqual(s["drift"], 0)++ def test_a_linked_clip_is_never_written_to_by_the_carry(self):+ # An absent `audio` means LINKED. Writing one to carry a ripple would+ # unlink a clip behind the user's back.+ absent, drift = self.r["pairCarryLeavesLinkedAlone"]+ self.assertTrue(absent)+ self.assertEqual(drift, 0)++ def test_split_cuts_the_strip_once_instead_of_copying_it_twice(self):+ ok, left, right = self.r["pairSplit"]+ self.assertTrue(ok)+ self.assertEqual(left["vid"], [4, 6])+ self.assertEqual(left["snd"], [4, 6])+ self.assertEqual(left["ssrc"], [0, 2])+ self.assertEqual(right["vid"], [6, 8])+ self.assertEqual(right["snd"], [6, 8]) # butt-joined, not overlapped+ self.assertEqual(right["ssrc"], [2, 4])+ self.assertEqual([left["drift"], right["drift"]], [0, 0])++ def test_split_keeps_the_drift_a_pair_already_had(self):+ # The cut is expressed in the source clock the two halves share, so a+ # J-cut survives being split rather than snapping back into sync.+ ok, dl, dr, snd_l, snd_r = self.r["pairSplitKeepsTheDrift"]+ self.assertTrue(ok)+ self.assertEqual([dl, dr], [-2, -2])+ self.assertEqual(snd_l, [4, 6])+ self.assertEqual(snd_r, [6, 8])++ def test_split_refuses_a_cut_the_strip_does_not_reach(self):+ # "This half has no sound" is a state the document cannot express — an+ # absent `audio` means LINKED, which would invent sound the film never+ # had — so the answer is an honest no rather than a guess.+ ok, why, ssrc = self.r["pairSplitOutsideTheStrip"]+ self.assertFalse(ok)+ self.assertIn("does not reach this cut", why)+ self.assertEqual(ssrc, [2, 4])++ def test_resync_puts_the_sound_back_under_the_frame_it_came_from(self):+ ok, s = self.r["pairResync"]+ self.assertTrue(ok)+ self.assertEqual(s["vid"], [6, 10])+ self.assertEqual(s["snd"], [6, 10])+ self.assertEqual(s["drift"], 0)+ # ...and it stays UNLINKED. Rematching is not re-linking.+ self.assertFalse(s["linked"])++ def test_resync_is_a_rematch_and_not_an_un_trim(self):+ # The strip's in-point is one second into the take, so it lands one+ # second after the picture does — that is what "in sync" means for a+ # sound somebody deliberately shortened.+ ok, s = self.r["pairResyncKeepsTheTrim"]+ self.assertTrue(ok)+ self.assertEqual(s["vid"], [5, 9])+ self.assertEqual(s["ssrc"], [1, 4]) # the trim survives+ self.assertEqual(s["snd"], [6, 9])+ self.assertEqual(s["drift"], 0)++ def test_resync_refuses_what_it_has_nothing_to_do_to(self):+ ok, why = self.r["pairResyncRefusesWhenAlreadyThere"]+ self.assertFalse(ok)+ self.assertIn("already in sync", why)+ ok, why = self.r["pairResyncRefusesALinkedClip"]+ self.assertFalse(ok)+ self.assertIn("already under its own picture", why)++ def test_relink_freezes_the_offset_instead_of_throwing_it_away(self):+ # It used to DELETE the field, which snapped the sound back under the+ # picture — so the one button that said "link" destroyed the J-cut the+ # moment it was made. That is why he reached for LOCK instead, and why+ # the clip then refused every drag with a forbidden cursor.+ s, flagged = self.r["pairRelinkFreezesTheOffset"]+ self.assertTrue(flagged) # audio.linked === true+ self.assertEqual(s["vid"], [6, 10])+ self.assertEqual(s["snd"], [4, 8]) # exactly where he put it+ self.assertEqual(s["drift"], -2)+ self.assertTrue(s["coupled"])+ self.assertTrue(s["linked"]) # ...and inert to a drag++ def test_an_in_sync_relink_still_leaves_no_trace(self):+ # The migration promise: a split somebody tried and undid produces a+ # document identical to one that never had the field.+ gone, s = self.r["pairRelinkInSyncRemovesTheField"]+ self.assertTrue(gone)+ self.assertFalse(s["split"])+ self.assertEqual(s["snd"], s["vid"])++ def test_a_coupled_pair_travels_together(self):+ # "You just drag it, and the sound below stays, and then you can lock+ # it and move it, and then the sound starts before the clip starts."+ s, drift, trim_ok = self.r["pairCoupledTravels"]+ self.assertEqual(s["vid"], [10, 14])+ self.assertEqual(s["snd"], [8, 12]) # carried, offset intact+ self.assertEqual(drift, -2)+ self.assertTrue(trim_ok) # and still trimmable++ def test_a_coupled_strip_cannot_be_dragged_on_its_own(self):+ ok, why = self.r["pairCoupledStripRefusesTheDrag"]+ self.assertFalse(ok)+ self.assertIn("travels with its picture", why)++ def test_the_toggle_round_trip_keeps_both_halves_editable(self):+ # What he actually did: unlink, trim, "lock", move, unlink again. Every+ # step is accepted and the offset he built survives all of them.+ tail, made, frozen, moved, head, freed, again = \+ self.r["pairToggleRoundTrip"]+ self.assertEqual(tail, [True, 0]) # tail trim while unlinked+ self.assertEqual(made, -1.5) # the J-cut he dragged+ self.assertEqual(frozen, [-1.5, True]) # re-link keeps it+ self.assertEqual(moved, [-1.5, [7.5, 11.5]]) # the pair moves as one+ self.assertEqual(head, [True, -1.5]) # head trim, still coupled+ self.assertEqual(freed, [-1.5, False, False]) # unlink gives it back+ self.assertEqual(again, [True, -1.5]) # and it is draggable again++ def test_the_scenario_he_described_start_to_finish(self):+ # "I clip a little from the visuals and then move all together to fill+ # the gap. So you start hearing the character before you see it."+ q = self.r["pairHisScenario"]+ # A head trim leaves the strip reaching back under the shot before it —+ # and its DRIFT is zero, because the same source second still plays at+ # the same film second. That is the J-cut, and it is IN SYNC.+ self.assertEqual(q["trimOpensTheGap"], [[5, 8], [4, 8], 0])+ # ...so re-linking may not drop the field on the strength of the drift+ # alone: doing that deleted the second of sound the trim had just+ # exposed. Only a strip that IS the picture's own window can go.+ self.assertEqual(q["frozen"], [True, 0])+ # Then the pair moves as one unit to close the gap.+ self.assertEqual(q["videoDelta"], q["soundDelta"])+ self.assertEqual(q["videoDelta"], -1)+ self.assertEqual(q["moved"], [[4, 7], [3, 7], 0])+ self.assertEqual(q["soundLeadsBy"], 1) # heard before he is seen++ def test_a_coupled_pair_is_never_flagged_as_out_of_sync(self):+ free, coupled, drift = self.r["pairCoupledIsNotFlagged"]+ self.assertTrue(free) # a free strip that drifted carries a flag+ self.assertFalse(coupled) # a frozen relationship does not+ self.assertEqual(drift, -2) # ...even though the offset is real++ def test_resync_reaches_a_couple_and_leaves_nothing_behind(self):+ ok, gone, s = self.r["pairResyncACouple"]+ self.assertTrue(ok)+ self.assertTrue(gone) # a rematched couple has nothing to say+ self.assertEqual(s["snd"], s["vid"])+ self.assertEqual(s["drift"], 0)++ def test_a_coupled_pair_splits_into_two_coupled_pairs(self):+ ok, left, right = self.r["pairSplitACouple"]+ self.assertTrue(ok)+ self.assertEqual([left["vid"], left["snd"]], [[6, 8], [4, 6]])+ self.assertEqual([right["vid"], right["snd"]], [[8, 10], [6, 8]])+ self.assertEqual([left["drift"], right["drift"]], [-2, -2])+ self.assertTrue(left["coupled"] and right["coupled"])++ def test_a_head_trim_can_never_slip_the_picture_inside_its_own_slot(self):+ # Two seconds of head asked for, one second of room: the handle takes+ # the second it has and the mapping of the frames it keeps is unchanged,+ # so the sound underneath is still describing the right frame. Before+ # the clamp the in-point moved the full two seconds while the slot stood+ # still — the tail grew the wrong way and the pair went -1.00s out.+ ok, s = self.r["pairHeadTrimCannotSlip"]+ self.assertTrue(ok)+ self.assertEqual(s["vid"], [2, 6]) # the tail does NOT move+ self.assertEqual(s["vsrc"], [1, 5])+ self.assertEqual(s["drift"], 0)+ got = self.r["pairHeadTrimUsesTheRoomItHas"]+ self.assertEqual(got["vid"], [2.5, 6])+ self.assertEqual(got["vsrc"], [1.5, 5])+ self.assertEqual(got["drift"], 0)+ # Hard against a neighbour there is no room at all, so it refuses.+ ok, why, s = self.r["pairHeadTrimAgainstANeighbour"]+ self.assertFalse(ok)+ self.assertEqual(why, "edge")+ self.assertEqual(s["vid"], [4, 8])++ def test_the_flag_prints_a_signed_number_and_late_is_positive(self):+ early, late, early_label, late_label = self.r["pairDriftSigns"]+ self.assertEqual([early, late], [-2, 2])+ self.assertEqual([early_label, late_label], ["-2.00s", "+2.00s"])++ def test_in_sync_has_a_tolerance_of_half_a_frame(self):+ exact, near, past, linked = self.r["pairInSyncTolerance"]+ self.assertTrue(exact)+ self.assertTrue(near) # 1/96 s — inside half a frame at 24 fps+ self.assertFalse(past) # 1/12 s — two frames, and it says so+ self.assertTrue(linked) # a linked clip cannot drift++ def test_both_halves_of_a_drifted_pair_carry_the_flag(self):+ # The blocks sit in different lanes, so "are these still together" is+ # not a question the eye can answer at fit zoom.+ for fn in ("sbePaintTrack", "sbePaintAudioLane"):+ self.assertIn("sbeSyncBadge(c)", extract_function(fn, self.src))+ badge = extract_function("sbeSyncBadge", self.src)+ self.assertIn("sbeAudioInSync(c)", badge)+ self.assertIn("sbeDriftLabel", badge)+ self.assertIn('data-sync="', badge)++ def test_the_flag_is_a_button_and_neither_drag_handler_swallows_it(self):+ for fn in ("sbeOnTrackDown", "sbeOnAudioDown"):+ body = extract_function(fn, self.src)+ self.assertIn(".sbe-sync", body)+ self.assertIn("sbeResyncSel(badge.dataset.sync)", body)+ # ...and it happens BEFORE the drag is armed, or pointerdown wins.+ self.assertLess(body.index("sbe-sync"), body.index("setPointerCapture"))++ def test_the_inspector_offers_the_rematch_next_to_the_relink(self):+ fn = extract_function("sbePaintInspector", self.src)+ self.assertIn("sbeResyncSel()", fn)+ self.assertIn("Resync sound", fn)+ self.assertIn("sbeAudioInSync(c)", fn)+ # The two verbs are different and the inspector says which is which.+ self.assertLess(fn.index("Re-link sound"), fn.index("Resync sound"))++ def test_a_locked_shot_says_so_instead_of_a_forbidden_cursor(self):+ # `.sbe-clip.is-locked` sets `cursor: not-allowed` and hides both+ # grips, and the drag handler refused in silence — so a locked shot+ # read as an editor that had broken. He hit it precisely because Lock+ # was the only button that sounded like "keep these two together".+ self.assertIn(".sbe-clip.is-locked { cursor: not-allowed; }", self.src)+ body = extract_function("sbeOnTrackDown", self.src)+ self.assertIn("c.locked", body)+ self.assertIn("click Unlock in the", body)+ # ...and the refusal happens BEFORE the drag is armed.+ self.assertLess(body.index("c.locked"), body.index("setPointerCapture"))+ lane = extract_function("sbeOnAudioDown", self.src)+ self.assertIn("c.locked", lane)++ def test_the_right_grip_is_on_the_RIGHT(self):+ # `.sbe-grip { left: 0 }` was written after `.sbe-grip.r { right: 0 }`,+ # and a box with left, right and width all set is over-constrained —+ # LTR drops `right`. Both grips rendered on top of each other at the+ # LEFT edge of every clip: measured live, clip 315–455, `.l` 316–325,+ # `.r` 316–325. So the right edge had no handle (pulling the tail MOVED+ # the clip) and the left edge hit `.r`, later in DOM order, so reaching+ # for the head trimmed the TAIL. Both lanes, every clip.+ src = self.src+ widen = src.index(".sbe-grip { left: 0; }")+ fix = src.index(".sbe-grip.r { left: auto; right: 0; }")+ self.assertLess(widen, fix, "the reset must come AFTER the widening")+ # ...and the pseudo-element skirt still covers the border column.+ #+ # THE 3 IS A VARIABLE NOW, and this assertion had to follow it there.+ # The fade handle's inset is measured from the far side of this skirt —+ # `grip-w + skirt` is the first x on a block that is not a trim — so+ # the two numbers are one number, declared on `.sbe-tl` and read by+ # both. This used to assert the whole rule as one literal line, which+ # is a spelling and not a behaviour: what it is really protecting is+ # that the skirt is still NEGATIVE on the horizontal axis and zero on+ # the vertical, so the grip can be hit past what it draws without+ # growing over the block above or below it. The effect is measured for+ # real in `scripts/measure_editor_layout.py`, which reconstructs the+ # grip's true hit rectangle from this custom property and fails if+ # anything else has moved into it.+ skirt = src[src.index(".sbe-grip::before {"):]+ skirt = skirt[:skirt.index("}") + 1]+ self.assertIn("position: absolute", skirt)+ self.assertIn("inset: 0 calc(-1 * var(--sbe-grip-skirt", skirt)+ self.assertIn("--sbe-grip-skirt: 3px;", src)+ self.assertIn("--sbe-grip-w: 9px;", src)++ def test_the_corner_handle_stands_beside_the_grip_and_not_inside_it(self):+ """"Not sure that grabbing the top corner is working."++ Measured on his screen: `.sbe-fade-h` was 12x12 at `top:0; left:0` with+ `z-index: 7`, and `.sbe-grip` was 9x54 at the SAME corner with+ `z-index: 6` and a 3px hit skirt. On a 56px block the fade owned the+ top 22% of that corner and the trim owned the other 78%, so aiming at+ the corner hit trim almost every time. The handler was already correct+ — the fade is tested before the grips — and no handler can rescue a+ target that is not there.++ The two are separated in SPACE now: the grip keeps the outer strip for+ the block's full height because trimming is an edge gesture, and the+ handle sits inset from it, starting exactly where the grip's hit area+ stops. The inset is DERIVED from the grip's own two variables so the+ two can never drift; the rectangles are then measured for real, at both+ ends of the lane range, by `scripts/measure_editor_layout.py`.+ """+ src = self.src+ band = src[src.index(".sbe-fade-band {"):]+ band = band[:band.index("}")]+ # Inset from BOTH grips, by the grip's own width plus its own skirt.+ for side in ("left", "right"):+ self.assertIn(f"{side}: calc(var(--sbe-grip-w, 9px) + "+ f"var(--sbe-grip-skirt, 3px))", band)+ # The two handles share a band too narrow for both rather than stack on+ # it, which is the other overlap the old absolute boxes could produce.+ self.assertIn("justify-content: space-between", band)+ self.assertIn("pointer-events: none", band)++ handle = src[src.index(" .sbe-fade-h {"):]+ handle = handle[:handle.index("}")]+ self.assertIn("flex: 0 1 var(--sbe-fade-hit, 22px)", handle)+ self.assertIn("pointer-events: auto", handle)+ # A REAL TARGET, sized against the SHORTEST lane the share table can+ # produce rather than against a lane the user can drag. 12px was a+ # fraction of a picture track that later lost a quarter of its height+ # in the calm-chrome rebalance, and nobody touched the handle.+ hit = int(re.search(r"--sbe-fade-hit:\s*(\d+)px", src).group(1))+ self.assertGreaterEqual(hit, 20)+ # THE SHORTEST LANE THE SHARE TABLE CAN PRODUCE, read back out of the+ # table rather than written down here — the whole point is that the+ # handle must not be sized against a number somebody can move. The+ # block inside a lane is inset 6px top and bottom; the strip 3px.+ lanes = dict(re.findall(+ r"\{ key: '(\w+)',\s+base:\s*(\d+), cap:\s*\d+, share: [\d.]+ \}",+ src))+ for key, inset in (("track", 12), ("alane", 7)):+ block = int(lanes[key]) - inset+ self.assertLess(+ hit, block,+ f"a {hit}px handle does not fit the {block}px block a "+ f"{lanes[key]}px {key} lane leaves at its floor")++ # ...and both lanes emit it, wrapped, so neither can drift from the+ # other: a strip that behaved differently from the block above it would+ # be a difference no user could name.+ track = extract_function("sbePaintTrack", src)+ lane = extract_function("sbePaintAudioLane", src)+ for fn, attr in ((track, "data-fade"), (lane, "data-afade")):+ self.assertIn('sbe-fade-band', fn)+ self.assertLess(fn.index("sbe-fade-band"), fn.index(attr + '="in"'))++ def test_the_level_line_declines_while_the_pointer_is_on_a_handle(self):+ # The clipped hit path keeps the LINE off the handles' pixels, but the+ # same pair also answers a proximity test that knows nothing about+ # paths — and the hover ghost asks it. Without this a fade handle sat+ # under a ghost promising a keyframe it could never place. Asked of the+ # real hit target rather than of a rectangle, so it stays exact at+ # every lane height and every zoom.+ fn = extract_function("sbeStripAt", self.src)+ self.assertIn("ev.target.closest('.sbe-fade-h')", fn)+ self.assertLess(fn.index(".sbe-fade-h"), fn.index("sbeStripEditable"))++ def test_the_sync_flag_stays_out_of_both_gestures_in_that_corner(self):+ # It was already clear of the grips. The fade handle then moved into+ # the space it was standing in, and the handle is higher in the stack —+ # so the flag would have had its clicks swallowed by a control that was+ # not there when its position was chosen. Derived from the same three+ # variables, so it cannot be left behind a second time.+ # The rule that PLACES it, which is the last `.sbe-sync {` that sets a+ # `right` — the ones after it only nudge `top` per block kind.+ css = [b for b in re.findall(r"\.sbe-sync \{(.*?)\}", self.src, re.S)+ if "right:" in b]+ self.assertTrue(css, "no .sbe-sync rule sets a `right`")+ css = css[-1]+ self.assertIn("var(--sbe-grip-w", css)+ self.assertIn("var(--sbe-grip-skirt", css)+ self.assertIn("var(--sbe-fade-hit", css)+ # ...and both pointerdown handlers still test it first, which is what+ # makes the z-index above the band safe rather than a second bug.+ for fn in ("sbeOnTrackDown", "sbeOnAudioDown"):+ body = extract_function(fn, self.src)+ self.assertLess(body.index(".sbe-sync"), body.index(".sbe-fade-h"))++ def test_a_drag_that_moved_only_the_SOUND_is_still_an_edit(self):+ # `sbeOnTrackUp` decides "did anything change" from a fingerprint of+ # four picture fields, and RESTORES the pointerdown snapshot when they+ # match. A gesture whose only effect was on a strip — a ripple carrying+ # an unlinked sound, a coupled pair travelling with its picture — was+ # therefore discarded: the document was never marked dirty and the+ # header went on saying "saved · revision N" over the work it had just+ # thrown away.+ # THE FINGERPRINT IS A NAMED FUNCTION NOW, so this is driven rather+ # than read: the closure it replaces was rewritten once per gesture and+ # was short each time. `sbeDragFingerprint` is exercised in the node+ # harness against every mode that writes a field — see+ # `TheSoundsEnvelopeOnTheClient.test_every_mode_a_track_drag_has`.+ body = extract_function("sbeOnTrackUp", self.src)+ self.assertIn("sbeDragFingerprint(before)", body)+ self.assertLess(body.index("sbeDragFingerprint(before)"),+ body.index("SBE.dirty = true"))+ fp = extract_function("sbeDragFingerprint", self.src)+ self.assertIn("JSON.stringify(c.audio || null)", fp)++ def test_the_locked_toast_names_the_verb_he_actually_wanted(self):+ body = extract_function("sbeOnTrackDown", self.src)+ self.assertIn("locked to its place on the __SEQ__", body)+ self.assertIn("Link sound", body)++ def test_neither_lane_can_be_wedged_by_the_other_s_lost_pointerup(self):+ # A pointerup that lands off the edge leaves a drag object behind, and+ # a stale one makes the next gesture answer to the wrong lane.+ self.assertIn("SBE.audioDrag = null;", extract_function("sbeOnTrackDown", self.src))+ self.assertIn("SBE.drag = null;", extract_function("sbeOnAudioDown", self.src))++ def test_the_toggle_names_the_offset_it_is_about_to_freeze(self):+ fn = extract_function("sbePaintInspector", self.src)+ self.assertIn("'Link sound'", fn)+ self.assertIn("Re-link sound", fn)+ self.assertIn("sbeAudioInSync(c)", fn)++ def test_every_reflow_marks_the_sound_before_it_moves_the_picture(self):+ # The carry is the fix, and a new operation that calls sbeLayout without+ # it is the same bug again. Each of these reflows the track.+ for fn in ("sbeMoveTo", "sbeTrim", "sbeRippleDelete", "sbeSplitAt",+ "sbeInsertAt", "sbeReorderTo", "sbePlaceUnplaced"):+ body = extract_function(fn, self.src)+ self.assertIn("sbeSyncMark(", body, fn)+ self.assertIn("sbeSyncCarry(", body, fn)+ self.assertLess(body.index("sbeSyncMark("), body.index("sbeSyncCarry("), fn)+++class TimelineVersions(unittest.TestCase):+ """Wave 4 — what the picker says about a file you would restore over your+ own work. Wording is the entire interface here, so it is a gate."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_the_age_reads_as_a_duration_in_one_unit(self):+ self.assertEqual(self.r["ago"],+ ["just now", "5 min ago", "2 h ago", "5 d ago", ""])++ def test_an_autosave_says_so_and_names_what_it_holds(self):+ line = self.r["lineAuto"]+ self.assertEqual(line["name"], "autosave")+ self.assertEqual(line["meta"], "revision 7 · 9 clips · 0:39.71 · 5 min ago")+ self.assertFalse(line["kept"])++ def test_an_unnamed_save_is_not_called_an_autosave(self):+ # The two-lane split exists to separate the user's decisions from the+ # machine's, and then labelled his decisions with the machine's word:+ # the lane headed YOUR SAVES OF THIS DRAFT listed rows called+ # "autosave".+ self.assertEqual(self.r["lineMine"]["name"], "Save")++ def test_the_verb_that_names_a_save_is_reachable_again(self):+ # The route is alive and documented; the drafts rewrite left the panel+ # with no way to press it, while the history went on rendering named+ # saves in their own accent — so the owner's film contains a kind of+ # entry he had no way to make again.+ self.assertIn('id="sbeKeepSaveBtn"', self.src)+ fn = extract_function("sbeKeepVersion", self.src)+ self.assertIn("'/storyboard/edit/version'", fn)+ self.assertIn("fd.set('label', label)", fn)+ self.assertIn("sbeVersionsLoad()", fn)++ def test_the_name_field_knows_which_verb_it_is(self):+ # Enter was hard-wired to "new draft", so pressing Rename on a row,+ # typing, and pressing Enter created a duplicate draft carrying the+ # half-edited name. The old order also focused the box BEFORE writing+ # the old name into it, so the caret sat behind the text and typing+ # appended to it.+ self.assertIn("sbeNameEnter()", self.src)+ enter = extract_function("sbeNameEnter", self.src)+ self.assertIn("SBE.renaming", enter)+ ren = extract_function("sbeDraftRename", self.src)+ self.assertIn("sbeNameMode(slug)", ren)+ self.assertIn("box.value = was || '';", ren)+ self.assertLess(ren.index("box.value = was"), ren.index("box.focus()"))+ self.assertIn("box.select()", ren)++ def test_the_drafts_list_cannot_be_squeezed_out_by_the_snapshots(self):+ # Both lists carried `flex: 1 1 auto; min-height: 0` inside one+ # 520px box, so expanding fifty automatic snapshots collapsed "This+ # film's drafts" — the headline of the whole feature — to an+ # eleven-pixel sliver, with the row for the draft you have OPEN the+ # one cut in half.+ css = self.src[self.src.index(".sbe-vers-list {"):]+ css = css[:css.index(".sbe-vers-row {")]+ self.assertIn("#sbeDraftList { flex: 0 0 auto;", css)+ self.assertIn("#sbeVersList { flex: 1 1 auto;", css)++ def test_a_named_version_shows_its_name(self):+ line = self.r["lineKept"]+ self.assertEqual(line["name"], "the good one")+ self.assertIn("1 clip ", line["meta"] + " ")+ self.assertTrue(line["kept"])++ def test_an_unreadable_entry_says_that_rather_than_disappearing(self):+ line = self.r["lineBad"]+ self.assertEqual(line["name"], "unreadable")+ self.assertTrue(line["bad"])++ # ---- the markup ------------------------------------------------------+ def test_the_save_button_says_it_saved(self):+ self.assertIn('id="sbeSaveBtn" onclick="sbeSaveNow()"', self.src)+ fn = extract_function("sbeSaveNow", self.src)+ self.assertIn("Saved — revision", fn)+ # ...and the autosave stays silent: it fires a second after every drag.+ self.assertNotIn("phosToast", extract_function("sbeQueueSave", self.src))++ def test_no_draft_verb_reaches_for_a_browser_dialog(self):+ # The rule is "names in this app are typed into panel controls, never+ # into a browser dialog", and it was enforced for `window.prompt`+ # only — so `sbeDraftDelete` gated the one DESTRUCTIVE verb in this+ # feature on a `window.confirm`, the single piece of Chrome chrome on+ # a claude.ai-grade surface. Delete is a two-step in the panel now.+ self.assertIn('id="sbeVersName"', self.src)+ for name in ("sbeDraftNew", "sbeDraftRename", "sbeDraftDelete",+ "sbeKeepVersion"):+ fn = extract_function(name, self.src)+ for bad in ("window.prompt", "window.confirm", "window.alert"):+ self.assertNotIn(bad, fn, f"{name} / {bad}")+ for name in ("sbeDraftNew", "sbeDraftRename"):+ self.assertIn("sbeEl('sbeVersName')",+ extract_function(name, self.src))+ arm = extract_function("sbeDraftDelete", self.src)+ self.assertIn("'Delete?'", arm)+ self.assertIn("btn.dataset.armed", arm)+ self.assertIn("'/storyboard/edit/draft'",+ extract_function("sbeDraftOp", self.src))++ def test_only_the_user_writes_his_draft(self):+ # "He should have control over the saving, and only he should have+ # that control." The debounce every mutation calls now writes a crash+ # BACKUP; the Save button is the only thing that writes the document.+ q = extract_function("sbeQueueSave", self.src)+ self.assertIn("sbeBackup()", q)+ self.assertNotIn("sbeSave(", q)+ b = extract_function("sbeBackup", self.src)+ self.assertIn("'/storyboard/edit/backup'", b)+ self.assertNotIn("sbeAdopt", b) # it changes nothing on screen+ self.assertIn("expect: null", b) # it cannot conflict with anything+ # ...and leaving the tab backs up rather than saving over his draft.+ close = extract_function("sbeCloseDoc", self.src)+ self.assertIn("sbeBackup(true)", close)+ self.assertNotIn("sbeSave(true)", close)++ def test_opening_a_film_is_not_an_edit_to_it(self):+ # sbeAdopt sets the mode dropdown to agree with the document on every+ # load, and that call was marking the document dirty and queueing a+ # write — so every OPEN of every film produced a save nobody made.+ fn = extract_function("sbeSetMusicMode", self.src)+ self.assertIn("if (String(SBE.audio.mode || 'under') === mode) return;", fn)+ self.assertLess(fn.index("=== mode) return"), fn.index("SBE.dirty = true"))++ def test_the_lane_has_nothing_left_to_guard(self):+ # The guard is gone because the thing it guarded is gone: snapshots+ # are per-file now, so writing one cannot destroy another. What must+ # NOT come back is any early return keyed on an unanswered offer.+ fn = extract_function("sbeBackup", self.src)+ self.assertNotIn("if (SBE.backup) return false;", fn)+ self.assertIn("versioned now", fn)+ self.assertNotIn("return;", fn) # it still answers its callers++ def test_a_backup_that_is_not_being_written_still_screams(self):+ # It is the safety net, and its absence is invisible by nature.+ self.assertIn("sbeSaveAlarm", extract_function("sbeBackup", self.src))++ def test_the_switch_is_REFUSED_when_the_backup_could_not_write(self):+ # Driven, not grepped: with an unanswered offer on screen the backup+ # cannot write, so the draft op must refuse before anything leaves the+ # panel and must not clear `dirty` on the way out.+ got, fetches, dirty, said = \+ self.r["draftSwitchRefusesWhenTheBackupCannotWrite"]+ self.assertIs(got, False)+ # The one fetch is the snapshot POST that failed; the draft op itself+ # never left the panel.+ self.assertEqual(fetches, 1)+ self.assertTrue(dirty)+ self.assertIn("unsaved changes", said)++ def test_nothing_swaps_the_document_on_a_backup_that_did_not_happen(self):+ # `await sbeBackup(true)` with the result thrown away: the switch went+ # ahead, cleared `dirty` and adopted the server's document — while+ # `activate_draft` stashes the last SAVED file, so the work on screen+ # went with no offer, no toast and nothing to click. The comment above+ # the call states the exact invariant the missing branch broke.+ fn = extract_function("sbeDraftOp", self.src)+ self.assertIn("!(await sbeBackup(true))", fn)+ self.assertIn("could not be snapshotted", fn)+ self.assertIn("return false;", fn)++ def test_nothing_acts_on_the_saved_file_after_a_save_that_failed(self):+ # Restore, relink, render and the NLE export all read what is on+ # DISK. A save that 409s or errors leaves the server holding an older+ # cut, and every one of these would then act on that one — the render+ # most visibly, by building a film that is quietly not the one on+ # screen.+ for name in ("sbeRestoreVersion", "sbeRelink", "sbeRenderFilm",+ "sbeExportNle"):+ fn = extract_function(name, self.src)+ self.assertIn("!(await sbeSave(true))", fn, name)+ self.assertIn("kind: 'danger'", fn, name)++ def test_the_recovery_is_an_offer_and_never_an_action(self):+ # Silently applying a newer backup would be the autosave the owner+ # asked us to remove, wearing a different name.+ el = self.src[self.src.index('id="sbeRecover"'):]+ el = el[:el.index("</div>")]+ self.assertIn("Unsaved snapshot", el)+ self.assertIn("Restore it", el)+ self.assertIn("Discard", el)+ paint = extract_function("sbePaintRecovery", self.src)+ # It says WHAT IT IS, not what to do about it: the old sentence+ # compared clip counts out loud and then said "Nothing has been+ # changed", which read as a question about a difference it could not+ # name. See docs/EDITOR_SAVE_MODEL.md §4.+ self.assertIn("your saved draft is untouched", paint)+ self.assertNotIn("Nothing has been changed", paint)+ # The offer is painted on adopt; nothing calls sbeRecover for you.+ adopt = extract_function("sbeAdopt", self.src)+ self.assertIn("sbePaintRecovery()", adopt)+ self.assertNotIn("sbeRecover()", adopt)++ def test_the_users_saves_come_before_the_machines(self):+ # "The auto saves should be saved separately from the manual saves, at+ # least, so the user can go back and see the manual saves."+ fn = extract_function("sbeVersionsPaint", self.src)+ self.assertIn("Your saves of this draft", fn)+ self.assertIn("v.manual !== false", fn)+ self.assertIn("automatic snapshot", fn)+ self.assertIn("<details", fn)+ # The user's lane is drawn first, the machine's is folded under it.+ self.assertLess(fn.index("Your saves of this draft"),+ fn.index("automatic snapshot"))++ def test_the_draft_you_are_cutting_names_itself(self):+ fn = extract_function("sbePaintDraft", self.src)+ self.assertIn("sbeDraftName", fn)+ self.assertIn("dot.hidden = !SBE.dirty", fn)+ # The chip and the dot cannot disagree — one drives the other.+ self.assertIn("sbePaintDraft()", extract_function("sbeSetState", self.src))++ def test_every_draft_verb_goes_through_one_door(self):+ fn = extract_function("sbeDraftOp", self.src)+ for op in ("new", "duplicate", "rename", "delete", "activate"):+ self.assertIn(op, self.src)+ # Switching drafts backs the current one up first, or the last few+ # minutes would be left pointing at a draft nobody is looking at.+ self.assertIn("await sbeBackup(true)", fn)+ self.assertIn("sbeAdopt(r, true)", fn)++ def test_the_panel_is_portalled_to_the_body(self):+ # The header and the stage column both carry overflow; a panel left+ # where it was declared is sliced at their edge.+ fn = extract_function("sbeVersionsEl", self.src)+ self.assertIn("document.body.appendChild", fn)++ def test_restore_adopts_the_server_payload_and_drops_the_undo_stack(self):+ fn = extract_function("sbeRestoreVersion", self.src)+ self.assertIn("'/storyboard/edit/restore'", fn)+ self.assertIn("SBE.undo.length = 0", fn)+ self.assertIn("sbeAdopt(r, true)", fn)+ # It says what happened to the arrangement it replaced.+ self.assertIn("was kept", fn)+++class TheTimelineIsResizable(unittest.TestCase):+ """The top edge is a handle, and the height it drags lands on the SOUND.++ "The timeline is too constricted and cannot be expanded vertically. It+ needs to allow you to drag the upper side of the timeline, which will+ change the layout a little bit, enabling expansion in case you have some+ sound editing in there."++ Nothing here resizes an element: the drag moves one number and+ sbeFitMonitors sizes the monitors off what is left. So the tests are about+ that number — what it may be, where it goes, and where it is kept.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ # ---- the clamps ------------------------------------------------------+ def test_the_timeline_can_never_collapse_or_eat_the_monitors(self):+ c = self.r["tlClamp"]+ self.assertEqual(c["under"], 280) # its own contents are the floor+ self.assertEqual(c["over"], 600) # what the window measured+ self.assertEqual(c["exact"], 400)+ # A window with nothing to spare pins the handle rather than handing+ # the monitors a negative height.+ self.assertEqual(c["noRoom"], 280)+ # ...and no measurement can authorise more than the lanes can use.+ self.assertEqual(c["ceiling"], 638)+ self.assertEqual(c["junk"], 280)++ def test_the_ceiling_leaves_the_monitors_a_picture(self):+ # The one clamp that keeps this honest lives in sbeFitMonitors: the+ # timeline's ceiling is the column minus the smallest thing that is+ # still a monitor, which is the floor sbeMonitorFit has always used.+ fn = extract_function("sbeFitMonitors", self.src)+ self.assertIn("SBE_MON_MIN_H", fn)+ self.assertIn("SBE.tlMax", fn)+ self.assertIn("sbeTlClamp(SBE.tlH", fn)+ # The preference is READ here and never written: shrink the window and+ # the height is given back, widen it and the drag is still there.+ self.assertNotIn("SBE.tlH =", fn)++ # ---- where the height goes ------------------------------------------+ def test_at_the_floor_the_sound_is_already_legible(self):+ # The bases the 2026-08-20 rebalance settled on. The clip strip starts+ # at 44 rather than 26 because a level line has to be a control AT+ # REST — "I still don't understand how to add keyframes" was said+ # about a 20px band — and the picture drops to 64 because its block is+ # a label with a thumbnail hint, not a poster.+ # ...and the soundtrack starts at 108 rather than 72 for the same+ # reason one lane up: the bed carries a level line, points and two+ # corner fade handles now, and its HEAD carries the mix — the level+ # and the duck the renderer used to keep to itself.+ self.assertEqual(self.r["lanesAtFloor"],+ {"ruler": 18, "ov": 32, "track": 64,+ "alane": 44, "wave": 108})++ def test_every_dragged_pixel_is_spent_on_a_lane(self):+ # Chrome + the four lanes == the height that was asked for, at both+ # ends and in the middle. A distribution that loses pixels leaves a+ # dead band under the soundtrack.+ self.assertEqual(self.r["laneSums"], [0, 0, 0])++ def test_the_sound_takes_the_biggest_share_because_that_was_the_ask(self):+ g = self.r["laneGain"]+ self.assertEqual(sum(g.values()), 100)+ # 70 of every 100px goes to the two sound lanes...+ self.assertGreaterEqual(g["alane"] + g["wave"], 70)+ # ...and the per-clip strip — the one with the level line and the+ # points on it — takes the single biggest share.+ self.assertEqual(max(g, key=g.get), "alane")+ # A 26px strip becomes one you can actually put a keyframe in.+ self.assertGreaterEqual(self.r["lanesMid"]["alane"], 60)++ def test_a_capped_lane_hands_its_share_back_rather_than_dropping_it(self):+ # 340px of drag fills the two lanes with the tightest caps — the+ # overlay strip and the per-clip sound — and what they cannot take is+ # offered AGAIN to the lanes still growing rather than left as dead+ # band at the bottom of the box.+ past = self.r["lanesPastTheTrackCap"]+ self.assertEqual(past["ov"], 56)+ self.assertEqual(past["alane"], 190)+ self.assertEqual(self.r["laneRedistributed"], 0)+ # Both survivors have MORE than their bare share of 340px (47.6 and+ # 115.6) — the difference is what the two capped lanes handed back.+ self.assertGreater(past["track"], 64 + 48)+ self.assertGreater(past["wave"], 108 + 116)++ def test_the_ruler_never_grows(self):+ # It is a scale, not a surface: a taller ruler is not a more legible+ # one, and every pixel it took would be a pixel off a waveform.+ self.assertEqual(self.r["rulerFixed"], [18, 18])++ def test_at_the_ceiling_every_lane_is_at_its_cap(self):+ self.assertEqual(self.r["lanesAtCeiling"],+ {"ruler": 18, "ov": 56, "track": 120,+ "alane": 190, "wave": 240})++ # ---- where the preference lives -------------------------------------+ def test_the_height_survives_a_reload_and_is_clamped_on_the_way_back(self):+ p = self.r["tlPref"]+ self.assertEqual(p["fresh"], 280) # nothing stored → the floor+ self.assertEqual(p["stored"], "392")+ self.assertEqual(p["restored"], 392) # what the next tab reads+ self.assertEqual(p["absurd"], 638) # a stored screenful is capped+ self.assertEqual(p["junk"], 280) # ...and junk is the floor+ self.assertEqual(p["keys"], ["phos_sbe_tl_h"])++ def test_the_height_is_a_view_preference_and_NOT_sequence_data(self):+ # It is not in the save payload, so a drag cannot bump the document's+ # revision, race the snapshot lane, or hand the next machine somebody+ # else's screen. localStorage is where every other view preference in+ # this panel already lives.+ self.assertEqual(self.r["tlIsNotInTheSave"], [-1, -1, -1])+ self.assertIn("localStorage.getItem('phos_sbe_tl_h')", self.src)+ self.assertIn("localStorage.setItem('phos_sbe_tl_h'", self.src)+ # The server's document model has never heard of it.+ model = (Path(__file__).resolve().parent+ / "storyboard_editor.py").read_text(encoding="utf-8")+ self.assertNotIn("tl_h", model)++ # ---- the handle itself ----------------------------------------------+ def test_the_handle_is_on_the_timelines_top_edge_and_costs_no_height(self):+ el = extract_element("sbeTlGrab", self.src)+ self.assertIn("sbeTlGrabDown(event)", el)+ self.assertIn("sbeTlGrabMove(event)", el)+ self.assertIn("sbeTlGrabUp(event)", el)+ self.assertIn("sbeTlReset()", el) # double-click resets+ self.assertIn('role="separator"', el)+ self.assertIn('tabindex="0"', el)+ # It lives INSIDE the transport, absolutely positioned over the gap+ # below it: sbeFitMonitors budgets against every child of the column+ # it can measure, so a grip with a height of its own would have been+ # paid for out of the picture.+ transport = self.src[self.src.index('<div class="sbe-transport">'):]+ transport = transport[:transport.index("<div class=\"sbe-tl\"")]+ self.assertIn('id="sbeTlGrab"', transport)+ css = self.src[self.src.index(".sbe-tl-grab {"):]+ css = css[:css.index(".sbe-tl-grab:focus-visible {")]+ self.assertIn("position: absolute", css)+ self.assertIn("cursor: row-resize", css)+ self.assertIn("bottom: -8px", css)++ def test_the_drag_captures_the_pointer_and_does_not_select_the_page(self):+ down = extract_function("sbeTlGrabDown", self.src)+ self.assertIn("setPointerCapture", down)+ self.assertIn("sbe-resizing", down)+ # NOT preventDefault: cancelling pointerdown suppresses the+ # compatibility mouse events, and the double-click reset is one.+ self.assertNotIn("ev.preventDefault()", down)+ up = extract_function("sbeTlGrabUp", self.src)+ self.assertIn("releasePointerCapture", up)+ self.assertIn("sbeTlPrefWrite", up) # the drag is what persists+ self.assertIn("body.sbe-resizing { user-select: none;", self.src)++ def test_up_is_taller(self):+ # clientY falls as the pointer rises, so the delta is SUBTRACTED. Get+ # this backwards and the handle runs away from the pointer.+ move = extract_function("sbeTlGrabMove", self.src)+ self.assertIn("d.h0 - (ev.clientY - d.y0)", move)++ def test_the_handles_arrows_do_not_reach_the_editors_own_shortcuts(self):+ key = extract_function("sbeTlGrabKey", self.src)+ self.assertIn("stopPropagation", key) # ←→ are a frame at a time+ self.assertIn("ArrowUp", key)+ self.assertIn("ArrowDown", key)++ def test_the_lanes_are_painted_at_the_height_they_were_given(self):+ # The strip's waveform and its level line are drawn into H, and H is+ # the lane's own height — not the 20px the strip used to be. A+ # keyframe's drag reads the strip's RECTANGLE for the same reason, so+ # the picture and the pointer cannot disagree.+ wave = extract_function("sbeStripWave", self.src)+ self.assertIn("const H = sbeStripH()", wave)+ self.assertNotIn("const H = 20", wave)+ # EVERY gesture that reads a level goes through the one pair, so none+ # of them can carry its own copy of a band again.+ move = extract_function("sbeOnAudioMove", self.src)+ self.assertIn("sbeStripGain(ev.clientY, r.top, r.height)", move)+ self.assertNotIn("/ 20)", move)+ dbl = extract_function("sbeOnAudioDbl", self.src)+ self.assertIn("sbeStripGain(ev.clientY, r.top, r.height)", dbl)+ self.assertNotIn("r.top - 3", dbl)+ wave = extract_function("sbeStripWave", self.src)+ self.assertIn("sbeStripY(g, H)", wave)+ # ...and the soundtrack's canvas reads the same distribution.+ cv = extract_function("sbePaintWave", self.src)+ self.assertIn("sbeLaneHeights(", cv)+ self.assertNotIn("const h = 54", cv)++ def test_the_handle_stands_down_where_the_page_is_the_scroller(self):+ # Below the stacking breakpoint sbeFitMonitors removes its variables+ # and returns; a handle that moved a number nobody reads would be a+ # control that does nothing.+ narrow = self.src[self.src.index("@media (max-width: 900px) {"):]+ narrow = narrow[:narrow.index("CAPABILITY TIER")]+ self.assertIn(".sbe-tl-grab { display: none; }", narrow)+ fn = extract_function("sbeFitMonitors", self.src)+ self.assertIn("'--sbe-tl-h'", fn)+ self.assertIn("removeProperty", fn)++ def test_the_resize_does_not_reflow_the_notice_surface(self):+ # THE rule: notices live in one compact surface and never push the+ # workspace around. The handle writes variables onto #sbTimeline and+ # touches nothing else, so there is no path from a drag to a notice.+ for fn in ("sbeTlSet", "sbeApplyTl", "sbeTlGrabDown", "sbeTlGrabUp",+ "sbeTlReset"):+ body = extract_function(fn, self.src)+ self.assertNotIn("sbeNotice", body)+ self.assertNotIn("phosToast", body)+ self.assertNotIn("sbePaintNotices", body)+++class TheLevelLineTeachesItself(unittest.TestCase):+ """"I still don't understand how to add keyframes, to be honest."++ Said after using it, which makes it a defect in the control and not in the+ user. The gesture was double-click to add, drag to set, shift-click to+ remove — three things knowable only by being told. These lock the routes+ that replaced it, and the arithmetic that has to hold at every lane height+ the resize handle can produce.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ # ---- the arithmetic -------------------------------------------------+ def test_the_gain_round_trips_at_every_height_the_table_can_produce(self):+ # THE 20PX BAND MUST NOT COME BACK. It came back twice — once in the+ # drag and once in the double-click — because each gesture carried its+ # own copy. One pair now, and it closes exactly at four strip heights+ # spanning the whole range of the share table.+ self.assertEqual(self.r["lvlRoundTrip"], [])+ self.assertGreaterEqual(len(self.r["stripHeights"]), 4)+ self.assertLess(min(self.r["stripHeights"]), 40)+ self.assertGreater(max(self.r["stripHeights"]), 150)++ def test_the_top_of_a_strip_is_unity_and_the_bottom_is_silence(self):+ for pair in self.r["lvlEnds"]:+ self.assertEqual(pair, [1, 0])++ def test_half_way_down_is_half_at_every_height(self):+ # A hard-coded band gets this right at one height and wrong at every+ # other, which is exactly how the old bug read: correct on the lane it+ # was written for, silence everywhere below fourteen pixels.+ for mid in self.r["lvlMid"]:+ self.assertAlmostEqual(mid, 0.5, delta=0.02)++ def test_unity_sits_clear_of_the_strips_own_top_edge(self):+ """"Maybe you should put the orange line a little lower."++ Unity was drawn at y=1 — ON the strip's top edge. `.sbe-lvl-hit` is a+ 14px stroke centred on the line, so six of its seven upper pixels fell+ outside the box and were clipped away by the SVG's own viewport,+ leaving a one-sided sliver to aim at that also competed with the lane's+ border. The headroom has to be at least half the stroke, at EVERY+ height the share table can produce — including the 37px floor, which is+ the one it is hardest to find room in.+ """+ half = 7 # half of the 14px target+ for h, y in zip(self.r["stripHeights"], self.r["lvlUnityY"]):+ self.assertGreaterEqual(+ y, half + 1,+ f"a {h}px strip draws unity at y={y}, so {half - y:g}px of its "+ f"own target is outside the box")+ # ...and silence keeps the same headroom at the other end, or the+ # bottom of the range becomes the ungrabbable one instead.+ self.assertGreaterEqual(h - y, half + 1)+ for gap in self.r["lvlSilenceGap"]:+ self.assertGreaterEqual(gap, half + 1)++ # ---- and the span of it that belongs to nothing else -----------------+ def test_the_level_target_stops_where_the_corner_handles_start(self):+ """No pixel belongs to two controls.++ Three affordances share a strip's top corner now — the trim grip, the+ fade handle and the level line — and the line is the one that runs+ under both of the others for its whole length. It is DRAWN end to end,+ because that is the truth about the gain; its TARGET stops clear of+ both handles. The rectangles are measured for real in+ `scripts/measure_editor_layout.py`; this is the arithmetic underneath.+ """+ d = self.r["lvlHitFlat"]+ self.assertTrue(d.startswith("M33.00,"), d)+ # 400 - 33 at the other end, and the y is the line's own y throughout.+ self.assertIn("367.00,", d)+ self.assertNotIn("M0.00", d)++ def test_the_cut_lands_on_the_line_and_not_on_a_chord(self):+ d = self.r["lvlHitSloped"]+ want_start, want_end = self.r["lvlHitSlopedWant"]+ # Gain ramps 1 -> 0 across the strip, so the y at each cut is the y of+ # the gain AT that x — interpolating between whole points instead would+ # put the target above or below the line it is supposed to be on.+ self.assertTrue(d.startswith(f"M33.00,{want_start:.2f}"),+ f"{d} does not start at the line's own y {want_start}")+ self.assertTrue(d.endswith(f"367.00,{want_end:.2f}"),+ f"{d} does not end at the line's own y {want_end}")++ def test_a_strip_with_no_room_between_the_handles_offers_no_line(self):+ # 70px of strip is 66 of corner handle. An 8px stub of a control is+ # worse than none: it teaches that the line is grabbable and then is+ # not, and the inspector's Sound section is the route that never+ # depends on how far the timeline is zoomed out.+ self.assertEqual(self.r["lvlHitNarrow"], "")++ def test_a_segment_inside_a_handles_column_is_dropped_not_clamped(self):+ # The first and last segments of this curve live entirely under the+ # corner handles. Clamping them to the cut would run the target back to+ # x=0, which is the overlap this whole change exists to remove.+ d = self.r["lvlHitPoints"]+ self.assertTrue(d.startswith("M33.00,"), d)+ self.assertNotIn("0.00,", d.split("L")[0][1:])+ # ...and what is left is the middle segment, cut at both ends.+ self.assertIn("367.00,", d)++ # ---- and the gesture is not thrown away on the way out ---------------+ def test_every_mode_a_track_drag_has_counts_as_an_edit(self):+ """A fade that snapped back the moment you let go.++ `sbeOnTrackUp` restores the pointerdown snapshot when the film did not+ change — necessary, because dragging a clip that is already hard+ against its neighbour clamps to nowhere and would otherwise burn a+ revision. But the fingerprint it decides on listed four picture fields,+ then five, and `mode: 'fade'` writes `fx` and NOTHING else. So the ramp+ followed the pointer for the whole drag, painted correctly, and was+ discarded on pointerup with the document still saying "saved".++ This drives every mode rather than reading the source, because the+ source has been right-looking and short twice.+ """+ d = self.r["dragFp"]+ self.assertTrue(d["still"],+ "a drag that moved nothing must still compare equal, "+ "or every clamped drag burns a revision")+ for mode in ("fade", "fadeOut", "trim", "move", "sound"):+ self.assertTrue(d[mode],+ f"a drag whose only effect was `{mode}` compares "+ f"equal to the state it started from, so "+ f"sbeOnTrackUp restores the snapshot over it")++ def test_one_rule_says_which_strips_can_be_shaped(self):+ e = self.r["editable"]+ self.assertTrue(e["unlinked"])+ self.assertFalse(e["linked"]) # the rule the dblclick always had+ self.assertFalse(e["locked"])+ self.assertFalse(e["silent"]) # nothing to shape+ self.assertFalse(e["nothing"])++ # ---- hover teaches --------------------------------------------------+ def test_hovering_the_line_shows_where_the_point_would_go(self):+ fn = extract_function("sbeAudioGhost", self.src)+ self.assertIn("SBE_LVL_GRAB", fn)+ self.assertIn("sbeStripY(", fn)+ self.assertIn("SBE.kfGhost", fn)+ # ONE LANE, not the whole timeline: a ghost that repainted every clip+ # block and both canvases on each mouse move would make the pointer+ # feel heavy over the lane this is meant to make inviting.+ self.assertIn("sbePaintAudioLane()", fn)+ self.assertNotIn("sbePaint()", fn)+ # ...and it is only computed while nothing is being dragged.+ move = extract_function("sbeOnAudioMove", self.src)+ self.assertIn("if (!k && !SBE.audioDrag) { sbeAudioGhost(ev); return; }",+ move)+ wave = extract_function("sbeStripWave", self.src)+ self.assertIn("sbe-kf-ghost", wave)++ def test_the_line_is_a_target_and_not_only_a_picture(self):+ wave = extract_function("sbeStripWave", self.src)+ # Three paths: a dark one under it, the line, and the fat invisible one+ # that makes it hittable.+ self.assertIn("sbe-lvl-u", wave)+ self.assertIn("sbe-lvl-hit", wave)+ css = self.src[self.src.index(".sbe-lvl-hit {"):]+ css = css[:css.index("}")]+ self.assertIn("pointer-events: stroke", css)+ self.assertIn("cursor: ns-resize", css)+ # And it is only offered on a strip that can take a point.+ self.assertIn("const shape = sbeStripEditable(c);", wave)++ def test_a_single_click_on_the_line_places_a_point_and_drags_it(self):+ fn = extract_function("sbeLevelClick", self.src)+ self.assertIn("sbeAddKeyframe(", fn)+ self.assertIn("SBE.kfDrag", fn) # same gesture sets the level+ self.assertIn("setPointerCapture", fn)+ self.assertIn("SBE_LVL_GRAB", fn)+ down = extract_function("sbeOnAudioDown", self.src)+ # The grips are 7px of edge and the more specific target, so trimming+ # can never be mistaken for shaping.+ self.assertIn("if (!ev.target.closest('.sbe-grip') && sbeLevelClick(ev))",+ down)+ # Double-click still adds one: muscle memory is not taken away to+ # teach somebody else.+ self.assertIn("sbeAddKeyframe(", extract_function("sbeOnAudioDbl", self.src))++ def test_removing_a_point_has_a_route_you_can_find(self):+ fn = extract_function("sbeOnAudioMenu", self.src)+ self.assertIn("sbe-kf", fn)+ self.assertIn("preventDefault", fn)+ self.assertIn("sbeDeleteKeyframe", fn)+ self.assertIn("alane.addEventListener('contextmenu', sbeOnAudioMenu);",+ self.src)+ # Shift-click stays.+ self.assertIn("ev.shiftKey", extract_function("sbeOnAudioDown", self.src))++ def test_there_is_a_route_that_needs_no_gesture_at_all(self):+ fn = extract_function("sbeAddPointAtPlayhead", self.src)+ self.assertIn("SBE.playhead", fn)+ self.assertIn("sbeAddKeyframe(", fn)+ self.assertIn("sbeStripEditable(", fn)+ # It refuses OUTSIDE the strip rather than putting a point at an end+ # the user was not pointing at.+ self.assertIn("w.len + 1e-6", fn)+ insp = extract_function("sbePaintInspector", self.src)+ self.assertIn("sbeAddPointAtPlayhead()", insp)+ self.assertIn("sbeClearPoints()", insp)+ # A linked strip says what to do instead of offering a refusing button.+ self.assertIn("unlink the sound to shape its", insp)++ def test_the_legend_lists_the_gestures_that_actually_exist(self):+ legend = self.r["legend"]+ for phrase in ("click the yellow line", "drag it to set",+ "right-click it to remove", "top edge"):+ self.assertIn(phrase, legend)+ # ONE copy of it: the markup renders the function, so the gestures a+ # user is told about cannot drift from the ones the lane implements.+ self.assertIn('<span class="sbe-note sbe-keys" id="sbeKeys"></span>',+ self.src)+ self.assertIn("sbeKeysLegend()", extract_function("sbePaintKeys", self.src))+++class TheStageLayersAreNotOverpainted(unittest.TestCase):+ """A fade may not turn on the layer the stylesheet is turning off.++ THE REGRESSION, reported as "videos are not loading": they were loading+ fine — ready state 4, frames decoded — and a black rectangle was sitting on+ top of them. `sbeFadePaint` wrote the ramp onto BOTH stage layers:++ if (v) v.style.opacity = String(o);+ if (img) img.style.opacity = String(o);++ But opacity is not only the ramp on this stage, it is the LAYER SWITCH:+ `.sbe-stage img.sbe-still` is opacity:0 until it wins `.is-on`. An inline+ value beats the stylesheet, so the hidden still was forced to 1 — and the+ still is last in `#sbeStage` and backed with `#000`. The unit tests were+ green throughout, because every one of them asked about the arrangement and+ none of them asked what the painter wrote onto an element.++ These run the real painter and read the inline styles back.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.r = run_contract()+ cls.src = panel_source()++ def test_only_the_layer_that_is_showing_is_graded(self):+ # The video is on: it carries the ramp, and the still is handed back to+ # the stylesheet — an EMPTY string, not "0". Writing "0" would be a+ # second source of truth for a state the class already owns.+ self.assertEqual(self.r["stage"]["videoOnInFade"], ["0.5", ""])++ def test_the_same_holds_when_the_still_is_the_one_showing(self):+ self.assertEqual(self.r["stage"]["stillOnInFade"], ["", "0.5"])++ def test_a_layer_that_stops_showing_gives_its_inline_value_back(self):+ # THE GHOST CASE, and the one a "write 0 to the other layer" fix would+ # have missed: a layer that carried 0.5 and then loses `.is-on` must be+ # cleared, or the stylesheet's opacity:0 is overridden by a stale 0.5+ # and half a still hangs over the picture.+ self.assertEqual(self.r["stage"]["videoAfterHandover"], "")++ def test_outside_a_fade_the_showing_layer_is_fully_up(self):+ self.assertEqual(self.r["stage"]["outsideFade"], ["1", ""])++ def test_with_no_clip_at_the_playhead_nothing_is_dimmed(self):+ self.assertEqual(self.r["stage"]["noClip"], ["1", ""])++ def test_with_neither_layer_showing_neither_is_written(self):+ self.assertEqual(self.r["stage"]["neitherOn"], ["", ""])++ def test_the_source_monitors_layers_are_not_this_painters_business(self):+ # The source stage carries the SAME opacity switch, so a painter that+ # reached for it would reproduce the bug one monitor to the left. It+ # does not touch them at all — not even to clear them.+ self.assertEqual(self.r["stage"]["sourceUntouched"], [True, True])++ def test_the_overlay_layer_switches_on_display_so_its_ramp_is_free(self):+ # The sibling case, locked so the contrast stays true: `.sbe-ov-layer`+ # is display:none/block, so opacity there is only ever a ramp and+ # nothing it writes can turn the layer on. If that switch is ever+ # changed to opacity, this test is the one that should be read first.+ during, after = self.r["overlayLayer"]["during"], self.r["overlayLayer"]["after"]+ self.assertEqual(during[0], "0.5")+ self.assertTrue(during[1])+ self.assertFalse(after[1]) # off, whatever the stale ramp says++ # ---- the gate, not the instance -------------------------------------+ def test_no_painter_may_write_opacity_onto_a_layer_opacity_switches(self):+ """Every function that writes `.style.opacity` on a stage layer must+ ask which layer is showing first.++ This is the cheap gate the bug got past. It reads the STYLESHEET for+ the layers whose visibility is switched with opacity, then reads the+ JS for anyone writing opacity onto them — and requires the write to be+ conditional on `is-on`. It fails on the code that shipped and passes on+ the fix.+ """+ # 1. which layers does the stylesheet switch with opacity?+ switched = [" ".join(m.group(1).split())+ for m in re.finditer(r"([^\n{}]*\.is-on)\s*\{([^}]*)\}", self.src)+ if "opacity" in m.group(2)]+ self.assertEqual(sorted(switched),+ [".sbe-stage img.sbe-still.is-on", ".sbe-stage video.is-on"],+ "a new opacity-switched layer appeared — every painter "+ "that touches it has to ask `is-on` first")+ # ...and each has an OFF state, which is what an inline write defeats.+ self.assertIn("object-fit: contain; opacity: 0; background: #000;", self.src)++ # 2. the ids those rules govern, from the real markup.+ layers = ("sbeVideo", "sbeStill", "sbeSrcVideo", "sbeSrcStill")+ for i in layers:+ self.assertIn('id="%s"' % i, self.src)++ # 3. every opacity write in the file, with the function it lives in.+ offenders = []+ for m in re.finditer(r"\.style\.opacity\s*=", self.src):+ head = self.src.rfind("\nfunction ", 0, m.start())+ if head < 0:+ continue+ name = self.src[head + len("\nfunction "):self.src.index("(", head + 1)]+ body = extract_function(name.strip(), self.src)+ # COMMENTS DO NOT COUNT. The first version of this gate read the+ # raw body, and a comment explaining the rule was enough to satisfy+ # it — a gate that passes on prose is the same failure as a gate+ # that passes on grep.+ code = re.sub(r"/\*.*?\*/", "", body, flags=re.S)+ code = re.sub(r"//[^\n]*", "", code)+ if not any(i in code for i in layers):+ continue # not a stage layer: not this rule's business+ if "is-on" not in code:+ offenders.append(name.strip())+ self.assertEqual(offenders, [], "these paint a stage layer's opacity "+ "without asking which layer is showing")+++class TheHeaderIsOneRow(unittest.TestCase):+ """"The save button pops up sometimes and it's super big."++ Measured in the owner's browser at 1920x936, dpr 1: `sbeSaveBtn` 1554px+ wide, the header 125px tall in three rows, one spacer eating 1048 of them.++ THE CAUSE IS ONE MISSING DECLARATION. The global form rule is `input,+ textarea, select, button { width: 100% }`. `.ghost-btn` cancels it with+ `width: auto`; `button.primary` never did. Save is a ghost button until+ there is something to save, and `sbePaintChrome` swaps it to `.primary` the+ moment there is — so its flex basis became 100% of the header and the row+ wrapped around it. "Sometimes" was exactly "while unsaved". `flex-wrap:+ wrap` was not the cause, it was the permission.++ Render escaped the same trap by accident: it sits inside `.sbe-split`,+ whose inline-flex shrink-to-fit makes its 100% resolve against its own+ content. The old bottom bar carried `.sbe-actions .primary { width: auto }`+ for exactly this reason; deleting that bar moved a primary into a row with+ no such rule.++ Measured after the fix, in a real browser at four widths — 1920, 1520,+ 1280 and 1100 — header 49px, one row, Save 56px, no horizontal overflow at+ any of them.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()++ def test_the_head_cancels_the_global_stretch_for_both_kinds_of_button(self):+ rule = self.src[self.src.index(".sbe-head .ghost-btn, .sbe-head .primary {"):]+ rule = rule[:rule.index("}")]+ self.assertIn("width: auto", rule)+ self.assertIn("flex: 0 0 auto", rule)++ def test_the_head_may_not_wrap_and_says_so_at_a_specificity_that_wins(self):+ # `.carousel-head { flex-wrap: wrap }` is declared LATER in the sheet,+ # so a single-class `.sbe-head` rule loses to it on source order — the+ # first version of this fix was silently a no-op for that reason.+ self.assertIn(".carousel-head.sbe-head {", self.src)+ rule = self.src[self.src.index(".carousel-head.sbe-head {"):]+ rule = rule[:rule.index("}")]+ self.assertIn("flex-wrap: nowrap", rule)+ # Specificity, not source order, is what wins here — (0,2,0) beats+ # (0,1,0) wherever the two sit — and the one-class version of this+ # rule is what a future edit would reach for.+ self.assertIn("\n .carousel-head {", self.src)+ self.assertNotIn("\n .sbe-head { position: relative", self.src)++ def test_the_row_degrades_by_ellipsis_and_folding_never_by_stacking(self):+ # A header that stacks pushes the monitors and the timeline down the+ # column, which is the one thing this layout exists not to do.+ title = self.src[self.src.index(".sbe-head .sbe-title {"):]+ title = title[:title.index("}")]+ self.assertIn("min-width", title) # or flex refuses to shrink+ self.assertIn("text-overflow: ellipsis", title)+ self.assertIn("white-space: nowrap", title)+ # ...and the two things that fold, in order, at their breakpoints.+ self.assertIn("#sbeStateText { display: none; }", self.src)+ self.assertIn("#sbeDraftName { display: none; }", self.src)++ def test_every_primary_the_client_creates_lives_under_a_width_rule(self):+ """THE CLASS: a `.primary` in a flex row inherits `width: 100%`.++ Whoever adds the next one has to give it a width, and this is the list+ of the places that already do.+ """+ # Where the client TURNS something into a primary at runtime...+ self.assertIn("classList.toggle('primary'", self.src)+ # ...and every editor row that hosts buttons cancels the stretch.+ for rule in (".sbe-head .ghost-btn, .sbe-head .primary {",+ ".sbe-transport .primary {",+ ".sbe-recover .ghost-btn, .sbe-recover .primary {",+ ".sbe-vers-new .primary {"):+ self.assertIn(rule, self.src, "%s is gone — the row it styled "+ "still hosts a button" % rule)+ block = self.src[self.src.index(rule):]+ block = block[:block.index("}")]+ self.assertIn("width: auto", block,+ "%s hosts a button and does not cancel the global "+ "button stretch" % rule)++ def test_the_two_rows_the_calm_layout_added_cannot_wrap_either(self):+ # The transport is the other flex row that gained controls, and the+ # gutter is a fixed column beside a scroller. Measured at 1100px: the+ # transport is 34px and one row, the gutter 124px.+ t = self.src[self.src.index("\n .sbe-transport {"):]+ t = t[:t.index("}")]+ self.assertIn("flex-wrap: wrap", t) # it MAY wrap: it is the row that+ # has somewhere to go — nothing below it is pinned to the viewport, and+ # sbeFitMonitors measures whatever height it ends up with. Stated here+ # so the difference from the header is a decision, not an oversight.+ g = self.src[self.src.index("\n .sbe-gutter {"):]+ g = g[:g.index("}")]+ self.assertIn("flex: 0 0 124px", g)+++class TheCalmChrome(unittest.TestCase):+ """The Editor rearranged — and the contract that nothing went missing.++ The bottom bar is deleted, Render came up rather than out, the four-button+ row collapsed into a chip and a kebab, and the soundtrack's row became the+ A2 lane header. Every one of those is a control MOVED, and a moved control+ is one rename away from being a control nobody can reach.+ """++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()++ # Every id the old surface had, and the client still writes to. This list+ # IS the mapping table: if a rearrangement drops one, this turns red+ # rather than the button quietly ceasing to exist.+ REACHABLE = (+ "sbeTitle", "sbeKeepBtn", "sbeDraftName", "sbeDraftDot", "sbeState",+ "sbeUndoBtn", "sbeRedoBtn", "sbeSaveBtn", "sbeRenderBtn", "sbeNleBtn",+ "sbeRenderNote", "sbeVersBtn", "sbeImportBtn", "sbeAutoBtn",+ "sbeBoardBtn", "sbeCloseBtn", "sbeRelinkBtn", "sbeNotices",+ "sbeMusicPath", "sbeMusicMode", "sbeMusic", "sbeMusicChange",+ "sbePrepBtn", "sbePrepCancel", "sbePrepText", "sbePrepBar",+ "sbeMusicWarn", "sbeSnapOn", "sbeZoomRange", "sbeMuteBtn",+ "sbePlayBtn", "sbeTime", "sbeApprox", "sbeKeys", "sbeTlGrab",+ "sbeInspect", "sbeUnplacedWrap", "sbeSrcAddBtn", "sbeSrcPlayBtn",+ )++ def test_nothing_became_unreachable(self):+ for i in self.REACHABLE:+ self.assertIn('id="%s"' % i, self.src, "%s vanished" % i)++ def test_the_bottom_bar_is_gone_and_render_came_up(self):+ # 54px of chrome under the timeline held two buttons. Render is the+ # one thing this screen is FOR, so it is the one filled control on it.+ self.assertNotIn('<div class="sbe-actions">', self.src)+ head = self.src[self.src.index('<header class="carousel-head sbe-head">'):]+ head = head[:head.index("</header>")]+ self.assertIn('id="sbeRenderBtn"', head)+ self.assertIn('class="primary"', head)+ # Export is the same verb pointed elsewhere: under the caret.+ menu = self.src[self.src.index('id="sbeRenderMenu"'):]+ menu = menu[:menu.index("</div>")]+ self.assertIn("sbeNleBtn", menu)+ self.assertIn("sbeRenderNote", menu)++ def test_navigation_nests_under_the_kebab(self):+ menu = self.src[self.src.index('id="sbeMoreMenu"'):]+ menu = menu[:menu.index("\n </div>")]+ for i in ("sbeVersBtn", "sbeImportBtn", "sbeAutoBtn", "sbeBoardBtn",+ "sbeCloseBtn"):+ self.assertIn(i, menu)++ def test_a_menu_cannot_push_the_workspace_around(self):+ # THE rule this editor was built on: notices live in one compact+ # surface and never reflow the column. A menu is the same argument —+ # so every one of them is fixed, hidden, and measured off its anchor.+ css = self.src[self.src.index("\n .sbe-pop {"):]+ css = css[:css.index("}")]+ self.assertIn("position: fixed", css)+ self.assertIn('.sbe-pop[hidden] { display: none !important; }', self.src)+ fn = extract_function("sbePopToggle", self.src)+ self.assertIn("getBoundingClientRect", fn)+ self.assertIn("window.innerWidth", fn) # clamped on screen+ self.assertIn("window.innerHeight", fn) # ...and flipped when low+ # One at a time, and click-away closes them.+ self.assertIn("sbePopCloseAll", fn)+ self.assertIn("document.addEventListener('click', sbePopGlobal, true);",+ self.src)++ def test_escape_closes_the_menu_before_the_document(self):+ # Esc has always closed the document here; a menu is one layer above+ # it, and closing the whole cut out from under an open menu is the+ # surprise this ordering exists to prevent.+ i = self.src.index("if (sbePopAnyOpen()) { sbePopCloseAll(''); return; }")+ j = self.src.index("sbeClose();", i)+ self.assertLess(i, j)++ def test_the_soundtracks_row_became_its_lane_header(self):+ # It was a full-width strip at the top of the column, four inches from+ # the lane it acts on. Identity on the head, verbs in its menu.+ self.assertNotIn('<div class="sbe-prep" id="sbePrepare">', self.src)+ head = self.src[self.src.index('class="sbe-gh sbe-gh-mus"'):]+ head = head[:head.index("<div class=\"sbe-gh sbe-gh-foot\"")]+ self.assertIn("A2", head)+ self.assertIn('id="sbeMusicPath"', head)+ self.assertIn('id="sbeMusicMode"', head)+ self.assertIn("sbePopToggle('sbeMusicMenu'", head)+ menu = self.src[self.src.index('id="sbeMusicMenu"'):]+ menu = menu[:menu.index("\n </div>")]+ for i in ("sbeMusic", "sbeMusicChange", "sbePrepBtn", "sbePrepCancel",+ "sbePrepBar", "sbeMusicWarn"):+ self.assertIn(i, menu)++ def test_the_lane_heads_read_the_same_heights_as_the_lanes(self):+ # Two columns that describe the same four rows. They are driven by the+ # SAME variables, so no drag can put a label beside the wrong lane —+ # measured on screen at 1px, which is the scroller's own border.+ css = self.src[self.src.index("\n .sbe-gutter {"):]+ css = css[:css.index(".sbe-gh-tag {")]+ for var in ("--sbe-ov-h", "--sbe-track-h", "--sbe-alane-h",+ "--sbe-wave-h"):+ self.assertIn("var(%s" % var, css)+ # And the column budget now counts the WRAPPER, not the scroller.+ fn = extract_function("sbeFitMonitors", self.src)+ self.assertIn("kid.id === 'sbeTlWrap'", fn)++ def test_the_prose_became_affordances(self):+ # Two lines of preview caveat across the middle of the transport, and+ # a run-on keyboard sentence under the timeline. Both are true; both+ # cost a row every time they were shown.+ self.assertIn('class="sbe-info" id="sbeApprox"', self.src)+ self.assertIn("The preview is approximate", self.src)+ self.assertIn('id="sbeKeysBtn"', self.src)+ self.assertIn("sbePopToggle('sbeKeysPop', 'sbeKeysBtn')", self.src)++ def test_the_draft_chip_says_which_of_how_many(self):+ fn = extract_function("sbePaintDraft", self.src)+ self.assertIn("' of ' + n", fn)+++class TimelineMarkup(unittest.TestCase):+ """The controls the JS drives have to EXIST, in the real markup."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.src = panel_source()++ def test_the_stage_carries_exactly_one_video(self):+ # Double-buffering measured no benefit against all-intra proxies, and+ # two elements is two decoders.+ stage = self.src[self.src.index('<div class="sbe-stage" id="sbeStage">'):]+ stage = stage[:stage.index("</div>", stage.index("sbeStageEmpty"))]+ self.assertEqual(stage.count("<video"), 1)++ def test_the_video_is_not_muted_in_the_markup(self):+ # Inverted deliberately. The attribute was "belt and braces" for a+ # loader that hard-muted anyway; with sbeSetMute owning mute state, a+ # `muted` in the markup is a second source of truth that disagrees with+ # the first. There is no `autoplay` on this element, so nothing plays+ # without sbePlay, which sets muted explicitly and has its own fallback.+ el = extract_element("sbeVideo", self.src)+ self.assertNotIn("muted", el)+ self.assertNotIn("autoplay", el)++ def test_nothing_in_the_editor_hides_media_with_display_none(self):+ # WebKit will not load a display:none <video>.+ css = self.src[self.src.index(".sbe-stage video {"):]+ css = css[:css.index(".sbe-stage-badge")]+ self.assertIn("opacity: 0", css)+ self.assertNotIn("display: none", css)++ def test_the_preview_says_it_is_an_approximation(self):+ el = self.src[self.src.index('id="sbeApprox"'):]+ el = el[:el.index("</span>")]+ self.assertIn("approximate", el)+ self.assertIn("render is exact", el)++ def test_the_auto_edit_warns_that_it_discards_the_arrangement(self):+ fn = extract_function("sbeAuto", self.src)+ self.assertIn("THROWS AWAY", fn)++ def test_the_render_discloses_that_the_concat_closes_gaps(self):+ fn = extract_function("sbeRenderFilm", self.src)+ self.assertIn("gaps_note", fn)+ self.assertIn("CONCATENATES", fn)++ def test_generate_shows_the_params_that_will_ACTUALLY_render(self):+ # make_job silently drops any form field it does not name, so the+ # server reads the queued job back. The client has to show that, not+ # the request it sent.+ fn = extract_function("sbeGenSubmit", self.src)+ self.assertIn("r.params", fn)+ self.assertIn("sbeGenParams", fn)++ def test_the_preview_prefers_the_proxy_and_labels_the_fallback(self):+ fn = extract_function("sbeClipUrl", self.src)+ self.assertIn("c.proxy", fn)+ self.assertIn("proxy_url", panel_source()[:0] + "proxy_url")+ badge = extract_function("sbeShowFrameAt", self.src)+ self.assertIn("SOURCE (slow", badge)++ # The three below are SOURCE assertions, not behaviour, because the thing+ # under test is CSS and there is no way to run CSS in node. They are here+ # because each one is a rule a browser caught and a reader would not:+ # deleting any of them puts the storyboard's planning column back on top of+ # the editor, which is exactly the bug they were written for.+ def test_the_editor_gets_its_own_two_column_window(self):+ # This test used to lock a MODE: `body.sbe-open` narrowed the+ # storyboard's planning column to 300px while the timeline was open+ # inside it. The 2026-08-17 review's verdict was that the mode was the+ # bug — "the editor deserves its own window … called Editor" — so the+ # rule it locked is gone and this locks its replacement: the Editor is+ # a workflow with two columns of its own, the pool and the cut.+ self.assertNotIn("sbe-open main.layout", self.src)+ css = self.src[self.src.index("THE EDITOR OWNS ITS OWN WINDOW"):]+ css = css[:css.index(".sbe { gap")]+ wide, _, after = css.partition("@media (max-width: 1100px)")+ self.assertIn('body[data-workflow="editor"] main.layout', wide)+ self.assertIn("minmax(0, 300px)", wide)+ # The breakpoint block, brace-matched so the assertions below cannot+ # wander into the rules that follow it.+ depth, narrow = 0, ""+ for ch in after:+ narrow += ch+ if ch == "{":+ depth += 1+ elif ch == "}":+ depth -= 1+ if depth == 0:+ break+ # The pool is the tab's other half. Folding it away at a breakpoint —+ # which is what the storyboard rule did to its column — would leave+ # the Editor with no way to reach a clip. It stacks instead.+ self.assertNotIn("display: none", narrow)+ self.assertIn("grid-row: 2 / 3", narrow)+ # The editor's own stage element, and the fold that gives it the tab.+ self.assertIn('body[data-workflow="editor"] #edStage { display: flex; }',+ self.src)++ def test_the_stage_is_TWO_monitors_and_the_source_is_its_own(self):+ # "a split screen with the left screen showing you when you click on+ # the clips … you have two screens." The program monitor is unchanged+ # (the test above still counts exactly one video in it); the source is+ # a second element with its own video, still, badge and empty state.+ row = self.src[self.src.index('<div class="sbe-monitors" id="sbeMonitors">'):]+ row = row[:row.index('<div class="sbe-transport">')]+ self.assertIn('id="sbeSrcVideo"', row)+ self.assertIn('id="sbeSrcStill"', row)+ self.assertIn('id="sbeSrcAddBtn"', row)+ self.assertIn('id="sbeStage"', row) # the program+ self.assertIn("Click a clip to preview it.", row)+ # Two monitors, two videos — and no third one that nobody owns.+ self.assertEqual(row.count("<video id="), 2)+ # The source is a player, not a second editor: no track, no trim.+ self.assertNotIn("sbe-track", row)++ def test_only_one_monitor_ever_plays(self):+ # Two elements is two decoders only if both decode. sbePlay stops the+ # source and sbeSrcPlay stops the program, so it is one at a time —+ # which is also the only way "one opinion about sound" can be true.+ self.assertIn("sbeSrcStop()", extract_function("sbePlay", self.src))+ self.assertIn("sbeStop()", extract_function("sbeSrcPlay", self.src))+ self.assertIn("sbeSrcStop()", extract_function("sbeSuspend", self.src))++ def test_the_mute_switch_governs_BOTH_monitors(self):+ fn = extract_function("sbeSetMute", self.src)+ self.assertIn("sbeSrcVideo", fn)+ self.assertIn("sv.muted = SBE.muted", fn)++ def test_a_deliberate_pause_is_not_mistaken_for_a_blocked_autoplay(self):+ # Measured: pressing Play on the program rejected the source's pending+ # play() with AbortError, the catch read that as "the browser blocked+ # sound", MUTED the editor and started the source playing again under+ # the program. Both players now tell the two apart.+ for name in ("sbeSrcPlay", "sbePlay"):+ fn = extract_function(name, self.src)+ self.assertIn("AbortError", fn)++ def test_the_source_prefers_a_proxy_and_says_when_it_has_none(self):+ # A pool row has no proxy of its own — it is a path, not a clip — so+ # the URL is the proxy of a clip already cut from the same file when+ # there is one. A Generations row has never been near this document+ # and plays the file, which is fine forward-only and is labelled.+ fn = extract_function("sbeSrcUrl", self.src)+ self.assertIn("c.proxy", fn)+ self.assertIn("SBE.proxyUrl", fn)+ self.assertIn("/file?path=", fn)+ self.assertIn("source file", extract_function("sbePaintSource", self.src))++ def test_clicking_a_pool_row_previews_it_and_the_plus_still_adds(self):+ # The verb on the row CHANGED, which is the whole two-screen point:+ # "you can watch the clips before you add them". The old verb keeps a+ # control of its own so nobody who already knows a clip has to watch+ # it — and a <button> inside a <button> is not markup, hence the div.+ fn = extract_function("edPoolPaint", self.src)+ self.assertIn('onclick="edPoolPreview(', fn)+ self.assertIn('class="ed-pool-add"', fn)+ self.assertIn("edPoolAdd(", fn)+ self.assertIn('role="button"', fn)+ self.assertNotIn('<button type="button" class="ed-pool-row"', fn)+ # Add-from-the-source-monitor is the SAME call, by construction.+ self.assertIn("edPoolAdd(SBE.srcIndex)", extract_function("sbeSrcAdd", self.src))++ def test_a_drag_that_ends_in_a_click_does_not_also_preview(self):+ # edPoolAdd has carried this guard since drop-where-you-dropped-it+ # shipped; the preview needs the same one or every drop would change+ # the left screen as well as the track.+ self.assertIn("ED.suppressClick", extract_function("edPoolPreview", self.src))++ def test_the_preview_frame_is_the_shape_of_the_picture(self):+ # `width: 100%` + `aspect-ratio` + `max-height` do not compose: a block+ # box's auto width is stretch-fit and outranks the ratio, so the frame+ # came out 1070x300 with a 16:9 picture floating in the middle of it and+ # ~270px of black either side. Measured in a browser; reported as+ # "it looks weird, it looks warped".+ css = self.src[self.src.index(".sbe-stage {"):]+ css = css[:css.index(".sbe-stage video")]+ self.assertIn("aspect-ratio: 16 / 9", css)+ # Parse real declarations: the prose above them quotes the broken rule,+ # and a substring test also trips over the legitimate `max-width: 100%`.+ body = css[css.index("{") + 1:]+ body = re.sub(r"/\*.*?\*/", "", body, flags=re.S)+ decls = {}+ for part in body.split(";"):+ if ":" in part:+ prop, _, val = part.partition(":")+ decls[prop.strip()] = val.strip()+ self.assertEqual(decls.get("width"), "fit-content")+ self.assertEqual(decls.get("max-width"), "100%") # cap, not stretch+ self.assertEqual(decls.get("margin-inline"), "auto")+ # A definite height is what lets the ratio drive the width. Without it+ # `fit-content` collapses instead. It is a variable now rather than a+ # min() — sbeFitMonitors measures and writes it, and .sbe-monitors+ # carries the fallback for the frame before that runs.+ self.assertEqual(decls.get("height"), "var(--sbe-prog-h)")+ self.assertNotIn("max-height: min(", css)++ def test_the_stage_leaves_room_for_everything_under_it(self):+ # The budget was `100vh - 748px` and it was measured against a column+ # that was 170px shorter than this one (the editor's stage-pane did+ # not span the bottomPane's grid row) and against a stage that was+ # alone on its row. Both changed, so the number did.+ # RE-MEASURED 2026-08-18 at 1440x900, live, in the Editor's own tab:+ # the column is 100vh - 116px (88px of header + 28px of stage-pane+ # padding) and everything else in it comes to 452px — header 50,+ # prepare 55, transport 32, ruler + waveform + 78px track + 12px+ # scrollbar 164, inspector 38, action bar 65, six 8px gaps 48.+ # Hence 568. Both directions are locked: too small is a cramped+ # picture, too large is the sticky Render bar back on the timeline.+ css = self.src[self.src.index(".sbe-monitors {"):]+ css = css[:css.index(".sbe-mon {")]+ self.assertIn("calc(100vh - 568px)", css)+ self.assertNotIn("calc(100vh - 748px)", css)+ self.assertNotIn("calc(100vh - 700px)", css)+ self.assertNotIn("calc(100vh - 819px)", css)+ # The whole reason the column got 170px taller. This rule read+ # `grid-row: 1 / 2` for two releases, which reserved the bottomPane's+ # row across the entire grid while only the 300px left column had+ # anything in it — 1140x170 of page background under the timeline,+ # which is the band the owner circled.+ self.assertIn("grid-column: 2 / 3; grid-row: 1 / span 2;", self.src)++ def test_the_timeline_scroller_shows_a_scrollbar_you_can_actually_see(self):+ # THE defect: "when you get to the 36 seconds, you cannot scroll."+ # `overflow-x: auto` was always here and the box always could scroll —+ # but macOS overlay scrollbars paint nothing until something is+ # already scrolling, and nothing on a mouse scrolls a horizontal box.+ # Declaring ::-webkit-scrollbar opts out of overlay scrollbars; naming+ # the STANDARD `scrollbar-width` puts them straight back, because+ # Chrome 121+ ignores every ::-webkit- rule once it is present.+ # Measured: with scrollbar-width, offsetHeight - clientHeight was 2px+ # (the borders alone); without it, 14px.+ css = self.src[self.src.index("\n .sbe-tl {"):]+ css = css[:css.index(".sbe-tl-inner {")]+ self.assertIn("overflow-x: scroll", css)+ self.assertIn(".sbe-tl::-webkit-scrollbar { height: 12px; }", css)+ # Declarations only — the comment above them quotes the property it is+ # warning about, exactly like the aspect-ratio test one screen up.+ decls = re.sub(r"/\*.*?\*/", "", css, flags=re.S)+ self.assertNotIn("scrollbar-width", decls)+ # And it is the row that absorbs the column's leftover height, which+ # is what keeps a tall window from ending in a dead band. Its floor is+ # a variable because the user owns it — the handle on the transport's+ # bottom edge writes it — and the fallback is the constant.+ self.assertIn("flex: 1 1 auto", css)+ # The floor lives on the WRAPPER now — the gutter shares the height —+ # and the scroller's job is to fill it.+ wrap = self.src[self.src.index("\n .sbe-tlwrap {"):]+ wrap = wrap[:wrap.index("}")]+ self.assertIn("min-height: var(--sbe-tl-h, 280px)", wrap)+ self.assertIn(".sbe > .sbe-tlwrap { flex: 1 1 auto; }", self.src)++ def test_the_zoom_slider_exists_beside_the_buttons(self):+ # "Normal video editors usually have two sliders: one to move and one+ # to make the clips smaller." The scrollbar above is the first.+ zoom = self.src[self.src.index('<span class="sbe-zoom">'):]+ zoom = zoom[:zoom.index("</span>", zoom.index("sbeZoomRange"))]+ self.assertIn('id="sbeZoomRange"', zoom)+ self.assertIn('type="range"', zoom)+ self.assertIn('oninput="sbeZoomSlide(', zoom)+ self.assertIn("sbeZoom(-1)", zoom) # the buttons stay+ self.assertIn("sbeZoom(1)", zoom)+ # The − / + ladder is clamped to the same live floor as the slider, or+ # the two controls would disagree about what "all the way out" means.+ self.assertIn("sbeZoomMin()", extract_function("sbeZoom", self.src))+ self.assertIn("sbeZoomMin()", extract_function("sbeZoomSlide", self.src))++ def test_shift_wheel_pans_and_alt_wheel_zooms(self):+ fn = extract_function("sbeOnTlWheel", self.src)+ self.assertIn("ev.altKey", fn)+ self.assertIn("ev.shiftKey", fn)+ self.assertIn("sbeZoomTo(", fn)+ self.assertIn("scrollLeft", fn)+ # A plain vertical wheel belongs to the column, which scrolls.+ self.assertIn("ev.deltaX", fn)++ def test_the_monitor_row_is_measured_rather_than_assumed(self):+ # "Measure, don't guess" — and the one thing it may NOT measure is the+ # row it is sizing, or the budget becomes its own input. The timeline+ # is counted at its CSS floor for exactly that reason.+ fn = extract_function("sbeFitMonitors", self.src)+ self.assertIn("SBE_TL_MIN_H", fn)+ self.assertIn("clientHeight", fn)+ self.assertIn("sbeMonitorFit(", fn)+ self.assertIn("--sbe-prog-h", fn)+ self.assertIn("--sbe-rail-w", fn)+ # The corrective pass is bounded: it can only shrink, and only once.+ self.assertIn("scrollHeight - col.clientHeight", fn)+ self.assertEqual(fn.count("apply(budget"), 2)++ def test_the_unbounded_list_is_the_one_that_scrolls_not_the_inspector(self):+ # Measured live at 1440x900 on a nine-clip film with thirteen unplaced+ # shots: #sbeInspect was 36px around 223px of content, so "Unlink+ # sound" — the only entry point the J/L feature has — was off-screen,+ # and the one control fully visible at the bottom of that unmarked+ # scroll was Ripple delete. The inspector's content is bounded and+ # known; the unplaced strip is not.+ css = self.src[self.src.index(".sbe-rail {"):]+ css = css[:css.index(".sbe-stage {")]+ self.assertIn(".sbe-rail > .sbe-inspect {\n flex: 0 0 auto", css)+ self.assertIn(".sbe-rail > .sbe-unplaced {\n flex: 1 1 auto", css)+ # ...and it still fills the rail when there is nothing unplaced, or it+ # is a small card floating in page background.+ self.assertIn(".sbe-rail:has(> .sbe-unplaced[hidden]) > .sbe-inspect", css)++ def test_the_column_is_re_fitted_when_its_BOX_changes_not_just_the_window(self):+ # Measured: a viewport change from 1900x1000 to 1440x900 left both+ # monitors 437px tall inside a 501px column — 16:9 boxes squashed to+ # 1.15:1 by `max-width` — because the window's resize event never+ # reached sbePaint. The column is the box the budget is about.+ wire = self.src[self.src.index("(function sbeWire() {"):]+ wire = wire[:wire.index("\n})();")]+ self.assertIn("ResizeObserver", wire)+ self.assertIn("edStage", wire)+ # Coalesced, and NOT on rAF: measured in a preview pane the compositor+ # had backgrounded, where the animation-frame callback never ran at+ # all and the monitors kept the previous window's height. A resize is+ # exactly when a background tab is about to be looked at.+ self.assertIn("pending = setTimeout(", wire)+ self.assertNotIn("pending = requestAnimationFrame", wire)++ def test_the_action_bar_is_one_row_because_the_button_is_not_full_bleed(self):+ # `button { width: 100% }` is the panel's base rule and this bar never+ # overrode it: the Render button measured 1590px, wrapped to its own+ # line, and doubled the sticky bar's height onto the inspector.+ css = self.src[self.src.index(".sbe-actions {"):]+ css = css[:css.index(".sbe-note {")]+ self.assertIn(".sbe-actions .primary", css)+ self.assertIn("width: auto", css)++ def test_the_preview_is_not_hard_muted(self):+ # Proxies carry audio (recipe v2+) and on a dialogue film the clips ARE+ # the performance. `v.muted = true` in the loader silently threw that+ # away, so the fix that gave proxies an audio track shipped inaudible+ # and the owner reported the same bug twice: "when you run in the+ # timeline, you cannot listen to the sound."+ fn = extract_function("sbeLoadInto", self.src)+ self.assertNotIn("v.muted = true", fn)+ self.assertIn("v.muted = !!SBE.muted", fn)++ def test_sound_is_on_by_default(self):+ # A muted editor is indistinguishable from a broken one, so the stored+ # preference has to default to audible: only an explicit '1' mutes.+ state = self.src[self.src.index("window.SBE = {"):]+ state = state[:state.index("const SBE_MIN_CLIP")]+ self.assertIn("localStorage.getItem('sbeMuted') === '1'", state)++ def test_one_switch_drives_picture_soundtrack_and_button(self):+ fn = extract_function("sbeSetMute", self.src)+ for target in ("v.muted = SBE.muted", "a.muted = SBE.muted", "sbeMuteBtn"):+ self.assertIn(target, fn)+ self.assertIn("localStorage.setItem('sbeMuted'", fn)++ def test_blocked_autoplay_falls_back_to_muted_rather_than_to_nothing(self):+ # Unmuted play needs user activation. If Chrome refuses, losing the+ # sound beats losing the picture — and a Play button that visibly does+ # nothing is the worst of the three.+ fn = extract_function("sbePlay", self.src)+ self.assertIn("v.muted = true", fn)+ self.assertIn("sbeSetMute(true", fn)++ def test_leaving_the_tab_suspends_the_editor_and_never_closes_it(self):+ # The regression this replaces: sbSyncStage owned `body.sbe-open` and+ # workflowSwitch ran sbeTeardown() on the way out, so glancing at the+ # gallery threw away the open document and its undo stack. A tab+ # switch is not a close — it stops the clock and the picture, and+ # flushes the debounced save, and that is all.+ sync = extract_function("sbSyncStage", self.src)+ self.assertNotIn("classList.toggle('sbe-open'", sync)+ self.assertNotIn("SBE.open", sync)+ self.assertNotIn("sbeTeardown", extract_function("sbTeardown", self.src))+ wf = extract_function("workflowSwitch", self.src)+ self.assertIn("sbeSuspend()", wf)+ self.assertNotIn("sbeTeardown()", wf)+ susp = extract_function("sbeSuspend", self.src)+ self.assertIn("sbeStop()", susp) # the picture stops+ self.assertIn("sbeSave(true)", susp) # the work is kept+ self.assertNotIn("SBE.open = false", susp) # the document is not++ def test_the_document_only_closes_when_the_document_is_closed(self):+ close = extract_function("sbeCloseDoc", self.src)+ self.assertIn("SBE.open = false", close)+ self.assertIn("SBE.clips = []", close)+ # Esc and the header's Close both come here.+ self.assertIn("sbeCloseDoc()", extract_function("sbeClose", self.src))++ def test_the_surface_is_called_Editor_before_it_is_called_anything(self):+ # One name, everywhere — and the default is the name of the place,+ # not the name of the widget. It said "Timeline" while the tab said+ # Editor and the rail said Arrange: three words for one screen.+ self.assertIn('id="sbeTitle">Editor<', self.src)+ self.assertIn(">Open in Editor<", self.src)+ self.assertIn('<span class="sb-rail-t">Edit</span>', self.src)+ self.assertNotIn(">Arrange<", self.src)++ def test_the_editor_tab_exists_and_is_always_reachable(self):+ # A tab with no board open is the whole point: "an editor that only+ # exists inside a storyboard is an editor most clips can never reach".+ self.assertIn('<button data-workflow="editor">', self.src)+ self.assertIn(">Editor<", self.src)+ # It MUST be in the localStorage restore list or the tab never comes+ # back across a reload — the trap the comment beside it documents.+ boot = self.src[self.src.index("const saved = localStorage.getItem('phos_workflow')"):]+ boot = boot[:boot.index("workflowSwitch(saved);")]+ self.assertIn("saved === 'editor'", boot)+ # And it opens with nothing on disk: an empty state, not an error.+ self.assertIn('id="edEmpty"', self.src)+ self.assertIn("edShowPicker", extract_function("edInit", self.src))++ def test_a_remembered_document_that_is_gone_falls_back_to_the_picker(self):+ # The silent-failure restore the review flagged: a deleted film left+ # the Editor showing an error box for a film nobody asked to open.+ init = extract_function("edInit", self.src)+ self.assertIn("onMissing", init)+ load = extract_function("sbeLoad", self.src)+ self.assertIn("SBE.onMissing", load)+ self.assertIn("r.corrupt", load) # corrupt is still NOT swallowed++ def test_the_document_id_is_not_the_open_boards_id(self):+ fn = extract_function("sbeOpen", self.src)+ self.assertNotIn("SBE.id = SB.id", fn)+ self.assertNotIn("if (!SB.id) return", fn)+ self.assertIn("edDoc()", fn) # last document, remembered+ self.assertIn("edRemember(want)", fn)++ def test_the_narrow_layout_stops_stretching_so_the_page_can_scroll(self):+ # .layout is `flex: 1 1 auto` in a flex body, so the breakpoint's+ # `height: auto` never did anything: the grid kept the full viewport+ # height, its three auto rows were squeezed, and ~480px of the brief+ # spilled through the stage.+ mq = self.src[self.src.index('@media (max-width: 900px)'):]+ mq = mq[:mq.index(".sb-shot-head { flex-wrap: wrap; }")]+ self.assertIn("flex: 0 0 auto;", mq)++ # ---- the media pool -------------------------------------------------+ def test_the_window_prompt_import_is_gone(self):+ # It asked the user to type the NUMBER of a film from a numbered list,+ # in an OS dialog, while the gallery holding every clip they had ever+ # made was display:none for the whole surface.+ self.assertNotIn("sbeImportOpen", self.src)+ self.assertNotIn("Bring clips from which film?", self.src)++ def test_the_pool_offers_all_three_sources(self):+ pane = self.src[self.src.index('id="edSectionTab"'):]+ pane = pane[:pane.index('id="edPoolNote"')]+ for src in ('data-src="film"', 'data-src="other"', 'data-src="gallery"'):+ self.assertIn(src, pane)+ for word in ("This __SEQCAP__", "Other __SEQS__", "Generations"):+ self.assertIn(word, pane)++ def test_each_source_is_fed_by_the_endpoint_that_owns_it(self):+ fn = extract_function("edPoolRefresh", self.src)+ self.assertIn("SBE.pool", fn) # this film — off the payload+ self.assertIn("'/outputs?limit=", fn) # the generations gallery+ other = extract_function("edPoolLoadFilms", self.src)+ self.assertIn("'/storyboard/list'", other)+ shots = extract_function("edPoolLoadFilmShots", self.src)+ self.assertIn("'/storyboard/get?id='", shots)++ def test_adding_a_clip_lands_it_on_the_TRACK_and_saves(self):+ # Not on the board, and not in a chip row waiting to be placed: the+ # click said "put this in my film", so it goes on the timeline.+ fn = extract_function("edPoolAdd", self.src)+ self.assertIn("'/storyboard/edit/add-clip'", fn)+ self.assertIn("sbePlaceUnplaced", fn)+ self.assertIn("sbeFilmDuration(cs)", fn) # a CLICK: at the END+ self.assertIn("sbeInsertAt(cs, item, at)", fn) # a DROP: where it fell+ self.assertIn("sbeSave(true)", fn)++ def test_adding_a_clip_from_another_film_uses_the_import_subset_param(self):+ # `only=` has been on the server since the import shipped and no+ # screen could send it.+ self.assertIn("fd.set('only'", extract_function("edPoolAdd", self.src))++ def test_adding_a_clip_never_ejects_the_user_from_the_editor(self):+ # The old import ended with sbOpen(SBE.id), which threw the user back+ # onto the shot list — after an action whose whole purpose was to+ # carry on cutting.+ fn = extract_function("edPoolAdd", self.src)+ self.assertNotIn("workflowSwitch", fn)+ self.assertNotIn("sbOpen(", fn)+ self.assertNotIn("sbShow(", fn)++ def test_pool_thumbnails_are_lazy_because_media_elements_are_finite(self):+ # Chrome caps media elements per document and the carousel already+ # holds hundreds on a working install. src is attached on the way in+ # and taken away on the way out.+ fn = extract_function("edPoolPaint", self.src)+ self.assertIn("data-src=", fn)+ self.assertNotIn('video preload="metadata" muted playsinline src=', fn)+ obs = extract_function("edPoolObserve", self.src)+ self.assertIn("IntersectionObserver", obs)+ self.assertIn("removeAttribute('src')", obs)+ # …and the first screenful does not wait for a callback, because+ # intersection callbacks do not run in an occluded tab.+ self.assertIn(".slice(0, 12)", obs)++ # ---- relink ---------------------------------------------------------+ def test_the_relink_banner_says_how_many_and_offers_one_button(self):+ fn = extract_function("sbePaintRelink", self.src)+ self.assertIn("finished since this cut", fn)+ self.assertIn("SBE.relink", fn)+ bar = self.src[self.src.index('id="sbeRelink"'):]+ bar = bar[:bar.index("</div>")]+ self.assertIn("sbeRelink()", bar)+ self.assertIn("Use the finished versions", bar)++ def test_relink_saves_first_then_asks_the_server_to_rewrite(self):+ # The server rewrites edit.json on disk; an unsaved arrangement would+ # be rewritten out from under itself.+ fn = extract_function("sbeRelink", self.src)+ self.assertLess(fn.index("sbeSave(true)"),+ fn.index("/storyboard/edit/relink"))+ self.assertIn("sbeAdopt(r, true)", fn)++ # ---- WAVE 2: the surfaces the new verbs need -------------------------+ def test_the_pool_offers_images_as_a_fourth_source(self):+ pane = self.src[self.src.index('id="edSectionTab"'):]+ pane = pane[:pane.index('id="edPoolNote"')]+ self.assertIn('data-src="images"', pane)+ self.assertIn("Images", pane)+ # The gallery has carried kind:'image' since it was unified; what was+ # missing was a clip that could BE one.+ fn = extract_function("edPoolRefresh", self.src)+ self.assertIn("o.kind === 'image'", fn)+ self.assertIn("kind: 'still'", fn)++ def test_a_still_thumbnail_is_capped_like_every_other_thumbnail(self):+ # The still branch emits a bare <img> and the sizing rule named only+ # `video` and `.ed-pool-blank`, so an image row had no width cap:+ # measured live at 180x101 in a 261px row with the text column+ # squeezed to 22px, every filename ellipsised to one character and a+ # dot, rows three times the height of the Generations tab next door.+ css = self.src[self.src.index(".ed-pool-row {"):]+ css = css[:css.index(".ed-pool-row .ed-pool-name {")]+ self.assertIn(".ed-pool-row img, .ed-pool-row video", css)+ # ...and the text column has to be able to claim what is left.+ self.assertIn(".ed-pool-row .ed-pool-meta {\n min-width: 0; "+ "flex: 1 1 auto;", css)++ def test_black_is_made_not_picked(self):+ # It has no file, so it has no row in any list. It is a length.+ pane = self.src[self.src.index('id="edSectionTab"'):]+ pane = pane[:pane.index('id="edPoolNote"')]+ self.assertIn('id="edSlugSecs"', pane)+ self.assertIn("edAddSlug()", pane)+ fn = extract_function("edAddSlug", self.src)+ self.assertIn("kind: 'slug'", fn)+ self.assertIn("sbeInsertAt", fn)+ # No server round trip: nothing on disk to check, no geometry to+ # probe, no proxy to build.+ self.assertNotIn("fetch(", fn)++ def test_a_still_previews_from_image_not_file(self):+ # /file is OUTPUT-bound and the image library lives under+ # panel_uploads, so the obvious fallback would 404 every still.+ fn = extract_function("sbeClipUrl", self.src)+ self.assertIn("'/image?path='", fn)+ self.assertLess(fn.index("/image?path="), fn.index("/file?path="))+ self.assertIn('id="sbeStill"', self.src)++ def test_a_slug_previews_as_black_with_no_file_on_disk(self):+ fn = extract_function("sbeShowFrameAt", self.src)+ self.assertIn("kind === 'slug'", fn)+ # Both layers off leaves the stage's own black — the one case where+ # the preview is not an approximation at all.+ head = fn[fn.index("kind === 'slug'"):]+ head = head[:head.index("kind === 'still'")]+ self.assertIn("v.classList.remove('is-on')", head)+ self.assertNotIn("sbeLoadInto", head)++ def test_a_still_never_reaches_the_missing_proxy_warning(self):+ # "SOURCE (slow — run Prepare)" is advice to run a Prepare that would+ # do nothing: a still needs no proxy and a slug has no file.+ fn = extract_function("sbePaintTrack", self.src)+ self.assertIn("kind === 'video' && !c.proxy ? 'slow' : ''", fn)++ def test_the_track_paints_the_three_kinds_distinctly(self):+ fn = extract_function("sbePaintTrack", self.src)+ self.assertIn("'sbe-clip is-' + kind", fn)+ self.assertIn("sbe-cl-thumb", fn) # a still shows its picture+ self.assertIn("'black'", fn) # a slug says what it is+ css = self.src[self.src.index("THE TIMELINE EDITOR — the sixth"):]+ css = css[:css.index("The panel has no layout breakpoint today")]+ self.assertIn(".sbe-clip.is-slug", css)+ self.assertIn(".sbe-clip.is-still", css)++ def test_the_brightness_slider_previews_live_and_commits_once(self):+ # oninput at pointer speed would push eighty undo steps and eighty+ # saves for one gesture; onchange fires once, when the drag ends.+ fn = extract_function("sbePaintInspector", self.src)+ self.assertIn('oninput="sbeBrightPreview(this.value)"', fn)+ self.assertIn('onchange="sbeBrightCommit(this.value)"', fn)+ preview = extract_function("sbeBrightPreview", self.src)+ self.assertNotIn("sbeMutate", preview)+ self.assertNotIn("sbeQueueSave", preview)+ commit = extract_function("sbeBrightCommit", self.src)+ self.assertIn("sbeSetBrightness", commit)+ self.assertIn("sbeQueueSave", commit)+ # A slug's colour is what a slug IS — there is nothing to grade.+ self.assertIn("(kind === 'slug') ? '' :", fn)++ def test_the_preview_filter_drives_both_stage_layers(self):+ # One place decides what the stage looks like, so the video and the+ # still can never disagree about the grade.+ fn = extract_function("sbeApplyPreviewFilter", self.src)+ self.assertIn("sbeBrightnessCss", fn)+ self.assertIn("sbeEl('sbeVideo')", fn)+ self.assertIn("sbeEl('sbeStill')", fn)++ def test_the_pool_drag_is_pointer_based_and_portals_its_ghost(self):+ # HTML5 dragstart would swallow the track's pointer capture; the same+ # substrate the track already uses coexists by construction.+ self.assertNotIn("ondragstart", self.src)+ start = extract_function("edPoolDragStart", self.src)+ self.assertIn("pointermove", start)+ self.assertIn("pointerup", start)+ move = extract_function("edPoolDragMove", self.src)+ self.assertIn("document.body.appendChild", move) # NOT inside the list+ self.assertIn("ed-drag-ghost", move)+ end = extract_function("edPoolDragEnd", self.src)+ # A press that never leaves the row ends in a click on it, and without+ # the flag that click would act a second time — adding the clip at the+ # end of the track, and (since the two-screen pass) also changing the+ # left monitor. But a drag ONTO THE TRACK fires no click on the row at+ # all, so arming the flag unconditionally left it set to eat the next+ # genuine click: drop a clip, click another to preview it, nothing+ # happens until the second click. The guard is armed only when the+ # pointer came back up inside the row it started in.+ self.assertIn("d.el.contains(ev.target)", end)+ self.assertNotIn("ED.suppressClick = true", end)+ # ...and the pool's drag stops the browser painting the whole editor+ # in selection blue on its way past.+ self.assertIn("ev.preventDefault()", start)+ add = extract_function("edPoolAdd", self.src)+ self.assertIn("if (ED.suppressClick && dropAt === undefined)", add)+ # Add-at-the-end still works and still lands at the end — it is the ++ # on the row now rather than the whole row, because clicking the row+ # previews. `stopPropagation` is what keeps one press from doing both.+ pool = extract_function("edPoolPaint", self.src)+ self.assertIn("edPoolAdd(' + i + ')", pool)+ self.assertIn("event.stopPropagation()", pool)+ self.assertIn('onpointerdown="edPoolDragStart(event,', pool)++ def test_shift_reorders_and_a_plain_drag_still_moves(self):+ down = extract_function("sbeOnTrackDown", self.src)+ self.assertIn("ev.shiftKey ? 'reorder' : 'move'", down)+ move = extract_function("sbeOnTrackMove", self.src)+ self.assertIn("sbeReorderTo(SBE.clips", move)+ self.assertIn("sbeMoveTo(SBE.clips", move)+ # The legend teaches it, in the same voice as the Alt override.+ self.assertIn("reorder instead of move", extract_function(+ "sbeKeysLegend", self.src))++ def test_the_nle_export_is_offered_and_says_what_the_audio_is(self):+ self.assertIn('id="sbeNleBtn"', self.src)+ self.assertIn("Export for Premiere / Resolve / AE", self.src)+ fn = extract_function("sbeExportNle", self.src)+ self.assertIn("'/storyboard/edit/export-nle'", fn)+ # Stems, not the ducked mix — said on screen, not in a support thread.+ self.assertIn("STEMS", fn)+ self.assertIn("/storyboard/edit/reveal", fn)++ def test_the_music_lane_is_below_the_clip_track(self):+ # "It is unusual that the music is above the clips; it's not normal."+ # The inner is a flex column with no `order` anywhere, so DOM order is+ # screen order and this assertion is the layout.+ inner = self.src[self.src.index('id="sbeInner"'):]+ inner = inner[:inner.index('id="sbeHead"')]+ self.assertLess(inner.index('id="sbeRuler"'), inner.index('id="sbeTrack"'))+ self.assertLess(inner.index('id="sbeTrack"'), inner.index('id="sbeWave"'))+ self.assertLess(inner.index('id="sbeWave"'), inner.index('id="sbeWaveNone"'))+ self.assertNotIn("order:", inner)++ def test_every_empty_surface_says_what_is_true_and_what_to_do(self):+ # A pool that goes blank reads as broken, and the four sources fail+ # for four different reasons.+ fn = extract_function("edPoolPaint", self.src)+ for phrase in ("No generations yet",+ "No images yet — press Upload",+ "No other __SEQS__ yet",+ "This __SEQ__ has no rendered clips yet",+ "matches"):+ self.assertIn(phrase, fn)+ # ...and an empty timeline names the next move rather than sitting+ # there with a clip count of zero — ON THE TIMELINE. It used to be+ # written into the inspector, a short auto-scrolled box in the corner,+ # so the user of a brand-new draft read the sentence starting mid-word+ # while the track itself rendered nothing at all.+ track = extract_function("sbePaintTrack", self.src)+ self.assertIn("sbe-track-empty", track)+ self.assertIn("Nothing on the timeline yet", track)+ self.assertNotIn("Nothing on the timeline yet",+ extract_function("sbePaintInspector", self.src))+ # The program monitor's empty state was markup nobody ever filled, so+ # the two monitors spoke two languages about the same condition.+ chrome = extract_function("sbePaintChrome", self.src)+ self.assertIn("sbeStageEmpty", chrome)+ self.assertIn("Nothing on the timeline yet", chrome)++ def test_the_pool_can_take_a_file_from_the_user(self):+ # "You cannot upload your own images and insert them into the+ # timeline." The input is hidden because a bare file input cannot be+ # made to look like anything else in this panel; the button is the+ # control, and it belongs to the source that shows what it uploads.+ self.assertIn('id="edPoolFile"', self.src)+ self.assertIn('id="edPoolUploadBtn"', self.src)+ el = extract_element("edPoolFile", self.src)+ self.assertIn("multiple", el)+ for ext in (".png", ".jpg", ".webp", ".mp4", ".mov", ".webm"):+ self.assertIn(ext, el)+ src = extract_function("edPoolSrc", self.src)+ self.assertIn("edPoolUploadBtn", src)+ fn = extract_function("edPoolUpload", self.src)+ self.assertIn("'/storyboard/edit/upload'", fn)+ # ONE REQUEST PER FILE, so a rejected one names itself instead of+ # failing the batch behind it.+ self.assertIn("for (const f of list)", fn)++ def test_a_picture_is_added_as_a_still_whatever_the_row_forgot(self):+ # A pool row that reached the add path without its `kind` — an upload+ # dragged onto the track — made the client ask /file for a PNG and+ # hand it to a <video>. Black frame, no explanation.+ fn = extract_function("edPoolAdd", self.src)+ self.assertIn("row.kind === 'still'", fn)+ self.assertIn("png|jpe?g|webp", fn)++ def test_an_uploaded_clip_is_a_pool_row_like_any_other(self):+ fn = extract_function("edPoolUploadRow", self.src)+ self.assertIn("'still'", fn)+ self.assertIn("SBE_STILL_SECONDS", fn)+ refresh = extract_function("edPoolRefresh", self.src)+ self.assertIn("'/storyboard/edit/uploads'", refresh)+ self.assertIn("ED.uploaded", refresh)++ def test_the_editor_uses_the_panels_own_colour_tokens(self):+ # --ink / --ink-500 / --line are not defined anywhere in this panel.+ css = self.src[self.src.index("THE TIMELINE EDITOR — the sixth"):]+ css = css[:css.index("The panel has no layout breakpoint today")]+ for stray in ("var(--ink", "var(--line", "var(--ink-500"):+ self.assertNotIn(stray, css)+ self.assertIn("var(--panel", css)+ self.assertIn("var(--border", css)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_storyboard_film.py b/test_storyboard_film.pynew file mode 100644index 0000000..eb5a4c9--- /dev/null+++ b/test_storyboard_film.py@@ -0,0 +1,536 @@+#!/usr/bin/env python3+"""The finished film — the folder it lands in, and the screen that shows it.++Both assemblers (Export's whole-clip join and the timeline's render) wrote an+mp4 into `mlx_outputs/storyboards/<date>_<slug>/` and then told nobody: the+gallery globs `OUTPUT/*.mp4` and never descends, so the one thing the feature+makes was the one thing it could not show you. The owner's words: *"it+shouldn't be so hard to see the finalized clip instead of seeing these clips+all around. Where is the finalized clip?"*++Two halves are locked here, the same way the rest of the storyboard suite locks+its two halves.++**Server.** One function owns the folder name, so the writer and the reader can+never disagree about where a film is. A film is anything in that folder that is+not a `S07_*.mp4` shot copy. The assembler writes down what it already knows,+so the board list can say "0:28" without shelling out to ffprobe twice a+second.++**Client.** The rail — the four steps a film goes through — decides what is+reachable, and it is the answer to the other complaint: *"how do I get to the+editor? It doesn't even have a button."* Its model is pure and runs in node+here, as does `sbOpen`'s promise: the row's Edit button used to open the+timeline and then have it torn straight back down, because `sbOpen` swallowed+the load it was supposed to return.++Run: python3 -m unittest test_storyboard_film+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import time+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402+import mlx_ltx_panel as panel # noqa: E402++NODE = shutil.which("node")+++def _board(**kw) -> dict:+ b = {"schema": 1, "id": "sb_film_test", "title": "The Last Dawn",+ "created_at": 1_700_000_000, "cast": [], "shots": []}+ b.update(kw)+ return b+++# =============================================================================+# The folder — one name, one owner+# =============================================================================+class FilmDir(unittest.TestCase):++ def test_the_folder_is_date_and_slug_under_the_outputs_root(self):+ d = panel._sb_film_dir(_board())+ self.assertEqual(d.parent, panel.OUTPUT / "storyboards")+ self.assertTrue(d.name.endswith("_the-last-dawn"), d.name)+ day = time.strftime("%Y-%m-%d", time.localtime(1_700_000_000))+ self.assertTrue(d.name.startswith(day), d.name)++ def test_an_untitled_board_still_gets_a_folder(self):+ self.assertTrue(str(panel._sb_film_dir(_board(title=""))).endswith("_storyboard"))++ def test_the_export_writes_into_exactly_that_folder(self):+ # The whole point of the helper: the writer and the reader agree by+ # construction, not by two copies of the same six lines.+ with tempfile.TemporaryDirectory() as tmp:+ with mock.patch.object(panel, "OUTPUT", Path(tmp)):+ b = _board()+ res = panel._sb_export(b)+ self.assertEqual(Path(res["dir"]), panel._sb_film_dir(b))++ def test_a_path_inside_the_install_is_shown_relative(self):+ shown = panel._sb_display_path(panel.OUTPUT / "storyboards" / "x")+ self.assertFalse(Path(shown).is_absolute(), shown)+ self.assertIn("storyboards", shown)++ def test_a_path_outside_everything_is_shown_whole_rather_than_wrong(self):+ self.assertEqual(panel._sb_display_path(Path("/nowhere/at/all")),+ "/nowhere/at/all")+++# =============================================================================+# What counts as a film+# =============================================================================+class Films(unittest.TestCase):++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.out = Path(self.tmp.name)+ self.board = _board()+ p = mock.patch.object(panel, "OUTPUT", self.out)+ p.start()+ self.addCleanup(p.stop)+ self.dir = panel._sb_film_dir(self.board)+ self.dir.mkdir(parents=True)+ panel._SB_FILM_FACTS.clear()++ def tearDown(self):+ self.tmp.cleanup()++ def _write(self, name, *, at=None, sidecar=None, size=1024):+ p = self.dir / name+ p.write_bytes(b"\0" * size)+ if at:+ import os+ os.utime(p, (at, at))+ if sidecar is not None:+ (self.dir / (name + ".json")).write_text(+ json.dumps({"film": sidecar}), encoding="utf-8")+ return p++ def test_a_shot_copy_is_not_a_film(self):+ self._write("S01_cold-open.mp4")+ self._write("S12_the-empty-gym.mp4")+ self.assertEqual(panel._sb_films(self.board, probe=False), [])++ def test_a_legacy_timeline_render_is_still_named_as_one(self):+ # There is ONE assembler now, and one name — `<slug>_film.mp4` from+ # either door. `_timeline.mp4` only exists on installs that rendered+ # before the merge, and the screen should not rewrite their history.+ self._write("the-last-dawn_film.mp4", at=1000, sidecar={"duration": 30})+ self._write("the-last-dawn_timeline.mp4", at=2000, sidecar={"duration": 20})+ films = panel._sb_films(self.board, probe=False)+ self.assertEqual([f["name"] for f in films],+ ["the-last-dawn_timeline.mp4", "the-last-dawn_film.mp4"])+ self.assertEqual([f["kind"] for f in films], ["timeline", "film"])++ def test_films_are_newest_first(self):+ self._write("a_film.mp4", at=1000, sidecar={"duration": 1})+ self._write("b_timeline.mp4", at=5000, sidecar={"duration": 1})+ self._write("c_cut.mp4", at=3000, sidecar={"duration": 1})+ self.assertEqual([f["name"] for f in panel._sb_films(self.board, probe=False)],+ ["b_timeline.mp4", "c_cut.mp4", "a_film.mp4"])++ def test_the_url_is_the_panels_own_file_route(self):+ p = self._write("x_film.mp4", sidecar={"duration": 3})+ row = panel._sb_films(self.board, probe=False)[0]+ self.assertTrue(row["url"].startswith("/file?path="))+ self.assertIn(p.name, row["url"])++ def test_the_sidecar_answers_without_an_ffprobe(self):+ self._write("x_film.mp4", sidecar={"duration": 27.875, "width": 1280,+ "height": 720, "clips": 6})+ with mock.patch.object(panel, "_sb_probe_clip",+ side_effect=AssertionError("must not probe")):+ row = panel._sb_films(self.board, probe=False)[0]+ self.assertEqual(row["duration"], 27.875)+ self.assertEqual(row["width"], 1280)+ self.assertEqual(row["clips"], 6)++ def test_the_polling_path_never_shells_out(self):+ # The board list asks "does this board have a film" every two seconds.+ # A list that shells out is a list that stutters.+ self._write("x_film.mp4") # no sidecar at all+ with mock.patch.object(panel, "_sb_probe_clip",+ side_effect=AssertionError("must not probe")):+ row = panel._sb_films(self.board, probe=False)[0]+ self.assertIsNone(row["duration"])++ def test_a_film_with_no_sidecar_is_probed_once_and_written_down(self):+ self._write("old_film.mp4")+ calls = []++ def fake(p):+ calls.append(p)+ return {"w": 640, "h": 360, "duration": 12.5,+ "has_audio": True, "sample_rate": 48000}++ with mock.patch.object(panel, "_sb_probe_clip", side_effect=fake):+ first = panel._sb_films(self.board)[0]+ second = panel._sb_films(self.board)[0]+ self.assertEqual(first["duration"], 12.5)+ self.assertEqual(second["duration"], 12.5)+ self.assertEqual(len(calls), 1, "probed twice for the same bytes")+ # And it survives a restart, because it is on disk now.+ self.assertTrue((self.dir / "old_film.mp4.json").is_file())++ def test_a_missing_folder_is_no_films_not_an_error(self):+ shutil.rmtree(self.dir)+ self.assertEqual(panel._sb_films(self.board), [])++ def test_the_summary_is_the_newest_film_and_how_many_there_are(self):+ self._write("a_film.mp4", at=1000, sidecar={"duration": 9})+ self._write("b_timeline.mp4", at=9000, sidecar={"duration": 25})+ s = panel._sb_film_summary(self.board)+ self.assertEqual(s["name"], "b_timeline.mp4")+ self.assertEqual(s["duration"], 25)+ self.assertEqual(s["count"], 2)++ def test_a_board_with_no_film_summarises_to_nothing(self):+ self.assertIsNone(panel._sb_film_summary(self.board))++ def test_the_board_summary_carries_the_film_so_the_row_can_say_so(self):+ self._write("b_timeline.mp4", at=9000, sidecar={"duration": 25})+ row = panel._sb_board_summary(self.board)+ self.assertIn("film", row)+ self.assertEqual(row["film"]["name"], "b_timeline.mp4")+++# =============================================================================+# The assembler writes down what it knows+# =============================================================================+class Sidecar(unittest.TestCase):++ def test_a_successful_assembly_leaves_its_facts_beside_the_film(self):+ with tempfile.TemporaryDirectory() as tmp:+ out = Path(tmp) / "x_film.mp4"++ def fake_ffmpeg(cmd, *a, **kw):+ out.write_bytes(b"\0" * 4096)++ probe = {"w": 1024, "h": 576, "duration": 5.0,+ "has_audio": True, "sample_rate": 48000}+ with mock.patch.object(panel, "_sb_probe_clip", return_value=probe), \+ mock.patch.object(panel, "run_ffmpeg_tracked", side_effect=fake_ffmpeg), \+ mock.patch.object(panel, "output_codec_settings",+ return_value={"pix_fmt": "yuv420p", "crf": "23"}):+ res = panel._sb_assemble_film([Path(tmp) / "a.mp4",+ Path(tmp) / "b.mp4"], out)+ self.assertTrue(res["ok"], res.get("error"))+ side = json.loads((Path(tmp) / "x_film.mp4.json").read_text())+ self.assertEqual(side["film"]["clips"], 2)+ self.assertEqual(side["film"]["width"], 1024)+ self.assertAlmostEqual(side["film"]["duration"], 10.0, places=3)++ def test_a_failed_assembly_writes_no_sidecar(self):+ # A sidecar for a film that does not exist would make the board list+ # advertise a film nobody can play.+ with tempfile.TemporaryDirectory() as tmp:+ out = Path(tmp) / "x_film.mp4"+ with mock.patch.object(panel, "_sb_probe_clip", return_value=None):+ res = panel._sb_assemble_film([Path(tmp) / "a.mp4"], out)+ self.assertFalse(res["ok"])+ self.assertFalse((Path(tmp) / "x_film.mp4.json").exists())+++# =============================================================================+# The client: the rail, the row, and the promise that broke the Edit button+# =============================================================================+FUNCTIONS = ("sbFmtClock", "sbFmtBytes", "sbFmtAgo", "sbFilmKind", "sbFilmPick",+ "sbRailModel", "sbBoardChip", "sbRowAction", "sbOpen", "sbOpenAt",+ "sbGo", "edOpenBoard")++SHIM = r"""+'use strict';+const ORDER = [];+const SB = { id: '', films: [], filmsFor: '', filmOpen: '', stage: '' };+let SBE = { open: false };+function escapeHtml(s) { return String(s).replace(/&/g, '&').replace(/</g, '<'); }+const localStorage = { setItem() {}, getItem() { return ''; }, removeItem() {} };+// The four things sbGo can reach for. Stubs, because what is under test is+// which one it picks — not what they do.+function sbeClose() { ORDER.push('sbeClose'); SBE.open = false; }+function sbeOpen(id) { ORDER.push('sbeOpen'); SBE.open = true; SBE.id = id || SB.id; }+// The Editor is a TAB now. Step 3 switches to it carrying the film, so the+// door under test is a workflow switch plus an open — not a stage swap.+function workflowSwitch(n) { ORDER.push('workflowSwitch:' + n); }+function sbOpenReplan() { ORDER.push('sbOpenReplan'); }+function sbFilmOpen() { ORDER.push('sbFilmOpen'); }+function sbShow(w) { ORDER.push('sbShow:' + w); SB.stage = w; }+function sbRenderPlan() { ORDER.push('sbRenderPlan'); }+let LOAD_DELAY = 0;+async function sbLoad(id) {+ await new Promise(r => setTimeout(r, LOAD_DELAY));+ ORDER.push('sbLoad:' + id);+}+__FUNCTIONS__+async function main() {+ const out = {};++ // ---- formatting ----+ out.clock = [sbFmtClock(0), sbFmtClock(27.875), sbFmtClock(65), sbFmtClock(600)];+ out.bytes = [sbFmtBytes(0), sbFmtBytes(2048), sbFmtBytes(18179743),+ sbFmtBytes(3 * 1073741824)];+ const NOW = 1700000000000;+ out.ago = [sbFmtAgo(0, NOW), sbFmtAgo(NOW / 1000 - 10, NOW),+ sbFmtAgo(NOW / 1000 - 600, NOW), sbFmtAgo(NOW / 1000 - 7200, NOW),+ sbFmtAgo(NOW / 1000 - 172800, NOW)];+ out.kinds = [sbFilmKind({ kind: 'timeline' }), sbFilmKind({ kind: 'export' }),+ sbFilmKind({ kind: 'film' }), sbFilmKind(null)];++ // ---- which film is on screen ----+ const films = [{ name: 'b.mp4', at: 2 }, { name: 'a.mp4', at: 1 }];+ out.pickNewest = sbFilmPick(films, '').name;+ out.pickNamed = sbFilmPick(films, 'a.mp4').name;+ out.pickMissing = sbFilmPick(films, 'gone.mp4').name;+ out.pickEmpty = sbFilmPick([], 'a.mp4');++ // ---- the rail ----+ out.railNoClips = sbRailModel({ clips: 0, shots: 6, film: null, stage: 'plan' })+ .map(s => [s.key, s.state]);+ out.railClips = sbRailModel({ clips: 6, shots: 6, film: null, stage: '' })+ .map(s => [s.key, s.state]);+ out.railTimeline = sbRailModel({ clips: 6, shots: 6, film: null, stage: 'editor' })+ .map(s => [s.key, s.state]);+ out.railFilm = sbRailModel({ clips: 6, shots: 6, film: { duration: 27.875 },+ stage: 'film' });+ out.railLockedHint = sbRailModel({ clips: 0, shots: 6, film: null, stage: 'plan' })+ .filter(s => s.key === 'edit')[0].hint;+ out.railShotsSub = [+ sbRailModel({ clips: 0, shots: 6, film: null, stage: 'plan' })+ .filter(s => s.key === 'shots')[0].sub,+ sbRailModel({ clips: 4, shots: 6, film: null, stage: 'plan' })+ .filter(s => s.key === 'shots')[0].sub];++ // ---- the board row ----+ out.chips = [+ sbBoardChip({ planning: true, shots: 6, done: 0, clips: 0 }),+ sbBoardChip({ running: true, shots: 6, done: 2, clips: 2 }),+ sbBoardChip({ shots: 6, done: 0, clips: 0 }),+ sbBoardChip({ shots: 7, done: 0, clips: 7 }),+ sbBoardChip({ shots: 6, done: 6, clips: 6 }),+ sbBoardChip({ shots: 6, done: 3, clips: 3 }),+ sbBoardChip({ shots: 6, done: 1, clips: 1, failed: 2 })];+ out.rowNothing = sbRowAction({ id: 'x', shots: 6, done: 0, clips: 0 });+ out.rowClips = sbRowAction({ id: 'x', shots: 6, done: 0, clips: 7 });+ out.rowFilm = sbRowAction({ id: 'x', shots: 6, done: 6, clips: 6,+ film: { name: 'x.mp4', duration: 27.875 } });++ // ---- the promise the Edit button needed ----+ ORDER.length = 0;+ LOAD_DELAY = 20;+ SB.id = '';+ await sbOpenAt('sb_demo', 'edit');+ out.openAtOrder = ORDER.slice();++ // ---- every door ----+ ORDER.length = 0;+ SB.id = 'sb_demo'; SBE.open = false; SB.stage = 'plan';+ sbGo('edit'); sbGo('film');+ SBE.open = true; sbGo('shots');+ SBE.open = false; sbGo('plan');+ out.doors = ORDER.slice();+ ORDER.length = 0;+ SB.id = '';+ sbGo('edit');+ out.doorsWithNoBoard = ORDER.slice();++ process.stdout.write(JSON.stringify(out));+}+main();+"""+++def run_client() -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ body = "\n".join(extract_function(n) for n in FUNCTIONS)+ script = SHIM.replace("__FUNCTIONS__", body)+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = Path(fh.name)+ try:+ res = subprocess.run([NODE, str(path)], capture_output=True, text=True,+ timeout=60)+ if res.returncode:+ raise AssertionError(res.stdout + "\n" + res.stderr)+ return json.loads(res.stdout)+ finally:+ path.unlink(missing_ok=True)++[email protected](NODE, "needs node")+class FilmClient(unittest.TestCase):++ @classmethod+ def setUpClass(cls):+ cls.r = run_client()++ # ---- formatting ------------------------------------------------------+ def test_a_films_length_is_written_the_way_a_player_writes_it(self):+ self.assertEqual(self.r["clock"], ["0:00", "0:28", "1:05", "10:00"])++ def test_sizes_are_readable(self):+ self.assertEqual(self.r["bytes"], ["0 B", "2 KB", "17 MB", "3.0 GB"])++ def test_when_it_was_made_needs_no_arithmetic(self):+ self.assertEqual(self.r["ago"],+ ["", "just now", "10 minutes ago", "2 hours ago",+ "2 days ago"])++ def test_the_screen_says_which_button_made_the_file(self):+ # `export` survives as a client label for anything still carrying that+ # kind, but nothing writes it any more: one assembler, one name, so a+ # new film is just the film. `timeline` remains for the files written+ # before the merge — the screen should not rewrite their history.+ self.assertEqual(self.r["kinds"],+ ["Timeline render", "Export", "Film", "Film"])++ def test_new_films_are_no_longer_labelled_by_the_button_that_made_them(self):+ import inspect+ self.assertIn("'Timeline render'", extract_function("sbFilmKind"))+ code = inspect.getsource(panel._sb_films)+ self.assertIn('"timeline" if p.stem.endswith("_timeline") else "film"',+ code)+ self.assertNotIn('"export"', code)++ # ---- which film ------------------------------------------------------+ def test_the_newest_film_is_the_one_on_screen_by_default(self):+ self.assertEqual(self.r["pickNewest"], "b.mp4")++ def test_a_named_film_wins_over_the_newest(self):+ # The render that just finished is the one to show, even in the second+ # it takes the folder listing to agree about mtimes.+ self.assertEqual(self.r["pickNamed"], "a.mp4")++ def test_a_name_that_is_gone_falls_back_rather_than_showing_nothing(self):+ self.assertEqual(self.r["pickMissing"], "b.mp4")++ def test_no_films_is_no_film(self):+ self.assertIsNone(self.r["pickEmpty"])++ # ---- the rail --------------------------------------------------------+ def test_with_nothing_rendered_the_last_two_steps_are_locked(self):+ self.assertEqual(self.r["railNoClips"],+ [["plan", "done"], ["shots", "now"],+ ["edit", "locked"], ["film", "locked"]])++ def test_a_clip_on_disk_unlocks_the_editor(self):+ # Not `done` — that counts jobs THIS panel ran. A board of imported or+ # restored clips is exactly as editable, and gating on `done` hid the+ # timeline on a film whose clips were sitting right there.+ self.assertEqual(self.r["railClips"],+ [["plan", "done"], ["shots", "done"],+ ["edit", "ready"], ["film", "ready"]])++ def test_the_step_you_are_standing_in_says_so(self):+ # "Standing in it" now means the EDITOR TAB holds this film — the+ # timeline stopped being a state of the storyboard's stage.+ self.assertEqual(self.r["railTimeline"],+ [["plan", "done"], ["shots", "done"],+ ["edit", "now"], ["film", "ready"]])++ def test_the_film_step_carries_the_runtime(self):+ film = [s for s in self.r["railFilm"] if s["key"] == "film"][0]+ self.assertEqual(film["state"], "now")+ self.assertEqual(film["sub"], "0:28")++ def test_a_locked_step_still_says_what_would_unlock_it(self):+ self.assertIn("Render a shot first", self.r["railLockedHint"])++ def test_the_shots_step_counts_what_is_on_disk(self):+ self.assertEqual(self.r["railShotsSub"], ["6 planned", "4 of 6 rendered"])++ # ---- the board row ---------------------------------------------------+ def test_a_board_of_imported_clips_is_not_called_plan_only(self):+ # It said "plan only" while seven finished shots sat in the folder.+ self.assertEqual(self.r["chips"],+ ["planning", "rendering", "plan only", "7 clips",+ "drafts done", "3 of 6", "2 failed"])++ def test_a_board_with_no_clips_offers_nothing_it_cannot_do(self):+ self.assertEqual(self.r["rowNothing"], "")++ def test_a_board_with_clips_offers_the_editor(self):+ # One name for one surface: the row says "Open in Editor", the rail's+ # step 3 says "Edit", the tab says "Editor". Nothing says "Arrange".+ self.assertIn("sbOpenAt('x','edit')", self.r["rowClips"])+ self.assertIn("Open in Editor", self.r["rowClips"])++ def test_a_board_with_a_film_offers_the_film_and_its_length(self):+ self.assertIn("sbOpenAt('x','film')", self.r["rowFilm"])+ self.assertIn("0:28", self.r["rowFilm"])+ self.assertNotIn("'edit'", self.r["rowFilm"])++ # ---- the bug the Edit button had -------------------------------------+ def test_the_step_is_taken_AFTER_the_board_has_loaded(self): # noqa: D401+ # sbOpen() used to swallow sbLoad()'s promise, so `await sbOpen(id)`+ # resolved immediately, the timeline opened, and the load that was+ # still in flight then called sbShow('plan') and tore it back down.+ # Clicking Edit landed on the shot list. Order is the whole fix.+ self.assertEqual(self.r["openAtOrder"],+ ["sbLoad:sb_demo", "workflowSwitch:editor", "sbeOpen"])++ # ---- every door ------------------------------------------------------+ def test_each_step_opens_exactly_one_thing(self):+ # Step 3 is a TAB SWITCH that carries the film. Step 2 no longer has+ # to close the editor to show the shot list — they are different tabs+ # now, and leaving one does not tear the other down.+ self.assertEqual(self.r["doors"],+ ["workflowSwitch:editor", "sbeOpen", "sbFilmOpen",+ "sbShow:plan", "sbOpenReplan"])++ def test_no_board_open_is_nowhere_to_go(self):+ self.assertEqual(self.r["doorsWithNoBoard"], [])+++# =============================================================================+# The markup the client drives has to exist+# =============================================================================+class FilmMarkup(unittest.TestCase):++ @classmethod+ def setUpClass(cls):+ cls.src = panel.HTML++ def test_the_rail_carries_all_four_steps(self):+ for step in ("plan", "shots", "edit", "film"):+ self.assertIn('data-step="%s"' % step, self.src)++ def test_the_film_state_exists_and_has_somewhere_to_paint(self):+ self.assertIn('id="sbFilm"', self.src)+ self.assertIn('id="sbFilmBody"', self.src)++ def test_sbShow_knows_about_the_film_state(self):+ self.assertIn("film: 'sbFilm'", extract_function("sbShow"))++ def test_leaving_the_film_screen_stops_its_player(self):+ # A <video> left playing behind a hidden div is a decoder and a+ # soundtrack nobody can see.+ self.assertIn("v.pause()", extract_function("sbShow"))++ def test_both_assemblies_end_on_the_film(self):+ # A toast that fades is what made the finished film invisible.+ self.assertIn("sbFilmOpen", extract_function("sbeRenderFilm"))+ self.assertIn("sbFilmOpen", extract_function("sbExport"))++ def test_the_render_still_discloses_that_the_concat_closes_gaps(self):+ # The disclosure the editor gate already locks — proving the landing+ # was added to it, not swapped for it.+ fn = extract_function("sbeRenderFilm")+ self.assertIn("gaps_note", fn)+ self.assertIn("CONCATENATES", fn)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard_planner.py b/test_storyboard_planner.pyindex 1aaa784..3ebcb6a 100644--- a/test_storyboard_planner.py+++ b/test_storyboard_planner.py@@ -43,9 +43,23 @@ import storyboard_planner as P # noqa: E402class StubSession(object):"""Stands in for PlannerSession. Replays canned replies, records what it was asked."""- def __init__(self, replies):+ def __init__(self, replies, screenplay="", geography=""):self.replies = list(replies)+ # The screenplay pass answers from its OWN slot and never consumes a+ # queued reply. `replies` is the shot-pass script in every test in this+ # file, and threading a screenplay through all of them would have made+ # 27 tests about pass ordering instead of about what they each test.+ # Default "" == the model gave nothing usable, which is the documented+ # fallback and makes the shot brief byte-identical to before this pass.+ self.screenplay = screenplay+ # The geography pass gets its own slot for the same reason, and needs+ # one more than the screenplay did: it only runs when the brief carries+ # a location, so the default "" leaves every test that names no place+ # measuring exactly what it measured before it existed.+ self.geography = geographyself.calls = []+ self.screenplay_calls = []+ self.geography_calls = []self.model_path = Path("stub-model")self.stats = {"model_path": "stub-model", "load_s": 0.0, "calls": 0,"gen_s_total": 0.0, "prompt_tokens": 0, "output_tokens": 0,@@ -53,8 +67,24 @@ class StubSession(object):self.released = Falsedef generate(self, system, user, **kw):- self.calls.append({"system": system, "user": user, "kw": kw})self.stats["calls"] += 1+ if system == P._SCREENPLAY_SYSTEM:+ # Recorded SEPARATELY. Every assertion in this file reads `calls` as+ # "calls in the shot pass" — indexing into it for the repair prompt,+ # and counting it to prove a clean plan cost no re-plan. Appending+ # the screenplay call to the same list would silently redefine what+ # eleven of those tests measure. `stats["calls"]` still counts it,+ # so the real cost is not hidden anywhere.+ self.screenplay_calls.append({"system": system, "user": user, "kw": kw})+ return {"text": self.screenplay, "load_s": 0.0, "gen_s": 0.0,+ "prompt_tokens": 10, "output_tokens": 10,+ "peak_rss_bytes": 0, "mx_peak_bytes": 0}+ if system == P._GEOGRAPHY_SYSTEM:+ self.geography_calls.append({"system": system, "user": user, "kw": kw})+ return {"text": self.geography, "load_s": 0.0, "gen_s": 0.0,+ "prompt_tokens": 10, "output_tokens": 10,+ "peak_rss_bytes": 0, "mx_peak_bytes": 0}+ self.calls.append({"system": system, "user": user, "kw": kw})if not self.replies:raise AssertionError("stub ran out of replies after %d calls" % len(self.calls))nxt = self.replies.pop(0)@@ -113,7 +143,8 @@ def _plan(replies, **kw):The stub is installed as the PlannerSession class rather than handed in as`session=`, so plan_film() owns it and its `finally:` release is exercised."""- stub = StubSession(replies)+ stub = StubSession(replies, screenplay=kw.pop("screenplay_text", ""),+ geography=kw.pop("geography_text", ""))kw.setdefault("concept", "a lost brass key finds its door")kw.setdefault("n_shots", 6)concept = kw.pop("concept")@@ -1320,5 +1351,533 @@ class TestLawEnforcement(unittest.TestCase):self.assertIn("SPEECH (L13)", stub.calls[1]["user"])+class TestScreenplayPass(unittest.TestCase):+ """Pass one writes the SCENE; pass two shoots it.++ Owner, on the films this planner produced before it existed: "the prompt+ writing should be like a movie director... The action is well planned. You+ understand what I mean? It is not working properly. It's just a succession+ of shots." Maestro does screenplay -> shot breakdown -> per-model polish;+ this had no screenplay step at all, so structure and coverage were being+ invented in the same breath.+ """+ SCENE = "\n".join([+ "BEAT - He throws both arms wide in front of the soapy car.",+ 'BIZARRO: "Ladies and gentlemen."',+ "BEAT - She keeps scrubbing and does not look up.",+ 'ARIA: "Update the app."',+ ])++ def _film(self, desc="A man stands in the rain."):+ return json.dumps({"title": "T", "shots": [+ {"n": i + 1, "title": "B%d" % (i + 1), "character_id": None,+ "duration_s": 5, "camera": "static", "description": desc,+ "settle": "he is still", "soundscape": "Rain, no voices.",+ "music": "N/A"} for i in range(2)]})++ def test_the_scene_is_written_before_the_shots(self):+ spec, stub = _plan([self._film()], n_shots=2, screenplay_text=self.SCENE)+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertEqual(len(stub.screenplay_calls), 1)+ self.assertIn("You are a screenwriter", stub.screenplay_calls[0]["system"])++ def test_the_scene_reaches_the_shot_brief_verbatim(self):+ spec, stub = _plan([self._film()], n_shots=2, screenplay_text=self.SCENE)+ brief = stub.calls[0]["user"]+ self.assertIn("THE SCENE", brief)+ self.assertIn('BIZARRO: "Ladies and gentlemen."', brief)+ self.assertIn("keep every spoken line", brief)++ def test_a_model_that_answers_with_chatter_is_ignored(self):+ # Small models like to open with "Sure! Here is the scene:" and a+ # paragraph that is not a beat. Handing that down as if it were the+ # scene is worse than having no scene.+ _, stub = _plan([self._film()], n_shots=2,+ screenplay_text="Sure! Here is a great scene for you.\nEnjoy!")+ self.assertNotIn("THE SCENE", stub.calls[0]["user"])++ def test_no_screenplay_leaves_the_brief_exactly_as_it_was(self):+ _, stub = _plan([self._film()], n_shots=2, screenplay_text="")+ self.assertNotIn("THE SCENE", stub.calls[0]["user"])++ def test_it_can_be_turned_off(self):+ _, stub = _plan([self._film()], n_shots=2, screenplay=False,+ screenplay_text=self.SCENE)+ self.assertEqual(stub.screenplay_calls, [])++ def test_a_reroll_does_not_rewrite_the_scene(self):+ # A per-shot re-roll is fixing ONE shot. Regenerating the screenplay+ # under it would move the ground the other shots are standing on.+ base, _ = _plan([_plan_json(6)])+ _, stub = _plan([_plan_json(1)], n_shots=6, previous=base,+ feedback={"shot": 1, "note": "again"},+ screenplay_text=self.SCENE)+ self.assertEqual(stub.screenplay_calls, [])+++# --------------------------------------------------------------------------------------+# The geography pass — the screenplay is TIME, this is SPACE+# --------------------------------------------------------------------------------------++CARWASH = {"id": "carwash", "name": "The car wash",+ "description": "a suburban driveway on a bright afternoon"}++# What the blocking model is asked for, on the day's own scene. Everything the+# feature promises is in these two views: the reverse does not hold the car and+# SAYS so, and the sun that rakes in from camera left rakes in from camera right+# once the camera has turned around.+GEO_JSON = json.dumps({+ "floor_plan":+ "The driveway runs left to right in front of the garage. BIZARRO stands at the "+ "near end of a soapy blue sedan facing the street; behind him is the garage door. "+ "ARIA crouches at the front wheel with a sponge. Across the street, behind "+ "BIZARRO's eyeline, is a row of low houses and a hand-painted sign on the verge. "+ "The low afternoon sun comes over the houses.",+ "views": [+ {"location": "The car wash", "id": "establishing",+ "name": "Establishing - facing the driveway", "light": "camera left",+ "description": "the soapy blue sedan on the driveway with a woman crouched at "+ "the front wheel, the garage door behind them"},+ {"location": "The car wash", "id": "reverse",+ "name": "Reverse - facing the street", "light": "camera right",+ "description": "the row of low houses across the street and a hand-painted sign "+ "on the far verge, no car in frame"},+ ]})+++def _geo_film(shots):+ return json.dumps({"title": "The Car Wash", "shots": shots})+++class TestGeographyPass(unittest.TestCase):+ """The planner learns SPACE.++ Owner, after a full day of manual continuity work: "Do you notice all the+ work I had to do to make this scene happen in the same place and have+ proper angles? ... You need to first make a concept of the whole situation.+ For instance, a man or woman in a bar — behind him there is this, behind her+ there is that. When they sit together, this is what you see."++ The whole day was the prototype: carwash/carwash_reverse, the flipped sun,+ the off-frame eyelines, the no-car reverse background — all hand-built, all+ derivable from one paragraph of floor plan.+ """++ def _film(self, n=2, **kw):+ rows = []+ for i in range(n):+ row = {"n": i + 1, "title": "B%d" % (i + 1), "character_id": None,+ "duration_s": 5, "camera": "static",+ "description": "A man throws both arms wide.",+ "settle": "he is still", "soundscape": "Hose water, no voices.",+ "music": "N/A", "location": "The car wash"}+ row.update(kw)+ rows.append(row)+ return _geo_film(rows)++ def _plan_carwash(self, replies=None, **kw):+ kw.setdefault("n_shots", 2)+ kw.setdefault("locations", [dict(CARWASH)])+ kw.setdefault("geography_text", GEO_JSON)+ return _plan(replies or [self._film()], **kw)++ # ---- the pass itself ----------------------------------------------------+ def test_the_floor_plan_is_written_before_the_shots(self):+ spec, stub = self._plan_carwash()+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertEqual(len(stub.geography_calls), 1)+ self.assertIn("You are a director blocking a scene",+ stub.geography_calls[0]["system"])+ self.assertIn("The car wash", stub.geography_calls[0]["user"])++ def test_it_reads_the_scene_so_it_knows_who_turns_to_whom(self):+ scene = "\n".join(['BEAT - He turns to her.',+ 'BIZARRO: "Ladies and gentlemen."',+ 'BEAT - She keeps scrubbing.',+ 'ARIA: "Update the app."'])+ _, stub = self._plan_carwash(screenplay_text=scene)+ self.assertIn("THE SCENE THAT HAPPENS HERE", stub.geography_calls[0]["user"])+ self.assertIn("Ladies and gentlemen", stub.geography_calls[0]["user"])++ def test_the_views_are_merged_into_the_boards_locations(self):+ spec, _ = self._plan_carwash()+ views = spec["locations"][0]["views"]+ self.assertEqual([v["id"] for v in views], ["establishing", "reverse"])+ self.assertIn("sedan", views[0]["description"])+ self.assertIn("houses", views[1]["description"])+ self.assertNotIn("sedan", views[1]["description"])++ def test_the_light_flips_at_180_degrees(self):+ # Measured on the real cut, and the one thing a second hand-authored+ # location got right only because a human remembered to flip it.+ spec, _ = self._plan_carwash()+ front, back = spec["locations"][0]["views"]+ self.assertIn("camera left", front["description"])+ self.assertNotIn("camera right", front["description"])+ self.assertIn("camera right", back["description"])+ self.assertNotIn("camera left", back["description"])++ def test_the_views_and_the_laws_reach_the_shot_brief(self):+ _, stub = self._plan_carwash()+ brief = stub.calls[0]["user"]+ self.assertIn("VIEWS of The car wash", brief)+ self.assertIn("establishing", brief)+ self.assertIn("reverse", brief)+ self.assertIn("THE FLOOR PLAN", brief)+ self.assertIn("behind him is the garage door", brief)+ self.assertIn("THE 180-DEGREE RULE", brief)+ self.assertIn("Never put a character's own body in the view behind them", brief)++ def test_views_without_a_floor_plan_still_reach_the_model(self):+ # THE COERCION BUG. `_geography_plan` derives the floor plan from the+ # model's own optional key, so a reply carrying views and no plan+ # legitimately returns ("", {...views...}) — and the shot prompt was+ # only rebuilt `if scene_text or floor_plan`. With the screenplay also+ # empty (routine: `_screenplay_text` returns "" whenever fewer than+ # three lines match the form), `locs` had been replaced by the merged+ # list while the brief was still the pre-geography one: no view ids,+ # no laws. The model named no view, `_apply_geography` found views on+ # the location and none on any shot, and stamped views[0] on every+ # shot — the whole film pinned to the establishing angle, which is the+ # behaviour this pass exists to end.+ geo = json.dumps({"views": json.loads(GEO_JSON)["views"]})+ film = self._film(view="reverse")+ spec, stub = self._plan_carwash([film], geography_text=geo,+ screenplay_text="")+ self.assertFalse(P.is_plan_error(spec), spec)+ brief = stub.calls[0]["user"]+ self.assertIn("VIEWS of The car wash", brief)+ self.assertIn("establishing", brief)+ self.assertIn("reverse", brief)+ self.assertIn("THE 180-DEGREE RULE", brief)+ # ...and a model that WAS told keeps the view it named, rather than+ # being coerced onto the establishing angle it never saw.+ self.assertEqual(spec["shots"][0]["view"], "reverse")+ self.assertFalse([w for w in spec["_planner"]["warnings"]+ if "the establishing view" in w],+ spec["_planner"]["warnings"])++ def test_a_film_with_no_views_reads_exactly_as_it_did_before(self):+ _, stub = _plan([self._film()], n_shots=2, locations=[dict(CARWASH)],+ geography=False)+ brief = stub.calls[0]["user"]+ self.assertIn("LOCATIONS", brief)+ self.assertNotIn("VIEWS of", brief)+ self.assertNotIn("THE 180-DEGREE RULE", brief)+ self.assertNotIn("THE FLOOR PLAN", brief)++ def test_chatter_is_discarded_and_the_plan_proceeds(self):+ # The screenplay pass's rule, one pass over: a model that answers a+ # blocking brief with enthusiasm must leave the plan behaving exactly+ # as it did before this pass existed.+ spec, stub = self._plan_carwash(+ geography_text="Sure! Here is a great layout for your scene. Enjoy!")+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertNotIn("views", spec["locations"][0])+ self.assertNotIn("VIEWS of", stub.calls[0]["user"])+ self.assertTrue(any("no usable floor plan" in w+ for w in spec["_planner"]["warnings"]),+ spec["_planner"]["warnings"])++ def test_it_can_be_turned_off(self):+ _, stub = self._plan_carwash(geography=False)+ self.assertEqual(stub.geography_calls, [])++ def test_a_film_with_nowhere_to_be_does_not_pay_for_a_floor_plan(self):+ # There is nowhere to hang a view and no board field to carry it.+ _, stub = _plan([_plan_json(2)], n_shots=2, geography_text=GEO_JSON)+ self.assertEqual(stub.geography_calls, [])++ def test_a_reroll_does_not_reblock_the_scene(self):+ # The other shots are standing on this geography.+ base, _ = self._plan_carwash()+ _, stub = self._plan_carwash([self._film(1)], previous=base,+ feedback={"shot": 1, "note": "again"})+ self.assertEqual(stub.geography_calls, [])++ # ---- what lands on the shots -------------------------------------------+ def test_a_shot_carries_its_view_and_its_eyeline(self):+ spec, _ = self._plan_carwash([self._film(view="reverse", eyeline="frame-left")])+ self.assertEqual(spec["shots"][0]["view"], "reverse")+ self.assertEqual(spec["shots"][0]["eyeline"], "left")+ self.assertEqual(P._load_validator()[0](spec), [])++ def test_a_shot_that_names_no_view_is_put_on_the_establishing_one(self):+ # Unspecified coverage is the master. Leaving it blank composes the+ # location's own neutral sentence — the pre-views behaviour this pass+ # exists to end.+ spec, _ = self._plan_carwash()+ self.assertEqual(spec["shots"][0]["view"], "establishing")+ self.assertTrue(any("no view of The car wash" in w+ for w in spec["_planner"]["warnings"]),+ spec["_planner"]["warnings"])++ def test_a_view_that_is_not_on_the_floor_plan_never_reaches_the_board(self):+ # `unknown_view` is a hard validator error; writing the model's+ # invention onto the shot would fail the plan outright.+ spec, _ = self._plan_carwash([self._film(view="from_the_roof")])+ self.assertEqual(spec["shots"][0]["view"], "establishing")+ self.assertEqual(P._load_validator()[0](spec), [])++ def test_an_eyeline_outside_the_vocabulary_is_dropped_not_written(self):+ spec, _ = self._plan_carwash([self._film(eyeline="over the shoulder")])+ self.assertNotIn("eyeline", spec["shots"][0])+ self.assertEqual(P._load_validator()[0](spec), [])+ self.assertTrue(any("not left, right or lens" in w+ for w in spec["_planner"]["warnings"]))++ def test_every_way_a_model_says_a_side_lands_in_the_vocabulary(self):+ for raw, want in (("frame-right", "right"), ("screen left", "left"),+ ("Camera Right", "right"), ("to camera", "lens"),+ ("LENS", "lens"), ("left.", "left")):+ self.assertEqual(P._eyeline_key(raw), want, raw)+ for junk in ("over the shoulder", "up", "", None, "north"):+ self.assertEqual(P._eyeline_key(junk), "")++ def test_a_film_level_replan_is_shown_the_geography_it_must_keep(self):+ # Without this the re-plan came back with every shot re-coerced onto+ # the establishing view: nothing in the plan the model was shown said+ # which way any of them had been pointing.+ base, _ = self._plan_carwash([self._film(view="reverse", eyeline="right")])+ _, stub = self._plan_carwash([self._film(view="reverse", eyeline="right")],+ previous=base, feedback="make it colder")+ brief = stub.calls[0]["user"]+ self.assertIn('"view": "reverse"', brief)+ self.assertIn('"eyeline": "right"', brief)+ self.assertIn('"location": "carwash"', brief)++ def test_the_plan_carries_the_places_its_shots_name(self):+ # THE REGRESSION: shots have been stamped with `location_id` since+ # locations existed and the spec never carried `locations`, so the+ # validator returned `unknown_location` for EVERY shot — a brief with a+ # location in it spent its one repair round-trip on a fault no model+ # could fix and came back `invalid_plan`.+ spec, _ = _plan([self._film()], n_shots=2, locations=[dict(CARWASH)])+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertEqual([l["id"] for l in spec["locations"]], ["carwash"])+ self.assertEqual(spec["shots"][0]["location_id"], "carwash")+ self.assertEqual(P._load_validator()[0](spec), [])+++class TestGeographyLaws(unittest.TestCase):+ """Warning level, both of them, and neither can fail a plan.++ A film whose eyelines are a little loose is still a film; a film that will+ not render is not.+ """+ LOCS = [dict(CARWASH, views=[+ {"id": "establishing", "name": "Establishing",+ "description": "the soapy blue sedan on the driveway, camera left light"},+ {"id": "reverse", "name": "Reverse",+ "description": "the row of low houses across the street, no car in frame, "+ "camera right light"},+ ])]++ def _spec(self, *shots):+ return {"shots": [dict({"n": i + 1, "location_id": "carwash"}, **s)+ for i, s in enumerate(shots)]}++ # ---- the 180-degree line ------------------------------------------------+ def test_two_people_cannot_both_look_the_same_way(self):+ warn = []+ spec = P._enforce_eyelines(+ self._spec({"character_id": "bizarrotrn", "eyeline": "right"},+ {"character_id": "ariatrn", "eyeline": "right"}), warn)+ self.assertEqual(spec["shots"][1]["eyeline"], "left")+ self.assertIn("180-degree line", warn[0])++ def test_a_complementary_pair_is_left_alone(self):+ warn = []+ spec = P._enforce_eyelines(+ self._spec({"character_id": "bizarrotrn", "eyeline": "right"},+ {"character_id": "ariatrn", "eyeline": "left"}), warn)+ self.assertEqual([s["eyeline"] for s in spec["shots"]], ["right", "left"])+ self.assertEqual(warn, [])++ def test_the_same_person_twice_is_not_a_reverse(self):+ # Two shots of one man looking the same way is continuity, not a break.+ warn = []+ P._enforce_eyelines(+ self._spec({"character_id": "bizarrotrn", "eyeline": "right"},+ {"character_id": "bizarrotrn", "eyeline": "right"}), warn)+ self.assertEqual(warn, [])++ def test_a_cut_to_another_place_does_not_cross_the_line(self):+ warn = []+ spec = self._spec({"character_id": "bizarrotrn", "eyeline": "right"},+ {"character_id": "ariatrn", "eyeline": "right"})+ spec["shots"][1]["location_id"] = "kitchen"+ P._enforce_eyelines(spec, warn)+ self.assertEqual(spec["shots"][1]["eyeline"], "right")+ self.assertEqual(warn, [])++ def test_the_lens_and_the_unstated_are_never_flipped(self):+ # "lens" is a claim; nothing is not. Neither is a side of the line.+ warn = []+ spec = P._enforce_eyelines(+ self._spec({"character_id": "a", "eyeline": "lens"},+ {"character_id": "b", "eyeline": "lens"},+ {"character_id": "a"}, {"character_id": "b"}), warn)+ self.assertEqual([s.get("eyeline") for s in spec["shots"]],+ ["lens", "lens", None, None])+ self.assertEqual(warn, [])++ # ---- what the reverse angle exists to keep out --------------------------+ def test_the_car_is_not_allowed_back_into_the_reverse(self):+ warn = []+ spec = self._spec({"view": "reverse",+ "description": "He turns from the car and grins at her."})+ P._enforce_geography(spec, self.LOCS, warn)+ self.assertEqual(len(warn), 1, warn)+ self.assertIn("shot 1", warn[0])+ self.assertIn("'reverse'", warn[0])+ self.assertIn("car", warn[0])++ def test_the_same_object_on_the_view_that_holds_it_is_fine(self):+ warn = []+ P._enforce_geography(+ self._spec({"view": "establishing",+ "description": "He turns from the car and grins at her."}),+ self.LOCS, warn)+ self.assertEqual(warn, [])++ def test_the_other_person_in_a_reverse_is_never_a_violation(self):+ # An earlier draft inferred absence by diffing the content words of the+ # other views, and flagged exactly the thing a reverse angle is FOR:+ # her, her sponge, her wheel, all legitimately in frame.+ warn = []+ P._enforce_geography(+ self._spec({"view": "reverse",+ "description": "The woman looks up from the front wheel, sponge "+ "in hand, and answers him."}),+ self.LOCS, warn)+ self.assertEqual(warn, [])++ # ---- the wiring ---------------------------------------------------------+ def test_both_laws_run_inside_plan_film(self):+ # A law that is only unit-tested is a law that can be left unwired.+ cast = [{"id": "bizarrotrn", "trigger": "bizarrotrn", "name": "Bizarro"},+ {"id": "ariatrn", "trigger": "ariatrn", "name": "Aria"}]+ rows = [+ {"n": 1, "title": "A", "character_id": "bizarrotrn", "duration_s": 5,+ "camera": "static", "description": "bizarrotrn throws both arms wide and grins.",+ "settle": "he is still", "soundscape": "Hose water, no voices.",+ "music": "N/A", "location": "The car wash", "view": "establishing",+ "eyeline": "right"},+ {"n": 2, "title": "B", "character_id": "ariatrn", "duration_s": 5,+ "camera": "static",+ "description": "ariatrn lifts the sponge from the car and shrugs.",+ "settle": "she is still", "soundscape": "Hose water, no voices.",+ "music": "N/A", "location": "The car wash", "view": "reverse",+ "eyeline": "right"},+ ]+ spec, _ = _plan([json.dumps({"title": "The Car Wash", "shots": rows})],+ n_shots=2, characters=cast, engine="ltx",+ locations=[dict(CARWASH)], geography_text=GEO_JSON)+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertEqual([s["eyeline"] for s in spec["shots"]], ["right", "left"])+ self.assertEqual(P._load_validator()[0](+ spec, known_character_ids=["bizarrotrn", "ariatrn"]), [])+ warns = spec["_planner"]["warnings"]+ self.assertTrue(any("180-degree line" in w for w in warns), warns)+ self.assertTrue(any("puts the car back in frame" in w for w in warns), warns)+ # WARNING level: a loose eyeline is not a reason to call a film broken.+ self.assertTrue(spec["_planner"]["ok"])+ self.assertFalse(spec["_planner"]["degraded"])++ def test_absence_is_read_from_the_views_own_words(self):+ self.assertEqual(P._absent_terms("houses across the street, no car in frame"),+ ["car"])+ self.assertEqual(P._absent_terms("the verge, without the hand-painted sign"),+ ["hand-painted", "sign"])+ # A view that negates nothing constrains nothing.+ self.assertEqual(P._absent_terms("the row of low houses across the street"), [])+ self.assertEqual(P._absent_terms("the sign is not visible from here"), [])+++class TestGeographyParser(unittest.TestCase):+ """`_geography_plan`: everything between the model's JSON and the board."""++ def _plan_from(self, obj, locs=(CARWASH,)):+ return P._geography_plan({"text": json.dumps(obj)}, [dict(l) for l in locs])++ def test_the_carwash_reply_parses_into_two_views(self):+ floor, views = P._geography_plan({"text": GEO_JSON}, [dict(CARWASH)])+ self.assertIn("garage door", floor)+ self.assertEqual([v["id"] for v in views["carwash"]],+ ["establishing", "reverse"])++ def test_the_light_side_is_folded_into_the_sentence_that_renders(self):+ # The side is the most load-bearing word in a reverse angle, and the+ # model likes to answer it in `light` and forget it in the prose.+ _, views = self._plan_from({"floor_plan": "x", "views": [+ {"location": "The car wash", "id": "reverse",+ "light": "camera right",+ "description": "the row of low houses across the street"}]})+ self.assertIn("the light rakes in from camera right",+ views["carwash"][0]["description"])++ def test_a_sentence_that_already_names_a_side_is_left_alone(self):+ _, views = self._plan_from({"floor_plan": "x", "views": [+ {"location": "The car wash", "id": "reverse", "light": "camera right",+ "description": "the houses, the sun raking in from camera right"}]})+ self.assertEqual(views["carwash"][0]["description"].count("camera right"), 1)++ def test_ids_are_slugged_deduped_and_capped(self):+ _, views = self._plan_from({"floor_plan": "x", "views": [+ {"location": "The car wash", "name": "Establishing — facing the drive",+ "description": "the soapy sedan on the driveway, camera left"},+ {"location": "The car wash", "id": "Reverse Angle!",+ "description": "the houses across the street, no car, camera right"},+ {"location": "The car wash", "id": "reverse_angle",+ "description": "the houses again, a second time, camera right"},+ {"location": "The car wash", "id": "d",+ "description": "over her shoulder at the garage door, camera left"},+ {"location": "The car wash", "id": "e",+ "description": "the fifth angle nobody asked for, camera left"},+ ]})+ ids = [v["id"] for v in views["carwash"]]+ self.assertEqual(len(ids), P.MAX_VIEWS_PER_LOCATION)+ self.assertEqual(len(set(ids)), len(ids))+ self.assertTrue(all(P._VIEW_ID_RE.match(i) for i in ids), ids)+ self.assertEqual(ids[0], "establishing_facing_the_drive")++ def test_a_view_with_no_description_is_not_a_view(self):+ # An id with nothing under it composes the location's own text and+ # pretends coverage exists.+ floor, views = self._plan_from({"floor_plan": "x", "views": [+ {"location": "The car wash", "id": "reverse", "description": "too short"}]})+ self.assertEqual((floor, views), ("", {}))++ def test_a_single_location_takes_the_views_that_name_nothing(self):+ _, views = self._plan_from({"floor_plan": "x", "views": [+ {"id": "reverse", "description": "the houses across the street, camera right"}]})+ self.assertEqual(list(views), ["carwash"])++ def test_a_view_for_a_place_that_is_not_in_the_film_is_dropped(self):+ floor, views = self._plan_from(+ {"floor_plan": "x", "views": [+ {"location": "The bar", "id": "wide",+ "description": "the bar shelves behind him, camera left"}]},+ locs=(CARWASH, {"id": "kitchen", "name": "The kitchen",+ "description": "a kitchen"}))+ self.assertEqual((floor, views), ("", {}))++ def test_chatter_and_broken_json_yield_nothing(self):+ for text in ("Sure! Here is the layout.", "", "{not json",+ json.dumps({"floor_plan": "x"}),+ json.dumps({"floor_plan": "x", "views": "wide"})):+ self.assertEqual(P._geography_plan({"text": text}, [dict(CARWASH)]),+ ("", {}), text)++ def test_the_users_own_locations_are_never_rewritten_in_place(self):+ # On the panel `locations` IS the user's Locations box, parsed.+ mine = [dict(CARWASH)]+ merged = P._merge_views(mine, {"carwash": [{"id": "a", "name": "A",+ "description": "d"}]})+ self.assertNotIn("views", mine[0])+ self.assertIn("views", merged[0])++if __name__ == "__main__":unittest.main(verbosity=2)