diff --git a/calliope-backend/src/calliope/queue/worker.py b/calliope-backend/src/calliope/queue/worker.py index 70379af9..8ac17d08 100644 --- a/calliope-backend/src/calliope/queue/worker.py +++ b/calliope-backend/src/calliope/queue/worker.py @@ -6,10 +6,14 @@ import json import logging from typing import Any +from pathlib import Path as _fs_path + from calliope import config from calliope.comfyui.client import ComfyUIClient from calliope.comfyui.dry_run import write_placeholder_mp4, write_placeholder_png +from calliope.comfyui.parser import parse_dynamic_inputs from calliope.comfyui.patcher import patch_workflow +from calliope.comfyui.roles import input_has_role from calliope.db import get_db from calliope.events.bus import event_bus from calliope.export.runner import run_export @@ -128,6 +132,10 @@ class QueueWorker: raise RuntimeError("No workflow found for job") input_values = payload.get("input_values") or {} + if payload.get("continue_source") and kind == "video": + input_values = await self._resolve_continue_source( + job, payload, workflow, dict(input_values) + ) patched = patch_workflow(workflow, input_values) patched = await client.prepare_media_inputs(patched) prompt_id = await client.queue_prompt(patched) @@ -161,6 +169,78 @@ class QueueWorker: finally: await client.close() + async def _resolve_continue_source( + self, + job: dict[str, Any], + payload: dict[str, Any], + workflow: dict[str, Any], + input_values: dict[str, Any], + ) -> dict[str, Any]: + """Fill the workflow's video input with the previous scene's clip. + + Enqueue defers continue-scenes whose earlier clip does not exist yet + (batch generation); the queue is concurrency-1, so by the time this job + runs the earlier clip has been rendered and attached to its scene. The + path is injected into ``input_values`` like any user-provided value — + ``patch_workflow`` writes it onto the ``(Input:video)`` node and + ``prepare_media_inputs`` uploads it to ComfyUI before queuing. + """ + project_id = job["project_id"] + order_index = (payload.get("continue_source") or {}).get("scene_order_index") + if order_index is None: + order_index = payload.get("scene_order_index") or 0 + + prev_order: int | None = None + prev_clip: str | None = None + conn = get_db(config.settings.db_path) + try: + row = conn.execute( + """ + SELECT order_index, video_path FROM scenes + WHERE project_id = ? AND order_index < ? + ORDER BY order_index DESC LIMIT 1 + """, + (project_id, order_index), + ).fetchone() + if row: + prev_order = row["order_index"] + prev_clip = row["video_path"] + finally: + conn.close() + + scene_n = order_index + if prev_order is None: + raise RuntimeError( + f"Continue scene {scene_n}: no earlier scene in this project to continue from." + ) + if not prev_clip or not _fs_path(prev_clip).exists(): + raise RuntimeError( + f"Continue scene {scene_n}: previous clip (scene {prev_order}) has no video file " + "— generate the earlier clip first." + ) + + video_node: str | None = None + for inp in parse_dynamic_inputs(workflow): + if input_has_role(inp, "video"): + video_node = str(inp["nodeId"]) + break + if video_node is None: + raise RuntimeError( + "Continue scene " + f"{scene_n}: workflow has no (Input:video) node to receive the previous clip." + ) + + input_values[video_node] = prev_clip + await event_bus.publish( + "job.progress", + { + "job_id": job["id"], + "project_id": project_id, + "message": f"Continuing from scene {prev_order} clip", + }, + ) + return input_values + async def _dry_run(self, job: dict[str, Any], payload: dict[str, Any]) -> list[str]: project_id = job["project_id"] kind = job["kind"] diff --git a/calliope-backend/tests/test_video_continue.py b/calliope-backend/tests/test_video_continue.py index 0be8597b..b648993d 100644 --- a/calliope-backend/tests/test_video_continue.py +++ b/calliope-backend/tests/test_video_continue.py @@ -5,9 +5,14 @@ import asyncio import json from pathlib import Path +import pytest + from calliope.agent.video_agent import enqueue_video_jobs +from calliope.comfyui.client import ComfyUIClient from calliope.config import settings from calliope.db import get_db +from calliope.queue.manager import queue_manager +from calliope.queue.worker import queue_worker # One prompt node, one video input slot — the minimum viable "continue" workflow. VIDEO_WORKFLOW = { @@ -215,3 +220,193 @@ def test_non_continue_scene_untouched(client): assert "scene_order_index" not in payload assert "chain_replace_value" not in payload assert "20" not in payload["input_values"] + + +def _last_job_row(pid: int) -> dict: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT * FROM jobs WHERE project_id = ? AND kind = 'video' ORDER BY id DESC LIMIT 1", + (pid,), + ).fetchone() + assert row is not None + return dict(row) + finally: + conn.close() + + +def _scene_ids(pid: int) -> list[int]: + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT id FROM scenes WHERE project_id = ? ORDER BY order_index", (pid,) + ).fetchall() + return [r["id"] for r in rows] + finally: + conn.close() + + +async def _fake_history(_client, _prompt_id): + """A successful ComfyUI history with one video output named out.mp4.""" + return { + "status": {"status_str": "success", "completed": True}, + "outputs": { + "99": {"videos": [{"filename": "out.mp4", "subfolder": "", "type": "output"}]} + }, + } + + +def _stub_comfy(monkeypatch, captured: dict) -> list[str]: + """Run the worker's real (non-dry) path with ComfyUI faked in-process. + + The live worker (started by the TestClient lifespan) is paused so it can + not claim the pending jobs; queue_prompt captures the patched workflow so + tests can assert on it; upload_video records which local path + prepare_media_inputs handed it; download_image writes out.mp4. Returns + the list that collects uploaded local paths. + """ + queue_manager.paused = True + uploads: list[str] = [] + + async def fake_upload_video(self, path, subfolder="calliope"): + uploads.append(str(path)) + return f"{subfolder}/{Path(path).name}" + + async def fake_queue_prompt(self, workflow): + captured.update(workflow) + return "test-prompt-id" + + async def fake_download(self, filename, subfolder="", folder_type="output", dest=None): + dest.write_bytes(b"mp4-placeholder") + return dest + + async def fake_health(self): + return True + + monkeypatch.setattr(ComfyUIClient, "health", fake_health) + monkeypatch.setattr(ComfyUIClient, "upload_video", fake_upload_video) + monkeypatch.setattr(ComfyUIClient, "queue_prompt", fake_queue_prompt) + monkeypatch.setattr(ComfyUIClient, "download_image", fake_download) + monkeypatch.setattr(queue_worker, "_poll_history", _fake_history) + # conftest sets dry_run=True for placeholder generation; the assertions + # here need the real patch path, so turn it off for the direct _run_job. + monkeypatch.setattr(settings, "dry_run", False) + return uploads + + +def test_worker_resolves_continue_source_into_video_node(client, monkeypatch): + """Continue_source job: worker injects the earlier clip before patching.""" + pid = _mk_project(client, "Worker Resolve") + _add_scene(client, pid, 1) + scene2 = _add_scene(client, pid, 2) + _set_chain(client, pid, scene2["id"], True) + clip = _touch_clip("worker-resolve.mp4") + conn = get_db(settings.db_path) + try: + wid = _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW) + conn.execute( + "UPDATE scenes SET video_path = ? WHERE order_index = 1 AND project_id = ?", + (clip, pid), + ) + conn.commit() + finally: + conn.close() + + # Same enqueue shape as the deferred batch case: scene 1 renders first, so + # at enqueue time scene 2's clip does not exist yet and lands in + # continue_source. The worker must resolve it before patching. + jobs = asyncio.run(enqueue_video_jobs(pid)) + assert len(jobs) == 2 + payloads = _job_payloads(pid) + assert payloads[1].get("continue_source") == {"scene_order_index": 2} + + job = _last_job_row(pid) + assert job["workflow_id"] == wid + captured: dict = {} + uploads = _stub_comfy(monkeypatch, captured) + + # Re-create the previous clip now: enqueue_video_jobs cleared scene 1's + # video_path row (supersede pass) and the paused real worker can't have + # rendered it. The row points at the file the earlier job would produce. + conn = get_db(settings.db_path) + try: + conn.execute( + "UPDATE scenes SET video_path = ? WHERE order_index = 1 AND project_id = ?", + (clip, pid), + ) + conn.commit() + finally: + conn.close() + + outputs = asyncio.run(queue_worker._run_job(job)) + assert len(outputs) == 1 + # The resolved local path reached prepare_media_inputs, which uploaded it. + assert uploads == [clip] + # ...and the video node now carries the uploaded (Comfy-side) file name. + assert captured["20"]["inputs"]["file"] == f"calliope/{Path(clip).name}" + # The scene's own clip was refreshed by the job output. + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT video_path FROM scenes WHERE id = ?", (scene2["id"],) + ).fetchone() + assert row["video_path"] == outputs[0] + finally: + conn.close() + + +def test_worker_fails_continue_job_without_previous_clip(client, monkeypatch): + pid = _mk_project(client, "Worker Missing") + _add_scene(client, pid, 1) + scene2 = _add_scene(client, pid, 2) + _set_chain(client, pid, scene2["id"], True) + conn = get_db(settings.db_path) + try: + _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW) + finally: + conn.close() + + asyncio.run(enqueue_video_jobs(pid)) + payloads = _job_payloads(pid) + assert payloads[1].get("continue_source") == {"scene_order_index": 2} + job = _last_job_row(pid) + + # Run only the continue job: its earlier scene has no clip on disk yet, + # so the worker must fail it with a clear message (the loop records it + # via mark_failed + job.failed event). + captured: dict = {} + _stub_comfy(monkeypatch, captured) + with pytest.raises(RuntimeError) as excinfo: + asyncio.run(queue_worker._run_job(job)) + message = str(excinfo.value) + assert "Continue scene 2" in message + assert "previous clip (scene 1) has no video file" in message + assert "generate the earlier clip first" in message + # Nothing reached ComfyUI. + assert captured == {} + + +def test_worker_passes_plain_job_unchanged(client, monkeypatch): + pid = _mk_project(client, "Worker Plain") + _add_scene(client, pid, 1) + conn = get_db(settings.db_path) + try: + wid = _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW) + finally: + conn.close() + + jobs = asyncio.run(enqueue_video_jobs(pid, scene_ids=[_scene_ids(pid)[0]])) + payloads = _job_payloads(pid) + assert len(payloads) == 1 + assert "continue_source" not in payloads[0] + job = _last_job_row(pid) + + captured: dict = {} + _stub_comfy(monkeypatch, captured) + outputs = asyncio.run(queue_worker._run_job(job)) + + assert len(outputs) == 1 + # No video value was injected; the LoadVideo node keeps its empty default. + assert captured["20"]["inputs"]["file"] == "" + assert captured["10"]["inputs"]["text"] # scene prompt was filled + assert job["workflow_id"] == wid