Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Cinema: retry chains as a unit, safe generate, project-scoped deletes, durable spend

Claude86c8de595cc9
diff --git a/src/app/api/cinema/projects/[id]/items/route.ts b/src/app/api/cinema/projects/[id]/items/route.ts
index 9c9235bc..7e73ca97 100644
--- a/src/app/api/cinema/projects/[id]/items/route.ts
+++ b/src/app/api/cinema/projects/[id]/items/route.ts
@@ -34,7 +34,7 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/pro
});
}
-/** Bulk: take out of the project; `deleteGenerations` also deletes them from the library. */
+/** Bulk: take out of the project; `deleteGenerations` moves them to the library's Trash (restorable, still filed here). Only this project's takes are touched. */
export async function DELETE(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {
return handle(async () => {
const { id } = await ctx.params;
diff --git a/src/server/cinema-director.ts b/src/server/cinema-director.ts
index e195a2ff..b223e435 100644
--- a/src/server/cinema-director.ts
+++ b/src/server/cinema-director.ts
@@ -195,7 +195,56 @@ function beats(text: string, want?: number): { beat: string; frame?: number }[]
return order.map((frame) => ({ beat: `${idea}, ${(ad ? AD_BEATS : STORY_BEATS)[frame]}`, frame }));
}
+/** "Which lens should I use for a close-up?" — a question to answer, not an idea to storyboard. */
+export function isQuestion(text: string): boolean {
+ const t = text.trim();
+ if (t.includes("\n") || /\b(storyboard|shot list|break (it |this )?down|\d+[- ]?shots?)\b/i.test(t)) return false;
+ // Requests ("Can you write a script about…?") and ideas ("What if a cat ran a bakery?") get the breakdown.
+ if (/^(please\s+)?(can|could|would|will) you\s+(please\s+)?(write|make|create|generate|give|break|turn|draft|plan|storyboard|shoot|direct)\b/i.test(t) || /^(what if|how about)\b/i.test(t)) return false;
+ return /\?\s*$/.test(t) || /^(what|which|how|why|when|where|should|shall|can|could|would|is|are|does|do)\b/i.test(t);
+}
+
+const TIPS: { when: RegExp; tip: string }[] = [
+ {
+ when: /\b(lens|focal|mm\b|close[- ]?up|portrait|wide angle|telephoto)/i,
+ tip: "For a close-up, 85mm flatters faces and softens the background; 50mm feels natural, like the eye; 24–35mm keeps the room in frame for wides and movement. Pick it under Camera → Focal length — an anamorphic lens adds the oval bokeh and flares.",
+ },
+ {
+ when: /\b(light|lighting|lit|shadow|exposure|backlight|silhouette)/i,
+ tip: "Start from the story's mood: Window light for soft, honest drama; Practicals (lamps, neon, candles in frame) for night interiors; Contre-jour for a backlit, hopeful glow; Silhouette or hard top light for menace. Set it under Lighting, or build your own two-light rig.",
+ },
+ {
+ when: /\b(move|movement|camera move|dolly|pan|tilt|crane|tracking|handheld|orbit|zoom)/i,
+ tip: "Move with intent: a slow dolly-in builds tension or intimacy, tracking follows action, a crane reveals the world, a static shot lets the acting breathe. Type # in the prompt to add moves — chain two at most per shot.",
+ },
+ {
+ when: /\b(colou?r|palette|grade|tone|look)\b/i,
+ tip: "A palette carries the genre: teal and amber for modern thrillers, desaturated steel for war and horror, warm pastels for romance. Pick one under Palette (or pull one from a frame you like) — on the open engine, Palette lock grades every take to it.",
+ },
+ {
+ when: /\b(aperture|depth of field|bokeh|f\/?\d|blur)/i,
+ tip: "Open the aperture (f/1.4–f/2) to isolate a face against a soft background; stop down (f/8 and up) to keep a whole room sharp. Set it under Camera → Aperture.",
+ },
+ {
+ when: /\b(how long|duration|seconds|length|pacing|tempo|cut)/i,
+ tip: "Most shots land at 4–8 seconds: shorter for action and commercials, longer for dialogue and mood. Tempo in Film setup decides how fast the cuts come; Extend makes a take longer without losing continuity.",
+ },
+];
+
+/** A short, practical answer to a craft question, without a storyboard. */
+function answerQuestion(text: string): string {
+ const tip = TIPS.find((x) => x.when.test(text))?.tip;
+ return (
+ tip ??
+ "Tell me the scene and the feeling you're after and I'll suggest the camera, lens, light and palette — or ask for a storyboard (“break this into 6 shots”) and I'll write the shots for you."
+ );
+}
+
+/** "an action look", "a noir look". */
+const article = (word: string) => (/^[aeiou]/i.test(word) ? "an" : "a");
+
export function offlineDirector(text: string, project: Pick<CinemaProject, "brief" | "director">): { reply: string; shots: DirectorShot[]; brief?: string } {
+ if (isQuestion(text)) return { reply: answerQuestion(text), shots: [] };
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);
@@ -230,12 +279,21 @@ export function offlineDirector(text: string, project: Pick<CinemaProject, "brie
settings: { ...look, focal: project.director.focal ?? f.focal },
};
});
+ const genre = look.genre ? GENRES.find((g) => g.slug === look.genre)?.name.toLowerCase() : undefined;
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.`,
+ reply: `Here's a ${shots.length}-shot breakdown${genre ? ` with ${article(genre)} ${genre} look` : ""}. Load a shot into the prompt bar to review it — nothing renders until you press Generate.`,
shots,
};
}
+/** An LLM's plain-text answer, without code fences, trimmed to a chat message. */
+export function prose(raw: string): string {
+ return raw
+ .replace(/```[a-z]*\n?/gi, "")
+ .trim()
+ .slice(0, 4000);
+}
+
function settingsLine(s: DirectorSettings): string {
const d = directorSummary(s);
return d.length ? d.join(", ") : "all Auto";
@@ -256,9 +314,15 @@ export async function askDirector(projectId: string, text: string): Promise<Dire
]
.filter(Boolean)
.join("\n\n");
- const raw = await llmText(SYSTEM, context).catch(() => null);
+ const raw = (await llmText(SYSTEM, context).catch(() => null))?.trim() || 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 answer =
+ parsed && (parsed.reply || parsed.shots.length || parsed.brief)
+ ? { ...parsed, source: "llm" as const }
+ : raw && !parsed
+ ? // The model answered in prose (no JSON): that's still its answer.
+ { reply: prose(raw), shots: [], source: "llm" as const }
+ : { ...offlineDirector(user.text, project), source: "offline" as const };
const reply: DirectorMessage = {
id: nanoid(8),
role: "assistant",
diff --git a/src/server/cinema-generate.ts b/src/server/cinema-generate.ts
index 7762f709..6e5620cc 100644
--- a/src/server/cinema-generate.ts
+++ b/src/server/cinema-generate.ts
@@ -13,7 +13,7 @@ import {
type DirectorSettings,
} from "@/lib/catalog/cinema";
import type { Generation, GenerationRequest } from "@/lib/catalog/types";
-import { CinemaError, addItems, getProject, spentUsd } from "./cinema";
+import { CinemaError, folderExists, getProject, recordTakes, spentUsd } from "./cinema";
import { createGenerations, previewGeneration } from "./generations";
import { encodePng } from "./png";
import { provider } from "./providers";
@@ -59,16 +59,32 @@ export function planForProject(projectId: string, input: CinemaRequest): CinemaP
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 {
+type Preview = ReturnType<typeof previewGeneration>;
+
+/**
+ * Check and price every step before any is created, from the server's own route choice (engine
+ * mode, keys, demo): a step that can't run must not leave the earlier ones running and billed.
+ */
+function previewSteps(steps: CinemaStep[]): Preview[] {
+ return steps.map((s) => {
+ try {
+ return previewGeneration(withPlaceholders(s));
+ } catch (e) {
+ throw new CinemaError((e as Error).message, 422);
+ }
+ });
+}
+
+/** What the run will really cost (0 for demo-mode steps). */
+function realCost(steps: CinemaStep[], previews: Preview[]): number {
let total = 0;
const jobs: Record<string, number> = {};
- for (const s of steps) {
- const p = previewGeneration(withPlaceholders(s));
+ steps.forEach((s, i) => {
+ const p = previews[i];
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;
}
@@ -79,22 +95,32 @@ function terminal(list: Generation[]): Generation[] {
export interface CinemaRunResult {
items: Generation[];
+ /** Where the takes were filed: the scene asked for, or the project root when that scene no longer exists. */
+ folderId: string | null;
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).
+ * Plan, check every step and 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: CinemaRequest, folderId: string | null = null): CinemaRunResult {
const project = getProject(projectId);
if (!project) throw new CinemaError("Project not found", 404);
+ const notes: string[] = [];
+ // A scene deleted since the view loaded (the sidebar, another tab): file the takes at the root rather than lose them.
+ let folder = folderId;
+ if (folder && !folderExists(projectId, folder)) {
+ folder = null;
+ notes.push("That scene was deleted, so the take is in Home");
+ }
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);
+ const previews = previewSteps(plan.steps);
if (project.costCapUsd != null) {
- const cost = realCost(plan.steps);
+ const cost = realCost(plan.steps, previews);
const spent = spentUsd(projectId);
if (cost > 0 && spent + cost > project.costCapUsd + 1e-9) {
throw new CinemaError(
@@ -130,9 +156,9 @@ export function generateInProject(projectId: string, input: CinemaRequest, folde
}
} 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, take);
+ recordTakes(projectId, all, folder, take);
throw new CinemaError((e as Error).message, 422);
}
- addItems(projectId, all.map((g) => g.id), folderId, take);
- return { items: all, plan: { notes: plan.notes, costUsd: plan.costUsd, outputs: plan.outputs, modelId: plan.model.id } };
+ recordTakes(projectId, all, folder, take);
+ return { items: all, folderId: folder, plan: { notes: [...notes, ...plan.notes], costUsd: plan.costUsd, outputs: plan.outputs, modelId: plan.model.id } };
}
diff --git a/src/server/cinema.ts b/src/server/cinema.ts
index f3e6906a..7ee32042 100644
--- a/src/server/cinema.ts
+++ b/src/server/cinema.ts
@@ -1,9 +1,11 @@
import "server-only";
import { nanoid } from "nanoid";
+import { getModel } from "@/lib/catalog";
import type { CinemaFolder, CinemaItem, CinemaProject, CinemaTakeInfo, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";
-import type { Generation } from "@/lib/catalog/types";
+import type { Generation, GenerationRequest } from "@/lib/catalog/types";
import { db } from "./db";
-import { createGenerations, deleteGeneration, getGeneration, listGenerations } from "./generations";
+import { createGenerations, getGeneration, listGenerations, previewChained, previewGeneration, toGeneration } from "./generations";
+import { trashGenerations } from "./library";
/**
* Cinema Studio projects: Director settings, brief and AI Director chat per project, nested folders
@@ -90,8 +92,20 @@ const toFolder = (r: FolderRow): CinemaFolder => ({
updatedAt: r.updated_at,
});
+/** What a project keeps per take besides its folder (cinema_items.meta_json). */
+interface ItemMeta {
+ tiles?: CinemaTile[];
+ take?: CinemaTakeInfo;
+ /** Estimated cost when the take was made: still counted once the generation is deleted for good. */
+ cost?: number;
+ /** A chained step's request before its inputs were filled in, so Retry can run it against its dependencies again. */
+ req?: GenerationRequest;
+ /** Taken out of the project: hidden, but kept so what it cost still counts toward the cap. */
+ removed?: boolean;
+}
+
const toItem = (r: ItemRow): CinemaItem => {
- const meta = parse<{ tiles?: CinemaTile[]; take?: CinemaTakeInfo }>(r.meta_json, {});
+ const meta = parse<ItemMeta>(r.meta_json, {});
return {
generationId: r.generation_id,
folderId: r.folder_id,
@@ -101,6 +115,9 @@ const toItem = (r: ItemRow): CinemaItem => {
};
};
+/** SQL: a membership row that wasn't taken out of its project. */
+const LISTED = "json_extract(i.meta_json, '$.removed') IS NULL";
+
/** 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;
@@ -125,25 +142,35 @@ function requireProject(id: string): CinemaProject {
return p;
}
-/** Estimated spend so far: the recorded cost of every take that didn't fail. */
+/**
+ * What the project's takes cost, summed in SQL: a generation's recorded cost unless it failed, and for
+ * one deleted for good (emptied from the Trash) the cost recorded when the take was made. Deleting
+ * or taking out takes never lowers it: that money is spent.
+ */
+const SPENT = `COALESCE(SUM(CASE
+ WHEN g.id IS NULL THEN COALESCE(json_extract(i.meta_json, '$.cost'), 0)
+ WHEN g.status IN ('failed', 'canceled') THEN 0
+ ELSE COALESCE(g.cost_usd, 0) END), 0)`;
+
+const round3 = (n: number) => Math.round(n * 1000) / 1000;
+
+/** Estimated spend so far: the cost of every take made in the project 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;
+ const r = db().prepare(`SELECT ${SPENT} AS s FROM cinema_items i LEFT JOIN generations g ON g.id = i.generation_id WHERE i.project_id = ?`).get(projectId) as { s: number };
+ return round3(r.s);
}
-/** Newest finished image (or video) of a project: the card cover when none was picked. */
+/** Newest finished image (or video) of a project: the card cover when none was picked. One query. */
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 }[];
+ const rows = db()
+ .prepare(
+ `SELECT g.outputs_json FROM cinema_items i JOIN generations g ON g.id = i.generation_id LEFT JOIN generation_trash t ON t.generation_id = g.id
+ WHERE i.project_id = ? AND g.status = 'succeeded' AND t.deleted_at IS NULL AND ${LISTED} ORDER BY i.created_at DESC LIMIT 40`,
+ )
+ .all(projectId) as { outputs_json: 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, []);
+ for (const r of rows) {
+ const outs = parse<{ url: string; kind: string }[]>(r.outputs_json, []);
const img = outs.find((o) => o.kind === "image");
if (img) return img.url;
video ??= outs.find((o) => o.kind === "video")?.url ?? null;
@@ -153,10 +180,23 @@ function autoCover(projectId: string): string | null {
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) } };
- });
+ // Counts and spend for every project in two grouped queries (not one per project).
+ const counts = new Map(
+ (
+ db()
+ .prepare(
+ `SELECT i.project_id AS p, COUNT(*) AS n FROM cinema_items i JOIN generations g ON g.id = i.generation_id
+ LEFT JOIN generation_trash t ON t.generation_id = g.id WHERE t.deleted_at IS NULL AND ${LISTED} GROUP BY i.project_id`,
+ )
+ .all() as { p: string; n: number }[]
+ ).map((r) => [r.p, r.n]),
+ );
+ const spent = new Map(
+ (db().prepare(`SELECT i.project_id AS p, ${SPENT} AS s FROM cinema_items i LEFT JOIN generations g ON g.id = i.generation_id GROUP BY i.project_id`).all() as { p: string; s: number }[]).map(
+ (r) => [r.p, round3(r.s)],
+ ),
+ );
+ return rows.map((r) => ({ ...toProject(r), stats: { items: counts.get(r.id) ?? 0, spentUsd: spent.get(r.id) ?? 0, cover: r.cover_url ?? autoCover(r.id) } }));
}
export function createProject(input: { name: string; description?: string | null; cover?: string | null; costCapUsd?: number | null }): CinemaProject {
@@ -278,6 +318,11 @@ export function descendants(projectId: string, folderId: string): Set<string> {
return out;
}
+/** Whether a folder (scene) of this project still exists: one deleted in another tab or the sidebar doesn't. */
+export function folderExists(projectId: string, folderId: string): boolean {
+ return folderRow(folderId)?.project_id === projectId;
+}
+
function checkParent(projectId: string, parentId: string | null | undefined, self?: string): void {
if (!parentId) return;
const p = folderRow(parentId);
@@ -342,7 +387,13 @@ export function deleteFolder(projectId: string, id: string): void {
// ---------------------------------------------------------------------------
// Items: the project's generations
-export type CinemaGeneration = Generation & { folderId: string | null; tiles?: CinemaTile[]; take?: CinemaTakeInfo };
+export type CinemaGeneration = Generation & {
+ folderId: string | null;
+ tiles?: CinemaTile[];
+ take?: CinemaTakeInfo;
+ /** The project the take belongs to ("My Generations" lists every project's). */
+ projectId?: string | null;
+};
export interface ItemQuery {
/** A folder id; null = the project root only; undefined = everything in the project. */
@@ -352,97 +403,305 @@ export interface ItemQuery {
favorites?: boolean;
}
+/** Library columns plus the membership row, as one JOIN (no query per take). */
+const ITEMS_FROM = `SELECT g.*, t.deleted_at AS deleted_at, fi.folder_id AS folder_id, i.project_id AS c_project, i.folder_id AS c_folder, i.meta_json AS c_meta
+ FROM cinema_items i JOIN generations g ON g.id = i.generation_id
+ LEFT JOIN generation_trash t ON t.generation_id = g.id LEFT JOIN folder_items fi ON fi.generation_id = g.id
+ WHERE t.deleted_at IS NULL AND ${LISTED}`;
+
+type JoinedRow = Parameters<typeof toGeneration>[0] & { c_project: string; c_folder: string | null; c_meta: string | null };
+
+function toCinemaGeneration(r: JoinedRow): CinemaGeneration {
+ const meta = parse<ItemMeta>(r.c_meta, {});
+ return {
+ ...toGeneration(r),
+ folderId: r.c_folder,
+ projectId: r.c_project,
+ ...(meta.tiles?.length ? { tiles: meta.tiles } : {}),
+ ...(meta.take ? { take: meta.take } : {}),
+ };
+}
+
+const marks = (n: number) => Array.from({ length: n }, () => "?").join(", ");
+
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);
+ const where = ["i.project_id = ?"];
+ const args: unknown[] = [projectId];
+ if (q.folderId === null) where.push("i.folder_id IS NULL");
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 set = [...(q.nested ? descendants(projectId, q.folderId) : new Set([q.folderId]))];
+ where.push(`i.folder_id IN (${marks(set.length)})`);
+ args.push(...set);
}
- 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 } : {}), ...(item.take ? { take: item.take } : {}) });
- }
- return out.sort((a, b) => b.createdAt - a.createdAt);
+ if (q.favorites) where.push("g.favorite = 1");
+ const rows = db()
+ .prepare(`${ITEMS_FROM} AND ${where.join(" AND ")} ORDER BY g.created_at DESC, g.id DESC`)
+ .all(...args) as JoinedRow[];
+ return rows.map(toCinemaGeneration);
}
-/** Every Cinema Studio generation, whichever project it's in ("My Generations"). */
+/** Every Cinema Studio generation, whichever project it's in ("My Generations"), with its project. */
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]),
+ const list = listGenerations({ features: ["cinema*"], limit: 200 }).filter((g) => !(g as Generation & { deletedAt?: number | null }).deletedAt);
+ if (!list.length) return [];
+ const rows = db()
+ .prepare(`SELECT i.generation_id, i.project_id, i.folder_id, i.meta_json FROM cinema_items i WHERE i.generation_id IN (${marks(list.length)}) AND ${LISTED}`)
+ .all(...list.map((g) => g.id)) as { generation_id: string; project_id: string; folder_id: string | null; meta_json: string | null }[];
+ const by = new Map(rows.map((r) => [r.generation_id, r]));
+ return list.map((g) => {
+ const r = by.get(g.id);
+ const meta = parse<ItemMeta>(r?.meta_json, {});
+ return { ...g, folderId: r?.folder_id ?? null, projectId: r?.project_id ?? null, ...(meta.tiles?.length ? { tiles: meta.tiles } : {}), ...(meta.take ? { take: meta.take } : {}) };
+ });
+}
+
+/**
+ * Write membership rows. Re-adding a take that was taken out brings it back; a take already listed
+ * in the project is left as it is.
+ */
+function insertItems(projectId: string, entries: { id: string; meta: ItemMeta }[], folderId: string | null): void {
+ const now = Date.now();
+ const ins = db().prepare(
+ `INSERT INTO cinema_items (project_id, generation_id, folder_id, meta_json, created_at) VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(project_id, generation_id) DO UPDATE SET folder_id = excluded.folder_id, meta_json = excluded.meta_json, created_at = excluded.created_at
+ WHERE json_extract(cinema_items.meta_json, '$.removed') IS NOT NULL`,
);
- return listGenerations({ features: ["cinema*"], limit: 200 })
- .filter((g) => !(g as Generation & { deletedAt?: number | null }).deletedAt)
- .map((g) => ({ ...g, folderId: folders.get(g.id) ?? null }));
+ db().transaction(() => entries.forEach((e, i) => ins.run(projectId, e.id, folderId, Object.keys(e.meta).length ? JSON.stringify(e.meta) : null, now + i)))();
+ touch(projectId);
+}
+
+const dependsOf = (v: string | null | undefined): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);
+
+/** What each generation waits for (generations.depends_on). */
+function dependencies(ids: string[]): Map<string, string[]> {
+ if (!ids.length) return new Map();
+ const rows = db().prepare(`SELECT id, depends_on FROM generations WHERE id IN (${marks(ids.length)})`).all(...ids) as { id: string; depends_on: string | null }[];
+ return new Map(rows.map((r) => [r.id, dependsOf(r.depends_on)]));
+}
+
+/** The meta a new take starts with: its estimated cost and, for a chained step, its request before the inputs were filled in. */
+function metaFor(g: Pick<Generation, "costUsd" | "request">, deps: string[] | undefined, take?: CinemaTakeInfo): ItemMeta {
+ return { ...(take ? { take } : {}), cost: g.costUsd ?? 0, ...(deps?.length ? { req: g.request } : {}) };
}
export function addItems(projectId: string, generationIds: string[], folderId: string | null = null, take?: CinemaTakeInfo): void {
requireProject(projectId);
if (folderId) checkParent(projectId, folderId);
- const now = Date.now();
- const meta = take ? JSON.stringify({ take }) : null;
- const ins = db().prepare("INSERT OR IGNORE INTO cinema_items (project_id, generation_id, folder_id, meta_json, created_at) VALUES (?, ?, ?, ?, ?)");
- db().transaction(() => generationIds.forEach((id, i) => ins.run(projectId, id, folderId, meta, now + i)))();
- touch(projectId);
+ const deps = dependencies(generationIds);
+ const entries = generationIds.map((id) => {
+ const g = getGeneration(id, { includeDeleted: true });
+ return { id, meta: g ? metaFor(g, deps.get(id), take) : take ? { take } : {} };
+ });
+ insertItems(projectId, entries, folderId);
+}
+
+/** Record generations just made from the workspace (their requests are still the unfilled originals). */
+export function recordTakes(projectId: string, made: Generation[], folderId: string | null, take?: CinemaTakeInfo): void {
+ if (!made.length) return;
+ const deps = dependencies(made.map((g) => g.id));
+ insertItems(
+ projectId,
+ made.map((g) => ({ id: g.id, meta: metaFor(g, deps.get(g.id), take) })),
+ folderId,
+ );
+}
+
+/** The ids among `ids` that are listed in the project. */
+function memberIds(projectId: string, ids: string[]): string[] {
+ const list = [...new Set(ids)];
+ if (!list.length) return [];
+ return (
+ db()
+ .prepare(`SELECT generation_id FROM cinema_items i WHERE i.project_id = ? AND i.generation_id IN (${marks(list.length)}) AND ${LISTED}`)
+ .all(projectId, ...list) as { generation_id: string }[]
+ ).map((r) => r.generation_id);
}
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)))();
+ const ids = memberIds(projectId, generationIds);
+ db().transaction(() => ids.forEach((id) => up.run(folderId, projectId, id)))();
touch(projectId);
- return n;
+ return ids.length;
}
-/** Remove takes from the project; with `deleteGenerations` they are deleted from the library too. */
+/**
+ * Take takes out of the project. With `deleteGenerations` (the workspace's Delete) they move to the
+ * library's Trash and stay filed here, so Restore brings them back where they were; otherwise they're
+ * only taken out. The rows are kept either way (hidden), so what the takes cost still counts toward
+ * the cap. Only this project's takes are touched.
+ */
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);
+ const ids = memberIds(projectId, generationIds);
+ if (!ids.length) return 0;
+ if (opts.deleteGenerations) trashGenerations(ids);
+ else {
+ // Snapshot what each take cost (nothing if it failed) before hiding it.
+ const out = db().prepare(
+ `UPDATE cinema_items SET meta_json = json_set(COALESCE(meta_json, '{}'), '$.removed', json('true'), '$.cost',
+ COALESCE((SELECT CASE WHEN g.status IN ('failed', 'canceled') THEN 0 ELSE COALESCE(g.cost_usd, 0) END FROM generations g WHERE g.id = cinema_items.generation_id), json_extract(meta_json, '$.cost'), 0))
+ WHERE project_id = ? AND generation_id = ?`,
+ );
+ db().transaction(() => ids.forEach((id) => out.run(projectId, id)))();
+ }
touch(projectId);
- return n;
+ return ids.length;
}
-export function setFavorites(projectId: string, generationIds: string[], favorite: boolean): void {
+export function setFavorites(projectId: string, generationIds: string[], favorite: boolean): number {
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)))();
+ const ids = memberIds(projectId, generationIds);
+ const up = db().prepare("UPDATE generations SET favorite = ?, updated_at = ? WHERE id = ?");
+ db().transaction(() => ids.forEach((id) => up.run(favorite ? 1 : 0, Date.now(), id)))();
+ return ids.length;
+}
+
+// ---------------------------------------------------------------------------
+// Retry
+
+const BROKEN = new Set<Generation["status"]>(["failed", "canceled"]);
+
+function itemRow(projectId: string, generationId: string): ItemRow | undefined {
+ const r = db().prepare("SELECT * FROM cinema_items WHERE project_id = ? AND generation_id = ?").get(projectId, generationId) as ItemRow | undefined;
+ return r && !parse<ItemMeta>(r.meta_json, {}).removed ? r : undefined;
+}
+
+/** Generations that wait for `id`. */
+function dependentsOf(id: string): string[] {
+ return (
+ db()
+ .prepare("SELECT id FROM generations WHERE depends_on = ? OR (substr(depends_on, 1, 1) = '[' AND instr(depends_on, ?) > 0) ORDER BY created_at")
+ .all(id, `"${id}"`) as { id: string }[]
+ ).map((r) => r.id);
+}
+
+/** Queued behind a dependency that will never finish (the runner fails it on its next pass). */
+const waiting = (g: Generation, deps: string[]) => g.status === "queued" && deps.length > 0;
+
+interface RedoStep {
+ g: Generation;
+ deps: string[];
+ row: ItemRow;
}
/**
- * Run a failed or canceled take again, in the same folder. A chained step that already got its
- * inputs runs on its own; one whose earlier step failed needs that step retried first.
+ * The request a step runs again with, and what it waits for. A root step makes one job (one take of
+ * a batch of 4 is one take: the other three are still there).
+ */
+function redoRequest(s: RedoStep, launched: boolean): { req: GenerationRequest; deps: string[] } {
+ const meta = parse<ItemMeta>(s.row.meta_json, {});
+ if (s.deps.length && meta.req) return { req: structuredClone(meta.req), deps: s.deps };
+ const req = structuredClone(s.g.request);
+ if (s.deps.length && !launched) return { req, deps: s.deps };
+ // A root step, or (takes recorded before the unfilled request was kept) a step whose inputs were already filled in.
+ delete req.chain;
+ delete req.chainFrom;
+ const requested = req.params?.numOutputs ?? 1;
+ if (requested > 1) req.params = { ...req.params, numOutputs: Math.max(1, Math.min(requested, getModel(req.modelId)?.options.maxOutputs ?? 1)) };
+ return { req, deps: [] };
+}
+
+/**
+ * Run a failed or canceled take again, in the same folder. Chained takes retry as a unit: the failed
+ * steps it waits for and the steps that failed because of it are made again too, wired to the new
+ * ids, while steps that finished are reused rather than re-run. Every step is checked before any
+ * starts; the replaced failures move to the Trash so the new run takes their place in the feed.
*/
export function retryItem(projectId: string, generationId: string): Generation[] {
- const r = db().prepare("SELECT * FROM cinema_items WHERE project_id = ? AND generation_id = ?").get(projectId, generationId) as ItemRow | undefined;
- const g = r ? liveGeneration(generationId) : null;
- if (!r || !g) throw new CinemaError("That take isn't in this project", 404);
- const req = { ...g.request };
- if (req.chain?.length || req.chainFrom) {
- const filled = req.chain?.every((c) => (c.slot === "images" || c.slot === "videos" ? (req.inputs?.[c.slot]?.length ?? 0) > 0 : c.slot === "prompt" ? !!req.prompt : !!req.inputs?.[c.slot]));
- if (!filled) throw new CinemaError("An earlier step of this take didn't finish — retry that one first", 422);
- delete req.chain;
- delete req.chainFrom;
+ const start = itemRow(projectId, generationId);
+ const first = start ? liveGeneration(generationId) : null;
+ if (!start || !first) throw new CinemaError("That take isn't in this project", 404);
+ if (first.status === "queued" || first.status === "running") throw new CinemaError("That take is still rendering", 422);
+
+ const redo = new Map<string, RedoStep>([[generationId, { g: first, deps: dependencies([generationId]).get(generationId) ?? [], row: start }]]);
+ const consider = (id: string, upstream: boolean): boolean => {
+ if (redo.has(id)) return false;
+ const g = getGeneration(id, { includeDeleted: true });
+ if (!g) {
+ if (upstream) throw new CinemaError("An earlier step of this take was deleted — make the take again", 422);
+ return false;
+ }
+ const deps = dependencies([id]).get(id) ?? [];
+ // Upstream, a finished or still-running step is waited on as it is; downstream, only steps that failed (or will) are redone.
+ if (!BROKEN.has(g.status) && !(!upstream && waiting(g, deps))) return false;
+ const row = itemRow(projectId, id);
+ if (!row) {
+ if (upstream) throw new CinemaError("An earlier step of this take isn't in this project any more — make the take again", 422);
+ return false;
+ }
+ redo.set(id, { g, deps, row });
+ return true;
+ };
+ for (let grew = true; grew; ) {
+ grew = false;
+ for (const s of [...redo.values()]) {
+ for (const d of s.deps) grew = consider(d, true) || grew;
+ for (const c of dependentsOf(s.g.id)) grew = consider(c, false) || grew;
+ }
+ }
+
+ // Dependencies first.
+ const order: RedoStep[] = [];
+ const placed = new Set<string>();
+ while (order.length < redo.size) {
+ const next = [...redo.values()].filter((s) => !placed.has(s.g.id) && s.deps.every((d) => !redo.has(d) || placed.has(d)));
+ if (!next.length) throw new CinemaError("This take's steps wait for each other in a loop", 422);
+ for (const s of next.sort((a, b) => a.g.createdAt - b.g.createdAt)) {
+ order.push(s);
+ placed.add(s.g.id);
+ }
+ }
+ const launched = new Set(
+ (
+ db()
+ .prepare(`SELECT id FROM generations WHERE id IN (${marks(order.length)}) AND (external_id IS NOT NULL OR provider_input_json IS NOT NULL)`)
+ .all(...order.map((s) => s.g.id)) as { id: string }[]
+ ).map((r) => r.id),
+ );
+ const plans = order.map((s) => ({ s, ...redoRequest(s, launched.has(s.g.id)) }));
+ // Check every step before starting any: a refusal must not leave half a chain running.
+ for (const p of plans) {
+ try {
+ if (p.deps.length) previewChained(p.req, p.deps.length);
+ else previewGeneration(p.req);
+ } catch (e) {
+ throw new CinemaError((e as Error).message, 422);
+ }
+ }
+
+ const fresh = new Map<string, string>();
+ const created: Generation[] = [];
+ try {
+ for (const p of plans) {
+ const deps = p.deps.map((d) => fresh.get(d) ?? d);
+ const opts = p.s.g.batchId ? { batchId: p.s.g.batchId } : {};
+ const made = deps.length ? createGenerations(p.req, { ...opts, dependsOn: deps.length === 1 ? deps[0] : deps }) : createGenerations(p.req, opts);
+ // A joined film comes first: dependents wait for it.
+ fresh.set(p.s.g.id, made[0].id);
+ created.push(...made);
+ recordTakes(projectId, made, p.s.row.folder_id, parse<ItemMeta>(p.s.row.meta_json, {}).take);
+ }
+ } catch (e) {
+ throw new CinemaError((e as Error).message, 422);
+ }
+ const replaced = order.filter((s) => BROKEN.has(s.g.status) || waiting(s.g, s.deps)).map((s) => s.g.id);
+ if (replaced.length) {
+ trashGenerations(replaced);
+ // They cost nothing (they failed), even after the Trash is emptied.
+ const zero = db().prepare("UPDATE cinema_items SET meta_json = json_set(COALESCE(meta_json, '{}'), '$.cost', 0) WHERE project_id = ? AND generation_id = ?");
+ db().transaction(() => replaced.forEach((id) => zero.run(projectId, id)))();
}
- const created = createGenerations(req, g.batchId ? { batchId: g.batchId } : {});
- const item = toItem(r);
- addItems(projectId, created.map((x) => x.id), item.folderId, item.take);
return created;
}
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;
+ const r = itemRow(projectId, generationId);
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) };
+ const meta = { ...parse<ItemMeta>(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/tests/cinema-director.test.ts b/tests/cinema-director.test.ts
new file mode 100644
index 00000000..9b27babc
--- /dev/null
+++ b/tests/cinema-director.test.ts
@@ -0,0 +1,63 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+// The AI Director answers questions instead of storyboarding them, and keeps an LLM's prose answer.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-director-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const llm = vi.hoisted(() => ({ answer: null as string | null }));
+vi.mock("@/server/enhance", async (orig) => ({ ...(await orig<typeof import("@/server/enhance")>()), llmText: async () => llm.answer }));
+
+const cinema = await import("@/server/cinema");
+const { askDirector, isQuestion, offlineDirector, prose } = await import("@/server/cinema-director");
+
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const empty = { brief: { title: "", body: "" }, director: {} };
+
+describe("AI Director", () => {
+ it("answers a craft question with a tip, not a storyboard", () => {
+ expect(isQuestion("Which lens should I use for a close-up?")).toBe(true);
+ expect(isQuestion("how do I light a night interior")).toBe(true);
+ expect(isQuestion("Generate an 8-shot storyboard for a sci-fi chase scene")).toBe(false);
+ expect(isQuestion("Can you write a script about a lighthouse keeper?")).toBe(false);
+ expect(isQuestion("What if a cat ran a bakery?")).toBe(false);
+ expect(isQuestion("She opens the letter?\nHer hands shake.")).toBe(false);
+
+ const lens = offlineDirector("Which lens should I use for a close-up?", empty);
+ expect(lens.shots).toEqual([]);
+ expect(lens.reply).toMatch(/85mm/);
+ expect(offlineDirector("How should I light a candle-lit dinner?", empty).reply).toMatch(/Practicals/);
+ expect(offlineDirector("What should I do next?", empty).reply).toMatch(/storyboard/);
+ });
+
+ it("uses “an” before a vowel", () => {
+ const r = offlineDirector("A heist crew escapes across the rooftops at night", empty);
+ expect(r.shots.length).toBeGreaterThan(0);
+ expect(r.reply).toMatch(/with an action look/);
+ expect(offlineDirector("A detective smokes in the rain", empty).reply).toMatch(/with a noir look/);
+ });
+
+ it("keeps an LLM's prose answer instead of replacing it with the offline breakdown", async () => {
+ const p = cinema.createProject({ name: "Prose" });
+ llm.answer = "Use an 85mm lens at f/2 — it compresses the background and keeps the eyes sharp.";
+ const messages = await askDirector(p.id, "Which lens for a close-up?");
+ expect(messages[1]).toMatchObject({ role: "assistant", source: "llm", text: llm.answer });
+ expect(messages[1].shots).toBeUndefined();
+
+ llm.answer = '{"reply":"Two shots.","shots":[{"title":"Open","prompt":"Wide of the harbour","duration":5}]}';
+ const json = await askDirector(p.id, "Storyboard the harbour opening");
+ expect(json[3]).toMatchObject({ source: "llm", text: "Two shots." });
+ expect(json[3].shots).toHaveLength(1);
+
+ llm.answer = null;
+ const offline = await askDirector(p.id, "Which lens for a close-up?");
+ expect(offline[5]).toMatchObject({ source: "offline" });
+ expect(offline[5].text).toMatch(/85mm/);
+ expect(prose("```\nHello\n```")).toBe("Hello");
+ });
+});
diff --git a/tests/cinema-fixes.test.ts b/tests/cinema-fixes.test.ts
new file mode 100644
index 00000000..16d43b7f
--- /dev/null
+++ b/tests/cinema-fixes.test.ts
@@ -0,0 +1,215 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+// Round-3 review fixes: retry (batches, chains as a unit), stale folders, step previews, project-scoped
+// deletes, spend that survives deletes, "My Generations" ownership.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-fixes-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { db } = await import("@/server/db");
+const gens = await import("@/server/generations");
+const library = await import("@/server/library");
+const cinema = await import("@/server/cinema");
+const { generateInProject, swatchUrl } = await import("@/server/cinema-generate");
+const generateRoute = await import("@/app/api/cinema/projects/[id]/generate/route");
+const itemsRoute = await import("@/app/api/cinema/projects/[id]/items/route");
+const { PALETTES } = await import("@/lib/catalog/cinema");
+
+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) });
+
+const VIDEO = { engine: "cloud" as const, mode: "video" as const, action: "generate" as const, prompt: "A detective lights a match in the rain", duration: 5, aspectRatio: "16:9", batch: 1, settings: {} };
+const CIRCUS = { palette: { kind: "preset" as const, slug: "the-circus" } };
+const circusSwatch = () => swatchUrl(PALETTES.find((p) => p.slug === "the-circus")!.hex);
+
+async function settle(id: string, ms = 40_000) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id, { includeDeleted: true })!;
+ 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, 250));
+ }
+}
+
+const dependsOn = (id: string) => {
+ const v = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;
+ return !v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v];
+};
+const count = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+
+describe("Cinema retry", () => {
+ it("retries one take of a batch of 4 as one job, in place of the failed one", async () => {
+ const p = cinema.createProject({ name: "Batch" });
+ const { items } = generateInProject(p.id, { ...VIDEO, batch: 4 });
+ expect(items).toHaveLength(4);
+ await gens.cancelGeneration(items[0].id);
+ const again = cinema.retryItem(p.id, items[0].id);
+ expect(again).toHaveLength(1);
+ expect(again[0].request.params?.numOutputs).toBe(1);
+ expect(again[0].batchId).toBe(items[0].batchId);
+ // The canceled take moved to the Trash: the project still shows four takes.
+ expect(gens.getGeneration(items[0].id)).toBeNull();
+ expect(cinema.listItems(p.id).map((g) => g.id).sort()).toEqual([again[0].id, ...items.slice(1).map((g) => g.id)].sort());
+ // A take that's still rendering isn't retried (the new one was just queued).
+ expect(() => cinema.retryItem(p.id, again[0].id)).toThrow(/still rendering/);
+ });
+
+ it("retries a palette-locked take as a unit: the failed main step brings its palette step back", async () => {
+ const p = cinema.createProject({ name: "Chain" });
+ const { items } = generateInProject(p.id, { ...VIDEO, engine: "open", settings: CIRCUS });
+ expect(items.map((g) => g.modelId)).toEqual(["oss-wan22-14b-fast", "oss-palette-video"]);
+ await gens.cancelGeneration(items[0].id);
+ expect((await settle(items[1].id)).status).toBe("failed");
+
+ // Retrying the dependent finds the broken step it waits for; retrying the main finds its dependent.
+ const again = cinema.retryItem(p.id, items[1].id);
+ expect(again.map((g) => g.modelId)).toEqual(["oss-wan22-14b-fast", "oss-palette-video"]);
+ expect(dependsOn(again[1].id)).toEqual([again[0].id]);
+ // Its request is the unfilled one: the swatch only, the clip arrives through the chain.
+ expect(again[1].request.inputs?.images).toEqual([circusSwatch()]);
+ expect(again[1].request.chain).toEqual([{ slot: "video" }]);
+ expect(cinema.listItems(p.id).map((g) => g.id).sort()).toEqual(again.map((g) => g.id).sort());
+ const lock = await settle(again[1].id, 50_000);
+ expect(lock.status).toBe("succeeded");
+ expect(lock.request.inputs?.video).toBe(gens.getGeneration(again[0].id)!.outputs[0].url);
+ }, 70_000);
+
+ it("retries a failed dependent on its own when its inputs finished, rebuilding them from the dependency", async () => {
+ const p = cinema.createProject({ name: "Still palette" });
+ const { items } = generateInProject(p.id, { ...VIDEO, engine: "open", mode: "image", settings: { camera: "modern", lens: "clean-sharp", focal: "50mm", ...CIRCUS } });
+ expect(items.map((g) => g.modelId)).toEqual([expect.any(String), "oss-palette-image"]);
+ await settle(items[1].id, 50_000);
+ const still = gens.getGeneration(items[0].id)!;
+ expect(still.status).toBe("succeeded");
+ // The palette step failed after it got its inputs (its stored request is the filled one).
+ db().prepare("UPDATE generations SET status = 'failed', error = 'boom' WHERE id = ?").run(items[1].id);
+ const again = cinema.retryItem(p.id, items[1].id);
+ expect(again).toHaveLength(1);
+ expect(dependsOn(again[0].id)).toEqual([items[0].id]);
+ expect(again[0].request.inputs?.images).toEqual([circusSwatch()]);
+ const done = await settle(again[0].id, 50_000);
+ expect(done.status).toBe("succeeded");
+ expect(done.request.inputs?.images).toEqual([still.outputs[0].url, circusSwatch()]);
+ }, 90_000);
+
+ it("retries a prequel chain from any step, wiring the new steps to each other", async () => {
+ const p = cinema.createProject({ name: "Prequel retry" });
+ 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"]);
+ await gens.cancelGeneration(items[0].id);
+ await settle(items[2].id);
+ const again = cinema.retryItem(p.id, items[2].id);
+ expect(again.map((g) => g.op)).toEqual(["frame", "edit", "flf2v"]);
+ expect(dependsOn(again[1].id)).toEqual([again[0].id]);
+ expect(dependsOn(again[2].id)).toEqual([again[1].id, again[0].id]);
+ const film = await settle(again[2].id, 60_000);
+ expect(film.status).toBe("succeeded");
+ expect(film.request.inputs?.endImage).toBe(gens.getGeneration(again[0].id)!.outputs[0].url);
+ }, 90_000);
+});
+
+describe("Cinema generate", () => {
+ it("files the take at the project root when its scene was deleted", async () => {
+ const p = cinema.createProject({ name: "Gone folder" });
+ const f = cinema.createFolder(p.id, { name: "Scene" });
+ cinema.deleteFolder(p.id, f.id);
+ const res = await generateRoute.POST(json("POST", { input: VIDEO, folderId: f.id }), params({ id: p.id }));
+ expect(res.status).toBe(201);
+ const body = await res.json();
+ expect(body.folderId).toBeNull();
+ expect(body.plan.notes[0]).toMatch(/scene was deleted/);
+ expect(cinema.listItems(p.id, { folderId: null }).map((g) => g.id)).toEqual(body.items.map((g: { id: string }) => g.id));
+ });
+
+ it("checks every step before starting any, and answers 422 (not 500) for an engine-mode mismatch with a cap", async () => {
+ const src = gens.createGenerations({ feature: "cinema", modelId: "seedance-2-5", prompt: "source", params: { duration: 5 } })[0];
+ const take = await settle(src.id);
+ setSetting("engineMode", "cloud");
+ try {
+ // Open prequel without a first frame: step 1 (fal extract-frame) is allowed, step 2 (open edit) isn't.
+ const p = cinema.createProject({ name: "Mixed" });
+ const before = count();
+ expect(() => generateInProject(p.id, { ...VIDEO, engine: "open", action: "extend-backward", prompt: "", source: { url: take.outputs[0].url, kind: "video" } })).toThrow(/open-source model/);
+ expect(count()).toBe(before);
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ setSetting("engineMode", "open");
+ try {
+ const capped = cinema.createProject({ name: "Capped mode", costCapUsd: 5 });
+ const res = await generateRoute.POST(json("POST", { input: VIDEO }), params({ id: capped.id }));
+ expect(res.status).toBe(422);
+ expect((await res.json()).error).toMatch(/open source only/);
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ }, 60_000);
+});
+
+describe("Cinema items", () => {
+ it("deletes only the project's own takes, to the Trash, and Restore brings them back", async () => {
+ const a = cinema.createProject({ name: "A" });
+ const other = gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", prompt: "unrelated" })[0];
+ const res = await itemsRoute.DELETE(json("DELETE", { ids: [other.id], deleteGenerations: true }), params({ id: a.id }));
+ expect((await res.json()).removed).toBe(0);
+ expect(gens.getGeneration(other.id)).not.toBeNull();
+
+ const mine = gens.createGenerations({ feature: "cinema", modelId: "nano-banana-pro", prompt: "mine" })[0];
+ cinema.addItems(a.id, [mine.id]);
+ expect((await (await itemsRoute.DELETE(json("DELETE", { ids: [mine.id, other.id], deleteGenerations: true }), params({ id: a.id }))).json()).removed).toBe(1);
+ expect(cinema.listItems(a.id)).toHaveLength(0);
+ library.restoreGenerations([mine.id]);
+ expect(cinema.listItems(a.id).map((g) => g.id)).toEqual([mine.id]);
+ });
+
+ it("keeps what was spent when takes are deleted, taken out or emptied from the Trash", async () => {
+ const p = cinema.createProject({ name: "Spend", costCapUsd: 10 });
+ const ids = [0, 1, 2].map(() => gens.createGenerations({ feature: "cinema", modelId: "nano-banana-pro", prompt: "paid" })[0].id);
+ db().prepare(`UPDATE generations SET cost_usd = 0.5 WHERE id IN (${ids.map(() => "?").join(", ")})`).run(...ids);
+ cinema.addItems(p.id, ids);
+ expect(cinema.spentUsd(p.id)).toBe(1.5);
+ cinema.removeItems(p.id, [ids[0]], { deleteGenerations: true });
+ expect(cinema.spentUsd(p.id)).toBe(1.5);
+ await library.deleteForever([ids[0]]);
+ expect(gens.getGeneration(ids[0], { includeDeleted: true })).toBeNull();
+ expect(cinema.spentUsd(p.id)).toBe(1.5);
+ // Taken out of the project (not deleted): hidden, still counted, and back when re-added.
+ expect(cinema.removeItems(p.id, [ids[1]])).toBe(1);
+ expect(cinema.listItems(p.id).map((g) => g.id)).toEqual([ids[2]]);
+ expect(cinema.spentUsd(p.id)).toBe(1.5);
+ expect(cinema.listProjects().find((x) => x.id === p.id)?.stats).toMatchObject({ items: 1, spentUsd: 1.5 });
+ cinema.addItems(p.id, [ids[1]]);
+ expect(cinema.listItems(p.id).map((g) => g.id).sort()).toEqual([ids[1], ids[2]].sort());
+ expect(cinema.spentUsd(p.id)).toBe(1.5);
+ });
+
+ it("names the owning project of every take in My Generations", async () => {
+ const a = cinema.createProject({ name: "Studio A" });
+ const b = cinema.createProject({ name: "Studio B" });
+ const { items: ta } = generateInProject(a.id, VIDEO);
+ const { items: tb } = generateInProject(b.id, VIDEO);
+ const studio = cinema.listStudioGenerations();
+ expect(studio.find((g) => g.id === ta[0].id)?.projectId).toBe(a.id);
+ expect(studio.find((g) => g.id === tb[0].id)?.projectId).toBe(b.id);
+ // Project-scoped likes and moves leave other projects' takes alone.
+ const patch = await itemsRoute.PATCH(json("PATCH", { ids: [tb[0].id], favorite: true }), params({ id: a.id }));
+ expect(patch.status).toBe(200);
+ expect(gens.getGeneration(tb[0].id)?.favorite).toBe(false);
+ expect(cinema.moveItems(a.id, [tb[0].id], null)).toBe(0);
+ });
+});