Merge pull request #31 from benjiyaya/test-pr-25
Video-extend continue flow + clip source modal (1.2.3)
This commit is contained in:
@@ -75,7 +75,7 @@ The app walks a project through four stages — **Story, Assets, Script, Video**
|
||||
- **Story:** describe your idea and **Draft Storyline** — this opens a project-linked chat in the Agents view with the prompt pre-filled, and the agent writes beats, characters, locations, and misc. items. Edit anything by hand before moving on.
|
||||
- **Assets:** each character, location, and item has its own **Image prompt**. Pick a workflow and shared settings (width/height/etc.) at the top, then click Generate per entity to produce reference images on your ComfyUI. Regenerate any single entity without touching the others.
|
||||
- **Script:** **Regenerate Script** also opens a project-linked Agents chat (pre-filled) to rewrite the per-scene script. Scenes link back to the characters and locations from the Story stage.
|
||||
- **Video:** each scene gets a **Generate** button that queues a clip job on ComfyUI with the right prompt and reference images (plus optional video/audio file refs). Import a FirstMotion + NextMotion H3 pair to chain clips: clip 1 starts a motion, clips 2+ continue the last 22 frames and 1s of audio from the previous latent so the export stitch reads as one long take.
|
||||
- **Video:** each scene gets a **Generate** button that queues a clip job on ComfyUI with the right prompt and reference images (plus optional video/audio file refs). Scenes marked **Continue from previous video** in Script extend the previous clip instead of cutting fresh — see [Continue from previous clip (video extend)](#continue-from-previous-clip-video-extend).
|
||||
- **Film view:** once scenes have clips, **Export film** stitches them with ffmpeg: clips are normalized to 1080p at the **majority frame rate of the clips themselves** (24 fps clips export at 24 fps; mixed-rate projects conform to whichever rate most clips use), joined with 0.5s crossfades, and loudness-normalized into one final file.
|
||||
- When everything is done the project is automatically marked **Completed**.
|
||||
|
||||
@@ -124,7 +124,6 @@ Input roles:
|
||||
| `image` | `img` | Generic image input (ordered ref slot — see below) |
|
||||
| `video` | `vid` | Video file input (`LoadVideo`) |
|
||||
| `audio` | `sound`, `sfx` | Audio file input (`LoadAudio`) |
|
||||
| `clipindex` | `clip_index` | H3 Motion Context Primitive INT (`Load` / `Save` in the title) |
|
||||
| `seed` | — | Shared form |
|
||||
| `duration` | `dur`, `length`, `seconds` | Scene duration (video jobs) |
|
||||
|
||||
@@ -149,6 +148,22 @@ For multi-reference workflows, generic `(Input:image)` inputs are filled in **no
|
||||
- **Ref 1 / Ref 2 — leave them on "Choose asset…"** to auto-fill from the scene's characters (in scene order) then the location, with `<Subject N>` numbering matched to those slots. Picking an asset manually overrides just that slot (and you take over subject numbering for it).
|
||||
- **Duration** auto-fills from the scene's estimated duration; edit it only when you want a different clip length.
|
||||
|
||||
### Continue from previous clip (video extend)
|
||||
|
||||
Long takes don't have to be one giant generation. Mark a scene **Continue from previous video** in the **Script** stage and instead of cutting a fresh clip, it extends the previous scene's clip as real continuation footage (the first scene can't use the toggle).
|
||||
|
||||
The **Video** stage enforces one requirement: the scene's workflow must have an input tagged `(Input:video)` (a `LoadVideo` node). Continue scenes on a workflow without one have Generate disabled with a warning.
|
||||
|
||||
When the workflow qualifies, a **clip source picker** appears on the continue scene:
|
||||
|
||||
- **Auto** (default) — the previous scene's clip is used, resolved when the job actually runs.
|
||||
- **Upload file** — extend from any video you provide (a Playground upload).
|
||||
- **From timeline** — pick a specific earlier scene's clip explicitly.
|
||||
|
||||
Auto is safe even when scenes are queued in one batch: Calliope's queue renders one job at a time, so by the time a continue scene runs, the scene before it has already rendered and its clip is picked up automatically.
|
||||
|
||||
The workflow pattern (per [kat3ri/ComfyUI-MiniMax-H3-Extend](https://github.com/kat3ri/ComfyUI-MiniMax-H3-Extend)) is a `LoadVideo (Input:video)` node feeding the MiniMax H3 extend patched nodes (`MiniMaxH3EncodeAVPatched` → `MiniMaxH3VideoExtendPatched`) with the `(Output:video)` node at the end. Recommended starting settings from that repo: `context_frames` **2**, `ref_spacing` **1–2**, `ref_decay` **0.3**, `ref_ramp` **3–4** (5–6 if the prior clip had heavy motion).
|
||||
|
||||
### 3. Export the workflow
|
||||
|
||||
In ComfyUI, use **Save (API Format)** — not the regular UI workflow graph format. Calliope only understands API Format JSON.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "calliope"
|
||||
version = "1.2.1"
|
||||
version = "1.2.3"
|
||||
description = "Local-first AI story-to-video studio"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
|
||||
@@ -3,6 +3,8 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.llm import LLMClient
|
||||
@@ -11,11 +13,8 @@ from calliope.agent.prompts import (
|
||||
minimax_h3_ref_fallback,
|
||||
scene_video_prompt,
|
||||
)
|
||||
from calliope.comfyui.motion_context import (
|
||||
classify_motion_role,
|
||||
continued_duration,
|
||||
)
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs
|
||||
from calliope.comfyui.roles import input_has_role
|
||||
from calliope.comfyui.smart_fill import ref_image_slots, smart_fill_inputs
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
@@ -81,6 +80,42 @@ async def _h3_rewrite(scene: dict[str, Any], subjects: list[dict[str, Any]]) ->
|
||||
await client.close()
|
||||
|
||||
|
||||
def _video_input(inputs: list[dict[str, Any]]) -> dict[str, Any] | None:
|
||||
"""First workflow input whose canonical role is ``video``."""
|
||||
for inp in inputs:
|
||||
if input_has_role(inp, "video"):
|
||||
return inp
|
||||
return None
|
||||
|
||||
|
||||
def _previous_clip(
|
||||
conn: sqlite3.Connection,
|
||||
project_id: int,
|
||||
order_index: int,
|
||||
) -> tuple[str | None, bool]:
|
||||
"""Nearest earlier scene's clip path + whether any earlier scene exists.
|
||||
|
||||
Returns ``(path, has_earlier_scene)``; path is None when the clip file does
|
||||
not exist on disk (not yet generated) or there is no earlier scene.
|
||||
"""
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT video_path FROM scenes
|
||||
WHERE project_id = ? AND order_index < ? AND video_path IS NOT NULL
|
||||
ORDER BY order_index DESC LIMIT 1
|
||||
""",
|
||||
(project_id, order_index),
|
||||
).fetchone()
|
||||
has_earlier = conn.execute(
|
||||
"SELECT 1 FROM scenes WHERE project_id = ? AND order_index < ? LIMIT 1",
|
||||
(project_id, order_index),
|
||||
).fetchone() is not None
|
||||
path = row["video_path"] if row else None
|
||||
if path and Path(path).exists():
|
||||
return path, has_earlier
|
||||
return None, has_earlier
|
||||
|
||||
|
||||
def _workflow_json(workflow: dict[str, Any] | None) -> dict[str, Any]:
|
||||
if not workflow:
|
||||
return {}
|
||||
@@ -90,20 +125,6 @@ def _workflow_json(workflow: dict[str, Any] | None) -> dict[str, Any]:
|
||||
return raw or {}
|
||||
|
||||
|
||||
def _motion_pair(
|
||||
workflows: list[dict[str, Any]],
|
||||
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
|
||||
first: dict[str, Any] | None = None
|
||||
nxt: dict[str, Any] | None = None
|
||||
for wf in workflows:
|
||||
role = classify_motion_role(_workflow_json(wf))
|
||||
if role == "first" and first is None:
|
||||
first = wf
|
||||
elif role == "next" and nxt is None:
|
||||
nxt = wf
|
||||
return first, nxt
|
||||
|
||||
|
||||
def _get_workflow(workflow_id: int | None = None) -> dict[str, Any] | None:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
@@ -130,7 +151,6 @@ async def enqueue_video_jobs(
|
||||
scene_ids: list[int] | None = None,
|
||||
workflow_id: int | None = None,
|
||||
input_values_override: dict[str, Any] | None = None,
|
||||
continue_motion: bool | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
await event_bus.publish(
|
||||
"agent.thinking", {"message": "Queuing video jobs…", "project_id": project_id}
|
||||
@@ -146,21 +166,6 @@ async def enqueue_video_jobs(
|
||||
params.extend(scene_ids)
|
||||
query += " ORDER BY order_index"
|
||||
scenes = [row_to_dict(r) for r in conn.execute(query, params).fetchall()]
|
||||
all_scenes = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
]
|
||||
video_wfs = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM workflows WHERE is_enabled = 1 AND kind = 'video' ORDER BY id ASC"
|
||||
).fetchall()
|
||||
]
|
||||
first_wf, next_wf = _motion_pair(video_wfs)
|
||||
batch_ids = {s["id"] for s in scenes}
|
||||
|
||||
for scene in scenes:
|
||||
# Supersede leftover pending jobs so a re-Generate always starts fresh
|
||||
@@ -182,49 +187,12 @@ async def enqueue_video_jobs(
|
||||
# self-deadlocks (sqlite3.OperationalError: database is locked).
|
||||
conn.commit()
|
||||
|
||||
earlier = [s for s in all_scenes if s["order_index"] < scene["order_index"]]
|
||||
prev = earlier[-1] if earlier else None
|
||||
|
||||
prev_ready = False
|
||||
if prev:
|
||||
if prev.get("video_path") or prev["id"] in batch_ids:
|
||||
prev_ready = True
|
||||
else:
|
||||
pending = conn.execute(
|
||||
"""
|
||||
SELECT id FROM jobs
|
||||
WHERE scene_id = ? AND kind = 'video'
|
||||
AND status IN ('pending', 'running')
|
||||
""",
|
||||
(prev["id"],),
|
||||
).fetchone()
|
||||
prev_ready = bool(pending)
|
||||
|
||||
want_continue = bool(prev) and (continue_motion if continue_motion is not None else prev_ready)
|
||||
if want_continue and prev and not prev_ready:
|
||||
raise ValueError(
|
||||
"Continue motion needs the previous clip "
|
||||
f"(scene {prev.get('order_index')}) generated first."
|
||||
)
|
||||
|
||||
wf_id = workflow_id or scene.get("workflow_id")
|
||||
explicit = _get_workflow(wf_id) if wf_id else None
|
||||
explicit_role = classify_motion_role(_workflow_json(explicit)) if explicit else None
|
||||
if first_wf and next_wf and (explicit is None or explicit_role in ("first", "next")):
|
||||
# Pair swap: clip 1 / continue-off → First; clips 2+ → Next.
|
||||
workflow = next_wf if want_continue else first_wf
|
||||
else:
|
||||
workflow = explicit or _get_workflow(wf_id)
|
||||
workflow = _get_workflow(wf_id)
|
||||
|
||||
workflow_json = _workflow_json(workflow)
|
||||
inputs = parse_dynamic_inputs(workflow_json) if workflow_json else []
|
||||
motion_role = classify_motion_role(workflow_json)
|
||||
is_next = motion_role == "next" and want_continue
|
||||
duration = scene.get("duration_sec")
|
||||
if is_next:
|
||||
duration = continued_duration(duration)
|
||||
save_index = max(int(scene.get("order_index") or 1), 1)
|
||||
load_index = max(int(prev["order_index"]), 1) if prev and want_continue else None
|
||||
|
||||
char_rows = conn.execute(
|
||||
"""
|
||||
@@ -268,8 +236,6 @@ async def enqueue_video_jobs(
|
||||
prompt=prompt,
|
||||
ref_images=ref_paths,
|
||||
duration=duration,
|
||||
clip_index_load=load_index,
|
||||
clip_index_save=save_index,
|
||||
extra=input_values_override,
|
||||
)
|
||||
else:
|
||||
@@ -280,20 +246,41 @@ async def enqueue_video_jobs(
|
||||
character_image=char_image,
|
||||
location_image=loc_image,
|
||||
duration=duration,
|
||||
clip_index_load=load_index,
|
||||
clip_index_save=save_index,
|
||||
extra=input_values_override,
|
||||
)
|
||||
payload: dict[str, Any] = {"input_values": values, "prompt": prompt}
|
||||
if scene.get("chain_from_prev"):
|
||||
# Resolved at RUN time by the worker (the previous scene's clip may not
|
||||
# exist yet at enqueue time — e.g. a batch queues all scenes up front).
|
||||
payload["chain_from_prev"] = True
|
||||
payload["scene_order_index"] = scene.get("order_index")
|
||||
# The value the location/first-image ref slot holds right now, so the
|
||||
# worker can find and replace that exact slot whatever the layout.
|
||||
payload["chain_replace_value"] = loc_image
|
||||
payload["continue_motion"] = bool(want_continue and motion_role == "next")
|
||||
video_input = _video_input(inputs)
|
||||
if not video_input:
|
||||
raise ValueError(
|
||||
f"Scene {scene.get('order_index')} is marked continue-from-previous "
|
||||
f"but workflow '{(workflow or {}).get('name') or workflow_id}' has no "
|
||||
"video input — pick a workflow with a (Input:video) node."
|
||||
)
|
||||
video_node_id = str(video_input["nodeId"])
|
||||
if not values.get(video_node_id):
|
||||
# Explicit clip from the form / input_values_override wins.
|
||||
prev_clip, has_earlier = _previous_clip(
|
||||
conn, project_id, scene.get("order_index") or 0
|
||||
)
|
||||
if prev_clip:
|
||||
# Local path: the worker's prepare_media_inputs uploads it
|
||||
# to ComfyUI before queuing (same shape as char/loc refs).
|
||||
values[video_node_id] = prev_clip
|
||||
elif has_earlier:
|
||||
# Previous clip not generated yet (typical when a batch is
|
||||
# queued in one go). The worker resolves it at RUN time —
|
||||
# the queue is concurrency-1, so the earlier scene's clip
|
||||
# will exist by then.
|
||||
payload["continue_source"] = {
|
||||
"scene_order_index": scene.get("order_index"),
|
||||
}
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Scene {scene.get('order_index')} is marked continue-from-previous "
|
||||
"but no previous clip exists yet — generate an earlier clip first "
|
||||
"or upload a video in the Video stage."
|
||||
)
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind="video",
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
"""H3 Motion Context pairing: FirstMotion vs NextMotion, prefix isolation."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
MotionRole = Literal["first", "next"]
|
||||
|
||||
CLASS_SAVE = "MiniMaxH3MotionContextSaveLatent"
|
||||
CLASS_LOAD = "MiniMaxH3MotionContextLoadLatent"
|
||||
CLASS_CONTEXT = "MiniMaxH3MotionContext"
|
||||
CLASS_TRIM = "MiniMaxH3MotionContextTrim"
|
||||
|
||||
# H3 native rate. context_length 22 frames ≈ 0.92s removed by Trim on NextMotion.
|
||||
CONTEXT_LENGTH = 22
|
||||
CONTEXT_FPS = 24.0
|
||||
|
||||
|
||||
def _class_types(workflow: dict[str, Any]) -> set[str]:
|
||||
return {
|
||||
str(node.get("class_type") or "")
|
||||
for node in workflow.values()
|
||||
if isinstance(node, dict)
|
||||
}
|
||||
|
||||
|
||||
def classify_motion_role(workflow: dict[str, Any]) -> MotionRole | None:
|
||||
"""``first`` / ``next`` from live H3 Motion Context class_types, else None."""
|
||||
classes = _class_types(workflow)
|
||||
has_save = CLASS_SAVE in classes
|
||||
has_load = CLASS_LOAD in classes
|
||||
has_ctx = CLASS_CONTEXT in classes
|
||||
if has_load and has_ctx:
|
||||
return "next"
|
||||
if has_save and not has_load:
|
||||
return "first"
|
||||
return None
|
||||
|
||||
|
||||
def motion_prefix(project_id: int) -> tuple[str, str]:
|
||||
"""(save filename_prefix, load latent_path folder) under Comfy output/."""
|
||||
folder = f"calliope/p{int(project_id)}"
|
||||
return f"{folder}/clip", folder
|
||||
|
||||
|
||||
def apply_motion_context(
|
||||
workflow: dict[str, Any],
|
||||
*,
|
||||
project_id: int,
|
||||
continue_motion: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""Rewrite Save/Load paths onto a per-project folder.
|
||||
|
||||
When ``continue_motion`` is false, drop ``context_latent`` so a NextMotion
|
||||
graph can run as a chain start (Load is then unreachable).
|
||||
"""
|
||||
save_prefix, load_folder = motion_prefix(project_id)
|
||||
for node in workflow.values():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
class_type = node.get("class_type") or ""
|
||||
inputs = dict(node.get("inputs") or {})
|
||||
if class_type == CLASS_SAVE:
|
||||
inputs["filename_prefix"] = save_prefix
|
||||
node["inputs"] = inputs
|
||||
elif class_type == CLASS_LOAD:
|
||||
inputs["latent_path"] = load_folder
|
||||
node["inputs"] = inputs
|
||||
elif class_type == CLASS_CONTEXT and not continue_motion:
|
||||
inputs.pop("context_latent", None)
|
||||
node["inputs"] = inputs
|
||||
return workflow
|
||||
|
||||
|
||||
def continued_duration(duration_sec: int | float | None) -> float | None:
|
||||
"""Add the Trim head so delivered length matches the scene duration."""
|
||||
if duration_sec is None:
|
||||
return None
|
||||
return float(duration_sec) + (CONTEXT_LENGTH / CONTEXT_FPS)
|
||||
@@ -21,7 +21,6 @@ INPUT_ROLE_ALIASES: dict[str, frozenset[str]] = {
|
||||
"image": frozenset({"image", "img"}),
|
||||
"video": frozenset({"video", "vid"}),
|
||||
"audio": frozenset({"audio", "sound", "sfx"}),
|
||||
"clipindex": frozenset({"clipindex", "clip_index"}),
|
||||
"seed": frozenset({"seed"}),
|
||||
"duration": frozenset({"duration", "dur", "length", "seconds"}),
|
||||
}
|
||||
|
||||
@@ -43,34 +43,6 @@ def ref_audio_slots(inputs: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return _find_all_by_role(inputs, "audio")
|
||||
|
||||
|
||||
def _clipindex_kind(inp: dict[str, Any]) -> str | None:
|
||||
"""``load`` or ``save`` from the stripped title label. None if unclear."""
|
||||
label = (inp.get("label") or "").lower()
|
||||
if "load" in label:
|
||||
return "load"
|
||||
if "save" in label:
|
||||
return "save"
|
||||
return None
|
||||
|
||||
|
||||
def _fill_clipindex(
|
||||
inputs: list[dict[str, Any]],
|
||||
values: dict[str, Any],
|
||||
clip_index_load: int | None,
|
||||
clip_index_save: int | None,
|
||||
) -> None:
|
||||
"""Write every ``(Input:clipindex)`` primitive. Timeline owns these values."""
|
||||
for inp in _find_all_by_role(inputs, "clipindex"):
|
||||
kind = _clipindex_kind(inp)
|
||||
if kind == "load" and clip_index_load is not None:
|
||||
values[str(inp["nodeId"])] = max(int(clip_index_load), 1)
|
||||
elif kind == "save" and clip_index_save is not None:
|
||||
values[str(inp["nodeId"])] = max(int(clip_index_save), 1)
|
||||
elif kind is None and clip_index_save is not None:
|
||||
# Single untagged clipindex (FirstMotion Save-only) → this clip.
|
||||
values[str(inp["nodeId"])] = max(int(clip_index_save), 1)
|
||||
|
||||
|
||||
def _legacy_prompt_node(inputs: list[dict[str, Any]]) -> dict[str, Any] | None:
|
||||
"""Deprecated: untagged (Input) text nodes — prefer (Input:prompt)."""
|
||||
for inp in inputs:
|
||||
@@ -104,8 +76,6 @@ def smart_fill_inputs(
|
||||
ref_videos: list[str] | None = None,
|
||||
ref_audios: list[str] | None = None,
|
||||
duration: int | float | None = None,
|
||||
clip_index_load: int | None = None,
|
||||
clip_index_save: int | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build valuesByNodeId from workflow dynamic inputs + context.
|
||||
@@ -201,7 +171,7 @@ def smart_fill_inputs(
|
||||
reserved = {
|
||||
str(inp["nodeId"])
|
||||
for inp in inputs
|
||||
if normalize_input_role(inp.get("role")) in ("duration", "clipindex")
|
||||
if normalize_input_role(inp.get("role")) == "duration"
|
||||
}
|
||||
for k, v in extra.items():
|
||||
if v is None:
|
||||
@@ -212,7 +182,4 @@ def smart_fill_inputs(
|
||||
continue
|
||||
values[str(k)] = v
|
||||
|
||||
# Timeline-owned — always overwrite form defaults / extras.
|
||||
_fill_clipindex(inputs, values, clip_index_load, clip_index_save)
|
||||
|
||||
return values
|
||||
|
||||
@@ -201,4 +201,3 @@ class GenerateVideosRequest(BaseModel):
|
||||
scene_ids: list[int] | None = None
|
||||
workflow_id: int | None = None
|
||||
input_values: dict[str, Any] | None = None
|
||||
continue_motion: bool | None = None
|
||||
|
||||
@@ -6,11 +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.motion_context import apply_motion_context
|
||||
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
|
||||
@@ -129,16 +132,11 @@ class QueueWorker:
|
||||
raise RuntimeError("No workflow found for job")
|
||||
|
||||
input_values = payload.get("input_values") or {}
|
||||
if payload.get("chain_from_prev") and kind == "video":
|
||||
input_values = await self._apply_chain_from_prev(
|
||||
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 = apply_motion_context(
|
||||
patched,
|
||||
project_id=project_id,
|
||||
continue_motion=bool(payload.get("continue_motion")),
|
||||
)
|
||||
patched = await client.prepare_media_inputs(patched)
|
||||
prompt_id = await client.queue_prompt(patched)
|
||||
|
||||
@@ -171,112 +169,74 @@ class QueueWorker:
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
async def _apply_chain_from_prev(
|
||||
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]:
|
||||
"""Start this clip from the previous scene's last frame.
|
||||
"""Fill the workflow's video input with the previous scene's clip.
|
||||
|
||||
Runs at job time — in a batch the previous scene has rendered by now even
|
||||
though it had not at enqueue time. Extracts the nearest earlier scene's
|
||||
last frame and swaps it into the slot that held the location/first-image
|
||||
reference (found by value; falls back to the location-role node). If no
|
||||
previous clip exists, the job proceeds with its original refs.
|
||||
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.
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs
|
||||
from calliope.comfyui.roles import normalize_input_role
|
||||
|
||||
project_id = job["project_id"]
|
||||
order_index = payload.get("scene_order_index")
|
||||
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:
|
||||
rows = conn.execute(
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT video_path FROM scenes
|
||||
WHERE project_id = ? AND order_index < ? AND video_path IS NOT NULL
|
||||
ORDER BY order_index DESC
|
||||
SELECT order_index, video_path FROM scenes
|
||||
WHERE project_id = ? AND order_index < ?
|
||||
ORDER BY order_index DESC LIMIT 1
|
||||
""",
|
||||
(project_id, order_index if order_index is not None else 0),
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
from pathlib import Path as _P
|
||||
|
||||
if r["video_path"] and _P(r["video_path"]).exists():
|
||||
prev_clip = r["video_path"]
|
||||
break
|
||||
(project_id, order_index),
|
||||
).fetchone()
|
||||
if row:
|
||||
prev_order = row["order_index"]
|
||||
prev_clip = row["video_path"]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if not prev_clip:
|
||||
await event_bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"project_id": project_id,
|
||||
"message": "Chain-from-previous: no earlier clip yet — using the scene's own refs",
|
||||
},
|
||||
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."
|
||||
)
|
||||
return input_values
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
frame_dir = config.settings.assets_dir / str(project_id) / "chain"
|
||||
frame_dir.mkdir(parents=True, exist_ok=True)
|
||||
frame = frame_dir / f"scene{job.get('scene_id')}_from_prev.png"
|
||||
proc = subprocess.run(
|
||||
["ffmpeg", "-y", "-v", "error", "-sseof", "-0.1", "-i", prev_clip,
|
||||
"-update", "1", "-vframes", "1", str(frame)],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
if proc.returncode != 0 or not frame.exists():
|
||||
await event_bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"project_id": project_id,
|
||||
"message": f"Chain-from-previous: frame extraction failed ({proc.stderr[:120]}) — using original refs",
|
||||
},
|
||||
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."
|
||||
)
|
||||
return input_values
|
||||
|
||||
# Find the slot to replace: the node holding the enqueue-time location value,
|
||||
# else the workflow's location-role input (may be empty when no location is set).
|
||||
replace_value = payload.get("chain_replace_value")
|
||||
target_node: str | None = None
|
||||
if replace_value:
|
||||
for node_id, value in input_values.items():
|
||||
if value == replace_value:
|
||||
target_node = str(node_id)
|
||||
break
|
||||
if target_node is None:
|
||||
for inp in parse_dynamic_inputs(workflow):
|
||||
if normalize_input_role(inp.get("role")) == "location":
|
||||
target_node = str(inp["nodeId"])
|
||||
break
|
||||
if target_node is None:
|
||||
await event_bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"project_id": project_id,
|
||||
"message": "Chain-from-previous: no ref slot found to carry the frame — using original refs",
|
||||
},
|
||||
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."
|
||||
)
|
||||
return input_values
|
||||
|
||||
input_values[target_node] = str(frame)
|
||||
input_values[video_node] = prev_clip
|
||||
await event_bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"project_id": project_id,
|
||||
"message": "Chain-from-previous: starting from the previous clip's last frame",
|
||||
"message": f"Continuing from scene {prev_order} clip",
|
||||
},
|
||||
)
|
||||
return input_values
|
||||
|
||||
@@ -63,7 +63,6 @@ async def generate_videos(
|
||||
scene_ids=body.scene_ids,
|
||||
workflow_id=body.workflow_id,
|
||||
input_values_override=body.input_values,
|
||||
continue_motion=body.continue_motion,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from calliope.comfyui.motion_context import classify_motion_role
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs, parse_dynamic_outputs
|
||||
from calliope.comfyui.profiles import detect_prompt_profile
|
||||
from calliope.config import settings
|
||||
@@ -21,7 +20,6 @@ def _serialize_workflow(row: Any) -> dict[str, Any]:
|
||||
data["input_schema"] = json.loads(data["input_schema"]) if data.get("input_schema") else []
|
||||
data["output_schema"] = json.loads(data["output_schema"]) if data.get("output_schema") else []
|
||||
data["is_enabled"] = bool(data.get("is_enabled"))
|
||||
data["motion_role"] = classify_motion_role(data["workflow_json"])
|
||||
return data
|
||||
|
||||
|
||||
@@ -33,7 +31,6 @@ async def analyze_workflow(payload: WorkflowAnalyze) -> dict[str, Any]:
|
||||
"inputs": inputs,
|
||||
"outputs": outputs,
|
||||
"suggested_profile": detect_prompt_profile(payload.workflow_json),
|
||||
"motion_role": classify_motion_role(payload.workflow_json),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
"""H3 Motion Context pair detect, prefix rewrite, duration bump."""
|
||||
from __future__ import annotations
|
||||
|
||||
from calliope.comfyui.motion_context import (
|
||||
apply_motion_context,
|
||||
classify_motion_role,
|
||||
continued_duration,
|
||||
motion_prefix,
|
||||
)
|
||||
from calliope.comfyui.registry import class_to_input_kind, class_to_patch_field
|
||||
|
||||
|
||||
def test_load_video_kind_and_patch_field():
|
||||
assert class_to_input_kind("LoadVideo") == "video"
|
||||
assert class_to_patch_field("LoadVideo") == "file"
|
||||
assert class_to_patch_field("VHS_LoadVideo") == "video"
|
||||
|
||||
|
||||
def test_classify_first_vs_next():
|
||||
first = {
|
||||
"274": {"class_type": "MiniMaxH3MotionContextSaveLatent", "inputs": {}},
|
||||
"272": {"class_type": "MiniMaxH3ReferenceToVideo", "inputs": {}},
|
||||
}
|
||||
nxt = {
|
||||
"274": {"class_type": "MiniMaxH3MotionContextSaveLatent", "inputs": {}},
|
||||
"275": {"class_type": "MiniMaxH3MotionContext", "inputs": {"context_latent": ["277", 0]}},
|
||||
"277": {"class_type": "MiniMaxH3MotionContextLoadLatent", "inputs": {}},
|
||||
"276": {"class_type": "MiniMaxH3MotionContextTrim", "inputs": {}},
|
||||
}
|
||||
plain = {"3": {"class_type": "SaveVideo", "inputs": {}}}
|
||||
assert classify_motion_role(first) == "first"
|
||||
assert classify_motion_role(nxt) == "next"
|
||||
assert classify_motion_role(plain) is None
|
||||
|
||||
|
||||
def test_apply_prefix_and_unwire():
|
||||
wf = {
|
||||
"274": {
|
||||
"class_type": "MiniMaxH3MotionContextSaveLatent",
|
||||
"inputs": {"filename_prefix": "h3_context/clip", "clip_index": 2},
|
||||
},
|
||||
"277": {
|
||||
"class_type": "MiniMaxH3MotionContextLoadLatent",
|
||||
"inputs": {"latent_path": "h3_context", "clip_index": 1},
|
||||
},
|
||||
"275": {
|
||||
"class_type": "MiniMaxH3MotionContext",
|
||||
"inputs": {"context_latent": ["277", 0], "conditioning": ["272", 0]},
|
||||
},
|
||||
}
|
||||
save_prefix, load_folder = motion_prefix(12)
|
||||
started = apply_motion_context(wf, project_id=12, continue_motion=False)
|
||||
assert started["274"]["inputs"]["filename_prefix"] == save_prefix
|
||||
assert started["277"]["inputs"]["latent_path"] == load_folder
|
||||
assert "context_latent" not in started["275"]["inputs"]
|
||||
|
||||
chained = apply_motion_context(
|
||||
{
|
||||
"275": {
|
||||
"class_type": "MiniMaxH3MotionContext",
|
||||
"inputs": {"context_latent": ["277", 0]},
|
||||
},
|
||||
},
|
||||
project_id=12,
|
||||
continue_motion=True,
|
||||
)
|
||||
assert chained["275"]["inputs"]["context_latent"] == ["277", 0]
|
||||
|
||||
|
||||
def test_continued_duration():
|
||||
assert continued_duration(5) == 5 + 22 / 24
|
||||
assert continued_duration(None) is None
|
||||
|
||||
|
||||
def test_prepare_media_inputs_uploads_video(tmp_path):
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from calliope.comfyui.client import ComfyUIClient
|
||||
|
||||
video = tmp_path / "walk.mp4"
|
||||
video.write_bytes(b"fake-mp4")
|
||||
client = ComfyUIClient(base_url="http://comfy.test")
|
||||
client.upload_video = AsyncMock(return_value="calliope/walk.mp4")
|
||||
wf = {
|
||||
"10": {
|
||||
"class_type": "LoadVideo",
|
||||
"inputs": {"file": str(video)},
|
||||
}
|
||||
}
|
||||
try:
|
||||
out = asyncio.run(client.prepare_media_inputs(wf))
|
||||
assert out["10"]["inputs"]["file"] == "calliope/walk.mp4"
|
||||
client.upload_video.assert_awaited_once()
|
||||
finally:
|
||||
asyncio.run(client.close())
|
||||
|
||||
|
||||
FIRST_MOTION = {
|
||||
"274": {
|
||||
"class_type": "MiniMaxH3MotionContextSaveLatent",
|
||||
"inputs": {"filename_prefix": "h3_context/clip"},
|
||||
},
|
||||
"209": {
|
||||
"class_type": "PrimitiveStringMultiline",
|
||||
"inputs": {"value": ""},
|
||||
"_meta": {"title": "Prompt (Input:prompt)"},
|
||||
},
|
||||
"5": {
|
||||
"class_type": "PrimitiveFloat",
|
||||
"inputs": {"value": 5},
|
||||
"_meta": {"title": "(Input:duration) Duration"},
|
||||
},
|
||||
"282": {
|
||||
"class_type": "PrimitiveInt",
|
||||
"inputs": {"value": 1},
|
||||
"_meta": {"title": "(input:clipindex) Save Motion Context Clip Index"},
|
||||
},
|
||||
}
|
||||
|
||||
NEXT_MOTION = {
|
||||
**FIRST_MOTION,
|
||||
"275": {
|
||||
"class_type": "MiniMaxH3MotionContext",
|
||||
"inputs": {"context_latent": ["277", 0]},
|
||||
},
|
||||
"277": {"class_type": "MiniMaxH3MotionContextLoadLatent", "inputs": {}},
|
||||
"276": {"class_type": "MiniMaxH3MotionContextTrim", "inputs": {}},
|
||||
"281": {
|
||||
"class_type": "PrimitiveInt",
|
||||
"inputs": {"value": 1},
|
||||
"_meta": {"title": "(input:clipindex) Load Motion Context Clip Index"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_analyze_and_enqueue_picks_first_then_next(client):
|
||||
first_a = client.post("/api/workflows/analyze", json={"workflow_json": FIRST_MOTION})
|
||||
next_a = client.post("/api/workflows/analyze", json={"workflow_json": NEXT_MOTION})
|
||||
assert first_a.status_code == 200
|
||||
assert first_a.json()["motion_role"] == "first"
|
||||
assert next_a.status_code == 200
|
||||
assert next_a.json()["motion_role"] == "next"
|
||||
|
||||
first = client.post(
|
||||
"/api/workflows",
|
||||
json={
|
||||
"name": "FirstMotion",
|
||||
"kind": "video",
|
||||
"workflow_json": FIRST_MOTION,
|
||||
"prompt_profile": "prose",
|
||||
},
|
||||
).json()
|
||||
nxt = client.post(
|
||||
"/api/workflows",
|
||||
json={
|
||||
"name": "NextMotion",
|
||||
"kind": "video",
|
||||
"workflow_json": NEXT_MOTION,
|
||||
"prompt_profile": "prose",
|
||||
},
|
||||
).json()
|
||||
assert first["motion_role"] == "first"
|
||||
assert nxt["motion_role"] == "next"
|
||||
|
||||
pid = client.post("/api/projects", json={"title": "Hallway"}).json()["id"]
|
||||
s1 = client.post(
|
||||
f"/api/projects/{pid}/scenes",
|
||||
json={"heading": "Walk", "order_index": 1, "duration_sec": 5},
|
||||
).json()
|
||||
s2 = client.post(
|
||||
f"/api/projects/{pid}/scenes",
|
||||
json={"heading": "Door", "order_index": 2, "duration_sec": 5},
|
||||
).json()
|
||||
|
||||
client.post("/api/jobs/pause")
|
||||
try:
|
||||
r = client.post(
|
||||
f"/api/jobs/projects/{pid}/generate-videos",
|
||||
json={"scene_ids": [s1["id"], s2["id"]]},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
jobs = r.json()["jobs"]
|
||||
assert len(jobs) == 2
|
||||
j1, j2 = jobs
|
||||
assert j1["workflow_id"] == first["id"]
|
||||
assert j1["payload"]["continue_motion"] is False
|
||||
assert j1["payload"]["input_values"]["282"] == 1
|
||||
assert j1["payload"]["input_values"]["5"] == 5
|
||||
|
||||
assert j2["workflow_id"] == nxt["id"]
|
||||
assert j2["payload"]["continue_motion"] is True
|
||||
assert j2["payload"]["input_values"]["281"] == 1
|
||||
assert j2["payload"]["input_values"]["282"] == 2
|
||||
assert j2["payload"]["input_values"]["5"] == 5 + 22 / 24
|
||||
finally:
|
||||
client.post("/api/jobs/resume")
|
||||
|
||||
|
||||
def test_continue_motion_fails_without_previous_clip(client):
|
||||
client.post(
|
||||
"/api/workflows",
|
||||
json={
|
||||
"name": "FirstMotion",
|
||||
"kind": "video",
|
||||
"workflow_json": FIRST_MOTION,
|
||||
"prompt_profile": "prose",
|
||||
},
|
||||
)
|
||||
client.post(
|
||||
"/api/workflows",
|
||||
json={
|
||||
"name": "NextMotion",
|
||||
"kind": "video",
|
||||
"workflow_json": NEXT_MOTION,
|
||||
"prompt_profile": "prose",
|
||||
},
|
||||
)
|
||||
pid = client.post("/api/projects", json={"title": "No prev"}).json()["id"]
|
||||
client.post(
|
||||
f"/api/projects/{pid}/scenes",
|
||||
json={"heading": "One", "order_index": 1, "duration_sec": 5},
|
||||
)
|
||||
s2 = client.post(
|
||||
f"/api/projects/{pid}/scenes",
|
||||
json={"heading": "Two", "order_index": 2, "duration_sec": 5},
|
||||
).json()
|
||||
|
||||
client.post("/api/jobs/pause")
|
||||
try:
|
||||
r = client.post(
|
||||
f"/api/jobs/projects/{pid}/generate-videos",
|
||||
json={"scene_ids": [s2["id"]], "continue_motion": True},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "previous clip" in r.json()["detail"].lower()
|
||||
finally:
|
||||
client.post("/api/jobs/resume")
|
||||
@@ -128,40 +128,3 @@ def test_video_and_audio_roles():
|
||||
)
|
||||
assert values["10"] == "/tmp/walk.mp4"
|
||||
assert values["11"] == "/tmp/bed.mp3"
|
||||
|
||||
|
||||
def test_clipindex_load_vs_save_by_label():
|
||||
workflow = {
|
||||
"281": {
|
||||
"inputs": {"value": 1},
|
||||
"class_type": "PrimitiveInt",
|
||||
"_meta": {"title": "(input:clipindex) Load Motion Context Clip Index"},
|
||||
},
|
||||
"282": {
|
||||
"inputs": {"value": 2},
|
||||
"class_type": "PrimitiveInt",
|
||||
"_meta": {"title": "(input:clipindex) Save Motion Context Clip Index"},
|
||||
},
|
||||
}
|
||||
inputs = parse_dynamic_inputs(workflow)
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
clip_index_load=3,
|
||||
clip_index_save=4,
|
||||
extra={"281": 1, "282": 2},
|
||||
)
|
||||
assert values["281"] == 3
|
||||
assert values["282"] == 4
|
||||
|
||||
|
||||
def test_clipindex_never_zero():
|
||||
workflow = {
|
||||
"282": {
|
||||
"inputs": {"value": 2},
|
||||
"class_type": "PrimitiveInt",
|
||||
"_meta": {"title": "(input:clipindex) Save Motion Context Clip Index"},
|
||||
},
|
||||
}
|
||||
inputs = parse_dynamic_inputs(workflow)
|
||||
values = smart_fill_inputs(inputs, clip_index_save=0)
|
||||
assert values["282"] == 1
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
"""Continue-from-previous scenes: enqueue-time video validation + source resolution."""
|
||||
from __future__ import annotations
|
||||
|
||||
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 = {
|
||||
"10": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": ""},
|
||||
"_meta": {"title": "Main Prompt (Input:prompt)"},
|
||||
},
|
||||
"20": {
|
||||
"class_type": "LoadVideo",
|
||||
"inputs": {"file": ""},
|
||||
"_meta": {"title": "Previous Clip (Input:video)"},
|
||||
},
|
||||
}
|
||||
|
||||
# Same but the video slot is missing entirely — must be rejected at enqueue.
|
||||
NO_VIDEO_WORKFLOW = {
|
||||
"10": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": ""},
|
||||
"_meta": {"title": "Main Prompt (Input:prompt)"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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 _set_chain(client, pid: int, scene_id: int, on: bool) -> None:
|
||||
r = client.patch(
|
||||
f"/api/projects/{pid}/scenes/{scene_id}", json={"chain_from_prev": on}
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def _insert_workflow(conn, name: str, wf_json: dict) -> int:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema, is_enabled)
|
||||
VALUES (?, 'video', ?, '[]', '[]', 1)
|
||||
""",
|
||||
(name, json.dumps(wf_json)),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
|
||||
|
||||
def _job_payloads(pid: int) -> list[dict]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT payload_json FROM jobs WHERE project_id = ? AND kind = 'video' "
|
||||
"ORDER BY id",
|
||||
(pid,),
|
||||
).fetchall()
|
||||
return [json.loads(r["payload_json"]) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _touch_clip(name: str) -> str:
|
||||
root = Path(settings.assets_dir)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
path = root / name
|
||||
path.write_bytes(b"mp4-placeholder")
|
||||
return str(path)
|
||||
|
||||
|
||||
def test_continue_scene_requires_video_input_role(client):
|
||||
pid = _mk_project(client, "No Video WF")
|
||||
_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, "no-video", NO_VIDEO_WORKFLOW)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
try:
|
||||
asyncio.run(enqueue_video_jobs(pid))
|
||||
except ValueError as exc:
|
||||
assert "no video input" in str(exc)
|
||||
assert "(Input:video)" in str(exc)
|
||||
else:
|
||||
raise AssertionError("expected ValueError for workflow without video role")
|
||||
|
||||
# Supersede + video_path clear happened for scene 1 before the failure on
|
||||
# scene 2; the failing scene must not have produced a job.
|
||||
assert len(_job_payloads(pid)) == 1
|
||||
|
||||
|
||||
def test_continue_scene_uses_previous_clip_path(client):
|
||||
pid = _mk_project(client, "Prev Clip")
|
||||
_add_scene(client, pid, 1)
|
||||
scene2 = _add_scene(client, pid, 2)
|
||||
_set_chain(client, pid, scene2["id"], True)
|
||||
clip = _touch_clip("prev-clip.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()
|
||||
|
||||
# Re-generate only the continue scene: scene 1 is not in the batch, so its
|
||||
# clip stays on disk and is injected directly (no worker deferral needed).
|
||||
jobs = asyncio.run(enqueue_video_jobs(pid, scene_ids=[scene2["id"]]))
|
||||
payloads = _job_payloads(pid)
|
||||
assert len(payloads) == 1
|
||||
|
||||
video_values = payloads[0]["input_values"]
|
||||
# Node 20 (Input:video) holds the previous scene's local clip path.
|
||||
assert video_values["20"] == clip
|
||||
assert "continue_source" not in payloads[0]
|
||||
assert jobs[0]["workflow_id"] == wid
|
||||
|
||||
|
||||
def test_continue_scene_defers_to_worker_without_clip(client):
|
||||
pid = _mk_project(client, "Deferred Clip")
|
||||
_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()
|
||||
|
||||
jobs = asyncio.run(enqueue_video_jobs(pid))
|
||||
payloads = _job_payloads(pid)
|
||||
assert len(payloads) == 2
|
||||
assert payloads[1]["continue_source"] == {"scene_order_index": 2}
|
||||
assert "20" not in payloads[1]["input_values"]
|
||||
assert jobs[1]["scene_id"] == scene2["id"]
|
||||
|
||||
|
||||
def test_continue_scene_on_first_scene_raises(client):
|
||||
pid = _mk_project(client, "First Scene")
|
||||
scene1 = _add_scene(client, pid, 1)
|
||||
_set_chain(client, pid, scene1["id"], True)
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
_insert_workflow(conn, "video-wf", VIDEO_WORKFLOW)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
try:
|
||||
asyncio.run(enqueue_video_jobs(pid))
|
||||
except ValueError as exc:
|
||||
assert "no previous clip exists yet" in str(exc)
|
||||
else:
|
||||
raise AssertionError("expected ValueError for continue on first scene")
|
||||
|
||||
# Nothing was enqueued for the failing scene.
|
||||
assert _job_payloads(pid) == []
|
||||
|
||||
|
||||
def test_continue_scene_explicit_value_wins_over_previous(client):
|
||||
pid = _mk_project(client, "Explicit Clip")
|
||||
_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:
|
||||
wid = _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW)
|
||||
finally:
|
||||
conn.close()
|
||||
explicit_clip = _touch_clip("user-upload.mp4")
|
||||
|
||||
jobs = asyncio.run(enqueue_video_jobs(pid, input_values_override={"20": explicit_clip}))
|
||||
payloads = _job_payloads(pid)
|
||||
assert len(payloads) == 2
|
||||
assert payloads[1]["input_values"]["20"] == explicit_clip
|
||||
assert "continue_source" not in payloads[1]
|
||||
assert jobs[1]["workflow_id"] == wid
|
||||
|
||||
|
||||
def test_non_continue_scene_untouched(client):
|
||||
pid = _mk_project(client, "Plain Scenes")
|
||||
_add_scene(client, pid, 1)
|
||||
_add_scene(client, pid, 2)
|
||||
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 len(payloads) == 2
|
||||
for payload in payloads:
|
||||
assert "continue_source" not in payload
|
||||
assert "chain_from_prev" not in payload
|
||||
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
|
||||
Generated
+4036
-4052
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "calliope-web",
|
||||
"version": "1.2.1",
|
||||
"name": "calliope-web",
|
||||
"version": "1.2.3",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
|
||||
@@ -235,7 +235,6 @@ export const workflows = {
|
||||
inputs: ComfyDynamicInput[];
|
||||
outputs: ComfyDynamicOutput[];
|
||||
suggested_profile?: string;
|
||||
motion_role?: 'first' | 'next' | null;
|
||||
}>('/api/workflows/analyze', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ workflow_json }),
|
||||
@@ -275,7 +274,6 @@ export const jobsApi = {
|
||||
scene_ids?: number[];
|
||||
workflow_id?: number;
|
||||
input_values?: Record<string, unknown>;
|
||||
continue_motion?: boolean;
|
||||
} = {},
|
||||
) =>
|
||||
api<{ ok: boolean; jobs: Job[] }>(`/api/jobs/projects/${projectId}/generate-videos`, {
|
||||
|
||||
@@ -49,11 +49,6 @@ export function classifyInput(inp: ComfyDynamicInput): ClassifiedInput {
|
||||
return { input: inp, zone: 'composer', widget: 'negativeTextarea' };
|
||||
}
|
||||
|
||||
// Timeline-owned — filled on enqueue, never a user widget.
|
||||
if (role === 'clipindex') {
|
||||
return { input: inp, zone: 'hidden', widget: 'numberPill' };
|
||||
}
|
||||
|
||||
// --- Media tray ---
|
||||
if (
|
||||
role === 'character' ||
|
||||
|
||||
@@ -29,7 +29,6 @@ const INPUT_ROLE_ALIASES: Record<string, string[]> = {
|
||||
image: ['image', 'img'],
|
||||
video: ['video', 'vid'],
|
||||
audio: ['audio', 'sound', 'sfx'],
|
||||
clipindex: ['clipindex', 'clip_index'],
|
||||
seed: ['seed'],
|
||||
duration: ['duration', 'dur', 'length', 'seconds'],
|
||||
};
|
||||
|
||||
@@ -35,8 +35,6 @@ export interface Workflow {
|
||||
description: string | null;
|
||||
prompt_profile: string;
|
||||
is_enabled: boolean;
|
||||
/** H3 Motion Context pair: FirstMotion vs NextMotion. */
|
||||
motion_role?: 'first' | 'next' | null;
|
||||
}
|
||||
|
||||
export interface Job {
|
||||
|
||||
@@ -48,6 +48,10 @@
|
||||
onSubmit?: () => void;
|
||||
/** Pending state for the Generate button (shows spinner-ish label). */
|
||||
submitting?: boolean;
|
||||
/** Disable the Generate button (e.g. workflow cannot fulfil the scene). */
|
||||
disabled?: boolean;
|
||||
/** Why Generate is disabled — surfaced as the button's title tooltip. */
|
||||
generateDisabledHint?: string;
|
||||
/** Custom label for the Generate button. */
|
||||
generateLabel?: string;
|
||||
}
|
||||
@@ -65,6 +69,8 @@
|
||||
onChange,
|
||||
onSubmit,
|
||||
submitting = false,
|
||||
disabled = false,
|
||||
generateDisabledHint = '',
|
||||
generateLabel = 'Generate',
|
||||
}: Props = $props();
|
||||
|
||||
@@ -355,8 +361,9 @@
|
||||
<button
|
||||
type="button"
|
||||
class="generate-btn"
|
||||
class:disabled={submitting}
|
||||
disabled={submitting}
|
||||
class:disabled={submitting || disabled}
|
||||
disabled={submitting || disabled}
|
||||
title={disabled ? generateDisabledHint : undefined}
|
||||
onclick={() => onSubmit?.()}
|
||||
aria-label="Generate"
|
||||
>
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
type Workflow,
|
||||
} from '$lib/api';
|
||||
import { compactInputValues } from '$lib/comfy/promptInput';
|
||||
import { createUploadManager } from '$lib/comfy/useUpload.svelte';
|
||||
import { normalizeInputRole } from '$lib/comfy/parser';
|
||||
import type { ComfyDynamicInput } from '$lib/comfy/types';
|
||||
import type { AssetOption } from '$lib/assetPicker';
|
||||
import { progressFor } from '$lib/jobProgress';
|
||||
import SafeMedia from './SafeMedia.svelte';
|
||||
@@ -36,8 +39,25 @@
|
||||
let formValues = $state<Record<string, string | number>>({});
|
||||
let selectedWorkflow = $state<Record<number, number>>({});
|
||||
let lastFormScene = $state<number | null>(null);
|
||||
// Clip source for continue scenes, keyed per scene: 'auto' | 'upload' | scene id.
|
||||
let clipSource = $state<Record<number, string>>({});
|
||||
// Hidden file input backing "Upload file" in the video source modal.
|
||||
let videoFileInput = $state<HTMLInputElement | null>(null);
|
||||
const videoUploadMgr = createUploadManager();
|
||||
|
||||
// Per-scene input cache — switching scenes no longer wipes the form.
|
||||
async function onVideoFileChosen(e: Event) {
|
||||
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 path = await videoUploadMgr.uploadSafe(node.nodeId, file);
|
||||
if (path) {
|
||||
formValues = { ...formValues, [node.nodeId]: path };
|
||||
}
|
||||
}
|
||||
|
||||
// Per-scene input cache — switching scenes no longer wipes the form.
|
||||
const formCache = new Map<number, Record<string, string | number>>();
|
||||
|
||||
const scenesQuery = createQuery(
|
||||
@@ -73,8 +93,6 @@
|
||||
queryFn: playgroundApi.listUploads,
|
||||
});
|
||||
|
||||
let continueByScene = $state<Record<number, boolean>>({});
|
||||
|
||||
const scenes = $derived(($scenesQuery.data?.scenes ?? []) as Scene[]);
|
||||
const totalSec = $derived(
|
||||
scenes.reduce((sum, s) => sum + Math.max(s.duration_sec || 5, 1), 0),
|
||||
@@ -139,10 +157,6 @@
|
||||
? videoWorkflows
|
||||
: (($workflowsQuery.data ?? []) as Workflow[]).filter((w) => w.is_enabled),
|
||||
);
|
||||
const motionPairReady = $derived(
|
||||
enabledWorkflows.some((w) => w.motion_role === 'first') &&
|
||||
enabledWorkflows.some((w) => w.motion_role === 'next'),
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (selectedId != null) return;
|
||||
@@ -175,17 +189,23 @@
|
||||
return seed;
|
||||
}
|
||||
|
||||
function previousScene(scene: Scene | null): Scene | null {
|
||||
if (!scene) return null;
|
||||
const earlier = scenes.filter((s) => s.order_index < scene.order_index);
|
||||
return earlier.length ? earlier[earlier.length - 1] : null;
|
||||
function workflowHasVideoInput(wf: Workflow | undefined): boolean {
|
||||
return Boolean(
|
||||
wf?.input_schema?.some((inp) => normalizeInputRole(inp.role ?? null) === 'video'),
|
||||
);
|
||||
}
|
||||
|
||||
function continueMotionFor(scene: Scene): boolean {
|
||||
const prev = previousScene(scene);
|
||||
if (!prev) return false;
|
||||
if (continueByScene[scene.id] !== undefined) return continueByScene[scene.id];
|
||||
return Boolean(prev.video_path);
|
||||
function videoInputNodeFor(wf: Workflow | undefined): ComfyDynamicInput | undefined {
|
||||
return wf?.input_schema?.find((inp) => normalizeInputRole(inp.role ?? null) === 'video');
|
||||
}
|
||||
|
||||
// Timeline source options for a continue scene: any other scene that has
|
||||
// rendered a clip, ordered by timeline position.
|
||||
function timelineClipOptions(current: Scene | null): Scene[] {
|
||||
if (!current) return [];
|
||||
return scenes
|
||||
.filter((s) => s.id !== current.id && s.video_path)
|
||||
.sort((a, b) => a.order_index - b.order_index);
|
||||
}
|
||||
|
||||
const generateOne = createMutation({
|
||||
@@ -196,7 +216,6 @@
|
||||
scene_ids: [sceneId],
|
||||
workflow_id: selectedWorkflow[sceneId] ?? wf?.id,
|
||||
input_values: compactInputValues(formValues),
|
||||
continue_motion: scene ? continueMotionFor(scene) : false,
|
||||
});
|
||||
},
|
||||
onSuccess: async () => {
|
||||
@@ -211,8 +230,8 @@
|
||||
// One POST per scene (the H3 prompt rewrite runs synchronously inside each
|
||||
// request, so a single all-scenes POST could take minutes and time out).
|
||||
// The queue worker then renders them strictly in sequence (concurrency 1).
|
||||
// Do not send continue_motion here: omit it so the backend can treat a
|
||||
// just-queued previous scene as "ready" and pick First/Next correctly.
|
||||
// No per-scene form values here: continue scenes resolve their previous
|
||||
// clip at enqueue or run time on the backend.
|
||||
let batching = $state(false);
|
||||
let batchNote = $state('');
|
||||
|
||||
@@ -316,7 +335,7 @@
|
||||
return `${m}:${r.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// Same compact "3m ago" style as ProjectCard — local copy keeps this stage self-contained.
|
||||
// Same compact "3m ago" style as ProjectCard — local copy keeps this stage self-contained.
|
||||
function relativeTime(iso: string): string {
|
||||
const then = new Date(iso).getTime();
|
||||
if (Number.isNaN(then)) return '';
|
||||
@@ -349,7 +368,7 @@
|
||||
selectedId = id;
|
||||
}
|
||||
|
||||
// Filmstrip click → jump back to the editor with that scene selected.
|
||||
// Filmstrip click → jump back to the editor with that scene selected.
|
||||
function editScene(id: number) {
|
||||
selectedId = id;
|
||||
view = 'edit';
|
||||
@@ -386,7 +405,7 @@
|
||||
? ((exportJob.output_paths ?? []).find((p) => /\.mp4$/i.test(p)) ?? null)
|
||||
: null,
|
||||
);
|
||||
// A clip finished after the export completed → the film no longer matches the timeline.
|
||||
// A clip finished after the export completed → the film no longer matches the timeline.
|
||||
const exportStale = $derived.by(() => {
|
||||
if (exportJob?.status !== 'done' || !exportJob.completed_at) return false;
|
||||
const exportAt = Date.parse(exportJob.completed_at);
|
||||
@@ -468,7 +487,7 @@
|
||||
{#if scenes.length === 0}
|
||||
Build a script first, then cut clips on the timeline.
|
||||
{:else}
|
||||
{doneCount}/{scenes.length} clips done · {formatClock(totalSec)} total
|
||||
{doneCount}/{scenes.length} clips done · {formatClock(totalSec)} total
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
@@ -520,7 +539,7 @@
|
||||
<div class="paused-banner" role="status">
|
||||
<Icon name="alert" size={16} />
|
||||
<StatusChip status="paused" label="Queue paused" />
|
||||
<span class="paused-text">Renders are held — workers sit idle until you resume.</span>
|
||||
<span class="paused-text">Renders are held — workers sit idle until you resume.</span>
|
||||
<span class="paused-action">
|
||||
<Button size="sm" variant="secondary" onclick={resumeQueue}>Resume now</Button>
|
||||
</span>
|
||||
@@ -536,6 +555,20 @@
|
||||
{@const selWf = workflowFor(selected)}
|
||||
{@const selStatus = statusOf(selected)}
|
||||
{@const selPreview = previewPath(selected)}
|
||||
{@const selHasVideoInput = workflowHasVideoInput(selWf)}
|
||||
{@const selVideoNode = videoInputNodeFor(selWf)}
|
||||
{@const selClips = timelineClipOptions(selected)}
|
||||
{@const selChain = Boolean(selected.chain_from_prev)}
|
||||
{@const selSource = clipSource[selected.id] ?? 'auto'}
|
||||
{@const selSourceValid = selSource === 'auto' || selSource === 'upload' || selClips.some((s) => String(s.id) === selSource)}
|
||||
{@const selBlocked = selChain && !selHasVideoInput}
|
||||
<input
|
||||
bind:this={videoFileInput}
|
||||
type="file"
|
||||
class="sr-only-video-file"
|
||||
accept="video/*,.mp4,.webm,.mov,.mkv"
|
||||
onchange={onVideoFileChosen}
|
||||
/>
|
||||
<VideoEditWorkspace
|
||||
{scenes}
|
||||
{selected}
|
||||
@@ -554,12 +587,38 @@
|
||||
{statusOf}
|
||||
{thumbFor}
|
||||
{formatClock}
|
||||
showContinueMotion={motionPairReady && previousScene(selected) != null}
|
||||
continueMotion={continueMotionFor(selected)}
|
||||
chained={continueMotionFor}
|
||||
onContinueChange={(on) => {
|
||||
continueByScene = { ...continueByScene, [selected.id]: on };
|
||||
chained={(scene) => Boolean(scene.chain_from_prev)}
|
||||
generateDisabled={selBlocked}
|
||||
generateDisabledReason={selBlocked
|
||||
? 'This scene continues from the previous video — pick a workflow with a video input'
|
||||
: ''}
|
||||
clipSource={{
|
||||
enabled: selChain && selHasVideoInput && Boolean(selVideoNode),
|
||||
value: selSourceValid ? selSource : 'auto',
|
||||
options: selClips.map((s) => ({
|
||||
id: String(s.id),
|
||||
label: `#${s.order_index} ${s.heading || 'Scene'}`,
|
||||
path: s.video_path ?? undefined,
|
||||
})),
|
||||
}}
|
||||
onClipSourceChange={(val) => {
|
||||
if (val === 'auto') {
|
||||
// Back to Auto: send nothing — the backend resolves the previous clip.
|
||||
const next = { ...clipSource };
|
||||
delete next[selected.id];
|
||||
clipSource = next;
|
||||
if (selVideoNode) formValues = { ...formValues, [selVideoNode.nodeId]: '' };
|
||||
} else if (val === 'upload') {
|
||||
clipSource = { ...clipSource, [selected.id]: 'upload' };
|
||||
} else {
|
||||
clipSource = { ...clipSource, [selected.id]: val };
|
||||
const clip = selClips.find((s) => String(s.id) === val);
|
||||
if (clip?.video_path && selVideoNode) {
|
||||
formValues = { ...formValues, [selVideoNode.nodeId]: clip.video_path };
|
||||
}
|
||||
}
|
||||
}}
|
||||
onClipSourceUpload={() => videoFileInput?.click()}
|
||||
onSelect={selectScene}
|
||||
onStep={step}
|
||||
onWorkflowChange={(id) => {
|
||||
@@ -589,13 +648,13 @@
|
||||
{#if exportStale}
|
||||
<div class="stale-banner" role="status">
|
||||
<Icon name="alert" size={14} />
|
||||
<span>Clips changed since this export — re-export to update.</span>
|
||||
<span>Clips changed since this export — re-export to update.</span>
|
||||
</div>
|
||||
{/if}
|
||||
{:else if exportState === 'active'}
|
||||
<div class="program-slate">
|
||||
<Spinner size="lg" />
|
||||
<h3 class="slate-title">Exporting your film…</h3>
|
||||
<h3 class="slate-title">Exporting your film…</h3>
|
||||
<div class="slate-progress">
|
||||
<ProgressBar
|
||||
value={exportProg?.progress ?? 0}
|
||||
@@ -603,7 +662,7 @@
|
||||
label={exportProg?.message}
|
||||
/>
|
||||
</div>
|
||||
<p class="slate-sub">You can keep editing — export runs in the background.</p>
|
||||
<p class="slate-sub">You can keep editing — export runs in the background.</p>
|
||||
<Button variant="ghost" size="sm" onclick={cancelExport}>Cancel</Button>
|
||||
</div>
|
||||
{:else if exportState === 'failed'}
|
||||
@@ -630,7 +689,7 @@
|
||||
</span>
|
||||
<h3 class="slate-title">Your film isn't exported yet</h3>
|
||||
<p class="slate-sub">
|
||||
{clipsReady} clips · {formatClock(totalSec)} · 0.5s crossfades · loudness matched
|
||||
{clipsReady} clips · {formatClock(totalSec)} · 0.5s crossfades · loudness matched
|
||||
</p>
|
||||
{#if clipsMissing > 0}
|
||||
<p class="slate-warn" role="status">
|
||||
@@ -657,7 +716,7 @@
|
||||
{@const exportUrl = assetUrl(exportPath)}
|
||||
<div class="film-meta">
|
||||
<span class="film-meta-text">
|
||||
{exportClipCount} clips · {formatClock(totalSec)}{#if exportedAgo} · Exported {exportedAgo}{/if}
|
||||
{exportClipCount} clips · {formatClock(totalSec)}{#if exportedAgo} · Exported {exportedAgo}{/if}
|
||||
</span>
|
||||
<div class="film-actions">
|
||||
{#if exportUrl}
|
||||
@@ -686,7 +745,7 @@
|
||||
<button
|
||||
type="button"
|
||||
class="filmstrip-item"
|
||||
title={`${scene.heading || 'Scene'} — edit in timeline`}
|
||||
title={`${scene.heading || 'Scene'} — edit in timeline`}
|
||||
onclick={() => editScene(scene.id)}
|
||||
>
|
||||
{#if thumb?.kind === 'image'}
|
||||
@@ -708,6 +767,18 @@
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.sr-only-video-file {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.queue-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -380,11 +380,11 @@
|
||||
class="chip chip-toggle"
|
||||
class:chip-on={Boolean(scene.chain_from_prev)}
|
||||
disabled={chainPendingId === scene.id}
|
||||
title="When on, this clip's <Picture 1> / first image is the LAST FRAME of the previous scene's clip (resolved when the render actually runs, so batches chain correctly). Replaces the location reference for this scene."
|
||||
onclick={() => toggleChain(scene)}
|
||||
>
|
||||
<Icon name="film" size={12} />
|
||||
{Boolean(scene.chain_from_prev) ? 'Chained from prev clip' : 'Chain from prev clip'}
|
||||
title="This scene's clip continues from a previous video (Extend-style). Requires a workflow with a video input; pick the source clip in the Video stage."
|
||||
onclick={() => toggleChain(scene)}
|
||||
>
|
||||
<Icon name="film" size={12} />
|
||||
{Boolean(scene.chain_from_prev) ? 'Continues from previous video' : 'Continue from previous video'}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -65,6 +65,16 @@
|
||||
wasOpen = now;
|
||||
});
|
||||
|
||||
// The modal instance can be reused across tiles whose kind differs (e.g. a
|
||||
// workflow swap turns an image node into video). If the stored tab is not in
|
||||
// the visible list, the body would render one tab while the header shows
|
||||
// another — clamp it instead.
|
||||
$effect(() => {
|
||||
if (tabs.length > 0 && !tabs.some((t) => t.id === tab)) {
|
||||
tab = tabs[0].id;
|
||||
}
|
||||
});
|
||||
|
||||
const q = $derived(query.trim().toLowerCase());
|
||||
|
||||
const visible = $derived.by(() => {
|
||||
|
||||
@@ -73,11 +73,19 @@
|
||||
|
||||
const isImageKind = $derived(input.kind === 'image' || input.kind === 'image_url');
|
||||
const isVideoKind = $derived(input.kind === 'video');
|
||||
const matchingAssets = $derived(
|
||||
assetOptions.filter(
|
||||
(o) => !o.kind || o.kind === input.kind || (isImageKind && o.kind === 'image'),
|
||||
),
|
||||
);
|
||||
const matchingAssets = $derived.by(() => {
|
||||
// The same path can arrive twice (e.g. a scene clip that was also
|
||||
// uploaded to the playground). Duplicate keys crash the keyed each
|
||||
// in the picker grid, so dedupe by path first.
|
||||
const seen = new Set<string>();
|
||||
return assetOptions.filter((o) => {
|
||||
const match =
|
||||
!o.kind || o.kind === input.kind || (isImageKind && o.kind === 'image');
|
||||
if (!match || seen.has(o.path)) return false;
|
||||
seen.add(o.path);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
const displayLabel = $derived(
|
||||
input.role === 'character'
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
let analyzedInputs = $state<ComfyDynamicInput[]>([]);
|
||||
let analyzedOutputs = $state<ComfyDynamicOutput[]>([]);
|
||||
let analyzed = $state(false);
|
||||
let analyzedMotion = $state<'first' | 'next' | null>(null);
|
||||
let pendingJson = $state<Record<string, unknown> | null>(null);
|
||||
|
||||
let wfName = $state('');
|
||||
@@ -40,7 +39,6 @@
|
||||
analyzed = false;
|
||||
analyzedInputs = [];
|
||||
analyzedOutputs = [];
|
||||
analyzedMotion = null;
|
||||
pendingJson = null;
|
||||
try {
|
||||
const json = JSON.parse(text) as Record<string, unknown>;
|
||||
@@ -48,10 +46,8 @@
|
||||
const result = await workflows.analyze(json);
|
||||
analyzedInputs = result.inputs;
|
||||
analyzedOutputs = result.outputs;
|
||||
analyzedMotion = result.motion_role ?? null;
|
||||
analyzed = true;
|
||||
wfProfile = result.suggested_profile ?? 'prose';
|
||||
if (result.motion_role) wfKind = 'video';
|
||||
if (!wfName.trim() && uploadedFileName) {
|
||||
wfName = uploadedFileName.replace(/\.json$/i, '');
|
||||
}
|
||||
@@ -231,11 +227,6 @@
|
||||
{/if}
|
||||
|
||||
{#if analyzed}
|
||||
{#if analyzedMotion}
|
||||
<p class="muted">
|
||||
Motion chain: {analyzedMotion === 'first' ? 'First motion (clip 1)' : 'Next motion (clips 2+)'}
|
||||
</p>
|
||||
{/if}
|
||||
<div class="io-panel">
|
||||
<div class="io-col">
|
||||
<h4>Detected inputs ({analyzedInputs.length})</h4>
|
||||
@@ -363,11 +354,6 @@
|
||||
{#if wf.prompt_profile === 'minimax_h3_ref'}
|
||||
<span class="kind-badge h3">H3-ref</span>
|
||||
{/if}
|
||||
{#if wf.motion_role === 'first'}
|
||||
<span class="kind-badge h3">First motion</span>
|
||||
{:else if wf.motion_role === 'next'}
|
||||
<span class="kind-badge h3">Next motion</span>
|
||||
{/if}
|
||||
<span class="count">{wf.input_schema?.length ?? 0} inputs</span>
|
||||
<span class="count">{wf.output_schema?.length ?? 0} outputs</span>
|
||||
{#if !wf.is_enabled}<StatusChip status="disabled" label="Disabled" />{/if}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
interface Props {
|
||||
open?: boolean;
|
||||
title?: string;
|
||||
size?: 'md' | 'lg';
|
||||
size?: 'md' | 'lg' | 'xl';
|
||||
dismissible?: boolean;
|
||||
onclose?: () => void;
|
||||
footer?: Snippet;
|
||||
@@ -163,6 +163,9 @@
|
||||
.modal-panel.size-lg {
|
||||
width: min(920px, 100%);
|
||||
}
|
||||
.modal-panel.size-xl {
|
||||
width: min(1180px, 100%);
|
||||
}
|
||||
.modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* Video source picker for continue scenes — Auto (previous clip),
|
||||
* Upload file, or any other scene's clip in the project timeline.
|
||||
* Replaces the cramped native select.
|
||||
*/
|
||||
import { assetUrl } from '$lib/api';
|
||||
import Button from '$lib/components/ui/Button.svelte';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import Modal from '$lib/components/ui/Modal.svelte';
|
||||
|
||||
interface ClipSourceOption {
|
||||
/** Scene id as string, or the 'auto' / 'upload' sentinels. */
|
||||
id: string;
|
||||
label: string;
|
||||
/** Clip path — renders a video thumbnail when present. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open?: boolean;
|
||||
/** Current source: 'auto' | 'upload' | a scene id from options. */
|
||||
value?: string;
|
||||
options?: ClipSourceOption[];
|
||||
/** Picking Auto or a project clip. */
|
||||
onselect: (source: string) => void;
|
||||
/** Picking Upload file — caller opens the file dialog and applies the result. */
|
||||
onupload: () => void;
|
||||
}
|
||||
|
||||
let { open = $bindable(false), value = 'auto', options = [], onselect, onupload }: Props =
|
||||
$props();
|
||||
|
||||
function hideBroken(e: Event) {
|
||||
const el = e.currentTarget as HTMLElement | null;
|
||||
if (el) el.style.display = 'none';
|
||||
}
|
||||
|
||||
function pick(source: string) {
|
||||
onselect(source);
|
||||
open = false;
|
||||
}
|
||||
|
||||
function pickUpload() {
|
||||
onupload();
|
||||
open = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal bind:open title="Video source" size="xl">
|
||||
<div class="sources">
|
||||
<button
|
||||
type="button"
|
||||
class="source-card"
|
||||
class:selected={value === 'auto'}
|
||||
onclick={() => pick('auto')}
|
||||
>
|
||||
<span class="source-icon"><Icon name="sparkle" size={18} /></span>
|
||||
<span class="source-text">
|
||||
<span class="source-name">Auto (previous clip)</span>
|
||||
<span class="source-desc">Continue from the previous scene's clip</span>
|
||||
</span>
|
||||
{#if value === 'auto'}
|
||||
<span class="check"><Icon name="check" size={12} /></span>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="source-card"
|
||||
class:selected={value === 'upload'}
|
||||
onclick={pickUpload}
|
||||
>
|
||||
<span class="source-icon"><Icon name="upload" size={18} /></span>
|
||||
<span class="source-text">
|
||||
<span class="source-name">Upload file</span>
|
||||
<span class="source-desc">Pick a video from your computer</span>
|
||||
</span>
|
||||
{#if value === 'upload'}
|
||||
<span class="check"><Icon name="check" size={12} /></span>
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if options.length > 0}
|
||||
<p class="section-label">Project clips <span class="count">{options.length}</span></p>
|
||||
<div class="grid-wrap">
|
||||
<div class="grid">
|
||||
{#each options as opt (opt.id)}
|
||||
{@const isSelected = value === opt.id}
|
||||
<button
|
||||
type="button"
|
||||
class="clip-card"
|
||||
class:selected={isSelected}
|
||||
onclick={() => pick(opt.id)}
|
||||
title={opt.label}
|
||||
>
|
||||
<div class="thumb">
|
||||
{#if opt.path}
|
||||
<!-- svelte-ignore a11y_media_has_caption -->
|
||||
<video
|
||||
src={assetUrl(opt.path)}
|
||||
muted
|
||||
playsinline
|
||||
preload="metadata"
|
||||
onerror={hideBroken}
|
||||
></video>
|
||||
{:else}
|
||||
<Icon name="film" size={22} />
|
||||
{/if}
|
||||
{#if isSelected}
|
||||
<span class="check"><Icon name="check" size={12} /></span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="name">{opt.label}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="empty">No clips in the project yet. Generate a clip first, or upload a video file.</p>
|
||||
{/if}
|
||||
|
||||
{#snippet footer()}
|
||||
<Button variant="ghost" onclick={() => (open = false)}>Cancel</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
|
||||
<style>
|
||||
.sources {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.source-card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
text-align: left;
|
||||
font: inherit;
|
||||
font-size: 14px;
|
||||
color: var(--text-secondary);
|
||||
background: var(--bg-elevated);
|
||||
border: 1.5px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.source-card:hover {
|
||||
border-color: var(--text-muted);
|
||||
}
|
||||
|
||||
.source-card:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.source-card.selected {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.source-icon {
|
||||
flex-shrink: 0;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.source-card.selected .source-icon {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.source-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.source-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.source-desc {
|
||||
font-size: 12.5px;
|
||||
line-height: 1.4;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.section-label {
|
||||
margin: 16px 0 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.count {
|
||||
margin-left: 4px;
|
||||
font-weight: 500;
|
||||
color: var(--text-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.grid-wrap {
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
max-height: min(52vh, 560px);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.clip-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.thumb {
|
||||
position: relative;
|
||||
aspect-ratio: 16 / 9;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1.5px solid var(--border);
|
||||
background: var(--bg-elevated);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.clip-card:hover .thumb {
|
||||
border-color: var(--text-muted);
|
||||
}
|
||||
|
||||
.clip-card.selected .thumb {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.clip-card:focus-visible .thumb {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.thumb video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.check {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 6px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 9999px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.35;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.clip-card.selected .name {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 32px 8px;
|
||||
text-align: center;
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
</style>
|
||||
@@ -7,7 +7,9 @@
|
||||
import type { Scene, Workflow } from '$lib/api';
|
||||
import OmniComposer from '$lib/components/OmniComposer.svelte';
|
||||
import type { AssetOption } from '$lib/assetPicker';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import ClipMonitor from './ClipMonitor.svelte';
|
||||
import ClipSourceModal from './ClipSourceModal.svelte';
|
||||
import SceneFilmstrip from './SceneFilmstrip.svelte';
|
||||
import SceneScriptDrawer from './SceneScriptDrawer.svelte';
|
||||
|
||||
@@ -18,6 +20,21 @@
|
||||
message?: string;
|
||||
}
|
||||
|
||||
interface ClipSourceOption {
|
||||
/** Scene id as string, or the 'auto' / 'upload' sentinels. */
|
||||
id: string;
|
||||
label: string;
|
||||
/** Clip path — the source modal renders video thumbnails when present. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
interface ClipSourceConfig {
|
||||
/** Only offered when the scene continues from the previous video and the workflow can accept it. */
|
||||
enabled: boolean;
|
||||
value: string;
|
||||
options: ClipSourceOption[];
|
||||
}
|
||||
|
||||
interface Props {
|
||||
scenes: Scene[];
|
||||
selected: Scene;
|
||||
@@ -32,9 +49,14 @@
|
||||
formValues: Record<string, string | number>;
|
||||
assetOptions: AssetOption[];
|
||||
allowUpload?: boolean;
|
||||
showContinueMotion?: boolean;
|
||||
continueMotion?: boolean;
|
||||
onContinueChange?: (on: boolean) => void;
|
||||
/** Disable Generate: scene continues from the previous video but the workflow cannot accept it. */
|
||||
generateDisabled?: boolean;
|
||||
generateDisabledReason?: string;
|
||||
/** Where this continue scene's video input comes from (auto / upload / a timeline clip). */
|
||||
clipSource?: ClipSourceConfig;
|
||||
onClipSourceChange?: (value: string) => void;
|
||||
/** Upload file picked in the source modal — caller opens the file dialog. */
|
||||
onClipSourceUpload?: () => void;
|
||||
chained?: (scene: Scene) => boolean;
|
||||
submitting?: boolean;
|
||||
statusOf: (scene: Scene) => string;
|
||||
@@ -61,9 +83,11 @@
|
||||
formValues = $bindable(),
|
||||
assetOptions,
|
||||
allowUpload = true,
|
||||
showContinueMotion = false,
|
||||
continueMotion = false,
|
||||
onContinueChange,
|
||||
generateDisabled = false,
|
||||
generateDisabledReason = '',
|
||||
clipSource,
|
||||
onClipSourceChange,
|
||||
onClipSourceUpload,
|
||||
chained = () => false,
|
||||
submitting = false,
|
||||
statusOf,
|
||||
@@ -75,6 +99,17 @@
|
||||
onFormChange,
|
||||
onGenerate,
|
||||
}: Props = $props();
|
||||
|
||||
let clipSourceOpen = $state(false);
|
||||
|
||||
/** The label shown on the Video source trigger. */
|
||||
const clipSourceLabel = $derived.by(() => {
|
||||
if (!clipSource?.enabled) return '';
|
||||
const val = clipSource.value;
|
||||
if (val === 'auto') return 'Auto (previous clip)';
|
||||
if (val === 'upload') return 'Upload file';
|
||||
return clipSource.options.find((o) => o.id === val)?.label ?? 'Auto (previous clip)';
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="workspace">
|
||||
@@ -106,35 +141,62 @@
|
||||
|
||||
<div class="composer-dock">
|
||||
{#if workflow}
|
||||
{#if generateDisabled}
|
||||
<div class="continue-warning" role="alert">
|
||||
<Icon name="alert" size={16} />
|
||||
<div class="continue-warning-text">
|
||||
<span class="continue-warning-title">Workflow has no video input</span>
|
||||
<span>
|
||||
This scene continues from the previous video. Switch to a workflow that has a video
|
||||
input (LoadVideo node tagged (Input:video)).
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{:else if clipSource?.enabled}
|
||||
<div class="clip-source-row">
|
||||
<span class="clip-source-label" id="clip-source-label">Video source</span>
|
||||
<button
|
||||
type="button"
|
||||
class="clip-source-trigger"
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={clipSourceOpen}
|
||||
aria-labelledby="clip-source-label clip-source-value"
|
||||
onclick={() => (clipSourceOpen = true)}
|
||||
>
|
||||
<Icon name="film" size={14} />
|
||||
<span id="clip-source-value" class="clip-source-value">{clipSourceLabel}</span>
|
||||
<Icon name="chevron-down" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
<ClipSourceModal
|
||||
bind:open={clipSourceOpen}
|
||||
value={clipSource.value}
|
||||
options={clipSource.options}
|
||||
onselect={(source) => onClipSourceChange?.(source)}
|
||||
onupload={() => onClipSourceUpload?.()}
|
||||
/>
|
||||
{/if}
|
||||
{#if assetOptions.length === 0}
|
||||
<p class="asset-hint">
|
||||
No refs yet. Generate character sheets or environments in Assets, or upload a video/audio
|
||||
file here.
|
||||
</p>
|
||||
{/if}
|
||||
{#if showContinueMotion}
|
||||
<label class="continue-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={continueMotion}
|
||||
onchange={(e) => onContinueChange?.(e.currentTarget.checked)}
|
||||
/>
|
||||
<span>Continue motion from previous clip</span>
|
||||
</label>
|
||||
{/if}
|
||||
<OmniComposer
|
||||
inputs={workflow.input_schema}
|
||||
bind:values={formValues}
|
||||
{workflow}
|
||||
{workflows}
|
||||
onWorkflowChange={onWorkflowChange}
|
||||
{assetOptions}
|
||||
{allowUpload}
|
||||
generateLabel="Generate clip"
|
||||
{submitting}
|
||||
onChange={onFormChange}
|
||||
onSubmit={onGenerate}
|
||||
/>
|
||||
{assetOptions}
|
||||
{allowUpload}
|
||||
generateLabel="Generate clip"
|
||||
{submitting}
|
||||
disabled={generateDisabled}
|
||||
generateDisabledHint={generateDisabledReason}
|
||||
onChange={onFormChange}
|
||||
onSubmit={onGenerate}
|
||||
/>
|
||||
{:else}
|
||||
<div class="no-wf">
|
||||
<p class="empty-title">No video workflow enabled</p>
|
||||
@@ -175,18 +237,81 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.continue-row {
|
||||
.continue-warning {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
margin: 0 0 8px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid color-mix(in srgb, var(--warning) 40%, var(--border));
|
||||
background: color-mix(in srgb, var(--warning) 10%, var(--bg-surface));
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.continue-warning :global(svg) {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.continue-warning-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.continue-warning-title {
|
||||
font-weight: 650;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.clip-source-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.clip-source-label {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.clip-source-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
max-width: 360px;
|
||||
padding: 6px 12px;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.continue-row input {
|
||||
accent-color: var(--accent);
|
||||
.clip-source-trigger:hover {
|
||||
border-color: var(--text-muted);
|
||||
}
|
||||
|
||||
.clip-source-trigger:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.clip-source-trigger :global(svg:last-child) {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.clip-source-value {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.asset-hint {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Calliope changelog — 29 August 2026
|
||||
|
||||
**Per-agent LLMs + clip-native export** update. Development branch `test-pr-25`.
|
||||
**Per-agent LLMs + clip-native export + video-extend continue** update. Released as **v1.2.3**. Development branch `test-pr-25`.
|
||||
|
||||
Full changelog index: [README](./README.md). Previous: [2026-08-24](./2026-08-24.md).
|
||||
|
||||
@@ -37,6 +37,35 @@ Film export no longer forces everything to 30 fps.
|
||||
- The export progress message now reports the rate: **"Exporting film (24 fps)…"**.
|
||||
- Everything else in the pipeline is unchanged: 1080p normalize → 0.5s crossfades → loudness normalize.
|
||||
|
||||
## Video continue: file-based extension (replaces latent chain)
|
||||
|
||||
Long clips now chain through **actual video files**, not ComfyUI latents. The old FirstMotion/NextMotion Motion Context chain is gone.
|
||||
|
||||
Removed:
|
||||
|
||||
- `(Input:clipindex)` role and its `clip_index` aliases — Motion Context Primitive INT nodes are no longer detected or filled.
|
||||
- The FirstMotion/NextMotion pair mechanics: latent Save/Load wiring, the 22-frame Motion Context handoff, the ~0.92s duration trim, and the "First motion" / "Next motion" analyze labels.
|
||||
- Last-frame ffmpeg extraction (`_apply_chain_from_prev`) and the `continue_motion` API field.
|
||||
- `motion_role` no longer appears in workflow analyze.
|
||||
|
||||
Added:
|
||||
|
||||
- **Script stage:** per-scene **Continue from previous video** toggle (`chain_from_prev`; the first scene can't use it).
|
||||
- **Video stage:** continue scenes require a workflow with an `(Input:video)` input — otherwise Generate is disabled with a warning. When valid, a clip source picker offers **Auto** (previous clip, default), **Upload file**, or **From timeline** (explicit earlier clip).
|
||||
- **Enqueue:** resolution order is explicit value → nearest earlier scene's clip → `continue_source` payload for job-time resolution.
|
||||
- **Worker:** `_resolve_continue_source` picks up the nearest earlier scene's clip at run time (safe for batch enqueues — the queue is concurrency-1), writes it into the `(Input:video)` node, and uploads it to ComfyUI. No ffmpeg involved.
|
||||
- **Clip source modal:** the source picker is a full modal, not a cramped dropdown — **Auto (previous clip)** and **Upload file** cards plus a thumbnail grid of **any other scene's clip in the project** (not just earlier ones, not just assets). Picking a clip fills the workflow's video input; Auto defers resolution to the queue.
|
||||
|
||||
Migration:
|
||||
|
||||
- Existing FirstMotion/NextMotion workflows keep working as **plain video workflows** if they have an `(Input:video)` node — mark later scenes "Continue from previous video" and pick the workflow.
|
||||
- Workflows relying on `clipindex`-titled Motion Context nodes lose that auto-fill; re-tag the clip input with `(Input:video)`.
|
||||
- For the H3 extend pattern, target [kat3ri/ComfyUI-MiniMax-H3-Extend](https://github.com/kat3ri/ComfyUI-MiniMax-H3-Extend): `LoadVideo (Input:video)` → MiniMax H3 encode/extend patched nodes → `(Output:video)`.
|
||||
|
||||
## Fixed
|
||||
|
||||
- **"Choose Video" modal could render the wrong tab content** (e.g. the header showing Clips/Uploads while the body said "No character sheets yet"). Two causes fixed: the same file appearing twice in the picker grid (a scene clip that was also uploaded) crashed Svelte's keyed rendering mid-draw — options are now deduped by path; and a tile whose media kind changes could keep a stale active tab — the modal now clamps the tab to the visible list.
|
||||
|
||||
## Housekeeping
|
||||
|
||||
- Added `.gitignore` files inside `calliope-backend/` and `calliope-web/` (venv, caches, SQLite data, node_modules, build output) so each sub-folder is self-protecting in addition to the repo-root rules.
|
||||
@@ -47,4 +76,6 @@ Film export no longer forces everything to 30 fps.
|
||||
- New config knob: `agent_llm_assignments` (role → profile id or null), exposed via `GET/POST /api/settings`.
|
||||
- `POST /api/settings` accepts `agent_llm_assignments` with server-side validation.
|
||||
- Export: `probe()` now returns `fps` (from ffprobe `r_frame_rate`), `parse_rate()` parses rational rates like `24000/1001`, `target_fps()` votes the conform rate, and `build_ffmpeg_cmd(..., fps=...)` takes an optional override.
|
||||
- New `ClipSourceModal.svelte` component backs the video source picker; `Modal.svelte` gained an `xl` size (1180px).
|
||||
- Version bumped to **1.2.3** (`calliope-web/package.json`, `calliope-backend/pyproject.toml`).
|
||||
- Full backend suite: **248 passed**.
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
|
||||
Dated notes for GitHub releases. Newest first.
|
||||
|
||||
- [2026-08-29](./2026-08-29.md) — Model per agent + clip-native export fps
|
||||
- [2026-08-29](./2026-08-29.md) — Model per agent + clip-native export fps + video-extend continue (1.2.3)
|
||||
- [2026-08-24](./2026-08-24.md) — Agent + Assets Management (1.2.1)
|
||||
- [2026-08-23](./2026-08-23.md) — 1.2.0 / 1.2.1 video, H3, picker, release notes
|
||||
|
||||
Reference in New Issue
Block a user