Add tabbed video ref picker, stricter agent HITL, and item attach.

Playground creates a new misc. item instead of overwriting one; item generate jobs persist the image path. Notes in docs/changelogs/2026-08-23.md.
This commit is contained in:
Benjiyaya
2026-08-24 04:29:49 +08:00
parent e87a7d3180
commit 71bed77095
30 changed files with 1584 additions and 350 deletions
+4 -1
View File
@@ -40,6 +40,9 @@ AGENTS.md
start.bat
end.bat
ScreenShots/
docs/
docs/*
!docs/changelogs/
!docs/changelogs/**
prototype/
2026-*.md
!docs/changelogs/*.md
+1 -1
View File
@@ -191,7 +191,7 @@ This project is licensed under the [MIT License](LICENSE)
calliope-backend/ FastAPI backend (Python)
calliope-web/ SvelteKit frontend
example_ComfyUI_workflows/ ready-to-import API-format workflow JSONs
docs/ design notes (wiki source), including ComfyUI HTTP vs MCP
docs/wiki/ design notes (wiki source): ComfyUI HTTP vs MCP, multi-ref workflows
```
The Windows desktop app is built from this repo but not shipped in it — download it from the [Releases](../../releases) page.
@@ -9,9 +9,13 @@ individual plugins.
from __future__ import annotations
import logging
import re
from calliope.agent.harness.plugins import load_all as _load_plugins
from calliope.agent.harness.policy import (
is_confirmation,
is_render_request,
user_allows_render,
)
from calliope.agent.harness.prompts import (
SystemPromptService,
register_builtin_sections,
@@ -27,38 +31,9 @@ from calliope.agent.harness.registry import (
logger = logging.getLogger("calliope.harness")
# Affirmation / destructive-intent cues used to recognise an explicit user
# "yes" (or "replace it" / "start over" request) for the destructive guard.
_CONFIRM_RE = re.compile(
r"\b(yes|yeah|yep|yup|sure|ok|okay|k|confirm(?:ed)?|proceed|"
r"go\s+ahead|do\s+it|please\s+do|overwrite|replace|regenerate|"
r"redo|re-?do|start\s+over|restart|delete|wipe|reset|from\s+scratch|"
r"go\s+for\s+it|fine|sounds\s+good|that'?s\s+fine)\b",
re.IGNORECASE,
)
_NEGATE_RE = re.compile(
r"\b(no|not|don'?t|do\s+not|cancel|stop|never|abort|skip|hold\s+on|wait)\b",
re.IGNORECASE,
)
# Image/video *generation* intent cues, used by the render-approval guard. We
# deliberately avoid a bare "generate" (which would also match "generate the
# story") — only unambiguous render words unlock generation.
_RENDER_REQUEST_RE = re.compile(
r"\b(render\w*|image\w*|video\w*|portrait\w*|sheet\w*|artwork\w*|visual\w*|thumbnail\w*)\b",
re.IGNORECASE,
)
def _is_confirmation(text: str) -> bool:
"""A terse, non-negated message carrying an explicit affirmative cue."""
t = (text or "").strip()
if not t or len(t) > 200:
return False
if _NEGATE_RE.search(t):
return False
return bool(_CONFIRM_RE.search(t))
# Re-exports for tests / older imports.
_is_confirmation = is_confirmation
_is_render_request = is_render_request
def _user_confirmed_replacement(ctx: ToolContext) -> bool:
@@ -66,15 +41,7 @@ def _user_confirmed_replacement(ctx: ToolContext) -> bool:
destructive replace (derived from the event log — no separate state)."""
from calliope.agent.harness import log as session_log
return _is_confirmation(session_log.latest_user_message(ctx.session_id) or "")
def _is_render_request(text: str) -> bool:
"""True when the message explicitly asks for image/video generation."""
t = (text or "").strip()
if not t or _NEGATE_RE.search(t):
return False
return bool(_RENDER_REQUEST_RE.search(t))
return is_confirmation(session_log.latest_user_message(ctx.session_id) or "")
def _render_approval_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> PreExecuteDecision:
@@ -90,10 +57,7 @@ def _render_approval_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> P
"""
if not t.requires_approval:
return allow()
from calliope.agent.harness import log as session_log
latest = session_log.latest_user_message(ctx.session_id) or ""
if _is_render_request(latest) or _is_confirmation(latest):
if user_allows_render(ctx):
return allow()
return deny(
"Image/video generation is human-in-the-loop and needs explicit user approval. "
@@ -146,7 +146,11 @@ def latest_user_message(session_id: int) -> str | None:
except (json.JSONDecodeError, TypeError):
return None
content = data.get("content")
return content.strip() if isinstance(content, str) else None
if not isinstance(content, str):
return None
# Never treat the machine appendix as user intent (kind=image, etc.).
prose = content.split("[Calliope context]", 1)[0].strip()
return prose or None
finally:
conn.close()
@@ -60,6 +60,7 @@ ROLE_TOOLS: dict[str, list[str]] = {
"list_workflows",
"run_workflow",
"enqueue_video_jobs",
"attach_asset",
"list_jobs",
"get_job_status",
"wait_for_jobs",
@@ -84,7 +85,8 @@ Respond with ONLY a JSON object:
Rules:
- The standard EDIT pipeline (story → script → add/update assets text) is swarm work: one task per role, in that order.
- Image/video GENERATION is human-in-the-loop: only include assets/video RENDER tasks (enqueue_asset_jobs / enqueue_video_jobs / run_workflow) when the user explicitly asked to generate. For text-only edits (add/update characters, locations, items, scenes, story, script), schedule the edit task and DO NOT schedule render tasks.
- A tagged-workflow generate ([Calliope context] with workflow_id=) is a SIMPLE request — reply {"mode": "single"} so the main loop can call run_workflow.
- Film clips: video sub-agent must enqueue_video_jobs with orders (#N on Video) or scene_ids from list_scenes — ONLY the clips the user named. Never dump every scene_id. Never add_scene to attach a generated mp4. Orphan jobs (scene_id null) do not show on the Video timeline.
- A tagged workflow ([Calliope context] with workflow_id=) is a SIMPLE request — reply {"mode": "single"}. The main loop may call run_workflow only if the user asked to generate; tagging alone is not permission. Linked-film video still needs scene_id.
- Tasks run in the order you list them. Later tasks can use earlier results.
- Keep task goals concrete and self-contained; each sub-agent sees the project state fresh.
- 2-4 tasks typical. Never more than 6.
@@ -96,11 +98,7 @@ def _scoped_payload(ctx: ToolContext, allowed: list[str]) -> list[dict[str, Any]
out: list[dict[str, Any]] = []
for n in allowed:
t = registry.get(n)
if t is None:
continue
if t.requires_project and ctx.project_id is None:
continue
if t.blind_only and ctx.project_id is not None:
if t is None or not registry._visible(t, ctx):
continue
out.append(
{
@@ -382,8 +380,12 @@ async def _run_sub_agent(
"summary when done — no tool call.\n"
"Image/video generation (enqueue_asset_jobs / enqueue_video_jobs / "
"run_workflow) is human-in-the-loop: only call it when the user "
"explicitly asked to generate. For a [Calliope context] workflow_id=, "
"call run_workflow. For text-only edits, do the edit and stop."
"explicitly asked to generate. A workflow_id= appendix is not "
"permission. There is no MCP run_workflow. Film clips: "
"enqueue_video_jobs with orders (Video #N) or scene_ids from "
"list_scenes — only the clips they named, never the whole timeline. "
"Never add_scene to attach an mp4. For text-only edits, "
"do the edit and stop."
)
hardening = hardening_text()
if hardening:
@@ -57,20 +57,33 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="enqueue_video_jobs",
description=(
"Queue video clip generation for scenes (ComfyUI video jobs with "
"reference images wired automatically). Reference-based "
"workflows need character sheets / location images to EXIST "
"first — check get_workspace (✓img marks) and "
"enqueue_asset_jobs + wait_for_jobs before this. Omit scene_ids "
"to render all scenes."
"Queue video clip generation for SPECIFIC scenes. Users say "
"'#25' / 'scene 25' meaning Video-page order — pass those as "
"orders, or list_scenes.scene_id as scene_ids. NEVER dump every "
"scene_id. NEVER omit the target list (that used to mean 'all' "
"and flooded the queue). Set all_scenes=true ONLY when the user "
"explicitly asked for every clip. More than 3 clips is blocked "
"unless they said all/every/entire."
),
parameters={
"type": "object",
"properties": {
"orders": {
"type": "array",
"items": {"type": "integer"},
"description": (
"Video page clip numbers (#1, #25). Preferred when "
"the user names scenes by #."
),
},
"scene_ids": {
"type": "array",
"items": {"type": "integer"},
"description": "Real scene ids from list_scenes; omit for all",
"description": "Database ids from list_scenes.scene_id — not #N",
},
"all_scenes": {
"type": "boolean",
"description": "True only if the user asked to render every clip",
},
"workflow_id": {
"type": "integer",
@@ -87,13 +100,15 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="run_workflow",
description=(
"Queue a Calliope ComfyUI workflow. Works in sandbox AND linked "
"sessions. Sandbox jobs go to the hidden Playground scratch — "
"do NOT create_project just to generate. Use this when the user "
"message has a [Calliope context] appendix with workflow_id= "
"(from an @workflow mention). Do NOT call list_workflows to "
"guess the id. Call comfy_server_info first. prompt lands on "
"(Input:prompt). "
"Queue a Calliope ComfyUI workflow. Sandbox jobs go to Playground "
"scratch. Linked-film VIDEO clips MUST pass scene_id (from "
"list_scenes) — the worker then writes scenes.video_path. Prefer "
"enqueue_video_jobs for one or more scenes. A video job without "
"scene_id will NOT appear on the Video timeline. "
"Use this when the user message has a [Calliope context] "
"appendix with workflow_id= (from an @workflow mention). Do NOT "
"call list_workflows to guess the id. Call comfy_server_info "
"first. prompt lands on (Input:prompt). "
"width/height fill (Input:width)/(Input:height) by role. "
"attachments are ordered local paths for (Input:image) / "
"(Input:character) slots. Aspect ratio in the user's prose "
@@ -108,6 +123,13 @@ def register(registry: ToolRegistry) -> None:
"type": "integer",
"description": "Calliope workflow id from [Calliope context]",
},
"scene_id": {
"type": "integer",
"description": (
"Required for video on a linked film — real scene id "
"from list_scenes. Omit in sandbox / image generates."
),
},
"prompt": {
"type": "string",
"description": "Text for the (Input:prompt) node",
@@ -211,13 +233,13 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="attach_asset",
description=(
"Add a generated image (from a job_id or a local path) to a "
"project as a character sheet, environment, or misc. item. "
"Works in sandbox — do not create_project just to file an "
"image. Call list_projects first if the user named a film. "
"Pass an existing character_id / location_id / item_id, or "
"a name (matches an existing entity case-insensitively, "
"otherwise creates one). job_id should be the "
"Add a generated file to a project: image as character sheet / "
"environment / misc. item, or a video clip onto an existing "
"scene (target=scene). Works in sandbox — do not create_project "
"just to file a generate. Call list_projects first if the user "
"named a film. For images: character_id / location_id / item_id "
"or a name. For scene clips: scene_id from list_scenes (never "
"add_scene to 'fix' a missing clip). job_id should be the "
"run_workflow / Playground job that produced the file."
),
parameters={
@@ -237,12 +259,16 @@ def register(registry: ToolRegistry) -> None:
},
"target": {
"type": "string",
"enum": ["character_sheet", "location", "item"],
"description": "Where to file the image",
"enum": ["character_sheet", "location", "item", "scene"],
"description": "Where to file the generate",
},
"character_id": {"type": "integer"},
"location_id": {"type": "integer"},
"item_id": {"type": "integer"},
"scene_id": {
"type": "integer",
"description": "Existing scene id when target=scene",
},
"name": {
"type": "string",
"description": "Entity name — updates a match, or creates if none",
@@ -301,18 +327,94 @@ async def t_enqueue_asset_jobs(ctx: ToolContext, args: dict[str, Any]) -> dict[s
return {"jobs": jobs, "count": len(jobs)}
def _int_list(raw: Any) -> list[int]:
out: list[int] = []
for x in raw or []:
try:
out.append(int(x))
except (TypeError, ValueError):
continue
return out
async def t_enqueue_video_jobs(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
from calliope.agent.harness import log as session_log
from calliope.agent.harness.plugins.script import resolve_scene_ref
from calliope.agent.harness.policy import allows_bulk_video_enqueue
from calliope.agent.video_agent import enqueue_video_jobs as _enqueue
scene_ids = _int_list(args.get("scene_ids"))
orders = _int_list(args.get("orders"))
all_scenes = bool(args.get("all_scenes"))
latest = session_log.latest_user_message(ctx.session_id) or ""
resolved: list[int] = []
if orders or scene_ids:
conn = _db()
try:
for sid in scene_ids:
found, err = resolve_scene_ref(conn, ctx.project_id, scene_id=sid)
if err:
return {"ok": False, "error": err}
resolved.append(found)
for order in orders:
found, err = resolve_scene_ref(conn, ctx.project_id, order=order)
if err:
return {"ok": False, "error": err}
resolved.append(found)
finally:
conn.close()
# Preserve order, drop dupes.
seen: set[int] = set()
unique: list[int] = []
for sid in resolved:
if sid not in seen:
seen.add(sid)
unique.append(sid)
resolved = unique
elif all_scenes:
conn = _db()
try:
rows = conn.execute(
"SELECT id FROM scenes WHERE project_id = ? ORDER BY order_index",
(ctx.project_id,),
).fetchall()
resolved = [int(r["id"]) for r in rows]
finally:
conn.close()
else:
return {
"ok": False,
"error": (
"Say which clips: pass orders (Video page #N) or scene_ids "
"from list_scenes. Do not enqueue the whole timeline. "
"all_scenes=true only when the user asked for every clip."
),
}
if not resolved:
return {"ok": False, "error": "No matching scenes to enqueue"}
allowed_bulk = allows_bulk_video_enqueue(latest, len(resolved))
if not allowed_bulk:
return {
"ok": False,
"error": (
f"Blocked: {len(resolved)} clips is a bulk render. Users usually "
"mean the #N they named (2–3 clips). Pass only those orders, or "
"wait until they say all scenes / every clip / the entire film."
),
}
try:
jobs = await _enqueue(
ctx.project_id,
scene_ids=args.get("scene_ids"),
scene_ids=resolved,
workflow_id=args.get("workflow_id"),
)
except ValueError as exc:
return {"ok": False, "error": str(exc)}
return {"jobs": jobs, "count": len(jobs)}
return {"jobs": jobs, "count": len(jobs), "scene_ids": resolved}
_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"}
@@ -385,6 +487,55 @@ async def t_run_workflow(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
finally:
conn.close()
scene_id: int | None = None
raw_scene = args.get("scene_id")
if raw_scene is not None and str(raw_scene).strip() != "":
try:
scene_id = int(raw_scene)
except (TypeError, ValueError):
return {"ok": False, "error": "scene_id must be an integer from list_scenes"}
# Linked-film video must be a scene job. Orphans (scene_id NULL) finish in
# the queue but never write scenes.video_path — the clip is preview-only.
if kind == "video" and ctx.project_id is not None:
if scene_id is None:
return {
"ok": False,
"error": (
"Linked-film video requires scene_id from list_scenes. "
"Prefer enqueue_video_jobs. Do not add_scene to attach a clip."
),
}
conn = _db()
try:
scene = conn.execute(
"SELECT id FROM scenes WHERE id = ? AND project_id = ?",
(scene_id, int(ctx.project_id)),
).fetchone()
finally:
conn.close()
if not scene:
return {"ok": False, "error": f"Scene {scene_id} not found in this project"}
from calliope.agent.video_agent import enqueue_video_jobs as _enqueue
try:
jobs = await _enqueue(
int(ctx.project_id),
scene_ids=[scene_id],
workflow_id=workflow_id,
)
except ValueError as exc:
return {"ok": False, "error": str(exc)}
return {
"jobs": [_sc_job_dict_lite(j) for j in jobs],
"count": len(jobs),
"workflow_id": workflow_id,
"workflow_name": wf_name,
"sandbox": False,
"wired_to_scene": True,
"scene_id": scene_id,
}
raw_paths = [str(p) for p in (args.get("attachments") or []) if p]
safe_paths, path_err = _sandbox_attachment_paths(raw_paths)
if path_err:
@@ -440,6 +591,7 @@ async def t_run_workflow(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
"workflow_id": workflow_id,
"workflow_name": wf_name,
"sandbox": sandbox,
"wired_to_scene": False,
}
@@ -473,8 +625,8 @@ async def t_attach_asset(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
from calliope.routers.playground import PLAYGROUND_STATUS
target = str(args.get("target") or "")
if target not in ("character_sheet", "location", "item"):
return {"ok": False, "error": "target must be character_sheet, location, or item"}
if target not in ("character_sheet", "location", "item", "scene"):
return {"ok": False, "error": "target must be character_sheet, location, item, or scene"}
project_id = args.get("project_id")
if project_id is None:
@@ -571,7 +723,7 @@ async def t_attach_asset(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
row = conn.execute("SELECT * FROM locations WHERE id = ?", (cur.lastrowid,)).fetchone()
entity = row_to_dict(row)
entity["reference_image_path"] = path
else:
elif target == "item":
iid = args.get("item_id")
row = None
if iid is not None:
@@ -599,6 +751,30 @@ async def t_attach_asset(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
row = conn.execute("SELECT * FROM items WHERE id = ?", (cur.lastrowid,)).fetchone()
entity = row_to_dict(row)
entity["reference_image_path"] = path
else:
sid = args.get("scene_id")
if sid is None:
return {"ok": False, "error": "scene_id is required for target=scene — list_scenes, never add_scene"}
row = conn.execute(
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
(int(sid), project_id),
).fetchone()
if not row:
return {"ok": False, "error": f"Scene {sid} not found in this project"}
conn.execute(
"UPDATE scenes SET video_path = ? WHERE id = ?",
(path, int(sid)),
)
job_id = args.get("job_id")
if job_id is not None:
conn.execute(
"UPDATE jobs SET scene_id = ? WHERE id = ? AND scene_id IS NULL",
(int(sid), int(job_id)),
)
created = False
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (int(sid),)).fetchone()
entity = row_to_dict(row)
entity["video_path"] = path
conn.execute(
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
@@ -642,6 +818,7 @@ def _sc_job_dict_lite(job: dict[str, Any]) -> dict[str, Any]:
"kind": job["kind"],
"status": job["status"],
"scene_id": job.get("scene_id"),
"wired_to_scene": bool(job.get("scene_id")),
"error": job.get("error"),
"output_paths": paths or [],
}
@@ -12,6 +12,58 @@ from calliope.agent.harness.registry import (
from calliope.db import row_to_dict
def annotate_scene_row(s: dict[str, Any]) -> dict[str, Any]:
"""Label user-facing clip # vs database scene_id. #N on Video is order."""
oid = int(s["id"])
order = int(s.get("order_index") or 0)
s["scene_id"] = oid
s["order"] = order
s["clip"] = f"#{order}"
return s
def resolve_scene_ref(
conn,
project_id: int,
*,
scene_id: Any = None,
order: Any = None,
) -> tuple[int | None, str | None]:
"""Resolve one scene. `order` is the Video page #N; `scene_id` is the DB id."""
if scene_id is not None and str(scene_id).strip() != "":
try:
sid = int(scene_id)
except (TypeError, ValueError):
return None, "scene_id must be an integer from list_scenes"
row = conn.execute(
"SELECT id FROM scenes WHERE id = ? AND project_id = ?",
(sid, project_id),
).fetchone()
if not row:
return None, (
f"Scene {sid} not found in this project. "
"That number is not the #N on the Video page — list_scenes "
"and use scene_id or order."
)
return int(row["id"]), None
if order is not None and str(order).strip() != "":
try:
num = int(order)
except (TypeError, ValueError):
return None, "order must be the clip number from the Video page (#1, #25)"
row = conn.execute(
"SELECT id FROM scenes WHERE project_id = ? AND order_index = ?",
(project_id, num),
).fetchone()
if not row:
return None, (
f"No clip #{num} in this project. "
"Users say #N for order (list_scenes.order / clip), not scene_id."
)
return int(row["id"]), None
return None, "Pass scene_id (database id) or order (Video page #N)"
def register(registry: ToolRegistry) -> None:
registry.register(
ToolDefinition(
@@ -41,10 +93,26 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="list_scenes",
description=(
"List the linked project's scenes in order with their real ids, "
"cast, and location — the source of truth for scene_id arguments."
"List or search scenes. EACH row has scene_id (database id) AND "
"order / clip (#N on the Video page). Users say '#25' or "
"'scene 25' meaning order=25 — NEVER treat that as scene_id. "
"Optional query (heading/action text) or orders (clip numbers) "
"to search without dumping the whole timeline."
),
parameters={"type": "object", "properties": {}},
parameters={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Optional heading/action search (user words)",
},
"orders": {
"type": "array",
"items": {"type": "integer"},
"description": "Video page clip numbers (#1, #25) — not scene_id",
},
},
},
executor=t_list_scenes,
category="script",
)
@@ -53,15 +121,20 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="update_scene",
description=(
"Update one existing scene. scene_id must come from list_scenes "
"or get_workspace — never guess it. Pass only the fields to change."
"Update one existing scene. Identify it with scene_id "
"(list_scenes.scene_id) OR order (Video page #N). Never guess. "
"Pass only the fields to change."
),
parameters={
"type": "object",
"properties": {
"scene_id": {
"type": "integer",
"description": "Real id from list_scenes/get_workspace",
"description": "Database id from list_scenes — not the #N on Video",
},
"order": {
"type": "integer",
"description": "Clip number from the Video page (#25 → 25)",
},
"heading": {"type": "string"},
"action": {"type": "string"},
@@ -74,7 +147,6 @@ def register(registry: ToolRegistry) -> None:
"description": "Replace the scene's character cast",
},
},
"required": ["scene_id"],
},
executor=t_update_scene,
category="script",
@@ -115,14 +187,21 @@ def register(registry: ToolRegistry) -> None:
ToolDefinition(
name="delete_scene",
description=(
"Delete a scene permanently. scene_id must come from list_scenes. "
"Prefer update_scene for content changes; use this only when the "
"user wants the scene gone."
"Delete a scene permanently. Identify with scene_id or order "
"(Video page #N). Prefer update_scene for content changes."
),
parameters={
"type": "object",
"properties": {"scene_id": {"type": "integer"}},
"required": ["scene_id"],
"properties": {
"scene_id": {
"type": "integer",
"description": "Database id from list_scenes",
},
"order": {
"type": "integer",
"description": "Clip number from the Video page (#N)",
},
},
},
executor=t_delete_scene,
category="script",
@@ -170,7 +249,25 @@ async def t_list_scenes(ctx: ToolContext, args: dict[str, Any]) -> list[dict[str
rows = conn.execute(
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index", (ctx.project_id,)
).fetchall()
scenes = [row_to_dict(r) for r in rows]
scenes = [annotate_scene_row(row_to_dict(r)) for r in rows]
raw_orders = args.get("orders") or []
if raw_orders:
want = set()
for x in raw_orders:
try:
want.add(int(x))
except (TypeError, ValueError):
continue
scenes = [s for s in scenes if int(s.get("order") or 0) in want]
query = str(args.get("query") or "").strip().lower()
if query:
scenes = [
s
for s in scenes
if query in (s.get("heading") or "").lower()
or query in (s.get("action") or "").lower()
or query in (s.get("dialog") or "").lower()
]
for s in scenes:
chars = conn.execute(
"""
@@ -189,7 +286,14 @@ async def t_list_scenes(ctx: ToolContext, args: dict[str, Any]) -> list[dict[str
async def t_update_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
conn = _db()
try:
scene_id = int(args["scene_id"])
scene_id, err = resolve_scene_ref(
conn,
ctx.project_id,
scene_id=args.get("scene_id"),
order=args.get("order"),
)
if err:
return {"ok": False, "error": err}
existing = conn.execute(
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
(scene_id, ctx.project_id),
@@ -248,7 +352,7 @@ async def t_update_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
(scene_id, ctx.project_id),
).fetchone()
return {"scene": row_to_dict(row)}
return {"scene": annotate_scene_row(row_to_dict(row))}
finally:
conn.close()
@@ -319,7 +423,7 @@ async def t_add_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
)
conn.commit()
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone()
return {"scene": row_to_dict(row)}
return {"scene": annotate_scene_row(row_to_dict(row))}
finally:
conn.close()
@@ -327,7 +431,14 @@ async def t_add_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
async def t_delete_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
conn = _db()
try:
scene_id = int(args["scene_id"])
scene_id, err = resolve_scene_ref(
conn,
ctx.project_id,
scene_id=args.get("scene_id"),
order=args.get("order"),
)
if err:
return {"ok": False, "error": err}
cur = conn.execute(
"DELETE FROM scenes WHERE id = ? AND project_id = ?", (scene_id, ctx.project_id)
)
@@ -356,6 +467,6 @@ async def t_reorder_scenes(ctx: ToolContext, args: dict[str, Any]) -> dict[str,
"SELECT id, order_index, heading FROM scenes WHERE project_id = ? ORDER BY order_index",
(ctx.project_id,),
).fetchall()
return {"scenes": [row_to_dict(r) for r in rows]}
return {"scenes": [annotate_scene_row(row_to_dict(r)) for r in rows]}
finally:
conn.close()
@@ -0,0 +1,91 @@
"""HITL / confirmation policy — used by guards and tool-payload filtering.
Kept out of ``__init__`` / ``registry`` so those modules can import this
without a cycle. Intent is always derived from the latest user prose, never
from the machine ``[Calliope context]`` appendix.
"""
from __future__ import annotations
import re
from calliope.agent.harness.registry import ToolContext
# Affirmation / destructive-intent cues for an explicit user "yes"
# (or "replace it" / "start over") for the destructive guard.
_CONFIRM_RE = re.compile(
r"\b(yes|yeah|yep|yup|sure|ok|okay|k|confirm(?:ed)?|proceed|"
r"go\s+ahead|do\s+it|please\s+do|overwrite|replace|regenerate|"
r"redo|re-?do|start\s+over|restart|delete|wipe|reset|from\s+scratch|"
r"go\s+for\s+it|fine|sounds\s+good|that'?s\s+fine)\b",
re.IGNORECASE,
)
_NEGATE_RE = re.compile(
r"\b(no|not|don'?t|do\s+not|cancel|stop|never|abort|skip|hold\s+on|wait)\b",
re.IGNORECASE,
)
# Image/video *generation* intent. A bare "generate" is skipped on purpose
# (it would also match "generate the story").
_RENDER_REQUEST_RE = re.compile(
r"\b(render\w*|image\w*|video\w*|portrait\w*|sheet\w*|artwork\w*|visual\w*|thumbnail\w*)\b",
re.IGNORECASE,
)
_APPENDIX_MARK = "[Calliope context]"
def user_prose(text: str) -> str:
"""Visible user words only — drop a trailing Calliope context appendix."""
raw = text or ""
if _APPENDIX_MARK in raw:
raw = raw.split(_APPENDIX_MARK, 1)[0]
return raw.strip()
def is_confirmation(text: str) -> bool:
"""A terse, non-negated message carrying an explicit affirmative cue."""
t = user_prose(text)
if not t or len(t) > 200:
return False
if _NEGATE_RE.search(t):
return False
return bool(_CONFIRM_RE.search(t))
def is_render_request(text: str) -> bool:
"""True when the message explicitly asks for image/video generation."""
t = user_prose(text)
if not t or _NEGATE_RE.search(t):
return False
return bool(_RENDER_REQUEST_RE.search(t))
# More than this many clips needs an explicit "all scenes / every clip" in
# the latest user prose. A bare "yes" after a 2-clip offer must not enqueue
# the whole timeline (the model has dumped every scene_id before).
BULK_ENQUEUE_LIMIT = 3
_BULK_VIDEO_RE = re.compile(
r"\b("
r"all(\s+the)?\s+(scenes?|clips?|videos?|shots?)"
r"|every\s+(scene|clip|shot)"
r"|entire\s+(film|project|script|timeline)"
r"|whole\s+(film|project|script)"
r"|all\s+remaining"
r")\b",
re.IGNORECASE,
)
def allows_bulk_video_enqueue(text: str, count: int) -> bool:
"""True when `count` clips is a small targeted batch, or the user asked for all."""
if count <= BULK_ENQUEUE_LIMIT:
return True
return bool(_BULK_VIDEO_RE.search(user_prose(text)))
def user_allows_render(ctx: ToolContext) -> bool:
"""Latest user prose asks to generate, or tersely confirms an offer."""
from calliope.agent.harness import log as session_log
latest = session_log.latest_user_message(ctx.session_id) or ""
return is_render_request(latest) or is_confirmation(latest)
@@ -83,9 +83,10 @@ def _mode_text(ctx: ToolContext) -> str:
return (
"SESSION MODE: SANDBOX — no project is linked yet.\n"
"- You can brainstorm and discuss ideas freely.\n"
"- Tagged @workflow generates: call run_workflow directly. Do NOT "
"create_project or link_project for an image/video generate. The "
"session stays sandbox; jobs land on the hidden Playground scratch.\n"
"- Tagged @workflow + the user asked to generate/render: call "
"run_workflow (Playground scratch). Do NOT create_project or "
"link_project just for an image. If they only tagged a workflow "
"while drafting text, do NOT call run_workflow — offer and wait.\n"
"- To file a generated image onto an existing film: list_projects, "
"then attach_asset with that project_id + job_id (or path) and a "
"target (character_sheet / location / item). Do not create_project "
@@ -104,8 +105,17 @@ def _mode_text(ctx: ToolContext) -> str:
"project id.\n"
"- scene_id / character_id / location_id / job_id / workflow_id are "
"REAL numeric ids from tool results — never invent them.\n"
"- Video page #N is order (clip number), NOT scene_id. list_scenes "
"returns clip=#N, order, and scene_id. Users say 'scene 25' / '#25' "
"meaning order=25 — pass enqueue_video_jobs.orders=[25] or "
"update_scene.order=25. Never treat a # as a database id.\n"
"- To file a generated image onto a character, environment, or item: "
"attach_asset with job_id (or path) and a name or entity id."
"attach_asset with job_id (or path) and a name or entity id.\n"
"- Film clips: enqueue_video_jobs with orders or scene_ids for ONLY "
"the clips they named. Never dump every scene_id. Never omit the "
"list (that is not 'all'). all_scenes=true only if they said all/"
"every clip. Orphan video jobs (wired_to_scene=false) use "
"attach_asset target=scene + scene_id."
)
@@ -177,7 +187,8 @@ def _render_digest(p, stats, beats, chars, locs, scenes, pending) -> str:
lines.append(f"locations: {ready}")
if scenes:
s = " ".join(
f"#{sc['id']}:'{sc['heading']}'{'✓vid' if sc['video_path'] else '✗vid'}"
f"#{sc['order_index']} id={sc['id']}:'{sc['heading']}'"
f"{'✓vid' if sc['video_path'] else '✗vid'}"
for sc in scenes[:15]
)
lines.append(f"scenes: {s}" + (" …" if len(scenes) > 15 else ""))
@@ -206,15 +217,29 @@ async def _tool_discipline_section(ctx: ToolContext) -> str | None:
"Text edits — add_item, add_character, add_location, update_scene, "
"generate_story, generate_script, etc. — are NOT permission to render. "
"After text edits, if images/videos are missing, tell the user and ASK "
"whether to generate; wait for their yes. Also call comfy_server_info "
"first; if ComfyUI is unreachable or dry_run is on, say so and stop.\n"
"4b. NO COMFY MCP. There are no comfy_run_workflow / comfy_run_template / "
"comfy_search_templates / comfy_list_saved_workflows tools. The only "
"comfy_* tool is comfy_server_info (health). Generate with run_workflow "
"(tagged @workflow) or enqueue_asset_jobs / enqueue_video_jobs.\n"
"whether to generate; wait for their yes — do not call run_workflow in "
"the same turn as the question. Render tools are hidden until they ask. "
"Also call comfy_server_info first; if ComfyUI is unreachable or dry_run "
"is on, say so and stop.\n"
"4b. NO COMFY MCP. There is no MCP run_workflow / comfy_run_workflow / "
"comfy_run_template / comfy_search_templates. The only comfy_* tool is "
"comfy_server_info (health). Calliope run_workflow is the HTTP queue "
"(tagged @workflow), not MCP. Use enqueue_asset_jobs / enqueue_video_jobs "
"for project assets and clips.\n"
"5. ASSETS BEFORE VIDEO: reference-based video needs character sheets "
"and location images to exist. After enqueue_asset_jobs, wait_for_jobs "
"and only enqueue_video_jobs once images are ready.\n"
"5b. SCENE CLIPS ARE WIRED IN CODE. On a linked film, video generate "
"must be enqueue_video_jobs (orders=#N or scene_ids) or run_workflow "
"with scene_id from list_scenes. The worker writes scenes.video_path "
"from job.scene_id. Do not add_scene to 'fix' a missing clip. If "
"wait_for_jobs returns wired_to_scene=false, call attach_asset "
"target=scene with that job_id and the existing scene_id.\n"
"5c. #N IS ORDER. The Video page shows #1, #2… as order_index. "
"scene_id is a different, larger database id. list_scenes / "
"update_scene / delete_scene / enqueue_video_jobs accept order so "
"you can follow the user. Search with list_scenes query= or "
"orders=[25,26]. Never enqueue more clips than they named.\n"
"6. Standard EDIT pipeline (text only, no renders): create_project → "
"generate_story → generate_script → add/update assets (characters, "
"locations, items) as needed. Rendering is a SEPARATE step that only "
@@ -227,15 +252,14 @@ async def _tool_discipline_section(ctx: ToolContext) -> str | None:
async def _mentions_section(ctx: ToolContext) -> str | None:
return (
"Tagged workflows: when the user message includes a [Calliope context] "
"appendix with workflow_id=, call run_workflow with that id (plus the "
"user's prompt, width/height from any stated aspect ratio, and attached "
"paths). There is at most ONE tagged workflow per user message — if "
"several workflow_id= lines appear, use the first and ignore the rest. "
"Do not guess the workflow from list_workflows. In a sandbox session "
"call run_workflow immediately — do not create_project just to "
"generate. Video file attachments are context only (the worker "
"uploads image + audio refs)."
"Tagged workflows: a [Calliope context] appendix with workflow_id= "
"names the Calliope graph. It is NOT render permission and there is "
"no MCP run_workflow. Only call Calliope run_workflow when the user's "
"own words ask to generate (or they confirm an offer). Then use that "
"id plus prompt / aspect / attachments — do not list_workflows guess. "
"One tagged workflow per message (first id wins). Sandbox: do not "
"create_project just to generate. Video file attachments are context "
"only (the worker uploads image + audio refs)."
)
@@ -120,6 +120,14 @@ class ToolRegistry:
return False
if t.blind_only and ctx.project_id is not None:
return False
# Hide render tools until the user asks — the model still "knows"
# run_workflow from earlier turns, but a missing tool is harder to
# call than one that only fails in pre-execute (HITL cards).
if t.requires_approval:
from calliope.agent.harness.policy import user_allows_render
if not user_allows_render(ctx):
return False
return True
def openai_payload(self, ctx: ToolContext) -> list[dict[str, Any]]:
@@ -367,6 +367,12 @@ class QueueWorker:
).fetchone()
name = row["name"] if row else f"#{payload['location_id']}"
return f"{name} · environment"
if payload.get("item_id"):
row = conn.execute(
"SELECT name FROM items WHERE id = ?", (payload["item_id"],)
).fetchone()
name = row["name"] if row else f"#{payload['item_id']}"
return f"{name} · item"
if job.get("scene_id"):
row = conn.execute(
"SELECT heading, order_index FROM scenes WHERE id = ?", (job["scene_id"],)
@@ -387,6 +393,7 @@ class QueueWorker:
primary = paths[0]
character_id = payload.get("character_id")
location_id = payload.get("location_id")
item_id = payload.get("item_id")
scene_id = job.get("scene_id")
conn = get_db(config.settings.db_path)
try:
@@ -408,6 +415,11 @@ class QueueWorker:
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
(primary, location_id),
)
if item_id:
conn.execute(
"UPDATE items SET reference_image_path = ? WHERE id = ?",
(primary, item_id),
)
if scene_id and job["kind"] == "video":
conn.execute(
"UPDATE scenes SET video_path = ? WHERE id = ?",
@@ -12,6 +12,7 @@ from fastapi import APIRouter, File, HTTPException, UploadFile
from pydantic import BaseModel, Field
from calliope import config
from calliope.agent.prompts import item_reference_prompt
from calliope.db import get_db, row_to_dict
from calliope.events.bus import event_bus
from calliope.queue.manager import queue_manager
@@ -30,10 +31,12 @@ class PlaygroundGenerate(BaseModel):
class PlaygroundAttach(BaseModel):
path: str
project_id: int
target: Literal["character_sheet", "location", "scene"]
target: Literal["character_sheet", "location", "item", "scene"]
character_id: int | None = None
location_id: int | None = None
item_id: int | None = None # ignored: items always insert a new row
scene_id: int | None = None
name: str | None = None
def _job_public(job: dict[str, Any]) -> dict[str, Any]:
@@ -147,6 +150,10 @@ def _clear_entity_refs(conn, paths: list[str]) -> None:
"UPDATE locations SET reference_image_path = NULL WHERE reference_image_path = ?",
(path,),
)
conn.execute(
"UPDATE items SET reference_image_path = NULL WHERE reference_image_path = ?",
(path,),
)
conn.execute("UPDATE scenes SET video_path = NULL WHERE video_path = ?", (path,))
@@ -360,6 +367,27 @@ async def attach_to_project(payload: PlaygroundAttach) -> dict[str, Any]:
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
(path, payload.location_id),
)
elif payload.target == "item":
# Always insert a new misc. item — Playground attach must not
# overwrite an existing project item (item_id is ignored).
raw_name = (payload.name or "").strip()
if not raw_name:
stem = Path(path).stem
raw_name = stem.split("-", 1)[-1] if len(stem) > 9 and stem[8:9] == "-" else stem
name = raw_name or "Playground item"
consistency = item_reference_prompt(
{"name": name, "description": "Added from Playground"}
)
cur = conn.execute(
"""
INSERT INTO items (
project_id, name, description, consistency_prompt, reference_image_path
)
VALUES (?, ?, ?, ?, ?)
""",
(payload.project_id, name, "Added from Playground", consistency, path),
)
created_item_id = int(cur.lastrowid)
elif payload.target == "scene":
if not payload.scene_id:
raise HTTPException(status_code=400, detail="scene_id required")
@@ -390,6 +418,14 @@ async def attach_to_project(payload: PlaygroundAttach) -> dict[str, Any]:
"source": "playground_attach",
},
)
return {"ok": True, "path": path, "target": payload.target, "project_id": payload.project_id}
out: dict[str, Any] = {
"ok": True,
"path": path,
"target": payload.target,
"project_id": payload.project_id,
}
if payload.target == "item":
out["item_id"] = created_item_id
return out
finally:
conn.close()
+97 -4
View File
@@ -37,9 +37,13 @@ def test_tool_registry_schemas_valid():
def test_openai_payload_scoping():
"""Blind sessions see only requires_project=False tools."""
blind = ToolContext(session_id=1, project_id=None)
linked = ToolContext(session_id=1, project_id=99)
"""Blind sessions see only requires_project=False tools.
session_id is unused/high so a leftover local DB row cannot unlock
requires_approval tools (those stay hidden until the user asks to render).
"""
blind = ToolContext(session_id=9_999_001, project_id=None)
linked = ToolContext(session_id=9_999_001, project_id=99)
blind_names = {
entry["function"]["name"] for entry in openai_tools_payload(blind)
@@ -52,7 +56,7 @@ def test_openai_payload_scoping():
assert "list_projects" in blind_names
assert "get_workspace" in blind_names
assert "comfy_server_info" in blind_names
assert "run_workflow" in blind_names
assert "run_workflow" not in blind_names # HITL: hidden until user asks
assert "attach_asset" in blind_names
# Blind must NOT see project-scoped tools
assert "generate_story" not in blind_names
@@ -589,3 +593,92 @@ def test_linked_session_scoping(client):
# Cross-project update rejected
out = execute_tool_sync(ctx, "update_scene", {"scene_id": 1, "heading": "hack"})
assert out["ok"] is False
def _add_scene(client, pid: int, heading: str, order: int) -> int:
r = client.post(
f"/api/projects/{pid}/scenes",
json={"heading": heading, "order_index": order, "action": heading},
)
assert r.status_code == 200
return r.json()["id"]
def test_list_scenes_search_and_order_labels(client):
"""#N is order; scene_id is the DB id. Search by query or clip numbers."""
pid = _make_project(client)
sid = client.post("/api/agent/sessions", json={"project_id": pid}).json()["id"]
ctx = ToolContext(session_id=sid, project_id=pid)
a = _add_scene(client, pid, "EXT. GANGNAM NIGHT", 1)
b = _add_scene(client, pid, "INT. SAFEHOUSE", 2)
_add_scene(client, pid, "EXT. SKYLINE", 3)
all_rows = execute_tool_sync(ctx, "list_scenes", {})["result"]
assert [s["order"] for s in all_rows] == [1, 2, 3]
assert all_rows[0]["scene_id"] == a
assert all_rows[0]["clip"] == "#1"
assert all_rows[0]["id"] == a
by_order = execute_tool_sync(ctx, "list_scenes", {"orders": [2]})["result"]
assert [s["scene_id"] for s in by_order] == [b]
assert by_order[0]["clip"] == "#2"
found = execute_tool_sync(ctx, "list_scenes", {"query": "gangnam"})["result"]
assert [s["order"] for s in found] == [1]
def test_update_scene_by_video_order(client):
pid = _make_project(client)
sid = client.post("/api/agent/sessions", json={"project_id": pid}).json()["id"]
ctx = ToolContext(session_id=sid, project_id=pid)
_add_scene(client, pid, "OLD HEADING", 1)
out = execute_tool_sync(ctx, "update_scene", {"order": 1, "heading": "NEW HEADING"})
assert out["ok"] is True
assert out["scene"]["heading"] == "NEW HEADING"
assert out["scene"]["order"] == 1
assert out["scene"]["clip"] == "#1"
def test_enqueue_video_refuses_omit_and_bulk_dump(client):
"""A 'yes' after a 2-clip offer must not enqueue the whole timeline."""
pid = _make_project(client)
sid = client.post("/api/agent/sessions", json={"project_id": pid}).json()["id"]
ctx = ToolContext(session_id=sid, project_id=pid)
ids = [_add_scene(client, pid, f"S{i}", i) for i in range(1, 6)]
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "yes"})
omitted = execute_tool_sync(ctx, "enqueue_video_jobs", {"workflow_id": 40})
assert omitted["ok"] is False
assert "orders" in omitted["error"] or "scene_ids" in omitted["error"]
dumped = execute_tool_sync(
ctx, "enqueue_video_jobs", {"workflow_id": 40, "scene_ids": ids}
)
assert dumped["ok"] is False
assert "bulk" in dumped["error"].lower()
all_flag = execute_tool_sync(
ctx, "enqueue_video_jobs", {"workflow_id": 40, "all_scenes": True}
)
assert all_flag["ok"] is False
assert "bulk" in all_flag["error"].lower()
def test_workspace_digest_labels_order_and_id(client):
from calliope.agent.harness.prompts import workspace_digest
pid = _make_project(client)
scene_id = _add_scene(client, pid, "EXT. TEST", 1)
ctx = ToolContext(session_id=1, project_id=pid)
digest = workspace_digest(ctx)
assert f"#{scene_id}:" not in digest
assert f"#1 id={scene_id}:" in digest
def test_bulk_video_policy_phrases():
from calliope.agent.harness.policy import allows_bulk_video_enqueue
assert allows_bulk_video_enqueue("yes", 2) is True
assert allows_bulk_video_enqueue("yes", 24) is False
assert allows_bulk_video_enqueue("generate all scenes", 24) is True
assert allows_bulk_video_enqueue("do every clip", 10) is True
@@ -342,6 +342,56 @@ def test_render_guard_allows_run_workflow_on_generate(client):
assert decision.kind == "allow"
def test_render_tools_hidden_until_user_asks(client):
"""run_workflow must not appear in the model payload until HITL unlocks.
Asking-then-calling in the same turn produced failed HITL cards; hiding
the tool is stronger than a deny after the model already called it.
"""
from calliope.agent.harness.tools import openai_tools_payload
pid = _mk_project(client, "HITL Hide")
sid = _mk_session(pid)
ctx = ToolContext(session_id=sid, project_id=pid)
names = {e["function"]["name"] for e in openai_tools_payload(ctx)}
assert "run_workflow" not in names
assert "enqueue_asset_jobs" not in names
assert "enqueue_video_jobs" not in names
assert "comfy_run_workflow" not in names
assert "list_workflows" in names
session_log.append_event(sid, session_log.USER_MESSAGE, {"content": "draft outfits only"})
names = {e["function"]["name"] for e in openai_tools_payload(ctx)}
assert "run_workflow" not in names
session_log.append_event(
sid, session_log.USER_MESSAGE, {"content": "yes, generate the images"}
)
names = {e["function"]["name"] for e in openai_tools_payload(ctx)}
assert "run_workflow" in names
assert "enqueue_asset_jobs" in names
def test_render_guard_strips_appendix_in_content(client):
"""kind=image in a stored appendix must not unlock renders."""
registry, _ = build_harness()
pid = _mk_project(client, "HITL Appendix Content")
sid = _mk_session(pid)
session_log.append_event(
sid,
session_log.USER_MESSAGE,
{
"content": (
"create a Misc. Item only\n\n[Calliope context]\n"
'workflow_id=39 name="krea" kind=image'
)
},
)
t = registry.get("run_workflow")
decision = _render_approval_guard(ToolContext(session_id=sid, project_id=pid), t, {})
assert decision.kind == "deny"
def test_run_workflow_sandbox_uses_playground_scratch(client):
"""Sandbox @generate must not create a user project — queue on Playground scratch."""
registry, _ = build_harness()
@@ -539,6 +589,130 @@ def test_attach_asset_sandbox_requires_project_id(client):
assert "project_id" in out["error"]
def _insert_video_workflow(conn) -> int:
wf_json = json.dumps(
{
"10": {
"class_type": "CLIPTextEncode",
"inputs": {"text": ""},
"_meta": {"title": "Main Prompt (Input:prompt)"},
}
}
)
cur = conn.execute(
"""
INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema, is_enabled)
VALUES ('h3-test', 'video', ?, '[]', '[]', 1)
""",
(wf_json,),
)
conn.commit()
return int(cur.lastrowid)
def test_run_workflow_linked_video_requires_scene_id(client):
"""A film clip without scene_id would orphan the mp4 (preview only)."""
registry, _ = build_harness()
pid = _mk_project(client, "Wire Film")
sid = _mk_session(pid)
session_log.append_event(
sid, session_log.USER_MESSAGE, {"content": "generate the video clip"}
)
conn = get_db(settings.db_path)
try:
wid = _insert_video_workflow(conn)
finally:
conn.close()
ctx = ToolContext(session_id=sid, project_id=pid)
out = asyncio.run(registry.execute(ctx, "run_workflow", {"workflow_id": wid, "prompt": "rain"}))
assert out.get("ok") is False
assert "scene_id" in out["error"]
from calliope.queue.manager import queue_manager
orphans = [
j
for j in queue_manager.list_jobs(project_id=pid, limit=20)
if j.get("kind") == "video" and not j.get("scene_id")
]
assert orphans == []
def test_run_workflow_linked_video_wires_scene(client):
"""run_workflow with scene_id enqueues a scene-backed job (worker can attach)."""
registry, _ = build_harness()
pid = _mk_project(client, "Wire Scene")
scene = client.post(
f"/api/projects/{pid}/scenes", json={"heading": "EXT. STREET", "order_index": 1}
).json()
sid = _mk_session(pid)
session_log.append_event(
sid, session_log.USER_MESSAGE, {"content": "render the video for this scene"}
)
conn = get_db(settings.db_path)
try:
wid = _insert_video_workflow(conn)
finally:
conn.close()
ctx = ToolContext(session_id=sid, project_id=pid)
out = asyncio.run(
registry.execute(
ctx,
"run_workflow",
{"workflow_id": wid, "scene_id": scene["id"], "prompt": "night rain"},
)
)
assert out.get("ok") is True
assert out.get("wired_to_scene") is True
assert out["jobs"][0]["scene_id"] == scene["id"]
assert out["jobs"][0]["wired_to_scene"] is True
def test_attach_asset_job_to_scene(client):
"""Backfill an orphan video job onto an existing scene."""
registry, _ = build_harness()
pid = _mk_project(client, "Backfill Clip")
scene = client.post(
f"/api/projects/{pid}/scenes", json={"heading": "EXT. ALLEY", "order_index": 1}
).json()
path = _touch_asset("orphan-clip.mp4")
from calliope.queue.manager import queue_manager
job = queue_manager.enqueue(project_id=pid, kind="video", payload={})
queue_manager.mark_done(job["id"], [path])
ctx = ToolContext(session_id=_mk_session(), project_id=None)
out = asyncio.run(
registry.execute(
ctx,
"attach_asset",
{
"job_id": job["id"],
"project_id": pid,
"target": "scene",
"scene_id": scene["id"],
},
)
)
assert out.get("ok") is True
assert out["entity"]["video_path"] == path
conn = get_db(settings.db_path)
try:
scene_row = conn.execute(
"SELECT video_path FROM scenes WHERE id = ?", (scene["id"],)
).fetchone()
job_row = conn.execute(
"SELECT scene_id FROM jobs WHERE id = ?", (job["id"],)
).fetchone()
n = conn.execute(
"SELECT COUNT(*) AS n FROM scenes WHERE project_id = ?", (pid,)
).fetchone()["n"]
finally:
conn.close()
assert scene_row["video_path"] == path
assert job_row["scene_id"] == scene["id"]
assert n == 1
def test_run_workflow_blocks_without_approval(client):
registry, _ = build_harness()
pid = _mk_project(client, "No Approve")
@@ -0,0 +1,51 @@
"""Misc. Item generate jobs must attach the downloaded file to the item row."""
from __future__ import annotations
from calliope.config import settings
from calliope.db import get_db
from calliope.queue.worker import queue_worker
def test_item_generate_attaches_reference_image(client):
pid = client.post("/api/projects", json={"title": "Item Attach"}).json()["id"]
item = client.post(
f"/api/projects/{pid}/items",
json={"name": "Mecha Suits", "description": "exoskeletons"},
).json()
assert item.get("reference_image_path") in (None, "")
dest = settings.assets_dir / str(pid) / "image"
dest.mkdir(parents=True, exist_ok=True)
path = dest / "mecha.png"
path.write_bytes(b"\x89PNG\r\n")
queue_worker._apply_outputs_to_entities(
{"kind": "image", "scene_id": None},
{"item_id": item["id"]},
[str(path)],
)
assets = client.get(f"/api/projects/{pid}/assets").json()
row = next(i for i in assets["items"] if i["id"] == item["id"])
assert row["reference_image_path"] == str(path)
conn = get_db(settings.db_path)
try:
db_row = conn.execute(
"SELECT reference_image_path FROM items WHERE id = ?", (item["id"],)
).fetchone()
finally:
conn.close()
assert db_row["reference_image_path"] == str(path)
def test_item_job_label_uses_name(client):
pid = client.post("/api/projects", json={"title": "Item Label"}).json()["id"]
item = client.post(
f"/api/projects/{pid}/items",
json={"name": "Energy Shield", "description": "bubble"},
).json()
label = queue_worker._job_label(
{"kind": "image", "id": 301, "payload_json": f'{{"item_id": {item["id"]}}}'},
)
assert label == "Energy Shield · item"
+55
View File
@@ -120,3 +120,58 @@ def test_playground_generate_and_attach(client):
assets2 = client.get(f"/api/projects/{proj['id']}/assets").json()
sheet2 = next(c for c in assets2["characters"] if c["id"] == char["id"])["sheet_path"]
assert sheet2 is None
def test_playground_attach_item(client):
wf = client.post(
"/api/workflows",
json={"name": "PG Item", "kind": "image", "workflow_json": SAMPLE_WORKFLOW},
)
assert wf.status_code == 200
gen = client.post(
"/api/playground/generate",
json={"workflow_id": wf.json()["id"], "input_values": {"1": "a blaster"}},
)
assert gen.status_code == 200
job = gen.json()["job"]
proj = client.post("/api/projects", json={"title": "Gear"}).json()
existing = client.post(
f"/api/projects/{proj['id']}/items",
json={"name": "Old Prop", "description": "must stay untouched"},
).json()
import time
path = None
for _ in range(40):
jobs = client.get("/api/playground/jobs").json()
done = next((j for j in jobs if j["id"] == job["id"] and j["status"] == "done"), None)
if done and done["output_paths"]:
path = done["output_paths"][0]
break
time.sleep(0.25)
assert path, "playground job did not finish in dry-run"
attach = client.post(
"/api/playground/attach",
json={
"path": path,
"project_id": proj["id"],
"target": "item",
"name": "Alien Blaster",
"item_id": existing["id"],
},
)
assert attach.status_code == 200, attach.text
created_id = attach.json()["item_id"]
assert created_id != existing["id"]
assets = client.get(f"/api/projects/{proj['id']}/assets").json()
items = assets["items"]
old = next(i for i in items if i["id"] == existing["id"])
new = next(i for i in items if i["id"] == created_id)
assert old["name"] == "Old Prop"
assert old["reference_image_path"] is None
assert new["name"] == "Alien Blaster"
assert new["reference_image_path"] == path
+4 -2
View File
@@ -275,7 +275,7 @@ export const jobsApi = {
api<{ ok: boolean; job: Job }>(`/api/jobs/projects/${projectId}/export`, { method: 'POST' }),
};
export type PlaygroundAttachTarget = 'character_sheet' | 'location' | 'scene';
export type PlaygroundAttachTarget = 'character_sheet' | 'location' | 'item' | 'scene';
export type UploadKind = 'image' | 'video' | 'audio';
@@ -319,9 +319,11 @@ export const playgroundApi = {
target: PlaygroundAttachTarget;
character_id?: number;
location_id?: number;
item_id?: number;
scene_id?: number;
name?: string;
}) =>
api<{ ok: boolean; path: string; target: string; project_id: number }>(
api<{ ok: boolean; path: string; target: string; project_id: number; item_id?: number }>(
'/api/playground/attach',
{ method: 'POST', body: JSON.stringify(payload) },
),
+48
View File
@@ -0,0 +1,48 @@
/** Shared shape for Omni / video ref pickers. */
export type AssetGroup = 'character' | 'location' | 'item' | 'upload' | 'clip';
export interface AssetOption {
label: string;
path: string;
kind?: 'image' | 'video' | 'audio';
group?: AssetGroup;
}
const GROUP_FROM_SUFFIX: Array<{ re: RegExp; group: AssetGroup }> = [
{ re: /\s·\s*sheet$/i, group: 'character' },
{ re: /\s·\s*environment$/i, group: 'location' },
{ re: /\s·\s*item$/i, group: 'item' },
{ re: /\s·\s*upload$/i, group: 'upload' },
{ re: /^clip\s*#/i, group: 'clip' },
];
export function assetGroup(opt: AssetOption): AssetGroup {
if (opt.group) return opt.group;
for (const { re, group } of GROUP_FROM_SUFFIX) {
if (re.test(opt.label)) return group;
}
return 'upload';
}
/** Strip the " · sheet" style suffix so the tab already names the type. */
export function assetDisplayName(opt: AssetOption): string {
return opt.label.replace(/\s·\s*(sheet|environment|item|upload)\s*$/i, '').trim() || opt.label;
}
export const ASSET_GROUP_TABS: Array<{ id: AssetGroup; label: string }> = [
{ id: 'character', label: 'Characters' },
{ id: 'location', label: 'Environments' },
{ id: 'item', label: 'Misc. Items' },
{ id: 'clip', label: 'Clips' },
{ id: 'upload', label: 'Uploads' },
];
export function tabsForMediaKind(kind: string | undefined): Array<{ id: AssetGroup; label: string }> {
const ids: AssetGroup[] =
kind === 'video'
? ['clip', 'upload']
: kind === 'audio'
? ['upload']
: ['character', 'location', 'item', 'upload'];
return ASSET_GROUP_TABS.filter((t) => ids.includes(t.id));
}
@@ -148,18 +148,25 @@
const chars = $assetsQuery.data?.characters ?? [];
const locs = $assetsQuery.data?.locations ?? [];
const items = $assetsQuery.data?.items ?? [];
const opts: Array<{ label: string; path: string }> = [];
const opts: Array<{ label: string; path: string; group?: 'character' | 'location' | 'item' }> =
[];
for (const c of chars) {
if (c.sheet_path) opts.push({ label: `${c.name} · sheet`, path: c.sheet_path });
if (c.sheet_path) {
opts.push({ label: `${c.name} · sheet`, path: c.sheet_path, group: 'character' });
}
}
for (const loc of locs) {
if (loc.reference_image_path) {
opts.push({ label: `${loc.name} · environment`, path: loc.reference_image_path });
opts.push({
label: `${loc.name} · environment`,
path: loc.reference_image_path,
group: 'location',
});
}
}
for (const it of items) {
if (it.reference_image_path) {
opts.push({ label: `${it.name} · item`, path: it.reference_image_path });
opts.push({ label: `${it.name} · item`, path: it.reference_image_path, group: 'item' });
}
}
return opts;
@@ -29,6 +29,7 @@
let target = $state<PlaygroundAttachTarget>('character_sheet');
let characterId = $state<number | ''>('');
let locationId = $state<number | ''>('');
let itemName = $state('');
let sceneId = $state<number | ''>('');
let message = $state('');
let characters = $state<Character[]>([]);
@@ -99,6 +100,9 @@
} else if (target === 'location') {
if (locationId === '') throw new Error('Pick a location');
payload.location_id = Number(locationId);
} else if (target === 'item') {
const name = itemName.trim();
if (name) payload.name = name;
} else {
if (sceneId === '') throw new Error('Pick a scene');
payload.scene_id = Number(sceneId);
@@ -118,6 +122,14 @@
},
});
function defaultMiscName(filePath: string): string {
const base = filePath.replace(/\\/g, '/').split('/').pop() ?? '';
const stem = base.replace(/\.[^.]+$/, '');
const stripped = stem.replace(/^[0-9a-f]{8}-/i, '');
const pretty = (stripped || stem).replace(/[_-]+/g, ' ').trim();
return pretty || 'New item';
}
const projectList = $derived(($projectsQuery.data ?? []) as Project[]);
// Stage-URL contract: images land on Assets, clips on Video.
@@ -142,7 +154,15 @@
</button>
</div>
{:else if !open}
<Button variant="secondary" onclick={() => (open = true)}>Add to project</Button>
<Button
variant="secondary"
onclick={() => {
itemName = defaultMiscName(path);
open = true;
}}
>
Add to project
</Button>
{:else}
<div class="panel" role="group" aria-label="Add artifact to project">
<label class="field">
@@ -161,6 +181,7 @@
<select class="field-select" bind:value={target}>
<option value="character_sheet">Character sheet</option>
<option value="location">Background / location</option>
<option value="item">Misc. item</option>
</select>
</label>
@@ -177,7 +198,7 @@
<span class="field-hint">No characters in this project yet.</span>
{/if}
</label>
{:else}
{:else if target === 'location'}
<label class="field">
<span class="field-label">Location</span>
<select class="field-select" bind:value={locationId} disabled={projectId === '' || loadingTargets}>
@@ -190,6 +211,17 @@
<span class="field-hint">No locations in this project yet.</span>
{/if}
</label>
{:else}
<label class="field">
<span class="field-label">Name</span>
<input
class="field-input"
type="text"
bind:value={itemName}
placeholder="New misc. item"
/>
<span class="field-hint">Adds a new misc. item. Existing items are left unchanged.</span>
</label>
{/if}
{:else}
<label class="field">
@@ -17,6 +17,7 @@
import { classifyAll, RESOLUTION_PRESETS, resolutionLabel } from '$lib/comfy/classifyInput';
import { createUploadManager } from '$lib/comfy/useUpload.svelte';
import { normalizeInputRole } from '$lib/comfy/parser';
import type { AssetOption } from '$lib/assetPicker';
import { assetUrl } from '$lib/api';
import Icon from '$lib/components/ui/Icon.svelte';
import PillSelect from './omni/PillSelect.svelte';
@@ -30,12 +31,6 @@
kind: string;
}
interface AssetOption {
label: string;
path: string;
kind?: 'image' | 'video' | 'audio';
}
interface Props {
inputs: ComfyDynamicInput[];
values: Record<string, string | number>;
@@ -13,6 +13,7 @@
type Workflow,
} from '$lib/api';
import { compactInputValues } from '$lib/comfy/promptInput';
import type { AssetOption } from '$lib/assetPicker';
import { progressFor } from '$lib/jobProgress';
import SafeMedia from './SafeMedia.svelte';
import VideoEditWorkspace from './video/VideoEditWorkspace.svelte';
@@ -82,9 +83,17 @@
const assetOptions = $derived.by(() => {
const chars = $assetsQuery.data?.characters ?? [];
const locs = $assetsQuery.data?.locations ?? [];
const opts: Array<{ label: string; path: string; kind?: 'image' | 'video' | 'audio' }> = [];
const items = $assetsQuery.data?.items ?? [];
const opts: AssetOption[] = [];
for (const c of chars) {
if (c.sheet_path) opts.push({ label: `${c.name} · sheet`, path: c.sheet_path, kind: 'image' });
if (c.sheet_path) {
opts.push({
label: `${c.name} · sheet`,
path: c.sheet_path,
kind: 'image',
group: 'character',
});
}
}
for (const loc of locs) {
if (loc.reference_image_path) {
@@ -92,6 +101,17 @@
label: `${loc.name} · environment`,
path: loc.reference_image_path,
kind: 'image',
group: 'location',
});
}
}
for (const it of items) {
if (it.reference_image_path) {
opts.push({
label: `${it.name} · item`,
path: it.reference_image_path,
kind: 'image',
group: 'item',
});
}
}
@@ -101,11 +121,12 @@
label: `Clip #${sc.order_index} · ${sc.heading || 'scene'}`,
path: sc.video_path,
kind: 'video',
group: 'clip',
});
}
}
for (const up of $uploadsQuery.data ?? []) {
opts.push({ label: `${up.name} · upload`, path: up.path, kind: up.kind });
opts.push({ label: `${up.name} · upload`, path: up.path, kind: up.kind, group: 'upload' });
}
return opts;
});
@@ -190,6 +211,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.
let batching = $state(false);
let batchNote = $state('');
@@ -0,0 +1,358 @@
<script lang="ts">
/**
* Tabbed asset picker for Omni media tiles (characters / environments /
* items / uploads / clips). Replaces the old single-column dropdown.
*/
import { assetUrl } from '$lib/api';
import {
assetDisplayName,
assetGroup,
tabsForMediaKind,
type AssetGroup,
type AssetOption,
} from '$lib/assetPicker';
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 Props {
open?: boolean;
title?: string;
assets?: AssetOption[];
value?: string;
kind?: string;
allowUpload?: boolean;
onselect: (path: string) => void;
onupload?: () => void;
onclear?: () => void;
}
let {
open = $bindable(false),
title = 'Choose reference',
assets = [],
value = '',
kind = 'image',
allowUpload = true,
onselect,
onupload,
onclear,
}: Props = $props();
let tab = $state<AssetGroup>('character');
let query = $state('');
let wasOpen = $state(false);
const tabs = $derived(tabsForMediaKind(kind));
function hideBroken(e: Event) {
const el = e.currentTarget as HTMLElement | null;
if (el) el.style.display = 'none';
}
$effect(() => {
const now = open;
if (now && !wasOpen) {
query = '';
const match = assets.find((a) => a.path === value);
const preferred = match ? assetGroup(match) : null;
const firstWithItems =
tabs.find((t) => assets.some((a) => assetGroup(a) === t.id))?.id ?? tabs[0]?.id;
tab =
(preferred && tabs.some((t) => t.id === preferred) ? preferred : firstWithItems) ??
'upload';
}
wasOpen = now;
});
const q = $derived(query.trim().toLowerCase());
const visible = $derived.by(() => {
const inTab = assets.filter((a) => assetGroup(a) === tab);
if (!q) return inTab;
return inTab.filter(
(a) => a.label.toLowerCase().includes(q) || assetDisplayName(a).toLowerCase().includes(q),
);
});
function countFor(id: AssetGroup): number {
return assets.filter((a) => assetGroup(a) === id).length;
}
const emptyHint = $derived.by(() => {
if (q) return `No matches for “${query.trim()}”.`;
if (tab === 'character') return 'No character sheets yet. Generate them on Assets.';
if (tab === 'location') return 'No environment images yet. Generate them on Assets.';
if (tab === 'item') return 'No misc. item images yet. Generate them on Assets.';
if (tab === 'clip') return 'No scene clips in this film yet.';
return allowUpload ? 'No uploads yet. Use Upload new… below.' : 'No uploads yet.';
});
function pick(path: string) {
onselect(path);
open = false;
}
function upload() {
onupload?.();
open = false;
}
function clear() {
onclear?.();
open = false;
}
</script>
<Modal bind:open {title} size="lg">
<div class="picker">
{#if tabs.length > 1}
<div class="tabs" role="tablist" aria-label="Asset type">
{#each tabs as t (t.id)}
<button
type="button"
role="tab"
id="asset-tab-{t.id}"
aria-selected={tab === t.id}
class:active={tab === t.id}
onclick={() => (tab = t.id)}
>
{t.label}
<span class="count">{countFor(t.id)}</span>
</button>
{/each}
</div>
{/if}
<label class="search">
<Icon name="search" size={14} />
<input
type="search"
placeholder="Search in {tabs.find((t) => t.id === tab)?.label ?? 'this list'}…"
bind:value={query}
aria-label="Search assets"
/>
</label>
<div class="grid-wrap" role="tabpanel" aria-labelledby="asset-tab-{tab}">
{#if visible.length === 0}
<p class="empty">{emptyHint}</p>
{:else}
<div class="grid">
{#each visible as opt (opt.path)}
{@const selected = opt.path === value}
{@const src = assetUrl(opt.path)}
{@const isVideo = (opt.kind ?? kind) === 'video'}
<button
type="button"
class="card"
class:selected
onclick={() => pick(opt.path)}
title={opt.label}
>
<div class="thumb">
{#if isVideo}
<!-- svelte-ignore a11y_media_has_caption -->
<video src={src} muted playsinline preload="metadata" onerror={hideBroken}></video>
{:else if (opt.kind ?? kind) === 'audio'}
<Icon name="music" size={28} />
{:else}
<img src={src} alt="" onerror={hideBroken} />
{/if}
{#if selected}
<span class="check"><Icon name="check" size={12} /></span>
{/if}
</div>
<span class="name">{assetDisplayName(opt)}</span>
</button>
{/each}
</div>
{/if}
</div>
</div>
{#snippet footer()}
{#if value && onclear}
<Button variant="ghost" onclick={clear}>Clear slot</Button>
{/if}
{#if allowUpload}
<Button variant="secondary" onclick={upload}>
<Icon name="upload" size={14} />
Upload new…
</Button>
{/if}
<Button variant="ghost" onclick={() => (open = false)}>Cancel</Button>
{/snippet}
</Modal>
<style>
.picker {
display: flex;
flex-direction: column;
gap: 12px;
min-height: 320px;
}
.tabs {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.tabs button {
display: inline-flex;
align-items: center;
gap: 6px;
background: var(--bg-elevated);
border: 1px solid var(--border);
color: var(--text-secondary);
border-radius: var(--radius-sm);
padding: 7px 12px;
cursor: pointer;
min-height: 34px;
font: inherit;
font-size: 13px;
}
.tabs button.active {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
.tabs button:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.count {
font-size: 11px;
opacity: 0.8;
font-variant-numeric: tabular-nums;
}
.search {
display: flex;
align-items: center;
gap: 8px;
padding: 0 10px;
min-height: 36px;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-elevated);
color: var(--text-muted);
}
.search input {
flex: 1;
min-width: 0;
border: none;
background: transparent;
color: var(--text-primary);
font: inherit;
font-size: 13px;
outline: none;
}
.search:focus-within {
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-glow);
}
.grid-wrap {
overflow-y: auto;
overscroll-behavior: contain;
max-height: min(52vh, 480px);
min-height: 200px;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(128px, 1fr));
gap: 10px;
}
.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: 1;
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);
}
.card:hover .thumb {
border-color: var(--text-muted);
}
.card.selected .thumb {
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-glow);
}
.card:focus-visible .thumb {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.thumb img,
.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: 12px;
color: var(--text-secondary);
line-height: 1.3;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 2px;
}
.card.selected .name {
color: var(--text-primary);
font-weight: 600;
}
.empty {
margin: 48px 8px;
text-align: center;
color: var(--text-muted);
font-size: 13px;
line-height: 1.45;
}
</style>
@@ -1,22 +1,17 @@
<script lang="ts">
/**
* MediaTile — square thumbnail for image/ref/audio inputs.
*
* Asset picker menu is portaled to document.body so OmniComposer
* overflow:hidden cannot clip it (same fix as PillSelect).
* Clicking opens a tabbed asset picker modal (characters / environments /
* items / uploads) instead of a clipped dropdown.
*/
import { assetUrl } from '$lib/api';
import type { AssetOption } from '$lib/assetPicker';
import type { ComfyDynamicInput } from '$lib/comfy/types';
import AssetPickerModal from './AssetPickerModal.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import Spinner from '$lib/components/ui/Spinner.svelte';
import { acceptForKind } from '$lib/comfy/useUpload.svelte';
interface AssetOption {
label: string;
path: string;
kind?: 'image' | 'video' | 'audio';
}
interface Props {
input: ComfyDynamicInput;
value: string;
@@ -43,19 +38,15 @@
let fileInput = $state<HTMLInputElement | null>(null);
let dragOver = $state(false);
let showAssetMenu = $state(false);
let tileEl = $state<HTMLElement | null>(null);
let menuEl = $state<HTMLElement | null>(null);
let menuPos = $state({ top: 0, left: 0, maxHeight: 280, minWidth: 200 });
let pickerOpen = $state(false);
function openPicker(e: MouseEvent) {
e.stopPropagation();
function openPicker() {
if (uploadingName) return;
if (matchingAssets.length) {
showAssetMenu = !showAssetMenu;
} else if (allowUpload) {
fileInput?.click();
if (matchingAssets.length || allowUpload) {
pickerOpen = true;
return;
}
fileInput?.click();
}
function onFileChosen(e: Event) {
@@ -83,74 +74,10 @@
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')),
assetOptions.filter(
(o) => !o.kind || o.kind === input.kind || (isImageKind && o.kind === 'image'),
),
);
const hasAssets = $derived(matchingAssets.length > 0);
function placeMenu() {
if (!tileEl || !menuEl) return;
const rect = tileEl.getBoundingClientRect();
const gap = 6;
const pad = 8;
const spaceBelow = window.innerHeight - rect.bottom - gap - pad;
const spaceAbove = rect.top - gap - pad;
const preferred = Math.min(320, Math.max(menuEl.scrollHeight, 80));
const openUp = spaceBelow < Math.min(preferred, 160) && spaceAbove > spaceBelow;
const maxHeight = Math.max(120, openUp ? spaceAbove : spaceBelow);
const h = Math.min(menuEl.scrollHeight, maxHeight);
const minWidth = Math.max(200, rect.width);
let top = openUp ? rect.top - h - gap : rect.bottom + gap;
let left = rect.left;
left = Math.max(pad, Math.min(left, window.innerWidth - minWidth - pad));
top = Math.max(pad, Math.min(top, window.innerHeight - Math.min(h, maxHeight) - pad));
menuPos = { top, left, maxHeight, minWidth };
}
function onWindowClick(e: MouseEvent) {
if (!showAssetMenu) return;
const t = e.target as Node;
if (tileEl?.contains(t) || menuEl?.contains(t)) return;
showAssetMenu = false;
}
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') showAssetMenu = false;
}
$effect(() => {
if (!showAssetMenu || !menuEl) return;
document.body.appendChild(menuEl);
return () => {
menuEl?.remove();
};
});
$effect(() => {
if (!showAssetMenu) return;
const t = window.setTimeout(() => {
placeMenu();
window.addEventListener('click', onWindowClick);
window.addEventListener('keydown', onKey);
window.addEventListener('resize', placeMenu);
window.addEventListener('scroll', placeMenu, true);
}, 0);
return () => {
clearTimeout(t);
window.removeEventListener('click', onWindowClick);
window.removeEventListener('keydown', onKey);
window.removeEventListener('resize', placeMenu);
window.removeEventListener('scroll', placeMenu, true);
};
});
$effect(() => {
if (showAssetMenu && menuEl && tileEl) {
void assetOptions.length;
requestAnimationFrame(placeMenu);
}
});
const displayLabel = $derived(
input.role === 'character'
@@ -167,7 +94,7 @@
const accept = $derived(acceptForKind(input.kind));
</script>
<div class="tile-wrap" bind:this={tileEl}>
<div class="tile-wrap">
<input
bind:this={fileInput}
type="file"
@@ -176,8 +103,6 @@
onchange={onFileChosen}
/>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="tile"
class:filled={!!value}
@@ -191,11 +116,17 @@
ondragover={(e) => e.preventDefault()}
ondrop={onDrop}
onclick={openPicker}
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
openPicker();
}
}}
role="button"
tabindex="0"
title={displayLabel}
aria-haspopup={matchingAssets.length ? 'menu' : undefined}
aria-expanded={matchingAssets.length ? showAssetMenu : undefined}
aria-haspopup="dialog"
aria-expanded={pickerOpen}
>
{#if uploadingName}
<div class="tile-uploading">
@@ -238,48 +169,17 @@
{/if}
</div>
{#if showAssetMenu && hasAssets}
<div
bind:this={menuEl}
class="asset-menu"
style="top: {menuPos.top}px; left: {menuPos.left}px; max-height: {menuPos.maxHeight}px; min-width: {menuPos.minWidth}px"
role="menu"
>
{#each matchingAssets as opt (opt.path)}
<button
type="button"
class="asset-item"
class:active={opt.path === value}
role="menuitem"
onclick={(e) => {
e.stopPropagation();
onselectAsset(opt.path);
showAssetMenu = false;
}}
>
<span class="item-label">{opt.label}</span>
{#if opt.path === value}
<Icon name="check" size={14} />
{/if}
</button>
{/each}
{#if allowUpload}
<button
type="button"
class="asset-item upload-opt"
role="menuitem"
onclick={(e) => {
e.stopPropagation();
showAssetMenu = false;
fileInput?.click();
}}
>
<Icon name="upload" size={12} />
Upload new…
</button>
{/if}
</div>
{/if}
<AssetPickerModal
bind:open={pickerOpen}
title="Choose {displayLabel}"
assets={matchingAssets}
{value}
kind={input.kind}
{allowUpload}
onselect={onselectAsset}
onupload={() => fileInput?.click()}
onclear={value ? onclear : undefined}
/>
<style>
.tile-wrap {
@@ -395,64 +295,6 @@
font-weight: 600;
}
.asset-menu {
position: fixed;
z-index: 10000;
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
box-shadow:
0 8px 24px rgba(0, 0, 0, 0.5),
0 0 0 1px rgba(0, 0, 0, 0.3);
padding: 4px;
display: flex;
flex-direction: column;
gap: 2px;
overflow-y: auto;
overscroll-behavior: contain;
}
.asset-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 12px;
border-radius: var(--radius-sm);
background: transparent;
border: none;
color: var(--text-secondary);
font-size: 12px;
font-family: var(--font-body);
cursor: pointer;
text-align: left;
width: 100%;
}
.item-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.asset-item:hover {
background: var(--bg-elevated);
color: var(--text-primary);
}
.asset-item.active {
color: var(--accent);
font-weight: 600;
}
.upload-opt {
color: var(--text-muted);
border-top: 1px solid var(--border);
margin-top: 2px;
padding-top: 10px;
border-radius: 0 0 var(--radius-sm) var(--radius-sm);
}
.sr-only {
position: absolute;
width: 1px;
@@ -5,6 +5,7 @@
interface Props {
open?: boolean;
title?: string;
size?: 'md' | 'lg';
dismissible?: boolean;
onclose?: () => void;
footer?: Snippet;
@@ -14,6 +15,7 @@
let {
open = $bindable(false),
title,
size = 'md',
dismissible = true,
onclose,
footer,
@@ -96,7 +98,7 @@
<div class="modal-backdrop" onclick={handleBackdropClick}>
<div
bind:this={panel}
class="modal-panel"
class="modal-panel size-{size}"
role="dialog"
aria-modal="true"
aria-labelledby={title ? titleId : undefined}
@@ -158,6 +160,9 @@
outline: none;
animation: modal-rise 180ms ease-out;
}
.modal-panel.size-lg {
width: min(920px, 100%);
}
.modal-header {
display: flex;
align-items: center;
@@ -20,6 +20,7 @@
status: string;
heading: string;
orderIndex: number;
sceneId?: number;
progress?: Progress | null;
error?: string;
errorLong?: boolean;
@@ -30,6 +31,7 @@
status,
heading,
orderIndex,
sceneId,
progress = null,
error = '',
errorLong = false,
@@ -52,6 +54,9 @@
{:else}
<div class="empty">
<span class="slate">#{orderIndex}</span>
{#if sceneId != null}
<p class="sid">scene_id {sceneId}</p>
{/if}
<p class="title">{heading || 'Untitled'}</p>
{#if status === 'pending' || status === 'running'}
<div class="busy" aria-busy="true">
@@ -84,6 +89,12 @@
{/if}
</div>
<div class="ids">
<span>#{orderIndex}</span>
{#if sceneId != null}
<span class="ids-db">id {sceneId}</span>
{/if}
</div>
{#if previewUrl}
<div class="foot">
<a class="dl" href={previewUrl} download>
@@ -143,6 +154,15 @@
margin-bottom: 6px;
}
.sid {
margin: 0 0 8px;
font-family: var(--font-mono);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.04em;
color: var(--text-muted);
}
.title {
margin: 0 0 8px;
font-size: 14px;
@@ -204,6 +224,23 @@
overflow-y: auto;
}
.ids {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 2px 0;
font-family: var(--font-mono);
font-size: 12px;
font-weight: 700;
color: var(--accent);
flex-shrink: 0;
}
.ids-db {
font-weight: 600;
color: var(--text-muted);
}
.foot {
display: flex;
justify-content: flex-end;
@@ -73,7 +73,7 @@
class:selected={selectedId === scene.id}
class:chained={chained(scene)}
onclick={() => onSelect(scene.id)}
title={`${scene.heading || 'Scene'} · ${formatClock(scene.duration_sec || 5)}`}
title={`#${scene.order_index} · id ${scene.id} · ${scene.heading || 'Scene'} · ${formatClock(scene.duration_sec || 5)}`}
>
<span class="bar" aria-hidden="true"></span>
<span class="thumb" aria-hidden="true">
@@ -88,7 +88,7 @@
</span>
<span class="meta">
<span class="num">#{scene.order_index}</span>
<span class="dur">{formatClock(scene.duration_sec || 5)}</span>
<span class="sid">id {scene.id}</span>
</span>
</button>
{/each}
@@ -99,7 +99,7 @@
<Icon name="chevron-left" size={14} /> Prev
</Button>
<span class="pos">
{selected ? `Scene ${selected.order_index} of ${scenes.length}` : '—'}
{selected ? `#${selected.order_index} of ${scenes.length} · id ${selected.id}` : '—'}
</span>
<Button variant="ghost" size="sm" disabled={!selected} onclick={() => onStep(1)}>
Next <Icon name="chevron-right" size={14} />
@@ -232,9 +232,10 @@
color: var(--accent);
}
.dur {
.sid {
font-family: var(--font-mono);
font-size: 10px;
font-size: 9px;
font-weight: 600;
color: var(--text-muted);
}
@@ -248,7 +249,7 @@
.pos {
font-size: 12px;
color: var(--text-secondary);
min-width: 12ch;
min-width: 22ch;
text-align: center;
}
</style>
@@ -21,6 +21,7 @@
<div class="meta-wrap">
<div class="row">
<span class="num mono">#{scene.order_index}</span>
<span class="sid mono">id {scene.id}</span>
<span class="heading" title={scene.heading || 'Untitled scene'}>
{scene.heading || 'Untitled scene'}
</span>
@@ -98,6 +99,13 @@
flex-shrink: 0;
}
.sid {
font-size: 11px;
font-weight: 600;
color: var(--text-muted);
flex-shrink: 0;
}
.heading {
flex: 1;
min-width: 0;
@@ -6,18 +6,13 @@
*/
import type { Scene, Workflow } from '$lib/api';
import OmniComposer from '$lib/components/OmniComposer.svelte';
import type { AssetOption } from '$lib/assetPicker';
import ClipMonitor from './ClipMonitor.svelte';
import SceneFilmstrip from './SceneFilmstrip.svelte';
import SceneScriptDrawer from './SceneScriptDrawer.svelte';
type Thumb = { kind: 'image' | 'video'; src: string } | null;
interface AssetOption {
label: string;
path: string;
kind?: 'image' | 'video' | 'audio';
}
interface Progress {
progress?: number;
message?: string;
@@ -89,6 +84,7 @@
{status}
heading={selected.heading || 'Untitled'}
orderIndex={selected.order_index}
sceneId={selected.id}
{progress}
{error}
{errorLong}
+75
View File
@@ -0,0 +1,75 @@
# Calliope changelog — 23 August 2026
Notes for GitHub. Version on `main` before this follow-up was **1.2.0** (`a1e329c`).
---
## 1.2.0 (on `main`)
### Agents
- New **Agents** chat: plugin harness, event-sourced session log, sandbox vs linked-project modes.
- Tools for story, script, assets, video enqueue, `run_workflow`, and workspace bootstrap (`create_project` / `link_project` / `list_projects`).
- Settings → Agent: operator **hardening rules** appended to the system prompt (blank disables). Step budget `agent_max_steps`.
- `@workflow` mentions and file attachments in the composer.
- Human-in-the-loop for renders: `enqueue_asset_jobs` / `enqueue_video_jobs` / `run_workflow` need an explicit generate/confirm.
- Comfy MCP `comfy_*` generate tools are **not loaded**. Agents use Calliope HTTP tools only (`comfy_server_info`, `run_workflow`, enqueue).
- Sandbox `@generate` queues on hidden **Playground scratch** — does not `create_project` just to make an image.
- `attach_asset`: file a finished generate (`job_id` or path) onto a film as a character sheet, environment, or misc. item. Works from sandbox; refuses Playground scratch.
- Sandbox job cards poll Playground jobs so completed images show in chat.
- Composer `@` typeahead no longer crashes (`MENTION_LIMIT`); session load shows an error / loading state instead of an empty welcome.
### Assets
- Third entity type: **Misc. Items** (props/objects). LLM-extracted, editable in Story, generated on Assets. Items do not feed video ref slots.
### Video / ComfyUI
- Role tags: `(Input:video)`, `(Input:audio)`, `(Input:clipindex)` plus existing prompt/ref/size roles.
- **H3 Motion Context**: import FirstMotion + NextMotion pair; Video toggle **Continue motion from previous clip**; per-project latent prefix so projects do not collide in Comfy’s output folder.
- Ordered generic `(Input:image)` ref slots (node-id order) for multi-ref workflows (MiniMax H3).
- Worker uploads video via Comfy `/upload/image`; duration bump when continuing motion.
- Settings → Queue: poll timeout default **30 min** (`0` = wait indefinitely). Agent `wait_for_jobs` uses the same value.
### Script / continuity
- Per-scene **Chain from prev clip** (Script tab, merged from `#15`): at job run time, take the previous scene’s last frame (ffmpeg) and swap it into the location/ref slot for continuity. Missing previous clip falls back to the scene’s own refs.
### App / install
- Windows zip install path documented for **1.2.0**.
- Example MiniMax H3 Turbo T2V / I2V API-format workflows.
### UI polish (same day, on `main`)
- Agents welcome chips stay on a newly created session (`b587c56`).
---
## Follow-up (this commit)
### Video — reference picker
- Project → Video: Ref tiles open a **tabbed modal** instead of a long dropdown.
- Tabs: Characters, Environments, Misc. Items, Uploads (clips + uploads when the slot is video).
- Thumbnail grid, search, Upload new…, Clear slot.
- Video picker now includes **item** images as well as sheets, environments, clips, and uploads.
### Agents — HITL tightening
- Render tools (`run_workflow`, enqueue) are **hidden** from the model until the user asks to generate or confirms. Tagging `@workflow` alone is not permission.
- `[Calliope context]` appendix is stripped before intent checks (`kind=image` in the appendix cannot unlock renders).
- Confirmation / render-intent helpers live in `harness/policy.py`.
### Misc. Items
- Generate jobs write the output path onto the **item** row (`reference_image_path`). Queue labels show `Name · item`.
- Playground **Add to project** can create a **new** misc. item (does not overwrite existing items).
---
## Suggested GitHub release blurb (1.2.0 + follow-up)
Calliope 1.2.0 adds Agents chat (sandbox generates without creating a film, then `attach_asset` to file the picture), Misc. Items, H3 motion-context clip chaining, video/audio ref roles, a 30-minute Comfy poll timeout, and Script-tab chain-from-previous-clip.
Follow-up: tabbed video ref picker, stricter render HITL, and item generate/attach.