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,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: