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: accounts make and run their own projects
Adarsh41eef1f597e2
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 12206d8b..318e969b 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -77,7 +77,7 @@ An account is signed in, but it sees the owner's studio as a guest does:owner's results, files, uploads, folders, shares, projects (Layers, Cinema, Canvas, storyboards,elements…) and Assist threads are hidden: the lists come back empty, and other reads answer 403.Every change to them (create, rename, move, share, delete) answers 403 with `code: "library"`.- Accounts have their own uploads and runs (below), but no projects yet.+ Accounts have their own uploads and runs (below), and their own Cinema Studio projects.A Canvas Kinetic node renders in the owner's browser; keeping its run on the board(`PUT /api/canvases/<id>/runs/<node>`) is a canvas change like any other (403 `library` for an account, 401for a guest), and it takes only the owner's own finished Kinetic Motion results.@@ -99,7 +99,8 @@ An account is signed in, but it sees the owner's studio as a guest does:board shows read-only with its steps editable in Nodes. Assist, Cinema Studio,Storyboard, Elements, Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad andMarketing Studio show their ready-made starters the same way (`<studio>/start/<id>`); making one- (`POST /api/starters/<id>`) is the owner's, and an account gets 403 `library`. A starter without its+ (`POST /api/starters/<id>`) is the owner's, and an account gets 403 `library`, except Cinema Studio's+ ready films, which an account makes as its own project (a guest gets the sign-up card). A starter without itscover yet is the owner's only: its card, its words and its page (404 for anyone else). Storyboard'sready stories with a cover also fill its composer for anyone (`/storyboard?starter=<id>`), and theLibrary's "Make your first" row links to pages everyone can open.@@ -263,7 +264,7 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188uploads, outputs and cancels go there, and nothing falls back to the studio's own providers. Ifthe account's ComfyUI can't be reached, the run fails and says so. A cloud model, an AI helper orthe studio's local LLM is refused; "Enhance prompt" uses Fuobe's offline wording. Other tools- (Canvas, Cinema, Assist, Marketing…) answer 403 with `code: "own-gpu-tool"`, because they+ (Canvas, Assist, Marketing…) answer 403 with `code: "own-gpu-tool"`, because theyplan with the studio's own AI helpers or keep projects of their own. A 3D model sent here answers thesame: Image to 3D has its own route (below). So do the Audio hub's Splitsoundtrack and Edit speech and Video tools → Remove dialogue (all `POST /api/audio-tools`) and the@@ -332,6 +333,16 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188owner's read as not found (404). It keeps up to 50 shorts. Deleting a short deletes its runs for good (an accounthas no Trash). It downloads the full video and each part; "Download parts" as one zip is the owner's for now.Enhance (`.../enhance`) isn't offered to it yet (403 `own-gpu-tool`). A guest gets the sign-up card.+- **Cinema Studio.** An account makes, reopens and runs its own projects (`/api/cinema/projects/**`): up to 50,+ each with its folders, takes, Director settings, brief and AI Director chat, deleted with the account. Another+ account's project, or the owner's, reads as not found (404), and the owner's lists never show an account's. A take+ (`POST .../generate`, World mode and Blockout to film included), a retry (`.../items/<id>/retry`) and a 2K finish+ (`.../items/<id>/finish`) run the same way as Genjutsu's: every step on the account's ComfyUI or its own fal.ai or+ Replicate key, with only its own files, after the same checks. A project's cover and a grid's tiles must be its own+ files. Its AI Director writes the shot breakdown without the studio's AI helper (no GPU or key needed). Its Delete+ deletes a take for good (it has no Trash). "Create 3D scene" and an exact orbit run there too: on its GPU their first+ step is a 3D model, finished on this server under its limits as Image to 3D's are. Saving a still as an element, the+ elements list and sharing a project are left out: those are the owner's library. A guest gets the sign-up card.- **Files a run takes.** A run on your GPU takes only files you uploaded here, or your own results.A link or a `data:` URI answers 400 with `code: "input-not-allowed"`, someone else's file 403(`input-not-yours`), and a file that has expired 404 (`input-gone`, "That file has expired.diff --git a/src/app/(studio)/cinema/[id]/page.tsx b/src/app/(studio)/cinema/[id]/page.tsxindex e47ff32c..435b6523 100644--- a/src/app/(studio)/cinema/[id]/page.tsx+++ b/src/app/(studio)/cinema/[id]/page.tsx@@ -1,14 +1,16 @@import type { Metadata } from "next";+import { headers } from "next/headers";import { notFound } from "next/navigation";import { Suspense } from "react";import { CinemaWorkspace } from "@/components/cinema/workspace";-import { recordExists } from "@/server/records";+import { recordFor } from "@/server/records";export const metadata: Metadata = { title: "Cinema Studio" };async function Workspace({ params }: { params: PageProps<"/cinema/[id]">["params"] }) {const { id } = await params;- if (!recordExists({ kind: "cinema", ids: [id] })) notFound();+ // The owner's projects, or a signed-in account's own.+ if (!recordFor({ kind: "cinema", ids: [id] }, await headers())) notFound();return <CinemaWorkspace id={id} />;}diff --git a/src/app/api/cinema/projects/[id]/director/route.ts b/src/app/api/cinema/projects/[id]/director/route.tsindex a406359a..72c997be 100644--- a/src/app/api/cinema/projects/[id]/director/route.ts+++ b/src/app/api/cinema/projects/[id]/director/route.ts@@ -1,32 +1,44 @@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";+import { DirectorAsk, asCinemaViewer, body } from "@/server/cinema-schemas";-export async function GET(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {+export async function GET(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {await connection();- return handle(async () => {+ return asCinemaViewer(request, 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). */+/**+ * Ask the AI Director; answers with the whole conversation (the reply proposes shots, never renders them). An account's+ * Director never uses the studio's own AI helper: inside its work there is none (enhance.ts llmTextBackend), so it gets+ * the built-in breakdown, which needs no GPU and no key.+ */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 });- }, request);+ return asCinemaViewer(+ request,+ 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 });+ },+ { change: true },+ );}export async function DELETE(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {- return handle(async () => {- const { id } = await ctx.params;- clearChat(id);- return new Response(null, { status: 204 });- }, request);+ return asCinemaViewer(+ request,+ async () => {+ const { id } = await ctx.params;+ clearChat(id);+ return new Response(null, { status: 204 });+ },+ { change: true },+ );}diff --git a/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts b/src/app/api/cinema/projects/[id]/folders/[folderId]/route.tsindex 8445ca5d..0b7596d3 100644--- a/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts+++ b/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts@@ -1,19 +1,27 @@import { deleteFolder, updateFolder } from "@/server/cinema";-import { FolderPatch, body, handle } from "@/server/cinema-schemas";+import { FolderPatch, asCinemaViewer, body } 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));- }, request);+ return asCinemaViewer(+ request,+ 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));+ },+ { change: true },+ );}/** Its takes and subfolders move up to the parent folder. */export async function DELETE(request: 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 });- }, request);+ return asCinemaViewer(+ request,+ async () => {+ const { id, folderId } = await ctx.params;+ deleteFolder(id, folderId);+ return new Response(null, { status: 204 });+ },+ { change: true },+ );}diff --git a/src/app/api/cinema/projects/[id]/folders/route.ts b/src/app/api/cinema/projects/[id]/folders/route.tsindex ad0c00c4..4965cf0b 100644--- a/src/app/api/cinema/projects/[id]/folders/route.ts+++ b/src/app/api/cinema/projects/[id]/folders/route.ts@@ -1,10 +1,14 @@import { createFolder } from "@/server/cinema";-import { FolderCreate, body, handle } from "@/server/cinema-schemas";+import { FolderCreate, asCinemaViewer, body } 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 });- }, request);+ return asCinemaViewer(+ request,+ 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 });+ },+ { change: true },+ );}diff --git a/src/app/api/cinema/projects/[id]/generate/route.ts b/src/app/api/cinema/projects/[id]/generate/route.tsindex 827180d3..ab935f48 100644--- a/src/app/api/cinema/projects/[id]/generate/route.ts+++ b/src/app/api/cinema/projects/[id]/generate/route.ts@@ -1,14 +1,38 @@-import { generateInProject } from "@/server/cinema-generate";-import { GenerateBody, body, handle } from "@/server/cinema-schemas";+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { cinemaSteps, generateInProject, prepareCinemaRun, startCinemaRun, type CinemaRun } from "@/server/cinema-generate";+import { GenerateBody, body, fileRefs, handle, withStatus } 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`).+ * cap, creates the generations and records them in the project (in `folderId`). The owner's run as+ * always; a signed-in account's in its own project, on its own GPU or its own fal.ai or Replicate key,+ * with its own files, after the checks a studio run gets (src/server/account-tool-run.ts); a guest+ * signs up first.*/export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/generate">) {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }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, b.folderId ?? null), { status: 201 });+ if (viewer.kind === "owner") return Response.json(generateInProject(id, b.input, b.folderId ?? null), { status: 201 });+ let run: CinemaRun | null = null;+ return onceForAccount(+ viewer.account,+ `cinema:${id}`,+ undefined,+ () =>+ runAccountTool(request, viewer.account, {+ tool: "cinema",+ files: fileRefs(b.input),+ plan: () => withStatus(() => cinemaSteps((run = prepareCinemaRun(id, b.input, b.folderId ?? null)))),+ start: () => startCinemaRun(run!),+ }),+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),+ );}, request);}diff --git a/src/app/api/cinema/projects/[id]/items/[generationId]/finish/route.ts b/src/app/api/cinema/projects/[id]/items/[generationId]/finish/route.tsindex 969564a7..be3fdc59 100644--- a/src/app/api/cinema/projects/[id]/items/[generationId]/finish/route.ts+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/finish/route.ts@@ -1,12 +1,17 @@-import { CinemaError, finishTake } from "@/server/cinema";-import { handle } from "@/server/cinema-schemas";+import { guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { CinemaError, finishTake, planFinish, startFinish, type FinishPlan } from "@/server/cinema";+import { handle, withStatus } from "@/server/cinema-schemas";import { once } from "@/server/shorts-schemas";/*** Finish in 2K: a MiniMax H3 take made again at 2K (fal), or redrawn at 2K on your GPU (Open-H3 Regenerate), same folder.* The body may carry a requestId: a repeat of it (a double click, a retried POST) gets the first answer, not a second run.+ * A signed-in account's take in its own project, on its own GPU or key, after an account run's checks; a guest signs up+ * first.*/export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/finish">) {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();return handle(async () => {const { id, generationId } = await ctx.params;const text = await request.text().catch(() => "");@@ -18,7 +23,29 @@ export async function POST(request: Request, ctx: RouteContext<"/api/cinema/proj}const asked = (body as { requestId?: unknown } | null)?.requestId;if (asked !== undefined && !(typeof asked === "string" && /^[\w-]{1,64}$/.test(asked))) throw new CinemaError("Bad request", 400);- const items = await once(`cinema-finish:${id}:${generationId}`, asked, () => finishTake(id, generationId));- return Response.json({ items }, { status: 201 });+ const requestId = asked as string | undefined;+ if (viewer.kind === "owner") {+ const items = await once(`cinema-finish:${id}:${generationId}`, requestId, () => finishTake(id, generationId));+ return Response.json({ items }, { status: 201 });+ }+ let plan: FinishPlan | null = null;+ // An account's repeat gets its own first run, never another's.+ return onceForAccount(+ viewer.account,+ `cinema-finish:${id}:${generationId}`,+ requestId,+ () =>+ runAccountTool(request, viewer.account, {+ tool: "cinema",+ files: [],+ plan: () =>+ withStatus(() => {+ plan = planFinish(id, generationId);+ return [{ request: plan.request }];+ }),+ start: () => startFinish(plan!),+ }),+ ({ value, gpuWarning }) => Response.json({ items: value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),+ );}, request);}diff --git a/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts b/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.tsindex 6f13903f..05d7a1e6 100644--- a/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts@@ -1,10 +1,30 @@-import { retryItem } from "@/server/cinema";-import { handle } from "@/server/cinema-schemas";+import { guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { planRetry, retryItem, retrySteps, startRetry, type RetryPlan } from "@/server/cinema";+import { handle, withStatus } from "@/server/cinema-schemas";-/** Run a failed take again (same request, same folder). */+/**+ * Run a failed take again (same request, same folder). A signed-in account's take in its own project, on its own GPU+ * or key, after an account run's checks; a guest signs up first.+ */export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/retry">) {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();return handle(async () => {const { id, generationId } = await ctx.params;- return Response.json({ items: retryItem(id, generationId) }, { status: 201 });+ if (viewer.kind === "owner") return Response.json({ items: retryItem(id, generationId) }, { status: 201 });+ let plan: RetryPlan | null = null;+ return onceForAccount(+ viewer.account,+ `cinema-retry:${id}:${generationId}`,+ undefined,+ () =>+ runAccountTool(request, viewer.account, {+ tool: "cinema",+ files: [],+ plan: () => withStatus(() => retrySteps((plan = planRetry(id, generationId)))),+ start: () => startRetry(plan!),+ }),+ ({ value, gpuWarning }) => Response.json({ items: value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),+ );}, request);}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.tsindex 903e9c3f..81db09c3 100644--- a/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.ts+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.ts@@ -1,11 +1,20 @@import { setTiles } from "@/server/cinema";-import { TilesPut, body, handle } from "@/server/cinema-schemas";+import { TilesPut, asCinemaViewer, body, refsRefused } from "@/server/cinema-schemas";-/** The tiles the browser cut from a grid contact sheet (each already saved as an upload). */+/** The tiles the browser cut from a grid contact sheet (each already saved as an upload: an account's own). */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));- });+ return asCinemaViewer(+ request,+ async (viewer) => {+ const { id, generationId } = await ctx.params;+ const b = await body(request, TilesPut, "Those tiles aren't valid");+ const refused = refsRefused(+ viewer,+ b.tiles.map((t) => t.url),+ );+ if (refused) return refused;+ return Response.json(setTiles(id, generationId, b.tiles));+ },+ { change: true },+ );}diff --git a/src/app/api/cinema/projects/[id]/items/route.ts b/src/app/api/cinema/projects/[id]/items/route.tsindex 8316aacd..ded3d76a 100644--- a/src/app/api/cinema/projects/[id]/items/route.ts+++ b/src/app/api/cinema/projects/[id]/items/route.ts@@ -1,18 +1,22 @@import { connection } from "next/server";-import { listItems, listStudioGenerations, moveItems, removeItems, setFavorites } from "@/server/cinema";-import { ItemsDelete, ItemsPatch, body, handle } from "@/server/cinema-schemas";+import { CinemaError, deleteTakes, getProject, listItems, listStudioGenerations, moveItems, removeItems, setFavorites } from "@/server/cinema";+import { ItemsDelete, ItemsPatch, asCinemaViewer, body } 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.+ * A signed-in account reaches its own projects and runs only.*/export async function GET(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {await connection();- return handle(async () => {+ return asCinemaViewer(request, async () => {const { id } = await ctx.params;const qs = new URL(request.url).searchParams;- if (qs.get("scope") === "studio") return Response.json({ items: listStudioGenerations() });+ if (qs.get("scope") === "studio") {+ if (!getProject(id)) throw new CinemaError("Project not found", 404);+ return Response.json({ items: listStudioGenerations() });+ }const folder = qs.get("folder");const items = listItems(id, {folderId: folder === "root" ? null : folder || undefined,@@ -25,21 +29,33 @@ export async function GET(request: Request, ctx: RouteContext<"/api/cinema/proje/** 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");- // Only this project's takes change; the counts say how many did.- const moved = b.folderId !== undefined ? moveItems(id, b.ids, b.folderId) : 0;- const liked = b.favorite !== undefined ? setFavorites(id, b.ids, b.favorite) : 0;- return Response.json({ ok: true, moved, liked });- }, request);+ return asCinemaViewer(+ request,+ async () => {+ const { id } = await ctx.params;+ const b = await body(request, ItemsPatch, "Pick the takes to change");+ // Only this project's takes change; the counts say how many did.+ const moved = b.folderId !== undefined ? moveItems(id, b.ids, b.folderId) : 0;+ const liked = b.favorite !== undefined ? setFavorites(id, b.ids, b.favorite) : 0;+ return Response.json({ ok: true, moved, liked });+ },+ { change: true },+ );}-/** 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. */+/**+ * Bulk: take out of the project; `deleteGenerations` moves them to the library's Trash (restorable, still filed here).+ * An account has no Trash: its takes are deleted for good. 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;- const b = await body(request, ItemsDelete, "Pick the takes to delete");- return Response.json({ removed: removeItems(id, b.ids, { deleteGenerations: b.deleteGenerations }) });- }, request);+ return asCinemaViewer(+ request,+ async (viewer) => {+ const { id } = await ctx.params;+ const b = await body(request, ItemsDelete, "Pick the takes to delete");+ const removed = viewer.kind === "account" && b.deleteGenerations ? await deleteTakes(id, b.ids) : removeItems(id, b.ids, { deleteGenerations: b.deleteGenerations });+ return Response.json({ removed });+ },+ { change: true },+ );}diff --git a/src/app/api/cinema/projects/[id]/route.ts b/src/app/api/cinema/projects/[id]/route.tsindex 26a4feb1..b6a40f80 100644--- a/src/app/api/cinema/projects/[id]/route.ts+++ b/src/app/api/cinema/projects/[id]/route.ts@@ -1,36 +1,48 @@import { connection } from "next/server";import { CinemaError, deleteProject, getProject, listFolders, spentUsd, updateProject } from "@/server/cinema";-import { ProjectPatch, body, handle } from "@/server/cinema-schemas";-import { requestViewer } from "@/server/auth";+import { ProjectPatch, asCinemaViewer, body, refsRefused } from "@/server/cinema-schemas";import { cinemaContext } from "@/server/cinema-generate";import { worldcastContextNow } from "@/server/worldcast-on";-/** The project with its folders, its estimated spend and what this install can run (cloud models allowed, a civitai key). */+/**+ * The project with its folders, its estimated spend and what this install can run (cloud models allowed, a civitai key).+ * The owner's projects, or a signed-in account's own (another's, or the owner's, reads as not found).+ */export async function GET(req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {await connection();- return handle(async () => {+ return asCinemaViewer(req, async (viewer) => {const { id } = await ctx.params;const project = getProject(id);if (!project) throw new CinemaError("Project not found", 404);const { cloudAllowed, civitai } = cinemaContext();// The studio's WorldCast worker, for its owner only (N7-9): the Fly path says what it films on.- const worldcast = requestViewer(req).kind === "owner" ? await worldcastContextNow() : undefined;+ const worldcast = viewer.kind === "owner" ? await worldcastContextNow() : undefined;return Response.json({ project, folders: listFolders(id), spentUsd: spentUsd(id), context: { cloudAllowed, civitai, ...(worldcast !== undefined && { worldcast }) } });});}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));- }, request);+ return asCinemaViewer(+ request,+ async (viewer) => {+ const { id } = await ctx.params;+ const patch = await body(request, ProjectPatch, "Those project settings aren't valid");+ const refused = refsRefused(viewer, [patch.cover]);+ if (refused) return refused;+ return Response.json(updateProject(id, patch));+ },+ { change: true },+ );}export async function DELETE(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {- return handle(async () => {- const { id } = await ctx.params;- deleteProject(id);- return new Response(null, { status: 204 });- }, request);+ return asCinemaViewer(+ request,+ async () => {+ const { id } = await ctx.params;+ deleteProject(id);+ return new Response(null, { status: 204 });+ },+ { change: true },+ );}diff --git a/src/app/api/cinema/projects/route.ts b/src/app/api/cinema/projects/route.tsindex eccf931e..8e89cb5b 100644--- a/src/app/api/cinema/projects/route.ts+++ b/src/app/api/cinema/projects/route.ts@@ -1,15 +1,25 @@import { connection } from "next/server";+import { toolViewer } from "@/server/account-tool-run";import { createProject, listProjects } from "@/server/cinema";-import { ProjectCreate, body, handle } from "@/server/cinema-schemas";+import { ProjectCreate, asCinemaViewer, body, refsRefused } from "@/server/cinema-schemas";-export async function GET() {+/** The asker's projects: the owner's, or a signed-in account's own (a guest's list is empty). */+export async function GET(request: Request) {await connection();- return handle(() => Response.json({ items: listProjects() }));+ if (toolViewer(request).kind === "guest") return Response.json({ items: [] }, { headers: { "Cache-Control": "no-store" } });+ return asCinemaViewer(request, () => Response.json({ items: listProjects() }));}+/** A new project: the owner's, or the account's own (its cover one of its own files). A guest signs up first. */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 });- }, request);+ return asCinemaViewer(+ request,+ async (viewer) => {+ const input = await body(request, ProjectCreate, "Give the project a name");+ const refused = refsRefused(viewer, [input.cover]);+ if (refused) return refused;+ return Response.json(createProject(input), { status: 201 });+ },+ { change: true },+ );}diff --git a/src/app/api/starters/[id]/route.ts b/src/app/api/starters/[id]/route.tsindex c8c5892a..78aeb2d9 100644--- a/src/app/api/starters/[id]/route.ts+++ b/src/app/api/starters/[id]/route.ts@@ -1,20 +1,35 @@import { z } from "zod";+import { LIBRARY_MESSAGE } from "@/lib/guest-access";+import { getStarter } from "@/lib/starters/catalog";+import { projectSavesLimited } from "@/server/account-projects";+import { guestRun, toolViewer } from "@/server/account-tool-run";+import { asAccount } from "@/server/generations";import { createFromStarter, StarterError } from "@/server/starters";const Body = z.object({ engine: z.enum(["cloud", "open"]).default("cloud") });/*** The owner's "Use template" on a ready-made starter: makes it (a channel set up for its first episode, a brand kit with- * its product) and answers `{ href }`, where it opens. Guests get 401 and accounts 403 before this runs (LIBRARY_CHANGES).+ * its product) and answers `{ href }`, where it opens. A signed-in account makes Cinema Studio's ready films only, each+ * as its own project (src/server/cinema.ts); the rest are saved to the owner's library (403 for an account). A guest+ * signs up first.*/export async function POST(request: Request, { params }: RouteContext<"/api/starters/[id]">) {const { id } = await params;+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "account") {+ if (getStarter(id)?.seed.kind !== "cinema") return Response.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });+ const limited = projectSavesLimited(viewer.account.id);+ if (limited) return limited;+ }const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return Response.json({ error: "Pick an engine" }, { status: 400 });try {- return Response.json(await createFromStarter(id, parsed.data.engine), { status: 201 });+ const make = () => createFromStarter(id, parsed.data.engine);+ return Response.json(await (viewer.kind === "account" ? asAccount(viewer.account.id, make) : make()), { status: 201 });} catch (e) {- // A studio's own refusal (an engine this install doesn't use, a missing photo) keeps its status.+ // A studio's own refusal (an engine this install doesn't use, a missing photo, an account's limit of projects) keeps its status.const status = e instanceof StarterError ? e.status : ((e as { status?: number }).status ?? 400);return Response.json({ error: (e as Error).message || "That starter couldn't be made" }, { status });}diff --git a/src/components/cinema/cinema-feed.tsx b/src/components/cinema/cinema-feed.tsxindex ad6866cf..8d4b2ac5 100644--- a/src/components/cinema/cinema-feed.tsx+++ b/src/components/cinema/cinema-feed.tsx@@ -57,7 +57,7 @@ import { getModel } from "@/lib/catalog";import type { CinemaFolder } from "@/lib/catalog/cinema";import type { Generation, OutputFile } from "@/lib/catalog/types";import { formatCost, timeAgo } from "@/lib/format";-import { useEngineMode, useLikelyVisitor } from "@/lib/api";+import { useEngineMode, useIsOwner, useLikelyVisitor } from "@/lib/api";import { finishedTakes, finishIn2k, REGEN_OFFERED } from "@/lib/catalog/regenerate";import { useSubmitGuard } from "@/components/shorts/hooks";import { cn } from "@/lib/utils";@@ -177,17 +177,22 @@ export interface FeedHandlers {onUseTake: (g: CinemaGeneration, o: OutputFile) => void;onAnimate: (url: string) => void;onReference: (url: string, kind: OutputFile["kind"]) => void;- onSaveElement: (g: CinemaGeneration, url: string, kind: "character" | "location") => void;+ /** Save a still as an element (absent where elements can't be saved: they are the owner's library). */+ onSaveElement?: (g: CinemaGeneration, url: string, kind: "character" | "location") => void;/** "Create 3D scene" from a still (asks first, with the price). */- onCreateScene: (g: CinemaGeneration, url: string) => void;+ onCreateScene?: (g: CinemaGeneration, url: string) => void;onOpenScene: (g: CinemaGeneration) => void;/** What building a scene costs on the current engine ("Free", "≈ $0.03"). */scenePrice: string;}-/** A grid contact sheet and its tiles are one take: moving any of them to the Trash moves the lot. */-export function deleteLabel(g: CinemaGeneration): string {+/**+ * A grid contact sheet and its tiles are one take: moving any of them to the Trash moves the lot. `forever`: whoever has+ * no Trash (a signed-in account) deletes it for good.+ */+export function deleteLabel(g: CinemaGeneration, forever = false): string {const tiles = g.tiles?.length ?? (g.feature === "cinema-grid" && g.outputs.length > 1 ? g.outputs.length - 1 : 0);+ if (forever) return tiles ? `Delete grid (sheet + ${tiles} tiles)` : "Delete take";return tiles ? `Move grid to Trash (sheet + ${tiles} tiles)` : "Move take to Trash";}@@ -202,6 +207,8 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; foldconst guard = useSubmitGuard();// Remove a person runs on a self-hosted Fuobe only: a guest or an account isn't sent there.const visitor = useLikelyVisitor();+ // The Trash is the owner's: anyone else's Delete is for good.+ const owner = useIsOwner();const o = u.output;const elsewhere = foreign(u.g, projectId);// Finish in 2K: a MiniMax H3 take below 2K (fal renders it again at 2K; your GPU redraws it with Open-H3 Regenerate),@@ -236,21 +243,27 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold)}{o?.kind === "image" && !u.scene && (<>- <DropdownMenuItem onClick={() => handlers.onCreateScene(u.g, o.url)}>- <Box /> Create 3D scene <span className="ml-auto text-[11.5px] text-muted-foreground">{handlers.scenePrice}</span>- </DropdownMenuItem>+ {handlers.onCreateScene && (+ <DropdownMenuItem onClick={() => handlers.onCreateScene?.(u.g, o.url)}>+ <Box /> Create 3D scene <span className="ml-auto text-[11.5px] text-muted-foreground">{handlers.scenePrice}</span>+ </DropdownMenuItem>+ )}<DropdownMenuItem onClick={() => handlers.onAnimate(o.url)}><Clapperboard /> Animate (start frame)</DropdownMenuItem><DropdownMenuItem onClick={() => handlers.onReference(o.url, "image")}><ImagePlus /> Use as reference</DropdownMenuItem>- <DropdownMenuItem onClick={() => handlers.onSaveElement(u.g, o.url, "character")}>- <UserRoundPlus /> Save as character- </DropdownMenuItem>- <DropdownMenuItem onClick={() => handlers.onSaveElement(u.g, o.url, "location")}>- <MapPin /> Save as location- </DropdownMenuItem>+ {handlers.onSaveElement && (+ <>+ <DropdownMenuItem onClick={() => handlers.onSaveElement?.(u.g, o.url, "character")}>+ <UserRoundPlus /> Save as character+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => handlers.onSaveElement?.(u.g, o.url, "location")}>+ <MapPin /> Save as location+ </DropdownMenuItem>+ </>+ )}</>)}{o?.kind === "video" && (@@ -333,7 +346,7 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold)}<DropdownMenuSeparator /><DropdownMenuItem variant="destructive" onClick={() => onDelete([u.g.id])}>- <Trash2 /> {deleteLabel(u.g)}+ <Trash2 /> {deleteLabel(u.g, !owner)}</DropdownMenuItem></DropdownMenuContent></DropdownMenu>@@ -514,14 +527,16 @@ function TileView({</TooltipTrigger><TooltipContent>Animate: use as the start frame</TooltipContent></Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <button type="button" onClick={() => handlers.onCreateScene(g, u.output!.url)} className="grid size-7 place-items-center rounded-lg text-white/90 hover:bg-white/20 hover:text-white" aria-label={`Create 3D scene · ${handlers.scenePrice}`}>- <Box className="size-4" />- </button>- </TooltipTrigger>- <TooltipContent>Create 3D scene · {handlers.scenePrice}</TooltipContent>- </Tooltip>+ {handlers.onCreateScene && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => handlers.onCreateScene?.(g, u.output!.url)} className="grid size-7 place-items-center rounded-lg text-white/90 hover:bg-white/20 hover:text-white" aria-label={`Create 3D scene · ${handlers.scenePrice}`}>+ <Box className="size-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Create 3D scene · {handlers.scenePrice}</TooltipContent>+ </Tooltip>+ )}</>))}@@ -666,7 +681,9 @@ export function CinemaFeed({}, [all, prefs.split]);const layoutCls = prefs.layout === "square" ? "grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 2xl:grid-cols-5" : prefs.layout === "masonry" ? "columns-2 gap-3 sm:columns-3 lg:columns-4 2xl:columns-5" : "space-y-2";- // Delete moves to the Trash (the takes stay filed in their project): Undo puts them back.+ // Delete moves to the Trash (the takes stay filed in their project): Undo puts them back. Whoever has no Trash (a+ // signed-in account) deletes for good.+ const owner = useIsOwner();const del = async (list: string[]) => {setSelected(new Set());try {@@ -675,6 +692,7 @@ export function CinemaFeed({toastError(e);return;}+ if (!owner) return void toast(list.length > 1 ? `${list.length} takes deleted` : "Deleted", { id: "cinema-trash", duration: 3000 });toast(list.length > 1 ? `${list.length} takes moved to Trash` : "Moved to Trash", {id: "cinema-trash",duration: 6000,@@ -797,7 +815,7 @@ export function CinemaFeed({</DropdownMenu>)}<button type="button" onClick={() => void del(live)} className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium text-destructive hover:bg-destructive/10">- <Trash2 className="size-3.5" /> Move to Trash+ <Trash2 className="size-3.5" /> {owner ? "Move to Trash" : "Delete"}</button></div>)}diff --git a/src/components/cinema/folder-sidebar.tsx b/src/components/cinema/folder-sidebar.tsxindex 0520d8e1..9f2e88a5 100644--- a/src/components/cinema/folder-sidebar.tsx+++ b/src/components/cinema/folder-sidebar.tsx@@ -306,6 +306,7 @@ export function FolderSidebar({setView,counts,onDropItems,+ elements = true,className,}: {projectId: string;@@ -314,6 +315,8 @@ export function FolderSidebar({setView: (v: CinemaView) => void;counts: { home: number; favorites: number; folders: Map<string, number> };onDropItems: (ids: string[], folderId: string) => void;+ /** "My Elements": the studio's saved elements (the owner's library), so the owner's only. */+ elements?: boolean;className?: string;}) {const actions = useFolderActions(projectId);@@ -326,7 +329,7 @@ export function FolderSidebar({const sections: { view: CinemaView; label: string; icon: typeof Home; count?: number }[] = [{ view: { kind: "home" }, label: "Home", icon: Home, count: counts.home },{ view: { kind: "studio" }, label: "My Generations", icon: Library },- { view: { kind: "elements" }, label: "My Elements", icon: AtSign },+ ...(elements ? [{ view: { kind: "elements" } as CinemaView, label: "My Elements", icon: AtSign }] : []),{ view: { kind: "favorites" }, label: "My Favorites", icon: Heart, count: counts.favorites },];const newFolder = async () => {diff --git a/src/components/cinema/hooks.ts b/src/components/cinema/hooks.tsindex 7d2698d7..5989c86a 100644--- a/src/components/cinema/hooks.ts+++ b/src/components/cinema/hooks.ts@@ -4,7 +4,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useEffect, useState } from "react";import type { CinemaFolder, CinemaGenerateInput, CinemaProject, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";import type { Generation } from "@/lib/catalog/types";-import { useGenerationEvents } from "@/lib/api";+import { COMPUTER_KICK_EVENT, useGenerationEvents, useIsOwner } from "@/lib/api";import { responseError } from "@/lib/refusals";import { Autosaver } from "./autosave";import { applyToTakes, type CinemaGeneration } from "./live";@@ -33,6 +33,12 @@ const send = async <T,>(url: string, method: string, body?: unknown, keepalive =const active = (g: Generation) => g.status === "queued" || g.status === "running";+/**+ * A take started: the tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks+ * for them at once, as after a studio run.+ */+const kick = () => window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));+// ---------------------------------------------------------------------------// Live updates: the app's one shared generation stream (useGenerationEvents in lib/api.ts, one// connection per browser rather than one per Cinema tab). While it's connected the takes update in@@ -196,10 +202,12 @@ export const foreign = (g: CinemaGeneration, projectId: string) => !!g.projectId/*** Actions on takes. Likes and deletes go through the library (/api/generations/bulk) so they work* on any project's take; Delete moves to the Trash and comes with Undo. Moves are this project's- * only; retries go to the project that owns the take.+ * only; retries go to the project that owns the take. A signed-in account has no Trash: its Delete+ * deletes its own takes for good (DELETE /api/generations/<id>).*/export function useItemActions(projectId: string) {const qc = useQueryClient();+ const owner = useIsOwner();const keys = [["cinema", projectId, "items"], ["cinema", "studio"]];const patchLocal = (ids: string[], fn: (g: CinemaGeneration) => CinemaGeneration | null) => {for (const key of keys) qc.setQueryData<CinemaGeneration[]>(key, (old) => old?.map((g) => (ids.includes(g.id) ? fn(g) : g)).filter((g): g is CinemaGeneration => !!g));@@ -224,7 +232,8 @@ export function useItemActions(projectId: string) {/** Move to the Trash (restore with `restore`): the takes stay filed in their project. */remove: async (ids: string[]) => {patchLocal(ids, () => null);- await bulk("trash", ids).finally(settle);+ if (owner) return void (await bulk("trash", ids).finally(settle));+ await Promise.all(ids.map(async (id) => json<void>(await fetch(`/api/generations/${encodeURIComponent(id)}`, { method: "DELETE" })))).finally(settle);},restore: async (ids: string[]) => {await bulk("restore", ids).finally(settle);@@ -235,10 +244,12 @@ export function useItemActions(projectId: string) {},retry: async (g: CinemaGeneration) => {await send(`/api/cinema/projects/${g.projectId ?? projectId}/items/${g.id}/retry`, "POST").finally(settle);+ kick();},/** Finish in 2K: a MiniMax H3 take made again at 2K (fal) or redrawn at 2K on your GPU, in the same folder. */finish2k: async (g: CinemaGeneration, requestId?: string) => {await send(`/api/cinema/projects/${g.projectId ?? projectId}/items/${g.id}/finish`, "POST", requestId ? { requestId } : undefined).finally(settle);+ kick();return true;},saveTiles: async (generationId: string, tiles: CinemaTile[]) => {@@ -256,6 +267,7 @@ export function useCinemaGenerate(projectId: string) {return useMutation({mutationFn: (body: GenerateBody) => send<GenerateResult>(`/api/cinema/projects/${projectId}/generate`, "POST", body),onSuccess: (res, body) => {+ kick();// New takes appear at once (where the server filed them); the stream and polling take over.const folderId = res.folderId === undefined ? body.folderId : res.folderId;qc.setQueryData<CinemaGeneration[]>(["cinema", projectId, "items"], (old) =>diff --git a/src/components/cinema/projects-view.tsx b/src/components/cinema/projects-view.tsxindex c3062134..e6159644 100644--- a/src/components/cinema/projects-view.tsx+++ b/src/components/cinema/projects-view.tsx@@ -7,10 +7,9 @@ import { Suspense, useCallback, useEffect, useState } from "react";import { PageShell } from "@/components/page-shell";import { PageHeader } from "@/components/page-shell";import { HadItemsScript, useHadItems } from "@/components/use-had-items";-import { SelfHostNote } from "@/components/self-host-note";import { ExampleRow } from "@/components/studio/example-row";import { StarterSection, useStarters } from "@/components/starters/starter-section";-import { useIsVisitor } from "@/lib/api";+import { askToSignUp, useIsGuest } from "@/lib/api";import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Skeleton } from "@/components/ui/skeleton";@@ -127,8 +126,7 @@ const GRID = "grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-3 xl:* The first-production block, or (`loading`) a placeholder of exactly its size: a grid skeleton* swapped for this block moved the page (CLS 0.048 in the round-4 audit).*/-/** onCreate: none for a guest or an account (a project is saved to the owner's library), who is told so instead. */-function EmptyProjects({ loading, onCreate, className }: { loading?: boolean; onCreate?: () => void; className?: string }) {+function EmptyProjects({ loading, onCreate, className }: { loading?: boolean; onCreate: () => void; className?: string }) {return (<div className={cn("mx-auto flex max-w-md flex-col items-center pt-[8vh] text-center", className)} aria-busy={loading || undefined} aria-label={loading ? "Loading projects" : undefined}>{loading ? (@@ -149,20 +147,11 @@ function EmptyProjects({ loading, onCreate, className }: { loading?: boolean; on<div className="grid size-14 place-items-center rounded-2xl bg-brand-faint text-brand-text"><Clapperboard className="size-6" /></div>- {onCreate ? (- <>- <h2 className="mt-5 font-heading text-[26px] leading-tight">Start your first production</h2>- <p className="mt-2 text-[15px] text-muted-foreground">Projects keep your generations, elements, and chats together – create one to start.</p>- <Button className="mt-6" onClick={onCreate}>- <Plus /> New project- </Button>- </>- ) : (- <>- <h2 className="mt-5 font-heading text-[26px] leading-tight">Projects aren't available here</h2>- <SelfHostNote className="mt-2 text-[15px]" />- </>- )}+ <h2 className="mt-5 font-heading text-[26px] leading-tight">Start your first production</h2>+ <p className="mt-2 text-[15px] text-muted-foreground">Projects keep your generations, elements, and chats together – create one to start.</p>+ <Button className="mt-6" onClick={onCreate}>+ <Plus /> New project+ </Button></>)}</div>@@ -178,9 +167,9 @@ export function CinemaProjects({ examples, starters: given = [] }: { examples?:const router = useRouter();const [creating, setCreating] = useState(false);const [editing, setEditing] = useState<CinemaProject | null>(null);- // A project is saved to the studio's library, which is its owner's: a guest or an account can't start one.- const visitor = useIsVisitor();- const onCreate = visitor ? undefined : () => setCreating(true);+ // The owner's projects, or a signed-in account's own; a guest is offered a free account first.+ const guest = useIsGuest();+ const onCreate = () => (guest ? askToSignUp("run") : setCreating(true));// The ready films this viewer sees: a visitor only those with their real cover (the page carries only those), the// owner every one.const { owner, starters } = useStarters("cinema", given);@@ -193,23 +182,21 @@ export function CinemaProjects({ examples, starters: given = [] }: { examples?:return (<PageShell wide><PageHeader title="Cinema Studio" description="Direct films shot by shot: genre, camera, lens, palette and light, with characters and locations that stay the same.">- {!visitor && (- <Button onClick={() => setCreating(true)}>- <Plus /> New project- </Button>- )}+ <Button onClick={onCreate}>+ <Plus /> New project+ </Button></PageHeader><Suspense fallback={null}><OpenerQuery onOpener={markOpener} /></Suspense>{blockout && !!data?.length && (<p className="mb-5 flex items-center gap-2 rounded-xl bg-brand-faint px-3 py-2.5 text-[13px] text-brand-text">- <Box className="size-4 shrink-0" /> Blockout to film: pick the project to film it in{onCreate ? ", or start a new one" : ""}.+ <Box className="size-4 shrink-0" /> Blockout to film: pick the project to film it in, or start a new one.</p>)}{opener === "world" && !!data?.length && (<p className="mb-5 flex items-center gap-2 rounded-xl bg-brand-faint px-3 py-2.5 text-[13px] text-brand-text">- <Globe className="size-4 shrink-0" /> World: pick the project to film it in{onCreate ? ", or start a new one" : ""}.+ <Globe className="size-4 shrink-0" /> World: pick the project to film it in, or start a new one.</p>)}{isLoading ? (@@ -230,10 +217,7 @@ export function CinemaProjects({ examples, starters: given = [] }: { examples?:) : !data?.length ? (<div key="empty">{hasStarters ? (- <>- {!owner && <SelfHostNote className="mb-5">Projects aren't available here.</SelfHostNote>}- <StarterSection surface="cinema" starters={given} />- </>+ <StarterSection surface="cinema" starters={given} />) : (<EmptyProjects onCreate={onCreate} />)}@@ -246,7 +230,7 @@ export function CinemaProjects({ examples, starters: given = [] }: { examples?:<ProjectCard key={p.id} project={p} onSettings={() => setEditing(p)} query={query} />))}<button- onClick={() => setCreating(true)}+ onClick={onCreate}className="flex aspect-video flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border-strong text-[13px] font-medium text-muted-foreground transition-colors hover:border-primary hover:bg-brand-faint hover:text-brand-text"><Plus className="size-5" /> New projectdiff --git a/src/components/cinema/prompt-bar.tsx b/src/components/cinema/prompt-bar.tsxindex 688bc822..f6ce20a8 100644--- a/src/components/cinema/prompt-bar.tsx+++ b/src/components/cinema/prompt-bar.tsx@@ -14,7 +14,7 @@ import { PromptInput, ELEMENT_ICONS, type PromptInputHandle } from "@/componentsimport { ShotsEditor } from "@/components/studio/shots-editor";import { ResponsivePanel } from "@/components/studio/responsive-panel";import { useEdgeFade } from "@/components/studio/use-edge-fade";-import { uploadFile, useAssets, useIsOwner, useModelAccess, useStatus } from "@/lib/api";+import { uploadFile, useAssets, useModelAccess, useStatus } from "@/lib/api";import { offered } from "@/lib/model-access";import { getModel } from "@/lib/catalog";import {@@ -359,8 +359,6 @@ export function PromptBar(props: PromptBarProps) {// Reference clips make the take reference-to-video: the first image is then a reference, not the start frame.const refMode = plan.steps.find((s) => s.key === "main")?.request.op === "ref2v";const video = draft.mode === "video";- // Exact orbits start with a 3D depth step and run on the studio's own GPU: the owner's for now.- const owner = useIsOwner();const action = input.action;const busy = generate.isPending || preparing;// The take's length: the main clip, plus what an extend adds (Fuobe Cinema past 20 s in the cloud).@@ -674,7 +672,7 @@ export function PromptBar(props: PromptBarProps) {</div>{video && <MoveChips moves={draft.moves} onChange={(moves) => setDraft(withMoves(draft, moves))} />}- {video && owner && action === "generate" && takesExact(draft.moves[0]) && (+ {video && action === "generate" && takesExact(draft.moves[0]) && (<div className="px-2 pb-1.5"><ExactOrbitControls compact engine={engine} value={draft.exact ?? null} defaults={exactDefaults(draft.moves[0])} onChange={(exact) => setDraft({ exact })} /></div>diff --git a/src/components/cinema/side-panel.tsx b/src/components/cinema/side-panel.tsxindex 7e4f067b..ce7f8106 100644--- a/src/components/cinema/side-panel.tsx+++ b/src/components/cinema/side-panel.tsx@@ -8,6 +8,7 @@ import { Input } from "@/components/ui/input";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { directorSummary, moveBySlug, type CinemaProject, type DirectorMessage, type DirectorSettings, type DirectorShot } from "@/lib/catalog/cinema";import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";+import { useIsOwner } from "@/lib/api";import { toastError } from "@/lib/refusals";import { useAutosave, useDirectorChat, useUpdateProject } from "./hooks";@@ -44,6 +45,8 @@ function ShotCard({ shot, onLoad }: { shot: DirectorShot; onLoad: (s: DirectorSh}function Message({ m, onLoad, onBrief }: { m: DirectorMessage; onLoad: (s: DirectorShot) => void; onBrief: (b: string) => void }) {+ // Connecting an AI helper is the owner's (Settings): nobody else is told about it.+ const owner = useIsOwner();if (m.role === "user")return (<div className="flex justify-end">@@ -58,7 +61,7 @@ function Message({ m, onLoad, onBrief }: { m: DirectorMessage; onLoad: (s: Direc</span><div className="min-w-0 flex-1"><p className="text-[13.5px] leading-relaxed whitespace-pre-wrap">{m.text}</p>- {m.source === "offline" && <p className="mt-0.5 text-[11px] text-muted-foreground">Offline breakdown — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for a smarter Director.</p>}+ {m.source === "offline" && owner && <p className="mt-0.5 text-[11px] text-muted-foreground">Offline breakdown — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for a smarter Director.</p>}</div></div>{m.brief && (@@ -83,6 +86,8 @@ function Message({ m, onLoad, onBrief }: { m: DirectorMessage; onLoad: (s: Direcfunction DirectorChat({ projectId, onLoadShot, onBrief, promptText }: { projectId: string; onLoadShot: (s: DirectorShot) => void; onBrief: (b: string) => void; promptText: string }) {const { messages, ask, clear } = useDirectorChat(projectId);+ // Only the owner's Director can use an AI helper (a visitor's writes its breakdown without one).+ const owner = useIsOwner();const [text, setText] = useState("");const end = useRef<HTMLDivElement>(null);useEffect(() => {@@ -163,7 +168,7 @@ function DirectorChat({ projectId, onLoadShot, onBrief, promptText }: { projectI</Button></div></div>- <p className="px-1 pt-1.5 text-[10.5px] text-muted-foreground">LLMs can make mistakes. The Director only proposes: nothing runs and nothing is spent until you press Generate.</p>+ <p className="px-1 pt-1.5 text-[10.5px] text-muted-foreground">{owner && "LLMs can make mistakes. "}The Director only proposes: nothing runs and nothing is spent until you press Generate.</p></div></div>);diff --git a/src/components/cinema/soul-builders.tsx b/src/components/cinema/soul-builders.tsxindex e8173e00..3443bec0 100644--- a/src/components/cinema/soul-builders.tsx+++ b/src/components/cinema/soul-builders.tsx@@ -55,6 +55,8 @@ interface BuilderProps {settings: DirectorSettings;context: { cloudAllowed: boolean; civitai?: boolean; worldcast?: boolean };brief: string;+ /** Saving the pick as an element (the studio's library: the owner's). Without it the pictures stay as the project's takes. */+ canSave?: boolean;}/** "${v}M" → "$250M", "{v}s" → "2020s", "{v}yo" → "35yo". */@@ -246,7 +248,7 @@ export function SoulCastDialog(props: BuilderProps) {);}-function SoulCast({ projectId, folderId, engine, context, brief, onOpenChange }: BuilderProps) {+function SoulCast({ projectId, folderId, engine, context, brief, onOpenChange, canSave = true }: BuilderProps) {const [values, setValues] = useState<CastValues>(castDefaults);const [tab, setTab] = useState(SOUL_CAST_TABS[0]);const [notes, setNotes] = useState("");@@ -347,7 +349,7 @@ function SoulCast({ projectId, folderId, engine, context, brief, onOpenChange }:<p className="text-[12.5px] font-medium">Select an image variant for your cast</p><Results items={results} picked={chosen} onPick={(u) => setPicked((p) => (p.map(current).includes(u) ? [] : [u]))} /><CastTurnaround projectId={projectId} folderId={folderId} engine={engine} name={castName(visible)} results={results} picked={chosen[0]} />- <SaveElement kind="character" defaultName={castName(visible)} picked={chosen} description={castPrompt(visible, notes)} onSaved={() => onOpenChange(false)} />+ {canSave && <SaveElement kind="character" defaultName={castName(visible)} picked={chosen} description={castPrompt(visible, notes)} onSaved={() => onOpenChange(false)} />}</div>)}</>@@ -394,7 +396,7 @@ export function SoulLocationDialog(props: BuilderProps) {);}-function SoulLocation({ projectId, folderId, engine, settings, context, brief, onOpenChange }: BuilderProps) {+function SoulLocation({ projectId, folderId, engine, settings, context, brief, onOpenChange, canSave = true }: BuilderProps) {const [prompt, setPrompt] = useState("");const [batch, setBatch] = useState(2);const [picked, setPicked] = useState<string[]>([]);@@ -485,7 +487,7 @@ function SoulLocation({ projectId, folderId, engine, settings, context, brief, o))}</div>)}- <SaveElement kind="location" defaultName={locationName(prompt)} picked={chosen} description={prompt} onSaved={() => onOpenChange(false)} />+ {canSave && <SaveElement kind="location" defaultName={locationName(prompt)} picked={chosen} description={prompt} onSaved={() => onOpenChange(false)} />}</div>)}</>diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsxindex 941c7b37..c2e0e55e 100644--- a/src/components/cinema/workspace.tsx+++ b/src/components/cinema/workspace.tsx@@ -16,7 +16,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { EngineSwitch } from "@/components/studio/engine-switch";import type { PromptInputHandle } from "@/components/studio/prompt-input";-import { useElements, useEngine, useSaveElement } from "@/lib/api";+import { useElements, useEngine, useIsOwner, useSaveElement } from "@/lib/api";import { rigError, type CinemaFolder, type DirectorSettings, type DirectorShot } from "@/lib/catalog/cinema";import type { StudioElement } from "@/lib/catalog/elements";import type { OutputFile } from "@/lib/catalog/types";@@ -212,7 +212,11 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaGconst { project, folders, spentUsd, context } = data;const id = project.id;const router = useRouter();- const share = useShare();+ // Sharing a project and saving elements keep to the studio's library: the owner's only. A signed-in account's project+ // is its own, with everything else here.+ const owner = useIsOwner();+ const shareApi = useShare();+ const share = owner ? shareApi : null;const [engine, setEngine, engineMode] = useEngine();const [view, setView] = useState<CinemaView>({ kind: "home" });const [nested, setNested] = useState(true);@@ -377,7 +381,9 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaGsetDraft((d) => (d.refs.some((r) => r.ref === url) ? {} : { refs: [...d.refs, { id: nanoid(6), ref: url, preview: url, kind }] }));toast("Added to references", { duration: 1500 });},- onSaveElement: (g, url, kind) =>+ onSaveElement: !owner+ ? undefined+ : (g, url, kind) =>saveElement.mutate({ name: nameFrom(g.take?.prompt ?? g.request.prompt, kind === "character" ? "New character" : "New location"), kind, references: [url] },{@@ -454,13 +460,14 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG}}counts={counts}onDropItems={(ids, f) => void actions.move(ids, f).then(() => toast(`Moved ${ids.length} take${ids.length > 1 ? "s" : ""}`, { duration: 1500 }))}+ elements={owner}className="h-full"/>);const sidePanel = panel && (<SidePanel project={project} tab={panel} setTab={setPanel} onClose={() => setPanel(null)} onLoadShot={onLoadShot} promptText={draft.prompt} />);- const builderProps = { projectId: id, folderId, engine, settings, context, brief: project.brief.body };+ const builderProps = { projectId: id, folderId, engine, settings, context, brief: project.brief.body, canSave: owner };const proposedShot = Number(search.get("shot")) || 0;return (diff --git a/src/components/starters/starter-page.tsx b/src/components/starters/starter-page.tsxindex 59c35b04..6ed34c93 100644--- a/src/components/starters/starter-page.tsx+++ b/src/components/starters/starter-page.tsx@@ -7,7 +7,7 @@ import { PageShell } from "@/components/page-shell";import { SelfHostNote } from "@/components/self-host-note";import { CoverArt, CoverImg, useCoverPlayback } from "@/components/template-cover";import { useIsOwner, useIsVisitor } from "@/lib/api";-import { STARTER_SURFACES, starterShown, type StarterCardData, type StarterInput } from "@/lib/starters/types";+import { STARTER_SURFACES, VISITOR_MAKES, starterShown, type StarterCardData, type StarterInput } from "@/lib/starters/types";import { StarterIcon } from "./starter-icon";import { useStarterUse } from "./starter-section";import { StepsGlyph } from "./steps-glyph";@@ -106,7 +106,7 @@ export function StarterPage({ s }: { s: StarterCardData }) {</div><p className="mt-2 text-[15px] text-pretty text-muted-foreground">{s.description}</p>- {owner ? (+ {owner || VISITOR_MAKES.has(s.surface) ? (<div className="mt-4 flex flex-wrap items-center gap-3">{s.use.kind === "fill" ? (<Button asChild className="rounded-full">diff --git a/src/components/starters/starter-section.tsx b/src/components/starters/starter-section.tsxindex 537e8640..061b4b0a 100644--- a/src/components/starters/starter-section.tsx+++ b/src/components/starters/starter-section.tsx@@ -9,7 +9,7 @@ import { Button } from "@/components/ui/button";import { StepFlow } from "@/components/canvas/template-card";import { useEngine, useIsOwner } from "@/lib/api";import { responseError, toastError } from "@/lib/refusals";-import { STARTER_SURFACES, starterHref, starterShown, type OwnerStarters, type StarterCardData, type StarterFill, type StarterSurface } from "@/lib/starters/types";+import { STARTER_SURFACES, VISITOR_MAKES, starterHref, starterShown, type OwnerStarters, type StarterCardData, type StarterFill, type StarterSurface } from "@/lib/starters/types";import { cn } from "@/lib/utils";import { StarterCard } from "./starter-card";import { StarterIcon } from "./starter-icon";@@ -104,7 +104,7 @@ export function StarterTile({ s, owner, busy, onUse, wide, compact }: { s: Start<span className="inline-flex items-center gap-1 text-[13px] font-medium text-foreground">Open it <ArrowRight className="size-3.5 transition-transform group-hover/starter:translate-x-0.5" /></span>- ) : owner ? (+ ) : owner || VISITOR_MAKES.has(s.surface) ? (<Button size="sm" className="w-fit rounded-full" onClick={onUse} disabled={busy}>{busy ? <Loader2 className="animate-spin" /> : <Plus />} Use template</Button>diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 1ba3c353..59f8970d 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -284,6 +284,8 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [/^\/api\/genjutsu\/describe$/,// Character Swap Studio's jobs on an account's own project (src/server/swap-studio-account.ts)./^\/api\/swap-studio\/projects\/[^/]+\/(anchors|assemble|clips|masks|prepare|queue|sharpen|transcribe)$/,+ // Cinema Studio: a take in the account's own project, a retry and a 2K finish of one of its takes.+ /^\/api\/cinema\/projects\/[^/]+\/(generate|items\/[^/]+\/(retry|finish))$/,];/**@@ -299,6 +301,10 @@ export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [// presets. Enhance isn't here: it isn't offered on an account's own GPU yet./^\/api\/shorts\/sessions(\/[^/]+(\/stitch|\/segments\/[^/]+(\/primary)?)?)?$/,/^\/api\/shorts\/presets(\/[^/]+)?$/,+ // Cinema Studio: its projects, folders, takes, grid tiles and AI Director chat (the Director's built-in breakdown:+ // no AI helper, GPU or key), and a ready film made as its own project (src/server/cinema.ts).+ /^\/api\/cinema\/projects(\/[^/]+(\/(director|folders|items|folders\/[^/]+|items\/[^/]+\/tiles))?)?$/,+ /^\/api\/starters\/cinema\.[^/]+$/,];export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));diff --git a/src/lib/starters/types.ts b/src/lib/starters/types.tsindex 42205f5c..592c53d0 100644--- a/src/lib/starters/types.ts+++ b/src/lib/starters/types.ts@@ -26,7 +26,6 @@ export const STARTER_SURFACES: Record<StarterSurface, { base: string; name: striname: "Cinema Studio",section: "Start from a ready film",note: "Each one comes with its look, its brief and three shots. It opens with shot 1 ready to make.",- visitorNote: "Each one comes with its look, its brief and three shots.",unavailable: "Projects aren't available here.",},storyboard: {@@ -130,3 +129,9 @@ export const starterHref = (s: Pick<StarterCardData, "id" | "surface"> & { use?:/** Who sees a starter's card: a visitor only one with its real cover (the owner sees all, marked). */export const starterShown = (s: Pick<StarterCardData, "cover">, visitor: boolean) => !visitor || !!s.cover;++/**+ * Surfaces whose starters a visitor makes too: a signed-in account's Cinema film is its own project (a guest is offered a+ * free account first). Elsewhere a starter is saved to the owner's library, so only the owner makes it.+ */+export const VISITOR_MAKES: ReadonlySet<StarterSurface> = new Set<StarterSurface>(["cinema"]);diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.tsindex 86e1437c..6f697564 100644--- a/src/server/account-sweep.ts+++ b/src/server/account-sweep.ts@@ -4,6 +4,7 @@ import path from "node:path";import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";import { deleteAccountCanvases } from "./account-canvas";import { deleteAccountProjects } from "./account-projects";+import { deleteAccountCinema } from "./cinema";import { clearAccountLoras } from "./account-loras";import { accountById, deleteAccount, readAccountIds, setAccountDisabled } from "./auth";import { strayAccountIds } from "./auth-store";@@ -46,6 +47,8 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: nfor (const f of files) deleteAsset(f);clearAccountLoras(id);deleteAccountCanvases(id);+ // A tool's own rows under its projects go before the projects themselves.+ deleteAccountCinema(id);deleteAccountProjects(id);await runAccountDeletedHooks(id);return { runs, files: files.length };diff --git a/src/server/cinema-generate.ts b/src/server/cinema-generate.tsindex d984ac56..22afada2 100644--- a/src/server/cinema-generate.ts+++ b/src/server/cinema-generate.ts@@ -24,24 +24,29 @@ import { encodePng } from "./png";import { engineMode, getSetting } from "./settings";import { saveFile, storedMedia } from "./storage";import { isOffered } from "./model-access";+import { tenantAccount } from "./tenant";import { worldcastContext } from "./worldcast-on";/*** What this install can run right now (cloud fallbacks such as reading a take's first frame, the workflows it has, a- * camera LoRA that downloads from civitai, which fal gets only with the user's civitai key).+ * camera LoRA that downloads from civitai, which fal gets only with the user's civitai key). Inside an account's work the+ * engine mode is its own, and the studio's civitai key is never its (loras.ts leaves those LoRAs out of its runs).*/export function cinemaContext(): CinemaContext {- return { cloudAllowed: engineMode() !== "open", has: (id) => !!getModel(id) && isOffered(id), civitai: !!getSetting("civitaiKey"), worldcast: worldcastContext() };+ return { cloudAllowed: engineMode() !== "open", has: (id) => !!getModel(id) && isOffered(id), civitai: !tenantAccount() && !!getSetting("civitaiKey"), worldcast: worldcastContext() };}declare global {var __fuobeSwatches: Map<string, string> | undefined;}-/** A 12-stripe PNG of the palette: the reference image palette-transfer recolours toward. */+/**+ * A 12-stripe PNG of the palette: the reference image palette-transfer recolours toward. Each one's own file: an+ * account's run reads only its own files, so an account's swatch is stored as its own (and never handed to another).+ */export function swatchUrl(hex: string[]): string {globalThis.__fuobeSwatches ??= new Map();- const key = hex.join(",").toLowerCase();+ const key = `${tenantAccount() ?? ""}|${hex.join(",").toLowerCase()}`;const hit = globalThis.__fuobeSwatches.get(key);if (hit) return hit;const stripe = 32;@@ -133,6 +138,27 @@ export interface CinemaRunResult {* in the project (in `folderId`, the scene the user is looking at).*/export function generateInProject(projectId: string, asked: CinemaRequest, folderId: string | null = null): CinemaRunResult {+ return startCinemaRun(prepareCinemaRun(projectId, asked, folderId));+}++/** A take, planned and checked (the project's limit included): what startCinemaRun makes. */+export interface CinemaRun {+ projectId: string;+ input: CinemaRequest;+ plan: CinemaPlan;+ folder: string | null;+ notes: string[];+}++/**+ * The run's steps as an account's run checks them (account-tool-run.ts): each request and how many earlier steps it+ * waits for (one per job of the step before it, or one per step it follows).+ */+export const cinemaSteps = (run: CinemaRun): { request: GenerationRequest; deps: number }[] =>+ run.plan.steps.map((s) => ({ request: s.request, deps: s.perJobOf ? 1 : (s.after?.length ?? 0) }));++/** Plan a take in the project and check every step and the project's limit; nothing is made yet. */+export function prepareCinemaRun(projectId: string, asked: CinemaRequest, folderId: string | null = null): CinemaRun {const project = getProject(projectId);if (!project) throw new CinemaError("Project not found", 404);// A blockout's take remembers the length its file says, as the plan films it.@@ -159,7 +185,11 @@ export function generateInProject(projectId: string, asked: CinemaRequest, folde);}}+ return { projectId, input, plan, folder, notes };+}+/** Make a planned take: its chained generations, recorded in the project. */+export function startCinemaRun({ projectId, input, plan, folder, notes }: CinemaRun): CinemaRunResult {const take: CinemaTakeInfo = {mode: input.mode,action: input.action,diff --git a/src/server/cinema-schemas.ts b/src/server/cinema-schemas.tsindex c5096144..fed4407e 100644--- a/src/server/cinema-schemas.ts+++ b/src/server/cinema-schemas.ts@@ -1,12 +1,16 @@import "server-only";import { z } from "zod";import { BLOCKOUT } from "@/lib/blockout";+import { GUEST_HEADER, GUEST_LIBRARY_MESSAGE } from "@/lib/guest-access";import { PERSPECTIVES, STYLES, WORLD_LIMITS, type Perspective, type WorldStyle } from "@/lib/world";import { DISTANCE, MAX_KEYS } from "@/lib/camera-path";import { APERTURE, LENS } from "@/lib/scene3d";+import { AccountProjectError, projectRefsProblem, projectSavesLimited } from "./account-projects";+import { guestRun, toolViewer, type ToolViewer } from "./account-tool-run";import { CinemaError } from "./cinema";import { connectRefusal } from "./connect-refusal";-import { ConnectComfyError } from "./generations";+import { asAccount, ConnectComfyError } from "./generations";+import { ShortsError } from "./shorts";import { TurnaroundSchema } from "./turnaround";/** Request bodies of /api/cinema/** (zod drops unknown keys). */@@ -217,9 +221,60 @@ export async function handle(fn: () => Promise<Response> | Response, request?: Rreturn await fn();} catch (e) {if (e instanceof CinemaError) return Response.json({ error: e.message }, { status: e.status });+ // An account's project refused (its limit of projects, a project too big to save).+ if (e instanceof AccountProjectError) return Response.json({ error: e.message }, { status: e.status });// A run nothing connected can make: the connect card in the owner's browser (src/server/connect-refusal.ts).if (e instanceof ConnectComfyError) return (request && connectRefusal(e, request)) || Response.json({ error: e.message }, { status: 422 });console.error("[cinema]", e);return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });}}++// ---------------------------------------------------------------------------+// Who asks (public sign-up)++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * A Cinema route as its asker sees it: the owner's projects as always; a signed-in account's own projects, inside its+ * own work (asAccount: cinema.ts then reads and changes its projects only, and another's reads as not found); a guest's+ * change gets the sign-up card and its read nothing of the owner's (as the proxy answers it). `change`: a save, counted+ * against the account's saves a minute (account-projects.ts).+ */+export async function asCinemaViewer(request: Request, fn: (viewer: ToolViewer) => Response | Promise<Response>, opts: { change?: boolean } = {}): Promise<Response> {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return opts.change ? guestRun() : Response.json({ error: GUEST_LIBRARY_MESSAGE }, { status: 401, headers: { [GUEST_HEADER]: "1", ...NO_STORE } });+ if (viewer.kind === "owner") return handle(() => fn(viewer), request);+ if (opts.change) {+ const limited = projectSavesLimited(viewer.account.id);+ if (limited) return limited;+ }+ const id = viewer.account.id;+ return handle(() => asAccount(id, () => fn(viewer)), request);+}++/** The files an account's project names (a cover, a grid's tiles): its own uploads and results only. Null: fine. */+export function refsRefused(viewer: ToolViewer, files: (string | null | undefined)[]): Response | null {+ if (viewer.kind !== "account") return null;+ const problem = projectRefsProblem(viewer.account.id, { files: files.filter((f): f is string => !!f) });+ return problem ? Response.json({ error: problem.error, code: problem.code }, { status: problem.status, headers: NO_STORE }) : null;+}++/** Every stored file a request names, wherever it sits in it (each FileRef above: an account's run takes only its own). */+export function fileRefs(value: unknown, out: string[] = []): string[] {+ if (typeof value === "string") {+ if (value.startsWith("/api/files/")) out.push(value);+ } else if (Array.isArray(value)) for (const v of value) fileRefs(v, out);+ else if (value && typeof value === "object") for (const v of Object.values(value)) fileRefs(v, out);+ return out;+}++/** An account's plan refused with the status Cinema gives it (account-tool-run.ts keeps a ShortsError's status). */+export function withStatus<T>(fn: () => T): T {+ try {+ return fn();+ } catch (e) {+ if (e instanceof CinemaError) throw new ShortsError(e.message, e.status);+ throw e;+ }+}diff --git a/src/server/cinema.ts b/src/server/cinema.tsindex fd4cb959..20270e64 100644--- a/src/server/cinema.ts+++ b/src/server/cinema.ts@@ -4,15 +4,23 @@ import { getModel } from "@/lib/catalog";import type { CinemaFolder, CinemaItem, CinemaProject, CinemaTakeInfo, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";import { finishIn2k, REGEN_COPY, REGEN_OFFERED } from "@/lib/catalog/regenerate";import type { Generation, GenerationRequest } from "@/lib/catalog/types";+import { createAccountProject, deleteAccountProject, getAccountProject, listAccountProjects, updateAccountProject, type AccountProject } from "./account-projects";import { db } from "./db";import { ConnectComfyError, createGenerations, getGeneration, listGenerations, previewChained, previewGeneration, toGeneration } from "./generations";-import { trashGenerations } from "./library";+import { deleteForever, trashGenerations } from "./library";import { engineMode } from "./settings";+import { tenantAccount } from "./tenant";/*** 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.+ *+ * Whose projects: the owner's are rows of `cinema_projects`. A signed-in account's (public sign-up) are its own+ * projects in account-projects.ts (kind "cinema"), read and changed only inside its own work (tenant.ts asAccount):+ * every function here reads the projects of whoever the work is for, so an account never reaches the owner's projects+ * or another account's (they read as "not found"), and the owner's lists never hold an account's. A project's folders+ * and takes are rows of `cinema_folders` and `cinema_items` under its id either way, reached only through its project.*/export class CinemaError extends Error {@@ -129,10 +137,66 @@ function liveGeneration(id: string): Generation | null {// ---------------------------------------------------------------------------// Projects+/** An account's project kind in account-projects.ts. */+const ACCOUNT_KIND = "cinema";++/** What an account's project keeps beside its name (account-projects.ts data): the columns of `cinema_projects`. */+interface AccountCinema {+ description: string | null;+ cover: string | null;+ costCapUsd: number | null;+ director: DirectorSettings;+ palettes: CinemaProject["palettes"];+ brief: { title: string; body: string };+ chat: DirectorMessage[];+ pinned: boolean;+}++/** An account's AI Director chat keeps its last messages (a project's data stays well under its size limit). */+const ACCOUNT_CHAT = 50;++const accountRow = (p: AccountProject<AccountCinema>): ProjectRow => ({+ id: p.id,+ name: p.name,+ description: p.data.description ?? null,+ cover_url: p.data.cover ?? null,+ cost_cap_usd: p.data.costCapUsd ?? null,+ director_json: JSON.stringify(p.data.director ?? {}),+ palettes_json: JSON.stringify(p.data.palettes ?? []),+ brief_title: p.data.brief?.title ?? "",+ brief_body: p.data.brief?.body ?? "",+ chat_json: JSON.stringify(p.data.chat ?? []),+ pinned: p.data.pinned ? 1 : 0,+ created_at: p.createdAt,+ updated_at: p.updatedAt,+});++const accountData = (r: ProjectRow): AccountCinema => ({+ 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 },+ chat: parse<DirectorMessage[]>(r.chat_json, []).slice(-ACCOUNT_CHAT),+ pinned: !!r.pinned,+});++/** One project of whoever the work is for: the owner's row, or the account's own project (another's reads as none). */function projectRow(id: string): ProjectRow | undefined {+ const account = tenantAccount();+ if (account) {+ const p = getAccountProject<AccountCinema>(account, ACCOUNT_KIND, id);+ return p ? accountRow(p) : undefined;+ }return db().prepare("SELECT * FROM cinema_projects WHERE id = ?").get(id) as ProjectRow | undefined;}+/** Write an account's project back (its name and data): the account's own only. */+function saveAccountRow(account: string, r: ProjectRow): void {+ if (!updateAccountProject(account, ACCOUNT_KIND, r.id, { name: r.name, data: accountData(r) })) throw new CinemaError("Project not found", 404);+}+export function getProject(id: string): CinemaProject | null {const r = projectRow(id);return r ? toProject(r) : null;@@ -183,28 +247,58 @@ function autoCover(projectId: string): string | null {return video;}+/** The projects of whoever the work is for: the owner's rows, or an account's own projects (pinned first, then newest). */+function projectRows(): ProjectRow[] {+ const account = tenantAccount();+ if (!account) return db().prepare("SELECT * FROM cinema_projects ORDER BY pinned DESC, updated_at DESC").all() as ProjectRow[];+ const rows = listAccountProjects(account, ACCOUNT_KIND).flatMap((x) => {+ const p = getAccountProject<AccountCinema>(account, ACCOUNT_KIND, x.id);+ return p ? [accountRow(p)] : [];+ });+ return rows.sort((a, b) => b.pinned - a.pinned || b.updated_at - a.updated_at);+}+export function listProjects(): CinemaProject[] {- const rows = db().prepare("SELECT * FROM cinema_projects ORDER BY pinned DESC, updated_at DESC").all() as ProjectRow[];- // Counts and spend for every project in two grouped queries (not one per project).+ const rows = projectRows();+ if (!rows.length) return [];+ // Counts and spend for these projects in two grouped queries (not one per project).+ const ids = rows.map((r) => r.id);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`,+ LEFT JOIN generation_trash t ON t.generation_id = g.id WHERE i.project_id IN (${marks(ids.length)}) AND t.deleted_at IS NULL AND ${LISTED} GROUP BY i.project_id`,)- .all() as { p: string; n: number }[]+ .all(...ids) 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)],- ),+ (+ 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 WHERE i.project_id IN (${marks(ids.length)}) GROUP BY i.project_id`)+ .all(...ids) 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 {+ const account = tenantAccount();+ if (account) {+ // An account's own project (account-projects.ts keeps its limit): never a row of the owner's table.+ const data: AccountCinema = {+ description: input.description?.trim().slice(0, 140) || null,+ cover: input.cover ?? null,+ costCapUsd: input.costCapUsd ?? null,+ director: {},+ palettes: [],+ brief: { title: "", body: "" },+ chat: [],+ pinned: false,+ };+ return toProject(accountRow(createAccountProject(account, ACCOUNT_KIND, { name: input.name.trim().slice(0, 80) || "Untitled project", data })));+ }const now = Date.now();const row: ProjectRow = {id: nanoid(10),@@ -253,6 +347,11 @@ export function updateProject(id: string, patch: ProjectPatch): CinemaProject {pinned: patch.pinned === undefined ? Number(cur.pinned) : Number(patch.pinned),updated_at: Date.now(),};+ const account = tenantAccount();+ if (account) {+ saveAccountRow(account, { ...projectRow(id)!, ...next });+ return getProject(id)!;+ }db().prepare(`UPDATE cinema_projects SET name = @name, description = @description, cover_url = @cover_url, cost_cap_usd = @cost_cap_usd,@@ -265,6 +364,16 @@ export function updateProject(id: string, patch: ProjectPatch): CinemaProject {/** Deletes the project and its folders; its generations stay in the library. */export function deleteProject(id: string): void {+ const account = tenantAccount();+ if (account) {+ // Only the account's own project, then its folders and memberships (its runs stay its own).+ if (!deleteAccountProject(account, ACCOUNT_KIND, id)) return;+ db().transaction(() => {+ db().prepare("DELETE FROM cinema_items WHERE project_id = ?").run(id);+ db().prepare("DELETE FROM cinema_folders WHERE project_id = ?").run(id);+ })();+ return;+ }db().transaction(() => {db().prepare("DELETE FROM cinema_items WHERE project_id = ?").run(id);db().prepare("DELETE FROM cinema_folders WHERE project_id = ?").run(id);@@ -273,7 +382,22 @@ export function deleteProject(id: string): void {}function touch(projectId: string): void {- db().prepare("UPDATE cinema_projects SET updated_at = ? WHERE id = ?").run(Date.now(), projectId);+ const account = tenantAccount();+ if (account) updateAccountProject(account, ACCOUNT_KIND, projectId, {});+ else db().prepare("UPDATE cinema_projects SET updated_at = ? WHERE id = ?").run(Date.now(), projectId);+}++/**+ * When an account is deleted (account-sweep.ts purgeAccount, before its projects go): the folders and memberships of+ * its Cinema projects. Its runs are deleted with the account.+ */+export function deleteAccountCinema(accountId: string): void {+ const ids = listAccountProjects(accountId, ACCOUNT_KIND).map((p) => p.id);+ if (!ids.length) return;+ db().transaction(() => {+ db().prepare(`DELETE FROM cinema_items WHERE project_id IN (${marks(ids.length)})`).run(...ids);+ db().prepare(`DELETE FROM cinema_folders WHERE project_id IN (${marks(ids.length)})`).run(...ids);+ })();}// ---------------------------------------------------------------------------@@ -286,19 +410,28 @@ export function getChat(projectId: string): DirectorMessage[] {}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);+ const account = tenantAccount();+ const next = [...getChat(projectId), ...messages].slice(account ? -ACCOUNT_CHAT : -100);+ if (account) saveAccountRow(account, { ...projectRow(projectId)!, chat_json: JSON.stringify(next) });+ else 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);+ const account = tenantAccount();+ if (account) {+ const r = projectRow(projectId);+ if (!r) throw new CinemaError("Project not found", 404);+ saveAccountRow(account, { ...r, chat_json: "[]" });+ } else db().prepare("UPDATE cinema_projects SET chat_json = '[]' WHERE id = ?").run(projectId);}// ---------------------------------------------------------------------------// Folders (scenes)export function listFolders(projectId: string): CinemaFolder[] {+ // Inside an account's work, only its own project's folders.+ if (tenantAccount() && !projectRow(projectId)) return [];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);}@@ -359,6 +492,7 @@ export function createFolder(projectId: string, input: { name: string; parentId?}export function updateFolder(projectId: string, id: string, patch: { name?: string; color?: string | null; pinned?: boolean; parentId?: string | null; position?: number }): CinemaFolder {+ requireProject(projectId);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);@@ -379,6 +513,7 @@ export function updateFolder(projectId: string, id: string, patch: { name?: stri/** Deleting a folder moves its takes and subfolders up to its parent (as Higgsfield does). */export function deleteFolder(projectId: string, id: string): void {+ requireProject(projectId);const cur = folderRow(id);if (!cur || cur.project_id !== projectId) throw new CinemaError("Folder not found", 404);db().transaction(() => {@@ -448,7 +583,9 @@ export function listItems(projectId: string, q: ItemQuery = {}): CinemaGeneratio/** Every Cinema Studio generation, whichever project it's in ("My Generations"), with its project. */export function listStudioGenerations(): CinemaGeneration[] {- const list = listGenerations({ features: ["cinema*"], limit: 200 }).filter((g) => !(g as Generation & { deletedAt?: number | null }).deletedAt);+ // An account's own runs only (the owner's list never holds an account's).+ const account = tenantAccount();+ const list = listGenerations({ features: ["cinema*"], limit: 200, ...(account && { account }) }).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}`)@@ -540,20 +677,37 @@ export function moveItems(projectId: string, generationIds: string[], folderId:* the cap. Only this project's takes are touched.*/export function removeItems(projectId: string, generationIds: string[], opts: { deleteGenerations?: boolean } = {}): number {+ const ids = takeOut(projectId, generationIds, !!opts.deleteGenerations);+ if (ids.length && opts.deleteGenerations) trashGenerations(ids);+ return ids.length;+}++/**+ * Snapshot what each take cost (nothing if it failed) before it goes: taking it out hides it, and+ * the Trash cancels a running take, which would otherwise read as free. Answers the project's takes among `generationIds`.+ */+function takeOut(projectId: string, generationIds: string[], deleting: boolean): string[] {requireProject(projectId);const ids = memberIds(projectId, generationIds);- if (!ids.length) return 0;- // Snapshot what each take cost (nothing if it failed) before it goes: taking it out hides it, and- // the Trash cancels a running take, which would otherwise read as free.+ if (!ids.length) return [];const 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)`;const snapshot = db().prepare(- opts.deleteGenerations+ deleting? `UPDATE cinema_items SET meta_json = json_set(COALESCE(meta_json, '{}'), '$.costLocked', json('true'), '$.cost', ${cost}) WHERE project_id = ? AND generation_id = ?`: `UPDATE cinema_items SET meta_json = json_set(COALESCE(meta_json, '{}'), '$.removed', json('true'), '$.cost', ${cost}) WHERE project_id = ? AND generation_id = ?`,);db().transaction(() => ids.forEach((id) => snapshot.run(projectId, id)))();- if (opts.deleteGenerations) trashGenerations(ids);touch(projectId);+ return ids;+}++/**+ * An account's Delete (it has no Trash): the project's takes among `generationIds` are deleted for good, their files+ * with them, so its space comes back at once. What they cost still counts toward the project's limit.+ */+export async function deleteTakes(projectId: string, generationIds: string[]): Promise<number> {+ const ids = takeOut(projectId, generationIds, true);+ if (ids.length) await deleteForever(ids);return ids.length;}@@ -617,6 +771,22 @@ function redoRequest(s: RedoStep, launched: boolean): { req: GenerationRequest;* 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[] {+ return startRetry(planRetry(projectId, generationId));+}++/** A retry, checked: the steps to make again (dependencies first), each with its request and what it waits for. */+export interface RetryPlan {+ projectId: string;+ order: RedoStep[];+ plans: { s: RedoStep; req: GenerationRequest; deps: string[] }[];+}++/** A retry's steps as an account's run checks them (account-tool-run.ts): each request and how many steps it waits for. */+export const retrySteps = (plan: RetryPlan): { request: GenerationRequest; deps: number }[] => plan.plans.map((p) => ({ request: p.req, deps: p.deps.length }));++/** Plan a retry (see retryItem) and check every step; nothing is made yet. */+export function planRetry(projectId: string, generationId: string): RetryPlan {+ requireProject(projectId);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);@@ -678,7 +848,11 @@ export function retryItem(projectId: string, generationId: string): Generation[]throw new CinemaError((e as Error).message, 422);}}+ return { projectId, order, plans };+}+/** Make a planned retry: the steps in order, wired to the new ids, then the replaced failures go to the Trash. */+export function startRetry({ projectId, order, plans }: RetryPlan): Generation[] {const fresh = new Map<string, string>();const created: Generation[] = [];try {@@ -711,6 +885,20 @@ export function retryItem(projectId: string, generationId: string): Generation[]* 768p latent when its draft kept one (finishIn2k). The 2K take lands beside the first one.*/export function finishTake(projectId: string, generationId: string): Generation[] {+ return startFinish(planFinish(projectId, generationId));+}++/** A 2K finish, checked: the take, its membership row and the request that finishes it. */+export interface FinishPlan {+ projectId: string;+ row: ItemRow;+ g: Generation;+ request: GenerationRequest;+}++/** Plan a 2K finish (see finishTake) and check it, the project's limit included; nothing is made yet. */+export function planFinish(projectId: string, generationId: string): FinishPlan {+ requireProject(projectId);const row = itemRow(projectId, generationId);const g = row ? liveGeneration(generationId) : null;if (!row || !g) throw new CinemaError("That take isn't in this project", 404);@@ -734,9 +922,14 @@ export function finishTake(projectId: string, generationId: string): Generation[throw new CinemaError(`Finishing in 2K (≈ $${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);}}+ return { projectId, row, g, request: finish.request };+}++/** Make a planned 2K finish beside its take. */+export function startFinish({ projectId, row, g, request }: FinishPlan): Generation[] {let made: Generation[];try {- made = createGenerations(finish.request, g.batchId ? { batchId: g.batchId } : {});+ made = createGenerations(request, g.batchId ? { batchId: g.batchId } : {});} catch (e) {if (e instanceof ConnectComfyError) throw e;throw new CinemaError((e as Error).message, 422);@@ -756,6 +949,7 @@ function finishedIn2k(generationId: string): boolean {}export function setTiles(projectId: string, generationId: string, tiles: CinemaTile[]): CinemaItem {+ requireProject(projectId);const r = itemRow(projectId, generationId);if (!r) throw new CinemaError("That take isn't in this project", 404);const meta = { ...parse<ItemMeta>(r.meta_json, {}), tiles: tiles.slice(0, 16) };diff --git a/src/server/records.ts b/src/server/records.tsindex bf61ee84..8ffbca44 100644--- a/src/server/records.ts+++ b/src/server/records.ts@@ -35,7 +35,7 @@ export function recordExists(ref: RecordRef): boolean {}/** Record pages a tool keeps per account (public sign-up): the project kind it keeps them as (account-projects.ts). */-const ACCOUNT_KINDS: Partial<Record<RecordRef["kind"], string>> = { shorts: "shorts" };+const ACCOUNT_KINDS: Partial<Record<RecordRef["kind"], string>> = { shorts: "shorts", cinema: "cinema" };/*** For a signed-in account: whether the record a page names is one of its own, on a page a tool keeps per account (null:diff --git a/src/server/starters.ts b/src/server/starters.tsindex 07e3aaac..b2da5e89 100644--- a/src/server/starters.ts+++ b/src/server/starters.ts@@ -17,7 +17,8 @@ import { createChannel, listChannels, updateChannel } from "./faceless";* fills a composer (Assist, Storyboard, Content Factory, Explainer) or links to one (the Library's) is opened, not made.** Guests get 401 and accounts 403 "library" before this runs (LIBRARY_CHANGES in src/lib/guest-access.ts): a starter- * is saved to the owner's library.+ * is saved to the owner's library. The one exception is a Cinema Studio film for a signed-in account: made inside its+ * own work (asAccount), it is that account's own project (src/server/cinema.ts reads and makes the asker's projects).*/export class StarterError extends Error {diff --git a/tests/account-cinema.test.ts b/tests/account-cinema.test.tsnew file mode 100644index 00000000..9ab835ae--- /dev/null+++ b/tests/account-cinema.test.ts@@ -0,0 +1,528 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++/**+ * Cinema Studio for a signed-in account (public sign-up): its own projects (account-projects.ts, kind "cinema"), its+ * takes on its own ComfyUI (a stand-in here) through the same generations every studio run makes, with only its own+ * files. Another account's project and the owner's projects and files are never reached; a guest gets the sign-up card.+ */+// The routes' reads wait for a request (connection) and the Director keeps its answer going (after): outside Next here.+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {}, after: () => {} }));++const dir = tempDir("fuobe-account-cinema-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+// The studio's own AI helper: recorded, so a test sees that an account's Director never reaches it.+process.env.OLLAMA_URL = "http://owner-llm.test:11434";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+delete process.env.FUOBE_HOSTED_RUNS;+globalThis.__fuobeTestDiskFree = 1e13;++// Plain fetch is the install's own ComfyUI ("owner-comfy.test") or AI helper: recorded, so a test sees that nothing reached them.+const realFetch = globalThis.fetch;+const fetched: string[] = [];+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(String(input instanceof Request ? input.url : input));+ if (url.hostname === "127.0.0.1") return realFetch(input, init);+ fetched.push(url.toString());+ if (url.host !== "owner-comfy.test:8188") return new Response("not stubbed", { status: 599 });+ if (url.pathname === "/system_stats") return Response.json({ system: { comfyui_version: "owner", ram_total: 1 }, devices: [] });+ return Response.json({});+}) as typeof fetch;++const auth = await import("@/server/auth");+const projectsRoute = await import("@/app/api/cinema/projects/route");+const projectRoute = await import("@/app/api/cinema/projects/[id]/route");+const directorRoute = await import("@/app/api/cinema/projects/[id]/director/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 retryRoute = await import("@/app/api/cinema/projects/[id]/items/[generationId]/retry/route");+const finishRoute = await import("@/app/api/cinema/projects/[id]/items/[generationId]/finish/route");+const tilesRoute = await import("@/app/api/cinema/projects/[id]/items/[generationId]/tiles/route");+const startersRoute = await import("@/app/api/starters/[id]/route");+const uploadsRoute = await import("@/app/api/uploads/route");+const gpuRoute = await import("@/app/api/account/gpu/route");+const { proxy } = await import("@/proxy");+const access = await import("@/lib/guest-access");+const cinema = await import("@/server/cinema");+const { cancelGeneration, getGeneration } = await import("@/server/generations");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { clearAccountLoras } = await import("@/server/account-loras");+const { saveFile } = await import("@/server/storage");+const { runAsTenant } = await import("@/server/tenant");+const { ACCOUNT_LIMITS } = await import("@/server/account-files");+const { ACCOUNT_PROJECT_LIMITS, listAccountProjects } = await import("@/server/account-projects");+const { accountRecordExists } = await import("@/server/records");+const { purgeAccount } = await import("@/server/account-sweep");+const { WORLD_MODEL } = await import("@/lib/world");++let fake: FakeComfy;+let a = "";+let b = "";+let c = "";+const cookies: Record<string, string> = {};+beforeAll(async () => {+ fake = await startFakeComfy({ loras: [], delayMs: 0, output: "image" });+ globalThis.__fuobeTestGpuPort = fake.port;+ auth.setPassword("install password");+ for (const [k, email] of [+ ["a", "[email protected]"],+ ["b", "[email protected]"],+ ["c", "[email protected]"],+ ] as const) {+ const id = auth.createAccount(email, "long enough").id;+ cookies[k] = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;+ if (k === "a") a = id;+ if (k === "b") b = id;+ if (k === "c") c = id;+ }+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ // A and B link their own ComfyUI; C has neither a GPU nor a key.+ for (const who of ["a", "b"]) expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: fake.url }, who))).status).toBe(200);+});+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestGpuPort = undefined;+ globalThis.__fuobeTestDiskFree = undefined;+ await fake.close();+});+beforeEach(() => {+ resetRates();+ for (const id of [a, b]) clearAccountLoras(id);+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') IS NOT NULL").run();+});++function json(url: string, method: string, body?: unknown, who?: string): Request {+ const text = body === undefined ? undefined : JSON.stringify(body);+ return new Request(`http://localhost:3000${url}`, {+ method,+ headers: { host: "localhost:3000", "content-type": "application/json", ...(text !== undefined && { "content-length": String(Buffer.byteLength(text)) }), ...(who && { cookie: cookies[who] }) },+ ...(text !== undefined && { body: text }),+ });+}+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) });++const viaProxy = (url: string, method = "GET", who?: string) =>+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }), ...(method !== "GET" && { "content-type": "application/json" }) }, ...(method !== "GET" && { body: "{}" }) }));+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";++async function upload(who: string, data: Buffer, type: string, name: string): Promise<string> {+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": type, "x-file-name": name, "content-length": String(data.length) }, body: new Uint8Array(data) }));+ expect(r.status, await r.clone().text()).toBe(201);+ return ((await r.json()) as { url: string }).url;+}++/** Tick the runner until the row is done (or the time is up). */+async function settle(id: string, ms = 30_000) {+ const end = Date.now() + ms;+ for (;;) {+ await globalThis.__fuobeRunner?.tick();+ const g = getGeneration(id, { includeDeleted: true });+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;+ await new Promise((r) => setTimeout(r, 100));+ }+}++/** Make a project as `who` (through the route), answering its id. */+async function makeProject(who: string, name: string): Promise<string> {+ const r = await projectsRoute.POST(json("/api/cinema/projects", "POST", { name }, who));+ expect(r.status, await r.clone().text()).toBe(201);+ return ((await r.json()) as { id: string }).id;+}++const STILL = {+ engine: "open",+ mode: "image",+ action: "generate",+ prompt: "A detective under a neon sign in the rain, a wide shot",+ batch: 1,+ aspectRatio: "16:9",+ settings: { camera: "modern", lens: "clean-sharp", focal: "35mm" },+};++/** A take; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */+async function take(project: string, input: Record<string, unknown>, who: string, folderId: string | null = null): Promise<Response> {+ const send = () => generateRoute.POST(json(`/api/cinema/projects/${project}/generate`, "POST", { input, folderId }, who), params({ id: project }));+ let r = await send();+ if (r.status === 409) {+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };+ if (j.code === "comfy_missing_model" && j.fix) {+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix.items.map((i) => i.file)];+ for (const id of [a, b]) clearAccountLoras(id);+ r = await send();+ }+ }+ return r;+}++/** The owner's own project, made outside any account's work (as the owner's routes make it). */+const ownerProject = () => cinema.createProject({ name: "The owner's film" });++describe("the proxy opens Cinema Studio to accounts, and keeps the sign-up card for guests", () => {+ it("a guest gets the sign-up card on every change and run; its list is empty and a project is closed", async () => {+ for (const [method, p] of [+ ["POST", "/api/cinema/projects"],+ ["PATCH", "/api/cinema/projects/p1"],+ ["DELETE", "/api/cinema/projects/p1"],+ ["POST", "/api/cinema/projects/p1/director"],+ ["POST", "/api/cinema/projects/p1/folders"],+ ["PATCH", "/api/cinema/projects/p1/items"],+ ["POST", "/api/cinema/projects/p1/generate"],+ ["POST", "/api/cinema/projects/p1/items/g1/retry"],+ ["POST", "/api/cinema/projects/p1/items/g1/finish"],+ ["PUT", "/api/cinema/projects/p1/items/g1/tiles"],+ ["POST", "/api/starters/cinema.desert-couture"],+ ] as const) {+ const r = viaProxy(p, method);+ expect(r.status, `${method} ${p}`).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");+ }+ const list = viaProxy("/api/cinema/projects");+ expect(list.status).toBe(200);+ expect(await list.json()).toEqual({ items: [] });+ expect(viaProxy("/api/cinema/projects/p1").status).toBe(401);+ // The routes answer a guest the same way themselves.+ expect((await projectsRoute.POST(json("/api/cinema/projects", "POST", { name: "x" }))).status).toBe(401);+ expect((await generateRoute.POST(json("/api/cinema/projects/p1/generate", "POST", { input: STILL }), params({ id: "p1" }))).status).toBe(401);+ expect(await (await projectsRoute.GET(json("/api/cinema/projects", "GET"))).json()).toEqual({ items: [] });+ });++ it("an account reaches its project routes; runs need its own GPU or key", async () => {+ for (const [method, p] of [+ ["GET", "/api/cinema/projects"],+ ["POST", "/api/cinema/projects"],+ ["GET", "/api/cinema/projects/p1"],+ ["PATCH", "/api/cinema/projects/p1"],+ ["DELETE", "/api/cinema/projects/p1"],+ ["GET", "/api/cinema/projects/p1/director"],+ ["POST", "/api/cinema/projects/p1/director"],+ ["POST", "/api/cinema/projects/p1/folders"],+ ["PATCH", "/api/cinema/projects/p1/folders/f1"],+ ["GET", "/api/cinema/projects/p1/items"],+ ["DELETE", "/api/cinema/projects/p1/items"],+ ["PUT", "/api/cinema/projects/p1/items/g1/tiles"],+ ["POST", "/api/starters/cinema.desert-couture"],+ ] as const) {+ expect(passed(viaProxy(p, method, "a")), `${method} ${p}`).toBe(true);+ // Without a GPU or a key too: a project needs neither.+ expect(passed(viaProxy(p, method, "c")), `c: ${method} ${p}`).toBe(true);+ }+ for (const p of ["/api/cinema/projects/p1/generate", "/api/cinema/projects/p1/items/g1/retry", "/api/cinema/projects/p1/items/g1/finish"]) {+ expect(passed(viaProxy(p, "POST", "a")), p).toBe(true);+ const r = viaProxy(p, "POST", "c");+ expect(r.status, p).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await r.json()).code).toBe("connect-gpu");+ }+ // Another studio's starter is still the owner's library.+ const other = viaProxy("/api/starters/elements.amara", "POST", "a");+ expect(other.status).toBe(403);+ expect((await other.json()).code).toBe("library");+ // Not a run the route list knows.+ expect(access.ownGpuRun("POST", "/api/cinema/projects/p1/director")).toBe(false);+ expect(access.ownGpuRun("GET", "/api/cinema/projects/p1/generate")).toBe(false);+ });+});++describe("an account's own projects", () => {+ let mine = "";+ it("makes, lists, opens, renames and deletes its own projects", async () => {+ mine = await makeProject("a", "Night Shift");+ const list = (await (await projectsRoute.GET(json("/api/cinema/projects", "GET", undefined, "a"))).json()) as { items: { id: string; name: string }[] };+ expect(list.items.map((p) => p.id)).toEqual([mine]);+ const open = await projectRoute.GET(json(`/api/cinema/projects/${mine}`, "GET", undefined, "a"), params({ id: mine }));+ expect(open.status).toBe(200);+ const view = (await open.json()) as { project: { name: string }; folders: unknown[]; context: { civitai?: boolean; worldcast?: boolean } };+ expect(view.project.name).toBe("Night Shift");+ expect(view.context.civitai).toBe(false);+ expect(view.context.worldcast).toBeUndefined();+ const renamed = await projectRoute.PATCH(json(`/api/cinema/projects/${mine}`, "PATCH", { name: "Night Shift II", brief: { body: "Neo-noir." }, director: { genre: "noir" }, pinned: true }, "a"), params({ id: mine }));+ expect(renamed.status).toBe(200);+ expect(await renamed.json()).toMatchObject({ name: "Night Shift II", brief: { body: "Neo-noir." }, director: { genre: "noir" }, pinned: true });+ // It is the account's own project (account-projects.ts), never a row of the owner's table.+ expect(listAccountProjects(a, "cinema").map((p) => p.id)).toEqual([mine]);+ expect(db().prepare("SELECT 1 FROM cinema_projects WHERE id = ?").get(mine)).toBeUndefined();+ // Its page opens for it alone; an unknown id, or another account's, is a 404 page.+ expect(accountRecordExists({ kind: "cinema", ids: [mine] }, a)).toBe(true);+ expect(accountRecordExists({ kind: "cinema", ids: [mine] }, b)).toBe(false);+ expect(accountRecordExists({ kind: "cinema", ids: ["nope"] }, a)).toBe(false);+ expect(passed(viaProxy(`/cinema/${mine}`, "GET", "a"))).toBe(true);+ expect(viaProxy(`/cinema/${mine}`, "GET", "b").status).toBe(404);+ const gone = await makeProject("a", "Scratch");+ expect((await projectRoute.DELETE(json(`/api/cinema/projects/${gone}`, "DELETE", undefined, "a"), params({ id: gone }))).status).toBe(204);+ expect(listAccountProjects(a, "cinema").map((p) => p.id)).toEqual([mine]);+ });++ it("another account and the owner never see it; it never sees theirs", async () => {+ const theirs = ownerProject();+ // B: not in its list, and every route reads A's project as not found.+ expect(((await (await projectsRoute.GET(json("/api/cinema/projects", "GET", undefined, "b"))).json()) as { items: unknown[] }).items).toEqual([]);+ for (const id of [mine, theirs.id]) {+ expect((await projectRoute.GET(json(`/api/cinema/projects/${id}`, "GET", undefined, "b"), params({ id }))).status, id).toBe(404);+ expect((await projectRoute.PATCH(json(`/api/cinema/projects/${id}`, "PATCH", { name: "Mine now" }, "b"), params({ id }))).status, id).toBe(404);+ expect((await itemsRoute.GET(json(`/api/cinema/projects/${id}/items`, "GET", undefined, "b"), params({ id }))).status, id).toBe(404);+ expect((await itemsRoute.GET(json(`/api/cinema/projects/${id}/items?scope=studio`, "GET", undefined, "b"), params({ id }))).status, id).toBe(404);+ expect((await directorRoute.GET(json(`/api/cinema/projects/${id}/director`, "GET", undefined, "b"), params({ id }))).status, id).toBe(404);+ expect((await foldersRoute.POST(json(`/api/cinema/projects/${id}/folders`, "POST", { name: "Scene 1" }, "b"), params({ id }))).status, id).toBe(404);+ const run = await generateRoute.POST(json(`/api/cinema/projects/${id}/generate`, "POST", { input: STILL }, "b"), params({ id }));+ expect(run.status, id).toBe(404);+ }+ // Deleting another's project does nothing.+ await projectRoute.DELETE(json(`/api/cinema/projects/${mine}`, "DELETE", undefined, "b"), params({ id: mine }));+ await projectRoute.DELETE(json(`/api/cinema/projects/${theirs.id}`, "DELETE", undefined, "a"), params({ id: theirs.id }));+ expect(listAccountProjects(a, "cinema").map((p) => p.id)).toEqual([mine]);+ expect(cinema.getProject(theirs.id)?.name).toBe("The owner's film");+ // A never sees the owner's project; the owner's list never holds A's.+ const aList = (await (await projectsRoute.GET(json("/api/cinema/projects", "GET", undefined, "a"))).json()) as { items: { id: string }[] };+ expect(aList.items.map((p) => p.id)).not.toContain(theirs.id);+ const ownerList = (await (await projectsRoute.GET(json("/api/cinema/projects", "GET", undefined, "owner"))).json()) as { items: { id: string }[] };+ expect(ownerList.items.map((p) => p.id)).toContain(theirs.id);+ expect(ownerList.items.map((p) => p.id)).not.toContain(mine);+ expect((await projectRoute.GET(json(`/api/cinema/projects/${mine}`, "GET", undefined, "owner"), params({ id: mine }))).status).toBe(404);+ });++ it("names only its own files: the owner's file or another's is refused as a cover or a tile", async () => {+ const ownerFile = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "owner.png" }).url;+ const bFile = runAsTenant({ kind: "account", id: b }, () => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "b.png" }).url);+ for (const cover of [ownerFile, bFile]) {+ const r = await projectRoute.PATCH(json(`/api/cinema/projects/${mine}`, "PATCH", { cover }, "a"), params({ id: mine }));+ expect(r.status, cover).toBe(403);+ expect((await r.json()).code).toBe("input-not-yours");+ expect((await projectsRoute.POST(json("/api/cinema/projects", "POST", { name: "x", cover }, "a"))).status, cover).toBe(403);+ }+ const own = await upload("a", TINY_PNG, "image/png", "cover.png");+ expect((await projectRoute.PATCH(json(`/api/cinema/projects/${mine}`, "PATCH", { cover: own }, "a"), params({ id: mine }))).status).toBe(200);+ // An owner's file as a take's start frame: refused before anything is planned or sent.+ fake.log.length = 0;+ const r = await take(mine, { ...STILL, mode: "video", images: [ownerFile] }, "a");+ expect(r.status).toBe(403);+ expect((await r.json()).code).toBe("input-not-yours");+ expect(fake.log.some((e) => e.path === "/prompt")).toBe(false);+ });++ it("keeps its folders: make, rename, delete; another account can't touch them", async () => {+ const r = await foldersRoute.POST(json(`/api/cinema/projects/${mine}/folders`, "POST", { name: "Scene 1" }, "a"), params({ id: mine }));+ expect(r.status).toBe(201);+ const f = (await r.json()) as { id: string };+ expect((await folderRoute.PATCH(json(`/api/cinema/projects/${mine}/folders/${f.id}`, "PATCH", { name: "Rooftop" }, "a"), params({ id: mine, folderId: f.id }))).status).toBe(200);+ expect((await folderRoute.PATCH(json(`/api/cinema/projects/${mine}/folders/${f.id}`, "PATCH", { name: "Taken" }, "b"), params({ id: mine, folderId: f.id }))).status).toBe(404);+ expect((await folderRoute.DELETE(json(`/api/cinema/projects/${mine}/folders/${f.id}`, "DELETE", undefined, "b"), params({ id: mine, folderId: f.id }))).status).toBe(404);+ const view = (await (await projectRoute.GET(json(`/api/cinema/projects/${mine}`, "GET", undefined, "a"), params({ id: mine }))).json()) as { folders: { name: string }[] };+ expect(view.folders.map((x) => x.name)).toEqual(["Rooftop"]);+ expect((await folderRoute.DELETE(json(`/api/cinema/projects/${mine}/folders/${f.id}`, "DELETE", undefined, "a"), params({ id: mine, folderId: f.id }))).status).toBe(204);+ });++ it("its AI Director writes the breakdown without the studio's AI helper, and the chat is its own", async () => {+ fetched.length = 0;+ const r = await directorRoute.POST(json(`/api/cinema/projects/${mine}/director`, "POST", { text: "Generate a 4-shot storyboard for a rooftop chase at night" }, "a"), params({ id: mine }));+ expect(r.status).toBe(200);+ const { messages } = (await r.json()) as { messages: { role: string; source?: string; shots?: unknown[] }[] };+ expect(messages).toHaveLength(2);+ expect(messages[1]).toMatchObject({ role: "assistant", source: "offline" });+ expect(messages[1].shots?.length).toBe(4);+ expect(fetched).toEqual([]);+ const read = (await (await directorRoute.GET(json(`/api/cinema/projects/${mine}/director`, "GET", undefined, "a"), params({ id: mine }))).json()) as { messages: unknown[] };+ expect(read.messages).toHaveLength(2);+ expect((await directorRoute.DELETE(json(`/api/cinema/projects/${mine}/director`, "DELETE", undefined, "b"), params({ id: mine }))).status).toBe(404);+ expect((await directorRoute.DELETE(json(`/api/cinema/projects/${mine}/director`, "DELETE", undefined, "a"), params({ id: mine }))).status).toBe(204);+ });++ it("keeps its limit of projects", async () => {+ const before = listAccountProjects(c, "cinema").length;+ for (let i = before; i < ACCOUNT_PROJECT_LIMITS.projects; i++) runAsTenant({ kind: "account", id: c }, () => cinema.createProject({ name: `P${i}` }));+ const r = await projectsRoute.POST(json("/api/cinema/projects", "POST", { name: "One too many" }, "c"));+ expect(r.status).toBe(409);+ });+});++describe("an account's takes run on its own ComfyUI", () => {+ let project = "";+ let still = "";+ beforeAll(async () => {+ project = await makeProject("a", "Takes");+ });++ it("makes a take end to end: every step is its own, on its ComfyUI, and the result is its own file in its project", async () => {+ fake.log.length = 0;+ fetched.length = 0;+ const r = await take(project, STILL, "a");+ expect(r.status, await r.clone().text()).toBe(201);+ const body = (await r.json()) as { items: { id: string }[]; folderId: string | null };+ expect(body.items.length).toBeGreaterThan(0);+ for (const g of body.items) {+ expect(getGeneration(g.id)!.request.account, g.id).toBe(a);+ expect(getGeneration(g.id)!.provider).toBe("comfyui");+ }+ still = body.items[0].id;+ const done = await settle(still);+ expect(done?.status, done?.error ?? "").toBe("succeeded");+ // It went to its own ComfyUI; nothing reached the install's (the runner's own look at the studio's servers when it+ // starts, /system_stats and /api/tags, carries nothing of the account's).+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBeGreaterThan(0);+ expect(fetched.filter((u) => !u.endsWith("/system_stats") && !u.endsWith("/api/tags"))).toEqual([]);+ const out = done!.outputs[0];+ expect((db().prepare("SELECT account_id FROM assets WHERE id = ?").get(out.assetId) as { account_id: string }).account_id).toBe(a);+ // It shows in its project and its runs, opens and downloads for it alone.+ const items = (await (await itemsRoute.GET(json(`/api/cinema/projects/${project}/items`, "GET", undefined, "a"), params({ id: project }))).json()) as { items: { id: string }[] };+ expect(items.items.map((g) => g.id)).toContain(still);+ const studio = (await (await itemsRoute.GET(json(`/api/cinema/projects/${project}/items?scope=studio`, "GET", undefined, "a"), params({ id: project }))).json()) as { items: { id: string; projectId: string }[] };+ expect(studio.items.find((g) => g.id === still)?.projectId).toBe(project);+ expect(passed(viaProxy(out.url, "GET", "a"))).toBe(true);+ expect(passed(viaProxy(`/api/generations/${still}`, "GET", "a"))).toBe(true);+ expect(viaProxy(out.url, "GET", "b").status).toBe(403);+ expect(viaProxy(`/api/generations/${still}`, "GET", "b").status).toBe(403);+ // The project's card counts it.+ const list = (await (await projectsRoute.GET(json("/api/cinema/projects", "GET", undefined, "a"))).json()) as { items: { id: string; stats: { items: number } }[] };+ expect(list.items.find((p) => p.id === project)?.stats.items).toBeGreaterThan(0);+ // The owner's "My Generations" never lists it.+ expect(cinema.listStudioGenerations().map((g) => g.id)).not.toContain(still);+ });++ it("runs World mode's opening turn on its own ComfyUI", async () => {+ const script = {+ opening: { words: "A small orange fox stands on a stone path in a forest at dusk.", subject: "a small orange fox", move: "zoom_in", seconds: 5 },+ turns: [],+ seed: 1234,+ };+ const r = await take(project, { engine: "open", mode: "video", action: "world", prompt: "", world: { script, turn: 0 } }, "a");+ expect(r.status, await r.clone().text()).toBe(201);+ const body = (await r.json()) as { items: { id: string; modelId: string; op: string }[] };+ expect(body.items).toHaveLength(1);+ expect(body.items[0]).toMatchObject({ modelId: WORLD_MODEL, op: "world-turn" });+ const g = getGeneration(body.items[0].id)!;+ expect(g.request.account).toBe(a);+ expect(g.provider).toBe("comfyui");+ const item = runAsTenant({ kind: "account", id: a }, () => cinema.listItems(project)).find((x) => x.id === g.id);+ expect(item?.take?.action).toBe("world");+ // Outside the account's work (the owner's), its project isn't there.+ expect(() => cinema.listItems(project)).toThrow(/not found/);+ });++ it("builds a 3D scene from its still and films an exact orbit on its own ComfyUI (the 3D step under its own limits)", async () => {+ const pic = await upload("a", TINY_PNG, "image/png", "start.png");+ const scene = await take(project, { engine: "open", mode: "image", action: "scene", prompt: "", source: { url: pic, kind: "image" }, aspectRatio: "16:9" }, "a");+ expect(scene.status, await scene.clone().text()).toBe(201);+ for (const g of ((await scene.json()) as { items: { id: string }[] }).items) {+ expect(getGeneration(g.id)!.request.account).toBe(a);+ expect(getGeneration(g.id)!.provider).toBe("comfyui");+ }+ const orbit = await take(project, { ...STILL, mode: "video", moves: ["drone-orbit"], exact: { degrees: 90, direction: "cw" }, images: [pic], duration: 5 }, "a");+ expect(orbit.status, await orbit.clone().text()).toBe(201);+ const steps = ((await orbit.json()) as { items: { id: string; op: string }[] }).items;+ expect(steps.map((s) => s.op)).toContain("camera-path");+ for (const g of steps) expect(getGeneration(g.id)!.request.account).toBe(a);+ });++ it("retries a canceled take as its own run; another account can't retry it", async () => {+ const r = await take(project, STILL, "a");+ expect(r.status).toBe(201);+ const first = ((await r.json()) as { items: { id: string }[] }).items[0].id;+ await cancelGeneration(first);+ const other = await retryRoute.POST(json(`/api/cinema/projects/${project}/items/${first}/retry`, "POST", undefined, "b"), params({ id: project, generationId: first }));+ expect(other.status).toBe(404);+ const again = await retryRoute.POST(json(`/api/cinema/projects/${project}/items/${first}/retry`, "POST", undefined, "a"), params({ id: project, generationId: first }));+ expect(again.status, await again.clone().text()).toBe(201);+ const items = ((await again.json()) as { items: { id: string }[] }).items;+ expect(items).toHaveLength(1);+ expect(getGeneration(items[0].id)!.request.account).toBe(a);+ const listed = runAsTenant({ kind: "account", id: a }, () => cinema.listItems(project)).map((g) => g.id);+ expect(listed).toContain(items[0].id);+ expect(listed).not.toContain(first);+ });++ it("2K finish: only for its own takes, and only for a MiniMax H3 take", async () => {+ const other = await finishRoute.POST(json(`/api/cinema/projects/${project}/items/${still}/finish`, "POST", { requestId: "fin-1" }, "b"), params({ id: project, generationId: still }));+ expect(other.status).toBe(404);+ const r = await finishRoute.POST(json(`/api/cinema/projects/${project}/items/${still}/finish`, "POST", { requestId: "fin-1" }, "a"), params({ id: project, generationId: still }));+ expect(r.status).toBe(422);+ expect((await r.json()).error).toMatch(/MiniMax H3/);+ });++ it("saves a grid's tiles from its own files only", async () => {+ const own = await upload("a", TINY_PNG, "image/png", "tile.png");+ const ownerFile = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "owner-tile.png" }).url;+ const bad = await tilesRoute.PUT(json(`/api/cinema/projects/${project}/items/${still}/tiles`, "PUT", { tiles: [{ url: ownerFile, row: 0, col: 0 }] }, "a"), params({ id: project, generationId: still }));+ expect(bad.status).toBe(403);+ const good = await tilesRoute.PUT(json(`/api/cinema/projects/${project}/items/${still}/tiles`, "PUT", { tiles: [{ url: own, row: 0, col: 0 }] }, "a"), params({ id: project, generationId: still }));+ expect(good.status).toBe(200);+ const theirs = await tilesRoute.PUT(json(`/api/cinema/projects/${project}/items/${still}/tiles`, "PUT", { tiles: [] }, "b"), params({ id: project, generationId: still }));+ expect(theirs.status).toBe(404);+ });++ it("keeps the account's limits: runs going at once, and a body too big", async () => {+ const now = Date.now();+ const add = db().prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'cinema', 'oss-trim', 'open', 'comfyui', 'trim', 'video', 'queued', ?, '[]', ?, ?)",+ );+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-cinema-${i}`, JSON.stringify({ feature: "cinema", modelId: "oss-trim", account: a }), now, now);+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;+ const r = await take(project, STILL, "a");+ expect(r.status).toBe(429);+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-cinema-%'").run();+ const big = new Request(`http://localhost:3000/api/cinema/projects/${project}/generate`, { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });+ expect((await generateRoute.POST(big, params({ id: project }))).status).toBe(413);+ });++ it("asks an account with neither a GPU nor a key to connect one, before anything is made", async () => {+ // One of its own projects (it keeps as many as it may).+ const own = listAccountProjects(c, "cinema")[0];+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;+ const r = await take(own.id, STILL, "c");+ expect(r.status).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await r.json()).code).toBe("connect-gpu");+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);+ });++ it("its Delete deletes a take for good (no Trash), its own only", async () => {+ const r = await take(project, STILL, "a");+ const id = ((await r.json()) as { items: { id: string }[] }).items[0].id;+ await settle(id);+ const theirs = await itemsRoute.DELETE(json(`/api/cinema/projects/${project}/items`, "DELETE", { ids: [id], deleteGenerations: true }, "b"), params({ id: project }));+ expect(theirs.status).toBe(404);+ const del = await itemsRoute.DELETE(json(`/api/cinema/projects/${project}/items`, "DELETE", { ids: [id], deleteGenerations: true }, "a"), params({ id: project }));+ expect(del.status).toBe(200);+ expect(await del.json()).toEqual({ removed: 1 });+ expect(getGeneration(id, { includeDeleted: true })).toBeNull();+ });+});++describe("a ready film and the account's deletion", () => {+ it("an account makes Cinema's ready film as its own project; the owner's list never shows it", async () => {+ const r = await startersRoute.POST(json("/api/starters/cinema.desert-couture", "POST", { engine: "open" }, "b"), params({ id: "cinema.desert-couture" }));+ expect(r.status, await r.clone().text()).toBe(201);+ const made = (await r.json()) as { href: string; id: string };+ expect(made.href).toBe(`/cinema/${made.id}?shot=1`);+ expect(listAccountProjects(b, "cinema").map((p) => p.id)).toContain(made.id);+ expect(cinema.listProjects().map((p) => p.id)).not.toContain(made.id);+ // Its proposed shots are in its own Director chat.+ const chat = (await (await directorRoute.GET(json(`/api/cinema/projects/${made.id}/director`, "GET", undefined, "b"), params({ id: made.id }))).json()) as { messages: { shots?: unknown[] }[] };+ expect(chat.messages.some((m) => m.shots?.length)).toBe(true);+ // Made again before anything is made in it: the same project.+ const again = await startersRoute.POST(json("/api/starters/cinema.desert-couture", "POST", { engine: "open" }, "b"), params({ id: "cinema.desert-couture" }));+ expect(((await again.json()) as { id: string }).id).toBe(made.id);+ // Another studio's starter stays the owner's library.+ const other = await startersRoute.POST(json("/api/starters/elements.amara", "POST", { engine: "open" }, "b"), params({ id: "elements.amara" }));+ expect(other.status).toBe(403);+ // A guest signs up first.+ expect((await startersRoute.POST(json("/api/starters/cinema.desert-couture", "POST", { engine: "open" }), params({ id: "cinema.desert-couture" }))).status).toBe(401);+ });++ it("deleting the account deletes its projects, their folders and takes' rows", async () => {+ const p = runAsTenant({ kind: "account", id: b }, () => cinema.createProject({ name: "Gone soon" }));+ runAsTenant({ kind: "account", id: b }, () => cinema.createFolder(p.id, { name: "Scene" }));+ expect((db().prepare("SELECT COUNT(*) AS n FROM cinema_folders WHERE project_id = ?").get(p.id) as { n: number }).n).toBe(1);+ await purgeAccount(b);+ expect(listAccountProjects(b, "cinema")).toEqual([]);+ expect((db().prepare("SELECT COUNT(*) AS n FROM cinema_folders WHERE project_id = ?").get(p.id) as { n: number }).n).toBe(0);+ });+});diff --git a/tests/e2e/cinema-accounts-live.mjs b/tests/e2e/cinema-accounts-live.mjsnew file mode 100644index 00000000..bbb39b8a--- /dev/null+++ b/tests/e2e/cinema-accounts-live.mjs@@ -0,0 +1,112 @@+// Cinema Studio for visitors, in a browser (a studio with a password and public sign-up, fuobe.com by default): a guest+// sees no "Projects aren't available here" note, and New project and a ready film's Use template open the sign-up card. A+// signed-in account (a throwaway one this script makes and deletes) makes its own project, opens it, asks the AI+// Director (its breakdown, with no note about Settings), and its Generate opens the connect card (it has no GPU or key):+// no refusal after a click. Its project is deleted with the account.+// Usage: node tests/e2e/cinema-accounts-live.mjs [appUrl] [--shots <dir>] Exits 1 on a failed check.+import fs from "node:fs";+import path from "node:path";+import crypto from "node:crypto";+import { launch } from "./_browser.mjs";++const argv = process.argv.slice(2);+const flag = (k) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : undefined);+const app = (argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--shots") ?? "https://fuobe.com").replace(/\/$/, "");+const shots = flag("--shots");+if (shots) fs.mkdirSync(shots, { recursive: true });++const failures = [];+const check = (label, ok, extra = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(72)}${extra ? ` ${extra}` : ""}`);+ if (!ok) failures.push(label);+};+const NOTE = /aren.t available here/;+const SIGN_UP = /Create a free account/;++const browser = await launch();+const email = `cinema-ui-${crypto.randomBytes(5).toString("hex")}@example.com`;+const password = crypto.randomBytes(18).toString("base64url");+let signedUp = false;+const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });+const shot = async (page, name) => shots && (await page.screenshot({ path: path.join(shots, `cinema-${name}.png`), fullPage: false }));+try {+ const page = await context.newPage();+ // A guest: the list, New project, a ready film's page.+ await page.goto(`${app}/cinema`, { waitUntil: "load", timeout: 60_000 });+ await page.waitForTimeout(3000);+ check("guest: no \"isn't available here\" note on /cinema", (await page.getByText(NOTE).count()) === 0);+ const newProject = page.getByRole("button", { name: "New project" }).first();+ check("guest: New project is offered", await newProject.isVisible());+ await newProject.click();+ await page.waitForTimeout(1500);+ check("guest: New project opens the sign-up card", (await page.getByText(SIGN_UP).count()) > 0);+ await shot(page, "guest-signup");+ await page.keyboard.press("Escape");+ await page.goto(`${app}/cinema/start/cinema.desert-couture`, { waitUntil: "load", timeout: 60_000 });+ await page.waitForTimeout(2500);+ check("guest: a ready film's page has no \"isn't available here\" note", (await page.getByText(NOTE).count()) === 0);+ // A ready film without its cover yet is the owner's only (its page says it isn't here): nothing more to check then.+ const shown = (await page.getByText("This starter isn't here.").count()) === 0;+ const use = page.getByRole("button", { name: /Use template/ }).first();+ if (shown) check("guest: a ready film offers Use template", (await use.count()) > 0 && (await use.isVisible()));+ else console.log(" (the ready film has no cover yet: the owner's only)");+ if (shown && (await use.count())) {+ await use.click();+ await page.waitForTimeout(2000);+ check("guest: Use template opens the sign-up card", (await page.getByText(SIGN_UP).count()) > 0);+ await page.keyboard.press("Escape");+ }++ // A throwaway account (signed in in this browser).+ const res = await page.request.post(`${app}/api/auth/signup`, { data: { email, password }, headers: { origin: app } });+ signedUp = res.ok();+ check("signed up a throwaway account", signedUp, String(res.status()));+ await page.goto(`${app}/cinema`, { waitUntil: "load", timeout: 60_000 });+ await page.waitForTimeout(3000);+ check("account: no \"isn't available here\" note on /cinema", (await page.getByText(NOTE).count()) === 0);+ await page.getByRole("button", { name: "New project" }).first().click();+ await page.getByPlaceholder("e.g. “Night Shift”").fill("Live check film");+ await page.getByRole("button", { name: "Create project" }).click();+ await page.waitForURL(/\/cinema\/[A-Za-z0-9_-]+/, { timeout: 30_000 }).catch(() => {});+ await page.waitForTimeout(3000);+ const id = /\/cinema\/([A-Za-z0-9_-]+)/.exec(new URL(page.url()).pathname)?.[1];+ check("account: New project opens its own project", !!id && (await page.getByRole("heading", { name: "Live check film" }).count()) > 0, page.url());+ check("account: no sharing or elements of the owner's library", (await page.getByLabel("Share a read-only link").count()) === 0 && (await page.getByText("My Elements").count()) === 0);+ await shot(page, "account-workspace");++ // The AI Director: a breakdown, and nothing about the studio's Settings.+ await page.getByRole("button", { name: "AI Director" }).first().click();+ await page.getByPlaceholder("Ask AI Director anything, or paste a script").fill("Generate a 4-shot storyboard for a rooftop chase at night");+ await page.getByRole("button", { name: "Send" }).click();+ await page.waitForTimeout(4000);+ check("account: the AI Director answers with shots", (await page.getByRole("button", { name: "Load into prompt bar" }).count()) >= 4);+ check("account: no note about connecting an AI helper", (await page.getByText(/connect Claude or a local model/).count()) === 0);+ await shot(page, "account-director");+ await page.getByRole("button", { name: "Load into prompt bar" }).first().click();+ await page.waitForTimeout(1000);++ // Generate with neither a GPU nor a key: the connect card, not a refusal.+ const generate = page.getByRole("button", { name: /^Generate/ }).last();+ if (await generate.isEnabled().catch(() => false)) {+ await generate.click();+ await page.waitForTimeout(3000);+ check("account: Generate opens the connect card", (await page.getByText(/Connect your GPU/).count()) > 0);+ check("account: no \"isn't available here\" after Generate", (await page.getByText(NOTE).count()) === 0);+ await shot(page, "account-generate");+ await page.keyboard.press("Escape");+ } else check("account: Generate is on once a shot is loaded", false);++ // Its list shows it; the API answers its own project.+ const list = await page.request.get(`${app}/api/cinema/projects`);+ const items = list.ok() ? (await list.json()).items : [];+ check("account: its list has its project", items.some((p) => p.id === id), String(list.status()));+} finally {+ if (signedUp) {+ const page = context.pages()[0];+ const del = await page.request.delete(`${app}/api/auth/me`, { data: { password }, headers: { origin: app } });+ console.log(`deleted the throwaway account: ${del.status()}`);+ }+ await browser.close();+}+console.log(failures.length ? `${failures.length} failed` : "all ok");+process.exit(failures.length ? 1 : 0);diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.tsindex 99ca6ec1..b51ad8a9 100644--- a/tests/public-signup-tools.test.ts+++ b/tests/public-signup-tools.test.ts@@ -146,13 +146,15 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {const cookie = auth.createSession(a.id).value;auth.setAccountGpu(a.id, { url: "https://gpu.example" });expect(passed(proxy(req("/api/generations", { method: "POST", cookie })))).toBe(true);- for (const p of ["/api/turnaround", "/api/audio-tools", "/api/cinema/projects/p1/generate", "/api/layout/plan"]) {+ for (const p of ["/api/turnaround", "/api/audio-tools", "/api/layout/plan"]) {const r = proxy(req(p, { method: "POST", cookie }));expect(r.status, p).toBe(403);expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();expect((await r.json()).code, p).toBe("own-gpu-tool");}expect(passed(proxy(req("/api/audio-tools/export?offset=0", { method: "POST", cookie })))).toBe(true);+ // Cinema Studio's takes run on its own GPU too (tests/account-cinema.test.ts).+ expect(passed(proxy(req("/api/cinema/projects/p1/generate", { method: "POST", cookie })))).toBe(true);});it("keeps the owner's runs and saves unchanged", () => {diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.tsindex 1fb9de90..6aebc4e8 100644--- a/tests/public-signup.test.ts+++ b/tests/public-signup.test.ts@@ -219,7 +219,6 @@ describe("accounts never run on the owner's keys or GPU", () => {// Everything else wouldn't run on it even once connected: said first, with no Connect your GPU card.for (const p of ["/api/canvases/c1/run",- "/api/cinema/projects/p1/generate","/api/layers/l1/jobs","/api/katana/k1/retry","/api/enhance",@@ -227,7 +226,6 @@ describe("accounts never run on the owner's keys or GPU", () => {"/api/faceless/episodes/e1/render","/api/content-factory/claude",// A run route that ignores ?preview=1 isn't a price check.- "/api/cinema/projects/p1/generate?preview=1","/api/faceless/episodes/e1/estimate",// Restore & colourise: its run and its prompt writer."/api/restore",@@ -237,16 +235,23 @@ describe("accounts never run on the owner's keys or GPU", () => {"/api/remove-object/reroll",// Plan layout plans with the studio's own AI helper."/api/layout/plan",- // Regenerate in Faceless, Shorts segments and Cinema takes (n7-10): studio jobs, like their renders.+ // Regenerate in Faceless and Shorts segments (n7-10): studio jobs, like their renders."/api/faceless/episodes/e1/regenerate","/api/shorts/sessions/s1/segments/0/enhance",- "/api/cinema/projects/p1/items/g1/finish",]) {const r = proxy(req(p, { method: "POST", cookie }));expect(r.status, p).toBe(403);expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();expect((await r.json()).code, p).toBe("own-gpu-tool");}+ // Cinema Studio's takes run on its own GPU or key (tests/account-cinema.test.ts): with neither, connect one first. A+ // run route that ignores ?preview=1 isn't a price check.+ for (const p of ["/api/cinema/projects/p1/generate", "/api/cinema/projects/p1/generate?preview=1", "/api/cinema/projects/p1/items/g1/finish"]) {+ const r = proxy(req(p, { method: "POST", cookie }));+ expect(r.status, p).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBe("1");+ expect((await r.json()).code, p).toBe("connect-gpu");+ }// Owner-only routes say so (not "connect your GPU").expect(proxy(req("/api/mcp", { method: "POST", cookie })).headers.get(access.CONNECT_GPU_HEADER)).toBeNull();// Price checks and signing out are fine.@@ -279,7 +284,8 @@ describe("accounts never see or change the owner's library", () => {layers: { lists: ["/api/layers"], records: ["/api/layers/l1"], changes: [["POST", "/api/layers"], ["PATCH", "/api/layers/l1"], ["DELETE", "/api/layers/l1"], ["POST", "/api/layers/l1/versions"]] },elements: { lists: ["/api/elements"], records: ["/api/elements/e1"], changes: [["POST", "/api/elements"], ["PATCH", "/api/elements/e1"], ["DELETE", "/api/elements/e1"]] },canvases: { lists: ["/api/canvases"], records: ["/api/canvases/c1"], changes: [["POST", "/api/canvases"], ["PATCH", "/api/canvases/c1"], ["DELETE", "/api/canvases/c1"], ["POST", "/api/canvases/c1/duplicate"]] },- cinema: { lists: ["/api/cinema/projects"], records: ["/api/cinema/projects/p1", "/api/cinema/projects/p1/items"], changes: [["POST", "/api/cinema/projects"], ["PATCH", "/api/cinema/projects/p1"], ["DELETE", "/api/cinema/projects/p1"]] },+ // (Cinema Studio's projects go to the routes, which answer an account with its own projects only:+ // tests/account-cinema.test.ts.)storyboards: { lists: [], records: ["/api/storyboards"], changes: [["POST", "/api/storyboards"]] },assist: {lists: ["/api/assist/projects", "/api/assist/memory"],diff --git a/tests/regenerate-held.test.ts b/tests/regenerate-held.test.tsindex 97e88740..f3595336 100644--- a/tests/regenerate-held.test.ts+++ b/tests/regenerate-held.test.ts@@ -190,7 +190,9 @@ describe("Open-H3 Regenerate while it is held", () => {expect(await settle(g.id)).toMatchObject({ status: "succeeded" });// Offered by the catalog as a free redraw on your GPU, refused while it is held.expect(R.finishIn2k(gens.getGeneration(g.id)!, "both")?.perSecond).toBeNull();- await refused(() => finishRoute.POST(json("POST"), params({ id: project.id, generationId: g.id })), R.REGEN_COPY.heldFinish);+ // The owner's take (the route answers anyone else with their own projects only).+ const asOwner = new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json", cookie: owner } });+ await refused(() => finishRoute.POST(asOwner, params({ id: project.id, generationId: g.id })), R.REGEN_COPY.heldFinish);expect(cinema.listItems(project.id).map((x) => x.id)).toEqual([g.id]);});});