The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Cinema Studio server: projects, folders (scenes), take membership, generate, AI Director
Claude2b43bb41ed21
diff --git a/src/app/api/cinema/projects/[id]/director/route.ts b/src/app/api/cinema/projects/[id]/director/route.tsnew file mode 100644index 00000000..c80c7118--- /dev/null+++ b/src/app/api/cinema/projects/[id]/director/route.ts@@ -0,0 +1,32 @@+import { after, connection } from "next/server";+import { clearChat, getChat } from "@/server/cinema";+import { askDirector } from "@/server/cinema-director";+import { DirectorAsk, body, handle } from "@/server/cinema-schemas";++export async function GET(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {+ await connection();+ return handle(async () => {+ const { id } = await ctx.params;+ return Response.json({ messages: getChat(id) });+ });+}++/** Ask the AI Director; answers with the whole conversation (the reply proposes shots, never renders them). */+export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const b = await body(request, DirectorAsk, "Write a message first");+ const reply = askDirector(id, b.text);+ // An LLM call can outlive a closed tab; keep it running so the answer is saved.+ after(() => reply.catch(() => {}));+ return Response.json({ messages: await reply });+ });+}++export async function DELETE(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {+ return handle(async () => {+ const { id } = await ctx.params;+ clearChat(id);+ return new Response(null, { status: 204 });+ });+}diff --git a/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts b/src/app/api/cinema/projects/[id]/folders/[folderId]/route.tsnew file mode 100644index 00000000..b28ef54f--- /dev/null+++ b/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts@@ -0,0 +1,19 @@+import { deleteFolder, updateFolder } from "@/server/cinema";+import { FolderPatch, body, handle } from "@/server/cinema-schemas";++export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders/[folderId]">) {+ return handle(async () => {+ const { id, folderId } = await ctx.params;+ const patch = await body(request, FolderPatch, "Those folder settings aren't valid");+ return Response.json(updateFolder(id, folderId, patch));+ });+}++/** Its takes and subfolders move up to the parent folder. */+export async function DELETE(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders/[folderId]">) {+ return handle(async () => {+ const { id, folderId } = await ctx.params;+ deleteFolder(id, folderId);+ return new Response(null, { status: 204 });+ });+}diff --git a/src/app/api/cinema/projects/[id]/folders/route.ts b/src/app/api/cinema/projects/[id]/folders/route.tsnew file mode 100644index 00000000..6347527c--- /dev/null+++ b/src/app/api/cinema/projects/[id]/folders/route.ts@@ -0,0 +1,10 @@+import { createFolder } from "@/server/cinema";+import { FolderCreate, body, handle } from "@/server/cinema-schemas";++export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const input = await body(request, FolderCreate, "Give the folder a name");+ return Response.json(createFolder(id, input), { status: 201 });+ });+}diff --git a/src/app/api/cinema/projects/[id]/generate/route.ts b/src/app/api/cinema/projects/[id]/generate/route.tsnew file mode 100644index 00000000..42be38d7--- /dev/null+++ b/src/app/api/cinema/projects/[id]/generate/route.ts@@ -0,0 +1,14 @@+import { generateInProject } from "@/server/cinema-generate";+import { GenerateBody, body, handle } from "@/server/cinema-schemas";++/**+ * Generate from the workspace: plans the run (model, chained steps), checks the project's cost+ * cap, creates the generations and records them in the project (in `folderId`).+ */+export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/generate">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const b = await body(request, GenerateBody, "That request isn't valid");+ return Response.json(generateInProject(id, b.input as Parameters<typeof generateInProject>[1], b.folderId ?? null), { status: 201 });+ });+}diff --git a/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.ts b/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.tsnew file mode 100644index 00000000..903e9c3f--- /dev/null+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.ts@@ -0,0 +1,11 @@+import { setTiles } from "@/server/cinema";+import { TilesPut, body, handle } from "@/server/cinema-schemas";++/** The tiles the browser cut from a grid contact sheet (each already saved as an upload). */+export async function PUT(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/tiles">) {+ return handle(async () => {+ const { id, generationId } = await ctx.params;+ const b = await body(request, TilesPut, "Those tiles aren't valid");+ return Response.json(setTiles(id, generationId, b.tiles));+ });+}diff --git a/src/app/api/cinema/projects/[id]/items/route.ts b/src/app/api/cinema/projects/[id]/items/route.tsnew file mode 100644index 00000000..9c9235bc--- /dev/null+++ b/src/app/api/cinema/projects/[id]/items/route.ts@@ -0,0 +1,44 @@+import { connection } from "next/server";+import { listItems, listStudioGenerations, moveItems, removeItems, setFavorites } from "@/server/cinema";+import { ItemsDelete, ItemsPatch, body, handle } from "@/server/cinema-schemas";++/**+ * The project's generations. `?folder=<id>` one folder (`&nested=1` with its subfolders),+ * `?folder=root` the takes outside any folder, `?favorites=1` liked takes, `?scope=studio` every+ * Cinema Studio generation in every project ("My Generations"). Default: the whole project.+ */+export async function GET(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {+ await connection();+ return handle(async () => {+ const { id } = await ctx.params;+ const qs = new URL(request.url).searchParams;+ if (qs.get("scope") === "studio") return Response.json({ items: listStudioGenerations() });+ const folder = qs.get("folder");+ const items = listItems(id, {+ folderId: folder === "root" ? null : folder || undefined,+ nested: qs.get("nested") === "1",+ favorites: qs.get("favorites") === "1",+ });+ return Response.json({ items });+ });+}++/** Bulk: move to a folder (`folderId`, null = project root) and/or like / unlike. */+export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const b = await body(request, ItemsPatch, "Pick the takes to change");+ if (b.folderId !== undefined) moveItems(id, b.ids, b.folderId);+ if (b.favorite !== undefined) setFavorites(id, b.ids, b.favorite);+ return Response.json({ ok: true });+ });+}++/** Bulk: take out of the project; `deleteGenerations` also deletes them from the library. */+export async function DELETE(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const b = await body(request, ItemsDelete, "Pick the takes to delete");+ return Response.json({ removed: removeItems(id, b.ids, { deleteGenerations: b.deleteGenerations }) });+ });+}diff --git a/src/app/api/cinema/projects/[id]/route.ts b/src/app/api/cinema/projects/[id]/route.tsnew file mode 100644index 00000000..6e5dd5a3--- /dev/null+++ b/src/app/api/cinema/projects/[id]/route.ts@@ -0,0 +1,32 @@+import { connection } from "next/server";+import { CinemaError, deleteProject, getProject, listFolders, spentUsd, updateProject } from "@/server/cinema";+import { ProjectPatch, body, handle } from "@/server/cinema-schemas";+import { cinemaContext } from "@/server/cinema-generate";++/** The project with its folders, its estimated spend and what this install can run (Higgsfield key or not). */+export async function GET(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {+ await connection();+ return handle(async () => {+ const { id } = await ctx.params;+ const project = getProject(id);+ if (!project) throw new CinemaError("Project not found", 404);+ const { higgsfield, cloudAllowed } = cinemaContext();+ return Response.json({ project, folders: listFolders(id), spentUsd: spentUsd(id), context: { higgsfield, cloudAllowed } });+ });+}++export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const patch = await body(request, ProjectPatch, "Those project settings aren't valid");+ return Response.json(updateProject(id, patch));+ });+}++export async function DELETE(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {+ return handle(async () => {+ const { id } = await ctx.params;+ deleteProject(id);+ return new Response(null, { status: 204 });+ });+}diff --git a/src/app/api/cinema/projects/route.ts b/src/app/api/cinema/projects/route.tsnew file mode 100644index 00000000..051abb94--- /dev/null+++ b/src/app/api/cinema/projects/route.ts@@ -0,0 +1,15 @@+import { connection } from "next/server";+import { createProject, listProjects } from "@/server/cinema";+import { ProjectCreate, body, handle } from "@/server/cinema-schemas";++export async function GET() {+ await connection();+ return handle(() => Response.json({ items: listProjects() }));+}++export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, ProjectCreate, "Give the project a name");+ return Response.json(createProject(input), { status: 201 });+ });+}diff --git a/src/server/cinema-director.ts b/src/server/cinema-director.tsnew file mode 100644index 00000000..2b616c3a--- /dev/null+++ b/src/server/cinema-director.ts@@ -0,0 +1,242 @@+import "server-only";+import { nanoid } from "nanoid";+import { z } from "zod";+import {+ APERTURES,+ CAMERA_BODIES,+ CAMERA_MOVES,+ DURATION,+ ERAS,+ FOCAL_LENGTHS,+ GENRES,+ LENSES,+ LIGHTING_PRESETS,+ PALETTES,+ TEMPOS,+ directorSummary,+ type CinemaProject,+ type DirectorMessage,+ type DirectorSettings,+ type DirectorShot,+} from "@/lib/catalog/cinema";+import { appendChat, getChat, getProject, CinemaError } from "./cinema";+import { llmText } from "./enhance";++/**+ * The AI Director: turns an idea or a script into shots with Director settings, camera moves and+ * prompts. It only proposes — every shot card has "Load into prompt bar" and nothing is generated+ * until the user presses Generate (Higgsfield's rule). Uses the configured LLM (Claude or Ollama)+ * and falls back to an offline breakdown so it always answers.+ */++const slugs = (xs: { slug: string | null }[]) => xs.flatMap((x) => (x.slug ? [x.slug] : []));++const SYSTEM = `You are the AI Director of a film studio app (like Higgsfield Cinema Studio's "Mr. Higgs").+You break ideas and scripts into shots, pick the camera, light the scene and write prompts. You never generate anything yourself: the user reviews each shot and presses Generate.++Answer with ONE JSON object and nothing else:+{"reply": "1–3 short sentences to the user", "shots": [{"title": "Shot name", "prompt": "what the camera sees: subject, action, setting, framing", "duration": 5, "moves": ["dolly-in"], "settings": {"genre": "noir", "era": "1980s", "tempo": "calm", "camera": "35mm-film", "lens": "anamorphic", "focal": "50mm", "aperture": "f4-moderate", "lighting": "window", "palette": "neon-rain-at-midnight"}}], "brief": "optional: a project brief, only when the user asks for one"}++Rules:+- Use only these values (omit a field to leave it on Auto):+ genre: ${slugs(GENRES).join(", ")}+ era: ${slugs(ERAS).join(", ")}+ tempo: ${slugs(TEMPOS).join(", ")}+ camera: ${slugs(CAMERA_BODIES).join(", ")}+ lens: ${slugs(LENSES).join(", ")}+ focal: ${slugs(FOCAL_LENGTHS).join(", ")}+ aperture: ${slugs(APERTURES).join(", ")}+ lighting: ${slugs(LIGHTING_PRESETS).join(", ")}+ palette: ${PALETTES.map((p) => p.slug).join(", ")}+ moves (camera moves, 0–3 per shot, in order): ${CAMERA_MOVES.map((m) => m.slug).join(", ")}+- duration: whole seconds from ${DURATION.min} to ${DURATION.max}. Keep @handles (characters, locations) exactly as the user wrote them.+- Put shared look decisions (genre, era, camera, palette, lighting) in every shot's settings so each shot can be loaded on its own.+- Follow the project brief. No shots when the user only asks a question; then just reply.`;++const Shot = z.object({+ title: z.string().max(120).catch("Shot"),+ prompt: z.string().min(1).max(2000),+ duration: z.coerce.number().catch(DURATION.default),+ moves: z.array(z.string()).catch([]),+ settings: z.record(z.string(), z.unknown()).catch({}),+});+const Answer = z.object({+ reply: z.string().catch(""),+ shots: z.array(z.unknown()).catch([]),+ brief: z.string().optional().catch(undefined),+});++const pickSlug = (list: { slug: string | null }[], v: unknown) => (typeof v === "string" && list.some((o) => o.slug === v) ? v : undefined);++/** Keep only values the Director's Panel knows; everything else stays Auto. */+export function cleanSettings(raw: Record<string, unknown>): Partial<DirectorSettings> {+ const out: Partial<DirectorSettings> = {};+ const set = <K extends keyof DirectorSettings>(k: K, v: DirectorSettings[K] | undefined) => {+ if (v !== undefined) out[k] = v;+ };+ set("genre", pickSlug(GENRES, raw.genre));+ set("era", pickSlug(ERAS, raw.era));+ set("tempo", pickSlug(TEMPOS, raw.tempo));+ set("camera", pickSlug(CAMERA_BODIES, raw.camera));+ set("lens", pickSlug(LENSES, raw.lens));+ set("focal", pickSlug(FOCAL_LENGTHS, raw.focal));+ set("aperture", pickSlug(APERTURES, raw.aperture));+ const light = pickSlug(LIGHTING_PRESETS, raw.lighting);+ if (light) out.lighting = { kind: "preset", slug: light };+ const palette = typeof raw.palette === "string" && PALETTES.some((p) => p.slug === raw.palette) ? raw.palette : undefined;+ if (palette) out.palette = { kind: "preset", slug: palette };+ return out;+}++function cleanShot(raw: unknown): DirectorShot | null {+ const s = Shot.safeParse(raw);+ if (!s.success) return null;+ return {+ title: s.data.title.trim() || "Shot",+ prompt: s.data.prompt.trim(),+ duration: Math.max(DURATION.min, Math.min(DURATION.max, Math.round(s.data.duration || DURATION.default))),+ moves: s.data.moves.filter((m) => CAMERA_MOVES.some((c) => c.slug === m)).slice(0, 3),+ settings: cleanSettings(s.data.settings),+ };+}++/** The first {...} block of a model's answer (models sometimes wrap JSON in prose or fences). */+export function parseDirectorAnswer(text: string): { reply: string; shots: DirectorShot[]; brief?: string } | null {+ const start = text.indexOf("{");+ const end = text.lastIndexOf("}");+ if (start < 0 || end <= start) return null;+ try {+ const a = Answer.parse(JSON.parse(text.slice(start, end + 1)));+ return { reply: a.reply.trim(), shots: a.shots.map(cleanShot).filter((s): s is DirectorShot => !!s).slice(0, 12), brief: a.brief?.trim() || undefined };+ } catch {+ return null;+ }+}++// ---------------------------------------------------------------------------+// Offline breakdown (no LLM configured): keywords → look, sentences → beats.++const has = (t: string, ...words: string[]) => words.some((w) => new RegExp(`\\b${w}`, "i").test(t));++function guessLook(t: string, current: DirectorSettings): Partial<DirectorSettings> {+ const s: Partial<DirectorSettings> = {};+ if (has(t, "chase", "fight", "explosion", "heist", "escape", "race", "gun")) s.genre = "action";+ else if (has(t, "ghost", "haunt", "blood", "scream", "monster", "creep")) s.genre = "horror";+ else if (has(t, "detective", "crime", "noir", "smok", "cigarette", "rain")) s.genre = "noir";+ else if (has(t, "funny", "comed", "laugh", "prank", "awkward")) s.genre = "comedy";+ else if (has(t, "battle", "kingdom", "empire", "vast", "epic", "army", "desert")) s.genre = "epic";+ else if (has(t, "love", "tears", "goodbye", "family", "grief", "letter")) s.genre = "drama";+ if (has(t, "commercial", "perfume", "product", "advert", "music video", "trailer")) s.tempo = "dynamic";+ else if (s.genre === "action") s.tempo = "chaotic";+ else if (s.genre === "drama" || s.genre === "noir") s.tempo = "calm";+ if (has(t, "80s", "1980")) s.era = "1980s";+ else if (has(t, "60s", "1960")) s.era = "1960s";+ else if (has(t, "90s", "1990", "vhs")) s.era = "1990s";+ if (has(t, "night", "neon", "candle", "lamp", "bar", "club")) s.lighting = { kind: "preset", slug: "practicals" };+ else if (has(t, "sunset", "backlit", "golden hour", "dawn")) s.lighting = { kind: "preset", slug: "contre-jour" };+ else if (has(t, "window", "morning", "kitchen", "office")) s.lighting = { kind: "preset", slug: "window" };+ else if (s.genre === "horror") s.lighting = { kind: "preset", slug: "silhouette" };+ if (s.genre === "noir") s.palette = { kind: "preset", slug: "neon-rain-at-midnight" };+ else if (s.genre === "epic") s.palette = { kind: "preset", slug: "amber-wasteland" };+ else if (s.genre === "horror") s.palette = { kind: "preset", slug: "the-iron-borough" };+ else if (has(t, "perfume", "fashion", "luxury", "beauty")) s.palette = { kind: "preset", slug: "pink-velvet" };+ s.camera = current.camera ?? (s.era === "1990s" ? "dv-camcorder" : s.era ? "35mm-film" : "modern");+ s.lens = current.lens ?? (s.genre === "epic" || s.genre === "noir" ? "anamorphic" : "clean-sharp");+ // Keep what the user already chose on the panel.+ return { ...s, ...Object.fromEntries(Object.entries(current).filter(([k, v]) => v != null && k !== "emotions")) };+}++const FRAMES: { title: string; frame: string; moves: (t: string) => string[]; focal: string }[] = [+ { title: "Establishing", frame: "Wide establishing shot", moves: (t) => (has(t, "city", "landscape", "desert", "sea", "mountain") ? ["aerial-pullback"] : ["crane-down"]), focal: "24mm" },+ { title: "The action", frame: "Medium shot", moves: (t) => (has(t, "run", "chase", "walk", "drive", "ride") ? ["tracking"] : ["slider-right"]), focal: "35mm" },+ { title: "Close-up", frame: "Close-up", moves: () => ["dolly-in"], focal: "85mm" },+ { title: "Detail", frame: "Insert detail shot", moves: (t) => (has(t, "product", "perfume", "bottle", "watch") ? ["robot-arm"] : ["rack-focus"]), focal: "50mm" },+ { title: "Reaction", frame: "Over-the-shoulder shot", moves: () => ["static-shot"], focal: "50mm" },+ { title: "Turn", frame: "Low-angle medium shot", moves: (t) => (has(t, "fight", "chase", "escape") ? ["whip-pan"] : ["arc-right"]), focal: "35mm" },+ { title: "Reveal", frame: "High wide shot", moves: () => ["crane-up"], focal: "24mm" },+ { title: "Closing", frame: "Wide closing shot", moves: () => ["dolly-out"], focal: "35mm" },+];++/** Split a script into beats: lines, else sentences; a one-line idea gets a 4-beat structure. */+function beats(text: string, want?: number): string[] {+ const body = text+ .replace(/^(please\s+)?(write|make|create|generate|break( down)?|turn)\b[^:]*:\s*/i, "")+ .trim();+ const lines = body.split(/\n+/).map((l) => l.replace(/^\s*(\d+[.)]|[-*•])\s*/, "").trim()).filter((l) => l.length > 3);+ let parts = lines.length > 1 ? lines : body.split(/(?<=[.!?])\s+/).map((s) => s.trim()).filter((s) => s.length > 3);+ const n = want ?? (parts.length > 1 ? Math.min(parts.length, 12) : 4);+ if (parts.length < n) {+ const idea = parts.join(" ") || body;+ parts = Array.from({ length: n }, (_, i) => parts[i] ?? idea);+ }+ return parts.slice(0, n);+}++export function offlineDirector(text: string, project: Pick<CinemaProject, "brief" | "director">): { reply: string; shots: DirectorShot[]; brief?: string } {+ const t = `${text} ${project.brief.body}`;+ if (/\bbrief\b/i.test(text) && !/\bshots?\b|storyboard|script/i.test(text)) {+ const look = guessLook(t, project.director);+ const summary = directorSummary(look as DirectorSettings).join(", ");+ const brief = [+ `Context: ${text.replace(/^(please\s+)?(write|draft|make)\s+(me\s+)?(a\s+)?(project\s+)?brief\s*(for|about)?\s*:?\s*/i, "").trim() || "Describe the production here."}`,+ `Look: ${summary || "decide genre, era, camera and palette on the Director's Panel"}.`,+ "Do: keep characters and locations as @elements so they stay the same in every shot; one idea per shot.",+ "Don't: change wardrobe, time of day or grade between shots of the same scene unless the story asks for it.",+ ].join("\n");+ return { reply: "Here's a starting brief. Apply it to the project, then edit it as you like.", shots: [], brief };+ }+ const count = /(\d+)\s*[- ]?\s*shots?/i.exec(text)?.[1];+ const seconds = /(\d+)\s*[- ]?\s*(s|sec|second)s?\b/i.exec(text)?.[1];+ const parts = beats(text, count ? Math.max(1, Math.min(12, Number(count))) : undefined);+ const each = seconds ? Math.max(DURATION.min, Math.min(DURATION.max, Math.round(Number(seconds) / parts.length))) : DURATION.default;+ const look = guessLook(t, project.director);+ const shots = parts.map((beat, i): DirectorShot => {+ const f = FRAMES[parts.length <= 4 ? [0, 1, 2, 7][i] : i % FRAMES.length] ?? FRAMES[i % FRAMES.length];+ return {+ title: `${i + 1}. ${f.title}`,+ prompt: `${f.frame}: ${beat.replace(/[.\s]+$/, "")}`,+ duration: each,+ moves: f.moves(beat),+ settings: { ...look, focal: project.director.focal ?? f.focal },+ };+ });+ return {+ reply: `Here's a ${shots.length}-shot breakdown${look.genre ? ` with a ${GENRES.find((g) => g.slug === look.genre)?.name.toLowerCase()} look` : ""}. Load a shot into the prompt bar to review it — nothing renders until you press Generate.`,+ shots,+ };+}++function settingsLine(s: DirectorSettings): string {+ const d = directorSummary(s);+ return d.length ? d.join(", ") : "all Auto";+}++/** Add the user's message, ask the Director, store and return the whole conversation. */+export async function askDirector(projectId: string, text: string): Promise<DirectorMessage[]> {+ const project = getProject(projectId);+ if (!project) throw new CinemaError("Project not found", 404);+ const user: DirectorMessage = { id: nanoid(8), role: "user", text: text.trim().slice(0, 8000), createdAt: Date.now() };+ const history = getChat(projectId).slice(-8);+ const context = [+ project.brief.body.trim() ? `Project brief:\n${project.brief.body.trim().slice(0, 4000)}` : "Project brief: (empty)",+ `Project: ${project.name}${project.description ? ` — ${project.description}` : ""}`,+ `Current Director's Panel: ${settingsLine(project.director)}`,+ history.length ? `Recent conversation:\n${history.map((m) => `${m.role === "user" ? "User" : "Director"}: ${m.text}${m.shots?.length ? ` [${m.shots.length} shots]` : ""}`).join("\n")}` : "",+ `User: ${user.text}`,+ ]+ .filter(Boolean)+ .join("\n\n");+ const raw = await llmText(SYSTEM, context).catch(() => null);+ const parsed = raw ? parseDirectorAnswer(raw) : null;+ const answer = parsed && (parsed.reply || parsed.shots.length || parsed.brief) ? { ...parsed, source: "llm" as const } : { ...offlineDirector(user.text, project), source: "offline" as const };+ const reply: DirectorMessage = {+ id: nanoid(8),+ role: "assistant",+ text: answer.reply || (answer.shots.length ? `${answer.shots.length} shots, ready to review.` : "Done."),+ ...(answer.shots.length ? { shots: answer.shots } : {}),+ ...(answer.brief ? { brief: answer.brief } : {}),+ source: answer.source,+ createdAt: Date.now() + 1,+ };+ return appendChat(projectId, user, reply);+}diff --git a/src/server/cinema-generate.ts b/src/server/cinema-generate.tsnew file mode 100644index 00000000..48ae03f5--- /dev/null+++ b/src/server/cinema-generate.ts@@ -0,0 +1,118 @@+import "server-only";+import { nanoid } from "nanoid";+import { getModel } from "@/lib/catalog";+import { SWATCH_PLACEHOLDER, planCinema, withPlaceholders, type CinemaContext, type CinemaGenerateInput, type CinemaPlan, type CinemaStep } from "@/lib/catalog/cinema";+import type { Generation, GenerationRequest } from "@/lib/catalog/types";+import { CinemaError, addItems, getProject, spentUsd } from "./cinema";+import { createGenerations, previewGeneration } from "./generations";+import { encodePng } from "./png";+import { provider } from "./providers";+import { engineMode } from "./settings";+import { saveFile } from "./storage";++/** What this install can run right now (decides Cinema Studio 4.0 vs Seedance, frame fallbacks). */+export function cinemaContext(): CinemaContext {+ return { higgsfield: provider("higgsfield").isConfigured(), cloudAllowed: engineMode() !== "open", has: (id) => !!getModel(id) };+}++declare global {+ var __fuobeSwatches: Map<string, string> | undefined;+}++/** A 12-stripe PNG of the palette: the reference image palette-transfer recolours toward. */+export function swatchUrl(hex: string[]): string {+ globalThis.__fuobeSwatches ??= new Map();+ const key = hex.join(",").toLowerCase();+ const hit = globalThis.__fuobeSwatches.get(key);+ if (hit) return hit;+ const stripe = 32;+ const width = stripe * hex.length;+ const height = 64;+ const data = Buffer.alloc(width * height * 4);+ hex.forEach((h, i) => {+ const n = parseInt(h.replace("#", ""), 16);+ for (let y = 0; y < height; y++)+ for (let x = i * stripe; x < (i + 1) * stripe; x++) data.set([(n >> 16) & 255, (n >> 8) & 255, n & 255, 255], (y * width + x) * 4);+ });+ const asset = saveFile({ data: encodePng({ width, height, data }), contentType: "image/png", name: "palette-swatch.png", source: "upload" });+ globalThis.__fuobeSwatches.set(key, asset.url);+ return asset.url;+}++/** The plan with this project's brief and (unless the request carries its own) Director settings. */+export function planForProject(projectId: string, input: CinemaGenerateInput): CinemaPlan {+ const project = getProject(projectId);+ if (!project) throw new CinemaError("Project not found", 404);+ return planCinema({ ...input, settings: input.settings ?? project.director, brief: project.brief.body }, cinemaContext());+}++/** What the run will really cost (0 for demo-mode steps), from the server's own route choice. */+function realCost(steps: CinemaStep[]): number {+ let total = 0;+ const jobs: Record<string, number> = {};+ for (const s of steps) {+ const p = previewGeneration(withPlaceholders(s));+ const n = s.perJobOf ? (jobs[s.perJobOf] ?? 1) : 1;+ jobs[s.key] = s.after?.length ? n : p.jobs;+ total += (p.costUsd ?? 0) * n;+ }+ return Math.round(total * 1000) / 1000;+}++/** The generations a dependent step waits for: a joined film counts once, otherwise each take. */+function terminal(list: Generation[]): Generation[] {+ return list[0]?.op === "concat" ? [list[0]] : list;+}++export interface CinemaRunResult {+ items: Generation[];+ plan: Pick<CinemaPlan, "notes" | "costUsd" | "outputs"> & { modelId: string };+}++/**+ * Plan, check the project's cost cap, create the chained generations and record them in the project+ * (in `folderId`, the scene the user is looking at).+ */+export function generateInProject(projectId: string, input: CinemaGenerateInput, folderId: string | null = null): CinemaRunResult {+ const project = getProject(projectId);+ if (!project) throw new CinemaError("Project not found", 404);+ const plan = planForProject(projectId, input);+ if (plan.blocker) throw new CinemaError(plan.blocker, 422);+ if (!plan.steps.length) throw new CinemaError("Nothing to generate", 422);++ if (project.costCapUsd != null) {+ const cost = realCost(plan.steps);+ const spent = spentUsd(projectId);+ if (cost > 0 && spent + cost > project.costCapUsd + 1e-9) {+ throw new CinemaError(+ `This run (≈ $${cost.toFixed(2)}) would take the project past its $${project.costCapUsd.toFixed(2)} limit — $${spent.toFixed(2)} is already spent. Raise the limit in project settings.`,+ 422,+ );+ }+ }++ const batchId = nanoid(10);+ const made: Record<string, Generation[]> = {};+ const all: Generation[] = [];+ try {+ for (const step of plan.steps) {+ const req: GenerationRequest = structuredClone(step.request);+ if (step.swatch && req.inputs?.images) req.inputs.images = req.inputs.images.map((u) => (u === SWATCH_PLACEHOLDER ? swatchUrl(step.swatch!) : u));+ let created: Generation[] = [];+ if (step.perJobOf) {+ for (const t of terminal(made[step.perJobOf] ?? [])) created.push(...createGenerations(req, { batchId, dependsOn: t.id }));+ } else if (step.after?.length) {+ const deps = step.after.map((k) => terminal(made[k] ?? [])[0]?.id).filter((x): x is string => !!x);+ created = createGenerations(req, { batchId, dependsOn: deps });+ } else created = createGenerations(req, { batchId });+ made[step.key] = created;+ all.push(...created);+ }+ } catch (e) {+ // Keep what already started visible in the project, then report the step that failed.+ if (all.length) addItems(projectId, all.map((g) => g.id), folderId);+ throw new CinemaError((e as Error).message, 422);+ }+ addItems(projectId, all.map((g) => g.id), folderId);+ return { items: all, plan: { notes: plan.notes, costUsd: plan.costUsd, outputs: plan.outputs, modelId: plan.model.id } };+}diff --git a/src/server/cinema-schemas.ts b/src/server/cinema-schemas.tsnew file mode 100644index 00000000..dc916f92--- /dev/null+++ b/src/server/cinema-schemas.ts@@ -0,0 +1,120 @@+import "server-only";+import { z } from "zod";+import { CinemaError } from "./cinema";++/** Request bodies of /api/cinema/** (zod drops unknown keys). */++const Hex = z.string().regex(/^#[0-9a-fA-F]{6}$/);+const FileRef = z.string().startsWith("/api/files/");+const Slug = z.string().max(80).nullable().optional();++export const DirectorSchema = z.object({+ genre: Slug,+ era: Slug,+ tempo: Slug,+ camera: Slug,+ lens: Slug,+ focal: Slug,+ aperture: Slug,+ palette: z+ .union([z.object({ kind: z.literal("preset"), slug: z.string().max(80) }), z.object({ kind: z.literal("custom"), name: z.string().max(60), hex: z.array(Hex).min(1).max(12) })])+ .nullable()+ .optional(),+ paletteLock: z.boolean().optional(),+ lighting: z+ .union([+ z.object({ kind: z.literal("preset"), slug: z.string().max(80) }),+ z.object({+ kind: z.literal("custom"),+ lights: z.array(z.object({ direction: z.string().max(40), color: Hex, brightness: z.number().int().min(0).max(100), diffuse: z.number().int().min(0).max(100) })).min(1).max(2),+ }),+ ])+ .nullable()+ .optional(),+ emotions: z.record(z.string().max(60), z.object({ family: z.string().max(30), step: z.number().int().min(0).max(2) })).optional(),+});++export const ProjectCreate = z.object({+ name: z.string().trim().min(1).max(80),+ description: z.string().max(140).nullable().optional(),+ cover: FileRef.nullable().optional(),+ costCapUsd: z.number().min(0).max(100_000).nullable().optional(),+});++export const ProjectPatch = z.object({+ name: z.string().trim().min(1).max(80).optional(),+ description: z.string().max(140).nullable().optional(),+ cover: FileRef.nullable().optional(),+ costCapUsd: z.number().min(0).max(100_000).nullable().optional(),+ director: DirectorSchema.optional(),+ palettes: z.array(z.object({ name: z.string().max(60), hex: z.array(Hex).min(1).max(12) })).max(60).optional(),+ brief: z.object({ title: z.string().max(120).optional(), body: z.string().max(20_000).optional() }).optional(),+ pinned: z.boolean().optional(),+});++export const FolderCreate = z.object({+ name: z.string().trim().min(1).max(60),+ parentId: z.string().max(40).nullable().optional(),+ color: Hex.nullable().optional(),+});++export const FolderPatch = z.object({+ name: z.string().trim().min(1).max(60).optional(),+ parentId: z.string().max(40).nullable().optional(),+ color: Hex.nullable().optional(),+ pinned: z.boolean().optional(),+ position: z.number().int().min(0).max(100_000).optional(),+});++const Ids = z.array(z.string().max(40)).min(1).max(500);+export const ItemsPatch = z.object({ ids: Ids, folderId: z.string().max(40).nullable().optional(), favorite: z.boolean().optional() });+export const ItemsDelete = z.object({ ids: Ids, deleteGenerations: z.boolean().optional() });+export const TilesPut = z.object({ tiles: z.array(z.object({ url: FileRef, row: z.number().int().min(0).max(15), col: z.number().int().min(0).max(15) })).max(16) });++const Shot = z.object({ prompt: z.string().max(2000), duration: z.number().min(1).max(30) });++export const GenerateBody = z.object({+ folderId: z.string().max(40).nullable().optional(),+ input: z.object({+ engine: z.enum(["cloud", "open"]),+ mode: z.enum(["video", "image"]),+ action: z.enum(["generate", "extend-forward", "extend-backward", "edit", "grid", "cast", "location", "location-view"]).default("generate"),+ modelId: z.string().max(80).optional(),+ prompt: z.string().max(60_000).default(""),+ moves: z.array(z.string().max(40)).max(12).optional(),+ settings: DirectorSchema.optional(),+ images: z.array(FileRef).max(30).optional(),+ videos: z.array(FileRef).max(10).optional(),+ audios: z.array(FileRef).max(10).optional(),+ duration: z.number().min(1).max(30).optional(),+ resolution: z.string().max(10).optional(),+ aspectRatio: z.string().max(10).optional(),+ batch: z.number().int().min(1).max(4).optional(),+ audio: z.boolean().optional(),+ multiShot: z.object({ mode: z.enum(["off", "auto", "manual"]), shots: z.array(Shot).max(12).optional() }).optional(),+ source: z.object({ url: FileRef, kind: z.enum(["image", "video"]), firstFrame: FileRef.optional() }).optional(),+ grid: z.object({ size: z.enum(["2x2", "3x3", "4x4"]), type: z.enum(["freeform", "zooms", "shots", "next_shots", "prev_shots"]) }).optional(),+ cast: z.record(z.string().max(40), z.union([z.string().max(300), z.number(), z.array(z.string().max(60)).max(10)])).optional(),+ view: z.string().max(20).optional(),+ }),+});++export const DirectorAsk = z.object({ text: z.string().trim().min(1).max(8000) });++/** Parse a JSON body or answer 400 with `message`. */+export async function body<S extends z.ZodType>(request: Request, schema: S, message: string): Promise<z.infer<S>> {+ const parsed = schema.safeParse(await request.json().catch(() => null));+ if (!parsed.success) throw new CinemaError(message, 400);+ return parsed.data;+}++/** Turn thrown errors into the API's `{ error }` responses. */+export async function handle(fn: () => Promise<Response> | Response): Promise<Response> {+ try {+ return await fn();+ } catch (e) {+ if (e instanceof CinemaError) return Response.json({ error: e.message }, { status: e.status });+ console.error("[cinema]", e);+ return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });+ }+}diff --git a/src/server/cinema.ts b/src/server/cinema.tsnew file mode 100644index 00000000..8b1b6993--- /dev/null+++ b/src/server/cinema.ts@@ -0,0 +1,415 @@+import "server-only";+import { nanoid } from "nanoid";+import type { CinemaFolder, CinemaItem, CinemaProject, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";+import type { Generation } from "@/lib/catalog/types";+import { db } from "./db";+import { deleteGeneration, getGeneration, listGenerations } from "./generations";++/**+ * Cinema Studio projects: Director settings, brief and AI Director chat per project, nested folders+ * (scenes) and which generations live where. Generations stay ordinary rows in `generations`; a+ * project only records their ids (cinema_items), written when a take is made from the workspace.+ */++export class CinemaError extends Error {+ constructor(+ message: string,+ readonly status = 400,+ ) {+ super(message);+ }+}++interface ProjectRow {+ id: string;+ name: string;+ description: string | null;+ cover_url: string | null;+ cost_cap_usd: number | null;+ director_json: string;+ palettes_json: string;+ brief_title: string;+ brief_body: string;+ chat_json: string;+ pinned: number;+ created_at: number;+ updated_at: number;+}++interface FolderRow {+ id: string;+ project_id: string;+ parent_id: string | null;+ name: string;+ color: string | null;+ pinned: number;+ position: number;+ created_at: number;+ updated_at: number;+}++interface ItemRow {+ project_id: string;+ generation_id: string;+ folder_id: string | null;+ meta_json: string | null;+ created_at: number;+}++const parse = <T,>(s: string | null | undefined, fallback: T): T => {+ try {+ return s ? (JSON.parse(s) as T) : fallback;+ } catch {+ return fallback;+ }+};++const toProject = (r: ProjectRow): CinemaProject => ({+ id: r.id,+ name: r.name,+ description: r.description,+ cover: r.cover_url,+ costCapUsd: r.cost_cap_usd,+ director: parse<DirectorSettings>(r.director_json, {}),+ palettes: parse(r.palettes_json, []),+ brief: { title: r.brief_title, body: r.brief_body },+ pinned: !!r.pinned,+ createdAt: r.created_at,+ updatedAt: r.updated_at,+});++const toFolder = (r: FolderRow): CinemaFolder => ({+ id: r.id,+ projectId: r.project_id,+ parentId: r.parent_id,+ name: r.name,+ color: r.color,+ pinned: !!r.pinned,+ position: r.position,+ createdAt: r.created_at,+ updatedAt: r.updated_at,+});++const toItem = (r: ItemRow): CinemaItem => {+ const meta = parse<{ tiles?: CinemaTile[] }>(r.meta_json, {});+ return { generationId: r.generation_id, folderId: r.folder_id, createdAt: r.created_at, ...(meta.tiles?.length ? { tiles: meta.tiles } : {}) };+};++/** A generation that still exists (soft-deleted rows from the Trash, when there is one, are left out). */+function liveGeneration(id: string): Generation | null {+ const g = getGeneration(id) as (Generation & { deletedAt?: number | null }) | null;+ return g && !g.deletedAt ? g : null;+}++// ---------------------------------------------------------------------------+// Projects++function projectRow(id: string): ProjectRow | undefined {+ return db().prepare("SELECT * FROM cinema_projects WHERE id = ?").get(id) as ProjectRow | undefined;+}++export function getProject(id: string): CinemaProject | null {+ const r = projectRow(id);+ return r ? toProject(r) : null;+}++function requireProject(id: string): CinemaProject {+ const p = getProject(id);+ if (!p) throw new CinemaError("Project not found", 404);+ return p;+}++/** Estimated spend so far: the recorded cost of every take that didn't fail. */+export function spentUsd(projectId: string): number {+ const r = db()+ .prepare(+ `SELECT COALESCE(SUM(g.cost_usd), 0) AS s FROM cinema_items i JOIN generations g ON g.id = i.generation_id+ WHERE i.project_id = ? AND g.status NOT IN ('failed', 'canceled')`,+ )+ .get(projectId) as { s: number };+ return Math.round(r.s * 1000) / 1000;+}++/** Newest finished image (or video) of a project: the card cover when none was picked. */+function autoCover(projectId: string): string | null {+ const ids = db().prepare("SELECT generation_id FROM cinema_items WHERE project_id = ? ORDER BY created_at DESC LIMIT 40").all(projectId) as { generation_id: string }[];+ let video: string | null = null;+ for (const { generation_id } of ids) {+ const g = db().prepare("SELECT status, outputs_json FROM generations WHERE id = ?").get(generation_id) as { status: string; outputs_json: string } | undefined;+ if (g?.status !== "succeeded") continue;+ const outs = parse<{ url: string; kind: string }[]>(g.outputs_json, []);+ const img = outs.find((o) => o.kind === "image");+ if (img) return img.url;+ video ??= outs.find((o) => o.kind === "video")?.url ?? null;+ }+ return video;+}++export function listProjects(): CinemaProject[] {+ const rows = db().prepare("SELECT * FROM cinema_projects ORDER BY pinned DESC, updated_at DESC").all() as ProjectRow[];+ return rows.map((r) => {+ const items = (db().prepare("SELECT COUNT(*) AS n FROM cinema_items WHERE project_id = ?").get(r.id) as { n: number }).n;+ return { ...toProject(r), stats: { items, spentUsd: spentUsd(r.id), cover: r.cover_url ?? autoCover(r.id) } };+ });+}++export function createProject(input: { name: string; description?: string | null; cover?: string | null; costCapUsd?: number | null }): CinemaProject {+ const now = Date.now();+ const row: ProjectRow = {+ id: nanoid(10),+ name: input.name.trim().slice(0, 80) || "Untitled project",+ description: input.description?.trim().slice(0, 140) || null,+ cover_url: input.cover ?? null,+ cost_cap_usd: input.costCapUsd ?? null,+ director_json: "{}",+ palettes_json: "[]",+ brief_title: "",+ brief_body: "",+ chat_json: "[]",+ pinned: 0,+ created_at: now,+ updated_at: now,+ };+ db()+ .prepare(`INSERT INTO cinema_projects (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)+ .run(row);+ return toProject(row);+}++export interface ProjectPatch {+ name?: string;+ description?: string | null;+ cover?: string | null;+ costCapUsd?: number | null;+ director?: DirectorSettings;+ palettes?: CinemaProject["palettes"];+ brief?: { title?: string; body?: string };+ pinned?: boolean;+}++export function updateProject(id: string, patch: ProjectPatch): CinemaProject {+ const cur = requireProject(id);+ const next = {+ id,+ name: patch.name?.trim().slice(0, 80) || cur.name,+ description: patch.description === undefined ? cur.description : patch.description?.trim().slice(0, 140) || null,+ cover_url: patch.cover === undefined ? cur.cover : patch.cover,+ cost_cap_usd: patch.costCapUsd === undefined ? cur.costCapUsd : patch.costCapUsd,+ director_json: JSON.stringify(patch.director ?? cur.director),+ palettes_json: JSON.stringify((patch.palettes ?? cur.palettes).slice(0, 60)),+ brief_title: patch.brief?.title === undefined ? cur.brief.title : patch.brief.title.slice(0, 120),+ brief_body: patch.brief?.body === undefined ? cur.brief.body : patch.brief.body.slice(0, 20_000),+ pinned: patch.pinned === undefined ? Number(cur.pinned) : Number(patch.pinned),+ updated_at: Date.now(),+ };+ db()+ .prepare(+ `UPDATE cinema_projects SET name = @name, description = @description, cover_url = @cover_url, cost_cap_usd = @cost_cap_usd,+ director_json = @director_json, palettes_json = @palettes_json, brief_title = @brief_title, brief_body = @brief_body,+ pinned = @pinned, updated_at = @updated_at WHERE id = @id`,+ )+ .run(next);+ return getProject(id)!;+}++/** Deletes the project and its folders; its generations stay in the library. */+export function deleteProject(id: string): void {+ db().transaction(() => {+ db().prepare("DELETE FROM cinema_items WHERE project_id = ?").run(id);+ db().prepare("DELETE FROM cinema_folders WHERE project_id = ?").run(id);+ db().prepare("DELETE FROM cinema_projects WHERE id = ?").run(id);+ })();+}++function touch(projectId: string): void {+ db().prepare("UPDATE cinema_projects SET updated_at = ? WHERE id = ?").run(Date.now(), projectId);+}++// ---------------------------------------------------------------------------+// AI Director chat (kept on the project: one production, one conversation)++export function getChat(projectId: string): DirectorMessage[] {+ const r = projectRow(projectId);+ if (!r) throw new CinemaError("Project not found", 404);+ return parse<DirectorMessage[]>(r.chat_json, []);+}++export function appendChat(projectId: string, ...messages: DirectorMessage[]): DirectorMessage[] {+ const next = [...getChat(projectId), ...messages].slice(-100);+ db().prepare("UPDATE cinema_projects SET chat_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(next), Date.now(), projectId);+ return next;+}++export function clearChat(projectId: string): void {+ db().prepare("UPDATE cinema_projects SET chat_json = '[]' WHERE id = ?").run(projectId);+}++// ---------------------------------------------------------------------------+// Folders (scenes)++export function listFolders(projectId: string): CinemaFolder[] {+ return (db().prepare("SELECT * FROM cinema_folders WHERE project_id = ? ORDER BY pinned DESC, position ASC, created_at ASC").all(projectId) as FolderRow[]).map(toFolder);+}++function folderRow(id: string): FolderRow | undefined {+ return db().prepare("SELECT * FROM cinema_folders WHERE id = ?").get(id) as FolderRow | undefined;+}++/** A folder and everything nested in it. */+export function descendants(projectId: string, folderId: string): Set<string> {+ const folders = listFolders(projectId);+ const out = new Set([folderId]);+ let grew = true;+ while (grew) {+ grew = false;+ for (const f of folders) if (f.parentId && out.has(f.parentId) && !out.has(f.id)) (out.add(f.id), (grew = true));+ }+ return out;+}++function checkParent(projectId: string, parentId: string | null | undefined, self?: string): void {+ if (!parentId) return;+ const p = folderRow(parentId);+ if (!p || p.project_id !== projectId) throw new CinemaError("That folder doesn't exist", 404);+ if (self && descendants(projectId, self).has(parentId)) throw new CinemaError("Cannot move into a subfolder");+}++export function createFolder(projectId: string, input: { name: string; parentId?: string | null; color?: string | null }): CinemaFolder {+ requireProject(projectId);+ checkParent(projectId, input.parentId);+ const now = Date.now();+ const position = (db().prepare("SELECT COALESCE(MAX(position), -1) + 1 AS p FROM cinema_folders WHERE project_id = ?").get(projectId) as { p: number }).p;+ const row: FolderRow = {+ id: nanoid(10),+ project_id: projectId,+ parent_id: input.parentId ?? null,+ name: input.name.trim().slice(0, 60) || "New scene",+ color: input.color ?? null,+ pinned: 0,+ position,+ created_at: now,+ updated_at: now,+ };+ db()+ .prepare(`INSERT INTO cinema_folders (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)+ .run(row);+ touch(projectId);+ return toFolder(row);+}++export function updateFolder(projectId: string, id: string, patch: { name?: string; color?: string | null; pinned?: boolean; parentId?: string | null; position?: number }): CinemaFolder {+ const cur = folderRow(id);+ if (!cur || cur.project_id !== projectId) throw new CinemaError("Folder not found", 404);+ if (patch.parentId !== undefined) checkParent(projectId, patch.parentId, id);+ db()+ .prepare("UPDATE cinema_folders SET name = ?, color = ?, pinned = ?, parent_id = ?, position = ?, updated_at = ? WHERE id = ?")+ .run(+ patch.name?.trim().slice(0, 60) || cur.name,+ patch.color === undefined ? cur.color : patch.color,+ patch.pinned === undefined ? cur.pinned : Number(patch.pinned),+ patch.parentId === undefined ? cur.parent_id : patch.parentId,+ patch.position ?? cur.position,+ Date.now(),+ id,+ );+ touch(projectId);+ return toFolder(folderRow(id)!);+}++/** Deleting a folder moves its takes and subfolders up to its parent (as Higgsfield does). */+export function deleteFolder(projectId: string, id: string): void {+ const cur = folderRow(id);+ if (!cur || cur.project_id !== projectId) throw new CinemaError("Folder not found", 404);+ db().transaction(() => {+ db().prepare("UPDATE cinema_items SET folder_id = ? WHERE project_id = ? AND folder_id = ?").run(cur.parent_id, projectId, id);+ db().prepare("UPDATE cinema_folders SET parent_id = ? WHERE project_id = ? AND parent_id = ?").run(cur.parent_id, projectId, id);+ db().prepare("DELETE FROM cinema_folders WHERE id = ?").run(id);+ })();+ touch(projectId);+}++// ---------------------------------------------------------------------------+// Items: the project's generations++export type CinemaGeneration = Generation & { folderId: string | null; tiles?: CinemaTile[] };++export interface ItemQuery {+ /** A folder id; null = the project root only; undefined = everything in the project. */+ folderId?: string | null;+ /** With a folder: also the takes in its subfolders. */+ nested?: boolean;+ favorites?: boolean;+}++export function listItems(projectId: string, q: ItemQuery = {}): CinemaGeneration[] {+ requireProject(projectId);+ let rows = db().prepare("SELECT * FROM cinema_items WHERE project_id = ? ORDER BY created_at DESC").all(projectId) as ItemRow[];+ if (q.folderId === null) rows = rows.filter((r) => !r.folder_id);+ else if (q.folderId) {+ const set = q.nested ? descendants(projectId, q.folderId) : new Set([q.folderId]);+ rows = rows.filter((r) => r.folder_id && set.has(r.folder_id));+ }+ const out: CinemaGeneration[] = [];+ for (const r of rows) {+ const g = liveGeneration(r.generation_id);+ if (!g) continue;+ if (q.favorites && !g.favorite) continue;+ const item = toItem(r);+ out.push({ ...g, folderId: item.folderId, ...(item.tiles ? { tiles: item.tiles } : {}) });+ }+ return out.sort((a, b) => b.createdAt - a.createdAt);+}++/** Every Cinema Studio generation, whichever project it's in ("My Generations"). */+export function listStudioGenerations(): CinemaGeneration[] {+ const folders = new Map(+ (db().prepare("SELECT generation_id, folder_id FROM cinema_items").all() as { generation_id: string; folder_id: string | null }[]).map((r) => [r.generation_id, r.folder_id]),+ );+ return listGenerations({ features: ["cinema*"], limit: 200 })+ .filter((g) => !(g as Generation & { deletedAt?: number | null }).deletedAt)+ .map((g) => ({ ...g, folderId: folders.get(g.id) ?? null }));+}++export function addItems(projectId: string, generationIds: string[], folderId: string | null = null): void {+ requireProject(projectId);+ if (folderId) checkParent(projectId, folderId);+ const now = Date.now();+ const ins = db().prepare("INSERT OR IGNORE INTO cinema_items (project_id, generation_id, folder_id, meta_json, created_at) VALUES (?, ?, ?, NULL, ?)");+ db().transaction(() => generationIds.forEach((id, i) => ins.run(projectId, id, folderId, now + i)))();+ touch(projectId);+}++export function moveItems(projectId: string, generationIds: string[], folderId: string | null): number {+ requireProject(projectId);+ if (folderId) checkParent(projectId, folderId);+ const up = db().prepare("UPDATE cinema_items SET folder_id = ? WHERE project_id = ? AND generation_id = ?");+ let n = 0;+ db().transaction(() => generationIds.forEach((id) => (n += up.run(folderId, projectId, id).changes)))();+ touch(projectId);+ return n;+}++/** Remove takes from the project; with `deleteGenerations` they are deleted from the library too. */+export function removeItems(projectId: string, generationIds: string[], opts: { deleteGenerations?: boolean } = {}): number {+ requireProject(projectId);+ const del = db().prepare("DELETE FROM cinema_items WHERE project_id = ? AND generation_id = ?");+ let n = 0;+ db().transaction(() => generationIds.forEach((id) => (n += del.run(projectId, id).changes)))();+ if (opts.deleteGenerations) for (const id of generationIds) deleteGeneration(id);+ touch(projectId);+ return n;+}++export function setFavorites(projectId: string, generationIds: string[], favorite: boolean): void {+ requireProject(projectId);+ const up = db().prepare("UPDATE generations SET favorite = ?, updated_at = ? WHERE id = ? AND id IN (SELECT generation_id FROM cinema_items WHERE project_id = ?)");+ db().transaction(() => generationIds.forEach((id) => up.run(favorite ? 1 : 0, Date.now(), id, projectId)))();+}++export function setTiles(projectId: string, generationId: string, tiles: CinemaTile[]): CinemaItem {+ const r = db().prepare("SELECT * FROM cinema_items WHERE project_id = ? AND generation_id = ?").get(projectId, generationId) as ItemRow | undefined;+ if (!r) throw new CinemaError("That take isn't in this project", 404);+ const meta = { ...parse<Record<string, unknown>>(r.meta_json, {}), tiles: tiles.slice(0, 16) };+ db().prepare("UPDATE cinema_items SET meta_json = ? WHERE project_id = ? AND generation_id = ?").run(JSON.stringify(meta), projectId, generationId);+ return toItem({ ...r, meta_json: JSON.stringify(meta) });+}diff --git a/src/server/db.ts b/src/server/db.tsindex 994f90a9..e15d33c7 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -101,6 +101,43 @@ const MIGRATIONS: string[] = [updated_at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS assist_threads_updated ON assist_threads(updated_at DESC);`,+ // Cinema Studio: projects (Director settings, brief, AI Director chat), folders = scenes, and the generations in them.+ `CREATE TABLE IF NOT EXISTS cinema_projects (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ cover_url TEXT,+ cost_cap_usd REAL,+ director_json TEXT NOT NULL DEFAULT '{}',+ palettes_json TEXT NOT NULL DEFAULT '[]',+ brief_title TEXT NOT NULL DEFAULT '',+ brief_body TEXT NOT NULL DEFAULT '',+ chat_json TEXT NOT NULL DEFAULT '[]',+ pinned INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE TABLE IF NOT EXISTS cinema_folders (+ id TEXT PRIMARY KEY,+ project_id TEXT NOT NULL,+ parent_id TEXT,+ name TEXT NOT NULL,+ color TEXT,+ pinned INTEGER NOT NULL DEFAULT 0,+ position INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS cinema_folders_project ON cinema_folders(project_id);+ CREATE TABLE IF NOT EXISTS cinema_items (+ project_id TEXT NOT NULL,+ generation_id TEXT NOT NULL,+ folder_id TEXT,+ meta_json TEXT,+ created_at INTEGER NOT NULL,+ PRIMARY KEY (project_id, generation_id)+ );+ CREATE INDEX IF NOT EXISTS cinema_items_generation ON cinema_items(generation_id);`,];declare global {diff --git a/tests/cinema-api.test.ts b/tests/cinema-api.test.tsnew file mode 100644index 00000000..9b6400e4--- /dev/null+++ b/tests/cinema-api.test.ts@@ -0,0 +1,201 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+// No LLM in tests: the AI Director answers offline.+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const gens = await import("@/server/generations");+const cinema = await import("@/server/cinema");+const { generateInProject, swatchUrl } = await import("@/server/cinema-generate");+const { askDirector, offlineDirector, parseDirectorAnswer } = await import("@/server/cinema-director");+const projectsRoute = await import("@/app/api/cinema/projects/route");+const projectRoute = await import("@/app/api/cinema/projects/[id]/route");+const foldersRoute = await import("@/app/api/cinema/projects/[id]/folders/route");+const folderRoute = await import("@/app/api/cinema/projects/[id]/folders/[folderId]/route");+const itemsRoute = await import("@/app/api/cinema/projects/[id]/items/route");+const generateRoute = await import("@/app/api/cinema/projects/[id]/generate/route");+const tilesRoute = await import("@/app/api/cinema/projects/[id]/items/[generationId]/tiles/route");++beforeAll(() => {+ setSetting("demoMode", "auto");+ setSetting("enhanceProvider", "none");+});+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const json = (method: string, body?: unknown) =>+ new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) });++async function settle(id: string, ms = 40_000) {+ const until = Date.now() + ms;+ for (;;) {+ const g = gens.getGeneration(id)!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);+ await new Promise((r) => setTimeout(r, 300));+ }+}++const VIDEO = {+ engine: "cloud" as const,+ mode: "video" as const,+ action: "generate" as const,+ prompt: "A detective lights a match in the rain",+ moves: ["dolly-in", "whip-pan"],+ duration: 5,+ aspectRatio: "16:9",+ batch: 1,+};++describe("Cinema API", () => {+ it("creates, lists and updates a project (Director settings and brief persist)", async () => {+ const res = await projectsRoute.POST(json("POST", { name: "Night Shift", description: "A neo-noir short" }));+ expect(res.status).toBe(201);+ const p = await res.json();+ expect(p).toMatchObject({ name: "Night Shift", description: "A neo-noir short", director: {}, brief: { title: "", body: "" } });+ expect((await projectsRoute.POST(json("POST", { name: "" }))).status).toBe(400);+ expect((await projectsRoute.POST(json("POST", { name: "x", description: "a".repeat(141) }))).status).toBe(400);++ const patch = await projectRoute.PATCH(+ json("PATCH", { director: { genre: "noir", palette: { kind: "preset", slug: "neon-rain-at-midnight" } }, brief: { body: "Rain, neon, regret." }, costCapUsd: 5 }),+ params({ id: p.id }),+ );+ expect(patch.status).toBe(200);+ const again = cinema.getProject(p.id)!;+ expect(again.director).toEqual({ genre: "noir", palette: { kind: "preset", slug: "neon-rain-at-midnight" } });+ expect(again.brief.body).toBe("Rain, neon, regret.");+ expect(again.costCapUsd).toBe(5);+ expect(cinema.listProjects().map((x) => x.name)).toContain("Night Shift");+ expect((await projectRoute.PATCH(json("PATCH", { director: { palette: { kind: "custom", name: "x", hex: ["red"] } } }), params({ id: p.id }))).status).toBe(400);+ expect((await projectRoute.PATCH(json("PATCH", { name: "y" }), params({ id: "nope" }))).status).toBe(404);+ });++ it("nests folders, refuses a move into its own subfolder and moves contents up on delete", async () => {+ const p = cinema.createProject({ name: "Folders" });+ const scene = await (await foldersRoute.POST(json("POST", { name: "Scene 1", color: "#c86058" }), params({ id: p.id }))).json();+ const take = await (await foldersRoute.POST(json("POST", { name: "Takes", parentId: scene.id }), params({ id: p.id }))).json();+ expect(take.parentId).toBe(scene.id);+ const bad = await folderRoute.PATCH(json("PATCH", { parentId: take.id }), params({ id: p.id, folderId: scene.id }));+ expect(bad.status).toBe(400);+ expect((await bad.json()).error).toBe("Cannot move into a subfolder");+ const pinned = await (await folderRoute.PATCH(json("PATCH", { pinned: true, name: "Opening" }), params({ id: p.id, folderId: scene.id }))).json();+ expect(pinned).toMatchObject({ pinned: true, name: "Opening", color: "#c86058" });++ const g = gens.createGenerations({ feature: "cinema", modelId: "nano-banana-pro", prompt: "a still" })[0];+ cinema.addItems(p.id, [g.id], take.id);+ expect(cinema.listItems(p.id, { folderId: scene.id }).length).toBe(0);+ expect(cinema.listItems(p.id, { folderId: scene.id, nested: true }).map((x) => x.id)).toEqual([g.id]);+ expect((await folderRoute.DELETE(json("DELETE"), params({ id: p.id, folderId: take.id }))).status).toBe(204);+ expect(cinema.listItems(p.id, { folderId: scene.id }).map((x) => x.folderId)).toEqual([scene.id]);++ // Bulk move to the root, like, then delete from the library.+ expect((await itemsRoute.PATCH(json("PATCH", { ids: [g.id], folderId: null, favorite: true }), params({ id: p.id }))).status).toBe(200);+ expect(cinema.listItems(p.id, { folderId: null })[0]).toMatchObject({ id: g.id, folderId: null, favorite: true });+ expect(cinema.listItems(p.id, { favorites: true })).toHaveLength(1);+ expect((await (await itemsRoute.DELETE(json("DELETE", { ids: [g.id], deleteGenerations: true }), params({ id: p.id }))).json()).removed).toBe(1);+ expect(gens.getGeneration(g.id)).toBeNull();+ });++ it("generates in demo mode and records the take in the folder it was made in", async () => {+ const p = cinema.createProject({ name: "Demo run" });+ cinema.updateProject(p.id, { brief: { body: "Rain, neon, regret." } });+ const folder = cinema.createFolder(p.id, { name: "Scene 2" });+ const res = await generateRoute.POST(json("POST", { input: { ...VIDEO, settings: { genre: "noir", focal: "50mm" } }, folderId: folder.id }), params({ id: p.id }));+ expect(res.status).toBe(201);+ const { items, plan } = await res.json();+ // No Higgsfield key: Seedance 2.5 with the Director compiled into the prompt.+ expect(plan.modelId).toBe("seedance-2-5");+ expect(items).toHaveLength(1);+ const g = gens.getGeneration(items[0].id)!;+ expect(g.prompt).toMatch(/^Project brief: Rain, neon, regret\. A detective lights a match in the rain\. Noir film/);+ expect(g.prompt).toMatch(/50mm focal length/);+ expect(cinema.listItems(p.id, { folderId: folder.id }).map((x) => x.id)).toEqual([g.id]);+ expect((await settle(g.id)).status).toBe("succeeded");++ const bad = await generateRoute.POST(json("POST", { input: { ...VIDEO, prompt: "" } }), params({ id: p.id }));+ expect(bad.status).toBe(422);+ expect((await bad.json()).error).toBe("Describe your scene first");+ const still = await generateRoute.POST(json("POST", { input: { ...VIDEO, mode: "image", settings: {} } }), params({ id: p.id }));+ expect((await still.json()).error).toMatch(/Camera settings are required/);+ }, 60_000);++ it("open engine: a palette-lock step waits for each take and gets the palette swatch", async () => {+ const p = cinema.createProject({ name: "Open run" });+ const { items } = generateInProject(p.id, { ...VIDEO, engine: "open", batch: 2, settings: { palette: { kind: "preset", slug: "the-circus" } } });+ expect(items.map((g) => g.modelId)).toEqual(["oss-wan22-14b-fast", "oss-wan22-14b-fast", "oss-palette-video", "oss-palette-video"]);+ const lock = items[2];+ expect(lock.request.inputs?.images?.[0]).toBe(swatchUrl(["#090a0b", "#900304", "#1d5768", "#58554a", "#8e5917", "#627163", "#979d7e", "#7daca6", "#7f907d", "#add3c0", "#ccebd8", "#b70204"]));+ const done = await settle(lock.id, 50_000);+ expect(done.status).toBe("succeeded");+ expect(done.request.inputs?.video).toBe(gens.getGeneration(items[0].id)!.outputs[0].url);+ expect(cinema.listItems(p.id)).toHaveLength(4);+ }, 70_000);++ it("refuses a run that would pass the project's cost cap", () => {+ const p = cinema.createProject({ name: "Capped", costCapUsd: 0.5 });+ // Demo mode runs are free, so the guard only bites on real (paid) routes; previewing with a fake key shows the message.+ setSetting("falKey", "test-key");+ try {+ expect(() => generateInProject(p.id, { ...VIDEO, duration: 10 })).toThrow(/past its \$0\.50 limit/);+ } finally {+ setSetting("falKey", "");+ }+ });++ it("extend backward chains first frame → the moment before → a clip ending on it", async () => {+ const p = cinema.createProject({ name: "Prequel" });+ const src = gens.createGenerations({ feature: "cinema", modelId: "seedance-2-5", prompt: "source take", params: { duration: 5 } })[0];+ const take = await settle(src.id);+ const { items } = generateInProject(p.id, { ...VIDEO, action: "extend-backward", prompt: "he walks up to the door", source: { url: take.outputs[0].url, kind: "video" } });+ expect(items.map((g) => g.op)).toEqual(["frame", "edit", "flf2v"]);+ const film = await settle(items[2].id, 60_000);+ expect(film.status).toBe("succeeded");+ expect(film.request.inputs?.endImage).toBe(gens.getGeneration(items[0].id)!.outputs[0].url);+ expect(film.request.inputs?.images?.[0]).toBe(gens.getGeneration(items[1].id)!.outputs[0].url);+ }, 90_000);++ it("stores the tiles cut from a grid sheet", async () => {+ const p = cinema.createProject({ name: "Grid" });+ const { items } = generateInProject(p.id, { ...VIDEO, mode: "image", action: "grid", grid: { size: "2x2", type: "shots" } });+ expect(items[0].prompt).toMatch(/2×2 grid of 4/);+ const tiles = [0, 1, 2, 3].map((i) => ({ url: `/api/files/uploads/t${i}.png`, row: Math.floor(i / 2), col: i % 2 }));+ expect((await tilesRoute.PUT(json("PUT", { tiles }), params({ id: p.id, generationId: items[0].id }))).status).toBe(200);+ expect(cinema.listItems(p.id)[0].tiles).toEqual(tiles);+ expect((await tilesRoute.PUT(json("PUT", { tiles }), params({ id: p.id, generationId: "missing" }))).status).toBe(404);+ });+});++describe("AI Director", () => {+ it("breaks an idea into shots offline and keeps the conversation", async () => {+ const p = cinema.createProject({ name: "Director" });+ const messages = await askDirector(p.id, "Generate an 8-shot storyboard for a sci-fi chase scene through a neon city at night");+ expect(messages).toHaveLength(2);+ const reply = messages[1];+ expect(reply.source).toBe("offline");+ expect(reply.shots).toHaveLength(8);+ expect(reply.shots![0].settings).toMatchObject({ genre: "action", tempo: "chaotic", lighting: { kind: "preset", slug: "practicals" } });+ expect(reply.shots!.every((s) => s.moves.length > 0 && s.prompt.length > 10)).toBe(true);+ expect(cinema.getChat(p.id)).toHaveLength(2);++ const script = offlineDirector("She opens the letter.\nHer hands shake.\nShe looks out the window at the rain.", { brief: { title: "", body: "" }, director: { camera: "35mm-film" } });+ expect(script.shots.map((s) => s.prompt)).toEqual(["Wide establishing shot: She opens the letter", "Medium shot: Her hands shake", "Close-up: She looks out the window at the rain"]);+ expect(script.shots[0].settings.camera).toBe("35mm-film");+ expect(offlineDirector("Write a project brief for a perfume commercial", { brief: { title: "", body: "" }, director: {} }).brief).toMatch(/^Context: /);+ });++ it("parses an LLM answer and drops values the panel doesn't know", () => {+ const a = parseDirectorAnswer(+ 'Sure!\n```json\n{"reply":"Two shots.","shots":[{"title":"Open","prompt":"Wide of the harbour","duration":45,"moves":["drone-orbit","spin"],"settings":{"genre":"noir","era":"1890s","lighting":"window","palette":"the-circus"}},{"title":"x"}]}\n```',+ )!;+ expect(a.reply).toBe("Two shots.");+ expect(a.shots).toHaveLength(1);+ expect(a.shots[0]).toEqual({ title: "Open", prompt: "Wide of the harbour", duration: 30, moves: ["drone-orbit"], settings: { genre: "noir", lighting: { kind: "preset", slug: "window" }, palette: { kind: "preset", slug: "the-circus" } } });+ expect(parseDirectorAnswer("no json here")).toBeNull();+ });+});