diff --git a/.gitignore b/.gitignore index c7194b84..e872604f 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,9 @@ AGENTS.md start.bat end.bat ScreenShots/ -docs/ +docs/* +!docs/changelogs/ +!docs/changelogs/** prototype/ 2026-*.md +!docs/changelogs/*.md diff --git a/README.md b/README.md index 70681341..d76881d1 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/calliope-backend/src/calliope/agent/harness/__init__.py b/calliope-backend/src/calliope/agent/harness/__init__.py index 3e167c62..c9559b23 100644 --- a/calliope-backend/src/calliope/agent/harness/__init__.py +++ b/calliope-backend/src/calliope/agent/harness/__init__.py @@ -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. " diff --git a/calliope-backend/src/calliope/agent/harness/log.py b/calliope-backend/src/calliope/agent/harness/log.py index 37923d0b..615c7524 100644 --- a/calliope-backend/src/calliope/agent/harness/log.py +++ b/calliope-backend/src/calliope/agent/harness/log.py @@ -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() diff --git a/calliope-backend/src/calliope/agent/harness/orchestrator.py b/calliope-backend/src/calliope/agent/harness/orchestrator.py index 9066751d..c1dbe03c 100644 --- a/calliope-backend/src/calliope/agent/harness/orchestrator.py +++ b/calliope-backend/src/calliope/agent/harness/orchestrator.py @@ -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: diff --git a/calliope-backend/src/calliope/agent/harness/plugins/render.py b/calliope-backend/src/calliope/agent/harness/plugins/render.py index 0e39114f..a7ddc6ad 100644 --- a/calliope-backend/src/calliope/agent/harness/plugins/render.py +++ b/calliope-backend/src/calliope/agent/harness/plugins/render.py @@ -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 [], } diff --git a/calliope-backend/src/calliope/agent/harness/plugins/script.py b/calliope-backend/src/calliope/agent/harness/plugins/script.py index 4581f0fa..e1e7a07b 100644 --- a/calliope-backend/src/calliope/agent/harness/plugins/script.py +++ b/calliope-backend/src/calliope/agent/harness/plugins/script.py @@ -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() diff --git a/calliope-backend/src/calliope/agent/harness/policy.py b/calliope-backend/src/calliope/agent/harness/policy.py new file mode 100644 index 00000000..f4c99223 --- /dev/null +++ b/calliope-backend/src/calliope/agent/harness/policy.py @@ -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) diff --git a/calliope-backend/src/calliope/agent/harness/prompts.py b/calliope-backend/src/calliope/agent/harness/prompts.py index 5aa353d2..a4b3f72f 100644 --- a/calliope-backend/src/calliope/agent/harness/prompts.py +++ b/calliope-backend/src/calliope/agent/harness/prompts.py @@ -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)." ) diff --git a/calliope-backend/src/calliope/agent/harness/registry.py b/calliope-backend/src/calliope/agent/harness/registry.py index c75cc086..29974293 100644 --- a/calliope-backend/src/calliope/agent/harness/registry.py +++ b/calliope-backend/src/calliope/agent/harness/registry.py @@ -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]]: diff --git a/calliope-backend/src/calliope/queue/worker.py b/calliope-backend/src/calliope/queue/worker.py index b00edb5e..1297452b 100644 --- a/calliope-backend/src/calliope/queue/worker.py +++ b/calliope-backend/src/calliope/queue/worker.py @@ -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 = ?", diff --git a/calliope-backend/src/calliope/routers/playground.py b/calliope-backend/src/calliope/routers/playground.py index a6f54ef7..eada8424 100644 --- a/calliope-backend/src/calliope/routers/playground.py +++ b/calliope-backend/src/calliope/routers/playground.py @@ -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() diff --git a/calliope-backend/tests/test_agent_harness.py b/calliope-backend/tests/test_agent_harness.py index d7e47051..1265ed70 100644 --- a/calliope-backend/tests/test_agent_harness.py +++ b/calliope-backend/tests/test_agent_harness.py @@ -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 diff --git a/calliope-backend/tests/test_agent_security.py b/calliope-backend/tests/test_agent_security.py index 6081d9d8..a1a09ad7 100644 --- a/calliope-backend/tests/test_agent_security.py +++ b/calliope-backend/tests/test_agent_security.py @@ -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") diff --git a/calliope-backend/tests/test_item_generate_attach.py b/calliope-backend/tests/test_item_generate_attach.py new file mode 100644 index 00000000..a38aeb72 --- /dev/null +++ b/calliope-backend/tests/test_item_generate_attach.py @@ -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" diff --git a/calliope-backend/tests/test_playground.py b/calliope-backend/tests/test_playground.py index d2c06317..221ed7ef 100644 --- a/calliope-backend/tests/test_playground.py +++ b/calliope-backend/tests/test_playground.py @@ -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 diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts index 93df1908..577f2e92 100644 --- a/calliope-web/src/lib/api.ts +++ b/calliope-web/src/lib/api.ts @@ -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) }, ), diff --git a/calliope-web/src/lib/assetPicker.ts b/calliope-web/src/lib/assetPicker.ts new file mode 100644 index 00000000..a940c48f --- /dev/null +++ b/calliope-web/src/lib/assetPicker.ts @@ -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)); +} diff --git a/calliope-web/src/lib/components/AssetsStage.svelte b/calliope-web/src/lib/components/AssetsStage.svelte index a1dd79c1..fc39a7f2 100644 --- a/calliope-web/src/lib/components/AssetsStage.svelte +++ b/calliope-web/src/lib/components/AssetsStage.svelte @@ -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; diff --git a/calliope-web/src/lib/components/AttachToProject.svelte b/calliope-web/src/lib/components/AttachToProject.svelte index ff15c980..b4a4302d 100644 --- a/calliope-web/src/lib/components/AttachToProject.svelte +++ b/calliope-web/src/lib/components/AttachToProject.svelte @@ -29,6 +29,7 @@ let target = $state('character_sheet'); let characterId = $state(''); let locationId = $state(''); + let itemName = $state(''); let sceneId = $state(''); let message = $state(''); let characters = $state([]); @@ -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 @@ {:else if !open} - + {:else}
@@ -177,7 +198,7 @@ No characters in this project yet. {/if} - {:else} + {:else if target === 'location'} {/if} {:else}