diff --git a/calliope-backend/src/calliope/__init__.py b/calliope-backend/src/calliope/__init__.py index 59390330..225a76c0 100644 --- a/calliope-backend/src/calliope/__init__.py +++ b/calliope-backend/src/calliope/__init__.py @@ -4,4 +4,4 @@ # reads this; pyproject.toml is kept in sync for the build (hatchling dynamic # version reads this file). PR #47: hard-coded literals drifted twice # (1.3.2 shipped reporting 1.2.1; 1.4.1's /api/health still said 1.4.0). -__version__ = "1.5.6" +__version__ = "1.5.7" diff --git a/calliope-backend/src/calliope/agent/harness/plugins/render.py b/calliope-backend/src/calliope/agent/harness/plugins/render.py index c92a5c33..7619682a 100644 --- a/calliope-backend/src/calliope/agent/harness/plugins/render.py +++ b/calliope-backend/src/calliope/agent/harness/plugins/render.py @@ -817,6 +817,34 @@ async def t_run_workflow(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An extra = {str(k): v for k, v in iv.items()} inputs = parse_dynamic_inputs(wf_json) if wf_json else [] + # Issue #67: reject directory / missing-file paths the model hand-writes + # into media-role inputs (e.g. ComfyUI's .../input dir) at CALL time, not + # as a failed job later. Bare/relative names may resolve on the Comfy side + # and pass; only local-looking absolute/qualified paths are checked. + media_node_ids = { + str(inp["nodeId"]) + for inp in inputs + if inp.get("kind") in ("image", "image_url", "audio", "video") + } + for nid in media_node_ids: + v = extra.get(nid) + if not isinstance(v, str) or v.startswith(("http://", "https://")): + continue + p = Path(v) + if p.is_absolute() or "/" in v or "\\" in v: + if p.is_dir(): + return { + "ok": False, + "error": f"input_values[{nid}] '{v}' is a directory — pass a media FILE path.", + } + if not p.exists(): + return { + "ok": False, + "error": ( + f"input_values[{nid}] file not found locally: '{v}'. Reference a " + "project asset path or attach the file in chat instead." + ), + } if args.get("width") is not None: for inp in inputs: if input_has_role(inp, "width"): diff --git a/calliope-backend/src/calliope/agent/prompts.py b/calliope-backend/src/calliope/agent/prompts.py index 86ee5b5c..c120bf78 100644 --- a/calliope-backend/src/calliope/agent/prompts.py +++ b/calliope-backend/src/calliope/agent/prompts.py @@ -16,9 +16,10 @@ SCRIPT_GENERATION_SYSTEM = ( "You are a screenwriter for AI video production. " "Write a scene-by-scene script that uses the provided characters and locations. " "A scene is a SCREENPLAY unit — a heading, full action prose, and all dialogue that plays " - "in it — exactly like a produced script. Scenes may be long; a later 'break into shots' " - "pass splits each scene into short renderable clips, so never compress the content to fit " - "a single video generation. " + "in it — exactly like a produced script. A later 'break into shots' pass splits each scene " + "into short renderable clips, so never compress what a scene needs to say — but scale the " + "TOTAL material to the runtime budget given in the user message: a 30-second film needs " + "30 seconds of action and dialogue, not two minutes. " "Always respond with a single valid JSON object. " "HARD RULE: the scenes array length must equal required_scene_count from the user message. " "Returning fewer scenes is a failure. Respect the user's chosen scene count." @@ -313,6 +314,9 @@ def build_script_messages( scene_n = max(recommended, int(scene_count)) if scene_count and scene_count > 0 else recommended # Stretch runtime floor when the user asked for more clips than duration alone implies secs = max(secs, scene_n * 6) + # Issue #64: the target is a budget, not a floor — give the model a concrete + # per-scene scale to write to so content volume matches the runtime. + per_scene_secs = max(3, round(secs / scene_n)) char_lines = "\n".join( f"- id={c['id']} {c['name']} ({c.get('role') or ''}): {c.get('appearance') or ''}" for c in characters @@ -328,8 +332,10 @@ def build_script_messages( Title: {title} Idea: {idea or ''} Target duration: {target_duration or 'short (~30-60 seconds)'} -Estimated runtime: ~{secs} seconds +Estimated runtime: ~{secs} seconds TOTAL — the finished film must play in about {secs}s required_scene_count: {scene_n} +Per-scene budget: ~{per_scene_secs} seconds each (sum across scenes ≈ {secs}s) — write +action length and dialogue VOLUME to this scale. Story beats: {beat_lines or '(none)'} @@ -344,9 +350,10 @@ Locations: 1. The JSON field "scenes" MUST contain EXACTLY {scene_n} objects. 2. order_index must run 1, 2, 3, ... {scene_n} with no gaps. 3. Do NOT collapse back to fewer scenes. The user expanded the script to {scene_n} scenes — fill all of them. -4. Spread the full story across all {scene_n} scenes. A scene is a SCREENPLAY unit — it may - run 30–120 seconds when the material needs it (a later pass breaks long scenes into - short renderable clips). NEVER compress or summarize action to make a scene shorter. +4. Spread the full story across all {scene_n} scenes. A scene is a SCREENPLAY unit — long scenes + are fine ONLY when the {secs}s total allows (≈{per_scene_secs}s each). Scale action detail + and the NUMBER of dialogue lines to that per-scene budget; do not write 2 minutes of + material into a {secs}s film. Never drop lines the story needs — write fewer instead. 5. Pace the total toward ~{secs} seconds overall — scenes with lots of dialogue run longer. === ACTION (full visible action prose — the fidelity contract) === @@ -421,6 +428,8 @@ def build_script_chunk_messages( continuity — heading style, location, who's on screen — without resending the whole script.""" secs = estimate_target_seconds(target_duration) + # Issue #64: per-scene budget so chunk content volume matches the runtime. + per_scene_secs = max(3, round(secs / scene_count)) char_lines = "\n".join( f"- id={c['id']} {c['name']} ({c.get('role') or ''}): {c.get('appearance') or ''}" for c in characters @@ -448,7 +457,10 @@ def build_script_chunk_messages( Title: {title} Idea: {idea or ''} Target duration: {target_duration or 'short (~30-60 seconds)'} +Estimated runtime: ~{secs} seconds TOTAL — the finished film must play in about {secs}s required_scene_count: {scene_count} +Per-scene budget: ~{per_scene_secs} seconds each (sum across the whole script ≈ {secs}s) — +write action length and dialogue VOLUME to this scale. THIS CHUNK: exactly {chunk_scenes} scenes, order_index {chunk_start} through {last}. Full script is {scene_count} scenes; other chunks are written separately — do NOT write scenes outside {chunk_start}..{last}. @@ -465,9 +477,11 @@ Locations: === HARD CONSTRAINTS (non-negotiable) === 1. The JSON field "scenes" MUST contain EXACTLY {chunk_scenes} objects. 2. order_index must run {chunk_start}, {chunk_start + 1}, ... {last} with no gaps. -3. A scene is a SCREENPLAY unit — it may run 30–120 seconds when the material needs it - (a later pass breaks long scenes into short renderable clips). NEVER compress or - summarize action to make a scene shorter. +3. A scene is a SCREENPLAY unit — long scenes are fine ONLY when the {secs}s total allows + (≈{per_scene_secs}s each). Scale action detail and the NUMBER of dialogue lines to that + per-scene budget; do not write 2 minutes of material into a {secs}s film. Never drop + lines the story needs — write fewer instead. A later pass breaks scenes into renderable + clips, so never compress what a scene needs to SAY. 4. Advance the beat arc across the whole {scene_count}-scene story; this chunk covers the part that falls at scenes {chunk_start}–{last}. 5. If earlier scenes are listed above, continue them naturally — same characters, diff --git a/calliope-backend/src/calliope/agent/script_agent.py b/calliope-backend/src/calliope/agent/script_agent.py index 6b387694..505b7531 100644 --- a/calliope-backend/src/calliope/agent/script_agent.py +++ b/calliope-backend/src/calliope/agent/script_agent.py @@ -296,6 +296,11 @@ async def generate_script( # guess — and the user's target runtime is the total they sum to. Runs # AFTER all chunks are committed, as a bulk UPDATE over the durable # board (the rescale is global; the rows were persisted per chunk). + # Issue #64: the scale may go BELOW 1.0 (floor 0.5) so an over-written + # script's scene budgets shrink toward the target too — the old + # max(..., 1.0) treated the target as a floor, and a 30s ask produced a + # 1:51 script. The floor keeps a wildly over-written board from being + # mislabeled more than 2x; content itself is not edited. if target_seconds: all_rows = conn.execute( "SELECT id, action, dialog FROM scenes WHERE project_id = ? ORDER BY order_index", @@ -307,7 +312,7 @@ async def generate_script( ] total_est = sum(estimates) if total_est > 0: - scale = max(target_seconds / total_est, 1.0) + scale = max(target_seconds / total_est, 0.5) for row, est in zip(all_rows, estimates): conn.execute( "UPDATE scenes SET duration_sec = ? WHERE id = ?", diff --git a/calliope-backend/src/calliope/comfyui/client.py b/calliope-backend/src/calliope/comfyui/client.py index 0a724e6a..72c5398a 100644 --- a/calliope-backend/src/calliope/comfyui/client.py +++ b/calliope-backend/src/calliope/comfyui/client.py @@ -113,9 +113,31 @@ class ComfyUIClient: sub = result.get("subfolder") or subfolder return f"{sub}/{name}" if sub else name + @staticmethod + def _reject_bad_media_path(value: str, node_id: str, class_type: str, field: str) -> None: + """Fail a job BEFORE queueing when a media input value is unusable. + + Issue #67: a directory (e.g. ComfyUI's `.../input`) or a nonexistent + local path previously passed through verbatim and died inside ComfyUI + with an opaque `ValueError: [Errno 21] Is a directory`. Bare/relative + names are legitimate Comfy-side references and are left alone. + """ + path = Path(value) + if path.is_dir(): + raise RuntimeError( + f"node {node_id} ({class_type}): {field} value '{value}' is a " + "directory — expected a media FILE path." + ) + if not path.exists(): + raise RuntimeError( + f"node {node_id} ({class_type}): {field} file not found locally: " + f"'{value}'. Upload the file through the Video stage's reference " + "picker or attach it in chat, then retry." + ) + async def prepare_media_inputs(self, workflow: dict[str, Any]) -> dict[str, Any]: """Upload local file paths referenced in LoadImage / LoadAudio / LoadVideo nodes.""" - for _node_id, node in workflow.items(): + for node_id, node in workflow.items(): if not isinstance(node, dict): continue class_type = node.get("class_type", "") @@ -125,8 +147,12 @@ class ComfyUIClient: if isinstance(image, str) and self._looks_like_local_path(image): path = Path(image) if path.exists(): + if path.is_dir(): + self._reject_bad_media_path(image, str(node_id), class_type, "image") inputs["image"] = await self.upload_image(path) node["inputs"] = inputs + else: + self._reject_bad_media_path(image, str(node_id), class_type, "image") elif class_type in AUDIO_CLASSES: # VHS_LoadAudio names its widget "audio:" (with colon); stock # LoadAudio uses "audio". Probe both so the file is uploaded @@ -140,16 +166,28 @@ class ComfyUIClient: if isinstance(audio, str) and self._looks_like_local_path(audio): path = Path(audio) if path.exists(): + if path.is_dir(): + self._reject_bad_media_path( + audio, str(node_id), class_type, audio_key + ) inputs[audio_key] = await self.upload_audio(path) node["inputs"] = inputs + else: + self._reject_bad_media_path( + audio, str(node_id), class_type, audio_key + ) elif class_type in VIDEO_CLASSES: field = "file" if class_type in VIDEO_FILE_CLASSES else "video" media = inputs.get(field) if isinstance(media, str) and self._looks_like_local_path(media): path = Path(media) if path.exists(): + if path.is_dir(): + self._reject_bad_media_path(media, str(node_id), class_type, field) inputs[field] = await self.upload_video(path) node["inputs"] = inputs + else: + self._reject_bad_media_path(media, str(node_id), class_type, field) return workflow @staticmethod diff --git a/calliope-backend/tests/test_script_chunking.py b/calliope-backend/tests/test_script_chunking.py index cf24cf66..c6475fa6 100644 --- a/calliope-backend/tests/test_script_chunking.py +++ b/calliope-backend/tests/test_script_chunking.py @@ -4,11 +4,34 @@ renumbering.""" from __future__ import annotations import asyncio +import tempfile +from pathlib import Path import pytest import calliope.agent.script_agent as sa -from calliope.agent.script_agent import _generate_scenes_chunked +from calliope.agent.script_agent import _generate_scenes_chunked, generate_script + + +@pytest.fixture(autouse=True, scope="module") +def _never_touch_real_db(): + """Redirect data_dir before ANY write in this module (repo test rule).""" + import calliope.config as config_module + from calliope.db import migrate_db + + prev = { + "data_dir": config_module.settings.data_dir, + "assets_dir": config_module.settings.assets_dir, + "dry_run": config_module.settings.dry_run, + } + with tempfile.TemporaryDirectory() as tmp: + config_module.settings.data_dir = Path(tmp) + config_module.settings.assets_dir = Path(tmp) / "assets" + config_module.settings.dry_run = True + asyncio.run(migrate_db(config_module.settings.db_path)) + yield + for k, v in prev.items(): + setattr(config_module.settings, k, v) def _scenes(n: int, start: int = 1): @@ -166,3 +189,114 @@ def test_continuity_tail_is_passed_to_next_chunk(monkeypatch): ) # First chunk has no tail; the second continues from the first's scenes. assert seen_tails == [False, True] + + +# ───────────────────────────────────────────────────────────────────────── +# Issue #64 — target runtime is a budget, not a floor +# ───────────────────────────────────────────────────────────────────────── + + +def test_chunk_prompt_carries_per_scene_budget(): + from calliope.agent.prompts import build_script_chunk_messages + + messages = build_script_chunk_messages( + title="T", + idea="i", + beats=[], + characters=[], + locations=[], + target_duration="30 seconds", + scene_count=5, + chunk_start=1, + chunk_scenes=5, + ) + user = messages[1]["content"] + # 30s / 5 scenes = 6s per scene; both the total and the per-scene scale + # must be stated so the model writes content volume to the runtime. + assert "Per-scene budget: ~6 seconds" in user + assert "must play in about 30s" in user + + +def test_script_prompt_carries_per_scene_budget(): + from calliope.agent.prompts import build_script_messages + + messages = build_script_messages( + title="T", + idea="i", + beats=[], + characters=[], + locations=[], + target_duration="30 seconds", + scene_count=5, + ) + user = messages[1]["content"] + assert "Per-scene budget: ~6 seconds" in user + assert "must play in about 30s" in user + + +def _mk_project() -> int: + from calliope.db import get_db + from calliope.config import settings + + conn = get_db(settings.db_path) + try: + cur = conn.execute( + "INSERT INTO projects (title, idea, target_duration) VALUES ('Budget', 'i', '30 seconds')" + ) + conn.commit() + return int(cur.lastrowid) + finally: + conn.close() + + +def _oversized_scenes(n: int) -> dict: + """Scenes whose content genuinely runs ~110s total (issue #64 numbers).""" + long_dialog = "\n".join(f"SPEAKER: {'word ' * 40}" for _ in range(4)) # 160w ≈ 64s + long_action = " ".join(["moves carefully forward"] * 40) # 160w ≈ 19s + return { + "scenes": [ + { + "order_index": i + 1, + "heading": f"SCENE {i + 1}", + "action": long_action, + "dialog": long_dialog, + "duration_sec": 8, + "character_ids": [], + "location_id": None, + } + for i in range(n) + ] + } + + +def test_oversized_script_durations_shrink_to_target(monkeypatch): + """Issue #64 regression: a 30s target with ~110s of written content must + rescale scene durations DOWN toward the target (old max(...,1.0) treated + the target as a floor and left the overrun untouched — 1:51 vs 0:30).""" + from calliope.config import settings + from calliope.db import get_db + + async def fake_structured(messages, temperature=0.7): + n = 0 + for line in messages[1]["content"].splitlines(): + if line.startswith("THIS CHUNK:"): + n = int(line.split("exactly", 1)[1].split("scenes")[0].strip()) + return _oversized_scenes(n) + + monkeypatch.setattr(sa, "generate_structured", fake_structured) + pid = _mk_project() + asyncio.run(generate_script(pid, with_clips=False)) + + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT duration_sec FROM scenes WHERE project_id = ? ORDER BY order_index", + (pid,), + ).fetchall() + finally: + conn.close() + total = sum(r["duration_sec"] for r in rows) + # 5 scenes × ~83s estimated ≈ 415s → floor 0.5 caps the shrink at ~207s. + # The old code left 415s; the fix must pull meaningfully below it. + assert total <= 220, f"scene durations did not shrink toward the 30s target: {total}s" + assert all(r["duration_sec"] >= 3 for r in rows) diff --git a/calliope-backend/tests/test_video_continue.py b/calliope-backend/tests/test_video_continue.py index b95890cc..6784de4c 100644 --- a/calliope-backend/tests/test_video_continue.py +++ b/calliope-backend/tests/test_video_continue.py @@ -420,3 +420,95 @@ def test_worker_passes_plain_job_unchanged(client, monkeypatch): assert captured["20"]["inputs"]["file"] == "" assert captured["10"]["inputs"]["text"] # scene prompt was filled assert job["workflow_id"] == wid + + +# ───────────────────────────────────────────────────────────────────────── +# Issue #67 — media inputs that are directories / missing local files must +# fail BEFORE queuing with a node-naming error, not as ComfyUI Errno 21. +# ───────────────────────────────────────────────────────────────────────── + + +def test_prepare_media_inputs_rejects_directory_value(client, tmp_path): + """The exact #67 failure shape: a LoadVideo fed ComfyUI's input DIR.""" + c = ComfyUIClient("http://127.0.0.1:8188") + wf = { + "20": { + "class_type": "VHS_LoadVideo", + "inputs": {"video": str(tmp_path)}, # a directory + "_meta": {"title": "Previous Clip (Input:video)"}, + }, + } + with pytest.raises(RuntimeError) as excinfo: + asyncio.run(c.prepare_media_inputs(wf)) + msg = str(excinfo.value) + assert "node 20" in msg + assert "is a directory" in msg + + +def test_prepare_media_inputs_rejects_missing_absolute_file(client, tmp_path): + c = ComfyUIClient("http://127.0.0.1:8188") + missing = tmp_path / "never_rendered.mp4" + wf = { + "20": { + "class_type": "LoadVideo", + "inputs": {"file": str(missing)}, + "_meta": {"title": "Previous Clip (Input:video)"}, + }, + } + with pytest.raises(RuntimeError) as excinfo: + asyncio.run(c.prepare_media_inputs(wf)) + msg = str(excinfo.value) + assert "node 20" in msg + assert "not found locally" in msg + + +def test_prepare_media_inputs_leaves_bare_comfy_names_alone(client): + """Bare names (no path separators) are legit Comfy-side references — no + guard fires and no upload is attempted.""" + c = ComfyUIClient("http://127.0.0.1:8188") + wf = { + "20": { + "class_type": "VHS_LoadVideo", + "inputs": {"video": "clip_3.mp4"}, + "_meta": {"title": "Previous Clip (Input:video)"}, + }, + "30": { + "class_type": "LoadImage", + "inputs": {"image": "example_image.png"}, + "_meta": {"title": "Ref (Input:image)"}, + }, + } + out = asyncio.run(c.prepare_media_inputs(wf)) + assert out["20"]["inputs"]["video"] == "clip_3.mp4" + assert out["30"]["inputs"]["image"] == "example_image.png" + + +def test_prepare_media_inputs_uploads_existing_video(client, tmp_path): + """A real local file still uploads normally (guard must not over-fire).""" + c = ComfyUIClient("http://127.0.0.1:8188") + clip = tmp_path / "prev.mp4" + clip.write_bytes(b"00") + + uploaded: list[str] = [] + + async def fake_upload(self, path, subfolder="calliope"): + uploaded.append(str(path)) + return f"{subfolder}/{Path(path).name}" + + import calliope.comfyui.client as client_mod + + orig = client_mod.ComfyUIClient.upload_video + client_mod.ComfyUIClient.upload_video = fake_upload + try: + wf = { + "20": { + "class_type": "VHS_LoadVideo", + "inputs": {"video": str(clip)}, + "_meta": {"title": "Previous Clip (Input:video)"}, + }, + } + out = asyncio.run(c.prepare_media_inputs(wf)) + finally: + client_mod.ComfyUIClient.upload_video = orig + assert uploaded == [str(clip)] + assert out["20"]["inputs"]["video"].endswith("prev.mp4") diff --git a/calliope-web/package-lock.json b/calliope-web/package-lock.json index 07fbbd7a..bdefcf81 100644 --- a/calliope-web/package-lock.json +++ b/calliope-web/package-lock.json @@ -1,12 +1,12 @@ { "name": "calliope-web", - "version": "1.5.6", + "version": "1.5.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "calliope-web", - "version": "1.5.6", + "version": "1.5.7", "dependencies": { "@tanstack/svelte-query": "^5.66.0", "@types/three": "0.185.0", diff --git a/calliope-web/package.json b/calliope-web/package.json index 0cd6d584..e9a2b263 100644 --- a/calliope-web/package.json +++ b/calliope-web/package.json @@ -1,6 +1,6 @@ { "name": "calliope-web", - "version": "1.5.6", + "version": "1.5.7", "private": true, "scripts": { "dev": "vite dev", diff --git a/calliope-web/src/lib/components/QueueStage.svelte b/calliope-web/src/lib/components/QueueStage.svelte index 76cc4cf7..d18ad60d 100644 --- a/calliope-web/src/lib/components/QueueStage.svelte +++ b/calliope-web/src/lib/components/QueueStage.svelte @@ -42,6 +42,9 @@ /** Selected render unit = a clip id (flattened playback order). */ let selectedClipId = $state(null); let formValues = $state>({}); + // Workflow choice is per CLIP (issue #66): two clips of one scene may use + // different workflows (e.g. image→video then video→video extend). Keys are + // clip ids; hydrated from clip.workflow_id / saved video_settings. let selectedWorkflow = $state>({}); let lastFormScene = $state(null); // Clip source for continue scenes, keyed per scene: 'auto' | 'upload' | scene id. @@ -54,8 +57,10 @@ const el = e.currentTarget as HTMLInputElement; const file = el.files?.[0]; el.value = ''; - const node = videoInputNodeFor(selected ? workflowFor(selected) : undefined); - if (!file || !selected || !node) return; + const node = videoInputNodeFor( + selectedEntry ? workflowForClip(selectedEntry.clip, selectedEntry.scene) : undefined, + ); + if (!file || !selectedEntry || !node) return; const path = await videoUploadMgr.uploadSafe(node.nodeId, file); if (path) { formValues = { ...formValues, [node.nodeId]: path }; @@ -228,6 +233,17 @@ if (id != null) { const entry = filmClips.find((c) => c.clip.id === id); if (!entry) return; + // Hydrate the per-clip workflow choice (issue #66) on first open — + // persisted clip row wins, else the saved form choice, else scene. + if (selectedWorkflow[id] == null) { + const wfId = + entry.clip.workflow_id ?? + entry.clip.video_settings?.form_workflow_id ?? + entry.scene.workflow_id; + if (wfId != null) { + selectedWorkflow = { ...selectedWorkflow, [id]: Number(wfId) }; + } + } const stored = formCache.get(id); if (stored) { formValues = { ...stored }; @@ -263,7 +279,9 @@ const out: Record = { input_values: compactInputValues(formValues), }; - const wfId = selectedWorkflow[selectedEntry.scene.id]; + // Per-clip workflow choice (issue #66) — saved inside video_settings for + // display hydration; the clips.workflow_id column is written alongside. + const wfId = selectedWorkflow[selectedEntry.clip.id]; if (wfId) out.form_workflow_id = wfId; const src = clipSource[selectedEntry.scene.id]; if (src) out.clip_source = src; @@ -292,8 +310,15 @@ const hash = settingsHash(next); if (hash === lastSavedHash) return; lastSavedHash = hash; + const wfId = selectedWorkflow[selectedEntry.clip.id]; projects - .updateClip(projectId, selectedEntry.clip.id, { video_settings: next }) + .updateClip(projectId, selectedEntry.clip.id, { + video_settings: next, + // Persist the per-clip workflow onto the column the enqueue + // path prefers (wf_id = workflow_id or clip.workflow_id) so + // Generate All renders each clip with its own workflow. + workflow_id: wfId, + }) .catch(() => { /* transient — next change retries */ }); @@ -312,7 +337,7 @@ function seedClipDefaults(entry: { clip: Clip; scene: Scene }): Record { const seed: Record = {}; if (!entry) return seed; - const wf = workflowFor(entry.scene); + const wf = workflowForClip(entry.clip, entry.scene); const secs = entry.clip.duration_sec ?? entry.scene.duration_sec; for (const inp of wf?.input_schema ?? []) { if (normalizeInputRole(inp.role ?? null) === 'duration' && secs != null) { @@ -356,17 +381,18 @@ } const generateOne = createMutation({ - mutationFn: (vars: { clipId: number; sceneId: number; prompt?: string }) => { - const { clipId, sceneId, prompt } = vars; - const scene = scenes.find((s) => s.id === sceneId); - const wf = scene ? workflowFor(scene) : undefined; - return jobsApi.generateVideos(projectId, { - clip_ids: [clipId], - workflow_id: selectedWorkflow[sceneId] ?? wf?.id, - input_values: compactInputValues(formValues), - prompts: prompt ? { [String(clipId)]: prompt } : undefined, - }); - }, + mutationFn: (vars: { clipId: number; sceneId: number; prompt?: string }) => { + const { clipId, sceneId, prompt } = vars; + const scene = scenes.find((s) => s.id === sceneId); + const clip = scene?.clips?.find((c) => c.id === clipId); + const wf = clip && scene ? workflowForClip(clip, scene) : undefined; + return jobsApi.generateVideos(projectId, { + clip_ids: [clipId], + workflow_id: selectedWorkflow[clipId] ?? clip?.workflow_id ?? wf?.id, + input_values: compactInputValues(formValues), + prompts: prompt ? { [String(clipId)]: prompt } : undefined, + }); + }, onSuccess: async () => { await client.invalidateQueries({ queryKey: ['jobs'] }); await client.invalidateQueries({ queryKey: ['scenes'] }); @@ -464,9 +490,10 @@ const generateOne = createMutation({ done++; batchNote = t('queue.queueingProgress', { n: done, total: totalClips }); try { - // Resolve like the per-clip button does: session pick → scene's stored - // workflow → first enabled video workflow. A scene whose stored workflow - // was deleted would otherwise enqueue a job doomed to "No workflow found". + // Resolve like the per-clip button does: session pick → clip's stored + // workflow → scene default → first enabled video workflow. Per CLIP + // (issue #66): a scene may mix image→video and video→video extend + // workflows across its clips, so each target resolves its own. // Fresh per-clip drafts ride along; stale/absent drafts get the backend's // auto-rewrite (deterministic template on LLM failure). const clip = clips.length > 0 ? clips.find((c) => c.id === target.id) : null; @@ -475,10 +502,11 @@ const generateOne = createMutation({ draft && clip?.video_settings?.prompt_draft_meta?.based_on ? clip.video_settings.prompt_draft_meta.based_on : null; + const wf = clip ? workflowForClip(clip, scene) : undefined; await jobsApi.generateVideos(projectId, { clip_ids: clip ? [target.id] : undefined, scene_ids: clip ? undefined : [target.id], - workflow_id: workflowFor(scene)?.id, + workflow_id: clip ? (selectedWorkflow[clip.id] ?? clip.workflow_id ?? wf?.id) : wf?.id, prompts: draft ? { [target.key]: draft } : undefined, }); queued++; @@ -505,8 +533,15 @@ const generateOne = createMutation({ await client.invalidateQueries({ queryKey: ['scenes'] }); } - function workflowFor(scene: Scene): Workflow | undefined { - const id = selectedWorkflow[scene.id] ?? scene.workflow_id ?? undefined; + /** Resolve the workflow for a CLIP (issue #66): explicit in-session pick → + * clip row's workflow_id → saved form choice → scene default → first enabled. */ + function workflowForClip(clip: Clip, scene: Scene | null | undefined): Workflow | undefined { + const id = + selectedWorkflow[clip.id] ?? + clip.workflow_id ?? + clip.video_settings?.form_workflow_id ?? + scene?.workflow_id ?? + undefined; return enabledWorkflows.find((w) => w.id === id) ?? enabledWorkflows[0] ?? undefined; } @@ -848,7 +883,7 @@ const generateOne = createMutation({

{t('queue.noTimelineBody')}

{:else if selected} - {@const selWf = workflowFor(selected)} + {@const selWf = selClip ? workflowForClip(selClip, selected) : undefined} {@const selStatus = selClip ? statusOfClip(selClip.id) : sceneStatus(selected)} {@const selPreview = selClip ? previewPathForClip(selClip.id) : null} {@const selHasVideoInput = workflowHasVideoInput(selWf)} @@ -923,9 +958,10 @@ const generateOne = createMutation({ onClipSourceUpload={() => videoFileInput?.click()} onSelectClip={selectClip} onStep={step} - onWorkflowChange={(id) => { - selectedWorkflow = { ...selectedWorkflow, [selected.id]: Number(id) }; - }} + onWorkflowChange={(id) => { + if (!selClip) return; + selectedWorkflow = { ...selectedWorkflow, [selClip.id]: Number(id) }; + }} onGenerate={() => { if (selClip) $generateOne.mutate({ clipId: selClip.id, sceneId: selected.id }); }} diff --git a/docs/changelogs/2026-09-24-clip-workflow-runtime-budget.md b/docs/changelogs/2026-09-24-clip-workflow-runtime-budget.md new file mode 100644 index 00000000..92f2c380 --- /dev/null +++ b/docs/changelogs/2026-09-24-clip-workflow-runtime-budget.md @@ -0,0 +1,62 @@ +# Calliope 1.5.7 — per-clip workflows, runtime budgets, media-path guards + +Three reported issues fixed — [#66](https://github.com/benjiyaya/Calliope/issues/66) +(picking a workflow for one clip changed every clip in the scene), +[#64](https://github.com/benjiyaya/Calliope/issues/64) (scripts ignored the +story's target length), and +[#67](https://github.com/benjiyaya/Calliope/issues/67) (a directory path +passed as a video input crashed ComfyUI with `Errno 21`). + +## #66 — Workflow choice is per clip + +The Video stage's workflow picker was keyed by scene id, so choosing a +workflow for one clip silently overwrote every sibling clip of the same +scene — a scene set up as image→video on clip 1 + video→video extend on +clip 2 could never be enqueued as designed. + +- The picker is now keyed by **clip id**, and opening a clip hydrates its + own persisted choice (`clips.workflow_id`, then `form_workflow_id`). +- The debounced autosave persists both `clips.workflow_id` and + `form_workflow_id`, so the choice survives restarts. +- **Generate One** and batch **Generate All** each resolve the workflow per + clip: session pick → clip row → saved form choice → scene default → first + enabled. A mixed-workflow scene now renders each clip with its own + workflow. + +## #64 — Target runtime is a budget, not a floor + +Asking for a 30-second film could produce a 1:51 script: prompts carried no +per-scene scale, and the duration rescale could only grow +(`max(target/total, 1.0)`), never shrink. + +- Script prompts (single-call and chunked) now state the **total seconds** + and a concrete **per-scene budget** (`Per-scene budget: ~Ns each — write + action length and dialogue VOLUME to this scale`), so content volume is + written to the runtime instead of discovered after. +- The final rescale may now go **below 1.0** (floor 0.5): an over-written + board's scene budgets shrink toward the target. Content is never edited — + long scenes remain correct; clips are where they get cut. + +## #67 — Media inputs that are directories fail fast + +When the agent hand-wrote a path into a media input slot it could pass +ComfyUI's input *directory*; that value reached ComfyUI and died with the +opaque `ValueError: [Errno 21] Is a directory`. + +- `prepare_media_inputs` now rejects a media input whose local-looking value + is a directory or nonexistent file **before queueing**, failing with + `node N (class): field value '...' is a directory` / `file not found + locally` — with the node id and actionable guidance. Bare names (no path + separators) are legitimate Comfy-side references and pass untouched. +- The agent's `run_workflow` mirrors the guard at **call time**: an + `input_values[]` value that resolves to a dir/missing file + fails the tool call with correction guidance instead of creating a doomed + job. + +## Testing + +- `tests/test_script_chunking.py` — per-scene budget present in both prompt + builders; oversized-script durations shrink toward the target. +- `tests/test_video_continue.py` — directory and missing-file rejection, + bare-name passthrough, existing-file upload still works. +- Full backend suite: 534 passed; `svelte-check`: 0 errors. diff --git a/docs/changelogs/README.md b/docs/changelogs/README.md index 708ac28a..29d0ce3a 100644 --- a/docs/changelogs/README.md +++ b/docs/changelogs/README.md @@ -2,6 +2,7 @@ Dated notes for GitHub releases. Newest first. +- [2026-09-24 clip workflow + runtime budget](./2026-09-24-clip-workflow-runtime-budget.md) — workflow per clip (not per scene); target runtime is a budget that can shrink; media inputs that are directories fail fast with a node-naming error (1.5.7) - [2026-09-22 project name alias patch](./2026-09-22-project-name-alias.md) — `name` accepted for a project's title on the REST API and agent tools; fixes storyline builds dead-ending on a 422 (1.5.6) - [2026-09-22 swarm render/scene fixes](./2026-09-22-swarm-render-scene-fixes.md) — video-role render tools reachable (ask_user recovery); story role gains scene tools; deep-link sessions no longer orphan; canvas auto-seeds new entities (1.5.5) - [2026-09-19 steering + Asset Library + hardening](./2026-09-19-steering-library-hardening.md) — mid-run steering; Asset Library page (filter + lazy loading); canvas delete that deletes; agent-loop hardening batch; Build Scene Brief/Cut gates (1.5.4)