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
+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)