Calliope 1.1.0: publish backend, web, and example workflows
This commit is contained in:
+45
@@ -0,0 +1,45 @@
|
||||
# --- Secrets & user data (NEVER commit) ---
|
||||
calliope-backend/calliope_config.json
|
||||
calliope-backend/data/
|
||||
backups/
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
.env
|
||||
.env.*
|
||||
|
||||
# --- Python ---
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
calliope-backend/build/
|
||||
calliope-backend/dist/
|
||||
*.egg-info/
|
||||
|
||||
# --- Node / Svelte ---
|
||||
node_modules/
|
||||
calliope-web/build/
|
||||
calliope-web/.svelte-kit/
|
||||
electron/dist/
|
||||
electron/builder-debug.yml
|
||||
|
||||
# --- Build artifacts (generated, not source) ---
|
||||
calliope-backend/src/calliope/static/
|
||||
*.zip
|
||||
|
||||
# --- Tooling / QA ---
|
||||
.playwright-mcp/
|
||||
.cursor/
|
||||
*.log
|
||||
|
||||
# --- Local-only files (not part of the public repo) ---
|
||||
electron/
|
||||
AGENTS.md
|
||||
start.bat
|
||||
end.bat
|
||||
ScreenShots/
|
||||
docs/
|
||||
prototype/
|
||||
2026-*.md
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
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.
|
||||
|
||||
## Download & run (Windows)
|
||||
## Install — Windows EXE (recommended)
|
||||
|
||||
1. Grab **`Calliope-win-x64.zip`** from the [latest release](../../releases).
|
||||
1. Download **`Calliope-<version>-win-x64.zip`** (e.g. `Calliope-1.1.0-win-x64.zip`) from the [latest release](../../releases).
|
||||
2. Unzip it anywhere writable (avoid `Program Files`).
|
||||
3. Run `win-unpacked\Calliope.exe`.
|
||||
|
||||
No installer, no dev setup. First launch shows a splash while the backend boots. Windows SmartScreen will warn on first run (unsigned binary) — that's expected.
|
||||
No installer, no dev setup. First launch shows a splash while the backend boots. Windows SmartScreen will warn on first run (unsigned binary) — that's expected: click **More info → Run anyway**.
|
||||
|
||||
**Portable:** your projects, database, generated media, and settings live next to the app:
|
||||
|
||||
@@ -19,21 +19,38 @@ No installer, no dev setup. First launch shows a splash while the backend boots.
|
||||
|
||||
Move or copy the whole unzipped folder to relocate the app together with its data.
|
||||
|
||||
<img width="1702" height="1041" alt="Screenshot 2026-07-28 045615" src="https://github.com/user-attachments/assets/e5450a46-d8f9-48fe-8163-5efffaeccb0e" />
|
||||
## Install — from source (npm + Python)
|
||||
|
||||
<img width="1702" height="1049" alt="Screenshot 2026-07-28 052215" src="https://github.com/user-attachments/assets/703c3def-c992-41f7-8fef-bb2c7ef51535" />
|
||||
For development, or if you prefer running the web UI in a browser instead of the Electron shell.
|
||||
|
||||
<img width="1697" height="1047" alt="Screenshot 2026-07-28 052242" src="https://github.com/user-attachments/assets/84618fe3-1f33-4482-bbe1-b8d13866bd96" />
|
||||
**Prerequisites**
|
||||
|
||||
<img width="1686" height="967" alt="Screenshot 2026-07-28 052349" src="https://github.com/user-attachments/assets/193af234-3862-467b-9087-373ffcd26d4a" />
|
||||
- Python 3.11+
|
||||
- Node.js 18+ (npm)
|
||||
- A running ComfyUI install, with the models your workflows need already set up
|
||||
- An OpenAI-compatible LLM endpoint — local (LM Studio, Ollama, etc.) or hosted
|
||||
- ffmpeg on PATH — needed for film export
|
||||
|
||||
**1. Backend (FastAPI)**
|
||||
|
||||
## Requirements
|
||||
```bash
|
||||
cd calliope-backend
|
||||
python -m venv .venv
|
||||
.venv\Scripts\pip install -e ".[dev]"
|
||||
.venv\Scripts\python -m calliope.main --host 127.0.0.1 --port 8247
|
||||
```
|
||||
|
||||
- **Windows 10/11**
|
||||
- **A running ComfyUI install**, with the models your workflows need already set up
|
||||
- **An OpenAI-compatible LLM endpoint** — local (LM Studio, Ollama, etc.) or hosted
|
||||
- **ffmpeg on PATH** — needed for film export
|
||||
Optionally copy `calliope_config.example.json` to `calliope_config.json` and edit it before starting (LLM endpoint, ComfyUI URL). You can also configure everything later in the app's **Settings** page. Never commit `calliope_config.json` — it stores your API key.
|
||||
|
||||
**2. Frontend (SvelteKit)**
|
||||
|
||||
```bash
|
||||
cd calliope-web
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:5173`. The dev server proxies `/api` to the backend on `127.0.0.1:8247`.
|
||||
|
||||
## First run
|
||||
|
||||
@@ -59,7 +76,7 @@ The app walks a project through four stages — **Story, Assets, Script, Video**
|
||||
|
||||
## ComfyUI workflows (important)
|
||||
|
||||
Calliope does **not** hardcode Comfy node IDs. It discovers editable nodes from **role tags** in the node titles of an **API Format** workflow JSON. The `ComfyAPI/` folder in this repo contains ready-to-import example workflows (LTX-2.3 ref2vid, krea2 t2i).
|
||||
Calliope does **not** hardcode Comfy node IDs. It discovers editable nodes from **role tags** in the node titles of an **API Format** workflow JSON. The `example_ComfyUI_workflows/` folder in this repo contains ready-to-import examples (MiniMax H3 reference-to-video, krea2 text-to-image, character sheet).
|
||||
|
||||
### 1. Tag your nodes in ComfyUI
|
||||
|
||||
@@ -95,8 +112,9 @@ Input roles:
|
||||
| `height` | `h` | Shared form / defaults |
|
||||
| `character` | `char`, `portrait`, `sheet`, `face`, `ref` | Character reference path |
|
||||
| `location` | `loc`, `environment`, `env`, `background`, `scene` | Location reference path |
|
||||
| `image` | `img` | Generic image input |
|
||||
| `image` | `img` | Generic image input (ordered ref slot — see below) |
|
||||
| `seed` | — | Shared form |
|
||||
| `duration` | `dur`, `length`, `seconds` | Scene duration (video jobs) |
|
||||
|
||||
Output roles:
|
||||
|
||||
@@ -107,6 +125,18 @@ Output roles:
|
||||
|
||||
Unknown roles still show up in the dynamic form; they just get no special auto-fill. Plain `(Input)` / `(Output)` without a role still works through a deprecated label fallback, so old workflows keep working — but tag new workflows with explicit roles.
|
||||
|
||||
#### Prompt profiles
|
||||
|
||||
Each workflow has a **Prompt format** setting (default *Plain prose*). When set to *MiniMax H3 reference (6-section)*, Calliope rewrites each scene prompt at generation time into MiniMax H3's full-reference format (`subject_definitions` → `summary` → `retention_analysis` → `detailed_description` → `overall_soundscape` → `non_diegetic_music`, with `<Subject N>` labels and `<d>[Language] …</d>` dialogue). It is auto-suggested on import when the workflow contains a `MiniMaxH3*` node.
|
||||
|
||||
For multi-reference workflows, generic `(Input:image)` inputs are filled in **node-id order** — characters in scene order, then the location — and that order defines the `<Subject N>` numbering in the prompt. Keep your ref node ids in the order you want subjects numbered. A `(Input:duration)` node receives the scene's duration in seconds.
|
||||
|
||||
**Using the H3 profile from the scene form (Generate clip):** the form's auto-fill vs. override rule is simple — anything you type or pick wins over the automatic value.
|
||||
|
||||
- **Text Prompt — leave it empty.** An empty field gets the LLM-rewritten six-section H3 prompt built from the scene's action, dialogue, characters, and location. If you type anything, your text is sent verbatim and the model receives plain prose instead of the H3 format.
|
||||
- **Ref 1 / Ref 2 — leave them on "Choose asset…"** to auto-fill from the scene's characters (in scene order) then the location, with `<Subject N>` numbering matched to those slots. Picking an asset manually overrides just that slot (and you take over subject numbering for it).
|
||||
- **Duration** auto-fills from the scene's estimated duration; edit it only when you want a different clip length.
|
||||
|
||||
### 3. Export the workflow
|
||||
|
||||
In ComfyUI, use **Save (API Format)** — not the regular UI workflow graph format. Calliope only understands API Format JSON.
|
||||
@@ -128,6 +158,16 @@ If ComfyUI "doesn't know what to generate" or jobs come back empty:
|
||||
|
||||
Calliope talks to ComfyUI purely over its HTTP API: it uploads reference files with `POST /upload/image`, patches the workflow JSON and queues it via `POST /prompt`, polls `/history/{prompt_id}`, and downloads the results. It **never reads or writes ComfyUI's local `input/` / `output/` folders** — any folder paths stay configured on the ComfyUI side, not in Calliope.
|
||||
|
||||
## Source code
|
||||
## License
|
||||
|
||||
The app source (FastAPI backend, SvelteKit frontend) is not published yet — this repo currently ships the packaged app (via Releases), the Electron shell (`electron/`), and example ComfyUI workflows (`ComfyAPI/`).
|
||||
All rights reserved — © 2026 Calliope contributors.
|
||||
|
||||
## Repo layout
|
||||
|
||||
```text
|
||||
calliope-backend/ FastAPI backend (Python)
|
||||
calliope-web/ SvelteKit frontend
|
||||
example_ComfyUI_workflows/ ready-to-import API-format workflow JSONs
|
||||
```
|
||||
|
||||
The Windows desktop app is built from this repo but not shipped in it — download it from the [Releases](../../releases) page.
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
# PyInstaller spec for the Calliope FastAPI backend (one-folder mode).
|
||||
#
|
||||
# Build (from calliope-backend/):
|
||||
# ./.venv/Scripts/python.exe -m PyInstaller calliope.spec --noconfirm
|
||||
#
|
||||
# Output:
|
||||
# dist/calliope-backend/calliope-backend.exe (+ _internal/ next to it)
|
||||
#
|
||||
# Storage note: when frozen, config.py anchors calliope_config.json and data/
|
||||
# NEXT TO the exe (portable app), so keep this folder user-writable.
|
||||
|
||||
import os
|
||||
|
||||
from PyInstaller.utils.hooks import collect_submodules
|
||||
|
||||
# SPECPATH is the directory containing this spec file (calliope-backend/).
|
||||
BACKEND_DIR = os.path.abspath(SPECPATH)
|
||||
|
||||
# Fresh SvelteKit adapter-static build. Bundled as calliope/static so the frozen
|
||||
# exe serves the SPA at its own origin (main.py mounts <package>/static at /).
|
||||
WEB_BUILD = os.path.abspath(os.path.join(BACKEND_DIR, "..", "calliope-web", "build"))
|
||||
|
||||
# main.py imports uvicorn dynamically via __import__("uvicorn"), which static
|
||||
# analysis cannot see — collect all uvicorn submodules (lifespan/loops/protocols)
|
||||
# plus its optional speedups and other lazily-imported packages explicitly.
|
||||
hidden = collect_submodules("uvicorn")
|
||||
hidden += ["httptools", "websockets", "multipart", "dotenv"]
|
||||
|
||||
|
||||
a = Analysis(
|
||||
# launcher.py imports calliope.main as a package module — see its docstring
|
||||
# for why the entry must NOT be src/calliope/main.py itself.
|
||||
[os.path.join(BACKEND_DIR, "launcher.py")],
|
||||
pathex=[BACKEND_DIR, os.path.join(BACKEND_DIR, "src")],
|
||||
binaries=[],
|
||||
datas=[(WEB_BUILD, "calliope/static")],
|
||||
hiddenimports=hidden,
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=["pytest", "pytest_asyncio", "ruff"],
|
||||
noarchive=False,
|
||||
)
|
||||
pyz = PYZ(a.pure, a.zipped_data)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name="calliope-backend",
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=False, # faster builds, fewer antivirus false-positives
|
||||
# Console stays ON so a user can run calliope-backend.exe from a terminal and
|
||||
# read uvicorn/ComfyUI error logs when debugging. The Electron shell always
|
||||
# spawns it with windowsHide=True, so no console window appears in normal use.
|
||||
console=True,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
)
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.zipfiles,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
upx_exclude=[],
|
||||
name="calliope-backend",
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"host": "127.0.0.1",
|
||||
"port": 8247,
|
||||
"data_dir": "./data",
|
||||
"assets_dir": "./data/assets",
|
||||
"db_name": "calliope.db",
|
||||
"llm_base_url": "http://127.0.0.1:11434/v1",
|
||||
"llm_model": "Qwen3.8-27B",
|
||||
"llm_api_key": "",
|
||||
"comfyui_base_url": "http://127.0.0.1:8188",
|
||||
"queue_concurrency": 1,
|
||||
"queue_poll_interval_sec": 2.0,
|
||||
"queue_max_retries": 4,
|
||||
"dry_run": false
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"""PyInstaller entry point for the Calliope backend.
|
||||
|
||||
Why this exists: using src/calliope/main.py directly as the frozen entry script
|
||||
makes PyInstaller bundle it as a TOP-LEVEL module named "main", so its __file__
|
||||
becomes <_MEIPASS>/main.pyc and main.py's __file__-relative lookup of the
|
||||
bundled SPA (<package>/static) breaks. Importing calliope.main as a package
|
||||
module here keeps its __file__ at <_MEIPASS>/calliope/main.pyc, so
|
||||
Path(__file__).parent / "static" resolves to the bundled calliope/static.
|
||||
|
||||
Dev flow is unaffected (python -m calliope.main still works); this file is only
|
||||
used by calliope.spec.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from calliope.main import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,34 @@
|
||||
[project]
|
||||
name = "calliope"
|
||||
version = "1.1.0"
|
||||
description = "Local-first AI story-to-video studio"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"fastapi>=0.115.0",
|
||||
"uvicorn[standard]>=0.32.0",
|
||||
"aiosqlite>=0.20.0",
|
||||
"pydantic>=2.9.0",
|
||||
"pydantic-settings>=2.6.0",
|
||||
"httpx>=0.27.0",
|
||||
"python-multipart>=0.0.12",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=8.3.0", "pytest-asyncio>=0.24.0", "ruff>=0.8.0"]
|
||||
|
||||
[project.scripts]
|
||||
calliope = "calliope.main:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
src = ["src"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "N", "W"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
@@ -0,0 +1,13 @@
|
||||
# Calliope Backend — runtime dependencies
|
||||
fastapi>=0.115.0
|
||||
uvicorn[standard]>=0.32.0
|
||||
aiosqlite>=0.20.0
|
||||
pydantic>=2.9.0
|
||||
pydantic-settings>=2.6.0
|
||||
httpx>=0.27.0
|
||||
python-multipart>=0.0.12
|
||||
|
||||
# Dev dependencies
|
||||
pytest>=8.3.0
|
||||
pytest-asyncio>=0.24.0
|
||||
ruff>=0.8.0
|
||||
@@ -0,0 +1 @@
|
||||
# Calliope backend package
|
||||
@@ -0,0 +1 @@
|
||||
# Agentic layer for Calliope
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Enqueue character/location image generation jobs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.prompts import character_image_prompt, location_image_prompt
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs
|
||||
from calliope.comfyui.smart_fill import smart_fill_inputs
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
|
||||
def _has_text_inputs(inputs: list[dict[str, Any]]) -> bool:
|
||||
return any(inp.get("kind") in ("text", "textarea") for inp in inputs)
|
||||
|
||||
|
||||
def _sanitize_input_overrides(extra: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""Drop null/blank overrides so empty shared Text Prompt cannot wipe the entity prompt."""
|
||||
if not extra:
|
||||
return None
|
||||
cleaned: dict[str, Any] = {}
|
||||
for k, v in extra.items():
|
||||
if v is None:
|
||||
continue
|
||||
if isinstance(v, str) and not v.strip():
|
||||
continue
|
||||
cleaned[str(k)] = v
|
||||
return cleaned or None
|
||||
|
||||
|
||||
def _get_enabled_workflow(kind: str = "image", workflow_id: int | None = None) -> dict[str, Any] | None:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if workflow_id:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE id = ? AND is_enabled = 1", (workflow_id,)
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE kind = ? AND is_enabled = 1 ORDER BY id ASC LIMIT 1",
|
||||
(kind,),
|
||||
).fetchone()
|
||||
return row_to_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
async def enqueue_asset_jobs(
|
||||
project_id: int,
|
||||
*,
|
||||
character_ids: list[int] | None = None,
|
||||
location_ids: list[int] | None = None,
|
||||
missing_only: bool = True,
|
||||
workflow_id: int | None = None,
|
||||
input_values_override: dict[str, Any] | None = None,
|
||||
asset_target: str = "sheet",
|
||||
prompt_override: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{"message": "Preparing asset generation from saved image prompts…", "project_id": project_id},
|
||||
)
|
||||
workflow = _get_enabled_workflow("image", workflow_id)
|
||||
workflow_json = json.loads(workflow["workflow_json"]) if workflow else {}
|
||||
inputs = parse_dynamic_inputs(workflow_json) if workflow_json else []
|
||||
target = asset_target if asset_target in {"sheet", "portrait"} else "sheet"
|
||||
input_values_override = _sanitize_input_overrides(input_values_override)
|
||||
has_override = bool(input_values_override)
|
||||
allow_empty_prompt = has_override or not _has_text_inputs(inputs)
|
||||
|
||||
conn = get_db(settings.db_path)
|
||||
jobs: list[dict[str, Any]] = []
|
||||
skipped: list[str] = []
|
||||
try:
|
||||
chars = conn.execute(
|
||||
"SELECT * FROM characters WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
locs = conn.execute(
|
||||
"SELECT * FROM locations WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
|
||||
for row in chars:
|
||||
c = row_to_dict(row)
|
||||
if character_ids is not None and c["id"] not in character_ids:
|
||||
continue
|
||||
existing = c.get("sheet_path") if target == "sheet" else c.get("portrait_path")
|
||||
if missing_only and existing:
|
||||
continue
|
||||
prompt = (prompt_override or "").strip() or character_image_prompt(c, kind=target)
|
||||
if not prompt.strip() and not allow_empty_prompt:
|
||||
skipped.append(c.get("name") or str(c["id"]))
|
||||
continue
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt or None,
|
||||
extra=input_values_override,
|
||||
)
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind="image",
|
||||
workflow_id=workflow["id"] if workflow else None,
|
||||
payload={
|
||||
"input_values": values,
|
||||
"character_id": c["id"],
|
||||
"asset_target": target,
|
||||
"prompt": prompt,
|
||||
},
|
||||
)
|
||||
jobs.append(job)
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": "image",
|
||||
"message": f"{c.get('name')} · {target}",
|
||||
},
|
||||
)
|
||||
|
||||
# Only enqueue locations when not doing a character-only generate
|
||||
enqueue_locs = location_ids is not None or character_ids is None
|
||||
if enqueue_locs:
|
||||
for row in locs:
|
||||
loc = row_to_dict(row)
|
||||
if location_ids is not None and loc["id"] not in location_ids:
|
||||
continue
|
||||
if character_ids is not None and location_ids is None:
|
||||
# Character-scoped call — skip locations
|
||||
continue
|
||||
if missing_only and loc.get("reference_image_path"):
|
||||
continue
|
||||
prompt = (prompt_override or "").strip() or location_image_prompt(loc)
|
||||
if not prompt.strip() and not allow_empty_prompt:
|
||||
skipped.append(loc.get("name") or str(loc["id"]))
|
||||
continue
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt or None,
|
||||
extra=input_values_override,
|
||||
)
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind="image",
|
||||
workflow_id=workflow["id"] if workflow else None,
|
||||
payload={
|
||||
"input_values": values,
|
||||
"location_id": loc["id"],
|
||||
"prompt": prompt,
|
||||
},
|
||||
)
|
||||
jobs.append(job)
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": "image",
|
||||
"message": f"{loc.get('name')} · environment",
|
||||
},
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if skipped:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"message": f"Skipped (empty image prompt): {', '.join(skipped)}",
|
||||
},
|
||||
)
|
||||
return jobs
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from calliope.config import settings
|
||||
|
||||
logger = logging.getLogger("calliope.llm")
|
||||
|
||||
|
||||
class LLMClient:
|
||||
def __init__(self) -> None:
|
||||
self.base_url = settings.llm_base_url.rstrip("/")
|
||||
self.model = settings.llm_model
|
||||
self.api_key = settings.llm_api_key
|
||||
self.client = httpx.AsyncClient(timeout=120.0)
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
return headers
|
||||
|
||||
async def chat(self, messages: list[dict[str, str]], temperature: float = 0.7, response_format: dict[str, str] | None = None) -> str:
|
||||
payload: dict[str, Any] = {
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
}
|
||||
if response_format:
|
||||
payload["response_format"] = response_format
|
||||
|
||||
url = f"{self.base_url}/chat/completions"
|
||||
logger.info("LLM request to %s with model %s", url, self.model)
|
||||
resp = await self.client.post(url, headers=self._headers(), json=payload)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
content = data["choices"][0]["message"]["content"]
|
||||
return content.strip()
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.client.aclose()
|
||||
|
||||
|
||||
def extract_json(text: str) -> dict[str, Any]:
|
||||
"""Extract JSON object from a markdown code block or raw text."""
|
||||
text = text.strip()
|
||||
if text.startswith("```"):
|
||||
# Strip fenced code block
|
||||
lines = text.splitlines()
|
||||
if lines[0].startswith("```"):
|
||||
lines = lines[1:]
|
||||
if lines and lines[-1].startswith("```"):
|
||||
lines = lines[:-1]
|
||||
text = "\n".join(lines).strip()
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
async def generate_structured(messages: list[dict[str, str]], temperature: float = 0.7) -> dict[str, Any]:
|
||||
client = LLMClient()
|
||||
try:
|
||||
response_format = {"type": "json_object"}
|
||||
text = await client.chat(messages, temperature=temperature, response_format=response_format)
|
||||
return extract_json(text)
|
||||
finally:
|
||||
await client.close()
|
||||
@@ -0,0 +1,489 @@
|
||||
"""Prompts for Calliope story / script / asset generation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
STORY_GENERATION_SYSTEM = (
|
||||
"You are a story development assistant for an AI video studio. "
|
||||
"You output ONLY a single valid JSON object. "
|
||||
"HARD RULE: the beats array length must equal required_beat_count from the user message. "
|
||||
"Returning fewer beats is a failure. Longer target runtimes require many fine-grained beats."
|
||||
)
|
||||
|
||||
SCRIPT_GENERATION_SYSTEM = (
|
||||
"You are a screenwriter for short-form AI video. "
|
||||
"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. "
|
||||
"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_target_seconds(target_duration: str | None) -> int:
|
||||
"""Best-effort parse of free-text duration into seconds."""
|
||||
text = (target_duration or "").strip().lower()
|
||||
if not text:
|
||||
return 30
|
||||
|
||||
# Explicit "N scenes" -> ~8s each as a coarse floor for beat planning
|
||||
scenes_m = re.search(r"(\d+)\s*scenes?", text)
|
||||
if scenes_m and "min" not in text and "sec" not in text:
|
||||
return max(30, int(scenes_m.group(1)) * 8)
|
||||
|
||||
minutes = 0.0
|
||||
seconds = 0.0
|
||||
for m in re.finditer(r"(\d+(?:\.\d+)?)\s*(min|mins|minutes?|m)\b", text):
|
||||
minutes += float(m.group(1))
|
||||
for m in re.finditer(r"(\d+(?:\.\d+)?)\s*(sec|secs|seconds?|s)\b", text):
|
||||
seconds += float(m.group(1))
|
||||
|
||||
if minutes or seconds:
|
||||
return max(15, int(minutes * 60 + seconds))
|
||||
|
||||
bare = re.search(r"\b(\d+(?:\.\d+)?)\b", text)
|
||||
if bare:
|
||||
n = float(bare.group(1))
|
||||
if "medium" in text or n >= 2:
|
||||
if n <= 30:
|
||||
return int(n * 60)
|
||||
if n <= 180:
|
||||
return int(n)
|
||||
|
||||
if "medium" in text:
|
||||
return 120
|
||||
if "short" in text or "brief" in text:
|
||||
return 30
|
||||
if "long" in text or "feature" in text:
|
||||
return 180
|
||||
return 60
|
||||
|
||||
|
||||
def recommend_beat_count(target_duration: str | None) -> int:
|
||||
"""
|
||||
Story beats for the AI video pipeline (~12s of narrative weight each).
|
||||
30s -> 4, 2 min -> 10, 5 min -> 25, 10 min -> 50 (capped at 60).
|
||||
"""
|
||||
secs = estimate_target_seconds(target_duration)
|
||||
return max(4, min(60, round(secs / 12)))
|
||||
|
||||
|
||||
def recommend_scene_count(target_duration: str | None) -> int:
|
||||
"""Video scenes (~7s each) for the target runtime."""
|
||||
secs = estimate_target_seconds(target_duration)
|
||||
return max(4, min(90, round(secs / 7)))
|
||||
|
||||
|
||||
def story_generation_user_prompt(
|
||||
title: str | None,
|
||||
idea: str | None,
|
||||
genre: str | None,
|
||||
tone: str | None,
|
||||
target_duration: str | None,
|
||||
) -> str:
|
||||
secs = estimate_target_seconds(target_duration)
|
||||
beat_n = recommend_beat_count(target_duration)
|
||||
return f"""Create a story brief for an AI-generated video.
|
||||
|
||||
required_beat_count: {beat_n}
|
||||
estimated_runtime_seconds: {secs}
|
||||
target_duration_text: {target_duration or "short (~30 seconds)"}
|
||||
|
||||
Title: {title or "Untitled"}
|
||||
Idea: {idea or "No idea provided."}
|
||||
Genre: {genre or "Not specified"}
|
||||
Tone: {tone or "cinematic, atmospheric"}
|
||||
|
||||
=== HARD CONSTRAINTS (non-negotiable) ===
|
||||
1. The JSON field "beats" MUST contain EXACTLY {beat_n} objects.
|
||||
2. order_index must run 1, 2, 3, ... {beat_n} with no gaps.
|
||||
3. Do NOT summarize into a short arc. Do NOT return 5-8 beats for a long runtime.
|
||||
4. For ~{secs}s (~{secs // 60} min), beats are fine-grained plot steps (~12 seconds of story weight each) so Script can later expand into many short video clips.
|
||||
5. Cover full arc across all {beat_n} beats: setup, rising complications, midpoint turn, escalation, climax, resolution — spread across the whole list, not compressed into the first few items.
|
||||
6. If you are unsure, add more concrete incident beats rather than fewer abstract ones.
|
||||
|
||||
=== OUTPUT SCHEMA (JSON only) ===
|
||||
{{
|
||||
"title": "a compelling story title",
|
||||
"logline": "one sentence hook",
|
||||
"beats": [
|
||||
{{"order_index": 1, "title": "Beat title", "description": "what happens visually / dramatically"}}
|
||||
],
|
||||
"characters": [
|
||||
{{
|
||||
"name": "Name",
|
||||
"role": "protagonist|antagonist|supporting",
|
||||
"age": "approximate age",
|
||||
"appearance": "concise visual description for image generation",
|
||||
"personality": "concise personality traits"
|
||||
}}
|
||||
],
|
||||
"locations": [
|
||||
{{
|
||||
"name": "Location name",
|
||||
"description": "concise visual description for image generation"
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
Keep descriptions visual and concrete. Characters and locations should be reusable across scenes.
|
||||
FINAL CHECK before responding: beats.length == {beat_n}. If not, fix it."""
|
||||
|
||||
|
||||
def build_story_messages(
|
||||
title: str | None,
|
||||
idea: str | None,
|
||||
genre: str | None,
|
||||
tone: str | None,
|
||||
target_duration: str | None,
|
||||
) -> list[dict[str, str]]:
|
||||
return [
|
||||
{"role": "system", "content": STORY_GENERATION_SYSTEM},
|
||||
{
|
||||
"role": "user",
|
||||
"content": story_generation_user_prompt(title, idea, genre, tone, target_duration),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def build_script_messages(
|
||||
*,
|
||||
title: str,
|
||||
idea: str | None,
|
||||
beats: list[dict[str, Any]],
|
||||
characters: list[dict[str, Any]],
|
||||
locations: list[dict[str, Any]],
|
||||
target_duration: str | None,
|
||||
scene_count: int | None = None,
|
||||
) -> list[dict[str, str]]:
|
||||
secs = estimate_target_seconds(target_duration)
|
||||
recommended = recommend_scene_count(target_duration)
|
||||
# Honor an explicit / existing count (e.g. user added empty scenes before regenerate)
|
||||
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
|
||||
)
|
||||
loc_lines = "\n".join(
|
||||
f"- id={l['id']} {l['name']}: {l.get('description') or ''}" for l in locations
|
||||
)
|
||||
beat_lines = "\n".join(
|
||||
f"- {b.get('order_index')}. {b.get('title')}: {b.get('description')}" for b in beats
|
||||
)
|
||||
user = f"""Write a scene script for this project.
|
||||
|
||||
Title: {title}
|
||||
Idea: {idea or ''}
|
||||
Target duration: {target_duration or 'short (~30-60 seconds)'}
|
||||
Estimated runtime: ~{secs} seconds
|
||||
required_scene_count: {scene_n}
|
||||
|
||||
Story beats:
|
||||
{beat_lines or '(none)'}
|
||||
|
||||
Characters:
|
||||
{char_lines or '(none)'}
|
||||
|
||||
Locations:
|
||||
{loc_lines or '(none)'}
|
||||
|
||||
=== 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.
|
||||
|
||||
=== 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
|
||||
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
|
||||
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.
|
||||
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".
|
||||
|
||||
Respond ONLY with JSON:
|
||||
{{
|
||||
"scenes": [
|
||||
{{
|
||||
"order_index": 1,
|
||||
"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,
|
||||
"character_ids": [1],
|
||||
"location_id": 1
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
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."""
|
||||
return [
|
||||
{"role": "system", "content": SCRIPT_GENERATION_SYSTEM},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
|
||||
|
||||
def character_sheet_prompt(character: dict[str, Any]) -> str:
|
||||
"""Transparent character-sheet template — what ComfyUI receives for turnarounds."""
|
||||
name = (character.get("name") or "Unnamed").strip()
|
||||
role = (character.get("role") or "character").strip()
|
||||
age = (character.get("age") or "unspecified age").strip()
|
||||
appearance = (character.get("appearance") or "no appearance notes yet").strip()
|
||||
personality = (character.get("personality") or "").strip()
|
||||
personality_line = f"Personality cues (visual only): {personality}\n" if personality else ""
|
||||
return (
|
||||
f"CHARACTER SHEET — {name}\n"
|
||||
f"Role: {role}. Age: {age}.\n"
|
||||
f"Appearance: {appearance}\n"
|
||||
f"{personality_line}"
|
||||
f"\n"
|
||||
f"Layout: single cinematic character reference sheet on a clean neutral backdrop, "
|
||||
f"multiple panels — front full body, side full body, back full body, three-quarter, "
|
||||
f"and a head close-up. Same face, hair, body proportions, and outfit in every panel. "
|
||||
f"Neutral standing pose, even studio lighting, high detail, no text watermarks, "
|
||||
f"no extra characters."
|
||||
)
|
||||
|
||||
|
||||
def character_portrait_prompt(character: dict[str, Any]) -> str:
|
||||
"""Transparent portrait template — face/upper-body lock for consistency."""
|
||||
name = (character.get("name") or "Unnamed").strip()
|
||||
role = (character.get("role") or "character").strip()
|
||||
age = (character.get("age") or "unspecified age").strip()
|
||||
appearance = (character.get("appearance") or "no appearance notes yet").strip()
|
||||
return (
|
||||
f"CHARACTER PORTRAIT — {name}\n"
|
||||
f"Role: {role}. Age: {age}.\n"
|
||||
f"Appearance: {appearance}\n"
|
||||
f"\n"
|
||||
f"Shot: cinematic head-and-shoulders portrait, eye-level, soft key light, "
|
||||
f"shallow depth of field, sharp facial features, consistent wardrobe collar/shoulders, "
|
||||
f"plain muted background, photoreal or high-end concept art, no text."
|
||||
)
|
||||
|
||||
|
||||
def location_reference_prompt(location: dict[str, Any]) -> str:
|
||||
"""Transparent environment reference template."""
|
||||
name = (location.get("name") or "Unnamed place").strip()
|
||||
description = (location.get("description") or "no description yet").strip()
|
||||
return (
|
||||
f"ENVIRONMENT REFERENCE — {name}\n"
|
||||
f"Description: {description}\n"
|
||||
f"\n"
|
||||
f"Shot: wide establishing concept art, cinematic atmosphere, clear readable space "
|
||||
f"for characters to stand in, consistent lighting and materials, no people, no text."
|
||||
)
|
||||
|
||||
|
||||
def character_image_prompt(character: dict[str, Any], *, kind: str = "sheet") -> str:
|
||||
"""
|
||||
Prefer the user-edited consistency_prompt when present.
|
||||
Otherwise fill the published template (never invent a hidden LLM prompt).
|
||||
"""
|
||||
saved = (character.get("consistency_prompt") or "").strip()
|
||||
if saved:
|
||||
return saved
|
||||
if kind == "portrait":
|
||||
return character_portrait_prompt(character)
|
||||
return character_sheet_prompt(character)
|
||||
|
||||
|
||||
def location_image_prompt(location: dict[str, Any]) -> str:
|
||||
saved = (location.get("consistency_prompt") or "").strip()
|
||||
if saved:
|
||||
return saved
|
||||
return location_reference_prompt(location)
|
||||
|
||||
|
||||
def scene_video_prompt(scene: dict[str, Any], characters: list[dict[str, Any]]) -> str:
|
||||
char_bits = ", ".join(
|
||||
f"{c.get('name')}: {c.get('consistency_prompt') or c.get('appearance') or ''}"
|
||||
for c in characters
|
||||
)
|
||||
parts = [
|
||||
scene.get("heading") or "",
|
||||
scene.get("action") or "",
|
||||
f"featuring {char_bits}" if char_bits else "",
|
||||
"cinematic motion, coherent continuity",
|
||||
]
|
||||
return ". ".join(p for p in parts if p)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MiniMax H3 full-reference (ref2video) prompt profile
|
||||
# ---------------------------------------------------------------------------
|
||||
# Condensed from MiniMax's VIDEO_PROMPT_WRITING_GUIDE_ref_en.md, adapted to
|
||||
# Calliope's single-scene clips: each subject's reference image is wired into
|
||||
# the workflow's generic (Input:image) slots in node-id order, and that order
|
||||
# defines the <Subject N> / <Picture N> numbering below.
|
||||
|
||||
MINIMAX_H3_REF_SYSTEM = (
|
||||
"You rewrite scene descriptions into MiniMax H3's full-reference video prompt format. "
|
||||
"Output ONLY the rewritten prompt as plain text — no markdown fences, no commentary. "
|
||||
"The output must contain exactly these six sections in this order, each starting with "
|
||||
"its header on its own line:\n"
|
||||
"subject_definitions:\n"
|
||||
"summary:\n"
|
||||
"retention_analysis:\n"
|
||||
"detailed_description:\n"
|
||||
"overall_soundscape:\n"
|
||||
"non_diegetic_music:\n"
|
||||
"\n"
|
||||
"Rules:\n"
|
||||
"1. subject_definitions: one line per referenced subject supplied in the user message, "
|
||||
"keeping its exact <Subject N> index. Form: '<Subject N> is the <description> in "
|
||||
"<Picture N>, with <key visual features to preserve>.' <Picture N> is the reference "
|
||||
"image wired to slot N — cite it inside the subject line, never as a standalone entry.\n"
|
||||
"2. summary: one short English paragraph starting with '[reference generation]' that "
|
||||
"states what happens using the <Subject N> labels.\n"
|
||||
"3. retention_analysis: one line per subject: '<Subject N> (appears in [Shot 1]…): "
|
||||
"fully_preserved - <which defined features are retained>.'\n"
|
||||
"4. detailed_description: the main body, 120–300 words. Open with one or two style "
|
||||
"sentences (lighting, palette, medium) BEFORE '[Shot 1]'. '[Shot 1]' has no timestamp; "
|
||||
"later cuts use '[Shot N] At MM:SS.mmm, …'. For clips under ~8 seconds prefer a single "
|
||||
"shot. Introduce each <Subject N> at its first visible appearance with its referenced "
|
||||
"features, position, and action; reuse the label afterwards. Describe only what is "
|
||||
"visible except sound/dialogue.\n"
|
||||
"5. Dialogue: give each speaker a stable ID in order of first speech — '<Subject N> (S1) "
|
||||
"says, <d>[English] …</d>'. A speaker with no defined subject uses a stable voice "
|
||||
"description, e.g. 'A narrator (S2) says, <d>[English] …</d>'. Keep the original "
|
||||
"language of every line inside <d> and tag it, e.g. [English], [Chinese].\n"
|
||||
"6. overall_soundscape: ambience and physical sounds across the clip, or 'N/A'. "
|
||||
"non_diegetic_music: audience-only score (instrumentation, tempo), or 'N/A'.\n"
|
||||
"Write everything in English except dialogue/lyrics inside <d> and visible on-screen text."
|
||||
)
|
||||
|
||||
|
||||
def _subject_roster_lines(subjects: list[dict[str, Any]]) -> str:
|
||||
lines = []
|
||||
for s in subjects:
|
||||
lines.append(
|
||||
f"<Subject {s['index']}> = {s['kind']} \"{s.get('name') or 'unnamed'}\" "
|
||||
f"(reference image slot {s['index']}): {s.get('appearance') or 'no description'}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_minimax_h3_ref_messages(
|
||||
scene: dict[str, Any], subjects: list[dict[str, Any]]
|
||||
) -> list[dict[str, str]]:
|
||||
"""LLM messages that rewrite a scene into H3's six-section ref format.
|
||||
|
||||
subjects: ordered roster — index N corresponds to ref image slot N.
|
||||
"""
|
||||
roster = _subject_roster_lines(subjects) or (
|
||||
"(no reference images — describe subjects from the action text)"
|
||||
)
|
||||
user = f"""Rewrite this scene into MiniMax H3 full-reference format.
|
||||
|
||||
Scene heading: {scene.get('heading') or '(none)'}
|
||||
Scene duration: ~{scene.get('duration_sec') or 6} seconds
|
||||
|
||||
Action (visual base for detailed_description):
|
||||
{scene.get('action') or '(none)'}
|
||||
|
||||
Dialogue (raw 'SPEAKER: line' format; optional '(delivery cue)' after the speaker —
|
||||
map speakers to subjects by name and keep cues as delivery direction):
|
||||
{scene.get('dialog') or '(none)'}
|
||||
|
||||
Referenced subjects (keep these exact indices):
|
||||
{roster}
|
||||
"""
|
||||
return [
|
||||
{"role": "system", "content": MINIMAX_H3_REF_SYSTEM},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
|
||||
|
||||
def minimax_h3_ref_fallback(scene: dict[str, Any], subjects: list[dict[str, Any]]) -> str:
|
||||
"""Deterministic six-section H3 prompt — used when the LLM rewrite fails."""
|
||||
defs = []
|
||||
retention = []
|
||||
for s in subjects:
|
||||
name = s.get("name") or "unnamed"
|
||||
desc = (s.get("appearance") or "").strip()
|
||||
defs.append(
|
||||
f"<Subject {s['index']}> is the {s['kind']} \"{name}\" in "
|
||||
f"<Picture {s['index']}>" + (f", {desc}." if desc else ".")
|
||||
)
|
||||
retention.append(
|
||||
f"<Subject {s['index']}> (appears in [Shot 1]): fully_preserved - "
|
||||
f"the referenced appearance of \"{name}\" is retained."
|
||||
)
|
||||
|
||||
heading = (scene.get("heading") or "").strip()
|
||||
action = (scene.get("action") or "").strip()
|
||||
labels = ", ".join(f"<Subject {s['index']}>" for s in subjects)
|
||||
summary = (
|
||||
f"[reference generation] {heading or 'A scene'} featuring {labels}."
|
||||
if labels
|
||||
else f"[reference generation] {heading or 'A scene'}."
|
||||
)
|
||||
|
||||
body = (
|
||||
"The target video is in a cinematic style consistent with the reference images, "
|
||||
"with coherent lighting and natural motion.\n"
|
||||
f"[Shot 1] {heading} {action}".strip()
|
||||
)
|
||||
|
||||
# Map 'SPEAKER: line' rows onto subjects by name; assign speaker IDs in speech order.
|
||||
# An optional delivery cue — 'MIA (whispering): line' — is kept as performance direction.
|
||||
dialog_lines = []
|
||||
speaker_ids: dict[str, int] = {}
|
||||
name_to_subject = {(s.get("name") or "").strip().lower(): s["index"] for s in subjects}
|
||||
for raw in (scene.get("dialog") or "").splitlines():
|
||||
if ":" not in raw:
|
||||
continue
|
||||
speaker, line = raw.split(":", 1)
|
||||
speaker, line = speaker.strip(), line.strip()
|
||||
if not line:
|
||||
continue
|
||||
cue_m = re.search(r"\(([^)]*)\)\s*$", speaker)
|
||||
cue = cue_m.group(1).strip() if cue_m else ""
|
||||
base = re.sub(r"\s*\([^)]*\)\s*$", "", speaker).strip() or speaker
|
||||
key = base.lower()
|
||||
if key not in speaker_ids:
|
||||
speaker_ids[key] = len(speaker_ids) + 1
|
||||
sid = speaker_ids[key]
|
||||
subj_idx = name_to_subject.get(key)
|
||||
who = f"<Subject {subj_idx}> (S{sid})" if subj_idx else f"{base.title()} (S{sid})"
|
||||
dialog_lines.append(f"{who} says{f' {cue}' if cue else ''}, <d>[English] {line}</d>")
|
||||
if dialog_lines:
|
||||
body += "\n" + "\n".join(dialog_lines)
|
||||
|
||||
return (
|
||||
"subject_definitions:\n" + ("\n".join(defs) if defs else "N/A") + "\n\n"
|
||||
"summary:\n" + summary + "\n\n"
|
||||
"retention_analysis:\n" + ("\n".join(retention) if retention else "N/A") + "\n\n"
|
||||
"detailed_description:\n" + body + "\n\n"
|
||||
"overall_soundscape:\nN/A\n\n"
|
||||
"non_diegetic_music:\nN/A"
|
||||
)
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Generate scene scripts via LLM and persist them."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.llm import generate_structured
|
||||
from calliope.agent.prompts import build_script_messages, recommend_scene_count
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
|
||||
|
||||
def _persist_scenes(
|
||||
conn,
|
||||
project_id: int,
|
||||
scenes: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
created: list[dict[str, Any]] = []
|
||||
for scene in scenes:
|
||||
loc_id = scene.get("location_id")
|
||||
env_path = None
|
||||
if loc_id:
|
||||
loc = conn.execute(
|
||||
"SELECT reference_image_path FROM locations WHERE id = ? AND project_id = ?",
|
||||
(loc_id, project_id),
|
||||
).fetchone()
|
||||
if loc:
|
||||
env_path = loc["reference_image_path"]
|
||||
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO scenes
|
||||
(project_id, order_index, heading, action, dialog, duration_sec, location_id, env_image_path)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
project_id,
|
||||
scene.get("order_index", 0),
|
||||
scene.get("heading"),
|
||||
scene.get("action"),
|
||||
scene.get("dialog"),
|
||||
scene.get("duration_sec"),
|
||||
loc_id,
|
||||
env_path,
|
||||
),
|
||||
)
|
||||
scene_id = cur.lastrowid
|
||||
for cid in scene.get("character_ids") or []:
|
||||
exists = conn.execute(
|
||||
"SELECT id FROM characters WHERE id = ? AND project_id = ?",
|
||||
(cid, project_id),
|
||||
).fetchone()
|
||||
if exists:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO scene_characters (scene_id, character_id) VALUES (?, ?)",
|
||||
(scene_id, cid),
|
||||
)
|
||||
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone()
|
||||
created.append(row_to_dict(row))
|
||||
return created
|
||||
|
||||
|
||||
async def generate_script(
|
||||
project_id: int,
|
||||
*,
|
||||
replace: bool = True,
|
||||
scene_count: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
await event_bus.publish(
|
||||
"agent.thinking", {"message": "Writing scene script…", "project_id": project_id}
|
||||
)
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not project:
|
||||
raise ValueError("Project not found")
|
||||
p = row_to_dict(project)
|
||||
beats = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM story_beats WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
]
|
||||
characters = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM characters WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
locations = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM locations WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
|
||||
existing_n = conn.execute(
|
||||
"SELECT COUNT(*) AS n FROM scenes WHERE project_id = ?",
|
||||
(project_id,),
|
||||
).fetchone()["n"]
|
||||
recommended = recommend_scene_count(p.get("target_duration"))
|
||||
# Prefer explicit request, else keep at least the board the user already built
|
||||
requested = scene_count if scene_count and scene_count > 0 else existing_n
|
||||
required_scenes = max(recommended, int(requested)) if requested else recommended
|
||||
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"message": f"Writing {required_scenes} scenes "
|
||||
f"(board had {existing_n}; duration suggests {recommended})…",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
|
||||
messages = build_script_messages(
|
||||
title=p["title"],
|
||||
idea=p.get("idea"),
|
||||
beats=beats,
|
||||
characters=characters,
|
||||
locations=locations,
|
||||
target_duration=p.get("target_duration"),
|
||||
scene_count=required_scenes,
|
||||
)
|
||||
result = await generate_structured(messages, temperature=0.7)
|
||||
scenes_out = result.get("scenes") or []
|
||||
|
||||
if len(scenes_out) < required_scenes:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"message": (
|
||||
f"Model returned {len(scenes_out)} scenes; "
|
||||
f"required {required_scenes}. Retrying…"
|
||||
),
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
retry_messages = [
|
||||
messages[0],
|
||||
{
|
||||
"role": "user",
|
||||
"content": messages[1]["content"]
|
||||
+ (
|
||||
f"\n\nPREVIOUS ATTEMPT FAILED: it only had {len(scenes_out)} scenes. "
|
||||
f"You MUST return exactly {required_scenes} scenes this time."
|
||||
),
|
||||
},
|
||||
]
|
||||
result = await generate_structured(retry_messages, temperature=0.5)
|
||||
scenes_out = result.get("scenes") or []
|
||||
if len(scenes_out) < required_scenes:
|
||||
raise ValueError(
|
||||
f"Script returned {len(scenes_out)} scenes but {required_scenes} were required. "
|
||||
"Add scenes again and retry, or raise target duration."
|
||||
)
|
||||
|
||||
if replace:
|
||||
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,))
|
||||
|
||||
created = _persist_scenes(conn, project_id, scenes_out)
|
||||
|
||||
conn.execute(
|
||||
"UPDATE projects SET status = 'in_progress', updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(project_id,),
|
||||
)
|
||||
conn.commit()
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"message": f"Script written — {len(created)} scenes",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
return {"ok": True, "scenes": created, "generated": result}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Enqueue per-scene video generation jobs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.llm import LLMClient
|
||||
from calliope.agent.prompts import (
|
||||
build_minimax_h3_ref_messages,
|
||||
minimax_h3_ref_fallback,
|
||||
scene_video_prompt,
|
||||
)
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs
|
||||
from calliope.comfyui.smart_fill import ref_image_slots, smart_fill_inputs
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
logger = logging.getLogger("calliope.video_agent")
|
||||
|
||||
|
||||
def _h3_subjects(
|
||||
characters: list[dict[str, Any]],
|
||||
location: dict[str, Any] | None,
|
||||
loc_image: str | None,
|
||||
inputs: list[dict[str, Any]],
|
||||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
"""Ordered subject roster + ref image paths for the H3 ref profile.
|
||||
|
||||
Order = ref wiring order: scene characters first (scene order), then the
|
||||
location. Capped at the workflow's generic (Input:image) slot count so
|
||||
<Subject N> always matches an actually-wired reference image.
|
||||
"""
|
||||
subjects: list[dict[str, Any]] = []
|
||||
paths: list[str] = []
|
||||
for c in characters:
|
||||
img = c.get("sheet_path") or c.get("portrait_path")
|
||||
if not img:
|
||||
continue
|
||||
subjects.append(
|
||||
{
|
||||
"index": len(subjects) + 1,
|
||||
"kind": "character",
|
||||
"name": c.get("name"),
|
||||
"appearance": c.get("consistency_prompt") or c.get("appearance") or "",
|
||||
}
|
||||
)
|
||||
paths.append(img)
|
||||
if loc_image:
|
||||
loc = location or {}
|
||||
subjects.append(
|
||||
{
|
||||
"index": len(subjects) + 1,
|
||||
"kind": "location",
|
||||
"name": loc.get("name"),
|
||||
"appearance": loc.get("consistency_prompt") or loc.get("description") or "",
|
||||
}
|
||||
)
|
||||
paths.append(loc_image)
|
||||
cap = len(ref_image_slots(inputs))
|
||||
return subjects[:cap], paths[:cap]
|
||||
|
||||
|
||||
async def _h3_rewrite(scene: dict[str, Any], subjects: list[dict[str, Any]]) -> str:
|
||||
"""LLM rewrite into H3's six-section format, deterministic template on failure."""
|
||||
client = LLMClient()
|
||||
try:
|
||||
return await client.chat(
|
||||
build_minimax_h3_ref_messages(scene, subjects), temperature=0.4
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("MiniMax H3 prompt rewrite failed (%s); using fallback template", exc)
|
||||
return minimax_h3_ref_fallback(scene, subjects)
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
def _get_workflow(workflow_id: int | None = None) -> dict[str, Any] | None:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if workflow_id:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE id = ? AND is_enabled = 1", (workflow_id,)
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE kind = 'video' AND is_enabled = 1 ORDER BY id ASC LIMIT 1"
|
||||
).fetchone()
|
||||
if not row:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE is_enabled = 1 ORDER BY id ASC LIMIT 1"
|
||||
).fetchone()
|
||||
return row_to_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
async def enqueue_video_jobs(
|
||||
project_id: int,
|
||||
*,
|
||||
scene_ids: list[int] | None = None,
|
||||
workflow_id: int | None = None,
|
||||
input_values_override: dict[str, Any] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
await event_bus.publish(
|
||||
"agent.thinking", {"message": "Queuing video jobs…", "project_id": project_id}
|
||||
)
|
||||
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()]
|
||||
|
||||
for scene in scenes:
|
||||
# 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'
|
||||
""",
|
||||
(scene["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"],),
|
||||
)
|
||||
# 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")
|
||||
workflow = _get_workflow(wf_id)
|
||||
workflow_json = json.loads(workflow["workflow_json"]) if workflow else {}
|
||||
inputs = parse_dynamic_inputs(workflow_json) if workflow_json else []
|
||||
|
||||
char_rows = conn.execute(
|
||||
"""
|
||||
SELECT c.* FROM characters c
|
||||
JOIN scene_characters sc ON sc.character_id = c.id
|
||||
WHERE sc.scene_id = ?
|
||||
""",
|
||||
(scene["id"],),
|
||||
).fetchall()
|
||||
characters = [row_to_dict(r) for r in char_rows]
|
||||
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_row: dict[str, Any] | None = None
|
||||
if scene.get("location_id"):
|
||||
row = conn.execute(
|
||||
"SELECT name, description, consistency_prompt, reference_image_path "
|
||||
"FROM locations WHERE id = ?",
|
||||
(scene["location_id"],),
|
||||
).fetchone()
|
||||
if row:
|
||||
loc_row = row_to_dict(row)
|
||||
if not loc_image:
|
||||
loc_image = loc_row["reference_image_path"]
|
||||
|
||||
profile = (workflow or {}).get("prompt_profile") or "prose"
|
||||
if profile == "minimax_h3_ref":
|
||||
subjects, ref_paths = _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,
|
||||
},
|
||||
)
|
||||
prompt = await _h3_rewrite(scene, subjects)
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt,
|
||||
ref_images=ref_paths,
|
||||
duration=scene.get("duration_sec"),
|
||||
extra=input_values_override,
|
||||
)
|
||||
else:
|
||||
prompt = scene_video_prompt(scene, characters)
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt,
|
||||
character_image=char_image,
|
||||
location_image=loc_image,
|
||||
extra=input_values_override,
|
||||
)
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind="video",
|
||||
workflow_id=workflow["id"] if workflow else None,
|
||||
scene_id=scene["id"],
|
||||
payload={"input_values": values, "prompt": prompt},
|
||||
)
|
||||
if workflow and not scene.get("workflow_id"):
|
||||
conn.execute(
|
||||
"UPDATE scenes SET workflow_id = ? WHERE id = ?",
|
||||
(workflow["id"], scene["id"]),
|
||||
)
|
||||
# Never hold a write lock across awaits (event publish below).
|
||||
conn.commit()
|
||||
jobs.append(job)
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": "video",
|
||||
"message": f"Scene · {scene.get('heading') or scene.get('order_index')}",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return jobs
|
||||
@@ -0,0 +1,5 @@
|
||||
"""ComfyUI integration package."""
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs, parse_dynamic_outputs
|
||||
from calliope.comfyui.patcher import patch_workflow
|
||||
|
||||
__all__ = ["parse_dynamic_inputs", "parse_dynamic_outputs", "patch_workflow"]
|
||||
@@ -0,0 +1,135 @@
|
||||
"""ComfyUI HTTP client: upload, prompt, poll, download."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from calliope.config import settings
|
||||
from calliope.comfyui.registry import IMAGE_CLASSES, AUDIO_CLASSES
|
||||
|
||||
logger = logging.getLogger("calliope.comfyui")
|
||||
|
||||
|
||||
class ComfyUIClient:
|
||||
def __init__(self, base_url: str | None = None) -> None:
|
||||
self.base_url = (base_url or settings.comfyui_base_url).rstrip("/")
|
||||
self.client_id = str(uuid.uuid4())
|
||||
self._http = httpx.AsyncClient(timeout=120.0)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._http.aclose()
|
||||
|
||||
async def health(self) -> bool:
|
||||
try:
|
||||
resp = await self._http.get(f"{self.base_url}/system_stats")
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def upload_image(self, path: Path, subfolder: str = "calliope") -> str:
|
||||
data = path.read_bytes()
|
||||
files = {"image": (path.name, data, "application/octet-stream")}
|
||||
form = {"overwrite": "true", "subfolder": subfolder}
|
||||
resp = await self._http.post(f"{self.base_url}/upload/image", files=files, data=form)
|
||||
resp.raise_for_status()
|
||||
result = resp.json()
|
||||
name = result.get("name", path.name)
|
||||
sub = result.get("subfolder") or subfolder
|
||||
return f"{sub}/{name}" if sub else name
|
||||
|
||||
async def upload_audio(self, path: Path, subfolder: str = "calliope") -> str:
|
||||
data = path.read_bytes()
|
||||
files = {"image": (path.name, data, "application/octet-stream")} # Comfy uses image field
|
||||
form = {"overwrite": "true", "subfolder": subfolder, "type": "input"}
|
||||
resp = await self._http.post(f"{self.base_url}/upload/image", files=files, data=form)
|
||||
resp.raise_for_status()
|
||||
result = resp.json()
|
||||
name = result.get("name", path.name)
|
||||
sub = result.get("subfolder") or subfolder
|
||||
return f"{sub}/{name}" if sub else name
|
||||
|
||||
async def prepare_media_inputs(self, workflow: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Upload local file paths referenced in LoadImage/LoadAudio nodes."""
|
||||
for _node_id, node in workflow.items():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
class_type = node.get("class_type", "")
|
||||
inputs = node.get("inputs") or {}
|
||||
if class_type in IMAGE_CLASSES:
|
||||
image = inputs.get("image")
|
||||
if isinstance(image, str) and self._looks_like_local_path(image):
|
||||
path = Path(image)
|
||||
if path.exists():
|
||||
inputs["image"] = await self.upload_image(path)
|
||||
node["inputs"] = inputs
|
||||
elif class_type in AUDIO_CLASSES:
|
||||
audio = inputs.get("audio")
|
||||
if isinstance(audio, str) and self._looks_like_local_path(audio):
|
||||
path = Path(audio)
|
||||
if path.exists():
|
||||
inputs["audio"] = await self.upload_audio(path)
|
||||
node["inputs"] = inputs
|
||||
return workflow
|
||||
|
||||
@staticmethod
|
||||
def _looks_like_local_path(value: str) -> bool:
|
||||
if value.startswith("http://") or value.startswith("https://"):
|
||||
return False
|
||||
p = Path(value)
|
||||
return p.is_absolute() or "/" in value or "\\" in value
|
||||
|
||||
async def queue_prompt(self, workflow: dict[str, Any]) -> str:
|
||||
payload = {"prompt": workflow, "client_id": self.client_id}
|
||||
resp = await self._http.post(f"{self.base_url}/prompt", json=payload)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
prompt_id = data.get("prompt_id")
|
||||
if not prompt_id:
|
||||
raise RuntimeError(f"ComfyUI /prompt missing prompt_id: {data}")
|
||||
return prompt_id
|
||||
|
||||
async def get_history(self, prompt_id: str) -> dict[str, Any] | None:
|
||||
resp = await self._http.get(f"{self.base_url}/history/{prompt_id}")
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data.get(prompt_id)
|
||||
|
||||
async def download_image(
|
||||
self,
|
||||
filename: str,
|
||||
subfolder: str = "",
|
||||
folder_type: str = "output",
|
||||
dest: Path | None = None,
|
||||
) -> Path:
|
||||
params = {"filename": filename, "subfolder": subfolder, "type": folder_type}
|
||||
resp = await self._http.get(f"{self.base_url}/view", params=params)
|
||||
resp.raise_for_status()
|
||||
if dest is None:
|
||||
dest = settings.assets_dir / "comfy_downloads" / filename
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(resp.content)
|
||||
return dest
|
||||
|
||||
async def interrupt(self) -> None:
|
||||
try:
|
||||
await self._http.post(f"{self.base_url}/interrupt")
|
||||
except Exception as exc:
|
||||
logger.warning("ComfyUI interrupt failed: %s", exc)
|
||||
|
||||
def extract_outputs(self, history: dict[str, Any]) -> list[dict[str, str]]:
|
||||
outputs: list[dict[str, str]] = []
|
||||
for _node_id, node_out in (history.get("outputs") or {}).items():
|
||||
for key in ("images", "gifs", "videos"):
|
||||
for item in node_out.get(key) or []:
|
||||
outputs.append(
|
||||
{
|
||||
"filename": item.get("filename", ""),
|
||||
"subfolder": item.get("subfolder", ""),
|
||||
"type": item.get("type", "output"),
|
||||
}
|
||||
)
|
||||
return outputs
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Dry-run placeholder asset generation when ComfyUI is offline."""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _png_chunk(chunk_type: bytes, data: bytes) -> bytes:
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ chunk_type
|
||||
+ data
|
||||
+ struct.pack(">I", zlib.crc32(chunk_type + data) & 0xFFFFFFFF)
|
||||
)
|
||||
|
||||
|
||||
def write_placeholder_png(dest: Path, width: int = 512, height: int = 512, label: str = "dry-run") -> Path:
|
||||
"""Write a minimal solid-color PNG (no Pillow dependency)."""
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Dark purple-ish RGB
|
||||
r, g, b = 40, 30, 70
|
||||
raw = b""
|
||||
for _y in range(height):
|
||||
raw += b"\x00" # filter none
|
||||
raw += bytes([r, g, b]) * width
|
||||
compressed = zlib.compress(raw, 9)
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
png = b"\x89PNG\r\n\x1a\n"
|
||||
png += _png_chunk(b"IHDR", ihdr)
|
||||
png += _png_chunk(b"IDAT", compressed)
|
||||
png += _png_chunk(b"IEND", b"")
|
||||
dest.write_bytes(png)
|
||||
# Write a tiny sidecar note
|
||||
dest.with_suffix(".txt").write_text(f"Calliope dry-run placeholder: {label}\n", encoding="utf-8")
|
||||
return dest
|
||||
|
||||
|
||||
def write_placeholder_mp4(dest: Path, label: str = "dry-run") -> Path:
|
||||
"""Write a tiny stub file with .mp4 extension (not a real video codec)."""
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Minimal ftyp box so some players recognize container; still a stub.
|
||||
data = (
|
||||
b"\x00\x00\x00\x18ftypmp42"
|
||||
b"\x00\x00\x00\x00mp42isom"
|
||||
+ f"Calliope dry-run stub: {label}".encode("utf-8")
|
||||
)
|
||||
dest.write_bytes(data)
|
||||
return dest
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Parse ComfyUI API-format workflows for (Input[:role]) / (Output[:role]) titled nodes."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from calliope.comfyui.registry import (
|
||||
ComfyOutputKind,
|
||||
IMAGE_CLASSES,
|
||||
AUDIO_CLASSES,
|
||||
class_to_input_kind,
|
||||
class_to_output_kind,
|
||||
)
|
||||
from calliope.comfyui.roles import (
|
||||
normalize_input_role,
|
||||
normalize_output_role,
|
||||
parse_title_tag,
|
||||
)
|
||||
|
||||
|
||||
def extract_default_value(node: dict[str, Any]) -> str | int | float | None:
|
||||
class_type = node.get("class_type", "")
|
||||
inputs = node.get("inputs") or {}
|
||||
if class_type in IMAGE_CLASSES or class_type in AUDIO_CLASSES:
|
||||
return None
|
||||
if isinstance(inputs.get("text"), str):
|
||||
return inputs["text"]
|
||||
value = inputs.get("value")
|
||||
if isinstance(value, (str, int, float)):
|
||||
return value
|
||||
if isinstance(inputs.get("int"), (int, float)):
|
||||
return inputs["int"]
|
||||
if isinstance(inputs.get("float"), (int, float)):
|
||||
return inputs["float"]
|
||||
return None
|
||||
|
||||
|
||||
def parse_dynamic_inputs(workflow: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
results: list[dict[str, Any]] = []
|
||||
for node_id, node in workflow.items():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
title = (node.get("_meta") or {}).get("title") or ""
|
||||
kind, role, label = parse_title_tag(title)
|
||||
if kind != "input":
|
||||
continue
|
||||
results.append(
|
||||
{
|
||||
"nodeId": str(node_id),
|
||||
"label": label or node.get("class_type", node_id),
|
||||
"role": normalize_input_role(role),
|
||||
"kind": class_to_input_kind(node.get("class_type", "")),
|
||||
"defaultValue": extract_default_value(node),
|
||||
"required": True,
|
||||
}
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def parse_dynamic_outputs(workflow: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
results: list[dict[str, Any]] = []
|
||||
for node_id, node in workflow.items():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
title = (node.get("_meta") or {}).get("title") or ""
|
||||
kind, role, label = parse_title_tag(title)
|
||||
if kind != "output":
|
||||
continue
|
||||
out_kind: ComfyOutputKind = class_to_output_kind(node.get("class_type", ""))
|
||||
canon = normalize_output_role(role)
|
||||
if canon == "video":
|
||||
out_kind = "video"
|
||||
elif canon == "image":
|
||||
out_kind = "image"
|
||||
results.append(
|
||||
{
|
||||
"nodeId": str(node_id),
|
||||
"label": label or node.get("class_type", node_id),
|
||||
"role": canon,
|
||||
"kind": out_kind,
|
||||
}
|
||||
)
|
||||
return results
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Patch user values into ComfyUI API-format workflow by nodeId."""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from typing import Any
|
||||
|
||||
from calliope.comfyui.registry import class_to_patch_field
|
||||
|
||||
|
||||
def patch_workflow(
|
||||
base: dict[str, Any],
|
||||
values_by_node_id: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
patched = copy.deepcopy(base)
|
||||
for node_id, value in values_by_node_id.items():
|
||||
if value is None:
|
||||
continue
|
||||
key = str(node_id)
|
||||
node = patched.get(key)
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
inputs = dict(node.get("inputs") or {})
|
||||
field = class_to_patch_field(node.get("class_type", ""))
|
||||
if field == "text" and "text" not in inputs and "value" in inputs:
|
||||
field = "value"
|
||||
if field == "value" and "text" in inputs and "value" not in inputs:
|
||||
field = "text"
|
||||
inputs[field] = value
|
||||
node["inputs"] = inputs
|
||||
patched[key] = node
|
||||
return patched
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Prompt profiles: how scene prompts are formatted for a workflow's model.
|
||||
|
||||
``prose`` (default) sends the classic flat prose paragraph. ``minimax_h3_ref``
|
||||
rewrites the scene into MiniMax H3's six-section full-reference format at
|
||||
video-enqueue time (see calliope.agent.prompts).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
PROFILES = ("prose", "minimax_h3_ref")
|
||||
|
||||
DEFAULT_PROFILE = "prose"
|
||||
|
||||
|
||||
def detect_prompt_profile(workflow_json: dict[str, Any]) -> str:
|
||||
"""Suggest a prompt profile from the workflow's node classes.
|
||||
|
||||
Deterministic class-type check (not title guessing): any MiniMaxH3* node
|
||||
(e.g. ``MiniMaxH3ReferenceToVideo``) means the workflow expects the H3
|
||||
full-reference prompt format.
|
||||
"""
|
||||
for node in workflow_json.values():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
if str(node.get("class_type", "")).startswith("MiniMaxH3"):
|
||||
return "minimax_h3_ref"
|
||||
return DEFAULT_PROFILE
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Unified class_type → kind + patch-field registry (MuseAgent port)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
ComfyInputKind = Literal["text", "textarea", "number", "image", "image_url", "audio"]
|
||||
ComfyOutputKind = Literal["image", "video", "other"]
|
||||
PatchField = Literal["image", "url", "audio", "text", "value", "int", "float"]
|
||||
|
||||
TEXT_AREA_CLASSES = frozenset(
|
||||
{
|
||||
"CLIPTextEncode",
|
||||
"Note",
|
||||
"ShowText",
|
||||
"ImpactWildcardProcessor",
|
||||
"PrimitiveStringMultiline",
|
||||
"PrimitiveString",
|
||||
}
|
||||
)
|
||||
NUMBER_CLASSES = frozenset(
|
||||
{"INT", "FLOAT", "PrimitiveInt", "PrimitiveFloat", "KSampler", "KSamplerAdvanced"}
|
||||
)
|
||||
IMAGE_CLASSES = frozenset({"LoadImage", "ImageLoader", "ETN_LoadImageBase64"})
|
||||
IMAGE_URL_CLASSES = frozenset({"Load Image From Url (mtb)"})
|
||||
AUDIO_CLASSES = frozenset({"LoadAudio", "VHS_LoadAudio"})
|
||||
VIDEO_OUTPUT_CLASSES = frozenset(
|
||||
{"VHS_VideoCombine", "SaveVideo", "VideoOutput", "AnimateDiffCombine"}
|
||||
)
|
||||
IMAGE_OUTPUT_CLASSES = frozenset(
|
||||
{"SaveImage", "PreviewImage", "SaveImageWebsocket", "ETN_SendImageWebSocket"}
|
||||
)
|
||||
|
||||
|
||||
def class_to_input_kind(class_type: str) -> ComfyInputKind:
|
||||
if class_type in IMAGE_CLASSES:
|
||||
return "image"
|
||||
if class_type in IMAGE_URL_CLASSES:
|
||||
return "image_url"
|
||||
if class_type in AUDIO_CLASSES:
|
||||
return "audio"
|
||||
if class_type in NUMBER_CLASSES:
|
||||
return "number"
|
||||
if class_type in TEXT_AREA_CLASSES:
|
||||
return "textarea"
|
||||
lower = class_type.lower()
|
||||
if "image" in lower or "load" in lower:
|
||||
return "image"
|
||||
if "audio" in lower:
|
||||
return "audio"
|
||||
if "int" in lower or "float" in lower or "seed" in lower:
|
||||
return "number"
|
||||
if "text" in lower or "clip" in lower or "prompt" in lower:
|
||||
return "textarea"
|
||||
return "text"
|
||||
|
||||
|
||||
def class_to_patch_field(class_type: str) -> PatchField:
|
||||
if class_type in IMAGE_CLASSES:
|
||||
return "image"
|
||||
if class_type in IMAGE_URL_CLASSES:
|
||||
return "url"
|
||||
if class_type in AUDIO_CLASSES:
|
||||
return "audio"
|
||||
if class_type in {"CLIPTextEncode", "Note", "ShowText", "ImpactWildcardProcessor"}:
|
||||
return "text"
|
||||
if class_type.startswith("Primitive"):
|
||||
return "value"
|
||||
kind = class_to_input_kind(class_type)
|
||||
if kind == "image":
|
||||
return "image"
|
||||
if kind == "image_url":
|
||||
return "url"
|
||||
if kind == "audio":
|
||||
return "audio"
|
||||
if kind == "textarea":
|
||||
return "text"
|
||||
return "value"
|
||||
|
||||
|
||||
def class_to_output_kind(class_type: str) -> ComfyOutputKind:
|
||||
if class_type in VIDEO_OUTPUT_CLASSES or "video" in class_type.lower():
|
||||
return "video"
|
||||
if class_type in IMAGE_OUTPUT_CLASSES or "image" in class_type.lower():
|
||||
return "image"
|
||||
return "other"
|
||||
@@ -0,0 +1,85 @@
|
||||
"""ComfyUI node title role tags: (Input:prompt), (Output:image), etc."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
# Title tag: (Input), (Input:prompt), (Output:image), …
|
||||
_TITLE_TAG_RE = re.compile(
|
||||
r"\((?P<kind>Input|Output)(?::(?P<role>[a-zA-Z0-9_-]+))?\)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Canonical role → accepted aliases (all lowercased).
|
||||
INPUT_ROLE_ALIASES: dict[str, frozenset[str]] = {
|
||||
"prompt": frozenset({"prompt", "positive"}),
|
||||
"negative": frozenset({"negative", "neg"}),
|
||||
"width": frozenset({"width", "w"}),
|
||||
"height": frozenset({"height", "h"}),
|
||||
"character": frozenset({"character", "char", "portrait", "sheet", "face", "ref"}),
|
||||
"location": frozenset({"location", "loc", "environment", "env", "background", "scene"}),
|
||||
"image": frozenset({"image", "img"}),
|
||||
"seed": frozenset({"seed"}),
|
||||
"duration": frozenset({"duration", "dur", "length", "seconds"}),
|
||||
}
|
||||
|
||||
OUTPUT_ROLE_ALIASES: dict[str, frozenset[str]] = {
|
||||
"image": frozenset({"image", "img"}),
|
||||
"video": frozenset({"video", "vid"}),
|
||||
}
|
||||
|
||||
|
||||
def parse_title_tag(title: str) -> tuple[str | None, str | None, str]:
|
||||
"""Return (kind, role, label) from a Comfy node title.
|
||||
|
||||
kind is ``\"input\"`` / ``\"output\"`` or None if no tag.
|
||||
role is the lowercase role string or None for plain ``(Input)`` / ``(Output)``.
|
||||
label is the display name with the tag stripped.
|
||||
"""
|
||||
if not title:
|
||||
return None, None, ""
|
||||
match = _TITLE_TAG_RE.search(title)
|
||||
if not match:
|
||||
return None, None, title.strip()
|
||||
kind = match.group("kind").lower()
|
||||
role_raw = match.group("role")
|
||||
role = role_raw.lower() if role_raw else None
|
||||
stripped = _TITLE_TAG_RE.sub("", title).strip()
|
||||
# Title is only the tag, e.g. "(Input:prompt)" → use role as display label.
|
||||
if stripped:
|
||||
label = stripped
|
||||
elif role:
|
||||
label = role
|
||||
else:
|
||||
label = kind
|
||||
return kind, role, label
|
||||
|
||||
|
||||
def normalize_input_role(role: str | None) -> str | None:
|
||||
"""Map an alias to its canonical input role, or return the role as-is if unknown."""
|
||||
if not role:
|
||||
return None
|
||||
r = role.lower().strip()
|
||||
for canonical, aliases in INPUT_ROLE_ALIASES.items():
|
||||
if r in aliases or r == canonical:
|
||||
return canonical
|
||||
return r
|
||||
|
||||
|
||||
def normalize_output_role(role: str | None) -> str | None:
|
||||
if not role:
|
||||
return None
|
||||
r = role.lower().strip()
|
||||
for canonical, aliases in OUTPUT_ROLE_ALIASES.items():
|
||||
if r in aliases or r == canonical:
|
||||
return canonical
|
||||
return r
|
||||
|
||||
|
||||
def input_has_role(inp: dict[str, Any], *canonical_roles: str) -> bool:
|
||||
"""True if this parsed input's role matches any of the canonical roles (incl. aliases)."""
|
||||
role = normalize_input_role(inp.get("role"))
|
||||
if not role:
|
||||
return False
|
||||
wanted = {normalize_input_role(c) for c in canonical_roles}
|
||||
return role in wanted
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Smart-fill ComfyUI dynamic inputs from project/scene context via role tags."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from calliope.comfyui.roles import input_has_role
|
||||
|
||||
|
||||
def _find_by_role(inputs: list[dict[str, Any]], *roles: str) -> dict[str, Any] | None:
|
||||
for inp in inputs:
|
||||
if input_has_role(inp, *roles):
|
||||
return inp
|
||||
return None
|
||||
|
||||
|
||||
def _find_all_by_role(inputs: list[dict[str, Any]], *roles: str) -> list[dict[str, Any]]:
|
||||
"""All inputs matching any of the roles, sorted by numeric node id.
|
||||
|
||||
Node-id order is the documented ref-slot order: for multi-reference
|
||||
workflows (e.g. MiniMax H3 ref2video), ``(Input:image)`` slots are filled
|
||||
in this order and it defines ``<Subject N>`` numbering in the prompt.
|
||||
"""
|
||||
matches = [inp for inp in inputs if input_has_role(inp, *roles)]
|
||||
return sorted(matches, key=lambda i: int(i["nodeId"]))
|
||||
|
||||
|
||||
def ref_image_slots(inputs: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Generic ``(Input:image)`` ref slots in documented fill order (node id).
|
||||
|
||||
For multi-reference workflows (e.g. MiniMax H3 ref2video) these slots are
|
||||
filled in this order and it defines ``<Subject N>`` prompt numbering.
|
||||
"""
|
||||
return _find_all_by_role(inputs, "image")
|
||||
|
||||
|
||||
def _legacy_prompt_node(inputs: list[dict[str, Any]]) -> dict[str, Any] | None:
|
||||
"""Deprecated: untagged (Input) text nodes — prefer (Input:prompt)."""
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") not in ("text", "textarea"):
|
||||
continue
|
||||
label = (inp.get("label") or "").lower()
|
||||
if "negative" in label:
|
||||
continue
|
||||
if any(k in label for k in ("prompt", "positive", "text")):
|
||||
return inp
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") in ("text", "textarea"):
|
||||
label = (inp.get("label") or "").lower()
|
||||
if "negative" not in label:
|
||||
return inp
|
||||
return None
|
||||
|
||||
|
||||
def smart_fill_inputs(
|
||||
inputs: list[dict[str, Any]],
|
||||
*,
|
||||
prompt: str | None = None,
|
||||
negative_prompt: str | None = None,
|
||||
character_image: str | None = None,
|
||||
location_image: str | None = None,
|
||||
ref_images: list[str] | None = None,
|
||||
duration: int | float | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build valuesByNodeId from workflow dynamic inputs + context.
|
||||
|
||||
Mapping is driven by Comfy title role tags, e.g. ``(Input:prompt)``.
|
||||
See ``AGENTS.md`` / README for the role contract.
|
||||
|
||||
Order: non-blank defaults → role-based context → shared extras (non-blank).
|
||||
User/form ``extra`` wins so regenerating a clip keeps the settings they edited.
|
||||
Blank extras are skipped so an empty shared Text Prompt cannot wipe context.
|
||||
"""
|
||||
values: dict[str, Any] = {}
|
||||
for inp in inputs:
|
||||
node_id = str(inp["nodeId"])
|
||||
default = inp.get("defaultValue")
|
||||
if default is None:
|
||||
continue
|
||||
if isinstance(default, str) and not default.strip():
|
||||
continue
|
||||
values[node_id] = default
|
||||
|
||||
if prompt:
|
||||
target = _find_by_role(inputs, "prompt") or _legacy_prompt_node(inputs)
|
||||
if target:
|
||||
values[str(target["nodeId"])] = prompt
|
||||
|
||||
if negative_prompt:
|
||||
target = _find_by_role(inputs, "negative")
|
||||
if target:
|
||||
values[str(target["nodeId"])] = negative_prompt
|
||||
else:
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") in ("text", "textarea") and "negative" in (
|
||||
inp.get("label") or ""
|
||||
).lower():
|
||||
values[str(inp["nodeId"])] = negative_prompt
|
||||
break
|
||||
|
||||
if character_image:
|
||||
target = _find_by_role(inputs, "character")
|
||||
if target:
|
||||
values[str(target["nodeId"])] = character_image
|
||||
else:
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") in ("image", "image_url"):
|
||||
label = (inp.get("label") or "").lower()
|
||||
if any(
|
||||
k in label
|
||||
for k in ("character", "portrait", "reference", "sheet", "face", "ref")
|
||||
) and not any(k in label for k in ("env", "location", "background", "scene")):
|
||||
values[str(inp["nodeId"])] = character_image
|
||||
break
|
||||
|
||||
if location_image:
|
||||
target = _find_by_role(inputs, "location")
|
||||
if target:
|
||||
values[str(target["nodeId"])] = location_image
|
||||
else:
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") in ("image", "image_url"):
|
||||
label = (inp.get("label") or "").lower()
|
||||
if any(
|
||||
k in label
|
||||
for k in ("env", "location", "background", "scene", "setting")
|
||||
):
|
||||
values[str(inp["nodeId"])] = location_image
|
||||
break
|
||||
|
||||
if ref_images:
|
||||
for inp, path in zip(ref_image_slots(inputs), ref_images):
|
||||
values[str(inp["nodeId"])] = path
|
||||
|
||||
if duration is not None:
|
||||
target = _find_by_role(inputs, "duration")
|
||||
if target:
|
||||
values[str(target["nodeId"])] = duration
|
||||
|
||||
if extra:
|
||||
for k, v in extra.items():
|
||||
if v is None:
|
||||
continue
|
||||
if isinstance(v, str) and not str(v).strip():
|
||||
continue
|
||||
values[str(k)] = v
|
||||
|
||||
return values
|
||||
@@ -0,0 +1,202 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
# calliope-backend/ — permanent home for config + default data (never %TEMP%)
|
||||
# PyInstaller-frozen exe: __file__ points inside the bundle (_internal/), which is
|
||||
# not where a portable app should keep user data. Anchor config + default data
|
||||
# NEXT TO the exe instead, so the app folder stays self-contained and writable.
|
||||
# Dev (non-frozen) resolution is unchanged.
|
||||
if getattr(sys, "frozen", False):
|
||||
BACKEND_ROOT = Path(sys.executable).resolve().parent
|
||||
else:
|
||||
BACKEND_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
CONFIG_FILE = BACKEND_ROOT / "calliope_config.json"
|
||||
DEFAULT_DATA_DIR = BACKEND_ROOT / "data"
|
||||
DEFAULT_ASSETS_DIR = DEFAULT_DATA_DIR / "assets"
|
||||
|
||||
|
||||
def _strip_path_str(value: str | Path | None) -> str | None:
|
||||
"""Normalize path strings; strip accidental wrapping quotes from UI paste."""
|
||||
if value is None:
|
||||
return None
|
||||
s = str(value).strip()
|
||||
if not s or s.lower() in {"none", "null"}:
|
||||
return None
|
||||
if (s.startswith('"') and s.endswith('"')) or (s.startswith("'") and s.endswith("'")):
|
||||
s = s[1:-1].strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def normalize_path(value: str | Path | None) -> Path | None:
|
||||
cleaned = _strip_path_str(value)
|
||||
if cleaned is None:
|
||||
return None
|
||||
return Path(cleaned)
|
||||
|
||||
|
||||
def is_ephemeral_path(path: Path | str | None) -> bool:
|
||||
"""True for OS temp / pytest TemporaryDirectory paths — never use as default storage."""
|
||||
if path is None:
|
||||
return False
|
||||
try:
|
||||
resolved = Path(path).resolve()
|
||||
except OSError:
|
||||
resolved = Path(path)
|
||||
parts_lower = {p.lower() for p in resolved.parts}
|
||||
if "temp" in parts_lower or "tmp" in parts_lower:
|
||||
# Windows %TEMP% and Unix /tmp
|
||||
temp_root = Path(tempfile.gettempdir()).resolve()
|
||||
try:
|
||||
resolved.relative_to(temp_root)
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
# pytest-style .../Temp/tmpXXXX
|
||||
name = resolved.name.lower()
|
||||
if name.startswith("tmp") and len(name) > 3:
|
||||
return True
|
||||
for parent in resolved.parents:
|
||||
if parent.name.lower().startswith("tmp") and parent.parent.resolve() == temp_root:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="CALLIOPE_",
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
host: str = "127.0.0.1"
|
||||
port: int = 8247
|
||||
data_dir: Path = DEFAULT_DATA_DIR
|
||||
assets_dir: Path = DEFAULT_ASSETS_DIR
|
||||
db_name: str = "calliope.db"
|
||||
|
||||
llm_base_url: str = "http://127.0.0.1:11434/v1"
|
||||
llm_model: str = "llama3.2"
|
||||
llm_api_key: str | None = None
|
||||
|
||||
comfyui_base_url: str = "http://127.0.0.1:8188"
|
||||
# Comfy is HTTP-only (upload / prompt / history / view). No local input/output dirs.
|
||||
|
||||
queue_concurrency: int = 1
|
||||
queue_poll_interval_sec: float = 2.0
|
||||
queue_max_retries: int = 2
|
||||
dry_run: bool = False # off by default — real ComfyUI jobs
|
||||
|
||||
@property
|
||||
def db_path(self) -> Path:
|
||||
return self.data_dir / self.db_name
|
||||
|
||||
def ensure_storage_dirs(self) -> None:
|
||||
self.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.assets_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def to_public_dict(self) -> dict[str, Any]:
|
||||
"""Return settings that are safe to expose to the frontend."""
|
||||
return {
|
||||
"host": self.host,
|
||||
"port": self.port,
|
||||
"data_dir": str(self.data_dir),
|
||||
"assets_dir": str(self.assets_dir),
|
||||
"db_name": self.db_name,
|
||||
"llm_base_url": self.llm_base_url,
|
||||
"llm_model": self.llm_model,
|
||||
"llm_api_key": bool(self.llm_api_key),
|
||||
"comfyui_base_url": self.comfyui_base_url,
|
||||
"queue_concurrency": self.queue_concurrency,
|
||||
"queue_poll_interval_sec": self.queue_poll_interval_sec,
|
||||
"queue_max_retries": self.queue_max_retries,
|
||||
"dry_run": bool(self.dry_run),
|
||||
}
|
||||
|
||||
def _apply_storage_paths(self, data_dir: Path | None, assets_dir: Path | None) -> None:
|
||||
if data_dir is not None:
|
||||
if is_ephemeral_path(data_dir):
|
||||
data_dir = DEFAULT_DATA_DIR
|
||||
self.data_dir = data_dir
|
||||
if assets_dir is not None:
|
||||
if is_ephemeral_path(assets_dir):
|
||||
assets_dir = DEFAULT_ASSETS_DIR
|
||||
self.assets_dir = assets_dir
|
||||
# Keep assets under data when data moved and assets still ephemeral
|
||||
if is_ephemeral_path(self.assets_dir):
|
||||
self.assets_dir = self.data_dir / "assets"
|
||||
|
||||
def load_config_file(self) -> None:
|
||||
if not CONFIG_FILE.exists():
|
||||
self.data_dir = DEFAULT_DATA_DIR
|
||||
self.assets_dir = DEFAULT_ASSETS_DIR
|
||||
self.dry_run = False
|
||||
self.ensure_storage_dirs()
|
||||
return
|
||||
|
||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
path_keys = {"data_dir", "assets_dir"}
|
||||
# Ignore legacy comfyui_input_dir / comfyui_output_dir if present in old configs.
|
||||
skip_keys = {"comfyui_input_dir", "comfyui_output_dir"}
|
||||
for key, value in data.items():
|
||||
if key in skip_keys:
|
||||
continue
|
||||
if key in path_keys:
|
||||
value = normalize_path(value)
|
||||
if key == "dry_run":
|
||||
value = bool(value)
|
||||
if hasattr(self, key) and key not in {"data_dir", "assets_dir"}:
|
||||
setattr(self, key, value)
|
||||
|
||||
data_dir = normalize_path(data.get("data_dir")) or DEFAULT_DATA_DIR
|
||||
assets_dir = normalize_path(data.get("assets_dir")) or (data_dir / "assets")
|
||||
self._apply_storage_paths(data_dir, assets_dir)
|
||||
self.dry_run = bool(data.get("dry_run", False))
|
||||
self.ensure_storage_dirs()
|
||||
|
||||
# Auto-heal poisoned config (temp paths / quoted dirs / legacy comfy dirs) back to disk
|
||||
needs_rewrite = is_ephemeral_path(normalize_path(data.get("data_dir"))) or any(
|
||||
isinstance(data.get(k), str) and str(data.get(k)).startswith('"')
|
||||
for k in ("data_dir", "assets_dir")
|
||||
if data.get(k)
|
||||
)
|
||||
if needs_rewrite or "comfyui_input_dir" in data or "comfyui_output_dir" in data:
|
||||
self.save_config_file()
|
||||
|
||||
def save_config_file(self) -> None:
|
||||
# Never persist pytest / OS temp storage as the real data home
|
||||
if is_ephemeral_path(self.data_dir):
|
||||
self.data_dir = DEFAULT_DATA_DIR
|
||||
if is_ephemeral_path(self.assets_dir):
|
||||
self.assets_dir = self.data_dir / "assets"
|
||||
self.dry_run = bool(self.dry_run)
|
||||
self.ensure_storage_dirs()
|
||||
|
||||
data = {
|
||||
"host": self.host,
|
||||
"port": self.port,
|
||||
"data_dir": str(self.data_dir),
|
||||
"assets_dir": str(self.assets_dir),
|
||||
"db_name": self.db_name,
|
||||
"llm_base_url": self.llm_base_url,
|
||||
"llm_model": self.llm_model,
|
||||
"llm_api_key": self.llm_api_key,
|
||||
"comfyui_base_url": self.comfyui_base_url,
|
||||
"queue_concurrency": self.queue_concurrency,
|
||||
"queue_poll_interval_sec": self.queue_poll_interval_sec,
|
||||
"queue_max_retries": self.queue_max_retries,
|
||||
"dry_run": bool(self.dry_run),
|
||||
}
|
||||
CONFIG_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
settings = Settings()
|
||||
settings.load_config_file()
|
||||
@@ -0,0 +1,225 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS projects (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
idea TEXT,
|
||||
genre TEXT,
|
||||
tone TEXT,
|
||||
target_duration TEXT,
|
||||
cover_path TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'draft',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS story_beats (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
order_index INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS characters (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
role TEXT,
|
||||
age TEXT,
|
||||
appearance TEXT,
|
||||
personality TEXT,
|
||||
portrait_path TEXT,
|
||||
sheet_path TEXT,
|
||||
consistency_prompt TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS locations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
reference_image_path TEXT,
|
||||
consistency_prompt TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scenes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
beat_id INTEGER REFERENCES story_beats(id) ON DELETE SET NULL,
|
||||
order_index INTEGER NOT NULL,
|
||||
heading TEXT,
|
||||
action TEXT,
|
||||
dialog TEXT,
|
||||
duration_sec INTEGER,
|
||||
workflow_id INTEGER,
|
||||
env_image_path TEXT,
|
||||
location_id INTEGER,
|
||||
video_path TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scene_characters (
|
||||
scene_id INTEGER NOT NULL REFERENCES scenes(id) ON DELETE CASCADE,
|
||||
character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (scene_id, character_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS workflows (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
kind TEXT NOT NULL CHECK(kind IN ('image', 'video')),
|
||||
workflow_json TEXT NOT NULL,
|
||||
input_node_map TEXT,
|
||||
output_node_name TEXT,
|
||||
input_schema TEXT,
|
||||
output_schema TEXT,
|
||||
description TEXT,
|
||||
prompt_profile TEXT NOT NULL DEFAULT 'prose',
|
||||
is_enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
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,
|
||||
kind TEXT NOT NULL,
|
||||
workflow_id INTEGER REFERENCES workflows(id) ON DELETE SET NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
payload_json TEXT,
|
||||
output_paths_json TEXT,
|
||||
error TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
started_at TIMESTAMP,
|
||||
completed_at TIMESTAMP,
|
||||
retry_count INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def get_db(db_path: Path) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(db_path, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
# WAL: readers never block writers (the UI polls jobs/settings constantly),
|
||||
# and busy_timeout makes writers wait instead of erroring on contention.
|
||||
conn.execute("PRAGMA journal_mode = WAL")
|
||||
conn.execute("PRAGMA busy_timeout = 10000")
|
||||
conn.execute("PRAGMA foreign_keys = ON")
|
||||
return conn
|
||||
|
||||
|
||||
def _sqlite_connect(path: Path) -> sqlite3.Connection:
|
||||
return sqlite3.connect(path)
|
||||
|
||||
|
||||
async def migrate_db(db_path: Path) -> None:
|
||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(db_path)
|
||||
conn.executescript(SCHEMA)
|
||||
# Additive migrations for existing DBs
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(workflows)").fetchall()}
|
||||
if "input_schema" not in cols:
|
||||
conn.execute("ALTER TABLE workflows ADD COLUMN input_schema TEXT")
|
||||
if "output_schema" not in cols:
|
||||
conn.execute("ALTER TABLE workflows ADD COLUMN output_schema TEXT")
|
||||
if "description" not in cols:
|
||||
conn.execute("ALTER TABLE workflows ADD COLUMN description TEXT")
|
||||
if "prompt_profile" not in cols:
|
||||
conn.execute(
|
||||
"ALTER TABLE workflows ADD COLUMN prompt_profile TEXT NOT NULL DEFAULT 'prose'"
|
||||
)
|
||||
scene_cols = {r[1] for r in conn.execute("PRAGMA table_info(scenes)").fetchall()}
|
||||
if "location_id" not in scene_cols:
|
||||
conn.execute("ALTER TABLE scenes ADD COLUMN location_id INTEGER")
|
||||
if "video_path" not in scene_cols:
|
||||
conn.execute("ALTER TABLE scenes ADD COLUMN video_path TEXT")
|
||||
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")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def row_to_dict(row: sqlite3.Row) -> dict[str, Any]:
|
||||
return {key: row[key] for key in row.keys()}
|
||||
|
||||
|
||||
# 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 = {
|
||||
"projects": ["cover_path"],
|
||||
"characters": ["portrait_path", "sheet_path"],
|
||||
"locations": ["reference_image_path"],
|
||||
"scenes": ["env_image_path", "video_path"],
|
||||
}
|
||||
|
||||
|
||||
def _rebase_path(value: Any, data_dir: Path, assets_dir: Path) -> str | None:
|
||||
"""Rebase an absolute path from a previous install location onto current dirs.
|
||||
|
||||
Returns the rebased path, or None when the value is not a stale absolute
|
||||
path (relative, already under data_dir, or has no 'assets' segment).
|
||||
"""
|
||||
if not value or not isinstance(value, str):
|
||||
return None
|
||||
p = Path(value)
|
||||
if not p.is_absolute():
|
||||
return None
|
||||
try:
|
||||
p.resolve().relative_to(data_dir.resolve())
|
||||
return None # already under the current install
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
parts_lower = [seg.lower() for seg in p.parts]
|
||||
if "assets" not in parts_lower:
|
||||
return None
|
||||
idx = len(parts_lower) - 1 - parts_lower[::-1].index("assets")
|
||||
rel = Path(*p.parts[idx + 1 :])
|
||||
if not rel.parts:
|
||||
return None
|
||||
return str(assets_dir / rel)
|
||||
|
||||
|
||||
def rebase_stale_asset_paths(conn: sqlite3.Connection, data_dir: Path, assets_dir: Path) -> int:
|
||||
"""Rewrite stored asset paths left over from a previous install location.
|
||||
|
||||
Call after migrate_db (needs all columns to exist). Returns the number of
|
||||
rewritten values; caller commits.
|
||||
"""
|
||||
count = 0
|
||||
for table, columns in _PATH_COLUMNS.items():
|
||||
for col in columns:
|
||||
rows = conn.execute(f"SELECT id, {col} FROM {table} WHERE {col} IS NOT NULL").fetchall()
|
||||
for row in rows:
|
||||
new = _rebase_path(row[col], data_dir, assets_dir)
|
||||
if new and new != row[col]:
|
||||
conn.execute(f"UPDATE {table} SET {col} = ? WHERE id = ?", (new, row["id"]))
|
||||
count += 1
|
||||
rows = conn.execute(
|
||||
"SELECT id, output_paths_json FROM jobs WHERE output_paths_json IS NOT NULL"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
try:
|
||||
paths = json.loads(row["output_paths_json"] or "[]")
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if not isinstance(paths, list):
|
||||
continue
|
||||
new_paths = [_rebase_path(p, data_dir, assets_dir) or p for p in paths]
|
||||
if new_paths != paths:
|
||||
conn.execute(
|
||||
"UPDATE jobs SET output_paths_json = ? WHERE id = ?",
|
||||
(json.dumps(new_paths), row["id"]),
|
||||
)
|
||||
count += 1
|
||||
return count
|
||||
@@ -0,0 +1,3 @@
|
||||
from calliope.events.bus import EventBus, event_bus
|
||||
|
||||
__all__ = ["EventBus", "event_bus"]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""In-process SSE event bus."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
|
||||
class EventBus:
|
||||
def __init__(self) -> None:
|
||||
self._subscribers: list[asyncio.Queue[dict[str, Any]]] = []
|
||||
self._lock = asyncio.Lock()
|
||||
self.recent: list[dict[str, Any]] = []
|
||||
|
||||
async def subscribe(self) -> asyncio.Queue[dict[str, Any]]:
|
||||
q: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=256)
|
||||
async with self._lock:
|
||||
self._subscribers.append(q)
|
||||
return q
|
||||
|
||||
async def unsubscribe(self, q: asyncio.Queue[dict[str, Any]]) -> None:
|
||||
async with self._lock:
|
||||
if q in self._subscribers:
|
||||
self._subscribers.remove(q)
|
||||
|
||||
async def publish(self, event_type: str, data: dict[str, Any] | None = None) -> None:
|
||||
event = {
|
||||
"type": event_type,
|
||||
"data": data or {},
|
||||
"ts": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
self.recent.append(event)
|
||||
if len(self.recent) > 200:
|
||||
self.recent = self.recent[-200:]
|
||||
async with self._lock:
|
||||
dead: list[asyncio.Queue[dict[str, Any]]] = []
|
||||
for q in self._subscribers:
|
||||
try:
|
||||
q.put_nowait(event)
|
||||
except asyncio.QueueFull:
|
||||
dead.append(q)
|
||||
for q in dead:
|
||||
self._subscribers.remove(q)
|
||||
|
||||
def format_sse(self, event: dict[str, Any]) -> str:
|
||||
return f"event: {event['type']}\ndata: {json.dumps(event)}\n\n"
|
||||
|
||||
|
||||
event_bus = EventBus()
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Film export: stitch a project's scene clips into one mp4 via ffmpeg.
|
||||
|
||||
Pipeline (validated on real clips — do not reinvent): normalize each clip →
|
||||
0.5s crossfades (xfade/acrossfade) → loudness normalize. ComfyUI is never
|
||||
involved; export jobs run locally against files on disk.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from calliope import config
|
||||
from calliope.comfyui.dry_run import write_placeholder_mp4
|
||||
from calliope.db import get_db, row_to_dict
|
||||
|
||||
logger = logging.getLogger("calliope.export")
|
||||
|
||||
# Normalization targets — every clip is conformed to these before stitching.
|
||||
EXPORT_WIDTH = 1920
|
||||
EXPORT_HEIGHT = 1080
|
||||
EXPORT_FPS = 30
|
||||
XFADE_SEC = 0.5
|
||||
PROGRESS_MIN_INTERVAL_SEC = 1.0
|
||||
|
||||
_running: dict[int, asyncio.subprocess.Process] = {}
|
||||
|
||||
|
||||
def kill_running(job_id: int) -> bool:
|
||||
"""Kill the ffmpeg process for a running export job. False when none."""
|
||||
proc = _running.get(job_id)
|
||||
if not proc or proc.returncode is not None:
|
||||
return False
|
||||
try:
|
||||
proc.kill()
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _require_binary(name: str) -> str:
|
||||
path = shutil.which(name)
|
||||
if not path:
|
||||
raise RuntimeError(f"{name} not found on PATH — install ffmpeg to enable film export.")
|
||||
return path
|
||||
|
||||
|
||||
def slugify(title: str) -> str:
|
||||
slug = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
|
||||
return slug or "film"
|
||||
|
||||
|
||||
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)."""
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
scenes = [row_to_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")]
|
||||
return with_clip, skipped
|
||||
|
||||
|
||||
def _project_title(project_id: int) -> str:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT title FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
return row["title"] if row else f"project-{project_id}"
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
async def probe(path: str | Path) -> dict[str, Any]:
|
||||
"""ffprobe a clip: duration (float seconds) and has_audio (bool)."""
|
||||
ffprobe = _require_binary("ffprobe")
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
ffprobe,
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"format=duration:stream=codec_type",
|
||||
"-of",
|
||||
"json",
|
||||
str(path),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
out, err = await proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
tail = err.decode("utf-8", "replace")[-500:]
|
||||
raise RuntimeError(f"ffprobe failed for {path}: {tail}")
|
||||
data = json.loads(out.decode("utf-8", "replace") or "{}")
|
||||
duration = float((data.get("format") or {}).get("duration") or 0.0)
|
||||
has_audio = any(s.get("codec_type") == "audio" for s in data.get("streams") or [])
|
||||
return {"duration": duration, "has_audio": has_audio}
|
||||
|
||||
|
||||
def build_ffmpeg_cmd(
|
||||
clips: list[dict[str, Any]],
|
||||
probes: list[dict[str, Any]],
|
||||
dest: str | Path,
|
||||
) -> list[str]:
|
||||
"""Assemble the validated normalize → xfade → loudnorm ffmpeg command."""
|
||||
if not clips:
|
||||
raise RuntimeError("No clips to export")
|
||||
if len(clips) != len(probes):
|
||||
raise ValueError("clips and probes must align")
|
||||
|
||||
n = len(clips)
|
||||
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"])]
|
||||
# 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] = {}
|
||||
next_index = n
|
||||
for i, p in enumerate(probes):
|
||||
if not p["has_audio"]:
|
||||
lavfi_index[i] = next_index
|
||||
next_index += 1
|
||||
cmd += ["-f", "lavfi", "-i", "anullsrc=cl=stereo:r=48000"]
|
||||
|
||||
v_chain = (
|
||||
f"scale={EXPORT_WIDTH}:{EXPORT_HEIGHT}:force_original_aspect_ratio=decrease,"
|
||||
f"pad={EXPORT_WIDTH}:{EXPORT_HEIGHT}:(ow-iw)/2:(oh-ih)/2,"
|
||||
f"setsar=1,fps={EXPORT_FPS},settb=AVTB"
|
||||
)
|
||||
a_chain = "aformat=sample_rates=48000:channel_layouts=stereo"
|
||||
|
||||
filters: list[str] = []
|
||||
for i, p in enumerate(probes):
|
||||
filters.append(f"[{i}:v]{v_chain}[v{i}]")
|
||||
if p["has_audio"]:
|
||||
filters.append(f"[{i}:a]{a_chain}[a{i}]")
|
||||
else:
|
||||
filters.append(
|
||||
f"[{lavfi_index[i]}:a]atrim=duration={float(p['duration']):.3f},"
|
||||
f"asetpts=PTS-STARTPTS,{a_chain}[a{i}]"
|
||||
)
|
||||
|
||||
durations = [float(p["duration"]) for p in probes]
|
||||
if n == 1:
|
||||
# Single clip: no crossfade, but same normalize + loudness treatment.
|
||||
filters.append("[v0]format=yuv420p[vout]")
|
||||
filters.append("[a0]loudnorm=I=-16:TP=-1.5:LRA=11[aout]")
|
||||
else:
|
||||
for k in range(1, n):
|
||||
offset = sum(durations[:k]) - k * XFADE_SEC
|
||||
vin = "[v0]" if k == 1 else f"[x{k - 1}]"
|
||||
ain = "[a0]" if k == 1 else f"[c{k - 1}]"
|
||||
filters.append(
|
||||
f"{vin}[v{k}]xfade=transition=fade:duration={XFADE_SEC}:offset={offset:.3f}[x{k}]"
|
||||
)
|
||||
filters.append(f"{ain}[a{k}]acrossfade=d={XFADE_SEC}:c1=tri:c2=tri[c{k}]")
|
||||
# format=yuv420p AFTER the final xfade — the chain renegotiates to
|
||||
# yuv444p otherwise and players choke on the result.
|
||||
filters.append(f"[x{n - 1}]format=yuv420p[vout]")
|
||||
filters.append(f"[c{n - 1}]loudnorm=I=-16:TP=-1.5:LRA=11[aout]")
|
||||
|
||||
cmd += ["-filter_complex", ";".join(filters)]
|
||||
cmd += ["-map", "[vout]", "-map", "[aout]"]
|
||||
cmd += [
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"medium",
|
||||
"-crf",
|
||||
"20",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"192k",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
str(dest),
|
||||
]
|
||||
return cmd
|
||||
|
||||
|
||||
async def run_export(
|
||||
job: dict[str, Any],
|
||||
payload: dict[str, Any],
|
||||
bus: Any,
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
) -> list[str]:
|
||||
"""Run one export job; returns the output mp4 path list."""
|
||||
project_id = job["project_id"]
|
||||
job_id = job["id"]
|
||||
clips, skipped = collect_clips(project_id)
|
||||
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()
|
||||
await bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job_id,
|
||||
"kind": "export",
|
||||
"message": f"Skipping scene «{heading}» — no clip",
|
||||
},
|
||||
)
|
||||
|
||||
dest_dir = Path(config.settings.assets_dir) / str(project_id) / "export"
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
dest = dest_dir / f"{slugify(_project_title(project_id))}-job{job_id}.mp4"
|
||||
|
||||
if dry_run:
|
||||
write_placeholder_mp4(dest, label=f"job-{job_id}-export")
|
||||
return [str(dest)]
|
||||
|
||||
_require_binary("ffmpeg")
|
||||
probes = [await probe(clip["video_path"]) for clip in clips]
|
||||
durations = [float(p["duration"]) for p in probes]
|
||||
total_us = (sum(durations) - XFADE_SEC * max(0, len(clips) - 1)) * 1_000_000
|
||||
|
||||
cmd = build_ffmpeg_cmd(clips, probes, dest)
|
||||
logger.info("Export job %s: %s", job_id, " ".join(cmd))
|
||||
|
||||
await bus.publish(
|
||||
"job.progress",
|
||||
{"job_id": job_id, "kind": "export", "percent": 0.0, "message": "Exporting film…"},
|
||||
)
|
||||
last_publish = time.monotonic()
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
_running[job_id] = proc
|
||||
try:
|
||||
assert proc.stdout is not None and proc.stderr is not None
|
||||
# Drain stderr concurrently — a full pipe buffer would deadlock ffmpeg.
|
||||
stderr_task = asyncio.create_task(proc.stderr.read())
|
||||
while True:
|
||||
line = await proc.stdout.readline()
|
||||
if not line:
|
||||
break
|
||||
text = line.decode("utf-8", "replace").strip()
|
||||
if not text.startswith("out_time_us="):
|
||||
continue
|
||||
try:
|
||||
out_us = int(text.split("=", 1)[1])
|
||||
except ValueError:
|
||||
continue
|
||||
now = time.monotonic()
|
||||
if now - last_publish < PROGRESS_MIN_INTERVAL_SEC:
|
||||
continue
|
||||
last_publish = now
|
||||
percent = min(99.0, max(0.0, out_us / total_us * 100.0)) if total_us > 0 else 0.0
|
||||
await bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job_id,
|
||||
"kind": "export",
|
||||
"percent": round(percent, 1),
|
||||
"message": "Exporting film…",
|
||||
},
|
||||
)
|
||||
stderr_bytes = await stderr_task
|
||||
returncode = await proc.wait()
|
||||
finally:
|
||||
_running.pop(job_id, None)
|
||||
|
||||
if returncode != 0:
|
||||
tail = stderr_bytes.decode("utf-8", "replace")[-2000:]
|
||||
raise RuntimeError(f"ffmpeg export failed (exit {returncode}): {tail}")
|
||||
return [str(dest)]
|
||||
@@ -0,0 +1,120 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, migrate_db, rebase_stale_asset_paths
|
||||
from calliope.queue.worker import queue_worker
|
||||
from calliope.routers import (
|
||||
assets,
|
||||
events,
|
||||
jobs,
|
||||
playground,
|
||||
projects,
|
||||
scenes,
|
||||
settings as settings_router,
|
||||
story,
|
||||
workflows,
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("calliope")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
settings.assets_dir.mkdir(parents=True, exist_ok=True)
|
||||
await migrate_db(settings.db_path)
|
||||
# Folder moved? Stored asset paths still point at the old install root —
|
||||
# rebase them onto the current data dir before serving anything.
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
rebased = rebase_stale_asset_paths(conn, settings.data_dir, settings.assets_dir)
|
||||
if rebased:
|
||||
conn.commit()
|
||||
logger.info(
|
||||
"Rebased %s asset path(s) from a previous install location onto %s",
|
||||
rebased,
|
||||
settings.data_dir,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
await queue_worker.start()
|
||||
logger.info("Calliope started — db=%s dry_run=%s", settings.db_path, settings.dry_run)
|
||||
yield
|
||||
await queue_worker.stop()
|
||||
logger.info("Calliope shutting down")
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(title="Calliope", version="1.1.0", lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(projects.router, prefix="/api/projects", tags=["projects"])
|
||||
app.include_router(settings_router.router, prefix="/api/settings", tags=["settings"])
|
||||
app.include_router(story.router, prefix="/api/projects", tags=["story"])
|
||||
app.include_router(scenes.router, prefix="/api/projects", tags=["scenes"])
|
||||
app.include_router(assets.router, prefix="/api", tags=["assets"])
|
||||
app.include_router(workflows.router, prefix="/api/workflows", tags=["workflows"])
|
||||
app.include_router(jobs.router, prefix="/api/jobs", tags=["jobs"])
|
||||
app.include_router(playground.router, prefix="/api/playground", tags=["playground"])
|
||||
app.include_router(events.router, prefix="/api/events", tags=["events"])
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health() -> dict:
|
||||
return {"status": "ok", "version": "1.1.0", "dry_run": settings.dry_run}
|
||||
|
||||
# Catch unknown /api/* before StaticFiles — otherwise POST falls through and
|
||||
# returns a confusing 405 Method Not Allowed from the file server.
|
||||
@app.api_route(
|
||||
"/api/{full_path:path}",
|
||||
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],
|
||||
include_in_schema=False,
|
||||
)
|
||||
async def api_not_found(full_path: str) -> None:
|
||||
raise HTTPException(status_code=404, detail=f"API route not found: /api/{full_path}")
|
||||
|
||||
static_dir = Path(__file__).resolve().parent / "static"
|
||||
if static_dir.exists():
|
||||
app.mount("/", StaticFiles(directory=static_dir, html=True), name="static")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def main() -> int:
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="Calliope backend server")
|
||||
parser.add_argument("--host", default=None, help="Bind host (default: from config)")
|
||||
parser.add_argument("--port", type=int, default=None, help="Bind port (default: from config)")
|
||||
args = parser.parse_args()
|
||||
|
||||
host = args.host or settings.host
|
||||
port = args.port or settings.port
|
||||
|
||||
app = create_app()
|
||||
uvicorn = __import__("uvicorn")
|
||||
uvicorn.run(app, host=host, port=port)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
# Models package
|
||||
@@ -0,0 +1,188 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class ProjectCreate(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=200)
|
||||
idea: str | None = None
|
||||
genre: str | None = None
|
||||
tone: str | None = None
|
||||
target_duration: str | None = None
|
||||
|
||||
|
||||
class ProjectUpdate(BaseModel):
|
||||
title: str | None = Field(None, min_length=1, max_length=200)
|
||||
idea: str | None = None
|
||||
genre: str | None = None
|
||||
tone: str | None = None
|
||||
target_duration: str | None = None
|
||||
cover_path: str | None = None
|
||||
status: str | None = None
|
||||
|
||||
|
||||
class ProjectStats(BaseModel):
|
||||
scene_count: int
|
||||
character_count: int
|
||||
asset_ready_count: int
|
||||
asset_total_count: int
|
||||
|
||||
|
||||
class Project(BaseModel):
|
||||
id: int
|
||||
title: str
|
||||
idea: str | None
|
||||
genre: str | None
|
||||
tone: str | None
|
||||
target_duration: str | None
|
||||
cover_path: str | None = None
|
||||
status: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
stats: ProjectStats | None = None
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class ProjectList(BaseModel):
|
||||
projects: list[Project]
|
||||
|
||||
|
||||
class ProjectStats(BaseModel):
|
||||
scene_count: int = 0
|
||||
character_count: int = 0
|
||||
asset_ready_count: int = 0
|
||||
asset_total_count: int = 0
|
||||
|
||||
|
||||
class BeatCreate(BaseModel):
|
||||
order_index: int = 0
|
||||
title: str = Field(..., min_length=1)
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class BeatUpdate(BaseModel):
|
||||
order_index: int | None = None
|
||||
title: str | None = None
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class CharacterCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1)
|
||||
role: str | None = None
|
||||
age: str | None = None
|
||||
appearance: str | None = None
|
||||
personality: str | None = None
|
||||
consistency_prompt: str | None = None
|
||||
|
||||
|
||||
class CharacterUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
role: str | None = None
|
||||
age: str | None = None
|
||||
appearance: str | None = None
|
||||
personality: str | None = None
|
||||
consistency_prompt: str | None = None
|
||||
portrait_path: str | None = None
|
||||
sheet_path: str | None = None
|
||||
|
||||
|
||||
class LocationCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1)
|
||||
description: str | None = None
|
||||
consistency_prompt: str | None = None
|
||||
|
||||
|
||||
class LocationUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
consistency_prompt: str | None = None
|
||||
reference_image_path: str | None = None
|
||||
|
||||
|
||||
class SceneCreate(BaseModel):
|
||||
order_index: int = 0
|
||||
heading: str | None = None
|
||||
action: str | None = None
|
||||
dialog: str | None = None
|
||||
duration_sec: int | None = None
|
||||
workflow_id: int | None = None
|
||||
env_image_path: str | None = None
|
||||
beat_id: int | None = None
|
||||
character_ids: list[int] = Field(default_factory=list)
|
||||
location_id: int | None = None
|
||||
|
||||
|
||||
class SceneUpdate(BaseModel):
|
||||
order_index: int | None = None
|
||||
heading: str | None = None
|
||||
action: str | None = None
|
||||
dialog: str | None = None
|
||||
duration_sec: int | None = None
|
||||
workflow_id: int | None = None
|
||||
env_image_path: str | None = None
|
||||
beat_id: int | None = None
|
||||
character_ids: list[int] | None = None
|
||||
location_id: int | None = None
|
||||
video_path: str | None = None
|
||||
|
||||
|
||||
class SceneReorder(BaseModel):
|
||||
scene_ids: list[int]
|
||||
|
||||
|
||||
class WorkflowCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1)
|
||||
kind: Literal["image", "video"] = "image"
|
||||
workflow_json: dict[str, Any]
|
||||
description: str | None = None
|
||||
prompt_profile: Literal["prose", "minimax_h3_ref"] | None = None
|
||||
|
||||
|
||||
class WorkflowUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
kind: Literal["image", "video"] | None = None
|
||||
description: str | None = None
|
||||
prompt_profile: Literal["prose", "minimax_h3_ref"] | None = None
|
||||
is_enabled: bool | None = None
|
||||
|
||||
|
||||
class WorkflowAnalyze(BaseModel):
|
||||
workflow_json: dict[str, Any]
|
||||
|
||||
|
||||
class JobCreate(BaseModel):
|
||||
scene_id: int | None = None
|
||||
kind: str
|
||||
workflow_id: int | None = None
|
||||
input_values: dict[str, Any] | None = None
|
||||
character_id: int | None = None
|
||||
location_id: int | None = None
|
||||
|
||||
|
||||
class GenerateAssetsRequest(BaseModel):
|
||||
character_ids: list[int] | None = None
|
||||
location_ids: list[int] | None = None
|
||||
missing_only: bool = True
|
||||
workflow_id: int | None = None
|
||||
input_values: dict[str, Any] | None = None
|
||||
# For characters: which image slot to write. Default/UI is "sheet" only
|
||||
# (sheet includes face close-up). "portrait" remains for legacy queued jobs.
|
||||
asset_target: str | None = "sheet"
|
||||
# Optional one-shot prompt override (must still be user-visible text from the UI).
|
||||
prompt: str | None = None
|
||||
|
||||
|
||||
class GenerateScenesRequest(BaseModel):
|
||||
replace: bool = True
|
||||
# When set (or inferred from existing scenes), regenerate must produce at least this many.
|
||||
scene_count: int | None = None
|
||||
|
||||
|
||||
class GenerateVideosRequest(BaseModel):
|
||||
scene_ids: list[int] | None = None
|
||||
workflow_id: int | None = None
|
||||
input_values: dict[str, Any] | None = None
|
||||
@@ -0,0 +1,4 @@
|
||||
from calliope.queue.manager import QueueManager, queue_manager
|
||||
from calliope.queue.worker import QueueWorker, queue_worker
|
||||
|
||||
__all__ = ["QueueManager", "queue_manager", "QueueWorker", "queue_worker"]
|
||||
@@ -0,0 +1,187 @@
|
||||
"""SQLite-backed job queue manager."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from calliope import config
|
||||
from calliope.db import get_db, row_to_dict
|
||||
|
||||
logger = logging.getLogger("calliope.queue")
|
||||
|
||||
|
||||
class QueueManager:
|
||||
def __init__(self) -> None:
|
||||
self.paused = False
|
||||
|
||||
def reset_stale_jobs(self) -> int:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"UPDATE jobs SET status = 'pending', started_at = NULL WHERE status = 'running'"
|
||||
)
|
||||
conn.commit()
|
||||
return cur.rowcount
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def enqueue(
|
||||
self,
|
||||
*,
|
||||
project_id: int,
|
||||
kind: str,
|
||||
workflow_id: int | None = None,
|
||||
scene_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', ?)
|
||||
""",
|
||||
(project_id, scene_id, kind, workflow_id, json.dumps(payload or {})),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def claim_next(self) -> dict[str, Any] | None:
|
||||
if self.paused:
|
||||
return None
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1"
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
job_id = row["id"]
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'running', started_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ? AND status = 'pending'
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
conn.commit()
|
||||
claimed = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
return row_to_dict(claimed) if claimed else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def mark_done(self, job_id: int, output_paths: list[str]) -> None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'done', output_paths_json = ?, error = NULL,
|
||||
completed_at = CURRENT_TIMESTAMP WHERE id = ?
|
||||
""",
|
||||
(json.dumps(output_paths), job_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def mark_failed(self, job_id: int, error: str) -> None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'failed', error = ?, completed_at = CURRENT_TIMESTAMP,
|
||||
retry_count = retry_count + 1 WHERE id = ?
|
||||
""",
|
||||
(error[:2000], job_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def retry(self, job_id: int) -> dict[str, Any] | None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'pending', error = NULL, started_at = NULL,
|
||||
completed_at = NULL WHERE id = ?
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
conn.commit()
|
||||
return row_to_dict(
|
||||
conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def cancel(self, job_id: int) -> bool:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'failed', error = 'cancelled',
|
||||
completed_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ? AND status IN ('pending', 'running')
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def list_jobs(
|
||||
self, project_id: int | None = None, status: str | None = None, limit: int = 100
|
||||
) -> list[dict[str, Any]]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
clauses: list[str] = []
|
||||
params: list[Any] = []
|
||||
if project_id is not None:
|
||||
clauses.append("project_id = ?")
|
||||
params.append(project_id)
|
||||
if status:
|
||||
clauses.append("status = ?")
|
||||
params.append(status)
|
||||
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
params.append(limit)
|
||||
rows = conn.execute(
|
||||
f"SELECT * FROM jobs {where} ORDER BY created_at DESC LIMIT ?",
|
||||
params,
|
||||
).fetchall()
|
||||
return [row_to_dict(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def get_job(self, job_id: int) -> dict[str, Any] | None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
return row_to_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def delete_job(self, job_id: int) -> dict[str, Any] | None:
|
||||
"""Remove job row. Returns the deleted job dict, or None if missing."""
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
job = row_to_dict(row)
|
||||
conn.execute("DELETE FROM jobs WHERE id = ?", (job_id,))
|
||||
conn.commit()
|
||||
return job
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
queue_manager = QueueManager()
|
||||
@@ -0,0 +1,294 @@
|
||||
"""Background queue worker loop."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from calliope import config
|
||||
from calliope.comfyui.client import ComfyUIClient
|
||||
from calliope.comfyui.dry_run import write_placeholder_mp4, write_placeholder_png
|
||||
from calliope.comfyui.patcher import patch_workflow
|
||||
from calliope.db import get_db
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.export.runner import run_export
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
logger = logging.getLogger("calliope.worker")
|
||||
|
||||
|
||||
class QueueWorker:
|
||||
def __init__(self) -> None:
|
||||
self._task: asyncio.Task | None = None
|
||||
self._stop = asyncio.Event()
|
||||
|
||||
async def start(self) -> None:
|
||||
reset = queue_manager.reset_stale_jobs()
|
||||
if reset:
|
||||
logger.info("Reset %s stale running jobs to pending", reset)
|
||||
self._stop.clear()
|
||||
self._task = asyncio.create_task(self._loop(), name="calliope-queue-worker")
|
||||
|
||||
async def stop(self) -> None:
|
||||
self._stop.set()
|
||||
if self._task:
|
||||
await asyncio.wait([self._task], timeout=5)
|
||||
|
||||
async def _loop(self) -> None:
|
||||
logger.info("Queue worker started")
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
if queue_manager.paused:
|
||||
await asyncio.sleep(config.settings.queue_poll_interval_sec)
|
||||
continue
|
||||
job = queue_manager.claim_next()
|
||||
if not job:
|
||||
await asyncio.sleep(config.settings.queue_poll_interval_sec)
|
||||
continue
|
||||
await event_bus.publish(
|
||||
"job.started",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": job["kind"],
|
||||
"project_id": job.get("project_id"),
|
||||
"message": self._job_label(job),
|
||||
},
|
||||
)
|
||||
try:
|
||||
outputs = await self._run_job(job)
|
||||
queue_manager.mark_done(job["id"], outputs)
|
||||
if job["kind"] == "export":
|
||||
self._mark_project_completed(job["project_id"])
|
||||
await event_bus.publish(
|
||||
"job.completed",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": job["kind"],
|
||||
"outputs": outputs,
|
||||
"project_id": job["project_id"],
|
||||
"message": f"{self._job_label(job)} · {len(outputs)} file(s)",
|
||||
},
|
||||
)
|
||||
if outputs:
|
||||
await event_bus.publish(
|
||||
"asset.ready",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": job["kind"],
|
||||
"paths": outputs,
|
||||
"project_id": job["project_id"],
|
||||
"message": f"Saved {self._job_label(job)}",
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Job %s failed", job["id"])
|
||||
queue_manager.mark_failed(job["id"], str(exc))
|
||||
await event_bus.publish(
|
||||
"job.failed",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": job["kind"],
|
||||
"error": str(exc),
|
||||
"project_id": job.get("project_id"),
|
||||
"message": f"{self._job_label(job)} failed",
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Worker loop error")
|
||||
await asyncio.sleep(config.settings.queue_poll_interval_sec)
|
||||
logger.info("Queue worker stopped")
|
||||
|
||||
async def _run_job(self, job: dict[str, Any]) -> list[str]:
|
||||
payload = json.loads(job["payload_json"] or "{}")
|
||||
project_id = job["project_id"]
|
||||
kind = job["kind"]
|
||||
use_dry = bool(config.settings.dry_run)
|
||||
|
||||
if kind == "export":
|
||||
# Export stitches local clips with ffmpeg — never touches ComfyUI,
|
||||
# and dry-run writes an mp4 placeholder (not the default PNG).
|
||||
return await run_export(job, payload, event_bus, dry_run=use_dry)
|
||||
|
||||
client = ComfyUIClient(config.settings.comfyui_base_url)
|
||||
try:
|
||||
if use_dry:
|
||||
return await self._dry_run(job, payload)
|
||||
|
||||
healthy = await client.health()
|
||||
if not healthy:
|
||||
raise RuntimeError(
|
||||
f"ComfyUI unreachable at {config.settings.comfyui_base_url}. "
|
||||
"Start ComfyUI, or enable Dry-run in Settings only for placeholder testing."
|
||||
)
|
||||
|
||||
workflow_id = job.get("workflow_id") or payload.get("workflow_id")
|
||||
workflow = self._load_workflow(workflow_id)
|
||||
if not workflow:
|
||||
raise RuntimeError("No workflow found for job")
|
||||
|
||||
input_values = payload.get("input_values") or {}
|
||||
patched = patch_workflow(workflow, input_values)
|
||||
patched = await client.prepare_media_inputs(patched)
|
||||
prompt_id = await client.queue_prompt(patched)
|
||||
|
||||
history = await self._poll_history(client, prompt_id)
|
||||
if not history:
|
||||
raise RuntimeError("Timed out waiting for ComfyUI history")
|
||||
|
||||
status = history.get("status") or {}
|
||||
if status.get("status_str") == "error" or status.get("completed") is False:
|
||||
messages = status.get("messages") or []
|
||||
raise RuntimeError(f"ComfyUI error: {messages}")
|
||||
|
||||
outputs_meta = client.extract_outputs(history)
|
||||
dest_dir = config.settings.assets_dir / str(project_id) / kind
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
paths: list[str] = []
|
||||
for meta in outputs_meta:
|
||||
filename = meta["filename"]
|
||||
dest = dest_dir / filename
|
||||
await client.download_image(
|
||||
filename,
|
||||
subfolder=meta.get("subfolder", ""),
|
||||
folder_type=meta.get("type", "output"),
|
||||
dest=dest,
|
||||
)
|
||||
paths.append(str(dest))
|
||||
|
||||
self._apply_outputs_to_entities(job, payload, paths)
|
||||
return paths
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
async def _dry_run(self, job: dict[str, Any], payload: dict[str, Any]) -> list[str]:
|
||||
project_id = job["project_id"]
|
||||
kind = job["kind"]
|
||||
dest_dir = config.settings.assets_dir / str(project_id) / kind
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
label = f"job-{job['id']}-{kind}"
|
||||
if kind == "video":
|
||||
path = write_placeholder_mp4(dest_dir / f"{label}.mp4", label=label)
|
||||
else:
|
||||
path = write_placeholder_png(dest_dir / f"{label}.png", label=label)
|
||||
paths = [str(path)]
|
||||
self._apply_outputs_to_entities(job, payload, paths)
|
||||
await asyncio.sleep(0.3)
|
||||
return paths
|
||||
|
||||
async def _poll_history(self, client: ComfyUIClient, prompt_id: str) -> dict[str, Any] | None:
|
||||
attempts = int(600 / max(config.settings.queue_poll_interval_sec, 0.5))
|
||||
for _ in range(attempts):
|
||||
if self._stop.is_set():
|
||||
return None
|
||||
history = await client.get_history(prompt_id)
|
||||
if history:
|
||||
return history
|
||||
await asyncio.sleep(config.settings.queue_poll_interval_sec)
|
||||
await event_bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"prompt_id": prompt_id,
|
||||
"message": f"Waiting on ComfyUI ({prompt_id[:8]}…)",
|
||||
},
|
||||
)
|
||||
return None
|
||||
|
||||
def _mark_project_completed(self, project_id: int) -> None:
|
||||
"""A finished export closes the project lifecycle."""
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"UPDATE projects SET status = 'completed' WHERE id = ? AND status != 'completed'",
|
||||
(project_id,),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def _load_workflow(self, workflow_id: int | None) -> dict[str, Any] | None:
|
||||
if not workflow_id:
|
||||
return None
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT workflow_json FROM workflows WHERE id = ?", (workflow_id,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return json.loads(row["workflow_json"])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def _job_label(self, job: dict[str, Any]) -> str:
|
||||
payload = json.loads(job.get("payload_json") or "{}")
|
||||
kind = job.get("kind") or "job"
|
||||
if kind == "export":
|
||||
return "Export film"
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
if payload.get("character_id"):
|
||||
row = conn.execute(
|
||||
"SELECT name FROM characters WHERE id = ?", (payload["character_id"],)
|
||||
).fetchone()
|
||||
name = row["name"] if row else f"#{payload['character_id']}"
|
||||
target = payload.get("asset_target") or "sheet"
|
||||
return f"{name} · {target}"
|
||||
if payload.get("location_id"):
|
||||
row = conn.execute(
|
||||
"SELECT name FROM locations WHERE id = ?", (payload["location_id"],)
|
||||
).fetchone()
|
||||
name = row["name"] if row else f"#{payload['location_id']}"
|
||||
return f"{name} · environment"
|
||||
if job.get("scene_id"):
|
||||
row = conn.execute(
|
||||
"SELECT heading, order_index FROM scenes WHERE id = ?", (job["scene_id"],)
|
||||
).fetchone()
|
||||
if row:
|
||||
heading = (row["heading"] or f"Scene {row['order_index']}").strip()
|
||||
return f"Scene · {heading}"
|
||||
return f"Scene #{job['scene_id']}"
|
||||
finally:
|
||||
conn.close()
|
||||
return f"{kind} #{job.get('id')}"
|
||||
|
||||
def _apply_outputs_to_entities(
|
||||
self, job: dict[str, Any], payload: dict[str, Any], paths: list[str]
|
||||
) -> None:
|
||||
if not paths:
|
||||
return
|
||||
primary = paths[0]
|
||||
character_id = payload.get("character_id")
|
||||
location_id = payload.get("location_id")
|
||||
scene_id = job.get("scene_id")
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
if character_id:
|
||||
target = payload.get("asset_target") or "sheet"
|
||||
if target == "portrait":
|
||||
# Legacy jobs only — UI no longer generates portraits
|
||||
conn.execute(
|
||||
"UPDATE characters SET portrait_path = ? WHERE id = ?",
|
||||
(primary, character_id),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"UPDATE characters SET sheet_path = ? WHERE id = ?",
|
||||
(primary, character_id),
|
||||
)
|
||||
if location_id:
|
||||
conn.execute(
|
||||
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
|
||||
(primary, location_id),
|
||||
)
|
||||
if scene_id and job["kind"] == "video":
|
||||
conn.execute(
|
||||
"UPDATE scenes SET video_path = ? WHERE id = ?",
|
||||
(primary, scene_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
queue_worker = QueueWorker()
|
||||
@@ -0,0 +1 @@
|
||||
# Routers package
|
||||
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from calliope.agent.asset_agent import enqueue_asset_jobs
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.models.schemas import GenerateAssetsRequest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/projects/{project_id}/assets")
|
||||
async def list_assets(project_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = conn.execute("SELECT id FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
characters = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM characters WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
locations = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM locations WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
return {"characters": characters, "locations": locations}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/generate-assets")
|
||||
async def generate_assets(project_id: int, payload: GenerateAssetsRequest) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if not conn.execute("SELECT id FROM projects WHERE id = ?", (project_id,)).fetchone():
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
finally:
|
||||
conn.close()
|
||||
jobs = await enqueue_asset_jobs(
|
||||
project_id,
|
||||
character_ids=payload.character_ids,
|
||||
location_ids=payload.location_ids,
|
||||
missing_only=payload.missing_only,
|
||||
workflow_id=payload.workflow_id,
|
||||
input_values_override=payload.input_values,
|
||||
asset_target=payload.asset_target or "sheet",
|
||||
prompt_override=payload.prompt,
|
||||
)
|
||||
return {"ok": True, "jobs": jobs}
|
||||
|
||||
|
||||
@router.get("/file")
|
||||
async def get_asset_file(path: str = Query(...)) -> FileResponse:
|
||||
assets_root = settings.assets_dir.resolve()
|
||||
target = Path(path).resolve()
|
||||
try:
|
||||
target.relative_to(assets_root)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=403, detail="Path outside assets directory") from exc
|
||||
if not target.exists() or not target.is_file():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
return FileResponse(target)
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from calliope.events.bus import event_bus
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def events_stream(request: Request):
|
||||
async def generator():
|
||||
q = await event_bus.subscribe()
|
||||
try:
|
||||
# Send recent backlog
|
||||
for event in event_bus.recent[-20:]:
|
||||
yield event_bus.format_sse(event)
|
||||
while True:
|
||||
if await request.is_disconnected():
|
||||
break
|
||||
try:
|
||||
event = await asyncio.wait_for(q.get(), timeout=15.0)
|
||||
yield event_bus.format_sse(event)
|
||||
except asyncio.TimeoutError:
|
||||
yield ": keepalive\n\n"
|
||||
finally:
|
||||
await event_bus.unsubscribe(q)
|
||||
|
||||
return StreamingResponse(
|
||||
generator(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,157 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
|
||||
from calliope.agent.video_agent import enqueue_video_jobs
|
||||
from calliope.comfyui.client import ComfyUIClient
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.export.runner import kill_running
|
||||
from calliope.models.schemas import GenerateVideosRequest, JobCreate
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _job_public(job: dict[str, Any]) -> dict[str, Any]:
|
||||
out = dict(job)
|
||||
out["payload"] = json.loads(job.get("payload_json") or "{}")
|
||||
out["output_paths"] = json.loads(job.get("output_paths_json") or "[]")
|
||||
out.pop("payload_json", None)
|
||||
out.pop("output_paths_json", None)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_jobs(
|
||||
project_id: int | None = None,
|
||||
status: str | None = None,
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
) -> list[dict[str, Any]]:
|
||||
return [_job_public(j) for j in queue_manager.list_jobs(project_id, status, limit)]
|
||||
|
||||
|
||||
@router.get("/queue-status")
|
||||
async def queue_status() -> dict[str, Any]:
|
||||
return {"paused": queue_manager.paused}
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause_queue() -> dict[str, Any]:
|
||||
queue_manager.paused = True
|
||||
return {"ok": True, "paused": True}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume_queue() -> dict[str, Any]:
|
||||
queue_manager.paused = False
|
||||
return {"ok": True, "paused": False}
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/generate-videos")
|
||||
async def generate_videos(
|
||||
project_id: int, payload: GenerateVideosRequest | None = None
|
||||
) -> dict[str, Any]:
|
||||
body = payload or GenerateVideosRequest()
|
||||
jobs = await enqueue_video_jobs(
|
||||
project_id,
|
||||
scene_ids=body.scene_ids,
|
||||
workflow_id=body.workflow_id,
|
||||
input_values_override=body.input_values,
|
||||
)
|
||||
return {"ok": True, "jobs": [_job_public(j) for j in jobs]}
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/export")
|
||||
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",
|
||||
(project_id,),
|
||||
).fetchone()
|
||||
if not row or row["n"] == 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="No scene clips to export — generate videos first",
|
||||
)
|
||||
# Supersede leftover pending exports so a re-Export always starts fresh
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'failed', error = 'superseded by new export',
|
||||
completed_at = CURRENT_TIMESTAMP
|
||||
WHERE project_id = ? AND kind = 'export' AND status = 'pending'
|
||||
""",
|
||||
(project_id,),
|
||||
)
|
||||
# Commit BEFORE enqueue: queue_manager.enqueue writes on its own connection.
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
job = queue_manager.enqueue(project_id=project_id, kind="export", payload={})
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": "export",
|
||||
"message": "Export film",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
return {"ok": True, "job": _job_public(job)}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_job(payload: JobCreate, project_id: int = Query(...)) -> dict[str, Any]:
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind=payload.kind,
|
||||
workflow_id=payload.workflow_id,
|
||||
scene_id=payload.scene_id,
|
||||
payload={
|
||||
"input_values": payload.input_values or {},
|
||||
"character_id": payload.character_id,
|
||||
"location_id": payload.location_id,
|
||||
},
|
||||
)
|
||||
return _job_public(job)
|
||||
|
||||
|
||||
@router.get("/{job_id}")
|
||||
async def get_job(job_id: int) -> dict[str, Any]:
|
||||
job = queue_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
return _job_public(job)
|
||||
|
||||
|
||||
@router.post("/{job_id}/retry")
|
||||
async def retry_job(job_id: int) -> dict[str, Any]:
|
||||
job = queue_manager.retry(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
return _job_public(job)
|
||||
|
||||
|
||||
@router.post("/{job_id}/cancel")
|
||||
async def cancel_job(job_id: int) -> dict[str, Any]:
|
||||
job = queue_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not cancellable")
|
||||
ok = queue_manager.cancel(job_id)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail="Job not cancellable")
|
||||
if job["kind"] == "export":
|
||||
# Export runs local ffmpeg, not Comfy — kill the process instead.
|
||||
kill_running(job_id)
|
||||
else:
|
||||
client = ComfyUIClient()
|
||||
try:
|
||||
await client.interrupt()
|
||||
finally:
|
||||
await client.close()
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,395 @@
|
||||
"""Standalone ComfyUI playground — generate freely, attach favorites to projects."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, File, HTTPException, UploadFile
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from calliope import config
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
PLAYGROUND_STATUS = "system"
|
||||
PLAYGROUND_TITLE = "Playground Scratch"
|
||||
|
||||
|
||||
class PlaygroundGenerate(BaseModel):
|
||||
workflow_id: int
|
||||
input_values: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class PlaygroundAttach(BaseModel):
|
||||
path: str
|
||||
project_id: int
|
||||
target: Literal["character_sheet", "location", "scene"]
|
||||
character_id: int | None = None
|
||||
location_id: int | None = None
|
||||
scene_id: int | None = None
|
||||
|
||||
|
||||
def _job_public(job: dict[str, Any]) -> dict[str, Any]:
|
||||
out = dict(job)
|
||||
out["payload"] = json.loads(job.get("payload_json") or "{}")
|
||||
out["output_paths"] = json.loads(job.get("output_paths_json") or "[]")
|
||||
out.pop("payload_json", None)
|
||||
out.pop("output_paths_json", None)
|
||||
return out
|
||||
|
||||
|
||||
def ensure_playground_project(conn) -> int:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM projects WHERE status = ? ORDER BY id ASC LIMIT 1",
|
||||
(PLAYGROUND_STATUS,),
|
||||
).fetchone()
|
||||
if row:
|
||||
return int(row["id"])
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO projects (title, idea, status)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(
|
||||
PLAYGROUND_TITLE,
|
||||
"System scratch for ComfyUI playground jobs — hidden from project list",
|
||||
PLAYGROUND_STATUS,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
|
||||
|
||||
def _assert_path_in_assets(path: str) -> Path:
|
||||
assets_root = config.settings.assets_dir.resolve()
|
||||
target = Path(path).resolve()
|
||||
try:
|
||||
target.relative_to(assets_root)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=403, detail="Path outside assets directory") from exc
|
||||
if not target.exists() or not target.is_file():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
return target
|
||||
|
||||
|
||||
def _safe_unlink_asset(path_str: str) -> bool:
|
||||
"""Delete a file if it resolves under assets_dir. Missing files count as already gone."""
|
||||
assets_root = config.settings.assets_dir.resolve()
|
||||
try:
|
||||
target = Path(path_str).resolve()
|
||||
target.relative_to(assets_root)
|
||||
except (ValueError, OSError):
|
||||
return False
|
||||
if not target.is_file():
|
||||
return False
|
||||
try:
|
||||
target.unlink()
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
UPLOAD_KIND_BY_EXT: dict[str, str] = {
|
||||
".png": "image",
|
||||
".jpg": "image",
|
||||
".jpeg": "image",
|
||||
".webp": "image",
|
||||
".gif": "image",
|
||||
".bmp": "image",
|
||||
".mp4": "video",
|
||||
".webm": "video",
|
||||
".mov": "video",
|
||||
".mkv": "video",
|
||||
".mp3": "audio",
|
||||
".wav": "audio",
|
||||
".flac": "audio",
|
||||
".ogg": "audio",
|
||||
".m4a": "audio",
|
||||
}
|
||||
|
||||
UPLOAD_CHUNK_SIZE = 1024 * 1024 # 1MB
|
||||
UPLOAD_MAX_BYTES = 500 * 1024 * 1024 # 500MB
|
||||
_UPLOAD_PREFIX_RE = re.compile(r"^[0-9a-f]{8}-")
|
||||
|
||||
|
||||
def _kind_for_ext(ext: str) -> str | None:
|
||||
return UPLOAD_KIND_BY_EXT.get(ext.lower())
|
||||
|
||||
|
||||
def _uploads_dir() -> Path:
|
||||
return config.settings.assets_dir / "uploads"
|
||||
|
||||
|
||||
def _safe_upload_name(filename: str) -> str:
|
||||
return re.sub(r"[^A-Za-z0-9._-]", "_", filename)
|
||||
|
||||
|
||||
def _upload_display_name(filename: str) -> str:
|
||||
"""Strip the uuid prefix written at upload time (``deadbeef-name.png`` → ``name.png``)."""
|
||||
if _UPLOAD_PREFIX_RE.match(filename):
|
||||
return filename[9:]
|
||||
return filename
|
||||
|
||||
|
||||
def _clear_entity_refs(conn, paths: list[str]) -> None:
|
||||
"""If playground outputs were attached to entities, clear those path columns."""
|
||||
for path in paths:
|
||||
conn.execute("UPDATE characters SET portrait_path = NULL WHERE portrait_path = ?", (path,))
|
||||
conn.execute("UPDATE characters SET sheet_path = NULL WHERE sheet_path = ?", (path,))
|
||||
conn.execute(
|
||||
"UPDATE locations SET reference_image_path = NULL WHERE reference_image_path = ?",
|
||||
(path,),
|
||||
)
|
||||
conn.execute("UPDATE scenes SET video_path = NULL WHERE video_path = ?", (path,))
|
||||
|
||||
|
||||
@router.get("/project")
|
||||
async def playground_project() -> dict[str, Any]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
pid = ensure_playground_project(conn)
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (pid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/jobs")
|
||||
async def list_playground_jobs(limit: int = 50) -> list[dict[str, Any]]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
pid = ensure_playground_project(conn)
|
||||
finally:
|
||||
conn.close()
|
||||
return [_job_public(j) for j in queue_manager.list_jobs(pid, None, limit)]
|
||||
|
||||
|
||||
@router.delete("/jobs/{job_id}")
|
||||
async def delete_playground_job(job_id: int) -> dict[str, Any]:
|
||||
"""Delete a playground job row and its output files under assets_dir."""
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
pid = ensure_playground_project(conn)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
job = queue_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
if int(job["project_id"]) != int(pid):
|
||||
raise HTTPException(status_code=403, detail="Not a playground job")
|
||||
|
||||
paths = json.loads(job.get("output_paths_json") or "[]")
|
||||
if not isinstance(paths, list):
|
||||
paths = []
|
||||
|
||||
deleted_files: list[str] = []
|
||||
missing_files: list[str] = []
|
||||
for p in paths:
|
||||
if not isinstance(p, str) or not p.strip():
|
||||
continue
|
||||
if _safe_unlink_asset(p):
|
||||
deleted_files.append(p)
|
||||
else:
|
||||
missing_files.append(p)
|
||||
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
_clear_entity_refs(conn, [p for p in paths if isinstance(p, str)])
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
removed = queue_manager.delete_job(job_id)
|
||||
if not removed:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
await event_bus.publish(
|
||||
"job.deleted",
|
||||
{
|
||||
"job_id": job_id,
|
||||
"source": "playground",
|
||||
"deleted_files": deleted_files,
|
||||
"missing_files": missing_files,
|
||||
},
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"job_id": job_id,
|
||||
"deleted_files": deleted_files,
|
||||
"missing_files": missing_files,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/uploads")
|
||||
async def upload_media(file: UploadFile = File(...)) -> dict[str, Any]:
|
||||
"""Store a client-provided media file under assets_dir/uploads for use as a job input."""
|
||||
original = Path(file.filename or "upload").name
|
||||
ext = Path(original).suffix.lower()
|
||||
kind = _kind_for_ext(ext)
|
||||
if kind is None:
|
||||
allowed = " ".join(sorted(UPLOAD_KIND_BY_EXT))
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unsupported file type '{ext or '(none)'}'. Allowed extensions: {allowed}",
|
||||
)
|
||||
|
||||
uploads = _uploads_dir()
|
||||
uploads.mkdir(parents=True, exist_ok=True)
|
||||
dest = uploads / f"{uuid4().hex[:8]}-{_safe_upload_name(original)}"
|
||||
|
||||
size = 0
|
||||
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)")
|
||||
out.write(chunk)
|
||||
except Exception:
|
||||
dest.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
return {"ok": True, "path": str(dest.resolve()), "name": original, "kind": kind}
|
||||
|
||||
|
||||
@router.get("/uploads")
|
||||
async def list_uploaded_media() -> list[dict[str, Any]]:
|
||||
"""List previously uploaded media files, newest first."""
|
||||
uploads = _uploads_dir()
|
||||
if not uploads.is_dir():
|
||||
return []
|
||||
entries: list[tuple[float, dict[str, Any]]] = []
|
||||
for f in uploads.iterdir():
|
||||
if not f.is_file():
|
||||
continue
|
||||
kind = _kind_for_ext(f.suffix)
|
||||
if kind is None:
|
||||
continue
|
||||
stat = f.stat()
|
||||
entries.append(
|
||||
(
|
||||
stat.st_mtime,
|
||||
{
|
||||
"name": _upload_display_name(f.name),
|
||||
"path": str(f.resolve()),
|
||||
"kind": kind,
|
||||
"size": stat.st_size,
|
||||
"mtime": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat(),
|
||||
},
|
||||
)
|
||||
)
|
||||
entries.sort(key=lambda e: e[0], reverse=True)
|
||||
return [item for _, item in entries]
|
||||
|
||||
|
||||
@router.post("/generate")
|
||||
async def generate(payload: PlaygroundGenerate) -> dict[str, Any]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
pid = ensure_playground_project(conn)
|
||||
wf = conn.execute(
|
||||
"SELECT id, kind, is_enabled FROM workflows WHERE id = ?",
|
||||
(payload.workflow_id,),
|
||||
).fetchone()
|
||||
if not wf:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found")
|
||||
if not wf["is_enabled"]:
|
||||
raise HTTPException(status_code=400, detail="Workflow is disabled")
|
||||
kind = wf["kind"]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
job = queue_manager.enqueue(
|
||||
project_id=pid,
|
||||
kind=kind,
|
||||
workflow_id=payload.workflow_id,
|
||||
scene_id=None,
|
||||
payload={"input_values": payload.input_values, "source": "playground"},
|
||||
)
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{"job_id": job["id"], "kind": kind, "source": "playground", "project_id": pid},
|
||||
)
|
||||
return {"ok": True, "job": _job_public(job)}
|
||||
|
||||
|
||||
@router.post("/attach")
|
||||
async def attach_to_project(payload: PlaygroundAttach) -> dict[str, Any]:
|
||||
path = str(_assert_path_in_assets(payload.path))
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
project = conn.execute(
|
||||
"SELECT id, status FROM projects WHERE id = ?", (payload.project_id,)
|
||||
).fetchone()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
if project["status"] == PLAYGROUND_STATUS:
|
||||
raise HTTPException(status_code=400, detail="Cannot attach to playground scratch")
|
||||
|
||||
if payload.target == "character_sheet":
|
||||
if not payload.character_id:
|
||||
raise HTTPException(status_code=400, detail="character_id required")
|
||||
char = conn.execute(
|
||||
"SELECT id FROM characters WHERE id = ? AND project_id = ?",
|
||||
(payload.character_id, payload.project_id),
|
||||
).fetchone()
|
||||
if not char:
|
||||
raise HTTPException(status_code=404, detail="Character not found")
|
||||
conn.execute(
|
||||
"UPDATE characters SET sheet_path = ? WHERE id = ?",
|
||||
(path, payload.character_id),
|
||||
)
|
||||
elif payload.target == "location":
|
||||
if not payload.location_id:
|
||||
raise HTTPException(status_code=400, detail="location_id required")
|
||||
loc = conn.execute(
|
||||
"SELECT id FROM locations WHERE id = ? AND project_id = ?",
|
||||
(payload.location_id, payload.project_id),
|
||||
).fetchone()
|
||||
if not loc:
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
conn.execute(
|
||||
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
|
||||
(path, payload.location_id),
|
||||
)
|
||||
elif payload.target == "scene":
|
||||
if not payload.scene_id:
|
||||
raise HTTPException(status_code=400, detail="scene_id required")
|
||||
scene = conn.execute(
|
||||
"SELECT id FROM scenes WHERE id = ? AND project_id = ?",
|
||||
(payload.scene_id, payload.project_id),
|
||||
).fetchone()
|
||||
if not scene:
|
||||
raise HTTPException(status_code=404, detail="Scene not found")
|
||||
conn.execute(
|
||||
"UPDATE scenes SET video_path = ? WHERE id = ?",
|
||||
(path, payload.scene_id),
|
||||
)
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail="Invalid target")
|
||||
|
||||
conn.execute(
|
||||
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(payload.project_id,),
|
||||
)
|
||||
conn.commit()
|
||||
await event_bus.publish(
|
||||
"asset.ready",
|
||||
{
|
||||
"path": path,
|
||||
"project_id": payload.project_id,
|
||||
"target": payload.target,
|
||||
"source": "playground_attach",
|
||||
},
|
||||
)
|
||||
return {"ok": True, "path": path, "target": payload.target, "project_id": payload.project_id}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.models.schemas import Project, ProjectCreate, ProjectUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _project_stats(project_id: int, conn) -> dict[str, int]:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM scenes WHERE project_id = :pid) AS scene_count,
|
||||
(SELECT COUNT(*) FROM characters WHERE project_id = :pid) AS character_count,
|
||||
(SELECT COUNT(*) FROM characters WHERE project_id = :pid AND sheet_path IS NOT NULL)
|
||||
+ (SELECT COUNT(*) FROM locations WHERE project_id = :pid AND reference_image_path IS NOT NULL) AS asset_ready_count,
|
||||
(SELECT COUNT(*) FROM characters WHERE project_id = :pid)
|
||||
+ (SELECT COUNT(*) FROM locations WHERE project_id = :pid) AS asset_total_count
|
||||
""",
|
||||
{"pid": project_id},
|
||||
)
|
||||
return dict(cur.fetchone())
|
||||
|
||||
|
||||
@router.post("", response_model=Project)
|
||||
async def create_project(payload: ProjectCreate):
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO projects (title, idea, genre, tone, target_duration)
|
||||
VALUES (:title, :idea, :genre, :tone, :target_duration)
|
||||
""",
|
||||
payload.model_dump(),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("", response_model=list[Project])
|
||||
async def list_projects():
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM projects WHERE status != 'system' ORDER BY updated_at DESC"
|
||||
).fetchall()
|
||||
out = []
|
||||
for row in rows:
|
||||
project = row_to_dict(row)
|
||||
project["stats"] = _project_stats(row["id"], conn)
|
||||
out.append(project)
|
||||
return out
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/{project_id}")
|
||||
async def get_project(project_id: int):
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
project = row_to_dict(row)
|
||||
project["stats"] = _project_stats(project_id, conn)
|
||||
return project
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}", response_model=Project)
|
||||
async def update_project(project_id: int, payload: ProjectUpdate):
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
# exclude_unset keeps explicitly-sent nulls (e.g. clearing cover_path)
|
||||
# while leaving fields the client did not send untouched.
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if not data:
|
||||
return row_to_dict(existing)
|
||||
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data.keys())
|
||||
data["id"] = project_id
|
||||
conn.execute(
|
||||
f"UPDATE projects SET {fields}, updated_at = CURRENT_TIMESTAMP WHERE id = :id",
|
||||
data,
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}")
|
||||
async def delete_project(project_id: int):
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute("DELETE FROM projects WHERE id = ?", (project_id,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,166 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
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
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _scene_with_chars(conn, scene_row) -> dict[str, Any]:
|
||||
scene = row_to_dict(scene_row)
|
||||
chars = conn.execute(
|
||||
"""
|
||||
SELECT c.id, c.name, c.role, c.portrait_path, c.sheet_path
|
||||
FROM characters c
|
||||
JOIN scene_characters sc ON sc.character_id = c.id
|
||||
WHERE sc.scene_id = ?
|
||||
""",
|
||||
(scene["id"],),
|
||||
).fetchall()
|
||||
scene["characters"] = [row_to_dict(c) for c in chars]
|
||||
scene["character_ids"] = [c["id"] for c in scene["characters"]]
|
||||
return scene
|
||||
|
||||
|
||||
@router.get("/{project_id}/scenes")
|
||||
async def list_scenes(project_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if not conn.execute("SELECT id FROM projects WHERE id = ?", (project_id,)).fetchone():
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index",
|
||||
(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}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/{project_id}/generate-script")
|
||||
async def generate_script_endpoint(project_id: int, payload: GenerateScenesRequest | None = None) -> dict[str, Any]:
|
||||
replace = True if payload is None else payload.replace
|
||||
scene_count = None if payload is None else payload.scene_count
|
||||
try:
|
||||
return await generate_script(project_id, replace=replace, scene_count=scene_count)
|
||||
except ValueError as exc:
|
||||
# Distinguish not-found vs constraint failures
|
||||
detail = str(exc)
|
||||
code = 404 if "not found" in detail.lower() 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)
|
||||
try:
|
||||
if not conn.execute("SELECT id FROM projects WHERE id = ?", (project_id,)).fetchone():
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO scenes
|
||||
(project_id, beat_id, order_index, heading, action, dialog, duration_sec,
|
||||
workflow_id, env_image_path, location_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
project_id,
|
||||
payload.beat_id,
|
||||
payload.order_index,
|
||||
payload.heading,
|
||||
payload.action,
|
||||
payload.dialog,
|
||||
payload.duration_sec,
|
||||
payload.workflow_id,
|
||||
payload.env_image_path,
|
||||
payload.location_id,
|
||||
),
|
||||
)
|
||||
scene_id = cur.lastrowid
|
||||
for cid in payload.character_ids:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO scene_characters (scene_id, character_id) VALUES (?, ?)",
|
||||
(scene_id, cid),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone()
|
||||
return _scene_with_chars(conn, row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}/scenes/{scene_id}")
|
||||
async def update_scene(project_id: int, scene_id: int, payload: SceneUpdate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
|
||||
(scene_id, project_id),
|
||||
).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Scene not found")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
char_ids = data.pop("character_ids", None)
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = scene_id
|
||||
conn.execute(f"UPDATE scenes SET {fields} WHERE id = :id", data)
|
||||
if char_ids is not None:
|
||||
conn.execute("DELETE FROM scene_characters WHERE scene_id = ?", (scene_id,))
|
||||
for cid in char_ids:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO scene_characters (scene_id, character_id) VALUES (?, ?)",
|
||||
(scene_id, cid),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone()
|
||||
return _scene_with_chars(conn, row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}/scenes/{scene_id}")
|
||||
async def delete_scene(project_id: int, scene_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
conn.execute("DELETE FROM scene_characters WHERE scene_id = ?", (scene_id,))
|
||||
cur = conn.execute(
|
||||
"DELETE FROM scenes WHERE id = ? AND project_id = ?",
|
||||
(scene_id, project_id),
|
||||
)
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Scene not found")
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/{project_id}/scenes/reorder")
|
||||
async def reorder_scenes(project_id: int, payload: SceneReorder) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
for index, scene_id in enumerate(payload.scene_ids, start=1):
|
||||
conn.execute(
|
||||
"UPDATE scenes SET order_index = ? WHERE id = ? AND project_id = ?",
|
||||
(index, scene_id, project_id),
|
||||
)
|
||||
conn.commit()
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
return {"scenes": [_scene_with_chars(conn, r) for r in rows]}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from calliope.config import normalize_path, settings
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class SettingsUpdate(BaseModel):
|
||||
llm_base_url: str | None = None
|
||||
llm_model: str | None = None
|
||||
llm_api_key: str | None = None
|
||||
comfyui_base_url: str | None = None
|
||||
data_dir: str | None = None
|
||||
assets_dir: str | None = None
|
||||
queue_concurrency: int | None = Field(None, ge=1, le=8)
|
||||
queue_poll_interval_sec: float | None = Field(None, ge=0.5, le=60.0)
|
||||
queue_max_retries: int | None = Field(None, ge=0, le=10)
|
||||
dry_run: bool | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_settings() -> dict[str, Any]:
|
||||
return settings.to_public_dict()
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def update_settings(payload: SettingsUpdate) -> dict[str, Any]:
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
for key, value in data.items():
|
||||
if key in {"data_dir", "assets_dir"}:
|
||||
path = normalize_path(value)
|
||||
if path is not None:
|
||||
setattr(settings, key, path)
|
||||
continue
|
||||
if key == "dry_run":
|
||||
setattr(settings, key, bool(value))
|
||||
continue
|
||||
setattr(settings, key, value)
|
||||
|
||||
settings.save_config_file()
|
||||
return settings.to_public_dict()
|
||||
@@ -0,0 +1,460 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from calliope.agent.llm import generate_structured
|
||||
from calliope.agent.prompts import (
|
||||
build_story_messages,
|
||||
character_sheet_prompt,
|
||||
location_reference_prompt,
|
||||
recommend_beat_count,
|
||||
story_generation_user_prompt,
|
||||
)
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.models.schemas import (
|
||||
BeatCreate,
|
||||
BeatUpdate,
|
||||
CharacterCreate,
|
||||
CharacterUpdate,
|
||||
LocationCreate,
|
||||
LocationUpdate,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("calliope.story")
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _touch_project(conn, project_id: int) -> None:
|
||||
conn.execute(
|
||||
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(project_id,),
|
||||
)
|
||||
|
||||
|
||||
def _require_project(conn, project_id: int) -> dict[str, Any]:
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return row_to_dict(row)
|
||||
|
||||
|
||||
@router.post("/{project_id}/generate-story")
|
||||
async def generate_story(project_id: int, replace: bool = True) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = _require_project(conn, project_id)
|
||||
|
||||
required_beats = recommend_beat_count(project.get("target_duration"))
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"message": (
|
||||
f"Drafting storyline for \"{project['title']}\" "
|
||||
f"(target {project.get('target_duration') or '?'} -> {required_beats} beats)..."
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
messages = build_story_messages(
|
||||
title=project["title"],
|
||||
idea=project["idea"],
|
||||
genre=project["genre"],
|
||||
tone=project["tone"],
|
||||
target_duration=project["target_duration"],
|
||||
)
|
||||
result = await generate_structured(messages, temperature=0.7)
|
||||
beats_out = result.get("beats") or []
|
||||
|
||||
# Models often under-deliver on long runtimes — one corrective retry.
|
||||
if len(beats_out) < required_beats:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"message": (
|
||||
f"Model returned {len(beats_out)} beats; "
|
||||
f"required {required_beats}. Retrying..."
|
||||
),
|
||||
},
|
||||
)
|
||||
repair = [
|
||||
{"role": "system", "content": messages[0]["content"]},
|
||||
{
|
||||
"role": "user",
|
||||
"content": story_generation_user_prompt(
|
||||
project["title"],
|
||||
project["idea"],
|
||||
project["genre"],
|
||||
project["tone"],
|
||||
project["target_duration"],
|
||||
)
|
||||
+ (
|
||||
f"\n\nPREVIOUS ATTEMPT FAILED: it only had {len(beats_out)} beats. "
|
||||
f"You MUST return exactly {required_beats} beats this time."
|
||||
),
|
||||
},
|
||||
]
|
||||
result = await generate_structured(repair, temperature=0.4)
|
||||
beats_out = result.get("beats") or []
|
||||
if len(beats_out) < required_beats:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=(
|
||||
f"Story draft returned {len(beats_out)} 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,))
|
||||
|
||||
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,
|
||||
},
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
beat_n = len(result.get("beats", []))
|
||||
await event_bus.publish(
|
||||
"story.ready",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"message": f"Story drafted — {beat_n} beats",
|
||||
},
|
||||
)
|
||||
return {"ok": True, "project_id": project_id, "generated": result}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.exception("Story generation failed for project %s", project_id)
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{"project_id": project_id, "message": f"Story draft failed: {exc}"},
|
||||
)
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/{project_id}/story")
|
||||
async def get_story(project_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = conn.execute(
|
||||
"SELECT id, title, idea, genre, tone, target_duration, status FROM projects WHERE id = ?",
|
||||
(project_id,),
|
||||
).fetchone()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
beats = conn.execute(
|
||||
"SELECT id, order_index, title, description FROM story_beats WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
characters = conn.execute(
|
||||
"""
|
||||
SELECT id, name, role, age, appearance, personality, portrait_path, sheet_path, consistency_prompt
|
||||
FROM characters WHERE project_id = ?
|
||||
""",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
locations = conn.execute(
|
||||
"""
|
||||
SELECT id, name, description, reference_image_path, consistency_prompt
|
||||
FROM locations WHERE project_id = ?
|
||||
""",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
|
||||
return {
|
||||
"project": row_to_dict(project),
|
||||
"beats": [row_to_dict(b) for b in beats],
|
||||
"characters": [row_to_dict(c) for c in characters],
|
||||
"locations": [row_to_dict(l) for l in locations],
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# --- Beats CRUD ---
|
||||
|
||||
|
||||
@router.post("/{project_id}/beats")
|
||||
async def create_beat(project_id: int, payload: BeatCreate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
_require_project(conn, project_id)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO story_beats (project_id, order_index, title, description)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""",
|
||||
(project_id, payload.order_index, payload.title, payload.description),
|
||||
)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM story_beats WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}/beats/{beat_id}")
|
||||
async def update_beat(project_id: int, beat_id: int, payload: BeatUpdate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM story_beats WHERE id = ? AND project_id = ?",
|
||||
(beat_id, project_id),
|
||||
).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Beat not found")
|
||||
data = {k: v for k, v in payload.model_dump().items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = beat_id
|
||||
conn.execute(f"UPDATE story_beats SET {fields} WHERE id = :id", data)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM story_beats WHERE id = ?", (beat_id,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}/beats/{beat_id}")
|
||||
async def delete_beat(project_id: int, beat_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM story_beats WHERE id = ? AND project_id = ?",
|
||||
(beat_id, project_id),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Beat not found")
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# --- Characters CRUD ---
|
||||
|
||||
|
||||
@router.post("/{project_id}/characters")
|
||||
async def create_character(project_id: int, payload: CharacterCreate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
_require_project(conn, project_id)
|
||||
consistency = payload.consistency_prompt or character_sheet_prompt(
|
||||
{
|
||||
"name": payload.name,
|
||||
"role": payload.role,
|
||||
"age": payload.age,
|
||||
"appearance": payload.appearance,
|
||||
"personality": payload.personality,
|
||||
}
|
||||
)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO characters
|
||||
(project_id, name, role, age, appearance, personality, consistency_prompt)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
project_id,
|
||||
payload.name,
|
||||
payload.role,
|
||||
payload.age,
|
||||
payload.appearance,
|
||||
payload.personality,
|
||||
consistency,
|
||||
),
|
||||
)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM characters WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}/characters/{character_id}")
|
||||
async def update_character(
|
||||
project_id: int, character_id: int, payload: CharacterUpdate
|
||||
) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM characters WHERE id = ? AND project_id = ?",
|
||||
(character_id, project_id),
|
||||
).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Character not found")
|
||||
data = {k: v for k, v in payload.model_dump().items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = character_id
|
||||
conn.execute(f"UPDATE characters SET {fields} WHERE id = :id", data)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM characters WHERE id = ?", (character_id,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}/characters/{character_id}")
|
||||
async def delete_character(project_id: int, character_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM characters WHERE id = ? AND project_id = ?",
|
||||
(character_id, project_id),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Character not found")
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# --- Locations CRUD ---
|
||||
|
||||
|
||||
@router.post("/{project_id}/locations")
|
||||
async def create_location(project_id: int, payload: LocationCreate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
_require_project(conn, project_id)
|
||||
consistency = payload.consistency_prompt or location_reference_prompt(
|
||||
{"name": payload.name, "description": payload.description}
|
||||
)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO locations (project_id, name, description, consistency_prompt)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""",
|
||||
(project_id, payload.name, payload.description, consistency),
|
||||
)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM locations WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}/locations/{location_id}")
|
||||
async def update_location(
|
||||
project_id: int, location_id: int, payload: LocationUpdate
|
||||
) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM locations WHERE id = ? AND project_id = ?",
|
||||
(location_id, project_id),
|
||||
).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
data = {k: v for k, v in payload.model_dump().items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = location_id
|
||||
conn.execute(f"UPDATE locations SET {fields} WHERE id = :id", data)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM locations WHERE id = ?", (location_id,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}/locations/{location_id}")
|
||||
async def delete_location(project_id: int, location_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM locations WHERE id = ? AND project_id = ?",
|
||||
(location_id, project_id),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs, parse_dynamic_outputs
|
||||
from calliope.comfyui.profiles import detect_prompt_profile
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.models.schemas import WorkflowAnalyze, WorkflowCreate, WorkflowUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _serialize_workflow(row: Any) -> dict[str, Any]:
|
||||
data = row_to_dict(row)
|
||||
data["workflow_json"] = json.loads(data["workflow_json"])
|
||||
data["input_schema"] = json.loads(data["input_schema"]) if data.get("input_schema") else []
|
||||
data["output_schema"] = json.loads(data["output_schema"]) if data.get("output_schema") else []
|
||||
data["is_enabled"] = bool(data.get("is_enabled"))
|
||||
return data
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze_workflow(payload: WorkflowAnalyze) -> dict[str, Any]:
|
||||
inputs = parse_dynamic_inputs(payload.workflow_json)
|
||||
outputs = parse_dynamic_outputs(payload.workflow_json)
|
||||
return {
|
||||
"inputs": inputs,
|
||||
"outputs": outputs,
|
||||
"suggested_profile": detect_prompt_profile(payload.workflow_json),
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_workflows() -> list[dict[str, Any]]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
rows = conn.execute("SELECT * FROM workflows ORDER BY id DESC").fetchall()
|
||||
return [_serialize_workflow(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
|
||||
inputs = parse_dynamic_inputs(payload.workflow_json)
|
||||
outputs = parse_dynamic_outputs(payload.workflow_json)
|
||||
profile = payload.prompt_profile or detect_prompt_profile(payload.workflow_json)
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO workflows (name, kind, workflow_json, input_schema,
|
||||
output_schema, description, prompt_profile, is_enabled)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 1)
|
||||
""",
|
||||
(
|
||||
payload.name,
|
||||
payload.kind,
|
||||
json.dumps(payload.workflow_json),
|
||||
json.dumps(inputs),
|
||||
json.dumps(outputs),
|
||||
payload.description,
|
||||
profile,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return _serialize_workflow(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/{workflow_id}")
|
||||
async def get_workflow(workflow_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found")
|
||||
return _serialize_workflow(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{workflow_id}")
|
||||
async def update_workflow(workflow_id: int, payload: WorkflowUpdate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "is_enabled" in data and data["is_enabled"] is not None:
|
||||
data["is_enabled"] = 1 if data["is_enabled"] else 0
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = workflow_id
|
||||
conn.execute(f"UPDATE workflows SET {fields} WHERE id = :id", data)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
|
||||
return _serialize_workflow(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{workflow_id}")
|
||||
async def delete_workflow(workflow_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute("DELETE FROM workflows WHERE id = ?", (workflow_id,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found")
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from calliope.db import migrate_db
|
||||
from calliope.main import create_app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
import calliope.config as config_module
|
||||
|
||||
# Mutate singleton in place so all `from calliope.config import settings` refs update
|
||||
s = config_module.settings
|
||||
prev = {
|
||||
"data_dir": s.data_dir,
|
||||
"assets_dir": s.assets_dir,
|
||||
"dry_run": s.dry_run,
|
||||
"queue_poll_interval_sec": s.queue_poll_interval_sec,
|
||||
}
|
||||
s.data_dir = Path(tmpdir)
|
||||
s.assets_dir = Path(tmpdir) / "assets"
|
||||
s.dry_run = True
|
||||
s.queue_poll_interval_sec = 0.5
|
||||
# Never persist temp test paths into the real calliope_config.json
|
||||
monkeypatch.setattr(config_module.Settings, "save_config_file", lambda self: None)
|
||||
asyncio.run(migrate_db(s.db_path))
|
||||
app = create_app()
|
||||
try:
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
finally:
|
||||
for k, v in prev.items():
|
||||
setattr(s, k, v)
|
||||
@@ -0,0 +1,207 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from calliope.comfyui.client import ComfyUIClient
|
||||
from calliope.export.runner import build_ffmpeg_cmd, collect_clips
|
||||
|
||||
|
||||
def _make_project_with_clips(client, title: str = "My Film") -> int:
|
||||
pid = client.post("/api/projects", json={"title": title}).json()["id"]
|
||||
s1 = client.post(
|
||||
f"/api/projects/{pid}/scenes", json={"order_index": 1, "heading": "Opening"}
|
||||
).json()
|
||||
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"}
|
||||
)
|
||||
return pid
|
||||
|
||||
|
||||
def test_build_ffmpeg_cmd_two_clips():
|
||||
clips = [{"video_path": "a.mp4"}, {"video_path": "b.mp4"}]
|
||||
probes = [
|
||||
{"duration": 8.02, "has_audio": True},
|
||||
{"duration": 8.0, "has_audio": True},
|
||||
]
|
||||
cmd = build_ffmpeg_cmd(clips, probes, Path("out.mp4"))
|
||||
joined = " ".join(str(c) for c in cmd)
|
||||
# offset = 8.02 - 0.5 = 7.52
|
||||
assert "xfade=transition=fade:duration=0.5:offset=7.52" in joined
|
||||
assert "acrossfade=d=0.5:c1=tri:c2=tri" in joined
|
||||
# format=yuv420p must come AFTER the xfade output label
|
||||
assert "[x1]format=yuv420p[vout]" in joined
|
||||
assert "loudnorm=I=-16:TP=-1.5:LRA=11" in joined
|
||||
assert "scale=1920:1080:force_original_aspect_ratio=decrease" in joined
|
||||
assert "fps=30" in joined
|
||||
assert "-c:v libx264" in joined
|
||||
assert "-crf 20" in joined
|
||||
assert "-b:a 192k" in joined
|
||||
assert "-movflags +faststart" in joined
|
||||
assert "-progress pipe:1" in joined
|
||||
assert "anullsrc" not in joined
|
||||
assert cmd[-1] == "out.mp4"
|
||||
|
||||
|
||||
def test_build_ffmpeg_cmd_anullsrc_for_silent_clip():
|
||||
clips = [{"video_path": "a.mp4"}, {"video_path": "b.mp4"}]
|
||||
probes = [
|
||||
{"duration": 8.0, "has_audio": True},
|
||||
{"duration": 4.0, "has_audio": False},
|
||||
]
|
||||
cmd = build_ffmpeg_cmd(clips, probes, "out.mp4")
|
||||
joined = " ".join(str(c) for c in cmd)
|
||||
# One lavfi silence donor input appended after the 2 clip inputs (index 2)
|
||||
assert joined.count("-f lavfi -i anullsrc=cl=stereo:r=48000") == 1
|
||||
assert (
|
||||
"[2:a]atrim=duration=4.000,asetpts=PTS-STARTPTS,"
|
||||
"aformat=sample_rates=48000:channel_layouts=stereo[a1]" in joined
|
||||
)
|
||||
# Real clip keeps its own audio chain
|
||||
assert "[0:a]aformat=sample_rates=48000:channel_layouts=stereo[a0]" in joined
|
||||
assert "xfade=transition=fade:duration=0.5:offset=7.500" in joined
|
||||
|
||||
|
||||
def test_build_ffmpeg_cmd_single_clip():
|
||||
cmd = build_ffmpeg_cmd(
|
||||
[{"video_path": "a.mp4"}], [{"duration": 5.0, "has_audio": True}], "out.mp4"
|
||||
)
|
||||
joined = " ".join(str(c) for c in cmd)
|
||||
assert "xfade" not in joined
|
||||
assert "acrossfade" not in joined
|
||||
assert "[v0]format=yuv420p[vout]" in joined
|
||||
assert "[a0]loudnorm=I=-16:TP=-1.5:LRA=11[aout]" in joined
|
||||
assert "-c:v libx264" in joined
|
||||
|
||||
|
||||
def test_build_ffmpeg_cmd_no_clips_raises():
|
||||
with pytest.raises(RuntimeError):
|
||||
build_ffmpeg_cmd([], [], "out.mp4")
|
||||
|
||||
|
||||
def test_collect_clips_split_and_order(client):
|
||||
pid = client.post("/api/projects", json={"title": "Order"}).json()["id"]
|
||||
s_b = client.post(
|
||||
f"/api/projects/{pid}/scenes", json={"order_index": 2, "heading": "B"}
|
||||
).json()
|
||||
s_a = client.post(
|
||||
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"})
|
||||
|
||||
clips, skipped = collect_clips(pid)
|
||||
assert [c["heading"] for c in clips] == ["A", "B"]
|
||||
assert [s["heading"] for s in skipped] == ["C"]
|
||||
|
||||
|
||||
def test_export_requires_scene_clips(client):
|
||||
pid = client.post("/api/projects", json={"title": "Empty"}).json()["id"]
|
||||
client.post(f"/api/projects/{pid}/scenes", json={"order_index": 1, "heading": "No clip"})
|
||||
r = client.post(f"/api/jobs/projects/{pid}/export")
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_export_supersedes_pending(client):
|
||||
pid = _make_project_with_clips(client)
|
||||
try:
|
||||
client.post("/api/jobs/pause")
|
||||
r1 = client.post(f"/api/jobs/projects/{pid}/export")
|
||||
r2 = client.post(f"/api/jobs/projects/{pid}/export")
|
||||
assert r1.status_code == 200
|
||||
assert r2.status_code == 200
|
||||
j1 = client.get(f"/api/jobs/{r1.json()['job']['id']}").json()
|
||||
assert j1["status"] == "failed"
|
||||
assert "superseded" in j1["error"]
|
||||
j2 = client.get(f"/api/jobs/{r2.json()['job']['id']}").json()
|
||||
assert j2["status"] == "pending"
|
||||
assert j2["kind"] == "export"
|
||||
finally:
|
||||
client.post("/api/jobs/resume")
|
||||
|
||||
|
||||
def test_export_job_dry_run(client):
|
||||
pid = _make_project_with_clips(client)
|
||||
r = client.post(f"/api/jobs/projects/{pid}/export")
|
||||
assert r.status_code == 200
|
||||
job = r.json()["job"]
|
||||
assert job["kind"] == "export"
|
||||
|
||||
final = None
|
||||
for _ in range(40):
|
||||
time.sleep(0.25)
|
||||
got = client.get(f"/api/jobs/{job['id']}").json()
|
||||
if got["status"] in {"done", "failed"}:
|
||||
final = got
|
||||
break
|
||||
assert final is not None, "export job never finished"
|
||||
assert final["status"] == "done", final
|
||||
outputs = final["output_paths"]
|
||||
assert len(outputs) == 1
|
||||
norm = outputs[0].replace("\\", "/")
|
||||
assert f"/{pid}/export/" in norm
|
||||
assert norm.endswith(f"my-film-job{job['id']}.mp4")
|
||||
assert Path(outputs[0]).exists()
|
||||
|
||||
# A finished export closes the project lifecycle
|
||||
project = client.get(f"/api/projects/{pid}").json()
|
||||
assert project["status"] == "completed"
|
||||
|
||||
|
||||
def test_cancel_export_skips_comfy_interrupt(client, monkeypatch):
|
||||
calls = {"interrupt": 0, "kill": 0}
|
||||
|
||||
async def fake_interrupt(self):
|
||||
calls["interrupt"] += 1
|
||||
|
||||
def fake_kill(job_id: int) -> bool:
|
||||
calls["kill"] += 1
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(ComfyUIClient, "interrupt", fake_interrupt)
|
||||
monkeypatch.setattr("calliope.routers.jobs.kill_running", fake_kill)
|
||||
|
||||
pid = _make_project_with_clips(client)
|
||||
try:
|
||||
client.post("/api/jobs/pause")
|
||||
job_id = client.post(f"/api/jobs/projects/{pid}/export").json()["job"]["id"]
|
||||
r = client.post(f"/api/jobs/{job_id}/cancel")
|
||||
assert r.status_code == 200
|
||||
assert calls["kill"] == 1
|
||||
assert calls["interrupt"] == 0
|
||||
finally:
|
||||
client.post("/api/jobs/resume")
|
||||
|
||||
|
||||
def test_cancel_comfy_job_calls_interrupt(client, monkeypatch):
|
||||
calls = {"interrupt": 0, "kill": 0}
|
||||
|
||||
async def fake_interrupt(self):
|
||||
calls["interrupt"] += 1
|
||||
|
||||
def fake_kill(job_id: int) -> bool:
|
||||
calls["kill"] += 1
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(ComfyUIClient, "interrupt", fake_interrupt)
|
||||
monkeypatch.setattr("calliope.routers.jobs.kill_running", fake_kill)
|
||||
|
||||
pid = client.post("/api/projects", json={"title": "Comfy"}).json()["id"]
|
||||
try:
|
||||
client.post("/api/jobs/pause")
|
||||
job_id = client.post(f"/api/jobs?project_id={pid}", json={"kind": "image"}).json()["id"]
|
||||
r = client.post(f"/api/jobs/{job_id}/cancel")
|
||||
assert r.status_code == 200
|
||||
assert calls["interrupt"] == 1
|
||||
assert calls["kill"] == 0
|
||||
finally:
|
||||
client.post("/api/jobs/resume")
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Tests for the MiniMax H3 ref2video prompt profile."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from calliope.agent.prompts import minimax_h3_ref_fallback
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs, parse_dynamic_outputs
|
||||
from calliope.comfyui.profiles import detect_prompt_profile
|
||||
from calliope.comfyui.smart_fill import ref_image_slots, smart_fill_inputs
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
H3_WORKFLOW = REPO_ROOT / "ComfyAPI" / "video_minimax_h3_r2v_API.json"
|
||||
KREA_WORKFLOW = REPO_ROOT / "ComfyAPI" / "krea2_t2i_2pass-nsfwEnable-API.json"
|
||||
|
||||
|
||||
def _load(path: Path) -> dict:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def test_h3_workflow_parses_expected_roles():
|
||||
workflow = _load(H3_WORKFLOW)
|
||||
inputs = parse_dynamic_inputs(workflow)
|
||||
by_node = {i["nodeId"]: i for i in inputs}
|
||||
|
||||
assert by_node["138"]["role"] == "prompt"
|
||||
assert by_node["132"]["role"] == "duration"
|
||||
image_slots = [i["nodeId"] for i in ref_image_slots(inputs)]
|
||||
assert image_slots == ["148", "149"] # node-id order = ref wiring order
|
||||
|
||||
outputs = parse_dynamic_outputs(workflow)
|
||||
assert any(o["nodeId"] == "153" and o["kind"] == "video" for o in outputs)
|
||||
|
||||
|
||||
def test_detect_prompt_profile():
|
||||
assert detect_prompt_profile(_load(H3_WORKFLOW)) == "minimax_h3_ref"
|
||||
assert detect_prompt_profile(_load(KREA_WORKFLOW)) == "prose"
|
||||
|
||||
|
||||
def test_smart_fill_ref_images_and_duration():
|
||||
inputs = parse_dynamic_inputs(_load(H3_WORKFLOW))
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt="six-section h3 prompt",
|
||||
ref_images=["char.png", "loc.png", "surplus.png"],
|
||||
duration=8,
|
||||
)
|
||||
assert values["138"] == "six-section h3 prompt"
|
||||
assert values["148"] == "char.png"
|
||||
assert values["149"] == "loc.png"
|
||||
assert "surplus.png" not in values.values()
|
||||
assert values["132"] == 8
|
||||
|
||||
|
||||
def test_smart_fill_ref_images_user_extra_wins():
|
||||
inputs = parse_dynamic_inputs(_load(H3_WORKFLOW))
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
ref_images=["char.png"],
|
||||
extra={"148": "user-override.png"},
|
||||
)
|
||||
assert values["148"] == "user-override.png"
|
||||
|
||||
|
||||
def test_h3_fallback_prompt_structure():
|
||||
scene = {
|
||||
"heading": "INT. COFFEE SHOP - DAY",
|
||||
"action": "Mia sits on the orange sofa, guarding a cookie.",
|
||||
"dialog": "MIA: Hey! Watch your dog!\nNARRATOR: Later that day.",
|
||||
"duration_sec": 6,
|
||||
}
|
||||
subjects = [
|
||||
{
|
||||
"index": 1,
|
||||
"kind": "character",
|
||||
"name": "Mia",
|
||||
"appearance": "long dark hair, blue cardigan",
|
||||
},
|
||||
{
|
||||
"index": 2,
|
||||
"kind": "location",
|
||||
"name": "Coffee Shop",
|
||||
"appearance": "exposed brick wall, neon sign",
|
||||
},
|
||||
]
|
||||
text = minimax_h3_ref_fallback(scene, subjects)
|
||||
|
||||
sections = [
|
||||
"subject_definitions:",
|
||||
"summary:",
|
||||
"retention_analysis:",
|
||||
"detailed_description:",
|
||||
"overall_soundscape:",
|
||||
"non_diegetic_music:",
|
||||
]
|
||||
positions = [text.index(s) for s in sections]
|
||||
assert positions == sorted(positions), "sections must appear in the canonical order"
|
||||
|
||||
assert '<Subject 1> is the character "Mia" in <Picture 1>' in text
|
||||
assert '<Subject 2> is the location "Coffee Shop" in <Picture 2>' in text
|
||||
assert text.count("fully_preserved") == 2
|
||||
assert "[reference generation]" in text
|
||||
assert "[Shot 1]" in text
|
||||
assert "<Subject 1> (S1) says, <d>[English] Hey! Watch your dog!</d>" in text
|
||||
# Narrator has no subject → stable voice description with its own speaker ID
|
||||
assert "Narrator (S2) says, <d>[English] Later that day.</d>" in text
|
||||
|
||||
|
||||
def test_h3_fallback_without_subjects_or_dialog():
|
||||
scene = {"heading": "EXT. FOREST - NIGHT", "action": "Fog drifts between trees."}
|
||||
text = minimax_h3_ref_fallback(scene, [])
|
||||
assert "detailed_description:" in text
|
||||
assert "[Shot 1]" in text
|
||||
assert "<d>" not in text
|
||||
|
||||
|
||||
def test_h3_fallback_dialog_delivery_cue():
|
||||
scene = {
|
||||
"heading": "INT. HALL - NIGHT",
|
||||
"action": "Mia freezes.",
|
||||
"dialog": "MIA (whispering): Did you hear that?",
|
||||
}
|
||||
subjects = [
|
||||
{"index": 1, "kind": "character", "name": "Mia", "appearance": "chestnut ponytail"},
|
||||
]
|
||||
text = minimax_h3_ref_fallback(scene, subjects)
|
||||
# Cue kept as delivery direction; speaker still matched to the subject
|
||||
assert "<Subject 1> (S1) says whispering, <d>[English] Did you hear that?</d>" in text
|
||||
@@ -0,0 +1,165 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs, parse_dynamic_outputs
|
||||
from calliope.comfyui.patcher import patch_workflow
|
||||
|
||||
|
||||
SAMPLE_WORKFLOW = {
|
||||
"102": {
|
||||
"inputs": {"value": 1280},
|
||||
"class_type": "PrimitiveInt",
|
||||
"_meta": {"title": "Width (Input:width)"},
|
||||
},
|
||||
"209": {
|
||||
"inputs": {"value": "My prompt"},
|
||||
"class_type": "PrimitiveStringMultiline",
|
||||
"_meta": {"title": "Text Prompt (Input:prompt)"},
|
||||
},
|
||||
"10": {
|
||||
"inputs": {"image": "x.png"},
|
||||
"class_type": "LoadImage",
|
||||
"_meta": {"title": "Reference Image (Input:character)"},
|
||||
},
|
||||
"99": {
|
||||
"inputs": {"filename_prefix": "out"},
|
||||
"class_type": "SaveImage",
|
||||
"_meta": {"title": "Final Image (Output:image)"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_parse_dynamic_inputs_outputs():
|
||||
inputs = parse_dynamic_inputs(SAMPLE_WORKFLOW)
|
||||
outputs = parse_dynamic_outputs(SAMPLE_WORKFLOW)
|
||||
assert len(inputs) == 3
|
||||
assert {i["kind"] for i in inputs} >= {"number", "textarea", "image"}
|
||||
by_role = {i["role"]: i for i in inputs}
|
||||
assert by_role["width"]["nodeId"] == "102"
|
||||
assert by_role["prompt"]["nodeId"] == "209"
|
||||
assert by_role["character"]["nodeId"] == "10"
|
||||
assert len(outputs) == 1
|
||||
assert outputs[0]["kind"] == "image"
|
||||
assert outputs[0]["role"] == "image"
|
||||
|
||||
|
||||
def test_patch_workflow_by_node_id():
|
||||
patched = patch_workflow(SAMPLE_WORKFLOW, {"209": "New prompt", "102": 720, "10": "ref.png"})
|
||||
assert patched["209"]["inputs"]["value"] == "New prompt"
|
||||
assert patched["102"]["inputs"]["value"] == 720
|
||||
assert patched["10"]["inputs"]["image"] == "ref.png"
|
||||
|
||||
|
||||
def test_workflow_analyze_and_create(client):
|
||||
r = client.post("/api/workflows/analyze", json={"workflow_json": SAMPLE_WORKFLOW})
|
||||
assert r.status_code == 200
|
||||
assert len(r.json()["inputs"]) == 3
|
||||
|
||||
r = client.post(
|
||||
"/api/workflows",
|
||||
json={"name": "Test WF", "kind": "image", "workflow_json": SAMPLE_WORKFLOW},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["name"] == "Test WF"
|
||||
assert len(data["input_schema"]) == 3
|
||||
|
||||
|
||||
def test_story_replace_on_regenerate(client, monkeypatch):
|
||||
async def fake_structured(messages, temperature=0.7):
|
||||
return {
|
||||
"title": "T",
|
||||
"logline": "L",
|
||||
"beats": [
|
||||
{"order_index": i, "title": f"B{i}", "description": "d"} for i in range(1, 5)
|
||||
],
|
||||
"characters": [
|
||||
{
|
||||
"name": "Hero",
|
||||
"role": "protagonist",
|
||||
"age": "20",
|
||||
"appearance": "tall",
|
||||
"personality": "brave",
|
||||
}
|
||||
],
|
||||
"locations": [{"name": "Forest", "description": "dark woods"}],
|
||||
}
|
||||
|
||||
monkeypatch.setattr("calliope.routers.story.generate_structured", fake_structured)
|
||||
|
||||
r = client.post("/api/projects", json={"title": "P", "idea": "idea"})
|
||||
pid = r.json()["id"]
|
||||
r = client.post(f"/api/projects/{pid}/generate-story")
|
||||
assert r.status_code == 200
|
||||
r = client.get(f"/api/projects/{pid}/story")
|
||||
assert len(r.json()["beats"]) == 4
|
||||
assert len(r.json()["characters"]) == 1
|
||||
|
||||
# regenerate should replace, not append
|
||||
r = client.post(f"/api/projects/{pid}/generate-story")
|
||||
assert r.status_code == 200
|
||||
r = client.get(f"/api/projects/{pid}/story")
|
||||
assert len(r.json()["beats"]) == 4
|
||||
assert len(r.json()["characters"]) == 1
|
||||
|
||||
|
||||
def test_enqueue_dry_run_job(client):
|
||||
r = client.post("/api/projects", json={"title": "Q"})
|
||||
pid = r.json()["id"]
|
||||
r = client.post(
|
||||
"/api/workflows",
|
||||
json={"name": "Img", "kind": "image", "workflow_json": SAMPLE_WORKFLOW},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
# create character manually via story path monkeypatch-less insert through generate-assets empty
|
||||
# use character create endpoint
|
||||
r = client.post(
|
||||
f"/api/projects/{pid}/characters",
|
||||
json={"name": "A", "appearance": "blue hair"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
r = client.post(f"/api/projects/{pid}/generate-assets", json={"missing_only": True})
|
||||
assert r.status_code == 200
|
||||
jobs = r.json()["jobs"]
|
||||
assert len(jobs) >= 1
|
||||
|
||||
# wait briefly for dry-run worker
|
||||
import time
|
||||
|
||||
done = False
|
||||
for _ in range(20):
|
||||
time.sleep(0.25)
|
||||
listed = client.get(f"/api/jobs?project_id={pid}").json()
|
||||
if listed and listed[0]["status"] in {"done", "failed"}:
|
||||
done = listed[0]["status"] == "done"
|
||||
break
|
||||
assert done
|
||||
|
||||
|
||||
def test_settings_dry_run(client):
|
||||
r = client.get("/api/settings")
|
||||
assert r.status_code == 200
|
||||
assert "dry_run" in r.json()
|
||||
r = client.post("/api/settings", json={"dry_run": True})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["dry_run"] is True
|
||||
|
||||
|
||||
def test_duration_beat_budget():
|
||||
from calliope.agent.prompts import (
|
||||
estimate_target_seconds,
|
||||
recommend_beat_count,
|
||||
story_generation_user_prompt,
|
||||
)
|
||||
|
||||
assert estimate_target_seconds("2 minutes") == 120
|
||||
assert recommend_beat_count("2 minutes") == 10
|
||||
assert recommend_beat_count("medium (~2 min)") == 10
|
||||
assert recommend_beat_count("10 minutes") == 50
|
||||
assert recommend_beat_count("30 seconds") == 4
|
||||
prompt = story_generation_user_prompt("T", "idea", "Horror", "Dark", "10 minutes")
|
||||
assert "required_beat_count: 50" in prompt
|
||||
assert "EXACTLY 50" in prompt
|
||||
@@ -0,0 +1,122 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from calliope.db import migrate_db
|
||||
from calliope.main import create_app
|
||||
|
||||
|
||||
SAMPLE_WORKFLOW = {
|
||||
"1": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": "hello"},
|
||||
"_meta": {"title": "Prompt (Input:prompt)"},
|
||||
},
|
||||
"2": {
|
||||
"class_type": "SaveImage",
|
||||
"inputs": {"images": ["1", 0]},
|
||||
"_meta": {"title": "Save (Output:image)"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
import asyncio
|
||||
import calliope.config as config_module
|
||||
|
||||
s = config_module.settings
|
||||
prev = {
|
||||
"data_dir": s.data_dir,
|
||||
"assets_dir": s.assets_dir,
|
||||
"dry_run": s.dry_run,
|
||||
}
|
||||
s.data_dir = Path(tmpdir)
|
||||
s.assets_dir = Path(tmpdir) / "assets"
|
||||
s.assets_dir.mkdir(parents=True, exist_ok=True)
|
||||
s.dry_run = True
|
||||
monkeypatch.setattr(config_module.Settings, "save_config_file", lambda self: None)
|
||||
asyncio.run(migrate_db(s.db_path))
|
||||
app = create_app()
|
||||
try:
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
finally:
|
||||
for k, v in prev.items():
|
||||
setattr(s, k, v)
|
||||
|
||||
|
||||
def test_playground_generate_and_attach(client):
|
||||
wf = client.post(
|
||||
"/api/workflows",
|
||||
json={"name": "PG Img", "kind": "image", "workflow_json": SAMPLE_WORKFLOW},
|
||||
)
|
||||
assert wf.status_code == 200
|
||||
workflow_id = wf.json()["id"]
|
||||
|
||||
gen = client.post(
|
||||
"/api/playground/generate",
|
||||
json={"workflow_id": workflow_id, "input_values": {"1": "a cat"}},
|
||||
)
|
||||
assert gen.status_code == 200
|
||||
job = gen.json()["job"]
|
||||
assert job["kind"] == "image"
|
||||
assert job["status"] == "pending"
|
||||
|
||||
# Scratch project hidden from list
|
||||
listed = client.get("/api/projects").json()
|
||||
assert all(p.get("status") != "system" for p in listed)
|
||||
|
||||
proj = client.post("/api/projects", json={"title": "Reel"}).json()
|
||||
char = client.post(
|
||||
f"/api/projects/{proj['id']}/characters",
|
||||
json={"name": "Hero"},
|
||||
).json()
|
||||
|
||||
# Wait briefly for dry-run worker, or poll jobs
|
||||
import time
|
||||
|
||||
path = None
|
||||
done = None
|
||||
for _ in range(40):
|
||||
jobs = client.get("/api/playground/jobs").json()
|
||||
done = next((j for j in jobs if j["id"] == job["id"] and j["status"] == "done"), None)
|
||||
if done and done["output_paths"]:
|
||||
path = done["output_paths"][0]
|
||||
break
|
||||
time.sleep(0.25)
|
||||
assert path and done, "playground job did not finish in dry-run"
|
||||
|
||||
attach = client.post(
|
||||
"/api/playground/attach",
|
||||
json={
|
||||
"path": path,
|
||||
"project_id": proj["id"],
|
||||
"target": "character_sheet",
|
||||
"character_id": char["id"],
|
||||
},
|
||||
)
|
||||
assert attach.status_code == 200
|
||||
|
||||
assets = client.get(f"/api/projects/{proj['id']}/assets").json()
|
||||
sheet = next(c for c in assets["characters"] if c["id"] == char["id"])["sheet_path"]
|
||||
assert sheet == path
|
||||
|
||||
from pathlib import Path as P
|
||||
|
||||
assert P(path).is_file()
|
||||
dead = client.delete(f"/api/playground/jobs/{done['id']}")
|
||||
assert dead.status_code == 200
|
||||
assert dead.json()["ok"] is True
|
||||
assert path in dead.json()["deleted_files"]
|
||||
assert not P(path).exists()
|
||||
assert done["id"] not in [j["id"] for j in client.get("/api/playground/jobs").json()]
|
||||
|
||||
assets2 = client.get(f"/api/projects/{proj['id']}/assets").json()
|
||||
sheet2 = next(c for c in assets2["characters"] if c["id"] == char["id"])["sheet_path"]
|
||||
assert sheet2 is None
|
||||
@@ -0,0 +1,80 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import calliope.config as config_module
|
||||
from calliope.routers.playground import UPLOAD_KIND_BY_EXT, _kind_for_ext
|
||||
|
||||
PNG_BYTES = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32
|
||||
MP3_BYTES = b"ID3" + b"\x00" * 32
|
||||
|
||||
|
||||
def _uploads_root() -> Path:
|
||||
return config_module.settings.assets_dir.resolve() / "uploads"
|
||||
|
||||
|
||||
def test_upload_image_ok(client):
|
||||
res = client.post(
|
||||
"/api/playground/uploads",
|
||||
files={"file": ("ref one.png", PNG_BYTES, "image/png")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["ok"] is True
|
||||
assert data["kind"] == "image"
|
||||
assert data["name"] == "ref one.png"
|
||||
|
||||
dest = Path(data["path"]).resolve()
|
||||
assert dest.is_relative_to(_uploads_root())
|
||||
assert dest.is_file()
|
||||
assert dest.read_bytes() == PNG_BYTES
|
||||
# Stored as "<8-char uuid>-<sanitized name>"
|
||||
assert dest.name[8] == "-"
|
||||
assert dest.name[9:] == "ref_one.png"
|
||||
|
||||
|
||||
def test_upload_bad_extension(client):
|
||||
res = client.post(
|
||||
"/api/playground/uploads",
|
||||
files={"file": ("evil.exe", b"MZ", "application/octet-stream")},
|
||||
)
|
||||
assert res.status_code == 400
|
||||
assert "Unsupported file type" in res.json()["detail"]
|
||||
|
||||
|
||||
def test_list_uploads_newest_first(client):
|
||||
first = client.post(
|
||||
"/api/playground/uploads",
|
||||
files={"file": ("old.png", PNG_BYTES, "image/png")},
|
||||
).json()
|
||||
second = client.post(
|
||||
"/api/playground/uploads",
|
||||
files={"file": ("new.mp3", MP3_BYTES, "audio/mpeg")},
|
||||
).json()
|
||||
|
||||
# Backdate the first file so ordering does not depend on mtime resolution
|
||||
old_mtime = time.time() - 100
|
||||
os.utime(first["path"], (old_mtime, old_mtime))
|
||||
|
||||
items = client.get("/api/playground/uploads").json()
|
||||
assert [i["path"] for i in items] == [second["path"], first["path"]]
|
||||
assert items[0]["name"] == "new.mp3"
|
||||
assert items[0]["kind"] == "audio"
|
||||
assert items[0]["size"] == len(MP3_BYTES)
|
||||
assert items[0]["mtime"]
|
||||
assert items[1]["name"] == "old.png"
|
||||
assert items[1]["kind"] == "image"
|
||||
|
||||
|
||||
def test_upload_extension_map():
|
||||
assert UPLOAD_KIND_BY_EXT[".png"] == "image"
|
||||
assert UPLOAD_KIND_BY_EXT[".webp"] == "image"
|
||||
assert UPLOAD_KIND_BY_EXT[".mp4"] == "video"
|
||||
assert UPLOAD_KIND_BY_EXT[".mkv"] == "video"
|
||||
assert UPLOAD_KIND_BY_EXT[".wav"] == "audio"
|
||||
assert UPLOAD_KIND_BY_EXT[".m4a"] == "audio"
|
||||
assert _kind_for_ext(".JPG") == "image" # case-insensitive
|
||||
assert _kind_for_ext(".exe") is None
|
||||
assert _kind_for_ext("") is None
|
||||
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from calliope.config import Settings
|
||||
from calliope.main import create_app
|
||||
from calliope.db import migrate_db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
import calliope.config as config_module
|
||||
import asyncio
|
||||
|
||||
s = config_module.settings
|
||||
prev = {
|
||||
"data_dir": s.data_dir,
|
||||
"assets_dir": s.assets_dir,
|
||||
"dry_run": s.dry_run,
|
||||
}
|
||||
s.data_dir = Path(tmpdir)
|
||||
s.assets_dir = Path(tmpdir) / "assets"
|
||||
s.dry_run = True
|
||||
monkeypatch.setattr(config_module.Settings, "save_config_file", lambda self: None)
|
||||
asyncio.run(migrate_db(s.db_path))
|
||||
app = create_app()
|
||||
try:
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
finally:
|
||||
for k, v in prev.items():
|
||||
setattr(s, k, v)
|
||||
|
||||
|
||||
def test_health(client):
|
||||
r = client.get("/api/health")
|
||||
assert r.status_code == 200
|
||||
assert r.json()["status"] == "ok"
|
||||
|
||||
|
||||
def test_create_and_list_project(client):
|
||||
r = client.post("/api/projects", json={"title": "Test", "idea": "idea"})
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["title"] == "Test"
|
||||
assert data["idea"] == "idea"
|
||||
pid = data["id"]
|
||||
|
||||
r = client.get("/api/projects")
|
||||
assert r.status_code == 200
|
||||
assert any(p["id"] == pid for p in r.json())
|
||||
|
||||
|
||||
def test_list_projects_includes_stats(client):
|
||||
r = client.post("/api/projects", json={"title": "ListStats"})
|
||||
pid = r.json()["id"]
|
||||
r = client.get("/api/projects")
|
||||
assert r.status_code == 200
|
||||
item = next(p for p in r.json() if p["id"] == pid)
|
||||
assert item["stats"] == {
|
||||
"scene_count": 0,
|
||||
"character_count": 0,
|
||||
"asset_ready_count": 0,
|
||||
"asset_total_count": 0,
|
||||
}
|
||||
|
||||
|
||||
def test_get_project_with_stats(client):
|
||||
r = client.post("/api/projects", json={"title": "Stats"})
|
||||
pid = r.json()["id"]
|
||||
r = client.get(f"/api/projects/{pid}")
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["stats"]["scene_count"] == 0
|
||||
|
||||
|
||||
def test_update_project(client):
|
||||
r = client.post("/api/projects", json={"title": "Old"})
|
||||
pid = r.json()["id"]
|
||||
r = client.patch(f"/api/projects/{pid}", json={"title": "New"})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["title"] == "New"
|
||||
|
||||
|
||||
def test_update_project_cover(client):
|
||||
r = client.post("/api/projects", json={"title": "Cover"})
|
||||
pid = r.json()["id"]
|
||||
assert r.json()["cover_path"] is None
|
||||
|
||||
r = client.patch(f"/api/projects/{pid}", json={"cover_path": "/tmp/cover.png"})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["cover_path"] == "/tmp/cover.png"
|
||||
|
||||
r = client.get(f"/api/projects/{pid}")
|
||||
assert r.json()["cover_path"] == "/tmp/cover.png"
|
||||
r = client.get("/api/projects")
|
||||
assert next(p for p in r.json() if p["id"] == pid)["cover_path"] == "/tmp/cover.png"
|
||||
|
||||
# Explicit null clears the cover again.
|
||||
r = client.patch(f"/api/projects/{pid}", json={"cover_path": None})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["cover_path"] is None
|
||||
|
||||
# Unrelated patches leave the (cleared) cover untouched.
|
||||
r = client.patch(f"/api/projects/{pid}", json={"title": "Cover 2"})
|
||||
assert r.json()["title"] == "Cover 2"
|
||||
assert r.json()["cover_path"] is None
|
||||
|
||||
|
||||
def test_delete_project(client):
|
||||
r = client.post("/api/projects", json={"title": "Delete"})
|
||||
pid = r.json()["id"]
|
||||
r = client.delete(f"/api/projects/{pid}")
|
||||
assert r.status_code == 200
|
||||
r = client.get(f"/api/projects/{pid}")
|
||||
assert r.status_code == 404
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Tests for rebasing stored asset paths after the install folder moves."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from calliope.db import SCHEMA, rebase_stale_asset_paths, get_db
|
||||
|
||||
|
||||
def _make_db(tmp_path):
|
||||
db_path = tmp_path / "calliope.db"
|
||||
conn = get_db(db_path)
|
||||
conn.executescript(SCHEMA)
|
||||
return conn
|
||||
|
||||
|
||||
def test_rebase_stale_paths(tmp_path):
|
||||
old_root = tmp_path / "old" / "Calliope" / "calliope-backend" / "data"
|
||||
new_data = tmp_path / "new" / "data"
|
||||
new_assets = new_data / "assets"
|
||||
conn = _make_db(tmp_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT INTO projects (title) VALUES ('demo')",
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO characters (project_id, name, sheet_path) VALUES (1, 'Mia', ?)",
|
||||
(str(old_root / "assets" / "1" / "image" / "sheet.png"),),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO scenes (project_id, order_index, video_path) VALUES (1, 1, ?)",
|
||||
(str(old_root / "assets" / "1" / "video" / "clip.mp4"),),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO jobs (project_id, kind, output_paths_json) VALUES (1, 'image', ?)",
|
||||
(json.dumps([str(old_root / "assets" / "1" / "image" / "out.png")]),),
|
||||
)
|
||||
# A path already under the current install must be left alone
|
||||
current = str(new_assets / "2" / "image" / "keep.png")
|
||||
conn.execute(
|
||||
"INSERT INTO locations (project_id, name, reference_image_path) VALUES (1, 'Lab', ?)",
|
||||
(current,),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
rebased = rebase_stale_asset_paths(conn, new_data, new_assets)
|
||||
conn.commit()
|
||||
|
||||
assert rebased == 3
|
||||
row = conn.execute("SELECT sheet_path FROM characters WHERE id = 1").fetchone()
|
||||
assert row["sheet_path"] == str(new_assets / "1" / "image" / "sheet.png")
|
||||
row = conn.execute("SELECT video_path FROM scenes WHERE id = 1").fetchone()
|
||||
assert row["video_path"] == str(new_assets / "1" / "video" / "clip.mp4")
|
||||
row = conn.execute("SELECT output_paths_json FROM jobs WHERE id = 1").fetchone()
|
||||
assert json.loads(row["output_paths_json"]) == [
|
||||
str(new_assets / "1" / "image" / "out.png")
|
||||
]
|
||||
row = conn.execute("SELECT reference_image_path FROM locations WHERE id = 1").fetchone()
|
||||
assert row["reference_image_path"] == current
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_rebase_ignores_relative_and_foreign_paths(tmp_path):
|
||||
new_data = tmp_path / "data"
|
||||
new_assets = new_data / "assets"
|
||||
conn = _make_db(tmp_path)
|
||||
try:
|
||||
conn.execute("INSERT INTO projects (title, cover_path) VALUES ('demo', 'relative/x.png')")
|
||||
conn.execute(
|
||||
"INSERT INTO characters (project_id, name, sheet_path) VALUES (1, 'A', ?)",
|
||||
("C:/elsewhere/no-assets-segment.png",),
|
||||
)
|
||||
conn.commit()
|
||||
assert rebase_stale_asset_paths(conn, new_data, new_assets) == 0
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Tests for Comfy title role tags and smart-fill by role."""
|
||||
from __future__ import annotations
|
||||
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs
|
||||
from calliope.comfyui.roles import parse_title_tag
|
||||
from calliope.comfyui.smart_fill import smart_fill_inputs
|
||||
|
||||
|
||||
def test_parse_title_tag_with_role():
|
||||
kind, role, label = parse_title_tag("主提示词 (Input:prompt)")
|
||||
assert kind == "input"
|
||||
assert role == "prompt"
|
||||
assert "主提示词" in label
|
||||
assert "(Input" not in label
|
||||
|
||||
|
||||
def test_parse_title_tag_role_only():
|
||||
kind, role, label = parse_title_tag("(Input:prompt)")
|
||||
assert kind == "input"
|
||||
assert role == "prompt"
|
||||
assert label == "prompt"
|
||||
|
||||
|
||||
def test_parse_title_tag_plain_input():
|
||||
kind, role, label = parse_title_tag("Width (Input)")
|
||||
assert kind == "input"
|
||||
assert role is None
|
||||
assert label == "Width"
|
||||
|
||||
|
||||
def test_smart_fill_uses_role_not_node_id():
|
||||
workflow = {
|
||||
"999": {
|
||||
"inputs": {"value": ""},
|
||||
"class_type": "PrimitiveStringMultiline",
|
||||
"_meta": {"title": "Whatever Name (Input:prompt)"},
|
||||
},
|
||||
"7": {
|
||||
"inputs": {"value": 512},
|
||||
"class_type": "PrimitiveInt",
|
||||
"_meta": {"title": "W (Input:width)"},
|
||||
},
|
||||
}
|
||||
inputs = parse_dynamic_inputs(workflow)
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt="Jake tall athletic",
|
||||
extra={"999": "", "7": 1280},
|
||||
)
|
||||
assert values["999"] == "Jake tall athletic"
|
||||
assert values["7"] == 1280
|
||||
|
||||
|
||||
def test_input_prompt_alias_positive():
|
||||
workflow = {
|
||||
"3": {
|
||||
"inputs": {"text": ""},
|
||||
"class_type": "CLIPTextEncode",
|
||||
"_meta": {"title": "Pos (Input:positive)"},
|
||||
},
|
||||
}
|
||||
inputs = parse_dynamic_inputs(workflow)
|
||||
assert inputs[0]["role"] == "prompt"
|
||||
values = smart_fill_inputs(inputs, prompt="hello")
|
||||
assert values["3"] == "hello"
|
||||
|
||||
|
||||
def test_smart_fill_extra_overrides_context():
|
||||
"""Form/user values must win on regenerate so edits are not wiped."""
|
||||
workflow = {
|
||||
"9": {
|
||||
"inputs": {"value": ""},
|
||||
"class_type": "PrimitiveStringMultiline",
|
||||
"_meta": {"title": "Global (Input:prompt)"},
|
||||
},
|
||||
"12": {
|
||||
"inputs": {"image": ""},
|
||||
"class_type": "LoadImage",
|
||||
"_meta": {"title": "Ref 1 (Input:character)"},
|
||||
},
|
||||
}
|
||||
inputs = parse_dynamic_inputs(workflow)
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt="auto from scene",
|
||||
character_image="/old/sheet.png",
|
||||
extra={"9": "user edited prompt", "12": "/new/ref.png"},
|
||||
)
|
||||
assert values["9"] == "user edited prompt"
|
||||
assert values["12"] == "/new/ref.png"
|
||||
|
||||
|
||||
def test_input_duration_alias():
|
||||
workflow = {
|
||||
"5": {
|
||||
"inputs": {"value": 10},
|
||||
"class_type": "PrimitiveFloat",
|
||||
"_meta": {"title": "(input:duration) Duration"},
|
||||
},
|
||||
}
|
||||
inputs = parse_dynamic_inputs(workflow)
|
||||
assert inputs[0]["role"] == "duration"
|
||||
values = smart_fill_inputs(inputs, duration=7)
|
||||
assert values["5"] == 7
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Script regenerate must honor an expanded scene board."""
|
||||
from __future__ import annotations
|
||||
|
||||
from calliope.agent.prompts import build_script_messages, recommend_scene_count
|
||||
|
||||
|
||||
def test_build_script_messages_honors_expanded_scene_count():
|
||||
msgs = build_script_messages(
|
||||
title="T",
|
||||
idea="idea",
|
||||
beats=[{"order_index": 1, "title": "B", "description": "d"}],
|
||||
characters=[{"id": 1, "name": "Hero", "role": "lead", "appearance": "tall"}],
|
||||
locations=[{"id": 1, "name": "Camp", "description": "night"}],
|
||||
target_duration="30 seconds",
|
||||
scene_count=6,
|
||||
)
|
||||
user = msgs[1]["content"]
|
||||
recommended = recommend_scene_count("30 seconds")
|
||||
assert recommended <= 6
|
||||
assert "required_scene_count: 6" in user
|
||||
assert "EXACTLY 6 objects" in user
|
||||
assert "scenes.length == 6" in user
|
||||
|
||||
|
||||
def test_script_regenerate_keeps_expanded_count(client, monkeypatch):
|
||||
calls: list[int] = []
|
||||
|
||||
async def fake_structured(messages, temperature=0.7):
|
||||
user = messages[1]["content"]
|
||||
# Parse required count from prompt
|
||||
n = 4
|
||||
for line in user.splitlines():
|
||||
if line.startswith("required_scene_count:"):
|
||||
n = int(line.split(":", 1)[1].strip())
|
||||
break
|
||||
calls.append(n)
|
||||
return {
|
||||
"scenes": [
|
||||
{
|
||||
"order_index": i,
|
||||
"heading": f"SCENE {i}",
|
||||
"action": f"action {i}",
|
||||
"dialog": "",
|
||||
"duration_sec": 5,
|
||||
"character_ids": [],
|
||||
"location_id": None,
|
||||
}
|
||||
for i in range(1, n + 1)
|
||||
]
|
||||
}
|
||||
|
||||
monkeypatch.setattr("calliope.agent.script_agent.generate_structured", fake_structured)
|
||||
|
||||
r = client.post("/api/projects", json={"title": "Expand", "idea": "desert", "target_duration": "30 seconds"})
|
||||
pid = r.json()["id"]
|
||||
|
||||
# Seed 4 scenes via generate
|
||||
r = client.post(f"/api/projects/{pid}/generate-script", json={"replace": True})
|
||||
assert r.status_code == 200
|
||||
assert len(r.json()["scenes"]) == calls[-1]
|
||||
|
||||
# User expands board with empty scenes
|
||||
for i in range(2):
|
||||
existing = client.get(f"/api/projects/{pid}/scenes").json()["scenes"]
|
||||
client.post(
|
||||
f"/api/projects/{pid}/scenes",
|
||||
json={
|
||||
"order_index": len(existing) + 1,
|
||||
"heading": f"NEW SCENE {len(existing) + 1}",
|
||||
"action": "",
|
||||
"dialog": "",
|
||||
"duration_sec": 5,
|
||||
},
|
||||
)
|
||||
|
||||
board = client.get(f"/api/projects/{pid}/scenes").json()["scenes"]
|
||||
expanded = len(board)
|
||||
assert expanded >= 6
|
||||
|
||||
r = client.post(
|
||||
f"/api/projects/{pid}/generate-script",
|
||||
json={"replace": True, "scene_count": expanded},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert len(r.json()["scenes"]) == expanded
|
||||
assert calls[-1] == expanded
|
||||
Generated
+4054
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "calliope-web",
|
||||
"version": "1.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"lint": "prettier --check . && eslint .",
|
||||
"format": "prettier --write ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-static": "^3.0.8",
|
||||
"@sveltejs/kit": "^2.20.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.0",
|
||||
"@types/node": "^22.13.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.20.0",
|
||||
"eslint-plugin-svelte": "^2.46.0",
|
||||
"postcss": "^8.5.0",
|
||||
"prettier": "^3.5.0",
|
||||
"prettier-plugin-svelte": "^3.3.0",
|
||||
"svelte": "^5.20.0",
|
||||
"svelte-check": "^4.1.0",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "^5.7.0",
|
||||
"vite": "^6.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/svelte-query": "^5.66.0"
|
||||
},
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { HandleClientError } from '@sveltejs/kit';
|
||||
|
||||
export const handleError: HandleClientError = ({ error }) => {
|
||||
console.error(error);
|
||||
return {
|
||||
message: 'Something went wrong.',
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
export async function handle({ event, resolve }) {
|
||||
const response = await resolve(event);
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
const API_BASE = '';
|
||||
|
||||
export interface Project {
|
||||
id: number;
|
||||
title: string;
|
||||
idea: string | null;
|
||||
genre: string | null;
|
||||
tone: string | null;
|
||||
target_duration: string | null;
|
||||
cover_path: string | null;
|
||||
status: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
stats?: ProjectStats;
|
||||
}
|
||||
|
||||
export interface ProjectStats {
|
||||
scene_count: number;
|
||||
character_count: number;
|
||||
asset_ready_count: number;
|
||||
asset_total_count: number;
|
||||
}
|
||||
|
||||
export interface ProjectCreate {
|
||||
title: string;
|
||||
idea?: string;
|
||||
genre?: string;
|
||||
tone?: string;
|
||||
target_duration?: string;
|
||||
}
|
||||
|
||||
export interface Beat {
|
||||
id: number;
|
||||
order_index: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
export interface Character {
|
||||
id: number;
|
||||
name: string;
|
||||
role: string | null;
|
||||
age: string | null;
|
||||
appearance: string | null;
|
||||
personality: string | null;
|
||||
portrait_path: string | null;
|
||||
sheet_path: string | null;
|
||||
consistency_prompt: string | null;
|
||||
}
|
||||
|
||||
export interface Location {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string | null;
|
||||
reference_image_path: string | null;
|
||||
consistency_prompt: string | null;
|
||||
}
|
||||
|
||||
export interface StoryData {
|
||||
project: Project;
|
||||
beats: Beat[];
|
||||
characters: Character[];
|
||||
locations: Location[];
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
host: string;
|
||||
port: number;
|
||||
data_dir: string;
|
||||
assets_dir: string;
|
||||
db_name: string;
|
||||
llm_base_url: string;
|
||||
llm_model: string;
|
||||
llm_api_key: boolean;
|
||||
comfyui_base_url: string;
|
||||
queue_concurrency: number;
|
||||
queue_poll_interval_sec: number;
|
||||
queue_max_retries: number;
|
||||
dry_run: boolean;
|
||||
}
|
||||
|
||||
import type { Job, Scene, Workflow, ComfyDynamicInput, ComfyDynamicOutput } from './comfy/types';
|
||||
export type { Job, Scene, Workflow, ComfyDynamicInput, ComfyDynamicOutput };
|
||||
|
||||
async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => 'unknown error');
|
||||
throw new Error(`${res.status}: ${body}`);
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
/** Multipart variant of api() — FormData sets its own Content-Type boundary. */
|
||||
async function apiUpload<T>(path: string, form: FormData): Promise<T> {
|
||||
const res = await fetch(`${API_BASE}${path}`, { method: 'POST', body: form });
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => 'unknown error');
|
||||
throw new Error(`${res.status}: ${body}`);
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export function assetUrl(path: string | null | undefined): string | null {
|
||||
if (!path) return null;
|
||||
return `/api/file?path=${encodeURIComponent(path)}`;
|
||||
}
|
||||
|
||||
export const projects = {
|
||||
list: () => api<Project[]>('/api/projects'),
|
||||
create: (payload: ProjectCreate) =>
|
||||
api<Project>('/api/projects', { method: 'POST', body: JSON.stringify(payload) }),
|
||||
get: (id: number) => api<Project & { stats: ProjectStats }>(`/api/projects/${id}`),
|
||||
update: (id: number, payload: Partial<ProjectCreate & { status?: string; cover_path?: string | null }>) =>
|
||||
api<Project>(`/api/projects/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
|
||||
delete: (id: number) => api<{ ok: boolean }>(`/api/projects/${id}`, { method: 'DELETE' }),
|
||||
generateStory: (id: number) =>
|
||||
api<{ ok: boolean; generated: unknown }>(`/api/projects/${id}/generate-story`, {
|
||||
method: 'POST',
|
||||
}),
|
||||
getStory: (id: number) => api<StoryData>(`/api/projects/${id}/story`),
|
||||
updateBeat: (projectId: number, beatId: number, payload: Partial<Beat>) =>
|
||||
api<Beat>(`/api/projects/${projectId}/beats/${beatId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
updateCharacter: (projectId: number, characterId: number, payload: Partial<Character>) =>
|
||||
api<Character>(`/api/projects/${projectId}/characters/${characterId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
updateLocation: (projectId: number, locationId: number, payload: Partial<Location>) =>
|
||||
api<Location>(`/api/projects/${projectId}/locations/${locationId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
deleteBeat: (projectId: number, beatId: number) =>
|
||||
api<{ ok: boolean }>(`/api/projects/${projectId}/beats/${beatId}`, { method: 'DELETE' }),
|
||||
deleteCharacter: (projectId: number, characterId: number) =>
|
||||
api<{ ok: boolean }>(`/api/projects/${projectId}/characters/${characterId}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
deleteLocation: (projectId: number, locationId: number) =>
|
||||
api<{ ok: boolean }>(`/api/projects/${projectId}/locations/${locationId}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
getScenes: (id: number) =>
|
||||
api<{ scenes: Scene[]; estimated_duration_sec: number }>(`/api/projects/${id}/scenes`),
|
||||
generateScript: (id: number, opts?: { scene_count?: number }) =>
|
||||
api<{ ok: boolean; scenes: Scene[] }>(`/api/projects/${id}/generate-script`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
replace: true,
|
||||
...(opts?.scene_count != null ? { scene_count: opts.scene_count } : {}),
|
||||
}),
|
||||
}),
|
||||
updateScene: (projectId: number, sceneId: number, payload: Record<string, unknown>) =>
|
||||
api<Scene>(`/api/projects/${projectId}/scenes/${sceneId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
createScene: (projectId: number, payload: Record<string, unknown>) =>
|
||||
api<Scene>(`/api/projects/${projectId}/scenes`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
deleteScene: (projectId: number, sceneId: number) =>
|
||||
api<{ ok: boolean }>(`/api/projects/${projectId}/scenes/${sceneId}`, { method: 'DELETE' }),
|
||||
reorderScenes: (projectId: number, sceneIds: number[]) =>
|
||||
api<{ scenes: Scene[] }>(`/api/projects/${projectId}/scenes/reorder`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ scene_ids: sceneIds }),
|
||||
}),
|
||||
generateAssets: (
|
||||
id: number,
|
||||
payload: {
|
||||
missing_only?: boolean;
|
||||
character_ids?: number[];
|
||||
location_ids?: number[];
|
||||
workflow_id?: number;
|
||||
input_values?: Record<string, unknown>;
|
||||
asset_target?: 'sheet';
|
||||
prompt?: string;
|
||||
} = {},
|
||||
) =>
|
||||
api<{ ok: boolean; jobs: Job[] }>(`/api/projects/${id}/generate-assets`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
getAssets: (id: number) =>
|
||||
api<{ characters: Character[]; locations: Location[] }>(`/api/projects/${id}/assets`),
|
||||
};
|
||||
|
||||
export const settings = {
|
||||
get: () => api<Settings>('/api/settings'),
|
||||
update: (payload: Record<string, unknown>) =>
|
||||
api<Settings>('/api/settings', { method: 'POST', body: JSON.stringify(payload) }),
|
||||
};
|
||||
|
||||
export const workflows = {
|
||||
list: () => api<Workflow[]>('/api/workflows'),
|
||||
analyze: (workflow_json: Record<string, unknown>) =>
|
||||
api<{
|
||||
inputs: ComfyDynamicInput[];
|
||||
outputs: ComfyDynamicOutput[];
|
||||
suggested_profile?: string;
|
||||
}>('/api/workflows/analyze', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ workflow_json }),
|
||||
}),
|
||||
create: (payload: {
|
||||
name: string;
|
||||
kind: 'image' | 'video';
|
||||
workflow_json: Record<string, unknown>;
|
||||
description?: string;
|
||||
prompt_profile?: string;
|
||||
}) => api<Workflow>('/api/workflows', { method: 'POST', body: JSON.stringify(payload) }),
|
||||
update: (
|
||||
id: number,
|
||||
payload: Partial<{
|
||||
name: string;
|
||||
kind: string;
|
||||
is_enabled: boolean;
|
||||
description: string;
|
||||
prompt_profile: string;
|
||||
}>,
|
||||
) => api<Workflow>(`/api/workflows/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
|
||||
delete: (id: number) => api<{ ok: boolean }>(`/api/workflows/${id}`, { method: 'DELETE' }),
|
||||
get: (id: number) => api<Workflow>(`/api/workflows/${id}`),
|
||||
};
|
||||
|
||||
export const jobsApi = {
|
||||
list: (projectId?: number) =>
|
||||
api<Job[]>(`/api/jobs${projectId != null ? `?project_id=${projectId}` : ''}`),
|
||||
retry: (id: number) => api<Job>(`/api/jobs/${id}/retry`, { method: 'POST' }),
|
||||
cancel: (id: number) => api<{ ok: boolean }>(`/api/jobs/${id}/cancel`, { method: 'POST' }),
|
||||
pause: () => api<{ ok: boolean; paused: boolean }>('/api/jobs/pause', { method: 'POST' }),
|
||||
resume: () => api<{ ok: boolean; paused: boolean }>('/api/jobs/resume', { method: 'POST' }),
|
||||
queueStatus: () => api<{ paused: boolean }>('/api/jobs/queue-status'),
|
||||
generateVideos: (
|
||||
projectId: number,
|
||||
payload: {
|
||||
scene_ids?: number[];
|
||||
workflow_id?: number;
|
||||
input_values?: Record<string, unknown>;
|
||||
} = {},
|
||||
) =>
|
||||
api<{ ok: boolean; jobs: Job[] }>(`/api/jobs/projects/${projectId}/generate-videos`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
exportFilm: (projectId: number) =>
|
||||
api<{ ok: boolean; job: Job }>(`/api/jobs/projects/${projectId}/export`, { method: 'POST' }),
|
||||
};
|
||||
|
||||
export type PlaygroundAttachTarget = 'character_sheet' | 'location' | 'scene';
|
||||
|
||||
export type UploadKind = 'image' | 'video' | 'audio';
|
||||
|
||||
export interface PlaygroundUpload {
|
||||
ok: boolean;
|
||||
path: string;
|
||||
name: string;
|
||||
kind: UploadKind;
|
||||
}
|
||||
|
||||
export interface PlaygroundUploadListItem {
|
||||
name: string;
|
||||
path: string;
|
||||
kind: UploadKind;
|
||||
size: number;
|
||||
mtime: string;
|
||||
}
|
||||
|
||||
export const playgroundApi = {
|
||||
project: () => api<Project>('/api/playground/project'),
|
||||
jobs: () => api<Job[]>('/api/playground/jobs'),
|
||||
generate: (payload: { workflow_id: number; input_values?: Record<string, unknown> }) =>
|
||||
api<{ ok: boolean; job: Job }>('/api/playground/generate', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
upload: (file: File) => {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return apiUpload<PlaygroundUpload>('/api/playground/uploads', form);
|
||||
},
|
||||
listUploads: () => api<PlaygroundUploadListItem[]>('/api/playground/uploads'),
|
||||
deleteJob: (jobId: number) =>
|
||||
api<{ ok: boolean; job_id: number; deleted_files: string[]; missing_files: string[] }>(
|
||||
`/api/playground/jobs/${jobId}`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
attach: (payload: {
|
||||
path: string;
|
||||
project_id: number;
|
||||
target: PlaygroundAttachTarget;
|
||||
character_id?: number;
|
||||
location_id?: number;
|
||||
scene_id?: number;
|
||||
}) =>
|
||||
api<{ ok: boolean; path: string; target: string; project_id: number }>(
|
||||
'/api/playground/attach',
|
||||
{ method: 'POST', body: JSON.stringify(payload) },
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Omni Composer input classification.
|
||||
*
|
||||
* Maps each ComfyDynamicInput — based on its canonical role — to a UI zone
|
||||
* and widget type inside the Omni layout. This is presentation-only: the
|
||||
* underlying values map (nodeId → value) is identical to what
|
||||
* ComfyDynamicForm would produce.
|
||||
*
|
||||
* Zones:
|
||||
* composer → main prompt textarea + collapsible negative
|
||||
* media → thumbnail tiles (upload / asset-pick)
|
||||
* control → compact pills (resolution, duration, seed)
|
||||
* advanced → hidden inside an "Advanced" popover
|
||||
*/
|
||||
import type { ComfyDynamicInput } from './types';
|
||||
import { normalizeInputRole } from './parser';
|
||||
|
||||
export type InputZone = 'composer' | 'media' | 'control' | 'advanced';
|
||||
|
||||
export type OmniWidget =
|
||||
| 'promptTextarea'
|
||||
| 'negativeTextarea'
|
||||
| 'uploadTile'
|
||||
| 'assetTile'
|
||||
| 'resolutionPill'
|
||||
| 'numberPill'
|
||||
| 'textPill';
|
||||
|
||||
export interface ClassifiedInput {
|
||||
input: ComfyDynamicInput;
|
||||
zone: InputZone;
|
||||
widget: OmniWidget;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a single input by its canonical role.
|
||||
*
|
||||
* The rules are deliberately exhaustive — every input lands in exactly one
|
||||
* zone. Unknown roles fall to `advanced` so no field is ever hidden or lost.
|
||||
*/
|
||||
export function classifyInput(inp: ComfyDynamicInput): ClassifiedInput {
|
||||
const role = normalizeInputRole(inp.role);
|
||||
|
||||
// --- Composer ---
|
||||
if (role === 'prompt' || role === 'positive') {
|
||||
return { input: inp, zone: 'composer', widget: 'promptTextarea' };
|
||||
}
|
||||
if (role === 'negative') {
|
||||
return { input: inp, zone: 'composer', widget: 'negativeTextarea' };
|
||||
}
|
||||
|
||||
// --- Media tray ---
|
||||
if (role === 'character' || role === 'location' || role === 'image') {
|
||||
const isImageKind = inp.kind === 'image' || inp.kind === 'image_url';
|
||||
return {
|
||||
input: inp,
|
||||
zone: 'media',
|
||||
widget: isImageKind ? 'uploadTile' : 'assetTile',
|
||||
};
|
||||
}
|
||||
|
||||
// --- Control bar ---
|
||||
if (role === 'width' || role === 'height') {
|
||||
return { input: inp, zone: 'control', widget: 'resolutionPill' };
|
||||
}
|
||||
if (role === 'duration' || role === 'seed') {
|
||||
return { input: inp, zone: 'control', widget: 'numberPill' };
|
||||
}
|
||||
|
||||
// --- Advanced popover ---
|
||||
if (inp.kind === 'number') {
|
||||
return { input: inp, zone: 'advanced', widget: 'numberPill' };
|
||||
}
|
||||
return { input: inp, zone: 'advanced', widget: 'textPill' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch-classify an entire input schema into grouped buckets.
|
||||
*
|
||||
* Resolution pairs (width + height in the same schema) are detected so the
|
||||
* OmniComposer can render a single "Resolution" pill that writes both
|
||||
* nodeIds on change.
|
||||
*/
|
||||
export function classifyAll(inputs: ComfyDynamicInput[]): {
|
||||
prompt: ClassifiedInput | null;
|
||||
negative: ClassifiedInput | null;
|
||||
media: ClassifiedInput[];
|
||||
control: ClassifiedInput[];
|
||||
advanced: ClassifiedInput[];
|
||||
/** Non-null when both width AND height are present → merge into one pill. */
|
||||
resolutionPair: { width: ClassifiedInput; height: ClassifiedInput } | null;
|
||||
} {
|
||||
const classified = inputs.map(classifyInput);
|
||||
|
||||
const prompt = classified.find((c) => c.widget === 'promptTextarea') ?? null;
|
||||
const negative = classified.find((c) => c.widget === 'negativeTextarea') ?? null;
|
||||
const media = classified.filter((c) => c.zone === 'media');
|
||||
const advanced = classified.filter((c) => c.zone === 'advanced');
|
||||
|
||||
// Separate resolution from other control inputs
|
||||
const controlNonRes = classified.filter(
|
||||
(c) => c.zone === 'control' && c.widget !== 'resolutionPill',
|
||||
);
|
||||
const resInputs = classified.filter((c) => c.widget === 'resolutionPill');
|
||||
|
||||
// Detect width + height pair
|
||||
const wInput = resInputs.find((c) => normalizeInputRole(c.input.role) === 'width');
|
||||
const hInput = resInputs.find((c) => normalizeInputRole(c.input.role) === 'height');
|
||||
const resolutionPair =
|
||||
wInput && hInput ? { width: wInput, height: hInput } : null;
|
||||
|
||||
// If only one of width/height exists, treat it as a standalone control number pill
|
||||
const standaloneRes = resolutionPair ? [] : resInputs;
|
||||
|
||||
return {
|
||||
prompt,
|
||||
negative,
|
||||
media,
|
||||
control: [...controlNonRes, ...standaloneRes],
|
||||
advanced,
|
||||
resolutionPair,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Resolution presets ────────────────────────────────────────────────────────
|
||||
|
||||
export interface ResolutionPreset {
|
||||
label: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export const RESOLUTION_PRESETS: ResolutionPreset[] = [
|
||||
{ label: '720p', width: 1280, height: 720 },
|
||||
{ label: '1080p', width: 1920, height: 1080 },
|
||||
];
|
||||
|
||||
/**
|
||||
* Given current width/height values, find the matching preset label
|
||||
* (or return null for custom / unset values).
|
||||
*/
|
||||
export function resolutionLabel(
|
||||
width: number | string | undefined,
|
||||
height: number | string | undefined,
|
||||
): string | null {
|
||||
const w = Number(width);
|
||||
const h = Number(height);
|
||||
if (!w || !h) return null;
|
||||
const match = RESOLUTION_PRESETS.find((p) => p.width === w && p.height === h);
|
||||
return match?.label ?? `${w}×${h}`;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { ComfyDynamicInput, ComfyDynamicOutput, WorkflowNode } from './types';
|
||||
|
||||
const TEXT_AREA = new Set([
|
||||
'CLIPTextEncode',
|
||||
'Note',
|
||||
'ShowText',
|
||||
'ImpactWildcardProcessor',
|
||||
'PrimitiveStringMultiline',
|
||||
'PrimitiveString',
|
||||
]);
|
||||
const NUMBER = new Set(['INT', 'FLOAT', 'PrimitiveInt', 'PrimitiveFloat', 'KSampler', 'KSamplerAdvanced']);
|
||||
const IMAGE = new Set(['LoadImage', 'ImageLoader', 'ETN_LoadImageBase64']);
|
||||
const IMAGE_URL = new Set(['Load Image From Url (mtb)']);
|
||||
const AUDIO = new Set(['LoadAudio', 'VHS_LoadAudio']);
|
||||
const VIDEO_OUT = new Set(['VHS_VideoCombine', 'SaveVideo', 'VideoOutput', 'AnimateDiffCombine']);
|
||||
const IMAGE_OUT = new Set(['SaveImage', 'PreviewImage', 'SaveImageWebsocket', 'ETN_SendImageWebSocket']);
|
||||
|
||||
/** Matches (Input), (Input:prompt), (Output:image), … */
|
||||
const TITLE_TAG_RE = /\((Input|Output)(?::([a-zA-Z0-9_-]+))?\)/i;
|
||||
|
||||
const INPUT_ROLE_ALIASES: Record<string, string[]> = {
|
||||
prompt: ['prompt', 'positive'],
|
||||
negative: ['negative', 'neg'],
|
||||
width: ['width', 'w'],
|
||||
height: ['height', 'h'],
|
||||
character: ['character', 'char', 'portrait', 'sheet', 'face', 'ref'],
|
||||
location: ['location', 'loc', 'environment', 'env', 'background', 'scene'],
|
||||
image: ['image', 'img'],
|
||||
seed: ['seed'],
|
||||
duration: ['duration', 'dur', 'length', 'seconds'],
|
||||
};
|
||||
|
||||
const OUTPUT_ROLE_ALIASES: Record<string, string[]> = {
|
||||
image: ['image', 'img'],
|
||||
video: ['video', 'vid'],
|
||||
};
|
||||
|
||||
export function parseTitleTag(title: string): {
|
||||
kind: 'input' | 'output' | null;
|
||||
role: string | null;
|
||||
label: string;
|
||||
} {
|
||||
if (!title) return { kind: null, role: null, label: '' };
|
||||
const match = TITLE_TAG_RE.exec(title);
|
||||
if (!match) return { kind: null, role: null, label: title.trim() };
|
||||
const kind = match[1].toLowerCase() as 'input' | 'output';
|
||||
const role = match[2] ? match[2].toLowerCase() : null;
|
||||
const stripped = title.replace(TITLE_TAG_RE, '').trim();
|
||||
const label = stripped || role || kind;
|
||||
return { kind, role, label };
|
||||
}
|
||||
|
||||
export function normalizeInputRole(role: string | null | undefined): string | null {
|
||||
if (!role) return null;
|
||||
const r = role.toLowerCase().trim();
|
||||
for (const [canonical, aliases] of Object.entries(INPUT_ROLE_ALIASES)) {
|
||||
if (r === canonical || aliases.includes(r)) return canonical;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
export function normalizeOutputRole(role: string | null | undefined): string | null {
|
||||
if (!role) return null;
|
||||
const r = role.toLowerCase().trim();
|
||||
for (const [canonical, aliases] of Object.entries(OUTPUT_ROLE_ALIASES)) {
|
||||
if (r === canonical || aliases.includes(r)) return canonical;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
function classToInputKind(classType: string): ComfyDynamicInput['kind'] {
|
||||
if (IMAGE.has(classType)) return 'image';
|
||||
if (IMAGE_URL.has(classType)) return 'image_url';
|
||||
if (AUDIO.has(classType)) return 'audio';
|
||||
if (NUMBER.has(classType)) return 'number';
|
||||
if (TEXT_AREA.has(classType)) return 'textarea';
|
||||
const lower = classType.toLowerCase();
|
||||
if (lower.includes('image') || lower.includes('load')) return 'image';
|
||||
if (lower.includes('audio')) return 'audio';
|
||||
if (lower.includes('int') || lower.includes('float') || lower.includes('seed')) return 'number';
|
||||
if (lower.includes('text') || lower.includes('clip') || lower.includes('prompt')) return 'textarea';
|
||||
return 'text';
|
||||
}
|
||||
|
||||
function extractDefault(node: WorkflowNode): string | number | undefined {
|
||||
const { inputs, class_type } = node;
|
||||
if (IMAGE.has(class_type) || AUDIO.has(class_type)) return undefined;
|
||||
if (typeof inputs.text === 'string') return inputs.text;
|
||||
if (typeof inputs.value === 'string' || typeof inputs.value === 'number') return inputs.value;
|
||||
if (typeof inputs.int === 'number') return inputs.int;
|
||||
if (typeof inputs.float === 'number') return inputs.float;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseDynamicInputs(workflow: Record<string, WorkflowNode>): ComfyDynamicInput[] {
|
||||
const results: ComfyDynamicInput[] = [];
|
||||
for (const [nodeId, node] of Object.entries(workflow)) {
|
||||
const title = node._meta?.title ?? '';
|
||||
const { kind, role, label } = parseTitleTag(title);
|
||||
if (kind !== 'input') continue;
|
||||
results.push({
|
||||
nodeId,
|
||||
label: label || node.class_type,
|
||||
role: normalizeInputRole(role),
|
||||
kind: classToInputKind(node.class_type),
|
||||
defaultValue: extractDefault(node),
|
||||
required: true,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export function parseDynamicOutputs(workflow: Record<string, WorkflowNode>): ComfyDynamicOutput[] {
|
||||
const results: ComfyDynamicOutput[] = [];
|
||||
for (const [nodeId, node] of Object.entries(workflow)) {
|
||||
const title = node._meta?.title ?? '';
|
||||
const { kind, role, label } = parseTitleTag(title);
|
||||
if (kind !== 'output') continue;
|
||||
const canon = normalizeOutputRole(role);
|
||||
let outKind: ComfyDynamicOutput['kind'] = 'other';
|
||||
if (canon === 'video' || VIDEO_OUT.has(node.class_type) || node.class_type.toLowerCase().includes('video'))
|
||||
outKind = 'video';
|
||||
else if (
|
||||
canon === 'image' ||
|
||||
IMAGE_OUT.has(node.class_type) ||
|
||||
node.class_type.toLowerCase().includes('image')
|
||||
)
|
||||
outKind = 'image';
|
||||
results.push({
|
||||
nodeId,
|
||||
label: label || node.class_type,
|
||||
role: canon,
|
||||
kind: outKind,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ComfyDynamicInput } from './types';
|
||||
import { normalizeInputRole } from './parser';
|
||||
|
||||
const PROMPT_ROLES = new Set(['prompt', 'positive']);
|
||||
|
||||
function roleOf(inp: ComfyDynamicInput): string | null {
|
||||
return normalizeInputRole(inp.role ?? null);
|
||||
}
|
||||
|
||||
/** Positive prompt input — prefers (Input:prompt), legacy label fallback. */
|
||||
export function isPromptLikeInput(inp: ComfyDynamicInput): boolean {
|
||||
const role = roleOf(inp);
|
||||
if (role && PROMPT_ROLES.has(role)) return true;
|
||||
if (role) return false; // other roles are never "the" prompt
|
||||
if (inp.kind !== 'text' && inp.kind !== 'textarea') return false;
|
||||
const label = (inp.label || '').toLowerCase();
|
||||
if (label.includes('negative')) return false;
|
||||
return (
|
||||
label.includes('prompt') ||
|
||||
label.includes('positive') ||
|
||||
label.includes('text') ||
|
||||
inp.kind === 'textarea'
|
||||
);
|
||||
}
|
||||
|
||||
/** Drop prompt-role fields from shared workflow forms (entity Image prompt owns those). */
|
||||
export function withoutPromptInputs(inputs: ComfyDynamicInput[] | undefined | null): ComfyDynamicInput[] {
|
||||
if (!inputs?.length) return [];
|
||||
return inputs.filter((inp) => !isPromptLikeInput(inp));
|
||||
}
|
||||
|
||||
/** True if this workflow schema has a prompt-role (or legacy prompt-like) (Input). */
|
||||
export function workflowHasPromptInput(inputs: ComfyDynamicInput[] | undefined | null): boolean {
|
||||
if (!inputs?.length) return false;
|
||||
return inputs.some(isPromptLikeInput);
|
||||
}
|
||||
|
||||
/** Strip blank strings so empty fields cannot wipe smart-fill. */
|
||||
export function compactInputValues(
|
||||
values: Record<string, unknown> | undefined | null,
|
||||
): Record<string, unknown> {
|
||||
if (!values) return {};
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(values)) {
|
||||
if (v === null || v === undefined) continue;
|
||||
if (typeof v === 'string' && !v.trim()) continue;
|
||||
out[k] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
export type ComfyInputKind = 'text' | 'textarea' | 'number' | 'image' | 'image_url' | 'audio';
|
||||
export type ComfyOutputKind = 'image' | 'video' | 'other';
|
||||
|
||||
export interface ComfyDynamicInput {
|
||||
nodeId: string;
|
||||
label: string;
|
||||
/** Role from title tag, e.g. (Input:prompt) → "prompt". Null for plain (Input). */
|
||||
role?: string | null;
|
||||
kind: ComfyInputKind;
|
||||
defaultValue?: string | number;
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
export interface ComfyDynamicOutput {
|
||||
nodeId: string;
|
||||
label: string;
|
||||
/** Role from title tag, e.g. (Output:image) → "image". */
|
||||
role?: string | null;
|
||||
kind: ComfyOutputKind;
|
||||
}
|
||||
|
||||
export interface WorkflowNode {
|
||||
class_type: string;
|
||||
inputs: Record<string, unknown>;
|
||||
_meta?: { title?: string };
|
||||
}
|
||||
|
||||
export interface Workflow {
|
||||
id: number;
|
||||
name: string;
|
||||
kind: 'image' | 'video';
|
||||
workflow_json: Record<string, WorkflowNode>;
|
||||
input_schema: ComfyDynamicInput[];
|
||||
output_schema: ComfyDynamicOutput[];
|
||||
description: string | null;
|
||||
prompt_profile: string;
|
||||
is_enabled: boolean;
|
||||
}
|
||||
|
||||
export interface Job {
|
||||
id: number;
|
||||
project_id: number;
|
||||
scene_id: number | null;
|
||||
kind: string;
|
||||
workflow_id: number | null;
|
||||
status: string;
|
||||
payload: Record<string, unknown>;
|
||||
output_paths: string[];
|
||||
error: string | null;
|
||||
created_at: string;
|
||||
started_at: string | null;
|
||||
completed_at: string | null;
|
||||
retry_count: number;
|
||||
}
|
||||
|
||||
export interface Scene {
|
||||
id: number;
|
||||
project_id: number;
|
||||
order_index: number;
|
||||
heading: string | null;
|
||||
action: string | null;
|
||||
dialog: string | null;
|
||||
duration_sec: number | null;
|
||||
workflow_id: number | null;
|
||||
env_image_path: string | null;
|
||||
location_id: number | null;
|
||||
video_path: string | null;
|
||||
character_ids: number[];
|
||||
characters: Array<{
|
||||
id: number;
|
||||
name: string;
|
||||
role: string | null;
|
||||
portrait_path: string | null;
|
||||
sheet_path: string | null;
|
||||
}>;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Shared upload logic — extracted from ComfyDynamicForm so both the legacy
|
||||
* form and OmniComposer can use it without duplication.
|
||||
*
|
||||
* Provides a Svelte 5 `$state`-based upload manager that handles:
|
||||
* - file picker (click to browse)
|
||||
* - drag-and-drop
|
||||
* - upload progress per nodeId
|
||||
* - metadata (name, kind) for uploaded files
|
||||
*/
|
||||
import { playgroundApi, type UploadKind } from '$lib/api';
|
||||
import { toast } from '$lib/toast';
|
||||
|
||||
export interface UploadState {
|
||||
/** nodeId → uploading filename (present while upload is in-flight) */
|
||||
uploading: Record<string, string>;
|
||||
/** path → { name, kind } for previously uploaded files */
|
||||
uploadedMeta: Record<string, { name: string; kind: UploadKind }>;
|
||||
}
|
||||
|
||||
export function createUploadManager() {
|
||||
let uploading = $state<Record<string, string>>({});
|
||||
let uploadedMeta = $state<Record<string, { name: string; kind: UploadKind }>>({});
|
||||
|
||||
return {
|
||||
get uploading() {
|
||||
return uploading;
|
||||
},
|
||||
get uploadedMeta() {
|
||||
return uploadedMeta;
|
||||
},
|
||||
|
||||
isUploading(nodeId: string): boolean {
|
||||
return !!uploading[nodeId];
|
||||
},
|
||||
|
||||
uploadMetaFor(path: string): { name: string; kind: UploadKind } {
|
||||
const meta = uploadedMeta[path];
|
||||
if (meta) return meta;
|
||||
const base = path.split(/[/\\]/).pop() ?? path;
|
||||
const ext = base.slice(base.lastIndexOf('.')).toLowerCase();
|
||||
if (['.mp4', '.webm', '.mov', '.mkv'].includes(ext))
|
||||
return { name: base, kind: 'video' };
|
||||
if (['.mp3', '.wav', '.flac', '.ogg', '.m4a'].includes(ext))
|
||||
return { name: base, kind: 'audio' };
|
||||
return { name: base, kind: 'image' };
|
||||
},
|
||||
|
||||
/**
|
||||
* Upload a file and return the server path.
|
||||
* Manages uploading state and metadata internally.
|
||||
* Throws on failure (caller handles toast if needed).
|
||||
*/
|
||||
async upload(nodeId: string, file: File): Promise<string> {
|
||||
uploading = { ...uploading, [nodeId]: file.name };
|
||||
try {
|
||||
const res = await playgroundApi.upload(file);
|
||||
uploadedMeta = {
|
||||
...uploadedMeta,
|
||||
[res.path]: { name: res.name, kind: res.kind },
|
||||
};
|
||||
return res.path;
|
||||
} finally {
|
||||
const next = { ...uploading };
|
||||
delete next[nodeId];
|
||||
uploading = next;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Convenience: upload + toast on error, return path or null.
|
||||
*/
|
||||
async uploadSafe(nodeId: string, file: File): Promise<string | null> {
|
||||
try {
|
||||
return await this.upload(nodeId, file);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Upload failed');
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type UploadManager = ReturnType<typeof createUploadManager>;
|
||||
|
||||
export function truncateMiddle(name: string, max = 32): string {
|
||||
if (name.length <= max) return name;
|
||||
const head = Math.ceil((max - 1) / 2);
|
||||
const tail = Math.floor((max - 1) / 2);
|
||||
return `${name.slice(0, head)}…${name.slice(name.length - tail)}`;
|
||||
}
|
||||
|
||||
export function acceptForKind(kind: string): string {
|
||||
return kind === 'audio' ? 'audio/*' : 'image/*';
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
<script lang="ts">
|
||||
import { createQuery } from '@tanstack/svelte-query';
|
||||
import { toStore } from 'svelte/store';
|
||||
import { jobsApi, type Job } from '$lib/api';
|
||||
import type { CalliopeEvent, EventConnectionState } from '$lib/events';
|
||||
import JobRow from './JobRow.svelte';
|
||||
import Button from './ui/Button.svelte';
|
||||
import Icon from './ui/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
logs: CalliopeEvent[];
|
||||
projectId: number;
|
||||
/** Real SSE connection state from events.ts — drives the live pip. */
|
||||
connState: EventConnectionState;
|
||||
collapsed?: boolean;
|
||||
onToggle?: () => void;
|
||||
}
|
||||
|
||||
let { logs, projectId, connState, collapsed = false, onToggle }: Props = $props();
|
||||
|
||||
type Tone = 'info' | 'ok' | 'warn' | 'err' | 'work';
|
||||
|
||||
type LogEntry = {
|
||||
key: string;
|
||||
ts: string;
|
||||
title: string;
|
||||
detail: string;
|
||||
tone: Tone;
|
||||
type: string;
|
||||
};
|
||||
|
||||
function str(v: unknown): string {
|
||||
if (v == null) return '';
|
||||
if (typeof v === 'string') return v;
|
||||
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
|
||||
return '';
|
||||
}
|
||||
|
||||
function formatEvent(ev: CalliopeEvent, index: number): LogEntry | null {
|
||||
// Poll spam — progress lives in the jobProgress store, not the log
|
||||
if (ev.type === 'job.progress') return null;
|
||||
|
||||
const d = ev.data ?? {};
|
||||
const msg = str(d.message).trim();
|
||||
const kind = str(d.kind);
|
||||
const jobId = d.job_id != null ? `#${d.job_id}` : '';
|
||||
const err = str(d.error).trim();
|
||||
const paths = Array.isArray(d.paths) ? d.paths.length : 0;
|
||||
const outputs = Array.isArray(d.outputs) ? d.outputs.length : 0;
|
||||
const time = ev.ts?.includes('T') ? ev.ts.slice(11, 19) : ev.ts?.slice(0, 8) || '';
|
||||
|
||||
let title = ev.type;
|
||||
let detail = msg;
|
||||
let tone: Tone = 'info';
|
||||
|
||||
switch (ev.type) {
|
||||
case 'agent.thinking':
|
||||
title = 'Agent';
|
||||
detail = msg || 'Working…';
|
||||
tone = 'work';
|
||||
break;
|
||||
case 'story.ready':
|
||||
title = 'Story ready';
|
||||
detail = msg || 'Storyline drafted';
|
||||
tone = 'ok';
|
||||
break;
|
||||
case 'job.created':
|
||||
title = 'Queued';
|
||||
detail = msg || [kind, jobId].filter(Boolean).join(' ');
|
||||
tone = 'info';
|
||||
break;
|
||||
case 'job.started':
|
||||
title = 'Running';
|
||||
detail = msg || [kind, jobId].filter(Boolean).join(' ');
|
||||
tone = 'work';
|
||||
break;
|
||||
case 'job.completed':
|
||||
title = 'Finished';
|
||||
detail =
|
||||
msg ||
|
||||
[kind, jobId, outputs ? `${outputs} file(s)` : ''].filter(Boolean).join(' · ');
|
||||
tone = 'ok';
|
||||
break;
|
||||
case 'job.failed':
|
||||
title = 'Failed';
|
||||
detail = err || msg || [kind, jobId].filter(Boolean).join(' ');
|
||||
tone = 'err';
|
||||
break;
|
||||
case 'asset.ready':
|
||||
title = 'Asset ready';
|
||||
detail = msg || (paths ? `${paths} file(s) saved` : 'Output saved');
|
||||
tone = 'ok';
|
||||
break;
|
||||
case 'job.deleted':
|
||||
title = 'Removed';
|
||||
detail = msg || jobId || 'Job deleted';
|
||||
tone = 'warn';
|
||||
break;
|
||||
default:
|
||||
title = ev.type.replace(/\./g, ' · ');
|
||||
detail = msg || err || kind;
|
||||
tone = 'info';
|
||||
}
|
||||
|
||||
return {
|
||||
key: `${ev.ts}-${ev.type}-${index}`,
|
||||
ts: time,
|
||||
title,
|
||||
detail,
|
||||
tone,
|
||||
type: ev.type,
|
||||
};
|
||||
}
|
||||
|
||||
const entries = $derived.by(() => {
|
||||
const raw = logs
|
||||
.slice(-120)
|
||||
.map((ev, i) => formatEvent(ev, i))
|
||||
.filter((e): e is LogEntry => e != null);
|
||||
|
||||
// Collapse consecutive identical agent lines
|
||||
const collapsed: LogEntry[] = [];
|
||||
for (const e of raw) {
|
||||
const prev = collapsed[collapsed.length - 1];
|
||||
if (prev && prev.type === e.type && prev.detail === e.detail) {
|
||||
continue;
|
||||
}
|
||||
collapsed.push(e);
|
||||
}
|
||||
return collapsed.slice(-60).reverse();
|
||||
});
|
||||
|
||||
// Same query key as QueueStage — the cache (and its refetch) is shared.
|
||||
const jobsQuery = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ['jobs', projectId],
|
||||
queryFn: () => jobsApi.list(projectId),
|
||||
refetchInterval: 5000,
|
||||
})),
|
||||
);
|
||||
|
||||
const allJobs = $derived(($jobsQuery.data ?? []) as Job[]);
|
||||
|
||||
function activeWeight(job: Job): number {
|
||||
if (job.status === 'running') return 0;
|
||||
if (job.status === 'pending') return 1;
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Active jobs first, then most recent — capped so the log keeps room.
|
||||
const queueRows = $derived(
|
||||
[...allJobs].sort((a, b) => activeWeight(a) - activeWeight(b) || b.id - a.id).slice(0, 6),
|
||||
);
|
||||
|
||||
const stats = $derived({
|
||||
running: allJobs.filter((j) => j.status === 'running').length,
|
||||
queued: allJobs.filter((j) => j.status === 'pending').length,
|
||||
done: allJobs.filter((j) => j.status === 'done').length,
|
||||
failed: allJobs.filter((j) => j.status === 'failed').length,
|
||||
});
|
||||
const busyCount = $derived(stats.running + stats.queued);
|
||||
|
||||
const connected = $derived(connState === 'open');
|
||||
</script>
|
||||
|
||||
<aside class="activity" class:collapsed aria-label="Activity">
|
||||
{#if collapsed}
|
||||
<button
|
||||
type="button"
|
||||
class="rail-toggle"
|
||||
onclick={onToggle}
|
||||
aria-expanded="false"
|
||||
title="Show activity"
|
||||
>
|
||||
<span class="pip rail-pip" class:live={connected} class:reconnecting={connState === 'reconnecting'} aria-hidden="true"></span>
|
||||
{#if busyCount > 0}
|
||||
<span class="rail-count" title="{busyCount} job(s) running or queued">{busyCount}</span>
|
||||
{/if}
|
||||
<span class="rail-label">Activity</span>
|
||||
<span class="rail-chevron" aria-hidden="true">‹</span>
|
||||
</button>
|
||||
{:else}
|
||||
<header class="head">
|
||||
<div class="head-title">
|
||||
<span class="pip" class:live={connected} class:reconnecting={connState === 'reconnecting'} aria-hidden="true"></span>
|
||||
<strong>Activity</strong>
|
||||
{#if connState === 'reconnecting'}
|
||||
<span class="conn-state warn">Reconnecting…</span>
|
||||
{:else if connState === 'connecting'}
|
||||
<span class="conn-state">Connecting…</span>
|
||||
{/if}
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onclick={onToggle} title="Hide activity">
|
||||
Hide <Icon name="chevron-right" size={13} />
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
<section class="queue" aria-label="Queue">
|
||||
<div class="section-head">
|
||||
<p class="eyebrow">Queue</p>
|
||||
</div>
|
||||
{#if queueRows.length === 0}
|
||||
<p class="queue-empty">Queue idle — renders and generations land here.</p>
|
||||
{:else}
|
||||
<div class="job-list">
|
||||
{#each queueRows as job (job.id)}
|
||||
<JobRow {job} />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="stats-strip" aria-label="Queue stats">
|
||||
<span><span class="sd sd-running" aria-hidden="true"></span>{stats.running} running</span>
|
||||
<span><span class="sd sd-queued" aria-hidden="true"></span>{stats.queued} queued</span>
|
||||
<span><span class="sd sd-done" aria-hidden="true"></span>{stats.done} done</span>
|
||||
<span><span class="sd sd-failed" aria-hidden="true"></span>{stats.failed} failed</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="log-section" aria-label="Agent log">
|
||||
<p class="eyebrow">Agent log</p>
|
||||
{#if entries.length === 0}
|
||||
<div class="empty">
|
||||
<p>Quiet for now.</p>
|
||||
<p class="hint">Draft a story, generate assets, or regenerate the script — progress shows up here.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<ul class="log">
|
||||
{#each entries as ev (ev.key)}
|
||||
<li class="entry tone-{ev.tone}">
|
||||
<span class="dot" aria-hidden="true"></span>
|
||||
<div class="meta">
|
||||
<div class="row">
|
||||
<span class="title">{ev.title}</span>
|
||||
<time class="ts" datetime={ev.ts}>{ev.ts}</time>
|
||||
</div>
|
||||
{#if ev.detail}
|
||||
<p class="detail">{ev.detail}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
{/if}
|
||||
</aside>
|
||||
|
||||
<style>
|
||||
.activity {
|
||||
--panel-w: 320px;
|
||||
--rail-w: 44px;
|
||||
width: var(--panel-w);
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
border-left: 1px solid var(--border);
|
||||
background:
|
||||
linear-gradient(180deg, rgba(139, 92, 246, 0.06) 0%, transparent 120px),
|
||||
var(--bg-surface);
|
||||
overflow: hidden;
|
||||
transition: width 0.2s ease;
|
||||
}
|
||||
|
||||
.activity.collapsed {
|
||||
width: var(--rail-w);
|
||||
background: var(--bg-surface);
|
||||
}
|
||||
|
||||
.rail-toggle {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 16px 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rail-toggle:hover {
|
||||
background: rgba(139, 92, 246, 0.08);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.rail-toggle:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.rail-label {
|
||||
writing-mode: vertical-rl;
|
||||
transform: rotate(180deg);
|
||||
font-family: var(--font-display);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.rail-chevron {
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.rail-count {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 20px;
|
||||
height: 20px;
|
||||
padding: 0 5px;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.pip {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.pip.live {
|
||||
background: var(--accent);
|
||||
box-shadow: 0 0 0 4px var(--accent-glow);
|
||||
animation: live-pulse 1.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.pip.reconnecting {
|
||||
background: var(--warning);
|
||||
box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.18);
|
||||
}
|
||||
|
||||
@keyframes live-pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.65;
|
||||
transform: scale(0.92);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.activity {
|
||||
transition: none;
|
||||
}
|
||||
.pip.live {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 14px 14px 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.head-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.head-title strong {
|
||||
font-family: var(--font-display);
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.conn-state {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.conn-state.warn {
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 12px 10px 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.queue {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.section-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.job-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
max-height: 216px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.queue-empty {
|
||||
margin: 0 6px 4px;
|
||||
padding: 12px 14px;
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.stats-strip {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
margin: 10px 6px 0;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--border);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
color: var(--text-secondary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.stats-strip > span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sd {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.sd-running {
|
||||
background: var(--info);
|
||||
}
|
||||
.sd-queued {
|
||||
background: var(--text-muted);
|
||||
}
|
||||
.sd-done {
|
||||
background: var(--success);
|
||||
}
|
||||
.sd-failed {
|
||||
background: var(--error);
|
||||
}
|
||||
|
||||
.log-section {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 6px 10px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 8px 6px;
|
||||
padding: 16px;
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.empty p {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.empty .hint {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.log {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0 4px 8px 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.entry {
|
||||
display: grid;
|
||||
grid-template-columns: 14px 1fr;
|
||||
gap: 8px;
|
||||
padding: 8px 8px 8px 4px;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.entry:hover {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
margin-top: 5px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-muted);
|
||||
justify-self: center;
|
||||
}
|
||||
|
||||
.tone-ok .dot {
|
||||
background: var(--success);
|
||||
}
|
||||
.tone-err .dot {
|
||||
background: var(--error);
|
||||
}
|
||||
.tone-warn .dot {
|
||||
background: var(--warning);
|
||||
}
|
||||
.tone-work .dot {
|
||||
background: var(--accent);
|
||||
}
|
||||
.tone-info .dot {
|
||||
background: var(--info);
|
||||
}
|
||||
|
||||
.meta {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.ts {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.detail {
|
||||
margin: 3px 0 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
color: var(--text-secondary);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.tone-err .detail {
|
||||
color: #fca5a5;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,132 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
active?: 'projects' | 'playground' | 'settings';
|
||||
crumb?: string;
|
||||
/** Optional status content rendered between the crumb and the nav. */
|
||||
status?: import('svelte').Snippet;
|
||||
children?: import('svelte').Snippet;
|
||||
}
|
||||
|
||||
let { active, crumb, status, children }: Props = $props();
|
||||
</script>
|
||||
|
||||
<header class="header">
|
||||
<div class="header-left">
|
||||
<a class="logo" href="/" title="Projects">
|
||||
Calliope <span>Lab</span>
|
||||
</a>
|
||||
{#if crumb}
|
||||
<span class="crumb">{crumb}</span>
|
||||
{/if}
|
||||
{#if status}
|
||||
<div class="header-status">
|
||||
{@render status()}
|
||||
</div>
|
||||
{/if}
|
||||
<nav class="top-nav" aria-label="Primary">
|
||||
<a class="nav-link" class:active={active === 'projects'} href="/">Projects</a>
|
||||
<a class="nav-link" class:active={active === 'playground'} href="/playground">Playground</a>
|
||||
<a class="nav-link" class:active={active === 'settings'} href="/settings">Settings</a>
|
||||
</nav>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
{#if children}
|
||||
{@render children()}
|
||||
{/if}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<style>
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-md);
|
||||
padding: 14px 24px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-surface);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-md);
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.logo {
|
||||
font-family: var(--font-display);
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
text-decoration: none;
|
||||
letter-spacing: -0.02em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.logo span {
|
||||
color: var(--accent);
|
||||
font-weight: 500;
|
||||
}
|
||||
.crumb {
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.header-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.top-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: 8px;
|
||||
}
|
||||
.nav-link {
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-secondary);
|
||||
text-decoration: none;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
transition: color 0.15s, background 0.15s;
|
||||
min-height: 36px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.nav-link:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.nav-link.active {
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-elevated);
|
||||
box-shadow: inset 0 -2px 0 var(--accent);
|
||||
}
|
||||
.nav-link:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.header {
|
||||
padding: 12px 16px;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
.top-nav {
|
||||
margin-left: 0;
|
||||
width: 100%;
|
||||
}
|
||||
.nav-link {
|
||||
flex: 1;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,132 @@
|
||||
<script lang="ts">
|
||||
import SafeMedia from '$lib/components/SafeMedia.svelte';
|
||||
import StatusChip from '$lib/components/ui/StatusChip.svelte';
|
||||
|
||||
interface Props {
|
||||
src: string | null;
|
||||
alt: string;
|
||||
placeholder: string;
|
||||
wide?: boolean;
|
||||
/** Taller 4:3 media-first crop (asset card grids). */
|
||||
tall?: boolean;
|
||||
/** Latest generation-job state for this asset, if the parent tracks jobs. */
|
||||
jobState?: 'generating' | 'failed' | null;
|
||||
onPreview?: (src: string) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
src,
|
||||
alt,
|
||||
placeholder,
|
||||
wide = false,
|
||||
tall = false,
|
||||
jobState = null,
|
||||
onPreview,
|
||||
}: Props = $props();
|
||||
|
||||
let available = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
void src;
|
||||
available = false;
|
||||
});
|
||||
|
||||
// Job state (live from the queue) wins over the media-derived state.
|
||||
const chip = $derived.by((): { status: string; label: string } => {
|
||||
if (jobState === 'generating') return { status: 'generating', label: 'Generating' };
|
||||
if (jobState === 'failed') return { status: 'failed', label: 'Failed' };
|
||||
if (available) return { status: 'ready', label: 'Ready' };
|
||||
if (src) return { status: 'missing', label: 'Missing' };
|
||||
return { status: 'pending', label: 'Pending' };
|
||||
});
|
||||
|
||||
function open() {
|
||||
if (available && src && onPreview) onPreview(src);
|
||||
}
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
open();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex a11y_no_noninteractive_element_interactions -->
|
||||
<div
|
||||
class="thumb"
|
||||
class:wide
|
||||
class:tall
|
||||
class:clickable={available && !!onPreview}
|
||||
role={available && onPreview ? 'button' : undefined}
|
||||
tabindex={available && onPreview ? 0 : undefined}
|
||||
onclick={open}
|
||||
onkeydown={available && onPreview ? onKey : undefined}
|
||||
>
|
||||
<SafeMedia
|
||||
class="fill"
|
||||
{src}
|
||||
{alt}
|
||||
label={placeholder}
|
||||
onAvailable={() => (available = true)}
|
||||
onUnavailable={() => (available = false)}
|
||||
/>
|
||||
<span class="thumb-chip">
|
||||
<StatusChip status={chip.status} label={chip.label} />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.thumb {
|
||||
aspect-ratio: 1;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.thumb.wide {
|
||||
aspect-ratio: 16 / 10;
|
||||
}
|
||||
.thumb.tall {
|
||||
aspect-ratio: 4 / 3;
|
||||
}
|
||||
.thumb.clickable {
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.thumb.clickable:hover {
|
||||
border-color: var(--accent, #a78bfa);
|
||||
}
|
||||
.thumb.clickable:focus-visible {
|
||||
outline: 2px solid var(--accent, #a78bfa);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.thumb :global(.fill) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.thumb :global(.safe-media-ph.fill) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
.thumb-chip {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
z-index: 1;
|
||||
filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.6));
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,319 @@
|
||||
<script lang="ts">
|
||||
import { createMutation, createQuery } from '@tanstack/svelte-query';
|
||||
import {
|
||||
playgroundApi,
|
||||
projects,
|
||||
type Character,
|
||||
type Location,
|
||||
type PlaygroundAttachTarget,
|
||||
type Project,
|
||||
type Scene,
|
||||
} from '$lib/api';
|
||||
import { toast } from '$lib/toast';
|
||||
import Button from './ui/Button.svelte';
|
||||
import Icon from './ui/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
path: string;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
let { path, kind }: Props = $props();
|
||||
|
||||
const isVideo = $derived(
|
||||
kind === 'video' || path.toLowerCase().endsWith('.mp4') || path.toLowerCase().endsWith('.webm'),
|
||||
);
|
||||
|
||||
let open = $state(false);
|
||||
let projectId = $state<number | ''>('');
|
||||
let target = $state<PlaygroundAttachTarget>('character_sheet');
|
||||
let characterId = $state<number | ''>('');
|
||||
let locationId = $state<number | ''>('');
|
||||
let sceneId = $state<number | ''>('');
|
||||
let message = $state('');
|
||||
let characters = $state<Character[]>([]);
|
||||
let locations = $state<Location[]>([]);
|
||||
let scenes = $state<Scene[]>([]);
|
||||
let loadingTargets = $state(false);
|
||||
let attached = $state<{ projectId: number; title: string } | null>(null);
|
||||
|
||||
const projectsQuery = createQuery({
|
||||
queryKey: ['projects'],
|
||||
queryFn: projects.list,
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
if (isVideo) {
|
||||
target = 'scene';
|
||||
} else if (target === 'scene') {
|
||||
target = 'character_sheet';
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const pid = projectId;
|
||||
characterId = '';
|
||||
locationId = '';
|
||||
sceneId = '';
|
||||
message = '';
|
||||
characters = [];
|
||||
locations = [];
|
||||
scenes = [];
|
||||
if (!open || pid === '') return;
|
||||
|
||||
let cancelled = false;
|
||||
loadingTargets = true;
|
||||
const load = async () => {
|
||||
try {
|
||||
const assets = await projects.getAssets(Number(pid));
|
||||
if (cancelled) return;
|
||||
characters = assets.characters;
|
||||
locations = assets.locations;
|
||||
if (isVideo) {
|
||||
const sceneData = await projects.getScenes(Number(pid));
|
||||
if (cancelled) return;
|
||||
scenes = sceneData.scenes;
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) loadingTargets = false;
|
||||
}
|
||||
};
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
});
|
||||
|
||||
const attachMutation = createMutation({
|
||||
mutationFn: () => {
|
||||
if (projectId === '') throw new Error('Pick a project');
|
||||
const payload: Parameters<typeof playgroundApi.attach>[0] = {
|
||||
path,
|
||||
project_id: Number(projectId),
|
||||
target,
|
||||
};
|
||||
if (target === 'character_sheet') {
|
||||
if (characterId === '') throw new Error('Pick a character');
|
||||
payload.character_id = Number(characterId);
|
||||
} else if (target === 'location') {
|
||||
if (locationId === '') throw new Error('Pick a location');
|
||||
payload.location_id = Number(locationId);
|
||||
} else {
|
||||
if (sceneId === '') throw new Error('Pick a scene');
|
||||
payload.scene_id = Number(sceneId);
|
||||
}
|
||||
return playgroundApi.attach(payload);
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
message = '';
|
||||
open = false;
|
||||
const p = projectList.find((x) => x.id === res.project_id);
|
||||
attached = { projectId: res.project_id, title: p?.title ?? `Project #${res.project_id}` };
|
||||
toast.success('Added to project');
|
||||
},
|
||||
onError: (err) => {
|
||||
message = err instanceof Error ? err.message : 'Attach failed';
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
|
||||
const projectList = $derived(($projectsQuery.data ?? []) as Project[]);
|
||||
|
||||
// Stage-URL contract: images land on Assets, clips on Video.
|
||||
const stageLink = $derived(
|
||||
attached ? `/project/${attached.projectId}?stage=${isVideo ? 'video' : 'assets'}` : '',
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="attach">
|
||||
{#if attached && !open}
|
||||
<div class="attached" role="status">
|
||||
<span class="attached-check" aria-hidden="true"><Icon name="check" size={14} /></span>
|
||||
<span class="attached-text">Added to <strong>{attached.title}</strong></span>
|
||||
<a class="attached-link" href={stageLink}>View in project</a>
|
||||
<button
|
||||
class="attached-dismiss"
|
||||
type="button"
|
||||
title="Dismiss"
|
||||
onclick={() => (attached = null)}
|
||||
>
|
||||
<Icon name="close" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
{:else if !open}
|
||||
<Button variant="secondary" onclick={() => (open = true)}>Add to project</Button>
|
||||
{:else}
|
||||
<div class="panel" role="group" aria-label="Add artifact to project">
|
||||
<label class="field">
|
||||
<span class="field-label">Project</span>
|
||||
<select class="field-select" bind:value={projectId}>
|
||||
<option value="">Select project…</option>
|
||||
{#each projectList as p}
|
||||
<option value={p.id}>{p.title}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{#if !isVideo}
|
||||
<label class="field">
|
||||
<span class="field-label">Add as</span>
|
||||
<select class="field-select" bind:value={target}>
|
||||
<option value="character_sheet">Character sheet</option>
|
||||
<option value="location">Background / location</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{#if target === 'character_sheet'}
|
||||
<label class="field">
|
||||
<span class="field-label">Character</span>
|
||||
<select class="field-select" bind:value={characterId} disabled={projectId === '' || loadingTargets}>
|
||||
<option value="">Select character…</option>
|
||||
{#each characters as c}
|
||||
<option value={c.id}>{c.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if projectId !== '' && !loadingTargets && characters.length === 0}
|
||||
<span class="field-hint">No characters in this project yet.</span>
|
||||
{/if}
|
||||
</label>
|
||||
{:else}
|
||||
<label class="field">
|
||||
<span class="field-label">Location</span>
|
||||
<select class="field-select" bind:value={locationId} disabled={projectId === '' || loadingTargets}>
|
||||
<option value="">Select location…</option>
|
||||
{#each locations as loc}
|
||||
<option value={loc.id}>{loc.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if projectId !== '' && !loadingTargets && locations.length === 0}
|
||||
<span class="field-hint">No locations in this project yet.</span>
|
||||
{/if}
|
||||
</label>
|
||||
{/if}
|
||||
{:else}
|
||||
<label class="field">
|
||||
<span class="field-label">Scene</span>
|
||||
<select class="field-select" bind:value={sceneId} disabled={projectId === '' || loadingTargets}>
|
||||
<option value="">Select scene…</option>
|
||||
{#each scenes as s}
|
||||
<option value={s.id}>#{s.order_index} {s.heading || 'Scene'}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if projectId !== '' && !loadingTargets && scenes.length === 0}
|
||||
<span class="field-hint">No scenes yet — generate a script first.</span>
|
||||
{/if}
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
<div class="actions">
|
||||
<Button
|
||||
variant="primary"
|
||||
loading={$attachMutation.isPending}
|
||||
disabled={projectId === ''}
|
||||
onclick={() => $attachMutation.mutate()}
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
<Button variant="ghost" onclick={() => (open = false)}>Cancel</Button>
|
||||
</div>
|
||||
{#if message && $attachMutation.isError}
|
||||
<p class="err" role="alert">{message}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.attach {
|
||||
margin-top: 10px;
|
||||
}
|
||||
.attached {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
background: rgba(34, 197, 94, 0.08);
|
||||
border: 1px solid rgba(34, 197, 94, 0.3);
|
||||
border-radius: var(--radius-md);
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.attached-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background: var(--success);
|
||||
color: #052e12;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.attached-text {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.attached-text strong {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
.attached-link {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.attached-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.attached-link:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
.attached-dismiss {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
margin-left: auto;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.attached-dismiss:hover {
|
||||
color: var(--text-primary);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.attached-dismiss:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 12px;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.err {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--error);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,694 @@
|
||||
<script lang="ts">
|
||||
import { assetUrl, playgroundApi, type UploadKind } from '$lib/api';
|
||||
import type { ComfyDynamicInput } from '$lib/comfy/types';
|
||||
import { toast } from '$lib/toast';
|
||||
import Icon from './ui/Icon.svelte';
|
||||
import Spinner from './ui/Spinner.svelte';
|
||||
|
||||
interface Props {
|
||||
inputs: ComfyDynamicInput[];
|
||||
values?: Record<string, string | number>;
|
||||
readonly?: boolean;
|
||||
/** Hide technical role/kind chips (Playground human labels). */
|
||||
quiet?: boolean;
|
||||
assetOptions?: Array<{ label: string; path: string }>;
|
||||
/** Allow client-file uploads (dropzone) for image/audio inputs. */
|
||||
allowUpload?: boolean;
|
||||
/** Force required-field error rings visible (e.g. after a blocked Generate). */
|
||||
showErrors?: boolean;
|
||||
/** Emits labels of required-but-empty inputs whenever the set changes. */
|
||||
onValidityChange?: (missing: string[]) => void;
|
||||
onChange?: (values: Record<string, string | number>) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
inputs,
|
||||
values = $bindable({}),
|
||||
readonly = false,
|
||||
quiet = false,
|
||||
assetOptions = [],
|
||||
allowUpload = false,
|
||||
showErrors = false,
|
||||
onValidityChange,
|
||||
onChange,
|
||||
}: Props = $props();
|
||||
|
||||
// Unique per mounted form so label/id pairs never collide across instances.
|
||||
const uid = Math.random().toString(36).slice(2, 8);
|
||||
let touched = $state<Record<string, boolean>>({});
|
||||
|
||||
function inputId(nodeId: string): string {
|
||||
return `cdf-${uid}-${nodeId.replace(/[^a-zA-Z0-9_-]/g, '')}`;
|
||||
}
|
||||
|
||||
function setValue(nodeId: string, value: string | number) {
|
||||
values = { ...values, [nodeId]: value };
|
||||
onChange?.(values);
|
||||
}
|
||||
|
||||
function setNumberValue(nodeId: string, raw: string) {
|
||||
// '' must stay '' — Number('') === 0 would silently turn a cleared field into 0.
|
||||
// Blank strings are stripped by compactInputValues before submission.
|
||||
if (raw === '') {
|
||||
setValue(nodeId, '');
|
||||
return;
|
||||
}
|
||||
const n = Number(raw);
|
||||
if (!Number.isNaN(n)) setValue(nodeId, n);
|
||||
}
|
||||
|
||||
function markTouched(nodeId: string) {
|
||||
if (!touched[nodeId]) touched = { ...touched, [nodeId]: true };
|
||||
}
|
||||
|
||||
function isBlank(value: string | number | undefined): boolean {
|
||||
return value === undefined || (typeof value === 'string' && !value.trim());
|
||||
}
|
||||
|
||||
function isMissing(inp: ComfyDynamicInput): boolean {
|
||||
return inp.required && isBlank(values[inp.nodeId]);
|
||||
}
|
||||
|
||||
const missingLabels = $derived(inputs.filter(isMissing).map((inp) => inp.label));
|
||||
|
||||
$effect(() => {
|
||||
onValidityChange?.(missingLabels);
|
||||
});
|
||||
|
||||
function showError(inp: ComfyDynamicInput): boolean {
|
||||
return isMissing(inp) && (showErrors || !!touched[inp.nodeId]);
|
||||
}
|
||||
|
||||
function thumbFor(current: string): string | null {
|
||||
if (!current) return null;
|
||||
const opt = assetOptions.find((o) => o.path === current);
|
||||
return opt ? assetUrl(opt.path) : null;
|
||||
}
|
||||
|
||||
/** Hide a broken preview image (asset moved/deleted on disk). */
|
||||
function hideBrokenThumb(e: Event) {
|
||||
const img = e.currentTarget as HTMLImageElement | null;
|
||||
if (img) img.style.display = 'none';
|
||||
}
|
||||
|
||||
function isImageKind(kind: string) {
|
||||
return kind === 'image' || kind === 'image_url';
|
||||
}
|
||||
|
||||
function isUploadKind(kind: string) {
|
||||
return isImageKind(kind) || kind === 'audio';
|
||||
}
|
||||
|
||||
// --- Client-file uploads (allowUpload) ---
|
||||
// One shared hidden file input serves every uploadable field; uploadNodeId
|
||||
// remembers which field the picker was opened for.
|
||||
let fileInput = $state<HTMLInputElement | null>(null);
|
||||
let uploadNodeId: string | null = null;
|
||||
let uploading = $state<Record<string, string>>({});
|
||||
let dragDepth = $state<Record<string, number>>({});
|
||||
let uploadedMeta = $state<Record<string, { name: string; kind: UploadKind }>>({});
|
||||
|
||||
function uploadKindLabel(kind: string) {
|
||||
return kind === 'audio' ? 'audio' : 'image';
|
||||
}
|
||||
|
||||
function acceptFor(kind: string) {
|
||||
return kind === 'audio' ? 'audio/*' : 'image/*';
|
||||
}
|
||||
|
||||
function truncateMiddle(name: string, max = 32): string {
|
||||
if (name.length <= max) return name;
|
||||
const head = Math.ceil((max - 1) / 2);
|
||||
const tail = Math.floor((max - 1) / 2);
|
||||
return `${name.slice(0, head)}…${name.slice(name.length - tail)}`;
|
||||
}
|
||||
|
||||
/** Display name + media kind for an uploaded path (falls back to extension sniffing). */
|
||||
function uploadMetaFor(path: string): { name: string; kind: UploadKind } {
|
||||
const meta = uploadedMeta[path];
|
||||
if (meta) return meta;
|
||||
const base = path.split(/[/\\]/).pop() ?? path;
|
||||
const ext = base.slice(base.lastIndexOf('.')).toLowerCase();
|
||||
if (['.mp4', '.webm', '.mov', '.mkv'].includes(ext)) return { name: base, kind: 'video' };
|
||||
if (['.mp3', '.wav', '.flac', '.ogg', '.m4a'].includes(ext))
|
||||
return { name: base, kind: 'audio' };
|
||||
return { name: base, kind: 'image' };
|
||||
}
|
||||
|
||||
function openFilePicker(inp: ComfyDynamicInput) {
|
||||
if (!fileInput || uploading[inp.nodeId]) return;
|
||||
uploadNodeId = inp.nodeId;
|
||||
fileInput.accept = acceptFor(inp.kind);
|
||||
fileInput.value = '';
|
||||
fileInput.click();
|
||||
}
|
||||
|
||||
function onFileChosen(e: Event) {
|
||||
const el = e.currentTarget as HTMLInputElement;
|
||||
const file = el.files?.[0];
|
||||
const nodeId = uploadNodeId;
|
||||
uploadNodeId = null;
|
||||
if (!file || !nodeId) return;
|
||||
const inp = inputs.find((i) => i.nodeId === nodeId);
|
||||
if (inp) void doUpload(inp, file);
|
||||
}
|
||||
|
||||
function onUploadDragEnter(nodeId: string, e: DragEvent) {
|
||||
e.preventDefault();
|
||||
dragDepth = { ...dragDepth, [nodeId]: (dragDepth[nodeId] ?? 0) + 1 };
|
||||
}
|
||||
|
||||
function onUploadDragLeave(nodeId: string) {
|
||||
dragDepth = { ...dragDepth, [nodeId]: Math.max(0, (dragDepth[nodeId] ?? 0) - 1) };
|
||||
}
|
||||
|
||||
function onUploadDrop(inp: ComfyDynamicInput, e: DragEvent) {
|
||||
e.preventDefault();
|
||||
dragDepth = { ...dragDepth, [inp.nodeId]: 0 };
|
||||
if (uploading[inp.nodeId]) return;
|
||||
const file = e.dataTransfer?.files?.[0];
|
||||
if (file) void doUpload(inp, file);
|
||||
}
|
||||
|
||||
async function doUpload(inp: ComfyDynamicInput, file: File) {
|
||||
uploading = { ...uploading, [inp.nodeId]: file.name };
|
||||
try {
|
||||
const res = await playgroundApi.upload(file);
|
||||
uploadedMeta = { ...uploadedMeta, [res.path]: { name: res.name, kind: res.kind } };
|
||||
setValue(inp.nodeId, res.path);
|
||||
markTouched(inp.nodeId);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Upload failed');
|
||||
} finally {
|
||||
const next = { ...uploading };
|
||||
delete next[inp.nodeId];
|
||||
uploading = next;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const next = { ...values };
|
||||
let changed = false;
|
||||
for (const inp of inputs) {
|
||||
if (next[inp.nodeId] === undefined && inp.defaultValue !== undefined && inp.defaultValue !== '') {
|
||||
next[inp.nodeId] = inp.defaultValue;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
values = next;
|
||||
onChange?.(values);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if inputs.length === 0}
|
||||
<p class="muted">
|
||||
No (Input) / (Input:role) nodes detected. In ComfyUI, title editable nodes like
|
||||
<code>(Input:prompt)</code> — see AGENTS.md.
|
||||
</p>
|
||||
{:else}
|
||||
<div class="form">
|
||||
{#if allowUpload}
|
||||
<input
|
||||
bind:this={fileInput}
|
||||
type="file"
|
||||
class="sr-only-file"
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
onchange={onFileChosen}
|
||||
/>
|
||||
{/if}
|
||||
{#each inputs as inp (inp.nodeId)}
|
||||
{@const current = String(values[inp.nodeId] ?? '')}
|
||||
{@const id = inputId(inp.nodeId)}
|
||||
{@const errored = showError(inp)}
|
||||
<div class="field">
|
||||
<label class="label" for={id}>
|
||||
{inp.label}
|
||||
{#if inp.required}
|
||||
<span class="req" title="Required" aria-hidden="true">*</span>
|
||||
{/if}
|
||||
{#if !quiet}
|
||||
{#if inp.role}<span class="role">{inp.role}</span>{/if}
|
||||
<span class="kind">{inp.kind}</span>
|
||||
{/if}
|
||||
</label>
|
||||
{#if readonly}
|
||||
<div class="readonly">{values[inp.nodeId] ?? inp.defaultValue ?? '—'}</div>
|
||||
{:else if inp.kind === 'textarea'}
|
||||
<textarea
|
||||
{id}
|
||||
rows="3"
|
||||
class:invalid={errored}
|
||||
aria-required={inp.required || undefined}
|
||||
aria-invalid={errored || undefined}
|
||||
value={current}
|
||||
oninput={(e) => setValue(inp.nodeId, e.currentTarget.value)}
|
||||
onblur={() => markTouched(inp.nodeId)}
|
||||
></textarea>
|
||||
{:else if inp.kind === 'number'}
|
||||
<input
|
||||
{id}
|
||||
type="number"
|
||||
class:invalid={errored}
|
||||
aria-required={inp.required || undefined}
|
||||
aria-invalid={errored || undefined}
|
||||
value={values[inp.nodeId] ?? ''}
|
||||
oninput={(e) => setNumberValue(inp.nodeId, e.currentTarget.value)}
|
||||
onblur={() => markTouched(inp.nodeId)}
|
||||
/>
|
||||
{:else if allowUpload && isUploadKind(inp.kind)}
|
||||
{@const uploadingName = uploading[inp.nodeId]}
|
||||
{@const isUpload = !!current && !assetOptions.some((o) => o.path === current)}
|
||||
<div class="upload-field">
|
||||
{#if isUpload}
|
||||
{@const meta = uploadMetaFor(current)}
|
||||
<div class="upload-preview">
|
||||
{#if meta.kind === 'image'}
|
||||
<img
|
||||
class="upload-thumb"
|
||||
src={assetUrl(current)}
|
||||
alt="Uploaded file preview"
|
||||
onerror={hideBrokenThumb}
|
||||
/>
|
||||
{:else}
|
||||
<span class="upload-file-icon" aria-hidden="true">
|
||||
<Icon name={meta.kind === 'audio' ? 'music' : 'film'} size={18} />
|
||||
</span>
|
||||
{/if}
|
||||
<span class="upload-name" title={meta.name}>{truncateMiddle(meta.name)}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="upload-clear"
|
||||
aria-label="Clear"
|
||||
onclick={() => setValue(inp.nodeId, '')}
|
||||
>
|
||||
<Icon name="close" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
id={assetOptions.length ? `${id}-upload` : id}
|
||||
class="dropzone"
|
||||
class:drag={(dragDepth[inp.nodeId] ?? 0) > 0}
|
||||
class:invalid={errored}
|
||||
disabled={!!uploadingName}
|
||||
aria-busy={!!uploadingName || undefined}
|
||||
onclick={() => openFilePicker(inp)}
|
||||
ondragenter={(e) => onUploadDragEnter(inp.nodeId, e)}
|
||||
ondragleave={() => onUploadDragLeave(inp.nodeId)}
|
||||
ondragover={(e) => e.preventDefault()}
|
||||
ondrop={(e) => onUploadDrop(inp, e)}
|
||||
>
|
||||
{#if uploadingName}
|
||||
<Spinner size="sm" />
|
||||
<span>Uploading {truncateMiddle(uploadingName, 24)}…</span>
|
||||
{:else}
|
||||
<Icon name="upload" size={16} />
|
||||
<span>Drop {uploadKindLabel(inp.kind)} here or <u>browse</u></span>
|
||||
{/if}
|
||||
</button>
|
||||
{#if assetOptions.length}
|
||||
{@const thumb = thumbFor(current)}
|
||||
<p class="upload-divider" aria-hidden="true">
|
||||
<span>or choose an existing asset</span>
|
||||
</p>
|
||||
<div class="pick-row">
|
||||
{#if isImageKind(inp.kind) && thumb}
|
||||
<img
|
||||
class="pick-thumb"
|
||||
src={thumb}
|
||||
alt="Selected asset preview"
|
||||
onerror={hideBrokenThumb}
|
||||
/>
|
||||
{/if}
|
||||
<select
|
||||
{id}
|
||||
class="pick-select"
|
||||
class:invalid={errored}
|
||||
aria-required={inp.required || undefined}
|
||||
aria-invalid={errored || undefined}
|
||||
value={current}
|
||||
onchange={(e) => {
|
||||
setValue(inp.nodeId, e.currentTarget.value);
|
||||
markTouched(inp.nodeId);
|
||||
}}
|
||||
>
|
||||
<option value="">Choose asset…</option>
|
||||
{#each assetOptions as opt}
|
||||
<option value={opt.path}>{opt.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if current}
|
||||
<button
|
||||
type="button"
|
||||
class="clear"
|
||||
onclick={() => setValue(inp.nodeId, '')}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if isImageKind(inp.kind)}
|
||||
{#if assetOptions.length}
|
||||
{@const thumb = thumbFor(current)}
|
||||
<div class="pick-row">
|
||||
{#if thumb}
|
||||
<img
|
||||
class="pick-thumb"
|
||||
src={thumb}
|
||||
alt="Selected asset preview"
|
||||
onerror={hideBrokenThumb}
|
||||
/>
|
||||
{/if}
|
||||
<select
|
||||
{id}
|
||||
class="pick-select"
|
||||
class:invalid={errored}
|
||||
aria-required={inp.required || undefined}
|
||||
aria-invalid={errored || undefined}
|
||||
value={current}
|
||||
onchange={(e) => {
|
||||
setValue(inp.nodeId, e.currentTarget.value);
|
||||
markTouched(inp.nodeId);
|
||||
}}
|
||||
>
|
||||
<option value="">Choose asset…</option>
|
||||
{#each assetOptions as opt}
|
||||
<option value={opt.path}>{opt.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if current}
|
||||
<button
|
||||
type="button"
|
||||
class="clear"
|
||||
onclick={() => setValue(inp.nodeId, '')}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="hint">No assets yet — generate sheets / environments in Assets first.</p>
|
||||
{/if}
|
||||
{:else if inp.kind === 'audio'}
|
||||
{#if assetOptions.length}
|
||||
<select
|
||||
{id}
|
||||
class:invalid={errored}
|
||||
aria-required={inp.required || undefined}
|
||||
aria-invalid={errored || undefined}
|
||||
value={current}
|
||||
onchange={(e) => {
|
||||
setValue(inp.nodeId, e.currentTarget.value);
|
||||
markTouched(inp.nodeId);
|
||||
}}
|
||||
>
|
||||
<option value="">Choose asset…</option>
|
||||
{#each assetOptions as opt}
|
||||
<option value={opt.path}>{opt.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{:else}
|
||||
<input
|
||||
{id}
|
||||
type="text"
|
||||
class:invalid={errored}
|
||||
aria-required={inp.required || undefined}
|
||||
aria-invalid={errored || undefined}
|
||||
placeholder="Local path"
|
||||
value={current}
|
||||
oninput={(e) => setValue(inp.nodeId, e.currentTarget.value)}
|
||||
onblur={() => markTouched(inp.nodeId)}
|
||||
/>
|
||||
{/if}
|
||||
{:else}
|
||||
<input
|
||||
{id}
|
||||
type="text"
|
||||
class:invalid={errored}
|
||||
aria-required={inp.required || undefined}
|
||||
aria-invalid={errored || undefined}
|
||||
value={current}
|
||||
oninput={(e) => setValue(inp.nodeId, e.currentTarget.value)}
|
||||
onblur={() => markTouched(inp.nodeId)}
|
||||
/>
|
||||
{/if}
|
||||
{#if errored}
|
||||
<span class="error-msg" role="alert">{inp.label} is required</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.label {
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.req {
|
||||
color: var(--error);
|
||||
margin-left: 2px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.kind {
|
||||
font-weight: 400;
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
margin-left: 6px;
|
||||
}
|
||||
.role {
|
||||
font-weight: 600;
|
||||
color: var(--accent, #a78bfa);
|
||||
font-size: 11px;
|
||||
margin-left: 6px;
|
||||
font-family: ui-monospace, monospace;
|
||||
}
|
||||
.role::before {
|
||||
content: 'role:';
|
||||
}
|
||||
input,
|
||||
textarea,
|
||||
select {
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 8px 10px;
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
}
|
||||
input:focus-visible,
|
||||
textarea:focus-visible,
|
||||
select:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
input.invalid,
|
||||
textarea.invalid,
|
||||
select.invalid {
|
||||
border-color: var(--error);
|
||||
}
|
||||
input.invalid:focus-visible,
|
||||
textarea.invalid:focus-visible,
|
||||
select.invalid:focus-visible {
|
||||
box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.25);
|
||||
}
|
||||
.error-msg {
|
||||
font-size: 11px;
|
||||
color: var(--error);
|
||||
}
|
||||
.pick-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
.pick-thumb {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex-shrink: 0;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
object-fit: cover;
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.pick-select {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 36px;
|
||||
}
|
||||
.clear {
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--border);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
padding: 0 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
min-height: 36px;
|
||||
}
|
||||
.clear:hover {
|
||||
color: var(--error);
|
||||
border-color: rgba(239, 68, 68, 0.4);
|
||||
}
|
||||
.clear:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.readonly {
|
||||
padding: 8px 0;
|
||||
color: var(--text-secondary);
|
||||
word-break: break-all;
|
||||
}
|
||||
.muted {
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.hint {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.sr-only-file {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
.upload-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.dropzone {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 64px;
|
||||
padding: 10px 12px;
|
||||
border: 1.5px dashed var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
border-color 0.15s,
|
||||
background 0.15s;
|
||||
}
|
||||
.dropzone:hover:not(:disabled) {
|
||||
border-color: var(--text-muted);
|
||||
}
|
||||
.dropzone:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
.dropzone.drag {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-glow);
|
||||
}
|
||||
.dropzone:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.7;
|
||||
}
|
||||
.dropzone.invalid {
|
||||
border-color: var(--error);
|
||||
}
|
||||
.upload-divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.upload-divider::before,
|
||||
.upload-divider::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.upload-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.upload-thumb {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
flex-shrink: 0;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
object-fit: cover;
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.upload-file-icon {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.upload-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.upload-clear {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.upload-clear:hover {
|
||||
color: var(--error);
|
||||
}
|
||||
.upload-clear:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,89 @@
|
||||
<script lang="ts">
|
||||
import Spinner from '$lib/components/ui/Spinner.svelte';
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
/** Live status line (e.g. latest agent.thinking message) — hidden when null/empty. */
|
||||
status?: string | null;
|
||||
/** Small secondary copy under the status line. */
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
let { title, status = null, hint = '' }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="overlay" role="status" aria-live="polite">
|
||||
<div class="inner">
|
||||
<Spinner size="lg" />
|
||||
<p class="title">{title}</p>
|
||||
{#if status}
|
||||
<p class="status">{status}</p>
|
||||
{/if}
|
||||
{#if hint}
|
||||
<p class="hint">{hint}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 30;
|
||||
background: rgba(18, 18, 24, 0.78);
|
||||
backdrop-filter: blur(2px);
|
||||
border-radius: var(--radius-md);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
cursor: wait;
|
||||
user-select: none;
|
||||
animation: overlay-fade 0.2s ease-out;
|
||||
}
|
||||
.inner {
|
||||
position: sticky;
|
||||
top: 28%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 28px 32px;
|
||||
max-width: 460px;
|
||||
text-align: center;
|
||||
}
|
||||
.title {
|
||||
margin: 4px 0 0;
|
||||
font-family: var(--font-display);
|
||||
font-size: 17px;
|
||||
font-weight: 650;
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.status {
|
||||
margin: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-secondary);
|
||||
word-break: break-word;
|
||||
}
|
||||
.hint {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
@keyframes overlay-fade {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.overlay {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,315 @@
|
||||
<script lang="ts">
|
||||
import SafeMedia from '$lib/components/SafeMedia.svelte';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
src: string | null;
|
||||
alt?: string;
|
||||
onClose: () => void;
|
||||
/** Optional filmstrip — enables prev/next buttons and arrow keys. */
|
||||
images?: string[];
|
||||
index?: number;
|
||||
onnavigate?: (i: number) => void;
|
||||
caption?: string;
|
||||
/** Render a video player instead of a zoomable image. */
|
||||
kind?: 'image' | 'video';
|
||||
}
|
||||
|
||||
let {
|
||||
src,
|
||||
alt = '',
|
||||
onClose,
|
||||
images,
|
||||
index = 0,
|
||||
onnavigate,
|
||||
caption,
|
||||
kind = 'image',
|
||||
}: Props = $props();
|
||||
|
||||
let zoomed = $state(false);
|
||||
|
||||
const isVideo = $derived(kind === 'video');
|
||||
|
||||
$effect(() => {
|
||||
void src;
|
||||
zoomed = false;
|
||||
});
|
||||
|
||||
const hasNav = $derived(Boolean(images && images.length > 1 && onnavigate));
|
||||
|
||||
function step(delta: number) {
|
||||
if (!images || images.length === 0 || !onnavigate) return;
|
||||
onnavigate((index + delta + images.length) % images.length);
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') onClose();
|
||||
else if (hasNav && e.key === 'ArrowLeft') step(-1);
|
||||
else if (hasNav && e.key === 'ArrowRight') step(1);
|
||||
}
|
||||
|
||||
const downloadName = $derived.by(() => {
|
||||
if (!src) return 'media';
|
||||
try {
|
||||
const query = src.split('?')[1] ?? '';
|
||||
const path = new URLSearchParams(query).get('path');
|
||||
const name = path ? decodeURIComponent(path).split(/[\\/]/).pop() : null;
|
||||
if (name) return name;
|
||||
} catch {
|
||||
// fall through to the generic name
|
||||
}
|
||||
return alt ? `${alt.trim().replace(/\s+/g, '-').toLowerCase()}.png` : 'media';
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={src ? onKeydown : undefined} />
|
||||
|
||||
{#if src}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="backdrop"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={isVideo ? 'Video preview' : 'Image preview'}
|
||||
tabindex="-1"
|
||||
onclick={onClose}
|
||||
>
|
||||
<div class="toolbar">
|
||||
{#if hasNav}
|
||||
<span class="counter">{index + 1} / {images?.length ?? 0}</span>
|
||||
{/if}
|
||||
{#if !isVideo}
|
||||
<button
|
||||
class="tool"
|
||||
type="button"
|
||||
aria-label={zoomed ? 'Fit to screen' : 'Zoom to 100%'}
|
||||
title={zoomed ? 'Fit to screen' : 'Zoom to 100%'}
|
||||
onclick={() => (zoomed = !zoomed)}
|
||||
>
|
||||
<Icon name="zoom-in" size={17} />
|
||||
</button>
|
||||
{/if}
|
||||
<a
|
||||
class="tool"
|
||||
href={src}
|
||||
download={downloadName}
|
||||
aria-label="Download media"
|
||||
title="Download"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Icon name="download" size={17} />
|
||||
</a>
|
||||
<button
|
||||
class="tool"
|
||||
type="button"
|
||||
aria-label="Close preview"
|
||||
title="Close (Esc)"
|
||||
onclick={onClose}
|
||||
>
|
||||
<Icon name="close" size={17} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if hasNav}
|
||||
<button
|
||||
class="nav prev"
|
||||
type="button"
|
||||
aria-label="Previous image"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
step(-1);
|
||||
}}
|
||||
>
|
||||
<Icon name="chevron-left" size={22} />
|
||||
</button>
|
||||
<button
|
||||
class="nav next"
|
||||
type="button"
|
||||
aria-label="Next image"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
step(1);
|
||||
}}
|
||||
>
|
||||
<Icon name="chevron-right" size={22} />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#if isVideo}
|
||||
<!-- Clicks on the player (play/pause/seek) must not close the modal -->
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
|
||||
<div class="player-frame" onclick={(e) => e.stopPropagation()}>
|
||||
<SafeMedia
|
||||
class="player"
|
||||
{src}
|
||||
{alt}
|
||||
kind="video"
|
||||
label="Video unavailable"
|
||||
autoplay
|
||||
controls
|
||||
preload="auto"
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="frame"
|
||||
class:zoomed
|
||||
title={zoomed ? 'Click to fit' : 'Click to zoom'}
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
zoomed = !zoomed;
|
||||
}}
|
||||
>
|
||||
<SafeMedia class="preview" {src} {alt} label="Image unavailable" />
|
||||
</div>
|
||||
{/if}
|
||||
{#if caption}
|
||||
<p class="caption">{caption}</p>
|
||||
{/if}
|
||||
<p class="hint">
|
||||
{#if isVideo}
|
||||
Click outside or press Esc to close ·
|
||||
{:else}
|
||||
Click the image to zoom · Click outside or press Esc to close ·
|
||||
{/if}
|
||||
<a href={src} target="_blank" rel="noopener" onclick={(e) => e.stopPropagation()}
|
||||
>Open original</a
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10000;
|
||||
background: rgba(0, 0, 0, 0.88);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 48px 24px 32px;
|
||||
gap: 12px;
|
||||
}
|
||||
.toolbar {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.counter {
|
||||
font-size: 12px;
|
||||
color: rgba(255, 255, 255, 0.65);
|
||||
margin-right: 4px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.tool {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.tool:hover {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
.tool:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.nav {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.nav:hover {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
.nav:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.nav.prev {
|
||||
left: 16px;
|
||||
}
|
||||
.nav.next {
|
||||
right: 16px;
|
||||
}
|
||||
.frame {
|
||||
max-width: min(96vw, 1600px);
|
||||
max-height: calc(100vh - 140px);
|
||||
display: flex;
|
||||
overflow: auto;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.frame.zoomed {
|
||||
cursor: zoom-out;
|
||||
}
|
||||
.frame :global(.preview) {
|
||||
max-width: min(96vw, 1600px);
|
||||
max-height: calc(100vh - 140px);
|
||||
width: auto;
|
||||
height: auto;
|
||||
object-fit: contain;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.5);
|
||||
min-height: 120px;
|
||||
min-width: 200px;
|
||||
margin: auto;
|
||||
}
|
||||
.frame.zoomed :global(.preview) {
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
}
|
||||
/* ── Video player mode ───────────────────────────────────── */
|
||||
.player-frame {
|
||||
max-width: min(96vw, 1600px);
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
.player-frame :global(.player) {
|
||||
max-width: min(96vw, 1600px);
|
||||
max-height: calc(100vh - 160px);
|
||||
width: 100%;
|
||||
border-radius: 6px;
|
||||
background: #000;
|
||||
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
.caption {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
max-width: min(96vw, 720px);
|
||||
text-align: center;
|
||||
}
|
||||
.hint {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
.hint a {
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,163 @@
|
||||
<script lang="ts">
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import { jobsApi, type Job } from '$lib/api';
|
||||
import { progressFor } from '$lib/jobProgress';
|
||||
import { toast } from '$lib/toast';
|
||||
import Button from './ui/Button.svelte';
|
||||
import Icon from './ui/Icon.svelte';
|
||||
import type { IconName } from './ui/icons';
|
||||
import ProgressBar from './ui/ProgressBar.svelte';
|
||||
import StatusChip from './ui/StatusChip.svelte';
|
||||
|
||||
interface Props {
|
||||
job: Job;
|
||||
/** Optional override for the leading label (defaults to "Kind #id"). */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
let { job, label }: Props = $props();
|
||||
|
||||
const client = useQueryClient();
|
||||
let busy = $state(false);
|
||||
|
||||
const kindIcon: IconName = $derived(
|
||||
job.kind === 'video'
|
||||
? 'video'
|
||||
: job.kind === 'image'
|
||||
? 'image'
|
||||
: job.kind === 'export'
|
||||
? 'film'
|
||||
: 'queue',
|
||||
);
|
||||
const kindLabel = $derived(
|
||||
job.kind === 'export'
|
||||
? 'Export film'
|
||||
: job.kind.charAt(0).toUpperCase() + job.kind.slice(1),
|
||||
);
|
||||
const title = $derived(label ?? `${kindLabel} #${job.id}`);
|
||||
const active = $derived(job.status === 'pending' || job.status === 'running');
|
||||
const entry = $derived(progressFor(job.id));
|
||||
|
||||
async function refresh() {
|
||||
await client.invalidateQueries({ queryKey: ['jobs'] });
|
||||
await client.invalidateQueries({ queryKey: ['playground-jobs'] });
|
||||
}
|
||||
|
||||
async function cancel() {
|
||||
busy = true;
|
||||
try {
|
||||
await jobsApi.cancel(job.id);
|
||||
await refresh();
|
||||
toast.info(`Cancelled #${job.id}`);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Cancel failed');
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function retry() {
|
||||
busy = true;
|
||||
try {
|
||||
await jobsApi.retry(job.id);
|
||||
await refresh();
|
||||
toast.success(`Re-queued #${job.id}`);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Retry failed');
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="job-row">
|
||||
<span class="kind" aria-hidden="true"><Icon name={kindIcon} size={14} /></span>
|
||||
<div class="main">
|
||||
<div class="top">
|
||||
<span class="label" {title}>{title}</span>
|
||||
<StatusChip status={job.status} />
|
||||
</div>
|
||||
{#if active}
|
||||
<div class="bar">
|
||||
<ProgressBar
|
||||
size="sm"
|
||||
value={entry?.progress ?? 0}
|
||||
indeterminate={job.status === 'running' && entry == null}
|
||||
label={entry?.message}
|
||||
/>
|
||||
</div>
|
||||
{:else if job.status === 'failed' && job.error}
|
||||
<p class="err" title={job.error}>{job.error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="actions">
|
||||
{#if active}
|
||||
<Button size="sm" variant="ghost" loading={busy} title="Cancel job" onclick={cancel}>
|
||||
<Icon name="close" size={13} />
|
||||
</Button>
|
||||
{:else if job.status === 'failed'}
|
||||
<Button size="sm" variant="ghost" loading={busy} title="Retry job" onclick={retry}>
|
||||
<Icon name="retry" size={13} />
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.job-row {
|
||||
display: grid;
|
||||
grid-template-columns: 20px 1fr auto;
|
||||
gap: 8px;
|
||||
align-items: start;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.kind {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 20px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.main {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-height: 20px;
|
||||
}
|
||||
.label {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.bar {
|
||||
padding-bottom: 2px;
|
||||
}
|
||||
.err {
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
line-height: 1.4;
|
||||
color: var(--error);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,134 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import type { IconName } from '$lib/components/ui/icons';
|
||||
|
||||
const items: { id: string; label: string; icon: IconName }[] = [
|
||||
{ id: 'story', label: 'Story', icon: 'story' },
|
||||
{ id: 'assets', label: 'Assets', icon: 'assets' },
|
||||
{ id: 'script', label: 'Script', icon: 'script' },
|
||||
{ id: 'video', label: 'Video', icon: 'video' },
|
||||
];
|
||||
|
||||
interface Props {
|
||||
active?: string;
|
||||
onSelect?: (id: string) => void;
|
||||
/** Optional per-stage counts — a nonzero value shows a small pill on the icon. */
|
||||
badges?: Record<string, number>;
|
||||
}
|
||||
|
||||
let { active = 'story', onSelect, badges = {} }: Props = $props();
|
||||
</script>
|
||||
|
||||
<nav class="nav" aria-label="Project stages">
|
||||
<button
|
||||
class="nav-item home"
|
||||
title="Projects"
|
||||
aria-label="Back to projects"
|
||||
onclick={() => goto('/')}
|
||||
>
|
||||
<span class="icon"><Icon name="home" size={20} /></span>
|
||||
<span class="label">Home</span>
|
||||
</button>
|
||||
<div class="divider" aria-hidden="true"></div>
|
||||
{#each items as item (item.id)}
|
||||
{@const count = badges[item.id] ?? 0}
|
||||
<button
|
||||
class="nav-item"
|
||||
class:active={active === item.id}
|
||||
title={item.label}
|
||||
aria-current={active === item.id ? 'page' : undefined}
|
||||
onclick={() => onSelect?.(item.id)}
|
||||
>
|
||||
<span class="icon">
|
||||
<Icon name={item.icon} size={20} />
|
||||
{#if count > 0}
|
||||
<span class="badge" aria-label="{count} active">
|
||||
{count > 9 ? '9+' : count}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
<span class="label">{item.label}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</nav>
|
||||
|
||||
<style>
|
||||
.nav {
|
||||
width: 64px;
|
||||
background: var(--bg-surface);
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: var(--space-md) 0;
|
||||
gap: var(--space-sm);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.divider {
|
||||
width: 32px;
|
||||
height: 1px;
|
||||
background: var(--border);
|
||||
margin: 2px 0 4px;
|
||||
}
|
||||
.nav-item {
|
||||
width: 56px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
border-radius: var(--radius-md);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
padding: 8px 0;
|
||||
cursor: pointer;
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
font-family: inherit;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.nav-item:hover {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.nav-item.active {
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
box-shadow: 0 0 16px var(--accent-glow);
|
||||
}
|
||||
.nav-item.home:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
.nav-item:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.icon {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
line-height: 1;
|
||||
}
|
||||
.badge {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -12px;
|
||||
min-width: 15px;
|
||||
height: 15px;
|
||||
padding: 0 4px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
line-height: 15px;
|
||||
text-align: center;
|
||||
box-shadow: 0 0 0 2px var(--bg-surface);
|
||||
}
|
||||
.nav-item.active .badge {
|
||||
background: #fff;
|
||||
color: var(--accent);
|
||||
box-shadow: 0 0 0 2px var(--accent);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,554 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* OmniComposer — Kling AI / MiniMax H3 style unified composer.
|
||||
*
|
||||
* Replaces ComfyDynamicForm in contexts that benefit from the compact
|
||||
* Omni layout (Playground, QueueStage video scenes).
|
||||
*
|
||||
* Takes the same `ComfyDynamicInput[]` and `values` record, classifies
|
||||
* each input into a UI zone (composer / media / control / advanced),
|
||||
* and renders the appropriate compact widget per zone.
|
||||
*
|
||||
* The values contract is identical to ComfyDynamicForm — picking 1080p
|
||||
* from the resolution pill writes `values[widthNodeId] = 1920` and
|
||||
* `values[heightNodeId] = 1080`. Backend API is untouched.
|
||||
*/
|
||||
import type { ComfyDynamicInput } from '$lib/comfy/types';
|
||||
import { classifyAll, RESOLUTION_PRESETS, resolutionLabel } from '$lib/comfy/classifyInput';
|
||||
import { createUploadManager } from '$lib/comfy/useUpload.svelte';
|
||||
import { normalizeInputRole } from '$lib/comfy/parser';
|
||||
import { assetUrl } from '$lib/api';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import PillSelect from './omni/PillSelect.svelte';
|
||||
import PillStepper from './omni/PillStepper.svelte';
|
||||
import PillPopover from './omni/PillPopover.svelte';
|
||||
import MediaTile from './omni/MediaTile.svelte';
|
||||
|
||||
interface WorkflowOption {
|
||||
id: number;
|
||||
name: string;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
interface AssetOption {
|
||||
label: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
inputs: ComfyDynamicInput[];
|
||||
values: Record<string, string | number>;
|
||||
/** Current workflow (for model pill label). */
|
||||
workflow?: WorkflowOption | null;
|
||||
/** Available workflows (for model pill dropdown). */
|
||||
workflows?: WorkflowOption[];
|
||||
onWorkflowChange?: (id: number) => void;
|
||||
assetOptions?: AssetOption[];
|
||||
allowUpload?: boolean;
|
||||
showErrors?: boolean;
|
||||
onValidityChange?: (missing: string[]) => void;
|
||||
onChange?: (values: Record<string, string | number>) => void;
|
||||
/** Enter or Ctrl+Enter in prompt → trigger Generate. */
|
||||
onSubmit?: () => void;
|
||||
/** Pending state for the Generate button (shows spinner-ish label). */
|
||||
submitting?: boolean;
|
||||
/** Custom label for the Generate button. */
|
||||
generateLabel?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
inputs,
|
||||
values = $bindable(),
|
||||
workflow = null,
|
||||
workflows = [],
|
||||
onWorkflowChange,
|
||||
assetOptions = [],
|
||||
allowUpload = false,
|
||||
showErrors = false,
|
||||
onValidityChange,
|
||||
onChange,
|
||||
onSubmit,
|
||||
submitting = false,
|
||||
generateLabel = 'Generate',
|
||||
}: Props = $props();
|
||||
|
||||
const uploadMgr = createUploadManager();
|
||||
|
||||
// Classify inputs into UI zones
|
||||
const classified = $derived(classifyAll(inputs));
|
||||
|
||||
// ── Value helpers ─────────────────────────────────────────────────────
|
||||
|
||||
/** Prefill undefined fields from workflow JSON defaults (mirrors ComfyDynamicForm). */
|
||||
$effect(() => {
|
||||
const next = { ...values };
|
||||
let changed = false;
|
||||
for (const inp of inputs) {
|
||||
if (
|
||||
next[inp.nodeId] === undefined &&
|
||||
inp.defaultValue !== undefined &&
|
||||
inp.defaultValue !== ''
|
||||
) {
|
||||
next[inp.nodeId] = inp.defaultValue;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
values = next;
|
||||
onChange?.(values);
|
||||
}
|
||||
});
|
||||
|
||||
function setValue(nodeId: string, value: string | number) {
|
||||
values = { ...values, [nodeId]: value };
|
||||
onChange?.(values);
|
||||
}
|
||||
|
||||
function clearValue(nodeId: string) {
|
||||
values = { ...values, [nodeId]: '' };
|
||||
onChange?.(values);
|
||||
}
|
||||
|
||||
// ── Resolution pill ───────────────────────────────────────────────────
|
||||
|
||||
const resPair = $derived(classified.resolutionPair);
|
||||
|
||||
const currentResLabel = $derived(
|
||||
resPair
|
||||
? resolutionLabel(values[resPair.width.input.nodeId], values[resPair.height.input.nodeId])
|
||||
: null,
|
||||
);
|
||||
|
||||
function setResolution(w: number, h: number) {
|
||||
if (!resPair) return;
|
||||
const next = { ...values };
|
||||
next[resPair.width.input.nodeId] = w;
|
||||
next[resPair.height.input.nodeId] = h;
|
||||
values = next;
|
||||
onChange?.(values);
|
||||
}
|
||||
|
||||
const resOptions = $derived(
|
||||
RESOLUTION_PRESETS.map((p) => ({
|
||||
value: `${p.width}x${p.height}`,
|
||||
label: `${p.label} (${p.width}×${p.height})`,
|
||||
})),
|
||||
);
|
||||
|
||||
const currentResValue = $derived.by(() => {
|
||||
if (!resPair) return null;
|
||||
const w = values[resPair.width.input.nodeId];
|
||||
const h = values[resPair.height.input.nodeId];
|
||||
return w && h ? `${w}x${h}` : null;
|
||||
});
|
||||
|
||||
function onResChange(val: string | number) {
|
||||
const [w, h] = String(val).split('x').map(Number);
|
||||
if (w && h) setResolution(w, h);
|
||||
}
|
||||
|
||||
// ── Workflow / model pill ─────────────────────────────────────────────
|
||||
|
||||
const wfOptions = $derived(
|
||||
(workflows ?? []).map((w) => ({ value: w.id, label: w.name })),
|
||||
);
|
||||
|
||||
function onWfChange(val: string | number) {
|
||||
onWorkflowChange?.(Number(val));
|
||||
}
|
||||
|
||||
// ── Media tiles ───────────────────────────────────────────────────────
|
||||
|
||||
async function handleFileUpload(nodeId: string, file: File) {
|
||||
const path = await uploadMgr.uploadSafe(nodeId, file);
|
||||
if (path) {
|
||||
setValue(nodeId, path);
|
||||
}
|
||||
}
|
||||
|
||||
function handleAssetSelect(nodeId: string, path: string) {
|
||||
setValue(nodeId, path);
|
||||
}
|
||||
|
||||
// ── Prompt textarea ───────────────────────────────────────────────────
|
||||
|
||||
const promptNode = $derived(classified.prompt?.input ?? null);
|
||||
const negativeNode = $derived(classified.negative?.input ?? null);
|
||||
let showNegative = $state(false);
|
||||
|
||||
function onPromptKeydown(e: KeyboardEvent) {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
onSubmit?.();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Validity tracking ─────────────────────────────────────────────────
|
||||
|
||||
function isBlank(val: string | number | undefined): boolean {
|
||||
return val === undefined || (typeof val === 'string' && !val.trim());
|
||||
}
|
||||
|
||||
const missingLabels = $derived(
|
||||
inputs.filter((inp) => inp.required && isBlank(values[inp.nodeId])).map((inp) => inp.label),
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
onValidityChange?.(missingLabels);
|
||||
});
|
||||
|
||||
// ── Advanced popover fields ───────────────────────────────────────────
|
||||
|
||||
const hasAdvanced = $derived(classified.advanced.length > 0);
|
||||
</script>
|
||||
|
||||
<div class="omni-shell">
|
||||
<!-- ── Composer body ─────────────────────────────────────────────── -->
|
||||
<div class="omni-composer" class:has-media={classified.media.length > 0}>
|
||||
{#if classified.media.length > 0}
|
||||
<div class="media-tray">
|
||||
{#each classified.media as mc (mc.input.nodeId)}
|
||||
{@const nodeId = mc.input.nodeId}
|
||||
<MediaTile
|
||||
input={mc.input}
|
||||
value={String(values[nodeId] ?? '')}
|
||||
uploadingName={uploadMgr.uploading[nodeId] ?? null}
|
||||
{assetOptions}
|
||||
{allowUpload}
|
||||
invalid={showErrors && isBlank(values[nodeId])}
|
||||
onselectFile={(file) => handleFileUpload(nodeId, file)}
|
||||
onselectAsset={(path) => handleAssetSelect(nodeId, path)}
|
||||
onclear={() => clearValue(nodeId)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if promptNode}
|
||||
<textarea
|
||||
class="prompt-area"
|
||||
placeholder="Describe the scene you want to generate…"
|
||||
rows="3"
|
||||
value={values[promptNode.nodeId] ?? ''}
|
||||
oninput={(e) => setValue(promptNode.nodeId, e.currentTarget.value)}
|
||||
onkeydown={onPromptKeydown}
|
||||
aria-label="Prompt"
|
||||
></textarea>
|
||||
{:else}
|
||||
<textarea
|
||||
class="prompt-area no-prompt-role"
|
||||
placeholder="This workflow has no (Input:prompt) field. Use the Advanced pill below for raw inputs."
|
||||
rows="2"
|
||||
disabled
|
||||
></textarea>
|
||||
{/if}
|
||||
|
||||
{#if negativeNode}
|
||||
<div class="negative-section">
|
||||
{#if showNegative}
|
||||
<textarea
|
||||
class="negative-area"
|
||||
placeholder="Negative prompt (what to avoid)…"
|
||||
rows="2"
|
||||
value={values[negativeNode.nodeId] ?? ''}
|
||||
oninput={(e) => setValue(negativeNode.nodeId, e.currentTarget.value)}
|
||||
onkeydown={onPromptKeydown}
|
||||
aria-label="Negative prompt"
|
||||
></textarea>
|
||||
{/if}
|
||||
<button type="button" class="negative-toggle" onclick={() => (showNegative = !showNegative)}>
|
||||
<Icon name={showNegative ? 'chevron-up' : 'chevron-down'} size={12} />
|
||||
Negative prompt
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- ── Control bar ───────────────────────────────────────────────── -->
|
||||
<div class="omni-controls">
|
||||
<!-- Model / workflow selector -->
|
||||
{#if workflow && workflows.length > 0}
|
||||
<PillSelect
|
||||
label={workflow.name}
|
||||
options={wfOptions}
|
||||
value={workflow.id}
|
||||
onchange={onWfChange}
|
||||
icon="sparkle"
|
||||
highlight
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<!-- Resolution pill (merged width + height) -->
|
||||
{#if resPair}
|
||||
<PillSelect
|
||||
label={currentResLabel ?? 'Resolution'}
|
||||
options={resOptions}
|
||||
value={currentResValue}
|
||||
onchange={onResChange}
|
||||
icon="image"
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<!-- Standalone width/height (only if not a pair) -->
|
||||
{#each classified.control.filter((c) => c.widget === 'resolutionPill') as ctrl (ctrl.input.nodeId)}
|
||||
{@const nodeId = ctrl.input.nodeId}
|
||||
<PillStepper
|
||||
label={ctrl.input.label}
|
||||
value={Number(values[nodeId]) || 0}
|
||||
min={256}
|
||||
max={4096}
|
||||
step={64}
|
||||
onchange={(v) => setValue(nodeId, v)}
|
||||
/>
|
||||
{/each}
|
||||
|
||||
<!-- Duration -->
|
||||
{#each classified.control.filter((c) => normalizeInputRole(c.input.role) === 'duration') as ctrl (ctrl.input.nodeId)}
|
||||
{@const nodeId = ctrl.input.nodeId}
|
||||
<PillStepper
|
||||
label="Duration"
|
||||
value={values[nodeId] ?? ctrl.input.defaultValue ?? 5}
|
||||
min={1}
|
||||
max={30}
|
||||
step={1}
|
||||
onchange={(v) => setValue(nodeId, v)}
|
||||
/>
|
||||
{/each}
|
||||
|
||||
<!-- Seed -->
|
||||
{#each classified.control.filter((c) => normalizeInputRole(c.input.role) === 'seed') as ctrl (ctrl.input.nodeId)}
|
||||
{@const nodeId = ctrl.input.nodeId}
|
||||
<PillStepper
|
||||
label="Seed"
|
||||
value={values[nodeId] ?? ctrl.input.defaultValue ?? 0}
|
||||
min={0}
|
||||
max={999999999}
|
||||
step={1}
|
||||
onchange={(v) => setValue(nodeId, v)}
|
||||
/>
|
||||
{/each}
|
||||
|
||||
<!-- Advanced (unknown roles, extra params) -->
|
||||
{#if hasAdvanced}
|
||||
<PillPopover label="Advanced" badge={classified.advanced.length} icon="settings">
|
||||
{#each classified.advanced as ctrl (ctrl.input.nodeId)}
|
||||
{@const nodeId = ctrl.input.nodeId}
|
||||
<label class="adv-field">
|
||||
<span class="adv-label">{ctrl.input.label}</span>
|
||||
{#if ctrl.input.kind === 'number'}
|
||||
<input
|
||||
class="adv-input"
|
||||
type="number"
|
||||
value={values[nodeId] ?? ctrl.input.defaultValue ?? ''}
|
||||
oninput={(e) => setValue(nodeId, Number(e.currentTarget.value) || 0)}
|
||||
/>
|
||||
{:else}
|
||||
<input
|
||||
class="adv-input"
|
||||
type="text"
|
||||
value={values[nodeId] ?? ctrl.input.defaultValue ?? ''}
|
||||
oninput={(e) => setValue(nodeId, e.currentTarget.value)}
|
||||
/>
|
||||
{/if}
|
||||
</label>
|
||||
{/each}
|
||||
</PillPopover>
|
||||
{/if}
|
||||
|
||||
<!-- Generate -->
|
||||
<button
|
||||
type="button"
|
||||
class="generate-btn"
|
||||
class:disabled={submitting}
|
||||
disabled={submitting}
|
||||
onclick={() => onSubmit?.()}
|
||||
aria-label="Generate"
|
||||
>
|
||||
<Icon name="sparkle" size={16} />
|
||||
{submitting ? 'Queuing…' : generateLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.omni-shell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
overflow: hidden;
|
||||
/* Prevent flex parents from collapsing this via overflow+min-height:auto */
|
||||
flex-shrink: 0;
|
||||
min-height: fit-content;
|
||||
}
|
||||
|
||||
/* ── Composer ──────────────────────────────────────────── */
|
||||
.omni-composer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
padding: 16px;
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.media-tray {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.prompt-area {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-body);
|
||||
font-size: 15px;
|
||||
line-height: 1.6;
|
||||
resize: vertical;
|
||||
min-height: 60px;
|
||||
outline: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.prompt-area::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.prompt-area:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.prompt-area.no-prompt-role {
|
||||
color: var(--text-muted);
|
||||
font-style: italic;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.negative-section {
|
||||
margin-top: 8px;
|
||||
border-top: 1px solid var(--border);
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.negative-area {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
font-family: var(--font-body);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
resize: vertical;
|
||||
min-height: 40px;
|
||||
outline: none;
|
||||
padding: 0;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.negative-area::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.negative-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
font-family: var(--font-body);
|
||||
cursor: pointer;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.negative-toggle:hover {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* ── Control bar ───────────────────────────────────────── */
|
||||
.omni-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 16px;
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-primary);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.generate-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 36px;
|
||||
padding: 0 20px;
|
||||
border-radius: 9999px;
|
||||
background: var(--success, #22c55e);
|
||||
border: none;
|
||||
color: #000;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
font-family: var(--font-body);
|
||||
cursor: pointer;
|
||||
margin-left: auto;
|
||||
transition: filter 0.15s, transform 0.1s;
|
||||
}
|
||||
|
||||
.generate-btn:hover {
|
||||
filter: brightness(1.1);
|
||||
}
|
||||
|
||||
.generate-btn:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.generate-btn.disabled,
|
||||
.generate-btn:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.7;
|
||||
transform: none;
|
||||
filter: none;
|
||||
}
|
||||
|
||||
.generate-btn:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--success) 35%, transparent);
|
||||
}
|
||||
|
||||
/* ── Advanced popover fields ───────────────────────────── */
|
||||
.adv-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.adv-label {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.adv-input {
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 8px 10px;
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
font-family: var(--font-mono);
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.adv-input:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,480 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
|
||||
import { assetUrl, projects, type Project } from '$lib/api';
|
||||
import { toast } from '$lib/toast';
|
||||
import Button from '$lib/components/ui/Button.svelte';
|
||||
import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import Modal from '$lib/components/ui/Modal.svelte';
|
||||
import StatusChip from '$lib/components/ui/StatusChip.svelte';
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
}
|
||||
|
||||
const { project }: Props = $props();
|
||||
|
||||
const client = useQueryClient();
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
draft: 'Draft',
|
||||
in_progress: 'In Progress',
|
||||
completed: 'Ready',
|
||||
};
|
||||
|
||||
const stats = $derived(
|
||||
project.stats ?? {
|
||||
scene_count: 0,
|
||||
character_count: 0,
|
||||
asset_ready_count: 0,
|
||||
asset_total_count: 0,
|
||||
},
|
||||
);
|
||||
|
||||
// Explicit project cover wins; otherwise fall back to the first asset image.
|
||||
// The project prop is stable for the lifetime of a card, so the eager
|
||||
// queryKey capture below is intentional.
|
||||
// svelte-ignore state_referenced_locally
|
||||
const assetsQuery = createQuery({
|
||||
queryKey: ['assets', project.id],
|
||||
queryFn: () => projects.getAssets(project.id),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const thumbUrl = $derived.by(() => {
|
||||
if (project.cover_path) return assetUrl(project.cover_path);
|
||||
const data = $assetsQuery.data;
|
||||
if (!data) return null;
|
||||
const char = data.characters.find((c) => c.portrait_path || c.sheet_path);
|
||||
const path =
|
||||
char?.portrait_path ??
|
||||
char?.sheet_path ??
|
||||
data.locations.find((l) => l.reference_image_path)?.reference_image_path ??
|
||||
null;
|
||||
return assetUrl(path);
|
||||
});
|
||||
|
||||
// A broken cover (deleted file, 404) falls back to the gradient tile.
|
||||
let thumbFailedFor = $state<string | null>(null);
|
||||
|
||||
function relativeTime(iso: string): string {
|
||||
const then = new Date(iso).getTime();
|
||||
if (Number.isNaN(then)) return '';
|
||||
const mins = Math.max(0, Math.round((Date.now() - then) / 60000));
|
||||
if (mins < 1) return 'just now';
|
||||
if (mins < 60) return `${mins}m ago`;
|
||||
const hours = Math.round(mins / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
const days = Math.round(hours / 24);
|
||||
if (days < 30) return `${days}d ago`;
|
||||
const months = Math.round(days / 30);
|
||||
if (months < 12) return `${months}mo ago`;
|
||||
return `${Math.round(months / 12)}y ago`;
|
||||
}
|
||||
|
||||
const updatedLabel = $derived(relativeTime(project.updated_at));
|
||||
const updatedTitle = $derived(new Date(project.updated_at).toLocaleString());
|
||||
|
||||
// Overflow menu (⋯) — closes on outside click, focus leaving, or Esc.
|
||||
let menuOpen = $state(false);
|
||||
let menuEl = $state<HTMLDivElement | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
if (!menuOpen) return;
|
||||
const onDocClick = (e: MouseEvent) => {
|
||||
if (menuEl && !menuEl.contains(e.target as Node)) menuOpen = false;
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') menuOpen = false;
|
||||
};
|
||||
const onFocusIn = (e: FocusEvent) => {
|
||||
if (menuEl && !menuEl.contains(e.target as Node)) menuOpen = false;
|
||||
};
|
||||
window.addEventListener('click', onDocClick);
|
||||
window.addEventListener('keydown', onKey);
|
||||
document.addEventListener('focusin', onFocusIn);
|
||||
return () => {
|
||||
window.removeEventListener('click', onDocClick);
|
||||
window.removeEventListener('keydown', onKey);
|
||||
document.removeEventListener('focusin', onFocusIn);
|
||||
};
|
||||
});
|
||||
|
||||
let renameOpen = $state(false);
|
||||
let renameValue = $state('');
|
||||
|
||||
const renameMutation = createMutation({
|
||||
mutationFn: (title: string) => projects.update(project.id, { title }),
|
||||
onSuccess: (updated) => {
|
||||
client.invalidateQueries({ queryKey: ['projects'] });
|
||||
toast.success(`Renamed to “${updated.title}”`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not rename project');
|
||||
},
|
||||
});
|
||||
|
||||
function openRename() {
|
||||
menuOpen = false;
|
||||
renameValue = project.title;
|
||||
renameOpen = true;
|
||||
}
|
||||
|
||||
function submitRename() {
|
||||
const title = renameValue.trim();
|
||||
renameOpen = false;
|
||||
if (!title || title === project.title) return;
|
||||
$renameMutation.mutate(title);
|
||||
}
|
||||
|
||||
let deleteOpen = $state(false);
|
||||
|
||||
const deleteMutation = createMutation({
|
||||
mutationFn: () => projects.delete(project.id),
|
||||
onSuccess: () => {
|
||||
client.invalidateQueries({ queryKey: ['projects'] });
|
||||
toast.success(`Deleted “${project.title}”`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not delete project');
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<article class="project-card">
|
||||
<button
|
||||
type="button"
|
||||
class="card-main"
|
||||
aria-label="Open project {project.title}"
|
||||
onclick={() => goto(`/project/${project.id}`)}
|
||||
>
|
||||
<div class="card-thumb">
|
||||
{#if thumbUrl && thumbFailedFor !== thumbUrl}
|
||||
<img
|
||||
class="thumb-img"
|
||||
src={thumbUrl}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
onerror={() => (thumbFailedFor = thumbUrl)}
|
||||
/>
|
||||
{:else}
|
||||
<div class="card-thumb-icon"><Icon name="video" size={26} /></div>
|
||||
{/if}
|
||||
<div class="card-status">
|
||||
<StatusChip status={project.status} label={STATUS_LABEL[project.status]} />
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title">
|
||||
{project.title}
|
||||
<span class="open-arrow">→</span>
|
||||
</div>
|
||||
<p class="card-desc">{project.idea || 'No story idea yet.'}</p>
|
||||
<div class="card-meta">
|
||||
<div class="card-stats">
|
||||
<span class="card-stat">
|
||||
<Icon name="script" size={13} />
|
||||
{stats.scene_count} scenes
|
||||
</span>
|
||||
<span class="card-stat">
|
||||
<Icon name="assets" size={13} />
|
||||
{stats.character_count} characters
|
||||
</span>
|
||||
<span class="card-stat">
|
||||
<Icon name="image" size={13} />
|
||||
{stats.asset_ready_count}/{stats.asset_total_count} assets
|
||||
</span>
|
||||
</div>
|
||||
<span title={updatedTitle}>{updatedLabel}</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div class="menu-wrap" bind:this={menuEl}>
|
||||
<button
|
||||
type="button"
|
||||
class="menu-btn"
|
||||
aria-label="Actions for {project.title}"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={menuOpen}
|
||||
onclick={() => (menuOpen = !menuOpen)}
|
||||
>
|
||||
⋯
|
||||
</button>
|
||||
{#if menuOpen}
|
||||
<div class="menu" role="menu" aria-label="Project actions">
|
||||
<button type="button" role="menuitem" class="menu-item" onclick={openRename}>
|
||||
<Icon name="edit" size={14} />
|
||||
Rename
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
class="menu-item"
|
||||
onclick={() => {
|
||||
menuOpen = false;
|
||||
goto(`/project/${project.id}?stage=assets`);
|
||||
}}
|
||||
>
|
||||
<Icon name="image" size={14} />
|
||||
Change cover…
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
class="menu-item danger"
|
||||
onclick={() => {
|
||||
menuOpen = false;
|
||||
deleteOpen = true;
|
||||
}}
|
||||
>
|
||||
<Icon name="trash" size={14} />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<Modal bind:open={renameOpen} title="Rename project">
|
||||
<form
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submitRename();
|
||||
}}
|
||||
>
|
||||
<label class="field">
|
||||
<span class="field-label">Title</span>
|
||||
<input class="field-input" bind:value={renameValue} required />
|
||||
</label>
|
||||
</form>
|
||||
{#snippet footer()}
|
||||
<Button variant="ghost" onclick={() => (renameOpen = false)}>Cancel</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={!renameValue.trim() || $renameMutation.isPending}
|
||||
onclick={submitRename}
|
||||
>
|
||||
Rename
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:open={deleteOpen}
|
||||
title="Delete project?"
|
||||
message="This deletes “{project.title}” and its story data. Generated asset files stay on disk. This cannot be undone."
|
||||
confirmLabel="Delete"
|
||||
danger
|
||||
onconfirm={() => $deleteMutation.mutate()}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.project-card {
|
||||
position: relative;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
overflow: hidden;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.project-card:hover {
|
||||
border-color: var(--accent);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
.project-card:hover .open-arrow {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
.card-main {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.card-main:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.card-thumb {
|
||||
height: 170px;
|
||||
background: linear-gradient(135deg, var(--bg-elevated) 0%, #1a1625 100%);
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
.card-thumb::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
radial-gradient(circle at 20% 30%, rgba(139, 92, 246, 0.12) 0%, transparent 40%),
|
||||
radial-gradient(circle at 80% 70%, rgba(59, 130, 246, 0.08) 0%, transparent 40%);
|
||||
}
|
||||
.thumb-img {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.card-thumb-icon {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: var(--radius-md);
|
||||
background: rgba(139, 92, 246, 0.12);
|
||||
border: 1px solid rgba(139, 92, 246, 0.2);
|
||||
color: var(--accent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
.card-status {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
z-index: 2;
|
||||
filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.6));
|
||||
}
|
||||
.card-body {
|
||||
padding: var(--space-md);
|
||||
}
|
||||
.card-title {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 var(--space-xs);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
.open-arrow {
|
||||
color: var(--accent);
|
||||
opacity: 0;
|
||||
transform: translateX(-8px);
|
||||
transition: all 0.2s;
|
||||
font-size: 14px;
|
||||
}
|
||||
.card-desc {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
margin: 0 0 var(--space-md);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.card-meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.card-stats {
|
||||
display: flex;
|
||||
gap: var(--space-md);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.card-stat {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.menu-wrap {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
z-index: 3;
|
||||
}
|
||||
.menu-btn {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-sm);
|
||||
background: rgba(10, 10, 12, 0.55);
|
||||
color: var(--text-secondary);
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.project-card:hover .menu-btn,
|
||||
.menu-btn:focus-visible,
|
||||
.menu-btn[aria-expanded='true'] {
|
||||
opacity: 1;
|
||||
}
|
||||
.menu-btn:hover {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border);
|
||||
}
|
||||
.menu-btn:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.menu {
|
||||
position: absolute;
|
||||
top: 34px;
|
||||
left: 0;
|
||||
min-width: 140px;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45);
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
.menu-item:hover {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.menu-item.danger {
|
||||
color: var(--error);
|
||||
}
|
||||
.menu-item.danger:hover {
|
||||
background: rgba(239, 68, 68, 0.12);
|
||||
}
|
||||
.menu-item:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.project-card:hover {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,916 @@
|
||||
<script lang="ts">
|
||||
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
|
||||
import { toStore } from 'svelte/store';
|
||||
import { toast } from '$lib/toast';
|
||||
import { assetUrl, jobsApi, projects, workflows, type Job, type Scene, type Workflow } from '$lib/api';
|
||||
import { compactInputValues } from '$lib/comfy/promptInput';
|
||||
import { progressFor } from '$lib/jobProgress';
|
||||
import SafeMedia from './SafeMedia.svelte';
|
||||
import VideoEditWorkspace from './video/VideoEditWorkspace.svelte';
|
||||
import Button from './ui/Button.svelte';
|
||||
import Icon from './ui/Icon.svelte';
|
||||
import ProgressBar from './ui/ProgressBar.svelte';
|
||||
import Spinner from './ui/Spinner.svelte';
|
||||
import StatusChip from './ui/StatusChip.svelte';
|
||||
|
||||
interface Props {
|
||||
projectId: number;
|
||||
projectTitle?: string;
|
||||
}
|
||||
|
||||
let { projectId, projectTitle = 'film' }: Props = $props();
|
||||
const client = useQueryClient();
|
||||
|
||||
let view = $state<'edit' | 'film'>('edit');
|
||||
let selectedId = $state<number | null>(null);
|
||||
let formValues = $state<Record<string, string | number>>({});
|
||||
let selectedWorkflow = $state<Record<number, number>>({});
|
||||
let lastFormScene = $state<number | null>(null);
|
||||
|
||||
// Per-scene input cache — switching scenes no longer wipes the form.
|
||||
const formCache = new Map<number, Record<string, string | number>>();
|
||||
|
||||
const scenesQuery = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ['scenes', projectId],
|
||||
queryFn: () => projects.getScenes(projectId),
|
||||
})),
|
||||
);
|
||||
const assetsQuery = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ['assets', projectId],
|
||||
queryFn: () => projects.getAssets(projectId),
|
||||
})),
|
||||
);
|
||||
const workflowsQuery = createQuery({
|
||||
queryKey: ['workflows'],
|
||||
queryFn: workflows.list,
|
||||
});
|
||||
const jobsQuery = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ['jobs', projectId],
|
||||
queryFn: () => jobsApi.list(projectId),
|
||||
refetchInterval: 5000,
|
||||
})),
|
||||
);
|
||||
const queueStatusQuery = createQuery({
|
||||
queryKey: ['queue-status'],
|
||||
queryFn: jobsApi.queueStatus,
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
|
||||
const scenes = $derived(($scenesQuery.data?.scenes ?? []) as Scene[]);
|
||||
const totalSec = $derived(
|
||||
scenes.reduce((sum, s) => sum + Math.max(s.duration_sec || 5, 1), 0),
|
||||
);
|
||||
|
||||
const assetOptions = $derived.by(() => {
|
||||
const chars = $assetsQuery.data?.characters ?? [];
|
||||
const locs = $assetsQuery.data?.locations ?? [];
|
||||
const opts: Array<{ label: string; path: string }> = [];
|
||||
for (const c of chars) {
|
||||
if (c.sheet_path) opts.push({ label: `${c.name} · sheet`, path: c.sheet_path });
|
||||
}
|
||||
for (const loc of locs) {
|
||||
if (loc.reference_image_path) {
|
||||
opts.push({ label: `${loc.name} · environment`, path: loc.reference_image_path });
|
||||
}
|
||||
}
|
||||
return opts;
|
||||
});
|
||||
|
||||
const videoWorkflows = $derived(
|
||||
(($workflowsQuery.data ?? []) as Workflow[]).filter((w) => w.is_enabled && w.kind === 'video'),
|
||||
);
|
||||
const enabledWorkflows = $derived(
|
||||
videoWorkflows.length > 0
|
||||
? videoWorkflows
|
||||
: (($workflowsQuery.data ?? []) as Workflow[]).filter((w) => w.is_enabled),
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (selectedId != null) return;
|
||||
if (scenes.length > 0) selectedId = scenes[0].id;
|
||||
});
|
||||
|
||||
const selected = $derived(scenes.find((s) => s.id === selectedId) ?? null);
|
||||
|
||||
$effect(() => {
|
||||
const id = selected?.id ?? null;
|
||||
if (id === lastFormScene) return;
|
||||
if (lastFormScene != null) formCache.set(lastFormScene, formValues);
|
||||
lastFormScene = id;
|
||||
formValues = id != null ? { ...(formCache.get(id) ?? seedSceneDefaults(selected)) } : {};
|
||||
});
|
||||
|
||||
// Context-aware defaults for a freshly opened scene form (user edits and the
|
||||
// workflow's static defaults must not override these). Duration-role inputs
|
||||
// seed from the scene's estimated duration; ComfyDynamicForm's own prefill
|
||||
// only applies to fields still undefined afterwards.
|
||||
function seedSceneDefaults(scene: Scene | null): Record<string, string | number> {
|
||||
const seed: Record<string, string | number> = {};
|
||||
if (!scene) return seed;
|
||||
const wf = workflowFor(scene);
|
||||
for (const inp of wf?.input_schema ?? []) {
|
||||
if (inp.role === 'duration' && scene.duration_sec != null) {
|
||||
seed[inp.nodeId] = scene.duration_sec;
|
||||
}
|
||||
}
|
||||
return seed;
|
||||
}
|
||||
|
||||
const generateOne = createMutation({
|
||||
mutationFn: (sceneId: number) => {
|
||||
const wf = selected ? workflowFor(selected) : undefined;
|
||||
return jobsApi.generateVideos(projectId, {
|
||||
scene_ids: [sceneId],
|
||||
workflow_id: selectedWorkflow[sceneId] ?? wf?.id,
|
||||
input_values: compactInputValues(formValues),
|
||||
});
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await client.invalidateQueries({ queryKey: ['jobs'] });
|
||||
await client.invalidateQueries({ queryKey: ['scenes'] });
|
||||
toast.success('Clip queued');
|
||||
},
|
||||
onError: (err) => toast.error(err instanceof Error ? err.message : String(err)),
|
||||
});
|
||||
|
||||
function workflowFor(scene: Scene): Workflow | undefined {
|
||||
const id = selectedWorkflow[scene.id] ?? scene.workflow_id ?? undefined;
|
||||
return enabledWorkflows.find((w) => w.id === id) ?? enabledWorkflows[0] ?? undefined;
|
||||
}
|
||||
|
||||
function jobForScene(sceneId: number): Job | undefined {
|
||||
const jobs = ($jobsQuery.data ?? []).filter((j) => j.scene_id === sceneId && j.kind === 'video');
|
||||
if (jobs.length === 0) return undefined;
|
||||
return [...jobs].sort((a, b) => b.id - a.id)[0];
|
||||
}
|
||||
|
||||
function statusOf(scene: Scene): string {
|
||||
const job = jobForScene(scene.id);
|
||||
if (job) return job.status;
|
||||
if (scene.video_path) return 'done';
|
||||
return 'idle';
|
||||
}
|
||||
|
||||
function previewPath(scene: Scene): string | null {
|
||||
const job = jobForScene(scene.id);
|
||||
// While a new job is queued/running, don't keep showing the previous clip
|
||||
if (job && (job.status === 'pending' || job.status === 'running')) return null;
|
||||
if (job?.status === 'done') {
|
||||
const fromJob = (job.output_paths ?? []).find((p) => /\.(mp4|webm)$/i.test(p));
|
||||
if (fromJob) return fromJob;
|
||||
}
|
||||
if (scene.video_path && /\.(mp4|webm)$/i.test(scene.video_path)) return scene.video_path;
|
||||
return null;
|
||||
}
|
||||
|
||||
type Thumb = { kind: 'image' | 'video'; src: string };
|
||||
|
||||
function thumbFor(scene: Scene): Thumb | null {
|
||||
if (scene.env_image_path) {
|
||||
const src = assetUrl(scene.env_image_path);
|
||||
if (src) return { kind: 'image', src };
|
||||
}
|
||||
const preview = previewPath(scene);
|
||||
if (preview) {
|
||||
const src = assetUrl(preview);
|
||||
if (src) return { kind: 'video', src };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatClock(sec: number): string {
|
||||
const s = Math.max(0, Math.round(sec));
|
||||
const m = Math.floor(s / 60);
|
||||
const r = s % 60;
|
||||
return `${m}:${r.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// Same compact "3m ago" style as ProjectCard — local copy keeps this stage self-contained.
|
||||
function relativeTime(iso: string): string {
|
||||
const then = new Date(iso).getTime();
|
||||
if (Number.isNaN(then)) return '';
|
||||
const mins = Math.max(0, Math.round((Date.now() - then) / 60000));
|
||||
if (mins < 1) return 'just now';
|
||||
if (mins < 60) return `${mins}m ago`;
|
||||
const hours = Math.round(mins / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
const days = Math.round(hours / 24);
|
||||
if (days < 30) return `${days}d ago`;
|
||||
const months = Math.round(days / 30);
|
||||
if (months < 12) return `${months}mo ago`;
|
||||
return `${Math.round(months / 12)}y ago`;
|
||||
}
|
||||
|
||||
const doneCount = $derived(scenes.filter((s) => statusOf(s) === 'done').length);
|
||||
|
||||
async function togglePause() {
|
||||
if ($queueStatusQuery.data?.paused) await jobsApi.resume();
|
||||
else await jobsApi.pause();
|
||||
client.invalidateQueries({ queryKey: ['queue-status'] });
|
||||
}
|
||||
|
||||
async function resumeQueue() {
|
||||
await jobsApi.resume();
|
||||
client.invalidateQueries({ queryKey: ['queue-status'] });
|
||||
}
|
||||
|
||||
function selectScene(id: number) {
|
||||
selectedId = id;
|
||||
}
|
||||
|
||||
// Filmstrip click → jump back to the editor with that scene selected.
|
||||
function editScene(id: number) {
|
||||
selectedId = id;
|
||||
view = 'edit';
|
||||
}
|
||||
|
||||
function neighborId(dir: -1 | 1): number | null {
|
||||
const idx = scenes.findIndex((s) => s.id === selectedId);
|
||||
const next = scenes[(idx < 0 ? 0 : idx) + dir];
|
||||
return next?.id ?? null;
|
||||
}
|
||||
|
||||
function step(dir: -1 | 1) {
|
||||
const id = neighborId(dir);
|
||||
if (id != null) selectedId = id;
|
||||
}
|
||||
|
||||
const selJob = $derived(selected ? jobForScene(selected.id) : undefined);
|
||||
const selProg = $derived(selJob ? progressFor(selJob.id) : undefined);
|
||||
const selError = $derived(selJob?.error ?? '');
|
||||
const selErrorLong = $derived(selError.length > 140 || selError.split('\n').length > 3);
|
||||
|
||||
// --- Export film (latest export job drives the Film view; no extra polling) ---
|
||||
const exportJob = $derived(
|
||||
($jobsQuery.data ?? [])
|
||||
.filter((j) => j.kind === 'export')
|
||||
.sort((a, b) => b.id - a.id)[0] ?? null,
|
||||
);
|
||||
const exportActive = $derived(
|
||||
exportJob?.status === 'pending' || exportJob?.status === 'running',
|
||||
);
|
||||
const exportProg = $derived(exportActive && exportJob ? progressFor(exportJob.id) : undefined);
|
||||
const exportPath = $derived(
|
||||
exportJob?.status === 'done'
|
||||
? ((exportJob.output_paths ?? []).find((p) => /\.mp4$/i.test(p)) ?? null)
|
||||
: null,
|
||||
);
|
||||
// A clip finished after the export completed → the film no longer matches the timeline.
|
||||
const exportStale = $derived.by(() => {
|
||||
if (exportJob?.status !== 'done' || !exportJob.completed_at) return false;
|
||||
const exportAt = Date.parse(exportJob.completed_at);
|
||||
if (Number.isNaN(exportAt)) return false;
|
||||
return ($jobsQuery.data ?? []).some(
|
||||
(j) =>
|
||||
j.kind === 'video' &&
|
||||
j.status === 'done' &&
|
||||
j.completed_at != null &&
|
||||
Date.parse(j.completed_at) > exportAt,
|
||||
);
|
||||
});
|
||||
const clipsReady = $derived(scenes.filter((s) => Boolean(s.video_path)).length);
|
||||
const clipsMissing = $derived(scenes.length - clipsReady);
|
||||
|
||||
type ExportState = 'idle' | 'active' | 'ready' | 'failed';
|
||||
const exportState = $derived.by((): ExportState => {
|
||||
if (!exportJob) return 'idle';
|
||||
if (exportActive) return 'active';
|
||||
if (exportJob.status === 'done') return 'ready';
|
||||
if (exportJob.status === 'failed') return 'failed';
|
||||
return 'idle';
|
||||
});
|
||||
|
||||
// Clip count recorded on the export job payload when the backend provides it;
|
||||
// otherwise fall back to the clips currently on the timeline.
|
||||
const exportClipCount = $derived.by(() => {
|
||||
const p = exportJob?.payload;
|
||||
const n = p?.clips ?? p?.clip_count;
|
||||
return typeof n === 'number' && Number.isFinite(n) && n > 0 ? n : clipsReady;
|
||||
});
|
||||
const exportedAgo = $derived(
|
||||
exportJob?.completed_at ? relativeTime(exportJob.completed_at) : '',
|
||||
);
|
||||
|
||||
const filmChip = $derived.by((): { status: string; label: string } => {
|
||||
if (exportState === 'active') return { status: 'running', label: 'Exporting' };
|
||||
if (exportState === 'ready') {
|
||||
return exportStale
|
||||
? { status: 'paused', label: 'Clips changed' }
|
||||
: { status: 'ready', label: 'Ready' };
|
||||
}
|
||||
if (exportState === 'failed') return { status: 'failed', label: 'Export failed' };
|
||||
return { status: 'idle', label: 'Not exported' };
|
||||
});
|
||||
|
||||
// Small status dot on the Film tab; the Film view itself carries the full text state.
|
||||
const filmDot = $derived.by((): 'success' | 'info' | 'warning' | null => {
|
||||
if (exportState === 'active') return 'info';
|
||||
if (exportState === 'ready') return exportStale ? 'warning' : 'success';
|
||||
return null;
|
||||
});
|
||||
|
||||
const exportFilm = createMutation({
|
||||
mutationFn: () => jobsApi.exportFilm(projectId),
|
||||
onSuccess: async () => {
|
||||
await client.invalidateQueries({ queryKey: ['jobs'] });
|
||||
toast.success('Export queued');
|
||||
},
|
||||
onError: (err) => toast.error(err instanceof Error ? err.message : String(err)),
|
||||
});
|
||||
|
||||
async function cancelExport() {
|
||||
if (!exportJob) return;
|
||||
try {
|
||||
await jobsApi.cancel(exportJob.id);
|
||||
await client.invalidateQueries({ queryKey: ['jobs'] });
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="queue-root" class:is-edit={view === 'edit'}>
|
||||
<header class="stage-header">
|
||||
<div>
|
||||
<h2>4. Video</h2>
|
||||
<p class="muted">
|
||||
{#if scenes.length === 0}
|
||||
Build a script first, then cut clips on the timeline.
|
||||
{:else}
|
||||
{doneCount}/{scenes.length} clips done · {formatClock(totalSec)} total
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<Button variant="secondary" onclick={togglePause}>
|
||||
{$queueStatusQuery.data?.paused ? 'Resume queue' : 'Pause queue'}
|
||||
</Button>
|
||||
<div class="view-toggle" role="tablist" aria-label="Video stage view">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={view === 'edit'}
|
||||
class="view-tab"
|
||||
class:active={view === 'edit'}
|
||||
onclick={() => (view = 'edit')}
|
||||
>
|
||||
<Icon name="edit" size={14} /> Edit
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={view === 'film'}
|
||||
class="view-tab"
|
||||
class:active={view === 'film'}
|
||||
onclick={() => (view = 'film')}
|
||||
>
|
||||
<Icon name="film" size={14} /> Film
|
||||
{#if filmDot}
|
||||
<span class="film-dot dot-{filmDot}" aria-hidden="true"></span>
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{#if view === 'edit'}
|
||||
{#if $queueStatusQuery.data?.paused}
|
||||
<div class="paused-banner" role="status">
|
||||
<Icon name="alert" size={16} />
|
||||
<StatusChip status="paused" label="Queue paused" />
|
||||
<span class="paused-text">Renders are held — workers sit idle until you resume.</span>
|
||||
<span class="paused-action">
|
||||
<Button size="sm" variant="secondary" onclick={resumeQueue}>Resume now</Button>
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if scenes.length === 0}
|
||||
<div class="empty">
|
||||
<p class="empty-title">No timeline yet</p>
|
||||
<p class="muted">Generate or add scenes in Script, then come back to render clips.</p>
|
||||
</div>
|
||||
{:else if selected}
|
||||
{@const selWf = workflowFor(selected)}
|
||||
{@const selStatus = statusOf(selected)}
|
||||
{@const selPreview = previewPath(selected)}
|
||||
<VideoEditWorkspace
|
||||
{scenes}
|
||||
{selected}
|
||||
{selectedId}
|
||||
status={selStatus}
|
||||
previewPath={selPreview}
|
||||
progress={selProg}
|
||||
error={selError}
|
||||
errorLong={selErrorLong}
|
||||
workflow={selWf}
|
||||
workflows={enabledWorkflows}
|
||||
bind:formValues
|
||||
{assetOptions}
|
||||
submitting={$generateOne.isPending}
|
||||
{statusOf}
|
||||
{thumbFor}
|
||||
{formatClock}
|
||||
onSelect={selectScene}
|
||||
onStep={step}
|
||||
onWorkflowChange={(id) => {
|
||||
selectedWorkflow = { ...selectedWorkflow, [selected.id]: Number(id) };
|
||||
}}
|
||||
onGenerate={() => $generateOne.mutate(selected.id)}
|
||||
/>
|
||||
{/if}
|
||||
{:else}
|
||||
<section class="film-view" aria-label="Film screening room">
|
||||
<div class="marquee">
|
||||
<span class="marquee-icon" aria-hidden="true"><Icon name="film" size={20} /></span>
|
||||
<h2 class="marquee-title">{projectTitle}</h2>
|
||||
<span class="marquee-chip">
|
||||
<StatusChip status={filmChip.status} label={filmChip.label} />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="program-frame">
|
||||
{#if exportState === 'ready'}
|
||||
<SafeMedia
|
||||
class="program-media"
|
||||
src={assetUrl(exportPath)}
|
||||
kind="video"
|
||||
label="Export unavailable"
|
||||
/>
|
||||
{#if exportStale}
|
||||
<div class="stale-banner" role="status">
|
||||
<Icon name="alert" size={14} />
|
||||
<span>Clips changed since this export — re-export to update.</span>
|
||||
</div>
|
||||
{/if}
|
||||
{:else if exportState === 'active'}
|
||||
<div class="program-slate">
|
||||
<Spinner size="lg" />
|
||||
<h3 class="slate-title">Exporting your film…</h3>
|
||||
<div class="slate-progress">
|
||||
<ProgressBar
|
||||
value={exportProg?.progress ?? 0}
|
||||
indeterminate={exportProg == null}
|
||||
label={exportProg?.message}
|
||||
/>
|
||||
</div>
|
||||
<p class="slate-sub">You can keep editing — export runs in the background.</p>
|
||||
<Button variant="ghost" size="sm" onclick={cancelExport}>Cancel</Button>
|
||||
</div>
|
||||
{:else if exportState === 'failed'}
|
||||
<div class="program-slate">
|
||||
<span class="slate-icon slate-icon-err" aria-hidden="true">
|
||||
<Icon name="alert" size={32} />
|
||||
</span>
|
||||
<h3 class="slate-title">Export failed</h3>
|
||||
<p class="slate-err" title={exportJob?.error ?? 'Export failed'}>
|
||||
{exportJob?.error || 'Export failed'}
|
||||
</p>
|
||||
<Button
|
||||
variant="secondary"
|
||||
loading={$exportFilm.isPending}
|
||||
onclick={() => $exportFilm.mutate()}
|
||||
>
|
||||
Retry export
|
||||
</Button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="program-slate">
|
||||
<span class="slate-icon" aria-hidden="true">
|
||||
<Icon name="film" size={32} />
|
||||
</span>
|
||||
<h3 class="slate-title">Your film isn't exported yet</h3>
|
||||
<p class="slate-sub">
|
||||
{clipsReady} clips · {formatClock(totalSec)} · 0.5s crossfades · loudness matched
|
||||
</p>
|
||||
{#if clipsMissing > 0}
|
||||
<p class="slate-warn" role="status">
|
||||
<Icon name="alert" size={14} />
|
||||
<span>
|
||||
{clipsMissing} scene{clipsMissing === 1 ? '' : 's'} without a clip will be skipped
|
||||
</span>
|
||||
</p>
|
||||
{/if}
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={clipsReady === 0}
|
||||
loading={$exportFilm.isPending}
|
||||
title={clipsReady === 0 ? 'Finish at least one clip to export a film' : 'Export film'}
|
||||
onclick={() => $exportFilm.mutate()}
|
||||
>
|
||||
<Icon name="film" size={14} /> Export film
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if exportState === 'ready'}
|
||||
{@const exportUrl = assetUrl(exportPath)}
|
||||
<div class="film-meta">
|
||||
<span class="film-meta-text">
|
||||
{exportClipCount} clips · {formatClock(totalSec)}{#if exportedAgo} · Exported {exportedAgo}{/if}
|
||||
</span>
|
||||
<div class="film-actions">
|
||||
{#if exportUrl}
|
||||
<a class="btn-dl" href={exportUrl} download={`${projectTitle}.mp4`}>
|
||||
<Icon name="download" size={14} /> Download film
|
||||
</a>
|
||||
{/if}
|
||||
<Button
|
||||
variant={exportStale ? 'primary' : 'ghost'}
|
||||
size="sm"
|
||||
loading={$exportFilm.isPending}
|
||||
onclick={() => $exportFilm.mutate()}
|
||||
>
|
||||
Re-export
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if scenes.length > 0}
|
||||
<div class="filmstrip-block">
|
||||
<p class="filmstrip-label">In this film</p>
|
||||
<div class="filmstrip">
|
||||
{#each scenes as scene (scene.id)}
|
||||
{@const thumb = thumbFor(scene)}
|
||||
<button
|
||||
type="button"
|
||||
class="filmstrip-item"
|
||||
title={`${scene.heading || 'Scene'} — edit in timeline`}
|
||||
onclick={() => editScene(scene.id)}
|
||||
>
|
||||
{#if thumb?.kind === 'image'}
|
||||
<img class="filmstrip-media" src={thumb.src} alt="" loading="lazy" />
|
||||
{:else if thumb?.kind === 'video'}
|
||||
<!-- svelte-ignore a11y_media_has_caption -->
|
||||
<video class="filmstrip-media" src={thumb.src} muted playsinline preload="metadata"></video>
|
||||
{:else}
|
||||
<span class="filmstrip-slate">#{scene.order_index}</span>
|
||||
{/if}
|
||||
<span class="filmstrip-num">#{scene.order_index}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.queue-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
gap: 10px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.queue-root.is-edit {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.stage-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-md);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.stage-header h2 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.muted {
|
||||
color: var(--text-secondary);
|
||||
margin: 0;
|
||||
}
|
||||
.small {
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.view-toggle {
|
||||
display: inline-flex;
|
||||
padding: 3px;
|
||||
gap: 2px;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 9999px;
|
||||
}
|
||||
.view-tab {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 30px;
|
||||
padding: 0 12px;
|
||||
border: none;
|
||||
border-radius: 9999px;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
font-family: var(--font-body);
|
||||
cursor: pointer;
|
||||
}
|
||||
.view-tab:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.view-tab.active {
|
||||
background: var(--bg-surface);
|
||||
color: var(--text-primary);
|
||||
box-shadow: 0 0 0 1px var(--accent);
|
||||
}
|
||||
.film-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
.film-dot.dot-success {
|
||||
background: var(--success);
|
||||
}
|
||||
.film-dot.dot-info {
|
||||
background: var(--warning);
|
||||
}
|
||||
.film-dot.dot-warning {
|
||||
background: var(--warning);
|
||||
}
|
||||
|
||||
.paused-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid color-mix(in srgb, var(--warning) 40%, var(--border));
|
||||
background: color-mix(in srgb, var(--warning) 10%, var(--bg-surface));
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.paused-text {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.paused-action {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 48px 24px;
|
||||
text-align: center;
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--bg-surface);
|
||||
margin: auto 0;
|
||||
}
|
||||
.empty-title {
|
||||
margin: 0 0 8px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
|
||||
/* --- Film view (screening room) --- */
|
||||
.film-view {
|
||||
max-width: 1080px;
|
||||
margin: 0 auto;
|
||||
padding: var(--space-lg) var(--space-md) var(--space-xl);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
.marquee {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.marquee-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: var(--accent);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.marquee-title {
|
||||
margin: 0;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.marquee-chip {
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.program-frame {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
background: #000;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
overflow: hidden;
|
||||
}
|
||||
.program-frame :global(.program-media) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
background: #000;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.stale-banner {
|
||||
position: absolute;
|
||||
inset: 0 0 auto 0;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
background: rgba(245, 158, 11, 0.12);
|
||||
border-bottom: 1px solid rgba(245, 158, 11, 0.35);
|
||||
color: var(--warning);
|
||||
font-size: 13px;
|
||||
}
|
||||
.program-slate {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: var(--space-lg);
|
||||
text-align: center;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.slate-icon {
|
||||
display: flex;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.slate-icon-err {
|
||||
color: var(--error);
|
||||
}
|
||||
.slate-title {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.slate-sub {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.slate-progress {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
}
|
||||
.slate-warn {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--warning);
|
||||
}
|
||||
.slate-err {
|
||||
margin: 0;
|
||||
max-width: 60ch;
|
||||
font-size: 13px;
|
||||
color: var(--error);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.film-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
.film-meta-text {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.film-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.btn-dl {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 28px;
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
white-space: nowrap;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-primary);
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color 150ms ease,
|
||||
border-color 150ms ease;
|
||||
}
|
||||
.btn-dl:hover {
|
||||
background: #23232b;
|
||||
border-color: #3f3f46;
|
||||
}
|
||||
.btn-dl:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.filmstrip-block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.filmstrip-label {
|
||||
margin: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.filmstrip {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
.filmstrip-item {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 104px;
|
||||
height: 64px;
|
||||
padding: 0;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-elevated);
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
transition: border-color 150ms ease;
|
||||
}
|
||||
.filmstrip-item:hover {
|
||||
border-color: #52525b;
|
||||
}
|
||||
.filmstrip-item:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.filmstrip-media {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
pointer-events: none;
|
||||
}
|
||||
.filmstrip-slate {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.filmstrip-num {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
padding: 1px 5px;
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,108 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
src: string | null | undefined;
|
||||
alt?: string;
|
||||
kind?: 'image' | 'video';
|
||||
label?: string;
|
||||
class?: string;
|
||||
loading?: 'lazy' | 'eager';
|
||||
controls?: boolean;
|
||||
preload?: 'none' | 'metadata' | 'auto';
|
||||
autoplay?: boolean;
|
||||
onUnavailable?: () => void;
|
||||
onAvailable?: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
src = null,
|
||||
alt = '',
|
||||
kind = 'image',
|
||||
label = 'No media',
|
||||
class: klass = '',
|
||||
loading = 'lazy',
|
||||
controls = true,
|
||||
preload = 'metadata',
|
||||
autoplay = false,
|
||||
onUnavailable,
|
||||
onAvailable,
|
||||
}: Props = $props();
|
||||
|
||||
let failed = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
void src;
|
||||
failed = false;
|
||||
if (!src) onUnavailable?.();
|
||||
});
|
||||
|
||||
const usable = $derived(Boolean(src) && !failed);
|
||||
|
||||
function markAvailable() {
|
||||
onAvailable?.();
|
||||
}
|
||||
|
||||
function markFailed() {
|
||||
failed = true;
|
||||
onUnavailable?.();
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if usable && src}
|
||||
{#if kind === 'video'}
|
||||
<!-- svelte-ignore a11y_media_has_caption -->
|
||||
<video
|
||||
class={klass}
|
||||
{src}
|
||||
{controls}
|
||||
{preload}
|
||||
{autoplay}
|
||||
onloadeddata={markAvailable}
|
||||
onerror={markFailed}
|
||||
></video>
|
||||
{:else}
|
||||
<img
|
||||
class={klass}
|
||||
{src}
|
||||
{alt}
|
||||
{loading}
|
||||
onload={markAvailable}
|
||||
onerror={markFailed}
|
||||
/>
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="safe-media-ph {klass}" role="img" aria-label={label}>
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.safe-media-ph {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: 72px;
|
||||
box-sizing: border-box;
|
||||
background:
|
||||
repeating-linear-gradient(
|
||||
-45deg,
|
||||
transparent,
|
||||
transparent 6px,
|
||||
rgba(255, 255, 255, 0.03) 6px,
|
||||
rgba(255, 255, 255, 0.03) 12px
|
||||
),
|
||||
var(--bg-elevated, #16161d);
|
||||
border: 1px dashed var(--border, #2a2a35);
|
||||
border-radius: inherit;
|
||||
color: var(--text-muted, #8b8b9a);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.safe-media-ph span {
|
||||
opacity: 0.9;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,659 @@
|
||||
<script lang="ts">
|
||||
import { tick } from 'svelte';
|
||||
import { toStore } from 'svelte/store';
|
||||
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
|
||||
import { assetUrl, jobsApi, projects, type Job, type Scene } from '$lib/api';
|
||||
import { estimateTargetSeconds } from '$lib/durationBudget';
|
||||
import { toast } from '$lib/toast';
|
||||
import Button from '$lib/components/ui/Button.svelte';
|
||||
import StatusChip from '$lib/components/ui/StatusChip.svelte';
|
||||
import Modal from '$lib/components/ui/Modal.svelte';
|
||||
import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte';
|
||||
import EmptyState from '$lib/components/ui/EmptyState.svelte';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import GeneratingOverlay from '$lib/components/GeneratingOverlay.svelte';
|
||||
|
||||
interface Props {
|
||||
projectId: number;
|
||||
/** Latest agent.thinking message from the project SSE stream. */
|
||||
agentStatus?: string | null;
|
||||
}
|
||||
|
||||
let { projectId, agentStatus = null }: Props = $props();
|
||||
const client = useQueryClient();
|
||||
let editing = $state<Scene | null>(null);
|
||||
let editOpen = $state(false);
|
||||
let highlightId = $state<number | null>(null);
|
||||
let adding = $state(false);
|
||||
let deletingId = $state<number | null>(null);
|
||||
let regenOpen = $state(false);
|
||||
let sceneToDelete = $state<Scene | null>(null);
|
||||
let deleteOpen = $state(false);
|
||||
|
||||
const scenesQuery = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ['scenes', projectId],
|
||||
queryFn: () => projects.getScenes(projectId),
|
||||
})),
|
||||
);
|
||||
|
||||
// Shared cache key with QueueStage — clip job state shows up on scene cards too.
|
||||
const jobsQuery = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ['jobs', projectId],
|
||||
queryFn: () => jobsApi.list(projectId),
|
||||
refetchInterval: 4000,
|
||||
})),
|
||||
);
|
||||
|
||||
// Cache-shared with the parent's story query — only used for the target-length hint.
|
||||
const storyQuery = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ['story', projectId],
|
||||
queryFn: () => projects.getStory(projectId),
|
||||
})),
|
||||
);
|
||||
|
||||
// Cache-shared with AssetsStage — resolves scene location chips.
|
||||
const assetsQuery = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ['assets', projectId],
|
||||
queryFn: () => projects.getAssets(projectId),
|
||||
})),
|
||||
);
|
||||
|
||||
const scenes = $derived($scenesQuery.data?.scenes ?? []);
|
||||
const sceneCount = $derived(scenes.length);
|
||||
const totalSec = $derived($scenesQuery.data?.estimated_duration_sec ?? 0);
|
||||
const targetSec = $derived.by(() => {
|
||||
const target = $storyQuery.data?.project?.target_duration;
|
||||
return target ? estimateTargetSeconds(target) : 0;
|
||||
});
|
||||
|
||||
const generateMutation = createMutation({
|
||||
mutationFn: () => {
|
||||
const n = $scenesQuery.data?.scenes.length ?? 0;
|
||||
return projects.generateScript(projectId, n > 0 ? { scene_count: n } : undefined);
|
||||
},
|
||||
onSuccess: () => {
|
||||
client.invalidateQueries({ queryKey: ['scenes'] });
|
||||
toast.success('Script regenerated');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Script generation failed');
|
||||
},
|
||||
});
|
||||
|
||||
const writing = $derived($generateMutation.isPending);
|
||||
const busy = $derived(writing || adding || deletingId != null);
|
||||
|
||||
const saveMutation = createMutation({
|
||||
mutationFn: () =>
|
||||
projects.updateScene(projectId, editing!.id, {
|
||||
heading: editing!.heading,
|
||||
action: editing!.action,
|
||||
dialog: editing!.dialog,
|
||||
duration_sec: editing!.duration_sec,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
editing = null;
|
||||
editOpen = false;
|
||||
client.invalidateQueries({ queryKey: ['scenes'] });
|
||||
toast.success('Scene saved');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not save scene');
|
||||
},
|
||||
});
|
||||
|
||||
function jobForScene(sceneId: number): Job | undefined {
|
||||
const jobs = ($jobsQuery.data ?? []).filter(
|
||||
(j) => j.scene_id === sceneId && j.kind === 'video',
|
||||
);
|
||||
if (jobs.length === 0) return undefined;
|
||||
return [...jobs].sort((a, b) => b.id - a.id)[0];
|
||||
}
|
||||
|
||||
/** Per-scene production status — only uses fields the API actually exposes. */
|
||||
function sceneStatus(scene: Scene): { status: string; label: string } {
|
||||
const job = jobForScene(scene.id);
|
||||
if (job && (job.status === 'pending' || job.status === 'running')) {
|
||||
return { status: 'generating', label: 'Rendering' };
|
||||
}
|
||||
if (job?.status === 'failed') return { status: 'failed', label: 'Render failed' };
|
||||
if (scene.video_path || job?.status === 'done') {
|
||||
return { status: 'ready', label: 'Clip ready' };
|
||||
}
|
||||
return { status: 'idle', label: 'No clip' };
|
||||
}
|
||||
|
||||
function locationName(scene: Scene): string | null {
|
||||
if (scene.location_id == null) return null;
|
||||
const locs = $assetsQuery.data?.locations ?? [];
|
||||
return locs.find((l) => l.id === scene.location_id)?.name ?? null;
|
||||
}
|
||||
|
||||
function avatarFor(char: { portrait_path: string | null; sheet_path: string | null }) {
|
||||
return assetUrl(char.portrait_path ?? char.sheet_path);
|
||||
}
|
||||
|
||||
function initialsOf(name: string): string {
|
||||
const parts = name.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) return '?';
|
||||
return parts
|
||||
.slice(0, 2)
|
||||
.map((p) => p[0].toUpperCase())
|
||||
.join('');
|
||||
}
|
||||
|
||||
/** Hide a broken avatar image (portrait moved/deleted on disk), revealing initials. */
|
||||
function hideBrokenAvatar(e: Event) {
|
||||
const img = e.currentTarget as HTMLImageElement | null;
|
||||
if (img) img.style.display = 'none';
|
||||
}
|
||||
|
||||
function formatClock(sec: number): string {
|
||||
const s = Math.max(0, Math.round(sec));
|
||||
const m = Math.floor(s / 60);
|
||||
const r = s % 60;
|
||||
return `${m}:${r.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
async function move(sceneId: number, dir: -1 | 1) {
|
||||
if (busy) return;
|
||||
const list = $scenesQuery.data?.scenes ?? [];
|
||||
const idx = list.findIndex((s) => s.id === sceneId);
|
||||
const swap = idx + dir;
|
||||
if (idx < 0 || swap < 0 || swap >= list.length) return;
|
||||
const ids = list.map((s) => s.id);
|
||||
[ids[idx], ids[swap]] = [ids[swap], ids[idx]];
|
||||
await projects.reorderScenes(projectId, ids);
|
||||
client.invalidateQueries({ queryKey: ['scenes'] });
|
||||
}
|
||||
|
||||
function requestRegenerate() {
|
||||
if (busy) return;
|
||||
if (sceneCount > 0) regenOpen = true;
|
||||
else $generateMutation.mutate();
|
||||
}
|
||||
|
||||
function openEdit(scene: Scene) {
|
||||
editing = { ...scene };
|
||||
editOpen = true;
|
||||
}
|
||||
|
||||
async function addScene() {
|
||||
if (busy) return;
|
||||
adding = true;
|
||||
try {
|
||||
const existing = $scenesQuery.data?.scenes ?? [];
|
||||
const nextIndex = existing.length + 1;
|
||||
const created = await projects.createScene(projectId, {
|
||||
order_index: nextIndex,
|
||||
heading: `NEW SCENE ${nextIndex}`,
|
||||
action: '',
|
||||
dialog: '',
|
||||
duration_sec: 5,
|
||||
});
|
||||
// Keep order_index contiguous 1..n so Regenerate sees the real board size
|
||||
const ids = [...existing.map((s) => s.id), created.id];
|
||||
await projects.reorderScenes(projectId, ids);
|
||||
await client.invalidateQueries({ queryKey: ['scenes'] });
|
||||
await client.refetchQueries({ queryKey: ['scenes', projectId] });
|
||||
editing = { ...created, order_index: nextIndex, heading: `NEW SCENE ${nextIndex}` };
|
||||
editOpen = true;
|
||||
highlightId = created.id;
|
||||
await tick();
|
||||
document
|
||||
.getElementById(`scene-${created.id}`)
|
||||
?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
toast.success(`Scene #${nextIndex} added — edit it below`);
|
||||
window.setTimeout(() => {
|
||||
if (highlightId === created.id) highlightId = null;
|
||||
}, 2800);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not add scene');
|
||||
} finally {
|
||||
adding = false;
|
||||
}
|
||||
}
|
||||
|
||||
function requestDelete(scene: Scene) {
|
||||
if (busy) return;
|
||||
sceneToDelete = scene;
|
||||
deleteOpen = true;
|
||||
}
|
||||
|
||||
async function confirmDeleteScene() {
|
||||
const scene = sceneToDelete;
|
||||
sceneToDelete = null;
|
||||
if (!scene || busy) return;
|
||||
const label = scene.heading?.trim() || `Scene #${scene.order_index}`;
|
||||
deletingId = scene.id;
|
||||
try {
|
||||
await projects.deleteScene(projectId, scene.id);
|
||||
if (editing?.id === scene.id) {
|
||||
editing = null;
|
||||
editOpen = false;
|
||||
}
|
||||
const remaining = ($scenesQuery.data?.scenes ?? [])
|
||||
.filter((s) => s.id !== scene.id)
|
||||
.map((s) => s.id);
|
||||
if (remaining.length > 0) {
|
||||
await projects.reorderScenes(projectId, remaining);
|
||||
}
|
||||
await client.invalidateQueries({ queryKey: ['scenes'] });
|
||||
toast.success(`Deleted ${label}`);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not delete scene');
|
||||
} finally {
|
||||
deletingId = null;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<header class="stage-header">
|
||||
<div>
|
||||
<h2>3. Script</h2>
|
||||
<p class="muted">
|
||||
Estimated duration: {formatClock(totalSec)}
|
||||
{#if targetSec > 0}
|
||||
/ target ~{formatClock(targetSec)}
|
||||
{/if}
|
||||
{#if sceneCount > 0}
|
||||
· {sceneCount} scenes
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
<div class="stage-actions">
|
||||
<Button variant="secondary" disabled={busy} loading={adding} onclick={addScene}>
|
||||
<Icon name="plus" size={14} /> Add Scene
|
||||
</Button>
|
||||
<Button variant="primary" disabled={busy} onclick={requestRegenerate}>
|
||||
{#if writing}
|
||||
Writing…
|
||||
{:else}
|
||||
<Icon name="sparkle" size={15} /> Regenerate Script
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="script-panel" aria-busy={writing}>
|
||||
{#if writing}
|
||||
<GeneratingOverlay
|
||||
title="AI is writing the script…"
|
||||
status={agentStatus}
|
||||
hint="Editing is paused until this finishes."
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if $scenesQuery.isLoading}
|
||||
<div class="card">Loading scenes…</div>
|
||||
{:else if sceneCount === 0}
|
||||
<EmptyState
|
||||
title="No scenes yet"
|
||||
body="Regenerate a full script, or add one scene and write it yourself."
|
||||
>
|
||||
{#snippet icon()}
|
||||
<Icon name="script" size={28} />
|
||||
{/snippet}
|
||||
{#snippet action()}
|
||||
<Button variant="secondary" disabled={busy} loading={adding} onclick={addScene}>
|
||||
<Icon name="plus" size={14} /> Add Scene
|
||||
</Button>
|
||||
{/snippet}
|
||||
</EmptyState>
|
||||
{:else}
|
||||
{#each scenes as scene, i (scene.id)}
|
||||
{@const st = sceneStatus(scene)}
|
||||
{@const locName = locationName(scene)}
|
||||
<article
|
||||
id="scene-{scene.id}"
|
||||
class="card scene"
|
||||
class:fresh={highlightId === scene.id}
|
||||
class:deleting={deletingId === scene.id}
|
||||
>
|
||||
<div class="scene-head">
|
||||
<div class="scene-title">
|
||||
<span class="grip" aria-hidden="true"><Icon name="drag" size={14} /></span>
|
||||
<span class="num">#{scene.order_index}</span>
|
||||
<strong>{scene.heading || 'Untitled scene'}</strong>
|
||||
{#if highlightId === scene.id}
|
||||
<span class="fresh-tag">Just added</span>
|
||||
{/if}
|
||||
<StatusChip status={st.status} label={st.label} />
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Move scene up"
|
||||
title="Move scene up"
|
||||
disabled={busy || i === 0}
|
||||
onclick={() => move(scene.id, -1)}
|
||||
>
|
||||
<Icon name="chevron-up" size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Move scene down"
|
||||
title="Move scene down"
|
||||
disabled={busy || i === sceneCount - 1}
|
||||
onclick={() => move(scene.id, 1)}
|
||||
>
|
||||
<Icon name="chevron-down" size={15} />
|
||||
</button>
|
||||
<Button variant="secondary" size="sm" disabled={busy} onclick={() => openEdit(scene)}>
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
loading={deletingId === scene.id}
|
||||
onclick={() => requestDelete(scene)}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{#if scene.action}
|
||||
<p class="muted">{scene.action}</p>
|
||||
{:else}
|
||||
<p class="muted empty-line">No action yet — open Edit to write the beat.</p>
|
||||
{/if}
|
||||
{#if scene.dialog}
|
||||
<pre class="dialog">{scene.dialog}</pre>
|
||||
{/if}
|
||||
<div class="chips">
|
||||
{#each scene.characters ?? [] as c (c.id)}
|
||||
{@const avatar = avatarFor(c)}
|
||||
<span class="chip">
|
||||
<span class="avatar">
|
||||
<span class="initials" aria-hidden="true">{initialsOf(c.name)}</span>
|
||||
{#if avatar}
|
||||
<img src={avatar} alt="" loading="lazy" onerror={hideBrokenAvatar} />
|
||||
{/if}
|
||||
</span>
|
||||
{c.name}
|
||||
</span>
|
||||
{/each}
|
||||
{#if locName}
|
||||
<span class="chip"><Icon name="folder" size={12} /> {locName}</span>
|
||||
{/if}
|
||||
{#if scene.duration_sec}
|
||||
<span class="chip"><Icon name="clock" size={12} /> {formatClock(scene.duration_sec)}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</article>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
bind:open={editOpen}
|
||||
title={editing ? `Edit Scene #${editing.order_index}` : 'Edit Scene'}
|
||||
onclose={() => (editing = null)}
|
||||
>
|
||||
{#if editing}
|
||||
<label class="field">
|
||||
<span class="field-label">Heading</span>
|
||||
<input class="field-input" bind:value={editing.heading} placeholder="INT. LOCATION - TIME" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Action</span>
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
bind:value={editing.action}
|
||||
rows="4"
|
||||
placeholder="What happens on screen"
|
||||
></textarea>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Dialog</span>
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
bind:value={editing.dialog}
|
||||
rows="4"
|
||||
placeholder="CHARACTER Line…"
|
||||
></textarea>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Duration (sec)</span>
|
||||
<input class="field-input" type="number" bind:value={editing.duration_sec} min="1" />
|
||||
</label>
|
||||
{/if}
|
||||
{#snippet footer()}
|
||||
<Button variant="ghost" onclick={() => (editOpen = false)}>Cancel</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
loading={$saveMutation.isPending}
|
||||
onclick={() => $saveMutation.mutate()}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:open={regenOpen}
|
||||
title="Regenerate script?"
|
||||
message="This replaces all {sceneCount} scenes and discards manual edits. Continue?"
|
||||
confirmLabel="Regenerate"
|
||||
danger
|
||||
onconfirm={() => {
|
||||
editing = null;
|
||||
editOpen = false;
|
||||
$generateMutation.mutate();
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:open={deleteOpen}
|
||||
title="Delete scene?"
|
||||
message={sceneToDelete
|
||||
? `Delete “${sceneToDelete.heading?.trim() || `Scene #${sceneToDelete.order_index}`}”? This cannot be undone.`
|
||||
: ''}
|
||||
confirmLabel="Delete"
|
||||
danger
|
||||
onconfirm={() => void confirmDeleteScene()}
|
||||
oncancel={() => (sceneToDelete = null)}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.stage-header {
|
||||
/* Pins inside the stage scroll container so Add Scene / Regenerate
|
||||
stay reachable while scrolling long scripts. */
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 5;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: var(--space-lg);
|
||||
gap: var(--space-md);
|
||||
padding: 8px 0 12px;
|
||||
background: var(--bg-primary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.stage-header h2 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.stage-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.muted {
|
||||
color: var(--text-secondary);
|
||||
margin: 0;
|
||||
}
|
||||
.script-panel {
|
||||
position: relative;
|
||||
min-height: 220px;
|
||||
}
|
||||
.card {
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
padding: var(--space-lg);
|
||||
margin-bottom: var(--space-md);
|
||||
scroll-margin-top: 84px;
|
||||
scroll-margin-bottom: 24px;
|
||||
}
|
||||
.scene {
|
||||
transition:
|
||||
border-color 0.25s ease,
|
||||
box-shadow 0.25s ease,
|
||||
opacity 0.2s ease;
|
||||
}
|
||||
.scene.fresh {
|
||||
border-color: var(--accent);
|
||||
box-shadow:
|
||||
0 0 0 1px var(--accent),
|
||||
0 0 24px var(--accent-glow);
|
||||
animation: scene-in 0.45s ease-out;
|
||||
}
|
||||
.scene.deleting {
|
||||
opacity: 0.45;
|
||||
}
|
||||
@keyframes scene-in {
|
||||
from {
|
||||
opacity: 0.35;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.scene.fresh {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
.scene-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.scene-title {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.grip {
|
||||
display: inline-flex;
|
||||
color: var(--text-muted);
|
||||
cursor: grab;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.num {
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
.fresh-tag {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--accent);
|
||||
background: var(--accent-glow);
|
||||
border-radius: 999px;
|
||||
padding: 2px 8px;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.icon-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
}
|
||||
.icon-btn:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border);
|
||||
}
|
||||
.icon-btn:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.icon-btn:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.empty-line {
|
||||
font-style: italic;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.dialog {
|
||||
background: var(--bg-elevated);
|
||||
padding: 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
white-space: pre-wrap;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
}
|
||||
.chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
padding: 2px 10px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.avatar {
|
||||
position: relative;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
overflow: hidden;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.avatar img {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.initials {
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
color: var(--accent);
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,927 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { createMutation, useQueryClient } from '@tanstack/svelte-query';
|
||||
import {
|
||||
projects,
|
||||
type Beat,
|
||||
type Character,
|
||||
type Location,
|
||||
type StoryData,
|
||||
} from '$lib/api';
|
||||
import {
|
||||
buildStoryDraftPromptPreview,
|
||||
estimateTargetSeconds,
|
||||
recommendBeatCount,
|
||||
recommendSceneCount,
|
||||
} from '$lib/durationBudget';
|
||||
import { toast } from '$lib/toast';
|
||||
import Button from '$lib/components/ui/Button.svelte';
|
||||
import Card from '$lib/components/ui/Card.svelte';
|
||||
import StatusChip from '$lib/components/ui/StatusChip.svelte';
|
||||
import Modal from '$lib/components/ui/Modal.svelte';
|
||||
import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte';
|
||||
import EmptyState from '$lib/components/ui/EmptyState.svelte';
|
||||
import Spinner from '$lib/components/ui/Spinner.svelte';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import GeneratingOverlay from '$lib/components/GeneratingOverlay.svelte';
|
||||
|
||||
interface Props {
|
||||
projectId: number;
|
||||
story: StoryData;
|
||||
generating?: boolean;
|
||||
onGenerate: () => Promise<unknown>;
|
||||
configured: boolean;
|
||||
error?: string;
|
||||
onGoAssets?: () => void;
|
||||
/** Latest agent.thinking message from the project SSE stream. */
|
||||
agentStatus?: string | null;
|
||||
}
|
||||
|
||||
let {
|
||||
projectId,
|
||||
story,
|
||||
generating = false,
|
||||
onGenerate,
|
||||
configured,
|
||||
error = '',
|
||||
agentStatus = null,
|
||||
}: Props = $props();
|
||||
const client = useQueryClient();
|
||||
let localBusy = $state(false);
|
||||
let localError = $state('');
|
||||
const busy = $derived(generating || localBusy);
|
||||
const shownError = $derived(localError || error);
|
||||
|
||||
const GENRES = [
|
||||
'Adventure / Mystery',
|
||||
'Drama',
|
||||
'Sci-Fi',
|
||||
'Fantasy',
|
||||
'Horror',
|
||||
'Romance',
|
||||
'Thriller',
|
||||
];
|
||||
const LENGTHS_HINT = 'e.g. 2 minutes, 90 seconds, ~12 scenes';
|
||||
const TONES = [
|
||||
'Cinematic, atmospheric',
|
||||
'Dark, tense',
|
||||
'Whimsical, warm',
|
||||
'Gritty, realistic',
|
||||
'Epic, sweeping',
|
||||
];
|
||||
|
||||
const EXAMPLE = {
|
||||
idea: 'A lone cartographer discovers a map that rewrites itself every midnight, leading her into a forgotten city beneath the desert.',
|
||||
genre: 'Adventure / Mystery',
|
||||
tone: 'Cinematic, atmospheric',
|
||||
target_duration: '2 minutes',
|
||||
};
|
||||
|
||||
let editingBeat = $state<Beat | null>(null);
|
||||
let editingChar = $state<Character | null>(null);
|
||||
let editingLoc = $state<Location | null>(null);
|
||||
let beatModalOpen = $state(false);
|
||||
let charModalOpen = $state(false);
|
||||
let locModalOpen = $state(false);
|
||||
let confirmExampleOpen = $state(false);
|
||||
let confirmDraftOpen = $state(false);
|
||||
let deletingBeat = $state<Beat | null>(null);
|
||||
let beatDeleteOpen = $state(false);
|
||||
let addingBeat = $state(false);
|
||||
// Static defaults — the $effect below syncs all drafts from the story prop.
|
||||
let ideaDraft = $state('');
|
||||
let genreDraft = $state(GENRES[0]);
|
||||
let toneDraft = $state(TONES[0]);
|
||||
let lengthDraft = $state('2 minutes');
|
||||
let showDraftPrompt = $state(false);
|
||||
|
||||
type SaveState = 'idle' | 'saving' | 'saved' | 'error';
|
||||
let saveState = $state<SaveState>('idle');
|
||||
let savedTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const beatBudget = $derived(recommendBeatCount(lengthDraft));
|
||||
const sceneBudget = $derived(recommendSceneCount(lengthDraft));
|
||||
const secsBudget = $derived(estimateTargetSeconds(lengthDraft));
|
||||
const draftPromptPreview = $derived(
|
||||
buildStoryDraftPromptPreview({
|
||||
title: story.project.title,
|
||||
idea: ideaDraft,
|
||||
genre: genreDraft,
|
||||
tone: toneDraft,
|
||||
targetDuration: lengthDraft,
|
||||
}),
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
ideaDraft = story.project.idea ?? '';
|
||||
genreDraft = story.project.genre || GENRES[0];
|
||||
toneDraft = story.project.tone || TONES[0];
|
||||
lengthDraft = story.project.target_duration || '2 minutes';
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
return () => {
|
||||
if (savedTimer) clearTimeout(savedTimer);
|
||||
};
|
||||
});
|
||||
|
||||
function armSavedTimer() {
|
||||
if (savedTimer) clearTimeout(savedTimer);
|
||||
savedTimer = setTimeout(() => {
|
||||
if (saveState === 'saved') saveState = 'idle';
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
const saveProject = createMutation({
|
||||
mutationFn: (payload: {
|
||||
idea?: string;
|
||||
genre?: string;
|
||||
tone?: string;
|
||||
target_duration?: string;
|
||||
}) => projects.update(projectId, payload),
|
||||
onMutate: () => {
|
||||
saveState = 'saving';
|
||||
},
|
||||
onSuccess: () => {
|
||||
client.invalidateQueries({ queryKey: ['story'] });
|
||||
saveState = 'saved';
|
||||
armSavedTimer();
|
||||
},
|
||||
onError: (err) => {
|
||||
saveState = 'error';
|
||||
toast.error(err instanceof Error ? err.message : 'Could not save story settings');
|
||||
},
|
||||
});
|
||||
|
||||
/** Autosave path — returns false on failure (mutation onError already toasted). */
|
||||
async function persistSettings(): Promise<boolean> {
|
||||
try {
|
||||
await $saveProject.mutateAsync({
|
||||
idea: ideaDraft,
|
||||
genre: genreDraft || undefined,
|
||||
tone: toneDraft || undefined,
|
||||
target_duration: lengthDraft || undefined,
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadExample() {
|
||||
ideaDraft = EXAMPLE.idea;
|
||||
genreDraft = EXAMPLE.genre;
|
||||
toneDraft = EXAMPLE.tone;
|
||||
lengthDraft = EXAMPLE.target_duration;
|
||||
const saved = await persistSettings();
|
||||
if (saved) toast.success('Example story loaded');
|
||||
}
|
||||
|
||||
function requestLoadExample() {
|
||||
if (ideaDraft.trim()) confirmExampleOpen = true;
|
||||
else void loadExample();
|
||||
}
|
||||
|
||||
async function draftStoryline() {
|
||||
if (busy || !configured) return;
|
||||
localError = '';
|
||||
localBusy = true;
|
||||
try {
|
||||
const saved = await persistSettings();
|
||||
if (!saved) {
|
||||
localError = 'Story settings could not be saved — fix that before drafting.';
|
||||
return;
|
||||
}
|
||||
await onGenerate();
|
||||
await client.invalidateQueries({ queryKey: ['story'] });
|
||||
} catch (err) {
|
||||
localError = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
localBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function requestDraft() {
|
||||
if (busy || !configured) return;
|
||||
if (story.beats.length > 0) confirmDraftOpen = true;
|
||||
else void draftStoryline();
|
||||
}
|
||||
|
||||
function openBeat(beat: Beat) {
|
||||
editingBeat = { ...beat };
|
||||
beatModalOpen = true;
|
||||
}
|
||||
|
||||
async function addBeat() {
|
||||
if (addingBeat) return;
|
||||
addingBeat = true;
|
||||
try {
|
||||
const nextIndex =
|
||||
story.beats.reduce((max, b) => Math.max(max, b.order_index), 0) + 1;
|
||||
// No api.ts binding exists yet for POST /beats — call the endpoint directly.
|
||||
const res = await fetch(`/api/projects/${projectId}/beats`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
order_index: nextIndex,
|
||||
title: `New beat ${nextIndex}`,
|
||||
description: '',
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => 'unknown error');
|
||||
throw new Error(`${res.status}: ${body}`);
|
||||
}
|
||||
const created = (await res.json()) as Beat;
|
||||
await client.invalidateQueries({ queryKey: ['story'] });
|
||||
toast.success(`Beat ${nextIndex} added — edit it now`);
|
||||
openBeat(created);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not add beat');
|
||||
} finally {
|
||||
addingBeat = false;
|
||||
}
|
||||
}
|
||||
|
||||
function requestDeleteBeat(beat: Beat) {
|
||||
deletingBeat = beat;
|
||||
beatDeleteOpen = true;
|
||||
}
|
||||
|
||||
const deleteBeatMutation = createMutation({
|
||||
mutationFn: (beatId: number) => projects.deleteBeat(projectId, beatId),
|
||||
onSuccess: () => {
|
||||
client.invalidateQueries({ queryKey: ['story'] });
|
||||
toast.success('Beat deleted');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not delete beat');
|
||||
},
|
||||
});
|
||||
|
||||
const saveBeat = createMutation({
|
||||
mutationFn: () =>
|
||||
projects.updateBeat(projectId, editingBeat!.id, {
|
||||
title: editingBeat!.title,
|
||||
description: editingBeat!.description,
|
||||
order_index: editingBeat!.order_index,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
editingBeat = null;
|
||||
beatModalOpen = false;
|
||||
client.invalidateQueries({ queryKey: ['story'] });
|
||||
toast.success('Beat saved');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not save beat');
|
||||
},
|
||||
});
|
||||
|
||||
const saveChar = createMutation({
|
||||
mutationFn: () =>
|
||||
projects.updateCharacter(projectId, editingChar!.id, {
|
||||
name: editingChar!.name,
|
||||
role: editingChar!.role,
|
||||
age: editingChar!.age,
|
||||
appearance: editingChar!.appearance,
|
||||
personality: editingChar!.personality,
|
||||
consistency_prompt: editingChar!.consistency_prompt,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
editingChar = null;
|
||||
charModalOpen = false;
|
||||
client.invalidateQueries({ queryKey: ['story'] });
|
||||
toast.success('Character saved');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not save character');
|
||||
},
|
||||
});
|
||||
|
||||
const saveLoc = createMutation({
|
||||
mutationFn: () =>
|
||||
projects.updateLocation(projectId, editingLoc!.id, {
|
||||
name: editingLoc!.name,
|
||||
description: editingLoc!.description,
|
||||
consistency_prompt: editingLoc!.consistency_prompt,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
editingLoc = null;
|
||||
locModalOpen = false;
|
||||
client.invalidateQueries({ queryKey: ['story'] });
|
||||
toast.success('Location saved');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not save location');
|
||||
},
|
||||
});
|
||||
|
||||
function goToAssets() {
|
||||
goto('?stage=assets', { keepFocus: true, noScroll: true });
|
||||
}
|
||||
|
||||
function beatCountLabel(n: number): string {
|
||||
return `${n} beat${n === 1 ? '' : 's'}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet saveIndicator()}
|
||||
{#if saveState === 'saving'}
|
||||
<span class="save-ind"><Spinner size="sm" /> Saving…</span>
|
||||
{:else if saveState === 'saved'}
|
||||
<span class="save-ind saved"><Icon name="check" size={13} /> Saved</span>
|
||||
{:else if saveState === 'error'}
|
||||
<span class="save-ind err">
|
||||
<Icon name="alert" size={13} /> Save failed
|
||||
<Button variant="ghost" size="sm" onclick={() => void persistSettings()}>Retry</Button>
|
||||
</span>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<header class="stage-header">
|
||||
<h2>1. Story</h2>
|
||||
<div class="stage-actions">
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={busy || $saveProject.isPending}
|
||||
onclick={requestLoadExample}
|
||||
>
|
||||
Load Example
|
||||
</Button>
|
||||
<Button variant="primary" disabled={busy || !configured} onclick={requestDraft}>
|
||||
{#if busy}
|
||||
Drafting… (LLM can take ~30s)
|
||||
{:else}
|
||||
<Icon name="sparkle" size={15} /> Draft Storyline
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{#if !configured}
|
||||
<div class="banner">Configure an LLM in Settings before drafting a storyline.</div>
|
||||
{/if}
|
||||
|
||||
{#if shownError}
|
||||
<div class="banner error">{shownError}</div>
|
||||
{/if}
|
||||
|
||||
<div class="stack-col" aria-busy={busy}>
|
||||
{#if busy}
|
||||
<GeneratingOverlay
|
||||
title="Agent is writing your story"
|
||||
status={agentStatus}
|
||||
hint="This can take ~30 seconds. The draft keeps running server-side — you can switch stages or tabs while it works."
|
||||
/>
|
||||
{/if}
|
||||
<Card>
|
||||
{#snippet header()}
|
||||
<h3 class="card-h">Story Idea</h3>
|
||||
{@render saveIndicator()}
|
||||
{/snippet}
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
bind:value={ideaDraft}
|
||||
rows="5"
|
||||
placeholder="A lone cartographer discovers a map that rewrites itself every midnight..."
|
||||
onblur={() => void persistSettings()}
|
||||
></textarea>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
{#snippet header()}
|
||||
<h3 class="card-h">Settings</h3>
|
||||
{@render saveIndicator()}
|
||||
{/snippet}
|
||||
<div class="grid-3">
|
||||
<label class="field">
|
||||
<span class="field-label">Genre</span>
|
||||
<select
|
||||
class="field-select"
|
||||
bind:value={genreDraft}
|
||||
onchange={() => void persistSettings()}
|
||||
>
|
||||
{#each GENRES as g}
|
||||
<option value={g}>{g}</option>
|
||||
{/each}
|
||||
{#if genreDraft && !GENRES.includes(genreDraft)}
|
||||
<option value={genreDraft}>{genreDraft}</option>
|
||||
{/if}
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Target Length</span>
|
||||
<input
|
||||
class="field-input"
|
||||
type="text"
|
||||
bind:value={lengthDraft}
|
||||
placeholder={LENGTHS_HINT}
|
||||
onblur={() => void persistSettings()}
|
||||
/>
|
||||
<span class="field-hint beat-hint">
|
||||
Parsed as ~{secsBudget}s → Draft Storyline will require
|
||||
<strong> {beatBudget} beats</strong>
|
||||
(Script later aims for ~{sceneBudget} scenes). Example: “10 minutes”.
|
||||
</span>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Tone</span>
|
||||
<select
|
||||
class="field-select"
|
||||
bind:value={toneDraft}
|
||||
onchange={() => void persistSettings()}
|
||||
>
|
||||
{#each TONES as t}
|
||||
<option value={t}>{t}</option>
|
||||
{/each}
|
||||
{#if toneDraft && !TONES.includes(toneDraft)}
|
||||
<option value={toneDraft}>{toneDraft}</option>
|
||||
{/if}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
{#snippet header()}
|
||||
<h3 class="card-h">Draft Storyline prompt</h3>
|
||||
<Button variant="ghost" size="sm" onclick={() => (showDraftPrompt = !showDraftPrompt)}>
|
||||
{showDraftPrompt ? 'Hide' : 'Show'} what we send to the LLM
|
||||
</Button>
|
||||
{/snippet}
|
||||
{#if showDraftPrompt}
|
||||
<pre class="prompt-preview">{draftPromptPreview}</pre>
|
||||
<p class="field-hint">
|
||||
This is the user message (plus a short system rule). Beat count is a hard constraint;
|
||||
if the model under-delivers, the server retries once, then errors instead of accepting a thin
|
||||
outline.
|
||||
</p>
|
||||
{:else}
|
||||
<p class="field-hint prompt-collapsed">
|
||||
Expand to inspect the exact prompt Draft Storyline sends to the LLM.
|
||||
</p>
|
||||
{/if}
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
{#snippet header()}
|
||||
<h3 class="card-h">Story Beats</h3>
|
||||
<div class="head-actions">
|
||||
{#if story.beats.length}
|
||||
<StatusChip status="ready" label={beatCountLabel(story.beats.length)} />
|
||||
{/if}
|
||||
<Button variant="secondary" size="sm" loading={addingBeat} onclick={addBeat}>
|
||||
<Icon name="plus" size={14} /> Add beat
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
{#if story.beats.length === 0}
|
||||
<EmptyState
|
||||
title="No beats yet"
|
||||
body="Draft a storyline to break your idea into beats, or add one manually and write it yourself."
|
||||
>
|
||||
{#snippet icon()}
|
||||
<Icon name="story" size={28} />
|
||||
{/snippet}
|
||||
{#snippet action()}
|
||||
<Button variant="secondary" size="sm" loading={addingBeat} onclick={addBeat}>
|
||||
<Icon name="plus" size={14} /> Add beat manually
|
||||
</Button>
|
||||
{/snippet}
|
||||
</EmptyState>
|
||||
{:else}
|
||||
<div class="beat-list">
|
||||
{#each story.beats as beat (beat.id)}
|
||||
<div class="beat-row">
|
||||
<button type="button" class="beat" onclick={() => openBeat(beat)}>
|
||||
<div class="beat-number">{beat.order_index}</div>
|
||||
<div class="beat-body">
|
||||
<h4>{beat.title}</h4>
|
||||
<p>{beat.description}</p>
|
||||
</div>
|
||||
</button>
|
||||
<div class="beat-actions">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
title="Delete beat {beat.order_index}"
|
||||
onclick={() => requestDeleteBeat(beat)}
|
||||
>
|
||||
<Icon name="trash" size={14} /><span class="sr-only"
|
||||
>Delete beat {beat.order_index}</span
|
||||
>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="beats-footer">
|
||||
<Button variant="primary" onclick={goToAssets}>
|
||||
Continue to Assets <Icon name="chevron-right" size={15} />
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</Card>
|
||||
|
||||
{#if story.characters.length || story.locations.length}
|
||||
<Card>
|
||||
{#snippet header()}
|
||||
<h3 class="card-h">Extracted</h3>
|
||||
<Button variant="ghost" size="sm" onclick={goToAssets}>
|
||||
Open in Assets <Icon name="chevron-right" size={14} />
|
||||
</Button>
|
||||
{/snippet}
|
||||
<div class="chips">
|
||||
{#each story.characters as char (char.id)}
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
onclick={() => {
|
||||
editingChar = { ...char };
|
||||
charModalOpen = true;
|
||||
}}
|
||||
title={char.appearance ?? ''}
|
||||
>
|
||||
<span class="chip-tag">Char</span>
|
||||
{char.name}
|
||||
</button>
|
||||
{/each}
|
||||
{#each story.locations as loc (loc.id)}
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
onclick={() => {
|
||||
editingLoc = { ...loc };
|
||||
locModalOpen = true;
|
||||
}}
|
||||
title={loc.description ?? ''}
|
||||
>
|
||||
<span class="chip-tag">Env</span>
|
||||
{loc.name}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</Card>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal bind:open={beatModalOpen} title="Edit Beat" onclose={() => (editingBeat = null)}>
|
||||
{#if editingBeat}
|
||||
<label class="field">
|
||||
<span class="field-label">Title</span>
|
||||
<input class="field-input" bind:value={editingBeat.title} />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Description</span>
|
||||
<textarea class="field-textarea" rows="4" bind:value={editingBeat.description}></textarea>
|
||||
</label>
|
||||
{/if}
|
||||
{#snippet footer()}
|
||||
<Button variant="ghost" onclick={() => (beatModalOpen = false)}>Cancel</Button>
|
||||
<Button variant="primary" loading={$saveBeat.isPending} onclick={() => $saveBeat.mutate()}>
|
||||
Save
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
|
||||
<Modal bind:open={charModalOpen} title="Edit Character" onclose={() => (editingChar = null)}>
|
||||
{#if editingChar}
|
||||
<label class="field">
|
||||
<span class="field-label">Name</span>
|
||||
<input class="field-input" bind:value={editingChar.name} placeholder="Name" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Role</span>
|
||||
<input class="field-input" bind:value={editingChar.role} placeholder="Role" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Age</span>
|
||||
<input class="field-input" bind:value={editingChar.age} placeholder="Age" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Appearance</span>
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
rows="3"
|
||||
bind:value={editingChar.appearance}
|
||||
placeholder="Appearance"
|
||||
></textarea>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Personality</span>
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
rows="2"
|
||||
bind:value={editingChar.personality}
|
||||
placeholder="Personality"
|
||||
></textarea>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Consistency prompt</span>
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
rows="2"
|
||||
bind:value={editingChar.consistency_prompt}
|
||||
placeholder="Consistency prompt"
|
||||
></textarea>
|
||||
</label>
|
||||
{/if}
|
||||
{#snippet footer()}
|
||||
<Button variant="ghost" onclick={() => (charModalOpen = false)}>Cancel</Button>
|
||||
<Button variant="primary" loading={$saveChar.isPending} onclick={() => $saveChar.mutate()}>
|
||||
Save
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
|
||||
<Modal bind:open={locModalOpen} title="Edit Location" onclose={() => (editingLoc = null)}>
|
||||
{#if editingLoc}
|
||||
<label class="field">
|
||||
<span class="field-label">Name</span>
|
||||
<input class="field-input" bind:value={editingLoc.name} placeholder="Name" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Description</span>
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
rows="3"
|
||||
bind:value={editingLoc.description}
|
||||
placeholder="Description"
|
||||
></textarea>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Consistency prompt</span>
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
rows="2"
|
||||
bind:value={editingLoc.consistency_prompt}
|
||||
placeholder="Consistency prompt"
|
||||
></textarea>
|
||||
</label>
|
||||
{/if}
|
||||
{#snippet footer()}
|
||||
<Button variant="ghost" onclick={() => (locModalOpen = false)}>Cancel</Button>
|
||||
<Button variant="primary" loading={$saveLoc.isPending} onclick={() => $saveLoc.mutate()}>
|
||||
Save
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:open={confirmExampleOpen}
|
||||
title="Load example?"
|
||||
message="Replace your current idea with the example? This overwrites the idea, genre, tone and target length."
|
||||
confirmLabel="Load example"
|
||||
onconfirm={() => void loadExample()}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:open={confirmDraftOpen}
|
||||
title="Replace storyline?"
|
||||
message="This replaces the existing {beatCountLabel(story.beats.length)} and regenerates characters and environments. Continue?"
|
||||
confirmLabel="Replace"
|
||||
danger
|
||||
onconfirm={() => void draftStoryline()}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:open={beatDeleteOpen}
|
||||
title="Delete beat?"
|
||||
message={deletingBeat
|
||||
? `Delete beat ${deletingBeat.order_index} “${deletingBeat.title}”? This cannot be undone.`
|
||||
: ''}
|
||||
confirmLabel="Delete"
|
||||
danger
|
||||
onconfirm={() => {
|
||||
const id = deletingBeat?.id;
|
||||
deletingBeat = null;
|
||||
if (id != null) $deleteBeatMutation.mutate(id);
|
||||
}}
|
||||
oncancel={() => (deletingBeat = null)}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.stage-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: var(--space-lg);
|
||||
gap: var(--space-md);
|
||||
}
|
||||
.stage-header h2 {
|
||||
margin: 0;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.stage-actions {
|
||||
display: flex;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
.banner {
|
||||
background: rgba(245, 158, 11, 0.1);
|
||||
border: 1px solid rgba(245, 158, 11, 0.3);
|
||||
color: var(--warning);
|
||||
padding: var(--space-md);
|
||||
border-radius: var(--radius-md);
|
||||
margin-bottom: var(--space-lg);
|
||||
font-size: 13px;
|
||||
}
|
||||
.banner.error {
|
||||
background: rgba(239, 68, 68, 0.12);
|
||||
border-color: rgba(239, 68, 68, 0.35);
|
||||
color: var(--error);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
.stack-col {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
.card-h {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
.head-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
.save-ind {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.save-ind.saved {
|
||||
color: var(--success);
|
||||
animation: saved-fade 2s ease forwards;
|
||||
}
|
||||
.save-ind.err {
|
||||
color: var(--error);
|
||||
}
|
||||
@keyframes saved-fade {
|
||||
0% {
|
||||
opacity: 0;
|
||||
}
|
||||
12% {
|
||||
opacity: 1;
|
||||
}
|
||||
78% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
.grid-3 {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: var(--space-md);
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.grid-3 {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
.grid-3 .field {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.beat-hint {
|
||||
display: block;
|
||||
}
|
||||
.beat-hint strong {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
.prompt-preview {
|
||||
margin: 0 0 var(--space-sm);
|
||||
padding: 12px;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
line-height: 1.45;
|
||||
white-space: pre-wrap;
|
||||
color: var(--text-secondary);
|
||||
max-height: 280px;
|
||||
overflow: auto;
|
||||
}
|
||||
.prompt-collapsed {
|
||||
margin: 0;
|
||||
}
|
||||
.beat-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.beat-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-xs);
|
||||
}
|
||||
.beat {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
gap: var(--space-md);
|
||||
align-items: flex-start;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-md);
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
}
|
||||
.beat:hover {
|
||||
border-color: var(--border);
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.beat:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.beat-actions {
|
||||
flex-shrink: 0;
|
||||
padding-top: 8px;
|
||||
}
|
||||
.beat-number {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--bg-elevated);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 700;
|
||||
color: var(--text-secondary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.beat-body h4 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.beat-body p {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.beats-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: var(--space-md);
|
||||
padding-top: var(--space-md);
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 6px 10px;
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chip:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.chip:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.chip-tag {
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,162 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
dismissToast,
|
||||
pauseToast,
|
||||
resumeToast,
|
||||
subscribeToasts,
|
||||
type Toast,
|
||||
} from '$lib/toast';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import type { IconName } from '$lib/components/ui/icons';
|
||||
|
||||
let items = $state<Toast[]>([]);
|
||||
|
||||
onMount(() => subscribeToasts((next) => (items = next)));
|
||||
|
||||
const kindIcon: Record<Toast['kind'], IconName> = {
|
||||
success: 'check',
|
||||
error: 'alert',
|
||||
info: 'info',
|
||||
};
|
||||
</script>
|
||||
|
||||
{#if items.length}
|
||||
<div class="toast-host" aria-live="polite" aria-relevant="additions">
|
||||
{#each items as t (t.id)}
|
||||
<div
|
||||
class="toast {t.kind}"
|
||||
role="status"
|
||||
onmouseenter={() => pauseToast(t.id)}
|
||||
onmouseleave={() => resumeToast(t.id)}
|
||||
onfocusin={() => pauseToast(t.id)}
|
||||
onfocusout={() => resumeToast(t.id)}
|
||||
>
|
||||
<span class="badge" aria-hidden="true">
|
||||
<span class="dot"></span>
|
||||
<Icon name={kindIcon[t.kind]} size={15} />
|
||||
</span>
|
||||
<span class="msg">{t.message}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="dismiss"
|
||||
aria-label="Dismiss"
|
||||
onclick={() => dismissToast(t.id)}
|
||||
>
|
||||
<Icon name="close" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.toast-host {
|
||||
position: fixed;
|
||||
top: 72px;
|
||||
right: 20px;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-width: min(360px, calc(100vw - 32px));
|
||||
pointer-events: none;
|
||||
}
|
||||
.toast {
|
||||
pointer-events: auto;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 12px 14px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-surface);
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45);
|
||||
animation: toast-in 0.22s ease-out;
|
||||
}
|
||||
.toast.success {
|
||||
border-color: rgba(34, 197, 94, 0.45);
|
||||
box-shadow:
|
||||
0 12px 32px rgba(0, 0, 0, 0.45),
|
||||
0 0 0 1px rgba(34, 197, 94, 0.12);
|
||||
}
|
||||
.toast.error {
|
||||
border-color: rgba(239, 68, 68, 0.5);
|
||||
}
|
||||
.toast.info {
|
||||
border-color: rgba(59, 130, 246, 0.45);
|
||||
}
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 1px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
.toast.success .badge {
|
||||
color: var(--success);
|
||||
}
|
||||
.toast.error .badge {
|
||||
color: var(--error);
|
||||
}
|
||||
.toast.info .badge {
|
||||
color: var(--info);
|
||||
}
|
||||
.msg {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
color: var(--text-primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
.dismiss {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
padding: 0 2px;
|
||||
min-width: 28px;
|
||||
min-height: 28px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.dismiss:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.dismiss:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
@keyframes toast-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.toast {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.toast-host {
|
||||
top: auto;
|
||||
bottom: 20px;
|
||||
right: 16px;
|
||||
left: 16px;
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,464 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* MediaTile — square thumbnail for image/ref/audio inputs.
|
||||
*
|
||||
* Asset picker menu is portaled to document.body so OmniComposer
|
||||
* overflow:hidden cannot clip it (same fix as PillSelect).
|
||||
*/
|
||||
import { assetUrl } from '$lib/api';
|
||||
import type { ComfyDynamicInput } from '$lib/comfy/types';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import Spinner from '$lib/components/ui/Spinner.svelte';
|
||||
import { acceptForKind } from '$lib/comfy/useUpload.svelte';
|
||||
|
||||
interface AssetOption {
|
||||
label: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
input: ComfyDynamicInput;
|
||||
value: string;
|
||||
uploadingName: string | null;
|
||||
assetOptions?: AssetOption[];
|
||||
allowUpload?: boolean;
|
||||
invalid?: boolean;
|
||||
onselectFile: (file: File) => void;
|
||||
onselectAsset: (path: string) => void;
|
||||
onclear: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
input,
|
||||
value,
|
||||
uploadingName,
|
||||
assetOptions = [],
|
||||
allowUpload = true,
|
||||
invalid = false,
|
||||
onselectFile,
|
||||
onselectAsset,
|
||||
onclear,
|
||||
}: Props = $props();
|
||||
|
||||
let fileInput = $state<HTMLInputElement | null>(null);
|
||||
let dragOver = $state(false);
|
||||
let showAssetMenu = $state(false);
|
||||
let tileEl = $state<HTMLElement | null>(null);
|
||||
let menuEl = $state<HTMLElement | null>(null);
|
||||
let menuPos = $state({ top: 0, left: 0, maxHeight: 280, minWidth: 200 });
|
||||
|
||||
const hasAssets = $derived(assetOptions.length > 0);
|
||||
|
||||
function openPicker(e: MouseEvent) {
|
||||
e.stopPropagation();
|
||||
if (uploadingName) return;
|
||||
if (hasAssets) {
|
||||
showAssetMenu = !showAssetMenu;
|
||||
} else if (allowUpload) {
|
||||
fileInput?.click();
|
||||
}
|
||||
}
|
||||
|
||||
function onFileChosen(e: Event) {
|
||||
const el = e.currentTarget as HTMLInputElement;
|
||||
const file = el.files?.[0];
|
||||
el.value = '';
|
||||
if (file) onselectFile(file);
|
||||
}
|
||||
|
||||
function onDrop(e: DragEvent) {
|
||||
e.preventDefault();
|
||||
dragOver = false;
|
||||
if (uploadingName) return;
|
||||
const file = e.dataTransfer?.files?.[0];
|
||||
if (file) onselectFile(file);
|
||||
}
|
||||
|
||||
function hideBrokenThumb(e: Event) {
|
||||
const img = e.currentTarget as HTMLImageElement | null;
|
||||
if (img) img.style.display = 'none';
|
||||
}
|
||||
|
||||
const thumbSrc = $derived(value ? assetUrl(value) : null);
|
||||
|
||||
const isImageKind = $derived(
|
||||
input.kind === 'image' || input.kind === 'image_url' || input.kind === 'audio',
|
||||
);
|
||||
|
||||
function placeMenu() {
|
||||
if (!tileEl || !menuEl) return;
|
||||
const rect = tileEl.getBoundingClientRect();
|
||||
const gap = 6;
|
||||
const pad = 8;
|
||||
const spaceBelow = window.innerHeight - rect.bottom - gap - pad;
|
||||
const spaceAbove = rect.top - gap - pad;
|
||||
const preferred = Math.min(320, Math.max(menuEl.scrollHeight, 80));
|
||||
const openUp = spaceBelow < Math.min(preferred, 160) && spaceAbove > spaceBelow;
|
||||
const maxHeight = Math.max(120, openUp ? spaceAbove : spaceBelow);
|
||||
const h = Math.min(menuEl.scrollHeight, maxHeight);
|
||||
const minWidth = Math.max(200, rect.width);
|
||||
|
||||
let top = openUp ? rect.top - h - gap : rect.bottom + gap;
|
||||
let left = rect.left;
|
||||
left = Math.max(pad, Math.min(left, window.innerWidth - minWidth - pad));
|
||||
top = Math.max(pad, Math.min(top, window.innerHeight - Math.min(h, maxHeight) - pad));
|
||||
|
||||
menuPos = { top, left, maxHeight, minWidth };
|
||||
}
|
||||
|
||||
function onWindowClick(e: MouseEvent) {
|
||||
if (!showAssetMenu) return;
|
||||
const t = e.target as Node;
|
||||
if (tileEl?.contains(t) || menuEl?.contains(t)) return;
|
||||
showAssetMenu = false;
|
||||
}
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') showAssetMenu = false;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!showAssetMenu || !menuEl) return;
|
||||
document.body.appendChild(menuEl);
|
||||
return () => {
|
||||
menuEl?.remove();
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!showAssetMenu) return;
|
||||
const t = window.setTimeout(() => {
|
||||
placeMenu();
|
||||
window.addEventListener('click', onWindowClick);
|
||||
window.addEventListener('keydown', onKey);
|
||||
window.addEventListener('resize', placeMenu);
|
||||
window.addEventListener('scroll', placeMenu, true);
|
||||
}, 0);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
window.removeEventListener('click', onWindowClick);
|
||||
window.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('resize', placeMenu);
|
||||
window.removeEventListener('scroll', placeMenu, true);
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (showAssetMenu && menuEl && tileEl) {
|
||||
void assetOptions.length;
|
||||
requestAnimationFrame(placeMenu);
|
||||
}
|
||||
});
|
||||
|
||||
const displayLabel = $derived(
|
||||
input.role === 'character'
|
||||
? 'Character'
|
||||
: input.role === 'location'
|
||||
? 'Location'
|
||||
: input.label,
|
||||
);
|
||||
|
||||
const accept = $derived(
|
||||
input.kind === 'audio'
|
||||
? 'audio/*'
|
||||
: input.kind === 'image' || input.kind === 'image_url'
|
||||
? 'image/*'
|
||||
: 'image/*,video/*,audio/*',
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="tile-wrap" bind:this={tileEl}>
|
||||
<input
|
||||
bind:this={fileInput}
|
||||
type="file"
|
||||
class="sr-only"
|
||||
accept={accept || acceptForKind(input.kind)}
|
||||
onchange={onFileChosen}
|
||||
/>
|
||||
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="tile"
|
||||
class:filled={!!value}
|
||||
class:dragover={dragOver}
|
||||
class:invalid
|
||||
ondragenter={(e) => {
|
||||
e.preventDefault();
|
||||
dragOver = true;
|
||||
}}
|
||||
ondragleave={() => (dragOver = false)}
|
||||
ondragover={(e) => e.preventDefault()}
|
||||
ondrop={onDrop}
|
||||
onclick={openPicker}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
title={displayLabel}
|
||||
aria-haspopup={hasAssets ? 'menu' : undefined}
|
||||
aria-expanded={hasAssets ? showAssetMenu : undefined}
|
||||
>
|
||||
{#if uploadingName}
|
||||
<div class="tile-uploading">
|
||||
<Spinner size="sm" />
|
||||
</div>
|
||||
{:else if value && thumbSrc && isImageKind}
|
||||
<img class="tile-thumb" src={thumbSrc} alt={displayLabel} onerror={hideBrokenThumb} />
|
||||
{:else if value}
|
||||
<div class="tile-file">
|
||||
<Icon name={input.kind === 'audio' ? 'music' : 'image'} size={20} />
|
||||
</div>
|
||||
{:else}
|
||||
<div class="tile-empty">
|
||||
<Icon name="plus" size={20} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if value && !uploadingName}
|
||||
<button
|
||||
type="button"
|
||||
class="tile-remove"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
onclear();
|
||||
}}
|
||||
aria-label="Remove {displayLabel}"
|
||||
>
|
||||
<Icon name="close" size={12} />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<span class="tile-label">{displayLabel}</span>
|
||||
|
||||
{#if invalid && !value}
|
||||
<span class="tile-req">Required</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if showAssetMenu && hasAssets}
|
||||
<div
|
||||
bind:this={menuEl}
|
||||
class="asset-menu"
|
||||
style="top: {menuPos.top}px; left: {menuPos.left}px; max-height: {menuPos.maxHeight}px; min-width: {menuPos.minWidth}px"
|
||||
role="menu"
|
||||
>
|
||||
{#each assetOptions as opt (opt.path)}
|
||||
<button
|
||||
type="button"
|
||||
class="asset-item"
|
||||
class:active={opt.path === value}
|
||||
role="menuitem"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
onselectAsset(opt.path);
|
||||
showAssetMenu = false;
|
||||
}}
|
||||
>
|
||||
<span class="item-label">{opt.label}</span>
|
||||
{#if opt.path === value}
|
||||
<Icon name="check" size={14} />
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
{#if allowUpload}
|
||||
<button
|
||||
type="button"
|
||||
class="asset-item upload-opt"
|
||||
role="menuitem"
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
showAssetMenu = false;
|
||||
fileInput?.click();
|
||||
}}
|
||||
>
|
||||
<Icon name="upload" size={12} />
|
||||
Upload new…
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.tile-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tile {
|
||||
position: relative;
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1.5px dashed var(--border);
|
||||
background: var(--bg-elevated);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
transition:
|
||||
border-color 0.15s,
|
||||
background 0.15s;
|
||||
}
|
||||
|
||||
.tile:hover:not(.filled) {
|
||||
border-color: var(--text-muted);
|
||||
}
|
||||
|
||||
.tile:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.tile.dragover {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-glow);
|
||||
border-style: solid;
|
||||
}
|
||||
|
||||
.tile.filled {
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.tile.invalid {
|
||||
border-color: var(--error);
|
||||
}
|
||||
|
||||
.tile-empty {
|
||||
color: var(--text-muted);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.tile-thumb {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.tile-file {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.tile-uploading {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.tile-remove {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 9999px;
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
border: none;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
|
||||
.tile:hover .tile-remove {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.tile-remove:hover {
|
||||
background: var(--error);
|
||||
}
|
||||
|
||||
.tile-label {
|
||||
font-size: 10px;
|
||||
color: var(--text-muted);
|
||||
font-weight: 500;
|
||||
max-width: 72px;
|
||||
text-align: center;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tile-req {
|
||||
font-size: 9px;
|
||||
color: var(--error);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.asset-menu {
|
||||
position: fixed;
|
||||
z-index: 10000;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow:
|
||||
0 8px 24px rgba(0, 0, 0, 0.5),
|
||||
0 0 0 1px rgba(0, 0, 0, 0.3);
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.asset-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-family: var(--font-body);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.item-label {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.asset-item:hover {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.asset-item.active {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.upload-opt {
|
||||
color: var(--text-muted);
|
||||
border-top: 1px solid var(--border);
|
||||
margin-top: 2px;
|
||||
padding-top: 10px;
|
||||
border-radius: 0 0 var(--radius-sm) var(--radius-sm);
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,199 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* PillPopover — pill that opens a panel with arbitrary content.
|
||||
*
|
||||
* Portaled to document.body and flipped upward near the viewport
|
||||
* bottom so the docked Omni composer does not clip it.
|
||||
*/
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
label: string;
|
||||
badge?: number;
|
||||
icon?: string;
|
||||
children: import('svelte').Snippet;
|
||||
}
|
||||
|
||||
let { label, badge = 0, icon, children }: Props = $props();
|
||||
|
||||
let open = $state(false);
|
||||
let pillEl = $state<HTMLElement | null>(null);
|
||||
let panelEl = $state<HTMLElement | null>(null);
|
||||
let menuPos = $state({ top: 0, left: 0, maxHeight: 360 });
|
||||
|
||||
function toggle(e: MouseEvent) {
|
||||
e.stopPropagation();
|
||||
open = !open;
|
||||
}
|
||||
|
||||
function onWindowClick(e: MouseEvent) {
|
||||
if (!open) return;
|
||||
const t = e.target as Node;
|
||||
if (pillEl?.contains(t) || panelEl?.contains(t)) return;
|
||||
open = false;
|
||||
}
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') open = false;
|
||||
}
|
||||
|
||||
function placePanel() {
|
||||
if (!pillEl || !panelEl) return;
|
||||
const rect = pillEl.getBoundingClientRect();
|
||||
const gap = 6;
|
||||
const pad = 8;
|
||||
const spaceBelow = window.innerHeight - rect.bottom - gap - pad;
|
||||
const spaceAbove = rect.top - gap - pad;
|
||||
const preferred = Math.min(400, Math.max(panelEl.scrollHeight, 80));
|
||||
const openUp = spaceBelow < Math.min(preferred, 180) && spaceAbove > spaceBelow;
|
||||
const maxHeight = Math.max(120, openUp ? spaceAbove : spaceBelow);
|
||||
const h = Math.min(panelEl.scrollHeight, maxHeight);
|
||||
|
||||
let top = openUp ? rect.top - h - gap : rect.bottom + gap;
|
||||
let left = rect.left;
|
||||
const width = Math.max(220, panelEl.offsetWidth);
|
||||
|
||||
left = Math.max(pad, Math.min(left, window.innerWidth - width - pad));
|
||||
top = Math.max(pad, Math.min(top, window.innerHeight - Math.min(h, maxHeight) - pad));
|
||||
|
||||
menuPos = { top, left, maxHeight };
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open || !panelEl) return;
|
||||
document.body.appendChild(panelEl);
|
||||
return () => {
|
||||
panelEl?.remove();
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
const t = window.setTimeout(() => {
|
||||
placePanel();
|
||||
window.addEventListener('click', onWindowClick);
|
||||
window.addEventListener('keydown', onKey);
|
||||
window.addEventListener('resize', placePanel);
|
||||
window.addEventListener('scroll', placePanel, true);
|
||||
}, 0);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
window.removeEventListener('click', onWindowClick);
|
||||
window.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('resize', placePanel);
|
||||
window.removeEventListener('scroll', placePanel, true);
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (open && panelEl && pillEl) {
|
||||
requestAnimationFrame(placePanel);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="pill-wrap" bind:this={pillEl}>
|
||||
<button
|
||||
type="button"
|
||||
class="pill"
|
||||
onclick={toggle}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
>
|
||||
{#if icon}
|
||||
<Icon name={icon as never} size={14} />
|
||||
{/if}
|
||||
<span class="pill-label">{label}</span>
|
||||
{#if badge > 0}
|
||||
<span class="pill-badge">{badge}</span>
|
||||
{/if}
|
||||
<Icon name="chevron-down" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if open}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
bind:this={panelEl}
|
||||
class="popover"
|
||||
style="top: {menuPos.top}px; left: {menuPos.left}px; max-height: {menuPos.maxHeight}px"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{@render children()}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.pill-wrap {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: var(--pill-height, 36px);
|
||||
padding: var(--pill-padding, 0 14px);
|
||||
border-radius: var(--pill-radius, 9999px);
|
||||
background: var(--pill-bg, var(--bg-elevated));
|
||||
border: 1px solid var(--pill-border, var(--border));
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--pill-font-size, 13px);
|
||||
font-family: var(--font-body);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
border-color 0.15s,
|
||||
background 0.15s;
|
||||
}
|
||||
|
||||
.pill:hover {
|
||||
border-color: var(--text-muted);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.pill:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.pill-label {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.pill-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
border-radius: 9999px;
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.popover {
|
||||
position: fixed;
|
||||
z-index: 10000;
|
||||
min-width: 220px;
|
||||
max-width: 320px;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow:
|
||||
0 8px 24px rgba(0, 0, 0, 0.5),
|
||||
0 0 0 1px rgba(0, 0, 0, 0.3);
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,259 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* PillSelect — pill-shaped dropdown for the Omni control bar.
|
||||
*
|
||||
* Menu is portaled to document.body so overflow:hidden ancestors
|
||||
* (composer shell) cannot clip it. Opens upward when there isn't
|
||||
* room below the pill (bottom-docked composer).
|
||||
*/
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
|
||||
interface Option {
|
||||
value: string | number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
label: string;
|
||||
options: Option[];
|
||||
value: string | number | null;
|
||||
onchange: (value: string | number) => void;
|
||||
icon?: string;
|
||||
highlight?: boolean;
|
||||
}
|
||||
|
||||
let {
|
||||
label,
|
||||
options,
|
||||
value,
|
||||
onchange,
|
||||
icon,
|
||||
highlight = false,
|
||||
}: Props = $props();
|
||||
|
||||
let open = $state(false);
|
||||
let pillEl = $state<HTMLElement | null>(null);
|
||||
let menuEl = $state<HTMLElement | null>(null);
|
||||
let menuPos = $state({ top: 0, left: 0, maxHeight: 320, minWidth: 160 });
|
||||
|
||||
function toggle(e: MouseEvent) {
|
||||
e.stopPropagation();
|
||||
open = !open;
|
||||
}
|
||||
|
||||
function select(val: string | number) {
|
||||
onchange(val);
|
||||
open = false;
|
||||
}
|
||||
|
||||
function onWindowClick(e: MouseEvent) {
|
||||
if (!open) return;
|
||||
const t = e.target as Node;
|
||||
if (pillEl?.contains(t) || menuEl?.contains(t)) return;
|
||||
open = false;
|
||||
}
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') open = false;
|
||||
}
|
||||
|
||||
function placeMenu() {
|
||||
if (!pillEl || !menuEl) return;
|
||||
const rect = pillEl.getBoundingClientRect();
|
||||
const gap = 6;
|
||||
const pad = 8;
|
||||
const spaceBelow = window.innerHeight - rect.bottom - gap - pad;
|
||||
const spaceAbove = rect.top - gap - pad;
|
||||
const preferred = Math.min(360, Math.max(menuEl.scrollHeight, 40));
|
||||
const openUp = spaceBelow < Math.min(preferred, 200) && spaceAbove > spaceBelow;
|
||||
const maxHeight = Math.max(120, openUp ? spaceAbove : spaceBelow);
|
||||
|
||||
// Measure after max-height applied next frame — use preferred for top calc
|
||||
const h = Math.min(menuEl.scrollHeight, maxHeight);
|
||||
let top = openUp ? rect.top - h - gap : rect.bottom + gap;
|
||||
let left = rect.left;
|
||||
const minWidth = Math.max(160, rect.width);
|
||||
|
||||
left = Math.max(pad, Math.min(left, window.innerWidth - minWidth - pad));
|
||||
top = Math.max(pad, Math.min(top, window.innerHeight - Math.min(h, maxHeight) - pad));
|
||||
|
||||
menuPos = { top, left, maxHeight, minWidth };
|
||||
}
|
||||
|
||||
// Portal menu to <body> so composer overflow cannot clip it
|
||||
$effect(() => {
|
||||
if (!open || !menuEl) return;
|
||||
document.body.appendChild(menuEl);
|
||||
return () => {
|
||||
menuEl?.remove();
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
const t = window.setTimeout(() => {
|
||||
placeMenu();
|
||||
window.addEventListener('click', onWindowClick);
|
||||
window.addEventListener('keydown', onKey);
|
||||
window.addEventListener('resize', placeMenu);
|
||||
window.addEventListener('scroll', placeMenu, true);
|
||||
}, 0);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
window.removeEventListener('click', onWindowClick);
|
||||
window.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('resize', placeMenu);
|
||||
window.removeEventListener('scroll', placeMenu, true);
|
||||
};
|
||||
});
|
||||
|
||||
// Re-place once menuEl binds / options change
|
||||
$effect(() => {
|
||||
if (open && menuEl && pillEl) {
|
||||
void options.length;
|
||||
requestAnimationFrame(placeMenu);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="pill-wrap" bind:this={pillEl}>
|
||||
<button
|
||||
type="button"
|
||||
class="pill"
|
||||
class:highlight
|
||||
onclick={toggle}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
>
|
||||
{#if icon}
|
||||
<Icon name={icon as never} size={14} />
|
||||
{/if}
|
||||
<span class="pill-label">{label}</span>
|
||||
<Icon name="chevron-down" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if open}
|
||||
<div
|
||||
bind:this={menuEl}
|
||||
class="pill-menu"
|
||||
style="top: {menuPos.top}px; left: {menuPos.left}px; max-height: {menuPos.maxHeight}px; min-width: {menuPos.minWidth}px"
|
||||
role="listbox"
|
||||
>
|
||||
{#each options as opt (opt.value)}
|
||||
<button
|
||||
type="button"
|
||||
class="menu-item"
|
||||
class:active={opt.value === value}
|
||||
role="option"
|
||||
aria-selected={opt.value === value}
|
||||
onclick={() => select(opt.value)}
|
||||
>
|
||||
<span class="item-label">{opt.label}</span>
|
||||
{#if opt.value === value}
|
||||
<Icon name="check" size={14} />
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.pill-wrap {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: var(--pill-height, 36px);
|
||||
padding: var(--pill-padding, 0 14px);
|
||||
border-radius: var(--pill-radius, 9999px);
|
||||
background: var(--pill-bg, var(--bg-elevated));
|
||||
border: 1px solid var(--pill-border, var(--border));
|
||||
color: var(--text-primary);
|
||||
font-size: var(--pill-font-size, 13px);
|
||||
font-family: var(--font-body);
|
||||
cursor: pointer;
|
||||
max-width: 100%;
|
||||
transition:
|
||||
border-color 0.15s,
|
||||
background 0.15s;
|
||||
}
|
||||
|
||||
.pill:hover {
|
||||
border-color: var(--text-muted);
|
||||
}
|
||||
|
||||
.pill:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.pill.highlight {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.pill-label {
|
||||
font-weight: 500;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 280px;
|
||||
}
|
||||
|
||||
.pill-menu {
|
||||
position: fixed;
|
||||
z-index: 10000;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow:
|
||||
0 8px 24px rgba(0, 0, 0, 0.5),
|
||||
0 0 0 1px rgba(0, 0, 0, 0.3);
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
font-family: var(--font-body);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.item-label {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.menu-item:hover {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.menu-item.active {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,110 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* PillStepper — a pill with − / + buttons for numeric values.
|
||||
*
|
||||
* Used for duration (3–10s) and seed in the control bar.
|
||||
* The value display sits between the two buttons, all inside one pill.
|
||||
*/
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
label: string;
|
||||
value: number | string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
/** If true, value is hidden behind a dice/randomize icon (for seed). */
|
||||
obscured?: boolean;
|
||||
onchange: (value: number) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
label,
|
||||
value,
|
||||
min = 0,
|
||||
max = 999999,
|
||||
step = 1,
|
||||
obscured = false,
|
||||
onchange,
|
||||
}: Props = $props();
|
||||
|
||||
function clamp(n: number): number {
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
function decrement() {
|
||||
const current = Number(value) || min;
|
||||
onchange(clamp(current - step));
|
||||
}
|
||||
|
||||
function increment() {
|
||||
const current = Number(value) || min;
|
||||
onchange(clamp(current + step));
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="stepper-pill" title={label}>
|
||||
<button type="button" class="step-btn" onclick={decrement} aria-label="Decrease {label}">
|
||||
<Icon name="close" size={12} />
|
||||
</button>
|
||||
<span class="step-value">
|
||||
{#if obscured && !value}
|
||||
<Icon name="sparkle" size={12} />
|
||||
{:else}
|
||||
{value}{label === 'Duration' ? 's' : ''}
|
||||
{/if}
|
||||
</span>
|
||||
<button type="button" class="step-btn" onclick={increment} aria-label="Increase {label}">
|
||||
<Icon name="plus" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.stepper-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
height: var(--pill-height, 36px);
|
||||
border-radius: var(--pill-radius, 9999px);
|
||||
background: var(--pill-bg, var(--bg-elevated));
|
||||
border: 1px solid var(--pill-border, var(--border));
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.step-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
|
||||
.step-btn:hover {
|
||||
color: var(--text-primary);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.step-btn:focus-visible {
|
||||
outline: none;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.step-value {
|
||||
min-width: 36px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-mono);
|
||||
padding: 0 2px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,108 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
|
||||
const items = [
|
||||
{ id: 'llm', href: '/settings?tab=llm', label: 'LLM', blurb: 'Model endpoint' },
|
||||
{ id: 'comfy', href: '/settings?tab=comfy', label: 'ComfyUI', blurb: 'Render farm' },
|
||||
{ id: 'workflows', href: '/settings?tab=workflows', label: 'Workflows', blurb: 'Library' },
|
||||
{ id: 'queue', href: '/settings?tab=queue', label: 'Queue', blurb: 'Concurrency' },
|
||||
{ id: 'storage', href: '/settings?tab=storage', label: 'Storage', blurb: 'Paths' },
|
||||
] as const;
|
||||
|
||||
interface Props {
|
||||
/** Section ids with unsaved edits — shown with a small warning dot. */
|
||||
dirty?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
let { dirty }: Props = $props();
|
||||
|
||||
let active = $derived($page.url.searchParams.get('tab') || 'llm');
|
||||
</script>
|
||||
|
||||
<aside class="side">
|
||||
<p class="eyebrow">Studio config</p>
|
||||
{#each items as item (item.id)}
|
||||
<a
|
||||
class="item"
|
||||
class:active={active === item.id}
|
||||
href={item.href}
|
||||
aria-current={active === item.id ? 'page' : undefined}
|
||||
>
|
||||
<span class="label">
|
||||
{item.label}
|
||||
{#if dirty?.has(item.id)}
|
||||
<span class="dirty-dot" title="Unsaved changes" aria-label="Unsaved changes"></span>
|
||||
{/if}
|
||||
</span>
|
||||
<span class="blurb">{item.blurb}</span>
|
||||
</a>
|
||||
{/each}
|
||||
</aside>
|
||||
|
||||
<style>
|
||||
.side {
|
||||
width: 220px;
|
||||
flex-shrink: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
background: var(--bg-surface);
|
||||
padding: var(--space-lg) var(--space-md);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-height: calc(100vh - 56px);
|
||||
}
|
||||
.eyebrow {
|
||||
margin: 0 8px 12px;
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--text-muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
.item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-md);
|
||||
text-decoration: none;
|
||||
color: var(--text-secondary);
|
||||
border: 1px solid transparent;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.item:hover {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.item.active {
|
||||
background: rgba(139, 92, 246, 0.12);
|
||||
border-color: rgba(139, 92, 246, 0.35);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.item:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
.dirty-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--warning);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.blurb {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.item.active .blurb {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,700 @@
|
||||
<script lang="ts">
|
||||
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
|
||||
import { workflows, type Workflow, type ComfyDynamicInput, type ComfyDynamicOutput } from '$lib/api';
|
||||
import { toast } from '$lib/toast';
|
||||
import Button from '$lib/components/ui/Button.svelte';
|
||||
import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte';
|
||||
import Skeleton from '$lib/components/ui/Skeleton.svelte';
|
||||
import StatusChip from '$lib/components/ui/StatusChip.svelte';
|
||||
|
||||
const client = useQueryClient();
|
||||
const workflowsQuery = createQuery({
|
||||
queryKey: ['workflows'],
|
||||
queryFn: workflows.list,
|
||||
});
|
||||
|
||||
let jsonText = $state('');
|
||||
let uploadedFileName = $state<string | null>(null);
|
||||
let dragging = $state(false);
|
||||
let parseError = $state('');
|
||||
let analyzedInputs = $state<ComfyDynamicInput[]>([]);
|
||||
let analyzedOutputs = $state<ComfyDynamicOutput[]>([]);
|
||||
let analyzed = $state(false);
|
||||
let pendingJson = $state<Record<string, unknown> | null>(null);
|
||||
|
||||
let wfName = $state('');
|
||||
let wfKind = $state<'image' | 'video'>('image');
|
||||
let wfProfile = $state('prose');
|
||||
let wfDescription = $state('');
|
||||
let saving = $state(false);
|
||||
|
||||
let editingId = $state<number | null>(null);
|
||||
let editName = $state('');
|
||||
let editDescription = $state('');
|
||||
let editProfile = $state('prose');
|
||||
let detailsId = $state<number | null>(null);
|
||||
|
||||
async function analyzeRaw(text: string) {
|
||||
parseError = '';
|
||||
analyzed = false;
|
||||
analyzedInputs = [];
|
||||
analyzedOutputs = [];
|
||||
pendingJson = null;
|
||||
try {
|
||||
const json = JSON.parse(text) as Record<string, unknown>;
|
||||
pendingJson = json;
|
||||
const result = await workflows.analyze(json);
|
||||
analyzedInputs = result.inputs;
|
||||
analyzedOutputs = result.outputs;
|
||||
analyzed = true;
|
||||
wfProfile = result.suggested_profile ?? 'prose';
|
||||
if (!wfName.trim() && uploadedFileName) {
|
||||
wfName = uploadedFileName.replace(/\.json$/i, '');
|
||||
}
|
||||
} catch (err) {
|
||||
parseError = err instanceof Error ? err.message : 'Invalid JSON';
|
||||
}
|
||||
}
|
||||
|
||||
async function onFile(file: File) {
|
||||
uploadedFileName = file.name;
|
||||
const text = await file.text();
|
||||
jsonText = text;
|
||||
await analyzeRaw(text);
|
||||
}
|
||||
|
||||
function onDrop(e: DragEvent) {
|
||||
e.preventDefault();
|
||||
dragging = false;
|
||||
const file = e.dataTransfer?.files?.[0];
|
||||
if (file) void onFile(file);
|
||||
}
|
||||
|
||||
async function saveToLibrary() {
|
||||
if (!pendingJson || !wfName.trim() || !analyzed) return;
|
||||
saving = true;
|
||||
try {
|
||||
await workflows.create({
|
||||
name: wfName.trim(),
|
||||
kind: wfKind,
|
||||
workflow_json: pendingJson,
|
||||
description: wfDescription.trim() || undefined,
|
||||
prompt_profile: wfProfile,
|
||||
});
|
||||
jsonText = '';
|
||||
uploadedFileName = null;
|
||||
analyzed = false;
|
||||
analyzedInputs = [];
|
||||
analyzedOutputs = [];
|
||||
pendingJson = null;
|
||||
const name = wfName.trim();
|
||||
wfName = '';
|
||||
wfDescription = '';
|
||||
wfKind = 'image';
|
||||
wfProfile = 'prose';
|
||||
client.invalidateQueries({ queryKey: ['workflows'] });
|
||||
toast.success(`Workflow “${name}” saved to library`);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not save workflow');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startEdit(wf: Workflow) {
|
||||
editingId = wf.id;
|
||||
editName = wf.name;
|
||||
editDescription = wf.description ?? '';
|
||||
editProfile = wf.prompt_profile ?? 'prose';
|
||||
}
|
||||
|
||||
async function saveEdit(id: number) {
|
||||
try {
|
||||
await workflows.update(id, {
|
||||
name: editName.trim(),
|
||||
description: editDescription.trim(),
|
||||
prompt_profile: editProfile,
|
||||
});
|
||||
editingId = null;
|
||||
client.invalidateQueries({ queryKey: ['workflows'] });
|
||||
toast.success('Workflow updated');
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not update workflow');
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleEnabled(wf: Workflow) {
|
||||
try {
|
||||
await workflows.update(wf.id, { is_enabled: !wf.is_enabled });
|
||||
client.invalidateQueries({ queryKey: ['workflows'] });
|
||||
toast.success(wf.is_enabled ? `Workflow “${wf.name}” disabled` : `Workflow “${wf.name}” enabled`);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not update workflow');
|
||||
}
|
||||
}
|
||||
|
||||
let deleteTarget = $state<Workflow | null>(null);
|
||||
let deleteOpen = $state(false);
|
||||
|
||||
function askDelete(wf: Workflow) {
|
||||
deleteTarget = wf;
|
||||
deleteOpen = true;
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
const wf = deleteTarget;
|
||||
deleteTarget = null;
|
||||
if (!wf) return;
|
||||
try {
|
||||
await workflows.delete(wf.id);
|
||||
if (detailsId === wf.id) detailsId = null;
|
||||
client.invalidateQueries({ queryKey: ['workflows'] });
|
||||
toast.success(`Workflow “${wf.name}” deleted`);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Could not delete workflow');
|
||||
}
|
||||
}
|
||||
|
||||
let list = $derived($workflowsQuery.data ?? []);
|
||||
let imageCount = $derived(list.filter((w) => w.kind === 'image').length);
|
||||
let videoCount = $derived(list.filter((w) => w.kind === 'video').length);
|
||||
</script>
|
||||
|
||||
<section class="block">
|
||||
<header class="block-head">
|
||||
<div>
|
||||
<h2>ComfyUI Workflows</h2>
|
||||
<p>
|
||||
Register API-format workflow JSONs as a reusable library. In ComfyUI, title editable
|
||||
nodes with role tags such as <code>(Input:prompt)</code>,
|
||||
<code>(Input:width)</code>, <code>(Output:image)</code> — see <code>AGENTS.md</code>.
|
||||
</p>
|
||||
</div>
|
||||
<div class="stats">
|
||||
<span class="stat">{list.length} saved</span>
|
||||
<span class="stat image">{imageCount} image</span>
|
||||
<span class="stat video">{videoCount} video</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="register panel">
|
||||
<h3>Analyze & register</h3>
|
||||
<div
|
||||
class="drop"
|
||||
class:dragging
|
||||
role="button"
|
||||
tabindex="0"
|
||||
ondragover={(e) => {
|
||||
e.preventDefault();
|
||||
dragging = true;
|
||||
}}
|
||||
ondragleave={() => (dragging = false)}
|
||||
ondrop={onDrop}
|
||||
onclick={() => document.getElementById('wf-file')?.click()}
|
||||
onkeydown={(e) => e.key === 'Enter' && document.getElementById('wf-file')?.click()}
|
||||
>
|
||||
<input
|
||||
id="wf-file"
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
hidden
|
||||
onchange={(e) => {
|
||||
const f = (e.currentTarget as HTMLInputElement).files?.[0];
|
||||
if (f) void onFile(f);
|
||||
}}
|
||||
/>
|
||||
<div class="drop-icon">JSON</div>
|
||||
<div>
|
||||
<strong>Drop ComfyUI API JSON here</strong>
|
||||
<p class="muted">or click to browse · Save (API Format) from ComfyUI</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if uploadedFileName}
|
||||
<p class="file-name mono">{uploadedFileName}</p>
|
||||
{/if}
|
||||
|
||||
{#if jsonText}
|
||||
<label class="field">
|
||||
<span class="field-label">JSON preview</span>
|
||||
<textarea class="field-textarea mono preview" rows="8" readonly value={jsonText}></textarea>
|
||||
</label>
|
||||
<Button variant="secondary" size="sm" onclick={() => analyzeRaw(jsonText)}>Re-analyze</Button>
|
||||
{/if}
|
||||
|
||||
{#if parseError}
|
||||
<div class="error">{parseError}</div>
|
||||
{/if}
|
||||
|
||||
{#if analyzed}
|
||||
<div class="io-panel">
|
||||
<div class="io-col">
|
||||
<h4>Detected inputs ({analyzedInputs.length})</h4>
|
||||
{#if analyzedInputs.length === 0}
|
||||
<p class="muted">None — add <code>(Input:prompt)</code> etc. to node titles in ComfyUI.</p>
|
||||
{:else}
|
||||
{#each analyzedInputs as inp}
|
||||
<div class="pill input">
|
||||
<span class="kind">{inp.kind}</span>
|
||||
{#if inp.role}<span class="kind">{inp.role}</span>{/if}
|
||||
<span>{inp.label}</span>
|
||||
<span class="node mono">#{inp.nodeId}</span>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
<div class="io-col">
|
||||
<h4>Detected outputs ({analyzedOutputs.length})</h4>
|
||||
{#if analyzedOutputs.length === 0}
|
||||
<p class="muted">None — add <code>(Output:image)</code> / <code>(Output:video)</code> to node titles.</p>
|
||||
{:else}
|
||||
{#each analyzedOutputs as out}
|
||||
<div class="pill output">
|
||||
<span class="kind">{out.kind}</span>
|
||||
{#if out.role}<span class="kind">{out.role}</span>{/if}
|
||||
<span>{out.label}</span>
|
||||
<span class="node mono">#{out.nodeId}</span>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="meta-grid">
|
||||
<label class="field">
|
||||
<span class="field-label">Name</span>
|
||||
<input class="field-input" bind:value={wfName} placeholder="LTX Ref-to-Video" required />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Kind</span>
|
||||
<select class="field-select" bind:value={wfKind}>
|
||||
<option value="image">Image (Keyframe)</option>
|
||||
<option value="video">Video</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label class="field">
|
||||
<span class="field-label">Prompt format</span>
|
||||
<select class="field-select" bind:value={wfProfile}>
|
||||
<option value="prose">Plain prose (default)</option>
|
||||
<option value="minimax_h3_ref">MiniMax H3 reference (6-section)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Description</span>
|
||||
<textarea
|
||||
class="field-textarea"
|
||||
bind:value={wfDescription}
|
||||
rows="2"
|
||||
placeholder="When to use this workflow…"
|
||||
></textarea>
|
||||
</label>
|
||||
<Button variant="primary" loading={saving} disabled={!wfName.trim()} onclick={saveToLibrary}>
|
||||
Save to library
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="library">
|
||||
<div class="library-head">
|
||||
<h3>Saved workflows ({list.length})</h3>
|
||||
</div>
|
||||
|
||||
{#if $workflowsQuery.isLoading}
|
||||
<div class="cards" aria-busy="true" aria-label="Loading workflows">
|
||||
{#each [1, 2, 3] as n (n)}
|
||||
<div class="card skel-card">
|
||||
<Skeleton circle height="40px" />
|
||||
<div class="skel-lines">
|
||||
<Skeleton width="45%" height="15px" />
|
||||
<Skeleton width="70%" />
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else if list.length === 0}
|
||||
<div class="empty">
|
||||
<strong>No workflows yet</strong>
|
||||
<p class="muted">Register at least one image and one video workflow to run the pipeline.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="cards">
|
||||
{#each list as wf (wf.id)}
|
||||
<article class="card" class:disabled={!wf.is_enabled}>
|
||||
{#if editingId === wf.id}
|
||||
<label class="field">
|
||||
<span class="field-label">Name</span>
|
||||
<input class="field-input" bind:value={editName} />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Description</span>
|
||||
<textarea class="field-textarea" rows="2" bind:value={editDescription}></textarea>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Prompt format</span>
|
||||
<select class="field-select" bind:value={editProfile}>
|
||||
<option value="prose">Plain prose (default)</option>
|
||||
<option value="minimax_h3_ref">MiniMax H3 reference (6-section)</option>
|
||||
</select>
|
||||
</label>
|
||||
<p class="field-hint">Workflow JSON is locked after registration.</p>
|
||||
<div class="row">
|
||||
<Button size="sm" onclick={() => saveEdit(wf.id)}>Save</Button>
|
||||
<Button variant="ghost" size="sm" onclick={() => (editingId = null)}>Cancel</Button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="card-top">
|
||||
<div class="tile" class:video={wf.kind === 'video'}>
|
||||
{wf.kind === 'video' ? 'VID' : 'IMG'}
|
||||
</div>
|
||||
<div class="card-meta">
|
||||
<strong>{wf.name}</strong>
|
||||
<div class="tags">
|
||||
<span class="kind-badge" class:video={wf.kind === 'video'}>{wf.kind}</span>
|
||||
{#if wf.prompt_profile === 'minimax_h3_ref'}
|
||||
<span class="kind-badge h3">H3-ref</span>
|
||||
{/if}
|
||||
<span class="count">{wf.input_schema?.length ?? 0} inputs</span>
|
||||
<span class="count">{wf.output_schema?.length ?? 0} outputs</span>
|
||||
{#if !wf.is_enabled}<StatusChip status="disabled" label="Disabled" />{/if}
|
||||
</div>
|
||||
{#if wf.description}
|
||||
<p class="desc">{wf.description}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<Button variant="ghost" size="sm" onclick={() => startEdit(wf)}>Edit</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onclick={() => (detailsId = detailsId === wf.id ? null : wf.id)}
|
||||
>
|
||||
{detailsId === wf.id ? 'Hide I/O' : 'View I/O'}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onclick={() => toggleEnabled(wf)}>
|
||||
{wf.is_enabled ? 'Disable' : 'Enable'}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onclick={() => askDelete(wf)}>Delete</Button>
|
||||
</div>
|
||||
{#if detailsId === wf.id}
|
||||
<div class="io-panel nested">
|
||||
<div class="io-col">
|
||||
<h4>Inputs</h4>
|
||||
{#each wf.input_schema ?? [] as inp}
|
||||
<div class="pill input">
|
||||
<span class="kind">{inp.kind}</span>
|
||||
{#if inp.role}<span class="kind">{inp.role}</span>{/if}
|
||||
<span>{inp.label}</span>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="muted">No inputs cached.</p>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="io-col">
|
||||
<h4>Outputs</h4>
|
||||
{#each wf.output_schema ?? [] as out}
|
||||
<div class="pill output">
|
||||
<span class="kind">{out.kind}</span>
|
||||
<span>{out.label}</span>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="muted">No outputs cached.</p>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</article>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:open={deleteOpen}
|
||||
title="Delete workflow?"
|
||||
message={deleteTarget
|
||||
? `This removes “${deleteTarget.name}” from the library. This cannot be undone.`
|
||||
: ''}
|
||||
confirmLabel="Delete"
|
||||
danger
|
||||
onconfirm={confirmDelete}
|
||||
oncancel={() => (deleteTarget = null)}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.block-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-lg);
|
||||
align-items: flex-start;
|
||||
margin-bottom: var(--space-lg);
|
||||
}
|
||||
.block-head h2 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 22px;
|
||||
}
|
||||
.block-head p {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
max-width: 52ch;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.block-head code {
|
||||
background: var(--bg-elevated);
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.stats {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.stat {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-muted);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
.stat.image {
|
||||
color: var(--accent);
|
||||
border-color: rgba(139, 92, 246, 0.35);
|
||||
}
|
||||
.stat.video {
|
||||
color: var(--info);
|
||||
border-color: rgba(59, 130, 246, 0.35);
|
||||
}
|
||||
.panel,
|
||||
.card {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: var(--space-lg);
|
||||
}
|
||||
.register {
|
||||
margin-bottom: var(--space-xl);
|
||||
}
|
||||
.register h3,
|
||||
.library-head h3 {
|
||||
margin: 0 0 var(--space-md);
|
||||
font-size: 16px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.drop {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-md);
|
||||
padding: var(--space-lg);
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
margin-bottom: var(--space-md);
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.drop:hover,
|
||||
.drop.dragging {
|
||||
border-color: var(--accent);
|
||||
background: rgba(139, 92, 246, 0.08);
|
||||
}
|
||||
.drop:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.drop-icon {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: var(--radius-md);
|
||||
background: rgba(139, 92, 246, 0.12);
|
||||
color: var(--accent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.muted {
|
||||
color: var(--text-muted);
|
||||
margin: 4px 0 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.file-name {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
margin: 0 0 var(--space-md);
|
||||
}
|
||||
.preview {
|
||||
font-size: 11px;
|
||||
max-height: 180px;
|
||||
}
|
||||
.error {
|
||||
margin: var(--space-md) 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||
color: var(--error);
|
||||
font-size: 13px;
|
||||
}
|
||||
.io-panel {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--space-md);
|
||||
margin: var(--space-md) 0;
|
||||
padding: var(--space-md);
|
||||
background: var(--bg-primary);
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
.io-panel.nested {
|
||||
margin-top: var(--space-md);
|
||||
}
|
||||
@media (max-width: 800px) {
|
||||
.io-panel {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
.io-col h4 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.pill {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 8px;
|
||||
border-radius: var(--radius-sm);
|
||||
margin-bottom: 6px;
|
||||
font-size: 13px;
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.pill .kind {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
padding: 2px 6px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.pill.input .kind {
|
||||
background: rgba(139, 92, 246, 0.2);
|
||||
color: var(--accent);
|
||||
}
|
||||
.pill.output .kind {
|
||||
background: rgba(34, 197, 94, 0.15);
|
||||
color: var(--success);
|
||||
}
|
||||
.pill .node {
|
||||
margin-left: auto;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.meta-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
.library-head {
|
||||
margin-bottom: var(--space-md);
|
||||
}
|
||||
.cards {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
.card.disabled {
|
||||
opacity: 0.55;
|
||||
}
|
||||
.card-top {
|
||||
display: flex;
|
||||
gap: var(--space-md);
|
||||
margin-bottom: var(--space-md);
|
||||
}
|
||||
.tile {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--radius-md);
|
||||
background: rgba(139, 92, 246, 0.12);
|
||||
color: var(--accent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
font-family: var(--font-mono);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tile.video {
|
||||
background: rgba(59, 130, 246, 0.12);
|
||||
color: var(--info);
|
||||
}
|
||||
.card-meta strong {
|
||||
font-size: 15px;
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
.tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.kind-badge {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: rgba(139, 92, 246, 0.15);
|
||||
color: var(--accent);
|
||||
}
|
||||
.kind-badge.video {
|
||||
background: rgba(59, 130, 246, 0.15);
|
||||
color: var(--info);
|
||||
}
|
||||
.kind-badge.h3 {
|
||||
background: rgba(34, 197, 94, 0.15);
|
||||
color: var(--success);
|
||||
}
|
||||
.count {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.desc {
|
||||
margin: 8px 0 0;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.empty {
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: var(--space-xl);
|
||||
text-align: center;
|
||||
}
|
||||
.skel-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
.skel-lines {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,147 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import Spinner from './Spinner.svelte';
|
||||
|
||||
interface Props {
|
||||
variant?: 'primary' | 'secondary' | 'ghost' | 'danger';
|
||||
size?: 'sm' | 'md';
|
||||
disabled?: boolean;
|
||||
loading?: boolean;
|
||||
type?: 'button' | 'submit' | 'reset';
|
||||
title?: string;
|
||||
onclick?: (event: MouseEvent) => void;
|
||||
children: Snippet;
|
||||
}
|
||||
|
||||
let {
|
||||
variant = 'secondary',
|
||||
size = 'md',
|
||||
disabled = false,
|
||||
loading = false,
|
||||
type = 'button',
|
||||
title,
|
||||
onclick,
|
||||
children,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<button
|
||||
{type}
|
||||
class="btn btn-{variant} btn-{size}"
|
||||
class:loading
|
||||
disabled={disabled || loading}
|
||||
{title}
|
||||
{onclick}
|
||||
>
|
||||
<span class="btn-content" aria-hidden={loading || undefined}
|
||||
>{@render children()}</span
|
||||
>
|
||||
{#if loading}
|
||||
<span class="btn-spinner">
|
||||
<Spinner size="sm" />
|
||||
</span>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<style>
|
||||
.btn {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-sm);
|
||||
font-family: inherit;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color 150ms ease,
|
||||
border-color 150ms ease,
|
||||
color 150ms ease,
|
||||
box-shadow 150ms ease,
|
||||
transform 100ms ease;
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 28px;
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.btn-md {
|
||||
min-height: 34px;
|
||||
padding: 8px 14px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg-elevated);
|
||||
border-color: var(--border);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
background: #23232b;
|
||||
border-color: #3f3f46;
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.btn-ghost:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
border-color: rgba(239, 68, 68, 0.3);
|
||||
color: var(--error);
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: rgba(239, 68, 68, 0.18);
|
||||
border-color: rgba(239, 68, 68, 0.45);
|
||||
}
|
||||
|
||||
.btn:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.btn:active:not(:disabled) {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.btn-content {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: inherit;
|
||||
}
|
||||
.btn.loading .btn-content {
|
||||
visibility: hidden;
|
||||
}
|
||||
.btn-spinner {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.btn-primary .btn-spinner,
|
||||
.btn-danger .btn-spinner {
|
||||
--spinner-track: rgba(255, 255, 255, 0.35);
|
||||
--spinner-arc: #fff;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,84 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
interface Props {
|
||||
hoverable?: boolean;
|
||||
title?: string;
|
||||
actions?: Snippet;
|
||||
header?: Snippet;
|
||||
children: Snippet;
|
||||
class?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
hoverable = false,
|
||||
title,
|
||||
actions,
|
||||
header,
|
||||
children,
|
||||
class: klass = '',
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="card {klass}" class:hoverable>
|
||||
{#if header}
|
||||
<div class="card-header">
|
||||
{@render header()}
|
||||
</div>
|
||||
{:else if title || actions}
|
||||
<div class="card-header">
|
||||
{#if title}
|
||||
<h3 class="card-title">{title}</h3>
|
||||
{/if}
|
||||
{#if actions}
|
||||
<div class="card-actions">
|
||||
{@render actions()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="card-body">
|
||||
{@render children()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.card {
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
.card.hoverable {
|
||||
transition:
|
||||
border-color 150ms ease,
|
||||
transform 150ms ease;
|
||||
}
|
||||
.card.hoverable:hover {
|
||||
border-color: #3f3f46;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.card-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.card-title {
|
||||
margin: 0;
|
||||
font-family: var(--font-display);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.card-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-left: auto;
|
||||
}
|
||||
.card-body {
|
||||
padding: 16px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,63 @@
|
||||
<script lang="ts">
|
||||
import Button from './Button.svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
|
||||
interface Props {
|
||||
open?: boolean;
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
danger?: boolean;
|
||||
onconfirm: () => void;
|
||||
oncancel?: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
title,
|
||||
message,
|
||||
confirmLabel = 'Confirm',
|
||||
cancelLabel = 'Cancel',
|
||||
danger = false,
|
||||
onconfirm,
|
||||
oncancel,
|
||||
}: Props = $props();
|
||||
|
||||
// Set when the user confirms, so the ensuing close is not reported as a cancel.
|
||||
let confirmed = false;
|
||||
|
||||
function handleConfirm() {
|
||||
confirmed = true;
|
||||
open = false;
|
||||
onconfirm();
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (confirmed) {
|
||||
confirmed = false;
|
||||
return;
|
||||
}
|
||||
oncancel?.();
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal bind:open {title} onclose={handleClose}>
|
||||
<p class="confirm-message">{message}</p>
|
||||
{#snippet footer()}
|
||||
<Button variant="ghost" onclick={() => (open = false)}>{cancelLabel}</Button
|
||||
>
|
||||
<Button variant={danger ? 'danger' : 'primary'} onclick={handleConfirm}
|
||||
>{confirmLabel}</Button
|
||||
>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
|
||||
<style>
|
||||
.confirm-message {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,64 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
body?: string;
|
||||
icon?: Snippet;
|
||||
action?: Snippet;
|
||||
}
|
||||
|
||||
let { title, body, icon, action }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="empty-state">
|
||||
{#if icon}
|
||||
<div class="empty-icon">
|
||||
{@render icon()}
|
||||
</div>
|
||||
{/if}
|
||||
<h3 class="empty-title">{title}</h3>
|
||||
{#if body}
|
||||
<p class="empty-body">{body}</p>
|
||||
{/if}
|
||||
{#if action}
|
||||
<div class="empty-action">
|
||||
{@render action()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 40px 24px;
|
||||
text-align: center;
|
||||
background: var(--bg-surface);
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
}
|
||||
.empty-icon {
|
||||
display: flex;
|
||||
margin-bottom: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.empty-title {
|
||||
margin: 0;
|
||||
font-family: var(--font-display);
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.empty-body {
|
||||
margin: 6px 0 0;
|
||||
max-width: 420px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.empty-action {
|
||||
margin-top: 16px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,37 @@
|
||||
<script lang="ts">
|
||||
import { icons, type IconName } from './icons';
|
||||
|
||||
interface Props {
|
||||
name: IconName;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
let { name, size = 18 }: Props = $props();
|
||||
|
||||
const content = $derived(icons[name] ?? '');
|
||||
</script>
|
||||
|
||||
{#if content}
|
||||
<svg
|
||||
class="icon"
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{@html content}
|
||||
</svg>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.icon {
|
||||
display: inline-block;
|
||||
vertical-align: -0.125em;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,230 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
open?: boolean;
|
||||
title?: string;
|
||||
dismissible?: boolean;
|
||||
onclose?: () => void;
|
||||
footer?: Snippet;
|
||||
children: Snippet;
|
||||
}
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
title,
|
||||
dismissible = true,
|
||||
onclose,
|
||||
footer,
|
||||
children,
|
||||
}: Props = $props();
|
||||
|
||||
const FOCUSABLE =
|
||||
'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
||||
|
||||
const titleId = `modal-title-${Math.random().toString(36).slice(2, 9)}`;
|
||||
|
||||
let panel = $state<HTMLDivElement | null>(null);
|
||||
|
||||
function requestClose() {
|
||||
if (!dismissible) return;
|
||||
open = false;
|
||||
}
|
||||
|
||||
function handleKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
requestClose();
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Tab') trapFocus(event);
|
||||
}
|
||||
|
||||
function trapFocus(event: KeyboardEvent) {
|
||||
if (!panel) return;
|
||||
const focusables = Array.from(
|
||||
panel.querySelectorAll<HTMLElement>(FOCUSABLE),
|
||||
).filter((el) => el.getClientRects().length > 0);
|
||||
if (focusables.length === 0) {
|
||||
event.preventDefault();
|
||||
panel.focus();
|
||||
return;
|
||||
}
|
||||
const first = focusables[0];
|
||||
const last = focusables[focusables.length - 1];
|
||||
const active = document.activeElement;
|
||||
const focusInside = panel.contains(active);
|
||||
if (event.shiftKey && (!focusInside || active === first)) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && (!focusInside || active === last)) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function handleBackdropClick(event: MouseEvent) {
|
||||
if (event.target === event.currentTarget) requestClose();
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
|
||||
const invoker = document.activeElement as HTMLElement | null;
|
||||
const previousOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
document.addEventListener('keydown', handleKeydown, true);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
if (!panel || panel.contains(document.activeElement)) return;
|
||||
const first = panel.querySelector<HTMLElement>(FOCUSABLE);
|
||||
(first ?? panel).focus();
|
||||
});
|
||||
|
||||
return () => {
|
||||
document.body.style.overflow = previousOverflow;
|
||||
document.removeEventListener('keydown', handleKeydown, true);
|
||||
if (invoker?.isConnected) invoker.focus();
|
||||
onclose?.();
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if open}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
|
||||
<div class="modal-backdrop" onclick={handleBackdropClick}>
|
||||
<div
|
||||
bind:this={panel}
|
||||
class="modal-panel"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={title ? titleId : undefined}
|
||||
aria-label={title ? undefined : 'Dialog'}
|
||||
tabindex="-1"
|
||||
>
|
||||
{#if title || dismissible}
|
||||
<div class="modal-header">
|
||||
{#if title}
|
||||
<h2 class="modal-title" id={titleId}>{title}</h2>
|
||||
{/if}
|
||||
{#if dismissible}
|
||||
<button
|
||||
type="button"
|
||||
class="modal-close"
|
||||
aria-label="Close dialog"
|
||||
onclick={requestClose}
|
||||
>
|
||||
<Icon name="close" size={16} />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="modal-body">
|
||||
{@render children()}
|
||||
</div>
|
||||
{#if footer}
|
||||
<div class="modal-footer">
|
||||
{@render footer()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 900;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: rgba(5, 5, 8, 0.6);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
animation: modal-fade 150ms ease-out;
|
||||
}
|
||||
.modal-panel {
|
||||
width: min(520px, 100%);
|
||||
max-height: calc(100vh - 96px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);
|
||||
outline: none;
|
||||
animation: modal-rise 180ms ease-out;
|
||||
}
|
||||
.modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 18px 20px 0;
|
||||
}
|
||||
.modal-title {
|
||||
margin: 0;
|
||||
font-family: var(--font-display);
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.modal-close {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
margin-left: auto;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color 150ms ease,
|
||||
color 150ms ease;
|
||||
}
|
||||
.modal-close:hover {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.modal-close:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.modal-body {
|
||||
padding: 16px 20px 20px;
|
||||
overflow-y: auto;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.modal-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 0 20px 20px;
|
||||
}
|
||||
@keyframes modal-fade {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes modal-rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,121 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
value?: number;
|
||||
indeterminate?: boolean;
|
||||
label?: string;
|
||||
size?: 'sm' | 'md';
|
||||
}
|
||||
|
||||
let {
|
||||
value = 0,
|
||||
indeterminate = false,
|
||||
label,
|
||||
size = 'md',
|
||||
}: Props = $props();
|
||||
|
||||
const pct = $derived(Math.round(Math.min(100, Math.max(0, value))));
|
||||
const showMeta = $derived(Boolean(label) || !indeterminate);
|
||||
</script>
|
||||
|
||||
<div class="progress progress-{size}">
|
||||
{#if showMeta}
|
||||
<div class="progress-meta">
|
||||
{#if label}
|
||||
<span class="progress-label">{label}</span>
|
||||
{/if}
|
||||
{#if !indeterminate}
|
||||
<span class="progress-value">{pct}%</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div
|
||||
class="track"
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={indeterminate ? undefined : pct}
|
||||
aria-label={label ?? 'Progress'}
|
||||
>
|
||||
{#if indeterminate}
|
||||
<div class="fill indeterminate"></div>
|
||||
{:else}
|
||||
<div class="fill" style:width={pct + '%'}></div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.progress {
|
||||
width: 100%;
|
||||
}
|
||||
.progress-meta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.progress-label {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.progress-value {
|
||||
margin-left: auto;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.track {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
background: var(--bg-elevated);
|
||||
border-radius: 999px;
|
||||
}
|
||||
.progress-sm .track {
|
||||
height: 4px;
|
||||
}
|
||||
.progress-md .track {
|
||||
height: 6px;
|
||||
}
|
||||
.fill {
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
border-radius: 999px;
|
||||
transition: width 250ms ease;
|
||||
}
|
||||
.fill.indeterminate {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 40%;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
var(--accent) 40%,
|
||||
var(--accent) 60%,
|
||||
transparent
|
||||
);
|
||||
transition: none;
|
||||
animation: progress-slide 1.2s ease-in-out infinite;
|
||||
}
|
||||
@keyframes progress-slide {
|
||||
0% {
|
||||
left: -40%;
|
||||
}
|
||||
100% {
|
||||
left: 100%;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.fill {
|
||||
transition: none;
|
||||
}
|
||||
.fill.indeterminate {
|
||||
animation: none;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
opacity: 0.4;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,263 @@
|
||||
# Calliope UI primitives
|
||||
|
||||
Shared component library for the Calliope UI. Import from `$lib/components/ui/`.
|
||||
Svelte 5 runes mode, TypeScript strict, scoped styles driven by the CSS vars in
|
||||
`src/routes/app.css`. No Tailwind.
|
||||
|
||||
Conventions shared by all primitives:
|
||||
|
||||
- Styling uses the global tokens (`--bg-surface`, `--border`, `--accent`, `--radius-*`, `--space-*`, fonts). Never hardcode hex colors outside this directory.
|
||||
- All interactive primitives expose a `:focus-visible` accent ring. `app.css` also provides a global `:focus-visible` fallback for native elements.
|
||||
- Motion respects `prefers-reduced-motion`: `app.css` kills animation/transition durations globally; components that need a styled static fallback (Skeleton, ProgressBar indeterminate, StatusChip pulse) handle it in their own scoped styles.
|
||||
|
||||
---
|
||||
|
||||
## Button
|
||||
|
||||
`import Button from '$lib/components/ui/Button.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| ---------- | ------------------------------------------------- | ------------- | -------------------------------------------------- |
|
||||
| `variant` | `'primary' \| 'secondary' \| 'ghost' \| 'danger'` | `'secondary'` | primary = `--accent` bg; danger = `--error` tinted |
|
||||
| `size` | `'sm' \| 'md'` | `'md'` | sm = 28px, md = 34px min-height |
|
||||
| `disabled` | `boolean` | `false` | reduced opacity, no pointer events |
|
||||
| `loading` | `boolean` | `false` | inline spinner, disables, width stays stable |
|
||||
| `type` | `'button' \| 'submit' \| 'reset'` | `'button'` | |
|
||||
| `title` | `string` | — | native tooltip |
|
||||
| `onclick` | `(event: MouseEvent) => void` | — | |
|
||||
| `children` | `Snippet` | required | label content |
|
||||
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
import Button from '$lib/components/ui/Button.svelte';
|
||||
let saving = $state(false);
|
||||
</script>
|
||||
|
||||
<Button variant="primary" loading={saving} onclick={() => (saving = true)}
|
||||
>Generate</Button
|
||||
>
|
||||
<Button variant="danger" size="sm" onclick={remove}>Delete</Button>
|
||||
<Button variant="ghost" onclick={cancel}>Cancel</Button>
|
||||
```
|
||||
|
||||
## Card
|
||||
|
||||
`import Card from '$lib/components/ui/Card.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| ----------- | --------- | -------- | ---------------------------------------------------- |
|
||||
| `hoverable` | `boolean` | `false` | border lightens + `translateY(-1px)` on hover |
|
||||
| `title` | `string` | — | renders default header row |
|
||||
| `actions` | `Snippet` | — | right side of the default header row |
|
||||
| `header` | `Snippet` | — | full custom header row (overrides `title`/`actions`) |
|
||||
| `children` | `Snippet` | required | body content |
|
||||
| `class` | `string` | `''` | extra class on the root |
|
||||
|
||||
```svelte
|
||||
<Card title="Renders" hoverable>
|
||||
{#snippet actions()}
|
||||
<Button size="sm" onclick={refresh}>Refresh</Button>
|
||||
{/snippet}
|
||||
<p>Body content here.</p>
|
||||
</Card>
|
||||
```
|
||||
|
||||
## StatusChip
|
||||
|
||||
`import StatusChip from '$lib/components/ui/StatusChip.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| -------- | -------- | -------- | -------------------------------------- |
|
||||
| `status` | `string` | required | matched case-insensitively after trim |
|
||||
| `label` | `string` | — | display text; defaults to raw `status` |
|
||||
|
||||
Status → color mapping (unknown strings fall back to muted and show the raw string):
|
||||
|
||||
| Tone | Color var | Statuses |
|
||||
| ------- | ------------------ | ---------------------------------------------- |
|
||||
| success | `--success` | `ready`, `done`, `completed` |
|
||||
| info | `--info` | `running` (dot pulses), `generating`, `queued` |
|
||||
| muted | `--text-secondary` | `pending`, `idle`, `draft`, + any unknown |
|
||||
| error | `--error` | `failed`, `error` |
|
||||
| warning | `--warning` | `paused` |
|
||||
| accent | `--accent` | `in_progress` |
|
||||
|
||||
```svelte
|
||||
<StatusChip status={job.status} />
|
||||
<StatusChip status="in_progress" label="Rendering" />
|
||||
```
|
||||
|
||||
## ProgressBar
|
||||
|
||||
`import ProgressBar from '$lib/components/ui/ProgressBar.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| --------------- | -------------- | ------- | ----------------------------------------- |
|
||||
| `value` | `number` | `0` | clamped to 0–100 |
|
||||
| `indeterminate` | `boolean` | `false` | sliding accent gradient, no % readout |
|
||||
| `label` | `string` | — | text above the track, also the aria-label |
|
||||
| `size` | `'sm' \| 'md'` | `'md'` | sm = 4px, md = 6px track |
|
||||
|
||||
```svelte
|
||||
<ProgressBar value={job.progress} label={job.name} />
|
||||
<ProgressBar indeterminate label="Connecting" size="sm" />
|
||||
```
|
||||
|
||||
## Skeleton
|
||||
|
||||
`import Skeleton from '$lib/components/ui/Skeleton.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| -------- | --------- | -------- | ------------------------------------------------------- |
|
||||
| `width` | `string` | `'100%'` | any CSS length |
|
||||
| `height` | `string` | `'14px'` | any CSS length |
|
||||
| `circle` | `boolean` | `false` | 50% radius; defaults width to `height` when width unset |
|
||||
|
||||
```svelte
|
||||
<Skeleton width="60%" />
|
||||
<Skeleton height="120px" />
|
||||
<Skeleton circle height="32px" />
|
||||
```
|
||||
|
||||
## Modal
|
||||
|
||||
`import Modal from '$lib/components/ui/Modal.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| ------------- | ------------ | -------- | --------------------------------------------------------------------------- |
|
||||
| `open` | `boolean` | `false` | **bindable** — use `bind:open` |
|
||||
| `title` | `string` | — | wired to `aria-labelledby`; falls back to `aria-label="Dialog"` |
|
||||
| `dismissible` | `boolean` | `true` | gates Esc, backdrop click, and the close button |
|
||||
| `onclose` | `() => void` | — | fires once when the modal closes (any cause, incl. external `open = false`) |
|
||||
| `footer` | `Snippet` | — | right-aligned action row |
|
||||
| `children` | `Snippet` | required | body content |
|
||||
|
||||
Behavior: Esc and backdrop click close when dismissible; focus is trapped while
|
||||
open; initial focus goes to the first focusable element (or the panel); focus is
|
||||
restored to the invoking element on close; body scroll is locked while open;
|
||||
`role="dialog" aria-modal="true"`; backdrop blur + fade, panel rises 8px.
|
||||
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
import Modal from '$lib/components/ui/Modal.svelte';
|
||||
import Button from '$lib/components/ui/Button.svelte';
|
||||
let open = $state(false);
|
||||
</script>
|
||||
|
||||
<Button variant="primary" onclick={() => (open = true)}>Open</Button>
|
||||
<Modal bind:open title="Render settings" onclose={() => console.log('closed')}>
|
||||
<p>Body content.</p>
|
||||
{#snippet footer()}
|
||||
<Button variant="ghost" onclick={() => (open = false)}>Cancel</Button>
|
||||
<Button variant="primary" onclick={save}>Save</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
```
|
||||
|
||||
## ConfirmDialog
|
||||
|
||||
`import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte';` (built on Modal)
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| -------------- | ------------ | ----------- | ------------------------------------------------------------------- |
|
||||
| `open` | `boolean` | `false` | **bindable** — use `bind:open` |
|
||||
| `title` | `string` | required | |
|
||||
| `message` | `string` | required | body copy |
|
||||
| `confirmLabel` | `string` | `'Confirm'` | |
|
||||
| `cancelLabel` | `string` | `'Cancel'` | |
|
||||
| `danger` | `boolean` | `false` | confirm button uses the danger variant |
|
||||
| `onconfirm` | `() => void` | required | fires once, after the dialog closes |
|
||||
| `oncancel` | `() => void` | — | fires when closed without confirming (Esc, backdrop, cancel button) |
|
||||
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte';
|
||||
let confirmDelete = $state(false);
|
||||
</script>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:open={confirmDelete}
|
||||
title="Delete asset?"
|
||||
message="This removes the asset and its generated files. This cannot be undone."
|
||||
confirmLabel="Delete"
|
||||
danger
|
||||
onconfirm={deleteAsset}
|
||||
oncancel={() => console.log('kept')}
|
||||
/>
|
||||
```
|
||||
|
||||
## EmptyState
|
||||
|
||||
`import EmptyState from '$lib/components/ui/EmptyState.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| -------- | --------- | -------- | -------------------------------------- |
|
||||
| `title` | `string` | required | |
|
||||
| `body` | `string` | — | supporting copy, max-width constrained |
|
||||
| `icon` | `Snippet` | — | rendered muted above the title |
|
||||
| `action` | `Snippet` | — | CTA row below the body |
|
||||
|
||||
```svelte
|
||||
<EmptyState
|
||||
title="No assets yet"
|
||||
body="Create a character or location to start generating."
|
||||
>
|
||||
{#snippet icon()}
|
||||
<Icon name="assets" size={28} />
|
||||
{/snippet}
|
||||
{#snippet action()}
|
||||
<Button variant="primary" onclick={addAsset}>New asset</Button>
|
||||
{/snippet}
|
||||
</EmptyState>
|
||||
```
|
||||
|
||||
## Spinner
|
||||
|
||||
`import Spinner from '$lib/components/ui/Spinner.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| ------ | ---------------------- | ------- | ------------------------------- |
|
||||
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | sm = 14px, md = 18px, lg = 28px |
|
||||
|
||||
`role="status"` with an sr-only "Loading". Colors can be overridden from a parent
|
||||
via the `--spinner-track` / `--spinner-arc` CSS vars (Button uses this on
|
||||
primary/danger).
|
||||
|
||||
```svelte
|
||||
<Spinner size="sm" />
|
||||
```
|
||||
|
||||
## Icon
|
||||
|
||||
`import Icon from '$lib/components/ui/Icon.svelte';`
|
||||
|
||||
| Prop | Type | Default | Notes |
|
||||
| ------ | ---------- | -------- | --------------------------------------------------------- |
|
||||
| `name` | `IconName` | required | union type from `icons.ts` — autocomplete lists all names |
|
||||
| `size` | `number` | `18` | px, square |
|
||||
|
||||
Stroke-based inline SVG (1.5px stroke, `currentColor`), inherits text color.
|
||||
`aria-hidden` — when an icon is the only content of a control, put an
|
||||
`aria-label` on the control itself. Use these instead of emoji everywhere.
|
||||
|
||||
Icon names (`import { icons, type IconName } from '$lib/components/ui/icons';`):
|
||||
|
||||
- Navigation: `home`, `story`, `assets`, `script`, `video`, `queue`, `settings`, `playground`
|
||||
- Actions: `plus`, `trash`, `edit`, `retry`, `close`, `download`, `upload`, `search`, `external-link`, `zoom-in`
|
||||
- Media transport: `play`, `pause`, `stop`
|
||||
- Status: `check`, `alert`, `info`, `clock`, `sparkle`
|
||||
- Media: `image`, `folder`, `film`, `music`
|
||||
- Chevrons: `chevron-left`, `chevron-right`, `chevron-up`, `chevron-down`
|
||||
- Misc: `drag`
|
||||
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
</script>
|
||||
|
||||
<Icon name="sparkle" />
|
||||
<Icon name="play" size={24} />
|
||||
<Button variant="ghost" title="Settings" aria-label="Settings"
|
||||
><Icon name="settings" /></Button
|
||||
>
|
||||
```
|
||||
@@ -0,0 +1,54 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
width?: string;
|
||||
height?: string;
|
||||
circle?: boolean;
|
||||
}
|
||||
|
||||
let { width = '100%', height = '14px', circle = false }: Props = $props();
|
||||
|
||||
const resolvedWidth = $derived(circle && width === '100%' ? height : width);
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="skeleton"
|
||||
class:circle
|
||||
style:width={resolvedWidth}
|
||||
style:height
|
||||
aria-hidden="true"
|
||||
></div>
|
||||
|
||||
<style>
|
||||
.skeleton {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: var(--bg-elevated);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
.skeleton.circle {
|
||||
border-radius: 50%;
|
||||
}
|
||||
.skeleton::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
rgba(255, 255, 255, 0.06),
|
||||
transparent
|
||||
);
|
||||
transform: translateX(-100%);
|
||||
animation: skeleton-shimmer 1.6s ease-in-out infinite;
|
||||
}
|
||||
@keyframes skeleton-shimmer {
|
||||
to {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.skeleton::after {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,59 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
}
|
||||
|
||||
let { size = 'md' }: Props = $props();
|
||||
</script>
|
||||
|
||||
<span class="spinner spinner-{size}" role="status">
|
||||
<span class="sr-only">Loading</span>
|
||||
</span>
|
||||
|
||||
<style>
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
flex-shrink: 0;
|
||||
border-radius: 50%;
|
||||
border-style: solid;
|
||||
border-color: var(--spinner-track, var(--bg-elevated));
|
||||
border-top-color: var(--spinner-arc, var(--accent));
|
||||
animation: spin 0.7s linear infinite;
|
||||
}
|
||||
.spinner-sm {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-width: 2px;
|
||||
}
|
||||
.spinner-md {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-width: 2px;
|
||||
}
|
||||
.spinner-lg {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-width: 3px;
|
||||
}
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.spinner {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user