feat: release 1.5.7 - per-clip workflows, runtime budgets, media-path guards

Three reported issues:

#66: the Video stage workflow picker was keyed by scene id, so choosing a
workflow for one clip overwrote every sibling clip. It is now keyed by clip
id, hydrates each clip's persisted choice, autosaves both
clips.workflow_id and form_workflow_id, and Generate One / Generate All
resolve the workflow per clip (a scene can mix image->video and
video->video extend across its clips).

#64: a 30-second ask could produce a 1:51 script - prompts carried no
per-scene scale and the duration rescale could only grow. Prompts now
state the total seconds and a per-scene budget, and the rescale may shrink
(floor 0.5) so over-written boards pull toward the target; content itself
is never edited.

#67: a hand-written directory path (e.g. ComfyUI's input dir) reached
ComfyUI and died as an opaque Errno 21. prepare_media_inputs now rejects
directory / missing local files before queueing with a node-naming error,
and the agent's run_workflow validates media input_values at call time.
Bare Comfy-side names pass untouched.

534 backend tests pass; svelte-check clean.
This commit is contained in:
Benjiyaya
2026-09-24 02:26:47 +08:00
parent 7551ba9d88
commit d2240b9c5a
12 changed files with 453 additions and 43 deletions
+1 -1
View File
@@ -4,4 +4,4 @@
# reads this; pyproject.toml is kept in sync for the build (hatchling dynamic
# version reads this file). PR #47: hard-coded literals drifted twice
# (1.3.2 shipped reporting 1.2.1; 1.4.1's /api/health still said 1.4.0).
__version__ = "1.5.6"
__version__ = "1.5.7"
@@ -817,6 +817,34 @@ async def t_run_workflow(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
extra = {str(k): v for k, v in iv.items()}
inputs = parse_dynamic_inputs(wf_json) if wf_json else []
# Issue #67: reject directory / missing-file paths the model hand-writes
# into media-role inputs (e.g. ComfyUI's .../input dir) at CALL time, not
# as a failed job later. Bare/relative names may resolve on the Comfy side
# and pass; only local-looking absolute/qualified paths are checked.
media_node_ids = {
str(inp["nodeId"])
for inp in inputs
if inp.get("kind") in ("image", "image_url", "audio", "video")
}
for nid in media_node_ids:
v = extra.get(nid)
if not isinstance(v, str) or v.startswith(("http://", "https://")):
continue
p = Path(v)
if p.is_absolute() or "/" in v or "\\" in v:
if p.is_dir():
return {
"ok": False,
"error": f"input_values[{nid}] '{v}' is a directory — pass a media FILE path.",
}
if not p.exists():
return {
"ok": False,
"error": (
f"input_values[{nid}] file not found locally: '{v}'. Reference a "
"project asset path or attach the file in chat instead."
),
}
if args.get("width") is not None:
for inp in inputs:
if input_has_role(inp, "width"):
+24 -10
View File
@@ -16,9 +16,10 @@ SCRIPT_GENERATION_SYSTEM = (
"You are a screenwriter for AI video production. "
"Write a scene-by-scene script that uses the provided characters and locations. "
"A scene is a SCREENPLAY unit — a heading, full action prose, and all dialogue that plays "
"in it — exactly like a produced script. Scenes may be long; a later 'break into shots' "
"pass splits each scene into short renderable clips, so never compress the content to fit "
"a single video generation. "
"in it — exactly like a produced script. A later 'break into shots' pass splits each scene "
"into short renderable clips, so never compress what a scene needs to say — but scale the "
"TOTAL material to the runtime budget given in the user message: a 30-second film needs "
"30 seconds of action and dialogue, not two minutes. "
"Always respond with a single valid JSON object. "
"HARD RULE: the scenes array length must equal required_scene_count from the user message. "
"Returning fewer scenes is a failure. Respect the user's chosen scene count."
@@ -313,6 +314,9 @@ def build_script_messages(
scene_n = max(recommended, int(scene_count)) if scene_count and scene_count > 0 else recommended
# Stretch runtime floor when the user asked for more clips than duration alone implies
secs = max(secs, scene_n * 6)
# Issue #64: the target is a budget, not a floor — give the model a concrete
# per-scene scale to write to so content volume matches the runtime.
per_scene_secs = max(3, round(secs / scene_n))
char_lines = "\n".join(
f"- id={c['id']} {c['name']} ({c.get('role') or ''}): {c.get('appearance') or ''}"
for c in characters
@@ -328,8 +332,10 @@ def build_script_messages(
Title: {title}
Idea: {idea or ''}
Target duration: {target_duration or 'short (~30-60 seconds)'}
Estimated runtime: ~{secs} seconds
Estimated runtime: ~{secs} seconds TOTAL — the finished film must play in about {secs}s
required_scene_count: {scene_n}
Per-scene budget: ~{per_scene_secs} seconds each (sum across scenes ≈ {secs}s) — write
action length and dialogue VOLUME to this scale.
Story beats:
{beat_lines or '(none)'}
@@ -344,9 +350,10 @@ Locations:
1. The JSON field "scenes" MUST contain EXACTLY {scene_n} objects.
2. order_index must run 1, 2, 3, ... {scene_n} with no gaps.
3. Do NOT collapse back to fewer scenes. The user expanded the script to {scene_n} scenes — fill all of them.
4. Spread the full story across all {scene_n} scenes. A scene is a SCREENPLAY unit — it may
run 30–120 seconds when the material needs it (a later pass breaks long scenes into
short renderable clips). NEVER compress or summarize action to make a scene shorter.
4. Spread the full story across all {scene_n} scenes. A scene is a SCREENPLAY unit — long scenes
are fine ONLY when the {secs}s total allows (≈{per_scene_secs}s each). Scale action detail
and the NUMBER of dialogue lines to that per-scene budget; do not write 2 minutes of
material into a {secs}s film. Never drop lines the story needs — write fewer instead.
5. Pace the total toward ~{secs} seconds overall — scenes with lots of dialogue run longer.
=== ACTION (full visible action prose — the fidelity contract) ===
@@ -421,6 +428,8 @@ def build_script_chunk_messages(
continuity — heading style, location, who's on screen — without resending
the whole script."""
secs = estimate_target_seconds(target_duration)
# Issue #64: per-scene budget so chunk content volume matches the runtime.
per_scene_secs = max(3, round(secs / scene_count))
char_lines = "\n".join(
f"- id={c['id']} {c['name']} ({c.get('role') or ''}): {c.get('appearance') or ''}"
for c in characters
@@ -448,7 +457,10 @@ def build_script_chunk_messages(
Title: {title}
Idea: {idea or ''}
Target duration: {target_duration or 'short (~30-60 seconds)'}
Estimated runtime: ~{secs} seconds TOTAL — the finished film must play in about {secs}s
required_scene_count: {scene_count}
Per-scene budget: ~{per_scene_secs} seconds each (sum across the whole script ≈ {secs}s) —
write action length and dialogue VOLUME to this scale.
THIS CHUNK: exactly {chunk_scenes} scenes, order_index {chunk_start} through {last}.
Full script is {scene_count} scenes; other chunks are written separately — do NOT write
scenes outside {chunk_start}..{last}.
@@ -465,9 +477,11 @@ Locations:
=== HARD CONSTRAINTS (non-negotiable) ===
1. The JSON field "scenes" MUST contain EXACTLY {chunk_scenes} objects.
2. order_index must run {chunk_start}, {chunk_start + 1}, ... {last} with no gaps.
3. A scene is a SCREENPLAY unit — it may run 30–120 seconds when the material needs it
(a later pass breaks long scenes into short renderable clips). NEVER compress or
summarize action to make a scene shorter.
3. A scene is a SCREENPLAY unit — long scenes are fine ONLY when the {secs}s total allows
(≈{per_scene_secs}s each). Scale action detail and the NUMBER of dialogue lines to that
per-scene budget; do not write 2 minutes of material into a {secs}s film. Never drop
lines the story needs — write fewer instead. A later pass breaks scenes into renderable
clips, so never compress what a scene needs to SAY.
4. Advance the beat arc across the whole {scene_count}-scene story; this chunk covers
the part that falls at scenes {chunk_start}–{last}.
5. If earlier scenes are listed above, continue them naturally — same characters,
@@ -296,6 +296,11 @@ async def generate_script(
# guess — and the user's target runtime is the total they sum to. Runs
# AFTER all chunks are committed, as a bulk UPDATE over the durable
# board (the rescale is global; the rows were persisted per chunk).
# Issue #64: the scale may go BELOW 1.0 (floor 0.5) so an over-written
# script's scene budgets shrink toward the target too — the old
# max(..., 1.0) treated the target as a floor, and a 30s ask produced a
# 1:51 script. The floor keeps a wildly over-written board from being
# mislabeled more than 2x; content itself is not edited.
if target_seconds:
all_rows = conn.execute(
"SELECT id, action, dialog FROM scenes WHERE project_id = ? ORDER BY order_index",
@@ -307,7 +312,7 @@ async def generate_script(
]
total_est = sum(estimates)
if total_est > 0:
scale = max(target_seconds / total_est, 1.0)
scale = max(target_seconds / total_est, 0.5)
for row, est in zip(all_rows, estimates):
conn.execute(
"UPDATE scenes SET duration_sec = ? WHERE id = ?",
@@ -113,9 +113,31 @@ class ComfyUIClient:
sub = result.get("subfolder") or subfolder
return f"{sub}/{name}" if sub else name
@staticmethod
def _reject_bad_media_path(value: str, node_id: str, class_type: str, field: str) -> None:
"""Fail a job BEFORE queueing when a media input value is unusable.
Issue #67: a directory (e.g. ComfyUI's `.../input`) or a nonexistent
local path previously passed through verbatim and died inside ComfyUI
with an opaque `ValueError: [Errno 21] Is a directory`. Bare/relative
names are legitimate Comfy-side references and are left alone.
"""
path = Path(value)
if path.is_dir():
raise RuntimeError(
f"node {node_id} ({class_type}): {field} value '{value}' is a "
"directory — expected a media FILE path."
)
if not path.exists():
raise RuntimeError(
f"node {node_id} ({class_type}): {field} file not found locally: "
f"'{value}'. Upload the file through the Video stage's reference "
"picker or attach it in chat, then retry."
)
async def prepare_media_inputs(self, workflow: dict[str, Any]) -> dict[str, Any]:
"""Upload local file paths referenced in LoadImage / LoadAudio / LoadVideo nodes."""
for _node_id, node in workflow.items():
for node_id, node in workflow.items():
if not isinstance(node, dict):
continue
class_type = node.get("class_type", "")
@@ -125,8 +147,12 @@ class ComfyUIClient:
if isinstance(image, str) and self._looks_like_local_path(image):
path = Path(image)
if path.exists():
if path.is_dir():
self._reject_bad_media_path(image, str(node_id), class_type, "image")
inputs["image"] = await self.upload_image(path)
node["inputs"] = inputs
else:
self._reject_bad_media_path(image, str(node_id), class_type, "image")
elif class_type in AUDIO_CLASSES:
# VHS_LoadAudio names its widget "audio:" (with colon); stock
# LoadAudio uses "audio". Probe both so the file is uploaded
@@ -140,16 +166,28 @@ class ComfyUIClient:
if isinstance(audio, str) and self._looks_like_local_path(audio):
path = Path(audio)
if path.exists():
if path.is_dir():
self._reject_bad_media_path(
audio, str(node_id), class_type, audio_key
)
inputs[audio_key] = await self.upload_audio(path)
node["inputs"] = inputs
else:
self._reject_bad_media_path(
audio, str(node_id), class_type, audio_key
)
elif class_type in VIDEO_CLASSES:
field = "file" if class_type in VIDEO_FILE_CLASSES else "video"
media = inputs.get(field)
if isinstance(media, str) and self._looks_like_local_path(media):
path = Path(media)
if path.exists():
if path.is_dir():
self._reject_bad_media_path(media, str(node_id), class_type, field)
inputs[field] = await self.upload_video(path)
node["inputs"] = inputs
else:
self._reject_bad_media_path(media, str(node_id), class_type, field)
return workflow
@staticmethod