Calliope 1.1.0: publish backend, web, and example workflows

This commit is contained in:
Benjiyaya
2026-08-19 03:53:29 +08:00
parent 83784ff4dc
commit 170dc0695d
138 changed files with 28423 additions and 3978 deletions
+18
View File
@@ -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>
+8
View File
@@ -0,0 +1,8 @@
import type { HandleClientError } from '@sveltejs/kit';
export const handleError: HandleClientError = ({ error }) => {
console.error(error);
return {
message: 'Something went wrong.',
};
};
+4
View File
@@ -0,0 +1,4 @@
export async function handle({ event, resolve }) {
const response = await resolve(event);
return response;
}
+312
View File
@@ -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) },
),
};
+151
View File
@@ -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}`;
}
+137
View File
@@ -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;
}
+50
View File
@@ -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;
}
+76
View File
@@ -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&#10;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 &amp; 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>
@@ -0,0 +1,106 @@
<script lang="ts">
interface Props {
status: string;
label?: string;
}
let { status, label }: Props = $props();
type Tone = 'success' | 'info' | 'muted' | 'error' | 'warning' | 'accent';
const toneByStatus: Record<string, Tone> = {
ready: 'success',
done: 'success',
completed: 'success',
running: 'info',
generating: 'info',
queued: 'info',
pending: 'muted',
idle: 'muted',
draft: 'muted',
failed: 'error',
error: 'error',
paused: 'warning',
in_progress: 'accent',
};
const key = $derived(status.trim().toLowerCase());
const tone: Tone = $derived(toneByStatus[key] ?? 'muted');
const pulsing = $derived(key === 'running');
</script>
<span class="chip chip-{tone}">
<span class="dot" class:pulsing></span>
<span class="chip-label">{label ?? status}</span>
</span>
<style>
.chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 9px;
border: 1px solid;
border-radius: 999px;
font-size: 10px;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
line-height: 1.4;
white-space: nowrap;
}
.dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
flex-shrink: 0;
}
.chip-success {
color: var(--success);
background: color-mix(in srgb, var(--success) 12%, transparent);
border-color: color-mix(in srgb, var(--success) 35%, transparent);
}
.chip-info {
color: var(--info);
background: color-mix(in srgb, var(--info) 12%, transparent);
border-color: color-mix(in srgb, var(--info) 35%, transparent);
}
.chip-error {
color: var(--error);
background: color-mix(in srgb, var(--error) 12%, transparent);
border-color: color-mix(in srgb, var(--error) 35%, transparent);
}
.chip-warning {
color: var(--warning);
background: color-mix(in srgb, var(--warning) 12%, transparent);
border-color: color-mix(in srgb, var(--warning) 35%, transparent);
}
.chip-accent {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, transparent);
border-color: color-mix(in srgb, var(--accent) 35%, transparent);
}
.chip-muted {
color: var(--text-secondary);
background: rgba(255, 255, 255, 0.04);
border-color: var(--border);
}
.dot.pulsing {
animation: chip-pulse 1.2s ease-in-out infinite;
}
@keyframes chip-pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.35;
}
}
@media (prefers-reduced-motion: reduce) {
.dot.pulsing {
animation: none;
}
}
</style>
@@ -0,0 +1,70 @@
/**
* Inline SVG icon set for Calliope UI primitives.
* 24x24 viewBox, stroke-based (1.5px), currentColor — Lucide-style geometry.
* Each entry is SVG inner content rendered by Icon.svelte via {@html}.
*/
export const icons = {
// Navigation
home: '<path d="m3 10 9-7 9 7v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/><path d="M9 22V12h6v10"/>',
story:
'<path d="M2 4h6a4 4 0 0 1 4 4v12a3 3 0 0 0-3-3H2z"/><path d="M22 4h-6a4 4 0 0 0-4 4v12a3 3 0 0 1 3-3h7z"/>',
assets:
'<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
script:
'<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/>',
video:
'<rect x="2" y="2" width="20" height="20" rx="2.18"/><path d="M7 2v20"/><path d="M17 2v20"/><path d="M2 12h20"/><path d="M2 7h5"/><path d="M2 17h5"/><path d="M17 17h5"/><path d="M17 7h5"/>',
queue:
'<path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/>',
settings:
'<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',
playground:
'<path d="M10 2v7.53a2 2 0 0 1-.21.9L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45L14.21 10.4a2 2 0 0 1-.21-.9V2"/><path d="M8.5 2h7"/><path d="M7 16h10"/>',
// Actions
plus: '<path d="M5 12h14"/><path d="M12 5v14"/>',
trash:
'<path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M10 11v6"/><path d="M14 11v6"/>',
edit: '<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/>',
retry:
'<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M3 21v-5h5"/>',
close: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
download:
'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>',
upload:
'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/>',
search: '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>',
'external-link':
'<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><path d="M15 3h6v6"/><path d="M10 14 21 3"/>',
'zoom-in':
'<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/><path d="M11 8v6"/><path d="M8 11h6"/>',
// Media transport
play: '<polygon points="6 3 20 12 6 21 6 3"/>',
pause:
'<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>',
stop: '<rect x="5" y="5" width="14" height="14" rx="2"/>',
// Status
check: '<path d="M20 6 9 17l-5-5"/>',
alert:
'<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',
info: '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',
clock: '<circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>',
sparkle:
'<path d="M12 3l1.9 5.76a2 2 0 0 0 1.24 1.24L21 12l-5.86 1.9a2 2 0 0 0-1.24 1.24L12 21l-1.9-5.86a2 2 0 0 0-1.24-1.24L3 12l5.86-1.9a2 2 0 0 0 1.24-1.24Z"/>',
// Media
image:
'<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.09-3.09a2 2 0 0 0-2.82 0L6 21"/>',
film: '<rect x="2" y="4" width="20" height="16" rx="2"/><path d="M2 8h20"/><path d="M2 16h20"/><path d="M9 8v8"/><path d="M15 8v8"/>',
music:
'<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>',
folder:
'<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>',
// Chevrons
'chevron-left': '<path d="m15 18-6-6 6-6"/>',
'chevron-right': '<path d="m9 18 6-6-6-6"/>',
'chevron-up': '<path d="m18 15-6-6-6 6"/>',
'chevron-down': '<path d="m6 9 6 6 6-6"/>',
// Misc
drag: '<circle cx="9" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="18" r="1"/>',
} as const satisfies Record<string, string>;
export type IconName = keyof typeof icons;
@@ -0,0 +1,227 @@
<script lang="ts">
/**
* ClipMonitor — 16:9 hero preview for a scene clip.
* Letterboxes video; shows slate / progress / error when no preview.
*/
import { assetUrl } from '$lib/api';
import SafeMedia from '$lib/components/SafeMedia.svelte';
import Button from '$lib/components/ui/Button.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import ProgressBar from '$lib/components/ui/ProgressBar.svelte';
import Spinner from '$lib/components/ui/Spinner.svelte';
interface Progress {
progress?: number;
message?: string;
}
interface Props {
previewPath: string | null;
status: string;
heading: string;
orderIndex: number;
progress?: Progress | null;
error?: string;
errorLong?: boolean;
}
let {
previewPath,
status,
heading,
orderIndex,
progress = null,
error = '',
errorLong = false,
}: Props = $props();
let errorOpen = $state(false);
const previewUrl = $derived(previewPath ? assetUrl(previewPath) : null);
$effect(() => {
void previewPath;
void error;
errorOpen = false;
});
</script>
<div class="monitor">
<div class="frame">
{#if previewUrl}
<SafeMedia class="media" src={previewUrl} kind="video" label="Video unavailable" />
{:else}
<div class="empty">
<span class="slate">#{orderIndex}</span>
<p class="title">{heading || 'Untitled'}</p>
{#if status === 'pending' || status === 'running'}
<div class="busy" aria-busy="true">
<div class="busy-head">
<Spinner size="sm" />
<span>{status === 'running' ? 'Generating…' : 'Queued — waiting for a worker'}</span>
</div>
{#if status === 'running'}
<ProgressBar
size="sm"
value={progress?.progress ?? 0}
indeterminate={progress == null}
label={progress?.message}
/>
{/if}
</div>
{:else if status === 'failed'}
<div class="fail">
<p class="err" class:open={errorOpen}>{error || 'Generation failed'}</p>
{#if errorLong}
<Button variant="ghost" size="sm" onclick={() => (errorOpen = !errorOpen)}>
{errorOpen ? 'Hide details' : 'Show details'}
</Button>
{/if}
</div>
{:else}
<p class="hint">No render yet — describe the shot below and generate.</p>
{/if}
</div>
{/if}
</div>
{#if previewUrl}
<div class="foot">
<a class="dl" href={previewUrl} download>
<Icon name="download" size={14} /> Download clip
</a>
</div>
{/if}
</div>
<style>
.monitor {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-height: 0;
}
.frame {
flex: 1;
min-height: 0;
width: 100%;
height: 100%;
background:
radial-gradient(ellipse at center, rgba(139, 92, 246, 0.08), transparent 55%),
#050508;
border: 1px solid var(--border);
border-radius: var(--radius-md);
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.frame :global(.media) {
width: 100%;
height: 100%;
object-fit: contain;
background: #000;
border: none;
border-radius: 0;
min-height: 0;
}
.empty {
padding: 24px;
text-align: center;
max-width: 42ch;
}
.slate {
display: inline-block;
font-family: var(--font-mono);
font-size: 22px;
font-weight: 700;
color: var(--accent);
margin-bottom: 6px;
}
.title {
margin: 0 0 8px;
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
}
.hint {
margin: 0;
font-size: 13px;
color: var(--text-muted);
line-height: 1.45;
}
.busy {
margin-top: 12px;
display: flex;
flex-direction: column;
gap: 8px;
text-align: left;
}
.busy-head {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
font-size: 13px;
font-weight: 600;
color: var(--warning);
}
.fail {
margin-top: 8px;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.err {
margin: 0;
font-size: 13px;
font-weight: 600;
color: var(--error);
display: -webkit-box;
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-word;
white-space: pre-wrap;
}
.err.open {
display: block;
overflow: visible;
max-height: 160px;
overflow-y: auto;
}
.foot {
display: flex;
justify-content: flex-end;
padding-top: 8px;
flex-shrink: 0;
}
.dl {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
font-weight: 600;
color: var(--text-secondary);
text-decoration: none;
}
.dl:hover {
color: var(--accent);
}
</style>
@@ -0,0 +1,239 @@
<script lang="ts">
/**
* SceneFilmstrip — slim horizontal scene strip under the hero monitor.
* Never sticky; fixed height; keyboard Left/Right/Home/End.
*/
import type { Scene } from '$lib/api';
import Button from '$lib/components/ui/Button.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
type Thumb = { kind: 'image' | 'video'; src: string } | null;
interface Props {
scenes: Scene[];
selectedId: number | null;
statusOf: (scene: Scene) => string;
thumbFor: (scene: Scene) => Thumb;
formatClock: (sec: number) => string;
onSelect: (id: number) => void;
onStep: (dir: -1 | 1) => void;
}
let {
scenes,
selectedId,
statusOf,
thumbFor,
formatClock,
onSelect,
onStep,
}: Props = $props();
const selected = $derived(scenes.find((s) => s.id === selectedId) ?? null);
const selectedIndex = $derived(scenes.findIndex((s) => s.id === selectedId));
function onKeydown(e: KeyboardEvent) {
if (scenes.length === 0) return;
let nextId: number | null = null;
if (e.key === 'ArrowRight') {
const i = selectedIndex < 0 ? 0 : selectedIndex + 1;
nextId = scenes[Math.min(i, scenes.length - 1)]?.id ?? null;
} else if (e.key === 'ArrowLeft') {
const i = selectedIndex < 0 ? 0 : selectedIndex - 1;
nextId = scenes[Math.max(i, 0)]?.id ?? null;
} else if (e.key === 'Home') nextId = scenes[0]?.id ?? null;
else if (e.key === 'End') nextId = scenes[scenes.length - 1]?.id ?? null;
if (nextId == null || nextId === selectedId) return;
e.preventDefault();
onSelect(nextId);
queueMicrotask(() => document.getElementById(`film-clip-${nextId}`)?.focus());
}
</script>
<section class="strip" aria-label="Scene filmstrip">
<div
class="track"
role="listbox"
aria-label="Scene clips"
aria-activedescendant={selectedId != null ? `film-clip-${selectedId}` : undefined}
tabindex="0"
onkeydown={onKeydown}
>
{#each scenes as scene (scene.id)}
{@const st = statusOf(scene)}
{@const thumb = thumbFor(scene)}
<button
type="button"
id="film-clip-{scene.id}"
role="option"
aria-selected={selectedId === scene.id}
class="clip status-{st}"
class:selected={selectedId === scene.id}
onclick={() => onSelect(scene.id)}
title={`${scene.heading || 'Scene'} · ${formatClock(scene.duration_sec || 5)}`}
>
<span class="bar" aria-hidden="true"></span>
<span class="thumb" aria-hidden="true">
{#if thumb?.kind === 'image'}
<img class="thumb-media" src={thumb.src} alt="" loading="lazy" />
{:else if thumb?.kind === 'video'}
<!-- svelte-ignore a11y_media_has_caption -->
<video class="thumb-media" src={thumb.src} muted playsinline preload="metadata"></video>
{:else}
<span class="thumb-slate">#{scene.order_index}</span>
{/if}
</span>
<span class="meta">
<span class="num">#{scene.order_index}</span>
<span class="dur">{formatClock(scene.duration_sec || 5)}</span>
</span>
</button>
{/each}
</div>
<div class="transport">
<Button variant="ghost" size="sm" disabled={!selected} onclick={() => onStep(-1)}>
<Icon name="chevron-left" size={14} /> Prev
</Button>
<span class="pos">
{selected ? `Scene ${selected.order_index} of ${scenes.length}` : '—'}
</span>
<Button variant="ghost" size="sm" disabled={!selected} onclick={() => onStep(1)}>
Next <Icon name="chevron-right" size={14} />
</Button>
</div>
</section>
<style>
.strip {
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px 0 0;
}
.track {
display: flex;
gap: 8px;
overflow-x: auto;
padding: 2px 2px 6px;
min-height: 72px;
scrollbar-width: thin;
}
.clip {
position: relative;
flex: 0 0 96px;
width: 96px;
height: 72px;
padding: 0;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-elevated);
color: var(--text-primary);
cursor: pointer;
overflow: hidden;
display: flex;
flex-direction: column;
transition:
border-color 0.15s,
box-shadow 0.15s;
}
.clip:hover {
border-color: var(--text-muted);
}
.clip.selected {
border-color: var(--accent);
box-shadow: 0 0 0 1px var(--accent);
}
.clip:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.bar {
position: absolute;
inset: 0 0 auto 0;
height: 3px;
z-index: 1;
background: #3f3f46;
}
.clip.status-done .bar {
background: var(--success);
}
.clip.status-running .bar,
.clip.status-pending .bar {
background: var(--warning);
}
.clip.status-failed .bar {
background: var(--error);
}
.thumb {
flex: 1;
min-height: 0;
background: var(--bg-primary);
}
.thumb-media {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
pointer-events: none;
}
.thumb-slate {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
font-family: var(--font-mono);
font-size: 14px;
font-weight: 700;
color: var(--text-muted);
}
.meta {
display: flex;
justify-content: space-between;
align-items: center;
padding: 3px 6px;
background: var(--bg-surface);
border-top: 1px solid var(--border);
flex-shrink: 0;
}
.num {
font-family: var(--font-mono);
font-size: 10px;
font-weight: 700;
color: var(--accent);
}
.dur {
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-muted);
}
.transport {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
}
.pos {
font-size: 12px;
color: var(--text-secondary);
min-width: 12ch;
text-align: center;
}
</style>
@@ -0,0 +1,207 @@
<script lang="ts">
/**
* SceneScriptDrawer — one-line scene meta + expandable script details.
* Default closed so the hero player stays dominant.
*/
import type { Scene } from '$lib/api';
import Icon from '$lib/components/ui/Icon.svelte';
import StatusChip from '$lib/components/ui/StatusChip.svelte';
interface Props {
scene: Scene;
status: string;
formatClock: (sec: number) => string;
}
let { scene, status, formatClock }: Props = $props();
let open = $state(false);
</script>
<div class="meta-wrap">
<div class="row">
<span class="num mono">#{scene.order_index}</span>
<span class="heading" title={scene.heading || 'Untitled scene'}>
{scene.heading || 'Untitled scene'}
</span>
<StatusChip {status} />
<span class="dur mono">{formatClock(scene.duration_sec || 5)}</span>
<button
type="button"
class="script-toggle"
class:open
aria-expanded={open}
onclick={() => (open = !open)}
>
<Icon name={open ? 'chevron-up' : 'chevron-down'} size={12} />
Script
</button>
</div>
{#if open}
<div class="drawer" role="region" aria-label="Scene script">
<div class="block">
<span class="k">Heading</span>
<p>{scene.heading || 'Untitled scene'}</p>
</div>
<div class="block">
<span class="k">Action / script</span>
{#if scene.action?.trim()}
<p>{scene.action}</p>
{:else}
<p class="muted">No action text for this scene.</p>
{/if}
</div>
<div class="block">
<span class="k">Dialog</span>
{#if scene.dialog?.trim()}
<pre class="dialog">{scene.dialog}</pre>
{:else}
<p class="muted">No dialog for this scene.</p>
{/if}
</div>
{#if (scene.characters ?? []).length}
<div class="block">
<span class="k">Characters</span>
<div class="chips">
{#each scene.characters as c}
<span class="chip">{c.name}</span>
{/each}
</div>
</div>
{/if}
</div>
{/if}
</div>
<style>
.meta-wrap {
flex-shrink: 0;
border: 1px solid var(--border);
border-radius: var(--radius-md);
background: var(--bg-surface);
overflow: hidden;
}
.row {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
min-height: 40px;
}
.num {
font-size: 12px;
font-weight: 700;
color: var(--accent);
flex-shrink: 0;
}
.heading {
flex: 1;
min-width: 0;
font-size: 13px;
font-weight: 600;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dur {
font-size: 12px;
color: var(--text-muted);
flex-shrink: 0;
}
.script-toggle {
display: inline-flex;
align-items: center;
gap: 4px;
height: 28px;
padding: 0 10px;
border-radius: 9999px;
border: 1px solid var(--border);
background: var(--bg-elevated);
color: var(--text-secondary);
font-size: 12px;
font-weight: 600;
font-family: var(--font-body);
cursor: pointer;
flex-shrink: 0;
}
.script-toggle:hover,
.script-toggle.open {
color: var(--text-primary);
border-color: var(--text-muted);
}
.drawer {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px 16px;
padding: 12px 14px 14px;
border-top: 1px solid var(--border);
background: var(--bg-primary);
max-height: 200px;
overflow-y: auto;
}
.block .k {
display: block;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--text-muted);
margin-bottom: 4px;
}
.block p {
margin: 0;
font-size: 13px;
line-height: 1.45;
color: var(--text-secondary);
white-space: pre-wrap;
}
.muted {
color: var(--text-muted) !important;
}
.dialog {
margin: 0;
padding: 8px 10px;
background: var(--bg-elevated);
border-radius: var(--radius-sm);
border: 1px solid var(--border);
font-family: var(--font-mono);
font-size: 12px;
line-height: 1.45;
white-space: pre-wrap;
color: var(--text-primary);
max-height: 100px;
overflow-y: auto;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.chip {
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: 999px;
padding: 2px 10px;
font-size: 12px;
color: var(--text-secondary);
}
.mono {
font-family: var(--font-mono);
}
</style>
@@ -0,0 +1,190 @@
<script lang="ts">
/**
* VideoEditWorkspace — modern Edit layout for Project → Video.
* Hero monitor + filmstrip + meta strip + docked Omni composer.
* Does not reuse the old top two-card clip-stage layout.
*/
import type { Scene, Workflow } from '$lib/api';
import OmniComposer from '$lib/components/OmniComposer.svelte';
import ClipMonitor from './ClipMonitor.svelte';
import SceneFilmstrip from './SceneFilmstrip.svelte';
import SceneScriptDrawer from './SceneScriptDrawer.svelte';
type Thumb = { kind: 'image' | 'video'; src: string } | null;
interface AssetOption {
label: string;
path: string;
}
interface Progress {
progress?: number;
message?: string;
}
interface Props {
scenes: Scene[];
selected: Scene;
selectedId: number | null;
status: string;
previewPath: string | null;
progress?: Progress | null;
error?: string;
errorLong?: boolean;
workflow: Workflow | undefined;
workflows: Workflow[];
formValues: Record<string, string | number>;
assetOptions: AssetOption[];
submitting?: boolean;
statusOf: (scene: Scene) => string;
thumbFor: (scene: Scene) => Thumb;
formatClock: (sec: number) => string;
onSelect: (id: number) => void;
onStep: (dir: -1 | 1) => void;
onWorkflowChange: (id: number) => void;
onFormChange?: (values: Record<string, string | number>) => void;
onGenerate: () => void;
}
let {
scenes,
selected,
selectedId,
status,
previewPath,
progress = null,
error = '',
errorLong = false,
workflow,
workflows,
formValues = $bindable(),
assetOptions,
submitting = false,
statusOf,
thumbFor,
formatClock,
onSelect,
onStep,
onWorkflowChange,
onFormChange,
onGenerate,
}: Props = $props();
</script>
<div class="workspace">
<div class="hero">
<ClipMonitor
{previewPath}
{status}
heading={selected.heading || 'Untitled'}
orderIndex={selected.order_index}
{progress}
{error}
{errorLong}
/>
</div>
<SceneFilmstrip
{scenes}
{selectedId}
{statusOf}
{thumbFor}
{formatClock}
{onSelect}
{onStep}
/>
<SceneScriptDrawer scene={selected} {status} {formatClock} />
<div class="composer-dock">
{#if workflow}
{#if assetOptions.length === 0}
<p class="asset-hint">
No image assets yet. Generate character sheets or environments in Assets to pick them as
refs.
</p>
{/if}
<OmniComposer
inputs={workflow.input_schema}
bind:values={formValues}
{workflow}
{workflows}
onWorkflowChange={onWorkflowChange}
{assetOptions}
generateLabel="Generate clip"
{submitting}
onChange={onFormChange}
onSubmit={onGenerate}
/>
{:else}
<div class="no-wf">
<p class="empty-title">No video workflow enabled</p>
<p class="muted">
Enable a video workflow in <a href="/settings?tab=workflows">Settings → Workflows</a>.
</p>
</div>
{/if}
</div>
</div>
<style>
.workspace {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: 10px;
overflow: hidden;
}
.hero {
flex: 1;
min-height: 140px;
display: flex;
align-items: stretch;
justify-content: stretch;
overflow: hidden;
width: 100%;
}
.composer-dock {
flex-shrink: 0;
min-height: 0;
}
.composer-dock :global(.omni-shell) {
flex-shrink: 0;
}
.asset-hint {
margin: 0 0 8px;
font-size: 12px;
color: var(--text-muted);
line-height: 1.4;
}
.no-wf {
padding: 20px;
text-align: center;
border: 1px dashed var(--border);
border-radius: var(--radius-lg);
background: var(--bg-surface);
}
.empty-title {
margin: 0 0 4px;
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
}
.muted {
margin: 0;
font-size: 13px;
color: var(--text-secondary);
}
.muted a {
color: var(--accent);
}
</style>
+81
View File
@@ -0,0 +1,81 @@
/**
* Mirror of calliope.agent.prompts duration helpers — keep in sync.
* Used so Story UI can show the beat budget before drafting.
*/
export function estimateTargetSeconds(targetDuration: string | null | undefined): number {
const text = (targetDuration || '').trim().toLowerCase();
if (!text) return 30;
const scenesM = text.match(/(\d+)\s*scenes?/);
if (scenesM && !/min|sec/.test(text)) {
return Math.max(30, Number(scenesM[1]) * 8);
}
let minutes = 0;
let seconds = 0;
for (const m of text.matchAll(/(\d+(?:\.\d+)?)\s*(min|mins|minutes?|m)\b/g)) {
minutes += Number(m[1]);
}
for (const m of text.matchAll(/(\d+(?:\.\d+)?)\s*(sec|secs|seconds?|s)\b/g)) {
seconds += Number(m[1]);
}
if (minutes || seconds) return Math.max(15, Math.round(minutes * 60 + seconds));
const bare = text.match(/\b(\d+(?:\.\d+)?)\b/);
if (bare) {
const n = Number(bare[1]);
if (text.includes('medium') || n >= 2) {
if (n <= 30) return Math.round(n * 60);
}
if (n <= 180) return Math.round(n);
}
if (text.includes('medium')) return 120;
if (text.includes('short') || text.includes('brief')) return 30;
if (text.includes('long') || text.includes('feature')) return 180;
return 60;
}
/** ~12s narrative weight per beat; capped at 60. */
export function recommendBeatCount(targetDuration: string | null | undefined): number {
const secs = estimateTargetSeconds(targetDuration);
return Math.max(4, Math.min(60, Math.round(secs / 12)));
}
export function recommendSceneCount(targetDuration: string | null | undefined): number {
const secs = estimateTargetSeconds(targetDuration);
return Math.max(4, Math.min(90, Math.round(secs / 7)));
}
/** Same user prompt the backend sends to the LLM (for transparency). */
export function buildStoryDraftPromptPreview(args: {
title: string;
idea: string;
genre: string;
tone: string;
targetDuration: string;
}): string {
const secs = estimateTargetSeconds(args.targetDuration);
const beatN = recommendBeatCount(args.targetDuration);
return `Create a story brief for an AI-generated video.
required_beat_count: ${beatN}
estimated_runtime_seconds: ${secs}
target_duration_text: ${args.targetDuration || 'short (~30 seconds)'}
Title: ${args.title || 'Untitled'}
Idea: ${args.idea || 'No idea provided.'}
Genre: ${args.genre || 'Not specified'}
Tone: ${args.tone || 'cinematic, atmospheric'}
=== HARD CONSTRAINTS (non-negotiable) ===
1. The JSON field "beats" MUST contain EXACTLY ${beatN} objects.
2. order_index must run 1..${beatN} with no gaps.
3. Do NOT compress a long runtime into a handful of beats.
4. ~${secs}s runtime → fine-grained beats (~12s story weight each).
(+ JSON schema for title, logline, beats, characters, locations)
FINAL CHECK: beats.length == ${beatN}`;
}
+67
View File
@@ -0,0 +1,67 @@
export type CalliopeEvent = {
type: string;
data: Record<string, unknown>;
ts: string;
};
/**
* SSE connection lifecycle:
* - `connecting` — first attach attempt in flight
* - `open` — stream established (EventSource.onopen fired)
* - `reconnecting` — stream dropped; the 3s re-attach loop is running
*/
export type EventConnectionState = 'connecting' | 'open' | 'reconnecting';
type Listener = (event: CalliopeEvent) => void;
type StateListener = (state: EventConnectionState) => void;
export function connectEvents(onEvent: Listener, onState?: StateListener): () => void {
let es: EventSource | null = null;
let closed = false;
let firstAttach = true;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
const attach = () => {
if (closed) return;
onState?.(firstAttach ? 'connecting' : 'reconnecting');
firstAttach = false;
es = new EventSource('/api/events');
es.onopen = () => onState?.('open');
const handler = (e: MessageEvent) => {
try {
const parsed = JSON.parse(e.data) as CalliopeEvent;
onEvent(parsed);
} catch {
/* ignore */
}
};
// Listen to named events + default message
[
'agent.thinking',
'job.created',
'job.started',
'job.progress',
'job.completed',
'job.failed',
'job.deleted',
'asset.ready',
'story.ready',
].forEach((name) => es!.addEventListener(name, handler as EventListener));
es.onmessage = handler;
es.onerror = () => {
onState?.('reconnecting');
es?.close();
if (!closed) {
reconnectTimer = setTimeout(attach, 3000);
}
};
};
attach();
return () => {
closed = true;
if (reconnectTimer) clearTimeout(reconnectTimer);
es?.close();
};
}
+200
View File
@@ -0,0 +1,200 @@
import { SvelteMap } from 'svelte/reactivity';
import type { CalliopeEvent } from './events';
/**
* Live per-job render progress, fed by the `/api/events` SSE stream.
*
* Backend reality (see calliope-backend/src/calliope/queue/worker.py):
* - `job.created` { job_id, kind, ... }
* - `job.started` { job_id, kind, message } ← message = job label
* - `job.progress` { prompt_id, message } ← NO job_id, NO percent
* - `job.completed` { job_id, outputs, message }
* - `job.failed` { job_id, error, message }
* - `job.deleted` { job_id }
*
* Because progress ticks carry neither a job id nor a percent, the store:
* 1. Attributes a tick to the currently running job (tracked from job.started;
* explicit `job_id` wins if a future backend sends one).
* 2. Honors a numeric payload field (`progress` / `percent` / `value`, 0–1 or
* 0–100) when present, otherwise synthesizes an asymptotic value that
* approaches TICK_CAP but never reaches it — only job.completed sets 100.
*
* Entries for completed jobs are kept briefly (progress pinned to 100) and for
* failed jobs a bit longer (last known progress + error), then removed, so the
* UI can flash the final state before the jobs query becomes the source of
* truth again. Consumers should only render the live bar while the job's
* queried status is still pending/running.
*/
export type JobProgressEntry = {
/** 0–100. Reaches 100 only via job.completed. */
progress: number;
/** Latest human-readable status line from the worker. */
message?: string;
/** True once the job reached a terminal state (done/failed). */
final: boolean;
/** Terminal status when final: 'done' | 'failed'. */
status?: 'done' | 'failed';
/** Last update, ms epoch. */
updatedAt: number;
};
/** Synthesized ticks never exceed this; only job.completed reports 100. */
const TICK_CAP = 95;
/** How long terminal entries linger so the UI can show the final state. */
const DONE_KEEP_MS = 6_000;
const FAILED_KEEP_MS = 10_000;
function num(v: unknown): number | null {
if (typeof v === 'number' && Number.isFinite(v)) return v;
if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return Number(v);
return null;
}
function str(v: unknown): string {
return typeof v === 'string' ? v : '';
}
/** Numeric progress from a payload, normalized to 0–100 (capped below 100). */
function progressValue(d: Record<string, unknown>): number | null {
const raw = num(d.progress ?? d.percent ?? d.value);
if (raw == null) return null;
const pct = raw <= 1 ? raw * 100 : raw;
return Math.min(TICK_CAP, Math.max(0, pct));
}
class JobProgressStore {
private map = new SvelteMap<number, JobProgressEntry>();
/** Jobs seen via job.started and not yet terminal — tick attribution. */
private running = new Set<number>();
private lastStarted: number | null = null;
private cleanupTimers = new Map<number, ReturnType<typeof setTimeout>>();
/** Live entry for a job id (tracked — safe inside $derived / markup). */
get(jobId: number | null | undefined): JobProgressEntry | undefined {
if (jobId == null) return undefined;
return this.map.get(jobId);
}
handleEvent(ev: CalliopeEvent): void {
const d = ev.data ?? {};
switch (ev.type) {
case 'job.created': {
const id = num(d.job_id);
if (id == null) return;
this.cancelCleanup(id);
this.map.set(id, {
progress: 0,
message: str(d.message) || 'Queued',
final: false,
updatedAt: Date.now(),
});
break;
}
case 'job.started': {
const id = num(d.job_id);
if (id == null) return;
this.cancelCleanup(id);
this.running.add(id);
this.lastStarted = id;
const prev = this.map.get(id);
this.map.set(id, {
progress: prev?.progress ?? 0,
message: str(d.message) || 'Running',
final: false,
updatedAt: Date.now(),
});
break;
}
case 'job.progress': {
const id = this.resolveJobId(d);
if (id == null) return;
const prev = this.map.get(id);
const progress = progressValue(d) ?? this.synthesize(prev?.progress ?? 0);
this.map.set(id, {
progress,
message: str(d.message) || prev?.message,
final: false,
updatedAt: Date.now(),
});
break;
}
case 'job.completed':
case 'job.failed': {
const id = num(d.job_id);
if (id == null) return;
this.running.delete(id);
if (this.lastStarted === id) this.lastStarted = null;
const failed = ev.type === 'job.failed';
const prev = this.map.get(id);
this.map.set(id, {
progress: failed ? (prev?.progress ?? 0) : 100,
message: str(d.error) || str(d.message) || prev?.message,
final: true,
status: failed ? 'failed' : 'done',
updatedAt: Date.now(),
});
this.scheduleCleanup(id, failed ? FAILED_KEEP_MS : DONE_KEEP_MS);
break;
}
case 'job.deleted': {
const id = num(d.job_id);
if (id == null) return;
this.running.delete(id);
if (this.lastStarted === id) this.lastStarted = null;
this.cancelCleanup(id);
this.map.delete(id);
break;
}
}
}
/**
* Today's job.progress payload is {prompt_id, message} with no job id.
* Attribute the tick to the only running job, else the most recently
* started one. Explicit job_id wins when a backend sends it.
*/
private resolveJobId(d: Record<string, unknown>): number | null {
const explicit = num(d.job_id);
if (explicit != null) return explicit;
if (this.running.size === 1) return [...this.running][0];
if (this.lastStarted != null && this.running.has(this.lastStarted)) return this.lastStarted;
return null;
}
/** Asymptotic approach to TICK_CAP — feels live, never falsely completes. */
private synthesize(prev: number): number {
return prev + (TICK_CAP - prev) * 0.08;
}
private scheduleCleanup(jobId: number, delayMs: number): void {
this.cancelCleanup(jobId);
this.cleanupTimers.set(
jobId,
setTimeout(() => {
this.cleanupTimers.delete(jobId);
this.map.delete(jobId);
}, delayMs),
);
}
private cancelCleanup(jobId: number): void {
const timer = this.cleanupTimers.get(jobId);
if (timer) {
clearTimeout(timer);
this.cleanupTimers.delete(jobId);
}
}
}
export const jobProgress = new JobProgressStore();
/** Feed one SSE event into the store. Safe to call for every event type. */
export function handleJobEvent(ev: CalliopeEvent): void {
jobProgress.handleEvent(ev);
}
/** Read the live entry for a job id (reactive via SvelteMap). */
export function progressFor(jobId: number | null | undefined): JobProgressEntry | undefined {
return jobProgress.get(jobId);
}
+70
View File
@@ -0,0 +1,70 @@
/**
* Image prompt templates — keep in sync with calliope.agent.prompts
* (character_sheet_prompt / character_portrait_prompt / location_reference_prompt).
*
* These are the prompts the user sees and edits. Generation must not invent a hidden string.
*/
export type CharacterPromptFields = {
name?: string | null;
role?: string | null;
age?: string | null;
appearance?: string | null;
personality?: string | null;
};
export type LocationPromptFields = {
name?: string | null;
description?: string | null;
};
export function characterSheetTemplate(c: CharacterPromptFields): string {
const name = (c.name || 'Unnamed').trim();
const role = (c.role || 'character').trim();
const age = (c.age || 'unspecified age').trim();
const appearance = (c.appearance || 'no appearance notes yet').trim();
const personality = (c.personality || '').trim();
const personalityLine = personality
? `Personality cues (visual only): ${personality}\n`
: '';
return (
`CHARACTER SHEET — ${name}\n` +
`Role: ${role}. Age: ${age}.\n` +
`Appearance: ${appearance}\n` +
personalityLine +
`\n` +
`Layout: single cinematic character reference sheet on a clean neutral backdrop, ` +
`multiple panels — front full body, side full body, back full body, three-quarter, ` +
`and a head close-up. Same face, hair, body proportions, and outfit in every panel. ` +
`Neutral standing pose, even studio lighting, high detail, no text watermarks, ` +
`no extra characters.`
);
}
export function characterPortraitTemplate(c: CharacterPromptFields): string {
const name = (c.name || 'Unnamed').trim();
const role = (c.role || 'character').trim();
const age = (c.age || 'unspecified age').trim();
const appearance = (c.appearance || 'no appearance notes yet').trim();
return (
`CHARACTER PORTRAIT — ${name}\n` +
`Role: ${role}. Age: ${age}.\n` +
`Appearance: ${appearance}\n` +
`\n` +
`Shot: cinematic head-and-shoulders portrait, eye-level, soft key light, ` +
`shallow depth of field, sharp facial features, consistent wardrobe collar/shoulders, ` +
`plain muted background, photoreal or high-end concept art, no text.`
);
}
export function locationReferenceTemplate(loc: LocationPromptFields): string {
const name = (loc.name || 'Unnamed place').trim();
const description = (loc.description || 'no description yet').trim();
return (
`ENVIRONMENT REFERENCE — ${name}\n` +
`Description: ${description}\n` +
`\n` +
`Shot: wide establishing concept art, cinematic atmosphere, clear readable space ` +
`for characters to stand in, consistent lighting and materials, no people, no text.`
);
}
+92
View File
@@ -0,0 +1,92 @@
export type ToastKind = 'success' | 'error' | 'info';
export type Toast = {
id: number;
message: string;
kind: ToastKind;
/** Auto-dismiss delay in ms. 0 = sticky until dismissed. */
duration: number;
};
type Listener = (toasts: Toast[]) => void;
const DEFAULT_DURATION = 3200;
let seq = 0;
let toasts: Toast[] = [];
const listeners = new Set<Listener>();
type TimerState = {
remaining: number;
startedAt: number;
handle: ReturnType<typeof setTimeout>;
};
const timers = new Map<number, TimerState>();
function emit() {
const snapshot = [...toasts];
for (const listener of listeners) listener(snapshot);
}
export function subscribeToasts(listener: Listener): () => void {
listeners.add(listener);
listener([...toasts]);
return () => listeners.delete(listener);
}
export function dismissToast(id: number) {
const timer = timers.get(id);
if (timer) {
clearTimeout(timer.handle);
timers.delete(id);
}
toasts = toasts.filter((t) => t.id !== id);
emit();
}
function schedule(id: number, delay: number) {
timers.set(id, {
remaining: delay,
startedAt: Date.now(),
handle: setTimeout(() => dismissToast(id), delay),
});
}
export function showToast(
message: string,
kind: ToastKind = 'success',
durationMs: number = DEFAULT_DURATION,
) {
const id = ++seq;
toasts = [...toasts, { id, message, kind, duration: durationMs }];
emit();
if (durationMs > 0) schedule(id, durationMs);
return id;
}
/** Pause auto-dismiss (e.g. while the pointer or focus is on the toast). */
export function pauseToast(id: number) {
const timer = timers.get(id);
if (!timer) return;
clearTimeout(timer.handle);
timer.remaining = Math.max(0, timer.remaining - (Date.now() - timer.startedAt));
timer.startedAt = Date.now();
}
/** Resume auto-dismiss after a pause. */
export function resumeToast(id: number) {
const timer = timers.get(id);
if (!timer) return;
clearTimeout(timer.handle);
const delay = Math.max(0, timer.remaining);
timer.remaining = delay;
timer.startedAt = Date.now();
timer.handle = setTimeout(() => dismissToast(id), delay);
}
export const toast = {
success: (message: string, duration?: number) => showToast(message, 'success', duration),
error: (message: string, duration?: number) => showToast(message, 'error', duration),
info: (message: string, duration?: number) => showToast(message, 'info', duration),
};
+16
View File
@@ -0,0 +1,16 @@
<script lang="ts">
import './app.css';
import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query';
import ToastHost from '$lib/components/ToastHost.svelte';
const queryClient = new QueryClient({
defaultOptions: {
queries: { refetchOnWindowFocus: false, retry: 1 },
},
});
</script>
<QueryClientProvider client={queryClient}>
<slot />
<ToastHost />
</QueryClientProvider>
+5
View File
@@ -0,0 +1,5 @@
import type { LayoutLoad } from './$types';
export const load: LayoutLoad = () => {
return {};
};
+441
View File
@@ -0,0 +1,441 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { projects, type Project } from '$lib/api';
import ProjectCard from '$lib/components/ProjectCard.svelte';
import AppHeader from '$lib/components/AppHeader.svelte';
import Button from '$lib/components/ui/Button.svelte';
import EmptyState from '$lib/components/ui/EmptyState.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import Skeleton from '$lib/components/ui/Skeleton.svelte';
import { toast } from '$lib/toast';
const client = useQueryClient();
const projectsQuery = createQuery({
queryKey: ['projects'],
queryFn: projects.list,
});
const createProjectMutation = createMutation({
mutationFn: projects.create,
onSuccess: (data: Project) => {
client.invalidateQueries({ queryKey: ['projects'] });
toast.success(`Project “${data.title}” created`);
goto(`/project/${data.id}`);
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : 'Could not create project');
},
});
const DURATIONS = ['30 seconds', '1 minute', '2 minutes', '5 minutes', '10 minutes'];
let title = $state('');
let idea = $state('');
let genre = $state('Adventure / Mystery');
let tone = $state('Cinematic, atmospheric');
let duration = $state('2 minutes');
let showForm = $state(false);
let search = $state('');
let filter = $state('all');
function onCreate(e: Event) {
e.preventDefault();
if (!title.trim()) return;
$createProjectMutation.mutate({
title: title.trim(),
idea: idea.trim() || undefined,
genre: genre || undefined,
tone: tone || undefined,
target_duration: duration || undefined,
});
}
function openForm() {
showForm = true;
title = '';
idea = '';
genre = 'Adventure / Mystery';
tone = 'Cinematic, atmospheric';
duration = '2 minutes';
}
const FILTERS: { id: string; label: string }[] = [
{ id: 'all', label: 'All' },
{ id: 'in_progress', label: 'In Progress' },
{ id: 'completed', label: 'Completed' },
{ id: 'draft', label: 'Drafts' },
];
const all = $derived($projectsQuery.data ?? []);
const filtered = $derived.by(() => {
let list = all;
if (filter !== 'all') list = list.filter((p) => p.status === filter);
const q = search.trim().toLowerCase();
if (q) {
list = list.filter(
(p) => p.title.toLowerCase().includes(q) || (p.idea ?? '').toLowerCase().includes(q),
);
}
return list;
});
function clearFilters() {
search = '';
filter = 'all';
}
</script>
<AppHeader active="projects">
<Button variant="primary" onclick={openForm}>
<Icon name="plus" size={15} />
New Project
</Button>
</AppHeader>
<main class="container">
<div class="hero">
<div>
<h1>Projects</h1>
<p>Your local story-to-video workspace. Pick up where you left off.</p>
</div>
</div>
{#if showForm}
<form class="new-project-card" onsubmit={onCreate}>
<div class="form-head">
<div>
<p class="eyebrow">New reel</p>
<h3>New Project</h3>
</div>
<Button variant="ghost" onclick={() => (showForm = false)}>Close</Button>
</div>
<label class="field">
<span class="field-label">Title</span>
<input class="field-input" bind:value={title} placeholder="Moonlit Harbor" required />
</label>
<label class="field">
<span class="field-label">Story idea</span>
<textarea
class="field-textarea"
bind:value={idea}
placeholder="A lighthouse keeper finds a glowing bottle that shows memories of sailors lost at sea…"
rows={4}
></textarea>
<p class="field-hint">Optional — you can refine this later on the Story stage.</p>
</label>
<div class="form-grid">
<label class="field">
<span class="field-label">Genre</span>
<select class="field-select" bind:value={genre}>
<option>Adventure / Mystery</option>
<option>Drama</option>
<option>Sci-Fi</option>
<option>Fantasy</option>
<option>Horror</option>
<option>Romance</option>
<option>Thriller</option>
</select>
</label>
<label class="field">
<span class="field-label">Tone</span>
<select class="field-select" bind:value={tone}>
<option>Cinematic, atmospheric</option>
<option>Dark, tense</option>
<option>Whimsical, warm</option>
<option>Gritty, realistic</option>
<option>Epic, sweeping</option>
</select>
</label>
<label class="field">
<span class="field-label">Target duration</span>
<select class="field-select" bind:value={duration}>
{#each DURATIONS as d (d)}
<option value={d}>{d}</option>
{/each}
</select>
<p class="field-hint">Guides beat and scene counts on the Story stage.</p>
</label>
</div>
<div class="form-actions">
<Button variant="secondary" onclick={() => (showForm = false)}>Cancel</Button>
<Button variant="primary" type="submit" loading={$createProjectMutation.isPending}>
Create project
</Button>
</div>
</form>
{/if}
<div class="toolbar">
<input
class="search field-input"
bind:value={search}
placeholder="Search projects…"
aria-label="Search projects"
/>
<div class="filter-group" role="group" aria-label="Filter by status">
{#each FILTERS as f (f.id)}
<button
type="button"
class="pill"
class:active={filter === f.id}
aria-pressed={filter === f.id}
onclick={() => (filter = f.id)}
>
{f.label}
</button>
{/each}
</div>
</div>
{#if $projectsQuery.isLoading}
<div class="grid" aria-busy="true" aria-label="Loading projects">
{#each [1, 2, 3, 4, 5, 6] as n (n)}
<div class="skel-card">
<Skeleton height="170px" />
<div class="skel-body">
<Skeleton width="60%" height="16px" />
<Skeleton />
<Skeleton width="80%" />
<Skeleton width="40%" height="12px" />
</div>
</div>
{/each}
</div>
{:else if $projectsQuery.isError}
<EmptyState
title="Couldn't load projects"
body={$projectsQuery.error instanceof Error
? $projectsQuery.error.message
: 'The backend did not respond.'}
>
{#snippet icon()}
<Icon name="alert" size={28} />
{/snippet}
{#snippet action()}
<Button variant="primary" onclick={() => $projectsQuery.refetch()}>
<Icon name="retry" size={15} />
Retry
</Button>
{/snippet}
</EmptyState>
{:else if all.length === 0}
<EmptyState
title="No projects yet"
body="Calliope turns a story idea into characters, shots and finished video — all on your machine."
>
{#snippet icon()}
<Icon name="video" size={28} />
{/snippet}
{#snippet action()}
<Button variant="primary" onclick={openForm}>
<Icon name="plus" size={15} />
Create your first project
</Button>
{/snippet}
</EmptyState>
{:else if filtered.length === 0}
<EmptyState
title={search.trim()
? `No projects match “${search.trim()}”`
: 'No projects match the current filter'}
body="Try a different search or clear the filters."
>
{#snippet icon()}
<Icon name="search" size={28} />
{/snippet}
{#snippet action()}
<Button variant="secondary" onclick={clearFilters}>Clear filters</Button>
{/snippet}
</EmptyState>
{:else}
<div class="grid">
{#each filtered as project (project.id)}
<ProjectCard {project} />
{/each}
<button type="button" class="new-card" onclick={openForm}>
<div class="new-card-icon"><Icon name="plus" size={24} /></div>
<div class="new-card-title">Create New Project</div>
<div class="new-card-sub">Start with a story idea</div>
</button>
</div>
{/if}
</main>
<style>
.container {
max-width: 1280px;
margin: 0 auto;
padding: var(--space-xl);
}
.hero {
display: flex;
justify-content: space-between;
align-items: flex-end;
margin-bottom: var(--space-xl);
}
.hero h1 {
margin: 0 0 var(--space-sm);
font-size: 32px;
}
.hero p {
margin: 0;
color: var(--text-secondary);
font-size: 15px;
}
.new-project-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);
margin-bottom: var(--space-xl);
box-shadow: 0 0 0 1px rgba(139, 92, 246, 0.08);
}
.form-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: var(--space-md);
}
.eyebrow {
margin: 0 0 4px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--accent);
font-weight: 600;
}
.new-project-card h3 {
margin: 0;
font-size: 20px;
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--space-md);
}
@media (max-width: 700px) {
.form-grid {
grid-template-columns: 1fr;
}
}
.form-actions {
display: flex;
justify-content: flex-end;
gap: var(--space-sm);
margin-top: var(--space-sm);
}
.toolbar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: var(--space-lg);
gap: var(--space-md);
flex-wrap: wrap;
}
.search {
flex: 1;
max-width: 360px;
}
.filter-group {
display: flex;
gap: var(--space-xs);
}
.pill {
border: 1px solid transparent;
border-radius: 999px;
background: transparent;
color: var(--text-secondary);
padding: 8px 14px;
cursor: pointer;
font-size: 13px;
font-weight: 500;
font-family: inherit;
transition:
background 0.15s,
color 0.15s,
border-color 0.15s;
}
.pill:hover {
background: var(--bg-elevated);
color: var(--text-primary);
}
.pill.active {
background: var(--bg-elevated);
border-color: var(--border);
color: var(--text-primary);
}
.pill:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: var(--space-lg);
}
.skel-card {
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
overflow: hidden;
}
.skel-card :global(.skeleton) {
border-radius: 0;
}
.skel-body {
display: flex;
flex-direction: column;
gap: 10px;
padding: var(--space-md);
}
.skel-body :global(.skeleton) {
border-radius: var(--radius-sm);
}
.new-card {
border: 2px dashed var(--border);
background: transparent;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 320px;
color: var(--text-muted);
gap: var(--space-md);
border-radius: var(--radius-lg);
cursor: pointer;
font-family: inherit;
transition: all 0.15s;
}
.new-card:hover {
border-color: var(--accent);
color: var(--text-primary);
background: rgba(139, 92, 246, 0.04);
}
.new-card:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.new-card-icon {
width: 56px;
height: 56px;
border-radius: var(--radius-md);
background: var(--bg-elevated);
display: flex;
align-items: center;
justify-content: center;
}
.new-card-title {
font-weight: 600;
font-size: 15px;
}
.new-card-sub {
font-size: 13px;
color: var(--text-muted);
}
</style>
+8
View File
@@ -0,0 +1,8 @@
import { error } from '@sveltejs/kit';
export const prerender = true;
export const ssr = false;
export function load() {
return {};
}
+158
View File
@@ -0,0 +1,158 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--bg-primary: #0a0a0c;
--bg-surface: #141418;
--bg-elevated: #1e1e24;
--border: #2a2a32;
--text-primary: #f4f4f5;
--text-secondary: #a1a1aa;
--text-muted: #71717a;
--accent: #8b5cf6;
--accent-hover: #7c3aed;
--accent-glow: rgba(139, 92, 246, 0.25);
--success: #22c55e;
--warning: #f59e0b;
--error: #ef4444;
--info: #3b82f6;
/* Omni Composer pill tokens */
--pill-bg: var(--bg-elevated);
--pill-border: var(--border);
--pill-radius: 9999px;
--pill-height: 36px;
--pill-padding: 0 14px;
--pill-font-size: 13px;
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 16px;
--space-xs: 4px;
--space-sm: 8px;
--space-md: 16px;
--space-lg: 24px;
--space-xl: 32px;
--font-display: 'Outfit', system-ui, sans-serif;
--font-body: 'IBM Plex Sans', system-ui, sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, monospace;
}
body {
background: var(--bg-primary);
color: var(--text-primary);
font-family: var(--font-body);
margin: 0;
min-height: 100vh;
}
h1,
h2,
h3,
.logo {
font-family: var(--font-display);
}
code,
.mono {
font-family: var(--font-mono);
}
.field {
display: block;
margin-bottom: var(--space-md);
}
.field-label {
display: block;
font-size: 12px;
font-weight: 500;
letter-spacing: 0.02em;
color: var(--text-muted);
margin-bottom: 6px;
}
.field-input,
.field-textarea,
.field-select {
width: 100%;
box-sizing: border-box;
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 10px 12px;
color: var(--text-primary);
font-size: 14px;
font-family: inherit;
}
.field-textarea {
resize: vertical;
min-height: 96px;
line-height: 1.5;
}
.field-input:focus,
.field-textarea:focus,
.field-select:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-glow);
}
.field-hint {
margin-top: 6px;
font-size: 12px;
color: var(--text-muted);
}
/* Dark theme scrollbars (Firefox + Chromium) */
* {
scrollbar-width: thin;
scrollbar-color: #3f3f46 transparent;
}
*::-webkit-scrollbar {
width: 10px;
height: 10px;
}
*::-webkit-scrollbar-track {
background: transparent;
}
*::-webkit-scrollbar-thumb {
background: #3f3f46;
border-radius: 999px;
border: 2px solid transparent;
background-clip: padding-box;
}
*::-webkit-scrollbar-thumb:hover {
background: #52525b;
border: 2px solid transparent;
background-clip: padding-box;
}
*::-webkit-scrollbar-corner {
background: transparent;
}
/* Global keyboard focus fallback: every natively focusable element gets a ring,
even before the ui/ primitives are adopted. Component-scoped :focus-visible
rules (e.g. .field-input) override this via higher specificity. */
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* Global reduced-motion baseline. Components that need a styled static fallback
(Skeleton shimmer, ProgressBar indeterminate, StatusChip pulse) also handle
this in their own scoped styles. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
@@ -0,0 +1,5 @@
import type { RequestHandler } from '@sveltejs/kit';
export const GET: RequestHandler = () => {
return new Response(null, { status: 204 });
};
@@ -0,0 +1,869 @@
<script lang="ts">
import { onMount } from 'svelte';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import AppHeader from '$lib/components/AppHeader.svelte';
import OmniComposer from '$lib/components/OmniComposer.svelte';
import AttachToProject from '$lib/components/AttachToProject.svelte';
import ImageLightbox from '$lib/components/ImageLightbox.svelte';
import SafeMedia from '$lib/components/SafeMedia.svelte';
import { assetUrl, jobsApi, playgroundApi, workflows, type Job, type Workflow } from '$lib/api';
import { connectEvents } from '$lib/events';
import { handleJobEvent, progressFor } from '$lib/jobProgress';
import ProgressBar from '$lib/components/ui/ProgressBar.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import { toast } from '$lib/toast';
const client = useQueryClient();
let workflowId = $state<number | ''>('');
let formValues = $state<Record<string, string | number>>({});
let formError = $state('');
let lastWorkflowId = $state<number | '' | null>(null);
let previewSrc = $state<string | null>(null);
let previewAlt = $state('');
let previewKind = $state<'image' | 'video'>('image');
let deletingId = $state<number | null>(null);
let attempted = $state(false);
let missingLabels = $state<string[]>([]);
const workflowsQuery = createQuery({
queryKey: ['workflows'],
queryFn: workflows.list,
});
const jobsQuery = createQuery({
queryKey: ['playground-jobs'],
queryFn: playgroundApi.jobs,
refetchInterval: (q) => {
const list = (q.state.data as Job[] | undefined) ?? [];
const busy = list.some((j) => j.status === 'pending' || j.status === 'running');
return busy ? 5000 : false;
},
placeholderData: (prev) => prev,
});
const enabledWorkflows = $derived(
($workflowsQuery.data ?? []).filter((w: Workflow) => w.is_enabled),
);
const selected = $derived(enabledWorkflows.find((w) => w.id === workflowId) ?? null);
// Mode: filter by workflow kind — Video Generation / Image Generation
let mode = $state<'video' | 'image'>('video');
const modeWorkflows = $derived(enabledWorkflows.filter((w) => w.kind === mode));
// When mode changes, keep workflowId valid within the mode's list
$effect(() => {
const list = modeWorkflows;
if (list.length === 0) return;
if (workflowId === '' || !list.some((w) => w.id === workflowId)) {
workflowId = list[0].id;
}
});
// If default mode 'video' has no workflows but image does, flip
$effect(() => {
if (workflowId === '' && enabledWorkflows.length > 0) {
const hasVideo = enabledWorkflows.some((w) => w.kind === 'video');
if (!hasVideo) mode = 'image';
}
});
$effect(() => {
if (workflowId === lastWorkflowId) return;
lastWorkflowId = workflowId;
formValues = {};
formError = '';
attempted = false;
});
const generateMutation = createMutation({
mutationFn: () => {
if (workflowId === '') throw new Error('Select a workflow');
// Seed defaults for required-but-unset fields from schema
const withDefaults: Record<string, string | number> = { ...formValues };
for (const inp of selected?.input_schema ?? []) {
if (
withDefaults[inp.nodeId] === undefined &&
inp.defaultValue !== undefined &&
inp.defaultValue !== ''
) {
withDefaults[inp.nodeId] = inp.defaultValue;
}
}
return playgroundApi.generate({
workflow_id: Number(workflowId),
input_values: withDefaults,
});
},
onSuccess: () => {
formError = '';
client.invalidateQueries({ queryKey: ['playground-jobs'] });
toast.success('Generation queued');
},
onError: (err) => {
formError = err instanceof Error ? err.message : 'Generate failed';
toast.error(formError);
},
});
function tryGenerate() {
if ($generateMutation.isPending) return;
if (workflowId === '') {
toast.error('Select a workflow first');
return;
}
if (missingLabels.length > 0) {
attempted = true;
toast.error(`Missing required inputs: ${missingLabels.join(', ')}`);
return;
}
$generateMutation.mutate();
}
async function deleteJob(job: Job) {
const n = job.output_paths?.length ?? 0;
const msg =
n > 0
? `Delete artifact #${job.id}? This removes the DB record and ${n} file(s) on disk.`
: `Delete artifact #${job.id}? This removes the DB record.`;
if (!confirm(msg)) return;
deletingId = job.id;
try {
const r = await playgroundApi.deleteJob(job.id);
await client.invalidateQueries({ queryKey: ['playground-jobs'] });
const gone = r.deleted_files?.length ?? 0;
const miss = r.missing_files?.length ?? 0;
if (gone && miss) {
toast.success(`Deleted #${job.id} (${gone} file(s); ${miss} already missing)`);
} else if (gone) {
toast.success(`Deleted #${job.id} and ${gone} file(s)`);
} else {
toast.success(`Deleted #${job.id}`);
}
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Delete failed');
} finally {
deletingId = null;
}
}
onMount(() => {
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
const scheduleRefresh = () => {
if (refreshTimer) return;
refreshTimer = setTimeout(() => {
refreshTimer = null;
client.invalidateQueries({ queryKey: ['playground-jobs'] });
}, 400);
};
const stop = connectEvents((ev) => {
// Feed the shared progress store (ProgressBars read it live)
handleJobEvent(ev);
if (ev.type === 'job.progress') return;
if (
ev.type === 'job.created' ||
ev.type === 'job.started' ||
ev.type === 'job.completed' ||
ev.type === 'job.failed' ||
ev.type === 'job.deleted' ||
ev.type === 'asset.ready'
) {
scheduleRefresh();
}
});
return () => {
if (refreshTimer) clearTimeout(refreshTimer);
stop();
};
});
const jobs = $derived(($jobsQuery.data ?? []) as Job[]);
const jobsLoading = $derived($jobsQuery.isLoading && jobs.length === 0);
const doneCount = $derived(jobs.filter((j) => j.status === 'done').length);
function isVideoPath(path: string, kind: string) {
const lower = path.toLowerCase();
return kind === 'video' || lower.endsWith('.mp4') || lower.endsWith('.webm');
}
function statusWord(status: string) {
if (status === 'done') return 'Ready';
if (status === 'running') return 'Running';
if (status === 'pending') return 'Queued';
if (status === 'failed') return 'Failed';
return status;
}
function switchMode(next: 'video' | 'image') {
mode = next;
}
function resetAll() {
formValues = {};
formError = '';
attempted = false;
missingLabels = [];
}
</script>
<div class="shell">
<AppHeader active="playground" />
<main class="omni-layout">
<!-- Mode tabs (Kling-style) -->
<div class="mode-tabs" role="tablist" aria-label="Generation mode">
<button
type="button"
role="tab"
aria-selected={mode === 'video'}
class="mode-tab"
class:active={mode === 'video'}
onclick={() => switchMode('video')}
>
<Icon name="video" size={15} />
Video Generation
</button>
<button
type="button"
role="tab"
aria-selected={mode === 'image'}
class="mode-tab"
class:active={mode === 'image'}
onclick={() => switchMode('image')}
>
<Icon name="image" size={15} />
Image Generation
</button>
<div class="spacer"></div>
<button type="button" class="mode-tab reset" onclick={resetAll} title="Clear all inputs">
<Icon name="retry" size={14} />
Reset
</button>
</div>
<!-- Results scroll above the docked composer -->
<section class="results" aria-labelledby="pg-artifacts">
<header class="artifacts-head">
<h2 id="pg-artifacts">Artifacts</h2>
<p class="count-block">
<span class="count mono">{jobs.length}</span>
<span class="count-label">{doneCount} ready</span>
</p>
</header>
{#if jobsLoading}
<div class="rail">
<div class="skeleton" aria-hidden="true"></div>
<div class="skeleton" aria-hidden="true"></div>
</div>
{:else if jobs.length === 0}
<div class="empty-rail">
<p class="empty-title">Nothing queued yet</p>
<p class="muted">Generations land here — pending first, then the media.</p>
</div>
{:else}
<ul class="rail">
{#each jobs as job (job.id)}
{@const primaryPath = job.output_paths?.[0] ?? null}
{@const primaryMedia = primaryPath ? assetUrl(primaryPath) : null}
<li
class="card"
class:done={job.status === 'done'}
class:failed={job.status === 'failed'}
>
<div class="card-meta">
<span class="id mono">#{job.id}</span>
<span class="badge {job.status}">{statusWord(job.status)}</span>
<span class="kind muted">{job.kind}</span>
</div>
{#if job.status === 'pending' || job.status === 'running'}
{@const prog = progressFor(job.id)}
<div class="waiting" aria-busy="true">
<span class="pulse"></span>
<div class="waiting-main">
<span class="waiting-text">
{job.status === 'running' ? (prog?.message ?? 'Generating…') : 'Queued'}
</span>
{#if job.status === 'running'}
<ProgressBar
size="sm"
value={prog?.progress ?? 0}
indeterminate={prog == null}
/>
{/if}
</div>
</div>
{/if}
{#if job.error}
<p class="err">{job.error}</p>
{/if}
{#if primaryMedia && primaryPath}
{#if isVideoPath(primaryPath, job.kind)}
<button
type="button"
class="media-hit"
aria-label="Play video, artifact {job.id}"
title="Play in viewer"
onclick={() => {
previewSrc = primaryMedia;
previewAlt = `Artifact #${job.id}`;
previewKind = 'video';
}}
>
<div class="media-frame">
<SafeMedia
class="artifact"
src={primaryMedia}
kind="video"
label="Video unavailable"
controls={false}
/>
<span class="play-badge" aria-hidden="true">
<Icon name="play" size={22} />
</span>
</div>
</button>
{:else}
<button
type="button"
class="media-hit"
aria-label="View image, artifact {job.id}"
onclick={() => {
previewSrc = primaryMedia;
previewAlt = `Artifact #${job.id}`;
previewKind = 'image';
}}
>
<div class="media-frame">
<SafeMedia
class="artifact"
src={primaryMedia}
alt="Artifact {job.id}"
label="Image unavailable"
/>
</div>
</button>
{/if}
{:else if job.status === 'done'}
<div class="missing">
<p>File missing on disk</p>
{#if primaryPath}
<p class="mono path-hint">{primaryPath.split(/[/\\]/).pop()}</p>
{/if}
</div>
{/if}
<div class="card-actions">
{#if primaryPath && primaryMedia}
<AttachToProject path={primaryPath} kind={job.kind} />
{/if}
{#if job.status === 'failed'}
<button
class="btn btn-secondary"
type="button"
onclick={() =>
jobsApi.retry(job.id).then(() =>
client.invalidateQueries({ queryKey: ['playground-jobs'] }),
)}
>
Retry
</button>
{/if}
<button
class="btn btn-ghost danger"
type="button"
disabled={deletingId === job.id}
onclick={() => deleteJob(job)}
>
{deletingId === job.id ? 'Deleting…' : 'Delete'}
</button>
</div>
</li>
{/each}
</ul>
{/if}
</section>
<!-- Composer docked at bottom — always visible (Kling Omni style) -->
<div class="composer-dock">
{#if modeWorkflows.length === 0}
<div class="empty-mode">
<p class="empty-title">No enabled {mode === 'video' ? 'video' : 'image'} workflows</p>
<p class="muted">
Enable a workflow in <a href="/settings?tab=workflows">Settings → Workflows</a>.
</p>
</div>
{:else if selected}
<OmniComposer
inputs={selected.input_schema}
bind:values={formValues}
workflow={selected}
workflows={modeWorkflows}
onWorkflowChange={(id) => (workflowId = id)}
allowUpload
showErrors={attempted}
onValidityChange={(m) => (missingLabels = m)}
onSubmit={tryGenerate}
submitting={$generateMutation.isPending}
/>
{#if formError}
<p class="err" role="alert">{formError}</p>
{/if}
{/if}
</div>
</main>
</div>
<ImageLightbox
src={previewSrc}
alt={previewAlt}
kind={previewKind}
caption={previewKind === 'video' ? `Video ${previewAlt}` : undefined}
onClose={() => {
previewSrc = null;
previewAlt = '';
}}
/>
<style>
.shell {
height: 100vh;
display: flex;
flex-direction: column;
background: var(--bg-primary);
overflow: hidden;
}
/* Fixed viewport column: tabs + scrollable results + docked composer */
.omni-layout {
flex: 1;
display: flex;
flex-direction: column;
gap: 12px;
padding: 12px var(--space-xl) 16px;
min-height: 0;
overflow: hidden;
background: var(--bg-primary);
max-width: 980px;
width: 100%;
margin: 0 auto;
box-sizing: border-box;
}
/* ── Mode tabs ───────────────────────────────────────────── */
.mode-tabs {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.spacer {
flex: 1;
}
.mode-tab {
display: inline-flex;
align-items: center;
gap: 7px;
height: 36px;
padding: 0 14px;
border-radius: 9999px;
background: var(--bg-elevated);
border: 1px solid var(--border);
color: var(--text-secondary);
font-size: 13px;
font-weight: 500;
font-family: var(--font-body);
cursor: pointer;
transition:
border-color 0.15s,
color 0.15s,
background 0.15s;
}
.mode-tab:hover {
color: var(--text-primary);
border-color: var(--text-muted);
}
.mode-tab.active {
background: var(--bg-surface);
color: var(--text-primary);
border-color: var(--accent);
}
.mode-tab.reset {
color: var(--text-muted);
}
.mode-tab:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* ── Scrollable results ──────────────────────────────────── */
.results {
flex: 1;
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: var(--space-md);
padding-right: 2px;
}
.artifacts-head {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: var(--space-md);
padding-bottom: var(--space-sm);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
position: sticky;
top: 0;
background: var(--bg-primary);
z-index: 1;
}
h2 {
margin: 0;
font-family: var(--font-display);
font-size: 18px;
font-weight: 700;
letter-spacing: -0.03em;
color: var(--text-primary);
}
.count-block {
margin: 0;
display: flex;
align-items: baseline;
gap: 6px;
}
.count {
font-size: 15px;
color: var(--text-primary);
font-weight: 600;
}
.count-label {
font-size: 12px;
color: var(--text-muted);
}
.rail {
list-style: none;
margin: 0;
padding: 0 0 8px;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: var(--space-md);
align-items: start;
}
.card {
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 10px;
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
overflow: hidden;
}
.card-meta {
display: flex;
align-items: center;
gap: 8px;
}
.id {
font-size: 12px;
color: var(--text-muted);
}
.kind {
font-size: 11px;
margin-left: auto;
}
.badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 9999px;
font-size: 11px;
font-weight: 600;
}
.badge.done {
background: color-mix(in srgb, var(--success) 15%, transparent);
color: var(--success);
}
.badge.failed {
background: color-mix(in srgb, var(--error) 15%, transparent);
color: var(--error);
}
.badge.pending,
.badge.running {
background: color-mix(in srgb, var(--warning) 15%, transparent);
color: var(--warning);
}
.err {
color: var(--error);
font-size: 13px;
margin: 0;
}
.waiting {
display: flex;
align-items: center;
gap: 10px;
}
.waiting-main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.waiting-text {
font-size: 13px;
color: var(--text-secondary);
}
.pulse {
width: 8px;
height: 8px;
flex-shrink: 0;
border-radius: 9999px;
background: var(--warning);
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse {
0%,
100% {
opacity: 0.4;
}
50% {
opacity: 1;
}
}
.media-hit {
padding: 0;
border: none;
background: transparent;
cursor: zoom-in;
display: block;
width: 100%;
min-width: 0;
}
/* Video thumb: native controls off, custom play affordance instead */
.media-hit:has(:global(video)) {
cursor: pointer;
}
.media-hit:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: var(--radius-sm);
}
.play-badge {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
transition: background 0.15s;
}
.play-badge::before {
content: '';
width: 52px;
height: 52px;
border-radius: 9999px;
background: rgba(0, 0, 0, 0.55);
backdrop-filter: blur(2px);
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.18);
transition:
transform 0.15s ease,
background 0.15s;
}
.play-badge :global(svg) {
position: absolute;
color: #fff;
fill: currentColor;
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.6));
/* optical centering for a solid play triangle */
margin-left: 3px;
}
.media-hit:hover .play-badge::before,
.media-hit:focus-visible .play-badge::before {
background: rgba(0, 0, 0, 0.72);
transform: scale(1.06);
}
.media-frame {
position: relative;
width: 100%;
aspect-ratio: 4 / 3;
border-radius: var(--radius-sm);
overflow: hidden;
background: var(--bg-elevated);
}
.media-frame :global(.artifact),
.media-frame :global(img),
.media-frame :global(video) {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
border-radius: 0;
}
.missing {
padding: 12px;
border-radius: var(--radius-sm);
background: var(--bg-elevated);
color: var(--text-muted);
font-size: 13px;
}
.path-hint {
font-size: 11px;
margin: 4px 0 0;
overflow-wrap: anywhere;
}
.card-actions {
display: flex;
gap: 8px;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
margin-top: 2px;
}
.skeleton {
height: 180px;
border-radius: var(--radius-md);
background: linear-gradient(
90deg,
var(--bg-surface) 25%,
var(--bg-elevated) 50%,
var(--bg-surface) 75%
);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.btn {
border-radius: 9999px;
font-size: 12px;
font-weight: 600;
padding: 6px 14px;
cursor: pointer;
transition: all 0.15s;
}
.btn-secondary {
background: transparent;
border: 1px solid var(--border);
color: var(--text-secondary);
}
.btn-secondary:hover {
border-color: var(--text-muted);
color: var(--text-primary);
}
.btn-ghost.danger {
background: transparent;
border: 1px solid transparent;
color: var(--text-muted);
}
.btn-ghost.danger:hover {
color: var(--error);
border-color: rgba(239, 68, 68, 0.4);
}
.empty-rail {
padding: 40px 24px;
text-align: center;
border: 1px dashed var(--border);
border-radius: var(--radius-lg);
margin: auto 0;
}
.empty-title {
margin: 0 0 4px;
font-size: 15px;
font-weight: 600;
color: var(--text-primary);
}
.muted {
color: var(--text-secondary);
font-size: 13px;
line-height: 1.5;
margin: 0;
}
.muted a {
color: var(--accent);
}
/* ── Composer dock (never shrinks away) ──────────────────── */
.composer-dock {
flex-shrink: 0;
min-height: 0;
}
.composer-dock :global(.omni-shell) {
/* overflow:hidden + flex shrink was collapsing this to 2px */
flex-shrink: 0;
}
.empty-mode {
padding: 28px 20px;
text-align: center;
border: 1px dashed var(--border);
border-radius: var(--radius-lg);
background: var(--bg-surface);
}
</style>
@@ -0,0 +1,2 @@
export const ssr = false;
export const prerender = false;
@@ -0,0 +1,329 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toStore } from 'svelte/store';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { createQuery, createMutation, useQueryClient } from '@tanstack/svelte-query';
import NavRail from '$lib/components/NavRail.svelte';
import StoryStage from '$lib/components/StoryStage.svelte';
import AssetsStage from '$lib/components/AssetsStage.svelte';
import ScriptStage from '$lib/components/ScriptStage.svelte';
import QueueStage from '$lib/components/QueueStage.svelte';
import ActivityPanel from '$lib/components/ActivityPanel.svelte';
import AppHeader from '$lib/components/AppHeader.svelte';
import Button from '$lib/components/ui/Button.svelte';
import EmptyState from '$lib/components/ui/EmptyState.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import Skeleton from '$lib/components/ui/Skeleton.svelte';
import StatusChip from '$lib/components/ui/StatusChip.svelte';
import { jobsApi, projects, settings } from '$lib/api';
import { connectEvents, type CalliopeEvent, type EventConnectionState } from '$lib/events';
import { handleJobEvent } from '$lib/jobProgress';
interface Props {
data: { id: string };
}
let { data }: Props = $props();
const client = useQueryClient();
const projectId = $derived(Number(data.id));
const enabled = $derived(!isNaN(projectId));
// Stage <-> URL contract: the active stage lives in ?stage=story|assets|script|video.
// Switching stages = goto('?stage=<id>'); deep links and browser Back/Forward work.
const STAGES = ['story', 'assets', 'script', 'video'] as const;
type Stage = (typeof STAGES)[number];
function stageFromUrl(url: URL): Stage {
const s = url.searchParams.get('stage');
return (STAGES as readonly string[]).includes(s ?? '') ? (s as Stage) : 'story';
}
const STAGE_LABELS: Record<Stage, string> = {
story: '1 · Story',
assets: '2 · Assets',
script: '3 · Script',
video: '4 · Video',
};
let activeTab = $state<Stage>(stageFromUrl(page.url));
let activityCollapsed = $state(false);
let logs = $state<CalliopeEvent[]>([]);
let connState = $state<EventConnectionState>('connecting');
// Latest agent.thinking message — fed to the stage overlays as a live status line.
let agentStatus = $state<string | null>(null);
// URL → state: deep links, browser Back/Forward
$effect(() => {
const s = stageFromUrl(page.url);
if (s !== activeTab) activeTab = s;
});
// State → URL: every stage switch goes through goto so history works
function selectStage(id: string) {
const stage: Stage = (STAGES as readonly string[]).includes(id) ? (id as Stage) : 'story';
if (stage === activeTab) return;
activeTab = stage;
goto(`?stage=${stage}`, { keepFocus: true, noScroll: true });
}
const storyQuery = createQuery(
toStore(() => ({
queryKey: ['story', projectId],
queryFn: () => projects.getStory(projectId),
enabled,
})),
);
const settingsQuery = createQuery({
queryKey: ['settings'],
queryFn: settings.get,
});
// Same query keys as QueueStage/ActivityPanel — cache is shared.
const jobsQuery = createQuery(
toStore(() => ({
queryKey: ['jobs', projectId],
queryFn: () => jobsApi.list(projectId),
enabled,
refetchInterval: 5000,
})),
);
const queueStatusQuery = createQuery(
toStore(() => ({
queryKey: ['queue-status'],
queryFn: jobsApi.queueStatus,
enabled,
refetchInterval: 5000,
})),
);
const generateStoryMutation = createMutation({
mutationFn: () => projects.generateStory(projectId),
onMutate: () => {
// Drop the previous run's status so the overlay starts clean.
agentStatus = null;
},
onSuccess: async () => {
await client.invalidateQueries({ queryKey: ['story'] });
await client.invalidateQueries({ queryKey: ['assets'] });
},
});
const isConfigured = $derived(
Boolean($settingsQuery.data?.llm_base_url && $settingsQuery.data?.llm_model),
);
const projectTitle = $derived($storyQuery.data?.project?.title ?? 'Project');
const generateError = $derived(
$generateStoryMutation.isError
? $generateStoryMutation.error instanceof Error
? $generateStoryMutation.error.message
: String($generateStoryMutation.error)
: '',
);
const runningCount = $derived(
($jobsQuery.data ?? []).filter((j) => j.status === 'running').length,
);
const queuedCount = $derived(
($jobsQuery.data ?? []).filter((j) => j.status === 'pending').length,
);
const queuePaused = $derived(Boolean($queueStatusQuery.data?.paused));
onMount(() => {
return connectEvents(
(ev) => {
// Live per-job progress for ProgressBars (Activity log stays clean)
handleJobEvent(ev);
// Don't keep Comfy poll ticks in the Activity log
if (ev.type !== 'job.progress') {
logs = [...logs, ev].slice(-120);
}
if (ev.type === 'agent.thinking') {
const msg = ev.data?.message;
const text = typeof msg === 'string' ? msg.trim() : '';
agentStatus = text || null;
}
if (
ev.type.startsWith('job.') ||
ev.type === 'asset.ready' ||
ev.type === 'agent.thinking' ||
ev.type.startsWith('story.')
) {
client.invalidateQueries({ queryKey: ['jobs'] });
client.invalidateQueries({ queryKey: ['assets'] });
client.invalidateQueries({ queryKey: ['story'] });
client.invalidateQueries({ queryKey: ['scenes'] });
}
},
(state) => (connState = state),
);
});
</script>
<div class="shell">
<AppHeader crumb={`· ${projectTitle}`} />
{#if !enabled}
<div class="invalid-wrap">
<EmptyState
title="Project not found"
body={`“${data.id}” isn’t a valid project id — the link may be broken or the project was deleted.`}
>
{#snippet icon()}
<Icon name="folder" size={28} />
{/snippet}
{#snippet action()}
<Button variant="primary" onclick={() => goto('/')}>Back to projects</Button>
{/snippet}
</EmptyState>
</div>
{:else}
<div class="workspace-bar">
<span class="stage-label">{STAGE_LABELS[activeTab]}</span>
<Button
variant="secondary"
size="sm"
title="Open the Video stage"
onclick={() => selectStage('video')}
>
<Icon name="queue" size={13} />
{runningCount + queuedCount > 0
? `${runningCount} running · ${queuedCount} queued`
: 'Queue idle'}
{#if queuePaused}
<StatusChip status="paused" />
{/if}
</Button>
</div>
<div class="workspace">
<NavRail active={activeTab} onSelect={selectStage} />
<main class="stage" class:stage-fill={activeTab === 'video'}>
{#if activeTab === 'story'}
{#if $storyQuery.isLoading}
<div class="card skel" aria-busy="true">
<Skeleton width="36%" height="22px" />
<Skeleton width="88%" />
<Skeleton width="72%" />
<Skeleton height="140px" />
</div>
{:else if $storyQuery.isError}
<div class="card" style="color: var(--error)">
Failed to load story: {$storyQuery.error?.message ?? 'unknown error'}
</div>
{:else if $storyQuery.data}
<StoryStage
{projectId}
story={$storyQuery.data}
generating={$generateStoryMutation.isPending}
configured={isConfigured}
error={generateError}
onGenerate={() => $generateStoryMutation.mutateAsync()}
onGoAssets={() => selectStage('assets')}
{agentStatus}
/>
{/if}
{:else if activeTab === 'assets'}
<AssetsStage {projectId} />
{:else if activeTab === 'script'}
<ScriptStage {projectId} {agentStatus} />
{:else if activeTab === 'video'}
<QueueStage {projectId} {projectTitle} />
{/if}
</main>
<ActivityPanel
{logs}
{projectId}
{connState}
collapsed={activityCollapsed}
onToggle={() => (activityCollapsed = !activityCollapsed)}
/>
</div>
{/if}
</div>
<style>
.shell {
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.invalid-wrap {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-lg);
overflow-y: auto;
}
.workspace-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-md);
padding: 8px var(--space-lg);
border-bottom: 1px solid var(--border);
background: var(--bg-surface);
flex-shrink: 0;
}
.stage-label {
font-family: var(--font-display);
font-size: 13px;
font-weight: 600;
letter-spacing: 0.02em;
color: var(--text-secondary);
}
.workspace {
display: flex;
flex: 1;
overflow: hidden;
}
.stage {
flex: 1;
padding: var(--space-lg);
overflow-y: auto;
background: var(--bg-primary);
min-width: 0;
}
.stage.stage-fill {
overflow: hidden;
display: flex;
flex-direction: column;
min-height: 0;
/* Bleed to column edges — Nav/Activity already frame the stage.
Old max-width+margin:auto looked off-center because this column
sits between unequal side rails. */
padding: 12px 0 12px;
}
.stage.stage-fill > :global(.queue-root) {
flex: 1;
min-height: 0;
padding-inline: 16px;
}
/* Player hero breaks out to full stage width; strip/composer keep inset */
.stage.stage-fill :global(.hero) {
margin-inline: -16px;
width: auto;
}
.stage.stage-fill :global(.hero .frame) {
border-radius: 0;
border-left: none;
border-right: none;
}
.card {
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: var(--space-lg);
}
.skel {
display: flex;
flex-direction: column;
gap: 12px;
}
</style>
@@ -0,0 +1,8 @@
import type { PageLoad } from './$types';
export const prerender = false;
export const ssr = false;
export const load: PageLoad = ({ params }) => {
return { id: params.id };
};
@@ -0,0 +1,410 @@
<script lang="ts">
import { page } from '$app/stores';
import { beforeNavigate, goto } from '$app/navigation';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import SettingsNav from '$lib/components/settings/SettingsNav.svelte';
import WorkflowsLibrary from '$lib/components/settings/WorkflowsLibrary.svelte';
import AppHeader from '$lib/components/AppHeader.svelte';
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 StatusChip from '$lib/components/ui/StatusChip.svelte';
import { settings, type Settings } from '$lib/api';
import { toast } from '$lib/toast';
const client = useQueryClient();
let tab = $derived(($page.url.searchParams.get('tab') || 'llm') as string);
const settingsQuery = createQuery({
queryKey: ['settings'],
queryFn: settings.get,
});
let draft = $state<Record<string, unknown>>({});
let apiKeyDraft = $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'] : []),
]);
const isDirty = $derived(dirtyKeys.length > 0);
const FIELD_TAB: Record<string, string> = {
llm_base_url: 'llm',
llm_model: 'llm',
llm_api_key: 'llm',
comfyui_base_url: 'comfy',
dry_run: 'comfy',
queue_concurrency: 'queue',
queue_poll_interval_sec: 'queue',
queue_max_retries: 'queue',
data_dir: 'storage',
assets_dir: 'storage',
db_name: 'storage',
};
const dirtyTabs = $derived(
new Set(dirtyKeys.map((k) => FIELD_TAB[k]).filter((t): t is string => Boolean(t))),
);
function discardDraft() {
draft = {};
apiKeyDraft = '';
}
const saveMutation = createMutation({
mutationFn: () => {
const update: Record<string, unknown> = {};
for (const [k, v] of Object.entries(draft)) {
if (v === undefined) continue;
// Allow false for dry_run; skip empty optional strings only
if (v === '' && k !== 'dry_run') continue;
if (typeof v === 'string' && (k.includes('_dir') || k.endsWith('_dir'))) {
// Strip wrapping quotes users often paste from Explorer
const cleaned = v.trim().replace(/^["']|["']$/g, '');
update[k] = cleaned;
continue;
}
update[k] = v;
}
if (apiKeyDraft) update.llm_api_key = apiKeyDraft;
return settings.update(update);
},
onSuccess: (saved) => {
client.invalidateQueries({ queryKey: ['settings'] });
discardDraft();
toast.success(
saved?.dry_run ? 'Settings saved (Dry-run is ON — placeholders only)' : 'Settings saved',
);
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : 'Could not save settings');
},
});
// Leave-guard: in-app navigation away from /settings asks to discard;
// same-path tab switches keep the draft. Tab close uses beforeunload.
let leaveOpen = $state(false);
let pendingUrl = $state<string | null>(null);
beforeNavigate((nav) => {
if (!isDirty || !nav.to) return;
if (nav.to.url.pathname === $page.url.pathname) return;
nav.cancel();
pendingUrl = `${nav.to.url.pathname}${nav.to.url.search}${nav.to.url.hash}`;
leaveOpen = true;
});
function confirmLeave() {
const url = pendingUrl;
pendingUrl = null;
discardDraft();
if (url) goto(url);
}
function onBeforeUnload(e: BeforeUnloadEvent) {
if (!isDirty) return;
e.preventDefault();
e.returnValue = '';
}
function fieldValue(key: keyof Settings, fallback: string | number | boolean | null | undefined) {
if (draft[key] !== undefined && draft[key] !== '') return draft[key] as string;
const raw = fallback ?? '';
if (typeof raw === 'string') return raw.replace(/^["']|["']$/g, '');
return raw;
}
function dryRunChecked(s: Settings): boolean {
if (draft.dry_run !== undefined) return Boolean(draft.dry_run);
return s.dry_run === true;
}
</script>
<svelte:window onbeforeunload={onBeforeUnload} />
<div class="shell">
<AppHeader active="settings" crumb="/ Settings">
{#snippet status()}
{#if isDirty}
<StatusChip status="paused" label="Unsaved changes" />
{/if}
{/snippet}
</AppHeader>
<div class="body">
<SettingsNav dirty={dirtyTabs} />
<main class="content">
{#if $settingsQuery.isLoading}
<p class="muted">Loading settings…</p>
{:else if $settingsQuery.data}
{@const s = $settingsQuery.data}
{#if tab === 'llm'}
<section class="panel">
<h1>LLM</h1>
<p class="lead">OpenAI-compatible chat endpoint used for story and script drafting.</p>
<label class="field">
<span class="field-label">Base URL</span>
<input
class="field-input"
value={String(fieldValue('llm_base_url', s.llm_base_url))}
oninput={(e) => (draft.llm_base_url = e.currentTarget.value)}
placeholder="http://127.0.0.1:11434/v1"
/>
</label>
<label class="field">
<span class="field-label">Model</span>
<input
class="field-input"
value={String(fieldValue('llm_model', s.llm_model))}
oninput={(e) => (draft.llm_model = e.currentTarget.value)}
placeholder="llama3.2"
/>
</label>
<label class="field">
<span class="field-label">API key</span>
<input
class="field-input"
type="password"
bind:value={apiKeyDraft}
placeholder={s.llm_api_key ? '•••••••• (saved)' : 'Optional for local servers'}
/>
<p class="field-hint">Stored in local config file, never in the project database.</p>
</label>
</section>
{:else if tab === 'comfy'}
<section class="panel">
<h1>ComfyUI</h1>
<p class="lead">Connection to your local render farm for image and video jobs.</p>
<label class="field">
<span class="field-label">Base URL</span>
<input
class="field-input"
value={String(fieldValue('comfyui_base_url', s.comfyui_base_url))}
oninput={(e) => (draft.comfyui_base_url = e.currentTarget.value)}
/>
<p class="field-hint">
Calliope talks to Comfy over HTTP only. Comfy’s own input/output folders stay in
ComfyUI — set them there, not here.
</p>
</label>
<label class="check">
<input
type="checkbox"
checked={dryRunChecked(s)}
onchange={(e) => (draft.dry_run = e.currentTarget.checked)}
/>
Dry-run mode (off by default) — skip ComfyUI and write placeholder assets for testing only
</label>
</section>
{:else if tab === 'queue'}
<section class="panel">
<h1>Queue</h1>
<p class="lead">Worker concurrency and retry behavior for long GPU jobs.</p>
<label class="field">
<span class="field-label">Concurrency</span>
<input
class="field-input"
type="number"
min="1"
max="8"
value={String(fieldValue('queue_concurrency', s.queue_concurrency))}
oninput={(e) => (draft.queue_concurrency = Number(e.currentTarget.value))}
/>
</label>
<label class="field">
<span class="field-label">Poll interval (seconds)</span>
<input
class="field-input"
type="number"
step="0.5"
value={String(fieldValue('queue_poll_interval_sec', s.queue_poll_interval_sec))}
oninput={(e) => (draft.queue_poll_interval_sec = Number(e.currentTarget.value))}
/>
</label>
<label class="field">
<span class="field-label">Max retries</span>
<input
class="field-input"
type="number"
value={String(fieldValue('queue_max_retries', s.queue_max_retries))}
oninput={(e) => (draft.queue_max_retries = Number(e.currentTarget.value))}
/>
</label>
</section>
{:else if tab === 'storage'}
<section class="panel">
<h1>Storage</h1>
<p class="lead">Where Calliope keeps SQLite and generated assets on disk.</p>
<div class="callout">
<Icon name="alert" size={16} />
<p>
<strong>Changing storage paths moves where Calliope writes data.</strong>
Do not point this at temporary folders — they are wiped.
</p>
</div>
<label class="field">
<span class="field-label">Data directory</span>
<input
class="field-input"
value={String(fieldValue('data_dir', s.data_dir))}
oninput={(e) => (draft.data_dir = e.currentTarget.value)}
/>
<p class="field-hint">Current: <code class="mono">{s.data_dir}</code></p>
</label>
<label class="field">
<span class="field-label">Assets directory</span>
<input
class="field-input"
value={String(fieldValue('assets_dir', s.assets_dir))}
oninput={(e) => (draft.assets_dir = e.currentTarget.value)}
/>
<p class="field-hint">Current: <code class="mono">{s.assets_dir}</code></p>
</label>
</section>
{:else if tab === 'workflows'}
<WorkflowsLibrary />
{/if}
{#if tab !== 'workflows'}
<div class="save-bar">
<span class="save-state" class:dirty={isDirty}>
{#if isDirty}
<span class="save-dot" aria-hidden="true"></span>Unsaved changes
{:else}
All changes saved
{/if}
</span>
<Button
variant="ghost"
disabled={!isDirty || $saveMutation.isPending}
onclick={discardDraft}
>
Discard
</Button>
<Button
variant="primary"
disabled={!isDirty}
loading={$saveMutation.isPending}
onclick={() => $saveMutation.mutate()}
>
Save changes
</Button>
</div>
{/if}
{/if}
</main>
</div>
</div>
<ConfirmDialog
bind:open={leaveOpen}
title="Discard unsaved changes?"
message="You have unsaved settings changes. Leaving now will discard them."
confirmLabel="Discard and leave"
danger
onconfirm={confirmLeave}
oncancel={() => (pendingUrl = null)}
/>
<style>
.shell {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.body {
display: flex;
flex: 1;
min-height: 0;
}
.content {
flex: 1;
padding: var(--space-xl);
overflow-y: auto;
max-width: 960px;
}
.panel {
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);
}
.panel h1 {
margin: 0 0 6px;
font-size: 22px;
}
.lead {
margin: 0 0 var(--space-lg);
color: var(--text-secondary);
font-size: 14px;
}
.check {
display: flex;
align-items: center;
gap: 10px;
font-size: 14px;
color: var(--text-secondary);
}
.check input {
width: auto;
}
.callout {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 12px 14px;
margin-bottom: var(--space-lg);
border-radius: var(--radius-md);
border: 1px solid rgba(245, 158, 11, 0.35);
background: rgba(245, 158, 11, 0.08);
color: var(--warning);
}
.callout :global(.icon) {
flex-shrink: 0;
margin-top: 2px;
}
.callout p {
margin: 0;
font-size: 13px;
line-height: 1.5;
color: var(--text-secondary);
}
.callout strong {
color: var(--warning);
}
.muted {
color: var(--text-muted);
}
.save-bar {
position: sticky;
bottom: 0;
z-index: 5;
display: flex;
align-items: center;
justify-content: flex-end;
gap: var(--space-sm);
margin: var(--space-xl) calc(-1 * var(--space-xl)) calc(-1 * var(--space-xl));
padding: var(--space-md) var(--space-xl);
background: var(--bg-surface);
border-top: 1px solid var(--border);
box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.25);
}
.save-state {
margin-right: auto;
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--text-muted);
}
.save-state.dirty {
color: var(--warning);
}
.save-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--warning);
}
</style>
@@ -0,0 +1,2 @@
export const ssr = false;
export const prerender = false;