From 34487703b461c941be7d39748547ceb153b2a5b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stef=C3=A1n=20Einarsson?= Date: Tue, 25 Aug 2026 21:13:13 +0200 Subject: [PATCH 1/5] Allow multiple LLM endpoints in Settings and pick which one is active. --- README.md | 8 +- calliope-backend/src/calliope/config.py | 147 +++++++++ .../src/calliope/routers/settings.py | 36 ++- calliope-web/src/lib/api.ts | 10 + .../components/settings/SettingsNav.svelte | 2 +- calliope-web/src/routes/settings/+page.svelte | 301 +++++++++++++++--- 6 files changed, 463 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 0b200324..1725f7c8 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ python -m venv .venv .venv\Scripts\python -m calliope.main --host 127.0.0.1 --port 8247 ``` -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. +Optionally copy `calliope_config.example.json` to `calliope_config.json` and edit it before starting (LLM endpoints, ComfyUI URL). You can also configure everything later in the app's **Settings** page. Never commit `calliope_config.json` — it stores your API keys. **2. Frontend (SvelteKit)** @@ -46,11 +46,15 @@ Open `http://127.0.0.1:5173`. The dev server proxies `/api` to the backend on `1 Open the app, go to **Settings**, and set: -1. **LLM** — base URL, model name, and API key of your OpenAI-compatible endpoint +1. **LLM** — add one or more OpenAI-compatible endpoints (base URL, model, API key) and mark which one is **Active** 2. **ComfyUI** — the base URL of your running ComfyUI (e.g. `http://127.0.0.1:8188`) Leave **Dry-run** off — it is meant for testing and produces placeholder results instead of real generations. +### LLM endpoints + +**Settings → LLM** stores a list of OpenAI-compatible chat endpoints (local or hosted). Add as many as you want — for example a local Ollama model and a cloud API — then select **Use this** on the one Calliope should use for story, script, and the agent. Only the **Active** endpoint is used until you switch and save. API keys stay in `calliope_config.json`, not in the project database. + ### Queue settings In **Settings → Queue** you can tune how the worker talks to ComfyUI: diff --git a/calliope-backend/src/calliope/config.py b/calliope-backend/src/calliope/config.py index 75cceff2..fedb32a8 100644 --- a/calliope-backend/src/calliope/config.py +++ b/calliope-backend/src/calliope/config.py @@ -3,9 +3,11 @@ from __future__ import annotations import json import sys import tempfile +import uuid from pathlib import Path from typing import Any +from pydantic import Field from pydantic_settings import BaseSettings, SettingsConfigDict @@ -99,6 +101,10 @@ class Settings(BaseSettings): llm_base_url: str = "http://127.0.0.1:11434/v1" llm_model: str = "llama3.2" llm_api_key: str | None = None + # Named OpenAI-compatible endpoints. `llm_*` above always mirror the active + # profile so LLMClient and env overrides keep working. + llm_profiles: list[dict[str, Any]] = Field(default_factory=list) + llm_active_id: 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. @@ -122,8 +128,144 @@ class Settings(BaseSettings): self.data_dir.mkdir(parents=True, exist_ok=True) self.assets_dir.mkdir(parents=True, exist_ok=True) + def ensure_llm_profiles(self) -> bool: + """Guarantee at least one profile and that llm_* match the active one. + + Returns True when the in-memory list was created or repaired (caller + may persist). Existing configs with only llm_base_url/model/key are + migrated into a single named profile. + """ + migrated = False + raw_list = self.llm_profiles if isinstance(self.llm_profiles, list) else [] + if not raw_list: + pid = str(uuid.uuid4()) + self.llm_profiles = [ + { + "id": pid, + "name": self.llm_model or "Default", + "base_url": self.llm_base_url, + "model": self.llm_model, + "api_key": self.llm_api_key, + } + ] + self.llm_active_id = pid + migrated = True + else: + normalized: list[dict[str, Any]] = [] + for item in raw_list: + if not isinstance(item, dict): + continue + pid = str(item.get("id") or uuid.uuid4()) + model = str(item.get("model") or self.llm_model or "llama3.2").strip() + name = str(item.get("name") or model or "LLM").strip() + base_url = str(item.get("base_url") or self.llm_base_url).strip() + key = item.get("api_key") + if not isinstance(key, str) or not key.strip(): + key = None + normalized.append( + { + "id": pid, + "name": name or model or "LLM", + "base_url": base_url or self.llm_base_url, + "model": model or "llama3.2", + "api_key": key, + } + ) + if not normalized: + self.llm_profiles = [] + return self.ensure_llm_profiles() + self.llm_profiles = normalized + ids = {p["id"] for p in normalized} + if self.llm_active_id not in ids: + self.llm_active_id = normalized[0]["id"] + migrated = True + self.apply_active_llm() + return migrated + + def apply_active_llm(self) -> None: + """Copy the active profile onto llm_base_url / llm_model / llm_api_key.""" + profiles = self.llm_profiles if isinstance(self.llm_profiles, list) else [] + profile = next((p for p in profiles if p.get("id") == self.llm_active_id), None) + if profile is None and profiles: + profile = profiles[0] + self.llm_active_id = str(profile.get("id") or "") + if profile is None: + return + if profile.get("base_url"): + self.llm_base_url = str(profile["base_url"]) + if profile.get("model"): + self.llm_model = str(profile["model"]) + self.llm_api_key = profile.get("api_key") if isinstance(profile.get("api_key"), str) else None + + def replace_llm_profiles(self, incoming: list[dict[str, Any]]) -> None: + """Replace the profile list, preserving secrets unless a new key is sent.""" + existing = { + str(p["id"]): p + for p in (self.llm_profiles or []) + if isinstance(p, dict) and p.get("id") + } + new_list: list[dict[str, Any]] = [] + for raw in incoming: + if not isinstance(raw, dict): + continue + pid = str(raw["id"]) if raw.get("id") else str(uuid.uuid4()) + old = existing.get(pid, {}) + model = str(raw.get("model") or old.get("model") or self.llm_model or "llama3.2").strip() + name = str(raw.get("name") or old.get("name") or model or "LLM").strip() + base_url = str(raw.get("base_url") or old.get("base_url") or self.llm_base_url or "").strip() + api_key = old.get("api_key") if isinstance(old.get("api_key"), str) else None + incoming_key = raw.get("api_key") + if isinstance(incoming_key, str) and incoming_key.strip(): + api_key = incoming_key.strip() + new_list.append( + { + "id": pid, + "name": name or model or "LLM", + "base_url": base_url or self.llm_base_url, + "model": model or "llama3.2", + "api_key": api_key, + } + ) + if not new_list: + raise ValueError("At least one LLM is required") + self.llm_profiles = new_list + ids = {p["id"] for p in new_list} + if self.llm_active_id not in ids: + self.llm_active_id = new_list[0]["id"] + self.apply_active_llm() + + def sync_legacy_llm_into_active(self) -> None: + """Write current llm_* fields onto the active profile (legacy PATCH).""" + base_url = self.llm_base_url + model = self.llm_model + api_key = self.llm_api_key + self.ensure_llm_profiles() + for profile in self.llm_profiles: + if profile.get("id") == self.llm_active_id: + profile["base_url"] = base_url + profile["model"] = model + profile["api_key"] = api_key + if not str(profile.get("name") or "").strip(): + profile["name"] = model + break + self.apply_active_llm() + + def _public_llm_profiles(self) -> list[dict[str, Any]]: + self.ensure_llm_profiles() + return [ + { + "id": p["id"], + "name": p["name"], + "base_url": p["base_url"], + "model": p["model"], + "api_key": bool(p.get("api_key")), + } + for p in self.llm_profiles + ] + def to_public_dict(self) -> dict[str, Any]: """Return settings that are safe to expose to the frontend.""" + profiles = self._public_llm_profiles() return { "host": self.host, "port": self.port, @@ -133,6 +275,8 @@ class Settings(BaseSettings): "llm_base_url": self.llm_base_url, "llm_model": self.llm_model, "llm_api_key": bool(self.llm_api_key), + "llm_profiles": profiles, + "llm_active_id": self.llm_active_id, "comfyui_base_url": self.comfyui_base_url, "queue_concurrency": self.queue_concurrency, "queue_poll_interval_sec": self.queue_poll_interval_sec, @@ -183,6 +327,7 @@ class Settings(BaseSettings): self._apply_storage_paths(data_dir, assets_dir) self.dry_run = bool(data.get("dry_run", False)) self.ensure_storage_dirs() + profiles_migrated = self.ensure_llm_profiles() # 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( @@ -211,6 +356,8 @@ class Settings(BaseSettings): "llm_base_url": self.llm_base_url, "llm_model": self.llm_model, "llm_api_key": self.llm_api_key, + "llm_profiles": self.llm_profiles, + "llm_active_id": self.llm_active_id, "comfyui_base_url": self.comfyui_base_url, "queue_concurrency": self.queue_concurrency, "queue_poll_interval_sec": self.queue_poll_interval_sec, diff --git a/calliope-backend/src/calliope/routers/settings.py b/calliope-backend/src/calliope/routers/settings.py index c472aabe..a5370062 100644 --- a/calliope-backend/src/calliope/routers/settings.py +++ b/calliope-backend/src/calliope/routers/settings.py @@ -2,18 +2,30 @@ from __future__ import annotations from typing import Any -from fastapi import APIRouter +from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from calliope.config import normalize_path, settings router = APIRouter() +_LEGACY_LLM_KEYS = {"llm_base_url", "llm_model", "llm_api_key"} + + +class LlmProfileIn(BaseModel): + id: str | None = None + name: str | None = None + base_url: str | None = None + model: str | None = None + api_key: str | None = None + class SettingsUpdate(BaseModel): llm_base_url: str | None = None llm_model: str | None = None llm_api_key: str | None = None + llm_profiles: list[LlmProfileIn] | None = None + llm_active_id: str | None = None comfyui_base_url: str | None = None data_dir: str | None = None assets_dir: str | None = None @@ -34,6 +46,9 @@ async def get_settings() -> dict[str, Any]: @router.post("") async def update_settings(payload: SettingsUpdate) -> dict[str, Any]: data = payload.model_dump(exclude_unset=True) + profiles_in = data.pop("llm_profiles", None) + active_in = data.pop("llm_active_id", None) + legacy_llm = {k: data.pop(k) for k in list(data) if k in _LEGACY_LLM_KEYS} for key, value in data.items(): if key in {"data_dir", "assets_dir"}: @@ -46,5 +61,24 @@ async def update_settings(payload: SettingsUpdate) -> dict[str, Any]: continue setattr(settings, key, value) + if profiles_in is not None: + try: + settings.replace_llm_profiles(profiles_in) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + if active_in is not None: + settings.ensure_llm_profiles() + ids = {p["id"] for p in settings.llm_profiles} + if active_in not in ids: + raise HTTPException(status_code=400, detail="Unknown LLM profile") + settings.llm_active_id = active_in + settings.apply_active_llm() + + if legacy_llm: + for key, value in legacy_llm.items(): + setattr(settings, key, value) + settings.sync_legacy_llm_into_active() + settings.save_config_file() return settings.to_public_dict() diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts index 577f2e92..e5b42a74 100644 --- a/calliope-web/src/lib/api.ts +++ b/calliope-web/src/lib/api.ts @@ -74,6 +74,14 @@ export interface StoryData { items: Item[]; } +export interface LlmProfile { + id: string; + name: string; + base_url: string; + model: string; + api_key: boolean; +} + export interface Settings { host: string; port: number; @@ -83,6 +91,8 @@ export interface Settings { llm_base_url: string; llm_model: string; llm_api_key: boolean; + llm_profiles: LlmProfile[]; + llm_active_id: string | null; comfyui_base_url: string; queue_concurrency: number; queue_poll_interval_sec: number; diff --git a/calliope-web/src/lib/components/settings/SettingsNav.svelte b/calliope-web/src/lib/components/settings/SettingsNav.svelte index 465d268b..c0f785c2 100644 --- a/calliope-web/src/lib/components/settings/SettingsNav.svelte +++ b/calliope-web/src/lib/components/settings/SettingsNav.svelte @@ -2,7 +2,7 @@ import { page } from '$app/stores'; const items = [ - { id: 'llm', href: '/settings?tab=llm', label: 'LLM', blurb: 'Model endpoint' }, + { id: 'llm', href: '/settings?tab=llm', label: 'LLM', blurb: 'Model endpoints' }, { id: 'comfy', href: '/settings?tab=comfy', label: 'ComfyUI', blurb: 'Render farm' }, { id: 'workflows', href: '/settings?tab=workflows', label: 'Workflows', blurb: 'Library' }, { id: 'agent', href: '/settings?tab=agent', label: 'Agent', blurb: 'Hardening rules' }, diff --git a/calliope-web/src/routes/settings/+page.svelte b/calliope-web/src/routes/settings/+page.svelte index 9150691c..8cefac05 100644 --- a/calliope-web/src/routes/settings/+page.svelte +++ b/calliope-web/src/routes/settings/+page.svelte @@ -9,7 +9,7 @@ import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte'; import Icon from '$lib/components/ui/Icon.svelte'; import StatusChip from '$lib/components/ui/StatusChip.svelte'; - import { settings, type Settings } from '$lib/api'; + import { settings, type LlmProfile, type Settings } from '$lib/api'; import { toast } from '$lib/toast'; const client = useQueryClient(); @@ -21,18 +21,18 @@ }); let draft = $state>({}); - let apiKeyDraft = $state(''); + let apiKeyDrafts = $state>({}); // Dirty tracking: any staged field (draft map or a typed API key) counts. const dirtyKeys = $derived([ ...Object.keys(draft).filter((k) => draft[k] !== undefined), - ...(apiKeyDraft ? ['llm_api_key'] : []), + ...(Object.values(apiKeyDrafts).some((v) => v) ? ['llm_api_key'] : []), ]); const isDirty = $derived(dirtyKeys.length > 0); const FIELD_TAB: Record = { - llm_base_url: 'llm', - llm_model: 'llm', + llm_profiles: 'llm', + llm_active_id: 'llm', llm_api_key: 'llm', comfyui_base_url: 'comfy', dry_run: 'comfy', @@ -78,13 +78,22 @@ const err = fieldError(key); if (err) errors[key] = err; } + const profiles = Array.isArray(draft.llm_profiles) ? (draft.llm_profiles as LlmProfile[]) : null; + if (profiles) { + if (profiles.length === 0) errors.llm_profiles = 'Add at least one LLM'; + for (const p of profiles) { + if (!p.name.trim()) errors[`llm_name_${p.id}`] = 'Name is required'; + if (!p.base_url.trim()) errors[`llm_url_${p.id}`] = 'Base URL is required'; + if (!p.model.trim()) errors[`llm_model_${p.id}`] = 'Model is required'; + } + } return errors; }); const isValid = $derived(Object.keys(validationErrors).length === 0); function discardDraft() { draft = {}; - apiKeyDraft = ''; + apiKeyDrafts = {}; } const saveMutation = createMutation({ @@ -92,6 +101,7 @@ const update: Record = {}; for (const [k, v] of Object.entries(draft)) { if (v === undefined) continue; + if (k === 'llm_profiles' || k === 'llm_active_id') continue; // Allow false for dry_run; skip empty optional strings only. // agent_hardening_prompt may be emptied to disable hardening. if (v === '' && k !== 'dry_run' && k !== 'agent_hardening_prompt') continue; @@ -103,7 +113,22 @@ } update[k] = v; } - if (apiKeyDraft) update.llm_api_key = apiKeyDraft; + if (Array.isArray(draft.llm_profiles)) { + update.llm_profiles = (draft.llm_profiles as LlmProfile[]).map((p) => { + const row: Record = { + id: p.id, + name: p.name.trim(), + base_url: p.base_url.trim(), + model: p.model.trim(), + }; + const key = apiKeyDrafts[p.id]; + if (key) row.api_key = key; + return row; + }); + } + if (typeof draft.llm_active_id === 'string' && draft.llm_active_id) { + update.llm_active_id = draft.llm_active_id; + } return settings.update(update); }, onSuccess: (saved) => { @@ -188,6 +213,80 @@ } return s.agent_hardening_prompt ?? ''; } + + function llmProfilesFromSettings(s: Settings): LlmProfile[] { + if (s.llm_profiles?.length) return s.llm_profiles.map((p) => ({ ...p })); + return [ + { + id: s.llm_active_id || 'legacy', + name: s.llm_model || 'Default', + base_url: s.llm_base_url, + model: s.llm_model, + api_key: s.llm_api_key, + }, + ]; + } + + function workingProfiles(s: Settings): LlmProfile[] { + if (Array.isArray(draft.llm_profiles)) return draft.llm_profiles as LlmProfile[]; + return llmProfilesFromSettings(s); + } + + function workingActiveId(s: Settings): string { + if (typeof draft.llm_active_id === 'string' && draft.llm_active_id) { + return draft.llm_active_id; + } + return s.llm_active_id || workingProfiles(s)[0]?.id || ''; + } + + function ensureLlmDraft(s: Settings) { + if (!Array.isArray(draft.llm_profiles)) { + draft.llm_profiles = llmProfilesFromSettings(s); + } + if (typeof draft.llm_active_id !== 'string' || !draft.llm_active_id) { + draft.llm_active_id = s.llm_active_id || (draft.llm_profiles as LlmProfile[])[0]?.id; + } + } + + function patchProfile(s: Settings, id: string, patch: Partial) { + ensureLlmDraft(s); + draft.llm_profiles = (draft.llm_profiles as LlmProfile[]).map((p) => + p.id === id ? { ...p, ...patch } : p, + ); + } + + function setActiveProfile(s: Settings, id: string) { + ensureLlmDraft(s); + draft.llm_active_id = id; + } + + function addProfile(s: Settings) { + ensureLlmDraft(s); + const id = crypto.randomUUID(); + draft.llm_profiles = [ + ...(draft.llm_profiles as LlmProfile[]), + { + id, + name: 'New LLM', + base_url: 'http://127.0.0.1:11434/v1', + model: '', + api_key: false, + }, + ]; + } + + function removeProfile(s: Settings, id: string) { + ensureLlmDraft(s); + const list = (draft.llm_profiles as LlmProfile[]).filter((p) => p.id !== id); + if (list.length === 0) return; + draft.llm_profiles = list; + if (workingActiveId(s) === id) { + draft.llm_active_id = list[0].id; + } + const nextKeys = { ...apiKeyDrafts }; + delete nextKeys[id]; + apiKeyDrafts = nextKeys; + } @@ -210,36 +309,112 @@ {@const s = $settingsQuery.data} {#if tab === 'llm'}
-

LLM

-

OpenAI-compatible chat endpoint used for story and script drafting.

- - - +
+
+

LLM

+

+ OpenAI-compatible chat endpoints used for story, script, and the agent. + Save several, then choose which one Calliope should use. +

+
+ +
+ {#if validationErrors.llm_profiles} +

{validationErrors.llm_profiles}

+ {/if} +
+ {#each workingProfiles(s) as profile (profile.id)} + {@const active = workingActiveId(s) === profile.id} +
+
+ + {#if workingProfiles(s).length > 1} + + {/if} +
+ + + + +
+ {/each} +
{:else if tab === 'comfy'}
@@ -578,4 +753,56 @@ font-size: 12px; color: var(--error); } + .panel-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: var(--space-md); + margin-bottom: var(--space-md); + } + .panel-head h1, + .panel-head .lead { + margin-bottom: 0; + } + .panel-head .lead { + margin-top: 6px; + } + .llm-list { + display: flex; + flex-direction: column; + gap: var(--space-md); + } + .llm-card { + padding: 14px 16px 4px; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: var(--radius-md); + background: rgba(0, 0, 0, 0.18); + } + .llm-card.active { + border-color: rgba(139, 92, 246, 0.45); + background: rgba(139, 92, 246, 0.08); + } + .llm-card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: var(--space-sm); + } + .llm-active { + display: inline-flex; + align-items: center; + gap: 8px; + font-size: 13px; + font-weight: 600; + color: var(--text-secondary); + cursor: pointer; + } + .llm-card.active .llm-active { + color: var(--accent); + } + .llm-active input { + width: auto; + accent-color: var(--accent); + } From 9a28a6d6794a44d0158800c56e4c4f09c6a97a5b Mon Sep 17 00:00:00 2001 From: stefanljosbra Date: Tue, 25 Aug 2026 21:32:31 +0200 Subject: [PATCH 2/5] Update README.md add special section to the extension --- README.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1725f7c8..d26f6705 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,10 @@ +# Extension and changes to the original Benji’s Calliope +## Settings +### LLM endpoints + +**Settings → LLM** stores a list of OpenAI-compatible chat endpoints (local or hosted). Add as many as you want — for example a local Ollama model and a cloud API — then select **Use this** on the one Calliope should use for story, script, and the agent. Only the **Active** endpoint is used until you switch and save. API keys stay in `calliope_config.json`, not in the project database. + +The Original Description: # Calliope Calliope is a local-first story-to-video studio. You type a story idea; Calliope drafts a storyline with beats, characters, and locations, writes a per-scene script, then generates a video clip per scene by driving your own ComfyUI install. When the clips are done, one click stitches them into a finished film with crossfades and matched loudness (ffmpeg). Everything runs on your machine: projects live in SQLite, media lives in folders, and no cloud service is involved beyond the LLM endpoint you point it at. @@ -51,10 +58,6 @@ Open the app, go to **Settings**, and set: Leave **Dry-run** off — it is meant for testing and produces placeholder results instead of real generations. -### LLM endpoints - -**Settings → LLM** stores a list of OpenAI-compatible chat endpoints (local or hosted). Add as many as you want — for example a local Ollama model and a cloud API — then select **Use this** on the one Calliope should use for story, script, and the agent. Only the **Active** endpoint is used until you switch and save. API keys stay in `calliope_config.json`, not in the project database. - ### Queue settings In **Settings → Queue** you can tune how the worker talks to ComfyUI: From 4e480f6195abca8d39fcc457dd4cd4b88f459ba8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stef=C3=A1n=20Einarsson?= Date: Tue, 25 Aug 2026 22:46:46 +0200 Subject: [PATCH 3/5] Add a button on Assets to upload or replace an image --- .../tests/test_playground_uploads.py | 52 +++++++ .../src/lib/components/AssetsStage.svelte | 136 +++++++++++++++++- 2 files changed, 186 insertions(+), 2 deletions(-) diff --git a/calliope-backend/tests/test_playground_uploads.py b/calliope-backend/tests/test_playground_uploads.py index f8cd9598..23c0390f 100644 --- a/calliope-backend/tests/test_playground_uploads.py +++ b/calliope-backend/tests/test_playground_uploads.py @@ -78,3 +78,55 @@ def test_upload_extension_map(): assert _kind_for_ext(".JPG") == "image" # case-insensitive assert _kind_for_ext(".exe") is None assert _kind_for_ext("") is None + + +def test_upload_assigned_to_character_sheet(client): + proj = client.post("/api/projects", json={"title": "Reel"}).json() + char = client.post( + f"/api/projects/{proj['id']}/characters", + json={"name": "Hero"}, + ).json() + up = client.post( + "/api/playground/uploads", + files={"file": ("hero.png", PNG_BYTES, "image/png")}, + ) + assert up.status_code == 200 + path = up.json()["path"] + + patched = client.patch( + f"/api/projects/{proj['id']}/characters/{char['id']}", + json={"sheet_path": path}, + ) + assert patched.status_code == 200 + assert patched.json()["sheet_path"] == path + + loc = client.post( + f"/api/projects/{proj['id']}/locations", + json={"name": "Dock"}, + ).json() + loc_up = client.post( + "/api/playground/uploads", + files={"file": ("dock.png", PNG_BYTES, "image/png")}, + ).json() + loc_patched = client.patch( + f"/api/projects/{proj['id']}/locations/{loc['id']}", + json={"reference_image_path": loc_up["path"]}, + ) + assert loc_patched.status_code == 200 + assert loc_patched.json()["reference_image_path"] == loc_up["path"] + + item = client.post( + f"/api/projects/{proj['id']}/items", + json={"name": "Key"}, + ).json() + item_up = client.post( + "/api/playground/uploads", + files={"file": ("key.png", PNG_BYTES, "image/png")}, + ).json() + item_patched = client.patch( + f"/api/projects/{proj['id']}/items/{item['id']}", + json={"reference_image_path": item_up["path"]}, + ) + assert item_patched.status_code == 200 + assert item_patched.json()["reference_image_path"] == item_up["path"] + diff --git a/calliope-web/src/lib/components/AssetsStage.svelte b/calliope-web/src/lib/components/AssetsStage.svelte index fc39a7f2..5a7531ea 100644 --- a/calliope-web/src/lib/components/AssetsStage.svelte +++ b/calliope-web/src/lib/components/AssetsStage.svelte @@ -5,6 +5,7 @@ import { assetUrl, jobsApi, + playgroundApi, projects, workflows, type Character, @@ -72,6 +73,9 @@ type DeleteTarget = { kind: 'character' | 'location' | 'item'; id: number; name: string }; let deleteTarget = $state(null); let deleteOpen = $state(false); + let fileInput: HTMLInputElement | null = $state(null); + let uploadTarget = $state(null); + let uploadingKey = $state(null); const assetsQuery = createQuery( toStore(() => ({ @@ -502,14 +506,73 @@ function goToStory() { goto('?stage=story', { keepFocus: true, noScroll: true }); } + + function uploadKey(kind: DeleteTarget['kind'], id: number) { + if (kind === 'character') return charKey(id); + if (kind === 'location') return locKey(id); + return itemKey(id); + } + + function openOwnImage(target: DeleteTarget) { + uploadTarget = target; + fileInput?.click(); + } + + async function onOwnImageChosen(e: Event) { + const input = e.currentTarget as HTMLInputElement; + const file = input.files?.[0]; + input.value = ''; + const target = uploadTarget; + uploadTarget = null; + if (!file || !target) return; + if (!file.type.startsWith('image/')) { + toast.error('Please choose an image file (png, jpg, webp, gif)'); + return; + } + const key = uploadKey(target.kind, target.id); + uploadingKey = key; + try { + const uploaded = await playgroundApi.upload(file); + if (uploaded.kind !== 'image') { + toast.error('That file is not an image'); + return; + } + if (target.kind === 'character') { + await projects.updateCharacter(projectId, target.id, { sheet_path: uploaded.path }); + } else if (target.kind === 'location') { + await projects.updateLocation(projectId, target.id, { + reference_image_path: uploaded.path, + }); + } else { + await projects.updateItem(projectId, target.id, { reference_image_path: uploaded.path }); + } + await client.invalidateQueries({ queryKey: ['assets', projectId] }); + await client.invalidateQueries({ queryKey: ['project', projectId] }); + await client.invalidateQueries({ queryKey: ['projects'] }); + toast.success(`Image added for ${target.name}`); + } catch (err) { + toast.error(err instanceof Error ? err.message : 'Could not add image'); + } finally { + uploadingKey = null; + } + } + +

2. Characters, Environments & Items

- Pick a workflow below. Sheet/environment/item prompts use the built-in template by - default — expand Edit prompt only if you need to tweak text. + Pick a workflow below, or upload your own image on any card. Sheet/environment/item + prompts use the built-in template by default — expand Edit prompt only if you need to + tweak text.

@@ -730,6 +793,18 @@ >View {char.name} sheet full size + {#if jstate === 'failed' && job} + {#if jstate === 'failed' && job} + {#if jstate === 'failed' && job}