feat: prompt review gate, ComfyUI error surfacing, saved scene setups (1.3.0)

Issues #27/#33/#28. Generate now resolves the prompt first (saved draft
or H3 rewrite) and opens an editable review modal before enqueueing;
job history drawer shows each render's exact payload with copy-to-form.
ComfyUI 400s surface error.type + per-node messages; audio uploads go
flat and VHS audio: widgets are patched. Per-scene video settings
persist via scenes.video_settings_json (additive migration) and batch
generate honors them. Version bumped to 1.3.0.
This commit is contained in:
Benjiyaya
2026-08-31 03:20:25 +08:00
parent 792e9c57b1
commit 9c8ea8f28f
22 changed files with 1697 additions and 56 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "calliope"
version = "1.2.3"
version = "1.3.0"
description = "Local-first AI story-to-video studio"
requires-python = ">=3.11"
dependencies = [
@@ -1,6 +1,7 @@
"""Enqueue per-scene video generation jobs."""
from __future__ import annotations
import hashlib
import json
import logging
import sqlite3
@@ -145,12 +146,122 @@ def _get_workflow(workflow_id: int | None = None) -> dict[str, Any] | None:
conn.close()
def _scene_video_settings(scene: dict[str, Any]) -> dict[str, Any]:
"""Parsed scenes.video_settings_json — {} when unset or malformed."""
raw = scene.get("video_settings_json")
if not raw:
return {}
try:
data = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return {}
return data if isinstance(data, dict) else {}
def _stored_input_values(scene: dict[str, Any]) -> dict[str, Any]:
"""Saved per-scene form values (input_values inside video_settings)."""
values = _scene_video_settings(scene).get("input_values")
if isinstance(values, dict):
return {k: v for k, v in values.items() if v not in (None, "")}
return {}
def _stored_prompt_draft(scene: dict[str, Any]) -> str | None:
draft = _scene_video_settings(scene).get("prompt_draft")
return draft if isinstance(draft, str) and draft.strip() else None
def _scene_prompt_hash(scene: dict[str, Any]) -> str:
"""Cheap fingerprint of the inputs a draft was based on (stale detection)."""
basis = "|".join(
str(scene.get(k) or "")
for k in ("heading", "action", "dialog", "duration_sec", "location_id")
)
chars = ",".join(str(c) for c in sorted(scene.get("character_ids") or []))
return hashlib.sha256((basis + "|" + chars).encode()).hexdigest()[:16]
async def preview_scene_prompt(
project_id: int,
scene_id: int,
workflow_id: int | None = None,
) -> dict[str, Any]:
"""Resolve the exact prompt a Generate would send — without enqueueing.
Returns {"prompt": str, "profile": str, "from_draft": bool, "based_on": str}
so the UI can show/edit/save it before the user commits to a render.
"""
conn = get_db(settings.db_path)
try:
row = conn.execute(
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
(scene_id, project_id),
).fetchone()
if not row:
raise ValueError(f"Scene {scene_id} not found in project {project_id}")
scene = row_to_dict(row)
char_rows = conn.execute(
"""
SELECT c.* FROM characters c
JOIN scene_characters sc ON sc.character_id = c.id
WHERE sc.scene_id = ?
""",
(scene_id,),
).fetchall()
characters = [row_to_dict(r) for r in char_rows]
loc_image = scene.get("env_image_path")
loc_row: dict[str, Any] | None = None
if scene.get("location_id"):
loc = conn.execute(
"SELECT name, description, consistency_prompt, reference_image_path "
"FROM locations WHERE id = ?",
(scene["location_id"],),
).fetchone()
if loc:
loc_row = row_to_dict(loc)
if not loc_image:
loc_image = loc_row["reference_image_path"]
finally:
conn.close()
wf_id = workflow_id or scene.get("workflow_id")
workflow = _get_workflow(wf_id)
if not workflow:
raise ValueError("No enabled video workflow found — configure one in Settings")
inputs = parse_dynamic_inputs(_workflow_json(workflow))
profile = workflow.get("prompt_profile") or "prose"
based_on = _scene_prompt_hash(scene)
if profile == "minimax_h3_ref":
# Fresh saved draft short-circuits the LLM call
draft = _stored_prompt_draft(scene)
if draft:
meta = _scene_video_settings(scene).get("prompt_draft_meta") or {}
if meta.get("based_on") == based_on:
return {
"prompt": draft,
"profile": profile,
"from_draft": True,
"based_on": based_on,
}
subjects, _ = _h3_subjects(characters, loc_row, loc_image, inputs)
await event_bus.publish(
"agent.thinking",
{"message": f"H3 prompt rewrite · scene {scene.get('order_index')}", "project_id": project_id},
)
prompt = await _h3_rewrite(scene, subjects)
else:
prompt = scene_video_prompt(scene, characters)
return {"prompt": prompt, "profile": profile, "from_draft": False, "based_on": based_on}
async def enqueue_video_jobs(
project_id: int,
*,
scene_ids: list[int] | None = None,
workflow_id: int | None = None,
input_values_override: dict[str, Any] | None = None,
prompts: dict[int, str] | None = None,
) -> list[dict[str, Any]]:
await event_bus.publish(
"agent.thinking", {"message": "Queuing video jobs…", "project_id": project_id}
@@ -221,33 +332,67 @@ async def enqueue_video_jobs(
loc_image = loc_row["reference_image_path"]
profile = (workflow or {}).get("prompt_profile") or "prose"
# Merge base: saved per-scene setup first, explicit request wins on
# top — so batch Generate-all honors persisted form setups.
stored_values = _stored_input_values(scene)
extra_values: dict[str, Any] = {**stored_values}
if input_values_override:
extra_values.update(
{k: v for k, v in input_values_override.items() if v not in (None, "")}
)
if profile == "minimax_h3_ref":
subjects, ref_paths = _h3_subjects(characters, loc_row, loc_image, inputs)
await event_bus.publish(
"agent.thinking",
{
"message": f"H3 prompt rewrite · scene {scene.get('order_index')}",
"project_id": project_id,
},
)
prompt = await _h3_rewrite(scene, subjects)
# Prompt precedence: explicit request → saved (fresh) draft → LLM.
explicit_prompt = (prompts or {}).get(scene["id"])
fresh_draft = None
if explicit_prompt is None:
candidate = _stored_prompt_draft(scene)
if candidate:
meta = _scene_video_settings(scene).get("prompt_draft_meta") or {}
if meta.get("based_on") == _scene_prompt_hash(scene):
fresh_draft = candidate
if explicit_prompt is not None:
prompt = explicit_prompt
elif fresh_draft:
prompt = fresh_draft
else:
await event_bus.publish(
"agent.thinking",
{
"message": f"H3 prompt rewrite · scene {scene.get('order_index')}",
"project_id": project_id,
},
)
prompt = await _h3_rewrite(scene, subjects)
values = smart_fill_inputs(
inputs,
prompt=prompt,
ref_images=ref_paths,
duration=duration,
extra=input_values_override,
extra=extra_values,
)
else:
prompt = scene_video_prompt(scene, characters)
prompt = (prompts or {}).get(scene["id"]) or scene_video_prompt(
scene, characters
)
values = smart_fill_inputs(
inputs,
prompt=prompt,
character_image=char_image,
location_image=loc_image,
duration=duration,
extra=input_values_override,
extra=extra_values,
)
# Stored per-scene setups override smart-fill's context choices
# (e.g. an edited duration). smart_fill skips duration-role nodes
# in `extra` by design — re-apply them here, request values win.
explicit_final = {
**stored_values,
**{k: v for k, v in (input_values_override or {}).items() if v not in (None, "")},
}
for k, v in explicit_final.items():
if v not in (None, ""):
values[str(k)] = v
payload: dict[str, Any] = {"input_values": values, "prompt": prompt}
if scene.get("chain_from_prev"):
video_input = _video_input(inputs)
+71 -13
View File
@@ -14,6 +14,44 @@ from calliope.comfyui.registry import IMAGE_CLASSES, AUDIO_CLASSES, VIDEO_CLASSE
logger = logging.getLogger("calliope.comfyui")
def _surface_error(prefix: str, resp: httpx.Response) -> RuntimeError:
"""Raise with ComfyUI's own error body instead of an opaque status line.
Comfy's /prompt replies carry {"error": {...}, "node_errors": {node_id: {...}}}
naming the exact node and message (e.g. 'Invalid audio file'). raise_for_status()
discards all of it, which turns diagnosable failures into one-line bug reports.
"""
detail = ""
try:
body = resp.json()
except Exception:
body = None
if isinstance(body, dict):
parts: list[str] = []
err = body.get("error")
if isinstance(err, dict):
err_type = err.get("type") or err.get("message")
if err_type:
parts.append(str(err_type))
elif isinstance(err, str) and err:
parts.append(err)
node_errors = body.get("node_errors")
if isinstance(node_errors, dict):
for node_id, node_err in node_errors.items():
if not isinstance(node_err, dict):
continue
errors = node_err.get("errors")
if isinstance(errors, list):
for e in errors:
if isinstance(e, dict):
msg = e.get("message") or e.get("details")
if msg:
parts.append(f"node {node_id}: {msg}")
detail = "; ".join(parts)
suffix = f": {detail}" if detail else ""
return RuntimeError(f"{prefix} ({resp.status_code}){suffix}")
class ComfyUIClient:
def __init__(self, base_url: str | None = None) -> None:
self.base_url = (base_url or settings.comfyui_base_url).rstrip("/")
@@ -35,18 +73,28 @@ class ComfyUIClient:
files = {"image": (path.name, data, "application/octet-stream")}
form = {"overwrite": "true", "subfolder": subfolder}
resp = await self._http.post(f"{self.base_url}/upload/image", files=files, data=form)
resp.raise_for_status()
if resp.status_code >= 400:
raise _surface_error("ComfyUI image upload failed", resp)
result = resp.json()
name = result.get("name", path.name)
sub = result.get("subfolder") or subfolder
return f"{sub}/{name}" if sub else name
async def upload_audio(self, path: Path, subfolder: str = "calliope") -> str:
async def upload_audio(self, path: Path, subfolder: str = "") -> str:
"""Upload audio via Comfy's /upload/image route (there is no /upload/audio
in core ComfyUI — its own frontend posts audio there too, field `image`).
Flat input dir + bare filename: LoadAudio's file list and VALIDATE_INPUTS
existence check are most reliable without a subfolder prefix.
"""
data = path.read_bytes()
files = {"image": (path.name, data, "application/octet-stream")} # Comfy uses image field
form = {"overwrite": "true", "subfolder": subfolder, "type": "input"}
files = {"image": (path.name, data, "application/octet-stream")}
form = {"overwrite": "true", "type": "input"}
if subfolder:
form["subfolder"] = subfolder
resp = await self._http.post(f"{self.base_url}/upload/image", files=files, data=form)
resp.raise_for_status()
if resp.status_code >= 400:
raise _surface_error("ComfyUI audio upload failed", resp)
result = resp.json()
name = result.get("name", path.name)
sub = result.get("subfolder") or subfolder
@@ -58,7 +106,8 @@ class ComfyUIClient:
files = {"image": (path.name, data, "application/octet-stream")}
form = {"overwrite": "true", "subfolder": subfolder, "type": "input"}
resp = await self._http.post(f"{self.base_url}/upload/image", files=files, data=form)
resp.raise_for_status()
if resp.status_code >= 400:
raise _surface_error("ComfyUI video upload failed", resp)
result = resp.json()
name = result.get("name", path.name)
sub = result.get("subfolder") or subfolder
@@ -79,12 +128,20 @@ class ComfyUIClient:
inputs["image"] = await self.upload_image(path)
node["inputs"] = inputs
elif class_type in AUDIO_CLASSES:
audio = inputs.get("audio")
if isinstance(audio, str) and self._looks_like_local_path(audio):
path = Path(audio)
if path.exists():
inputs["audio"] = await self.upload_audio(path)
node["inputs"] = inputs
# VHS_LoadAudio names its widget "audio:" (with colon); stock
# LoadAudio uses "audio". Probe both so the file is uploaded
# whichever variant the workflow uses.
audio_key = next(
(k for k in ("audio", "audio:") if isinstance(inputs.get(k), str)),
None,
)
if audio_key:
audio = inputs[audio_key]
if isinstance(audio, str) and self._looks_like_local_path(audio):
path = Path(audio)
if path.exists():
inputs[audio_key] = await self.upload_audio(path)
node["inputs"] = inputs
elif class_type in VIDEO_CLASSES:
field = "file" if class_type in VIDEO_FILE_CLASSES else "video"
media = inputs.get(field)
@@ -105,7 +162,8 @@ class ComfyUIClient:
async def queue_prompt(self, workflow: dict[str, Any]) -> str:
payload = {"prompt": workflow, "client_id": self.client_id}
resp = await self._http.post(f"{self.base_url}/prompt", json=payload)
resp.raise_for_status()
if resp.status_code >= 400:
raise _surface_error("ComfyUI rejected the workflow", resp)
data = resp.json()
prompt_id = data.get("prompt_id")
if not prompt_id:
@@ -7,6 +7,25 @@ from typing import Any
from calliope.comfyui.registry import class_to_patch_field
def _resolve_field(field: str, inputs: dict[str, Any]) -> str:
"""Map the computed patch field onto a key that exists on this node.
Known variants:
- text ↔ value (PrimitiveString-style nodes expose `value`, not `text`).
- audio ↔ audio: (VHS_LoadAudio names its widget `audio:` with a colon).
The fallback stays guarded to these exact sibling pairs — never a fuzzy
match — so an unknown node can't have its values written to some
unrelated key ComfyUI would silently ignore.
"""
if field in inputs:
return field
siblings = {"text": "value", "value": "text", "audio": "audio:", "audio:": "audio"}
alt = siblings.get(field)
if alt and alt in inputs:
return alt
return field
def patch_workflow(
base: dict[str, Any],
values_by_node_id: dict[str, Any],
@@ -20,11 +39,7 @@ def patch_workflow(
if not isinstance(node, dict):
continue
inputs = dict(node.get("inputs") or {})
field = class_to_patch_field(node.get("class_type", ""))
if field == "text" and "text" not in inputs and "value" in inputs:
field = "value"
if field == "value" and "text" in inputs and "value" not in inputs:
field = "text"
field = _resolve_field(class_to_patch_field(node.get("class_type", "")), inputs)
inputs[field] = value
node["inputs"] = inputs
patched[key] = node
+30
View File
@@ -75,6 +75,7 @@ CREATE TABLE IF NOT EXISTS scenes (
env_image_path TEXT,
location_id INTEGER,
video_path TEXT,
video_settings_json TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -192,6 +193,8 @@ async def migrate_db(db_path: Path) -> None:
conn.execute(
"ALTER TABLE scenes ADD COLUMN chain_from_prev INTEGER NOT NULL DEFAULT 0"
)
if "video_settings_json" not in scene_cols:
conn.execute("ALTER TABLE scenes ADD COLUMN video_settings_json TEXT")
project_cols = {r[1] for r in conn.execute("PRAGMA table_info(projects)").fetchall()}
if "cover_path" not in project_cols:
conn.execute("ALTER TABLE projects ADD COLUMN cover_path TEXT")
@@ -272,4 +275,31 @@ def rebase_stale_asset_paths(conn: sqlite3.Connection, data_dir: Path, assets_di
(json.dumps(new_paths), row["id"]),
)
count += 1
# Scene video settings embed absolute asset paths (ref images, uploaded
# clips) in input_values — rebase those too so a moved install keeps the
# saved setups working.
rows = conn.execute(
"SELECT id, video_settings_json FROM scenes WHERE video_settings_json IS NOT NULL"
).fetchall()
for row in rows:
try:
data = json.loads(row["video_settings_json"] or "{}")
except json.JSONDecodeError:
continue
if not isinstance(data, dict):
continue
values = data.get("input_values")
if isinstance(values, dict):
data["input_values"] = {
k: (_rebase_path(v, data_dir, assets_dir) or v if isinstance(v, str) else v)
for k, v in values.items()
}
draft = data.get("prompt_draft")
if isinstance(draft, str) and not draft:
data.pop("prompt_draft", None)
conn.execute(
"UPDATE scenes SET video_settings_json = ? WHERE id = ?",
(json.dumps(data), row["id"]),
)
count += 1
return count
@@ -142,6 +142,9 @@ class SceneUpdate(BaseModel):
location_id: int | None = None
video_path: str | None = None
chain_from_prev: bool | None = None
# Persisted video-stage setup: form input_values, clip source, prompt
# draft + metadata. Serialized into scenes.video_settings_json.
video_settings: dict[str, Any] | None = None
class SceneReorder(BaseModel):
@@ -201,3 +204,11 @@ class GenerateVideosRequest(BaseModel):
scene_ids: list[int] | None = None
workflow_id: int | None = None
input_values: dict[str, Any] | None = None
# Scene-id → confirmed prompt text (from the review modal). Wins over the
# LLM rewrite and over any saved draft.
prompts: dict[int, str] | None = None
class PreviewPromptRequest(BaseModel):
scene_id: int
workflow_id: int | None = None
+18 -2
View File
@@ -5,13 +5,17 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Query
from calliope.agent.video_agent import enqueue_video_jobs
from calliope.agent.video_agent import enqueue_video_jobs, preview_scene_prompt
from calliope.comfyui.client import ComfyUIClient
from calliope.config import settings
from calliope.db import get_db
from calliope.events.bus import event_bus
from calliope.export.runner import kill_running
from calliope.models.schemas import GenerateVideosRequest, JobCreate
from calliope.models.schemas import (
GenerateVideosRequest,
JobCreate,
PreviewPromptRequest,
)
from calliope.queue.manager import queue_manager
router = APIRouter()
@@ -63,12 +67,24 @@ async def generate_videos(
scene_ids=body.scene_ids,
workflow_id=body.workflow_id,
input_values_override=body.input_values,
prompts=body.prompts,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return {"ok": True, "jobs": [_job_public(j) for j in jobs]}
@router.post("/projects/{project_id}/preview-prompt")
async def preview_prompt(project_id: int, payload: PreviewPromptRequest) -> dict[str, Any]:
"""HITL review step: the exact prompt a Generate would send, no enqueue."""
try:
return await preview_scene_prompt(
project_id, payload.scene_id, workflow_id=payload.workflow_id
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.post("/projects/{project_id}/export")
async def export_film(project_id: int) -> dict[str, Any]:
conn = get_db(settings.db_path)
@@ -114,6 +114,9 @@ UPLOAD_KIND_BY_EXT: dict[str, str] = {
".wav": "audio",
".flac": "audio",
".ogg": "audio",
# Note: core ComfyUI's LoadAudio file list is typically wav/mp3/ogg/flac/aiff.
# .m4a uploads succeed here and land in Comfy's input dir, but some builds
# reject it at /prompt validation — prefer wav/mp3 for ref audio.
".m4a": "audio",
}
@@ -1,5 +1,6 @@
from __future__ import annotations
import json
from typing import Any
from fastapi import APIRouter, HTTPException
@@ -25,6 +26,14 @@ def _scene_with_chars(conn, scene_row) -> dict[str, Any]:
).fetchall()
scene["characters"] = [row_to_dict(c) for c in chars]
scene["character_ids"] = [c["id"] for c in scene["characters"]]
raw_settings = scene.pop("video_settings_json", None)
if raw_settings:
try:
scene["video_settings"] = json.loads(raw_settings)
except (json.JSONDecodeError, TypeError):
scene["video_settings"] = None
else:
scene["video_settings"] = None
return scene
@@ -111,11 +120,22 @@ async def update_scene(project_id: int, scene_id: int, payload: SceneUpdate) ->
raise HTTPException(status_code=404, detail="Scene not found")
data = payload.model_dump(exclude_unset=True)
char_ids = data.pop("character_ids", None)
# video_settings arrives as a dict — the generic UPDATE path below only
# handles scalars, so serialize it into its JSON column (or NULL it).
video_settings = data.pop("video_settings", None)
data = {k: v for k, v in data.items() if v is not None}
if data:
fields = ", ".join(f"{k} = :{k}" for k in data)
data["id"] = scene_id
if video_settings is not None:
data["video_settings_json"] = json.dumps(video_settings)
fields += ", video_settings_json = :video_settings_json"
conn.execute(f"UPDATE scenes SET {fields} WHERE id = :id", data)
elif video_settings is not None:
conn.execute(
"UPDATE scenes SET video_settings_json = ? WHERE id = ?",
(json.dumps(video_settings), scene_id),
)
if char_ids is not None:
conn.execute("DELETE FROM scene_characters WHERE scene_id = ?", (scene_id,))
for cid in char_ids:
+122
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
from pathlib import Path
from calliope.comfyui.parser import parse_dynamic_inputs, parse_dynamic_outputs
from calliope.comfyui.patcher import patch_workflow
@@ -53,6 +54,127 @@ def test_patch_workflow_by_node_id():
assert patched["10"]["inputs"]["image"] == "ref.png"
def test_patch_workflow_vhs_audio_colon_widget():
"""VHS_LoadAudio's widget is literally `audio:` — the patcher must write it."""
wf = {
"5": {
"inputs": {"audio:": "old.wav"},
"class_type": "VHS_LoadAudio",
"_meta": {"title": "Ref Audio (Input:audio)"},
}
}
patched = patch_workflow(wf, {"5": "C:/assets/new.wav"})
assert patched["5"]["inputs"]["audio:"] == "C:/assets/new.wav"
# no bogus `audio` key gets added alongside
assert "audio" not in patched["5"]["inputs"]
def test_patch_workflow_no_fuzzy_fallback():
"""Unknown field on a node with unrelated keys must not get rewritten."""
wf = {
"7": {
"inputs": {"aspect_ratio": "16:9", "megapixels": 1.0},
"class_type": "ResolutionSelector",
"_meta": {"title": "Resolution (Input)"},
}
}
patched = patch_workflow(wf, {"7": "9:16"})
# computed field 'value' doesn't exist and has no sibling pair — stays put
assert patched["7"]["inputs"].get("value") == "9:16"
assert patched["7"]["inputs"]["aspect_ratio"] == "16:9"
def test_queue_prompt_surfaces_comfy_error_body(monkeypatch):
"""A 400 from Comfy /prompt must name the node, not just the status code."""
import httpx
from calliope.comfyui.client import ComfyUIClient
body = {
"error": {"type": "prompt_outputs_failed_validation"},
"node_errors": {
"12": {"errors": [{"message": "Invalid audio file: ref.m4a"}]},
},
}
def fake_send(request, **kwargs):
return httpx.Response(400, json=body, request=request)
transport = httpx.MockTransport(fake_send)
client = ComfyUIClient(base_url="http://comfy.test")
client._http = httpx.AsyncClient(transport=transport)
import asyncio
async def run():
try:
await client.queue_prompt({"1": {"class_type": "X", "inputs": {}}})
except RuntimeError as exc:
return str(exc)
finally:
await client.close()
msg = asyncio.run(run())
assert "prompt_outputs_failed_validation" in msg
assert "node 12" in msg
assert "Invalid audio file" in msg
def test_upload_audio_flat_no_subfolder(tmp_path, monkeypatch):
"""Audio uploads go to the flat input dir and return a bare filename."""
import asyncio
import httpx
from calliope.comfyui.client import ComfyUIClient
sent: dict = {}
def fake_send(request, **kwargs):
sent["url"] = str(request.url)
sent["content_type"] = request.headers.get("content-type", "")
return httpx.Response(200, json={"name": "ref.wav", "subfolder": ""}, request=request)
transport = httpx.MockTransport(fake_send)
client = ComfyUIClient(base_url="http://comfy.test")
client._http = httpx.AsyncClient(transport=transport)
audio = tmp_path / "ref.wav"
audio.write_bytes(b"wav-placeholder")
async def run():
try:
return await client.upload_audio(audio)
finally:
await client.close()
name = asyncio.run(run())
assert name == "ref.wav" # bare filename, no calliope/ prefix
assert sent["url"].endswith("/upload/image")
def test_prepare_media_inputs_vhs_audio(tmp_path):
"""VHS_LoadAudio with an `audio:` widget gets its file uploaded in place."""
import asyncio
from calliope.comfyui.client import ComfyUIClient
audio = tmp_path / "voice.wav"
audio.write_bytes(b"wav-placeholder")
client = ComfyUIClient.__new__(ComfyUIClient) # skip __init__ HTTP client
async def fake_upload(path, subfolder=""):
assert Path(path) == audio
return "voice.wav"
client.upload_audio = fake_upload # type: ignore[method-assign]
wf = {
"5": {
"inputs": {"audio:": str(audio)},
"class_type": "VHS_LoadAudio",
"_meta": {"title": "Ref Audio (Input:audio)"},
}
}
out = asyncio.run(client.prepare_media_inputs(wf))
assert out["5"]["inputs"]["audio:"] == "voice.wav"
def test_workflow_analyze_and_create(client):
r = client.post("/api/workflows/analyze", json={"workflow_json": SAMPLE_WORKFLOW})
assert r.status_code == 200
@@ -0,0 +1,312 @@
"""Scene video_settings persistence (issue #28): PATCH round-trip, enqueue merge."""
from __future__ import annotations
import json
from calliope.agent.video_agent import enqueue_video_jobs
from calliope.config import settings
from calliope.db import get_db
def _mk_project(client, title: str) -> int:
return client.post("/api/projects", json={"title": title}).json()["id"]
def _add_scene(client, pid: int, order: int, **extra) -> dict:
payload = {"order_index": order, "heading": f"S{order}", **extra}
return client.post(f"/api/projects/{pid}/scenes", json=payload).json()
def test_scene_patch_video_settings_roundtrip(client):
pid = _mk_project(client, "Settings RT")
scene = _add_scene(client, pid, 1)
settings_payload = {
"input_values": {"102": 1280, "209": "my prompt"},
"clip_source": "auto",
"form_workflow_id": 3,
}
r = client.patch(
f"/api/projects/{pid}/scenes/{scene['id']}",
json={"video_settings": settings_payload},
)
assert r.status_code == 200
body = r.json()
assert body["video_settings"] == settings_payload
# GET path parses the column back out too
r = client.get(f"/api/projects/{pid}/scenes")
scenes = r.json()["scenes"]
assert scenes[0]["video_settings"] == settings_payload
def test_scene_patch_video_settings_alongside_other_fields(client):
pid = _mk_project(client, "Settings mixed")
scene = _add_scene(client, pid, 1)
r = client.patch(
f"/api/projects/{pid}/scenes/{scene['id']}",
json={"heading": "Renamed", "video_settings": {"input_values": {"5": "x.wav"}}},
)
assert r.status_code == 200
body = r.json()
assert body["heading"] == "Renamed"
assert body["video_settings"]["input_values"]["5"] == "x.wav"
def test_video_settings_survive_migration_column(client):
"""Existing DBs get the column via migrate_db — writes/reads work on it."""
conn = get_db(settings.db_path)
try:
cols = {r[1] for r in conn.execute("PRAGMA table_info(scenes)").fetchall()}
assert "video_settings_json" in cols
finally:
conn.close()
def _insert_h3_workflow(conn, name: str) -> int:
wf = {
"10": {
"class_type": "CLIPTextEncode",
"inputs": {"text": ""},
"_meta": {"title": "Main Prompt (Input:prompt)"},
},
"20": {
"class_type": "PrimitiveInt",
"inputs": {"value": 6},
"_meta": {"title": "Duration (Input:duration)"},
},
}
cur = conn.execute(
"""
INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema,
prompt_profile, is_enabled)
VALUES (?, 'video', ?, '[]', '[]', 'minimax_h3_ref', 1)
""",
(name, json.dumps(wf)),
)
conn.commit()
return cur.lastrowid
def test_enqueue_merges_stored_input_values(client, monkeypatch):
"""Batch enqueue with no form values must honor the saved per-scene setup."""
pid = _mk_project(client, "Merge stored")
scene = _add_scene(client, pid, 1)
conn = get_db(settings.db_path)
try:
wf_id = _insert_h3_workflow(conn, "H3 merge")
stored = {"input_values": {"20": 10}}
conn.execute(
"UPDATE scenes SET workflow_id = ?, video_settings_json = ? WHERE id = ?",
(wf_id, json.dumps(stored), scene["id"]),
)
conn.commit()
finally:
conn.close()
# Skip the LLM rewrite — the fallback template is deterministic
async def fake_rewrite(scene_, subjects):
return "fallback"
monkeypatch.setattr("calliope.agent.video_agent._h3_rewrite", fake_rewrite)
from calliope.queue.manager import queue_manager
queue_manager.paused = True
try:
jobs = asyncio_run(
enqueue_video_jobs(pid, scene_ids=[scene["id"]])
)
assert len(jobs) == 1
raw = json.loads(jobs[0]["payload_json"])
values = raw["input_values"]
assert values["20"] == 10 # stored setup applied
assert raw["prompt"] == "fallback"
finally:
queue_manager.paused = False
def test_preview_prompt_endpoint_h3_profile(client, monkeypatch):
"""Preview resolves the H3 rewrite without enqueueing anything."""
from calliope.queue.manager import queue_manager
pid = _mk_project(client, "Preview H3")
scene = _add_scene(client, pid, 1)
conn = get_db(settings.db_path)
try:
wf_id = _insert_h3_workflow(conn, "H3 preview")
conn.execute(
"UPDATE scenes SET workflow_id = ? WHERE id = ?", (wf_id, scene["id"])
)
conn.commit()
finally:
conn.close()
async def fake_rewrite(scene_, subjects):
return "H3 REWRITE"
monkeypatch.setattr("calliope.agent.video_agent._h3_rewrite", fake_rewrite)
queue_manager.paused = True
try:
r = client.post(
f"/api/jobs/projects/{pid}/preview-prompt",
json={"scene_id": scene["id"]},
)
assert r.status_code == 200
body = r.json()
assert body["prompt"] == "H3 REWRITE"
assert body["profile"] == "minimax_h3_ref"
assert body["from_draft"] is False
assert body["based_on"]
# No jobs were created by a preview
jobs = client.get(f"/api/jobs?project_id={pid}").json()
video_jobs = [j for j in jobs if j["kind"] == "video"]
assert video_jobs == []
finally:
queue_manager.paused = False
def test_preview_prompt_fresh_draft_shortcircuits_llm(client, monkeypatch):
"""A saved fresh draft is returned as-is — no LLM call."""
from calliope.agent.video_agent import preview_scene_prompt
pid = _mk_project(client, "Preview draft")
scene = _add_scene(client, pid, 1)
conn = get_db(settings.db_path)
try:
wf_id = _insert_h3_workflow(conn, "H3 draft")
conn.execute(
"UPDATE scenes SET workflow_id = ? WHERE id = ?", (wf_id, scene["id"])
)
conn.commit()
finally:
conn.close()
# Compute the hash the backend would, then store the draft with it
from calliope.agent.video_agent import _scene_prompt_hash
conn = get_db(settings.db_path)
try:
fresh_row = conn.execute(
"SELECT * FROM scenes WHERE id = ?", (scene["id"],)
).fetchone()
from calliope.db import row_to_dict
fresh_scene = row_to_dict(fresh_row)
# character_ids aren't on the row — hash treats them via scene dict
fresh_scene["character_ids"] = []
stored = {
"prompt_draft": "MY SAVED DRAFT",
"prompt_draft_meta": {"based_on": _scene_prompt_hash(fresh_scene)},
}
conn.execute(
"UPDATE scenes SET video_settings_json = ? WHERE id = ?",
(json.dumps(stored), scene["id"]),
)
conn.commit()
finally:
conn.close()
called = []
async def fake_rewrite(scene_, subjects):
called.append(1)
return "SHOULD NOT BE USED"
monkeypatch.setattr("calliope.agent.video_agent._h3_rewrite", fake_rewrite)
result = asyncio_run(preview_scene_prompt(pid, scene["id"]))
assert result["prompt"] == "MY SAVED DRAFT"
assert result["from_draft"] is True
assert called == [] # LLM never invoked
def test_enqueue_prompts_override(client, monkeypatch):
"""Confirmed prompt from the review modal wins over the rewrite."""
pid = _mk_project(client, "Prompt override")
scene = _add_scene(client, pid, 1)
conn = get_db(settings.db_path)
try:
wf_id = _insert_h3_workflow(conn, "H3 override")
conn.execute(
"UPDATE scenes SET workflow_id = ? WHERE id = ?", (wf_id, scene["id"])
)
conn.commit()
finally:
conn.close()
async def fake_rewrite(scene_, subjects):
return "LLM VERSION"
monkeypatch.setattr("calliope.agent.video_agent._h3_rewrite", fake_rewrite)
from calliope.queue.manager import queue_manager
queue_manager.paused = True
try:
jobs = asyncio_run(
enqueue_video_jobs(pid, scene_ids=[scene["id"]], prompts={scene["id"]: "CONFIRMED"})
)
raw = json.loads(jobs[0]["payload_json"])
assert raw["prompt"] == "CONFIRMED"
finally:
queue_manager.paused = False
def test_preview_prompt_prose_profile(client):
"""Prose workflows return the deterministic scene_video_prompt."""
pid = _mk_project(client, "Preview prose")
scene = _add_scene(client, pid, 1, action="A knight rides at dawn.")
conn = get_db(settings.db_path)
try:
wf = {
"10": {
"class_type": "CLIPTextEncode",
"inputs": {"text": ""},
"_meta": {"title": "Main Prompt (Input:prompt)"},
}
}
cur = conn.execute(
"""
INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema, is_enabled)
VALUES (?, 'video', ?, '[]', '[]', 1)
""",
("Prose WF", json.dumps(wf)),
)
conn.execute(
"UPDATE scenes SET workflow_id = ? WHERE id = ?", (cur.lastrowid, scene["id"])
)
conn.commit()
finally:
conn.close()
r = client.post(
f"/api/jobs/projects/{pid}/preview-prompt",
json={"scene_id": scene["id"]},
)
assert r.status_code == 200
body = r.json()
assert body["profile"] == "prose"
assert "knight" in body["prompt"]
def test_preview_prompt_missing_scene_400(client):
pid = _mk_project(client, "Preview missing")
r = client.post(
f"/api/jobs/projects/{pid}/preview-prompt",
json={"scene_id": 99999},
)
assert r.status_code == 400
def asyncio_run(coro):
import asyncio
return asyncio.run(coro)