The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Character Swap Studio: accounts keep projects and run them on their own GPU or key
Adarsh3a91b26d2510
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex ab050850..e9a41edc 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -310,6 +310,15 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188the browser ("Record turntable"), not on the server. Refine detail, the TRELLIS.2 final, Idol 3D's other sides andFilm it photoreal stay the owner's, and Retexture opens once its cloud models pass a live call. On this install'sGPUs (hosted runs) 3D isn't offered yet. A guest gets the sign-up card.+- **Character Swap Studio.** An account keeps Character Swap projects of its own (`/character-swap`; `GET`/`POST+ /api/swap-studio/projects`, `GET`/`PATCH`/`DELETE /api/swap-studio/projects/<id>`): its own only (another account's,+ or the owner's, reads as 404; a guest gets the sign-up card), up to 50 of 1 MB each and 120 saves a minute, deleted+ with the account. Every job in a project (a clip's 24 fps copy or browser copy, its words, a mask, a scene anchor,+ queued takes, Sharpen, the assembly) is a run of its own on the account's ComfyUI, or on its own fal.ai key on the+ cloud engine, with only its own uploads and results, after the same checks as Genjutsu's. A queue counts once against+ 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`.- **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)/character-swap/[id]/page.tsx b/src/app/(studio)/character-swap/[id]/page.tsxindex 617a9a05..f9ccd361 100644--- a/src/app/(studio)/character-swap/[id]/page.tsx+++ b/src/app/(studio)/character-swap/[id]/page.tsx@@ -2,13 +2,14 @@ import type { Metadata } from "next";import { notFound } from "next/navigation";import { Suspense } from "react";import { SwapWorkbench } from "@/components/swap-studio/workbench";-import { recordExists } from "@/server/records";+import { projectPageOpens } from "@/server/swap-studio-account";export const metadata: Metadata = { title: "Character Swap" };+/** A project's page: the owner's projects, or a signed-in account's own (its projects only). */async function Project({ params }: { params: PageProps<"/character-swap/[id]">["params"] }) {const { id } = await params;- if (!recordExists({ kind: "swap-project", ids: [id] })) notFound();+ if (!(await projectPageOpens(id))) notFound();return <SwapWorkbench id={id} />;}diff --git a/src/app/api/swap-studio/projects/[id]/anchors/route.ts b/src/app/api/swap-studio/projects/[id]/anchors/route.tsindex 84272ca9..b01d4de2 100644--- a/src/app/api/swap-studio/projects/[id]/anchors/route.ts+++ b/src/app/api/swap-studio/projects/[id]/anchors/route.ts@@ -1,10 +1,12 @@import { AnchorSchema, makeAnchor } from "@/server/swap-studio";-import { body, handle } from "@/server/shorts-schemas";+import { jobRoute } from "@/server/swap-studio-account";-/** A scene anchor for a shot (or a reference for a segment): your character put into its first frame. */+const run = jobRoute(AnchorSchema, "Pick a shot", makeAnchor);++/**+ * A scene anchor for a shot (or a reference for a segment): your character put into its first frame. An account's on its+ * own GPU or key (src/server/swap-studio-account.ts).+ */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/anchors">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(makeAnchor(id, await body(request, AnchorSchema, "Pick a shot")), { status: 201 });- }, request);+ return run(request, ctx);}diff --git a/src/app/api/swap-studio/projects/[id]/assemble/route.ts b/src/app/api/swap-studio/projects/[id]/assemble/route.tsindex 6ed6628b..14aaad63 100644--- a/src/app/api/swap-studio/projects/[id]/assemble/route.ts+++ b/src/app/api/swap-studio/projects/[id]/assemble/route.ts@@ -1,16 +1,17 @@import { ORIGINAL_SOUND_IDS } from "@/lib/av/original-sound";import { z } from "zod";-import { body, handle } from "@/server/shorts-schemas";import { assemble } from "@/server/swap-studio";+import { jobRoute } from "@/server/swap-studio-account";/** originalSound: what of the clip's sound goes back (src/lib/av/original-sound.ts). */const Assemble = z.object({ clipId: z.string().min(1).max(80), originalSound: z.enum(ORIGINAL_SOUND_IDS).optional() });-/** Assemble a clip: its chosen takes over the original timeline, with the clip's own sound. */+const run = jobRoute(Assemble, "Pick a clip", (id, b) => assemble(id, b.clipId, { originalSound: b.originalSound }));++/**+ * Assemble a clip: its chosen takes over the original timeline, with the clip's own sound. An account's on its own GPU or+ * key (src/server/swap-studio-account.ts); the result is one of its runs, to open and download.+ */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/assemble">) {- return handle(async () => {- const { id } = await ctx.params;- const b = await body(request, Assemble, "Pick a clip");- return Response.json(assemble(id, b.clipId, { originalSound: b.originalSound }), { status: 201 });- }, request);+ return run(request, ctx);}diff --git a/src/app/api/swap-studio/projects/[id]/clips/route.ts b/src/app/api/swap-studio/projects/[id]/clips/route.tsindex 8f095aea..c1131498 100644--- a/src/app/api/swap-studio/projects/[id]/clips/route.ts+++ b/src/app/api/swap-studio/projects/[id]/clips/route.ts@@ -1,10 +1,12 @@-import { body, handle } from "@/server/shorts-schemas";import { addClip, ClipSchema } from "@/server/swap-studio";+import { jobRoute } from "@/server/swap-studio-account";-/** Add an uploaded clip (MP4, MOV, MKV, WebM or AVI, at most 149.66 s); on your GPU its 24 fps copy starts now. */+const run = jobRoute(ClipSchema, "Upload a clip first", addClip, { files: (b) => [b.url] });++/**+ * Add an uploaded clip (MP4, MOV, MKV, WebM or AVI, at most 149.66 s); on your GPU its 24 fps copy starts now. An+ * account adds its own upload only, and its copy runs on its own GPU (src/server/swap-studio-account.ts).+ */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/clips">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(await addClip(id, await body(request, ClipSchema, "Upload a clip first")), { status: 201 });- }, request);+ return run(request, ctx);}diff --git a/src/app/api/swap-studio/projects/[id]/decisions/route.ts b/src/app/api/swap-studio/projects/[id]/decisions/route.tsindex 7fafdabf..2e74cc63 100644--- a/src/app/api/swap-studio/projects/[id]/decisions/route.ts+++ b/src/app/api/swap-studio/projects/[id]/decisions/route.ts@@ -1,13 +1,17 @@import { connection } from "next/server";-import { handle } from "@/server/shorts-schemas";import { decisions } from "@/server/swap-studio";+import { asViewer, guestProjectRead } from "@/server/swap-studio-account";/** "Export decisions": every clip's review and every take's favourite, decision and notes, as a JSON download. */-export async function GET(_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/decisions">) {+export async function GET(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/decisions">) {await connection();- return handle(async () => {- const out = decisions((await ctx.params).id);- const name = out.project.replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "character-swap";- return new Response(JSON.stringify(out, null, 2), { headers: { "Content-Type": "application/json; charset=utf-8", "Content-Disposition": `attachment; filename="${name}-decisions.json"` } });- });+ return asViewer(+ request,+ async () => {+ const out = decisions((await ctx.params).id);+ const name = out.project.replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "character-swap";+ return new Response(JSON.stringify(out, null, 2), { headers: { "Content-Type": "application/json; charset=utf-8", "Content-Disposition": `attachment; filename="${name}-decisions.json"` } });+ },+ { guest: guestProjectRead },+ );}diff --git a/src/app/api/swap-studio/projects/[id]/estimate/route.ts b/src/app/api/swap-studio/projects/[id]/estimate/route.tsindex 143df68c..b458d868 100644--- a/src/app/api/swap-studio/projects/[id]/estimate/route.ts+++ b/src/app/api/swap-studio/projects/[id]/estimate/route.ts@@ -1,9 +1,12 @@import { connection } from "next/server";-import { handle } from "@/server/shorts-schemas";import { estimateProject } from "@/server/swap-studio";+import { asViewer, guestProjectRead } from "@/server/swap-studio-account";-/** Prices before running: one take of each segment, each shot's and the project's queue, masks, anchors, words and assembly. */-export async function GET(_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/estimate">) {+/**+ * Prices before running: one take of each segment, each shot's and the project's queue, masks, anchors, words and+ * assembly. An account's are priced as its runs go: on its own GPU, or its own key (never a demo).+ */+export async function GET(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/estimate">) {await connection();- return handle(async () => Response.json(estimateProject((await ctx.params).id)));+ return asViewer(request, async () => Response.json(estimateProject((await ctx.params).id)), { guest: guestProjectRead });}diff --git a/src/app/api/swap-studio/projects/[id]/masks/route.ts b/src/app/api/swap-studio/projects/[id]/masks/route.tsindex 6133d3f9..1bbaf2e2 100644--- a/src/app/api/swap-studio/projects/[id]/masks/route.ts+++ b/src/app/api/swap-studio/projects/[id]/masks/route.ts@@ -1,10 +1,12 @@-import { body, handle } from "@/server/shorts-schemas";import { makeMask, MaskSchema } from "@/server/swap-studio";+import { jobRoute } from "@/server/swap-studio-account";-/** Who to swap, as a mask: Track shot (from a frame to the shot's end) or Update frame — a new mask version. */+const run = jobRoute(MaskSchema, "Pick a shot, a frame and who to swap", makeMask);++/**+ * Who to swap, as a mask: Track shot (from a frame to the shot's end) or Update frame — a new mask version. An account's+ * on its own GPU or key (src/server/swap-studio-account.ts).+ */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/masks">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(makeMask(id, await body(request, MaskSchema, "Pick a shot, a frame and who to swap")), { status: 201 });- }, request);+ return run(request, ctx);}diff --git a/src/app/api/swap-studio/projects/[id]/prepare/route.ts b/src/app/api/swap-studio/projects/[id]/prepare/route.tsindex e3167f27..9b5ac7d2 100644--- a/src/app/api/swap-studio/projects/[id]/prepare/route.ts+++ b/src/app/api/swap-studio/projects/[id]/prepare/route.ts@@ -1,13 +1,15 @@import { z } from "zod";-import { body, handle } from "@/server/shorts-schemas";import { prepareClip } from "@/server/swap-studio";+import { jobRoute } from "@/server/swap-studio-account";const Prepare = z.object({ clipId: z.string().min(1).max(80) });-/** Your GPU: make the clip's 24 fps copy (again). The cloud: its browser copy, when the page can't play the clip. */+const run = jobRoute(Prepare, "Pick a clip", (id, b) => prepareClip(id, b.clipId), { status: 200 });++/**+ * Your GPU: make the clip's 24 fps copy (again). The cloud: its browser copy, when the page can't play the clip. An+ * account's on its own GPU or key (src/server/swap-studio-account.ts).+ */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/prepare">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(prepareClip(id, (await body(request, Prepare, "Pick a clip")).clipId));- }, request);+ return run(request, ctx);}diff --git a/src/app/api/swap-studio/projects/[id]/queue/route.ts b/src/app/api/swap-studio/projects/[id]/queue/route.tsindex 522c60c4..ae9514e8 100644--- a/src/app/api/swap-studio/projects/[id]/queue/route.ts+++ b/src/app/api/swap-studio/projects/[id]/queue/route.ts@@ -1,10 +1,13 @@-import { body, handle } from "@/server/shorts-schemas";import { QueueSchema, queueTakes } from "@/server/swap-studio";+import { jobRoute } from "@/server/swap-studio-account";-/** Queue segment / Queue from here / Queue all segments: a take for each, continuations waiting for what they continue from. */+const run = jobRoute(QueueSchema, "Pick a segment to queue", queueTakes);++/**+ * Queue segment / Queue from here / Queue all segments: a take for each, continuations waiting for what they continue+ * from. An account's queue is one run on its own GPU or key, every take checked before any starts+ * (src/server/swap-studio-account.ts).+ */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/queue">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(queueTakes(id, await body(request, QueueSchema, "Pick a segment to queue")), { status: 201 });- }, request);+ return run(request, ctx);}diff --git a/src/app/api/swap-studio/projects/[id]/route.ts b/src/app/api/swap-studio/projects/[id]/route.tsindex ac49a0fd..fc233f4d 100644--- a/src/app/api/swap-studio/projects/[id]/route.ts+++ b/src/app/api/swap-studio/projects/[id]/route.ts@@ -1,25 +1,43 @@import { connection } from "next/server";-import { body, handle } from "@/server/shorts-schemas";+import { guestRun } from "@/server/account-tool-run";+import { body } from "@/server/shorts-schemas";import { deleteProject, EditSchema, editProject, projectView } from "@/server/swap-studio";+import { asViewer, guestProjectRead, refsRefused } from "@/server/swap-studio-account";-/** The project with every job's state (finished jobs are filled in, ready waiting takes launched). */-export async function GET(_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {+/**+ * The project with every job's state (finished jobs are filled in, ready waiting takes launched). An account's own+ * projects only (another's, or the owner's, is not found); a guest signs up first.+ */+export async function GET(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {await connection();- return handle(async () => Response.json(projectView((await ctx.params).id)));+ return asViewer(request, async () => Response.json(projectView((await ctx.params).id)), { guest: guestProjectRead });}-/** One edit (rename, character, cuts, shot and segment settings, layouts, takes, review…): the project as it is after it. */+/**+ * One edit (rename, character, cuts, shot and segment settings, layouts, takes, review…): the project as it is after it.+ * A picture an account's edit names (its character, an imported anchor) is one of its own.+ */export async function PATCH(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(await editProject(id, await body(request, EditSchema, "That change isn't valid")));- }, request);+ return asViewer(+ request,+ async (account) => {+ const { id } = await ctx.params;+ const edit = await body(request, EditSchema, "That change isn't valid");+ const bad = account && refsRefused(account.id, [edit.type === "character" ? edit.image : edit.type === "anchor-import" ? edit.url : null]);+ return bad || Response.json(await editProject(id, edit));+ },+ { guest: guestRun, save: true },+ );}-/** Delete the project, stopping what it still makes (the assembled clips stay in the Library). */+/** Delete the project, stopping what it still makes (the assembled clips stay in the Library, or an account's runs). */export async function DELETE(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {- return handle(async () => {- await deleteProject((await ctx.params).id);- return new Response(null, { status: 204 });- }, request);+ return asViewer(+ request,+ async () => {+ await deleteProject((await ctx.params).id);+ return new Response(null, { status: 204 });+ },+ { guest: guestRun },+ );}diff --git a/src/app/api/swap-studio/projects/[id]/sharpen/route.ts b/src/app/api/swap-studio/projects/[id]/sharpen/route.tsindex bd1a7814..0b645c38 100644--- a/src/app/api/swap-studio/projects/[id]/sharpen/route.ts+++ b/src/app/api/swap-studio/projects/[id]/sharpen/route.ts@@ -1,10 +1,12 @@-import { body, handle } from "@/server/shorts-schemas";import { SharpenSchema, sharpenClip } from "@/server/swap-studio";+import { jobRoute } from "@/server/swap-studio-account";-/** Sharpen: every chosen take of a clip made sharper at 1080p, 2K or 4K, each a version beside its take to compare. */+const run = jobRoute(SharpenSchema, "Pick a clip and a size", sharpenClip);++/**+ * Sharpen: every chosen take of a clip made sharper at 1080p, 2K or 4K, each a version beside its take to compare. An+ * account's on its own GPU or key (src/server/swap-studio-account.ts).+ */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/sharpen">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(await sharpenClip(id, await body(request, SharpenSchema, "Pick a clip and a size")), { status: 201 });- }, request);+ return run(request, ctx);}diff --git a/src/app/api/swap-studio/projects/[id]/stop/route.ts b/src/app/api/swap-studio/projects/[id]/stop/route.tsindex 3e6885fc..ba08b0e9 100644--- a/src/app/api/swap-studio/projects/[id]/stop/route.ts+++ b/src/app/api/swap-studio/projects/[id]/stop/route.ts@@ -1,10 +1,16 @@-import { body, handle } from "@/server/shorts-schemas";+import { guestRun } from "@/server/account-tool-run";+import { body } from "@/server/shorts-schemas";import { stopJob, StopSchema } from "@/server/swap-studio";+import { asViewer } from "@/server/swap-studio-account";-/** Stop a mask, anchor, transcript, 24 fps copy or assembly that is still being made. */+/** Stop a mask, anchor, transcript, 24 fps copy or assembly that is still being made (an account's: its own). */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/stop">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(await stopJob(id, await body(request, StopSchema, "Pick a job to stop")));- }, request);+ return asViewer(+ request,+ async () => {+ const { id } = await ctx.params;+ return Response.json(await stopJob(id, await body(request, StopSchema, "Pick a job to stop")));+ },+ { guest: guestRun },+ );}diff --git a/src/app/api/swap-studio/projects/[id]/takes/stop/route.ts b/src/app/api/swap-studio/projects/[id]/takes/stop/route.tsindex ffbe20ba..7ebd4d31 100644--- a/src/app/api/swap-studio/projects/[id]/takes/stop/route.ts+++ b/src/app/api/swap-studio/projects/[id]/takes/stop/route.ts@@ -1,10 +1,16 @@-import { body, handle } from "@/server/shorts-schemas";+import { guestRun } from "@/server/account-tool-run";+import { body } from "@/server/shorts-schemas";import { stopTake, TakeRefSchema } from "@/server/swap-studio";+import { asViewer } from "@/server/swap-studio-account";-/** Stop a take (waiting: it doesn't run; running: it is canceled, and the takes waiting on it stop too). */+/** Stop a take (waiting: it doesn't run; running: it is canceled, and the takes waiting on it stop too). An account's: its own. */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/takes/stop">) {- return handle(async () => {- const { id } = await ctx.params;- return Response.json(await stopTake(id, await body(request, TakeRefSchema, "Pick a take")));- }, request);+ return asViewer(+ request,+ async () => {+ const { id } = await ctx.params;+ return Response.json(await stopTake(id, await body(request, TakeRefSchema, "Pick a take")));+ },+ { guest: guestRun },+ );}diff --git a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts b/src/app/api/swap-studio/projects/[id]/transcribe/route.tsindex b20ed0a5..15e37e66 100644--- a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts+++ b/src/app/api/swap-studio/projects/[id]/transcribe/route.ts@@ -1,15 +1,22 @@import { z } from "zod";-import { body, handle } from "@/server/shorts-schemas";+import { ownGpuTool } from "@/server/account-tool-run";+import { soundLive } from "@/server/sound-live";import { transcribe } from "@/server/swap-studio";+import { jobRoute } from "@/server/swap-studio-account";/** cleanVoiceFirst: the speech apart from the music and effects before it's read (src/lib/av/voice-first.ts). */const Transcribe = z.object({ clipId: z.string().min(1).max(80), cleanVoiceFirst: z.boolean().optional() });-/** The clip's words, with who speaks when (Scribe v2 on the cloud, Qwen3-ASR on your GPU). */+const run = jobRoute(Transcribe, "Pick a clip", (id, b) => transcribe(id, b.clipId, { cleanVoiceFirst: b.cleanVoiceFirst }), {+ status: 200,+ // "Clean the voice first" opens to accounts once it has passed a real run (src/server/sound-live.ts), as in Genjutsu.+ refuse: (b) => (b.cleanVoiceFirst && !soundLive()["clean-voice-first"] ? ownGpuTool() : null),+});++/**+ * The clip's words, with who speaks when (Scribe v2 on the cloud, Qwen3-ASR on your GPU). An account's on its own GPU or+ * key (src/server/swap-studio-account.ts).+ */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/transcribe">) {- return handle(async () => {- const { id } = await ctx.params;- const b = await body(request, Transcribe, "Pick a clip");- return Response.json(transcribe(id, b.clipId, { cleanVoiceFirst: b.cleanVoiceFirst }));- }, request);+ return run(request, ctx);}diff --git a/src/app/api/swap-studio/projects/route.ts b/src/app/api/swap-studio/projects/route.tsindex deedcc01..5a9f2036 100644--- a/src/app/api/swap-studio/projects/route.ts+++ b/src/app/api/swap-studio/projects/route.ts@@ -1,14 +1,27 @@import { connection } from "next/server";-import { body, handle } from "@/server/shorts-schemas";+import { guestRun } from "@/server/account-tool-run";+import { body } from "@/server/shorts-schemas";import { createProject, CreateSchema, listProjects } from "@/server/swap-studio";+import { asViewer, refsRefused } from "@/server/swap-studio-account";-/** Character Swap Studio projects, most recently changed first. */-export async function GET() {+/**+ * Character Swap Studio projects, most recently changed first: the owner's, or a signed-in account's own (public+ * sign-up; src/server/swap-studio-account.ts). A guest has none.+ */+export async function GET(request: Request) {await connection();- return handle(() => Response.json({ items: listProjects() }));+ return asViewer(request, () => Response.json({ items: listProjects() }), { guest: () => Response.json({ items: [] }, { headers: { "Cache-Control": "no-store" } }) });}-/** A new project: a name, the engine, and (optionally) the character. */+/** A new project: a name, the engine, and (optionally) the character (an account's: a picture of its own). */export async function POST(request: Request) {- return handle(async () => Response.json(createProject(await body(request, CreateSchema, "Name the project and pick an engine")), { status: 201 }));+ return asViewer(+ request,+ async (account) => {+ const b = await body(request, CreateSchema, "Name the project and pick an engine");+ const bad = account && refsRefused(account.id, [b.character?.image]);+ return bad || Response.json(createProject(b), { status: 201 });+ },+ { guest: guestRun, save: true },+ );}diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex bfb2f279..929e0f97 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -1266,8 +1266,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Exengine={engine}maker={maker}cut={cut}- // Character Swap Studio's projects are the owner's for now: anyone else gets the link to the studio.- onOpenStudio={owner ? () => void openStudio() : undefined}+ onOpenStudio={() => void openStudio()}opening={opening}waiting={clip?.uploading || refs.some((x) => x.uploading) ? "waiting for the upload" : null}/>}diff --git a/src/components/swap-studio/home.tsx b/src/components/swap-studio/home.tsxindex 31b2e5a9..7c52bbc8 100644--- a/src/components/swap-studio/home.tsx+++ b/src/components/swap-studio/home.tsx@@ -10,13 +10,11 @@ import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { EngineSwitch } from "@/components/studio/engine-switch";-import { SelfHostNote } from "@/components/self-host-note";import { ExampleRow } from "@/components/studio/example-row";-import { useEngine, useLikelyVisitor } from "@/lib/api";+import { useEngine } from "@/lib/api";import { SWAP_STUDIO, type SwapProjectCard } from "@/lib/catalog/swap-studio";import { toastError } from "@/lib/refusals";import type { ExampleRowData } from "@/lib/examples/types";-import { cn } from "@/lib/utils";import { useCreateSwapProject, useDeleteSwapProject, useSwapProjects } from "./hooks";const STEPS = [@@ -44,8 +42,6 @@ export function SwapStudioHome({ examples }: { examples?: ExampleRowData | nullconst [name, setName] = useState("");const [confirm, setConfirm] = useState<SwapProjectCard | null>(null);const nameId = useId();- // A project is saved to the studio's library, which is its owner's: a guest or an account is told so up front.- const visitor = useLikelyVisitor();const start = () =>create.mutate(@@ -57,7 +53,7 @@ export function SwapStudioHome({ examples }: { examples?: ExampleRowData | null);return (- <ToolShell title="Character Swap Studio" engineSwitch={false} header={<EngineSwitch value={engine} onChange={setEngine} selfHostedOnly />} wide>+ <ToolShell title="Character Swap Studio" engineSwitch={false} header={<EngineSwitch value={engine} onChange={setEngine} />} wide><ToolHerotitle="Swap a character through whole clips"subtitle="Put your character into whole clips, shot by shot: pick who to swap, check each shot, keep the best take."@@ -66,7 +62,7 @@ export function SwapStudioHome({ examples }: { examples?: ExampleRowData | nullclassName="mt-6 flex w-full max-w-lg flex-col gap-2 sm:flex-row"onSubmit={(e) => {e.preventDefault();- if (!visitor) start();+ start();}}><label htmlFor={nameId} className="sr-only">@@ -78,18 +74,16 @@ export function SwapStudioHome({ examples }: { examples?: ExampleRowData | nullmaxLength={SWAP_STUDIO.maxNameChars}onChange={(e) => setName(e.target.value)}placeholder="Project name, e.g. Rain scene"- disabled={visitor}className="h-10 min-w-0 shrink-0 rounded-full border bg-background px-4 text-[14px] outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 sm:flex-1"/>- <Button type="submit" className="h-10 rounded-full px-5" disabled={create.isPending || visitor}>+ <Button type="submit" className="h-10 rounded-full px-5" disabled={create.isPending}>{create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Drama className="size-4" />}- {visitor ? "New project" : `New project · ${engine === "open" ? "your GPU" : "cloud"}`}+ {`New project · ${engine === "open" ? "your GPU" : "cloud"}`}</Button></form>- {visitor && <SelfHostNote className="mt-3 max-w-lg">Character Swap isn't available here.</SelfHostNote>}</ToolHero>- {examples && (visitor || (projects.isSuccess && !projects.data.length)) && <ExampleRow row={examples} className="mt-10" />}+ {examples && projects.isSuccess && !projects.data.length && <ExampleRow row={examples} className="mt-10" />}<ol className="mx-auto mt-8 grid max-w-[1040px] gap-3 sm:grid-cols-2 lg:grid-cols-4" aria-label="How it works">{STEPS.map((s, i) => (@@ -105,8 +99,8 @@ export function SwapStudioHome({ examples }: { examples?: ExampleRowData | null))}</ol>- {/* A guest or an account has no projects here and can't make one (the note above says why). */}- <section className={cn("mt-8", visitor && "hidden")} aria-labelledby="swap-projects">+ {/* The owner's projects, or a signed-in account's own (a guest has none yet: New project offers a free account). */}+ <section className="mt-8" aria-labelledby="swap-projects"><h2 id="swap-projects" className="mb-3 text-[15px] font-semibold">Projects</h2>diff --git a/src/components/swap-studio/workbench.tsx b/src/components/swap-studio/workbench.tsxindex 146d063b..01e57ecc 100644--- a/src/components/swap-studio/workbench.tsx+++ b/src/components/swap-studio/workbench.tsx@@ -10,7 +10,9 @@ import { Skeleton } from "@/components/ui/skeleton";import { Panel, ToolShell } from "@/components/av/tool-shell";import { tabKeys } from "@/components/shorts/ui";import { EngineSwitch } from "@/components/studio/engine-switch";-import { uploadFile } from "@/lib/api";+import { uploadFile, useAskBeforeUpload } from "@/lib/api";+import { limitMb, useClipLimit } from "@/lib/clip-limit";+import { postFileWithProgress } from "@/lib/upload";import { clipExtension, clipNeedsPreview, clipProblem, jobState, MODE_LABELS, pageClip, secondsLabel, SWAP_STUDIO, type GenSummary, type StudioEstimate, type SwapClip, type SwapProject, type SwapShot } from "@/lib/catalog/swap-studio";import { cn } from "@/lib/utils";import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";@@ -49,24 +51,8 @@ const STAGES = [] as const;type Stage = (typeof STAGES)[number]["id"];-/** Upload a clip with progress (the server reads its header when it's added). */-function uploadClip(file: File, onProgress: (p: number) => void): Promise<{ url: string; name?: string }> {- return new Promise((resolve, reject) => {- const xhr = new XMLHttpRequest();- xhr.open("POST", "/api/uploads");- xhr.responseType = "json";- xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(e.loaded / e.total);- xhr.onload = () => {- const body = xhr.response as { url?: string; name?: string; error?: string } | null;- if (xhr.status >= 200 && xhr.status < 300 && body?.url) resolve({ url: body.url, name: body.name });- else reject(new Error(body?.error ?? "That upload didn't go through. Please try again."));- };- xhr.onerror = () => reject(new Error("Upload failed — check your connection"));- const form = new FormData();- form.append("file", file);- xhr.send(form);- });-}+/** Upload a clip with progress, as the file itself (the server reads its header when it's added). */+const uploadClip = (file: File, onProgress: (p: number) => void) => postFileWithProgress(file, onProgress);/** What the browser reads of a clip before the server does (a format it can't play just has none of it). */function browserFacts(file: File): Promise<{ duration?: number; width?: number; height?: number }> {@@ -95,6 +81,8 @@ export function SwapWorkbench({ id }: { id: string }) {const [stage, setStage] = useState<Stage>("shots");const [shotId, setShotId] = useState<string | null>(null);const tabsId = useId();+ // The clip size this viewer may upload: an account's is smaller than the studio's own (src/lib/clip-limit.ts).+ const clipMax = useClipLimit(SWAP_STUDIO.maxBytes);const clip = project?.clips.find((c) => c.id === clipId) ?? project?.clips[0] ?? null;const shot = clip?.shots.find((s) => s.id === shotId) ?? clip?.shots.find((s) => s.mode === "generate") ?? clip?.shots[0] ?? null;@@ -134,6 +122,7 @@ export function SwapWorkbench({ id }: { id: string }) {const src = clip ? pageClip(project.engine, clip) : "";const props: StageProps | null = clip ? { id, project, clip, gens: v.gens, estimate, shot, setShot: setShotId, edit, src } : null;+ const clipMb = limitMb(clipMax);return (<ToolShell@@ -158,7 +147,7 @@ export function SwapWorkbench({ id }: { id: string }) {<div className="min-w-0 space-y-4"><ProjectPanel project={project} estimate={estimate} edit={edit} /><CharacterPanel project={project} edit={edit} />- <ClipsPanel id={id} project={project} gens={v.gens} selected={clip?.id ?? null} onSelect={(c) => {+ <ClipsPanel id={id} project={project} gens={v.gens} maxBytes={clipMax} selected={clip?.id ?? null} onSelect={(c) => {setClipId(c);setShotId(null);}} edit={edit} />@@ -170,7 +159,7 @@ export function SwapWorkbench({ id }: { id: string }) {<div className="flex flex-col items-center gap-2 py-12 text-center"><Film className="size-8 text-muted-foreground" aria-hidden /><p className="text-[14px] font-medium">Add a clip to start</p>- <p className="max-w-sm text-[12px] text-muted-foreground">MP4, MOV, MKV, WebM or AVI, up to 149.66 s and 200 MB. {project.engine === "open" ? "Your GPU works on a 24 fps copy, made as soon as it's added." : "The cloud reads it as filmed."}</p>+ <p className="max-w-sm text-[12px] text-muted-foreground">MP4, MOV, MKV, WebM or AVI, up to 149.66 s and {clipMb} MB. {project.engine === "open" ? "Your GPU works on a 24 fps copy, made as soon as it's added." : "The cloud reads it as filmed."}</p></div></Panel>) : (@@ -306,6 +295,7 @@ function ClipsPanel({id,project,gens,+ maxBytes,selected,onSelect,edit,@@ -313,6 +303,8 @@ function ClipsPanel({id: string;project: SwapProject;gens: Record<string, GenSummary>;+ /** The clip size this viewer may upload. */+ maxBytes: number;selected: string | null;onSelect: (id: string) => void;edit: StageProps["edit"];@@ -321,9 +313,12 @@ function ClipsPanel({const input = useRef<HTMLInputElement>(null);const [upload, setUpload] = useState<{ name: string; progress: number } | null>(null);const [remove, setRemove] = useState<SwapClip | null>(null);+ // Whoever the upload would refuse is asked first (a guest signs up, an account without a GPU or key connects one).+ const askFirst = useAskBeforeUpload();const pick = async (file: File) => {- const problem = !clipExtension(file.name) ? "Add an MP4, MOV, MKV, WebM or AVI clip" : clipProblem({ bytes: file.size });+ const tooBig = file.size > maxBytes ? `Keep clips under ${limitMb(maxBytes)} MB` : null;+ const problem = !clipExtension(file.name) ? "Add an MP4, MOV, MKV, WebM or AVI clip" : (tooBig ?? clipProblem({ bytes: file.size }));if (problem) return toast.error(problem);const facts = await browserFacts(file);const long = clipProblem({ duration: facts.duration });@@ -346,7 +341,9 @@ function ClipsPanel({<Paneltitle={`Clips · ${project.clips.length}`}aside={- <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => input.current?.click()} disabled={!!upload || project.clips.length >= SWAP_STUDIO.maxClips}>+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => {+ if (!askFirst()) input.current?.click();+ }} disabled={!!upload || project.clips.length >= SWAP_STUDIO.maxClips}><Plus className="size-3.5" /> Add clip</Button>}diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.tsindex ce4f643e..7b51574c 100644--- a/src/lib/catalog/swap-studio.ts+++ b/src/lib/catalog/swap-studio.ts@@ -223,6 +223,11 @@ export interface SwapTake {settled?: boolean;/** Its sharper version (Assemble → Finish → Sharpen), shown beside it until it is picked. */finish?: TakeFinish | null;+ /**+ * An account's take (public sign-up): the run its queue started. A take that starts later, once the one it continues+ * from is made, joins that run, so the whole queue counts once against the account's limits.+ */+ batchId?: string;}/**diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex c6c96aff..274044a5 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -282,6 +282,8 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [/^\/api\/image-to-3d$/,// Genjutsu's "Describe my character": the GPU describer on the account's own GPU./^\/api\/genjutsu\/describe$/,+ // Character Swap Studio's jobs on an account's own project (src/server/swap-studio-account.ts).+ /^\/api\/swap-studio\/projects\/[^/]+\/(anchors|assemble|clips|masks|prepare|queue|sharpen|transcribe)$/,];/**@@ -290,7 +292,10 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [* A guest's change gets the sign-up card; its reads go by guestRead. A tool adds its routes here when it opens to* accounts.*/-export const ACCOUNT_PROJECT_ROUTES: 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))?)?$/,+];export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));diff --git a/src/server/account-projects.ts b/src/server/account-projects.tsindex cc7b8082..a9fd5ac4 100644--- a/src/server/account-projects.ts+++ b/src/server/account-projects.ts@@ -185,6 +185,17 @@ export function deleteAccountProject(accountId: string, kind: string, id: stringreturn store().prepare("DELETE FROM account_projects WHERE id = ? AND account_id = ? AND kind = ?").run(id, accountId, kindOf(kind)).changes > 0;}+/**+ * Every account's projects of a kind whose summary has `field` above 0, for that tool's background work (Character Swap+ * Studio's takes waiting to start): each one's id and account, never its data. The tool reads each one as its account.+ */+export function accountProjectsWith(kind: string, field: string): { id: string; accountId: string }[] {+ if (!/^[a-zA-Z][a-zA-Z0-9]{0,31}$/.test(field)) throw new Error(`Not a summary field: ${field}`);+ return store()+ .prepare(`SELECT id, account_id AS accountId FROM account_projects WHERE kind = ? AND json_extract(summary_json, '$.${field}') > 0`)+ .all(kindOf(kind)) as { id: string; accountId: string }[];+}+/** Every project of an account, when the account is deleted. */export function deleteAccountProjects(accountId: string): number {return store().prepare("DELETE FROM account_projects WHERE account_id = ?").run(accountId).changes;diff --git a/src/server/swap-studio-account.ts b/src/server/swap-studio-account.tsnew file mode 100644index 00000000..a022a881--- /dev/null+++ b/src/server/swap-studio-account.ts@@ -0,0 +1,130 @@+import "server-only";+import { headers } from "next/headers";+import type { z } from "zod";+import { GUEST_HEADER, GUEST_LIBRARY_MESSAGE } from "@/lib/guest-access";+import { projectRefsProblem, projectSavesLimited } from "./account-projects";+import { bodyTooBig, guestRun, refusalResponse, runAccountTool, toolViewer } from "./account-tool-run";+import { requestViewer, type Account } from "./auth";+import { AccountRunError, asAccount } from "./generations";+import { recordExists } from "./records";+import { body, handle } from "./shorts-schemas";+import { accountHasProject, planSwapJob, startSwapJob, StudioError } from "./swap-studio";++/**+ * Character Swap Studio for each kind of viewer (public sign-up), for its routes:+ *+ * - the owner: as always (swap-studio.ts on the owner's projects);+ * - a signed-in account: inside its own work (asAccount), where swap-studio.ts reads and changes only the account's own+ * projects (account-projects.ts, kind "swap"): another account's, or the owner's, is not found. Every job (a clip's+ * copy, its words, a mask, an anchor, takes, Sharpen, the assembly) is planned first with nothing made, checked as+ * every account run is (src/server/account-tool-run.ts: room, its limits, only its own files, its own ComfyUI or+ * fal.ai key for every step, the GPU pre-flight, the LoRAs, moderation), then started as one run. Files a project+ * names (the character, an imported anchor, a clip) are its own uploads or results only;+ * - a guest: the sign-up card on a change, "Sign up to see this" on a project (the proxy answers both first).+ */++const NO_STORE = { "Cache-Control": "no-store" };++/** A guest's read of a project (it has none): "Sign up to see this". */+export const guestProjectRead = () => Response.json({ error: GUEST_LIBRARY_MESSAGE }, { status: 401, headers: { [GUEST_HEADER]: "1", ...NO_STORE } });++/** The first file a project would name that isn't the account's own (or one of Fuobe's example files): the answer, or null. */+export function refsRefused(accountId: string, files: (string | null | undefined)[]): Response | null {+ const problem = projectRefsProblem(accountId, { files: files.filter((f): f is string => typeof f === "string" && f.length > 0) });+ return problem ? Response.json({ error: problem.error, code: problem.code }, { status: problem.status, headers: NO_STORE }) : null;+}++/** A refused job: the account's own refusal (Connect your GPU, Add your key), or the planner's words with their status. */+function refused(e: unknown): Response {+ if (e instanceof AccountRunError) return refusalResponse(e.refusal);+ if (e instanceof StudioError) return Response.json({ error: e.message }, { status: e.status, headers: NO_STORE });+ return Response.json({ error: (e as Error).message || "Something went wrong. Please try again." }, { status: 422, headers: NO_STORE });+}++/**+ * One of an account's jobs (see the header): `files` the request names itself (a clip's upload), checked first; then the+ * job planned, checked and started as one run. A job that makes nothing (a clip the cloud reads as filmed) is a save.+ */+export async function runSwapJob(request: Request, account: Account, job: { run: () => unknown; files?: (string | null | undefined)[]; status?: number }): Promise<Response> {+ const bad = refsRefused(account.id, job.files ?? []);+ if (bad) return bad;+ let planned: Awaited<ReturnType<typeof planSwapJob>>;+ try {+ planned = await asAccount(account.id, () => planSwapJob(job.run));+ } catch (e) {+ return refused(e);+ }+ const status = job.status ?? 201;+ if (!planned.steps.length) {+ const limited = projectSavesLimited(account.id);+ if (limited) return limited;+ try {+ return Response.json(await asAccount(account.id, () => startSwapJob(job.run)), { status });+ } catch (e) {+ return refused(e);+ }+ }+ const files = [...(job.files ?? []), ...planned.files].filter((f): f is string => !!f);+ const r = await runAccountTool(request, account, { tool: "character-swap", files, plan: () => planned.steps, start: () => startSwapJob(job.run) });+ return r.ok ? Response.json(r.value, { status }) : r.response;+}++type Ctx = { params: Promise<{ id: string }> };++/**+ * A job route (POST /api/swap-studio/projects/<id>/<job>): the owner's as before; an account's through runSwapJob; a+ * guest's the sign-up card. `files`: what the body names that must be the account's own. `refuse`: a part of the job+ * that isn't open to accounts yet (its answer, or null).+ */+export function jobRoute<S extends z.ZodType>(+ schema: S,+ message: string,+ start: (id: string, b: z.infer<S>) => unknown,+ opts: { status?: number; files?: (b: z.infer<S>) => (string | null | undefined)[]; refuse?: (b: z.infer<S>) => Response | null } = {},+) {+ return async (request: Request, ctx: Ctx): Promise<Response> => {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }+ return handle(async () => {+ const { id } = await ctx.params;+ const b = await body(request, schema, message);+ if (viewer.kind === "owner") return Response.json(await start(id, b), { status: opts.status ?? 201 });+ const no = opts.refuse?.(b);+ if (no) return no;+ return runSwapJob(request, viewer.account, { run: () => start(id, b), files: opts.files?.(b), status: opts.status });+ }, request);+ };+}++/**+ * A project route that isn't a run (the list, a project, an edit, a delete, a stop, the prices, the decisions): the+ * owner's as before; an account's inside its own work (its own projects only), with its saves limited when `save`; a+ * guest's `guest` (the sign-up card on a change, "Sign up to see this" on a read).+ */+export function asViewer(request: Request, fn: (account: Account | null) => Response | Promise<Response>, opts: { guest: () => Response; save?: boolean }): Promise<Response> {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return Promise.resolve(opts.guest());+ if (viewer.kind === "owner") return handle(() => fn(null), request);+ const account = viewer.account;+ if (opts.save) {+ const big = bodyTooBig(request);+ if (big) return Promise.resolve(big);+ const limited = projectSavesLimited(account.id);+ if (limited) return Promise.resolve(limited);+ }+ return handle(() => asAccount(account.id, () => fn(account)), request);+}++/**+ * Whether the page of this project opens for whoever asks: an account opens only its own projects; the owner and a+ * guest the owner's (a guest's page then says to sign up).+ */+export async function projectPageOpens(id: string): Promise<boolean> {+ const viewer = requestViewer(new Request("http://fuobe.local/", { headers: await headers() }));+ if (viewer.kind === "account") return accountHasProject(viewer.account.id, id);+ return recordExists({ kind: "swap-project", ids: [id] });+}diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.tsindex c8103a89..5ace3d48 100644--- a/src/server/swap-studio.ts+++ b/src/server/swap-studio.ts@@ -1,5 +1,8 @@import "server-only";+import { AsyncLocalStorage } from "node:async_hooks";+import { nanoid } from "nanoid";import { originalSoundOn, type OriginalSound } from "@/lib/av/original-sound";+import { addKeyMessage } from "@/lib/your-keys";import { z } from "zod";import { getModel } from "@/lib/catalog";import { ANCHOR_MODELS, anchorModel, CHARACTER_SWAP, h3Canvas, SWAP_LORAS, swapLoraRef, TURBO_LORA } from "@/lib/catalog/character-swap";@@ -51,13 +54,17 @@ import { REGEN_MODEL } from "@/lib/catalog/regenerate";import { COMPOSITE_MODEL, filmSize, SHARPEN_COPY, SHARPEN_TIERS, sharpenOptions, sharpenTierFor, type SharpenTier } from "@/lib/catalog/sharpen";import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";import { ACCESS_PLACE } from "@/lib/model-access";+import { paidAllowed } from "./account-keys";+import { AccountProjectError, accountProjectsWith, createAccountProject, deleteAccountProject, getAccountProject, listAccountProjects, updateAccountProject } from "./account-projects";+import type { ToolStep } from "./account-tool-run";import { silenceWriter } from "./canvas";import { createPipeline } from "./chains";import { db } from "./db";-import { cancelGeneration, getGeneration, previewChained } from "./generations";+import { AccountRunError, asAccount, cancelGeneration, getGeneration, OPEN_ONLY_RUN, previewChained } from "./generations";import { isOffered, offeredLoras } from "./model-access";import { engineMode } from "./settings";import { probeSource, ShortsError } from "./shorts";+import { tenant, tenantAccount } from "./tenant";/*** Character Swap Studio on the server (/character-swap): projects in swap_projects (one JSON document each, see@@ -65,6 +72,11 @@ import { probeSource, ShortsError } from "./shorts";* "swap-studio-step", hidden from the Library; the assembled clip is "swap-studio" and lands in the Library). The* document names the generations; whoever reads a project (the page's poll, or the sweep below) fills in what they* made and launches takes that were waiting for the segments they continue from.+ *+ * A signed-in account (public sign-up) has projects of its own, kept in its account projects (account-projects.ts,+ * kind "swap"): inside its own work (asAccount, tenant.ts) every read and change here is of its own projects only, and+ * its jobs are its own runs on its own ComfyUI or fal.ai key. Its routes plan each job first (planSwapRun: nothing made+ * or saved), check it as every account run is checked, then start it (startSwapRun). See swap-studio-account.ts.*/export { ShortsError as StudioError };@@ -93,21 +105,76 @@ function fromRow(r: Row): SwapProject {const takesOf = (p: SwapProject) => p.clips.flatMap((c) => c.shots.flatMap((s) => (s.segments ?? []).flatMap((g) => g.takes)));+/** An account's projects in account-projects.ts. */+export const ACCOUNT_KIND = "swap";++/** What an account's list shows of a project (its summary): the card without its id, name and time. */+type CardSummary = Omit<SwapProjectCard, "id" | "name" | "updatedAt">;++function cardSummary(p: SwapProject, waiting: number): CardSummary {+ return {+ engine: p.engine,+ clips: p.clips.length,+ shots: p.clips.reduce((n, c) => n + c.shots.length, 0),+ swapped: p.clips.reduce((n, c) => n + c.shots.filter((s) => s.mode === "generate").length, 0),+ assembled: p.clips.filter((c) => c.assembly?.genId).length,+ waiting,+ character: p.character.image,+ };+}++/** A project's change that doesn't fit an account's store (too big, too many): its own words and status. */+function accountRefused<T>(fn: () => T): T {+ try {+ return fn();+ } catch (e) {+ if (e instanceof AccountProjectError) throw new ShortsError(e.message, e.status);+ throw e;+ }+}+function write(p: SwapProject): SwapProject {const next = { ...p, revision: p.revision + 1, updatedAt: Date.now() };+ // An account's job being planned (planSwapRun): nothing is saved.+ if (runScope()?.dry) return next;const waiting = takesOf(next).filter((t) => t.state === "waiting").length;+ const t = tenant();+ if (t?.kind === "guest") throw new ShortsError("Project not found", 404);+ if (t?.kind === "account") {+ const saved = accountRefused(() => updateAccountProject(t.id, ACCOUNT_KIND, next.id, { name: next.name, data: next, summary: cardSummary(next, waiting) }));+ if (!saved) throw new ShortsError("Project not found", 404);+ return { ...next, name: saved.name, updatedAt: saved.updatedAt };+ }db().prepare("UPDATE swap_projects SET name = ?, engine = ?, data_json = ?, revision = ?, waiting = ?, updated_at = ? WHERE id = ?").run(next.name, next.engine, JSON.stringify(next), next.revision, waiting, next.updatedAt, next.id);return next;}-function mustProject(id: string): SwapProject {+/**+ * The project with this id that the asker may read: the owner's, or inside an account's work only that account's own+ * (another account's, or the owner's, is not found, the same as one that doesn't exist). A guest has none.+ */+function load(id: string): SwapProject | null {+ const t = tenant();+ if (t?.kind === "guest") return null;+ if (t?.kind === "account") {+ const r = getAccountProject<SwapProject>(t.id, ACCOUNT_KIND, id);+ return r ? { ...r.data, id: r.id, name: r.name, engine: r.data.engine === "open" ? "open" : "cloud", createdAt: r.createdAt, updatedAt: r.updatedAt } : null;+ }const r = rowOf(id);- if (!r) throw new ShortsError("Project not found", 404);- return fromRow(r);+ return r ? fromRow(r) : null;+}++function mustProject(id: string): SwapProject {+ const p = load(id);+ if (!p) throw new ShortsError("Project not found", 404);+ return p;}+/** Whether this account has a Character Swap project with this id (its page opens only its own). */+export const accountHasProject = (accountId: string, id: string): boolean => !!getAccountProject(accountId, ACCOUNT_KIND, id);+/** Change a project in one synchronous read-modify-write (no await inside: nothing else runs between). */function mutate(id: string, fn: (p: SwapProject) => SwapProject): SwapProject {const cur = mustProject(id);@@ -150,12 +217,19 @@ export function genSummary(g: Generation): GenSummary {};}-/** One lookup per id for the duration of a read. */+/**+ * One lookup per id for the duration of a read. Inside an account's work only its own runs are found (its projects name+ * nothing else; this keeps it so).+ */function lookup(): (id: string | undefined) => Generation | null {const cache = new Map<string, Generation | null>();+ const account = tenantAccount();return (id) => {if (!id) return null;- if (!cache.has(id)) cache.set(id, getGeneration(id, { includeDeleted: true }));+ if (!cache.has(id)) {+ const g = getGeneration(id, { includeDeleted: true });+ cache.set(id, g && account && g.request.account !== account ? null : g);+ }return cache.get(id)!;};}@@ -311,7 +385,7 @@ function previousOf(shot: SwapShot, take: SwapTake, look: Look): { master?: strifunction launchTake(project: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, take: SwapTake, shotIndex: number, segIndex: number, look: Look): SwapTake {const previous = previousOf(shot, take, look);const plan = frozenTakePlan(project, clip, shot, seg, take, { shot: shotIndex + 1, segment: segIndex + 1, take: seg.takes.findIndex((t) => t.id === take.id) + 1 }, previous);- const pipe = run(plan.steps);+ const pipe = run(plan.steps, { batchId: take.batchId });return { ...take, state: "launched", waitsOn: undefined, genId: pipe.byKey[plan.final].id, stepIds: pipe.items.map((g) => g.id) };}@@ -362,7 +436,21 @@ export function ensureSwapStudioRunner(): void {} catch (e) {console.error("[swap-studio] sweep:", (e as Error).message);}+ // Accounts' projects (public sign-up), each read and advanced inside its own account's work.+ try {+ for (const r of accountProjectsWith(ACCOUNT_KIND, "waiting")) {+ try {+ asAccount(r.accountId, () => advanceProject(r.id));+ } catch (e) {+ console.error(`[swap-studio] ${r.id}:`, (e as Error).message);+ }+ }+ } catch (e) {+ console.error("[swap-studio] sweep:", (e as Error).message);+ }};+ // Started at boot (instrumentation.ts) or by the owner's queue: never from inside an account's work, whose context its+ // timers would keep (queueTakes).globalThis.__fuobeSwapStudioRunner = setInterval(tick, 3000);globalThis.__fuobeSwapStudioRunner.unref?.();setTimeout(tick, 500).unref?.();@@ -372,28 +460,27 @@ export function ensureSwapStudioRunner(): void {// Projects+/** The asker's projects, most recently changed first: the owner's, or inside an account's work its own (a guest has none). */export function listProjects(limit = 100): SwapProjectCard[] {+ const t = tenant();+ if (t?.kind === "guest") return [];+ if (t?.kind === "account") {+ return listAccountProjects<CardSummary>(t.id, ACCOUNT_KIND)+ .slice(0, limit)+ .map((r) => ({ engine: "open", clips: 0, shots: 0, swapped: 0, assembled: 0, waiting: 0, character: null, ...r.summary, id: r.id, name: r.name, updatedAt: r.updatedAt }));+ }const rows = db().prepare("SELECT * FROM swap_projects ORDER BY updated_at DESC LIMIT ?").all(limit) as Row[];return rows.map((r) => {const p = fromRow(r);- return {- id: p.id,- name: p.name,- engine: p.engine,- clips: p.clips.length,- shots: p.clips.reduce((n, c) => n + c.shots.length, 0),- swapped: p.clips.reduce((n, c) => n + c.shots.filter((s) => s.mode === "generate").length, 0),- assembled: p.clips.filter((c) => c.assembly?.genId).length,- waiting: r.waiting,- character: p.character.image,- updatedAt: p.updatedAt,- };+ return { id: p.id, name: p.name, ...cardSummary(p, r.waiting), updatedAt: p.updatedAt };});}const mustMatchMode = (engine: Engine) => {const mode = engineMode();if (mode !== "both" && mode !== engine) {+ // An account (public sign-up) runs the cloud on its own fal.ai key: its answer opens "Add your key".+ if (tenantAccount() && engine === "cloud") throw new AccountRunError(paidAllowed() ? { error: addKeyMessage("fal"), code: "add-key", provider: "fal" } : { error: OPEN_ONLY_RUN, code: "open-only" });throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);}};@@ -422,6 +509,13 @@ export function createProject(body: z.infer<typeof CreateSchema>): SwapProject {updatedAt: now,revision: 1,};+ const t = tenant();+ if (t?.kind === "guest") throw new ShortsError("Create a free account to make a project.", 401);+ // An account's project is its own (account-projects.ts): its id is the one its store gives it.+ if (t?.kind === "account") {+ const made = accountRefused(() => createAccountProject<SwapProject, CardSummary>(t.id, ACCOUNT_KIND, { name: p.name, data: p, summary: cardSummary(p, 0) }));+ return { ...p, id: made.id, name: made.name, createdAt: made.createdAt, updatedAt: made.updatedAt };+ }db().prepare("INSERT INTO swap_projects (id, name, engine, data_json, revision, waiting, created_at, updated_at) VALUES (?, ?, ?, ?, 1, 0, ?, ?)").run(p.id, p.name, p.engine, JSON.stringify(p), now, now);@@ -433,7 +527,9 @@ export async function deleteProject(id: string): Promise<void> {const p = mustProject(id);const look = lookup();const active = projectGenIds(p).filter((g) => ACTIVE.has(look(g)?.status ?? ""));- db().prepare("DELETE FROM swap_projects WHERE id = ?").run(id);+ const account = tenantAccount();+ if (account) deleteAccountProject(account, ACCOUNT_KIND, id);+ else db().prepare("DELETE FROM swap_projects WHERE id = ?").run(id);for (const g of active) await cancelGeneration(g).catch(() => undefined);}@@ -591,7 +687,8 @@ export async function editProject(projectId: string, body: EditBody): Promise<Swreturn out;});for (const g of after.orphans) await cancelGeneration(g).catch(() => undefined);- if (!after.engine) return next;+ // An account's copies are runs of its own, started from the clip's "Prepare at 24 fps" (the checks every run gets).+ if (!after.engine || tenantAccount()) return next;// Switched engines: on your GPU the clips need their 24 fps copies, on the cloud the page may need browser copies.for (const c of next.clips) {if (after.engine === "open" && !c.normalized) prepareClipQuietly(next.id, c.id);@@ -603,10 +700,72 @@ export async function editProject(projectId: string, body: EditBody): Promise<Sw// ---------------------------------------------------------------------------// Steps run as one pipeline-function run(steps: PlanStep[], existing?: Record<string, string>) {+/**+ * An account's job as its route runs it (swap-studio-account.ts): planned first (`dry`: the steps it would start are+ * kept, nothing is made or saved), then started, every pipeline of it in one batch (one run, as its limits count it).+ */+interface RunScope {+ dry: boolean;+ steps: PlanStep[];+ batchId?: string;+}++declare global {+ var __fuobeSwapRunScope: AsyncLocalStorage<RunScope> | undefined;+}++const runScopes = () => (globalThis.__fuobeSwapRunScope ??= new AsyncLocalStorage<RunScope>());+const runScope = () => runScopes().getStore();++/** The stand-in files the planners price with (no file is read): never one of the account's files to check. */+const STAND_IN = "/api/files/placeholder-";++const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });++/** An account's job planned, not started: the runs it would make (for the checks every account run gets) and the files they read. */+export interface PlannedSwapJob {+ steps: ToolStep[];+ files: string[];+}++/**+ * Plan an account's job (call it inside the account's work): `fn` goes as it will, but nothing is made or saved. The+ * steps it would start, and those it checks now and starts later (a take waiting for the one it continues from), come+ * back with every file they read.+ */+export async function planSwapJob(fn: () => unknown): Promise<PlannedSwapJob> {+ const scope: RunScope = { dry: true, steps: [] };+ await runScopes().run(scope, fn);+ const files = new Set<string>();+ for (const m of JSON.stringify(scope.steps.map((s) => s.request)).matchAll(/\/api\/files\/[^"\\\s?#]+/g)) if (!m[0].startsWith(STAND_IN)) files.add(m[0]);+ return { steps: scope.steps.map((s) => ({ request: withChain(s), deps: s.after?.length ?? 0 })), files: [...files] };+}++/** Start an account's job (inside its work, after its checks): every pipeline it makes is one run (one batch). */+export function startSwapJob<T>(fn: () => T): T {+ return runScopes().run({ dry: false, steps: [], batchId: nanoid(10) }, fn);+}++/** Steps checked now that may start later (a waiting take's): planned with the job, never made here. */+function checkLater(steps: PlanStep[]): void {+ const scope = runScope();+ if (scope?.dry) scope.steps.push(...steps);+}++function run(steps: PlanStep[], opts: { existing?: Record<string, string>; batchId?: string } = {}) {+ const scope = runScope();+ if (scope?.dry) {+ // Planned only: stand-in generations, so the job goes on as it will.+ const n = scope.steps.push(...steps);+ const byKey = Object.fromEntries(steps.map((s) => [s.key, { id: `planned-${n}-${s.key}`, status: "queued", outputs: [] } as unknown as Generation]));+ return { batchId: "planned", items: Object.values(byKey), byKey };+ }+ const batchId = opts.batchId ?? scope?.batchId;try {- return createPipeline(steps, existing ? { existing } : {});+ return createPipeline(steps, { ...(opts.existing && { existing: opts.existing }), ...(batchId && { batchId }) });} catch (e) {+ // An account's refusal stays one (Connect your GPU, Add your key).+ if (e instanceof AccountRunError) throw e;throw new ShortsError((e as Error).message, 422);}}@@ -743,7 +902,7 @@ export function transcribe(projectId: string, clipId: string, opts: { cleanVoicereturn mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, transcript: { genId, modelId, cues: null, voices: c.transcript?.voices ?? {} } })));}-const look1 = (gid?: string) => (gid ? getGeneration(gid, { includeDeleted: true }) : null);+const look1 = (gid?: string) => lookup()(gid);// ---------------------------------------------------------------------------// Masks@@ -934,12 +1093,15 @@ export function queueTakes(projectId: string, body: z.infer<typeof QueueSchema>)const { lora, note } = loraFor(cur.engine, shot.settings.lora);const items = currentSegments(shot).map((g) => ({ ...g }));const made = new Map<string, SwapTake>();+ // An account's queue is one run: a take that starts later joins it.+ const batchId = tenantAccount() ? runScope()?.batchId : undefined;for (const e of planned.entries) {const seg = items[e.index];if (seg.takes.length >= SWAP_STUDIO.maxTakes) throw new ShortsError(`Segment ${e.index + 1} keeps ${SWAP_STUDIO.maxTakes} takes — remove one first`, 422);// Takes it continues from in this queue are named by their new ids (they become the selection when made).const deps = e.dependencies.map((d) => ({ ...d, takeId: made.get(d.segmentId)?.id ?? d.takeId }));const take = newTake(cur, clip, shot, seg, deps, lora, masterKeep(items, e.index, shot.settings));+ if (batchId) take.batchId = batchId;made.set(seg.id, take);}// Every take's steps checked now (models switched off, demo and real mixed, a request a route refuses).@@ -950,11 +1112,15 @@ export function queueTakes(projectId: string, body: z.infer<typeof QueueSchema>)const take = made.get(items[e.index].id)!;const plan = takeSteps(cur, clip, checked, items[e.index], take, { shot: shotIndex + 1, segment: e.index + 1, take: items[e.index].takes.length + 1 });const priced = price(plan.steps);+ if (priced.refusal) throw priced.refusal;if (priced.problem) throw new ShortsError(priced.problem, 422);if (demo !== null && demo !== priced.demo) throw new ShortsError("Some takes would run as a demo and others for real — connect the missing provider in Settings", 422);demo = priced.demo;+ // An account's take that waits is checked with the queue, before anything starts.+ checkLater(plan.steps);}- ensureSwapStudioRunner();+ // (An account's takes are swept by the runner the server starts at boot: never started from inside its work.)+ if (!tenant()) ensureSwapStudioRunner();const project = mutate(projectId, (p) => {const next = mapClip(p, clip.id, (c) =>mapShot(c, shot.id, (s) => {@@ -1023,12 +1189,13 @@ export function assemble(projectId: string, clipId: string, opts: { originalSounreturn url;};const plan = planAssembly({ engine: p.engine, clip, pieces: found.pieces, videoOf, originalSound: sound });- // A silent clip's cloud assembly ends on its silence: the WAV is written now (silenceRef, as Genjutsu and Canvas do).- const withSilence = silenceWriter();+ // A silent clip's cloud assembly ends on its silence: the WAV is written now (silenceRef, as Genjutsu and Canvas do),+ // not while an account's job is only planned.+ const withSilence = runScope()?.dry ? (r: (typeof plan.steps)[number]["request"]) => r : silenceWriter();// The takes count as steps already made: a demo join of real takes is refused.const pipe = run(plan.steps.map((s) => ({ ...s, request: withSilence(s.request) })),- existing,+ { existing },);const assembly = { genId: pipe.byKey[plan.final].id, stepIds: pipe.items.map((g) => g.id), takes, ...(sound !== "everything" && { originalSound: sound }), createdAt: Date.now() };return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, assembly })));@@ -1103,12 +1270,14 @@ export async function sharpenClip(projectId: string, body: z.infer<typeof Sharpelet demo: boolean | null = null;for (const x of todo) {const priced = price(x.plan.steps);+ if (priced.refusal) throw priced.refusal;if (priced.problem) throw new ShortsError(priced.problem, 422);if (demo !== null && demo !== priced.demo) throw new ShortsError("Some takes would run as a demo and others for real — connect the missing provider in Settings", 422);demo = priced.demo;}// A version still being made at another size is replaced: it is stopped first (nothing would show it or stop it after).- for (const x of todo) for (const gid of finishIds(x.take.finish)) if (ACTIVE.has(look(gid)?.status ?? "")) await cancelGeneration(gid).catch(() => undefined);+ // Not while an account's job is only planned.+ if (!runScope()?.dry) for (const x of todo) for (const gid of finishIds(x.take.finish)) if (ACTIVE.has(look(gid)?.status ?? "")) await cancelGeneration(gid).catch(() => undefined);const made = new Map<string, TakeFinish>();for (const x of todo) {const pipe = run(x.plan.steps);@@ -1179,10 +1348,11 @@ export async function stopJob(projectId: string, body: z.infer<typeof StopSchema// ---------------------------------------------------------------------------// Prices-const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });--/** What steps cost together (null when a price is unknown), whether they'd run as a demo, and what stops them. */-function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean; problem: string | null } {+/**+ * What steps cost together (null when a price is unknown), whether they'd run as a demo, and what stops them. `refusal`:+ * an account's own answer (Add your key…), which a run gives as it is.+ */+function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean; problem: string | null; refusal?: AccountRunError } {let cost: number | null = 0;let demo = false;let real = false;@@ -1191,7 +1361,7 @@ function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean; probtry {p = previewChained(withChain(s), s.after?.length ?? 0);} catch (e) {- return { costUsd: null, demo: false, problem: (e as Error).message };+ return { costUsd: null, demo: false, problem: (e as Error).message, ...(e instanceof AccountRunError && { refusal: e }) };}if (p.demo) demo = true;else real = true;diff --git a/tests/account-swap-studio.test.ts b/tests/account-swap-studio.test.tsnew file mode 100644index 00000000..e2c8cb3d--- /dev/null+++ b/tests/account-swap-studio.test.ts@@ -0,0 +1,495 @@+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 type { SwapProject } from "@/lib/catalog/swap-studio";+import type { SwapProjectView } from "@/server/swap-studio";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++vi.setConfig({ testTimeout: 240_000 });+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++/**+ * Character Swap Studio for a signed-in account (public sign-up): its projects are its own (account-projects.ts, kind+ * "swap"), its jobs run on its own ComfyUI (a stand-in here) through the checks every account run gets, with only its+ * own files, and its results are its own runs. A guest gets the sign-up card; another account's projects and the owner's+ * are never in reach.+ */+const dir = tempDir("fuobe-account-swap-");+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 projectsRoute = await import("@/app/api/swap-studio/projects/route");+const projectRoute = await import("@/app/api/swap-studio/projects/[id]/route");+const clipsRoute = await import("@/app/api/swap-studio/projects/[id]/clips/route");+const transcribeRoute = await import("@/app/api/swap-studio/projects/[id]/transcribe/route");+const masksRoute = await import("@/app/api/swap-studio/projects/[id]/masks/route");+const queueRoute = await import("@/app/api/swap-studio/projects/[id]/queue/route");+const assembleRoute = await import("@/app/api/swap-studio/projects/[id]/assemble/route");+const estimateRoute = await import("@/app/api/swap-studio/projects/[id]/estimate/route");+const decisionsRoute = await import("@/app/api/swap-studio/projects/[id]/decisions/route");+const stopRoute = await import("@/app/api/swap-studio/projects/[id]/stop/route");+const stopTakeRoute = await import("@/app/api/swap-studio/projects/[id]/takes/stop/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 { accountProjectsWith, getAccountProject } = await import("@/server/account-projects");+const { accountHasProject, ensureSwapStudioRunner } = await import("@/server/swap-studio");+const { ACCOUNT_CLIP_BYTES } = await import("@/lib/clip-limit");+const { recordExists } = await import("@/server/records");++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 () => {+ fake = await startFakeComfy({ loras: [], delayMs: 0 });+ 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);+ // The sweep the server starts at boot: an account's waiting takes start inside its own work.+ ensureSwapStudioRunner();+});+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 = 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] }) },+ body: text,+ });+}+const get = (url: string, who?: string) => new Request(`http://localhost:3000${url}`, { headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }) } });+const del = (url: string, who?: string) => new Request(`http://localhost:3000${url}`, { method: "DELETE", headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }) } });+const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as never;+const base = (id: string) => `/api/swap-studio/projects/${id}`;++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" && method !== "DELETE" && { 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;+}++async function create(who: string | undefined, body: unknown): Promise<Response> {+ return projectsRoute.POST(json("/api/swap-studio/projects", "POST", body, who));+}+async function view(id: string, who: string): Promise<SwapProjectView> {+ const r = await projectRoute.GET(get(base(id), who), ctx(id));+ expect(r.status, await r.clone().text()).toBe(200);+ return r.json();+}+const list = async (who?: string) => ((await (await projectsRoute.GET(get("/api/swap-studio/projects", who))).json()) as { items: { id: string; waiting: number }[] }).items;+const patch = (id: string, edit: unknown, who: string) => projectRoute.PATCH(json(base(id), "PATCH", edit, who), ctx(id));++/** A job route; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */+async function job(route: { POST: (r: Request, c: never) => Promise<Response> }, id: string, sub: string, body: unknown, who: string): Promise<Response> {+ let r = await route.POST(json(`${base(id)}/${sub}`, "POST", body, who), ctx(id));+ if (r.status === 409) {+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };+ if (j.code === "comfy_missing_model" && j.fix) {+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix.items.map((i) => i.file)];+ for (const x of [a, b]) clearAccountLoras(x);+ r = await route.POST(json(`${base(id)}/${sub}`, "POST", body, who), ctx(id));+ }+ }+ return r;+}++/** Poll the project as its page does (the runner ticked) until `done` holds. */+async function until(id: string, who: string, done: (v: SwapProjectView) => boolean, ms = 60_000): Promise<SwapProjectView> {+ const end = Date.now() + ms;+ for (;;) {+ await globalThis.__fuobeRunner?.tick();+ const v = await view(id, who);+ if (done(v)) return v;+ if (Date.now() > end) throw new Error(`timed out: ${JSON.stringify(Object.values(v.gens).map((g) => [g.status, g.error]))}`);+ await new Promise((r) => setTimeout(r, 150));+ }+}++const RUNS = ["anchors", "assemble", "clips", "masks", "prepare", "queue", "sharpen", "transcribe"];++describe("the proxy opens Character Swap Studio to accounts, and keeps the sign-up card for guests", () => {+ it("a guest gets the sign-up card on every change, an empty list, and 'Sign up' on a project", async () => {+ for (const p of [...RUNS.map((r) => `${base("swap-1")}/${r}`), "/api/swap-studio/projects", `${base("swap-1")}/stop`, `${base("swap-1")}/takes/stop`]) {+ const r = viaProxy(p, "POST");+ expect(r.status, p).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");+ expect((await r.json()).error).toBe(access.GUEST_RUN_MESSAGE);+ }+ for (const m of ["PATCH", "DELETE"]) expect(viaProxy(base("swap-1"), m).status, m).toBe(401);+ const l = viaProxy("/api/swap-studio/projects");+ expect(l.status).toBe(200);+ expect(await l.json()).toEqual({ items: [] });+ for (const p of [base("swap-1"), `${base("swap-1")}/estimate`, `${base("swap-1")}/decisions`]) expect(viaProxy(p).status, p).toBe(401);+ });++ it("an account reaches its projects' routes; its jobs need its own GPU or key", async () => {+ for (const p of RUNS.map((r) => `${base("x")}/${r}`)) {+ expect(passed(viaProxy(p, "POST", "a")), p).toBe(true);+ const r = viaProxy(p, "POST", "c");+ expect(r.status, p).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await r.json()).code).toBe("connect-gpu");+ }+ // Its projects: the routes answer with its own only (a project with no GPU yet too).+ for (const [p, m] of [+ ["/api/swap-studio/projects", "GET"],+ ["/api/swap-studio/projects", "POST"],+ [base("x"), "GET"],+ [base("x"), "PATCH"],+ [base("x"), "DELETE"],+ [`${base("x")}/estimate`, "GET"],+ [`${base("x")}/decisions`, "GET"],+ [`${base("x")}/stop`, "POST"],+ [`${base("x")}/takes/stop`, "POST"],+ ]) {+ for (const who of ["a", "c"]) expect(passed(viaProxy(p, m, who)), `${m} ${p} ${who}`).toBe(true);+ }+ expect(access.accountProjectRoute(`${base("x")}/queue`)).toBe(false);+ expect(access.ownGpuRun("POST", `${base("x")}/queue`)).toBe(true);+ expect(access.ownGpuRun("POST", `${base("x")}/nope`)).toBe(false);+ });++ it("the routes refuse a guest themselves", async () => {+ const r = await create(undefined, { name: "x", engine: "open" });+ expect(r.status).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER)).toBe("1");+ expect(await list()).toEqual([]);+ expect((await projectRoute.GET(get(base("x")), ctx("x"))).status).toBe(401);+ expect((await projectRoute.PATCH(json(base("x"), "PATCH", { type: "rename", name: "y" }), ctx("x"))).status).toBe(401);+ expect((await projectRoute.DELETE(del(base("x")), ctx("x"))).status).toBe(401);+ for (const [route, sub] of [+ [masksRoute, "masks"],+ [queueRoute, "queue"],+ [clipsRoute, "clips"],+ [stopRoute, "stop"],+ ] as const) {+ const g = await route.POST(json(`${base("x")}/${sub}`, "POST", {}), ctx("x"));+ expect(g.status, sub).toBe(401);+ expect((await g.json()).error).toBe(access.GUEST_RUN_MESSAGE);+ }+ expect((await estimateRoute.GET(get(`${base("x")}/estimate`), ctx("x"))).status).toBe(401);+ expect((await decisionsRoute.GET(get(`${base("x")}/decisions`), ctx("x"))).status).toBe(401);+ });+});++describe("an account's projects are its own", () => {+ let mine = "";+ let owners = "";+ let pic = "";+ let clip = "";+ beforeAll(async () => {+ pic = await upload("a", TINY_PNG, "image/png", "me.png");+ clip = await upload("a", CLIP, "video/mp4", "dance.mp4");+ const o = await create("owner", { name: "The owner's", engine: "open" });+ expect(o.status).toBe(201);+ owners = ((await o.json()) as SwapProject).id;+ });++ it("creates, lists and reopens its own project; another account and the owner never see it", async () => {+ const r = await create("a", { name: "Rain scene", engine: "open", character: { image: pic, description: "a knight" } });+ expect(r.status, await r.clone().text()).toBe(201);+ const p = (await r.json()) as SwapProject;+ mine = p.id;+ expect(p).toMatchObject({ name: "Rain scene", engine: "open", character: { image: pic, description: "a knight" } });+ // Kept with the account, never in the owner's table.+ expect(getAccountProject(a, "swap", mine)).not.toBeNull();+ expect(recordExists({ kind: "swap-project", ids: [mine] })).toBe(false);+ expect(accountHasProject(a, mine)).toBe(true);+ expect(accountHasProject(b, mine)).toBe(false);+ expect(accountHasProject(a, owners)).toBe(false);+ // Its list has it (and never the owner's); B's and the owner's lists don't.+ expect((await list("a")).map((x) => x.id)).toEqual([mine]);+ expect(await list("b")).toEqual([]);+ expect((await list("owner")).map((x) => x.id)).toEqual([owners]);+ // Reopened: the project, with its jobs' states.+ const v = await view(mine, "a");+ expect(v.project).toMatchObject({ id: mine, name: "Rain scene", clips: [] });+ // Renamed by A.+ const ren = await patch(mine, { type: "rename", name: "Rain scene 2" }, "a");+ expect(ren.status).toBe(200);+ expect(((await ren.json()) as SwapProject).name).toBe("Rain scene 2");+ });++ it("another account reads, changes, runs and deletes nothing of it: not found", async () => {+ expect((await projectRoute.GET(get(base(mine), "b"), ctx(mine))).status).toBe(404);+ expect((await patch(mine, { type: "rename", name: "mine now" }, "b")).status).toBe(404);+ expect((await projectRoute.DELETE(del(base(mine), "b"), ctx(mine))).status).toBe(404);+ expect((await estimateRoute.GET(get(`${base(mine)}/estimate`, "b"), ctx(mine))).status).toBe(404);+ expect((await decisionsRoute.GET(get(`${base(mine)}/decisions`, "b"), ctx(mine))).status).toBe(404);+ const own = await upload("b", CLIP, "video/mp4", "b.mp4");+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;+ expect((await job(clipsRoute, mine, "clips", { url: own, name: "b.mp4" }, "b")).status).toBe(404);+ expect((await job(masksRoute, mine, "masks", { clipId: "c", shotId: "s", kind: "track", frame: 0 }, "b")).status).toBe(404);+ expect((await stopRoute.POST(json(`${base(mine)}/stop`, "POST", { kind: "normalize", clipId: "c" }, "b"), ctx(mine))).status).toBe(404);+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);+ expect(getAccountProject(a, "swap", mine)?.name).toBe("Rain scene 2");+ });++ it("the owner's projects are never in reach of an account", async () => {+ expect((await projectRoute.GET(get(base(owners), "a"), ctx(owners))).status).toBe(404);+ expect((await patch(owners, { type: "rename", name: "taken" }, "a")).status).toBe(404);+ expect((await projectRoute.DELETE(del(base(owners), "a"), ctx(owners))).status).toBe(404);+ expect((await job(clipsRoute, owners, "clips", { url: clip, name: "dance.mp4" }, "a")).status).toBe(404);+ expect(recordExists({ kind: "swap-project", ids: [owners] })).toBe(true);+ const o = await projectRoute.GET(get(base(owners), "owner"), ctx(owners));+ expect(((await o.json()) as SwapProjectView).project.name).toBe("The owner's");+ // The owner's own route reads only the owner's table: an account's project is no project of the owner's.+ expect((await projectRoute.GET(get(base(mine), "owner"), ctx(mine))).status).toBe(404);+ });++ it("names only its own files: another account's, the owner's, or a link is refused", async () => {+ const bPic = await upload("b", TINY_PNG, "image/png", "b.png");+ const ownerPic = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "owner.png" }).url;+ for (const [image, code] of [+ [bPic, "input-not-yours"],+ [ownerPic, "input-not-yours"],+ ] as const) {+ const r = await create("a", { name: "x", engine: "open", character: { image } });+ expect(r.status, image).toBe(403);+ expect((await r.json()).code).toBe(code);+ const e = await patch(mine, { type: "character", image }, "a");+ expect(e.status).toBe(403);+ const imp = await patch(mine, { type: "anchor-import", clipId: "c", shotId: "s", url: image }, "a");+ expect(imp.status).toBe(403);+ }+ // A clip that isn't its own: refused before anything is read or made.+ const bClip = await upload("b", CLIP, "video/mp4", "b2.mp4");+ const ownerClip = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "owner.mp4" }).url;+ for (const url of [bClip, ownerClip]) {+ const r = await job(clipsRoute, mine, "clips", { url, name: "x.mp4" }, "a");+ expect(r.status, url).toBe(403);+ expect((await r.json()).code).toBe("input-not-yours");+ }+ expect((await view(mine, "a")).project.clips).toEqual([]);+ });++ it("an account with neither a GPU nor a key makes a project, and is asked to connect one before a job", async () => {+ const r = await create("c", { name: "No GPU", engine: "open" });+ expect(r.status).toBe(201);+ const id = ((await r.json()) as SwapProject).id;+ 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 j = await job(clipsRoute, id, "clips", { url: own, name: "c.mp4" }, "c");+ expect(j.status).toBe(403);+ expect(j.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await j.json()).code).toBe("connect-gpu");+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);+ // The cloud is its own fal.ai key's: without one, the add-key answer.+ const cloud = await create("c", { name: "Cloud", engine: "cloud" });+ expect(cloud.status).toBe(422);+ expect((await cloud.json()).error).toMatch(/fal\.ai key/);+ });+});++describe("an account runs Character Swap Studio on its own ComfyUI", () => {+ let id = "";+ let pic = "";+ let clip = "";+ let clipId = "";+ let shotId = "";+ beforeAll(async () => {+ pic = await upload("a", TINY_PNG, "image/png", "hero.png");+ clip = await upload("a", CLIP, "video/mp4", "clip.mp4");+ const r = await create("a", { name: "GPU run", engine: "open", character: { image: pic, description: "a knight in silver armour" } });+ id = ((await r.json()) as SwapProject).id;+ });++ it("adds its clip: the 24 fps copy runs on its ComfyUI as its own run; nothing reaches the install's", async () => {+ fake.log.length = 0;+ fetched.length = 0;+ const r = await job(clipsRoute, id, "clips", { url: clip, name: "clip.mp4" }, "a");+ expect(r.status, await r.clone().text()).toBe(201);+ const p = (await r.json()) as SwapProject;+ const c = p.clips[0];+ clipId = c.id;+ shotId = c.shots[0].id;+ expect(c).toMatchObject({ frames: 288, source: { url: clip, duration: 12 } });+ const norm = getGeneration(c.normalized!.genId!)!;+ expect(norm).toMatchObject({ modelId: "oss-fit-clip", provider: "comfyui", feature: "swap-studio-step" });+ expect(norm.request.account).toBe(a);+ const v = await until(id, "a", (x) => !!x.project.clips[0].normalized?.url);+ expect(v.project.clips[0].normalized!.url).toMatch(/^\/api\/files\/outputs\//);+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBe(1);+ expect(fetched.filter((u) => !u.endsWith("/system_stats"))).toEqual([]);+ });++ it("transcribes its words and tracks who to swap, each its own run on its ComfyUI", async () => {+ const t = await job(transcribeRoute, id, "transcribe", { clipId }, "a");+ expect(t.status, await t.clone().text()).toBe(200);+ const tg = getGeneration(((await t.json()) as SwapProject).clips[0].transcript!.genId!)!;+ expect(tg).toMatchObject({ modelId: "oss-qwen3-asr", provider: "comfyui" });+ expect(tg.request.account).toBe(a);+ const m = await job(masksRoute, id, "masks", { clipId, shotId, kind: "track", frame: 0, points: [] }, "a");+ expect(m.status, await m.clone().text()).toBe(201);+ const mask = ((await m.json()) as SwapProject).clips[0].shots[0].masks[0];+ for (const g of [mask.genId!, ...(mask.stepIds ?? [])]) expect(getGeneration(g)!.request.account, g).toBe(a);+ await until(id, "a", (x) => !!x.project.clips[0].shots[0].masks[0].pieces[0].url && x.project.clips[0].transcript?.cues !== null);+ // A job of its own can be stopped (nothing is running now: it answers with the project).+ const s = await stopRoute.POST(json(`${base(id)}/stop`, "POST", { kind: "transcribe", clipId }, "a"), ctx(id));+ expect(s.status).toBe(200);+ });++ it("prices it for its own GPU, never as a demo", async () => {+ const r = await estimateRoute.GET(get(`${base(id)}/estimate`, "a"), ctx(id));+ expect(r.status, await r.clone().text()).toBe(200);+ expect(await r.json()).toMatchObject({ engine: "open", demo: false });+ });++ it("queues two segments as one run: the second waits, then starts inside its own work when the first is made", async () => {+ let p = ((await (await patch(id, { type: "cuts", clipId, cuts: [96], modes: ["generate", "preserve"] }, "a")).json()) as SwapProject);+ shotId = p.clips[0].shots[0].id;+ p = (await (await patch(id, { type: "shot", clipId, shotId, patch: { settings: { useAnchor: false } } }, "a")).json()) as SwapProject;+ const lay = await patch(id, { type: "layout", clipId, shotId, op: { op: "partition", frames: 48 } }, "a");+ expect(lay.status, await lay.clone().text()).toBe(200);+ p = (await lay.json()) as SwapProject;+ const segs = p.clips[0].shots[0].segments!;+ expect(segs.map((g) => g.connection)).toEqual(["start", "continue"]);+ for (const g of segs) expect((await patch(id, { type: "segment", clipId, shotId, segmentId: g.id, patch: { anchorMode: "none" } }, "a")).status).toBe(200);+ fake.log.length = 0;+ // A take comes out with its lossless master (what the next segment continues from).+ fake.opts.nodes = ["save", "save_master"];+ const q = await job(queueRoute, id, "queue", { clipId, shotId, segmentId: segs[0].id, mode: "all" }, "a");+ expect(q.status, await q.clone().text()).toBe(201);+ const out = (await q.json()) as { project: SwapProject; takes: string[] };+ const [t1, t2] = out.project.clips[0].shots[0].segments!.map((g) => g.takes.at(-1)!);+ expect(t1.state).toBe("launched");+ expect(t2).toMatchObject({ state: "waiting", batchId: t1.batchId });+ const first = getGeneration(t1.genId!)!;+ expect(first).toMatchObject({ modelId: "oss-h3-swap-segment", provider: "comfyui" });+ expect(first.request.account).toBe(a);+ // One run: its steps share the queue's batch.+ expect(t1.batchId).toBeTruthy();+ for (const g of t1.stepIds ?? []) expect(getGeneration(g)!.batchId).toBe(t1.batchId);+ // The waiting take is on its list, and the sweep sees it.+ expect((await list("a")).find((x) => x.id === id)?.waiting).toBe(1);+ expect(accountProjectsWith("swap", "waiting").map((x) => x.id)).toContain(id);+ // Made: the sweep (no page open) starts the second take inside A's own work, in the same run.+ const end = Date.now() + 60_000;+ let second: SwapProject["clips"][number]["shots"][number]["segments"] = null;+ for (;;) {+ await globalThis.__fuobeRunner?.tick();+ second = getAccountProject<SwapProject>(a, "swap", id)!.data.clips[0].shots[0].segments;+ if (second?.[1].takes.at(-1)!.state !== "waiting" || Date.now() > end) break;+ await new Promise((r) => setTimeout(r, 200));+ }+ const t2now = second![1].takes.at(-1)!;+ expect(t2now.state, t2now.reason).toBe("launched");+ const g2 = getGeneration(t2now.genId!)!;+ expect(g2.request.account).toBe(a);+ expect(g2.batchId).toBe(t1.batchId);+ // It continues from the first take's master.+ expect(g2.request.params?.extra).toMatchObject({ historyVideo: expect.stringMatching(/^\/api\/files\/outputs\//) });+ const v = await until(id, "a", (x) => x.project.clips[0].shots[0].segments!.every((g) => !!g.selectedTake));+ expect(v.project.clips[0].shots[0].segments!.map((g) => g.selectedTake)).toEqual([t1.id, t2.id]);+ delete fake.opts.nodes;+ });++ it("assembles its clip: the result is its own run and its own file, to open and download; nobody else's", async () => {+ const r = await job(assembleRoute, id, "assemble", { clipId }, "a");+ expect(r.status, await r.clone().text()).toBe(201);+ const asm = ((await r.json()) as SwapProject).clips[0].assembly!;+ for (const g of [asm.genId!, ...asm.stepIds!]) expect(getGeneration(g)!.request.account, g).toBe(a);+ const v = await until(id, "a", (x) => x.gens[x.project.clips[0].assembly!.genId!]?.status === "succeeded");+ const final = getGeneration(asm.genId!)!;+ expect(final.feature).toBe("swap-studio");+ const out = v.gens[asm.genId!].url!;+ expect(out).toMatch(/^\/api\/files\/outputs\//);+ expect(passed(viaProxy(out, "GET", "a"))).toBe(true);+ expect(passed(viaProxy(`/api/generations/${asm.genId}`, "GET", "a"))).toBe(true);+ expect(viaProxy(out, "GET", "b").status).toBe(403);+ expect(viaProxy(`/api/generations/${asm.genId}`, "GET", "b").status).toBe(403);+ expect(viaProxy(out, "GET").status).toBe(401);+ // Export decisions: its own project's.+ const d = await decisionsRoute.GET(get(`${base(id)}/decisions`, "a"), ctx(id));+ expect(d.status).toBe(200);+ expect(d.headers.get("Content-Disposition")).toMatch(/GPU-run-decisions\.json/);+ // Nothing went to the install's own ComfyUI.+ expect(fetched.filter((u) => !u.endsWith("/system_stats"))).toEqual([]);+ });++ it("keeps the account's limits: runs going at once, a run's size, and its saves", async () => {+ const now = Date.now();+ const add = db().prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'swap-studio-step', 'oss-fit-clip', 'open', 'comfyui', 'trim', 'video', 'queued', ?, '[]', ?, ?)",+ );+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-swap-${i}`, JSON.stringify({ feature: "swap-studio-step", modelId: "oss-fit-clip", account: a }), now, now);+ try {+ const r = await job(masksRoute, id, "masks", { clipId, shotId, kind: "track", frame: 0, points: [] }, "a");+ expect(r.status).toBe(429);+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);+ } finally {+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-swap-%'").run();+ }+ const big = new Request(`http://localhost:3000${base(id)}/masks`, { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });+ expect((await masksRoute.POST(big, ctx(id))).status).toBe(413);+ // An account's clip upload limit is what its upload boxes say.+ expect(ACCOUNT_CLIP_BYTES).toBe(ACCOUNT_LIMITS.videoBytes);+ });++ it("stops a waiting take and deletes its project", async () => {+ const s = await stopTakeRoute.POST(json(`${base(id)}/takes/stop`, "POST", { clipId, shotId, segmentId: "nope", takeId: "nope" }, "a"), ctx(id));+ expect(s.status).toBe(404);+ expect((await projectRoute.DELETE(del(base(id), "a"), ctx(id))).status).toBe(204);+ expect((await projectRoute.GET(get(base(id), "a"), ctx(id))).status).toBe(404);+ expect(getAccountProject(a, "swap", id)).toBeNull();+ });+});diff --git a/tests/e2e/character-swap-accounts-live.mjs b/tests/e2e/character-swap-accounts-live.mjsnew file mode 100644index 00000000..b97a546d--- /dev/null+++ b/tests/e2e/character-swap-accounts-live.mjs@@ -0,0 +1,106 @@+// Character Swap Studio for visitors, in a browser (a studio with a password and public sign-up, fuobe.com by default):+// a guest and a signed-in account see no "isn't available here" note and can press New project; the guest's opens the+// sign-up card, the account's makes a project of its own, which opens, lists, stays out of another's reach and is+// deleted. The upload boxes (here and in Genjutsu) say the clip size the viewer may upload. The account is a throwaway+// one this script makes and deletes. No run is started (that needs the account's own GPU or key).+// Usage: node tests/e2e/character-swap-accounts-live.mjs [appUrl] [--shots <dir>] Exits 1 on a failed check.+import fs from "node:fs";+import path from "node:path";+import crypto from "node:crypto";+import { launch } from "./_browser.mjs";++const argv = process.argv.slice(2);+const flag = (k) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : undefined);+const app = (argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--shots") ?? "https://fuobe.com").replace(/\/$/, "");+const shots = flag("--shots");+if (shots) fs.mkdirSync(shots, { recursive: true });++const failures = [];+const check = (label, ok, extra = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(72)}${extra ? ` ${extra}` : ""}`);+ if (!ok) failures.push(label);+};+const NOTE = "Character Swap isn't available here.";++const browser = await launch();+const email = `swap-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();+ const api = (method, url, data) => page.request.fetch(`${app}${url}`, { method, headers: { origin: app, ...(data && { "content-type": "application/json" }) }, ...(data && { data }) });+ const home = async (who) => {+ await page.goto(`${app}/character-swap`, { waitUntil: "load", timeout: 60_000 });+ await page.waitForTimeout(2500);+ check(`${who}: no "isn't available here" note`, (await page.getByText(NOTE).count()) === 0);+ const button = page.getByRole("button", { name: /New project/ });+ check(`${who}: New project is on`, (await button.count()) > 0 && (await button.first().isEnabled()));+ check(`${who}: the projects list shows`, (await page.locator("#swap-projects").count()) > 0);+ if (shots) await page.screenshot({ path: path.join(shots, `swap-${who}.png`) });+ return button.first();+ };+ const genjutsuBox = async (who) => {+ await page.goto(`${app}/genjutsu?mode=character`, { waitUntil: "load", timeout: 60_000 });+ await page.waitForTimeout(2500);+ check(`${who}: Genjutsu's upload box says 95 MB`, (await page.getByText(/· 95 MB/).count()) > 0 && (await page.getByText(/· 200 MB/).count()) === 0);+ };++ // A guest: the routes, then the page.+ const gl = await api("GET", "/api/swap-studio/projects");+ check("guest: the list is empty", gl.status() === 200 && JSON.stringify(await gl.json()) === '{"items":[]}', String(gl.status()));+ check("guest: a project is 'Sign up'", (await api("GET", "/api/swap-studio/projects/x")).status() === 401);+ for (const p of ["/api/swap-studio/projects", "/api/swap-studio/projects/x/queue", "/api/swap-studio/projects/x/clips"]) {+ const r = await api("POST", p, {});+ check(`guest: POST ${p} gets the sign-up card`, r.status() === 401 && r.headers()["x-fuobe-guest"] === "1", String(r.status()));+ }+ const newGuest = await home("guest");+ await newGuest.click();+ await page.waitForTimeout(2000);+ check("guest: New project opens the sign-up card", (await page.getByText(/Create a free account/).count()) > 0);+ if (shots) await page.screenshot({ path: path.join(shots, "swap-guest-new.png") });+ await genjutsuBox("guest");++ // A throwaway account (signed in in this browser).+ const res = await page.request.post(`${app}/api/auth/signup`, { data: { email, password }, headers: { origin: app } });+ signedUp = res.ok();+ check("signed up a throwaway account", signedUp, String(res.status()));+ const al = await api("GET", "/api/swap-studio/projects");+ check("account: its list starts empty", al.status() === 200 && (await al.json()).items.length === 0, String(al.status()));+ const newAccount = await home("account");+ await page.getByPlaceholder(/Project name/).fill("Live check");+ await newAccount.click();+ await page.waitForURL(/\/character-swap\/[^/]+$/, { timeout: 30_000 }).catch(() => {});+ const id = page.url().split("/character-swap/")[1];+ check("account: New project opens its own project", !!id && !id.includes("?"), page.url());+ await page.waitForTimeout(2500);+ check("account: the project opens (no 'not found')", (await page.getByText("Project not found").count()) === 0);+ check("account: the clip box says 95 MB", (await page.getByText(/up to 149\.66 s and 95 MB/).count()) > 0);+ if (shots) await page.screenshot({ path: path.join(shots, "swap-account-project.png") });+ const list = await (await api("GET", "/api/swap-studio/projects")).json();+ check("account: its list has the project", list.items.some((p) => p.id === id && p.name === "Live check"));+ check("account: its project reads", (await api("GET", `/api/swap-studio/projects/${id}`)).status() === 200);+ check("account: its prices read", (await api("GET", `/api/swap-studio/projects/${id}/estimate`)).status() === 200);+ check("account: another id is not found", (await api("GET", "/api/swap-studio/projects/swap-not-mine")).status() === 404);+ const job = await api("POST", `/api/swap-studio/projects/${id}/queue`, { clipId: "c", shotId: "s", segmentId: "g", mode: "segment" });+ check("account: a job without its own GPU or key asks to connect one", job.status() === 403 && job.headers()["x-fuobe-connect-gpu"] === "1", String(job.status()));+ await genjutsuBox("account");+ const gone = await api("DELETE", `/api/swap-studio/projects/${id}`);+ check("account: deletes its project", gone.status() === 204, String(gone.status()));+ check("account: the deleted project is gone", (await api("GET", `/api/swap-studio/projects/${id}`)).status() === 404);+ // Signed out: the account's project page is no guest's.+ await context.clearCookies();+ check("guest again: an account's project id reads as 'Sign up'", (await api("GET", `/api/swap-studio/projects/${id}`)).status() === 401);+ // Signed back in for the delete below.+ const back = await page.request.post(`${app}/api/auth/login`, { data: { email, password }, headers: { origin: app } });+ check("signed back in", back.ok(), String(back.status()));+} finally {+ if (signedUp) {+ const page = context.pages()[0];+ const del = await page.request.delete(`${app}/api/auth/me`, { data: { password }, headers: { origin: app } });+ console.log(`deleted the throwaway account: ${del.status()}`);+ }+ await browser.close();+}+console.log(failures.length ? `${failures.length} failed` : "all ok");+process.exit(failures.length ? 1 : 0);diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.tsindex 00773de1..28770233 100644--- a/tests/helpers/fake-comfy-runner.ts+++ b/tests/helpers/fake-comfy-runner.ts@@ -37,6 +37,8 @@ export interface FakeComfyOptions {echo?: boolean;/** A text result (SaveText, node 5): these words in the history and in the .txt file /view serves. */text?: string;+ /** The history lists one video under each of these node ids instead of node 900 (a graph's declared outputs, e.g. a take and its master). */+ nodes?: string[];}export interface FakeLogEntry {@@ -182,6 +184,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<Fif (opts.text !== undefined) return json(200, { [id]: { ...done, outputs: { "5": { text: [opts.text], files: [{ filename: "fake_00001_.txt", subfolder: "fuobe", type: "output" }] } } } });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" }] }])) } });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.test.ts b/tests/public-signup.test.tsindex ed89edd8..1fb9de90 100644--- a/tests/public-signup.test.ts+++ b/tests/public-signup.test.ts@@ -235,8 +235,6 @@ describe("accounts never run on the owner's keys or GPU", () => {// Remove a person on H3: its mask preview and "Redo from here"."/api/remove-object/preview","/api/remove-object/reroll",- // Character Swap Studio's Sharpen: a studio job, like its assembly.- "/api/swap-studio/projects/p1/sharpen",// Plan layout plans with the studio's own AI helper."/api/layout/plan",// Regenerate in Faceless, Shorts segments and Cinema takes (n7-10): studio jobs, like their renders.diff --git a/tests/swap-studio-api.test.ts b/tests/swap-studio-api.test.tsindex 2d1d44ad..62a77567 100644--- a/tests/swap-studio-api.test.ts+++ b/tests/swap-studio-api.test.ts@@ -87,7 +87,7 @@ describe("Character Swap Studio: the cloud, as a demo", () => {expect(created).toMatchObject({ name: "Rain scene", engine: "cloud", character: { image: hero } });expect(recordExists({ kind: "swap-project", ids: [id] })).toBe(true);expect(recordExists({ kind: "swap-project", ids: ["swap-nope"] })).toBe(false);- const list = await (await projects.GET()).json();+ const list = await (await projects.GET(req("GET"))).json();expect(list.items[0]).toMatchObject({ id, clips: 0 });const p = await post(clips, id, { url: clip, name: "dance.mp4" });diff --git a/tests/swap-studio-sharpen.test.ts b/tests/swap-studio-sharpen.test.tsindex d405945a..3caf56bf 100644--- a/tests/swap-studio-sharpen.test.ts+++ b/tests/swap-studio-sharpen.test.ts@@ -257,7 +257,7 @@ describe("Genjutsu's notes for a finishing size", () => {});describe("the route under public sign-up", () => {- it("gives guests and accounts own-gpu-tool (a studio job, like Assemble), and the owner the route", async () => {+ it("lets an account with its own GPU reach the route (a studio job, like Assemble); a guest signs up first", async () => {process.env.FUOBE_PASSWORD = "install password";process.env.FUOBE_PUBLIC_SIGNUP = "1";try {@@ -268,12 +268,13 @@ describe("the route under public sign-up", () => {const cookie = auth.createSession(account.id).value;auth.setAccountGpu(account.id, { url: "https://gpu.example" });const at = (url: string, c?: string) => new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: c ? { cookie: `${auth.SESSION_COOKIE}=${c}` } : {}, body: "{}" });+ // Character Swap Studio's jobs run on an account's own GPU or key (the route makes the account's checks, on its own+ // projects only: tests/account-swap-studio.test.ts).for (const p of ["/api/swap-studio/projects/swap-1/sharpen", "/api/swap-studio/projects/swap-1/assemble"]) {- for (const c of [undefined, cookie]) {- const r = proxy(at(p, c));- expect(r.status, `${p} ${c ? "account" : "guest"}`).toBe(403);- expect(await r.json()).toEqual({ error: access.OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" });- }+ expect(proxy(at(p, cookie)).headers.get("x-middleware-next"), p).toBe("1");+ const r = proxy(at(p));+ expect(r.status, p).toBe(401);+ expect((await r.json()).error).toBe(access.GUEST_RUN_MESSAGE);}// Genjutsu runs on an account's own GPU (its route makes the account's checks); a guest signs up first.expect(proxy(at("/api/genjutsu", cookie)).headers.get("x-middleware-next")).toBe("1");