Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Shorts Studio: accounts make shorts on their own GPU or key

Adarsh2f67c6499033
diff --git a/docs/public-signup.md b/docs/public-signup.md
index ab7e3415..12206d8b 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -32,7 +32,7 @@ it (files, uploads, projects, settings values, tokens) answer 401 "Sign up to se
Every change a guest sends (generate, upload, save a setting, create a project…) answers 401. The
studio shows a "Create a free account to run this" card with **Sign up** and **Log in**. Where
signing up wouldn't help, a guest gets an account's answer instead: 403 `assist-owner` for Assist,
-and 403 `own-gpu-tool` for a tool an account's own GPU or key doesn't run (Shorts, Katana,
+and 403 `own-gpu-tool` for a tool an account's own GPU or key doesn't run (Katana,
Marketing…). The pages of those tools say so up front and turn off their upload and Generate.
What is drawn in the browser itself is open to try: Click to Ad's animated end card and Marketing
Studio's code-drawn templates (Kinetic Motion) take a guest's words and play live (a code-drawn
@@ -263,7 +263,7 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
uploads, outputs and cancels go there, and nothing falls back to the studio's own providers. If
the account's ComfyUI can't be reached, the run fails and says so. A cloud model, an AI helper or
the studio's local LLM is refused; "Enhance prompt" uses Fuobe's offline wording. Other tools
- (Canvas, Cinema, Shorts, Assist, Marketing…) answer 403 with `code: "own-gpu-tool"`, because they
+ (Canvas, Cinema, Assist, Marketing…) answer 403 with `code: "own-gpu-tool"`, because they
plan with the studio's own AI helpers or keep projects of their own. A 3D model sent here answers the
same: Image to 3D has its own route (below). So do the Audio hub's Split
soundtrack and Edit speech and Video tools → Remove dialogue (all `POST /api/audio-tools`) and the
@@ -323,6 +323,15 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
its limits: a take that waits for the one before it starts later in the same run. The pictures a project names (the
character, an imported anchor) and its clips are the account's own. Its assembled clips are its own runs, to open and
download. The checks are `src/server/swap-studio-account.ts`.
+- **Shorts Studio.** An account makes its own shorts the same way (`POST /api/shorts/sessions`), on its own ComfyUI or
+ on its own fal.ai or Replicate key on the cloud engine: each segment's cut, restyle and the stitch under the clip's
+ sound are runs of its own, with only its own files, and a short counts once against its limits. A new take of a
+ segment (`POST /api/shorts/sessions/<id>/segments/<n>`) and Stitch again (`.../stitch`) go through the same checks.
+ Its shorts and the presets it makes from its own pictures are its own projects (`src/server/account-projects.ts`):
+ its History, a short's page (`/shorts/<id>`) and its preset list show only its own, and another account's or the
+ owner's read as not found (404). It keeps up to 50 shorts. Deleting a short deletes its runs for good (an account
+ has 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.
- **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)/shorts/[id]/page.tsx b/src/app/(studio)/shorts/[id]/page.tsx
index 30c9263f..a13b0e07 100644
--- a/src/app/(studio)/shorts/[id]/page.tsx
+++ b/src/app/(studio)/shorts/[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 { ShortsSessionView } from "@/components/shorts/session-view";
-import { recordExists } from "@/server/records";
+import { recordFor } from "@/server/records";
export const metadata: Metadata = { title: "Your short" };
async function Session({ params }: { params: PageProps<"/shorts/[id]">["params"] }) {
const { id } = await params;
- if (!recordExists({ kind: "shorts", ids: [id] })) notFound();
+ // The owner's sessions, or a signed-in account's own.
+ if (!recordFor({ kind: "shorts", ids: [id] }, await headers())) notFound();
return <ShortsSessionView id={id} />;
}
diff --git a/src/app/api/shorts/estimate/route.ts b/src/app/api/shorts/estimate/route.ts
index cce7d0ad..66da9eb2 100644
--- a/src/app/api/shorts/estimate/route.ts
+++ b/src/app/api/shorts/estimate/route.ts
@@ -1,16 +1,17 @@
+import { priceAsRun } from "@/server/account-tool-run";
import { estimateShorts } from "@/server/shorts";
import { ShortsEstimateSchema, body, handle } from "@/server/shorts-schemas";
-import { priceAs } from "@/server/visitor";
-/** What a session would cost (or that it runs as a demo), how many segments it makes, and notes. */
-async function post(request: Request) {
- return handle(async () => {
- const input = await body(request, ShortsEstimateSchema, "Pick a preset and the part of the clip to restyle");
- return Response.json(await estimateShorts(input));
- });
-}
-
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/**
+ * What a session would cost (or that it runs as a demo), how many segments it makes, and notes. A visitor (public
+ * sign-up) gets the price of its run as it would go: an account's on its own GPU or its own key (with its own presets),
+ * a guest's on the open engine; never a demo (src/server/account-tool-run.ts priceAsRun).
+ */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ return priceAsRun(request, () =>
+ handle(async () => {
+ const input = await body(request, ShortsEstimateSchema, "Pick a preset and the part of the clip to restyle");
+ return Response.json(await estimateShorts(input));
+ }),
+ );
}
diff --git a/src/app/api/shorts/presets/[id]/route.ts b/src/app/api/shorts/presets/[id]/route.ts
index 4ffe43c8..c17a4086 100644
--- a/src/app/api/shorts/presets/[id]/route.ts
+++ b/src/app/api/shorts/presets/[id]/route.ts
@@ -1,18 +1,29 @@
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, bodyTooBig, guestRun, toolViewer } from "@/server/account-tool-run";
import { deleteCustomPreset, ShortsError, updateCustomPreset } from "@/server/shorts";
import { PresetPatchSchema, body, handle } from "@/server/shorts-schemas";
+/** Change one of the viewer's own presets (an account's: its own only; another's reads as gone). */
export async function PATCH(request: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const refused = bodyTooBig(request) ?? projectSavesLimited(viewer.account.id);
+ if (refused) return refused;
+ }
return handle(async () => {
const { id } = await ctx.params;
const patch = await body(request, PresetPatchSchema, "Those preset settings aren't valid");
- return Response.json(updateCustomPreset(id, patch));
+ return Response.json(asViewer(viewer, () => updateCustomPreset(id, patch)));
}, request);
}
export async function DELETE(request: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id } = await ctx.params;
- if (!deleteCustomPreset(id)) throw new ShortsError("This preset no longer exists", 404);
+ if (!asViewer(viewer, () => deleteCustomPreset(id))) throw new ShortsError("This preset no longer exists", 404);
return new Response(null, { status: 204 });
}, request);
}
diff --git a/src/app/api/shorts/presets/route.ts b/src/app/api/shorts/presets/route.ts
index 1f4049d7..58cc1664 100644
--- a/src/app/api/shorts/presets/route.ts
+++ b/src/app/api/shorts/presets/route.ts
@@ -1,17 +1,26 @@
import { connection } from "next/server";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, bodyTooBig, guestRun, toolViewer } from "@/server/account-tool-run";
import { createCustomPreset, listCustomPresets } from "@/server/shorts";
import { PresetBodySchema, body, handle } from "@/server/shorts-schemas";
-/** The user's own presets ("Created by you"). */
-export async function GET() {
+/** The viewer's own presets ("Created by you"): the owner's, or a signed-in account's own (a guest has none). */
+export async function GET(request: Request) {
await connection();
- return handle(() => Response.json({ items: listCustomPresets() }));
+ const viewer = toolViewer(request);
+ return handle(() => Response.json({ items: asViewer(viewer, () => listCustomPresets()) }));
}
-/** Create a preset from up to 10 reference images. */
+/** Create a preset from up to 10 reference images (an account's: its own pictures only). */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const refused = bodyTooBig(request) ?? projectSavesLimited(viewer.account.id);
+ if (refused) return refused;
+ }
return handle(async () => {
const input = await body(request, PresetBodySchema, "Add 1–10 reference images");
- return Response.json(createCustomPreset(input), { status: 201 });
+ return Response.json(asViewer(viewer, () => createCustomPreset(input)), { status: 201 });
}, request);
}
diff --git a/src/app/api/shorts/sessions/[id]/route.ts b/src/app/api/shorts/sessions/[id]/route.ts
index 65f04bc3..8e88c978 100644
--- a/src/app/api/shorts/sessions/[id]/route.ts
+++ b/src/app/api/shorts/sessions/[id]/route.ts
@@ -1,31 +1,49 @@
import { connection } from "next/server";
import { z } from "zod";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, guestRun, toolViewer } from "@/server/account-tool-run";
import { deleteSession, getSession, regenerateCost, renameSession } from "@/server/shorts";
import { body, handle } from "@/server/shorts-schemas";
-/** The session with its generations (segments, takes, stitches) and what one more take costs. */
-export async function GET(_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {
+/**
+ * The session with its generations (segments, takes, stitches) and what one more take costs. An account opens its own
+ * sessions only (another's, or the owner's, reads as gone); a guest has none.
+ */
+export async function GET(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {
await connection();
+ const viewer = toolViewer(request);
return handle(async () => {
const { id } = await ctx.params;
- const s = getSession(id);
- return Response.json({ ...s, regenerateUsd: regenerateCost(s) });
+ return Response.json(
+ asViewer(viewer, () => {
+ const s = getSession(id);
+ return { ...s, regenerateUsd: regenerateCost(s) };
+ }),
+ );
});
}
export async function PATCH(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const limited = projectSavesLimited(viewer.account.id);
+ if (limited) return limited;
+ }
return handle(async () => {
const { id } = await ctx.params;
const { title } = await body(request, z.object({ title: z.string().trim().min(1).max(120) }), "Give the short a name");
- return Response.json(renameSession(id, title));
+ return Response.json(asViewer(viewer, () => renameSession(id, title)));
}, request);
}
-/** Delete the session; its videos move to the Trash unless ?keep=1. */
+/** Delete the session; its videos move to the Trash unless ?keep=1 (an account has no Trash: its own go for good). */
export async function DELETE(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const { id } = await ctx.params;
const keep = new URL(request.url).searchParams.get("keep") === "1";
- return Response.json({ trashed: deleteSession(id, { keep }) });
+ return Response.json({ trashed: await asViewer(viewer, () => deleteSession(id, { keep })) });
}, request);
}
diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/enhance/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/enhance/route.ts
index f1669392..51932386 100644
--- a/src/app/api/shorts/sessions/[id]/segments/[index]/enhance/route.ts
+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/enhance/route.ts
@@ -1,8 +1,13 @@
+import { ownGpuTool, toolViewer } from "@/server/account-tool-run";
import { enhanceSegment, ShortsError } from "@/server/shorts";
import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";
-/** Enhance (H3 regenerate): a 1080p take of this segment, redrawn on your GPU (a repeated requestId gets the first answer). */
+/**
+ * Enhance (H3 regenerate): a 1080p take of this segment, redrawn on your GPU (a repeated requestId gets the first answer).
+ * The owner's only: it isn't offered on an account's own GPU yet.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]/enhance">) {
+ if (toolViewer(request).kind !== "owner") return ownGpuTool();
return handle(async () => {
const { id, index } = await ctx.params;
const i = Number(index);
diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts
index d0561f2e..271b45c7 100644
--- a/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts
+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts
@@ -1,14 +1,22 @@
import { z } from "zod";
+import { projectSavesLimited } from "@/server/account-projects";
+import { asViewer, guestRun, toolViewer } from "@/server/account-tool-run";
import { makePrimary, ShortsError } from "@/server/shorts";
import { body, handle } from "@/server/shorts-schemas";
-/** Make a take the one the stitch uses. */
+/** Make a take the one the stitch uses (an account's own session only). */
export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]/primary">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const limited = projectSavesLimited(viewer.account.id);
+ if (limited) return limited;
+ }
return handle(async () => {
const { id, index } = await ctx.params;
const i = Number(index);
if (!Number.isInteger(i) || i < 0) throw new ShortsError("No such segment", 404);
const { generationId } = await body(request, z.object({ generationId: z.string().min(1).max(40) }), "Pick a take");
- return Response.json(makePrimary(id, i, generationId));
+ return Response.json(asViewer(viewer, () => makePrimary(id, i, generationId)));
}, request);
}
diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts
index 48f14cc7..547ed53b 100644
--- a/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts
+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts
@@ -1,13 +1,39 @@
-import { regenerateSegment, ShortsError } from "@/server/shorts";
+import { asViewer, bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { planTakeRun, regenerateSegment, sessionFiles, shortsSteps, ShortsError, startTake, type TakeRun } from "@/server/shorts";
import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";
-/** Regenerate: one more take of this segment (a repeated requestId gets the first answer, not a second take). */
+/**
+ * Regenerate: one more take of this segment (a repeated requestId gets the first answer, not a second take). An
+ * account's take runs on its own GPU or key, for its own session only (src/server/account-tool-run.ts).
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]">) {
+ 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, index } = await ctx.params;
const i = Number(index);
if (!Number.isInteger(i) || i < 0) throw new ShortsError("No such segment", 404);
const { requestId } = await optionalBody(request, NonceSchema);
- return Response.json(await once(`shorts-take:${id}:${i}`, requestId, () => regenerateSegment(id, i)), { status: 201 });
+ if (viewer.kind === "owner") return Response.json(await once(`shorts-take:${id}:${i}`, requestId, () => regenerateSegment(id, i)), { status: 201 });
+ // Its own session only (another's reads as gone), and the files its runs take.
+ const files = asViewer(viewer, () => sessionFiles(id));
+ let run: TakeRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ `shorts-take:${id}:${i}`,
+ requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "shorts",
+ files,
+ plan: () => shortsSteps((run = planTakeRun(id, i)).steps),
+ start: () => startTake(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/shorts/sessions/[id]/stitch/route.ts b/src/app/api/shorts/sessions/[id]/stitch/route.ts
index e50cb4ef..ff0ee71b 100644
--- a/src/app/api/shorts/sessions/[id]/stitch/route.ts
+++ b/src/app/api/shorts/sessions/[id]/stitch/route.ts
@@ -1,11 +1,40 @@
-import { stitchSession } from "@/server/shorts";
+import { asViewer, bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { planStitchRun, sessionFiles, shortsSteps, startStitch, stitchSession, type StitchRun } from "@/server/shorts";
import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";
-/** Stitch again: join the chosen takes and put the original sound back (a repeated requestId gets the first answer). */
+/**
+ * Stitch again: join the chosen takes and put the original sound back (a repeated requestId gets the first answer). An
+ * account's stitch runs on its own GPU or key, for its own session only (src/server/account-tool-run.ts).
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/stitch">) {
+ 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 { requestId } = await optionalBody(request, NonceSchema);
- return Response.json(await once(`shorts-stitch:${id}`, requestId, () => stitchSession(id)), { status: 201 });
+ if (viewer.kind === "owner") return Response.json(await once(`shorts-stitch:${id}`, requestId, () => stitchSession(id)), { status: 201 });
+ // Its own session only (another's reads as gone), and the files its runs take.
+ const files = asViewer(viewer, () => sessionFiles(id));
+ // One silent segment: its take is the short, and nothing runs.
+ const first = asViewer(viewer, () => planStitchRun(id));
+ if (!first.steps.length) return Response.json(asViewer(viewer, () => startStitch(first)), { status: 201 });
+ let run: StitchRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ `shorts-stitch:${id}`,
+ requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "shorts",
+ files: [...files, ...first.files],
+ plan: () => shortsSteps((run = planStitchRun(id)).steps),
+ start: () => startStitch(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/shorts/sessions/route.ts b/src/app/api/shorts/sessions/route.ts
index 3138dbfc..7d7d6c2a 100644
--- a/src/app/api/shorts/sessions/route.ts
+++ b/src/app/api/shorts/sessions/route.ts
@@ -1,18 +1,45 @@
import { connection } from "next/server";
-import { createSession, listSessions } from "@/server/shorts";
+import { asViewer, bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createSession, listSessions, planSessionRun, shortsSteps, startSession, type SessionRun } from "@/server/shorts";
import { ShortsBodySchema, body, handle, once } from "@/server/shorts-schemas";
-/** Shorts sessions, newest first (History). */
-export async function GET() {
+/** Shorts sessions, newest first (History): the owner's, or a signed-in account's own (a guest has none). */
+export async function GET(request: Request) {
await connection();
- return handle(() => Response.json({ items: listSessions() }));
+ const viewer = toolViewer(request);
+ return handle(() => Response.json({ items: asViewer(viewer, () => listSessions()) }));
}
-/** Start a session: cut the clip into segments, restyle each, stitch them under the original sound. */
+/**
+ * Start a session: cut the clip into segments, restyle each, stitch them under the original sound. The owner's as
+ * always; an account's 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) {
+ 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 input = await body(request, ShortsBodySchema, "Pick a preset, upload a clip and choose the part to restyle");
// A repeated requestId (a second click on Generate) gets the session the first one started.
- return Response.json(await once("shorts-session", input.requestId, () => createSession(input)), { status: 201 });
+ if (viewer.kind === "owner") return Response.json(await once("shorts-session", input.requestId, () => createSession(input)), { status: 201 });
+ let run: SessionRun | null = null;
+ // An account's repeat gets its own first session, never another's.
+ return onceForAccount(
+ viewer.account,
+ "shorts-session",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "shorts",
+ files: [input.source.url],
+ plan: async () => shortsSteps((run = await planSessionRun(input)).plan.steps),
+ start: () => startSession(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.ts
index 07e30b02..b77d17cb 100644
--- a/src/components/shorts/hooks.ts
+++ b/src/components/shorts/hooks.ts
@@ -6,11 +6,17 @@ import { nanoid } from "nanoid";
import { useCallback, useDeferredValue, useRef } from "react";
import type { ShortsCustomPreset, ShortsRange, ShortsRatio, ShortsSession } from "@/lib/catalog/shorts";
import type { Engine, Generation } from "@/lib/catalog/types";
-import { useGenerationEvents } from "@/lib/api";
+import { COMPUTER_KICK_EVENT, useGenerationEvents } from "@/lib/api";
import { responseError } from "@/lib/refusals";
/** React Query hooks for /api/shorts/** (kept next to the studio that uses them). */
+/**
+ * A run 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));
+
async function json<T>(res: Response): Promise<T> {
if (res.status === 204) return undefined as T;
const body = (await res.json().catch(() => ({}))) as T & { error?: string };
@@ -153,11 +159,17 @@ export function useShortsActions(id?: string) {
return {
create: useMutation({
mutationFn: (body: ShortsBody) => send<ShortsSession>("/api/shorts/sessions", "POST", body),
- onSuccess: () => void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] }),
+ onSuccess: () => {
+ kick();
+ void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] });
+ },
}),
regenerate: useMutation({
mutationFn: (v: { index: number; requestId?: string }) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${v.index}`, "POST", { requestId: v.requestId }),
- onSuccess: put,
+ onSuccess: (s: ShortsSessionView) => {
+ kick();
+ put(s);
+ },
}),
enhance: useMutation({
mutationFn: (v: { index: number; requestId?: string }) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${v.index}/enhance`, "POST", { requestId: v.requestId }),
@@ -169,7 +181,10 @@ export function useShortsActions(id?: string) {
}),
stitch: useMutation({
mutationFn: (v: { requestId?: string } = {}) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/stitch`, "POST", { requestId: v.requestId }),
- onSuccess: put,
+ onSuccess: (s: ShortsSessionView) => {
+ kick();
+ put(s);
+ },
}),
rename: useMutation({
mutationFn: (title: string) => send<ShortsSession>(`/api/shorts/sessions/${id}`, "PATCH", { title }),
diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsx
index 152e7e25..732a041a 100644
--- a/src/components/shorts/session-view.tsx
+++ b/src/components/shorts/session-view.tsx
@@ -25,7 +25,7 @@ import { Viewer } from "@/components/studio/viewer";
import { chainState, ENHANCE_COPY, formatSeconds, segmentSeconds, stitchCurrent, stitchSteps, takeSteps, type ChainState, type ShortsSessionSegment } from "@/lib/catalog/shorts";
import { finishLengthProblem, REGEN_OFFERED } from "@/lib/catalog/regenerate";
import { originalSoundLabel, originalSoundOn } from "@/lib/av/original-sound";
-import { useEngineMode } from "@/lib/api";
+import { useEngineMode, useIsOwner } from "@/lib/api";
import type { Generation } from "@/lib/catalog/types";
import { formatCost, ratioValue, timeAgo } from "@/lib/format";
import { downloadHref, downloadName } from "@/lib/library";
@@ -99,6 +99,8 @@ function Session({ s }: { s: View }) {
const router = useRouter();
const actions = useShortsActions(s.id);
const engineMode = useEngineMode();
+ // The studio's owner keeps a Trash and downloads the parts as one zip; a signed-in account's short is its own runs.
+ const owner = useIsOwner();
const [open, setOpen] = useState<Generation | null>(null);
const [confirm, setConfirm] = useState(false);
const gens = s.generations;
@@ -190,7 +192,7 @@ function Session({ s }: { s: View }) {
<Download className="size-4" /> Download full video
</a>
)}
- {parts.length > 0 && (
+ {owner && parts.length > 0 && (
<a href={`/api/generations/zip?ids=${parts.join(",")}`} className="inline-flex h-9 items-center gap-1.5 rounded-full border bg-background px-4 text-[13px] font-medium hover:bg-accent">
<FolderDown className="size-4" /> Download parts{parts.length < s.segments.length ? ` (${parts.length})` : ""}
</a>
@@ -278,7 +280,7 @@ function Session({ s }: { s: View }) {
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete this short?</AlertDialogTitle>
- <AlertDialogDescription>Its segments and videos move to the Trash, where you can restore them for 30 days.</AlertDialogDescription>
+ <AlertDialogDescription>{owner ? "Its segments and videos move to the Trash, where you can restore them for 30 days." : "Its segments and videos are deleted for good."}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Keep it</AlertDialogCancel>
@@ -287,7 +289,7 @@ function Session({ s }: { s: View }) {
onClick={() =>
actions.remove.mutate(s.id, {
onSuccess: () => {
- toast("Moved to Trash");
+ toast(owner ? "Moved to Trash" : "Deleted");
router.push("/shorts?tab=history");
},
onError: (e) => toastError(e),
diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsx
index 28650b95..c57cd97e 100644
--- a/src/components/shorts/shorts-studio.tsx
+++ b/src/components/shorts/shorts-studio.tsx
@@ -9,10 +9,9 @@ import { toast } from "sonner";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { PhoneNavButton } from "@/components/nav/phone-nav-button";
import { OldFootageOffer } from "@/components/restore/old-footage";
-import { SelfHostNote } from "@/components/self-host-note";
import { EngineSwitch } from "@/components/studio/engine-switch";
import { VideoTrimmer } from "@/components/studio/video-trimmer";
-import { useEngine, useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";
+import { useAskBeforeUpload, useEngine, useModelAccess } from "@/lib/api";
import {
clipShapeProblem,
coveredFirst,
@@ -59,9 +58,6 @@ export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]>
const source = useSourceClip(SHORTS.maxBytes);
const { clip } = source;
const [range, setRange] = useState<TrimRange | null>(null);
- // A short doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and the
- // upload and Generate are off, instead of a run the server refuses.
- const visitor = useLikelyVisitor();
// Hand-offs: /shorts?tab=history, ?preset=shorts-claymation, ?video=/api/files/….
useEffect(() => {
@@ -107,7 +103,7 @@ export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]>
</TabRow>
<div className="ml-auto shrink-0">
{/* A phone's header has room for the title and the tabs, not "Add key" too. */}
- <EngineSwitch value={engine} onChange={setEngine} wordless selfHostedOnly />
+ <EngineSwitch value={engine} onChange={setEngine} wordless />
</div>
<PhoneNavButton />
</header>
@@ -122,11 +118,9 @@ export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]>
<p className="mx-auto mt-2 max-w-[560px] text-body text-pretty text-muted-foreground">
Upload a clip up to 2 minutes, pick a look, and get a finished short. Your motion and sound stay.
</p>
- {visitor && <SelfHostNote className="mx-auto mt-3 max-w-[560px]">Shorts Studio isn&apos;t available here.</SelfHostNote>}
<Steps steps={STEPS} current={!presetId ? 0 : !clip?.url ? 1 : 1} className="mt-5" />
</div>
<Workspace
- visitor={visitor}
engine={engine}
models={engineModels}
presetId={presetId}
@@ -143,7 +137,6 @@ export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]>
}
function Workspace({
- visitor,
engine,
models,
presetId,
@@ -152,7 +145,6 @@ function Workspace({
range,
setRange,
}: {
- visitor: boolean;
engine: Engine;
models: ModelChoice[];
presetId: string | null;
@@ -167,9 +159,9 @@ function Workspace({
const selectedBuiltIn = SHORTS_PRESETS.find((p) => p.id === presetId);
const selectedCustom = custom.data?.find((p) => p.id === presetId);
const selectedName = selectedBuiltIn?.name ?? selectedCustom?.name;
- // A preset of your own is saved to the studio's library, which is its owner's: its card shows once that's known, so
- // a visitor never sees it in the grid and then gone.
- const isOwner = useIsOwner();
+ // A preset of your own is made of pictures you upload: a guest is asked to sign up first, and an account with neither
+ // its own GPU nor its own key to connect one (as before any upload).
+ const askFirst = useAskBeforeUpload();
// Phones: after picking a look, a bar points down to the upload step until it's on screen.
const [setupVisible, setSetupVisible] = useState(false);
@@ -188,13 +180,12 @@ function Workspace({
custom={custom.data ?? []}
presetId={presetId}
onSelect={setPresetId}
- onCreate={isOwner ? () => setDialog({ open: true }) : undefined}
+ onCreate={() => askFirst() || setDialog({ open: true })}
onEdit={(id) => setDialog({ open: true, preset: custom.data?.find((p) => p.id === id) })}
/>
</section>
<aside ref={setup} id="shorts-setup" aria-labelledby="shorts-step-2" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-[calc(var(--chrome-top)+1rem)] lg:max-h-[calc(var(--content-h)-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl">
<SetupPanel
- visitor={visitor}
engine={engine}
models={models}
presetId={presetId}
@@ -236,7 +227,6 @@ function PresetGrid({
custom: ShortsCustomPreset[];
presetId: string | null;
onSelect: (id: string) => void;
- /** None for a guest or an account: no "Create preset" card. */
onCreate?: () => void;
onEdit: (id: string) => void;
}) {
@@ -307,7 +297,6 @@ function PresetGrid({
const LIMITS = "MP4 or MOV · 4 s to 2 min · up to 200 MB";
function SetupPanel({
- visitor,
engine,
models,
presetId,
@@ -318,8 +307,6 @@ function SetupPanel({
range,
setRange,
}: {
- /** A guest or an account: the upload and Generate are off (the page says shorts run on a self-hosted Fuobe). */
- visitor: boolean;
engine: Engine;
models: ModelChoice[];
presetId: string | null;
@@ -345,8 +332,7 @@ function SetupPanel({
const pickedOn = models.some((m) => m.id === pickedModel[engine]) ? pickedModel[engine] : "";
const modelId = pickedOn || (customRefs > 0 && engine === "cloud" && refModel ? refModel : models[0]?.id);
const model = models.find((m) => m.id === modelId);
- // An open model is free on a self-hosted Fuobe: a guest or an account reads that, not "your GPU".
- const priceOf = (m?: ModelChoice) => (visitor && m?.engine === "open" ? "Not available here" : m?.price);
+ const priceOf = (m?: ModelChoice) => m?.price;
const duration = clipDuration(clip);
const actions = useShortsActions();
const presetType = SHORTS_PRESETS.find((p) => p.id === presetId)?.type;
@@ -376,7 +362,7 @@ function SetupPanel({
const estimate = useShortsEstimate(estimateBody);
const est = estimate.data;
- const setupBlocker = !presetId
+ const blocker = !presetId
? "Pick a preset first"
: !clip
? "Upload a video"
@@ -395,7 +381,6 @@ function SetupPanel({
: estimate.error
? (estimate.error as Error).message
: null;
- const blocker = visitor ? "Shorts Studio isn't available here" : setupBlocker;
const guard = useSubmitGuard();
const [leaving, setLeaving] = useState(false);
@@ -435,7 +420,6 @@ function SetupPanel({
<ClipDrop
accept={SHORTS.accept}
limits={LIMITS}
- disabled={visitor}
onFile={(f) => {
const err = source.pick(f);
if (err) toast.error(err);
@@ -546,7 +530,7 @@ function SetupPanel({
<span className="text-[13px] text-muted-foreground">{est ? `${est.segments} segment${est.segments === 1 ? "" : "s"} · ${est.seconds} s` : "Estimate"}</span>
<span className="flex items-center gap-1.5 font-mono text-[13px] font-medium tabular-nums" aria-live="polite">
{estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" />}
- {estimateBody ? costText(est, engine, visitor) : "—"}
+ {estimateBody ? costText(est, engine) : "—"}
</span>
</div>
{est && !est.demo && engine === "cloud" && <p className="text-[12px] text-muted-foreground">You&apos;re only charged for the actual length.</p>}
@@ -565,7 +549,7 @@ function SetupPanel({
<button
type="button"
onClick={generate}
- disabled={busy || visitor}
+ disabled={busy}
aria-disabled={!!blocker || busy}
aria-describedby={blocker ? "shorts-blocker" : undefined}
className={cn(
diff --git a/src/components/shorts/ui.tsx b/src/components/shorts/ui.tsx
index b638715a..93dcfb81 100644
--- a/src/components/shorts/ui.tsx
+++ b/src/components/shorts/ui.tsx
@@ -5,6 +5,7 @@ import { useRef, useState } from "react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { LibraryGrid } from "@/components/studio/media-slot";
import { radioKeys, radioTab } from "@/components/studio/radio-keys";
+import { useAskBeforeUpload } from "@/lib/api";
import { cn } from "@/lib/utils";
import type { SourceClip } from "./use-source-clip";
@@ -89,7 +90,8 @@ export function Field({ label, htmlFor, hint, children }: { label: string; htmlF
/**
* "Upload a video to edit": click, drop, or pick from the Library. disabled: a tool that can't run here for this
- * visitor (the page says why), so nothing is uploaded only to be refused.
+ * visitor (the page says why), so nothing is uploaded only to be refused. Anyone the upload would refuse is asked first
+ * (useAskBeforeUpload): a guest to sign up, an account with neither its own GPU nor its own key to connect one.
*/
export function ClipDrop({
accept,
@@ -107,6 +109,7 @@ export function ClipDrop({
const input = useRef<HTMLInputElement>(null);
const [over, setOver] = useState(false);
const [lib, setLib] = useState(false);
+ const askFirst = useAskBeforeUpload();
return (
<div
aria-disabled={disabled || undefined}
@@ -119,7 +122,7 @@ export function ClipDrop({
e.preventDefault();
setOver(false);
const f = e.dataTransfer.files?.[0];
- if (f && !disabled) onFile(f);
+ if (f && !disabled && !askFirst()) onFile(f);
}}
className={cn(
"flex flex-col items-center gap-3 rounded-xl border border-dashed border-border-strong px-4 py-7 text-center transition-colors",
@@ -134,7 +137,7 @@ export function ClipDrop({
<div className="flex flex-wrap justify-center gap-2">
<button
type="button"
- onClick={() => input.current?.click()}
+ onClick={() => askFirst() || input.current?.click()}
disabled={disabled}
className="inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3.5 text-[13px] font-medium text-primary-foreground hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50"
>
diff --git a/src/components/shorts/use-source-clip.ts b/src/components/shorts/use-source-clip.ts
index 8c822f94..7f22b222 100644
--- a/src/components/shorts/use-source-clip.ts
+++ b/src/components/shorts/use-source-clip.ts
@@ -47,8 +47,9 @@ export function checkClipFile(file: File, maxBytes: number): string | null {
/** The file as the body (streamed to disk): an account's clip up to its limit, not only a small form. */
const upload = (file: File, onProgress: (p: number) => void, signal: AbortSignal) => postFileWithProgress(file, onProgress, signal);
+/** The clip's header, read on the server (a signed-in account's own files only: src/app/api/media/probe). */
async function probe(url: string): Promise<SourceInfo> {
- const res = await fetch("/api/shorts/probe", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url }) });
+ const res = await fetch("/api/media/probe", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url }) });
return res.ok ? ((await res.json()) as SourceInfo) : {};
}
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 274044a5..1ba3c353 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -295,6 +295,10 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [
export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [
// Character Swap Studio: the list, a project, its prices, its decisions, and stopping its jobs.
/^\/api\/swap-studio\/projects(\/[^/]+(\/(decisions|estimate|stop|takes\/stop))?)?$/,
+ // Shorts Studio: its own sessions (start one, a new take, stitch again, pick a take, rename, delete) and its own
+ // 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(\/[^/]+)?$/,
];
export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));
diff --git a/src/proxy.ts b/src/proxy.ts
index a57811db..60ab7353 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -31,7 +31,7 @@ import {
import { ADMIN_BEARER, authEnabled, crossSite, hasCloudKey, hostAllowed, LoginGuard, publicSignup, sessionCookieOf, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";
import { fileAccount, generationAccount } from "@/server/account-library";
import { hit } from "@/server/rate";
-import { recordExists } from "@/server/records";
+import { accountRecordExists, recordExists } from "@/server/records";
import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";
import { hostedRunsOn } from "@/server/hosted-switch";
import { authStoreFailed } from "@/server/auth-store";
@@ -275,6 +275,10 @@ function account(request: NextRequest, who: Account): NextResponse {
if (file !== undefined) return fileAccount(safeDecode(file)) === who.id ? pass(request) : notYours();
// A tool's projects, kept per account: the route answers with its own only.
if (accountProjectRoute(pathname)) return pass(request);
+ // A tool's page for one of them (/shorts/<id>): its own, else a real 404 (never the owner's or another account's).
+ const record = request.method === "GET" || request.method === "HEAD" ? recordForPath(pathname) : null;
+ const own = record ? accountRecordExists(record, who.id) : null;
+ if (own !== null) return own ? NextResponse.next() : notFound(request);
if (request.method === "GET" || request.method === "HEAD") return accountOwnRead(pathname) ? pass(request) : readAsGuest(request, true);
if (isPriceCheck(request.method, pathname, search)) return priceCheck(request, `account:${who.id}`);
if (accountMayChange(request.method, pathname, search)) return pass(request);
diff --git a/src/server/records.ts b/src/server/records.ts
index 511fd52c..bf61ee84 100644
--- a/src/server/records.ts
+++ b/src/server/records.ts
@@ -1,5 +1,7 @@
import "server-only";
import type { RecordRef } from "@/lib/record-pages";
+import { getAccountProject } from "./account-projects";
+import { requestAccount } from "./auth";
import { db } from "./db";
/** The table and id columns behind each kind of record page (the ids are the page's segments, in order). */
@@ -31,3 +33,26 @@ export function recordExists(ref: RecordRef): boolean {
return true;
}
}
+
+/** 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" };
+
+/**
+ * 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:
+ * the page's kind isn't, and the check is recordExists's). Never the owner's records or another account's.
+ */
+export function accountRecordExists(ref: RecordRef, accountId: string): boolean | null {
+ const kind = ACCOUNT_KINDS[ref.kind];
+ if (!kind) return null;
+ try {
+ return !!getAccountProject(accountId, kind, ref.ids[0]);
+ } catch {
+ return true;
+ }
+}
+
+/** recordExists for whoever asks (a page's request headers): an account's own on a page kept per account. */
+export function recordFor(ref: RecordRef, headers: Headers): boolean {
+ const account = requestAccount({ headers } as Request);
+ return (account && accountRecordExists(ref, account.id)) ?? recordExists(ref);
+}
diff --git a/src/server/shorts.ts b/src/server/shorts.ts
index aaf7180f..8d2acb8d 100644
--- a/src/server/shorts.ts
+++ b/src/server/shorts.ts
@@ -38,20 +38,39 @@ import {
type TakeKeys,
} from "@/lib/catalog/shorts";
import { REGEN_COPY, REGEN_OFFERED } from "@/lib/catalog/regenerate";
-import type { Engine, Generation } from "@/lib/catalog/types";
+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+import { generationAccount } from "./account-library";
+import {
+ ACCOUNT_PROJECT_LIMITS,
+ AccountProjectError,
+ createAccountProject,
+ deleteAccountProject,
+ getAccountProject,
+ listAccountProjects,
+ projectRefsProblem,
+ updateAccountProject,
+} from "./account-projects";
import { createPipeline } from "./chains";
import { db } from "./db";
import { getGeneration, previewChained } from "./generations";
-import { trashGenerations } from "./library";
+import { deleteForever, trashGenerations } from "./library";
import { firstOn } from "./model-access";
import { engineMode } from "./settings";
import { readRef, RefError } from "./storage";
import { mediaFacts, type SourceInfo } from "./media-facts";
+import { tenant } from "./tenant";
/**
* Shorts Studio sessions: a clip cut into segments, each restyled (one or more takes, one of them
* primary) and stitched back together under the original sound. Every step is an ordinary
* generation made through createPipeline; a session only records which generation is which.
+ *
+ * Whose sessions and presets: the owner's are in shorts_sessions and shorts_presets. Inside an account's work
+ * (tenant.ts, asAccount; public sign-up) every read and change here is that account's own instead, kept in its own
+ * projects (account-projects.ts, kinds "shorts" and "shorts-preset"): it never reaches the owner's tables or another
+ * account's. A guest has none. An account's runs are checked and started through src/server/account-tool-run.ts, so
+ * each run is planned first (planSessionRun, planTakeRun, planStitchRun) and started after the checks (startSession,
+ * startTake, startStitch).
*/
export class ShortsError extends Error {
@@ -128,18 +147,114 @@ const toSession = (r: SessionRow): ShortsSession => ({
updatedAt: r.updated_at,
});
+/** An account's sessions and presets, as its own projects (account-projects.ts). */
+const SESSION_KIND = "shorts";
+const PRESET_KIND = "shorts-preset";
+
+/** Whose work this is: the owner's (undefined), an account's (its id), or a guest's (null: nothing of its own). */
+function whose(): string | null | undefined {
+ const t = tenant();
+ if (!t) return undefined;
+ return t.kind === "account" ? t.id : null;
+}
+
+const GONE = "This short no longer exists";
+
+/** A change the account's project store refused (too big, too many): its words and status. */
+function stored<T>(fn: () => T): T {
+ try {
+ return fn();
+ } catch (e) {
+ if (e instanceof AccountProjectError) throw new ShortsError(e.message, e.status);
+ throw e;
+ }
+}
+
+/** What an account's History shows of a session, kept beside it (the list never reads every session). */
+interface SessionLine {
+ engine: Engine;
+ lookName: string;
+ segments: number;
+ seconds: number;
+ /** The newest stitch's video. */
+ final?: string;
+ /** Each segment's chosen take. */
+ primaries: string[];
+}
+
+const lineOf = (s: Omit<ShortsSession, "id">): SessionLine => ({
+ engine: s.engine,
+ lookName: s.look.name,
+ segments: s.segments.length,
+ seconds: Math.round((s.range.end - s.range.start) * 10) / 10,
+ ...(s.stitches.length && { final: s.stitches[s.stitches.length - 1].final }),
+ primaries: s.segments.map((g) => g.primary),
+});
+
function readSession(id: string): ShortsSession {
- const r = db().prepare("SELECT * FROM shorts_sessions WHERE id = ?").get(id) as SessionRow | undefined;
- if (!r) throw new ShortsError("This short no longer exists", 404);
- return toSession(r);
+ const who = whose();
+ if (who === undefined) {
+ const r = db().prepare("SELECT * FROM shorts_sessions WHERE id = ?").get(id) as SessionRow | undefined;
+ if (!r) throw new ShortsError(GONE, 404);
+ return toSession(r);
+ }
+ // Another account's session, the owner's, or none: the same answer.
+ const p = who ? getAccountProject<ShortsSession>(who, SESSION_KIND, id) : null;
+ if (!p) throw new ShortsError(GONE, 404);
+ return { ...p.data, id: p.id, title: p.name, createdAt: p.createdAt, updatedAt: p.updatedAt };
}
function saveSession(s: ShortsSession): ShortsSession {
- const now = Date.now();
- db()
- .prepare("UPDATE shorts_sessions SET segments_json = ?, stitches_json = ?, title = ?, updated_at = ? WHERE id = ?")
- .run(JSON.stringify(s.segments), JSON.stringify(s.stitches), s.title, now, s.id);
- return { ...s, updatedAt: now };
+ const who = whose();
+ if (who === undefined) {
+ const now = Date.now();
+ db()
+ .prepare("UPDATE shorts_sessions SET segments_json = ?, stitches_json = ?, title = ?, updated_at = ? WHERE id = ?")
+ .run(JSON.stringify(s.segments), JSON.stringify(s.stitches), s.title, now, s.id);
+ return { ...s, updatedAt: now };
+ }
+ const saved = who ? stored(() => updateAccountProject(who, SESSION_KIND, s.id, { name: s.title, data: s, summary: lineOf(s) })) : null;
+ if (!saved) throw new ShortsError(GONE, 404);
+ return { ...s, title: saved.name, updatedAt: saved.updatedAt };
+}
+
+/** Store a new session: the owner's row, or the account's own project. Its id is the store's. */
+function insertSession(s: Omit<ShortsSession, "id">): ShortsSession {
+ const who = whose();
+ if (who === undefined) {
+ const session: ShortsSession = { id: nanoid(10), ...s };
+ db()
+ .prepare(
+ `INSERT INTO shorts_sessions (id, title, engine, batch_id, look_json, source_json, range_json, settings_json, segments_json, stitches_json, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(
+ session.id,
+ session.title,
+ session.engine,
+ session.batchId,
+ JSON.stringify(session.look),
+ JSON.stringify(session.source),
+ JSON.stringify(session.range),
+ JSON.stringify(session.settings),
+ JSON.stringify(session.segments),
+ JSON.stringify(session.stitches),
+ session.createdAt,
+ session.updatedAt,
+ );
+ return session;
+ }
+ if (!who) throw new ShortsError("Create a free account to make a short.", 401);
+ const p = stored(() => createAccountProject(who, SESSION_KIND, { name: s.title, data: s, summary: lineOf(s) }));
+ return { ...s, id: p.id, title: p.name, createdAt: p.createdAt, updatedAt: p.updatedAt };
+}
+
+/** An account keeps up to ACCOUNT_PROJECT_LIMITS.projects shorts: checked before anything is made. */
+function roomForSession(): void {
+ const who = whose();
+ if (who && listAccountProjects(who, SESSION_KIND).length >= ACCOUNT_PROJECT_LIMITS.projects) {
+ throw new ShortsError(`You can keep up to ${ACCOUNT_PROJECT_LIMITS.projects} shorts. Delete one to make another.`, 409);
+ }
}
interface PresetRow {
@@ -163,20 +278,55 @@ const toPreset = (r: PresetRow): ShortsCustomPreset => ({
// ---------------------------------------------------------------------------
// Custom presets ("Create a preset from references")
+/** An account's preset, as its project keeps it (the name is the project's). */
+interface PresetData {
+ description: string;
+ references: string[];
+}
+
+function accountPreset(who: string, id: string): ShortsCustomPreset | null {
+ const p = getAccountProject<PresetData>(who, PRESET_KIND, id);
+ return p ? { id: p.id, name: p.name, description: p.data.description, references: p.data.references, createdAt: p.createdAt, updatedAt: p.updatedAt } : null;
+}
+
+/** An account's references are its own uploads or results only (or Fuobe's example files): another's is refused. */
+function ownReferences(who: string, refs: string[]): void {
+ const problem = projectRefsProblem(who, { files: refs });
+ if (problem) throw new ShortsError(problem.error, problem.status);
+}
+
export function listCustomPresets(): ShortsCustomPreset[] {
- return (db().prepare("SELECT * FROM shorts_presets ORDER BY created_at DESC").all() as PresetRow[]).map(toPreset);
+ const who = whose();
+ if (who === undefined) return (db().prepare("SELECT * FROM shorts_presets ORDER BY created_at DESC").all() as PresetRow[]).map(toPreset);
+ if (!who) return [];
+ return listAccountProjects(who, PRESET_KIND)
+ .map((p) => accountPreset(who, p.id))
+ .filter((p): p is ShortsCustomPreset => !!p)
+ .sort((x, y) => y.createdAt - x.createdAt);
}
export function getCustomPreset(id: string): ShortsCustomPreset | null {
- const r = db().prepare("SELECT * FROM shorts_presets WHERE id = ?").get(id) as PresetRow | undefined;
- return r ? toPreset(r) : null;
+ const who = whose();
+ if (who === undefined) {
+ const r = db().prepare("SELECT * FROM shorts_presets WHERE id = ?").get(id) as PresetRow | undefined;
+ return r ? toPreset(r) : null;
+ }
+ return who ? accountPreset(who, id) : null;
}
export function createCustomPreset(input: { name?: string; description?: string; references: string[] }): ShortsCustomPreset {
const refs = [...new Set(input.references)].slice(0, SHORTS.maxReferences);
if (!refs.length) throw new ShortsError("Add at least one reference image");
- const count = (db().prepare("SELECT COUNT(*) AS n FROM shorts_presets").get() as { n: number }).n;
const description = (input.description ?? "").trim();
+ const who = whose();
+ if (who !== undefined) {
+ if (!who) throw new ShortsError("Create a free account to make a preset.", 401);
+ ownReferences(who, refs);
+ const name = input.name?.trim() || customPresetName(description, listAccountProjects(who, PRESET_KIND).length);
+ const p = stored(() => createAccountProject<PresetData>(who, PRESET_KIND, { name, data: { description, references: refs } }));
+ return accountPreset(who, p.id)!;
+ }
+ const count = (db().prepare("SELECT COUNT(*) AS n FROM shorts_presets").get() as { n: number }).n;
const name = input.name?.trim() || customPresetName(description, count);
const now = Date.now();
const id = `custom-${nanoid(10)}`;
@@ -191,6 +341,13 @@ export function updateCustomPreset(id: string, patch: { name?: string; descripti
if (!cur) throw new ShortsError("This preset no longer exists", 404);
const refs = patch.references ? [...new Set(patch.references)].slice(0, SHORTS.maxReferences) : cur.references;
if (!refs.length) throw new ShortsError("Keep at least one reference image");
+ const who = whose();
+ if (who) {
+ if (patch.references) ownReferences(who, refs);
+ const data: PresetData = { description: patch.description?.trim() ?? cur.description, references: refs };
+ if (!stored(() => updateAccountProject(who, PRESET_KIND, id, { name: patch.name?.trim() || cur.name, data }))) throw new ShortsError("This preset no longer exists", 404);
+ return accountPreset(who, id)!;
+ }
db()
.prepare("UPDATE shorts_presets SET name = ?, description = ?, references_json = ?, updated_at = ? WHERE id = ?")
.run(patch.name?.trim() || cur.name, patch.description?.trim() ?? cur.description, JSON.stringify(refs), Date.now(), id);
@@ -198,7 +355,9 @@ export function updateCustomPreset(id: string, patch: { name?: string; descripti
}
export function deleteCustomPreset(id: string): boolean {
- return db().prepare("DELETE FROM shorts_presets WHERE id = ?").run(id).changes > 0;
+ const who = whose();
+ if (who === undefined) return db().prepare("DELETE FROM shorts_presets WHERE id = ?").run(id).changes > 0;
+ return !!who && deleteAccountProject(who, PRESET_KIND, id);
}
// ---------------------------------------------------------------------------
@@ -369,17 +528,53 @@ export function estimateWith(body: ShortsBody, info: SourceInfo): ShortsEstimate
// ---------------------------------------------------------------------------
// Sessions
+/** A plan's steps as the requests they make, with how many earlier steps each waits for (account-tool-run.ts ToolStep). */
+export const shortsSteps = (steps: PlanStep[]): { request: GenerationRequest; deps: number }[] => steps.map((s) => ({ request: withChain(s), deps: s.after?.length ?? 0 }));
+
+/** The steps made, or the planner's words as a 422. */
+function pipelineOf(steps: PlanStep[], opts?: { batchId: string }): ReturnType<typeof createPipeline> {
+ try {
+ return createPipeline(steps, opts);
+ } catch (e) {
+ throw new ShortsError((e as Error).message, 422);
+ }
+}
+
+/** A new session planned (the clip's header read, every step planned), not started yet. */
+export interface SessionRun {
+ body: ShortsBody;
+ input: ShortsPlanInput;
+ info: SourceInfo;
+ plan: ReturnType<typeof planShorts>;
+}
+
+/** Plan a session as it will start; `known` is the clip's header when the caller read it already (else it's read here). */
+export async function planSessionRun(body: ShortsBody, known?: SourceInfo): Promise<SessionRun> {
+ roomForSession();
+ const { input, info } = known ? planWith(body, known) : await planInput(body, { probe: true });
+ // An account's preset is its own (lookFor), and so must its pictures still be.
+ const who = whose();
+ if (who && input.look.references?.length) ownReferences(who, input.look.references);
+ return { body, input, info, plan: planShorts(input) };
+}
+
+/** The files a session's runs take (its clip and its look's pictures): an account's run is checked for them first. */
+export function sessionFiles(id: string): string[] {
+ const s = readSession(id);
+ return [s.source.url, ...(s.look.references ?? [])];
+}
+
/** Start a session; `known` is the clip's header when the caller read it already (else it's read here). */
export async function createSession(body: ShortsBody, known?: SourceInfo): Promise<ShortsSession> {
- const { input, info } = known ? planWith(body, known) : await planInput(body, { probe: true });
- const plan = planShorts(input);
- const pipeline = (() => {
- try {
- return createPipeline(plan.steps);
- } catch (e) {
- throw new ShortsError((e as Error).message, 422);
- }
- })();
+ return startSession(await planSessionRun(body, known));
+}
+
+/** Start a planned session: its steps are made, and the session that records them is stored. */
+export function startSession(run: SessionRun): ShortsSession {
+ const { body, input, info, plan } = run;
+ // Checked again with nothing awaited before the session is stored: a full account starts nothing.
+ roomForSession();
+ const pipeline = pipelineOf(plan.steps);
const id = (k: string) => pipeline.byKey[k].id;
const now = Date.now();
const segments: ShortsSessionSegment[] = plan.segments.map((s, i) => {
@@ -393,8 +588,7 @@ export async function createSession(body: ShortsBody, known?: SourceInfo): Promi
clips: segments.map((s) => s.primary),
createdAt: now,
};
- const session: ShortsSession = {
- id: nanoid(10),
+ return insertSession({
title: input.title,
engine: input.engine,
batchId: pipeline.batchId,
@@ -414,27 +608,7 @@ export async function createSession(body: ShortsBody, known?: SourceInfo): Promi
stitches: [stitch],
createdAt: now,
updatedAt: now,
- };
- db()
- .prepare(
- `INSERT INTO shorts_sessions (id, title, engine, batch_id, look_json, source_json, range_json, settings_json, segments_json, stitches_json, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run(
- session.id,
- session.title,
- session.engine,
- session.batchId,
- JSON.stringify(session.look),
- JSON.stringify(session.source),
- JSON.stringify(session.range),
- JSON.stringify(session.settings),
- JSON.stringify(session.segments),
- JSON.stringify(session.stitches),
- now,
- now,
- );
- return session;
+ });
}
/** A take's generations by role, from its steps' keys. */
@@ -487,27 +661,41 @@ export interface ShortsSessionCard {
status: "rendering" | "ready" | "failed";
}
+/** A session's History card, from its line and its generations as they are now. */
+function cardOf(s: { id: string; title: string; createdAt: number; updatedAt: number }, l: SessionLine): ShortsSessionCard {
+ const final = l.final ? getGeneration(l.final) : null;
+ const looks = l.primaries.map((id) => getGeneration(id));
+ const active = [final, ...looks].some((g) => g && (g.status === "queued" || g.status === "running"));
+ const failed = [final, ...looks].some((g) => !g || g.status === "failed" || g.status === "canceled");
+ return {
+ id: s.id,
+ title: s.title,
+ engine: l.engine,
+ lookName: l.lookName,
+ segments: l.segments,
+ seconds: l.seconds,
+ createdAt: s.createdAt,
+ updatedAt: s.updatedAt,
+ cover: final?.status === "succeeded" ? final : (looks.find((g) => g?.status === "succeeded") ?? final ?? looks[0] ?? null),
+ status: active ? "rendering" : failed ? "failed" : "ready",
+ };
+}
+
export function listSessions(limit = 60): ShortsSessionCard[] {
- const rows = db().prepare("SELECT * FROM shorts_sessions ORDER BY created_at DESC LIMIT ?").all(limit) as SessionRow[];
- return rows.map((r) => {
- const s = toSession(r);
- const final = s.stitches.length ? getGeneration(s.stitches[s.stitches.length - 1].final) : null;
- const looks = s.segments.map((g) => getGeneration(g.primary));
- const active = [final, ...looks].some((g) => g && (g.status === "queued" || g.status === "running"));
- const failed = [final, ...looks].some((g) => !g || g.status === "failed" || g.status === "canceled");
- return {
- id: s.id,
- title: s.title,
- engine: s.engine,
- lookName: s.look.name,
- segments: s.segments.length,
- seconds: Math.round((s.range.end - s.range.start) * 10) / 10,
- createdAt: s.createdAt,
- updatedAt: s.updatedAt,
- cover: final?.status === "succeeded" ? final : (looks.find((g) => g?.status === "succeeded") ?? final ?? looks[0] ?? null),
- status: active ? "rendering" : failed ? "failed" : "ready",
- };
- });
+ const who = whose();
+ if (who === undefined) {
+ const rows = db().prepare("SELECT * FROM shorts_sessions ORDER BY created_at DESC LIMIT ?").all(limit) as SessionRow[];
+ return rows.map((r) => {
+ const s = toSession(r);
+ return cardOf(s, lineOf(s));
+ });
+ }
+ if (!who) return [];
+ return listAccountProjects<SessionLine>(who, SESSION_KIND)
+ .filter((p) => p.summary)
+ .sort((x, y) => y.createdAt - x.createdAt)
+ .slice(0, limit)
+ .map((p) => cardOf({ id: p.id, title: p.name, createdAt: p.createdAt, updatedAt: p.updatedAt }, p.summary!));
}
export function renameSession(id: string, title: string): ShortsSession {
@@ -515,12 +703,20 @@ export function renameSession(id: string, title: string): ShortsSession {
return saveSession({ ...s, title: title.trim().slice(0, 120) || s.title });
}
-/** Delete a session; its generations move to the Trash (restorable for 30 days) unless `keep`. */
-export function deleteSession(id: string, opts: { keep?: boolean } = {}): number {
+/**
+ * Delete a session; its generations move to the Trash (restorable for 30 days) unless `keep`. An account has no Trash
+ * (as DELETE /api/generations/<id>): its session's runs are deleted for good, and only ever its own.
+ */
+export async function deleteSession(id: string, opts: { keep?: boolean } = {}): Promise<number> {
const s = readSession(id);
- const trashed = opts.keep ? 0 : trashGenerations(sessionIds(s));
- db().prepare("DELETE FROM shorts_sessions WHERE id = ?").run(id);
- return trashed;
+ const who = whose();
+ if (who === undefined) {
+ const trashed = opts.keep ? 0 : trashGenerations(sessionIds(s));
+ db().prepare("DELETE FROM shorts_sessions WHERE id = ?").run(id);
+ return trashed;
+ }
+ if (!who || !deleteAccountProject(who, SESSION_KIND, id)) throw new ShortsError(GONE, 404);
+ return opts.keep ? 0 : deleteForever(sessionIds(s).filter((g) => generationAccount(g) === who));
}
const segmentAt = (s: ShortsSession, index: number) => {
@@ -534,23 +730,39 @@ const usable = (id: string) => {
return !!g && g.status !== "failed" && g.status !== "canceled";
};
-/** A new take of one segment (a fresh seed). It becomes the chosen take when the current one failed or is gone. */
-export function regenerateSegment(id: string, index: number): ShortsSessionView {
+/** A new take of one segment planned, not started yet. */
+export interface TakeRun {
+ id: string;
+ index: number;
+ steps: PlanStep[];
+ keys: TakeKeys;
+}
+
+/** Plan a new take of one segment (a fresh seed). */
+export function planTakeRun(id: string, index: number): TakeRun {
const s = readSession(id);
const seg = segmentAt(s, index);
checkEngine(s.engine);
const seed = Math.floor(Math.random() * 2 ** 31);
const take = planTake(sessionPlanInput(s, seed), seg, s.segments.length, `r${seg.takes.length}`);
- let pipeline;
- try {
- pipeline = createPipeline(take.steps, { batchId: s.batchId });
- } catch (e) {
- throw new ShortsError((e as Error).message, 422);
- }
- const next = takeOf(take.keys, (k) => pipeline.byKey[k].id, Date.now());
- const segments = s.segments.map((g, i) => (i === index ? { ...g, takes: [...g.takes, next], primary: usable(g.primary) ? g.primary : next.look } : g));
+ return { id, index, steps: take.steps, keys: take.keys };
+}
+
+/** Start a planned take. It becomes the chosen take when the current one failed or is gone. */
+export function startTake(run: TakeRun): ShortsSessionView {
+ // Read again before anything is made: the session may have gone meanwhile.
+ const s = readSession(run.id);
+ segmentAt(s, run.index);
+ const pipeline = pipelineOf(run.steps, { batchId: s.batchId });
+ const next = takeOf(run.keys, (k) => pipeline.byKey[k].id, Date.now());
+ const segments = s.segments.map((g, i) => (i === run.index ? { ...g, takes: [...g.takes, next], primary: usable(g.primary) ? g.primary : next.look } : g));
saveSession({ ...s, segments });
- return getSession(id);
+ return getSession(run.id);
+}
+
+/** A new take of one segment (a fresh seed). It becomes the chosen take when the current one failed or is gone. */
+export function regenerateSegment(id: string, index: number): ShortsSessionView {
+ return startTake(planTakeRun(id, index));
}
/**
@@ -598,8 +810,27 @@ export function makePrimary(id: string, index: number, lookId: string): ShortsSe
return getSession(id);
}
-/** Join the chosen takes again (after a regenerate or a new choice) and put the sound back. */
-export function stitchSession(id: string): ShortsSessionView {
+/** A second "Stitch again" while the same takes are still being stitched would pay for the same video twice. */
+function stitchingNow(s: ShortsSession): void {
+ const last = s.stitches[s.stitches.length - 1];
+ if (last && stitchCurrent(s) && [...last.ids, last.final].some((gid) => ["queued", "running"].includes(getGeneration(gid)?.status ?? ""))) {
+ throw new ShortsError("These takes are already being stitched", 409);
+ }
+}
+
+/** A stitch of the chosen takes planned, not started yet. No steps: one silent segment, whose take is the short. */
+export interface StitchRun {
+ id: string;
+ steps: PlanStep[];
+ final?: string;
+ /** The takes it joins (each segment's chosen one when it was planned). */
+ clips: string[];
+ /** Their videos (an account's run takes only its own files). */
+ files: string[];
+}
+
+/** Plan joining the chosen takes again (after a regenerate or a new choice), with the sound put back. */
+export function planStitchRun(id: string): StitchRun {
const s = readSession(id);
checkEngine(s.engine);
const clips = s.segments.map((seg, i) => {
@@ -610,29 +841,33 @@ export function stitchSession(id: string): ShortsSessionView {
if (g.status !== "succeeded" || !url) throw new ShortsError(`Segment ${i + 1} didn't render — regenerate it first`, 409);
return { url, enhanced: !!seg.takes.find((t) => t.look === seg.primary)?.enhance };
});
- // A second "Stitch again" while the same takes are still being stitched would pay for the same video twice.
- const last = s.stitches[s.stitches.length - 1];
- if (last && stitchCurrent(s) && [...last.ids, last.final].some((gid) => ["queued", "running"].includes(getGeneration(gid)?.status ?? ""))) {
- throw new ShortsError("These takes are already being stitched", 409);
- }
+ stitchingNow(s);
// Enhanced takes are 1080p at 24 fps: the others are brought to 24 fps and the join runs at 1080p (planFinishedStitch).
const plan = planFinishedStitch(sessionPlanInput(s), clips, `-s${s.stitches.length}`);
+ return { id, steps: plan.final ? plan.steps : [], ...(plan.final && { final: plan.final }), clips: s.segments.map((g) => g.primary), files: clips.map((c) => c.url) };
+}
+
+/** Start a planned stitch and record it on the session. */
+export function startStitch(run: StitchRun): ShortsSessionView {
+ // Read again before anything is made: the session may have gone, or a stitch started meanwhile.
+ const s = readSession(run.id);
+ stitchingNow(s);
const now = Date.now();
let stitch: ShortsStitch;
- if (!plan.steps.length || !plan.final) {
+ if (!run.steps.length || !run.final) {
// One silent segment: its take is the short.
- stitch = { ids: [], final: s.segments[0].primary, clips: s.segments.map((g) => g.primary), createdAt: now };
+ stitch = { ids: [], final: run.clips[0], clips: run.clips, createdAt: now };
} else {
- let pipeline;
- try {
- pipeline = createPipeline(plan.steps, { batchId: s.batchId });
- } catch (e) {
- throw new ShortsError((e as Error).message, 422);
- }
- stitch = { ids: plan.steps.map((x) => pipeline.byKey[x.key].id), final: pipeline.byKey[plan.final].id, clips: s.segments.map((g) => g.primary), createdAt: now };
+ const pipeline = pipelineOf(run.steps, { batchId: s.batchId });
+ stitch = { ids: run.steps.map((x) => pipeline.byKey[x.key].id), final: pipeline.byKey[run.final].id, clips: run.clips, createdAt: now };
}
saveSession({ ...s, stitches: [...s.stitches, stitch] });
- return getSession(id);
+ return getSession(run.id);
+}
+
+/** Join the chosen takes again (after a regenerate or a new choice) and put the sound back. */
+export function stitchSession(id: string): ShortsSessionView {
+ return startStitch(planStitchRun(id));
}
/** What one more take of a segment costs. */
diff --git a/tests/account-shorts.test.ts b/tests/account-shorts.test.ts
new file mode 100644
index 00000000..c6592228
--- /dev/null
+++ b/tests/account-shorts.test.ts
@@ -0,0 +1,522 @@
+import fs from "node:fs";
+import path from "node:path";
+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";
+
+vi.setConfig({ testTimeout: 120_000 });
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+/**
+ * Shorts Studio for a signed-in account (public sign-up): its sessions and presets are its own projects, its runs go to
+ * its own ComfyUI (a stand-in here) through the same generations every studio run makes, with only its own files. A
+ * guest gets the sign-up card; another account's sessions and the owner's are never reached.
+ */
+const dir = tempDir("fuobe-account-shorts-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+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"): recorded, so a test sees that nothing reached it.
+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 sessionsRoute = await import("@/app/api/shorts/sessions/route");
+const sessionRoute = await import("@/app/api/shorts/sessions/[id]/route");
+const takeRoute = await import("@/app/api/shorts/sessions/[id]/segments/[index]/route");
+const primaryRoute = await import("@/app/api/shorts/sessions/[id]/segments/[index]/primary/route");
+const enhanceRoute = await import("@/app/api/shorts/sessions/[id]/segments/[index]/enhance/route");
+const stitchRoute = await import("@/app/api/shorts/sessions/[id]/stitch/route");
+const estimateRoute = await import("@/app/api/shorts/estimate/route");
+const presetsRoute = await import("@/app/api/shorts/presets/route");
+const presetRoute = await import("@/app/api/shorts/presets/[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 { 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 store = await import("@/server/account-projects");
+const { recordFor } = await import("@/server/records");
+const { purgeAccount } = await import("@/server/account-sweep");
+
+const CLIP = fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4"));
+
+let fake: FakeComfy;
+let a = "";
+let b = "";
+let c = "";
+const cookies: Record<string, string> = {};
+beforeAll(async () => {
+ // Each job answers a clip and a picture: a segment's cut keeps its first frame for the restyle.
+ fake = await startFakeComfy({ loras: [], delayMs: 0, output: "both" });
+ 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);
+});
+
+function json(url: string, method: string, body?: unknown, who?: string): Request {
+ const text = body === undefined ? "" : JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, {
+ method,
+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(who && { cookie: cookies[who] }) },
+ ...(method !== "GET" && method !== "HEAD" && text && { body: text }),
+ });
+}
+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) }) as never;
+
+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;
+}
+
+/** An open-engine short of the first 10 s (two segments) in a built-in look. */
+const short = (clip: string, extra: Record<string, unknown> = {}) => ({
+ engine: "open",
+ presetId: "shorts-claymation",
+ source: { url: clip, name: "dance.mp4" },
+ range: { start: 0, end: 10 },
+ aspectRatio: "9:16",
+ language: "auto",
+ ...extra,
+});
+
+/** Send a run; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */
+async function run(send: () => Promise<Response>): Promise<Response> {
+ let r = await send();
+ for (let i = 0; i < 3 && r.status === 409; i++) {
+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };
+ if (j.code !== "comfy_missing_model" || !j.fix) break;
+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix.items.map((x) => x.file)];
+ for (const id of [a, b]) clearAccountLoras(id);
+ r = await send();
+ }
+ return r;
+}
+
+const create = (body: unknown, who: string) => run(() => sessionsRoute.POST(json("/api/shorts/sessions", "POST", body, who)));
+
+interface View {
+ id: string;
+ title: string;
+ segments: { primary: string; takes: { look: string }[] }[];
+ stitches: { final: string; ids: string[] }[];
+ generations: Record<string, { id: string; status: string; outputs: { url: string }[] }>;
+}
+
+const read = (id: string, who?: string) => sessionRoute.GET(json(`/api/shorts/sessions/${id}`, "GET", undefined, who), params({ id }));
+
+/** Tick the runner until every run of the session is done (or the time is up). */
+async function settle(id: string, who: string, ms = 60_000): Promise<View> {
+ const end = Date.now() + ms;
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const v = (await (await read(id, who)).json()) as View;
+ const ids = [...v.segments.flatMap((s) => s.takes.map((t) => t.look)), ...v.stitches.flatMap((s) => [...s.ids, s.final])];
+ const busy = ids.some((g) => ["queued", "running"].includes(getGeneration(g, { includeDeleted: true })?.status ?? ""));
+ if (!busy || Date.now() > end) return (await (await read(id, who)).json()) as View;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+const accountOf = (gid: string) => getGeneration(gid, { includeDeleted: true })?.request.account;
+
+/** A session the owner made: a row in the owner's own table, with one run of the owner's. */
+function ownerSession(): { id: string; gen: string } {
+ const t = Date.now();
+ const clip = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "owner.mp4" }).url;
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES ('owner-short-take', 'shorts', 'oss-trim', 'open', 'comfyui', 'trim', 'video', 'succeeded', ?, ?, ?, ?)",
+ )
+ .run(JSON.stringify({ feature: "shorts", modelId: "oss-trim" }), JSON.stringify([{ url: clip, kind: "video" }]), t, t);
+ const seg = { index: 0, start: 0, end: 5, takes: [{ cut: "owner-short-take", look: "owner-short-take", createdAt: t }], primary: "owner-short-take" };
+ db()
+ .prepare(
+ `INSERT INTO shorts_sessions (id, title, engine, batch_id, look_json, source_json, range_json, settings_json, segments_json, stitches_json, created_at, updated_at)
+ VALUES ('owner-short', 'The owner''s short', 'open', 'owner-batch', ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(
+ JSON.stringify({ presetId: "shorts-claymation", name: "Claymation", look: "claymation" }),
+ JSON.stringify({ url: clip, hasAudio: false }),
+ JSON.stringify({ start: 0, end: 5 }),
+ JSON.stringify({ aspectRatio: "9:16", language: "auto", modelId: "oss-shorts", maxRefs: 0 }),
+ JSON.stringify([seg]),
+ JSON.stringify([{ ids: [], final: "owner-short-take", clips: ["owner-short-take"], createdAt: t }]),
+ t,
+ t,
+ );
+ return { id: "owner-short", gen: "owner-short-take" };
+}
+
+describe("the proxy opens Shorts to accounts, and keeps the sign-up card for guests", () => {
+ it("a guest gets the sign-up card on every change, an empty History, and nobody's session", async () => {
+ for (const [method, p] of [
+ ["POST", "/api/shorts/sessions"],
+ ["POST", "/api/shorts/sessions/s1/segments/0"],
+ ["POST", "/api/shorts/sessions/s1/segments/0/primary"],
+ ["POST", "/api/shorts/sessions/s1/stitch"],
+ ["PATCH", "/api/shorts/sessions/s1"],
+ ["DELETE", "/api/shorts/sessions/s1"],
+ ["POST", "/api/shorts/presets"],
+ ["PATCH", "/api/shorts/presets/p1"],
+ ["DELETE", "/api/shorts/presets/p1"],
+ ] as const) {
+ const r = viaProxy(p, method);
+ expect(r.status, `${method} ${p}`).toBe(401);
+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");
+ expect((await r.json()).error).toBe(access.GUEST_RUN_MESSAGE);
+ }
+ expect(await viaProxy("/api/shorts/sessions").json()).toEqual({ items: [] });
+ expect(await viaProxy("/api/shorts/presets").json()).toEqual({ items: [] });
+ expect(viaProxy("/api/shorts/sessions/s1").status).toBe(401);
+ // The price check stays open to everyone; Enhance isn't offered to a visitor.
+ expect(passed(viaProxy("/api/shorts/estimate", "POST"))).toBe(true);
+ expect(viaProxy("/api/shorts/sessions/s1/segments/0/enhance", "POST").status).toBe(403);
+ });
+
+ it("an account reaches its own Shorts routes (the routes scope them); Enhance stays closed", async () => {
+ for (const [method, p] of [
+ ["GET", "/api/shorts/sessions"],
+ ["POST", "/api/shorts/sessions"],
+ ["GET", "/api/shorts/sessions/s1"],
+ ["PATCH", "/api/shorts/sessions/s1"],
+ ["DELETE", "/api/shorts/sessions/s1"],
+ ["POST", "/api/shorts/sessions/s1/segments/0"],
+ ["POST", "/api/shorts/sessions/s1/segments/0/primary"],
+ ["POST", "/api/shorts/sessions/s1/stitch"],
+ ["GET", "/api/shorts/presets"],
+ ["POST", "/api/shorts/presets"],
+ ["PATCH", "/api/shorts/presets/p1"],
+ ["DELETE", "/api/shorts/presets/p1"],
+ ] as const) {
+ expect(passed(viaProxy(p, method, "a")), `${method} ${p}`).toBe(true);
+ }
+ const e = viaProxy("/api/shorts/sessions/s1/segments/0/enhance", "POST", "a");
+ expect(e.status).toBe(403);
+ expect((await e.json()).code).toBe("own-gpu-tool");
+ });
+
+ it("the routes refuse a guest themselves, and Enhance refuses anyone but the owner", async () => {
+ const p = { id: "s1", index: "0" };
+ for (const [name, r] of [
+ ["create", () => sessionsRoute.POST(json("/api/shorts/sessions", "POST", {}))],
+ ["take", () => takeRoute.POST(json("/api/shorts/sessions/s1/segments/0", "POST", {}), params(p))],
+ ["primary", () => primaryRoute.POST(json("/api/shorts/sessions/s1/segments/0/primary", "POST", {}), params(p))],
+ ["stitch", () => stitchRoute.POST(json("/api/shorts/sessions/s1/stitch", "POST", {}), params(p))],
+ ["rename", () => sessionRoute.PATCH(json("/api/shorts/sessions/s1", "PATCH", { title: "x" }), params(p))],
+ ["delete", () => sessionRoute.DELETE(json("/api/shorts/sessions/s1", "DELETE"), params(p))],
+ ["preset", () => presetsRoute.POST(json("/api/shorts/presets", "POST", {}))],
+ ] as const) {
+ const res = await r();
+ expect(res.status, name).toBe(401);
+ expect(res.headers.get(access.GUEST_HEADER), name).toBe("1");
+ }
+ // A guest's reads have nothing of anyone's.
+ expect(await (await sessionsRoute.GET(json("/api/shorts/sessions", "GET"))).json()).toEqual({ items: [] });
+ expect(await (await presetsRoute.GET(json("/api/shorts/presets", "GET"))).json()).toEqual({ items: [] });
+ for (const who of [undefined, "a"]) {
+ const r = await enhanceRoute.POST(json("/api/shorts/sessions/s1/segments/0/enhance", "POST", {}, who), params(p));
+ expect(r.status).toBe(403);
+ expect((await r.json()).code).toBe("own-gpu-tool");
+ }
+ });
+});
+
+describe("an account makes, reopens and runs its own shorts on its own ComfyUI", () => {
+ let clip = "";
+ let id = "";
+ let view: View;
+ beforeAll(async () => {
+ clip = await upload("a", CLIP, "video/mp4", "dance.mp4");
+ });
+
+ it("prices it for its own GPU, never as a demo", async () => {
+ const r = await estimateRoute.POST(json("/api/shorts/estimate", "POST", short(clip), "a"));
+ expect(r.status, await r.clone().text()).toBe(200);
+ const e = (await r.json()) as { demo: boolean; segments: number };
+ expect(e.demo).toBe(false);
+ expect(e.segments).toBe(2);
+ });
+
+ it("runs a short end to end: every step is its own, on its ComfyUI, and the video is its own file", async () => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await create(short(clip, { requestId: "same-shorts-request-1" }), "a");
+ expect(r.status, await r.clone().text()).toBe(201);
+ id = ((await r.json()) as { id: string }).id;
+ view = await settle(id, "a");
+ const all = Object.values(view.generations);
+ expect(all.length).toBeGreaterThan(2);
+ for (const g of all) {
+ expect(accountOf(g.id), g.id).toBe(a);
+ expect(g.status, `${g.id} ${getGeneration(g.id)?.modelId} ${getGeneration(g.id)?.error ?? ""}`).toBe("succeeded");
+ }
+ // One run: its steps share a batch.
+ expect(new Set(all.map((g) => getGeneration(g.id)!.batchId)).size).toBe(1);
+ // Every step went to its own ComfyUI; nothing reached the install's.
+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBe(all.length);
+ expect(fetched.filter((u) => !u.endsWith("/system_stats"))).toEqual([]);
+ // The finished video is its own file, and it downloads.
+ const final = view.generations[view.stitches[0].final];
+ const out = final.outputs[0].url;
+ expect(out).toMatch(/^\/api\/files\/outputs\//);
+ expect(passed(viaProxy(out, "GET", "a"))).toBe(true);
+ // The session is the account's own project, never a row in the owner's table.
+ expect(store.getAccountProject(a, "shorts", id)).not.toBeNull();
+ expect(db().prepare("SELECT 1 FROM shorts_sessions WHERE id = ?").get(id)).toBeUndefined();
+ });
+
+ it("reopens it: its History lists it, and its page opens for it alone", async () => {
+ const list = (await (await sessionsRoute.GET(json("/api/shorts/sessions", "GET", undefined, "a"))).json()) as { items: { id: string; status: string; cover: { id: string } | null }[] };
+ expect(list.items.map((s) => s.id)).toEqual([id]);
+ expect(list.items[0].status).toBe("ready");
+ expect(list.items[0].cover?.id).toBe(view.stitches[0].final);
+ const r = await read(id, "a");
+ expect(r.status).toBe(200);
+ // Its page: the proxy and the page's own check find it for A, never for B or a guest.
+ expect(passed(viaProxy(`/shorts/${id}`, "GET", "a"))).toBe(true);
+ expect(viaProxy(`/shorts/${id}`, "GET", "b").status).toBe(404);
+ const h = (who: string) => new Headers({ host: "localhost:3000", cookie: cookies[who] });
+ expect(recordFor({ kind: "shorts", ids: [id] }, h("a"))).toBe(true);
+ expect(recordFor({ kind: "shorts", ids: [id] }, h("b"))).toBe(false);
+ });
+
+ it("a second click with the same request id gets the same short", async () => {
+ const r = await create(short(clip, { requestId: "same-shorts-request-1" }), "a");
+ expect(r.status).toBe(201);
+ expect(((await r.json()) as { id: string }).id).toBe(id);
+ });
+
+ it("a new take of a segment runs on its own GPU, can be picked, and is stitched again", async () => {
+ const r = await run(() => takeRoute.POST(json(`/api/shorts/sessions/${id}/segments/1`, "POST", { requestId: "take-request-0001" }, "a"), params({ id, index: "1" })));
+ expect(r.status, await r.clone().text()).toBe(201);
+ let v = await settle(id, "a");
+ const takes = v.segments[1].takes;
+ expect(takes.length).toBe(2);
+ expect(accountOf(takes[1].look)).toBe(a);
+ // Pick the new take, then stitch again.
+ const pick = await primaryRoute.POST(json(`/api/shorts/sessions/${id}/segments/1/primary`, "POST", { generationId: takes[1].look }, "a"), params({ id, index: "1" }));
+ expect(pick.status, await pick.clone().text()).toBe(200);
+ // Another session's take can't be picked here.
+ const wrong = await primaryRoute.POST(json(`/api/shorts/sessions/${id}/segments/1/primary`, "POST", { generationId: "owner-short-take" }, "a"), params({ id, index: "1" }));
+ expect(wrong.status).toBe(400);
+ const s = await run(() => stitchRoute.POST(json(`/api/shorts/sessions/${id}/stitch`, "POST", { requestId: "stitch-request-01" }, "a"), params({ id })));
+ expect(s.status, await s.clone().text()).toBe(201);
+ v = await settle(id, "a");
+ expect(v.stitches.length).toBe(2);
+ const final = getGeneration(v.stitches[1].final)!;
+ expect(final.status).toBe("succeeded");
+ expect(final.request.account).toBe(a);
+ // Renamed, it keeps its own name.
+ const named = await sessionRoute.PATCH(json(`/api/shorts/sessions/${id}`, "PATCH", { title: "Clay dance" }, "a"), params({ id }));
+ expect(named.status).toBe(200);
+ expect(((await (await read(id, "a")).json()) as View).title).toBe("Clay dance");
+ });
+
+ it("another account never sees, opens, changes or runs it", async () => {
+ // Not in B's History; its session reads as gone.
+ expect(await (await sessionsRoute.GET(json("/api/shorts/sessions", "GET", undefined, "b"))).json()).toEqual({ items: [] });
+ expect((await read(id, "b")).status).toBe(404);
+ // No take, no stitch, no pick, no rename, no delete.
+ fake.log.length = 0;
+ const p = { id, index: "0" };
+ expect((await takeRoute.POST(json(`/api/shorts/sessions/${id}/segments/0`, "POST", {}, "b"), params(p))).status).toBe(404);
+ expect((await stitchRoute.POST(json(`/api/shorts/sessions/${id}/stitch`, "POST", {}, "b"), params(p))).status).toBe(404);
+ expect((await primaryRoute.POST(json(`/api/shorts/sessions/${id}/segments/0/primary`, "POST", { generationId: view.segments[0].primary }, "b"), params(p))).status).toBe(404);
+ expect((await sessionRoute.PATCH(json(`/api/shorts/sessions/${id}`, "PATCH", { title: "mine" }, "b"), params(p))).status).toBe(404);
+ expect((await sessionRoute.DELETE(json(`/api/shorts/sessions/${id}`, "DELETE", undefined, "b"), params(p))).status).toBe(404);
+ expect(fake.log.some((e) => e.path === "/prompt")).toBe(false);
+ expect(store.getAccountProject(a, "shorts", id)).not.toBeNull();
+ // Its runs and files: 403 through the proxy.
+ const out = getGeneration(view.stitches[0].final)!.outputs[0].url;
+ expect(viaProxy(`/api/generations/${view.stitches[0].final}`, "GET", "b").status).toBe(403);
+ expect(viaProxy(out, "GET", "b").status).toBe(403);
+ // A's clip in B's short: refused before anything is planned or sent.
+ const r = await sessionsRoute.POST(json("/api/shorts/sessions", "POST", short(clip), "b"));
+ expect(r.status).toBe(403);
+ expect((await r.json()).code).toBe("input-not-yours");
+ // The same request id from B is B's own request, never A's short.
+ const bClip = await upload("b", CLIP, "video/mp4", "b.mp4");
+ const bRun = await create(short(bClip, { requestId: "same-shorts-request-1" }), "b");
+ expect(bRun.status, await bRun.clone().text()).toBe(201);
+ const bId = ((await bRun.json()) as { id: string }).id;
+ expect(bId).not.toBe(id);
+ expect(store.getAccountProject(b, "shorts", bId)).not.toBeNull();
+ expect(store.getAccountProject(a, "shorts", bId)).toBeNull();
+ await settle(bId, "b");
+ });
+
+ it("the owner's sessions and files are never reachable", async () => {
+ const owner = ownerSession();
+ // Not in its History, gone by id, and its page is a 404.
+ const list = (await (await sessionsRoute.GET(json("/api/shorts/sessions", "GET", undefined, "a"))).json()) as { items: { id: string }[] };
+ expect(list.items.map((s) => s.id)).not.toContain(owner.id);
+ expect((await read(owner.id, "a")).status).toBe(404);
+ expect(viaProxy(`/shorts/${owner.id}`, "GET", "a").status).toBe(404);
+ expect(recordFor({ kind: "shorts", ids: [owner.id] }, new Headers({ host: "localhost:3000", cookie: cookies.a }))).toBe(false);
+ // Nothing runs on it, nothing changes it.
+ const p = { id: owner.id, index: "0" };
+ expect((await takeRoute.POST(json(`/api/shorts/sessions/${owner.id}/segments/0`, "POST", {}, "a"), params(p))).status).toBe(404);
+ expect((await stitchRoute.POST(json(`/api/shorts/sessions/${owner.id}/stitch`, "POST", {}, "a"), params(p))).status).toBe(404);
+ expect((await sessionRoute.PATCH(json(`/api/shorts/sessions/${owner.id}`, "PATCH", { title: "mine" }, "a"), params(p))).status).toBe(404);
+ expect((await sessionRoute.DELETE(json(`/api/shorts/sessions/${owner.id}`, "DELETE", undefined, "a"), params(p))).status).toBe(404);
+ expect(db().prepare("SELECT title FROM shorts_sessions WHERE id = ?").get(owner.id)).toEqual({ title: "The owner's short" });
+ expect(getGeneration(owner.gen)?.status).toBe("succeeded");
+ // The owner's file in its run is refused; its run's file is closed to it.
+ const ownerClip = (db().prepare("SELECT source_json FROM shorts_sessions WHERE id = ?").get(owner.id) as { source_json: string }).source_json;
+ const url = (JSON.parse(ownerClip) as { url: string }).url;
+ const r = await sessionsRoute.POST(json("/api/shorts/sessions", "POST", short(url), "a"));
+ expect(r.status).toBe(403);
+ expect((await r.json()).code).toBe("input-not-yours");
+ expect(viaProxy(url, "GET", "a").status).toBe(403);
+ // The owner still sees it.
+ const mine = (await (await sessionsRoute.GET(json("/api/shorts/sessions", "GET", undefined, "owner"))).json()) as { items: { id: string }[] };
+ expect(mine.items.map((s) => s.id)).toEqual([owner.id]);
+ });
+
+ it("deletes its own short and its runs for good (an account has no Trash)", async () => {
+ const gens = Object.keys(((await (await read(id, "a")).json()) as View).generations);
+ const r = await sessionRoute.DELETE(json(`/api/shorts/sessions/${id}`, "DELETE", undefined, "a"), params({ id }));
+ expect(r.status).toBe(200);
+ expect(store.getAccountProject(a, "shorts", id)).toBeNull();
+ for (const g of gens) expect(getGeneration(g, { includeDeleted: true }), g).toBeFalsy();
+ expect((await read(id, "a")).status).toBe(404);
+ });
+});
+
+describe("an account's presets are its own", () => {
+ it("makes a preset from its own pictures, and nobody else sees or uses it", async () => {
+ const pic = await upload("a", TINY_PNG, "image/png", "look.png");
+ const r = await presetsRoute.POST(json("/api/shorts/presets", "POST", { name: "My clay", references: [pic] }, "a"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const preset = (await r.json()) as { id: string; name: string; references: string[] };
+ expect(preset).toMatchObject({ name: "My clay", references: [pic] });
+ const mine = (await (await presetsRoute.GET(json("/api/shorts/presets", "GET", undefined, "a"))).json()) as { items: { id: string }[] };
+ expect(mine.items.map((p) => p.id)).toEqual([preset.id]);
+ // B: not in its list, not changeable, not usable.
+ expect(await (await presetsRoute.GET(json("/api/shorts/presets", "GET", undefined, "b"))).json()).toEqual({ items: [] });
+ expect((await presetRoute.PATCH(json(`/api/shorts/presets/${preset.id}`, "PATCH", { name: "mine" }, "b"), params({ id: preset.id }))).status).toBe(404);
+ expect((await presetRoute.DELETE(json(`/api/shorts/presets/${preset.id}`, "DELETE", undefined, "b"), params({ id: preset.id }))).status).toBe(404);
+ const bClip = await upload("b", CLIP, "video/mp4", "b2.mp4");
+ const use = await estimateRoute.POST(json("/api/shorts/estimate", "POST", short(bClip, { presetId: preset.id }), "b"));
+ expect(use.status).toBe(400);
+ // A's picture in B's preset: refused.
+ const steal = await presetsRoute.POST(json("/api/shorts/presets", "POST", { references: [pic] }, "b"));
+ expect(steal.status).toBe(403);
+ // A renames and deletes its own.
+ const named = await presetRoute.PATCH(json(`/api/shorts/presets/${preset.id}`, "PATCH", { name: "Clay two" }, "a"), params({ id: preset.id }));
+ expect(((await named.json()) as { name: string }).name).toBe("Clay two");
+ expect((await presetRoute.DELETE(json(`/api/shorts/presets/${preset.id}`, "DELETE", undefined, "a"), params({ id: preset.id }))).status).toBe(204);
+ expect(store.getAccountProject(a, "shorts-preset", preset.id)).toBeNull();
+ });
+
+ it("never reaches the owner's presets", async () => {
+ const t = Date.now();
+ const ownerPic = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "owner-look.png" }).url;
+ db()
+ .prepare("INSERT INTO shorts_presets (id, name, description, references_json, created_at, updated_at) VALUES ('custom-owner01', 'Owner look', '', ?, ?, ?)")
+ .run(JSON.stringify([ownerPic]), t, t);
+ const list = (await (await presetsRoute.GET(json("/api/shorts/presets", "GET", undefined, "a"))).json()) as { items: { id: string }[] };
+ expect(list.items.map((p) => p.id)).not.toContain("custom-owner01");
+ expect((await presetRoute.PATCH(json("/api/shorts/presets/custom-owner01", "PATCH", { name: "mine" }, "a"), params({ id: "custom-owner01" }))).status).toBe(404);
+ expect((await presetRoute.DELETE(json("/api/shorts/presets/custom-owner01", "DELETE", undefined, "a"), params({ id: "custom-owner01" }))).status).toBe(404);
+ const clip = await upload("a", CLIP, "video/mp4", "own.mp4");
+ expect((await estimateRoute.POST(json("/api/shorts/estimate", "POST", short(clip, { presetId: "custom-owner01" }), "a"))).status).toBe(400);
+ expect((await sessionsRoute.POST(json("/api/shorts/sessions", "POST", short(clip, { presetId: "custom-owner01" }), "a"))).status).toBe(400);
+ expect(db().prepare("SELECT name FROM shorts_presets WHERE id = 'custom-owner01'").get()).toEqual({ name: "Owner look" });
+ // The owner's own list still has it.
+ const owner = (await (await presetsRoute.GET(json("/api/shorts/presets", "GET", undefined, "owner"))).json()) as { items: { id: string }[] };
+ expect(owner.items.map((p) => p.id)).toContain("custom-owner01");
+ });
+});
+
+describe("an account's limits", () => {
+ it("asks an account with neither a GPU nor a key to connect one, before anything is made", async () => {
+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "c.mp4" }).url);
+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const r = await sessionsRoute.POST(json("/api/shorts/sessions", "POST", short(own), "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);
+ expect(store.listAccountProjects(c, "shorts")).toEqual([]);
+ });
+
+ it("keeps runs going at once, a run's weight, and how many shorts it keeps", async () => {
+ const clip = await upload("a", CLIP, "video/mp4", "limits.mp4");
+ 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 (?, 'shorts', 'oss-trim', 'open', 'comfyui', 'trim', 'video', 'queued', ?, '[]', ?, ?)",
+ );
+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-shorts-${i}`, JSON.stringify({ feature: "shorts", modelId: "oss-trim", account: a }), now, now);
+ const r = await sessionsRoute.POST(json("/api/shorts/sessions", "POST", short(clip), "a"));
+ expect(r.status).toBe(429);
+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);
+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-shorts-%'").run();
+ // A run body over what an account's run may weigh is refused before it is read.
+ const big = new Request("http://localhost:3000/api/shorts/sessions", { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });
+ expect((await sessionsRoute.POST(big)).status).toBe(413);
+ // A full account starts nothing: delete one to make another.
+ const kept = store.listAccountProjects(a, "shorts").length;
+ for (let i = kept; i < store.ACCOUNT_PROJECT_LIMITS.projects; i++) store.createAccountProject(a, "shorts", { name: `filler ${i}`, data: {} });
+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const full = await sessionsRoute.POST(json("/api/shorts/sessions", "POST", short(clip), "a"));
+ expect(full.status).toBe(409);
+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);
+ // Its History skips what isn't a short of its own.
+ expect(((await (await sessionsRoute.GET(json("/api/shorts/sessions", "GET", undefined, "a"))).json()) as { items: unknown[] }).items).toEqual([]);
+ });
+
+ it("goes with the account", async () => {
+ await purgeAccount(b);
+ expect(store.listAccountProjects(b, "shorts")).toEqual([]);
+ });
+});
diff --git a/tests/e2e/shorts-accounts-live.mjs b/tests/e2e/shorts-accounts-live.mjs
new file mode 100644
index 00000000..614eeaa8
--- /dev/null
+++ b/tests/e2e/shorts-accounts-live.mjs
@@ -0,0 +1,129 @@
+// Shorts Studio for visitors (a studio with a password and public sign-up, fuobe.com by default), through its routes and
+// in a browser. A guest: the sign-up card on every change, an empty History, the price check open, no "isn't available
+// here" note, and the sign-up card when it chooses a video or a preset of its own. A signed-in account (a throwaway one
+// this script makes and deletes): its own empty History and presets, nobody else's short (404), Enhance not offered, the
+// page's upload, Create a preset and Generate on, and the connect card when it has neither a GPU nor a key.
+// No run is started (that needs the account's own GPU or key).
+// Usage: node tests/e2e/shorts-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 estimate = { engine: "open", presetId: "shorts-claymation", source: { url: "/api/files/placeholder.mp4", duration: 10, width: 720, height: 1280 }, range: { start: 0, end: 10 }, aspectRatio: "9:16", language: "auto" };
+
+/** The route checks, as a guest (`req`: a context's request, signed out) or as the account (signed in). */
+async function routes(req, who) {
+ const send = (method, p, data) => req.fetch(`${app}${p}`, { method, headers: { origin: app, "content-type": "application/json" }, ...(data !== undefined && { data }) });
+ const body = async (r) => r.json().catch(() => ({}));
+ const sessions = await send("GET", "/api/shorts/sessions");
+ check(`${who}: History is empty`, sessions.status() === 200 && JSON.stringify(await body(sessions)) === '{"items":[]}', String(sessions.status()));
+ const presets = await send("GET", "/api/shorts/presets");
+ check(`${who}: its presets are empty`, presets.status() === 200 && JSON.stringify(await body(presets)) === '{"items":[]}', String(presets.status()));
+ const price = await send("POST", "/api/shorts/estimate", estimate);
+ const e = await body(price);
+ check(`${who}: the price check works, never as a demo`, price.status() === 200 && e.demo === false && e.segments === 2, `${price.status()} ${JSON.stringify(e).slice(0, 80)}`);
+ const enhance = await send("POST", "/api/shorts/sessions/nope/segments/0/enhance", {});
+ check(`${who}: Enhance isn't offered`, enhance.status() === 403 && (await body(enhance)).code === "own-gpu-tool", String(enhance.status()));
+ const page = await send("GET", "/shorts/nope-not-a-short");
+ check(`${who}: an unknown short's page is a 404`, page.status() === 404, String(page.status()));
+ if (who === "guest") {
+ for (const [method, p] of [
+ ["POST", "/api/shorts/sessions"],
+ ["POST", "/api/shorts/sessions/nope/segments/0"],
+ ["POST", "/api/shorts/sessions/nope/stitch"],
+ ["PATCH", "/api/shorts/sessions/nope"],
+ ["DELETE", "/api/shorts/sessions/nope"],
+ ["POST", "/api/shorts/presets"],
+ ]) {
+ const r = await send(method, p, {});
+ check(`guest: ${method} ${p} asks to sign up`, r.status() === 401 && r.headers()["x-fuobe-guest"] === "1", String(r.status()));
+ }
+ const one = await send("GET", "/api/shorts/sessions/nope");
+ check("guest: a short by id is closed", one.status() === 401, String(one.status()));
+ return;
+ }
+ // The account reaches its routes, which answer with its own only.
+ const one = await send("GET", "/api/shorts/sessions/nope");
+ check("account: another's or no short reads as gone", one.status() === 404, String(one.status()));
+ for (const [method, p, data] of [
+ ["POST", "/api/shorts/sessions/nope/segments/0", {}],
+ ["POST", "/api/shorts/sessions/nope/stitch", {}],
+ ["POST", "/api/shorts/sessions/nope/segments/0/primary", { generationId: "x" }],
+ ["PATCH", "/api/shorts/sessions/nope", { title: "x" }],
+ ["DELETE", "/api/shorts/sessions/nope", undefined],
+ ["PATCH", "/api/shorts/presets/nope", { name: "x" }],
+ ]) {
+ const r = await send(method, p, data);
+ check(`account: ${method} ${p} is not found`, r.status() === 404, String(r.status()));
+ }
+ const bad = await send("POST", "/api/shorts/sessions", {});
+ check("account: its run reaches the route (a bad request is a 400)", bad.status() === 400, String(bad.status()));
+ const notMine = await send("POST", "/api/shorts/presets", { references: ["/api/files/not-mine.png"] });
+ check("account: a picture that isn't its own makes no preset", notMine.status() >= 400 && notMine.status() < 500 && notMine.status() !== 401, String(notMine.status()));
+}
+
+const browser = await launch();
+const email = `shorts-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 } });
+try {
+ const page = await context.newPage();
+ await routes(page.request, "guest");
+ const look = async (who) => {
+ await page.goto(`${app}/shorts`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(3000);
+ check(`${who}: no "isn't available here" note`, (await page.getByText("Shorts Studio isn't available here").count()) === 0);
+ check(`${who}: no price says "Not available here"`, (await page.getByText("Not available here").count()) === 0);
+ const choose = page.getByRole("button", { name: "Choose a video" });
+ check(`${who}: the clip drop is on`, (await choose.count()) > 0 && (await choose.first().isEnabled()));
+ check(`${who}: Create a preset is offered`, (await page.getByText("Create a preset").count()) > 0);
+ const generate = page.getByRole("button", { name: /Generate short/ });
+ check(`${who}: Generate is on`, (await generate.count()) > 0 && (await generate.first().isEnabled()));
+ if (shots) await page.screenshot({ path: path.join(shots, `shorts-${who}.png`), fullPage: false });
+ // Choosing a video asks first: the sign-up card for a guest, the connect card for an account with no GPU or key.
+ await choose.first().click();
+ await page.waitForTimeout(1500);
+ const card = who === "guest" ? /Create a free account/ : /Connect your GPU|your own files/;
+ check(`${who}: choosing a video opens the ${who === "guest" ? "sign-up" : "connect"} card`, (await page.getByText(card).count()) > 0);
+ if (shots) await page.screenshot({ path: path.join(shots, `shorts-${who}-choose.png`) });
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(500);
+ await page.goto(`${app}/shorts?tab=history`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(2500);
+ check(`${who}: History says there are no shorts yet`, (await page.getByText("No shorts yet").count()) > 0);
+ };
+ await look("guest");
+
+ // A throwaway account (signed in in this browser), then the same checks.
+ 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()));
+ if (signedUp) {
+ await routes(page.request, "account");
+ await look("account");
+ }
+} 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()}`);
+ check("deleted the throwaway account", del.status() === 204 || del.ok(), String(del.status()));
+ }
+ await browser.close();
+}
+console.log(failures.length ? `${failures.length} failed` : "all ok");
+process.exit(failures.length ? 1 : 0);
diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.ts
index 28770233..c3bafb24 100644
--- a/tests/helpers/fake-comfy-runner.ts
+++ b/tests/helpers/fake-comfy-runner.ts
@@ -7,8 +7,8 @@
*
* Options for tests: `loras` (GET /models/loras), `delayMs` (until the history says done), `drip` (the history
* answers one byte every 2 s, never finishing), `huge` (/view streams without end), `promptId` (the job id /prompt
- * answers), `missing` (a file /prompt answers "not in list" for), `output` ("video", "image" or "model3d": a one-triangle
- * GLB), `layers` (the
+ * answers), `missing` (a file /prompt answers "not in list" for), `output` ("video", "image", "model3d": a one-triangle
+ * GLB, or "both": a clip and a picture, as a step that cuts a clip and keeps its first frame), `layers` (the
* history lists that many Qwen-Image-Layered layers, node 60), `frames` (an EXR export: a preview clip, node 5, and
* that many frames, node 3), `historyError` (/history answers HTTP 500 and then sends nothing), `uploadStatus` (the HTTP
* status /upload/image answers, e.g. 500 to fail every upload), `refuseClass` (/prompt answers "not in list" for a graph with
@@ -27,7 +27,7 @@ export interface FakeComfyOptions {
huge?: boolean;
promptId?: string;
missing?: string;
- output?: "video" | "image" | "model3d";
+ output?: "video" | "image" | "model3d" | "both";
layers?: number;
frames?: number;
historyError?: boolean;
@@ -185,6 +185,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
if (opts.frames) return json(200, { [id]: { ...done, outputs: { "5": { gifs: list(1, "mp4") }, "3": { images: list(opts.frames, "exr") } } } });
if (opts.output === "model3d") return json(200, { [id]: { ...done, outputs: { "900": { "3d": [{ filename: "fake_00001_.glb", subfolder: "3D", type: "output" }] } } } });
if (opts.nodes?.length) return json(200, { [id]: { ...done, outputs: Object.fromEntries(opts.nodes.map((n, i) => [n, { gifs: [{ filename: `fake_${n}_${i + 1}.mp4`, subfolder: "", type: "output" }] }])) } });
+ if (opts.output === "both") return json(200, { [id]: { ...done, outputs: { "900": { gifs: list(1, "mp4") }, "901": { images: list(1, "png") } } } });
const file = opts.output === "image" ? { filename: "fake_00001_.png", subfolder: "", type: "output" } : { filename: "fake_00001.mp4", subfolder: "", type: "output" };
const key = opts.output === "image" ? "images" : "gifs";
return json(200, { [id]: { status: { completed: true, status_str: "success" }, outputs: { "900": { [key]: [file] } } } });
diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.ts
index ff5e2699..99ca6ec1 100644
--- a/tests/public-signup-tools.test.ts
+++ b/tests/public-signup-tools.test.ts
@@ -110,14 +110,15 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
for (const p of ["/api/turnaround/estimate", "/api/turnaround?preview=1", "/api/audio-tools?preview=1"]) expect(passed(proxy(req(p, { method: "POST" }))), p).toBe(true);
// Signing up wouldn't run these (an account's own GPU or key doesn't either): the account's answer, not the card.
- for (const p of ["/api/turnaround", "/api/audio-tools", "/api/shorts/sessions", "/api/katana", "/api/marketing/runs", "/api/layers/l1/jobs", "/api/layout/plan"]) {
+ for (const p of ["/api/turnaround", "/api/audio-tools", "/api/katana", "/api/marketing/runs", "/api/layers/l1/jobs", "/api/layout/plan"]) {
const r = proxy(req(p, { method: "POST" }));
expect(r.status, p).toBe(403);
expect(r.headers.get(access.GUEST_HEADER), p).toBeNull();
expect(await r.json(), p).toEqual({ error: access.OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" });
}
- // The studios' runs, an upload and a save to the library: signing up is the next step there.
- for (const p of ["/api/generations", "/api/media/probe", "/api/audio-tools/export?offset=0", "/api/canvases"]) {
+ // The studios' runs, a tool an account runs on its own GPU (Shorts), an upload and a save to the library: signing up
+ // is the next step there.
+ for (const p of ["/api/generations", "/api/shorts/sessions", "/api/media/probe", "/api/audio-tools/export?offset=0", "/api/canvases"]) {
const r = proxy(req(p, { method: "POST" }));
expect(r.status, p).toBe(401);
expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");
diff --git a/tests/regenerate-held.test.ts b/tests/regenerate-held.test.ts
index 1b159dcc..97e88740 100644
--- a/tests/regenerate-held.test.ts
+++ b/tests/regenerate-held.test.ts
@@ -153,10 +153,12 @@ describe("Open-H3 Regenerate while it is held", () => {
const source = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "beach day.mp4" }).url;
const s = await shorts.createSession({ engine: "open", presetId: "shorts-claymation", source: { url: source, name: "beach day.mp4" }, range: { start: 0, end: 12 }, aspectRatio: "9:16", language: "auto" } as never);
const takes = s.segments[1].takes.length;
- await refused(() => enhanceRoute.POST(json("POST", { requestId: "held-enhance-1" }), params({ id: s.id, index: "1" })), R.REGEN_COPY.heldEnhance);
+ // The owner's Enhance (anyone else's is refused before it is read: tests/account-shorts.test.ts).
+ const asOwner = (body?: unknown) => new Request("http://localhost:3000/api", { method: "POST", headers: { cookie: owner, host: "localhost:3000", "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+ await refused(() => enhanceRoute.POST(asOwner({ requestId: "held-enhance-1" }), params({ id: s.id, index: "1" })), R.REGEN_COPY.heldEnhance);
expect(shorts.getSession(s.id).segments[1].takes).toHaveLength(takes);
// A missing segment is still not found.
- expect((await enhanceRoute.POST(json("POST"), params({ id: s.id, index: "9" }))).status).toBe(404);
+ expect((await enhanceRoute.POST(asOwner(), params({ id: s.id, index: "9" }))).status).toBe(404);
});
it("refuses Faceless's Regenerate to 1080p on an episode", async () => {