From ce0b4e198314b21d9749951fee81ca33ffd64bd9 Mon Sep 17 00:00:00 2001 From: Benjiyaya Date: Fri, 11 Sep 2026 18:05:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20release=201.5.0=20=E2=80=94=20Build=20S?= =?UTF-8?q?cene=203D=20blockout=20composer=20+=201=20scene=20:=20N=20shot?= =?UTF-8?q?=20clips?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Build Scene (/build-scene): three.js + mannequin-js blockout viewport ported from open-media, with per-session compositions (origin='scene' keeps rails separate), agent shot_* tools as the only toolset for that surface, viewport toolbar, keyframe motion + camera timeline with 60s video export, and captures usable as project reference images. Scene to Clips: clips table (1 scene : N renderable shots), coverage agent breaks scenes into shots with full dialogue/action allocation, script generation stays faithful to the screenplay (verbatim dialogue, content- derived durations, chunked + durable inserts), video pipeline re-scoped to clips (enqueue, continue-from, export, drafts), Script/Video UI clip-first (#N.M labels, per-scene Break Into Shots scoped to one scene). Agent loop: lean ReAct discipline with fail-streak escalation and budget nudge; policy treats explicit user commands as permission; Build Scene tool scope enforced mechanically; document + video attachments feed the VLM. --- .gitignore | 3 + README.md | 27 +- calliope-backend/contracts.json | 31 +- calliope-backend/scripts/export_contracts.py | 3 + .../shot-composer-blockout/SKILL.md | 65 + .../references/motion-recipes.md | 118 ++ .../src/calliope/agent/coverage_agent.py | 318 +++++ .../src/calliope/agent/harness/__init__.py | 32 +- .../src/calliope/agent/harness/log.py | 229 +++- .../src/calliope/agent/harness/loop.py | 52 +- .../calliope/agent/harness/orchestrator.py | 9 + .../agent/harness/plugins/__init__.py | 1 + .../calliope/agent/harness/plugins/render.py | 158 ++- .../calliope/agent/harness/plugins/script.py | 476 ++++++- .../agent/harness/plugins/shot_builder.py | 1150 +++++++++++++++++ .../src/calliope/agent/harness/policy.py | 80 +- .../src/calliope/agent/harness/prompts.py | 129 +- .../src/calliope/agent/harness/registry.py | 47 +- .../src/calliope/agent/harness/runner.py | 33 +- calliope-backend/src/calliope/agent/llm.py | 68 +- .../src/calliope/agent/prompts.py | 127 +- .../src/calliope/agent/script_agent.py | 147 ++- .../src/calliope/agent/video_agent.py | 289 +++-- calliope-backend/src/calliope/db.py | 163 ++- .../src/calliope/export/runner.py | 30 +- calliope-backend/src/calliope/main.py | 3 + .../src/calliope/models/schemas.py | 41 +- calliope-backend/src/calliope/poses.py | 141 ++ .../src/calliope/queue/manager.py | 7 +- calliope-backend/src/calliope/queue/worker.py | 93 +- .../src/calliope/routers/agent.py | 68 +- calliope-backend/src/calliope/routers/jobs.py | 29 +- .../src/calliope/routers/playground.py | 12 +- .../src/calliope/routers/scenes.py | 244 +++- .../src/calliope/routers/shots.py | 434 +++++++ .../src/calliope/routers/story.py | 279 ++-- .../tests/test_agent_event_log.py | 119 +- calliope-backend/tests/test_agent_harness.py | 4 +- calliope-backend/tests/test_agent_skills.py | 2 + calliope-backend/tests/test_clips.py | 612 +++++++++ calliope-backend/tests/test_export.py | 49 +- calliope-backend/tests/test_scene_settings.py | 75 +- calliope-backend/tests/test_session_origin.py | 192 +++ calliope-backend/tests/test_shot_tools.py | 609 +++++++++ calliope-backend/tests/test_video_continue.py | 21 +- calliope-backend/tests/test_video_vision.py | 86 ++ calliope-web/package-lock.json | 71 +- calliope-web/package.json | 7 +- calliope-web/src/lib/agentComposer.ts | 2 +- calliope-web/src/lib/api.ts | 42 +- calliope-web/src/lib/assetPicker.ts | 8 +- calliope-web/src/lib/comfy/types.ts | 21 + .../src/lib/comfy/useUpload.svelte.ts | 1 + .../src/lib/components/AppHeader.svelte | 3 +- .../src/lib/components/QueueStage.svelte | 469 ++++--- .../src/lib/components/ScriptStage.svelte | 201 ++- .../lib/components/agent/AgentComposer.svelte | 6 +- .../components/omni/AssetPickerModal.svelte | 1 + calliope-web/src/lib/components/ui/icons.ts | 1 + .../lib/components/video/ClipMonitor.svelte | 58 +- .../components/video/ClipSourceModal.svelte | 2 +- .../video/PromptPreviewModal.svelte | 88 +- .../components/video/SceneFilmstrip.svelte | 120 +- .../video/VideoEditWorkspace.svelte | 69 +- calliope-web/src/lib/events.ts | 2 + calliope-web/src/lib/shot/api.ts | 55 + .../shot/calibration/compositionPresets.ts | 26 + .../src/lib/shot/calibration/shotAxes.ts | 24 + .../src/lib/shot/calibration/shotSolver.ts | 388 ++++++ .../lib/shot/components/CaptureStrip.svelte | 161 +++ .../src/lib/shot/components/ScenePanel.svelte | 237 ++++ .../lib/shot/components/ShotInspector.svelte | 311 +++++ .../shot/components/ShotSessionRail.svelte | 299 +++++ .../lib/shot/components/ShotViewport.svelte | 873 +++++++++++++ .../lib/shot/components/TimelineStrip.svelte | 311 +++++ .../shot/components/ViewportToolbar.svelte | 139 ++ .../src/lib/shot/helpers/cameraUtils.ts | 85 ++ .../src/lib/shot/helpers/jointConfig.ts | 222 ++++ .../src/lib/shot/helpers/mannequinFactory.ts | 141 ++ calliope-web/src/lib/shot/helpers/mirror.ts | 60 + calliope-web/src/lib/shot/helpers/posture.ts | 182 +++ .../src/lib/shot/helpers/primitiveFactory.ts | 45 + .../src/lib/shot/motion/sampleTrack.ts | 122 ++ calliope-web/src/lib/shot/shotStore.svelte.ts | 742 +++++++++++ .../src/lib/shot/types/mannequin-js.d.ts | 9 + .../src/routes/build-scene/+page.svelte | 665 ++++++++++ .../src/routes/canvas/[id]/+page.svelte | 33 +- docs/changelogs/2026-09-07-chunking-cards.md | 36 +- .../2026-09-10-build-scene-clips.md | 151 +++ docs/changelogs/README.md | 1 + 90 files changed, 12482 insertions(+), 913 deletions(-) create mode 100644 calliope-backend/skills_builtin/shot-composer-blockout/SKILL.md create mode 100644 calliope-backend/skills_builtin/shot-composer-blockout/references/motion-recipes.md create mode 100644 calliope-backend/src/calliope/agent/coverage_agent.py create mode 100644 calliope-backend/src/calliope/agent/harness/plugins/shot_builder.py create mode 100644 calliope-backend/src/calliope/poses.py create mode 100644 calliope-backend/src/calliope/routers/shots.py create mode 100644 calliope-backend/tests/test_clips.py create mode 100644 calliope-backend/tests/test_session_origin.py create mode 100644 calliope-backend/tests/test_shot_tools.py create mode 100644 calliope-backend/tests/test_video_vision.py create mode 100644 calliope-web/src/lib/shot/api.ts create mode 100644 calliope-web/src/lib/shot/calibration/compositionPresets.ts create mode 100644 calliope-web/src/lib/shot/calibration/shotAxes.ts create mode 100644 calliope-web/src/lib/shot/calibration/shotSolver.ts create mode 100644 calliope-web/src/lib/shot/components/CaptureStrip.svelte create mode 100644 calliope-web/src/lib/shot/components/ScenePanel.svelte create mode 100644 calliope-web/src/lib/shot/components/ShotInspector.svelte create mode 100644 calliope-web/src/lib/shot/components/ShotSessionRail.svelte create mode 100644 calliope-web/src/lib/shot/components/ShotViewport.svelte create mode 100644 calliope-web/src/lib/shot/components/TimelineStrip.svelte create mode 100644 calliope-web/src/lib/shot/components/ViewportToolbar.svelte create mode 100644 calliope-web/src/lib/shot/helpers/cameraUtils.ts create mode 100644 calliope-web/src/lib/shot/helpers/jointConfig.ts create mode 100644 calliope-web/src/lib/shot/helpers/mannequinFactory.ts create mode 100644 calliope-web/src/lib/shot/helpers/mirror.ts create mode 100644 calliope-web/src/lib/shot/helpers/posture.ts create mode 100644 calliope-web/src/lib/shot/helpers/primitiveFactory.ts create mode 100644 calliope-web/src/lib/shot/motion/sampleTrack.ts create mode 100644 calliope-web/src/lib/shot/shotStore.svelte.ts create mode 100644 calliope-web/src/lib/shot/types/mannequin-js.d.ts create mode 100644 calliope-web/src/routes/build-scene/+page.svelte create mode 100644 docs/changelogs/2026-09-10-build-scene-clips.md diff --git a/.gitignore b/.gitignore index da391df7..b060e466 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,6 @@ docs/* prototype/ 2026-*.md !docs/changelogs/*.md + +# --- Reference clones (vendored for porting only) --- +reference/ diff --git a/README.md b/README.md index 01ef76d5..bcaf6de1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Calliope -Calliope is a local-first story-to-video studio. You type a story idea; Calliope drafts a storyline with beats, characters, and locations, writes a per-scene script, then generates a video clip per scene by driving your own ComfyUI install. When the clips are done, one click stitches them into a finished film with crossfades and matched loudness (ffmpeg). Everything runs on your machine: projects live in SQLite, media lives in folders, and no cloud service is involved beyond the LLM endpoint you point it at. +Calliope is a local-first story-to-video studio. You type a story idea; Calliope drafts a storyline with beats, characters, and locations, writes a screenplay-faithful per-scene script, then **breaks each scene into shot clips** and generates one video per clip by driving your own ComfyUI install. When the clips are done, one click stitches them into a finished film with crossfades and matched loudness (ffmpeg). Everything runs on your machine: projects live in SQLite, media lives in folders, and no cloud service is involved beyond the LLM endpoint you point it at. Screenshot 2026-09-06 050058 @@ -76,13 +76,15 @@ The app walks a project through four stages — **Story, Assets, Script, Video** - **Story:** describe your idea and **Draft Storyline** — this opens a project-linked chat in the Agents view with the prompt pre-filled, and the agent writes beats, characters, locations, and misc. items. Edit anything by hand before moving on. - **Assets:** each character, location, and item has its own **Image prompt**. Pick a workflow and shared settings (width/height/etc.) at the top, then click Generate per entity to produce reference images on your ComfyUI. Regenerate any single entity without touching the others. -- **Script:** **Regenerate Script** also opens a project-linked Agents chat (pre-filled) to rewrite the per-scene script. Scenes link back to the characters and locations from the Story stage. -- **Video:** each scene gets a **Generate** button that queues a clip job on ComfyUI with the right prompt and reference images (plus optional video/audio file refs). Scenes marked **Continue from previous video** in Script extend the previous clip instead of cutting fresh — see [Continue from previous clip (video extend)](#continue-from-previous-clip-video-extend). -- **Film view:** once scenes have clips, **Export film** stitches them with ffmpeg: clips are normalized to 1080p at the **majority frame rate of the clips themselves** (24 fps clips export at 24 fps; mixed-rate projects conform to whichever rate most clips use), joined with 0.5s crossfades, and loudness-normalized into one final file. +- **Script:** **Regenerate Script** also opens a project-linked Agents chat (pre-filled) to rewrite the per-scene script. Scenes preserve the full screenplay: complete action prose and verbatim dialogue. Then **Break into shots** splits a scene into its shot clips — an LLM coverage pass allocates every dialogue line and action beat across clips of ~5–10 seconds (a 2-minute dialogue scene becomes a dozen clips, not one). Scenes link back to the characters and locations from the Story stage. +- **Video:** each clip gets rendered by a **Generate** pass that queues a job on ComfyUI with the right prompt and reference images (plus optional video/audio file refs). Clips marked **Continue from previous clip** extend the previous clip instead of cutting fresh — see [Continue from previous clip (video extend)](#continue-from-previous-clip-video-extend). +- **Film view:** once clips are rendered, **Export film** stitches them with ffmpeg: clips are normalized to 1080p at the **majority frame rate of the clips themselves** (24 fps clips export at 24 fps; mixed-rate projects conform to whichever rate most clips use), joined with 0.5s crossfades, and loudness-normalized into one final file. - When everything is done the project is automatically marked **Completed**. **Playground** is a free-form generation page outside the project pipeline: run any imported workflow with arbitrary inputs, upload your own files (image / video / audio) as inputs, and optionally attach a result to a project as an asset. +**Build Scene** is a browser-based 3D shot composer for blocking out cinematic shots before generating AI images or video. Instead of describing camera framing and character pose in text, you (or the agent chat) pose mannequin characters, place primitive props, and frame the camera in a three.js viewport — then **Capture PNG** (top-center of the viewport) a blockout that lands in every project reference picker under **From Build Scene**, ready to feed ControlNet-style `(Input:image)` slots. Scenes are managed like AI Canvas chats: a left rail holds any number of compositions, each bound to its own agent session, and deleting one removes its scene and captures. The viewport also has a **camera timeline** (max 60s): keyframe the camera at playheads, press play to fly the view along the track, and **Export video** to save the fly-through as a clip — it shows up alongside image blockouts in project clip pickers. The right-hand agent panel drives the same scene through built-in tools (no MCP): add/pose/frame commands mutate a server-side composition JSON, and `request_capture` grabs a render on demand. + **Agents** is a chat-driven way to run the same pipeline: talk to a production agent that operates Calliope through tools (create project, draft story, write script, queue asset/video renders, watch jobs). Every chat session is bound to at most one project — start a **Sandbox** chat with no project and the agent materializes one via `create_project`, linking the session automatically; or link a session to an existing project and ask for edits. Complex builds are decomposed by a planner into sub-agents (story → script → assets → video). Everything the agent does goes through the same database and render queue the project UI reads — nothing bypasses the normal pipeline. When the agent waits on renders (`wait_for_jobs`), it uses the same **Poll timeout** as the queue worker (default 30 minutes). ## ComfyUI workflows (important) @@ -152,32 +154,32 @@ For multi-reference workflows, generic `(Input:image)` inputs are filled in **no ### Continue from previous clip (video extend) -Long takes don't have to be one giant generation. Mark a scene **Continue from previous video** in the **Script** stage and instead of cutting a fresh clip, it extends the previous scene's clip as real continuation footage (the first scene can't use the toggle). +Long takes don't have to be one giant generation. Mark a clip **Continue from previous clip** in the **Script** stage (the toggle lives on a scene when it hasn't been expanded — expanding migrates it onto the clip) and instead of cutting a fresh clip, it extends the previous clip in the timeline as real continuation footage (the first clip can't use the toggle). -The **Video** stage enforces one requirement: the scene's workflow must have an input tagged `(Input:video)` (a `LoadVideo` node). Continue scenes on a workflow without one have Generate disabled with a warning. +The **Video** stage enforces one requirement: the workflow must have an input tagged `(Input:video)` (a `LoadVideo` node). Continue clips on a workflow without one have Generate disabled with a warning. When the workflow qualifies, a **clip source picker** appears on the continue scene: -- **Auto** (default) — the previous scene's clip is used, resolved when the job actually runs. +- **Auto** (default) — the previous clip in timeline order is used, resolved when the job actually runs. - **Upload file** — extend from any video you provide (a Playground upload). -- **From timeline** — pick a specific earlier scene's clip explicitly. +- **From timeline** — pick a specific earlier clip explicitly. -Auto is safe even when scenes are queued in one batch: Calliope's queue renders one job at a time, so by the time a continue scene runs, the scene before it has already rendered and its clip is picked up automatically. +Auto is safe even when clips are queued in one batch: Calliope's queue renders one job at a time, so by the time a continue clip runs, the clip before it has already rendered and is picked up automatically. The workflow pattern (per [kat3ri/ComfyUI-MiniMax-H3-Extend](https://github.com/kat3ri/ComfyUI-MiniMax-H3-Extend)) is a `LoadVideo (Input:video)` node feeding the MiniMax H3 extend patched nodes (`MiniMaxH3EncodeAVPatched` → `MiniMaxH3VideoExtendPatched`) with the `(Output:video)` node at the end. Recommended starting settings from that repo: `context_frames` **2**, `ref_spacing` **1–2**, `ref_decay` **0.3**, `ref_ramp` **3–4** (5–6 if the prior clip had heavy motion). ### Review the prompt before you generate -Generate no longer fires blind. Hitting **Generate clip** first opens a prompt preview: the exact text that will land on the workflow's `(Input:prompt)` node — your saved draft if there is one, otherwise a fresh MiniMax H3 rewrite (six-section format) or the prose scene prompt. +Generate no longer fires blind. Hitting **Generate** first opens a prompt preview: the exact text that will land on the workflow's `(Input:prompt)` node — your saved draft if there is one, otherwise a fresh MiniMax H3 rewrite (six-section format) or the prose clip prompt (scene heading, the clip's shot description, and only the dialogue lines that clip performs). - **Edit it inline** — typos, camera notes, pacing, anything. The edited text is what gets sent. - **Regenerate** re-runs the H3 rewrite for a different take. -- **Save draft** keeps it on the scene; future generates (single or **Generate all**) reuse the draft instead of calling the LLM again. A hint appears when the draft predates changes to the scene. +- **Save draft** keeps it on the clip; future generates (single or **Generate all**) reuse the draft instead of calling the LLM again. A hint appears when the draft predates changes to the scene or clip. - **Cancel** aborts with nothing enqueued. After a render, **View prompt & inputs** opens the scene's render history: every job as a chip, the payload each one actually sent to ComfyUI, and **Copy settings to form** to pull a past job's input values back into the live form. -Your video-stage setup (workflow choice, input values, clip source) auto-saves per scene and comes back after a reload or app restart. **Generate all** honors every scene's saved setup and drafts — the toast reports how many drafts were used. +Your video-stage setup (workflow choice, input values, clip source) auto-saves and comes back after a reload or app restart. **Generate all** honors every saved setup and draft — the toast reports how many drafts were used. ### Better ComfyUI errors @@ -216,4 +218,3 @@ calliope-web/ SvelteKit frontend example_ComfyUI_workflows/ ready-to-import API-format workflow JSONs docs/wiki/ design notes (wiki source): ComfyUI HTTP vs MCP, multi-ref workflows ``` - diff --git a/calliope-backend/contracts.json b/calliope-backend/contracts.json index 2b410aa7..a8aaf35c 100644 --- a/calliope-backend/contracts.json +++ b/calliope-backend/contracts.json @@ -59,21 +59,30 @@ "agent_tool_names": [ "add_beat", "add_character", + "add_clip", "add_item", + "add_keyframe", "add_location", + "add_object", "add_scene", + "apply_pose", "ask_user", "attach_asset", + "break_into_shots", "canvas_connect", "canvas_link", + "clear_scene", "comfy_server_info", "create_canvas_node", "create_project", "delete_beat", "delete_canvas_node", "delete_character", + "delete_clip", "delete_item", + "delete_keyframe", "delete_location", + "delete_object", "delete_scene", "enqueue_asset_jobs", "enqueue_video_jobs", @@ -81,27 +90,44 @@ "generate_script", "generate_story", "get_job_status", + "get_scene", "get_story", "get_workspace", "link_project", + "list_clips", "list_jobs", "list_memories", + "list_poses", "list_projects", "list_scenes", + "list_shot_presets", "list_skills", "list_workflows", + "move_keyframe_time", "post_artifact_to_canvas", "read_skill", + "rename_object", "reorder_scenes", + "request_capture", + "reset_pose", + "reset_transform", "run_canvas_node", "run_workflow", "save_memory", + "select_object", + "set_joint", + "set_playback", + "set_posture", + "set_shot", + "set_transform", "summarize_canvas", "unlink_project", "update_beat", "update_canvas_node", "update_character", + "update_clip", "update_item", + "update_keyframe", "update_location", "update_project", "update_scene", @@ -123,6 +149,8 @@ "job.failed", "job.progress", "job.started", + "shot.capture.saved", + "shot.updated", "story.ready" ], "prompt_profiles": [ @@ -131,6 +159,7 @@ ], "guard_codes": [ "guard_destructive_replace", - "guard_render_approval" + "guard_render_approval", + "guard_scene_tool_scope" ] } diff --git a/calliope-backend/scripts/export_contracts.py b/calliope-backend/scripts/export_contracts.py index 068d9609..69de15ac 100644 --- a/calliope-backend/scripts/export_contracts.py +++ b/calliope-backend/scripts/export_contracts.py @@ -73,7 +73,10 @@ def _extract_prompt_profiles() -> list[str]: def _extract_guard_codes() -> list[str]: + # Guard codes are DEFINED in registry.py (avoids the circular import) and + # re-exported through harness/__init__.py — scan both. text = (SRC / "agent" / "harness" / "__init__.py").read_text(encoding="utf-8") + text += "\n" + (SRC / "agent" / "harness" / "registry.py").read_text(encoding="utf-8") return sorted(set(re.findall(r'GUARD_[A-Z_]+ = "([a-z_]+)"', text))) diff --git a/calliope-backend/skills_builtin/shot-composer-blockout/SKILL.md b/calliope-backend/skills_builtin/shot-composer-blockout/SKILL.md new file mode 100644 index 00000000..5e62502d --- /dev/null +++ b/calliope-backend/skills_builtin/shot-composer-blockout/SKILL.md @@ -0,0 +1,65 @@ +--- +name: shot-composer-blockout +description: "Use when the user asks to build, pose, frame, or ANIMATE a 3D scene in Build Scene — characters, primitives, shot framing, keyframe motion, or exporting a blockout as a generation reference." +version: 1.0.0 +license: MIT +metadata: + author: Calliope + tags: [build-scene, 3d, blockout, keyframes, camera, controlnet] +--- + +# Shot Composer Blockout + +## Overview + +Judgment layer for driving the Build Scene composition through the `shot_*` +tools. The machine contract lives in the tools themselves; this skill is the +workflow — how to think about the scene, and in what order to touch it. +Adapted from open-media's agent guide, with motion-recipe judgment folded in. + +## Scene model + +- The scene is a flat list of **objects**: characters (`male`/`female`/`child`), + primitives (`cube`, `plane`, `cylinder`, `sphere`, `capsule`, `cone`, + `torus`). `get_scene` first, always — it's cheap and tells you what exists, + what's selected, playback state, and every keyframe id. +- Objects are addressed by **id** from `get_scene`/`add_object` — never invent + ids. `select_object` is for pointing the user's UI at the subject (and + `set_shot` solves from it); edits themselves always pass explicit ids. +- **Posture is opaque** (`{version, data:[...]}`, fixed-arity arrays). Never + hand-construct it — pose via `list_poses` + `apply_pose`, then fine-tune + single joints with `set_joint`. +- Framing (`shotSize/angle/elevation/composition`) is scene-global, not + per-object. `set_shot` merges partial updates. OTS needs a second character. + +## Preferred workflow + +1. `get_scene` — see what's there. +2. Build: `add_object`, `set_transform` ([x,y,z], y-up, characters stand on + y=0), `apply_pose` for stances. +3. Frame: `select_object` the subject → `set_shot` (montage via + `list_shot_presets` when unsure of valid ids). +4. Animate: stage → `add_keyframe` → stage → `add_keyframe` (see + `references/motion-recipes.md` — read it before any non-trivial motion). +5. `request_capture` when the user wants the frame as a generation reference. + It returns the saved PNG path — no GPU, no approval. + +## Motion rules (read before keyframing) + +- **Stage, then commit.** `set_transform`/`set_joint` write the object's live + state; `add_keyframe(object_id, time)` pins that state at a second (0-60). + An object with no track gets a spawn keyframe at t=0 automatically. +- **Never call `add_keyframe` twice with the same time for different poses** — + within 1/24s it REPLACES (upsert). Move it with `move_keyframe_time` instead. +- **Respect the track.** Once a track exists, `set_transform` only stages — it + does NOT rewrite committed keyframes. To change the pose AT a keyframe, edit + with `update_keyframe`, not `set_transform`. +- **Duration ≤ 60s.** `set_playback(duration)` caps there; keep keyframe times + within the duration. Preview loops. + +## When a capability seems missing + +Don't work around a gap by inventing behavior (no hand-rolled posture arrays, +no invented tool names). Check `get_scene` output first; if a capability truly +doesn't exist as a tool, say so — it's an app-feature gap, not a prompting +problem. diff --git a/calliope-backend/skills_builtin/shot-composer-blockout/references/motion-recipes.md b/calliope-backend/skills_builtin/shot-composer-blockout/references/motion-recipes.md new file mode 100644 index 00000000..d767f5d3 --- /dev/null +++ b/calliope-backend/skills_builtin/shot-composer-blockout/references/motion-recipes.md @@ -0,0 +1,118 @@ +# Motion Recipes + +Timing and choreography judgment for keyframed blockout motion, adapted from +classic animation-timing practice (anime.js/GSAP timeline choreography and the +12-principles shorthand) translated into `shot_*` tool calls. Times are +seconds; the timeline max is 60. + +## Core pattern: stage → commit + +Every recipe is the same loop: + +1. `set_transform` (and/or `set_joint`) — stage the pose +2. `add_keyframe(object_id, time)` — pin it +3. change only `time` between commits — the interpolation engine does the rest + +Spacing between keyframes controls speed; what you stage controls meaning. + +## Easing without an easing control + +Interpolation between two keyframes is smoothstep (ease-in-out). Use that as +the default motion feel. To fake other easings with plain keyframes: + +- **Ease-out (decelerate to rest)** — sample the curve: for a 3s move to + x=6, commit at t=0 (x=0), t=0.6 (x≈3.4), t=1.5 (x≈5.4), t=3 (x=6). Two + early keyframes close together, then a long glide. +- **Constant speed (linear)** — 3+ evenly spaced keyframes flatten the + smoothstep: t=0, 1, 2, 3 at equal position steps. +- **Anticipation (cartoon read)** — before the main move, commit a small pose + in the OPPOSITE direction: crouch at t=1 (y −0.15), launch at t=1.4, + land at t=2.6. The beat before the action sells the action. + +## Canonical recipes + +**Walk-across (A → B):** spawn key at t=0 (auto); `set_transform` B → +`add_keyframe` at t=d. Add a mid key at t=d/2 with a slight y bounce +(±0.05) if the character should feel alive. Legs won't step — this is +blockout framing, not final animation. + +**Jump:** crouch (y −0.2, knees bent via `set_joint`) at t=0 → apex +(y +1, legs extended) at t=0.5 → ground (y 0, knees bent landing) at t=1 → +settle (standing posture) at t=1.3. The crouch IS the anticipation. + +**Head turn / look:** keep position fixed; `set_joint` head y ±60°, key at +t=0.2, then to the new heading at t=0.8. Small and slow beats big and fast +for reads. + +**Door / prop interaction:** character walks to the prop (walk-across), +pause key 0.3s, arm extends (`set_joint` l_arm) + key, prop transform changes +(`update_keyframe` or its own track) on the same beat. + +**Two objects crossing:** keyframe object A on its track first (all its +times), then object B. Overlap the mid times so the crossing happens near +the same beat — the eye reads simultaneous motion as intentional. + +## Camera vs objects + +Object tracks are viewport preview for framing; the **camera track is what +export renders**. To feature object motion in an exported clip, keep motion +within the framed area and let the camera track hold (or slowly push) while +the action plays. Keys for the camera come from the timeline UI (◉), not +from `shot_*` tools. + +## Timing vocabulary (rule of thumb) + +| Read | Key spacing | +|---|---| +| Snap / impact | ≤ 0.2s between keys | +| Normal action | 0.5–1.5s | +| Drift / ambience | 3s+ | +| Hold | duplicate the same pose at a later time (never delete the last key) | + +## Failure handling + +- Object jumps back to an old position mid-playback: a stale keyframe is + being sampled — `get_scene`, find it, `update_keyframe` or + `move_keyframe_time` (don't re-stage over it with `set_transform`). +- `add_keyframe` refused at t>60: the timeline caps at 60s; widen the + choreography, don't fight the cap. +- Character vanishes after posing: a malformed posture array NaNs + mannequin-js silently — `reset_pose` restores it; never hand-build + posture data. + +## Video → blockout (attached clip recreation) + +An attached video arrives as ~8 evenly-spaced frames, each stamped with its +time in the clip (`frame at 1.25s`). The frames ARE the motion storyboard — +recreate it, don't improvise a new choreography. + +**Workflow:** + +1. **Read the frames in order** — identify subjects (characters vs moving + props), roughly where each starts/ends, and the big pose changes between + consecutive frames. +2. **Build the cast** — `add_object` for each subject, positioned to match + the FIRST frame. Name them after their role in the clip (e.g. + "Fighter A"). +3. **Key the opening pose** — stage pose/transform to match frame 1, then + `add_keyframe(subject, 0)`. +4. **Walk the frames** — for each later frame at time t: stage the pose + change you see (`set_transform` for travel, `set_joint` for limb work), + then `add_keyframe(subject, t)` using the FRAME's timestamp, not a + rounded number. Key EVERY subject on the SAME timestamps so their tracks + stay synchronized with each other and with the video clock. +5. **Finish** — `set_playback(duration=)`, then tell the user + what you captured and what you approximated. + +**Fidelity rules:** + +- Fast motion (a punch, a spin) between two frames: 2–3 keys on the travel + path beat one heroic guess — read the timing vocabulary table above. +- Camera moves in the clip are perspective changes, not subject motion — + block the SUBJECTS; do not move the camera for them (the camera track is + the user's, keyed from the timeline UI). +- 8 frames can't hold every beat. Prioritize the pose changes that define + the action (start, contact, recoil, end); say so in your summary. +- If the frames are ambiguous (motion blur, off-screen action), take the + simple read and note it — never fabricate precise choreography you can't + see. diff --git a/calliope-backend/src/calliope/agent/coverage_agent.py b/calliope-backend/src/calliope/agent/coverage_agent.py new file mode 100644 index 00000000..041750ea --- /dev/null +++ b/calliope-backend/src/calliope/agent/coverage_agent.py @@ -0,0 +1,318 @@ +"""Break a script scene into N renderable shot clips (coverage expansion). + +One script scene usually films as many shots: establishing wide, dialogue +coverage, cutaways, insert close-ups. This pass asks the LLM to allocate the +scene's full content — every dialogue line and significant action beat — +across those clips, with durations that sum to the scene's budget and each +clip inside the per-clip duration cap. +""" +from __future__ import annotations + +import asyncio +import json +import logging +from typing import Any + +from calliope.agent.llm import generate_structured +from calliope.agent.prompts import DEFAULT_CLIP_DURATION_SEC, estimate_scene_duration_sec +from calliope.config import settings +from calliope.db import get_db, row_to_dict +from calliope.events.bus import event_bus + +logger = logging.getLogger("calliope.coverage_agent") + +# Scenes expanded per LLM call (same chunking rationale as generate_script). +COVERAGE_CHUNK = 4 + + +def _dialog_lines(dialog: str | None) -> list[str]: + return [ln for ln in (dialog or "").splitlines() if ln.strip()] + + +def _coverage_messages( + *, + scene: dict[str, Any], + characters: list[dict[str, Any]], + previous_heading: str | None, + next_heading: str | None, + clip_cap: int, +) -> list[dict[str, str]]: + """LLM messages that split one scene into shot clips.""" + lines = _dialog_lines(scene.get("dialog")) + numbered_dialog = ( + "\n".join(f"{i + 1}. {ln}" for i, ln in enumerate(lines)) + or "(no dialogue in this scene)" + ) + char_lines = "\n".join( + f"- id={c['id']} {c['name']}: {(c.get('appearance') or '').strip()}" + for c in characters + ) + scene_secs = estimate_scene_duration_sec(scene) or scene.get("duration_sec") or clip_cap + n_clips_hint = max(1, round(scene_secs / clip_cap)) + context = "" + if previous_heading or next_heading: + context = ( + f"\nNeighbor scenes (for continuity, do NOT rewrite them):\n" + f" Before: {previous_heading or '(none)'}\n" + f" After: {next_heading or '(none)'}\n" + ) + user = f"""Break this script scene into AI-video shot clips (coverage). + +Scene {scene.get('order_index')}: {scene.get('heading') or '(no heading)'} +Scene budget: ~{scene_secs} seconds total across all clips +Typical clip length: {clip_cap} seconds (never longer — video models degrade beyond ~10s) +Suggested clip count: ~{n_clips_hint} (adjust to the material) +{context} +Characters in this scene: +{char_lines or '(none)'} + +Full action (cover ALL of it across the clips): +{scene.get('action') or '(none)'} + +Dialogue lines (verbatim, numbered): +{numbered_dialog} + +=== HARD CONSTRAINTS (non-negotiable) === +1. FULL COVERAGE: every numbered dialogue line is covered by EXACTLY ONE clip (via + dialog_lines_covered), and together the clips' descriptions perform the ENTIRE action — + no skipped beats, no duplicated dialogue. +2. Order: clip 1 plays first, then 2, ... matching the action's chronology. +3. Each clip's description is a self-contained video prompt: framing + subject + motion + + setting, present tense, 1–4 sentences. Include a character anchor (hair/outfit feature) + the first time a character appears in a clip. +4. duration_sec per clip: 3–{clip_cap}; the SUM should be approximately the scene budget. +5. shot_size is one of: wide, medium, closeUp, insert, overShoulder. +6. Set chain_from_prev=true ONLY when this clip should literally continue the previous + clip's rendered frames (same camera take / motion carry). Usually false — a cut is fine. + +Respond ONLY with JSON: +{{ + "clips": [ + {{ + "order_index": 1, + "description": "Wide establishing shot…", + "dialog_lines_covered": [], + "shot_size": "wide", + "duration_sec": 6, + "chain_from_prev": false + }} + ] +}} + +FINAL CHECK: every dialogue line number appears exactly once across all clips, durations +sum ≈ {scene_secs}, no clip exceeds {clip_cap}s. If not, fix it.""" + return [ + { + "role": "system", + "content": ( + "You are a film director planning shot coverage for AI video generation. " + "You output ONLY a single valid JSON object." + ), + }, + {"role": "user", "content": user}, + ] + + +def _normalize_clips( + raw_clips: list[dict[str, Any]], + *, + n_dialog_lines: int, + scene_budget: int, + clip_cap: int, +) -> list[dict[str, Any]]: + """Validate + clamp the LLM's clip list; derive missing fields deterministically.""" + valid_sizes = {"wide", "medium", "closeUp", "insert", "overShoulder"} + seen_lines: set[int] = set() + clips: list[dict[str, Any]] = [] + for i, c in enumerate(raw_clips, start=1): + if not isinstance(c, dict): + continue + covered = c.get("dialog_lines_covered") or [] + if not isinstance(covered, list): + covered = [] + covered = sorted( + { + int(n) + for n in covered + if isinstance(n, int) and 1 <= n <= n_dialog_lines and n not in seen_lines + } + ) + seen_lines.update(covered) + shot_size = c.get("shot_size") + if shot_size not in valid_sizes: + shot_size = None + duration = c.get("duration_sec") + try: + duration = int(duration) + except (TypeError, ValueError): + duration = None + if not duration or duration < 2: + duration = None + clips.append( + { + "order_index": c.get("order_index") if isinstance(c.get("order_index"), int) else i, + "description": (c.get("description") or "").strip() or None, + "dialog_lines_covered": covered, + "shot_size": shot_size, + "duration_sec": min(duration or clip_cap, clip_cap), + "chain_from_prev": bool(c.get("chain_from_prev")), + } + ) + # Renumber 1..N in the order given (models restart indexes per chunk). + for i, c in enumerate(clips, start=1): + c["order_index"] = i + if not clips: + return clips + # Uncovered dialogue is a coverage hole — attach any missed lines to the + # first clip whose description plausibly plays speech, else the last clip. + missing = [n for n in range(1, n_dialog_lines + 1) if n not in seen_lines] + if missing and clips: + clips[-1]["dialog_lines_covered"] = sorted( + set(clips[-1]["dialog_lines_covered"]) | set(missing) + ) + # Re-normalize durations to the scene budget when the model overshot/undershot + # wildly (>±35%); keep per-clip values inside the cap. + total = sum(c["duration_sec"] for c in clips) + if scene_budget > 0 and not (0.65 <= total / scene_budget <= 1.35): + scale = scene_budget / total + for c in clips: + c["duration_sec"] = max(2, min(clip_cap, round(c["duration_sec"] * scale))) + return clips + + +async def expand_scene_coverage( + project_id: int, + scene_ids: list[int] | None = None, + *, + guidance: str | None = None, + clip_cap: int | None = None, +) -> dict[str, Any]: + """Break scenes into shot clips, replacing each scene's existing clips. + + Expands ALL of the project's scenes when scene_ids is None. Each expanded + scene's old clips are deleted inside the same transaction that inserts the + new ones (its chain_from_prev migrates onto clip #1). Returns a summary. + """ + cap = clip_cap or DEFAULT_CLIP_DURATION_SEC + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index", + (project_id,), + ).fetchall() + all_scenes = [row_to_dict(r) for r in rows] + if scene_ids: + wanted = set(scene_ids) + scenes = [s for s in all_scenes if s["id"] in wanted] + else: + scenes = all_scenes + if not scenes: + raise ValueError("No scenes to expand — generate a script first") + + char_rows = conn.execute( + "SELECT id, name, appearance FROM characters WHERE project_id = ?", + (project_id,), + ).fetchall() + characters = [row_to_dict(r) for r in char_rows] + + results: list[dict[str, Any]] = [] + total = len(scenes) + for idx, scene in enumerate(scenes, start=1): + prev_heading = next( + (s["heading"] for s in all_scenes if s["order_index"] < scene["order_index"]), + None, + ) + next_heading = next( + (s["heading"] for s in all_scenes if s["order_index"] > scene["order_index"]), + None, + ) + await event_bus.publish( + "agent.thinking", + { + "message": f"Breaking scene {scene['order_index']} into shots " + f"({idx}/{total})…", + "project_id": project_id, + }, + ) + messages = _coverage_messages( + scene=scene, + characters=characters, + previous_heading=prev_heading, + next_heading=next_heading, + clip_cap=cap, + ) + if guidance: + messages[1]["content"] += f"\n\nExtra direction from the user: {guidance}" + result = await generate_structured(messages, temperature=0.5) + raw_clips = result.get("clips") or [] + if not raw_clips: + retry = [ + messages[0], + { + "role": "user", + "content": messages[1]["content"] + + "\n\nPREVIOUS ATTEMPT FAILED: no clips array. You MUST return a " + "\"clips\" JSON array with at least one clip.", + }, + ] + result = await generate_structured(retry, temperature=0.3) + raw_clips = result.get("clips") or [] + if not raw_clips: + raise ValueError( + f"Scene {scene['order_index']}: coverage pass returned no clips" + ) + dialog_lines = _dialog_lines(scene.get("dialog")) + budget = scene.get("duration_sec") or estimate_scene_duration_sec(scene) + clips = _normalize_clips( + raw_clips, n_dialog_lines=len(dialog_lines), scene_budget=budget, clip_cap=cap + ) + + # Replace-the-scene's-clips transaction. The scene-level chain flag + # migrates onto clip #1; the default clip (backfill) had copied it. + scene_chain = bool(scene.get("chain_from_prev")) + conn.execute("DELETE FROM clips WHERE scene_id = ?", (scene["id"],)) + for c in clips: + conn.execute( + """ + INSERT INTO clips (scene_id, project_id, order_index, description, + shot_size, dialog_lines_covered, duration_sec, + workflow_id, chain_from_prev) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + scene["id"], + project_id, + c["order_index"], + c["description"], + c["shot_size"], + json.dumps(c["dialog_lines_covered"]) if c["dialog_lines_covered"] else None, + c["duration_sec"], + scene.get("workflow_id"), + 1 if (c["order_index"] == 1 and scene_chain) or c["chain_from_prev"] else 0, + ), + ) + # The scene is now represented by its clips; clear its legacy + # 1:1 render mirror so stale single-clip paths don't resurface. + conn.execute( + "UPDATE scenes SET video_path = NULL, chain_from_prev = 0 WHERE id = ?", + (scene["id"],), + ) + conn.commit() + results.append( + { + "scene_id": scene["id"], + "order_index": scene["order_index"], + "clips": len(clips), + # UI-facing aliases (api.ts contract) — same values. + "clip_count": len(clips), + "duration_total": sum(c["duration_sec"] for c in clips), + "total_duration_sec": sum(c["duration_sec"] for c in clips), + } + ) + return { + "ok": True, + "scenes": results, + "total_clips": sum(r["clips"] for r in results), + } + finally: + conn.close() diff --git a/calliope-backend/src/calliope/agent/harness/__init__.py b/calliope-backend/src/calliope/agent/harness/__init__.py index dd5814d7..89803331 100644 --- a/calliope-backend/src/calliope/agent/harness/__init__.py +++ b/calliope-backend/src/calliope/agent/harness/__init__.py @@ -35,6 +35,12 @@ logger = logging.getLogger("calliope.harness") # human guidance text stays in the deny message for the model). GUARD_RENDER_APPROVAL = "guard_render_approval" GUARD_DESTRUCTIVE_REPLACE = "guard_destructive_replace" +# Scene tool scope guard lives in registry.py (circular-import free); the +# contracts exporter reads guard codes from THIS module, so re-export here. +from calliope.agent.harness.registry import ( # noqa: E402 + GUARD_SCENE_TOOL_SCOPE, + _scene_scoped, +) # Re-exports for tests / older imports. _is_confirmation = is_confirmation @@ -134,20 +140,22 @@ def _destructive_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> PreEx ) if replace: return deny( - counts + " replace=true DELETES all of it first. Ask the user to " - "confirm before replacing; once they confirm (e.g. 'yes, replace'), " - "call this tool again. For targeted changes use the granular tools " - "instead (add/update/delete for beats, characters, locations, " - "items, scenes).", + counts + " replace=true DELETES all of it first, and the user's " + "latest message did not ask for a replacement. Ask them once " + "(ask_user or plain text: 'replace the existing content?'); " + "after ANY affirmative reply, retry replace=true — it will be " + "allowed. Do not retry replace=true again before they answer; " + "do not call get_workspace repeatedly instead. For targeted " + "changes use the granular tools (add/update/delete) instead.", code=GUARD_DESTRUCTIVE_REPLACE, ) return deny( - counts + " replace=false would APPEND a second full set alongside the " - "existing content (e.g. doubling the beat list) — usually wrong. Ask " - "the user to confirm before appending; once they confirm (e.g. 'yes, " - "append'), call this tool again. For targeted changes use the granular " - "tools instead (add/update/delete for beats, characters, locations, " - "items, scenes).", + counts + " replace=false would APPEND a second full set alongside " + "the existing content (e.g. doubling the beat list). Ask the user " + "whether to replace or append; after ANY affirmative reply retry — " + "it will be allowed. Do not retry either mode again before they " + "answer. For targeted changes use the granular tools " + "(add/update/delete) instead.", code=GUARD_DESTRUCTIVE_REPLACE, ) @@ -172,6 +180,7 @@ def build_harness() -> tuple[ToolRegistry, SystemPromptService]: memory, render, script, + shot_builder, skills, story, workspace, @@ -185,6 +194,7 @@ def build_harness() -> tuple[ToolRegistry, SystemPromptService]: interaction.register(registry) memory.register(registry) skills.register(registry) + shot_builder.register(registry) registry.on_pre_execute(_destructive_guard) registry.on_pre_execute(_render_approval_guard) register_builtin_sections(prompts) diff --git a/calliope-backend/src/calliope/agent/harness/log.py b/calliope-backend/src/calliope/agent/harness/log.py index 179ed555..a8258356 100644 --- a/calliope-backend/src/calliope/agent/harness/log.py +++ b/calliope-backend/src/calliope/agent/harness/log.py @@ -16,6 +16,7 @@ import base64 import json import sqlite3 from dataclasses import dataclass +from pathlib import Path from typing import Any from calliope.config import settings @@ -249,7 +250,11 @@ def format_calliope_context( if not path: continue kind = str(a.get("kind") or "image") - att_lines.append(f"attached: {path} ({kind})") + if kind == "document": + name = str(a.get("name") or "").strip() or Path(path).name + att_lines.append(f'script document: "{name}" — the user uploaded their own script; draft from it') + else: + att_lines.append(f"attached: {path} ({kind})") # Guardrail: one Calliope workflow per turn so the model cannot fan out # run_workflow across several tagged ids. lines = ([wf_lines[0]] if wf_lines else []) + skill_lines + att_lines @@ -267,8 +272,10 @@ def project_user_content( Image attachments become OpenAI-style ``image_url`` content parts (data URLs read from disk), so vision-capable models see the actual pixels - instead of just a path line. Returns a plain string when there are no - usable images (the common text-only case). + instead of just a path line. Video attachments become evenly-spaced JPEG + frames (ffmpeg), each an ``image_url`` part, with a timestamp map in the + text part so the model can place motion on a timeline. Returns a plain + string when there are no usable attachments (the common text-only case). """ appendix = format_calliope_context(mentions, attachments) prose = (content or "").rstrip() @@ -277,20 +284,43 @@ def project_user_content( text = f"{prose}\n\n{appendix}" if prose else appendix image_parts: list[dict[str, Any]] = [] + video_lines: list[str] = [] + document_blocks: list[str] = [] for a in attachments or []: if not isinstance(a, dict): continue - if str(a.get("kind") or "image") != "image": - continue - data_url = _image_attachment_data_url(str(a.get("path") or "")) - if data_url: - image_parts.append( - {"type": "image_url", "image_url": {"url": data_url}} - ) - if not image_parts: + kind = str(a.get("kind") or "image") + path = str(a.get("path") or "") + if kind == "image": + data_url = _image_attachment_data_url(path) + if data_url: + image_parts.append( + {"type": "image_url", "image_url": {"url": data_url}} + ) + elif kind == "video": + frames = _video_attachment_frames(path) + for ts, data_url in frames: + image_parts.append( + {"type": "image_url", "image_url": {"url": data_url}} + ) + video_lines.append(f"{path} frame at {ts:.2f}s") + if not frames: + continue + elif kind == "document": + doc_text = _document_attachment_text(path, str(a.get("name") or "")) + if doc_text: + document_blocks.append(doc_text) + if not image_parts and not document_blocks: return text - parts: list[dict[str, Any]] = [{"type": "text", "text": text or "(see attached image)"}] + frame_map = "" + if video_lines: + frame_map = "\n\n[Video frames in order]\n" + "\n".join(video_lines) + if document_blocks: + frame_map = "\n\n" + "\n\n".join(document_blocks) + frame_map + parts: list[dict[str, Any]] = [ + {"type": "text", "text": (text or "(see attached)") + frame_map} + ] parts.extend(image_parts) return parts @@ -314,10 +344,6 @@ def _image_attachment_data_url(path: str) -> str | None: path is missing/outside assets_dir, not a known image type, or too large after decoding. """ - from pathlib import Path - - from calliope.config import settings - raw = str(path or "").strip() if not raw: return None @@ -338,6 +364,177 @@ def _image_attachment_data_url(path: str) -> str | None: return f"data:{mime};base64,{base64.b64encode(data).decode()}" +# Video attachments are "seen" as evenly-spaced frames (user choice: frame +# extraction over native video_url — works on ANY vision endpoint). 8 frames +# is enough for blockout motion mapping without drowning the context; each +# frame reuses the image budget. +_MAX_VIDEO_FRAMES = 8 +_MAX_VIDEO_FRAME_BYTES = 512_000 +_VIDEO_MIME_BY_EXT = { + ".mp4": "video/mp4", + ".webm": "video/webm", + ".mov": "video/quicktime", + ".mkv": "video/x-matroska", + ".m4v": "video/x-m4v", +} + + +def _run_ffmpeg(args: list[str], timeout: float = 30.0) -> bytes | None: + """Run a short ffmpeg/ffprobe command; stdout bytes or None.""" + import shutil + import subprocess + + exe = shutil.which(args[0]) + if not exe: + return None + try: + proc = subprocess.run( # noqa: S603 - fixed argv, no shell + [exe, *args[1:]], + capture_output=True, + timeout=timeout, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + except (OSError, subprocess.TimeoutExpired): + return None + if proc.returncode != 0: + return None + return proc.stdout + + +def _ffprobe_duration_seconds(path: Path) -> float | None: + out = _run_ffmpeg( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", str(path)], + timeout=15.0, + ) + if not out: + return None + try: + data = json.loads(out.decode("utf-8", "replace")) + duration = float(data["format"]["duration"]) + except (json.JSONDecodeError, KeyError, TypeError, ValueError): + return None + return duration if duration > 0 else None + + +def _extract_video_frames(path: Path) -> list[tuple[float, bytes]]: + """Evenly-spaced JPEG frames + timestamps (seconds), ≤ _MAX_VIDEO_FRAMES. + + Empty list when ffmpeg is unavailable or extraction fails — the caller + degrades to the path-only text line. + """ + import tempfile + + if _run_ffmpeg(["ffmpeg", "-version"], timeout=10.0) is None: + return [] + duration = _ffprobe_duration_seconds(path) + if duration is None: + return [] + # timestamped frames via the fps filter: N frames spread across the clip + fps_expr = f"fps={_MAX_VIDEO_FRAMES}/{duration:.6f}" + frames: list[tuple[float, bytes]] = [] + with tempfile.TemporaryDirectory(prefix="calliope-vidframes-") as tmp: + pattern = str(Path(tmp) / "frame_%02d.jpg") + _run_ffmpeg( + [ + "ffmpeg", "-y", "-v", "error", + "-i", str(path), + "-vf", f"{fps_expr},scale='min(768,iw)':-2", + "-frames:v", str(_MAX_VIDEO_FRAMES), + "-q:v", "5", + pattern, + ], + timeout=45.0, + ) + files = sorted(Path(tmp).glob("frame_*.jpg")) + for i, f in enumerate(files[:_MAX_VIDEO_FRAMES]): + data = f.read_bytes() + if not data or len(data) > _MAX_VIDEO_FRAME_BYTES: + continue + # frame k of N evenly spread over duration lands at k*duration/N + ts = round(i * duration / max(1, len(files)), 2) + frames.append((ts, data)) + return frames + + +def _video_attachment_frames(path: str) -> list[tuple[float, str]]: + """Frame data URLs (+timestamps) for a video attachment under assets_dir. + + Mirrors _image_attachment_data_url's containment rules; returns [] when + the path is missing/outside assets_dir, not a known video type, or when + ffmpeg/ffprobe is unavailable. + """ + raw = str(path or "").strip() + if not raw: + return [] + try: + target = Path(raw).resolve() + target.relative_to(settings.assets_dir.resolve()) + except (ValueError, OSError): + return [] + if target.suffix.lower() not in _VIDEO_MIME_BY_EXT or not target.is_file(): + return [] + frames = _extract_video_frames(target) + return [ + (ts, f"data:image/jpeg;base64,{base64.b64encode(data).decode()}") + for ts, data in frames + ] + + +# Document attachments (.txt/.md/.docx) are read as text and injected into the +# user turn between delimiters — the whole point is the agent drafting from a +# user-written script without any separate ingestion path. +_MAX_DOCUMENT_CHARS = 60_000 +_DOCUMENT_EXTS = {".txt", ".md", ".docx"} + + +def _extract_docx_text(target: Path) -> str: + """.docx → text via stdlib zipfile + XML tag-strip (word/document.xml).""" + import re as _re + import zipfile + + with zipfile.ZipFile(target) as zf: + xml = zf.read("word/document.xml").decode("utf-8", errors="replace") + # Paragraph and break tags become newlines before stripping. + xml = xml.replace("", "\n").replace("", "\n").replace("", "\t") + text = _re.sub(r"<[^>]+>", "", xml) + return text + + +def _document_attachment_text(path: str, name: str = "") -> str | None: + """Read a document attachment under assets_dir as bounded plain text. + + Returns None (the appendix still names the file) when the path is + missing/outside assets_dir or not a known document type. Text is truncated + at _MAX_DOCUMENT_CHARS with an explicit note so the model knows it saw a + partial document. + """ + import zipfile + raw = str(path or "").strip() + if not raw: + return None + try: + target = Path(raw).resolve() + target.relative_to(settings.assets_dir.resolve()) + except (ValueError, OSError): + return None + if target.suffix.lower() not in _DOCUMENT_EXTS or not target.is_file(): + return None + try: + if target.suffix.lower() == ".docx": + text = _extract_docx_text(target) + else: + text = target.read_text(encoding="utf-8", errors="replace") + except (OSError, zipfile.BadZipFile): + return None + label = name or target.name + if len(text) > _MAX_DOCUMENT_CHARS: + return ( + text[:_MAX_DOCUMENT_CHARS] + + f"\n\n[Document truncated: showing first {_MAX_DOCUMENT_CHARS} of {len(text)} characters]" + ) + return f"[Script document: {label}]\n{text}\n[/Script document]" + + def _downscale_image(target: Path, mime: str) -> bytes | None: """Re-encode large images at reduced width; passes small ones through.""" data = target.read_bytes() diff --git a/calliope-backend/src/calliope/agent/harness/loop.py b/calliope-backend/src/calliope/agent/harness/loop.py index 77dbaaab..951d317f 100644 --- a/calliope-backend/src/calliope/agent/harness/loop.py +++ b/calliope-backend/src/calliope/agent/harness/loop.py @@ -99,10 +99,17 @@ async def run_turn( repeat_cache: dict[str, dict[str, Any]] = {} repeat_counts: dict[str, int] = {} REPEAT_EXECUTE_LIMIT = 2 + # Failure thrash guard (canvas/70): an agent that keeps getting errors + # (guard denials, bad args) must CHANGE COURSE, not grind. After this + # many not-ok results in a row, a directive is injected that forces a + # different action or an explicit hand-back to the user. + FAIL_STREAK_LIMIT = 2 + fail_streak = 0 client = _llm_for_role("main") final_text = "" turn_status = "completed" + synthetic_idx: list[int] = [] # positions of budget-nudge messages (stripped after) try: messages = [m for m in history if m.get("role") != "system"] for iteration in range(1, max_iterations + 1): @@ -111,6 +118,27 @@ async def run_turn( # Rebuilt per step: linking mid-run flips tool visibility and the # workspace digest changes after each tool. system = await prompts.assemble(ctx) + remaining = max_iterations - iteration + if remaining == 0: + # Budget nudge: the FINAL step is dedicated to wrapping up + # (answer or report), not starting work it cannot finish — + # a turn that dies at the cap with no summary reads as + # "agent did nothing". + synthetic_idx.append(len(messages)) + messages.append( + { + "role": "user", + "content": ( + "[SYSTEM] This is your FINAL step of this turn. " + "Do not start new tool work. Either (a) if the " + "goal is already met, reply with a concise " + "summary, or (b) reply with exactly what is " + "blocked and why, and what you need to proceed. " + "The user can continue the task in their next " + "message." + ), + } + ) tools = registry.openai_payload(ctx) stream = client.chat_stream( [{"role": "system", "content": system}] + messages, @@ -297,6 +325,23 @@ async def run_turn( result_text = json.dumps(result, ensure_ascii=False, default=str) if len(result_text) > session_log.TOOL_RESULT_TRUNCATE: result_text = result_text[: session_log.TOOL_RESULT_TRUNCATE] + session_log.TRUNCATE_NOTE + # Thrash killer: a run of failures (guard denials, errors) + # escalates — the appended directive forces a DIFFERENT + # action or an explicit hand-back. Never a third blind try. + if isinstance(result, dict) and result.get("ok") is False: + fail_streak += 1 + elif isinstance(result, dict): + fail_streak = 0 + if fail_streak >= FAIL_STREAK_LIMIT: + result_text += ( + "\n\n[SYSTEM DIRECTIVE] That is " + f"{fail_streak} failed calls in a row on this goal. " + "STOP retrying the same tool. Now either (a) call a " + "DIFFERENT tool with corrected arguments, or (b) end " + "your turn with a clear plain-text report of what is " + "blocked and why, and what you need from the user. " + "Do not call any tool again with the same arguments." + ) messages.append( { "role": "tool", @@ -351,7 +396,12 @@ async def run_turn( finally: await client.close() log_append(session_log.TURN_END, {"turn": turn_no, "status": turn_status}) - # Persist the exchange into history (the runner saves it to the DB). + # Persist the exchange into history (the runner saves it to the DB), + # minus the synthetic budget-nudge message — it belongs to THIS + # turn's context only and would pollute the next turn. + for idx in reversed(synthetic_idx): + if 0 <= idx < len(messages) and messages[idx].get("content", "").startswith("[SYSTEM]"): + del messages[idx] history.clear() history.extend(messages) return final_text diff --git a/calliope-backend/src/calliope/agent/harness/orchestrator.py b/calliope-backend/src/calliope/agent/harness/orchestrator.py index 8d30d072..71e66abb 100644 --- a/calliope-backend/src/calliope/agent/harness/orchestrator.py +++ b/calliope-backend/src/calliope/agent/harness/orchestrator.py @@ -202,6 +202,15 @@ async def orchestrate( if len(summary) > 3000: summary = summary[:3000] + "…[truncated]" + if ctx.project_id is None: + # Blind/sandbox session (Build Scene, sandbox canvas): every swarm + # role's tool subset is project-scoped, so the planner can only + # misroute here. Skip it entirely — straight to the single loop — + # which also drops the misleading "scheduling a sub-agent" note. + history.clear() + history.extend(derived) + return await run_turn(ctx, history, on_message=on_message) + plan = await _plan(goal, summary) if plan.get("mode") == "swarm" and ctx.project_id is None: # Swarm sub-agents need project-scoped tools; in a sandbox the single diff --git a/calliope-backend/src/calliope/agent/harness/plugins/__init__.py b/calliope-backend/src/calliope/agent/harness/plugins/__init__.py index db272a65..c8205b32 100644 --- a/calliope-backend/src/calliope/agent/harness/plugins/__init__.py +++ b/calliope-backend/src/calliope/agent/harness/plugins/__init__.py @@ -17,6 +17,7 @@ _PLUGIN_MODULES = ( "calliope.agent.harness.plugins.interaction", "calliope.agent.harness.plugins.memory", "calliope.agent.harness.plugins.skills", + "calliope.agent.harness.plugins.shot_builder", ) diff --git a/calliope-backend/src/calliope/agent/harness/plugins/render.py b/calliope-backend/src/calliope/agent/harness/plugins/render.py index 7948d050..7d2c9ec0 100644 --- a/calliope-backend/src/calliope/agent/harness/plugins/render.py +++ b/calliope-backend/src/calliope/agent/harness/plugins/render.py @@ -74,31 +74,41 @@ def register(registry: ToolRegistry) -> None: ToolDefinition( name="enqueue_video_jobs", description=( - "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." + "Queue video generation for SPECIFIC clips (a scene may hold " + "several clips; each renders one ~5-10s video). Address them by " + "clip_ids (from list_clips) or refs ('#3.2'). Scene-level " + "shorthand still works: orders / scene_ids from list_scenes " + "expand to ALL of that scene's clips. NEVER dump every id. " + "NEVER omit the target list. all_clips=true ONLY when the user " + "explicitly asked for the whole film. More than 3 clips is " + "blocked unless they said all/every/entire." ), parameters={ "type": "object", "properties": { + "clip_ids": { + "type": "array", + "items": {"type": "integer"}, + "description": "Database clip ids from list_clips — most precise", + }, + "refs": { + "type": "array", + "items": {"type": "string"}, + "description": "Clip labels like '#3.2' (users say this form)", + }, "orders": { "type": "array", "items": {"type": "integer"}, "description": ( - "Video page clip numbers (#1, #25). Preferred when " - "the user names scenes by #." + "Scene order numbers (#3) — expands to every clip of scene 3" ), }, "scene_ids": { "type": "array", "items": {"type": "integer"}, - "description": "Database ids from list_scenes.scene_id — not #N", + "description": "Database scene ids from list_scenes.scene_id", }, - "all_scenes": { + "all_clips": { "type": "boolean", "description": "True only if the user asked to render every clip", }, @@ -456,16 +466,39 @@ def _int_list(raw: Any) -> list[int]: 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.plugins.script import ( + _resolve_clip_ref, + resolve_scene_ref, + ) from calliope.agent.harness.policy import allows_bulk_video_enqueue from calliope.agent.video_agent import enqueue_video_jobs as _enqueue + clip_ids = _int_list(args.get("clip_ids")) + refs = [str(r) for r in (args.get("refs") or []) if str(r).strip()] scene_ids = _int_list(args.get("scene_ids")) orders = _int_list(args.get("orders")) - all_scenes = bool(args.get("all_scenes")) + all_clips = bool(args.get("all_clips") or args.get("all_scenes")) latest = session_log.latest_user_message(ctx.session_id) or "" - resolved: list[int] = [] + # Clip-level resolution: exact clips win over scene expansion. + resolved_clips: list[int] = [] + if clip_ids or refs: + conn = _db() + try: + for cid in clip_ids: + found, err = _resolve_clip_ref(conn, ctx.project_id, clip_id=cid) + if err: + return {"ok": False, "error": err} + resolved_clips.append(found) + for ref in refs: + found, err = _resolve_clip_ref(conn, ctx.project_id, ref=ref) + if err: + return {"ok": False, "error": err} + resolved_clips.append(found) + finally: + conn.close() + + resolved_scenes: list[int] = [] if orders or scene_ids: conn = _db() try: @@ -473,66 +506,76 @@ async def t_enqueue_video_jobs(ctx: ToolContext, args: dict[str, Any]) -> dict[s found, err = resolve_scene_ref(conn, ctx.project_id, scene_id=sid) if err: return {"ok": False, "error": err} - resolved.append(found) + resolved_scenes.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) + resolved_scenes.append(found) + # Scene shorthand expands to ALL of that scene's clips (playback order). + if resolved_scenes: + placeholders = ",".join("?" * len(resolved_scenes)) + for r in conn.execute( + f"SELECT id FROM clips WHERE scene_id IN ({placeholders}) " + "ORDER BY scene_id, order_index, id", + resolved_scenes, + ).fetchall(): + resolved_clips.append(int(r["id"])) 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"} + if not resolved_clips and not resolved_scenes: + if all_clips: + conn = _db() + try: + resolved_clips = [ + int(r["id"]) + for r in conn.execute( + "SELECT id FROM clips WHERE project_id = ?", + (ctx.project_id,), + ).fetchall() + ] + finally: + conn.close() + else: + return { + "ok": False, + "error": ( + "Say which clips: pass refs ('#3.2') or clip_ids from " + "list_clips — a scene may hold several clips. Scene-level " + "orders/scene_ids expand to all of that scene's clips. " + "all_clips=true only when the user asked for the whole film." + ), + } - allowed_bulk = allows_bulk_video_enqueue(latest, len(resolved)) + # Preserve order, drop dupes. + seen: set[int] = set() + resolved_clips = [c for c in resolved_clips if not (c in seen or seen.add(c))] + + if not resolved_clips: + return {"ok": False, "error": "No matching clips to enqueue"} + + allowed_bulk = allows_bulk_video_enqueue(latest, len(resolved_clips)) 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." + f"Blocked: {len(resolved_clips)} clips is a bulk render. Users usually " + "mean the ones they named (2–3 clips). Pass only those refs/clip_ids, " + "or wait until they say all clips / the entire film." ), } try: jobs = await _enqueue( ctx.project_id, - scene_ids=resolved, + clip_ids=resolved_clips, workflow_id=args.get("workflow_id"), session_id=ctx.session_id, ) except ValueError as exc: return {"ok": False, "error": str(exc)} - return {"jobs": jobs, "count": len(jobs), "scene_ids": resolved} + return {"jobs": jobs, "count": len(jobs), "clip_ids": resolved_clips} _IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"} @@ -725,16 +768,23 @@ async def t_run_workflow(ctx: ToolContext, args: dict[str, Any]) -> dict[str, An "SELECT id FROM scenes WHERE id = ? AND project_id = ?", (scene_id, int(ctx.project_id)), ).fetchone() + if not scene: + return {"ok": False, "error": f"Scene {scene_id} not found in this project"} + # A scene's first clip is the write target (1 scene : N clips — a + # run_workflow video always lands on clip #1 of the scene). + first_clip = conn.execute( + "SELECT id FROM clips WHERE scene_id = ? ORDER BY order_index, id LIMIT 1", + (scene_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], + clip_ids=[int(first_clip["id"])] if first_clip else None, + scene_ids=[scene_id] if first_clip is None else None, workflow_id=workflow_id, ) except ValueError as exc: diff --git a/calliope-backend/src/calliope/agent/harness/plugins/script.py b/calliope-backend/src/calliope/agent/harness/plugins/script.py index e1e7a07b..4c1d271c 100644 --- a/calliope-backend/src/calliope/agent/harness/plugins/script.py +++ b/calliope-backend/src/calliope/agent/harness/plugins/script.py @@ -1,6 +1,7 @@ """Script plugin: scene generation + per-scene CRUD.""" from __future__ import annotations +import json from typing import Any from calliope.agent.harness.registry import ( @@ -70,14 +71,22 @@ def register(registry: ToolRegistry) -> None: name="generate_script", description=( "Generate the scene script for the linked project via the script " - "agent. DESTRUCTIVE: replace=true (default) DELETES all existing " - "scenes first. If the user only wants tweaks, use update_scene / " - "add_scene instead." + "agent, then break every scene into shot clips (with_clips, " + "default true). DESTRUCTIVE: replace=true (default) DELETES all " + "existing scenes first. If the user only wants tweaks, use " + "update_scene / add_scene instead." ), parameters={ "type": "object", "properties": { "scene_count": {"type": "integer", "minimum": 1}, + "with_clips": { + "type": "boolean", + "description": ( + "Also break every scene into shot clips (default true — " + "one call produces the full script + shot list)" + ), + }, "replace": { "type": "boolean", "description": "Replace existing scenes (default true = destructive)", @@ -97,7 +106,8 @@ def register(registry: ToolRegistry) -> None: "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." + "to search without dumping the whole timeline. Each scene also " + "reports its clip count (scenes expand into 1+ shot clips)." ), parameters={ "type": "object", @@ -117,6 +127,168 @@ def register(registry: ToolRegistry) -> None: category="script", ) ) + registry.register( + ToolDefinition( + name="list_clips", + description=( + "List shot clips under the project's scenes (a scene expands " + "into 1+ clips; each clip is one ~5-10s video render). Every " + "clip has clip_id (database id) and label '#.' " + "(e.g. #3.2 = scene 3, clip 2) — the #N.M form users say. " + "Optionally filter by scene_ids / orders (scene numbers) or " + "refs ('#3.2')." + ), + parameters={ + "type": "object", + "properties": { + "scene_ids": { + "type": "array", + "items": {"type": "integer"}, + "description": "Database scene ids (from list_scenes)", + }, + "orders": { + "type": "array", + "items": {"type": "integer"}, + "description": "Scene order numbers (#3 → all clips of scene 3)", + }, + "refs": { + "type": "array", + "items": {"type": "string"}, + "description": "Clip labels like '#3.2'", + }, + }, + }, + executor=t_list_clips, + category="script", + ) + ) + registry.register( + ToolDefinition( + name="break_into_shots", + description=( + "Break script scene(s) into shot clips via the coverage pass " + "(LLM allocates every dialogue line and action beat across " + "~5-10s clips, preserving full content). Use after " + "generate_script so long scenes get real coverage. Scope: pass " + "scene_ids / orders, or all_scenes=true ONLY when the user " + "asked for the whole script. Existing clips of those scenes " + "are replaced." + ), + parameters={ + "type": "object", + "properties": { + "scene_ids": { + "type": "array", + "items": {"type": "integer"}, + "description": "Database scene ids (from list_scenes)", + }, + "orders": { + "type": "array", + "items": {"type": "integer"}, + "description": "Scene order numbers (#3, #7)", + }, + "all_scenes": { + "type": "boolean", + "description": "Expand EVERY scene (bulk — only on explicit ask)", + }, + "guidance": { + "type": "string", + "description": "Optional style/direction hints for the split", + }, + }, + }, + executor=t_break_into_shots, + category="script", + destructive=True, + ) + ) + registry.register( + ToolDefinition( + name="add_clip", + description=( + "Add one shot clip to a scene's end (or order_index within it). " + "description = what the camera sees + which of the scene's " + "dialogue lines it performs; shot_size like 'wide' / 'medium' / " + "'close-up'; duration_sec 3-15 (videos render ~5-10s)." + ), + parameters={ + "type": "object", + "properties": { + "scene_id": {"type": "integer"}, + "order": { + "type": "integer", + "description": "Scene order number (#3) instead of scene_id", + }, + "order_index": { + "type": "integer", + "description": "Position within the scene (default: append)", + }, + "description": {"type": "string"}, + "shot_size": {"type": "string"}, + "dialog_lines_covered": { + "type": "array", + "items": {"type": "integer"}, + "description": "1-based dialogue line numbers this clip performs", + }, + "duration_sec": {"type": "number"}, + "workflow_id": {"type": "integer"}, + "chain_from_prev": {"type": "boolean"}, + }, + }, + executor=t_add_clip, + category="script", + ) + ) + registry.register( + ToolDefinition( + name="update_clip", + description=( + "Edit one clip (description / shot_size / dialog_lines_covered / " + "duration_sec / workflow_id / chain_from_prev). Address it by " + "clip_id (from list_clips) or ref '#3.2'." + ), + parameters={ + "type": "object", + "properties": { + "clip_id": {"type": "integer"}, + "ref": { + "type": "string", + "description": "Clip label like '#3.2' instead of clip_id", + }, + "description": {"type": "string"}, + "shot_size": {"type": "string"}, + "dialog_lines_covered": { + "type": "array", + "items": {"type": "integer"}, + }, + "duration_sec": {"type": "number"}, + "workflow_id": {"type": "integer"}, + "chain_from_prev": {"type": "boolean"}, + }, + }, + executor=t_update_clip, + category="script", + ) + ) + registry.register( + ToolDefinition( + name="delete_clip", + description=( + "Delete one clip (by clip_id or ref '#3.2') and renumber its " + "scene's remaining clips. The scene's LAST clip is protected — " + "delete the scene itself instead." + ), + parameters={ + "type": "object", + "properties": { + "clip_id": {"type": "integer"}, + "ref": {"type": "string", "description": "Clip label like '#3.2'"}, + }, + }, + executor=t_delete_clip, + category="script", + ) + ) registry.register( ToolDefinition( name="update_scene", @@ -240,6 +412,7 @@ async def t_generate_script(ctx: ToolContext, args: dict[str, Any]) -> dict[str, ctx.project_id, replace=bool(args.get("replace", True)), scene_count=int(scene_count) if scene_count else None, + with_clips=bool(args.get("with_clips", True)), ) @@ -278,6 +451,13 @@ async def t_list_scenes(ctx: ToolContext, args: dict[str, Any]) -> list[dict[str (s["id"],), ).fetchall() s["characters"] = [row_to_dict(c) for c in chars] + s["clip_count"] = conn.execute( + "SELECT COUNT(*) AS n FROM clips WHERE scene_id = ?", (s["id"],) + ).fetchone()["n"] + s["clips_ready"] = conn.execute( + "SELECT COUNT(*) AS n FROM clips WHERE scene_id = ? AND clip_path IS NOT NULL", + (s["id"],), + ).fetchone()["n"] return scenes finally: conn.close() @@ -470,3 +650,291 @@ async def t_reorder_scenes(ctx: ToolContext, args: dict[str, Any]) -> dict[str, return {"scenes": [annotate_scene_row(row_to_dict(r)) for r in rows]} finally: conn.close() + + +# ── Clips: the shot layer under each scene ────────────────────────────── + + +def _annotate_clip(c: dict[str, Any], scene_order: int) -> dict[str, Any]: + """User-facing labels: clip_id (db id) + label '#.'.""" + c["clip_id"] = int(c["id"]) + c["label"] = f"#{scene_order}.{c['order_index']}" + return c + + +def _resolve_clip_ref( + conn, + project_id: int, + *, + clip_id: Any = None, + ref: Any = None, +) -> tuple[int | None, str | None]: + """Resolve one clip. `ref` is the '#3.2' label form users say.""" + if clip_id is not None and str(clip_id).strip() != "": + try: + cid = int(clip_id) + except (TypeError, ValueError): + return None, "clip_id must be an integer from list_clips" + row = conn.execute( + "SELECT id FROM clips WHERE id = ? AND project_id = ?", + (cid, project_id), + ).fetchone() + if not row: + return None, f"Clip {clip_id} not found in this project — list_clips first" + return int(row["id"]), None + if ref is not None and str(ref).strip() != "": + text = str(ref).strip().lstrip("#") + parts = text.split(".") + if len(parts) != 2: + return None, "ref must look like '#3.2' (scene.clip) — list_clips first" + try: + s_pos, c_pos = int(parts[0]), int(parts[1]) + except ValueError: + return None, "ref must look like '#3.2' (scene.clip) — list_clips first" + row = conn.execute( + """ + SELECT c.id FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.project_id = ? AND s.order_index = ? AND c.order_index = ? + """, + (project_id, s_pos, c_pos), + ).fetchone() + if not row: + return None, f"No clip #{s_pos}.{c_pos} in this project — list_clips first" + return int(row["id"]), None + return None, "Pass clip_id (from list_clips) or ref ('#3.2')" + + +async def t_list_clips(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + conn = _db() + try: + rows = conn.execute( + """ + SELECT c.*, s.order_index AS scene_order, s.heading + FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.project_id = ? + ORDER BY s.order_index, c.order_index, c.id + """, + (ctx.project_id,), + ).fetchall() + clips = [ + _annotate_clip(row_to_dict(r), int(r["scene_order"])) for r in rows + ] + scene_ids = [int(i) for i in (args.get("scene_ids") or [])] + if scene_ids: + want = set() + for sid in scene_ids: + found, err = resolve_scene_ref(conn, ctx.project_id, scene_id=sid) + if err: + return {"ok": False, "error": err} + want.add(found) + clips = [c for c in clips if c["scene_id"] in want] + refs = [str(r) for r in (args.get("refs") or []) if str(r).strip()] + if refs: + want = set() + for ref in refs: + found, err = _resolve_clip_ref(conn, ctx.project_id, ref=ref) + if err: + return {"ok": False, "error": err} + want.add(found) + clips = [c for c in clips if c["id"] in want] + return {"clips": clips, "count": len(clips)} + finally: + conn.close() + + +async def t_break_into_shots(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + from calliope.agent.coverage_agent import expand_scene_coverage + from calliope.agent.harness import log as session_log + from calliope.agent.harness.policy import allows_bulk_video_enqueue + + scene_ids = [int(i) for i in (args.get("scene_ids") or [])] + orders = [int(i) for i in (args.get("orders") or [])] + all_scenes = bool(args.get("all_scenes")) + guidance = str(args.get("guidance") or "").strip() or None + + if not scene_ids and not orders and not all_scenes: + return { + "ok": False, + "error": ( + "Say which scenes to break: pass scene_ids / orders from " + "list_scenes, or all_scenes=true only when the user asked for " + "the whole script." + ), + } + conn = _db() + try: + resolved: list[int] = [] + 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) + if all_scenes: + resolved = [ + int(r["id"]) + for r in conn.execute( + "SELECT id FROM scenes WHERE project_id = ? ORDER BY order_index", + (ctx.project_id,), + ).fetchall() + ] + finally: + conn.close() + seen: set[int] = set() + resolved = [s for s in resolved if not (s in seen or seen.add(s))] + if not resolved: + return {"ok": False, "error": "No matching scenes to expand"} + + latest = session_log.latest_user_message(ctx.session_id) or "" + if len(resolved) > 3 and not allows_bulk_video_enqueue(latest, len(resolved)): + return { + "ok": False, + "error": ( + f"Breaking {len(resolved)} scenes is a bulk pass (~{len(resolved) * 5}+ " + "clips). Confirm the user asked for every scene, or name the ones they want." + ), + } + + try: + result = await expand_scene_coverage( + ctx.project_id, resolved, guidance=guidance + ) + except ValueError as exc: + return {"ok": False, "error": str(exc)} + total = sum(r["clips"] for r in result.get("scenes", [])) + return { + "ok": True, + "scenes": result.get("scenes", []), + "total_clips": total, + "note": "list_clips to see them; enqueue_video_jobs to render specific ones.", + } + + +async def t_add_clip(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + conn = _db() + try: + 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} + next_index = conn.execute( + "SELECT COALESCE(MAX(order_index), 0) + 1 AS n FROM clips WHERE scene_id = ?", + (scene_id,), + ).fetchone()["n"] + covered = args.get("dialog_lines_covered") + covered_json = json.dumps([int(i) for i in covered]) if covered else None + cur = conn.execute( + """ + INSERT INTO clips (scene_id, project_id, order_index, description, + shot_size, dialog_lines_covered, duration_sec, + workflow_id, chain_from_prev) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + scene_id, + ctx.project_id, + int(args.get("order_index") or next_index), + args.get("description"), + args.get("shot_size"), + covered_json, + args.get("duration_sec"), + args.get("workflow_id"), + 1 if args.get("chain_from_prev") else 0, + ), + ) + conn.execute( + "UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (ctx.project_id,), + ) + conn.commit() + row = conn.execute("SELECT * FROM clips WHERE id = ?", (cur.lastrowid,)).fetchone() + scene = conn.execute( + "SELECT order_index FROM scenes WHERE id = ?", (scene_id,) + ).fetchone() + return {"clip": _annotate_clip(row_to_dict(row), int(scene["order_index"]))} + finally: + conn.close() + + +async def t_update_clip(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + conn = _db() + try: + clip_id, err = _resolve_clip_ref( + conn, ctx.project_id, clip_id=args.get("clip_id"), ref=args.get("ref") + ) + if err: + return {"ok": False, "error": err} + cols = ("description", "shot_size", "duration_sec", "workflow_id", "chain_from_prev") + data = {k: v for k, v in args.items() if k in cols and v is not None} + if "dialog_lines_covered" in args and args["dialog_lines_covered"] is not None: + data["dialog_lines_covered"] = json.dumps( + [int(i) for i in args["dialog_lines_covered"]] + ) + if not data: + return {"ok": False, "error": "Nothing to update"} + fields = ", ".join(f"{k} = :{k}" for k in data) + data["id"] = clip_id + data["pid"] = ctx.project_id + conn.execute( + f"UPDATE clips SET {fields} WHERE id = :id AND project_id = :pid", data + ) + conn.execute( + "UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (ctx.project_id,), + ) + conn.commit() + row = conn.execute( + """ + SELECT c.*, s.order_index AS scene_order FROM clips c + JOIN scenes s ON s.id = c.scene_id WHERE c.id = ? + """, + (clip_id,), + ).fetchone() + return {"clip": _annotate_clip(row_to_dict(row), int(row["scene_order"]))} + finally: + conn.close() + + +async def t_delete_clip(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + conn = _db() + try: + clip_id, err = _resolve_clip_ref( + conn, ctx.project_id, clip_id=args.get("clip_id"), ref=args.get("ref") + ) + if err: + return {"ok": False, "error": err} + row = conn.execute( + "SELECT scene_id, order_index FROM clips WHERE id = ?", (clip_id,) + ).fetchone() + count = conn.execute( + "SELECT COUNT(*) AS n FROM clips WHERE scene_id = ?", (row["scene_id"],) + ).fetchone()["n"] + if count <= 1: + return { + "ok": False, + "error": "A scene needs at least one clip — delete_scene instead", + } + conn.execute("DELETE FROM clips WHERE id = ?", (clip_id,)) + # Renumber remaining clips gaplessly + remaining = conn.execute( + "SELECT id FROM clips WHERE scene_id = ? ORDER BY order_index, id", + (row["scene_id"],), + ).fetchall() + for idx, r in enumerate(remaining, start=1): + conn.execute("UPDATE clips SET order_index = ? WHERE id = ?", (idx, r["id"])) + conn.execute( + "UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (ctx.project_id,), + ) + conn.commit() + return {"ok": True, "deleted": f"#{args.get('ref') or clip_id}"} + finally: + conn.close() diff --git a/calliope-backend/src/calliope/agent/harness/plugins/shot_builder.py b/calliope-backend/src/calliope/agent/harness/plugins/shot_builder.py new file mode 100644 index 00000000..0221183b --- /dev/null +++ b/calliope-backend/src/calliope/agent/harness/plugins/shot_builder.py @@ -0,0 +1,1150 @@ +"""Shot-builder plugin: the Build Scene page's 3D blockout tools. + +Mirrors open-media's mcpBridge command set as built-in harness tools (no +MCP). One composition per session (get-or-create via +routers.shots.get_or_create_for_session); every tool mutates the stored +scene_json server-side and the frontend viewport follows via the +`shot.updated` SSE event. All tools are blind_only — the Build Scene surface +belongs to unlinked sandbox sessions, exactly like sandbox canvases. +""" +from __future__ import annotations + +import asyncio +import json +import time +import uuid +from typing import Any + +from calliope.agent.harness.registry import ( + ToolContext, + ToolDefinition, + ToolRegistry, + _db, +) +from calliope.events.bus import event_bus + +# ---- posture validation (port of posture.ts v7) ----------------------------- + +POSTURE_ENTRIES = ( + "body.position", + "body", + "torso", + "head", + "l_leg", + "l_knee", + "l_ankle", + "r_leg", + "r_knee", + "r_ankle", + "l_arm", + "l_elbow", + "l_wrist", + "l_finger_0", + "l_finger_1", + "l_finger_2", + "l_finger_3", + "l_finger_4", + "r_arm", + "r_elbow", + "r_wrist", + "r_finger_0", + "r_finger_1", + "r_finger_2", + "r_finger_3", + "r_finger_4", +) +POSTURE_ENTRY_LENGTHS = ( + 3, 3, 3, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 7, 7, 7, 7, 7, 3, 1, 3, 7, 7, 7, 7, 7, +) +POSTURE_VERSION = 7 + +JOINT_KEYS = {name for name in POSTURE_ENTRIES if name != "body.position"} + +SHOT_SIZES = ("wide", "full", "medium", "mcu", "closeup") +ANGLES = ("front", "threeQuarterLeft", "threeQuarterRight", "profile", "back", "ots") +ELEVATIONS = ("eye", "high", "low") +COMPOSITIONS = ( + "center", + "leftThird", + "rightThird", + "upperThird", + "lowerThird", + "negativeSpace", +) + +# Legacy ids the agent wrote before the vocabulary matched the frontend +# solver/composition presets (which NaN'd the camera on restore: the solver +# does ANGLE_AZIMUTH_DEG[angle] and '34_left' is undefined there). Accepted +# on input, never emitted. +_ANGLE_ALIASES = {"34_left": "threeQuarterLeft", "34_right": "threeQuarterRight"} +_COMPOSITION_ALIASES = { + "left_third": "leftThird", + "right_third": "rightThird", + "upper_third": "upperThird", + "lower_third": "lowerThird", + "negative_space": "negativeSpace", +} +OBJECT_TYPES = ( + "male", + "female", + "child", + "cube", + "plane", + "cylinder", + "sphere", + "capsule", + "cone", + "torus", + "camera", +) + +CAPTURE_POLL_TIMEOUT_S = 10.0 +CAPTURE_POLL_INTERVAL_S = 0.5 + + +def _scene_of(comp: dict[str, Any]) -> dict[str, Any]: + try: + scene = json.loads(comp.get("scene_json") or "{}") + except json.JSONDecodeError: + scene = {} + return scene if isinstance(scene, dict) else {} + + +def _find_object(scene: dict[str, Any], object_id: str) -> dict[str, Any] | None: + for obj in scene.get("objects", []): + if isinstance(obj, dict) and obj.get("id") == object_id: + return obj + return None + + +def _summarize_object(obj: dict[str, Any]) -> dict[str, Any]: + """Wire-format for the model — mirrors open-media's summarizeObject.""" + return { + "id": obj.get("id"), + "name": obj.get("name"), + "type": obj.get("type"), + "visible": obj.get("visible", True), + "locked": obj.get("locked", False), + "transform": obj.get("transform"), + "fov": obj.get("fov"), + "posture": obj.get("posture"), + "hasDefaultPosture": bool(obj.get("defaultPosture")), + "keyframes": [ + { + "id": k.get("id"), + "time": k.get("time"), + "transform": k.get("transform"), + "fov": k.get("fov"), + "hasPosture": bool(k.get("posture")), + } + for k in (obj.get("keyframes") or []) + if isinstance(k, dict) + ], + } + + +def _save_scene(ctx: ToolContext, scene: dict[str, Any]) -> dict[str, Any]: + from calliope.routers.shots import get_or_create_for_session, validate_scene_json + + raw = json.dumps(scene) + validate_scene_json(raw) + conn = _db() + try: + comp = get_or_create_for_session(conn, ctx.session_id) + comp_id = int(comp["id"]) + conn.execute( + "UPDATE shot_composition SET scene_json = ?, " + "updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (raw, comp_id), + ) + conn.commit() + finally: + conn.close() + return comp_id + + +async def _publish_updated(shot_id: int, reason: str) -> None: + await event_bus.publish("shot.updated", {"shot_id": shot_id, "reason": reason}) + + +def _ok(shot_id: int, **extra: Any) -> dict[str, Any]: + return {"ok": True, "shot_id": shot_id, **extra} + + +def _load_scene(ctx: ToolContext) -> tuple[int, dict[str, Any]]: + from calliope.routers.shots import get_or_create_for_session + + conn = _db() + try: + comp = get_or_create_for_session(conn, ctx.session_id) + finally: + conn.close() + return int(comp["id"]), _scene_of(comp) + + +def _validate_posture(posture: Any) -> str | None: + """Returns an error string, or None when the posture is well-formed.""" + if not isinstance(posture, dict): + return "posture must be an object" + version = posture.get("version") + if version != POSTURE_VERSION: + return f"posture.version must be {POSTURE_VERSION}" + data = posture.get("data") + if not isinstance(data, list) or len(data) != len(POSTURE_ENTRIES): + return ( + f"posture.data must be a list of {len(POSTURE_ENTRIES)} entries " + "(one per joint, in POSTURE_ENTRIES order)" + ) + for i, entry in enumerate(data): + expected = POSTURE_ENTRY_LENGTHS[i] + if not isinstance(entry, list) or len(entry) != expected or not all( + isinstance(v, (int, float)) for v in entry + ): + name = POSTURE_ENTRIES[i] + return ( + f"posture.data[{i}] ({name}) must be a list of {expected} numbers" + ) + return None + + +def _apply_joint( + obj: dict[str, Any], joint: str, values: list[float] +) -> None: + """Write one joint into the object's posture, initializing when absent. + + Fresh entries are zeroed at their real lengths, never empty arrays: + mannequin-js reads each entry with fixed-arity accessors (e.g. + ``rotation.set(rad(pos[0]), ...)``), so an empty array becomes NaN and the + whole figure silently stops rendering. + """ + posture = obj.get("posture") + if ( + not isinstance(posture, dict) + or posture.get("version") != POSTURE_VERSION + or not isinstance(posture.get("data"), list) + or len(posture["data"]) != len(POSTURE_ENTRIES) + ): + posture = { + "version": POSTURE_VERSION, + "data": [[0.0] * length for length in POSTURE_ENTRY_LENGTHS], + } + data = posture["data"] + idx = POSTURE_ENTRIES.index(joint) + data[idx] = [float(v) for v in values] + obj["posture"] = posture + + +# ---- tool executors --------------------------------------------------------- + + +async def t_get_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + shot_id, scene = _load_scene(ctx) + return _ok( + shot_id, + objects=[_summarize_object(o) for o in scene.get("objects", []) if isinstance(o, dict)], + shotParams=scene.get("shotParams"), + playback=scene.get("playback"), + ) + + +async def t_add_object(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + import uuid as _uuid + + otype = args.get("type") + if otype not in OBJECT_TYPES: + return {"ok": False, "error": f"type must be one of: {', '.join(OBJECT_TYPES)}"} + shot_id, scene = _load_scene(ctx) + objects = scene.setdefault("objects", []) + name = (args.get("name") or "").strip() or f"{otype.capitalize()} {len(objects) + 1:02d}" + transform = { + "position": [len(objects) * 1.5, 0, 0], + "rotation": [0, 0, 0], + "scale": [1, 1, 1], + } + obj = { + "id": str(_uuid.uuid4()), + "name": name, + "type": otype, + "visible": True, + "locked": False, + "transform": transform, + "keyframes": [] if otype == "camera" else [ + {"id": str(_uuid.uuid4()), "time": 0, "transform": transform} + ], + "liveEditTime": None, + } + if otype == "camera": + obj["fov"] = 10 + objects.append(obj) + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "object_added") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_delete_object(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + shot_id, scene = _load_scene(ctx) + objects = scene.get("objects", []) + remaining = [o for o in objects if isinstance(o, dict) and o.get("id") != object_id] + if len(remaining) == len(objects): + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + scene["objects"] = remaining + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "object_deleted") + return _ok(comp_id) + + +async def t_rename_object(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + name = (args.get("name") or "").strip() + if not name: + return {"ok": False, "error": "name is required"} + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + obj["name"] = name[:120] + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "object_renamed") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_set_transform(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + transform_in = args.get("transform") or {} + base = obj.get("transform") or { + "position": [0, 0, 0], + "rotation": [0, 0, 0], + "scale": [1, 1, 1], + } + merged = dict(base) + for key in ("position", "rotation", "scale"): + if key in transform_in: + vals = transform_in[key] + if not isinstance(vals, list) or len(vals) != 3 or not all( + isinstance(v, (int, float)) for v in vals + ): + return {"ok": False, "error": f"transform.{key} must be [x, y, z] numbers"} + merged[key] = [float(v) for v in vals] + obj["transform"] = merged + obj["liveEditTime"] = None + # A track-less object keeps its spawn keyframe in sync with the plain + # fields. An object WITH committed keyframes must not be touched here: + # force-rewriting keyframes[0] snapped every earlier keyframe to the new + # position (a keyed walk-across teleported at t=0) and broke the + # stage→add_keyframe recipe — the keyframe tools own the track. + if not obj.get("keyframes"): + obj["keyframes"] = [{"id": f"kf-{uuid.uuid4().hex[:12]}", "time": 0, "transform": merged}] + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "transform_set") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_reset_transform(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + args = dict(args) + args["transform"] = {"position": [0, 0, 0], "rotation": [0, 0, 0], "scale": [1, 1, 1]} + return await t_set_transform(ctx, args) + + +async def t_select_object(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + # Selection is a UI-only concern; the model uses it to point at an object + # so the user sees which figure is being discussed. + object_id = args.get("object_id") + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + scene["selectedObjectId"] = object_id + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "selection") + return _ok(comp_id, selected_object=_summarize_object(obj)) + + +async def t_clear_scene(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + shot_id, _scene = _load_scene(ctx) + comp_id = _save_scene(ctx, {"objects": []}) + await _publish_updated(comp_id, "cleared") + return _ok(comp_id) + + +# ── keyframes / motion (port of open-media's mcpBridge keyframe commands) ── + +_KEYFRAME_TIME_MAX = 60.0 # matches the frontend MAX_TIMELINE_DURATION cap + + +def _validate_keyframe_time(time: Any) -> str | None: + if not isinstance(time, (int, float)) or isinstance(time, bool): + return "time must be a number (seconds)" + if time < 0 or time > _KEYFRAME_TIME_MAX: + return f"time must be between 0 and {_KEYFRAME_TIME_MAX:g} seconds" + return None + + +async def t_add_keyframe(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + """Upserts a keyframe on the object's track at `time`. + + Seeds transform/posture/fov from the object's current state, so the common + agent flow is: set_transform → add_keyframe(t) → set_transform → + add_keyframe(t2) — each keyframe captures what the object looks like now. + An existing keyframe within one frame (1/24s) of `time` is replaced. + """ + object_id = args.get("object_id") + time = args.get("time") + if (err := _validate_keyframe_time(time)) is not None: + return {"ok": False, "error": err} + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + + transform = obj.get("transform") or { + "position": [0, 0, 0], + "rotation": [0, 0, 0], + "scale": [1, 1, 1], + } + keyframes = [k for k in (obj.get("keyframes") or []) if isinstance(k, dict)] + near = next( + (k for k in keyframes if abs(float(k.get("time", -1)) - float(time)) <= 1 / 24), + None, + ) + if near is not None: + near["time"] = float(time) + near["transform"] = transform + if obj.get("posture") is not None: + near["posture"] = obj["posture"] + if obj.get("fov") is not None: + near["fov"] = obj["fov"] + else: + keyframe: dict[str, Any] = { + "id": f"kf-{uuid.uuid4().hex[:12]}", + "time": float(time), + "transform": transform, + } + if obj.get("posture") is not None: + keyframe["posture"] = obj["posture"] + if obj.get("fov") is not None: + keyframe["fov"] = obj["fov"] + keyframes.append(keyframe) + obj["keyframes"] = sorted(keyframes, key=lambda k: float(k.get("time", 0))) + scene["playback"] = {**(scene.get("playback") or {}), "duration": max( + float((scene.get("playback") or {}).get("duration") or 6), float(time) + )} + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "keyframe_added") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_update_keyframe(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + keyframe_id = args.get("keyframe_id") + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + keyframe = next((k for k in obj.get("keyframes") or [] if k.get("id") == keyframe_id), None) + if keyframe is None: + return {"ok": False, "error": f"No keyframe '{keyframe_id}' on object '{object_id}'. Call get_scene to see keyframe ids."} + transform_in = args.get("transform") or {} + base = keyframe.get("transform") or { + "position": [0, 0, 0], + "rotation": [0, 0, 0], + "scale": [1, 1, 1], + } + merged = dict(base) + for key in ("position", "rotation", "scale"): + if key in transform_in: + vals = transform_in[key] + if not isinstance(vals, list) or len(vals) != 3 or not all( + isinstance(v, (int, float)) for v in vals + ): + return {"ok": False, "error": f"transform.{key} must be [x, y, z] numbers"} + merged[key] = [float(v) for v in vals] + keyframe["transform"] = merged + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "keyframe_updated") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_delete_keyframe(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + keyframe_id = args.get("keyframe_id") + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + keyframes = [k for k in (obj.get("keyframes") or []) if isinstance(k, dict)] + if len(keyframes) <= 1: + return {"ok": False, "error": "Refusing to delete the last keyframe — a track keeps at least one anchor."} + remaining = [k for k in keyframes if k.get("id") != keyframe_id] + if len(remaining) == len(keyframes): + return {"ok": False, "error": f"No keyframe '{keyframe_id}' on object '{object_id}'."} + obj["keyframes"] = remaining + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "keyframe_deleted") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_move_keyframe_time(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + keyframe_id = args.get("keyframe_id") + time = args.get("time") + if (err := _validate_keyframe_time(time)) is not None: + return {"ok": False, "error": err} + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + keyframe = next((k for k in obj.get("keyframes") or [] if k.get("id") == keyframe_id), None) + if keyframe is None: + return {"ok": False, "error": f"No keyframe '{keyframe_id}' on object '{object_id}'."} + keyframe["time"] = float(time) + obj["keyframes"] = sorted( + (k for k in obj.get("keyframes") or [] if isinstance(k, dict)), + key=lambda k: float(k.get("time", 0)), + ) + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "keyframe_moved") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_set_playback(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + """Controls the playhead the UI samples object tracks and the camera track at.""" + shot_id, scene = _load_scene(ctx) + playback = scene.get("playback") or {} + if "playing" in args: + playback["playing"] = bool(args["playing"]) + if "elapsed" in args: + elapsed = args["elapsed"] + if not isinstance(elapsed, (int, float)) or isinstance(elapsed, bool) or elapsed < 0: + return {"ok": False, "error": "elapsed must be a non-negative number (seconds)"} + playback["elapsed"] = float(elapsed) + if "speed" in args: + speed = args["speed"] + if not isinstance(speed, (int, float)) or isinstance(speed, bool) or speed <= 0: + return {"ok": False, "error": "speed must be a positive number"} + playback["speed"] = float(speed) + if "duration" in args: + duration = args["duration"] + if ( + not isinstance(duration, (int, float)) + or isinstance(duration, bool) + or duration < 1 + or duration > _KEYFRAME_TIME_MAX + ): + return {"ok": False, "error": f"duration must be between 1 and {_KEYFRAME_TIME_MAX:g} seconds"} + playback["duration"] = float(duration) + scene["playback"] = playback + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "playback_set") + return _ok(comp_id, playback=playback) + + +async def t_set_joint(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + joint = args.get("joint") + if joint not in JOINT_KEYS: + return {"ok": False, "error": f"joint must be one of: {', '.join(sorted(JOINT_KEYS))}"} + values = args.get("values") + expected = POSTURE_ENTRY_LENGTHS[POSTURE_ENTRIES.index(joint)] + if not isinstance(values, list) or len(values) != expected or not all( + isinstance(v, (int, float)) for v in values + ): + return { + "ok": False, + "error": f"values for '{joint}' must be a list of {expected} numbers " + "(degrees; euler xyz for most joints, a single bend for knees/elbows, " + "7 for fingers)", + } + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + if obj.get("type") in ("camera",) or obj.get("type", "").startswith( + ("cube", "plane", "cylinder", "sphere", "capsule", "cone", "torus") + ): + return {"ok": False, "error": f"Object '{obj.get('name')}' has no joints to pose."} + _apply_joint(obj, joint, values) + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "joint_set") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_set_posture(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + posture = args.get("posture") + error = _validate_posture(posture) + if error: + return {"ok": False, "error": f"Invalid posture: {error}"} + obj["posture"] = posture + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "posture_set") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_list_poses(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + from calliope.poses import list_builtin_poses + + return _ok(0, poses=list_builtin_poses()) + + +async def t_apply_pose(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + from calliope.poses import get_builtin_pose + + object_id = args.get("object_id") + pose_id = args.get("pose_id") + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + posture = get_builtin_pose(pose_id) + if posture is None: + return {"ok": False, "error": f"No pose with id '{pose_id}'. Call list_poses for valid ids."} + obj["posture"] = posture + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "pose_applied") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_reset_pose(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + object_id = args.get("object_id") + shot_id, scene = _load_scene(ctx) + obj = _find_object(scene, object_id) + if obj is None: + return {"ok": False, "error": f"No object with id '{object_id}' in this composition."} + obj.pop("posture", None) + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "pose_reset") + return _ok(comp_id, object=_summarize_object(obj)) + + +async def t_set_shot(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + shot_id, scene = _load_scene(ctx) + params = scene.get("shotParams") or {} + for key, allowed, aliases in ( + ("shotSize", SHOT_SIZES, {}), + ("angle", ANGLES, _ANGLE_ALIASES), + ("elevation", ELEVATIONS, {}), + ("composition", COMPOSITIONS, _COMPOSITION_ALIASES), + ): + value = args.get(key) + if value is None: + continue + if aliases and value in aliases: + value = aliases[value] + if value not in allowed: + return { + "ok": False, + "error": f"{key} must be one of: {', '.join(allowed)}", + } + params[key] = value + scene["shotParams"] = params + comp_id = _save_scene(ctx, scene) + await _publish_updated(comp_id, "shot_set") + return _ok(comp_id, shotParams=params) + + +async def t_list_shot_presets(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + return _ok( + 0, + shotSize=list(SHOT_SIZES), + angle=list(ANGLES), + elevation=list(ELEVATIONS), + composition=list(COMPOSITIONS), + ) + + +async def t_request_capture(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + """Stamp a capture request, then poll for the UI's posted capture row. + + The browser renders the PNG (it owns the WebGL canvas) and POSTs it to + /api/shots/{id}/captures, which clears capture_request_json — that clear + is the completion signal. + """ + from calliope.routers.shots import get_or_create_for_session + + label = (args.get("label") or "capture").strip()[:200] + conn = _db() + try: + comp = get_or_create_for_session(conn, ctx.session_id) + comp_id = int(comp["id"]) + conn.execute( + "UPDATE shot_composition SET capture_request_json = ?, " + "updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (json.dumps({"label": label, "requested_at": time.time()}), comp_id), + ) + conn.commit() + finally: + conn.close() + await _publish_updated(comp_id, "capture_requested") + + deadline = time.monotonic() + CAPTURE_POLL_TIMEOUT_S + while time.monotonic() < deadline: + await asyncio.sleep(CAPTURE_POLL_INTERVAL_S) + conn = _db() + try: + row = conn.execute( + "SELECT capture_request_json FROM shot_composition WHERE id = ?", + (comp_id,), + ).fetchone() + if row is not None and not row["capture_request_json"]: + cap = conn.execute( + "SELECT id, file_path, label FROM shot_capture " + "WHERE composition_id = ? ORDER BY id DESC LIMIT 1", + (comp_id,), + ).fetchone() + return _ok( + comp_id, + label=label, + capture_id=cap["id"] if cap else None, + file_path=cap["file_path"] if cap else None, + note="Capture saved. Reference it in generation by this path.", + ) + finally: + conn.close() + return _ok( + comp_id, + label=label, + note="Capture request sent — the page will save the PNG shortly " + "(it may be closed right now).", + ) + + +# ---- registration ----------------------------------------------------------- + + +def register(registry: ToolRegistry) -> None: + registry.register( + ToolDefinition( + name="get_scene", + description=( + "See the current 3D composition (Build Scene): every object's " + "id/name/type/transform/posture plus shot framing. Call before " + "any edit." + ), + parameters={"type": "object", "properties": {}}, + executor=t_get_scene, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="add_object", + description=( + "Add an object to the 3D composition: a character " + "('male'/'female'/'child'), a primitive blockout shape " + "(cube/plane/cylinder/sphere/capsule/cone/torus), or a camera. " + "Returns the new object id." + ), + parameters={ + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": list(OBJECT_TYPES), + }, + "name": {"type": "string", "description": "Optional display name"}, + }, + "required": ["type"], + }, + executor=t_add_object, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="delete_object", + description="Remove one object from the 3D composition.", + parameters={ + "type": "object", + "properties": {"object_id": {"type": "string"}}, + "required": ["object_id"], + }, + executor=t_delete_object, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="rename_object", + description="Rename an object in the 3D composition.", + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "name": {"type": "string"}, + }, + "required": ["object_id", "name"], + }, + executor=t_rename_object, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="set_transform", + description=( + "Move/rotate/scale an object. Partial — only the keys you send " + "change. position/rotation/scale are [x, y, z]; rotation is " + "degrees. y is up. Characters stand on y=0." + ), + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "transform": { + "type": "object", + "properties": { + "position": { + "type": "array", + "items": {"type": "number"}, + "minItems": 3, + "maxItems": 3, + }, + "rotation": { + "type": "array", + "items": {"type": "number"}, + "minItems": 3, + "maxItems": 3, + }, + "scale": { + "type": "array", + "items": {"type": "number"}, + "minItems": 3, + "maxItems": 3, + }, + }, + }, + }, + "required": ["object_id"], + }, + executor=t_set_transform, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="reset_transform", + description="Reset an object to the origin with identity rotation/scale.", + parameters={ + "type": "object", + "properties": {"object_id": {"type": "string"}}, + "required": ["object_id"], + }, + executor=t_reset_transform, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="select_object", + description=( + "Highlight an object for the user (UI selection). Use to point " + "at what you are talking about, not required before edits." + ), + parameters={ + "type": "object", + "properties": {"object_id": {"type": "string"}}, + "required": ["object_id"], + }, + executor=t_select_object, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="clear_scene", + description="Remove every object from the 3D composition (start over).", + parameters={"type": "object", "properties": {}}, + executor=t_clear_scene, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="set_joint", + description=( + "Pose one joint of a character (degrees). Joints: torso, head, " + "l_leg/r_leg, l_knee/r_knee (1 bend value), l_ankle/r_ankle, " + "l_arm/r_arm (shoulders), l_elbow/r_elbow (1 bend), " + "l_wrist/r_wrist, l_finger_0..4 / r_finger_0..4 (7 values). " + "Most joints take 3 euler values [x, y, z]." + ), + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "joint": {"type": "string"}, + "values": { + "type": "array", + "items": {"type": "number"}, + "description": "3 euler values, 1 for knees/elbows, 7 for fingers", + }, + }, + "required": ["object_id", "joint", "values"], + }, + executor=t_set_joint, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="set_posture", + description=( + "Advanced: replace a character's whole posture (the serialized " + "v7 posture object). Prefer set_joint for ordinary posing." + ), + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "posture": {"type": "object"}, + }, + "required": ["object_id", "posture"], + }, + executor=t_set_posture, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="list_poses", + description="List built-in poses that apply_pose can put on a character.", + parameters={"type": "object", "properties": {}}, + executor=t_list_poses, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="apply_pose", + description="Apply a built-in pose (id from list_poses) to a character.", + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "pose_id": {"type": "string"}, + }, + "required": ["object_id", "pose_id"], + }, + executor=t_apply_pose, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="reset_pose", + description="Clear a character's pose back to the default stance.", + parameters={ + "type": "object", + "properties": {"object_id": {"type": "string"}}, + "required": ["object_id"], + }, + executor=t_reset_pose, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="set_shot", + description=( + "Frame the shot: shotSize (wide/full/medium/mcu/closeup), angle " + "(front/threeQuarterLeft/threeQuarterRight/profile/back/ots), " + "elevation (eye/high/low), composition (center/leftThird/" + "rightThird/upperThird/lowerThird/negativeSpace). Partial — " + "only the keys you send change. OTS needs a second character." + ), + parameters={ + "type": "object", + "properties": { + "shotSize": {"type": "string", "enum": list(SHOT_SIZES)}, + "angle": {"type": "string", "enum": list(ANGLES)}, + "elevation": {"type": "string", "enum": list(ELEVATIONS)}, + "composition": {"type": "string", "enum": list(COMPOSITIONS)}, + }, + }, + executor=t_set_shot, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="list_shot_presets", + description="List valid shot-size/angle/elevation/composition ids for set_shot.", + parameters={"type": "object", "properties": {}}, + executor=t_list_shot_presets, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="request_capture", + description=( + "Render the current viewport as a PNG reference (for ControlNet " + "or prompt reference). The Build Scene page saves it; returns " + "the file path to reference in generation." + ), + parameters={ + "type": "object", + "properties": { + "label": {"type": "string", "description": "Short capture label"} + }, + }, + executor=t_request_capture, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="add_keyframe", + description=( + "Pin the object's CURRENT transform/posture as a keyframe at " + "`time` (seconds, 0-60). Workflow: set_transform the object, " + "add_keyframe, set_transform again, add_keyframe at a later " + "time — playback then glides between them. Replaces a " + "keyframe within 1/24s of `time`. Camera objects excluded " + "(keyframe the camera via the UI timeline instead)." + ), + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "time": {"type": "number", "description": "Seconds (0-60)"}, + }, + "required": ["object_id", "time"], + }, + executor=t_add_keyframe, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="update_keyframe", + description=( + "Change an existing keyframe's transform (partial position/" + "rotation/scale). Get keyframe ids from get_scene." + ), + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "keyframe_id": {"type": "string"}, + "transform": { + "type": "object", + "properties": { + "position": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}, + "rotation": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}, + "scale": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}, + }, + }, + }, + "required": ["object_id", "keyframe_id", "transform"], + }, + executor=t_update_keyframe, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="delete_keyframe", + description="Remove one keyframe from an object's track (the last remaining keyframe is kept).", + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "keyframe_id": {"type": "string"}, + }, + "required": ["object_id", "keyframe_id"], + }, + executor=t_delete_keyframe, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="move_keyframe_time", + description="Move an existing keyframe to a new time (seconds, 0-60) without changing what it stores.", + parameters={ + "type": "object", + "properties": { + "object_id": {"type": "string"}, + "keyframe_id": {"type": "string"}, + "time": {"type": "number", "description": "Seconds (0-60)"}, + }, + "required": ["object_id", "keyframe_id", "time"], + }, + executor=t_move_keyframe_time, + category="shot", + requires_project=False, + blind_only=True, + ) + ) + registry.register( + ToolDefinition( + name="set_playback", + description=( + "Control the timeline: play/pause, scrub the playhead " + "(elapsed seconds), speed, or duration (1-60s). Playback " + "samples every tracked object's keyframes and the camera " + "track; export renders the camera track." + ), + parameters={ + "type": "object", + "properties": { + "playing": {"type": "boolean"}, + "elapsed": {"type": "number", "description": "Seconds"}, + "speed": {"type": "number"}, + "duration": {"type": "number", "description": "Seconds (1-60)"}, + }, + }, + executor=t_set_playback, + category="shot", + requires_project=False, + blind_only=True, + ) + ) diff --git a/calliope-backend/src/calliope/agent/harness/policy.py b/calliope-backend/src/calliope/agent/harness/policy.py index dd2dc8ea..3cb09ecb 100644 --- a/calliope-backend/src/calliope/agent/harness/policy.py +++ b/calliope-backend/src/calliope/agent/harness/policy.py @@ -1,16 +1,20 @@ -"""HITL / confirmation policy — mechanical gates only. +"""Permission policy — the user's command IS the permission. -Design rule (learned the hard way on canvas/62 + canvas/65): policy decides -PERMISSION from explicit user acts; it never guesses SCOPE from prose. -Scope is enforced mechanically by the enqueue tools (explicit ids, or an -explicit all_missing=true / "all scenes" word). Prose heuristics here are -limited to: does this message ask for generation at all, or confirm an -offer — nothing more. +A local tool for local users. When someone types "Regenerate the full +script for this project — turn the story into scenes", that is an ORDER, +not a suggestion to negotiate. The policy's jobs: -Permission sources (any one grants): -- an ask_user card answered affirmatively with scope=render (structured), -- an @workflow tag (a deliberate picker act), -- render verbs in the user's own words, or a terse confirmation. +1. read INTENT from the user's own words (generation ask, confirmation); +2. keep structured approvals (ask_user cards) working; +3. leave SCOPE to the tools' arguments (ids, all_missing, refs) — prose + never decides scope. + +There is deliberately no message-length cap ("regenerate the full script +for this project, keep the characters and locations consistent" is one +command, not a suspicious wall of text), no global-negation veto ("don't +overthink, render all scenes" is a command), and no politeness filter. +Negation is CLAUSE-scoped: only a "no" inside ~4 words of the cue vetoes +that cue. """ from __future__ import annotations @@ -19,12 +23,14 @@ from typing import Any from calliope.agent.harness.registry import ToolContext -# Affirmation cues for an explicit user "yes" (or "replace it" / "start over"). +# Affirmation cues: an explicit yes OR a regeneration verb — "regenerate +# the script" both asks and authorizes in one message. _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|append|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", + r"regen\b|rebuild|rewrite|re-?write|go\s+for\s+it|fine|sounds\s+good|" + r"that'?s\s+fine)\b", re.IGNORECASE, ) _NEGATE_RE = re.compile( @@ -56,25 +62,44 @@ def user_prose(text: str) -> str: return raw.strip() +def _cue_is_negated(before: str, after: str) -> bool: + """Only a short negation directly adjacent to the cue vetoes it.""" + before_words = before.split() + if before_words and _NEGATE_RE.search(" ".join(before_words[-4:])): + return True + if re.match(r"\s*(no|not|don'?t|never)\b", after, re.IGNORECASE): + return True + return False + + def is_confirmation(text: str) -> bool: - """A terse, non-negated message carrying an explicit affirmative cue.""" + """True when any clause of the message commands/confirms an action. + + Clause-scoped negation: "don't change the story, regenerate the script" + confirms (the veto sits in a different clause than the cue); "no, don't + replace" does not. + """ t = user_prose(text) - if not t or len(t) > 200: + if not t: return False - if _NEGATE_RE.search(t): - return False - return bool(_CONFIRM_RE.search(t)) + for clause in re.split(r"[,.;!?]|\bbut\b|\bhowever\b", t, flags=re.IGNORECASE): + m = _CONFIRM_RE.search(clause) + if not m: + continue + before = clause[: m.start()] + after = clause[m.end() :] + if not _cue_is_negated(before, after): + return True + return False def is_render_request(text: str) -> bool: """True when the message explicitly asks for image/video generation. - Negation is CLAUSE-scoped, not message-global: "no image need, all 20 - scenes use this text2video workflow" is a render request with a negated - clause about images. A global veto made "do not overthink, make the - video" read as a refusal and hid the render tools (the agent then - fabricated job ids — the bug this keeps fixed). Only a negation in the - SAME clause as the render cue counts against it. + Clause-scoped negation: "no image need, all 20 scenes use this + text2video workflow" is a render request. A global veto made "do not + overthink, make the video" read as a refusal and hid the render tools + (canvas/62). Only a negation adjacent to the cue counts against it. """ t = user_prose(text) if not t: @@ -86,11 +111,8 @@ def is_render_request(text: str) -> bool: for match in _RENDER_REQUEST_RE.finditer(clause): before = clause[max(0, match.start() - 60) : match.start()] after = clause[match.end() : match.end() + 30] - if _NEGATE_RE.search(before) and len(before.split()) <= 4: - continue - if re.match(r"\s*(no|not|don'?t|never)\b", after, re.IGNORECASE): - continue - return True + if not _cue_is_negated(before, after): + return True return False diff --git a/calliope-backend/src/calliope/agent/harness/prompts.py b/calliope-backend/src/calliope/agent/harness/prompts.py index a4294fe2..bc3865f2 100644 --- a/calliope-backend/src/calliope/agent/harness/prompts.py +++ b/calliope-backend/src/calliope/agent/harness/prompts.py @@ -1,14 +1,22 @@ -"""System-prompt assembly from registered sections. +"""System prompt composition — a section registry, assembled per step. -Ported from the deepseek-harness `ctx.systemPrompt` seam: instead of one -hardcoded string, plugins contribute ordered sections. `assemble(ctx)` renders -them (a section may skip itself, e.g. workspace digest in sandbox mode). +Ported from the deepseek-harness shape: the system prompt is a list of +registered sections (key, order, render) sorted by order and joined. +One broken section must never kill the prompt. + +The tool-discipline section is deliberately LEAN. This is a local harness +for a local user: the rules teach the ReAct cycle (look → act → observe → +decide → finish) and get out of the way. The user's message is the plan; +permissions flow from it; guards exist to catch mistakes, not to run the +show. What killed canvas/70 was an agent that got a guard denial and then +ground in circles for ten minutes — the rules below make escalation and +finishing first-class moves instead. """ from __future__ import annotations import logging -from collections.abc import Awaitable, Callable -from dataclasses import dataclass +from dataclasses import dataclass, field +from typing import Awaitable, Callable from calliope.agent.harness.registry import ToolContext, _db, _project_stats from calliope.config import settings @@ -24,7 +32,7 @@ class PromptSection: key: str order: int # ascending; ties keep registration order render: Callable[[ToolContext], Awaitable[str | None]] - seq: int = 0 # registration-order tiebreaker + seq: int = field(default=0) # registration-order tiebreaker class SystemPromptService: @@ -50,7 +58,6 @@ class SystemPromptService: try: text = await section.render(ctx) except Exception: - # One broken section must not kill the whole system prompt. logger.exception("Prompt section %r failed; skipping", section.key) continue if text: @@ -59,7 +66,7 @@ class SystemPromptService: # ───────────────────────────────────────────────────────────────────────── -# Built-in sections (port of the previous monolithic prompt) +# Built-in sections # ───────────────────────────────────────────────────────────────────────── @@ -122,9 +129,9 @@ def _mode_text(ctx: ToolContext) -> str: "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.\n" - "- Film clips: enqueue_video_jobs with orders or scene_ids for ONLY " + "- Film clips: enqueue_video_jobs with refs/clip_ids/orders 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/" + "list (that is not 'all'). all_clips=true only if they said all/" "every clip. Orphan video jobs (wired_to_scene=false) use " "attach_asset target=scene + scene_id.\n" "- Clip versioning ('apply render 430 to scene 2', 'use the older " @@ -213,64 +220,48 @@ def _render_digest(p, stats, beats, chars, locs, scenes, pending) -> str: async def _tool_discipline_section(ctx: ToolContext) -> str | None: return ( - "Tool discipline:\n" - "1. READ BEFORE WRITE. Before generate_*, update_*, add_*, delete_*, " - "reorder_*, or enqueue_*: call get_workspace (or the matching list " - "tool) to see current state. Never edit blind.\n" - "2. ONE tool call at a time — wait for its result before the next. " - "Never fabricate results or guess ids.\n" - "3. DESTRUCTIVE TOOLS: generate_story and generate_script with " - "replace=true DELETE existing data (beats/characters/locations, or all " - "scenes). When the project already has content, the call is BLOCKED " - "unless the user's latest message explicitly asks for/confirms the " - "replacement. If it is blocked, ask the user; once they answer yes " - "(e.g. 'yes, replace'), retry replace=true and it will go through. " - "Otherwise pass replace=false to append.\n" - "4. RENDERS ARE HUMAN-IN-THE-LOOP. enqueue_asset_jobs, enqueue_video_jobs, " - "and run_workflow queue real renders. NEVER call them unless the user's " - "latest message explicitly asks for generation (e.g. 'generate the images', " - "'render the video', 'create an image') or confirms your offer. " - "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 — 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 " - "runs after the user explicitly asks for it.\n" - "7. FINISH: when the request is complete, reply with a concise " - "plain-text summary (what was created/changed, job ids enqueued, any " - "failures) with NO tool call.\n" - "8. MEMORY: save_memory records a DURABLE preference or convention " - "for future sessions — call it the moment the user states one " - "('I always want…', 'never do…', 'prefer terse', 'this project uses " - "X style') or corrects you in a way that will recur. One atomic " - "sentence. Do NOT save one-off task details or ids. Before saving, " - "list_memories; if a memory now contradicts an older one, " - "forget_memory the stale one first. Saved memories are injected into " - "your system prompt each turn — follow them." + "You work in a ReAct loop: each step you may call tools, see their " + "results, and decide the next move. Multi-step is normal — one tool " + "call per step, observe the result, then reason and act again. The " + "user's message is the plan; execute it.\n" + "1. ACT on the request. If a tool matches what the user asked, call " + "it — don't re-read state you already have, don't ask what has " + "already been answered. One get_workspace at the START of a turn is " + "plenty; the digest above is usually enough.\n" + "2. OBSERVE. Tool results tell you what happened. A result with " + "ok:false is information, not a wall: read the error, fix the " + "arguments or pick a different tool. NEVER repeat the exact same " + "call expecting a different result — after one failed attempt, " + "either CHANGE the approach (different args / different tool) or " + "hand control back to the user.\n" + "3. ESCALATE, don't spin. If you are blocked twice on the same " + "goal, or a guard denies you, stop retrying: tell the user exactly " + "what was denied and why, then either ask_user (question card) or " + "end the turn with a plain explanation. Two failed attempts = " + "report, not retry.\n" + "4. FINISH cleanly. When the goal is met, reply with a concise " + "summary of what was created/changed (ids, job numbers) and NO " + "tool call. Ending the turn with an answer is always allowed.\n" + "5. GUARDS: destructive tools (generate_story / generate_script " + "replace=true) are blocked only when the user did NOT ask for the " + "replacement — if they asked (e.g. 'regenerate the script'), the " + "guard allows it and you should just retry; if they didn't, " + "ask_user first, then retry once they confirm. Renders " + "(enqueue_*, run_workflow) need the user to have asked for " + "generation in their own words; render tools are hidden until " + "then. A guard denial names the reason — act on it once, don't " + "loop.\n" + "6. SCOPE from args, never from vibes: pass the ids/refs the user " + "named (orders=[3], clip_ids=[12], character_ids=[5]); bulk flags " + "(all_missing / all_clips) only when they said all/every/" + "remaining. Bulk enqueues above 3 targets are refused without " + "such a word — that gate is about size, not permission.\n" + "7. #N is ORDER (clip number), never a database id. IDs come only " + "from tool results. Never fabricate ids or results.\n" + "8. MEMORY: save_memory the moment the user states a durable " + "preference or corrects a recurring behavior (one atomic " + "sentence; list first, forget stale contradictions). Do not save " + "one-off task details." ) diff --git a/calliope-backend/src/calliope/agent/harness/registry.py b/calliope-backend/src/calliope/agent/harness/registry.py index 089787bd..83e6639b 100644 --- a/calliope-backend/src/calliope/agent/harness/registry.py +++ b/calliope-backend/src/calliope/agent/harness/registry.py @@ -21,6 +21,30 @@ from calliope.config import settings from calliope.db import get_db, row_to_dict from calliope.events.bus import event_bus +# ───────────────────────────────────────────────────────────────────────── +# Scene tool scope (Build Scene surface) +# ───────────────────────────────────────────────────────────────────────── + +# Build Scene sessions (origin='scene') are the 3D blockout surface: their +# toolset is the shot_* set plus this minimal base. Enforced at BOTH payload +# assembly and execute time (same two-layer pattern as requires_project). +# Defined here (not harness/__init__) to avoid a circular import; re-exported +# there for tests/UI consumers. +GUARD_SCENE_TOOL_SCOPE = "guard_scene_tool_scope" +_SCENE_ALLOWED_CATEGORIES = {"shot"} +_SCENE_ALLOWED_TOOLS = { + "ask_user", + "list_skills", + "read_skill", + "save_memory", + "list_memories", + "forget_memory", +} + + +def _scene_scoped(t: "ToolDefinition") -> bool: + return getattr(t, "category", None) in _SCENE_ALLOWED_CATEGORIES or t.name in _SCENE_ALLOWED_TOOLS + # ───────────────────────────────────────────────────────────────────────── # Context & definitions @@ -30,10 +54,14 @@ from calliope.events.bus import event_bus @dataclass class ToolContext: """Per-run context. `project_id` is the session's workspace binding: - None means a blind/sandbox session (only project-creating tools allowed).""" + None means a blind/sandbox session (only project-creating tools allowed). + `origin` stamps WHERE the session was born ('chat' | 'scene') — scene + sessions are Build Scene's blockout surface and get the shot-tool-only + payload; it says nothing about project linking.""" session_id: int project_id: int | None = None + origin: str = "chat" @dataclass @@ -121,6 +149,10 @@ class ToolRegistry: return False if t.blind_only and ctx.project_id is not None: return False + # Build Scene surface: shot tools + minimal base ONLY. A missing tool + # is harder to misuse than one that fails at execute time. + if ctx.origin == "scene" and not _scene_scoped(t): + 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). @@ -170,6 +202,19 @@ class ToolRegistry: "Call unlink_project first to return this session to sandbox." ), } + if ctx.origin == "scene" and not _scene_scoped(t): + return { + "ok": False, + "reason_code": GUARD_SCENE_TOOL_SCOPE, + "error": ( + "This is a Build Scene session: only the 3D blockout tools " + "(get_scene, add_object, set_transform, set_joint, add_keyframe, " + "set_shot, …) are available here. Build and pose the scene, then " + "use Capture / Export video — the blockout clip is picked as a " + "reference input from the Playground media library, not generated " + "from this chat." + ), + } decision = ALLOW for hook in self.pre_execute: diff --git a/calliope-backend/src/calliope/agent/harness/runner.py b/calliope-backend/src/calliope/agent/harness/runner.py index f0b7f37a..0e0b40f0 100644 --- a/calliope-backend/src/calliope/agent/harness/runner.py +++ b/calliope-backend/src/calliope/agent/harness/runner.py @@ -180,6 +180,34 @@ class AgentRunner: task = self._tasks.get(session_id) return task is not None and not task.done() + def recover_orphaned_sessions(self) -> int: + """Reset sessions stuck in ``running`` at startup. + + A crashed or killed process never reaches the loop's ``turn/end`` + (its finally-block died with it), so those rows stay ``running`` + forever — the UI shows a phantom "Working…" state with a dead Stop + button and the session looks unresumable. At startup no tasks exist + yet, so every ``running`` row is orphaned by definition. Returns the + number of rows reset.""" + conn = self._db() + try: + stuck = [r["id"] for r in conn.execute( + "SELECT id FROM agent_sessions WHERE status = 'running'" + ).fetchall()] + if stuck: + conn.execute( + "UPDATE agent_sessions SET status = 'idle' WHERE status = 'running'" + ) + conn.commit() + logger.warning( + "Startup recovery: reset %d agent session(s) left 'running' " + "by a previous process: %s", + len(stuck), stuck, + ) + return len(stuck) + finally: + conn.close() + async def start_turn( self, session_id: int, @@ -277,13 +305,14 @@ class AgentRunner: conn = self._db() try: row = conn.execute( - "SELECT project_id FROM agent_sessions WHERE id = ?", (session_id,) + "SELECT project_id, origin FROM agent_sessions WHERE id = ?", (session_id,) ).fetchone() project_id = row["project_id"] if row else None + origin = (row["origin"] if row else None) or "chat" finally: conn.close() - ctx = ToolContext(session_id=session_id, project_id=project_id) + ctx = ToolContext(session_id=session_id, project_id=project_id, origin=origin) try: final = await orchestrate( ctx, diff --git a/calliope-backend/src/calliope/agent/llm.py b/calliope-backend/src/calliope/agent/llm.py index 6b77af17..0c5afb3a 100644 --- a/calliope-backend/src/calliope/agent/llm.py +++ b/calliope-backend/src/calliope/agent/llm.py @@ -15,6 +15,10 @@ logger = logging.getLogger("calliope.llm") # else (401, 429, 5xx) is a real error and re-raises. _STREAM_UNSUPPORTED_STATUS = frozenset({400, 404, 405, 501}) +# Set when an endpoint rejects multimodal image parts — later calls in this +# process skip the parts-provision step entirely (text-only fallback). +_TEXT_ONLY_ENDPOINTS: set[str] = set() + _PROTECTED_PAYLOAD_KEYS = frozenset({"model", "messages", "stream"}) @@ -33,6 +37,42 @@ def _merge_extra_body(payload: dict[str, Any], extra_body: dict[str, Any] | None payload[key] = value +def _strip_image_parts(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Return a copy of the messages with image_url content parts removed. + + User messages whose content is a part-list collapse to their text part; + text-only content passes through untouched. + """ + out: list[dict[str, Any]] = [] + for msg in messages: + content = msg.get("content") + if not (isinstance(content, list) and any(p.get("type") == "image_url" for p in content)): + out.append(msg) + continue + text = " ".join( + str(p.get("text") or "") for p in content if isinstance(p, dict) and p.get("type") == "text" + ).strip() + out.append({**msg, "content": text}) + return out + + +def _has_image_parts(messages: list[dict[str, Any]]) -> bool: + return any( + isinstance(m.get("content"), list) + and any(isinstance(p, dict) and p.get("type") == "image_url" for p in m["content"]) + for m in messages + ) + + +def _looks_like_image_rejection(status_code: int, body: str) -> bool: + """Heuristic for HTTP 400s caused by image parts on a text-only endpoint.""" + if status_code != 400: + return False + lowered = (body or "").lower() + markers = ("image", "multimodal", "vision", "content part", "image_url") + return any(marker in lowered for marker in markers) + + class LLMClient: def __init__( self, @@ -51,6 +91,9 @@ class LLMClient: # server still fails fast. Shorter timeouts (e.g. the 30 s preview # path) trade headroom for a snappier deterministic fallback. self.client = httpx.AsyncClient(timeout=timeout) + # Flipped when the endpoint rejects image content parts; also tracked + # process-wide per base_url so new clients start with the knowledge. + self._text_only = self.base_url in _TEXT_ONLY_ENDPOINTS @classmethod def for_role(cls, role: str, *, timeout: float = 120.0) -> LLMClient: @@ -159,8 +202,31 @@ class LLMClient: Servers that reject the tools field get it dropped in-stream (the reply will have no tool_calls); servers that reject streaming itself get one - plain blocking call. + plain blocking call. Endpoints that reject image content parts get one + text-only retry and are remembered as text-only for the process. """ + if self._text_only or not _has_image_parts(messages): + return await self._chat_with_tools_impl(messages, temperature, tools, tool_choice) + try: + return await self._chat_with_tools_impl(messages, temperature, tools, tool_choice) + except httpx.HTTPStatusError as exc: + body = exc.response.text[:500] if exc.response is not None else "" + if not _looks_like_image_rejection(exc.response.status_code, body): + raise + logger.warning("Endpoint rejected image parts (%s); retrying text-only", body[:200]) + self._text_only = True + _TEXT_ONLY_ENDPOINTS.add(self.base_url) + return await self._chat_with_tools_impl( + _strip_image_parts(messages), temperature, tools, tool_choice + ) + + async def _chat_with_tools_impl( + self, + messages: list[dict[str, Any]], + temperature: float = 0.7, + tools: list[dict[str, Any]] | None = None, + tool_choice: str | dict[str, Any] | None = None, + ) -> dict[str, Any]: try: parts: list[str] = [] tool_calls: list[dict[str, Any]] = [] diff --git a/calliope-backend/src/calliope/agent/prompts.py b/calliope-backend/src/calliope/agent/prompts.py index ba0275a7..86ee5b5c 100644 --- a/calliope-backend/src/calliope/agent/prompts.py +++ b/calliope-backend/src/calliope/agent/prompts.py @@ -13,16 +13,35 @@ STORY_GENERATION_SYSTEM = ( ) SCRIPT_GENERATION_SYSTEM = ( - "You are a screenwriter for short-form AI video. " + "You are a screenwriter for AI video production. " "Write a scene-by-scene script that uses the provided characters and locations. " - "Each scene's action is fed directly into a video generation model, so it must be a " - "rich, multi-sentence cinematic description — never a single short sentence. " + "A scene is a SCREENPLAY unit — a heading, full action prose, and all dialogue that plays " + "in it — exactly like a produced script. Scenes may be long; a later 'break into shots' " + "pass splits each scene into short renderable clips, so never compress the content to fit " + "a single video generation. " "Always respond with a single valid JSON object. " "HARD RULE: the scenes array length must equal required_scene_count from the user message. " "Returning fewer scenes is a failure. Respect the user's chosen scene count." ) +def estimate_scene_duration_sec(scene: dict[str, Any]) -> int: + """Content-derived duration estimate for one scene. + + Dialogue reads at ~150 wpm (2.5 words/sec) + performance beats; action + prose at ~1 beat per 25 words, minimum 3 seconds. Replaces flat LLM + guesses so a scene's runtime matches what it actually contains — the + coverage pass splits this budget across the scene's clips. + """ + dialog_words = len((scene.get("dialog") or "").split()) + action_words = len((scene.get("action") or "").split()) + secs = dialog_words / 2.5 + action_words / 25.0 * 3.0 + return max(3, min(600, round(secs))) or 3 + + +DEFAULT_CLIP_DURATION_SEC = 8 # per-clip cap the coverage pass splits scenes into + + def estimate_target_seconds(target_duration: str | None) -> int: """Best-effort parse of free-text duration into seconds.""" text = (target_duration or "").strip().lower() @@ -294,7 +313,6 @@ def build_script_messages( scene_n = max(recommended, int(scene_count)) if scene_count and scene_count > 0 else recommended # Stretch runtime floor when the user asked for more clips than duration alone implies secs = max(secs, scene_n * 6) - duration_hint = max(4, round(secs / scene_n)) char_lines = "\n".join( f"- id={c['id']} {c['name']} ({c.get('role') or ''}): {c.get('appearance') or ''}" for c in characters @@ -325,35 +343,37 @@ Locations: === HARD CONSTRAINTS (non-negotiable) === 1. The JSON field "scenes" MUST contain EXACTLY {scene_n} objects. 2. order_index must run 1, 2, 3, ... {scene_n} with no gaps. -3. Do NOT collapse back to fewer scenes. The user expanded the script to {scene_n} clips — fill all of them. -4. Sum of duration_sec across all scenes should be approximately {secs} (within ±15%). -5. Prefer short scenes (5–10s) — this is for AI video clips. Spread the beat arc across all {scene_n} scenes. +3. Do NOT collapse back to fewer scenes. The user expanded the script to {scene_n} scenes — fill all of them. +4. Spread the full story across all {scene_n} scenes. A scene is a SCREENPLAY unit — it may + run 30–120 seconds when the material needs it (a later pass breaks long scenes into + short renderable clips). NEVER compress or summarize action to make a scene shorter. +5. Pace the total toward ~{secs} seconds overall — scenes with lots of dialogue run longer. -=== ACTION DETAIL (this text IS the video prompt — users copy it straight into the generator) === -Each scene's "action" is fed verbatim to an AI video generator. Write 4–6 vivid present-tense -sentences (~80–130 words) per scene as ONE flowing natural-English paragraph — no bullet points, -no labeled fragments (do NOT write "Shot:", "Lighting:", etc.), no line breaks. Rules: -1. ONE SHOT PER SCENE. A clip is only {duration_hint} seconds — describe a single continuous - camera setup with at most one simple action beat (one entrance, one gesture, one reveal). - If a beat needs more room, split it across multiple scenes instead of compressing it. -2. SHOT & MOTION. Name the framing and camera move (wide establishing, slow push-in, handheld - tracking, low angle, rack focus) AND what visibly moves in frame — video models need motion: - gestures, turning heads, hair and fabric, drifting dust, sweeping flashlight beams, an - expression shifting. A static description produces a static clip. -3. CHARACTER ANCHORS. The first time each character appears in a scene, attach a 3–8 word +=== ACTION (full visible action prose — the fidelity contract) === +Each scene's "action" is the complete on-screen action for that scene, present tense, +ONE flowing natural-English paragraph — no bullet points, no labeled fragments (do NOT +write "Shot:", "Lighting:", etc.), no line breaks. Cover EVERYTHING that visibly happens +in the scene from start to finish: entrances, blocking, gestures, reveals, who moves +where. Rules: +1. MOTION. Name framing and camera behavior where natural (wide establishing, slow + push-in, handheld tracking, low angle) AND what visibly moves in frame — gestures, + turning heads, hair and fabric, drifting dust, an expression shifting. A static + description produces a static clip downstream. +2. CHARACTER ANCHORS. The first time each character appears in a scene, attach a 3–8 word visual anchor taken from their description above (hair, outfit, one distinguishing feature), e.g. "MIA, a teenage girl with a chestnut ponytail and yellow rain jacket,". Later mentions in the same scene use the plain name. Never invent new appearance details — reuse these anchors so every clip matches the same face and wardrobe. -4. ENVIRONMENT & CONTINUITY. Concrete set details, props, weather, time-of-day — consistent +3. ENVIRONMENT & CONTINUITY. Concrete set details, props, weather, time-of-day — consistent with the location description and with earlier scenes set in the same location. -5. LIGHTING & MOOD. Named light sources, color palette, emotional tone of the moment. +4. LIGHTING & MOOD. Named light sources, color palette, emotional tone of the moment. Describe only what is VISIBLE (no inner thoughts; no sounds or music — dialogue covers audio). -Vary shot types across scenes — do not write {scene_n} identical wide shots. -=== DIALOGUE === -Keep lines short and natural. When delivery matters for performance, add a brief cue in -parentheses after the speaker name, e.g. "MIA (whispering): line" or "LIAM (hushed, excited): line". +=== DIALOGUE (verbatim fidelity) === +Every line the scene needs MUST appear in "dialog", formatted 'SPEAKER: line', one per +line, in play order. NEVER paraphrase, summarize, or drop lines ("they argue about the +money" is a FAILURE — write the actual lines). When delivery matters for performance, +add a brief cue in parentheses after the speaker name, e.g. "MIA (whispering): line". Respond ONLY with JSON: {{ @@ -363,7 +383,7 @@ Respond ONLY with JSON: "heading": "INT. LOCATION - TIME", "action": "Wide establishing shot, slow push-in through the cracked main doorway. MIA, a teenage girl with a chestnut ponytail and yellow rain jacket, steps into the dusty main hall, lantern held high, its warm glow catching drifting dust motes around her cautious, widening eyes. She freezes mid-step, fingers tightening on the lantern handle as she looks up. Overturned desks and a collapsed chalkboard fill the frame; moonlight cuts through shattered windows in pale blue shafts. The mood is hushed and uneasy, shadows pooling at the edges of the lantern light.", "dialog": "MIA (whispering): line\\nNARRATOR: line", - "duration_sec": 5, + "duration_sec": 8, "character_ids": [1], "location_id": 1 }} @@ -371,9 +391,9 @@ Respond ONLY with JSON: }} Use only the provided character_ids and location_ids. -FINAL CHECK before responding: scenes.length == {scene_n}, and every action is a flowing prose -paragraph of 4–6 sentences (~80–130 words) covering ONE shot, with a character anchor at each -character's first mention (no bullets, no labels, no invented appearances). If not, fix it.""" +FINAL CHECK before responding: scenes.length == {scene_n}, every action is a flowing prose +paragraph covering the WHOLE on-screen action, and every dialogue line is written out +verbatim in "dialog" (no summaries). If not, fix it.""" return [ {"role": "system", "content": SCRIPT_GENERATION_SYSTEM}, {"role": "user", "content": user}, @@ -401,7 +421,6 @@ def build_script_chunk_messages( continuity — heading style, location, who's on screen — without resending the whole script.""" secs = estimate_target_seconds(target_duration) - per_scene = max(4, round(secs / max(1, scene_count))) char_lines = "\n".join( f"- id={c['id']} {c['name']} ({c.get('role') or ''}): {c.get('appearance') or ''}" for c in characters @@ -446,36 +465,39 @@ Locations: === HARD CONSTRAINTS (non-negotiable) === 1. The JSON field "scenes" MUST contain EXACTLY {chunk_scenes} objects. 2. order_index must run {chunk_start}, {chunk_start + 1}, ... {last} with no gaps. -3. Each scene ~{per_scene} seconds (5–10s typical) — these are AI video clips. +3. A scene is a SCREENPLAY unit — it may run 30–120 seconds when the material needs it + (a later pass breaks long scenes into short renderable clips). NEVER compress or + summarize action to make a scene shorter. 4. Advance the beat arc across the whole {scene_count}-scene story; this chunk covers the part that falls at scenes {chunk_start}–{last}. 5. If earlier scenes are listed above, continue them naturally — same characters, consistent location, no abrupt reset{'' if previous_tail else ' (this is the first chunk)'}. -=== ACTION DETAIL (this text IS the video prompt — users copy it straight into the generator) === -Each scene's "action" is fed verbatim to an AI video generator. Write 4–6 vivid present-tense -sentences (~80–130 words) per scene as ONE flowing natural-English paragraph — no bullet points, -no labeled fragments (do NOT write "Shot:", "Lighting:", etc.), no line breaks. Rules: -1. ONE SHOT PER SCENE. A clip is only {per_scene} seconds — describe a single continuous - camera setup with at most one simple action beat (one entrance, one gesture, one reveal). -2. SHOT & MOTION. Name the framing and camera move (wide establishing, slow push-in, handheld - tracking, low angle, rack focus) AND what visibly moves in frame — video models need motion: - gestures, turning heads, hair and fabric, drifting dust, sweeping flashlight beams, an - expression shifting. A static description produces a static clip. -3. CHARACTER ANCHORS. The first time each character appears in a scene, attach a 3–8 word +=== ACTION (full visible action prose — the fidelity contract) === +Each scene's "action" is the complete on-screen action for that scene, present tense, +ONE flowing natural-English paragraph — no bullet points, no labeled fragments (do NOT +write "Shot:", "Lighting:", etc.), no line breaks. Cover EVERYTHING that visibly happens +in the scene from start to finish: entrances, blocking, gestures, reveals, who moves +where. Rules: +1. MOTION. Name framing and camera behavior where natural (wide establishing, slow + push-in, handheld tracking, low angle) AND what visibly moves in frame — gestures, + turning heads, hair and fabric, drifting dust, an expression shifting. A static + description produces a static clip downstream. +2. CHARACTER ANCHORS. The first time each character appears in a scene, attach a 3–8 word visual anchor taken from their description above (hair, outfit, one distinguishing feature), e.g. "MIA, a teenage girl with a chestnut ponytail and yellow rain jacket,". Later mentions in the same scene use the plain name. Never invent new appearance details — reuse these anchors so every clip matches the same face and wardrobe. -4. ENVIRONMENT & CONTINUITY. Concrete set details, props, weather, time-of-day — consistent +3. ENVIRONMENT & CONTINUITY. Concrete set details, props, weather, time-of-day — consistent with the location description and with earlier scenes set in the same location. -5. LIGHTING & MOOD. Named light sources, color palette, emotional tone of the moment. +4. LIGHTING & MOOD. Named light sources, color palette, emotional tone of the moment. Describe only what is VISIBLE (no inner thoughts; no sounds or music — dialogue covers audio). -Vary shot types across scenes. -=== DIALOGUE === -Keep lines short and natural. When delivery matters for performance, add a brief cue in -parentheses after the speaker name, e.g. "MIA (whispering): line". +=== DIALOGUE (verbatim fidelity) === +Every line the scene needs MUST appear in "dialog", formatted 'SPEAKER: line', one per +line, in play order. NEVER paraphrase, summarize, or drop lines ("they argue about the +money" is a FAILURE — write the actual lines). When delivery matters for performance, +add a brief cue in parentheses after the speaker name, e.g. "MIA (whispering): line". Respond ONLY with JSON: {{ @@ -485,7 +507,7 @@ Respond ONLY with JSON: "heading": "INT. LOCATION - TIME", "action": "Wide establishing shot, slow push-in through the cracked main doorway. MIA, a teenage girl with a chestnut ponytail and yellow rain jacket, steps into the dusty main hall, lantern held high, its warm glow catching drifting dust motes around her cautious, widening eyes.", "dialog": "MIA (whispering): line", - "duration_sec": 5, + "duration_sec": 8, "character_ids": [1], "location_id": 1 }} @@ -494,9 +516,9 @@ Respond ONLY with JSON: Use only the provided character_ids and location_ids. FINAL CHECK before responding: scenes.length == {chunk_scenes}, order_index runs -{chunk_start}..{last}, and every action is a flowing prose paragraph of 4–6 sentences -(~80–130 words) covering ONE shot with a character anchor at each character's first -mention (no bullets, no labels, no invented appearances). If not, fix it.""" +{chunk_start}..{last}, every action is a flowing prose paragraph covering the WHOLE +on-screen action, and every dialogue line is written out verbatim in "dialog" (no +summaries). If not, fix it.""" return [ {"role": "system", "content": SCRIPT_GENERATION_SYSTEM}, {"role": "user", "content": user}, @@ -603,6 +625,7 @@ def scene_video_prompt(scene: dict[str, Any], characters: list[dict[str, Any]]) parts = [ scene.get("heading") or "", scene.get("action") or "", + scene.get("dialog") or "", f"featuring {char_bits}" if char_bits else "", "cinematic motion, coherent continuity", ] diff --git a/calliope-backend/src/calliope/agent/script_agent.py b/calliope-backend/src/calliope/agent/script_agent.py index 477e3379..6b387694 100644 --- a/calliope-backend/src/calliope/agent/script_agent.py +++ b/calliope-backend/src/calliope/agent/script_agent.py @@ -4,9 +4,14 @@ from __future__ import annotations from typing import Any from calliope.agent.llm import generate_structured -from calliope.agent.prompts import build_script_chunk_messages, recommend_scene_count +from calliope.agent.prompts import ( + build_script_chunk_messages, + estimate_scene_duration_sec, + estimate_target_seconds, + recommend_scene_count, +) from calliope.config import settings -from calliope.db import get_db, row_to_dict +from calliope.db import ensure_default_clip, get_db, row_to_dict from calliope.events.bus import event_bus # Scenes per LLM call. A single 20-scene request means a multi-thousand-token @@ -59,7 +64,7 @@ async def _request_chunk( return scenes[:chunk_scenes] -async def _generate_scenes_chunked( +async def _iter_scene_chunks( *, project_id: int, p: dict[str, Any], @@ -67,7 +72,13 @@ async def _generate_scenes_chunked( characters: list[dict[str, Any]], locations: list[dict[str, Any]], required_scenes: int, -) -> list[dict[str, Any]]: +): + """Yield one list of scenes per chunk as each LLM call completes. + + Yields promptly so `generate_script` can persist + commit chunk by chunk — + a crash mid-generation keeps every already-committed chunk instead of + losing the whole script. Raises at the end if the board came up short. + """ plan: list[tuple[int, int]] = [] start = 1 while start <= required_scenes: @@ -102,12 +113,35 @@ async def _generate_scenes_chunked( for offset, scene in enumerate(scenes): scene["order_index"] = chunk_start + offset collected.extend(scenes) + yield scenes if len(collected) < required_scenes: raise ValueError( f"Script returned {len(collected)} scenes but {required_scenes} were required. " "Add scenes again and retry, or raise target duration." ) + + +async def _generate_scenes_chunked( + *, + project_id: int, + p: dict[str, Any], + beats: list[dict[str, Any]], + characters: list[dict[str, Any]], + locations: list[dict[str, Any]], + required_scenes: int, +) -> list[dict[str, Any]]: + """Whole-board convenience wrapper over `_iter_scene_chunks`.""" + collected: list[dict[str, Any]] = [] + async for scenes in _iter_scene_chunks( + project_id=project_id, + p=p, + beats=beats, + characters=characters, + locations=locations, + required_scenes=required_scenes, + ): + collected.extend(scenes) return collected[:required_scenes] @@ -146,6 +180,7 @@ def _persist_scenes( ), ) scene_id = cur.lastrowid + ensure_default_clip(conn, scene_id, project_id) for cid in scene.get("character_ids") or []: exists = conn.execute( "SELECT id FROM characters WHERE id = ? AND project_id = ?", @@ -166,6 +201,7 @@ async def generate_script( *, replace: bool = True, scene_count: int | None = None, + with_clips: bool = True, ) -> dict[str, Any]: await event_bus.publish( "agent.thinking", {"message": "Writing scene script…", "project_id": project_id} @@ -213,33 +249,70 @@ async def generate_script( "project_id": project_id, }, ) + target_seconds = estimate_target_seconds(p.get("target_duration")) # Chunked generation: one LLM call per SCRIPT_CHUNK scenes. A single # 20+ scene request means a multi-thousand-token JSON answer that # small/local models take minutes to stream (or fail outright and # trigger a full-script retry) — the "Regenerate Script hangs" bug. # Small boards (one chunk) keep the exact single-call behavior. - scenes_out = await _generate_scenes_chunked( + created: list[dict[str, Any]] = [] + first_chunk = True + async for scenes in _iter_scene_chunks( project_id=project_id, p=p, beats=beats, characters=characters, locations=locations, required_scenes=required_scenes, - ) + ): + if replace and first_chunk: + # Clear the old board only once the first replacement chunk is + # in hand — a failed first chunk leaves the old script intact. + scene_ids = [ + r["id"] + for r in conn.execute( + "SELECT id FROM scenes WHERE project_id = ?", (project_id,) + ).fetchall() + ] + for sid in scene_ids: + conn.execute("DELETE FROM scene_characters WHERE scene_id = ?", (sid,)) + conn.execute("DELETE FROM scenes WHERE project_id = ?", (project_id,)) + first_chunk = False + created.extend(_persist_scenes(conn, project_id, scenes)) + # Commit per chunk: every finished chunk is durable, so a crash, + # stop, or disconnect mid-generation keeps what was already paid + # for instead of losing the whole script in one failed transaction. + conn.commit() + await event_bus.publish( + "agent.thinking", + { + "message": f"Saved {len(created)}/{required_scenes} scenes…", + "project_id": project_id, + }, + ) - if replace: - scene_ids = [ - r["id"] - for r in conn.execute( - "SELECT id FROM scenes WHERE project_id = ?", (project_id,) - ).fetchall() + # Durations are OUR estimate from actual content, not the model's flat + # guess — and the user's target runtime is the total they sum to. Runs + # AFTER all chunks are committed, as a bulk UPDATE over the durable + # board (the rescale is global; the rows were persisted per chunk). + if target_seconds: + all_rows = conn.execute( + "SELECT id, action, dialog FROM scenes WHERE project_id = ? ORDER BY order_index", + (project_id,), + ).fetchall() + estimates = [ + estimate_scene_duration_sec({"action": r["action"], "dialog": r["dialog"]}) + for r in all_rows ] - for sid in scene_ids: - conn.execute("DELETE FROM scene_characters WHERE scene_id = ?", (sid,)) - conn.execute("DELETE FROM scenes WHERE project_id = ?", (project_id,)) - - created = _persist_scenes(conn, project_id, scenes_out) + total_est = sum(estimates) + if total_est > 0: + scale = max(target_seconds / total_est, 1.0) + for row, est in zip(all_rows, estimates): + conn.execute( + "UPDATE scenes SET duration_sec = ? WHERE id = ?", + (max(3, round(est * scale)), row["id"]), + ) conn.execute( "UPDATE projects SET status = 'in_progress', updated_at = CURRENT_TIMESTAMP WHERE id = ?", @@ -253,6 +326,44 @@ async def generate_script( "project_id": project_id, }, ) - return {"ok": True, "scenes": created, "generated": {"scenes": scenes_out}} + + # Break into shots: expand every fresh scene into renderable shot + # clips as part of the SAME tool call. `expand_scene_coverage` + # persists per scene (one commit per scene), so this stage is + # durable too — a crash keeps the script plus every clip already + # expanded. The default clip from `_persist_scenes` is what gets + # replaced here, so nothing is lost if this stage is interrupted. + clips_summary: list[dict[str, Any]] = [] + if with_clips and created: + await event_bus.publish( + "agent.thinking", + { + "message": f"Breaking {len(created)} scenes into shot clips…", + "project_id": project_id, + }, + ) + from calliope.agent.coverage_agent import expand_scene_coverage + + coverage = await expand_scene_coverage( + project_id, + [int(s["id"]) for s in created], + ) + clips_summary = coverage.get("scenes") or [] + total_clips = sum(int(r.get("clips") or 0) for r in clips_summary) + await event_bus.publish( + "agent.thinking", + { + "message": f"Shot list done — {total_clips} clips across " + f"{len(clips_summary)} scenes", + "project_id": project_id, + }, + ) + + return { + "ok": True, + "scenes": created, + "clips": clips_summary, + "generated": {"scenes": created}, + } finally: conn.close() diff --git a/calliope-backend/src/calliope/agent/video_agent.py b/calliope-backend/src/calliope/agent/video_agent.py index 1574a487..7f8bdec5 100644 --- a/calliope-backend/src/calliope/agent/video_agent.py +++ b/calliope-backend/src/calliope/agent/video_agent.py @@ -1,4 +1,4 @@ -"""Enqueue per-scene video generation jobs.""" +"""Enqueue per-clip video generation jobs (a scene expands into many clips).""" from __future__ import annotations import hashlib @@ -103,31 +103,85 @@ def _video_input(inputs: list[dict[str, Any]]) -> dict[str, Any] | None: def _previous_clip( conn: sqlite3.Connection, project_id: int, - order_index: int, + global_position: tuple[int, int], ) -> tuple[str | None, bool]: - """Nearest earlier scene's clip path + whether any earlier scene exists. + """Nearest earlier clip (global playback order) + whether any earlier clip exists. - Returns ``(path, has_earlier_scene)``; path is None when the clip file does - not exist on disk (not yet generated) or there is no earlier scene. + ``global_position`` is the current clip's ``(scene.order_index, clip.order_index)``. + Returns ``(path, has_earlier)``; path is None when the file does not exist on + disk (not yet generated) or there is no earlier clip. """ + scene_pos, clip_pos = global_position row = conn.execute( """ - SELECT video_path FROM scenes - WHERE project_id = ? AND order_index < ? AND video_path IS NOT NULL - ORDER BY order_index DESC LIMIT 1 + SELECT COALESCE(c.clip_path, s.video_path) AS clip_path FROM clips c + JOIN scenes s ON s.id = c.scene_id + WHERE c.project_id = ? + AND (s.order_index < ? OR (s.order_index = ? AND c.order_index < ?)) + AND COALESCE(c.clip_path, s.video_path) IS NOT NULL + ORDER BY s.order_index DESC, c.order_index DESC LIMIT 1 """, - (project_id, order_index), + (project_id, scene_pos, scene_pos, clip_pos), ).fetchone() has_earlier = conn.execute( - "SELECT 1 FROM scenes WHERE project_id = ? AND order_index < ? LIMIT 1", - (project_id, order_index), + """ + SELECT 1 FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.project_id = ? + AND (s.order_index < ? OR (s.order_index = ? AND c.order_index < ?)) + LIMIT 1 + """, + (project_id, scene_pos, scene_pos, clip_pos), ).fetchone() is not None - path = row["video_path"] if row else None + path = row["clip_path"] if row else None if path and Path(path).exists(): return path, has_earlier return None, has_earlier +def _fetch_clips( + conn: sqlite3.Connection, + project_id: int, + *, + scene_ids: list[int] | None = None, + clip_ids: list[int] | None = None, +) -> list[dict[str, Any]]: + """Clips joined with their scenes, in global playback order. + + Clip columns COALESCE onto the scene's legacy columns (video_path, chain) + so pre-clips rows and legacy scene-level writes keep working unchanged. + """ + query = """ + SELECT c.*, + COALESCE(c.clip_path, s.video_path) AS resolved_clip_path, + CASE WHEN COALESCE(c.chain_from_prev, 0) = 0 AND c.order_index = 1 + THEN COALESCE(s.chain_from_prev, 0) + ELSE COALESCE(c.chain_from_prev, 0) END AS chain_flag, + s.heading, s.action, s.dialog, s.order_index AS scene_order_index, + s.duration_sec AS scene_duration_sec, s.env_image_path, s.location_id + FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.project_id = ? + """ + params: list[Any] = [project_id] + if clip_ids: + placeholders = ",".join("?" * len(clip_ids)) + query += f" AND c.id IN ({placeholders})" + params.extend(clip_ids) + elif scene_ids: + placeholders = ",".join("?" * len(scene_ids)) + query += f" AND c.scene_id IN ({placeholders})" + params.extend(scene_ids) + query += " ORDER BY s.order_index, c.order_index, c.id" + rows = [dict(r) for r in conn.execute(query, params).fetchall()] + for r in rows: + # Legacy fallbacks: resolved names win over the raw clip columns. + r["clip_path"] = r.get("resolved_clip_path") or r.get("clip_path") + if r.get("chain_flag"): + r["chain_from_prev"] = r["chain_flag"] + r.pop("resolved_clip_path", None) + r.pop("chain_flag", None) + return rows + + def _workflow_json(workflow: dict[str, Any] | None) -> dict[str, Any]: if not workflow: return {} @@ -157,9 +211,9 @@ def _get_workflow(workflow_id: int | None = None) -> dict[str, Any] | None: conn.close() -def _scene_video_settings(scene: dict[str, Any]) -> dict[str, Any]: - """Parsed scenes.video_settings_json — {} when unset or malformed.""" - raw = scene.get("video_settings_json") +def _clip_video_settings(clip: dict[str, Any]) -> dict[str, Any]: + """Parsed clips.video_settings_json — {} when unset or malformed.""" + raw = clip.get("video_settings_json") if not raw: return {} try: @@ -169,32 +223,44 @@ def _scene_video_settings(scene: dict[str, Any]) -> dict[str, Any]: return data if isinstance(data, dict) else {} -def _stored_input_values(scene: dict[str, Any]) -> dict[str, Any]: - """Saved per-scene form values (input_values inside video_settings).""" - values = _scene_video_settings(scene).get("input_values") +def _stored_input_values(clip: dict[str, Any]) -> dict[str, Any]: + """Saved per-clip form values (input_values inside video_settings).""" + values = _clip_video_settings(clip).get("input_values") if isinstance(values, dict): return {k: v for k, v in values.items() if v not in (None, "")} return {} -def _stored_prompt_draft(scene: dict[str, Any]) -> str | None: - draft = _scene_video_settings(scene).get("prompt_draft") +def _stored_prompt_draft(clip: dict[str, Any]) -> str | None: + draft = _clip_video_settings(clip).get("prompt_draft") return draft if isinstance(draft, str) and draft.strip() else None -def _scene_prompt_hash(scene: dict[str, Any]) -> str: - """Cheap fingerprint of the inputs a draft was based on (stale detection).""" +def _clip_prompt_hash(clip: dict[str, Any]) -> str: + """Cheap fingerprint of the inputs a draft was based on (stale detection). + + Combines the scene's content fingerprint with the clip's own fields, so an + edit to either invalidates saved drafts. Keeps the scene-only fields in the + basis (heading/action/dialog/location/characters) so legacy drafts saved + against scene-level hashes invalidate consistently. + """ basis = "|".join( - str(scene.get(k) or "") + str(clip.get(k) or "") for k in ("heading", "action", "dialog", "duration_sec", "location_id") ) - chars = ",".join(str(c) for c in sorted(scene.get("character_ids") or [])) - return hashlib.sha256((basis + "|" + chars).encode()).hexdigest()[:16] + chars = ",".join(str(c) for c in sorted(clip.get("character_ids") or [])) + clip_basis = "|".join( + str(clip.get(k) or "") + for k in ("description", "shot_size", "duration_sec", "order_index") + ) + return hashlib.sha256( + (basis + "|" + chars + "|clip:" + clip_basis).encode() + ).hexdigest()[:16] -async def preview_scene_prompt( +async def preview_clip_prompt( project_id: int, - scene_id: int, + clip_id: int, workflow_id: int | None = None, ) -> dict[str, Any]: """Resolve the exact prompt a Generate would send — without enqueueing. @@ -205,12 +271,18 @@ async def preview_scene_prompt( conn = get_db(settings.db_path) try: row = conn.execute( - "SELECT * FROM scenes WHERE id = ? AND project_id = ?", - (scene_id, project_id), + """ + SELECT c.*, s.heading, s.action, s.dialog, s.order_index AS scene_order_index, + s.env_image_path, s.location_id + FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.id = ? AND c.project_id = ? + """, + (clip_id, project_id), ).fetchone() if not row: - raise ValueError(f"Scene {scene_id} not found in project {project_id}") - scene = row_to_dict(row) + raise ValueError(f"Clip {clip_id} not found in project {project_id}") + clip = dict(row) + scene_id = clip["scene_id"] char_rows = conn.execute( """ SELECT c.* FROM characters c @@ -220,13 +292,13 @@ async def preview_scene_prompt( (scene_id,), ).fetchall() characters = [row_to_dict(r) for r in char_rows] - loc_image = scene.get("env_image_path") + loc_image = clip.get("env_image_path") loc_row: dict[str, Any] | None = None - if scene.get("location_id"): + if clip.get("location_id"): loc = conn.execute( "SELECT name, description, consistency_prompt, reference_image_path " "FROM locations WHERE id = ?", - (scene["location_id"],), + (clip["location_id"],), ).fetchone() if loc: loc_row = row_to_dict(loc) @@ -235,19 +307,20 @@ async def preview_scene_prompt( finally: conn.close() - wf_id = workflow_id or scene.get("workflow_id") + scene = _scene_fields_from_clip(clip, characters) + wf_id = workflow_id or clip.get("workflow_id") workflow = _get_workflow(wf_id) if not workflow: raise ValueError("No enabled video workflow found — configure one in Settings") inputs = parse_dynamic_inputs(_workflow_json(workflow)) profile = workflow.get("prompt_profile") or "prose" - based_on = _scene_prompt_hash(scene) + based_on = _clip_prompt_hash({**clip, "character_ids": [c["id"] for c in characters]}) if profile == "minimax_h3_ref": # Fresh saved draft short-circuits the LLM call - draft = _stored_prompt_draft(scene) + draft = _stored_prompt_draft(clip) if draft: - meta = _scene_video_settings(scene).get("prompt_draft_meta") or {} + meta = _clip_video_settings(clip).get("prompt_draft_meta") or {} if meta.get("based_on") == based_on: return { "prompt": draft, @@ -258,7 +331,7 @@ async def preview_scene_prompt( subjects, _ = _h3_subjects(characters, loc_row, loc_image, inputs) await event_bus.publish( "agent.thinking", - {"message": f"H3 prompt rewrite · scene {scene.get('order_index')}", "project_id": project_id}, + {"message": f"H3 prompt rewrite · scene {clip.get('scene_order_index')} clip {clip.get('order_index')}", "project_id": project_id}, ) # Preview is interactive — fail fast to the deterministic template # instead of making the user wait out a dead endpoint. @@ -268,10 +341,50 @@ async def preview_scene_prompt( return {"prompt": prompt, "profile": profile, "from_draft": False, "based_on": based_on} +def _scene_fields_from_clip( + clip: dict[str, Any], characters: list[dict[str, Any]] +) -> dict[str, Any]: + """A scene-shaped dict whose action/dialog are narrowed to the clip's beat. + + Both the prose and H3 prompt builders consume scene rows; feeding them this + projection means a clip's prompt contains only what that clip performs. + """ + desc = (clip.get("description") or "").strip() + action = desc or (clip.get("action") or "").strip() + if desc and clip.get("shot_size"): + action = f"{clip['shot_size']} shot. {action}" + dialog = _clip_dialog(clip) + return { + "heading": clip.get("heading"), + "action": action, + "dialog": dialog, + "duration_sec": clip.get("duration_sec"), + "character_ids": [c["id"] for c in characters], + } + + +def _clip_dialog(clip: dict[str, Any]) -> str | None: + """The dialog lines this clip performs (from dialog_lines_covered), verbatim.""" + covered = clip.get("dialog_lines_covered") + if not covered: + return None + if isinstance(covered, str): + # Raw DB column is a JSON array string — parse before indexing. + try: + covered = json.loads(covered) + except (json.JSONDecodeError, TypeError): + return None + idxs = covered if isinstance(covered, list) else [] + lines = [ln for ln in (clip.get("dialog") or "").splitlines() if ln.strip()] + picked = [lines[i - 1] for i in idxs if isinstance(i, int) and 1 <= i <= len(lines)] + return "\n".join(picked) or None + + async def enqueue_video_jobs( project_id: int, *, scene_ids: list[int] | None = None, + clip_ids: list[int] | None = None, workflow_id: int | None = None, input_values_override: dict[str, Any] | None = None, prompts: dict[int, str] | None = None, @@ -283,41 +396,41 @@ async def enqueue_video_jobs( conn = get_db(settings.db_path) jobs: list[dict[str, Any]] = [] try: - query = "SELECT * FROM scenes WHERE project_id = ?" - params: list[Any] = [project_id] - if scene_ids: - placeholders = ",".join("?" * len(scene_ids)) - query += f" AND id IN ({placeholders})" - params.extend(scene_ids) - query += " ORDER BY order_index" - scenes = [row_to_dict(r) for r in conn.execute(query, params).fetchall()] + clips = _fetch_clips(conn, project_id, scene_ids=scene_ids, clip_ids=clip_ids) - for scene in scenes: + for clip in clips: + scene_id = clip["scene_id"] # Supersede leftover pending jobs so a re-Generate always starts fresh conn.execute( """ UPDATE jobs SET status = 'failed', error = 'superseded by new generate', completed_at = CURRENT_TIMESTAMP - WHERE scene_id = ? AND kind = 'video' AND status = 'pending' + WHERE clip_id = ? AND kind = 'video' AND status = 'pending' """, - (scene["id"],), + (clip["id"],), + ) + # Clear prior render so UI shows generating instead of the old video. + # Also NULL the scene's legacy mirror — COALESCE reads fall back to + # it, so a stale path there would resurrect the old render. + conn.execute( + "UPDATE clips SET clip_path = NULL WHERE id = ?", + (clip["id"],), ) - # Clear prior clip so UI shows generating instead of the old video conn.execute( "UPDATE scenes SET video_path = NULL WHERE id = ?", - (scene["id"],), + (scene_id,), ) # Commit BEFORE enqueue: queue_manager.enqueue writes on its own # connection, and holding this transaction open across that call # self-deadlocks (sqlite3.OperationalError: database is locked). conn.commit() - wf_id = workflow_id or scene.get("workflow_id") + wf_id = workflow_id or clip.get("workflow_id") workflow = _get_workflow(wf_id) workflow_json = _workflow_json(workflow) inputs = parse_dynamic_inputs(workflow_json) if workflow_json else [] - duration = scene.get("duration_sec") + duration = clip.get("duration_sec") or clip.get("scene_duration_sec") char_rows = conn.execute( """ @@ -325,30 +438,33 @@ async def enqueue_video_jobs( JOIN scene_characters sc ON sc.character_id = c.id WHERE sc.scene_id = ? """, - (scene["id"],), + (scene_id,), ).fetchall() characters = [row_to_dict(r) for r in char_rows] + char_ids = [c["id"] for c in characters] char_image = next( (c.get("sheet_path") or c.get("portrait_path") for c in characters if c.get("sheet_path") or c.get("portrait_path")), None, ) - loc_image = scene.get("env_image_path") + loc_image = clip.get("env_image_path") loc_row: dict[str, Any] | None = None - if scene.get("location_id"): + if clip.get("location_id"): row = conn.execute( "SELECT name, description, consistency_prompt, reference_image_path " "FROM locations WHERE id = ?", - (scene["location_id"],), + (clip["location_id"],), ).fetchone() if row: loc_row = row_to_dict(row) if not loc_image: loc_image = loc_row["reference_image_path"] + scene = _scene_fields_from_clip(clip, characters) profile = (workflow or {}).get("prompt_profile") or "prose" - # Merge base: saved per-scene setup first, explicit request wins on + hash_input = {**clip, "character_ids": char_ids} + # Merge base: saved per-clip setup first, explicit request wins on # top — so batch Generate-all honors persisted form setups. - stored_values = _stored_input_values(scene) + stored_values = _stored_input_values(clip) extra_values: dict[str, Any] = {**stored_values} if input_values_override: extra_values.update( @@ -357,13 +473,13 @@ async def enqueue_video_jobs( if profile == "minimax_h3_ref": subjects, ref_paths = _h3_subjects(characters, loc_row, loc_image, inputs) # Prompt precedence: explicit request → saved (fresh) draft → LLM. - explicit_prompt = (prompts or {}).get(scene["id"]) + explicit_prompt = (prompts or {}).get(clip["id"]) fresh_draft = None if explicit_prompt is None: - candidate = _stored_prompt_draft(scene) + candidate = _stored_prompt_draft(clip) if candidate: - meta = _scene_video_settings(scene).get("prompt_draft_meta") or {} - if meta.get("based_on") == _scene_prompt_hash(scene): + meta = _clip_video_settings(clip).get("prompt_draft_meta") or {} + if meta.get("based_on") == _clip_prompt_hash(hash_input): fresh_draft = candidate if explicit_prompt is not None: prompt = explicit_prompt @@ -373,7 +489,7 @@ async def enqueue_video_jobs( await event_bus.publish( "agent.thinking", { - "message": f"H3 prompt rewrite · scene {scene.get('order_index')}", + "message": f"H3 prompt rewrite · scene {clip.get('scene_order_index')} clip {clip.get('order_index')}", "project_id": project_id, }, ) @@ -386,7 +502,7 @@ async def enqueue_video_jobs( extra=extra_values, ) else: - prompt = (prompts or {}).get(scene["id"]) or scene_video_prompt( + prompt = (prompts or {}).get(clip["id"]) or scene_video_prompt( scene, characters ) values = smart_fill_inputs( @@ -397,7 +513,7 @@ async def enqueue_video_jobs( duration=duration, extra=extra_values, ) - # Stored per-scene setups override smart-fill's context choices + # Stored per-clip setups override smart-fill's context choices # (e.g. an edited duration). smart_fill skips duration-role nodes # in `extra` by design — re-apply them here, request values win. explicit_final = { @@ -410,19 +526,22 @@ async def enqueue_video_jobs( payload: dict[str, Any] = {"input_values": values, "prompt": prompt} if session_id is not None: payload["session_id"] = session_id - if scene.get("chain_from_prev"): + if clip.get("chain_from_prev"): video_input = _video_input(inputs) if not video_input: raise ValueError( - f"Scene {scene.get('order_index')} is marked continue-from-previous " - f"but workflow '{(workflow or {}).get('name') or workflow_id}' has no " + f"Clip {clip.get('scene_order_index')}.{clip.get('order_index')} is marked " + f"continue-from-previous but workflow " + f"'{(workflow or {}).get('name') or workflow_id}' has no " "video input — pick a workflow with a (Input:video) node." ) video_node_id = str(video_input["nodeId"]) if not values.get(video_node_id): # Explicit clip from the form / input_values_override wins. prev_clip, has_earlier = _previous_clip( - conn, project_id, scene.get("order_index") or 0 + conn, + project_id, + (clip.get("scene_order_index") or 0, clip.get("order_index") or 0), ) if prev_clip: # Local path: the worker's prepare_media_inputs uploads it @@ -431,28 +550,30 @@ async def enqueue_video_jobs( elif has_earlier: # Previous clip not generated yet (typical when a batch is # queued in one go). The worker resolves it at RUN time — - # the queue is concurrency-1, so the earlier scene's clip + # the queue is concurrency-1, so the earlier clip # will exist by then. payload["continue_source"] = { - "scene_order_index": scene.get("order_index"), + "scene_order_index": clip.get("scene_order_index"), + "clip_order_index": clip.get("order_index"), } else: raise ValueError( - f"Scene {scene.get('order_index')} is marked continue-from-previous " - "but no previous clip exists yet — generate an earlier clip first " - "or upload a video in the Video stage." + f"Clip {clip.get('scene_order_index')}.{clip.get('order_index')} is marked " + "continue-from-previous but no previous clip exists yet — generate an " + "earlier clip first or upload a video in the Video stage." ) job = queue_manager.enqueue( project_id=project_id, kind="video", workflow_id=workflow["id"] if workflow else None, - scene_id=scene["id"], + scene_id=scene_id, + clip_id=clip["id"], payload=payload, ) - if workflow and not scene.get("workflow_id"): + if workflow and not clip.get("workflow_id"): conn.execute( - "UPDATE scenes SET workflow_id = ? WHERE id = ?", - (workflow["id"], scene["id"]), + "UPDATE clips SET workflow_id = ? WHERE id = ?", + (workflow["id"], clip["id"]), ) # Never hold a write lock across awaits (event publish below). conn.commit() @@ -462,7 +583,7 @@ async def enqueue_video_jobs( { "job_id": job["id"], "kind": "video", - "message": f"Scene · {scene.get('heading') or scene.get('order_index')}", + "message": _clip_label(clip), "project_id": project_id, }, ) @@ -470,3 +591,9 @@ async def enqueue_video_jobs( finally: conn.close() return jobs + + +def _clip_label(clip: dict[str, Any]) -> str: + """Human label: '#. · ' (scene heading retained).""" + heading = (clip.get("heading") or f"Scene {clip.get('scene_order_index')}").strip() + return f"#{clip.get('scene_order_index')}.{clip.get('order_index')} · {heading}" diff --git a/calliope-backend/src/calliope/db.py b/calliope-backend/src/calliope/db.py index 8655810f..d411b086 100644 --- a/calliope-backend/src/calliope/db.py +++ b/calliope-backend/src/calliope/db.py @@ -85,6 +85,29 @@ CREATE TABLE IF NOT EXISTS scene_characters ( PRIMARY KEY (scene_id, character_id) ); +-- Shot-level layer: one script scene expands into MANY renderable clips +-- (coverage). The clip — not the scene — is the unit that gets generated, +-- holds video settings, and lands in the export timeline. Scenes keep the +-- screenplay content; every scene has >= 1 clip (a default clip mirrors the +-- legacy 1:1 behavior for un-expanded projects). +CREATE TABLE IF NOT EXISTS clips ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + scene_id INTEGER NOT NULL REFERENCES scenes(id) ON DELETE CASCADE, + project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + order_index INTEGER NOT NULL, + description TEXT, + shot_size TEXT, + dialog_lines_covered TEXT, + duration_sec INTEGER, + workflow_id INTEGER, + clip_path TEXT, + video_settings_json TEXT, + chain_from_prev INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_clips_scene ON clips(scene_id); +CREATE INDEX IF NOT EXISTS idx_clips_project ON clips(project_id); + CREATE TABLE IF NOT EXISTS workflows ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, @@ -104,6 +127,7 @@ CREATE TABLE IF NOT EXISTS jobs ( id INTEGER PRIMARY KEY AUTOINCREMENT, project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, scene_id INTEGER REFERENCES scenes(id) ON DELETE SET NULL, + clip_id INTEGER REFERENCES clips(id) ON DELETE SET NULL, kind TEXT NOT NULL, workflow_id INTEGER REFERENCES workflows(id) ON DELETE SET NULL, status TEXT NOT NULL DEFAULT 'pending', @@ -121,6 +145,7 @@ CREATE TABLE IF NOT EXISTS agent_sessions ( project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL, title TEXT NOT NULL DEFAULT 'New chat', status TEXT NOT NULL DEFAULT 'idle' CHECK(status IN ('idle', 'running', 'error')), + origin TEXT NOT NULL DEFAULT 'chat' CHECK(origin IN ('chat', 'scene')), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); @@ -214,6 +239,27 @@ CREATE TABLE IF NOT EXISTS agent_memory ( UNIQUE(scope, project_id, content) ); CREATE INDEX IF NOT EXISTS idx_agent_memory_scope ON agent_memory(scope, project_id); + +CREATE TABLE IF NOT EXISTS shot_composition ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + agent_session_id INTEGER UNIQUE REFERENCES agent_sessions(id) ON DELETE SET NULL, + title TEXT NOT NULL DEFAULT 'Untitled composition', + scene_json TEXT NOT NULL DEFAULT '{}', + capture_request_json TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS shot_capture ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + composition_id INTEGER NOT NULL REFERENCES shot_composition(id) ON DELETE CASCADE, + kind TEXT NOT NULL DEFAULT 'image' CHECK(kind IN ('image','video')), + label TEXT, + file_path TEXT, + meta_json TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_shot_capture_composition ON shot_capture(composition_id); """ @@ -283,6 +329,43 @@ async def migrate_db(db_path: Path) -> None: ) if "video_settings_json" not in scene_cols: conn.execute("ALTER TABLE scenes ADD COLUMN video_settings_json TEXT") + # Clips layer: mirror each existing scene's production state into a + # default clip #1 so the 1:1 legacy behavior keeps working unchanged. + # Guarded on table emptiness — runs once, never touches clips the user + # (or the coverage pass) already created. + conn.execute( + """ + INSERT INTO clips (scene_id, project_id, order_index, duration_sec, + workflow_id, clip_path, video_settings_json, chain_from_prev) + SELECT s.id, s.project_id, 1, s.duration_sec, s.workflow_id, + s.video_path, s.video_settings_json, s.chain_from_prev + FROM scenes s + WHERE NOT EXISTS (SELECT 1 FROM clips c WHERE c.scene_id = s.id) + """ + ) + job_cols = {r[1] for r in conn.execute("PRAGMA table_info(jobs)").fetchall()} + if "clip_id" not in job_cols: + conn.execute("ALTER TABLE jobs ADD COLUMN clip_id INTEGER REFERENCES clips(id) ON DELETE SET NULL") + # Point existing video jobs at their scene's default clip so worker + # write-back keeps landing on the row the UI reads. + conn.execute( + """ + UPDATE jobs SET clip_id = ( + SELECT c.id FROM clips c WHERE c.scene_id = jobs.scene_id + ORDER BY c.order_index, c.id LIMIT 1 + ) + WHERE kind = 'video' AND scene_id IS NOT NULL AND clip_id IS NULL + """ + ) + # Build Scene's per-scene sessions: origin stamps WHERE a blind session was + # born ('chat' = user-created in AI Canvas, 'scene' = auto-created by the + # Build Scene rail). The session list excludes origin='scene' so scene + # sessions don't pollute the AI Canvas sidebar; Build Scene filters on it. + session_cols = {r[1] for r in conn.execute("PRAGMA table_info(agent_sessions)").fetchall()} + if "origin" not in session_cols: + conn.execute("ALTER TABLE agent_sessions ADD COLUMN origin TEXT NOT NULL DEFAULT 'chat'") + # Backfill: existing Scene · N sessions were born in Build Scene. + conn.execute("UPDATE agent_sessions SET origin = 'scene' WHERE title LIKE 'Scene · %'") project_cols = {r[1] for r in conn.execute("PRAGMA table_info(projects)").fetchall()} if "cover_path" not in project_cols: conn.execute("ALTER TABLE projects ADD COLUMN cover_path TEXT") @@ -307,6 +390,29 @@ def row_to_dict(row: sqlite3.Row) -> dict[str, Any]: return {key: row[key] for key in row.keys()} +def ensure_default_clip(conn: sqlite3.Connection, scene_id: int, project_id: int) -> None: + """Every scene keeps >= 1 clip: inserts default clip #1 when none exist. + + The default inherits the scene's production fields (duration, workflow, + settings, chain) so an un-expanded project behaves exactly like the old + 1:1 model. Called by every scene-creation path (router CRUD, script + generation, coverage expansion replacement). + """ + conn.execute( + """ + INSERT INTO clips (scene_id, project_id, order_index, description, + duration_sec, workflow_id, clip_path, video_settings_json, + chain_from_prev) + SELECT ?, ?, 1, NULL, duration_sec, workflow_id, video_path, + video_settings_json, chain_from_prev + FROM scenes s + WHERE s.id = ? AND s.project_id = ? + AND NOT EXISTS (SELECT 1 FROM clips WHERE scene_id = ?) + """, + (scene_id, project_id, scene_id, project_id, scene_id), + ) + + # Columns that store absolute asset paths. When the app folder moves, these # still point at the old install root and /api/file rejects them (403). _PATH_COLUMNS = { @@ -315,7 +421,9 @@ _PATH_COLUMNS = { "locations": ["reference_image_path"], "items": ["reference_image_path"], "scenes": ["env_image_path", "video_path"], + "clips": ["clip_path"], "canvas_node": ["artifact_path"], + "shot_capture": ["file_path"], } @@ -377,31 +485,32 @@ def rebase_stale_asset_paths(conn: sqlite3.Connection, data_dir: Path, assets_di (json.dumps(new_paths), row["id"]), ) count += 1 - # Scene video settings embed absolute asset paths (ref images, uploaded - # clips) in input_values — rebase those too so a moved install keeps the - # saved setups working. - rows = conn.execute( - "SELECT id, video_settings_json FROM scenes WHERE video_settings_json IS NOT NULL" - ).fetchall() - for row in rows: - try: - data = json.loads(row["video_settings_json"] or "{}") - except json.JSONDecodeError: - continue - if not isinstance(data, dict): - continue - values = data.get("input_values") - if isinstance(values, dict): - data["input_values"] = { - k: (_rebase_path(v, data_dir, assets_dir) or v if isinstance(v, str) else v) - for k, v in values.items() - } - draft = data.get("prompt_draft") - if isinstance(draft, str) and not draft: - data.pop("prompt_draft", None) - conn.execute( - "UPDATE scenes SET video_settings_json = ? WHERE id = ?", - (json.dumps(data), row["id"]), - ) - count += 1 + # Scene/clip video settings embed absolute asset paths (ref images, + # uploaded clips) in input_values — rebase those too so a moved install + # keeps the saved setups working. + for table in ("scenes", "clips"): + rows = conn.execute( + f"SELECT id, video_settings_json FROM {table} WHERE video_settings_json IS NOT NULL" + ).fetchall() + for row in rows: + try: + data = json.loads(row["video_settings_json"] or "{}") + except json.JSONDecodeError: + continue + if not isinstance(data, dict): + continue + values = data.get("input_values") + if isinstance(values, dict): + data["input_values"] = { + k: (_rebase_path(v, data_dir, assets_dir) or v if isinstance(v, str) else v) + for k, v in values.items() + } + draft = data.get("prompt_draft") + if isinstance(draft, str) and not draft: + data.pop("prompt_draft", None) + conn.execute( + f"UPDATE {table} SET video_settings_json = ? WHERE id = ?", + (json.dumps(data), row["id"]), + ) + count += 1 return count diff --git a/calliope-backend/src/calliope/export/runner.py b/calliope-backend/src/calliope/export/runner.py index 757ffe8d..4861feaa 100644 --- a/calliope-backend/src/calliope/export/runner.py +++ b/calliope-backend/src/calliope/export/runner.py @@ -89,18 +89,25 @@ def target_fps(probes: list[dict[str, Any]]) -> float: def collect_clips(project_id: int) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - """Scenes in story order, split into (with video_path, without).""" + """Clips in global playback order (scene order, then clip order), split + into (with clip_path, without). Each row keeps its scene heading for the + skip-progress messages.""" conn = get_db(config.settings.db_path) try: rows = conn.execute( - "SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index", + """ + SELECT c.*, s.heading, s.order_index AS scene_order_index + FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.project_id = ? + ORDER BY s.order_index, c.order_index, c.id + """, (project_id,), ).fetchall() - scenes = [row_to_dict(r) for r in rows] + clips = [dict(r) for r in rows] finally: conn.close() - with_clip = [s for s in scenes if s.get("video_path")] - skipped = [s for s in scenes if not s.get("video_path")] + with_clip = [c for c in clips if c.get("clip_path")] + skipped = [c for c in clips if not c.get("clip_path")] return with_clip, skipped @@ -167,7 +174,7 @@ def build_ffmpeg_cmd( ffmpeg = shutil.which("ffmpeg") or "ffmpeg" cmd: list[str] = [ffmpeg, "-nostdin", "-nostats", "-progress", "pipe:1", "-y"] for clip in clips: - cmd += ["-i", str(clip["video_path"])] + cmd += ["-i", str(clip["clip_path"])] # Silent clips get a lavfi silence donor input, appended after the clip inputs # so input indices for real clips stay 0..n-1. lavfi_index: dict[int, int] = {} @@ -249,14 +256,17 @@ async def run_export( if not clips: raise RuntimeError("No scene clips to export — generate videos first") - for scene in skipped: - heading = (scene.get("heading") or f"Scene {scene.get('order_index')}").strip() + for clip in skipped: + heading = ( + (clip.get("heading") or f"Scene {clip.get('scene_order_index')}").strip() + ) + label = f"{clip.get('scene_order_index')}.{clip.get('order_index')} · {heading}" await bus.publish( "job.progress", { "job_id": job_id, "kind": "export", - "message": f"Skipping scene «{heading}» — no clip", + "message": f"Skipping clip «{label}» — no video", }, ) @@ -269,7 +279,7 @@ async def run_export( return [str(dest)] _require_binary("ffmpeg") - probes = [await probe(clip["video_path"]) for clip in clips] + probes = [await probe(clip["clip_path"]) for clip in clips] fps = target_fps(probes) durations = [float(p["duration"]) for p in probes] total_us = (sum(durations) - XFADE_SEC * max(0, len(clips) - 1)) * 1_000_000 diff --git a/calliope-backend/src/calliope/main.py b/calliope-backend/src/calliope/main.py index a45eafae..20aaf864 100644 --- a/calliope-backend/src/calliope/main.py +++ b/calliope-backend/src/calliope/main.py @@ -102,6 +102,9 @@ async def lifespan(app: FastAPI): ) finally: conn.close() + from calliope.agent.harness.runner import runner + + runner.recover_orphaned_sessions() await queue_worker.start() logger.info("Calliope started — db=%s dry_run=%s", settings.db_path, settings.dry_run) yield diff --git a/calliope-backend/src/calliope/models/schemas.py b/calliope-backend/src/calliope/models/schemas.py index 42cc9cd7..a73f834e 100644 --- a/calliope-backend/src/calliope/models/schemas.py +++ b/calliope-backend/src/calliope/models/schemas.py @@ -151,6 +151,39 @@ class SceneReorder(BaseModel): scene_ids: list[int] +class ClipCreate(BaseModel): + order_index: int | None = None # default: append at end of the scene + description: str | None = None + shot_size: str | None = None + dialog_lines_covered: list[int] | None = None + duration_sec: int | None = None + workflow_id: int | None = None + chain_from_prev: bool = False + video_settings: dict[str, Any] | None = None + + +class ClipUpdate(BaseModel): + order_index: int | None = None + description: str | None = None + shot_size: str | None = None + dialog_lines_covered: list[int] | None = None + duration_sec: int | None = None + workflow_id: int | None = None + clip_path: str | None = None + chain_from_prev: bool | None = None + video_settings: dict[str, Any] | None = None + + +class ClipReorder(BaseModel): + clip_ids: list[int] + + +class ExpandClipsRequest(BaseModel): + scene_ids: list[int] | None = None + guidance: str | None = None + clip_cap: int | None = None + + class WorkflowCreate(BaseModel): name: str = Field(..., min_length=1) kind: Literal["image", "video"] = "image" @@ -173,6 +206,7 @@ class WorkflowAnalyze(BaseModel): class JobCreate(BaseModel): scene_id: int | None = None + clip_id: int | None = None kind: str workflow_id: int | None = None input_values: dict[str, Any] | None = None @@ -201,14 +235,17 @@ class GenerateScenesRequest(BaseModel): class GenerateVideosRequest(BaseModel): + # Clip scoping is canonical; scene_ids expands to all clips of those scenes. scene_ids: list[int] | None = None + clip_ids: list[int] | None = None workflow_id: int | None = None input_values: dict[str, Any] | None = None - # Scene-id → confirmed prompt text (from the review modal). Wins over the + # Clip-id → confirmed prompt text (from the review modal). Wins over the # LLM rewrite and over any saved draft. prompts: dict[int, str] | None = None class PreviewPromptRequest(BaseModel): - scene_id: int + scene_id: int | None = None + clip_id: int | None = None workflow_id: int | None = None diff --git a/calliope-backend/src/calliope/poses.py b/calliope-backend/src/calliope/poses.py new file mode 100644 index 00000000..c0b05b59 --- /dev/null +++ b/calliope-backend/src/calliope/poses.py @@ -0,0 +1,141 @@ +"""Built-in pose library for the shot-builder (port of open-media's +public/poses/authoredPoses.json, MIT). Values are the serialized mannequin-js +v7 posture format — see harness/plugins/shot_builder.py for the entry table. +""" +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +_POSES: list[dict[str, Any]] = [ + { + "id": "authored.running-with-right-hand-forward", + "name": "running with right hand forward", + "posture": {"version": 7, "data": [[0,0,0],[0,-90,0],[0,0,-2],[0,0,5],[7.2,0.6,-8.4],[34.4],[-6,-6,-0.6],[-5.1,0.3,45.2],[62.4],[10.5,-17,26],[19.1,10.4,-47.8],[35.8],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-9.3,10.4,23.9],[96.8],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.sitting", + "name": "sitting", + "posture": {"version": 7, "data": [[0,0,0],[0,-90,0],[0,0,-2],[0,0,5],[6,0,62.1],[80.8],[-5.9,-0.1,-8.2],[-1.4,0.7,63.5],[80.1],[6,6,-0.6],[7,-0.6,-5],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-7,0.6,-5],[15],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.sitting-crossed-leg", + "name": "sitting crossed leg", + "posture": {"version": 7, "data": [[0,0,0],[0,-90,0],[0,0,-2],[0,0,5],[-4.3,-15.5,61.6],[80.8],[-5.9,-0.1,-8.2],[0.6,29.2,77],[80.1],[6,6,-0.6],[7,-0.6,-5],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-7,0.6,-5],[15],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.crossed-arm-standing", + "name": "crossed arm standing", + "posture": {"version": 7, "data": [[0,0,0],[-150.9,-84.6,-151.2],[-0.3,-0.1,-2],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[-0.5],[6,6,-0.6],[5.9,-16.3,13.3],[115.4],[72.5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[7.6,3.5,7.8],[161.2],[-77.1,-0.7,0],[61,-79.7,44.3,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.shake-hands", + "name": "shake hands", + "posture": {"version": 7, "data": [[0,0,0],[0,-90,0],[0,0,-2],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[0],[6,6,-0.6],[7,-0.6,-5],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-3,8.1,61.7],[15],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.hand-in-back-pockets", + "name": "hand in back pockets", + "posture": {"version": 7, "data": [[0,0,0],[0,-90,0],[0.1,-0.1,-2],[0,0,5],[6,0,-1.1],[0],[-6,-6,-0.6],[-6,0,0],[0],[6,6,-0.6],[14.2,-6.3,-42.3],[76],[5,-87.8,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[50.2,46.4,-74],[123.5],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.sleeping", + "name": "sleeping", + "posture": {"version": 7, "data": [[0,0,0],[-81.7,-90,0],[0.4,0.4,-2.1],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[0],[6,6,-0.6],[7,-0.6,-5],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-7,0.6,-5],[15],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.kneel-down", + "name": "kneel down", + "posture": {"version": 7, "data": [[0,-3,0],[0,-90,0],[0,0,-2],[0,0,5],[6,0,-3.3],[85.3],[0.5,8,65],[-6,0,0],[82.7],[1.7,-25.5,36.7],[7,-0.6,-5],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-7,0.6,-5],[15],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.kneel-down-praying", + "name": "kneel down praying", + "posture": {"version": 7, "data": [[0,-3,0],[0,-90,0],[0,0,-2],[0,0,5],[6,0,-3.3],[85.3],[0.5,8,65],[-6,0,0],[82.7],[1.7,-25.5,36.7],[-16.7,10.5,84.1],[52.6],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-6.5,9.7,82.5],[61.7],[-43.2,-33.5,6.2],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.arms-wide-open", + "name": "arms wide open", + "posture": {"version": 7, "data": [[0,0,0],[-174.7,-45.5,171],[0,0,16.9],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[0],[6,6,-0.6],[-17.2,82,99.6],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[30.5,-79.6,109.4],[14.2],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.walking-forward", + "name": "walking forward", + "posture": {"version": 7, "data": [[0,0,0],[0,-90,0],[0,0,-2],[0,0,5],[2,5.3,-12.5],[2.3],[-6,-6,-0.6],[0.6,6.7,11.9],[0],[6,6,-0.6],[1.8,-5,35.2],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-21,-3.4,-12.5],[2.2],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.raising-hand", + "name": "raising hand", + "posture": {"version": 7, "data": [[0,0,0],[0,-90,0],[0,0,-2],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[0],[6,6,-0.6],[122.6,66.6,51],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-7,0.6,-5],[15],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.shrugging", + "name": "shrugging", + "posture": {"version": 7, "data": [[0,0,0],[-174.7,-45.5,171],[0,0,16.9],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[0],[6,6,-0.6],[-117.6,77.3,123.8],[97.4],[5,-18.8,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[25.9,-85.9,38.1],[55],[-2.4,13.1,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.thinking-with-right-hand", + "name": "thinking with right hand", + "posture": {"version": 7, "data": [[0,0,0],[0,-90,0],[0,0,-2],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[0],[6,6,-0.6],[7,-0.6,-5],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-4.3,-14.9,90.7],[121.5],[-8.6,17.9,5.1],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.side-sleeping", + "name": "side sleeping", + "posture": {"version": 7, "data": [[0,-5.3,-0.1],[75.1,-0.3,52.2],[15.8,1.8,-2.7],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[7.2],[6,6,-0.6],[7,-0.6,-5],[40.7],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[-12.2,-2,5.9],[73.9],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, + { + "id": "authored.lying-down-hands-wide", + "name": "lying down hands wide", + "posture": {"version": 7, "data": [[0,0,0],[-177.3,-42.5,-89.5],[0,0,-2],[0,0,5],[6,0,0],[0],[-6,-6,-0.6],[-6,0,0],[0],[6,6,-0.6],[-173,84.7,-104.7],[15],[5,0,0],[-90,70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[171.5,-80.1,-110.3],[14.2],[-5,0,0],[90,-70,75,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10],[0,0,10,0,10,0,10]]}, + }, +] + +# User-added poses live here; they win over builtins on id collisions. +_CUSTOM_PATH = Path(__file__).resolve().parents[3] / "skills_builtin" / "shot_poses.json" + + +def list_builtin_poses() -> list[dict[str, Any]]: + """[{id, name, category, source}] — frontmatter only, never full postures.""" + out = [ + {"id": p["id"], "name": p["name"], "category": "authored", "source": "builtin"} + for p in _POSES + ] + custom = _load_custom() + known = {p["id"] for p in out} + for p in custom: + if p.get("id") in known: + for row in out: + if row["id"] == p["id"]: + row["name"] = p.get("name", row["name"]) + row["source"] = "custom" + else: + out.append( + { + "id": p["id"], + "name": p.get("name", p["id"]), + "category": p.get("category", "custom"), + "source": "custom", + } + ) + return out + + +def get_builtin_pose(pose_id: str) -> dict[str, Any] | None: + for p in _load_custom(): + if p.get("id") == pose_id: + posture = p.get("posture") + if isinstance(posture, dict): + return posture + for p in _POSES: + if p["id"] == pose_id: + return dict(p["posture"]) + return None + + +def _load_custom() -> list[dict[str, Any]]: + try: + raw = json.loads(_CUSTOM_PATH.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return [] + return raw if isinstance(raw, list) else [] diff --git a/calliope-backend/src/calliope/queue/manager.py b/calliope-backend/src/calliope/queue/manager.py index ed7556f5..eea7d645 100644 --- a/calliope-backend/src/calliope/queue/manager.py +++ b/calliope-backend/src/calliope/queue/manager.py @@ -33,16 +33,17 @@ class QueueManager: kind: str, workflow_id: int | None = None, scene_id: int | None = None, + clip_id: int | None = None, payload: dict[str, Any] | None = None, ) -> dict[str, Any]: conn = get_db(config.settings.db_path) try: cur = conn.execute( """ - INSERT INTO jobs (project_id, scene_id, kind, workflow_id, status, payload_json) - VALUES (?, ?, ?, ?, 'pending', ?) + INSERT INTO jobs (project_id, scene_id, clip_id, kind, workflow_id, status, payload_json) + VALUES (?, ?, ?, ?, ?, 'pending', ?) """, - (project_id, scene_id, kind, workflow_id, json.dumps(payload or {})), + (project_id, scene_id, clip_id, kind, workflow_id, json.dumps(payload or {})), ) conn.commit() row = conn.execute("SELECT * FROM jobs WHERE id = ?", (cur.lastrowid,)).fetchone() diff --git a/calliope-backend/src/calliope/queue/worker.py b/calliope-backend/src/calliope/queue/worker.py index 2905c3d7..f5a1e672 100644 --- a/calliope-backend/src/calliope/queue/worker.py +++ b/calliope-backend/src/calliope/queue/worker.py @@ -215,47 +215,54 @@ class QueueWorker: workflow: dict[str, Any], input_values: dict[str, Any], ) -> dict[str, Any]: - """Fill the workflow's video input with the previous scene's clip. + """Fill the workflow's video input with the previous clip's file. - Enqueue defers continue-scenes whose earlier clip does not exist yet + Enqueue defers continue-clips whose earlier clip does not exist yet (batch generation); the queue is concurrency-1, so by the time this job - runs the earlier clip has been rendered and attached to its scene. The - path is injected into ``input_values`` like any user-provided value — - ``patch_workflow`` writes it onto the ``(Input:video)`` node and + runs the earlier clip has been rendered and attached to its clip row. + The path is injected into ``input_values`` like any user-provided value + — ``patch_workflow`` writes it onto the ``(Input:video)`` node and ``prepare_media_inputs`` uploads it to ComfyUI before queuing. """ project_id = job["project_id"] - order_index = (payload.get("continue_source") or {}).get("scene_order_index") - if order_index is None: - order_index = payload.get("scene_order_index") or 0 + src = payload.get("continue_source") or {} + scene_pos = src.get("scene_order_index") + clip_pos = src.get("clip_order_index") + if scene_pos is None: + scene_pos = payload.get("scene_order_index") or 0 + if clip_pos is None: + clip_pos = 1 - prev_order: int | None = None + prev: tuple[int, int] | None = None # (scene_pos, clip_pos) of the donor prev_clip: str | None = None conn = get_db(config.settings.db_path) try: row = conn.execute( """ - SELECT order_index, video_path FROM scenes - WHERE project_id = ? AND order_index < ? - ORDER BY order_index DESC LIMIT 1 + SELECT s.order_index AS s_pos, c.order_index AS c_pos, + COALESCE(c.clip_path, s.video_path) AS clip_path + FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.project_id = ? + AND (s.order_index < ? OR (s.order_index = ? AND c.order_index < ?)) + ORDER BY s.order_index DESC, c.order_index DESC LIMIT 1 """, - (project_id, order_index), + (project_id, scene_pos, scene_pos, clip_pos), ).fetchone() if row: - prev_order = row["order_index"] - prev_clip = row["video_path"] + prev = (row["s_pos"], row["c_pos"]) + prev_clip = row["clip_path"] finally: conn.close() - scene_n = order_index - if prev_order is None: + pos_label = f"{scene_pos}.{clip_pos}" + if prev is None: raise RuntimeError( - f"Continue scene {scene_n}: no earlier scene in this project to continue from." + f"Continue clip {pos_label}: no earlier clip in this project to continue from." ) if not prev_clip or not _fs_path(prev_clip).exists(): raise RuntimeError( - f"Continue scene {scene_n}: previous clip (scene {prev_order}) has no video file " - "— generate the earlier clip first." + f"Continue clip {pos_label}: previous clip (scene {prev[0]}.{prev[1]}) has no " + "video file — generate the earlier clip first." ) video_node: str | None = None @@ -265,8 +272,8 @@ class QueueWorker: break if video_node is None: raise RuntimeError( - "Continue scene " - f"{scene_n}: workflow has no (Input:video) node to receive the previous clip." + "Continue clip " + f"{pos_label}: workflow has no (Input:video) node to receive the previous clip." ) input_values[video_node] = prev_clip @@ -275,7 +282,7 @@ class QueueWorker: { "job_id": job["id"], "project_id": project_id, - "message": f"Continuing from scene {prev_order} clip", + "message": f"Continuing from clip {prev[0]}.{prev[1]}", }, ) return input_values @@ -380,6 +387,19 @@ class QueueWorker: ).fetchone() name = row["name"] if row else f"#{payload['item_id']}" return f"{name} · item" + if job.get("clip_id"): + row = conn.execute( + """ + SELECT s.heading, s.order_index AS s_pos, c.order_index AS c_pos + FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.id = ? + """, + (job["clip_id"],), + ).fetchone() + if row: + heading = (row["heading"] or f"Scene {row['s_pos']}").strip() + return f"#{row['s_pos']}.{row['c_pos']} · {heading}" + return f"Clip #{job['clip_id']}" if job.get("scene_id"): row = conn.execute( "SELECT heading, order_index FROM scenes WHERE id = ?", (job["scene_id"],) @@ -427,7 +447,32 @@ class QueueWorker: "UPDATE items SET reference_image_path = ? WHERE id = ?", (primary, item_id), ) - if scene_id and job["kind"] == "video": + if job.get("clip_id") and job["kind"] == "video": + conn.execute( + "UPDATE clips SET clip_path = ? WHERE id = ?", + (primary, job["clip_id"]), + ) + # Mirror onto the scene for legacy readers (canvas scene cards, + # old queries). The clip row stays the source of truth. + conn.execute( + """ + UPDATE scenes SET video_path = ? WHERE id = ( + SELECT scene_id FROM clips WHERE id = ? + ) + """, + (primary, job["clip_id"]), + ) + elif scene_id and job["kind"] == "video": + # Legacy job (pre-clips schema): write the scene's default clip. + conn.execute( + """ + UPDATE clips SET clip_path = ? WHERE id = ( + SELECT c.id FROM clips c WHERE c.scene_id = ? + ORDER BY c.order_index, c.id LIMIT 1 + ) + """, + (primary, scene_id), + ) conn.execute( "UPDATE scenes SET video_path = ? WHERE id = ?", (primary, scene_id), diff --git a/calliope-backend/src/calliope/routers/agent.py b/calliope-backend/src/calliope/routers/agent.py index 28f1c3f0..5094d42b 100644 --- a/calliope-backend/src/calliope/routers/agent.py +++ b/calliope-backend/src/calliope/routers/agent.py @@ -17,6 +17,10 @@ router = APIRouter() class SessionCreate(BaseModel): title: str = "New chat" project_id: int | None = None + # WHERE the session was born: 'chat' (AI Canvas etc., default) or 'scene' + # (Build Scene's per-scene sessions). Scene-origin sessions are excluded + # from the generic session list so they never appear in the AI Canvas rail. + origin: str = "chat" @field_validator("title") @classmethod @@ -25,6 +29,13 @@ class SessionCreate(BaseModel): raise ValueError("Title too long (max 300 characters)") return v + @field_validator("origin") + @classmethod + def _bounded_origin(cls, v: str) -> str: + if v not in ("chat", "scene"): + raise ValueError("origin must be 'chat' or 'scene'") + return v + class SessionPatch(BaseModel): title: str | None = None @@ -59,7 +70,7 @@ class MessageMention(BaseModel): class MessageAttachment(BaseModel): path: str = Field(min_length=1, max_length=2000) name: str = Field(default="", max_length=500) - kind: Literal["image", "video", "audio"] = "image" + kind: Literal["image", "video", "audio", "document"] = "image" class MemoryCreate(BaseModel): @@ -156,18 +167,34 @@ def _rows_to_messages(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: @router.get("/sessions") -async def list_sessions(project_id: int | None = None) -> list[dict[str, Any]]: +async def list_sessions( + project_id: int | None = None, + origin: str | None = None, + include_scene: bool = False, +) -> list[dict[str, Any]]: + """Sessions for the sidebars. Scene-origin sessions (Build Scene's + per-scene chats) are excluded unless asked for by origin or flag — they + are Build Scene's rail entries, not AI Canvas chats.""" conn = get_db(settings.db_path) try: + where: list[str] = [] + params: list[Any] = [] if project_id is not None: - rows = conn.execute( - "SELECT * FROM agent_sessions WHERE project_id = ? ORDER BY updated_at DESC", - (project_id,), - ).fetchall() - else: - rows = conn.execute( - "SELECT * FROM agent_sessions ORDER BY updated_at DESC" - ).fetchall() + where.append("project_id = ?") + params.append(project_id) + if not include_scene: + # origin=scene is compatible with include_scene for clarity; a + # direct origin filter wins (Build Scene asks by origin). + if origin is not None: + where.append("origin = ?") + params.append(origin) + else: + where.append("origin != 'scene'") + sql = "SELECT * FROM agent_sessions" + if where: + sql += " WHERE " + " AND ".join(where) + sql += " ORDER BY updated_at DESC" + rows = conn.execute(sql, params).fetchall() out = [] for r in rows: s = _session_out(conn, r) @@ -188,8 +215,8 @@ async def create_session(payload: SessionCreate) -> dict[str, Any]: ).fetchone(): raise HTTPException(status_code=404, detail="Project not found") cur = conn.execute( - "INSERT INTO agent_sessions (title, project_id) VALUES (?, ?)", - (payload.title, payload.project_id), + "INSERT INTO agent_sessions (title, project_id, origin) VALUES (?, ?, ?)", + (payload.title, payload.project_id, payload.origin), ) conn.commit() row = conn.execute("SELECT * FROM agent_sessions WHERE id = ?", (cur.lastrowid,)).fetchone() @@ -248,7 +275,24 @@ async def patch_session(session_id: int, payload: SessionPatch) -> dict[str, Any raise HTTPException(status_code=404, detail="Session not found") if runner.is_running(session_id): raise HTTPException(status_code=409, detail="Session is running") + if payload.unlink: + conn.execute( + "UPDATE agent_sessions SET project_id = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (session_id,), + ) + elif payload.project_id is not None: + if not conn.execute( + "SELECT id FROM projects WHERE id = ?", (payload.project_id,) + ).fetchone(): + raise HTTPException(status_code=404, detail="Project not found") + conn.execute( + "UPDATE agent_sessions SET project_id = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (payload.project_id, session_id), + ) if payload.title is not None: + # Renaming must never change WHERE the session is listed: origin is + # fixed at creation (the old title-prefix check made a rename break + # Build Scene's rail; origin cannot drift, titles can). conn.execute( "UPDATE agent_sessions SET title = ? WHERE id = ?", (payload.title, session_id), diff --git a/calliope-backend/src/calliope/routers/jobs.py b/calliope-backend/src/calliope/routers/jobs.py index b4f3159d..50722817 100644 --- a/calliope-backend/src/calliope/routers/jobs.py +++ b/calliope-backend/src/calliope/routers/jobs.py @@ -5,7 +5,7 @@ from typing import Any from fastapi import APIRouter, HTTPException, Query -from calliope.agent.video_agent import enqueue_video_jobs, preview_scene_prompt +from calliope.agent.video_agent import enqueue_video_jobs, preview_clip_prompt from calliope.comfyui.client import ComfyUIClient from calliope.config import settings from calliope.db import get_db @@ -65,6 +65,7 @@ async def generate_videos( jobs = await enqueue_video_jobs( project_id, scene_ids=body.scene_ids, + clip_ids=body.clip_ids, workflow_id=body.workflow_id, input_values_override=body.input_values, prompts=body.prompts, @@ -77,9 +78,26 @@ async def generate_videos( @router.post("/projects/{project_id}/preview-prompt") async def preview_prompt(project_id: int, payload: PreviewPromptRequest) -> dict[str, Any]: """HITL review step: the exact prompt a Generate would send, no enqueue.""" + clip_id = payload.clip_id + if clip_id is None and payload.scene_id is None: + raise HTTPException(status_code=400, detail="clip_id or scene_id required") + if clip_id is None: + # Legacy scene addressing resolves to the scene's default (first) clip. + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT id FROM clips WHERE scene_id = ? AND project_id = ? " + "ORDER BY order_index, id LIMIT 1", + (payload.scene_id, project_id), + ).fetchone() + finally: + conn.close() + if not row: + raise HTTPException(status_code=404, detail="Scene has no clips") + clip_id = int(row["id"]) try: - return await preview_scene_prompt( - project_id, payload.scene_id, workflow_id=payload.workflow_id + return await preview_clip_prompt( + project_id, clip_id, workflow_id=payload.workflow_id ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @@ -90,13 +108,13 @@ async def export_film(project_id: int) -> dict[str, Any]: conn = get_db(settings.db_path) try: row = conn.execute( - "SELECT COUNT(*) AS n FROM scenes WHERE project_id = ? AND video_path IS NOT NULL", + "SELECT COUNT(*) AS n FROM clips WHERE project_id = ? AND clip_path IS NOT NULL", (project_id,), ).fetchone() if not row or row["n"] == 0: raise HTTPException( status_code=400, - detail="No scene clips to export — generate videos first", + detail="No clips to export — generate videos first", ) # Supersede leftover pending exports so a re-Export always starts fresh conn.execute( @@ -131,6 +149,7 @@ async def create_job(payload: JobCreate, project_id: int = Query(...)) -> dict[s kind=payload.kind, workflow_id=payload.workflow_id, scene_id=payload.scene_id, + clip_id=payload.clip_id, payload={ "input_values": payload.input_values or {}, "character_id": payload.character_id, diff --git a/calliope-backend/src/calliope/routers/playground.py b/calliope-backend/src/calliope/routers/playground.py index a6c793f0..cbae85f7 100644 --- a/calliope-backend/src/calliope/routers/playground.py +++ b/calliope-backend/src/calliope/routers/playground.py @@ -118,10 +118,16 @@ UPLOAD_KIND_BY_EXT: dict[str, str] = { # .m4a uploads succeed here and land in Comfy's input dir, but some builds # reject it at /prompt validation — prefer wav/mp3 for ref audio. ".m4a": "audio", + # Documents are agent-context material (script uploads projected as text), + # never Comfy job inputs — the agent routers' kind validators accept them. + ".txt": "document", + ".md": "document", + ".docx": "document", } UPLOAD_CHUNK_SIZE = 1024 * 1024 # 1MB UPLOAD_MAX_BYTES = 500 * 1024 * 1024 # 500MB +DOCUMENT_MAX_BYTES = 5 * 1024 * 1024 # 5MB — docs feed the LLM context, not Comfy _UPLOAD_PREFIX_RE = re.compile(r"^[0-9a-f]{8}-") @@ -256,12 +262,14 @@ async def upload_media(file: UploadFile = File(...)) -> dict[str, Any]: dest = uploads / f"{uuid4().hex[:8]}-{_safe_upload_name(original)}" size = 0 + max_bytes = DOCUMENT_MAX_BYTES if kind == "document" else UPLOAD_MAX_BYTES try: with dest.open("wb") as out: while chunk := await file.read(UPLOAD_CHUNK_SIZE): size += len(chunk) - if size > UPLOAD_MAX_BYTES: - raise HTTPException(status_code=413, detail="File too large (max 500MB)") + if size > max_bytes: + limit = "5MB" if kind == "document" else "500MB" + raise HTTPException(status_code=413, detail=f"File too large (max {limit})") out.write(chunk) except Exception: dest.unlink(missing_ok=True) diff --git a/calliope-backend/src/calliope/routers/scenes.py b/calliope-backend/src/calliope/routers/scenes.py index 6bef5320..530e7a1f 100644 --- a/calliope-backend/src/calliope/routers/scenes.py +++ b/calliope-backend/src/calliope/routers/scenes.py @@ -5,15 +5,54 @@ from typing import Any from fastapi import APIRouter, HTTPException +from calliope.agent.coverage_agent import expand_scene_coverage from calliope.agent.script_agent import generate_script from calliope.config import settings -from calliope.db import get_db, row_to_dict -from calliope.models.schemas import GenerateScenesRequest, SceneCreate, SceneReorder, SceneUpdate +from calliope.db import ensure_default_clip, get_db, row_to_dict +from calliope.models.schemas import ( + ClipCreate, + ClipReorder, + ClipUpdate, + ExpandClipsRequest, + GenerateScenesRequest, + SceneCreate, + SceneReorder, + SceneUpdate, +) router = APIRouter() -def _scene_with_chars(conn, scene_row) -> dict[str, Any]: +def _clip_public(clip_row) -> dict[str, Any]: + clip = row_to_dict(clip_row) + raw_settings = clip.pop("video_settings_json", None) + if raw_settings: + try: + clip["video_settings"] = json.loads(raw_settings) + except (json.JSONDecodeError, TypeError): + clip["video_settings"] = None + else: + clip["video_settings"] = None + raw_covered = clip.pop("dialog_lines_covered", None) + if raw_covered: + try: + clip["dialog_lines_covered"] = json.loads(raw_covered) + except (json.JSONDecodeError, TypeError): + clip["dialog_lines_covered"] = None + else: + clip["dialog_lines_covered"] = None + return clip + + +def _clips_for_scene(conn, scene_id: int) -> list[dict[str, Any]]: + rows = conn.execute( + "SELECT * FROM clips WHERE scene_id = ? ORDER BY order_index, id", + (scene_id,), + ).fetchall() + return [_clip_public(r) for r in rows] + + +def _scene_with_chars(conn, scene_row, *, with_clips: bool = True) -> dict[str, Any]: scene = row_to_dict(scene_row) chars = conn.execute( """ @@ -34,9 +73,15 @@ def _scene_with_chars(conn, scene_row) -> dict[str, Any]: scene["video_settings"] = None else: scene["video_settings"] = None + scene["clips"] = _clips_for_scene(conn, scene["id"]) if with_clips else [] return scene +def _ensure_default_clip(conn, scene_id: int, project_id: int) -> None: + """Thin alias — the shared invariant lives in db.ensure_default_clip.""" + ensure_default_clip(conn, scene_id, project_id) + + @router.get("/{project_id}/scenes") async def list_scenes(project_id: int) -> dict[str, Any]: conn = get_db(settings.db_path) @@ -48,8 +93,24 @@ async def list_scenes(project_id: int) -> dict[str, Any]: (project_id,), ).fetchall() scenes = [_scene_with_chars(conn, r) for r in rows] - total = sum((s.get("duration_sec") or 0) for s in scenes) - return {"scenes": scenes, "estimated_duration_sec": total} + clip_durations = conn.execute( + "SELECT scene_id, SUM(COALESCE(duration_sec, 0)) AS total FROM clips " + "WHERE project_id = ? GROUP BY scene_id", + (project_id,), + ).fetchall() + per_scene = {r["scene_id"]: r["total"] or 0 for r in clip_durations} + for s in scenes: + for c in s["clips"]: + c.setdefault("duration_sec", None) + # Estimated runtime = sum over CLIPS (the renderables), not scenes. + total = sum( + (c.get("duration_sec") or 0) for s in scenes for c in s["clips"] + ) + scene_budget_total = sum(per_scene.get(s["id"], 0) for s in scenes) + return { + "scenes": scenes, + "estimated_duration_sec": total or scene_budget_total, + } finally: conn.close() @@ -69,6 +130,49 @@ async def generate_script_endpoint(project_id: int, payload: GenerateScenesReque raise HTTPException(status_code=500, detail=str(exc)) from exc +@router.post("/{project_id}/scenes/{scene_id}/expand-clips") +async def expand_clips_endpoint( + project_id: int, + scene_id: int, + payload: ExpandClipsRequest | None = None, +) -> dict[str, Any]: + body = payload or ExpandClipsRequest() + try: + return await expand_scene_coverage( + project_id, + [scene_id], + guidance=body.guidance, + clip_cap=body.clip_cap, + ) + except ValueError as exc: + detail = str(exc) + code = 404 if "not found" in detail.lower() or "No scenes" in detail else 422 + raise HTTPException(status_code=code, detail=detail) from exc + except Exception as exc: + raise HTTPException(status_code=500, detail=str(exc)) from exc + + +@router.post("/{project_id}/expand-clips") +async def expand_all_clips_endpoint( + project_id: int, + payload: ExpandClipsRequest | None = None, +) -> dict[str, Any]: + body = payload or ExpandClipsRequest() + try: + return await expand_scene_coverage( + project_id, + body.scene_ids, + guidance=body.guidance, + clip_cap=body.clip_cap, + ) + except ValueError as exc: + detail = str(exc) + code = 404 if "not found" in detail.lower() or "No scenes" in detail else 422 + raise HTTPException(status_code=code, detail=detail) from exc + except Exception as exc: + raise HTTPException(status_code=500, detail=str(exc)) from exc + + @router.post("/{project_id}/scenes") async def create_scene(project_id: int, payload: SceneCreate) -> dict[str, Any]: conn = get_db(settings.db_path) @@ -101,6 +205,7 @@ async def create_scene(project_id: int, payload: SceneCreate) -> dict[str, Any]: "INSERT OR IGNORE INTO scene_characters (scene_id, character_id) VALUES (?, ?)", (scene_id, cid), ) + _ensure_default_clip(conn, scene_id, project_id) conn.commit() row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone() return _scene_with_chars(conn, row) @@ -143,6 +248,7 @@ async def update_scene(project_id: int, scene_id: int, payload: SceneUpdate) -> "INSERT OR IGNORE INTO scene_characters (scene_id, character_id) VALUES (?, ?)", (scene_id, cid), ) + _ensure_default_clip(conn, scene_id, project_id) conn.commit() row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone() return _scene_with_chars(conn, row) @@ -184,3 +290,131 @@ async def reorder_scenes(project_id: int, payload: SceneReorder) -> dict[str, An return {"scenes": [_scene_with_chars(conn, r) for r in rows]} finally: conn.close() + + +# ───────────────────────────────────────────────────────────────────────── +# Clips: the shot-level layer under each scene +# ───────────────────────────────────────────────────────────────────────── + + +@router.post("/{project_id}/scenes/{scene_id}/clips") +async def create_clip(project_id: int, scene_id: int, payload: ClipCreate) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + scene = conn.execute( + "SELECT id FROM scenes WHERE id = ? AND project_id = ?", + (scene_id, project_id), + ).fetchone() + if not scene: + raise HTTPException(status_code=404, detail="Scene not found") + covered = json.dumps(payload.dialog_lines_covered) if payload.dialog_lines_covered else None + next_index = conn.execute( + "SELECT COALESCE(MAX(order_index), 0) + 1 AS n FROM clips WHERE scene_id = ?", + (scene_id,), + ).fetchone()["n"] + cur = conn.execute( + """ + INSERT INTO clips (scene_id, project_id, order_index, description, shot_size, + dialog_lines_covered, duration_sec, workflow_id, + video_settings_json, chain_from_prev) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + scene_id, + project_id, + payload.order_index or next_index, + payload.description, + payload.shot_size, + covered, + payload.duration_sec, + payload.workflow_id, + json.dumps(payload.video_settings) if payload.video_settings else None, + 1 if payload.chain_from_prev else 0, + ), + ) + conn.commit() + row = conn.execute("SELECT * FROM clips WHERE id = ?", (cur.lastrowid,)).fetchone() + return _clip_public(row) + finally: + conn.close() + + +@router.patch("/{project_id}/clips/{clip_id}") +async def update_clip(project_id: int, clip_id: int, payload: ClipUpdate) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + existing = conn.execute( + "SELECT id FROM clips WHERE id = ? AND project_id = ?", + (clip_id, project_id), + ).fetchone() + if not existing: + raise HTTPException(status_code=404, detail="Clip not found") + data = payload.model_dump(exclude_unset=True) + video_settings = data.pop("video_settings", None) + covered = data.pop("dialog_lines_covered", None) + data = {k: v for k, v in data.items() if v is not None} + if covered is not None: + data["dialog_lines_covered"] = json.dumps(covered) if covered else None + if video_settings is not None: + data["video_settings_json"] = json.dumps(video_settings) + fields = [f"{k} = :{k}" for k in data] + params: dict[str, Any] = {"id": clip_id, **data} + if fields: + conn.execute( + f"UPDATE clips SET {', '.join(fields)} WHERE id = :id", params + ) + conn.commit() + row = conn.execute("SELECT * FROM clips WHERE id = ?", (clip_id,)).fetchone() + return _clip_public(row) + finally: + conn.close() + + +@router.delete("/{project_id}/clips/{clip_id}") +async def delete_clip(project_id: int, clip_id: int) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT scene_id FROM clips WHERE id = ? AND project_id = ?", + (clip_id, project_id), + ).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Clip not found") + count = conn.execute( + "SELECT COUNT(*) AS n FROM clips WHERE scene_id = ?", + (row["scene_id"],), + ).fetchone()["n"] + if count <= 1: + raise HTTPException( + status_code=422, + detail="A scene needs at least one clip — delete the scene instead", + ) + conn.execute( + "DELETE FROM clips WHERE id = ? AND project_id = ?", + (clip_id, project_id), + ) + conn.commit() + return {"ok": True} + finally: + conn.close() + + +@router.post("/{project_id}/scenes/{scene_id}/clips/reorder") +async def reorder_clips(project_id: int, scene_id: int, payload: ClipReorder) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + scene = conn.execute( + "SELECT id FROM scenes WHERE id = ? AND project_id = ?", + (scene_id, project_id), + ).fetchone() + if not scene: + raise HTTPException(status_code=404, detail="Scene not found") + for index, clip_id in enumerate(payload.clip_ids, start=1): + conn.execute( + "UPDATE clips SET order_index = ? WHERE id = ? AND scene_id = ?", + (index, clip_id, scene_id), + ) + conn.commit() + return {"clips": _clips_for_scene(conn, scene_id)} + finally: + conn.close() diff --git a/calliope-backend/src/calliope/routers/shots.py b/calliope-backend/src/calliope/routers/shots.py new file mode 100644 index 00000000..c11173a2 --- /dev/null +++ b/calliope-backend/src/calliope/routers/shots.py @@ -0,0 +1,434 @@ +"""Build Scene — shot composition + capture storage. + +One composition per agent session (get-or-create, keyed by the UNIQUE +agent_session_id). `scene_json` is the single source of truth for the 3D +blockout (objects, transforms, posture v7, shot params); the frontend and the +agent's shot_builder tools both mutate it through this router. Captures are +PNG renders posted as data URLs and saved under /shots/ (served by +/api/file and rebased on folder moves like every other asset path). +""" +from __future__ import annotations + +import base64 +import binascii +import json +import uuid +from datetime import datetime, timezone +from typing import Any + +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel, field_validator + +from calliope.config import settings +from calliope.db import get_db, row_to_dict +from calliope.events.bus import event_bus + +router = APIRouter() + +OBJECT_TYPES = { + "male", + "female", + "child", + "cube", + "plane", + "cylinder", + "sphere", + "capsule", + "cone", + "torus", + "camera", +} + +_MAX_SCENE_JSON_CHARS = 4_000_000 +_MAX_IMAGE_BYTES = 20_000_000 +_MAX_VIDEO_BYTES = 64_000_000 + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +class ShotCreate(BaseModel): + agent_session_id: int | None = None + title: str | None = None + scene_json: str | None = None + + @field_validator("title") + @classmethod + def _bound_title(cls, v: str | None) -> str | None: + if v is not None and len(v) > 300: + raise ValueError("Title too long (max 300 characters)") + return v + + +class ShotPatch(BaseModel): + title: str | None = None + scene_json: str | None = None + capture_request_json: str | None = None + + @field_validator("title") + @classmethod + def _bound_title(cls, v: str | None) -> str | None: + if v is not None and len(v) > 300: + raise ValueError("Title too long (max 300 characters)") + return v + + +class CaptureCreate(BaseModel): + data_url: str + label: str | None = None + meta_json: str | None = None + + @field_validator("label") + @classmethod + def _bound_label(cls, v: str | None) -> str | None: + if v is not None and len(v) > 200: + raise ValueError("Label too long (max 200 characters)") + return v + + +def validate_scene_json(raw: str) -> dict[str, Any]: + """Light structural validation — the client owns deep validation (posture + shapes, value ranges) via the ported posture module.""" + if len(raw) > _MAX_SCENE_JSON_CHARS: + raise HTTPException(status_code=413, detail="scene_json too large") + try: + data = json.loads(raw or "{}") + except json.JSONDecodeError as exc: + raise HTTPException(status_code=422, detail=f"scene_json is not valid JSON: {exc}") + if not isinstance(data, dict): + raise HTTPException(status_code=422, detail="scene_json must be a JSON object") + objects = data.get("objects", []) + if not isinstance(objects, list): + raise HTTPException(status_code=422, detail="scene_json.objects must be a list") + for idx, obj in enumerate(objects): + if not isinstance(obj, dict): + raise HTTPException(status_code=422, detail=f"objects[{idx}] must be an object") + if not obj.get("id") or not isinstance(obj.get("id"), str): + raise HTTPException(status_code=422, detail=f"objects[{idx}].id must be a string") + if obj.get("type") not in OBJECT_TYPES: + raise HTTPException( + status_code=422, + detail=f"objects[{idx}].type '{obj.get('type')}' is not a known object type", + ) + return data + + +def _composition_out(row: Any, *, include_scene: bool = False) -> dict[str, Any]: + out = { + "id": row["id"], + "agent_session_id": row["agent_session_id"], + "title": row["title"], + "capture_request_json": row["capture_request_json"], + "created_at": row["created_at"], + "updated_at": row["updated_at"], + } + if include_scene: + try: + out["scene"] = json.loads(row["scene_json"] or "{}") + except json.JSONDecodeError: + out["scene"] = {} + else: + out["has_scene"] = bool(row["scene_json"] and row["scene_json"] != "{}") + return out + + +def _capture_out(row: Any) -> dict[str, Any]: + return { + "id": row["id"], + "composition_id": row["composition_id"], + "kind": row["kind"], + "label": row["label"], + "file_path": row["file_path"], + "created_at": row["created_at"], + } + + +def get_or_create_for_session( + conn: Any, session_id: int, *, title: str | None = None +) -> dict[str, Any]: + """Shared with the shot_builder plugin: one composition per session.""" + row = conn.execute( + "SELECT * FROM shot_composition WHERE agent_session_id = ?", + (session_id,), + ).fetchone() + if row: + return row_to_dict(row) + effective_title = (title or "").strip() or "Untitled composition" + cur = conn.execute( + """ + INSERT INTO shot_composition (agent_session_id, title, scene_json, created_at, updated_at) + VALUES (?, ?, '{}', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + """, + (session_id, effective_title[:300]), + ) + conn.commit() + row = conn.execute( + "SELECT * FROM shot_composition WHERE id = ?", (cur.lastrowid,) + ).fetchone() + return row_to_dict(row) + + +@router.get("") +async def list_shots() -> list[dict[str, Any]]: + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT * FROM shot_composition ORDER BY updated_at DESC, id DESC" + ).fetchall() + return [_composition_out(r) for r in rows] + finally: + conn.close() + + +@router.post("") +async def create_shot(payload: ShotCreate) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + if payload.agent_session_id is not None: + if not conn.execute( + "SELECT id FROM agent_sessions WHERE id = ?", (payload.agent_session_id,) + ).fetchone(): + raise HTTPException(status_code=404, detail="Agent session not found") + row = get_or_create_for_session( + conn, payload.agent_session_id, title=payload.title + ) + created = row["created_at"] == row["updated_at"] + else: + title = (payload.title or "").strip() or "Untitled composition" + scene = "{}" + if payload.scene_json is not None: + validate_scene_json(payload.scene_json) + scene = payload.scene_json + cur = conn.execute( + """ + INSERT INTO shot_composition (agent_session_id, title, scene_json, created_at, updated_at) + VALUES (NULL, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + """, + (title[:300], scene), + ) + conn.commit() + row = conn.execute( + "SELECT * FROM shot_composition WHERE id = ?", (cur.lastrowid,) + ).fetchone() + created = True + out = _composition_out(row, include_scene=True) + out["created"] = created + finally: + conn.close() + await event_bus.publish( + "shot.updated", + {"shot_id": out["id"], "reason": "created"}, + ) + return out + + +@router.get("/by-session/{session_id}") +async def get_or_create_by_session(session_id: int) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + if not conn.execute( + "SELECT id FROM agent_sessions WHERE id = ?", (session_id,) + ).fetchone(): + raise HTTPException(status_code=404, detail="Agent session not found") + row = get_or_create_for_session(conn, session_id) + out = _composition_out(row, include_scene=True) + out["created"] = row["created_at"] == row["updated_at"] and not row["scene_json"] + finally: + conn.close() + if out.pop("created", False): + await event_bus.publish("shot.updated", {"shot_id": out["id"], "reason": "created"}) + return out + + +@router.get("/{shot_id}") +async def get_shot(shot_id: int) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT * FROM shot_composition WHERE id = ?", (shot_id,) + ).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Composition not found") + return _composition_out(row, include_scene=True) + finally: + conn.close() + + +@router.patch("/{shot_id}") +async def patch_shot(shot_id: int, payload: ShotPatch) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT * FROM shot_composition WHERE id = ?", (shot_id,) + ).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Composition not found") + sets: list[str] = ["updated_at = CURRENT_TIMESTAMP"] + params: list[Any] = [] + if payload.title is not None: + sets.append("title = ?") + params.append(payload.title.strip()[:300] or "Untitled composition") + if payload.scene_json is not None: + validate_scene_json(payload.scene_json) + sets.append("scene_json = ?") + params.append(payload.scene_json) + if payload.capture_request_json is not None: + if payload.capture_request_json == "": + sets.append("capture_request_json = NULL") + else: + try: + json.loads(payload.capture_request_json) + except json.JSONDecodeError as exc: + raise HTTPException( + status_code=422, detail=f"capture_request_json invalid: {exc}" + ) + sets.append("capture_request_json = ?") + params.append(payload.capture_request_json) + params.append(shot_id) + conn.execute( + f"UPDATE shot_composition SET {', '.join(sets)} WHERE id = ?", params + ) + conn.commit() + row = conn.execute( + "SELECT * FROM shot_composition WHERE id = ?", (shot_id,) + ).fetchone() + out = _composition_out(row, include_scene=True) + finally: + conn.close() + await event_bus.publish( + "shot.updated", + {"shot_id": shot_id, "reason": "patched"}, + ) + return out + + +@router.delete("/{shot_id}") +async def delete_shot(shot_id: int) -> dict[str, bool]: + conn = get_db(settings.db_path) + try: + if not conn.execute( + "SELECT id FROM shot_composition WHERE id = ?", (shot_id,) + ).fetchone(): + raise HTTPException(status_code=404, detail="Composition not found") + conn.execute("DELETE FROM shot_composition WHERE id = ?", (shot_id,)) + conn.commit() + finally: + conn.close() + await event_bus.publish("shot.updated", {"shot_id": shot_id, "reason": "deleted"}) + return {"ok": True} + + +# ---- captures -------------------------------------------------------------- + + +@router.get("/{shot_id}/captures") +async def list_captures(shot_id: int) -> list[dict[str, Any]]: + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT * FROM shot_capture WHERE composition_id = ? ORDER BY id DESC", + (shot_id,), + ).fetchall() + return [_capture_out(r) for r in rows] + finally: + conn.close() + + +def _decode_data_url(data_url: str) -> tuple[bytes, str, str]: + """Returns (raw bytes, extension, capture kind).""" + if not data_url.startswith("data:"): + raise HTTPException(status_code=422, detail="data_url must be an image or video data URL") + header, _, b64 = data_url.partition(",") + if not b64: + raise HTTPException(status_code=422, detail="data_url missing base64 payload") + mime = header[len("data:") :].split(";", 1)[0].strip().lower() + if mime.startswith("image/"): + kind = "image" + ext = "png" + marker = mime[len("image/") :] + if marker in {"png", "jpeg", "jpg", "webp", "gif"}: + ext = "jpeg" if marker == "jpg" else marker + max_bytes = _MAX_IMAGE_BYTES + elif mime.startswith("video/"): + kind = "video" + marker = mime[len("video/") :] + ext = {"mp4": "mp4", "webm": "webm", "quicktime": "mov"}.get(marker, "mp4") + max_bytes = _MAX_VIDEO_BYTES + else: + raise HTTPException( + status_code=422, detail="data_url must be an image/* or video/* data URL" + ) + try: + raw = base64.b64decode(b64, validate=True) + except (binascii.Error, ValueError): + raise HTTPException(status_code=422, detail="data_url payload is not valid base64") + if not raw or len(raw) > max_bytes: + raise HTTPException( + status_code=413, + detail=f"capture must be 1 byte..{max_bytes} bytes", + ) + return raw, ext, kind + + +@router.post("/{shot_id}/captures") +async def create_capture(shot_id: int, payload: CaptureCreate) -> dict[str, Any]: + raw, ext, kind = _decode_data_url(payload.data_url) + conn = get_db(settings.db_path) + try: + if not conn.execute( + "SELECT id FROM shot_composition WHERE id = ?", (shot_id,) + ).fetchone(): + raise HTTPException(status_code=404, detail="Composition not found") + shots_dir = settings.assets_dir / "shots" / str(shot_id) + shots_dir.mkdir(parents=True, exist_ok=True) + file_path = shots_dir / f"{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}.{ext}" + file_path.write_bytes(raw) + cur = conn.execute( + """ + INSERT INTO shot_capture (composition_id, kind, label, file_path, meta_json, created_at) + VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP) + """, + (shot_id, kind, payload.label, str(file_path), payload.meta_json), + ) + # The capture request has been fulfilled — clear it so the next + # request_capture polls for a fresh one. + conn.execute( + "UPDATE shot_composition SET capture_request_json = NULL, " + "updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (shot_id,), + ) + conn.commit() + row = conn.execute( + "SELECT * FROM shot_capture WHERE id = ?", (cur.lastrowid,) + ).fetchone() + out = _capture_out(row) + finally: + conn.close() + await event_bus.publish( + "shot.capture.saved", + { + "shot_id": shot_id, + "capture_id": out["id"], + "file_path": out["file_path"], + "label": out["label"], + }, + ) + return out + + +@router.delete("/{shot_id}/captures/{capture_id}") +async def delete_capture(shot_id: int, capture_id: int) -> dict[str, bool]: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT id, file_path FROM shot_capture WHERE id = ? AND composition_id = ?", + (capture_id, shot_id), + ).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Capture not found") + conn.execute("DELETE FROM shot_capture WHERE id = ?", (capture_id,)) + conn.commit() + finally: + conn.close() + return {"ok": True} diff --git a/calliope-backend/src/calliope/routers/story.py b/calliope-backend/src/calliope/routers/story.py index bb412db7..a78a9fe7 100644 --- a/calliope-backend/src/calliope/routers/story.py +++ b/calliope-backend/src/calliope/routers/story.py @@ -86,12 +86,18 @@ async def _request_beats_chunk( return beats -async def _draft_story_chunked( +async def _iter_story_chunks( project_id: int, project: dict[str, Any], required_beats: int -) -> dict[str, Any]: - """Beat list in chunks of STORY_CHUNK (brief + first beats in call 1, - continuations after). Boards that fit one chunk behave exactly like the - old single call, including the corrective retry.""" +): + """Yield one chunk dict per LLM call as it completes. + + The first yield carries the brief (title/logline/cast/locations/items + + first beats); continuation yields carry only their beats. The caller + persists + commits per yield, so a crash mid-draft keeps every chunk + already paid for instead of losing the whole story. Boards that fit one + chunk behave exactly like the old single call, including the corrective + retry. + """ system = STORY_GENERATION_SYSTEM if required_beats <= STORY_CHUNK: messages = build_story_messages( @@ -133,8 +139,15 @@ async def _draft_story_chunked( ] result = await generate_structured(repair, temperature=0.4) beats_out = result.get("beats") or [] - result = {**result, "beats": beats_out} - return result + yield { + "title": result.get("title"), + "logline": result.get("logline"), + "characters": result.get("characters") or [], + "locations": result.get("locations") or [], + "items": result.get("items") or [], + "beats": beats_out, + } + return # 1) Brief + first chunk first_n = min(STORY_CHUNK, required_beats) @@ -175,11 +188,21 @@ async def _draft_story_chunked( ] ) - # 2) Continuation chunks - written = [dict(b) for b in beats_out[:first_n]] - for offset, b in enumerate(written): + # 2) Continuation chunks — each yields as soon as its LLM call lands, so + # the caller can commit the chunk durably before the next call starts. + first = [dict(b) for b in beats_out[:first_n]] + for offset, b in enumerate(first): b["order_index"] = offset + 1 - start = len(written) + 1 + yield { + "title": title, + "logline": logline, + "characters": brief.get("characters") or [], + "locations": brief.get("locations") or [], + "items": brief.get("items") or [], + "beats": first, + } + written_tail = list(first) + start = len(first) + 1 total_calls = (required_beats + STORY_CHUNK - 1) // STORY_CHUNK call_no = 2 while start <= required_beats: @@ -200,7 +223,7 @@ async def _draft_story_chunked( total_beats=required_beats, chunk_start=start, chunk_beats=want, - previous_beats=written, + previous_beats=written_tail, cast_summary=cast_summary, ) chunk = await _request_beats_chunk(system, user, want=want) @@ -209,13 +232,19 @@ async def _draft_story_chunked( accepted = chunk[:want] for offset, b in enumerate(accepted): b["order_index"] = start + offset - written.append(b) + written_tail = list(written_tail) + accepted # continuity: last 6 beats # Advance by what was actually accepted, so a short chunk never # leaves a hole in the 1..N order_index sequence. start += len(accepted) call_no += 1 - - return {**brief, "title": title, "logline": logline, "beats": written} + yield { + "title": None, + "logline": None, + "characters": [], + "locations": [], + "items": [], + "beats": accepted, + } @router.post("/{project_id}/generate-story") @@ -236,115 +265,131 @@ async def generate_story(project_id: int, replace: bool = True) -> dict[str, Any }, ) - result = await _draft_story_chunked(project_id, project, required_beats) - beats_out = result.get("beats") or [] - if len(beats_out) < required_beats: + # Durable chunked draft: each yielded chunk (brief first, then beat + # continuations) is inserted and committed BEFORE the next LLM call + # starts — a crash mid-draft keeps every chunk already written. + title: str | None = None + logline: str | None = None + written = 0 + replace_started = False + + async for chunk in _iter_story_chunks(project_id, project, required_beats): + if title is None: + title = chunk.get("title") + logline = chunk.get("logline") + conn.execute( + "UPDATE projects SET title = ?, idea = COALESCE(?, idea), " + "status = 'in_progress', updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (title or project["title"], logline, project_id), + ) + if replace and not replace_started: + # Clear the old board only once the first chunk is in hand — + # a failed first call leaves the old story intact. + conn.execute("DELETE FROM story_beats WHERE project_id = ?", (project_id,)) + conn.execute("DELETE FROM characters WHERE project_id = ?", (project_id,)) + conn.execute("DELETE FROM locations WHERE project_id = ?", (project_id,)) + conn.execute("DELETE FROM items WHERE project_id = ?", (project_id,)) + # scenes.location_id has no FK — the mass delete above would leave + # every scene pointing at a dead location row. + conn.execute( + "UPDATE scenes SET location_id = NULL WHERE project_id = ?", (project_id,) + ) + replace_started = True + + for seed_kind, rows in ( + ("characters", chunk.get("characters") or []), + ("locations", chunk.get("locations") or []), + ("items", chunk.get("items") or []), + ): + for entity in rows: + if seed_kind == "characters": + appearance = entity.get("appearance", "") or "" + row_seed = { + "name": entity.get("name", ""), + "role": entity.get("role", ""), + "age": entity.get("age", ""), + "appearance": appearance, + "personality": entity.get("personality", ""), + } + # Seed with the published sheet template so Assets shows a real prompt, not a hidden blob. + conn.execute( + """ + INSERT INTO characters + (project_id, name, role, age, appearance, personality, consistency_prompt) + VALUES (:project_id, :name, :role, :age, :appearance, :personality, :consistency_prompt) + """, + { + "project_id": project_id, + **row_seed, + "consistency_prompt": character_sheet_prompt(row_seed), + }, + ) + elif seed_kind == "locations": + description = entity.get("description", "") or "" + loc_seed = {"name": entity.get("name", ""), "description": description} + conn.execute( + """ + INSERT INTO locations (project_id, name, description, consistency_prompt) + VALUES (:project_id, :name, :description, :consistency_prompt) + """, + { + "project_id": project_id, + **loc_seed, + "consistency_prompt": location_reference_prompt(loc_seed), + }, + ) + else: + description = entity.get("description", "") or "" + item_seed = {"name": entity.get("name", ""), "description": description} + conn.execute( + """ + INSERT INTO items (project_id, name, description, consistency_prompt) + VALUES (:project_id, :name, :description, :consistency_prompt) + """, + { + "project_id": project_id, + **item_seed, + "consistency_prompt": item_reference_prompt(item_seed), + }, + ) + + for beat in chunk.get("beats") or []: + conn.execute( + """ + INSERT INTO story_beats (project_id, order_index, title, description) + VALUES (:project_id, :order_index, :title, :description) + """, + { + "project_id": project_id, + "order_index": beat.get("order_index", 0), + "title": beat.get("title", ""), + "description": beat.get("description", ""), + }, + ) + written += 1 + + # Commit per chunk — the whole point of the generator split. + conn.commit() + if chunk.get("beats"): + await event_bus.publish( + "agent.thinking", + { + "project_id": project_id, + "message": f"Saved {written}/{required_beats} beats…", + }, + ) + + if written < required_beats: raise HTTPException( status_code=502, detail=( - f"Story draft returned {len(beats_out)} beats but target " + f"Story draft returned {written} beats but target " f"'{project.get('target_duration')}' requires {required_beats}. " "Try Draft Storyline again, or check the LLM follows JSON instructions." ), ) - title = result.get("title") or project["title"] - logline = result.get("logline") - conn.execute( - "UPDATE projects SET title = ?, idea = COALESCE(?, idea), status = 'in_progress', " - "updated_at = CURRENT_TIMESTAMP WHERE id = ?", - (title, logline, project_id), - ) - - if replace: - conn.execute("DELETE FROM story_beats WHERE project_id = ?", (project_id,)) - conn.execute("DELETE FROM characters WHERE project_id = ?", (project_id,)) - conn.execute("DELETE FROM locations WHERE project_id = ?", (project_id,)) - conn.execute("DELETE FROM items WHERE project_id = ?", (project_id,)) - # scenes.location_id has no FK — the mass delete above would leave - # every scene pointing at a dead location row. - conn.execute( - "UPDATE scenes SET location_id = NULL WHERE project_id = ?", (project_id,) - ) - - for beat in result.get("beats", []): - conn.execute( - """ - INSERT INTO story_beats (project_id, order_index, title, description) - VALUES (:project_id, :order_index, :title, :description) - """, - { - "project_id": project_id, - "order_index": beat.get("order_index", 0), - "title": beat.get("title", ""), - "description": beat.get("description", ""), - }, - ) - - for character in result.get("characters", []): - appearance = character.get("appearance", "") or "" - row_seed = { - "name": character.get("name", ""), - "role": character.get("role", ""), - "age": character.get("age", ""), - "appearance": appearance, - "personality": character.get("personality", ""), - } - # Seed with the published sheet template so Assets shows a real prompt, not a hidden blob. - sheet_prompt = character_sheet_prompt(row_seed) - conn.execute( - """ - INSERT INTO characters - (project_id, name, role, age, appearance, personality, consistency_prompt) - VALUES (:project_id, :name, :role, :age, :appearance, :personality, :consistency_prompt) - """, - { - "project_id": project_id, - **row_seed, - "consistency_prompt": sheet_prompt, - }, - ) - - for location in result.get("locations", []): - description = location.get("description", "") or "" - loc_seed = { - "name": location.get("name", ""), - "description": description, - } - env_prompt = location_reference_prompt(loc_seed) - conn.execute( - """ - INSERT INTO locations (project_id, name, description, consistency_prompt) - VALUES (:project_id, :name, :description, :consistency_prompt) - """, - { - "project_id": project_id, - **loc_seed, - "consistency_prompt": env_prompt, - }, - ) - - for item in result.get("items", []): - description = item.get("description", "") or "" - item_seed = { - "name": item.get("name", ""), - "description": description, - } - item_prompt = item_reference_prompt(item_seed) - conn.execute( - """ - INSERT INTO items (project_id, name, description, consistency_prompt) - VALUES (:project_id, :name, :description, :consistency_prompt) - """, - { - "project_id": project_id, - **item_seed, - "consistency_prompt": item_prompt, - }, - ) - - conn.commit() - beat_n = len(result.get("beats", [])) + beat_n = written await event_bus.publish( "story.ready", { @@ -352,7 +397,7 @@ async def generate_story(project_id: int, replace: bool = True) -> dict[str, Any "message": f"Story drafted — {beat_n} beats", }, ) - return {"ok": True, "project_id": project_id, "generated": result} + return {"ok": True, "project_id": project_id, "generated": {"beats": beat_n}} except HTTPException: raise except Exception as exc: diff --git a/calliope-backend/tests/test_agent_event_log.py b/calliope-backend/tests/test_agent_event_log.py index 385cda3f..a51c7475 100644 --- a/calliope-backend/tests/test_agent_event_log.py +++ b/calliope-backend/tests/test_agent_event_log.py @@ -361,9 +361,9 @@ def test_prompt_sections_ordered_and_skippable(client): # persona(10) < mode(20) < extra(25) < workspace(30) < discipline(40) assert text.index("production agent") < text.index("SANDBOX") assert text.index("SANDBOX") < text.index("EXTRA-SECTION") - assert text.index("EXTRA-SECTION") < text.index("Tool discipline") + assert text.index("EXTRA-SECTION") < text.index("ReAct loop") assert "Tagged workflows" in text - assert text.index("Tagged workflows") < text.index("Tool discipline") + assert text.index("Tagged workflows") < text.index("ReAct loop") def test_prompt_sections_tie_order_keeps_registration_order(client): @@ -397,7 +397,7 @@ def test_prompt_assemble_survives_broken_section(client): service.register("broken", 35, broken) text = asyncio.run(service.assemble(ToolContext(session_id=1))) assert "production agent" in text - assert "Tool discipline" in text + assert "ReAct loop" in text assert "exploded" not in text @@ -415,7 +415,7 @@ def test_hardening_section_reflects_settings(client): settings.agent_hardening_prompt = "CUSTOM-RULE: stay in scope" text = asyncio.run(service.assemble(ctx)) assert "CUSTOM-RULE: stay in scope" in text - assert text.index("Tool discipline") < text.index("CUSTOM-RULE: stay in scope") + assert text.index("ReAct loop") < text.index("CUSTOM-RULE: stay in scope") # Blank disables the hardening block. settings.agent_hardening_prompt = " " @@ -539,3 +539,114 @@ def test_format_calliope_context_empty(): ) assert "workflow_id=1" in two assert "workflow_id=2" not in two + + +def test_project_user_content_image_attachment_becomes_image_part(tmp_path, monkeypatch): + """User-attached images project as OpenAI image_url parts (visible to + vision models); video/audio attachments stay text-only path lines.""" + import base64 + + from calliope.config import settings as cfg + + img = tmp_path / "ref.png" + payload = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" + ) + img.write_bytes(payload) + monkeypatch.setattr(cfg, "assets_dir", tmp_path) + + content = session_log.project_user_content( + "match this pose", + attachments=[{"path": str(img), "name": "ref.png", "kind": "image"}], + ) + assert isinstance(content, list) + assert content[0]["type"] == "text" + assert "match this pose" in content[0]["text"] + assert "attached:" in content[0]["text"] + assert content[1]["type"] == "image_url" + assert content[1]["image_url"]["url"].startswith("data:image/png;base64,") + + # Non-image attachments never become parts. + text_only = session_log.project_user_content( + "hello", + attachments=[{"path": str(img), "name": "ref.png", "kind": "video"}], + ) + assert isinstance(text_only, str) + + # A path outside assets_dir degrades to text (no part, no crash). + outside = tmp_path.parent / "elsewhere.png" + outside.write_bytes(payload) + degraded = session_log.project_user_content( + "hi", + attachments=[{"path": str(outside), "name": "elsewhere.png", "kind": "image"}], + ) + assert isinstance(degraded, str) + + +def test_project_user_content_document_attachment_becomes_script_text(tmp_path, monkeypatch): + """.txt/.md/.docx attachments are read and injected between delimiters — + the script-upload path. Degradation mirrors image/video handling.""" + import zipfile + + from calliope.config import settings as cfg + + monkeypatch.setattr(cfg, "assets_dir", tmp_path) + + script = tmp_path / "my-script.txt" + script.write_text("INT. ROOFTOP - NIGHT\nMin-Ji stares at the skyline.", encoding="utf-8") + + content = session_log.project_user_content( + "make this into a story", + attachments=[{"path": str(script), "name": "my-script.txt", "kind": "document"}], + ) + assert isinstance(content, list) + text = content[0]["text"] + assert "[Script document: my-script.txt]" in text + assert "Min-Ji stares at the skyline." in text + assert "[/Script document]" in text + assert 'script document: "my-script.txt"' in text # appendix line + + # Markdown reads the same way. + md = tmp_path / "notes.md" + md.write_text("# Beat one", encoding="utf-8") + md_content = session_log.project_user_content( + "use this", + attachments=[{"path": str(md), "name": "notes.md", "kind": "document"}], + ) + assert isinstance(md_content, list) and "# Beat one" in md_content[0]["text"] + + # docx: minimal word/document.xml inside a zip. + docx_path = tmp_path / "script.docx" + with zipfile.ZipFile(docx_path, "w") as zf: + zf.writestr( + "word/document.xml", + '' + "Scene one line." + "Scene two line.", + ) + docx_content = session_log.project_user_content( + "from this doc", + attachments=[{"path": str(docx_path), "name": "script.docx", "kind": "document"}], + ) + assert isinstance(docx_content, list) + assert "Scene one line." in docx_content[0]["text"] + assert "Scene two line." in docx_content[0]["text"] + + # A path outside assets_dir degrades to the plain text branch. + outside = tmp_path.parent / "elsewhere.txt" + outside.write_text("secret", encoding="utf-8") + degraded = session_log.project_user_content( + "hi", + attachments=[{"path": str(outside), "name": "elsewhere.txt", "kind": "document"}], + ) + assert isinstance(degraded, str) + + # Oversized documents truncate with an explicit note. + big = tmp_path / "big.txt" + big.write_text("x" * 70_000, encoding="utf-8") + big_content = session_log.project_user_content( + "hi", + attachments=[{"path": str(big), "name": "big.txt", "kind": "document"}], + ) + assert isinstance(big_content, list) + assert "[Document truncated:" in big_content[0]["text"] diff --git a/calliope-backend/tests/test_agent_harness.py b/calliope-backend/tests/test_agent_harness.py index c96386fc..1e48027c 100644 --- a/calliope-backend/tests/test_agent_harness.py +++ b/calliope-backend/tests/test_agent_harness.py @@ -36,11 +36,13 @@ def test_tool_registry_schemas_valid(): assert all(r in t.parameters["properties"] for r in required), name -def test_openai_payload_scoping(): +def test_openai_payload_scoping(client): """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). + Needs the client fixture: visibility checks read the session log, which + requires a live temp DB (no leftover-settings flake). """ blind = ToolContext(session_id=9_999_001, project_id=None) linked = ToolContext(session_id=9_999_001, project_id=99) diff --git a/calliope-backend/tests/test_agent_skills.py b/calliope-backend/tests/test_agent_skills.py index 96ed2f4e..ebab8438 100644 --- a/calliope-backend/tests/test_agent_skills.py +++ b/calliope-backend/tests/test_agent_skills.py @@ -29,6 +29,8 @@ def test_builtin_skills_seeded(client): assert (root / "h3-video-prompt-enhancer" / "references" / "ref2va-format.md").is_file() assert (root / "scene-to-video" / "SKILL.md").is_file() assert (root / "character-consistency" / "SKILL.md").is_file() + assert (root / "shot-composer-blockout" / "SKILL.md").is_file() + assert (root / "shot-composer-blockout" / "references" / "motion-recipes.md").is_file() def test_seeding_never_overwrites_user_edits(client): diff --git a/calliope-backend/tests/test_clips.py b/calliope-backend/tests/test_clips.py new file mode 100644 index 00000000..2a61b54f --- /dev/null +++ b/calliope-backend/tests/test_clips.py @@ -0,0 +1,612 @@ +"""Scene → Clips: schema backfill, default-clip invariant, CRUD, coverage contract. + +These tests pin the 1 scene : N clips model — the renderable unit is a CLIP, +never the script scene itself. Real DB never touched (client fixture is +temp-scoped per the clean-test-artifacts rule). +""" +from __future__ import annotations + +import asyncio +import json + +import pytest + +from calliope.agent.coverage_agent import _normalize_clips, expand_scene_coverage +from calliope.agent.video_agent import ( + _clip_prompt_hash, + _fetch_clips, + enqueue_video_jobs, +) +from calliope.config import settings +from calliope.db import get_db + + +# ── helpers ───────────────────────────────────────────────────────────── + + +def _mk_project(client, title: str = "clip-project") -> int: + return client.post("/api/projects", json={"title": title}).json()["id"] + + +def _add_scene(client, pid: int, order: int, **extra) -> dict: + payload = {"order_index": order, "heading": f"S{order}", **extra} + return client.post(f"/api/projects/{pid}/scenes", json=payload).json() + + +def _insert_workflow(client, conn, name: str, wf_json: dict) -> int: + cur = conn.execute( + """ + INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema, is_enabled) + VALUES (?, 'video', ?, '{}', '{}', 1) + """, + (name, json.dumps(wf_json)), + ) + conn.commit() + return cur.lastrowid + + +def _scene_default_clip_id(conn, scene_id: int) -> int: + row = conn.execute( + "SELECT id FROM clips WHERE scene_id = ? ORDER BY order_index, id LIMIT 1", + (scene_id,), + ).fetchone() + assert row is not None, "scene must always have >= 1 clip" + return int(row["id"]) + + +@pytest.fixture() +def video_workflow(client): + conn = get_db(settings.db_path) + try: + wid = _insert_workflow( + client, + conn, + "test-video", + { + "10": { + "class_type": "CLIPTextEncode", + "inputs": {"text": ""}, + "_meta": {"title": "Main Prompt (Input:prompt)"}, + }, + }, + ) + return int(wid) + finally: + conn.close() + + +# ── schema + default-clip invariant ───────────────────────────────────── + + +def test_new_scene_gets_default_clip(client): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1, duration_sec=9, dialog="ANNA\nHello.") + assert len(scene["clips"]) == 1 + clip = scene["clips"][0] + assert clip["order_index"] == 1 + assert clip["duration_sec"] == 9 + + +def test_scene_update_ensures_default_clip(client): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + conn = get_db(settings.db_path) + try: + conn.execute("DELETE FROM clips WHERE scene_id = ?", (scene["id"],)) + conn.commit() + finally: + conn.close() + r = client.patch(f"/api/projects/{pid}/scenes/{scene['id']}", json={"heading": "NEW"}) + assert r.status_code == 200 + assert len(r.json()["clips"]) == 1 + + +def test_delete_last_clip_of_scene_rejected(client): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + clip_id = scene["clips"][0]["id"] + r = client.delete(f"/api/projects/{pid}/clips/{clip_id}") + assert r.status_code == 422 + assert "at least one clip" in r.json()["detail"] + + +def test_clip_crud_roundtrip(client): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + scene_id = scene["id"] + r = client.post( + f"/api/projects/{pid}/scenes/{scene_id}/clips", + json={ + "description": "Close-up of hands", + "shot_size": "closeUp", + "dialog_lines_covered": [1, 2], + "duration_sec": 6, + }, + ) + assert r.status_code == 200 + clip = r.json() + assert clip["order_index"] == 2 + assert clip["dialog_lines_covered"] == [1, 2] + + r = client.patch( + f"/api/projects/{pid}/clips/{clip['id']}", + json={"description": "Extreme close-up", "duration_sec": 5}, + ) + assert r.status_code == 200 + assert r.json()["description"] == "Extreme close-up" + + r = client.post( + f"/api/projects/{pid}/scenes/{scene_id}/clips/reorder", + json={"clip_ids": [clip["id"], scene["clips"][0]["id"]]}, + ) + assert r.status_code == 200 + orders = [c["order_index"] for c in r.json()["clips"]] + assert orders == [1, 2] + + r = client.delete(f"/api/projects/{pid}/clips/{clip['id']}") + assert r.status_code == 200 + r = client.get(f"/api/projects/{pid}/scenes").json() + assert [c["id"] for c in r["scenes"][0]["clips"]] == [scene["clips"][0]["id"]] + + +# ── enqueue re-scope: per-clip jobs ───────────────────────────────────── + + +def test_enqueue_scene_expands_to_all_clips(client, video_workflow): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1, dialog="ANNA\nOne.\nBOB\nTwo.") + scene_id = scene["id"] + conn = get_db(settings.db_path) + try: + for desc in ("wide", "medium"): + conn.execute( + "INSERT INTO clips (scene_id, project_id, order_index, description) VALUES (?, ?, ?, ?)", + (scene_id, pid, 0, desc), + ) + conn.execute("UPDATE clips SET order_index = order_index + 1 WHERE scene_id = ?", (scene_id,)) + conn.commit() + n_clips = conn.execute( + "SELECT COUNT(*) AS n FROM clips WHERE scene_id = ?", (scene_id,) + ).fetchone()["n"] + finally: + conn.close() + assert n_clips == 3 + + jobs = asyncio.run(enqueue_video_jobs(pid, scene_ids=[scene_id])) + assert len(jobs) == 3 + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT clip_id FROM jobs WHERE id IN (%s)" % ",".join("?" * len(jobs)), + [j["id"] for j in jobs], + ).fetchall() + clip_ids = {r["clip_id"] for r in rows} + all_clip_ids = { + r["id"] + for r in conn.execute("SELECT id FROM clips WHERE scene_id = ?", (scene_id,)).fetchall() + } + assert clip_ids == all_clip_ids + finally: + conn.close() + + +def test_enqueue_by_clip_ids_renders_only_those(client, video_workflow): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + scene_id = scene["id"] + conn = get_db(settings.db_path) + try: + for _ in range(2): + conn.execute( + "INSERT INTO clips (scene_id, project_id, order_index, description) VALUES (?, ?, ?, ?)", + (scene_id, pid, 0, "x"), + ) + conn.execute("UPDATE clips SET order_index = order_index + 1 WHERE scene_id = ?", (scene_id,)) + conn.commit() + ids = [ + int(r["id"]) + for r in conn.execute( + "SELECT id FROM clips WHERE scene_id = ? ORDER BY order_index", (scene_id,) + ).fetchall() + ] + finally: + conn.close() + jobs = asyncio.run(enqueue_video_jobs(pid, clip_ids=ids[:2])) + assert len(jobs) == 2 + conn = get_db(settings.db_path) + try: + got = { + int(r["clip_id"]) + for r in conn.execute( + "SELECT clip_id FROM jobs WHERE id IN (%s)" % ",".join("?" * len(jobs)), + [j["id"] for j in jobs], + ).fetchall() + } + finally: + conn.close() + assert got == set(ids[:2]) + + +def test_supersede_and_clear_are_per_clip(client, video_workflow): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + scene_id = scene["id"] + conn = get_db(settings.db_path) + try: + conn.execute( + "INSERT INTO clips (scene_id, project_id, order_index, description) VALUES (?, ?, 2, 'second')", + (scene_id, pid), + ) + first = _scene_default_clip_id(conn, scene_id) + second = conn.execute( + "SELECT id FROM clips WHERE scene_id = ? AND order_index = 2", (scene_id,) + ).fetchone()["id"] + conn.execute( + "UPDATE clips SET clip_path = '/x/first.mp4' WHERE id = ?", (first,) + ) + conn.commit() + finally: + conn.close() + jobs = asyncio.run(enqueue_video_jobs(pid, clip_ids=[int(second)])) + assert len(jobs) == 1 + conn = get_db(settings.db_path) + try: + untouched = conn.execute( + "SELECT clip_path FROM clips WHERE id = ?", (first,) + ).fetchone()["clip_path"] + cleared = conn.execute( + "SELECT clip_path FROM clips WHERE id = ?", (second,) + ).fetchone()["clip_path"] + finally: + conn.close() + assert untouched == "/x/first.mp4", "re-enqueue must clear ONLY the target clip" + assert cleared is None + + +# ── coverage expansion contract ───────────────────────────────────────── + + +def test_normalize_clips_distributes_missing_dialog_lines(): + clips = _normalize_clips( + [ + {"description": "wide", "dialog_lines_covered": [1], "duration_sec": 6}, + {"description": "medium", "dialog_lines_covered": [], "duration_sec": 6}, + ], + n_dialog_lines=3, + scene_budget=12, + clip_cap=8, + ) + all_covered = sorted(n for c in clips for n in c["dialog_lines_covered"]) + assert all_covered == [1, 2, 3], "uncovered lines attach to the last clip" + assert all(c["duration_sec"] <= 8 for c in clips) + + +def test_normalize_clips_reindexes_and_clamps_durations(): + clips = _normalize_clips( + [ + {"order_index": 5, "description": "a", "duration_sec": 40}, + {"order_index": 9, "description": "b", "duration_sec": 3}, + ], + n_dialog_lines=0, + scene_budget=8, + clip_cap=8, + ) + assert [c["order_index"] for c in clips] == [1, 2] + assert all(c["duration_sec"] <= 8 for c in clips) + assert sum(c["duration_sec"] for c in clips) == 8 + + +def test_expand_scene_coverage_replaces_clips_and_migrates_chain(client, monkeypatch): + pid = _mk_project(client) + scene = _add_scene( + client, pid, 1, dialog="ANNA\nHello.\nBOB\nHi.", duration_sec=12 + ) + scene_id = scene["id"] + r = client.patch( + f"/api/projects/{pid}/scenes/{scene_id}", json={"chain_from_prev": True} + ) + assert r.status_code == 200 + + async def fake_llm(messages, temperature=0.5): + return { + "clips": [ + { + "order_index": 1, + "description": "Establishing wide", + "dialog_lines_covered": [1, 2], + "shot_size": "wide", + "duration_sec": 6, + "chain_from_prev": True, + }, + { + "order_index": 2, + "description": "Reverse on BOB", + "dialog_lines_covered": [3, 4], + "shot_size": "medium", + "duration_sec": 6, + "chain_from_prev": False, + }, + ] + } + + monkeypatch.setattr("calliope.agent.coverage_agent.generate_structured", fake_llm) + result = asyncio.run(expand_scene_coverage(pid, [scene_id])) + assert result["scenes"][0]["clips"] == 2 + + conn = get_db(settings.db_path) + try: + rows = [ + dict(r) + for r in conn.execute( + "SELECT * FROM clips WHERE scene_id = ? ORDER BY order_index", (scene_id,) + ).fetchall() + ] + assert len(rows) == 2 + assert rows[0]["chain_from_prev"] == 1, "scene chain flag lands on clip #1" + assert rows[1]["chain_from_prev"] == 0 + assert json.loads(rows[0]["dialog_lines_covered"]) == [1, 2] + assert json.loads(rows[1]["dialog_lines_covered"]) == [3, 4] + # Legacy scene mirror cleared after expansion + scene_row = conn.execute( + "SELECT video_path, chain_from_prev FROM scenes WHERE id = ?", (scene_id,) + ).fetchone() + assert scene_row["video_path"] is None + assert scene_row["chain_from_prev"] == 0 + finally: + conn.close() + + +def test_expand_all_scenes_none_ids(client, monkeypatch): + pid = _mk_project(client) + _add_scene(client, pid, 1, action="A") + _add_scene(client, pid, 2, action="B") + + async def fake_llm(messages, temperature=0.5): + return { + "clips": [ + {"description": "shot", "dialog_lines_covered": [], "duration_sec": 5}, + ] + } + + monkeypatch.setattr("calliope.agent.coverage_agent.generate_structured", fake_llm) + result = asyncio.run(expand_scene_coverage(pid, None)) + assert len(result["scenes"]) == 2 + + +def test_expand_no_scenes_raises(client): + pid = _mk_project(client) + with pytest.raises(ValueError): + asyncio.run(expand_scene_coverage(pid, [])) + + +def test_expand_all_endpoint_honors_scene_ids(client, monkeypatch): + """Per-scene 'Break Into Shots' must touch ONLY that scene. + + Regression: the project-level POST /expand-clips endpoint ignored + body.scene_ids and always expanded every scene in the project. + """ + pid = _mk_project(client) + s1 = _add_scene(client, pid, 1, action="Scene one action.") + s2 = _add_scene(client, pid, 2, action="Scene two action.") + + async def fake_llm(messages, temperature=0.5): + return { + "clips": [ + {"description": "shot A", "dialog_lines_covered": [], "duration_sec": 5}, + {"description": "shot B", "dialog_lines_covered": [], "duration_sec": 5}, + ] + } + + # The prompt names scenes by ORDER index, not id — spy on order instead. + seen_orders: list[int] = [] + + async def spy(messages, temperature=0.5): + import re + + m = re.search(r"^Scene (\d+):", messages[1]["content"], re.MULTILINE) + if m: + seen_orders.append(int(m.group(1))) + return await fake_llm(messages, temperature) + + monkeypatch.setattr("calliope.agent.coverage_agent.generate_structured", spy) + + r = client.post(f"/api/projects/{pid}/expand-clips", json={"scene_ids": [s2["id"]]}) + assert r.status_code == 200, r.text + body = r.json() + assert body["ok"] is True + assert [s["scene_id"] for s in body["scenes"]] == [s2["id"]] + assert body["total_clips"] == 2 + # Exactly ONE scene went through the LLM coverage pass: scene #2. + assert seen_orders == [2], f"LLM was invoked for scenes {seen_orders}, expected [2]" + + conn = get_db(settings.db_path) + try: + n1 = conn.execute( + "SELECT COUNT(*) AS n FROM clips WHERE scene_id = ?", (s1["id"],) + ).fetchone()["n"] + n2 = conn.execute( + "SELECT COUNT(*) AS n FROM clips WHERE scene_id = ?", (s2["id"],) + ).fetchone()["n"] + finally: + conn.close() + assert n1 == 1, f"scene #1 was touched: {n1} clips (default clip only allowed)" + assert n2 == 2, f"scene #2 should have exactly 2 clips, got {n2}" + + +# ── clip prompt hash: scene + clip fields ─────────────────────────────── + + +def test_clip_prompt_hash_distinguishes_clips(): + base = {"heading": "INT. BAR", "action": "x", "dialog": "A\nB"} + c1 = { + **base, + "description": "wide", + "dialog_lines_covered": "[1]", + "duration_sec": 5, + "order_index": 1, + } + c2 = { + **base, + "description": "close", + "dialog_lines_covered": "[2]", + "duration_sec": 5, + "order_index": 2, + } + assert _clip_prompt_hash(c1) != _clip_prompt_hash(c2) + assert _clip_prompt_hash(c1) == _clip_prompt_hash(dict(c1)) + + +def test_fetch_clips_orders_by_scene_then_clip(client): + pid = _mk_project(client) + s1 = _add_scene(client, pid, 1) + s2 = _add_scene(client, pid, 2) + conn = get_db(settings.db_path) + try: + for sid in (s1["id"], s2["id"]): + conn.execute( + "INSERT INTO clips (scene_id, project_id, order_index) VALUES (?, ?, 2)", + (sid, pid), + ) + conn.commit() + finally: + conn.close() + conn = get_db(settings.db_path) + try: + clips = _fetch_clips(conn, pid) + finally: + conn.close() + order = [(c["scene_id"], c["order_index"]) for c in clips] + assert order == sorted(order) + assert len(clips) == 4 + + +# ── preview endpoint: clip_id ─────────────────────────────────────────── + + +def test_preview_prompt_accepts_clip_id(client, video_workflow): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1, dialog="ANNA\nLine one.") + clip_id = scene["clips"][0]["id"] + # Give the default clip a description + dialog coverage so the narrowed + # beat carries the line into the prompt. + client.patch( + f"/api/projects/{pid}/clips/{clip_id}", + json={"description": "medium on ANNA", "dialog_lines_covered": [1, 2]}, + ) + r = client.post( + f"/api/jobs/projects/{pid}/preview-prompt", + json={"clip_id": clip_id}, + ) + assert r.status_code == 200 + body = r.json() + assert "Line one." in body["prompt"] + + +def test_generate_videos_accepts_clip_ids(client, video_workflow): + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + clip_id = scene["clips"][0]["id"] + r = client.post( + f"/api/jobs/projects/{pid}/generate-videos", + json={"clip_ids": [clip_id]}, + ) + assert r.status_code == 200 + jobs = r.json()["jobs"] + assert len(jobs) == 1 + assert jobs[0]["clip_id"] == clip_id + + +# ── agent tool scope: break_into_shots guard + clip addressing ───────── + + +def _mk_tool_ctx(client, session_id: int, project_id: int): + from calliope.agent.harness.registry import ToolContext + + return ToolContext(session_id=session_id, project_id=project_id) + + +def test_break_into_shots_requires_scope(client): + from calliope.agent.harness.plugins.script import t_break_into_shots + + pid = _mk_project(client) + _add_scene(client, pid, 1) + ctx = _mk_tool_ctx(client, session_id=1, project_id=pid) + result = asyncio.run(t_break_into_shots(ctx, {})) + assert result["ok"] is False + assert "scene_ids" in result["error"] + + +def test_list_clips_labels(client): + from calliope.agent.harness.plugins.script import t_list_clips + + pid = _mk_project(client) + scene = _add_scene(client, pid, 3) + conn = get_db(settings.db_path) + try: + conn.execute( + "INSERT INTO clips (scene_id, project_id, order_index, description) VALUES (?, ?, 2, 'two')", + (scene["id"], pid), + ) + conn.commit() + finally: + conn.close() + ctx = _mk_tool_ctx(client, session_id=1, project_id=pid) + result = asyncio.run(t_list_clips(ctx, {})) + labels = [c["label"] for c in result["clips"]] + assert "#3.1" in labels and "#3.2" in labels + + +def test_delete_clip_tool_protects_last(client): + from calliope.agent.harness.plugins.script import t_delete_clip + + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + ctx = _mk_tool_ctx(client, session_id=1, project_id=pid) + result = asyncio.run(t_delete_clip(ctx, {"clip_id": scene["clips"][0]["id"]})) + assert result["ok"] is False + assert "at least one clip" in result["error"] + + +def test_update_clip_by_ref(client): + from calliope.agent.harness.plugins.script import t_update_clip + + pid = _mk_project(client) + scene = _add_scene(client, pid, 2) + ctx = _mk_tool_ctx(client, session_id=1, project_id=pid) + result = asyncio.run(t_update_clip(ctx, {"ref": "#2.1", "description": "updated", "duration_sec": 7})) + assert result.get("ok", True) is not False + assert result["clip"]["description"] == "updated" + + +def test_enqueue_video_jobs_tool_by_ref(client, video_workflow): + from calliope.agent.harness.plugins.render import t_enqueue_video_jobs + + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + ctx = _mk_tool_ctx(client, session_id=1, project_id=pid) + result = asyncio.run(t_enqueue_video_jobs(ctx, {"refs": ["#1.1"]})) + assert "jobs" in result + assert result["count"] == 1 + + +def test_enqueue_video_jobs_tool_bulk_guard(client, video_workflow): + from calliope.agent.harness.plugins.render import t_enqueue_video_jobs + + pid = _mk_project(client) + scene = _add_scene(client, pid, 1) + scene_id = scene["id"] + conn = get_db(settings.db_path) + try: + for i in range(2, 6): + conn.execute( + "INSERT INTO clips (scene_id, project_id, order_index, description) VALUES (?, ?, ?, 'c')", + (scene_id, pid, i), + ) + conn.commit() + finally: + conn.close() + ctx = _mk_tool_ctx(client, session_id=1, project_id=pid) + result = asyncio.run(t_enqueue_video_jobs(ctx, {"scene_ids": [scene_id]})) + # scene_ids expands to 6 clips (>3) without explicit user prose — blocked. + assert result["ok"] is False + assert "bulk" in result["error"] diff --git a/calliope-backend/tests/test_export.py b/calliope-backend/tests/test_export.py index 6dd0438d..0fb8477e 100644 --- a/calliope-backend/tests/test_export.py +++ b/calliope-backend/tests/test_export.py @@ -7,6 +7,31 @@ import pytest from calliope.comfyui.client import ComfyUIClient from calliope.export.runner import DEFAULT_EXPORT_FPS, build_ffmpeg_cmd, collect_clips, parse_rate, target_fps +from calliope.config import settings +from calliope.db import get_db + + +def _set_clip_path(clip_id: int, path: str) -> None: + conn = get_db(settings.db_path) + try: + conn.execute("UPDATE clips SET clip_path = ? WHERE id = ?", (path, clip_id)) + conn.commit() + finally: + conn.close() + + +def _scene_default_clip(pid: int, scene_id: int) -> int: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT id FROM clips WHERE scene_id = ? AND project_id = ? " + "ORDER BY order_index, id LIMIT 1", + (scene_id, pid), + ).fetchone() + assert row is not None + return row["id"] + finally: + conn.close() def _make_project_with_clips(client, title: str = "My Film") -> int: @@ -17,17 +42,13 @@ def _make_project_with_clips(client, title: str = "My Film") -> int: s2 = client.post( f"/api/projects/{pid}/scenes", json={"order_index": 2, "heading": "Chase"} ).json() - client.patch( - f"/api/projects/{pid}/scenes/{s1['id']}", json={"video_path": "C:/clips/a.mp4"} - ) - client.patch( - f"/api/projects/{pid}/scenes/{s2['id']}", json={"video_path": "C:/clips/b.mp4"} - ) + _set_clip_path(_scene_default_clip(pid, s1["id"]), "C:/clips/a.mp4") + _set_clip_path(_scene_default_clip(pid, s2["id"]), "C:/clips/b.mp4") return pid def test_build_ffmpeg_cmd_two_clips(): - clips = [{"video_path": "a.mp4"}, {"video_path": "b.mp4"}] + clips = [{"clip_path": "a.mp4"}, {"clip_path": "b.mp4"}] probes = [ {"duration": 8.02, "has_audio": True}, {"duration": 8.0, "has_audio": True}, @@ -52,7 +73,7 @@ def test_build_ffmpeg_cmd_two_clips(): def test_build_ffmpeg_cmd_anullsrc_for_silent_clip(): - clips = [{"video_path": "a.mp4"}, {"video_path": "b.mp4"}] + clips = [{"clip_path": "a.mp4"}, {"clip_path": "b.mp4"}] probes = [ {"duration": 8.0, "has_audio": True}, {"duration": 4.0, "has_audio": False}, @@ -72,7 +93,7 @@ def test_build_ffmpeg_cmd_anullsrc_for_silent_clip(): def test_build_ffmpeg_cmd_single_clip(): cmd = build_ffmpeg_cmd( - [{"video_path": "a.mp4"}], [{"duration": 5.0, "has_audio": True}], "out.mp4" + [{"clip_path": "a.mp4"}], [{"duration": 5.0, "has_audio": True}], "out.mp4" ) joined = " ".join(str(c) for c in cmd) assert "xfade" not in joined @@ -96,8 +117,8 @@ def test_collect_clips_split_and_order(client): f"/api/projects/{pid}/scenes", json={"order_index": 1, "heading": "A"} ).json() client.post(f"/api/projects/{pid}/scenes", json={"order_index": 3, "heading": "C"}) - client.patch(f"/api/projects/{pid}/scenes/{s_b['id']}", json={"video_path": "b.mp4"}) - client.patch(f"/api/projects/{pid}/scenes/{s_a['id']}", json={"video_path": "a.mp4"}) + _set_clip_path(_scene_default_clip(pid, s_b["id"]), "b.mp4") + _set_clip_path(_scene_default_clip(pid, s_a["id"]), "a.mp4") clips, skipped = collect_clips(pid) assert [c["heading"] for c in clips] == ["A", "B"] @@ -235,7 +256,7 @@ def test_target_fps_missing_falls_back_to_default(): def test_build_ffmpeg_cmd_explicit_fps_24(): - clips = [{"video_path": "a.mp4"}] + clips = [{"clip_path": "a.mp4"}] probes = [{"duration": 5.0, "has_audio": True, "fps": 30.0}] cmd = build_ffmpeg_cmd(clips, probes, "out.mp4", fps=24.0) joined = " ".join(str(c) for c in cmd) @@ -244,7 +265,7 @@ def test_build_ffmpeg_cmd_explicit_fps_24(): def test_build_ffmpeg_cmd_defaults_to_target_fps_vote(): - clips = [{"video_path": "a.mp4"}, {"video_path": "b.mp4"}] + clips = [{"clip_path": "a.mp4"}, {"clip_path": "b.mp4"}] probes = [ {"duration": 5.0, "has_audio": True, "fps": 24.0}, {"duration": 5.0, "has_audio": True, "fps": 24.0}, @@ -256,7 +277,7 @@ def test_build_ffmpeg_cmd_defaults_to_target_fps_vote(): def test_build_ffmpeg_cmd_fractional_fps_formatting(): - clips = [{"video_path": "a.mp4"}] + clips = [{"clip_path": "a.mp4"}] probes = [{"duration": 5.0, "has_audio": True, "fps": 23.976023976}] # Explicit fractional rate: target_fps votes on rounded fps (24), so :.6g # formatting is only reachable via the explicit override. diff --git a/calliope-backend/tests/test_scene_settings.py b/calliope-backend/tests/test_scene_settings.py index 7df47947..04f2a8a0 100644 --- a/calliope-backend/tests/test_scene_settings.py +++ b/calliope-backend/tests/test_scene_settings.py @@ -3,7 +3,7 @@ from __future__ import annotations import json -from calliope.agent.video_agent import enqueue_video_jobs +from calliope.agent.video_agent import enqueue_video_jobs, preview_clip_prompt from calliope.config import settings from calliope.db import get_db @@ -17,6 +17,20 @@ def _add_scene(client, pid: int, order: int, **extra) -> dict: return client.post(f"/api/projects/{pid}/scenes", json=payload).json() +def _scene_default_clip(pid: int, scene_id: int) -> int: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT id FROM clips WHERE scene_id = ? AND project_id = ? " + "ORDER BY order_index, id LIMIT 1", + (scene_id, pid), + ).fetchone() + assert row is not None + return row["id"] + finally: + conn.close() + + def test_scene_patch_video_settings_roundtrip(client): pid = _mk_project(client, "Settings RT") scene = _add_scene(client, pid, 1) @@ -90,17 +104,18 @@ def _insert_h3_workflow(conn, name: str) -> int: def test_enqueue_merges_stored_input_values(client, monkeypatch): - """Batch enqueue with no form values must honor the saved per-scene setup.""" + """Batch enqueue with no form values must honor the saved per-clip setup.""" pid = _mk_project(client, "Merge stored") scene = _add_scene(client, pid, 1) + clip_id = _scene_default_clip(pid, scene["id"]) conn = get_db(settings.db_path) try: wf_id = _insert_h3_workflow(conn, "H3 merge") stored = {"input_values": {"20": 10}} conn.execute( - "UPDATE scenes SET workflow_id = ?, video_settings_json = ? WHERE id = ?", - (wf_id, json.dumps(stored), scene["id"]), + "UPDATE clips SET workflow_id = ?, video_settings_json = ? WHERE id = ?", + (wf_id, json.dumps(stored), clip_id), ) conn.commit() finally: @@ -134,12 +149,13 @@ def test_preview_prompt_endpoint_h3_profile(client, monkeypatch): pid = _mk_project(client, "Preview H3") scene = _add_scene(client, pid, 1) + clip_id = _scene_default_clip(pid, scene["id"]) conn = get_db(settings.db_path) try: wf_id = _insert_h3_workflow(conn, "H3 preview") conn.execute( - "UPDATE scenes SET workflow_id = ? WHERE id = ?", (wf_id, scene["id"]) + "UPDATE clips SET workflow_id = ? WHERE id = ?", (wf_id, clip_id) ) conn.commit() finally: @@ -154,7 +170,7 @@ def test_preview_prompt_endpoint_h3_profile(client, monkeypatch): try: r = client.post( f"/api/jobs/projects/{pid}/preview-prompt", - json={"scene_id": scene["id"]}, + json={"clip_id": clip_id}, ) assert r.status_code == 200 body = r.json() @@ -172,41 +188,43 @@ def test_preview_prompt_endpoint_h3_profile(client, monkeypatch): def test_preview_prompt_fresh_draft_shortcircuits_llm(client, monkeypatch): """A saved fresh draft is returned as-is — no LLM call.""" - from calliope.agent.video_agent import preview_scene_prompt - pid = _mk_project(client, "Preview draft") scene = _add_scene(client, pid, 1) + clip_id = _scene_default_clip(pid, scene["id"]) conn = get_db(settings.db_path) try: wf_id = _insert_h3_workflow(conn, "H3 draft") conn.execute( - "UPDATE scenes SET workflow_id = ? WHERE id = ?", (wf_id, scene["id"]) + "UPDATE clips SET workflow_id = ? WHERE id = ?", (wf_id, clip_id) ) conn.commit() finally: conn.close() # Compute the hash the backend would, then store the draft with it - from calliope.agent.video_agent import _scene_prompt_hash + from calliope.agent.video_agent import _clip_prompt_hash conn = get_db(settings.db_path) try: fresh_row = conn.execute( - "SELECT * FROM scenes WHERE id = ?", (scene["id"],) + """ + SELECT c.*, s.heading, s.action, s.dialog, + s.order_index AS scene_order_index, + s.env_image_path, s.location_id + FROM clips c JOIN scenes s ON s.id = c.scene_id + WHERE c.id = ?""", + (clip_id,), ).fetchone() - from calliope.db import row_to_dict - - fresh_scene = row_to_dict(fresh_row) - # character_ids aren't on the row — hash treats them via scene dict - fresh_scene["character_ids"] = [] + fresh_clip = dict(fresh_row) + fresh_clip["character_ids"] = [] stored = { "prompt_draft": "MY SAVED DRAFT", - "prompt_draft_meta": {"based_on": _scene_prompt_hash(fresh_scene)}, + "prompt_draft_meta": {"based_on": _clip_prompt_hash(fresh_clip)}, } conn.execute( - "UPDATE scenes SET video_settings_json = ? WHERE id = ?", - (json.dumps(stored), scene["id"]), + "UPDATE clips SET video_settings_json = ? WHERE id = ?", + (json.dumps(stored), clip_id), ) conn.commit() finally: @@ -220,7 +238,7 @@ def test_preview_prompt_fresh_draft_shortcircuits_llm(client, monkeypatch): monkeypatch.setattr("calliope.agent.video_agent._h3_rewrite", fake_rewrite) - result = asyncio_run(preview_scene_prompt(pid, scene["id"])) + result = asyncio_run(preview_clip_prompt(pid, clip_id)) assert result["prompt"] == "MY SAVED DRAFT" assert result["from_draft"] is True assert called == [] # LLM never invoked @@ -236,12 +254,13 @@ def test_preview_prompt_dead_llm_returns_deterministic_fallback(client, monkeypa pid = _mk_project(client, "Preview dead LLM") scene = _add_scene(client, pid, 1, action="A lone rider crosses the salt flats.") + clip_id = _scene_default_clip(pid, scene["id"]) conn = get_db(settings.db_path) try: wf_id = _insert_h3_workflow(conn, "H3 dead") conn.execute( - "UPDATE scenes SET workflow_id = ? WHERE id = ?", (wf_id, scene["id"]) + "UPDATE clips SET workflow_id = ? WHERE id = ?", (wf_id, clip_id) ) conn.commit() finally: @@ -263,7 +282,7 @@ def test_preview_prompt_dead_llm_returns_deterministic_fallback(client, monkeypa type("LLMClientStub", (), {"for_role": staticmethod(lambda role, **kw: DeadClient())}), ) - result = asyncio_run(video_agent.preview_scene_prompt(pid, scene["id"])) + result = asyncio_run(video_agent.preview_clip_prompt(pid, clip_id)) assert result["profile"] == "minimax_h3_ref" assert result["from_draft"] is False # Deterministic template content, not an exception and not empty @@ -278,12 +297,13 @@ def test_enqueue_prompts_override(client, monkeypatch): """Confirmed prompt from the review modal wins over the rewrite.""" pid = _mk_project(client, "Prompt override") scene = _add_scene(client, pid, 1) + clip_id = _scene_default_clip(pid, scene["id"]) conn = get_db(settings.db_path) try: wf_id = _insert_h3_workflow(conn, "H3 override") conn.execute( - "UPDATE scenes SET workflow_id = ? WHERE id = ?", (wf_id, scene["id"]) + "UPDATE clips SET workflow_id = ? WHERE id = ?", (wf_id, clip_id) ) conn.commit() finally: @@ -299,7 +319,7 @@ def test_enqueue_prompts_override(client, monkeypatch): queue_manager.paused = True try: jobs = asyncio_run( - enqueue_video_jobs(pid, scene_ids=[scene["id"]], prompts={scene["id"]: "CONFIRMED"}) + enqueue_video_jobs(pid, scene_ids=[scene["id"]], prompts={clip_id: "CONFIRMED"}) ) raw = json.loads(jobs[0]["payload_json"]) assert raw["prompt"] == "CONFIRMED" @@ -311,6 +331,7 @@ def test_preview_prompt_prose_profile(client): """Prose workflows return the deterministic scene_video_prompt.""" pid = _mk_project(client, "Preview prose") scene = _add_scene(client, pid, 1, action="A knight rides at dawn.") + clip_id = _scene_default_clip(pid, scene["id"]) conn = get_db(settings.db_path) try: @@ -329,7 +350,7 @@ def test_preview_prompt_prose_profile(client): ("Prose WF", json.dumps(wf)), ) conn.execute( - "UPDATE scenes SET workflow_id = ? WHERE id = ?", (cur.lastrowid, scene["id"]) + "UPDATE clips SET workflow_id = ? WHERE id = ?", (cur.lastrowid, clip_id) ) conn.commit() finally: @@ -337,7 +358,7 @@ def test_preview_prompt_prose_profile(client): r = client.post( f"/api/jobs/projects/{pid}/preview-prompt", - json={"scene_id": scene["id"]}, + json={"clip_id": clip_id}, ) assert r.status_code == 200 body = r.json() @@ -349,7 +370,7 @@ def test_preview_prompt_missing_scene_400(client): pid = _mk_project(client, "Preview missing") r = client.post( f"/api/jobs/projects/{pid}/preview-prompt", - json={"scene_id": 99999}, + json={"clip_id": 99999}, ) assert r.status_code == 400 diff --git a/calliope-backend/tests/test_session_origin.py b/calliope-backend/tests/test_session_origin.py new file mode 100644 index 00000000..d0230a15 --- /dev/null +++ b/calliope-backend/tests/test_session_origin.py @@ -0,0 +1,192 @@ +"""Session-origin contract: Build Scene's per-scene sessions stay out of the +AI Canvas sidebar. origin is stamped at creation and never drifts via rename. +Scene-origin sessions are also scoped to the shot_* blockout tools only.""" +from __future__ import annotations + +import asyncio +import tempfile +from pathlib import Path + +import pytest + +from calliope.config import settings +from calliope.db import get_db, migrate_db +from calliope.agent.harness.registry import GUARD_SCENE_TOOL_SCOPE, ToolContext + + +@pytest.fixture(autouse=True, scope="module") +def _never_touch_real_db(): + """Tests in this file call get_db(settings.db_path) directly (the + backfill test has no client-only path) — redirect data_dir to a temp dir + for the whole module so the real calliope.db can never be written.""" + prev = settings.data_dir + with tempfile.TemporaryDirectory() as tmp: + settings.data_dir = Path(tmp) + asyncio.run(migrate_db(settings.db_path)) + yield + settings.data_dir = prev + + +def test_default_sessions_exclude_scene_origin(client): + chat = client.post("/api/agent/sessions", json={"title": "My chat"}).json() + scene = client.post("/api/agent/sessions", json={"title": "Scene · 999", "origin": "scene"}).json() + listed = client.get("/api/agent/sessions").json() + ids = {s["id"] for s in listed} + assert chat["id"] in ids + assert scene["id"] not in ids + assert all(s.get("origin") != "scene" for s in listed) + + +def test_origin_filter_returns_scene_sessions(client): + scene = client.post("/api/agent/sessions", json={"origin": "scene"}).json() + client.post("/api/agent/sessions", json={"title": "chat"}) + listed = client.get("/api/agent/sessions?origin=scene").json() + ids = {s["id"] for s in listed} + assert scene["id"] in ids + assert all(s["origin"] == "scene" for s in listed) + + +def test_origin_defaults_to_chat(client): + s = client.post("/api/agent/sessions", json={}).json() + assert s["origin"] == "chat" + + +def test_origin_rejects_unknown_value(client): + r = client.post("/api/agent/sessions", json={"origin": "plotter"}) + assert r.status_code == 422 + + +def test_rename_does_not_change_origin(client): + scene = client.post("/api/agent/sessions", json={"origin": "scene"}).json() + r = client.patch(f"/api/agent/sessions/{scene['id']}", json={"title": "Totally a chat"}) + assert r.status_code == 200 + listed = client.get("/api/agent/sessions").json() + assert scene["id"] not in {s["id"] for s in listed} + assert r.json()["title"] == "Totally a chat" + + +def test_backfill_matches_legacy_scene_titled_rows(client): + """The one-time backfill (run inside migrate_db when the origin column is + added) stamps origin='scene' on exactly the legacy rows titled + 'Scene · N' and nothing else. The migration branch itself is gated on the + ALTER (runs once), so this asserts the statement's row-matching + invariant directly on legacy-shaped data.""" + conn = get_db(settings.db_path) + try: + legacy_ids = [] + for title in ("Scene · 100", "Scene · 200"): + cur = conn.execute( + "INSERT INTO agent_sessions (title, origin) VALUES (?, 'chat')", (title,) + ) + legacy_ids.append(cur.lastrowid) + plain = conn.execute( + "INSERT INTO agent_sessions (title, origin) VALUES ('my chat', 'chat')" + ).lastrowid + # Scene-titled but already scene (idempotency); a title that merely + # contains the prefix without starting with it is NOT backfilled. + already = conn.execute( + "INSERT INTO agent_sessions (title, origin) VALUES ('Scene · 300', 'scene')" + ).lastrowid + tricky = conn.execute( + "INSERT INTO agent_sessions (title, origin) VALUES ('my Scene · chat', 'chat')" + ).lastrowid + conn.commit() + + conn.execute("UPDATE agent_sessions SET origin = 'scene' WHERE title LIKE 'Scene · %'") + conn.commit() + + for sid in legacy_ids + [already]: + row = conn.execute("SELECT origin FROM agent_sessions WHERE id = ?", (sid,)).fetchone() + assert row["origin"] == "scene", sid + for sid in (plain, tricky): + row = conn.execute("SELECT origin FROM agent_sessions WHERE id = ?", (sid,)).fetchone() + assert row["origin"] == "chat", sid + + for sid in (*legacy_ids, plain, already, tricky): + conn.execute("DELETE FROM agent_sessions WHERE id = ?", (sid,)) + conn.commit() + finally: + conn.close() + + +# ───────────────────────────────────────────────────────────────────────── +# Build Scene tool scope: scene-origin sessions see shot tools + base ONLY +# ───────────────────────────────────────────────────────────────────────── + + +def _scene_ctx() -> ToolContext: + return ToolContext(session_id=1, project_id=None, origin="scene") + + +def test_scene_payload_only_allowlisted_tools(client): + from calliope.agent.harness.tools import openai_tools_payload + + names = {entry["function"]["name"] for entry in openai_tools_payload(_scene_ctx())} + assert "get_scene" in names and "add_object" in names and "add_keyframe" in names + assert "run_workflow" not in names + assert "enqueue_asset_jobs" not in names + assert "generate_story" not in names + assert "create_canvas_node" not in names + assert "ask_user" in names and "read_skill" in names + + +def test_chat_payload_unaffected_by_scene_scope(client): + from calliope.agent.harness.tools import openai_tools_payload + + chat_ctx = ToolContext(session_id=1, project_id=None, origin="chat") + names = {t["function"]["name"] for t in openai_tools_payload(chat_ctx)} + # A chat sandbox still has its generation tools (render visibility is + # governed by user_allows_render, not origin). + assert "run_workflow" in names or "list_workflows" in names + + +def test_scene_execute_denies_out_of_scope_tool(client): + from calliope.agent.harness.tools import execute_tool + + result = asyncio.run(execute_tool(_scene_ctx(), "run_workflow", {"workflow_id": 1, "prompt": "x"})) + assert result["ok"] is False + assert result.get("reason_code") == GUARD_SCENE_TOOL_SCOPE + + +def test_scene_execute_still_runs_shot_tool(client): + from calliope.agent.harness.tools import execute_tool + + result = asyncio.run(execute_tool(_scene_ctx(), "get_scene", {})) + # The shot tool executes (empty scene is fine) — not scope-blocked. + assert result.get("ok") is True or "reason_code" not in result + + +# ───────────────────────────────────────────────────────────────────────── +# Startup recovery: sessions orphaned in 'running' by a killed process +# ───────────────────────────────────────────────────────────────────────── + + +def test_recover_orphaned_running_sessions(client): + """A backend restart leaves no live tasks, so every 'running' row at + startup is orphaned (the loop died before writing turn/end) and must be + reset to 'idle' — otherwise the UI shows a phantom Working… state with a + dead Stop button.""" + from calliope.agent.harness.runner import runner + + conn = get_db(settings.db_path) + try: + stuck = conn.execute( + "INSERT INTO agent_sessions (title, status) VALUES ('stuck', 'running')" + ).lastrowid + fine = conn.execute( + "INSERT INTO agent_sessions (title, status) VALUES ('idle-one', 'idle')" + ).lastrowid + errored = conn.execute( + "INSERT INTO agent_sessions (title, status) VALUES ('err-one', 'error')" + ).lastrowid + conn.commit() + + assert runner.recover_orphaned_sessions() >= 1 + + for sid, expected in ((stuck, "idle"), (fine, "idle"), (errored, "error")): + row = conn.execute( + "SELECT status FROM agent_sessions WHERE id = ?", (sid,) + ).fetchone() + assert row["status"] == expected, sid + finally: + conn.close() diff --git a/calliope-backend/tests/test_shot_tools.py b/calliope-backend/tests/test_shot_tools.py new file mode 100644 index 00000000..fb26cf1b --- /dev/null +++ b/calliope-backend/tests/test_shot_tools.py @@ -0,0 +1,609 @@ +"""Shot-builder plugin + /api/shots router tests (Build Scene). + +The module-scoped autouse fixture redirects data_dir BEFORE any direct +get_db(settings.db_path) use — never write into the real calliope.db +(see clean-test-artifacts rule). +""" +from __future__ import annotations + +import asyncio +import base64 +import json +import tempfile +from pathlib import Path + +import pytest + +from calliope.config import settings +from calliope.db import get_db, migrate_db +from calliope.agent.harness.registry import ToolContext +from calliope.agent.harness.tools import execute_tool, openai_tools_payload +from calliope.agent.harness.orchestrator import orchestrate + + +@pytest.fixture(autouse=True, scope="module") +def _never_touch_real_db(): + prev = settings.data_dir + with tempfile.TemporaryDirectory() as tmp: + settings.data_dir = Path(tmp) + settings.assets_dir = Path(tmp) / "assets" + asyncio.run(migrate_db(settings.db_path)) + yield + + +def _mk_session() -> int: + conn = get_db(settings.db_path) + try: + cur = conn.execute( + "INSERT INTO agent_sessions (title, project_id) VALUES (?, NULL)", + ("shot-test",), + ) + conn.commit() + return int(cur.lastrowid) + finally: + conn.close() + + +def _run(sid: int, tool: str, args: dict | None = None): + from calliope.agent.harness.tools import TOOLS + + t = TOOLS[tool] + return asyncio.run(t.executor(ToolContext(session_id=sid, project_id=None), args or {})) + + +def _png_data_url() -> str: + # 1x1 transparent PNG + raw = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" + ) + return "data:image/png;base64," + base64.b64encode(raw).decode() + + +# ── scoping ──────────────────────────────────────────────────────────────── + + +def test_shot_tools_hidden_in_linked_sessions(): + ctx = ToolContext(session_id=_mk_session(), project_id=42) + names = {e["function"]["name"] for e in openai_tools_payload(ctx)} + assert "get_scene" not in names + assert "add_object" not in names + assert "request_capture" not in names + + +def test_shot_tools_visible_in_sandbox(): + ctx = ToolContext(session_id=_mk_session(), project_id=None) + names = {e["function"]["name"] for e in openai_tools_payload(ctx)} + assert "get_scene" in names + assert "set_joint" in names + assert "set_shot" in names + assert "request_capture" in names + assert "add_keyframe" in names + assert "update_keyframe" in names + assert "delete_keyframe" in names + assert "move_keyframe_time" in names + assert "set_playback" in names + + +# ── get-or-create per session ────────────────────────────────────────────── + + +def test_get_scene_creates_one_composition_per_session(): + sid = _mk_session() + out = _run(sid, "get_scene") + assert out["ok"] is True + comp_id = out["shot_id"] + + out2 = _run(sid, "get_scene") + assert out2["shot_id"] == comp_id + + # A different session gets its own composition + out3 = _run(_mk_session(), "get_scene") + assert out3["shot_id"] != comp_id + + +# ── object CRUD ──────────────────────────────────────────────────────────── + + +def test_add_and_delete_object_roundtrip(): + sid = _mk_session() + added = _run(sid, "add_object", {"type": "male", "name": "Hero"}) + assert added["ok"] is True + obj = added["object"] + assert obj["type"] == "male" + assert obj["name"] == "Hero" + assert obj["transform"]["position"] == [0.0, 0, 0] + + scene = _run(sid, "get_scene") + assert any(o["id"] == obj["id"] for o in scene["objects"]) + + deleted = _run(sid, "delete_object", {"object_id": obj["id"]}) + assert deleted["ok"] is True + scene = _run(sid, "get_scene") + assert not any(o["id"] == obj["id"] for o in scene["objects"]) + + +def test_add_object_rejects_unknown_type(): + sid = _mk_session() + out = _run(sid, "add_object", {"type": "dragon"}) + assert out["ok"] is False + assert "type must be one of" in out["error"] + + +def test_delete_unknown_object_errors(): + sid = _mk_session() + out = _run(sid, "delete_object", {"object_id": "nope"}) + assert out["ok"] is False + + +# ── transforms ───────────────────────────────────────────────────────────── + + +def test_set_transform_partial_merge(): + sid = _mk_session() + obj = _run(sid, "add_object", {"type": "cube"})["object"] + out = _run( + sid, + "set_transform", + {"object_id": obj["id"], "transform": {"position": [1.5, 0, -2]}}, + ) + assert out["ok"] is True + assert out["object"]["transform"]["position"] == [1.5, 0.0, -2.0] + assert out["object"]["transform"]["scale"] == [1, 1, 1] # untouched + + bad = _run( + sid, + "set_transform", + {"object_id": obj["id"], "transform": {"position": [1, 2]}}, + ) + assert bad["ok"] is False + + +def test_reset_transform(): + sid = _mk_session() + obj = _run(sid, "add_object", {"type": "sphere"})["object"] + _run(sid, "set_transform", {"object_id": obj["id"], "transform": {"position": [3, 3, 3]}}) + out = _run(sid, "reset_transform", {"object_id": obj["id"]}) + assert out["object"]["transform"]["position"] == [0.0, 0.0, 0.0] + + +# ── pose / joints ────────────────────────────────────────────────────────── + + +def test_set_joint_validates_lengths(): + sid = _mk_session() + obj = _run(sid, "add_object", {"type": "female"})["object"] + + ok = _run(sid, "set_joint", {"object_id": obj["id"], "joint": "l_arm", "values": [10, 20, 30]}) + assert ok["ok"] is True + + knee = _run(sid, "set_joint", {"object_id": obj["id"], "joint": "l_knee", "values": [45]}) + assert knee["ok"] is True + + bad = _run(sid, "set_joint", {"object_id": obj["id"], "joint": "l_knee", "values": [1, 2, 3]}) + assert bad["ok"] is False + assert "1 numbers" in bad["error"] + + unknown = _run(sid, "set_joint", {"object_id": obj["id"], "joint": "tail", "values": [0]}) + assert unknown["ok"] is False + + +def test_set_joint_rejects_camera(): + sid = _mk_session() + obj = _run(sid, "add_object", {"type": "camera"})["object"] + out = _run(sid, "set_joint", {"object_id": obj["id"], "joint": "head", "values": [0, 0, 0]}) + assert out["ok"] is False + + +def test_set_posture_rejects_malformed(): + sid = _mk_session() + obj = _run(sid, "add_object", {"type": "male"})["object"] + out = _run( + sid, + "set_posture", + {"object_id": obj["id"], "posture": {"version": 7, "data": [[0, 0, 0]]}}, + ) + assert out["ok"] is False + assert "26 entries" in out["error"] + + +def test_apply_pose_from_library(): + sid = _mk_session() + obj = _run(sid, "add_object", {"type": "male"})["object"] + poses = _run(sid, "list_poses")["poses"] + assert len(poses) > 0 + out = _run( + sid, + "apply_pose", + {"object_id": obj["id"], "pose_id": poses[0]["id"]}, + ) + assert out["ok"] is True + assert out["object"]["posture"]["version"] == 7 + assert len(out["object"]["posture"]["data"]) == 26 + + missing = _run(sid, "apply_pose", {"object_id": obj["id"], "pose_id": "authored.nope"}) + assert missing["ok"] is False + + reset = _run(sid, "reset_pose", {"object_id": obj["id"]}) + assert reset["object"]["posture"] is None + + +# ── shot framing ─────────────────────────────────────────────────────────── + + +def test_set_shot_validates_and_merges(): + sid = _mk_session() + out = _run(sid, "set_shot", {"shotSize": "mcu", "angle": "threeQuarterLeft"}) + assert out["ok"] is True + assert out["shotParams"] == {"shotSize": "mcu", "angle": "threeQuarterLeft"} + + out = _run(sid, "set_shot", {"elevation": "low"}) + assert out["shotParams"]["shotSize"] == "mcu" # merged + assert out["shotParams"]["elevation"] == "low" + + bad = _run(sid, "set_shot", {"shotSize": "extreme"}) + assert bad["ok"] is False + + unknown_angle = _run(sid, "set_shot", {"angle": "dutch_45"}) + assert unknown_angle["ok"] is False + + +def test_set_shot_normalizes_legacy_ids(): + """Legacy '34_left'-era ids must map to the camelCase vocabulary the + frontend solver indexes — an unnormalized '34_left' used to NaN the + restored camera and blank the viewport after refresh.""" + sid = _mk_session() + out = _run(sid, "set_shot", {"angle": "34_left", "composition": "left_third"}) + assert out["ok"] is True + assert out["shotParams"]["angle"] == "threeQuarterLeft" + assert out["shotParams"]["composition"] == "leftThird" + + +def test_preset_values_match_between_tools(): + sid = _mk_session() + presets = _run(sid, "list_shot_presets") + bad = _run(sid, "set_shot", {"composition": presets["composition"][0]}) + assert bad["ok"] is True + + +# ── keyframes / motion ───────────────────────────────────────────────────── + + +def _add_block(sid: int) -> str: + out = _run(sid, "add_object", {"type": "cube"}) + return out["object"]["id"] + + +def test_add_keyframe_captures_current_transform(): + sid = _mk_session() + oid = _add_block(sid) + _run(sid, "set_transform", {"object_id": oid, "transform": {"position": [2, 0, 1]}}) + out = _run(sid, "add_keyframe", {"object_id": oid, "time": 1.5}) + assert out["ok"] is True + kfs = out["object"]["keyframes"] + assert len(kfs) == 2 # spawn keyframe at t=0 + this one + assert kfs[-1]["time"] == 1.5 + assert kfs[-1]["transform"]["position"] == [2.0, 0.0, 1.0] + + +def test_set_transform_never_rewrites_committed_track(): + """Once a track exists, set_transform only stages the live fields — + force-rewriting keyframes[0] snapped every earlier keyframe to the new + position (a keyed walk-across teleported at t=0) and broke the + stage→add_keyframe recipe.""" + sid = _mk_session() + oid = _add_block(sid) + _run(sid, "set_transform", {"object_id": oid, "transform": {"position": [4, 0, 0]}}) + _run(sid, "add_keyframe", {"object_id": oid, "time": 3.0}) + _run(sid, "set_transform", {"object_id": oid, "transform": {"position": [1, 0, 0]}}) + out = _run(sid, "get_scene", {}) + obj = next(o for o in out["objects"] if o["id"] == oid) + assert obj["transform"]["position"] == [1.0, 0.0, 0.0] # staged live + assert obj["keyframes"][-1]["transform"]["position"] == [4.0, 0.0, 0.0] # untouched + assert obj["keyframes"][0]["transform"]["position"] == [0.0, 0.0, 0.0] # spawn intact + + +def test_add_keyframe_replaces_near_time(): + sid = _mk_session() + oid = _add_block(sid) + _run(sid, "add_keyframe", {"object_id": oid, "time": 1.0}) + _run(sid, "set_transform", {"object_id": oid, "transform": {"position": [5, 0, 0]}}) + out = _run(sid, "add_keyframe", {"object_id": oid, "time": 1.01}) # within 1/24s + assert out["ok"] is True + kfs = out["object"]["keyframes"] + assert len(kfs) == 2 # replaced, not appended + assert kfs[-1]["time"] == 1.01 + assert kfs[-1]["transform"]["position"] == [5.0, 0.0, 0.0] + + +def test_add_keyframe_rejects_bad_time(): + sid = _mk_session() + oid = _add_block(sid) + out = _run(sid, "add_keyframe", {"object_id": oid, "time": 99}) + assert out["ok"] is False + assert "between 0 and 60" in out["error"] + + +def test_update_delete_move_keyframe_roundtrip(): + sid = _mk_session() + oid = _add_block(sid) + added = _run(sid, "add_keyframe", {"object_id": oid, "time": 2.0}) + kf_id = added["object"]["keyframes"][-1]["id"] + + upd = _run( + sid, + "update_keyframe", + {"object_id": oid, "keyframe_id": kf_id, "transform": {"position": [1, 2, 3]}}, + ) + assert upd["ok"] is True + assert upd["object"]["keyframes"][-1]["transform"]["position"] == [1.0, 2.0, 3.0] + + moved = _run(sid, "move_keyframe_time", {"object_id": oid, "keyframe_id": kf_id, "time": 4.0}) + assert moved["ok"] is True + assert moved["object"]["keyframes"][-1]["time"] == 4.0 + + # With two anchors, deletion works… + deleted = _run(sid, "delete_keyframe", {"object_id": oid, "keyframe_id": kf_id}) + assert deleted["ok"] is True + assert len(deleted["object"]["keyframes"]) == 1 + + # …but the last remaining keyframe is protected. + spawn_kf = deleted["object"]["keyframes"][0]["id"] + refuse = _run(sid, "delete_keyframe", {"object_id": oid, "keyframe_id": spawn_kf}) + assert refuse["ok"] is False + assert "last keyframe" in refuse["error"] + + +def test_set_playback_updates_and_validates(): + sid = _mk_session() + out = _run(sid, "set_playback", {"playing": True, "elapsed": 1.5, "speed": 2}) + assert out["ok"] is True + assert out["playback"]["playing"] is True + assert out["playback"]["elapsed"] == 1.5 + assert out["playback"]["speed"] == 2.0 + + bad = _run(sid, "set_playback", {"duration": 120}) + assert bad["ok"] is False + assert "1 and 60" in bad["error"] + + neg = _run(sid, "set_playback", {"elapsed": -1}) + assert neg["ok"] is False + + +# ── captures ─────────────────────────────────────────────────────────────── + + +def test_capture_request_poll_and_fulfill(client): + sid = _mk_session() + comp_id = _run(sid, "get_scene")["shot_id"] + + # Fulfillment races the poll: post the capture in a background task + import threading + import time + + def _fulfill(): + time.sleep(1.0) + c = get_db(settings.db_path) + try: + from fastapi.testclient import TestClient # noqa: F401 + + # Direct DB insert mirrors what the router does (POST is covered + # separately); the poll only checks capture_request_json. + c.execute( + "INSERT INTO shot_capture (composition_id, kind, label, file_path, created_at) " + "VALUES (?, 'image', 't', 'x.png', CURRENT_TIMESTAMP)", + (comp_id,), + ) + c.execute( + "UPDATE shot_composition SET capture_request_json = NULL WHERE id = ?", + (comp_id,), + ) + c.commit() + finally: + c.close() + + threading.Thread(target=_fulfill, daemon=True).start() + out = _run(sid, "request_capture", {"label": "pose ref"}) + assert out["ok"] is True + assert out["file_path"] == "x.png" + + +def test_capture_upload_via_router(client): + sid = _mk_session() + comp_id = _run(sid, "get_scene")["shot_id"] + resp = client.post( + f"/api/shots/{comp_id}/captures", + json={"data_url": _png_data_url(), "label": "ui capture"}, + ) + assert resp.status_code == 200, resp.text + body = resp.json() + assert body["kind"] == "image" + assert Path(body["file_path"]).exists() + assert Path(body["file_path"]).resolve().is_relative_to(Path(settings.assets_dir).resolve()) + + listing = client.get(f"/api/shots/{comp_id}/captures") + assert listing.status_code == 200 + assert any(c["id"] == body["id"] for c in listing.json()) + + # capture_request_json cleared + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT capture_request_json FROM shot_composition WHERE id = ?", (comp_id,) + ).fetchone() + assert row["capture_request_json"] is None + finally: + conn.close() + + +def test_capture_upload_rejects_garbage(client): + sid = _mk_session() + comp_id = _run(sid, "get_scene")["shot_id"] + resp = client.post( + f"/api/shots/{comp_id}/captures", + json={"data_url": "data:image/png;base64,!!!not-base64!!!"}, + ) + assert resp.status_code == 422 + + resp = client.post( + f"/api/shots/{comp_id}/captures", json={"data_url": "hello world"} + ) + assert resp.status_code == 422 + + +# ── router CRUD + validation ─────────────────────────────────────────────── + + +def test_router_scene_validation(client): + sid = _mk_session() + got = client.get(f"/api/shots/by-session/{sid}") + assert got.status_code == 200 + comp = got.json() + + ok = client.patch( + f"/api/shots/{comp['id']}", + json={"scene_json": json.dumps({"objects": [{"id": "a", "type": "cube"}]})}, + ) + assert ok.status_code == 200 + + bad = client.patch( + f"/api/shots/{comp['id']}", + json={"scene_json": json.dumps({"objects": [{"id": "a", "type": "dragon"}]})}, + ) + assert bad.status_code == 422 + + bad = client.patch( + f"/api/shots/{comp['id']}", json={"scene_json": "{not json"} + ) + assert bad.status_code == 422 + + # Title patch + ok = client.patch(f"/api/shots/{comp['id']}", json={"title": "Duel at dawn"}) + assert ok.json()["title"] == "Duel at dawn" + + +def test_delete_capture(client): + sid = _mk_session() + comp_id = _run(sid, "get_scene")["shot_id"] + body = client.post( + f"/api/shots/{comp_id}/captures", json={"data_url": _png_data_url()} + ).json() + resp = client.delete(f"/api/shots/{comp_id}/captures/{body['id']}") + assert resp.status_code == 200 + + +# ── posture init (mannequin-vanish regression) ───────────────────────────── + + +def test_apply_joint_initializes_zeroed_entries(): + from calliope.agent.harness.plugins.shot_builder import _apply_joint, POSTURE_ENTRY_LENGTHS + + obj: dict = {"id": "m1", "type": "male"} + _apply_joint(obj, "l_arm", [0.0, -0.5, 0.2]) + data = obj["posture"]["data"] + assert len(data) == len(POSTURE_ENTRY_LENGTHS) + for i, (entry, expected_len) in enumerate(zip(data, POSTURE_ENTRY_LENGTHS)): + assert isinstance(entry, list) + assert len(entry) == expected_len + if i != 10: # every untouched entry is properly zeroed, not empty + assert all(v == 0.0 for v in entry) + assert data[10] == [0.0, -0.5, 0.2] + + +def test_set_joint_no_empty_arrays_regression(): + # mannequin-js reads fixed-arity entries; an empty array NaNs the figure. + sid = _mk_session() + _run(sid, "get_scene") + obj_id = _run(sid, "add_object", {"type": "female", "name": "Hero"})["object"]["id"] + res = _run(sid, "set_joint", {"object_id": obj_id, "joint": "r_elbow", "values": [0.3]}) + assert res["ok"] is True + scene_obj = _run(sid, "get_scene")["objects"] + obj = next(o for o in scene_obj if o["id"] == obj_id) + entries = obj["posture"]["data"] + from calliope.agent.harness.plugins.shot_builder import POSTURE_ENTRY_LENGTHS + + assert all(len(e) == n for e, n in zip(entries, POSTURE_ENTRY_LENGTHS)) + assert not any(len(e) == 0 for e in entries) + + +# ── video captures ───────────────────────────────────────────────────────── + + +def _video_data_url() -> str: + # Not a real codec payload — the router only validates the MIME + base64. + raw = b"\x1aE\xdf\xa3fake-ebml-header" + b"0" * 256 + return "data:video/webm;base64," + base64.b64encode(raw).decode() + + +def test_video_capture_upload_via_router(client): + sid = _mk_session() + comp_id = _run(sid, "get_scene")["shot_id"] + resp = client.post( + f"/api/shots/{comp_id}/captures", + json={"data_url": _video_data_url(), "label": "camera export"}, + ) + assert resp.status_code == 200, resp.text + body = resp.json() + assert body["kind"] == "video" + assert Path(body["file_path"]).exists() + assert Path(body["file_path"]).suffix == ".webm" + assert Path(body["file_path"]).resolve().is_relative_to(Path(settings.assets_dir).resolve()) + + listing = client.get(f"/api/shots/{comp_id}/captures").json() + mine = next(c for c in listing if c["id"] == body["id"]) + assert mine["kind"] == "video" + + +def test_capture_rejects_unknown_mime(client): + sid = _mk_session() + comp_id = _run(sid, "get_scene")["shot_id"] + resp = client.post( + f"/api/shots/{comp_id}/captures", + json={"data_url": "data:application/pdf;base64," + base64.b64encode(b"%PDF").decode()}, + ) + assert resp.status_code == 422 + + +# ── blind sessions never route through the planner ───────────────────────── + + +def test_blind_session_skips_planner(client): + """Build Scene / sandbox turns go straight to the single loop: the planner + would only misroute to project-scoped sub-agents (no shot tools there).""" + import calliope.agent.harness.orchestrator as orch + + sid = _mk_session() + + class _SpyClient: + instantiated = 0 + + def __init__(self): + type(self).instantiated += 1 + + async def chat(self, *a, **kw): + return json.dumps( + { + "mode": "swarm", + "note": "Scheduling an assets sub-agent...", + "tasks": [{"role": "assets", "goal": "add blocks"}], + } + ) + + async def close(self): + return None + + async def fake_run_turn(ctx, history, *, on_message=None): + return "single-loop answer" + + orig_client = orch.LLMClient + orig_run_turn = orch.run_turn + orch.LLMClient = _SpyClient + orch.run_turn = fake_run_turn + try: + ctx = ToolContext(session_id=sid, project_id=None) + out = asyncio.run(orchestrate(ctx, [], session_id=sid)) + finally: + orch.LLMClient = orig_client + orch.run_turn = orig_run_turn + + assert out == "single-loop answer" + assert _SpyClient.instantiated == 0 diff --git a/calliope-backend/tests/test_video_continue.py b/calliope-backend/tests/test_video_continue.py index 9b24320f..b95890cc 100644 --- a/calliope-backend/tests/test_video_continue.py +++ b/calliope-backend/tests/test_video_continue.py @@ -155,7 +155,10 @@ def test_continue_scene_defers_to_worker_without_clip(client): jobs = asyncio.run(enqueue_video_jobs(pid)) payloads = _job_payloads(pid) assert len(payloads) == 2 - assert payloads[1]["continue_source"] == {"scene_order_index": 2} + assert payloads[1]["continue_source"] == { + "scene_order_index": 2, + "clip_order_index": 1, + } assert "20" not in payloads[1]["input_values"] assert jobs[1]["scene_id"] == scene2["id"] @@ -319,7 +322,10 @@ def test_worker_resolves_continue_source_into_video_node(client, monkeypatch): jobs = asyncio.run(enqueue_video_jobs(pid)) assert len(jobs) == 2 payloads = _job_payloads(pid) - assert payloads[1].get("continue_source") == {"scene_order_index": 2} + assert payloads[1].get("continue_source") == { + "scene_order_index": 2, + "clip_order_index": 1, + } job = _last_job_row(pid) assert job["workflow_id"] == wid @@ -369,10 +375,13 @@ def test_worker_fails_continue_job_without_previous_clip(client, monkeypatch): asyncio.run(enqueue_video_jobs(pid)) payloads = _job_payloads(pid) - assert payloads[1].get("continue_source") == {"scene_order_index": 2} + assert payloads[1].get("continue_source") == { + "scene_order_index": 2, + "clip_order_index": 1, + } job = _last_job_row(pid) - # Run only the continue job: its earlier scene has no clip on disk yet, + # Run only the continue job: its earlier clip has no video on disk yet, # so the worker must fail it with a clear message (the loop records it # via mark_failed + job.failed event). captured: dict = {} @@ -380,8 +389,8 @@ def test_worker_fails_continue_job_without_previous_clip(client, monkeypatch): with pytest.raises(RuntimeError) as excinfo: asyncio.run(queue_worker._run_job(job)) message = str(excinfo.value) - assert "Continue scene 2" in message - assert "previous clip (scene 1) has no video file" in message + assert "Continue clip 2.1" in message + assert "previous clip (scene 1.1) has no video file" in message assert "generate the earlier clip first" in message # Nothing reached ComfyUI. assert captured == {} diff --git a/calliope-backend/tests/test_video_vision.py b/calliope-backend/tests/test_video_vision.py new file mode 100644 index 00000000..28c11b17 --- /dev/null +++ b/calliope-backend/tests/test_video_vision.py @@ -0,0 +1,86 @@ +"""Video-attachment vision tests: attachments project as extracted frames. + +These run against the shared temp-scoped `client` fixture (never the real +DB / assets dir). `skipif` covers machines without ffmpeg/ffprobe on PATH. +""" +from __future__ import annotations + +import shutil +import subprocess + +import pytest + +from calliope.config import settings +from calliope.agent.harness.log import ( + _MAX_VIDEO_FRAMES, + _video_attachment_frames, + project_user_content, +) + +pytestmark = pytest.mark.skipif( + shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None, + reason="ffmpeg/ffprobe not on PATH", +) + + +def _make_test_clip(duration: float = 2.0) -> str: + """Tiny 2s MP4 (color sweep) written under the temp assets dir.""" + settings.assets_dir.mkdir(parents=True, exist_ok=True) + path = settings.assets_dir / "vision-test-clip.mp4" + cmd = [ + shutil.which("ffmpeg"), "-y", "-v", "error", + "-f", "lavfi", "-i", f"testsrc=duration={duration}:size=320x240:rate=10", + "-pix_fmt", "yuv420p", str(path), + ] + subprocess.run(cmd, check=True, capture_output=True, timeout=60) + return str(path) + + +def test_video_attachment_becomes_frame_parts(client): + clip = _make_test_clip() + parts = project_user_content("recreate this fight", attachments=[{"path": clip, "kind": "video", "name": "clip.mp4"}]) + assert isinstance(parts, list) + text = parts[0] + assert text["type"] == "text" + assert "recreate this fight" in text["text"] + assert "[Video frames in order]" in text["text"] + assert "frame at" in text["text"] + image_parts = [p for p in parts if p.get("type") == "image_url"] + assert 1 <= len(image_parts) <= _MAX_VIDEO_FRAMES + for p in image_parts: + assert p["image_url"]["url"].startswith("data:image/jpeg;base64,") + + +def test_frame_timestamps_are_ordered_and_bounded(client): + clip = _make_test_clip(duration=4.0) + frames = _video_attachment_frames(clip) + assert frames, "expected extracted frames" + assert len(frames) <= _MAX_VIDEO_FRAMES + stamps = [ts for ts, _ in frames] + assert stamps == sorted(stamps) + assert all(0 <= ts <= 4.0 for ts in stamps) + + +def test_missing_video_file_degrades_to_text(client): + parts = project_user_content( + "look", + attachments=[{"path": str(settings.assets_dir / "nope.mp4"), "kind": "video"}], + ) + assert isinstance(parts, str) + assert "look" in parts + + +def test_outside_assets_dir_video_is_ignored(client): + parts = project_user_content( + "look", + attachments=[{"path": "C:/Windows/notepad.exe", "kind": "video"}], + ) + assert isinstance(parts, str) + + +def test_audio_kind_stays_text_only(client): + parts = project_user_content( + "listen", + attachments=[{"path": str(settings.assets_dir / "song.mp3"), "kind": "audio"}], + ) + assert isinstance(parts, str) diff --git a/calliope-web/package-lock.json b/calliope-web/package-lock.json index bb5d9fe2..0cf7e0b5 100644 --- a/calliope-web/package-lock.json +++ b/calliope-web/package-lock.json @@ -1,15 +1,18 @@ { "name": "calliope-web", - "version": "1.4.1", + "version": "1.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "calliope-web", - "version": "1.4.1", + "version": "1.5.0", "dependencies": { "@tanstack/svelte-query": "^5.66.0", - "@xyflow/svelte": "^1.6.5" + "@types/three": "0.185.0", + "@xyflow/svelte": "^1.6.5", + "mannequin-js": "5.2.3", + "three": "0.185.1" }, "devDependencies": { "@sveltejs/adapter-static": "^3.0.8", @@ -42,6 +45,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "license": "Apache-2.0" + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", @@ -1326,6 +1335,12 @@ "svelte": "^3.54.0 || ^4.0.0 || ^5.0.0" } }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "license": "MIT" + }, "node_modules/@types/cookie": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", @@ -1405,12 +1420,38 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.185.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.185.0.tgz", + "integrity": "sha512-O2Uy8Cj4Nonr8dWUUbifMdPe8B0Mq7EdOHb89S4+kjUw/KhbjTZrUuYlrQ1bpUKG+EP9QJnN7qNxbHGlGoLHMA==", + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": ">=0.5.17", + "fflate": "~0.8.2", + "meshoptimizer": "~1.1.1" + } + }, "node_modules/@types/trusted-types": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", "license": "MIT" }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "license": "MIT" + }, "node_modules/@xyflow/svelte": { "version": "1.6.5", "resolved": "https://registry.npmjs.org/@xyflow/svelte/-/svelte-1.6.5.tgz", @@ -2397,6 +2438,12 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -2814,6 +2861,12 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/mannequin-js": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/mannequin-js/-/mannequin-js-5.2.3.tgz", + "integrity": "sha512-nAFGMy1WDtX41jKH64K/fAzfMFe/oNkcVxyWzIg5h6b8bisUvDldbJFOFf9HY3ZyRnnOF3MH1AKU+jxI6doHhA==", + "license": "GPL-3.0" + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -2824,6 +2877,12 @@ "node": ">= 8" } }, + "node_modules/meshoptimizer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", + "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", + "license": "MIT" + }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -3959,6 +4018,12 @@ "node": ">=0.8" } }, + "node_modules/three": { + "version": "0.185.1", + "resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz", + "integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==", + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", diff --git a/calliope-web/package.json b/calliope-web/package.json index 5093faa1..e361bdb4 100644 --- a/calliope-web/package.json +++ b/calliope-web/package.json @@ -1,6 +1,6 @@ { "name": "calliope-web", - "version": "1.4.1", + "version": "1.5.0", "private": true, "scripts": { "dev": "vite dev", @@ -29,7 +29,10 @@ }, "dependencies": { "@tanstack/svelte-query": "^5.66.0", - "@xyflow/svelte": "^1.6.5" + "@xyflow/svelte": "^1.6.5", + "mannequin-js": "5.2.3", + "three": "0.185.1", + "@types/three": "0.185.0" }, "type": "module" } diff --git a/calliope-web/src/lib/agentComposer.ts b/calliope-web/src/lib/agentComposer.ts index 6324a042..7a7b9531 100644 --- a/calliope-web/src/lib/agentComposer.ts +++ b/calliope-web/src/lib/agentComposer.ts @@ -3,7 +3,7 @@ */ export type WorkflowKind = 'image' | 'video'; -export type AttachmentKind = 'image' | 'video' | 'audio'; +export type AttachmentKind = 'image' | 'video' | 'audio' | 'document'; export interface WorkflowMention { type: 'workflow'; diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts index b1fbdae6..cc2a2e47 100644 --- a/calliope-web/src/lib/api.ts +++ b/calliope-web/src/lib/api.ts @@ -108,11 +108,12 @@ import type { Job, Scene, SceneVideoSettings, + Clip, Workflow, ComfyDynamicInput, ComfyDynamicOutput, } from './comfy/types'; -export type { Job, Scene, SceneVideoSettings, Workflow, ComfyDynamicInput, ComfyDynamicOutput }; +export type { Job, Scene, SceneVideoSettings, Clip, Workflow, ComfyDynamicInput, ComfyDynamicOutput }; async function api(path: string, init?: RequestInit): Promise { const res = await fetch(`${API_BASE}${path}`, { @@ -206,6 +207,35 @@ export const projects = { method: 'POST', body: JSON.stringify({ scene_ids: sceneIds }), }), + createClip: (projectId: number, sceneId: number, payload: Record) => + api(`/api/projects/${projectId}/scenes/${sceneId}/clips`, { + method: 'POST', + body: JSON.stringify(payload), + }), + updateClip: (projectId: number, clipId: number, payload: Record) => + api(`/api/projects/${projectId}/clips/${clipId}`, { + method: 'PATCH', + body: JSON.stringify(payload), + }), + deleteClip: (projectId: number, clipId: number) => + api<{ ok: boolean }>(`/api/projects/${projectId}/clips/${clipId}`, { method: 'DELETE' }), + reorderClips: (projectId: number, sceneId: number, clipIds: number[]) => + api<{ ok: boolean }>(`/api/projects/${projectId}/scenes/${sceneId}/clips/reorder`, { + method: 'POST', + body: JSON.stringify({ clip_ids: clipIds }), + }), + expandClips: ( + projectId: number, + payload: { scene_ids?: number[]; all?: boolean; guidance?: string } = {}, + ) => + api<{ + ok: boolean; + scenes: Array<{ scene_id: number; clip_count: number; total_duration_sec: number }>; + total_clips: number; + }>(`/api/projects/${projectId}/expand-clips`, { + method: 'POST', + body: JSON.stringify(payload), + }), generateAssets: ( id: number, payload: { @@ -281,6 +311,7 @@ export const jobsApi = { projectId: number, payload: { scene_ids?: number[]; + clip_ids?: number[]; workflow_id?: number; input_values?: Record; prompts?: Record; @@ -292,7 +323,7 @@ export const jobsApi = { }), previewPrompt: ( projectId: number, - payload: { scene_id: number; workflow_id?: number }, + payload: { clip_id?: number; scene_id?: number; workflow_id?: number }, ) => api<{ prompt: string; @@ -309,7 +340,7 @@ export const jobsApi = { export type PlaygroundAttachTarget = 'character_sheet' | 'location' | 'item' | 'scene'; -export type UploadKind = 'image' | 'video' | 'audio'; +export type UploadKind = 'image' | 'video' | 'audio' | 'document'; export interface PlaygroundUpload { ok: boolean; @@ -368,6 +399,8 @@ export interface AgentSession { project_id: number | null; title: string; status: 'idle' | 'running' | 'error'; + /** WHERE the session was born: 'chat' (AI Canvas) or 'scene' (Build Scene rail). */ + origin: 'chat' | 'scene'; created_at: string; updated_at: string; running?: boolean; @@ -407,9 +440,10 @@ export const agentApi = { api( `/api/agent/sessions${projectId != null ? `?project_id=${projectId}` : ''}`, ), + listSceneSessions: () => api('/api/agent/sessions?origin=scene'), listLinkableProjects: () => api<{ id: number; title: string; status: string }[]>('/api/agent/projects'), - createSession: (payload: { title?: string; project_id?: number | null }) => + createSession: (payload: { title?: string; project_id?: number | null; origin?: 'chat' | 'scene' }) => api('/api/agent/sessions', { method: 'POST', body: JSON.stringify(payload), diff --git a/calliope-web/src/lib/assetPicker.ts b/calliope-web/src/lib/assetPicker.ts index a940c48f..fe6a15be 100644 --- a/calliope-web/src/lib/assetPicker.ts +++ b/calliope-web/src/lib/assetPicker.ts @@ -1,5 +1,5 @@ /** Shared shape for Omni / video ref pickers. */ -export type AssetGroup = 'character' | 'location' | 'item' | 'upload' | 'clip'; +export type AssetGroup = 'character' | 'location' | 'item' | 'upload' | 'clip' | 'shot'; export interface AssetOption { label: string; @@ -13,6 +13,7 @@ const GROUP_FROM_SUFFIX: Array<{ re: RegExp; group: AssetGroup }> = [ { re: /\s·\s*environment$/i, group: 'location' }, { re: /\s·\s*item$/i, group: 'item' }, { re: /\s·\s*upload$/i, group: 'upload' }, + { re: /\s·\s*blockout(\s+clip)?$/i, group: 'shot' }, { re: /^clip\s*#/i, group: 'clip' }, ]; @@ -26,13 +27,14 @@ export function assetGroup(opt: AssetOption): AssetGroup { /** 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; + return opt.label.replace(/\s·\s*(sheet|environment|item|upload|blockout(\s+clip)?)\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: 'shot', label: 'From Build Scene' }, { id: 'clip', label: 'Clips' }, { id: 'upload', label: 'Uploads' }, ]; @@ -43,6 +45,6 @@ export function tabsForMediaKind(kind: string | undefined): Array<{ id: AssetGro ? ['clip', 'upload'] : kind === 'audio' ? ['upload'] - : ['character', 'location', 'item', 'upload']; + : ['character', 'location', 'item', 'shot', 'upload']; return ASSET_GROUP_TABS.filter((t) => ids.includes(t.id)); } diff --git a/calliope-web/src/lib/comfy/types.ts b/calliope-web/src/lib/comfy/types.ts index 393e85ab..5518e91c 100644 --- a/calliope-web/src/lib/comfy/types.ts +++ b/calliope-web/src/lib/comfy/types.ts @@ -41,6 +41,8 @@ export interface Job { id: number; project_id: number; scene_id: number | null; + /** Render unit — video jobs are clip jobs (scene_id stays for grouping). */ + clip_id: number | null; kind: string; workflow_id: number | null; status: string; @@ -85,4 +87,23 @@ export interface Scene { portrait_path: string | null; sheet_path: string | null; }>; + clips: Clip[]; +} + +/** Shot unit: one scene expands into 1+ clips; each renders one ~5-10s video. */ +export interface Clip { + id: number; + scene_id: number; + project_id: number; + order_index: number; + description: string | null; + shot_size: string | null; + dialog_lines_covered: number[] | null; + duration_sec: number | null; + workflow_id: number | null; + clip_path: string | null; + chain_from_prev?: number | boolean | null; + video_settings?: SceneVideoSettings | null; + /** '#3.2' — scene 3, clip 2 (display label). */ + label?: string; } diff --git a/calliope-web/src/lib/comfy/useUpload.svelte.ts b/calliope-web/src/lib/comfy/useUpload.svelte.ts index fcca9b87..61f1c619 100644 --- a/calliope-web/src/lib/comfy/useUpload.svelte.ts +++ b/calliope-web/src/lib/comfy/useUpload.svelte.ts @@ -93,5 +93,6 @@ export function truncateMiddle(name: string, max = 32): string { export function acceptForKind(kind: string): string { if (kind === 'audio') return 'audio/*'; if (kind === 'video') return 'video/*,.mp4,.webm,.mov,.mkv'; + if (kind === 'document') return '.txt,.md,.docx'; return 'image/*'; } diff --git a/calliope-web/src/lib/components/AppHeader.svelte b/calliope-web/src/lib/components/AppHeader.svelte index aef36205..6f568c69 100644 --- a/calliope-web/src/lib/components/AppHeader.svelte +++ b/calliope-web/src/lib/components/AppHeader.svelte @@ -1,6 +1,6 @@ - {#if !scene} -

No scene selected.

+ {#if !clip && !scene} +

No clip selected.

{:else if $preview.isPending}
@@ -141,17 +170,22 @@
{:else}
- Scene #{scene.order_index} · {scene.heading || 'Untitled'} + + {#if clip} + Shot {clip.label ?? `#${scene?.order_index ?? ''}`} · {scene?.heading || 'Untitled'} + {:else} + Scene #{scene?.order_index} · {scene?.heading || 'Untitled'} + {/if} + {workflow?.name ?? 'Default workflow'}
{#if stale}
- Saved draft is based on older scene content — regenerate to refresh it. + Saved draft is based on older content — regenerate to refresh it.
{/if} -