Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Character Swap Studio: projects, edits, jobs and the sweep on the server

Claude9cecc9308acf
diff --git a/src/app/api/swap-studio/projects/[id]/anchors/route.ts b/src/app/api/swap-studio/projects/[id]/anchors/route.ts
new file mode 100644
index 00000000..0c2a888f
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/anchors/route.ts
@@ -0,0 +1,10 @@
+import { AnchorSchema, makeAnchor } from "@/server/swap-studio";
+import { body, handle } from "@/server/shorts-schemas";
+
+/** A scene anchor for a shot (or a reference for a segment): your character put into its first frame. */
+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 });
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/assemble/route.ts b/src/app/api/swap-studio/projects/[id]/assemble/route.ts
new file mode 100644
index 00000000..772dd456
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/assemble/route.ts
@@ -0,0 +1,13 @@
+import { z } from "zod";
+import { body, handle } from "@/server/shorts-schemas";
+import { assemble } from "@/server/swap-studio";
+
+const Assemble = z.object({ clipId: z.string().min(1).max(80) });
+
+/** Assemble a clip: its chosen takes over the original timeline, with the clip's own sound. */
+export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/assemble">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ return Response.json(assemble(id, (await body(request, Assemble, "Pick a clip")).clipId), { status: 201 });
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/clips/route.ts b/src/app/api/swap-studio/projects/[id]/clips/route.ts
new file mode 100644
index 00000000..5405e038
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/clips/route.ts
@@ -0,0 +1,10 @@
+import { body, handle } from "@/server/shorts-schemas";
+import { addClip, ClipSchema } from "@/server/swap-studio";
+
+/** Add an uploaded clip (MP4, MOV, MKV, WebM or AVI, at most 149.66 s); on your GPU its 24 fps copy starts now. */
+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 });
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/decisions/route.ts b/src/app/api/swap-studio/projects/[id]/decisions/route.ts
new file mode 100644
index 00000000..7fafdabf
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/decisions/route.ts
@@ -0,0 +1,13 @@
+import { connection } from "next/server";
+import { handle } from "@/server/shorts-schemas";
+import { decisions } from "@/server/swap-studio";
+
+/** "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">) {
+ 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"` } });
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/estimate/route.ts b/src/app/api/swap-studio/projects/[id]/estimate/route.ts
new file mode 100644
index 00000000..143df68c
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/estimate/route.ts
@@ -0,0 +1,9 @@
+import { connection } from "next/server";
+import { handle } from "@/server/shorts-schemas";
+import { estimateProject } from "@/server/swap-studio";
+
+/** 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">) {
+ await connection();
+ return handle(async () => Response.json(estimateProject((await ctx.params).id)));
+}
diff --git a/src/app/api/swap-studio/projects/[id]/masks/route.ts b/src/app/api/swap-studio/projects/[id]/masks/route.ts
new file mode 100644
index 00000000..af0d49ee
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/masks/route.ts
@@ -0,0 +1,10 @@
+import { body, handle } from "@/server/shorts-schemas";
+import { makeMask, MaskSchema } from "@/server/swap-studio";
+
+/** Who to swap, as a mask: Track shot (from a frame to the shot's end) or Update frame — a new mask version. */
+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 });
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/prepare/route.ts b/src/app/api/swap-studio/projects/[id]/prepare/route.ts
new file mode 100644
index 00000000..6fcf02c2
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/prepare/route.ts
@@ -0,0 +1,13 @@
+import { z } from "zod";
+import { body, handle } from "@/server/shorts-schemas";
+import { prepareClip } from "@/server/swap-studio";
+
+const Prepare = z.object({ clipId: z.string().min(1).max(80) });
+
+/** Your GPU: make the clip's 24 fps copy (again). */
+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));
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/queue/route.ts b/src/app/api/swap-studio/projects/[id]/queue/route.ts
new file mode 100644
index 00000000..52b12b12
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/queue/route.ts
@@ -0,0 +1,10 @@
+import { body, handle } from "@/server/shorts-schemas";
+import { QueueSchema, queueTakes } from "@/server/swap-studio";
+
+/** Queue segment / Queue from here / Queue all segments: a take for each, continuations waiting for what they continue from. */
+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 });
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/route.ts b/src/app/api/swap-studio/projects/[id]/route.ts
new file mode 100644
index 00000000..f099cdf7
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/route.ts
@@ -0,0 +1,25 @@
+import { connection } from "next/server";
+import { body, handle } from "@/server/shorts-schemas";
+import { deleteProject, EditSchema, editProject, projectView } from "@/server/swap-studio";
+
+/** 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]">) {
+ await connection();
+ return handle(async () => Response.json(projectView((await ctx.params).id)));
+}
+
+/** One edit (rename, character, cuts, shot and segment settings, layouts, takes, review…): the project as it is after it. */
+export async function PATCH(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ return Response.json(editProject(id, await body(request, EditSchema, "That change isn't valid")));
+ });
+}
+
+/** Delete the project, stopping what it still makes (the assembled clips stay in the Library). */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {
+ return handle(async () => {
+ await deleteProject((await ctx.params).id);
+ return new Response(null, { status: 204 });
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/stop/route.ts b/src/app/api/swap-studio/projects/[id]/stop/route.ts
new file mode 100644
index 00000000..190a02fe
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/stop/route.ts
@@ -0,0 +1,10 @@
+import { body, handle } from "@/server/shorts-schemas";
+import { stopJob, StopSchema } from "@/server/swap-studio";
+
+/** Stop a mask, anchor, transcript, 24 fps copy or assembly that is still being made. */
+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")));
+ });
+}
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.ts
new file mode 100644
index 00000000..0036cada
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/takes/stop/route.ts
@@ -0,0 +1,10 @@
+import { body, handle } from "@/server/shorts-schemas";
+import { stopTake, TakeRefSchema } from "@/server/swap-studio";
+
+/** Stop a take (waiting: it doesn't run; running: it is canceled, and the takes waiting on it stop too). */
+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")));
+ });
+}
diff --git a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts b/src/app/api/swap-studio/projects/[id]/transcribe/route.ts
new file mode 100644
index 00000000..c8820b0e
--- /dev/null
+++ b/src/app/api/swap-studio/projects/[id]/transcribe/route.ts
@@ -0,0 +1,13 @@
+import { z } from "zod";
+import { body, handle } from "@/server/shorts-schemas";
+import { transcribe } from "@/server/swap-studio";
+
+const Transcribe = z.object({ clipId: z.string().min(1).max(80) });
+
+/** The clip's words, with who speaks when (Scribe v2 on the cloud, Qwen3-ASR on your GPU). */
+export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/transcribe">) {
+ return handle(async () => {
+ const { id } = await ctx.params;
+ return Response.json(transcribe(id, (await body(request, Transcribe, "Pick a clip")).clipId));
+ });
+}
diff --git a/src/app/api/swap-studio/projects/route.ts b/src/app/api/swap-studio/projects/route.ts
new file mode 100644
index 00000000..deedcc01
--- /dev/null
+++ b/src/app/api/swap-studio/projects/route.ts
@@ -0,0 +1,14 @@
+import { connection } from "next/server";
+import { body, handle } from "@/server/shorts-schemas";
+import { createProject, CreateSchema, listProjects } from "@/server/swap-studio";
+
+/** Character Swap Studio projects, most recently changed first. */
+export async function GET() {
+ await connection();
+ return handle(() => Response.json({ items: listProjects() }));
+}
+
+/** A new project: a name, the engine, and (optionally) the character. */
+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 }));
+}
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index fba1630f..1471ecf0 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -1,7 +1,8 @@
/**
* Runs once when the server starts: start the generation runner right away, so jobs that were in
* flight before a restart keep advancing (and live updates flow) even when the UI only lists them.
- * Also empties what has been in the Trash for 30 days (then daily), and starts Assist's scheduled tasks.
+ * Also empties what has been in the Trash for 30 days (then daily), starts Assist's scheduled tasks and Character
+ * Swap Studio's sweep.
*/
export async function register() {
if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.NEXT_PHASE === "phase-production-build") return;
@@ -15,4 +16,7 @@ export async function register() {
// Assist's scheduled tasks: a 30 s sweep starts the runs that are due (a run missed while the server was off happens once, a few seconds after boot).
const { ensureScheduleRunner } = await import("./server/assist/schedules");
ensureScheduleRunner({ soon: true });
+ // Character Swap Studio: takes queued behind the segments they continue from launch (or stop) when those finish.
+ const { ensureSwapStudioRunner } = await import("./server/swap-studio");
+ ensureSwapStudioRunner();
}
diff --git a/src/lib/catalog/swap-studio-edit.ts b/src/lib/catalog/swap-studio-edit.ts
new file mode 100644
index 00000000..48afce67
--- /dev/null
+++ b/src/lib/catalog/swap-studio-edit.ts
@@ -0,0 +1,356 @@
+/**
+ * Character Swap Studio's edits: every change the page makes to a project, as pure functions (the server checks the
+ * shape, applies them and saves; the tests run them here). Jobs that make something (the 24 fps copy, a transcript,
+ * a mask, an anchor, a take, an assembly) are in src/server/swap-studio.ts. Akatz Labs' rules carried over: a new
+ * character picture un-approves the anchors made with the old one; editing a segment's words or speaker keeps its
+ * prompt as it was (Update prompt rebuilds it, explicitly); a shot layout can't change under a running job.
+ */
+import { HISTORY_CHOICES, WINDOW_CHOICES, type SwapLora, type SwapWho } from "./character-swap";
+import {
+ applyLayout,
+ buildSegmentPrompt,
+ buildShotPrompt,
+ currentSegments,
+ cutsProblem,
+ removeTake,
+ segmentPrompt,
+ segmentsProblem,
+ selectTake,
+ shotsFromCuts,
+ SWAP_STUDIO,
+ tidyCuts,
+ updateTake,
+ type AnchorMode,
+ type Connection,
+ type Decision,
+ type LayoutOp,
+ type RenderMp,
+ type ShotMode,
+ type SwapClip,
+ type SwapProject,
+ type SwapRole,
+ type SwapSegment,
+ type SwapSettings,
+ type SwapShot,
+ type WhoToSwap,
+} from "./swap-studio";
+import type { Engine } from "./types";
+
+export interface SegmentPatch {
+ prompt?: string;
+ performancePrompt?: string | null;
+ dialogue?: string | null;
+ speaker?: SwapRole | null;
+ seed?: number;
+ connection?: Connection;
+ history?: number;
+ anchorMode?: AnchorMode;
+ anchor?: string | null;
+}
+
+export interface ShotPatch {
+ mode?: ShotMode;
+ speaker?: SwapRole | null;
+ dialogue?: string | null;
+ prompt?: string | null;
+ who?: Partial<WhoToSwap>;
+ settings?: Partial<SwapSettings>;
+ anchorInstructions?: string;
+ anchorBasePrompt?: string;
+ approvedAnchor?: string | null;
+ approvedMask?: string | null;
+}
+
+export type SwapEdit =
+ | { type: "rename"; name: string }
+ | { type: "engine"; engine: Engine }
+ | { type: "character"; image?: string | null; description?: string }
+ | { type: "defaults"; settings: Partial<SwapSettings> }
+ | { type: "clip"; clipId: string; name?: string; review?: Decision; reviewNotes?: string }
+ | { type: "remove-clip"; clipId: string }
+ | { type: "detected"; clipId: string; cuts: number[] }
+ | { type: "cuts"; clipId: string; cuts: number[]; modes?: ShotMode[] }
+ | { type: "voices"; clipId: string; voices: Record<string, SwapRole> }
+ | { type: "shot"; clipId: string; shotId: string; patch: ShotPatch }
+ | { type: "build-prompts"; clipId: string; shotId?: string }
+ | { type: "layout"; clipId: string; shotId: string; op: LayoutOp }
+ | { type: "segment"; clipId: string; shotId: string; segmentId: string; patch: SegmentPatch }
+ | { type: "update-prompt"; clipId: string; shotId: string; segmentId: string }
+ | { type: "take"; clipId: string; shotId: string; segmentId: string; takeId: string; select?: boolean; favourite?: boolean; decision?: Decision; notes?: string; remove?: boolean }
+ | { type: "anchor-import"; clipId: string; shotId: string; segmentId?: string; url: string; id: string; at: number }
+ | { type: "remove-anchor"; clipId: string; shotId: string; segmentId?: string; anchorId: string }
+ | { type: "remove-mask"; clipId: string; shotId: string; maskId: string };
+
+/** An edit the project can't take, with the status the API answers. */
+export class EditError extends Error {
+ constructor(
+ message: string,
+ readonly status = 422,
+ ) {
+ super(message);
+ }
+}
+
+const LORAS: SwapLora[] = ["v1.5", "v1", "none"];
+const SELECTIONS: SwapWho[] = ["largest", "leftmost", "rightmost", "index"];
+
+/** A settings patch on known values only (unknown values are refused, not dropped). */
+export function cleanSettings(patch: Partial<SwapSettings>): Partial<SwapSettings> {
+ const out: Partial<SwapSettings> = {};
+ if (patch.lora !== undefined) {
+ if (!LORAS.includes(patch.lora)) throw new EditError("Choose V1.5, V1 or no swap LoRA");
+ out.lora = patch.lora;
+ }
+ for (const k of ["useAnchor", "useMask"] as const) if (patch[k] !== undefined) out[k] = !!patch[k];
+ if (patch.renderMp !== undefined) {
+ if (patch.renderMp !== 0.5 && patch.renderMp !== 1) throw new EditError("Choose a render size of 0.5 MP (480) or 1.0 MP (768)");
+ out.renderMp = patch.renderMp as RenderMp;
+ }
+ if (patch.seed !== undefined) {
+ if (!Number.isInteger(patch.seed) || patch.seed < 0 || patch.seed > SWAP_STUDIO.maxSeed) throw new EditError("Use a whole-number seed");
+ out.seed = patch.seed;
+ }
+ if (patch.windowFrames !== undefined) {
+ if (!WINDOW_CHOICES.includes(patch.windowFrames)) throw new EditError("Choose a diffusion window of 22–362 frames (17n + 5)");
+ out.windowFrames = patch.windowFrames;
+ }
+ if (patch.historyFrames !== undefined) {
+ if (!HISTORY_CHOICES.includes(patch.historyFrames)) throw new EditError("Choose a continuation history of 0, 1 or 17n + 1 frames");
+ out.historyFrames = patch.historyFrames;
+ }
+ if (patch.expansion !== undefined) {
+ if (!Number.isInteger(patch.expansion) || patch.expansion < 0 || patch.expansion > 256) throw new EditError("Grow the mask by 0–256 pixels");
+ out.expansion = patch.expansion;
+ }
+ if (out.windowFrames !== undefined && out.historyFrames !== undefined && out.historyFrames >= out.windowFrames) throw new EditError("History must be shorter than the window");
+ return out;
+}
+
+const text = (v: string | null | undefined, max: number, what: string) => {
+ if (v == null) return v;
+ if (v.length > max) throw new EditError(`Keep the ${what} under ${max.toLocaleString("en-US")} characters`);
+ return v;
+};
+
+function mustClip(p: SwapProject, id: string): SwapClip {
+ const c = p.clips.find((x) => x.id === id);
+ if (!c) throw new EditError("That clip is no longer in this project — reload", 404);
+ return c;
+}
+function mustShot(c: SwapClip, id: string): SwapShot {
+ const s = c.shots.find((x) => x.id === id);
+ if (!s) throw new EditError("That shot changed — reload", 404);
+ return s;
+}
+
+/** Whether a shot has a take still being made (or waiting to be). */
+export function shotBusy(shot: SwapShot, active: (genId: string) => boolean): boolean {
+ return (shot.segments ?? []).some((g) => g.takes.some((t) => t.state === "waiting" || (t.state === "launched" && !!t.genId && active(t.genId))));
+}
+
+const mapClip = (p: SwapProject, id: string, f: (c: SwapClip) => SwapClip): SwapProject => ({ ...p, clips: p.clips.map((c) => (c.id === id ? f(c) : c)) });
+const mapShot = (c: SwapClip, id: string, f: (s: SwapShot) => SwapShot): SwapClip => ({ ...c, shots: c.shots.map((s) => (s.id === id ? f(s) : s)) });
+
+/** The shot's segments made explicit (the default layout becomes its own) with one segment changed. */
+function withSegment(shot: SwapShot, segmentId: string, f: (s: SwapSegment, items: SwapSegment[]) => SwapSegment): SwapShot {
+ const items = currentSegments(shot).map((s) => ({ ...s }));
+ const i = items.findIndex((s) => s.id === segmentId);
+ if (i < 0) throw new EditError("That segment changed — reload", 404);
+ items[i] = f(items[i], items);
+ return { ...shot, segments: items };
+}
+
+/**
+ * Apply one edit. `active` says whether a generation is still running (a shot layout can't change under a running
+ * take). Throws EditError with what to do instead.
+ */
+export function applyEdit(project: SwapProject, edit: SwapEdit, o: { active: (genId: string) => boolean; rand?: () => number }): SwapProject {
+ const p = project;
+ switch (edit.type) {
+ case "rename": {
+ const name = edit.name.trim().slice(0, SWAP_STUDIO.maxNameChars);
+ if (!name) throw new EditError("Give the project a name");
+ return { ...p, name };
+ }
+ case "engine":
+ return { ...p, engine: edit.engine };
+ case "character": {
+ const image = edit.image === undefined ? p.character.image : edit.image;
+ const description = text(edit.description, SWAP_STUDIO.maxDescriptionChars, "description") ?? p.character.description;
+ // Anchors were made with the old picture: they need approving again.
+ const changed = image !== p.character.image;
+ return {
+ ...p,
+ character: { image, description },
+ clips: changed ? p.clips.map((c) => ({ ...c, shots: c.shots.map((s) => ({ ...s, approvedAnchor: null })) })) : p.clips,
+ };
+ }
+ case "defaults":
+ return { ...p, defaults: { ...p.defaults, ...cleanSettings(edit.settings) } };
+ case "clip":
+ return mapClip(p, edit.clipId, (c) => ({
+ ...c,
+ ...(edit.name !== undefined ? { name: edit.name.trim().slice(0, SWAP_STUDIO.maxNameChars) || c.name } : {}),
+ ...(edit.review !== undefined ? { review: edit.review } : {}),
+ ...(edit.reviewNotes !== undefined ? { reviewNotes: text(edit.reviewNotes, SWAP_STUDIO.maxNotesChars, "notes")! } : {}),
+ }));
+ case "remove-clip": {
+ const c = mustClip(p, edit.clipId);
+ if (c.shots.some((s) => shotBusy(s, o.active))) throw new EditError("Wait for this clip's takes to finish (or stop them) before removing it", 409);
+ return { ...p, clips: p.clips.filter((x) => x.id !== edit.clipId) };
+ }
+ case "detected": {
+ const c = mustClip(p, edit.clipId);
+ const cuts = tidyCuts(edit.cuts.filter((n) => Number.isInteger(n) && n > 0 && n < c.frames));
+ return mapClip(p, c.id, (x) => ({ ...x, detected: cuts }));
+ }
+ case "cuts": {
+ const c = mustClip(p, edit.clipId);
+ const cuts = tidyCuts(edit.cuts);
+ const problem = cutsProblem(cuts, c.frames);
+ if (problem) throw new EditError(problem);
+ const shots = shotsFromCuts(c, cuts, p.defaults, edit.modes, o.rand);
+ if (edit.modes && edit.modes.length !== shots.length) throw new EditError("Choose Replace character or Keep original for each shot");
+ const kept = new Set(shots.map((s) => s.id));
+ if (c.shots.some((s) => !kept.has(s.id) && shotBusy(s, o.active))) throw new EditError("Wait for the takes of the shots you're changing to finish (or stop them) first", 409);
+ return mapClip(p, c.id, (x) => ({ ...x, cuts, shots, detected: null, cutsReviewed: true }));
+ }
+ case "voices":
+ return mapClip(p, edit.clipId, (c) => {
+ if (!c.transcript) throw new EditError("Transcribe the clip first");
+ return { ...c, transcript: { ...c.transcript, voices: { ...c.transcript.voices, ...edit.voices } } };
+ });
+ case "shot": {
+ const c = mustClip(p, edit.clipId);
+ mustShot(c, edit.shotId);
+ const x = edit.patch;
+ return mapClip(p, c.id, (cl) =>
+ mapShot(cl, edit.shotId, (s) => {
+ const settings = x.settings ? { ...s.settings, ...cleanSettings(x.settings) } : s.settings;
+ if (settings.historyFrames >= settings.windowFrames) throw new EditError("History must be shorter than the window");
+ const who = x.who ? { ...s.who, ...x.who } : s.who;
+ if (!SELECTIONS.includes(who.selection)) throw new EditError("Pick the largest, leftmost, rightmost or a numbered person");
+ if (!Number.isInteger(who.index) || who.index < 0 || who.index > 100) throw new EditError("Person numbers run from 1 to 101");
+ who.words = who.words.slice(0, 120);
+ if (x.approvedAnchor && !s.anchors.some((a) => a.id === x.approvedAnchor && a.url)) throw new EditError("That anchor isn't ready yet");
+ if (x.approvedMask && !s.masks.some((m) => m.id === x.approvedMask && m.pieces.every((pc) => pc.url))) throw new EditError("That mask isn't ready yet");
+ return {
+ ...s,
+ ...(x.mode ? { mode: x.mode } : {}),
+ ...(x.speaker !== undefined ? { speaker: x.speaker } : {}),
+ ...(x.dialogue !== undefined ? { dialogue: text(x.dialogue, SWAP_STUDIO.maxPromptChars, "dialogue") ?? null } : {}),
+ ...(x.prompt !== undefined ? { prompt: text(x.prompt, SWAP_STUDIO.maxPromptChars, "prompt") ?? null } : {}),
+ ...(x.anchorInstructions !== undefined ? { anchorInstructions: text(x.anchorInstructions, SWAP_STUDIO.maxPromptChars, "anchor instructions")! } : {}),
+ ...(x.anchorBasePrompt !== undefined ? { anchorBasePrompt: text(x.anchorBasePrompt, SWAP_STUDIO.maxPromptChars, "anchor base prompt")! } : {}),
+ ...(x.approvedAnchor !== undefined ? { approvedAnchor: x.approvedAnchor } : {}),
+ ...(x.approvedMask !== undefined ? { approvedMask: x.approvedMask } : {}),
+ who,
+ settings,
+ };
+ }),
+ );
+ }
+ case "build-prompts": {
+ const c = mustClip(p, edit.clipId);
+ return mapClip(p, c.id, (cl) => ({
+ ...cl,
+ shots: cl.shots.map((s) => (s.mode === "generate" && (!edit.shotId || s.id === edit.shotId) ? { ...s, prompt: buildShotPrompt(p, cl, s) } : s)),
+ }));
+ }
+ case "layout": {
+ const c = mustClip(p, edit.clipId);
+ const s = mustShot(c, edit.shotId);
+ if (shotBusy(s, o.active)) throw new EditError("Wait for this shot's takes to finish (or stop them) before changing its segments", 409);
+ let items: SwapSegment[];
+ try {
+ items = applyLayout(s, edit.op, o.rand);
+ } catch (e) {
+ throw new EditError((e as Error).message);
+ }
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, (x) => ({ ...x, segments: items })));
+ }
+ case "segment": {
+ const c = mustClip(p, edit.clipId);
+ const s = mustShot(c, edit.shotId);
+ const x = edit.patch;
+ const shot = withSegment(s, edit.segmentId, (seg) => {
+ const next: SwapSegment = { ...seg, needsReview: false };
+ // Words and speaker never rewrite the prompt by themselves: the prompt stays as it reads now.
+ if ((x.dialogue !== undefined || x.speaker !== undefined) && x.performancePrompt === undefined) next.performancePrompt = segmentPrompt(p, c, s, seg);
+ if (x.prompt !== undefined) next.prompt = text(x.prompt, SWAP_STUDIO.maxPromptChars, "direction")!;
+ if (x.performancePrompt !== undefined) next.performancePrompt = text(x.performancePrompt, SWAP_STUDIO.maxPromptChars, "prompt") ?? null;
+ if (x.dialogue !== undefined) next.dialogue = text(x.dialogue, SWAP_STUDIO.maxPromptChars, "dialogue") ?? null;
+ if (x.speaker !== undefined) next.speaker = x.speaker;
+ if (x.seed !== undefined) next.seed = x.seed;
+ if (x.connection !== undefined) next.connection = x.connection;
+ if (x.history !== undefined) next.history = x.history;
+ if (x.anchorMode !== undefined) next.anchorMode = x.anchorMode;
+ if (x.anchor !== undefined) {
+ if (x.anchor && !seg.anchors.some((a) => a.id === x.anchor && a.url)) throw new EditError("That reference isn't ready yet");
+ next.anchor = x.anchor;
+ }
+ return next;
+ });
+ const problem = segmentsProblem(shot, shot.segments!);
+ if (problem) throw new EditError(problem);
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, () => shot));
+ }
+ case "update-prompt": {
+ const c = mustClip(p, edit.clipId);
+ const s = mustShot(c, edit.shotId);
+ const shot = withSegment(s, edit.segmentId, (seg) => ({ ...seg, performancePrompt: buildSegmentPrompt(p, c, s, seg), needsReview: false }));
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, () => shot));
+ }
+ case "take": {
+ const c = mustClip(p, edit.clipId);
+ const s = mustShot(c, edit.shotId);
+ const shot = withSegment(s, edit.segmentId, (seg) => {
+ try {
+ let next = seg;
+ if (edit.remove) {
+ const t = next.takes.find((k) => k.id === edit.takeId);
+ if (t && (t.state === "waiting" || (t.genId && o.active(t.genId)))) throw new Error("Stop the take before removing it");
+ return removeTake(next, edit.takeId);
+ }
+ if (edit.select) next = selectTake(next, edit.takeId);
+ const patch = { ...(edit.favourite !== undefined ? { favourite: edit.favourite } : {}), ...(edit.decision ? { decision: edit.decision } : {}), ...(edit.notes !== undefined ? { notes: edit.notes } : {}) };
+ return Object.keys(patch).length ? updateTake(next, edit.takeId, patch) : next;
+ } catch (e) {
+ throw new EditError((e as Error).message);
+ }
+ });
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, () => shot));
+ }
+ case "anchor-import": {
+ const c = mustClip(p, edit.clipId);
+ const s = mustShot(c, edit.shotId);
+ if (!edit.url.startsWith("/api/files/")) throw new EditError("Upload the image first");
+ const variant = { id: edit.id, createdAt: edit.at, source: "imported" as const, url: edit.url };
+ if (edit.segmentId) {
+ const shot = withSegment(s, edit.segmentId, (seg) => {
+ if (seg.anchors.length >= SWAP_STUDIO.maxAnchors) throw new EditError(`Keep at most ${SWAP_STUDIO.maxAnchors} references a segment — remove one first`);
+ return { ...seg, anchors: [...seg.anchors, variant], anchor: seg.anchor ?? variant.id };
+ });
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, () => shot));
+ }
+ if (s.anchors.length >= SWAP_STUDIO.maxAnchors) throw new EditError(`Keep at most ${SWAP_STUDIO.maxAnchors} anchors a shot — remove one first`);
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, (x) => ({ ...x, anchors: [...x.anchors, variant] })));
+ }
+ case "remove-anchor": {
+ const c = mustClip(p, edit.clipId);
+ const s = mustShot(c, edit.shotId);
+ if (edit.segmentId) {
+ const shot = withSegment(s, edit.segmentId, (seg) => ({ ...seg, anchors: seg.anchors.filter((a) => a.id !== edit.anchorId), anchor: seg.anchor === edit.anchorId ? null : seg.anchor }));
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, () => shot));
+ }
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, (x) => ({ ...x, anchors: x.anchors.filter((a) => a.id !== edit.anchorId), approvedAnchor: x.approvedAnchor === edit.anchorId ? null : x.approvedAnchor })));
+ }
+ case "remove-mask": {
+ const c = mustClip(p, edit.clipId);
+ const s = mustShot(c, edit.shotId);
+ const m = s.masks.find((x) => x.id === edit.maskId);
+ if (m && [m.genId, ...m.pieces.map((x) => x.genId)].some((id) => !!id && o.active(id))) throw new EditError("That mask is still being made");
+ return mapClip(p, c.id, (cl) => mapShot(cl, s.id, (x) => ({ ...x, masks: x.masks.filter((v) => v.id !== edit.maskId), approvedMask: x.approvedMask === edit.maskId ? null : x.approvedMask })));
+ }
+ }
+}
diff --git a/src/lib/catalog/swap-studio-plan.ts b/src/lib/catalog/swap-studio-plan.ts
index 921289f6..ba50aff3 100644
--- a/src/lib/catalog/swap-studio-plan.ts
+++ b/src/lib/catalog/swap-studio-plan.ts
@@ -29,6 +29,7 @@ import {
type SwapProject,
type SwapSegment,
type SwapShot,
+ type SwapTake,
type WhoToSwap,
} from "./swap-studio";
import { silenceRef } from "./canvas";
@@ -371,6 +372,38 @@ export function planSegmentTake(p: SegmentPlanInput): { steps: PlanStep[]; final
return { steps, final: "swap" };
}
+/**
+ * A queued take's steps from what it was queued with (take.frozen): the shot's frames, settings, who to swap, anchor,
+ * mask, history, prompt and seed as they were, and the previous take it continues from as it came out.
+ */
+export function frozenTakePlan(
+ project: SwapProject,
+ clip: SwapClip,
+ shot: SwapShot,
+ seg: SwapSegment,
+ take: SwapTake,
+ numbers: { shot: number; segment: number; take: number },
+ previous: SegmentPlanInput["previous"],
+): { steps: PlanStep[]; final: string } {
+ const f = take.frozen;
+ if (!f) throw new Error("This take wasn't queued from the studio — queue the segment again");
+ return planSegmentTake({
+ engine: take.engine,
+ project: { ...project, character: { ...project.character, image: f.reference } },
+ clip,
+ shot: { ...shot, start: f.shotStart, settings: f.settings, who: f.who },
+ seg: { ...seg, start: f.start, end: f.end, seed: take.seed },
+ shotNumber: numbers.shot,
+ segNumber: numbers.segment,
+ takeNumber: numbers.take,
+ prompt: take.prompt,
+ history: f.history,
+ anchor: f.anchor,
+ mask: f.mask,
+ previous,
+ });
+}
+
// ---------------------------------------------------------------------------
// Assembly
diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.ts
index 2fbe6ece..fca5a132 100644
--- a/src/lib/catalog/swap-studio.ts
+++ b/src/lib/catalog/swap-studio.ts
@@ -142,8 +142,9 @@ export interface MaskVersion {
/** The version it corrects. */
base?: string;
pieces: MaskPiece[];
- /** The job that makes the newest piece. */
+ /** The job that makes the newest piece, and every step it took. */
genId?: string;
+ stepIds?: string[];
}
export interface AnchorVariant {
@@ -153,10 +154,30 @@ export interface AnchorVariant {
/** The image (an upload, or the job's output once it is done). */
url?: string;
genId?: string;
+ stepIds?: string[];
modelId?: string;
prompt?: string;
}
+/**
+ * What a take was queued with (Akatz's freeze): a continuation launches later, once the takes it continues from are
+ * made, and runs with the settings, words, anchor and mask it was queued with, not what was edited meanwhile.
+ */
+export interface FrozenTake {
+ reference: string;
+ /** The shot's first frame in the clip, and the segment's frames in the shot. */
+ shotStart: number;
+ start: number;
+ end: number;
+ /** Frames of continuation history (0: starts fresh). */
+ history: number;
+ anchor: string | null;
+ /** Your GPU: the approved mask video (masked generation on). */
+ mask: string | null;
+ settings: SwapSettings;
+ who: WhoToSwap;
+}
+
export interface TakeDependency {
segmentId: string;
takeId: string | null;
@@ -187,6 +208,9 @@ export interface SwapTake {
favourite: boolean;
decision: Decision;
notes: string;
+ frozen?: FrozenTake;
+ /** The studio has looked at its finished result (selected it, or left the selection alone). */
+ settled?: boolean;
}
export interface SwapSegment {
@@ -929,6 +953,10 @@ export function planQueue(
} catch (e) {
return { problem: `Segment ${n}: ${(e as Error).message.toLowerCase()}` };
}
+ // Your GPU continues from the segment before it: its take's lossless master holds that segment's frames only.
+ if (engine === "open" && deps.length > 1) {
+ return { problem: `Segment ${n}: its ${effectiveHistory(seg)} frames of history reach back past segment ${n - 1} — on your GPU a continuation reads the segment before it; shorten the history or lengthen segment ${n - 1}` };
+ }
for (const d of deps) {
const j = items.findIndex((s) => s.id === d.segmentId);
if (queued.has(j)) {
@@ -945,6 +973,106 @@ export function planQueue(
return { entries };
}
+/** A segment's take as queued now: what it will run with (see FrozenTake). */
+export function freezeTake(project: SwapProject, shot: SwapShot, seg: SwapSegment): FrozenTake {
+ const mask = project.engine === "open" && shot.settings.useMask ? (approvedMask(shot)?.pieces[0]?.url ?? null) : null;
+ return {
+ reference: project.character.image ?? "",
+ shotStart: shot.start,
+ start: seg.start,
+ end: seg.end,
+ history: effectiveHistory(seg),
+ anchor: segmentAnchor(shot, seg),
+ mask,
+ settings: { ...shot.settings },
+ who: { ...shot.who },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Jobs as the page sees them
+
+export type GenStatus = "queued" | "running" | "succeeded" | "failed" | "canceled";
+
+/** A generation as the project view reports it. */
+export interface GenSummary {
+ status: GenStatus;
+ progress: number | null;
+ message: string | null;
+ error: string | null;
+ /** The main output, and (your GPU's takes) the lossless master. */
+ url?: string;
+ master?: string;
+ costUsd: number | null;
+ demo: boolean;
+}
+
+export type JobStatus = "waiting" | "stopped" | GenStatus | "missing";
+
+/**
+ * One job (a take, a mask, an anchor, an assembly) from its generations: the final one's state, unless a step before it
+ * failed (its error is the reason) — progress counts the steps done.
+ */
+export function jobState(finalId: string | undefined, stepIds: string[] | undefined, gens: Record<string, GenSummary | undefined>): { status: JobStatus; progress: number | null; message: string | null } {
+ if (!finalId) return { status: "missing", progress: null, message: null };
+ const final = gens[finalId];
+ if (!final) return { status: "missing", progress: null, message: "This job is gone from the Library" };
+ const steps = (stepIds?.length ? stepIds : [finalId]).map((id) => gens[id]).filter((g): g is GenSummary => !!g);
+ const failed = steps.find((g) => g.status === "failed" && g.error);
+ if (final.status === "failed" || final.status === "canceled") return { status: final.status, progress: null, message: failed?.error ?? final.error ?? final.message };
+ if (final.status === "succeeded") return { status: "succeeded", progress: 1, message: null };
+ const done = steps.filter((g) => g.status === "succeeded").length;
+ const running = steps.find((g) => g.status === "running");
+ const progress = steps.length > 1 ? (done + (running?.progress ?? 0)) / steps.length : final.progress;
+ return { status: running || final.status === "running" ? "running" : "queued", progress, message: running?.message ?? final.message };
+}
+
+// ---------------------------------------------------------------------------
+// What the API answers (src/server/swap-studio.ts)
+
+export interface SwapProjectCard {
+ id: string;
+ name: string;
+ engine: Engine;
+ clips: number;
+ shots: number;
+ swapped: number;
+ assembled: number;
+ waiting: number;
+ character: string | null;
+ updatedAt: number;
+}
+
+export interface SwapProjectView {
+ project: SwapProject;
+ /** Every generation the project names. */
+ gens: Record<string, GenSummary>;
+ /** Akatz's "Finish" stage and the workers note, said on the page. */
+ workers: string;
+}
+
+export interface StudioEstimate {
+ engine: Engine;
+ /** Runs as a demo (no provider for it): nothing is paid for. */
+ demo: boolean;
+ /** Your GPU: nothing to pay. */
+ free: boolean;
+ /** One take of each generated segment (null: price unknown, or it can't run yet — see `problems`). */
+ segments: Record<string, number | null>;
+ problems: Record<string, string>;
+ /** "Queue all" for each shot: the segments that aren't current. */
+ shots: Record<string, { costUsd: number | null; segments: number }>;
+ /** Every shot's "Queue all", across the project. */
+ project: { costUsd: number | null; segments: number };
+ assembly: Record<string, number | null>;
+ transcribe: Record<string, number | null>;
+ /** Tracking a whole shot's mask. */
+ mask: Record<string, number | null>;
+ /** One anchor with each model on this engine. */
+ anchors: { id: string; label: string; note: string; costUsd: number | null; offered: boolean }[];
+ notes: string[];
+}
+
// ---------------------------------------------------------------------------
// Masks
diff --git a/src/lib/record-pages.ts b/src/lib/record-pages.ts
index ec33d506..a0f1cbd4 100644
--- a/src/lib/record-pages.ts
+++ b/src/lib/record-pages.ts
@@ -8,7 +8,7 @@
*/
import { HUB_MODES, type HubKind } from "./hubs";
-export type RecordKind = "cinema" | "canvas" | "assist-project" | "layers" | "shorts" | "brand" | "element" | "channel" | "episode" | "explainer" | "series";
+export type RecordKind = "cinema" | "canvas" | "assist-project" | "layers" | "shorts" | "brand" | "element" | "channel" | "episode" | "explainer" | "series" | "swap-project";
/** A record a page needs, with its ids in the order the lookup takes them. */
export interface RecordRef {
@@ -32,6 +32,7 @@ const PAGES: [RegExp, (m: string[]) => RecordRef][] = [
[new RegExp(`^/faceless/${SEG}$`), ([id]) => ({ kind: "channel", ids: [id] })],
[new RegExp(`^/explainer/${SEG}$`), ([id]) => ({ kind: "explainer", ids: [id] })],
[new RegExp(`^/content-factory/${SEG}$`), ([id]) => ({ kind: "series", ids: [id] })],
+ [new RegExp(`^/character-swap/${SEG}$`), ([id]) => ({ kind: "swap-project", ids: [id] })],
];
/** Static pages that a record pattern would also match (/ads/multiplier is not a brand). */
diff --git a/src/server/db.ts b/src/server/db.ts
index 72c5bc93..3e9ce4aa 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -538,6 +538,23 @@ const MIGRATIONS: string[] = [
ALTER TABLE assist_thread_state ADD COLUMN spent_usd REAL NOT NULL DEFAULT 0;
ALTER TABLE assist_thread_state ADD COLUMN connectors INTEGER NOT NULL DEFAULT 1;
CREATE INDEX IF NOT EXISTS assist_thread_state_schedule ON assist_thread_state(schedule_id);`,
+ // originals (o/h3-studio): Character Swap Studio projects — the character (picture and description), the clips with
+ // their 24 fps copies, cuts and shots, transcripts and voices, masks and anchors, segments with their takes, review
+ // decisions and assemblies, as one document (data_json; revision counts saves, so an open page knows it changed).
+ // Every job is an ordinary generation the document names by id. `waiting`: takes queued behind the segments they
+ // continue from, which the studio's sweep launches once those are made.
+ `CREATE TABLE IF NOT EXISTS swap_projects (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ engine TEXT NOT NULL,
+ data_json TEXT NOT NULL,
+ revision INTEGER NOT NULL DEFAULT 1,
+ waiting INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS swap_projects_updated ON swap_projects(updated_at DESC);
+ CREATE INDEX IF NOT EXISTS swap_projects_waiting ON swap_projects(waiting) WHERE waiting > 0;`,
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 00fedb01..dd99afaa 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -295,6 +295,8 @@ export const ASSET_REFS: AssetRef[] = [
{ table: "content_series", cols: ["data_json"], what: "Content Factory series", name: "COALESCE(json_extract(data_json, '$.name'), json_extract(data_json, '$.reference.title'))" },
// Assist's scheduled tasks: the files the prompt runs with.
{ table: "assist_schedules", cols: ["attachments_json"], what: "scheduled task", name: "title" },
+ // Character Swap Studio: the character picture, each clip and its 24 fps copy, masks, anchors, takes and their masters.
+ { table: "swap_projects", cols: ["data_json"], what: "Character Swap project", name: "name" },
];
/**
diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.ts
index 4d879795..4e7006dc 100644
--- a/src/server/providers/mock.ts
+++ b/src/server/providers/mock.ts
@@ -334,6 +334,11 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,
case "bg-remove-video":
return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true, role: meta.matteOutput } }];
case "video-swap":
+ return [
+ { url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true } },
+ // Character Swap Studio's segment graph also saves a lossless master the next segment continues from.
+ ...(meta.master ? [{ url: `sample:${sampleClip(ar)}`, kind: "video" as const, contentType: "video/mp4", meta: { role: "master", demo: true } }] : []),
+ ];
case "video-insert":
case "keyframes":
case "still-motion":
@@ -400,6 +405,8 @@ export const mockProvider: ProviderAdapter = {
lastMask: route.provider === "comfyui" && route.endpoint === "video-inpaint-wan-vace-painted" && input.extra?.[HAND_OFF] === true,
// Workflows whose second output is the cut's first frame (video-segment-resample).
firstFrame: route.provider === "comfyui" && route.endpoint === "video-segment-resample",
+ // Character Swap Studio's segment graph: the take and its lossless master (video-character-swap-h3-segment).
+ master: route.provider === "comfyui" && route.endpoint === "video-character-swap-h3-segment",
// A stem split that also transcribes (ComfyUI's dub-prepare-separate-transcribe).
transcript: route.op === "separate-audio" && route.provider === "comfyui" && route.endpoint.includes("transcribe"),
},
diff --git a/src/server/records.ts b/src/server/records.ts
index e5069846..511fd52c 100644
--- a/src/server/records.ts
+++ b/src/server/records.ts
@@ -15,6 +15,7 @@ const LOOKUPS: Record<RecordRef["kind"], string> = {
episode: "SELECT 1 FROM faceless_episodes WHERE channel_id = ? AND id = ?",
explainer: "SELECT 1 FROM faceless_episodes WHERE id = ?",
series: "SELECT 1 FROM content_series WHERE id = ?",
+ "swap-project": "SELECT 1 FROM swap_projects WHERE id = ?",
};
/**
diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.ts
new file mode 100644
index 00000000..e954c3e9
--- /dev/null
+++ b/src/server/swap-studio.ts
@@ -0,0 +1,1151 @@
+import "server-only";
+import { z } from "zod";
+import { getModel } from "@/lib/catalog";
+import { ANCHOR_MODELS, anchorModel, characterLicenceLine, SWAP_LORAS, swapLoraRef, TURBO_LORA } from "@/lib/catalog/character-swap";
+import { scalePoints } from "@/lib/catalog/remove-object";
+import type { PlanStep } from "@/lib/catalog/shorts";
+import {
+ approvedMask,
+ assemblyPieces,
+ assemblyTakes,
+ clipProblem,
+ currentSegments,
+ DEFAULT_SETTINGS,
+ exportDecisions,
+ freezeTake,
+ maskPieces,
+ maskProblem,
+ newShot,
+ normalizedSize,
+ planQueue,
+ segmentPrompt,
+ segmentStates,
+ settingSignature,
+ autoSelect,
+ SWAP_STUDIO,
+ uid,
+ WORKERS_NOTE,
+ type DecisionExport,
+ type GenSummary,
+ type StudioEstimate,
+ type SwapProjectCard,
+ type SwapProjectView,
+ type MaskVersion,
+ type QueueMode,
+ type SwapClip,
+ type SwapProject,
+ type SwapSegment,
+ type SwapShot,
+ type SwapTake,
+ type TranscriptCue,
+} from "@/lib/catalog/swap-studio";
+import { applyEdit, EditError, type SwapEdit } from "@/lib/catalog/swap-studio-edit";
+import { frozenTakePlan, planAnchor, planAssembly, planMask, planNormalize, planTranscribe, STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
+import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";
+import { ACCESS_PLACE } from "@/lib/model-access";
+import { createPipeline } from "./chains";
+import { db } from "./db";
+import { cancelGeneration, getGeneration, previewChained } from "./generations";
+import { isOffered, offeredLoras } from "./model-access";
+import { engineMode } from "./settings";
+import { probeSource, ShortsError } from "./shorts";
+
+/**
+ * Character Swap Studio on the server (/character-swap): projects in swap_projects (one JSON document each, see
+ * src/lib/catalog/swap-studio.ts), every job an ordinary generation made through createPipeline (feature
+ * "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.
+ */
+
+export { ShortsError as StudioError };
+export type { StudioEstimate, SwapProjectCard, SwapProjectView };
+
+// ---------------------------------------------------------------------------
+// Rows
+
+interface Row {
+ id: string;
+ name: string;
+ engine: string;
+ data_json: string;
+ revision: number;
+ waiting: number;
+ created_at: number;
+ updated_at: number;
+}
+
+const rowOf = (id: string) => db().prepare("SELECT * FROM swap_projects WHERE id = ?").get(id) as Row | undefined;
+
+function fromRow(r: Row): SwapProject {
+ const d = JSON.parse(r.data_json) as SwapProject;
+ return { ...d, id: r.id, name: r.name, engine: r.engine === "open" ? "open" : "cloud", revision: r.revision, createdAt: r.created_at, updatedAt: r.updated_at };
+}
+
+const takesOf = (p: SwapProject) => p.clips.flatMap((c) => c.shots.flatMap((s) => (s.segments ?? []).flatMap((g) => g.takes)));
+
+function write(p: SwapProject): SwapProject {
+ const next = { ...p, revision: p.revision + 1, updatedAt: Date.now() };
+ const waiting = takesOf(next).filter((t) => t.state === "waiting").length;
+ 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 {
+ const r = rowOf(id);
+ if (!r) throw new ShortsError("Project not found", 404);
+ return fromRow(r);
+}
+
+/** 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);
+ const next = fn(cur);
+ return next === cur ? cur : write(next);
+}
+
+function mustClip(p: SwapProject, clipId: string): SwapClip {
+ const c = p.clips.find((x) => x.id === clipId);
+ if (!c) throw new ShortsError("That clip is no longer in this project — reload", 404);
+ return c;
+}
+function mustShot(c: SwapClip, shotId: string): SwapShot {
+ const s = c.shots.find((x) => x.id === shotId);
+ if (!s) throw new ShortsError("That shot changed — reload", 404);
+ return s;
+}
+
+const mapClip = (p: SwapProject, id: string, f: (c: SwapClip) => SwapClip): SwapProject => ({ ...p, clips: p.clips.map((c) => (c.id === id ? f(c) : c)) });
+const mapShot = (c: SwapClip, id: string, f: (s: SwapShot) => SwapShot): SwapClip => ({ ...c, shots: c.shots.map((s) => (s.id === id ? f(s) : s)) });
+
+// ---------------------------------------------------------------------------
+// Generations as the studio reads them
+
+const mainOutput = (g: Generation) => g.outputs.find((o) => o.meta?.role !== "master") ?? g.outputs[0];
+const masterOutput = (g: Generation) => g.outputs.find((o) => o.meta?.role === "master");
+
+export function genSummary(g: Generation): GenSummary {
+ const main = mainOutput(g);
+ const master = masterOutput(g);
+ return {
+ status: g.status,
+ progress: g.progress,
+ message: g.message,
+ error: g.error,
+ ...(main ? { url: main.url } : {}),
+ ...(master ? { master: master.url } : {}),
+ costUsd: g.costUsd,
+ demo: g.provider === "mock",
+ };
+}
+
+/** One lookup per id for the duration of a read. */
+function lookup(): (id: string | undefined) => Generation | null {
+ const cache = new Map<string, Generation | null>();
+ return (id) => {
+ if (!id) return null;
+ if (!cache.has(id)) cache.set(id, getGeneration(id, { includeDeleted: true }));
+ return cache.get(id)!;
+ };
+}
+
+const ACTIVE = new Set(["queued", "running"]);
+
+/** Every generation a project names. */
+function projectGenIds(p: SwapProject): string[] {
+ const ids: (string | undefined)[] = [];
+ for (const c of p.clips) {
+ ids.push(c.normalized?.genId, c.transcript?.genId, c.assembly?.genId, ...(c.assembly?.stepIds ?? []));
+ for (const s of c.shots) {
+ for (const m of s.masks) ids.push(m.genId, ...(m.stepIds ?? []), ...m.pieces.map((x) => x.genId));
+ for (const a of s.anchors) ids.push(a.genId, ...(a.stepIds ?? []));
+ for (const g of s.segments ?? []) {
+ for (const a of g.anchors) ids.push(a.genId, ...(a.stepIds ?? []));
+ for (const t of g.takes) ids.push(t.genId, ...(t.stepIds ?? []));
+ }
+ }
+ }
+ return [...new Set(ids.filter((x): x is string => !!x))];
+}
+
+/** The transcript's cues (with the speakers a diarizing transcriber names). */
+function cuesOf(g: Generation): TranscriptCue[] {
+ const raw = g.outputs.find((o) => Array.isArray(o.meta?.cues))?.meta?.cues as unknown[] | undefined;
+ const out: TranscriptCue[] = [];
+ for (const c of raw ?? []) {
+ const x = c as Partial<TranscriptCue>;
+ if (typeof x.start !== "number" || typeof x.end !== "number" || typeof x.text !== "string") continue;
+ out.push({ start: x.start, end: x.end, text: x.text, ...(typeof x.speaker === "string" && x.speaker ? { speaker: x.speaker } : {}) });
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Settling: fill in what finished, select finished takes, launch or stop waiting ones
+
+type Look = ReturnType<typeof lookup>;
+
+function settleShot(project: SwapProject, clip: SwapClip, shot: SwapShot, look: Look, shotIndex: number): SwapShot {
+ const done = (id?: string) => {
+ const g = look(id);
+ return g?.status === "succeeded" ? g : null;
+ };
+ let s = shot;
+ // Masks: each piece's video once it is made (the matte).
+ if (s.masks.some((m) => m.pieces.some((x) => x.genId && !x.url && done(x.genId)))) {
+ s = { ...s, masks: s.masks.map((m) => ({ ...m, pieces: m.pieces.map((x) => (x.genId && !x.url && done(x.genId) ? { ...x, url: mainOutput(done(x.genId)!)?.url } : x)) })) };
+ }
+ // Anchors: the edited image.
+ const fill = <T extends { genId?: string; url?: string }>(list: T[]) => list.map((a) => (a.genId && !a.url && done(a.genId) ? { ...a, url: mainOutput(done(a.genId)!)?.url } : a));
+ if (s.anchors.some((a) => a.genId && !a.url && done(a.genId))) s = { ...s, anchors: fill(s.anchors) };
+ if (!s.segments) return s;
+ let items = s.segments;
+ if (items.some((g) => g.anchors.some((a) => a.genId && !a.url && done(a.genId)))) {
+ items = items.map((g) => {
+ const anchors = fill(g.anchors);
+ // A segment's first reference that is ready becomes its pick.
+ return { ...g, anchors, anchor: g.anchor ?? anchors.find((a) => a.url)?.id ?? null };
+ });
+ }
+ // Finished takes: selected when nothing changed since they were queued (Akatz's attach_take).
+ const view = { ...s, segments: items };
+ let next = items;
+ items.forEach((seg, i) => {
+ for (const t of seg.takes) {
+ if (t.state !== "launched" || t.settled || !t.genId) continue;
+ const g = look(t.genId);
+ if (!g || ACTIVE.has(g.status)) continue;
+ const pick = g.status === "succeeded" && autoSelect(project, clip, view, next[i], t, next);
+ next = next.map((x, j) => (j === i ? { ...x, selectedTake: pick ? t.id : x.selectedTake, takes: x.takes.map((k) => (k.id === t.id ? { ...k, settled: true } : k)) } : x));
+ }
+ });
+ if (next !== s.segments) s = { ...s, segments: next };
+ return launchWaiting(project, clip, s, look, shotIndex);
+}
+
+/** Waiting takes whose segments-before are made launch; those whose segments-before failed stop, with the reason. */
+function launchWaiting(project: SwapProject, clip: SwapClip, shot: SwapShot, look: Look, shotIndex: number): SwapShot {
+ const items = shot.segments ?? [];
+ if (!items.some((g) => g.takes.some((t) => t.state === "waiting"))) return shot;
+ const all = items.flatMap((g, i) => g.takes.map((t) => ({ take: t, seg: g, index: i })));
+ let out = items;
+ const update = (segId: string, take: SwapTake) => {
+ out = out.map((g) => (g.id === segId ? { ...g, takes: g.takes.map((t) => (t.id === take.id ? take : t)) } : g));
+ };
+ // In segment order, so a stop reaches every take after it in the same sweep.
+ for (const [i, seg] of items.entries()) {
+ for (const take of seg.takes) {
+ if (take.state !== "waiting") continue;
+ let blocked: string | null = null;
+ let ready = true;
+ for (const d of take.dependencies) {
+ const found = all.find((x) => x.take.id === d.takeId);
+ const current = found ? out[found.index].takes.find((t) => t.id === found.take.id)! : null;
+ const n = (found?.index ?? items.findIndex((g) => g.id === d.segmentId)) + 1;
+ if (!current) {
+ blocked = `Stopped: segment ${n}'s take it continues from was removed`;
+ break;
+ }
+ if (current.state === "stopped") {
+ blocked = `Stopped: segment ${n}'s take didn't run${current.reason ? ` (${current.reason.replace(/^Stopped: /, "")})` : ""}`;
+ break;
+ }
+ if (current.state === "waiting") {
+ ready = false;
+ continue;
+ }
+ const g = look(current.genId);
+ if (!g) {
+ blocked = `Stopped: segment ${n}'s take is gone from the Library`;
+ break;
+ }
+ if (g.status === "failed" || g.status === "canceled") {
+ const why = g.status === "failed" ? "failed" : "was stopped";
+ const steps = (current.stepIds ?? []).map((id) => look(id)).find((x) => x?.status === "failed" && x.error);
+ blocked = `Stopped: segment ${n}'s take ${why}${steps?.error || g.error ? ` — ${steps?.error ?? g.error}` : ""}`;
+ break;
+ }
+ if (g.status !== "succeeded") ready = false;
+ }
+ if (blocked) {
+ update(seg.id, { ...take, state: "stopped", reason: blocked, waitsOn: undefined });
+ continue;
+ }
+ if (!ready) continue;
+ try {
+ update(seg.id, launchTake(project, clip, { ...shot, segments: out }, out[i], take, shotIndex, i, look));
+ } catch (e) {
+ update(seg.id, { ...take, state: "stopped", reason: `Stopped: ${(e as Error).message}`, waitsOn: undefined });
+ }
+ }
+ }
+ return out === items ? shot : { ...shot, segments: out };
+}
+
+/** Start one take's generations (its segments-before are made). */
+function launchTake(project: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, take: SwapTake, shotIndex: number, segIndex: number, look: Look): SwapTake {
+ const items = shot.segments ?? [];
+ let previous: { master?: string; video?: string; frames: number } | null = null;
+ if (take.frozen && take.frozen.history > 0) {
+ // The segment right before it (your GPU continues from it alone; the cloud from its last frame).
+ const dep = take.dependencies[take.dependencies.length - 1];
+ const before = items.find((g) => g.id === dep?.segmentId);
+ const prev = before?.takes.find((t) => t.id === dep?.takeId);
+ const g = look(prev?.genId);
+ if (!before || !prev || !g) throw new Error("the take it continues from is gone");
+ previous = { master: masterOutput(g)?.url, video: mainOutput(g)?.url, frames: before.end - before.start };
+ }
+ 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);
+ return { ...take, state: "launched", waitsOn: undefined, genId: pipe.byKey[plan.final].id, stepIds: pipe.items.map((g) => g.id) };
+}
+
+function settleClip(project: SwapProject, clip: SwapClip, look: Look): SwapClip {
+ let c = clip;
+ const ok = (id?: string) => {
+ const g = look(id);
+ return g?.status === "succeeded" ? g : null;
+ };
+ if (c.normalized?.genId && !c.normalized.url && ok(c.normalized.genId)) c = { ...c, normalized: { ...c.normalized, url: mainOutput(ok(c.normalized.genId)!)?.url } };
+ if (c.transcript?.genId && c.transcript.cues === null && ok(c.transcript.genId)) c = { ...c, transcript: { ...c.transcript, cues: cuesOf(ok(c.transcript.genId)!) } };
+ const shots = c.shots.map((s, i) => settleShot(project, c, s, look, i));
+ return shots.some((s, i) => s !== c.shots[i]) ? { ...c, shots } : c;
+}
+
+/** The project with every finished job filled in and every ready waiting take launched (pure apart from launching). */
+function settle(p: SwapProject, look: Look): SwapProject {
+ const clips = p.clips.map((c) => settleClip(p, c, look));
+ return clips.some((c, i) => c !== p.clips[i]) ? { ...p, clips } : p;
+}
+
+/** Read a project and bring it up to date (saved when anything changed). */
+export function advanceProject(id: string): SwapProject {
+ return mutate(id, (p) => settle(p, lookup()));
+}
+
+declare global {
+ var __fuobeSwapStudioRunner: ReturnType<typeof setInterval> | undefined;
+}
+
+/**
+ * The sweep: takes queued behind the segments they continue from launch when those are made (or stop when they
+ * failed), also while nobody has the page open. Every 3 s over projects with waiting takes.
+ */
+export function ensureSwapStudioRunner(): void {
+ if (globalThis.__fuobeSwapStudioRunner) return;
+ const tick = () => {
+ try {
+ const rows = db().prepare("SELECT id FROM swap_projects WHERE waiting > 0").all() as { id: string }[];
+ for (const r of rows) {
+ try {
+ 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);
+ }
+ };
+ globalThis.__fuobeSwapStudioRunner = setInterval(tick, 3000);
+ globalThis.__fuobeSwapStudioRunner.unref?.();
+ setTimeout(tick, 500).unref?.();
+}
+
+// ---------------------------------------------------------------------------
+// Projects
+
+
+export function listProjects(limit = 100): SwapProjectCard[] {
+ 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,
+ };
+ });
+}
+
+const mustMatchMode = (engine: Engine) => {
+ const mode = engineMode();
+ if (mode !== "both" && mode !== engine) {
+ 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);
+ }
+};
+
+/** The engine a new project starts on: the install's only one, else your GPU (Akatz's tool is a local workbench). */
+export const defaultEngine = (): Engine => (engineMode() === "cloud" ? "cloud" : "open");
+
+export const CreateSchema = z.object({
+ name: z.string().max(200).optional(),
+ engine: z.enum(["cloud", "open"]).optional(),
+ character: z.object({ image: z.string().startsWith("/api/files/").max(500).nullable().optional(), description: z.string().max(SWAP_STUDIO.maxDescriptionChars).optional() }).optional(),
+});
+
+export function createProject(body: z.infer<typeof CreateSchema>): SwapProject {
+ const engine = body.engine ?? defaultEngine();
+ mustMatchMode(engine);
+ const now = Date.now();
+ const p: SwapProject = {
+ id: uid("swap-"),
+ name: body.name?.trim().slice(0, SWAP_STUDIO.maxNameChars) || "Untitled character swap",
+ engine,
+ character: { image: body.character?.image ?? null, description: body.character?.description?.trim() ?? "" },
+ defaults: { ...DEFAULT_SETTINGS },
+ clips: [],
+ createdAt: now,
+ updatedAt: now,
+ revision: 1,
+ };
+ 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);
+ return p;
+}
+
+/** Delete a project, stopping what it still makes (finished results stay in the Library). */
+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);
+ for (const g of active) await cancelGeneration(g).catch(() => undefined);
+}
+
+
+export function projectView(id: string): SwapProjectView {
+ const project = advanceProject(id);
+ const look = lookup();
+ const gens: Record<string, GenSummary> = {};
+ for (const gid of projectGenIds(project)) {
+ const g = look(gid);
+ if (g) gens[gid] = genSummary(g);
+ }
+ return { project, gens, workers: WORKERS_NOTE };
+}
+
+// ---------------------------------------------------------------------------
+// Edits
+
+const fileUrl = z.string().startsWith("/api/files/").max(500);
+const role = z.enum(["target", "other", "offscreen", "none"]);
+const decision = z.enum(["pending", "keep", "maybe", "skip"]);
+const settings = z
+ .object({
+ lora: z.enum(["v1.5", "v1", "none"]),
+ useAnchor: z.boolean(),
+ useMask: z.boolean(),
+ renderMp: z.union([z.literal(0.5), z.literal(1)]),
+ seed: z.number().int(),
+ windowFrames: z.number().int(),
+ historyFrames: z.number().int(),
+ expansion: z.number().int(),
+ })
+ .partial();
+const text = (max: number) => z.string().max(max);
+const id = z.string().min(1).max(80);
+
+export const EditSchema = z.discriminatedUnion("type", [
+ z.object({ type: z.literal("rename"), name: z.string().max(200) }),
+ z.object({ type: z.literal("engine"), engine: z.enum(["cloud", "open"]) }),
+ z.object({ type: z.literal("character"), image: fileUrl.nullable().optional(), description: text(SWAP_STUDIO.maxDescriptionChars).optional() }),
+ z.object({ type: z.literal("defaults"), settings }),
+ z.object({ type: z.literal("clip"), clipId: id, name: z.string().max(200).optional(), review: decision.optional(), reviewNotes: text(SWAP_STUDIO.maxNotesChars).optional() }),
+ z.object({ type: z.literal("remove-clip"), clipId: id }),
+ z.object({ type: z.literal("detected"), clipId: id, cuts: z.array(z.number().int()).max(2000) }),
+ z.object({ type: z.literal("cuts"), clipId: id, cuts: z.array(z.number().int()).max(2000), modes: z.array(z.enum(["generate", "preserve"])).max(2001).optional() }),
+ z.object({ type: z.literal("voices"), clipId: id, voices: z.record(z.string().max(80), role) }),
+ z.object({
+ type: z.literal("shot"),
+ clipId: id,
+ shotId: id,
+ patch: z.object({
+ mode: z.enum(["generate", "preserve"]).optional(),
+ speaker: role.nullable().optional(),
+ dialogue: text(SWAP_STUDIO.maxPromptChars).nullable().optional(),
+ prompt: text(SWAP_STUDIO.maxPromptChars).nullable().optional(),
+ who: z.object({ selection: z.enum(["largest", "leftmost", "rightmost", "index"]), index: z.number().int(), words: z.string().max(200) }).partial().optional(),
+ settings: settings.optional(),
+ anchorInstructions: text(SWAP_STUDIO.maxPromptChars).optional(),
+ anchorBasePrompt: text(SWAP_STUDIO.maxPromptChars).optional(),
+ approvedAnchor: id.nullable().optional(),
+ approvedMask: id.nullable().optional(),
+ }),
+ }),
+ z.object({ type: z.literal("build-prompts"), clipId: id, shotId: id.optional() }),
+ z.object({
+ type: z.literal("layout"),
+ clipId: id,
+ shotId: id,
+ op: z.discriminatedUnion("op", [
+ z.object({ op: z.literal("partition"), frames: z.number().int() }),
+ z.object({ op: z.literal("split"), frame: z.number().int() }),
+ z.object({ op: z.literal("merge"), index: z.number().int() }),
+ z.object({ op: z.literal("boundary"), index: z.number().int(), frame: z.number().int() }),
+ ]),
+ }),
+ z.object({
+ type: z.literal("segment"),
+ clipId: id,
+ shotId: id,
+ segmentId: id,
+ patch: z.object({
+ prompt: text(SWAP_STUDIO.maxPromptChars).optional(),
+ performancePrompt: text(SWAP_STUDIO.maxPromptChars).nullable().optional(),
+ dialogue: text(SWAP_STUDIO.maxPromptChars).nullable().optional(),
+ speaker: role.nullable().optional(),
+ seed: z.number().int().optional(),
+ connection: z.enum(["start", "continue"]).optional(),
+ history: z.number().int().optional(),
+ anchorMode: z.enum(["shot", "custom", "none"]).optional(),
+ anchor: id.nullable().optional(),
+ }),
+ }),
+ z.object({ type: z.literal("update-prompt"), clipId: id, shotId: id, segmentId: id }),
+ z.object({
+ type: z.literal("take"),
+ clipId: id,
+ shotId: id,
+ segmentId: id,
+ takeId: id,
+ select: z.boolean().optional(),
+ favourite: z.boolean().optional(),
+ decision: decision.optional(),
+ notes: text(SWAP_STUDIO.maxNotesChars).optional(),
+ remove: z.boolean().optional(),
+ }),
+ z.object({ type: z.literal("anchor-import"), clipId: id, shotId: id, segmentId: id.optional(), url: fileUrl }),
+ z.object({ type: z.literal("remove-anchor"), clipId: id, shotId: id, segmentId: id.optional(), anchorId: id }),
+ z.object({ type: z.literal("remove-mask"), clipId: id, shotId: id, maskId: id }),
+]);
+
+export type EditBody = z.infer<typeof EditSchema>;
+
+/** Apply one edit from the page (src/lib/catalog/swap-studio-edit.ts), on the project as it is now. */
+export function editProject(projectId: string, body: EditBody): SwapProject {
+ const look = lookup();
+ const active = (gid: string) => ACTIVE.has(look(gid)?.status ?? "");
+ const after: { engine: Engine | null } = { engine: null };
+ const next = mutate(projectId, (cur) => {
+ const p = settle(cur, look);
+ const edit: SwapEdit = body.type === "anchor-import" ? { ...body, id: uid("anchor-"), at: Date.now() } : (body as SwapEdit);
+ if (edit.type === "engine" && edit.engine !== p.engine) {
+ mustMatchMode(edit.engine);
+ after.engine = edit.engine;
+ }
+ // Only a take that came out can be chosen.
+ if (edit.type === "take" && edit.select) {
+ const clip = mustClip(p, edit.clipId);
+ const seg = currentSegments(mustShot(clip, edit.shotId)).find((g) => g.id === edit.segmentId);
+ const t = seg?.takes.find((k) => k.id === edit.takeId);
+ if (t && look(t.genId)?.status !== "succeeded") throw new ShortsError("Only a finished take can be chosen", 422);
+ }
+ try {
+ return applyEdit(p, edit, { active });
+ } catch (e) {
+ if (e instanceof EditError) throw new ShortsError(e.message, e.status);
+ throw e;
+ }
+ });
+ // Switched to your GPU: the clips need their 24 fps copies.
+ if (after.engine !== "open") return next;
+ for (const c of next.clips) if (!c.normalized) prepareClipQuietly(next.id, c.id);
+ return mustProject(projectId);
+}
+
+// ---------------------------------------------------------------------------
+// Steps run as one pipeline
+
+function run(steps: PlanStep[], existing?: Record<string, string>) {
+ try {
+ return createPipeline(steps, existing ? { existing } : {});
+ } catch (e) {
+ throw new ShortsError((e as Error).message, 422);
+ }
+}
+
+const mustOffer = (modelId: string, engine: Engine, instead?: string) => {
+ if (!isOffered(modelId, engine)) throw new ShortsError(`${getModel(modelId)?.name ?? modelId} is switched off in ${ACCESS_PLACE}${instead ? ` — ${instead}` : ""}`, 422);
+};
+
+// ---------------------------------------------------------------------------
+// Clips
+
+export const ClipSchema = z.object({
+ url: fileUrl,
+ name: z.string().max(200).optional(),
+ duration: z.number().finite().positive().max(36_000).optional(),
+ fps: z.number().finite().positive().max(1000).optional(),
+ width: z.number().int().positive().max(20_000).optional(),
+ height: z.number().int().positive().max(20_000).optional(),
+ hasAudio: z.boolean().optional(),
+ bytes: z.number().int().nonnegative().optional(),
+});
+
+/**
+ * Add a clip: its header is read here (MP4, MOV, MKV, WebM, AVI), it must be at most 149.66 s, and on your GPU its
+ * 24 fps copy starts right away (Akatz's normaliser). The clip starts as one shot until its edits are confirmed.
+ */
+export async function addClip(projectId: string, body: z.infer<typeof ClipSchema>): Promise<SwapProject> {
+ const before = mustProject(projectId);
+ if (before.clips.length >= SWAP_STUDIO.maxClips) throw new ShortsError(`A project holds ${SWAP_STUDIO.maxClips} clips — start another project for more`, 422);
+ const info = await probeSource(body.url);
+ const name = (body.name ?? "clip.mp4").slice(0, 200);
+ const duration = info.duration ?? body.duration;
+ const problem = clipProblem({ name, duration, bytes: body.bytes });
+ if (problem) throw new ShortsError(problem, 422);
+ if (!duration) throw new ShortsError("Couldn't read this clip's length — save it as an MP4 and add it again", 422);
+ const frames = Math.min(SWAP_STUDIO.maxFrames, Math.round(duration * SWAP_STUDIO.fps));
+ if (frames < 2) throw new ShortsError("This clip is too short — add one of at least a few frames", 422);
+ const hasAudio = info.hasAudio ?? body.hasAudio ?? false;
+ const clip: SwapClip = {
+ id: uid("clip-"),
+ name: name.replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, SWAP_STUDIO.maxNameChars) || "Clip",
+ source: { url: body.url, name, duration, fps: info.fps ?? body.fps, width: info.width ?? body.width, height: info.height ?? body.height, hasAudio, ...(body.bytes !== undefined ? { bytes: body.bytes } : {}) },
+ normalized: null,
+ frames,
+ cuts: [],
+ detected: null,
+ cutsReviewed: false,
+ shots: [newShot(0, frames, before.defaults, hasAudio)],
+ transcript: null,
+ review: "pending",
+ reviewNotes: "",
+ assembly: null,
+ };
+ if (before.engine === "open") {
+ mustMatchMode("open");
+ clip.normalized = { genId: normalizeJob(clip) };
+ }
+ return mutate(projectId, (p) => ({ ...p, clips: [...p.clips, clip] }));
+}
+
+function normalizeJob(clip: SwapClip): string {
+ mustOffer(STUDIO_MODELS.open.normalize, "open");
+ const pipe = run(planNormalize(clip));
+ return pipe.byKey.normalize.id;
+}
+
+/** Your GPU: make (or make again) a clip's 24 fps copy. */
+export function prepareClip(projectId: string, clipId: string): SwapProject {
+ const p = advanceProject(projectId);
+ if (p.engine !== "open") throw new ShortsError("The cloud reads the clip as filmed — no 24 fps copy needed", 422);
+ mustMatchMode("open");
+ const clip = mustClip(p, clipId);
+ const g = getGeneration(clip.normalized?.genId ?? "");
+ if (clip.normalized?.url || (g && ACTIVE.has(g.status))) throw new ShortsError("The 24 fps copy is ready or on its way", 409);
+ const genId = normalizeJob(clip);
+ return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, normalized: { genId } })));
+}
+
+function prepareClipQuietly(projectId: string, clipId: string): void {
+ try {
+ prepareClip(projectId, clipId);
+ } catch {
+ // Said on the page: the clip shows "Prepare at 24 fps" when its copy is missing.
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Transcript
+
+export function transcribe(projectId: string, clipId: string): SwapProject {
+ const p = advanceProject(projectId);
+ mustMatchMode(p.engine);
+ const clip = mustClip(p, clipId);
+ if (!clip.source.hasAudio) throw new ShortsError("This clip has no sound — nothing to transcribe", 422);
+ const modelId = STUDIO_MODELS[p.engine].transcribe;
+ mustOffer(modelId, p.engine, "type each shot's words instead");
+ const busy = look1(clip.transcript?.genId);
+ if (busy && ACTIVE.has(busy.status)) throw new ShortsError("The clip is being transcribed", 409);
+ const pipe = run(planTranscribe(clip, p.engine));
+ const genId = pipe.byKey.transcribe.id;
+ return 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);
+
+// ---------------------------------------------------------------------------
+// Masks
+
+export const MaskSchema = z.object({
+ clipId: id,
+ shotId: id,
+ kind: z.enum(["track", "frame"]),
+ /** The shot's frame (0 = its first). */
+ frame: z.number().int().min(0),
+ points: z.array(z.object({ x: z.number().finite().min(0).max(20_000), y: z.number().finite().min(0).max(20_000), label: z.enum(["positive", "negative"]).optional() })).max(SWAP_STUDIO.maxPoints).default([]),
+ /** The picture the points were placed on (the frame the page showed). */
+ size: z.object({ width: z.number().int().positive().max(20_000), height: z.number().int().positive().max(20_000) }).optional(),
+ /** The version it corrects (default: the approved one, else the newest). */
+ base: id.optional(),
+});
+
+/** The size of the video a job reads (your GPU's 24 fps copy, else the clip). */
+function workingSize(p: SwapProject, clip: SwapClip): { width: number; height: number } | null {
+ const { width, height } = clip.source;
+ if (!width || !height) return null;
+ return p.engine === "open" ? normalizedSize(width, height) : { width, height };
+}
+
+/** Track the shot (from a frame, to its end) or update one frame: a new mask version. */
+export function makeMask(projectId: string, body: z.infer<typeof MaskSchema>): SwapProject {
+ const p = advanceProject(projectId);
+ mustMatchMode(p.engine);
+ const clip = mustClip(p, body.clipId);
+ const shot = mustShot(clip, body.shotId);
+ const len = shot.end - shot.start;
+ if (shot.masks.length >= SWAP_STUDIO.maxMaskVersions) throw new ShortsError(`A shot keeps ${SWAP_STUDIO.maxMaskVersions} mask versions — remove one first`, 422);
+ const finished = (m: MaskVersion) => m.pieces.every((x) => x.url);
+ const base = body.base ? (shot.masks.find((m) => m.id === body.base) ?? null) : (approvedMask(shot) ?? [...shot.masks].reverse().find(finished) ?? null);
+ if (base && !finished(base)) throw new ShortsError("That mask version is still being made — wait for it", 409);
+ const size = workingSize(p, clip);
+ const points: PixelPoint[] = body.points.length && body.size && size ? scalePoints(body.points, body.size, size) : body.points;
+ const problem = maskProblem(p.engine, body.kind, body.frame, len, points, shot.who, base);
+ if (problem) throw new ShortsError(problem, 422);
+ if (p.engine === "open" && !clip.normalized?.url) throw new ShortsError("The clip is still being prepared at 24 fps — wait for it", 409);
+ mustOffer(STUDIO_MODELS[p.engine].mask, p.engine);
+ const pipe = run(planMask({ engine: p.engine, clip, shot, kind: body.kind, frame: body.frame, points, who: shot.who, base }));
+ const genId = pipe.byKey.mask.id;
+ const pieces = maskPieces(p.engine, body.kind, body.frame, len, base);
+ pieces[pieces.length - 1] = { ...pieces[pieces.length - 1], genId };
+ const version: MaskVersion = {
+ id: uid("mask-"),
+ createdAt: Date.now(),
+ kind: body.kind,
+ engine: p.engine,
+ frame: body.frame,
+ points,
+ who: { ...shot.who },
+ ...(base ? { base: base.id } : {}),
+ pieces,
+ genId,
+ stepIds: pipe.items.map((g) => g.id),
+ };
+ return mutate(projectId, (cur) => mapClip(cur, clip.id, (c) => mapShot(c, shot.id, (s) => ({ ...s, masks: [...s.masks, version] }))));
+}
+
+// ---------------------------------------------------------------------------
+// Anchors
+
+export const AnchorSchema = z.object({ clipId: id, shotId: id, segmentId: id.optional(), modelId: z.string().max(80).optional(), seed: z.number().int().min(0).max(SWAP_STUDIO.maxSeed).optional() });
+
+/** The anchor model that runs: the one asked for, else the engine's next one that is switched on. */
+function anchorModelFor(engine: Engine, asked?: string) {
+ const want = anchorModel(engine, asked);
+ if (isOffered(want.id, engine)) return want;
+ const next = ANCHOR_MODELS[engine].find((m) => isOffered(m.id, engine));
+ if (!next) throw new ShortsError(`The anchor models are switched off in ${ACCESS_PLACE} — import an anchor image instead`, 422);
+ return next;
+}
+
+/** A scene anchor for a shot (its first frame), or a reference for a segment (its first frame): your character in the frame. */
+export function makeAnchor(projectId: string, body: z.infer<typeof AnchorSchema>): SwapProject {
+ const p = advanceProject(projectId);
+ mustMatchMode(p.engine);
+ if (!p.character.image) throw new ShortsError("Add a picture of your character first", 422);
+ const clip = mustClip(p, body.clipId);
+ const shot = mustShot(clip, body.shotId);
+ const items = currentSegments(shot);
+ const seg = body.segmentId ? items.find((g) => g.id === body.segmentId) : undefined;
+ if (body.segmentId && !seg) throw new ShortsError("That segment changed — reload", 404);
+ const list = seg ? seg.anchors : shot.anchors;
+ if (list.length >= SWAP_STUDIO.maxAnchors) throw new ShortsError(`Keep at most ${SWAP_STUDIO.maxAnchors} ${seg ? "references a segment" : "anchors a shot"} — remove one first`, 422);
+ if (p.engine === "open" && !clip.normalized?.url) throw new ShortsError("The clip is still being prepared at 24 fps — wait for it", 409);
+ const am = anchorModelFor(p.engine, body.modelId);
+ const steps = planAnchor({ engine: p.engine, project: p, clip, shot, frame: shot.start + (seg?.start ?? 0), modelId: am.id, seed: body.seed });
+ const pipe = run(steps);
+ const variant = {
+ id: uid("anchor-"),
+ createdAt: Date.now(),
+ source: "generated" as const,
+ genId: pipe.byKey.anchor.id,
+ stepIds: pipe.items.map((g) => g.id),
+ modelId: am.id,
+ prompt: String(steps.find((s) => s.key === "anchor")?.request.prompt ?? ""),
+ };
+ return mutate(projectId, (cur) =>
+ mapClip(cur, clip.id, (c) =>
+ mapShot(c, shot.id, (s) => {
+ if (!seg) return { ...s, anchors: [...s.anchors, variant] };
+ const now = currentSegments(s);
+ if (!now.some((g) => g.id === seg.id)) throw new ShortsError("That segment changed — reload", 404);
+ return { ...s, segments: now.map((g) => (g.id === seg.id ? { ...g, anchors: [...g.anchors, variant] } : g)) };
+ }),
+ ),
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Takes
+
+export const QueueSchema = z.object({ clipId: id, shotId: id, segmentId: id, mode: z.enum(["segment", "from", "all"]) });
+
+/**
+ * The swap LoRA a shot runs with, with what Settings → Models & licences switched off taken out: on your GPU H3 runs
+ * without it (with a note); fal's route needs one. Turbo off stops your GPU's 8-step graph.
+ */
+function loraFor(engine: Engine, lora: SwapShot["settings"]["lora"]): { lora: SwapShot["settings"]["lora"]; note?: string } {
+ if (engine === "open" && offeredLoras([TURBO_LORA]).dropped.length) throw new ShortsError(`The H3 Turbo LoRA is switched off in ${ACCESS_PLACE}, and the segment graph's 8 steps need it — turn it on to run on your GPU`, 422);
+ if (engine === "cloud" && lora === "none") throw new ShortsError("On the cloud, fal's H3 route runs with a swap LoRA — pick V1.5 or V1 in the shot's settings (no LoRA runs on your GPU)", 422);
+ if (lora === "none" || !offeredLoras([swapLoraRef(lora)]).dropped.length) return { lora };
+ if (engine === "cloud") throw new ShortsError(`The swap LoRA (${SWAP_LORAS[lora].label}) is switched off in ${ACCESS_PLACE}, and fal's H3 route needs one — turn it on, or pick the other release`, 422);
+ return { lora: "none", note: `The swap LoRA is switched off in ${ACCESS_PLACE}: H3 runs with the Turbo LoRA alone` };
+}
+
+/** A take's steps with stand-ins for what the segment before will make (for prices and checks before anything runs). */
+function takeSteps(p: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, take: SwapTake, numbers: { shot: number; segment: number; take: number }) {
+ const previous = take.frozen && take.frozen.history > 0 ? { master: "/api/files/placeholder-master.mkv", video: "/api/files/placeholder-take.mp4", frames: Math.max(take.frozen.history, 1) } : null;
+ return frozenTakePlan(p, clip, shot, seg, take, numbers, previous);
+}
+
+/** A new take of a segment as it reads now (waiting until the takes it continues from are made). */
+function newTake(p: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, deps: SwapTake["dependencies"], lora: SwapShot["settings"]["lora"]): SwapTake {
+ const frozen = freezeTake(p, shot, seg);
+ frozen.settings = { ...frozen.settings, lora };
+ return {
+ id: uid("take-"),
+ createdAt: Date.now(),
+ engine: p.engine,
+ state: "waiting",
+ signature: settingSignature(p, clip, shot, seg),
+ dependencies: deps,
+ prompt: segmentPrompt(p, clip, shot, seg),
+ seed: seg.seed,
+ replaces: seg.selectedTake,
+ favourite: false,
+ decision: "pending",
+ notes: "",
+ frozen,
+ };
+}
+
+export interface QueueResult {
+ project: SwapProject;
+ takes: string[];
+ notes: string[];
+}
+
+/**
+ * "Queue segment", "Queue from here", "Queue all segments": a take for each segment (planQueue says which), each
+ * frozen as it reads now. A take that continues from another one in the same queue waits for it; the rest launch now.
+ * Everything is checked (and priced) before the first one starts.
+ */
+export function queueTakes(projectId: string, body: z.infer<typeof QueueSchema>): QueueResult {
+ const cur = advanceProject(projectId);
+ mustMatchMode(cur.engine);
+ const look = lookup();
+ const clip = mustClip(cur, body.clipId);
+ const shot = mustShot(clip, body.shotId);
+ const planned = planQueue(cur, clip, shot, body.segmentId, body.mode as QueueMode, {
+ active: (t) => ACTIVE.has(look(t.genId)?.status ?? ""),
+ hasMaster: (t) => {
+ const g = look(t.genId);
+ return !!g && !!masterOutput(g);
+ },
+ });
+ if ("problem" in planned) throw new ShortsError(planned.problem, 422);
+ mustOffer(STUDIO_MODELS[cur.engine].swap, cur.engine);
+ const { lora, note } = loraFor(cur.engine, shot.settings.lora);
+ const items = currentSegments(shot).map((g) => ({ ...g }));
+ const made = new Map<string, SwapTake>();
+ 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);
+ made.set(seg.id, take);
+ }
+ // Every take's steps checked now (models switched off, demo and real mixed, a request a route refuses).
+ const shotIndex = clip.shots.findIndex((s) => s.id === shot.id);
+ const checked = { ...shot, segments: items };
+ let demo: boolean | null = null;
+ for (const e of planned.entries) {
+ 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.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;
+ }
+ ensureSwapStudioRunner();
+ const project = mutate(projectId, (p) => {
+ const next = mapClip(p, clip.id, (c) =>
+ mapShot(c, shot.id, (s) => {
+ const now = currentSegments(s);
+ if (now.length !== items.length || now.some((g, i) => g.id !== items[i].id)) throw new ShortsError("The shot's segments changed — queue again", 409);
+ return { ...s, segments: now.map((g) => (made.has(g.id) ? { ...g, takes: [...g.takes, { ...made.get(g.id)!, waitsOn: made.get(g.id)!.dependencies.filter((d) => [...made.values()].some((t) => t.id === d.takeId)).map((d) => ({ segmentId: d.segmentId, takeId: d.takeId! })) }] } : g)) };
+ }),
+ );
+ // Launch what can start now.
+ return settle(next, lookup());
+ });
+ // A take that couldn't start says why on the page (stopped, with the reason), and so do the takes waiting on it.
+ return { project, takes: [...made.values()].map((t) => t.id), notes: note ? [note] : [] };
+}
+
+export const TakeRefSchema = z.object({ clipId: id, shotId: id, segmentId: id, takeId: id });
+
+/** Stop a take: one still waiting doesn't run; one running is canceled (takes waiting on it stop on the next sweep). */
+export async function stopTake(projectId: string, body: z.infer<typeof TakeRefSchema>): Promise<SwapProject> {
+ const p = mustProject(projectId);
+ const clip = mustClip(p, body.clipId);
+ const shot = mustShot(clip, body.shotId);
+ const take = currentSegments(shot)
+ .find((g) => g.id === body.segmentId)
+ ?.takes.find((t) => t.id === body.takeId);
+ if (!take) throw new ShortsError("That take is gone — reload", 404);
+ if (take.state === "waiting") {
+ mutate(projectId, (cur) =>
+ mapClip(cur, clip.id, (c) =>
+ mapShot(c, shot.id, (s) => ({ ...s, segments: (s.segments ?? []).map((g) => (g.id === body.segmentId ? { ...g, takes: g.takes.map((t) => (t.id === take.id && t.state === "waiting" ? { ...t, state: "stopped" as const, reason: "Stopped before it ran", waitsOn: undefined } : t)) } : g)) })),
+ ),
+ );
+ } else if (take.state === "launched") {
+ for (const gid of [...(take.stepIds ?? []), take.genId]) if (gid && ACTIVE.has(look1(gid)?.status ?? "")) await cancelGeneration(gid).catch(() => undefined);
+ }
+ return advanceProject(projectId);
+}
+
+// ---------------------------------------------------------------------------
+// Assembly
+
+/** The clip with its chosen takes over the original timeline and its own sound (the result goes to the Library). */
+export function assemble(projectId: string, clipId: string): SwapProject {
+ const p = advanceProject(projectId);
+ mustMatchMode(p.engine);
+ const clip = mustClip(p, clipId);
+ const look = lookup();
+ const found = assemblyPieces(p, clip);
+ if ("problem" in found) throw new ShortsError(found.problem, 422);
+ const takes = assemblyTakes(found.pieces);
+ const last = look(clip.assembly?.genId);
+ if (clip.assembly && last && last.status !== "failed" && last.status !== "canceled" && JSON.stringify(clip.assembly.takes) === JSON.stringify(takes)) {
+ throw new ShortsError(ACTIVE.has(last.status) ? "This clip is being assembled" : "Already assembled with these takes — download it below", 409);
+ }
+ if (p.engine === "open" && !clip.normalized?.url) throw new ShortsError("The clip is still being prepared at 24 fps — wait for it", 409);
+ const existing: Record<string, string> = {};
+ const videoOf = (piece: Extract<(typeof found.pieces)[number], { kind: "take" }>) => {
+ const g = look(piece.take.genId);
+ const url = g?.status === "succeeded" ? mainOutput(g)?.url : undefined;
+ if (!url) throw new ShortsError("A chosen take's video is missing — make it again", 422);
+ existing[`take-${piece.take.id}`] = g!.id;
+ return url;
+ };
+ const plan = planAssembly({ engine: p.engine, clip, pieces: found.pieces, videoOf });
+ // The takes count as steps already made: a demo join of real takes is refused.
+ const pipe = run(plan.steps, existing);
+ const assembly = { genId: pipe.byKey[plan.final].id, stepIds: pipe.items.map((g) => g.id), takes, createdAt: Date.now() };
+ return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, assembly })));
+}
+
+// ---------------------------------------------------------------------------
+// Stopping other jobs
+
+export const StopSchema = z.object({ kind: z.enum(["mask", "anchor", "assembly", "normalize", "transcribe"]), clipId: id, shotId: id.optional(), segmentId: id.optional(), jobId: id.optional() });
+
+export async function stopJob(projectId: string, body: z.infer<typeof StopSchema>): Promise<SwapProject> {
+ const p = mustProject(projectId);
+ const clip = mustClip(p, body.clipId);
+ let ids: (string | undefined)[] = [];
+ if (body.kind === "assembly") ids = [...(clip.assembly?.stepIds ?? []), clip.assembly?.genId];
+ if (body.kind === "normalize") ids = [clip.normalized?.genId];
+ if (body.kind === "transcribe") ids = [clip.transcript?.genId];
+ if (body.kind === "mask" || body.kind === "anchor") {
+ const shot = mustShot(clip, body.shotId ?? "");
+ const seg = body.segmentId ? currentSegments(shot).find((g) => g.id === body.segmentId) : undefined;
+ const job = body.kind === "mask" ? shot.masks.find((m) => m.id === body.jobId) : (seg?.anchors ?? shot.anchors).find((a) => a.id === body.jobId);
+ if (!job) throw new ShortsError("That job is gone — reload", 404);
+ ids = [...(job.stepIds ?? []), job.genId];
+ }
+ for (const gid of ids) if (gid && ACTIVE.has(look1(gid)?.status ?? "")) await cancelGeneration(gid).catch(() => undefined);
+ return advanceProject(projectId);
+}
+
+// ---------------------------------------------------------------------------
+// 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 } {
+ let cost: number | null = 0;
+ let demo = false;
+ let real = false;
+ for (const s of steps) {
+ let p: ReturnType<typeof previewChained>;
+ try {
+ p = previewChained(withChain(s), s.after?.length ?? 0);
+ } catch (e) {
+ return { costUsd: null, demo: false, problem: (e as Error).message };
+ }
+ if (p.demo) demo = true;
+ else real = true;
+ // Tokens-billed anchor models have no fixed price: left out of the total (the page says so).
+ const tokens = p.costUsd === null && ANCHOR_MODELS.cloud.some((m) => m.id === s.request.modelId && m.tokens);
+ if (tokens) continue;
+ cost = cost === null || p.costUsd === null ? null : cost + p.costUsd;
+ }
+ if (demo && real) {
+ const which = steps.find((s) => {
+ try {
+ return previewChained(withChain(s), s.after?.length ?? 0).demo;
+ } catch {
+ return false;
+ }
+ });
+ const m = which ? getModel(which.request.modelId) : undefined;
+ return { costUsd: null, demo, problem: `${m?.name ?? "A step"} would run as a demo while the others run for real — connect its provider in Settings, or turn on demo mode to try it all as a demo` };
+ }
+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo, problem: null };
+}
+
+
+const add = (a: number | null, b: number | null) => (a === null || b === null ? null : Math.round((a + b) * 10000) / 10000);
+
+/** Prices before running: a take of each segment, each shot's and the whole project's queue, masks, anchors, words, assembly. */
+export function estimateProject(projectId: string): StudioEstimate {
+ const p = advanceProject(projectId);
+ const look = lookup();
+ const engine = p.engine;
+ const out: StudioEstimate = { engine, demo: false, free: engine === "open", segments: {}, problems: {}, shots: {}, project: { costUsd: 0, segments: 0 }, assembly: {}, transcribe: {}, mask: {}, anchors: [], notes: [] };
+ const track = (r: { demo: boolean }) => {
+ if (r.demo) out.demo = true;
+ };
+ const stand = p.character.image ? p : { ...p, character: { ...p.character, image: "/api/files/placeholder-character.png" } };
+ let loraNote: string | undefined;
+ for (const clip of p.clips) {
+ const working = engine === "open" && !clip.normalized?.url ? { ...clip, normalized: { url: "/api/files/placeholder-24fps.mp4" } } : clip;
+ if (clip.source.hasAudio) {
+ const t = price(planTranscribe(working, engine));
+ track(t);
+ out.transcribe[clip.id] = t.costUsd;
+ }
+ for (const [si, shot] of clip.shots.entries()) {
+ if (shot.mode !== "generate") continue;
+ const m = price(planMask({ engine, clip: working, shot, kind: "track", frame: 0, points: [], who: shot.who, base: null }));
+ out.mask[shot.id] = m.costUsd;
+ const items = currentSegments(shot);
+ const states = segmentStates(p, clip, shot, items);
+ let lora = shot.settings.lora;
+ try {
+ const l = loraFor(engine, lora);
+ lora = l.lora;
+ loraNote ??= l.note;
+ } catch (e) {
+ for (const g of items) out.problems[g.id] = (e as Error).message;
+ out.shots[shot.id] = { costUsd: null, segments: 0 };
+ continue;
+ }
+ let shotCost: number | null = 0;
+ let count = 0;
+ for (const [gi, seg] of items.entries()) {
+ const take = newTake(stand, working, shot, seg, [], lora);
+ // A stand-in anchor where one is still to be made: the price doesn't depend on which picture it is.
+ if (seg.anchorMode !== "none" && !take.frozen!.anchor) take.frozen!.anchor = "/api/files/placeholder-anchor.png";
+ let r: ReturnType<typeof price>;
+ try {
+ r = price(takeSteps(stand, working, shot, seg, take, { shot: si + 1, segment: gi + 1, take: seg.takes.length + 1 }).steps);
+ } catch (e) {
+ r = { costUsd: null, demo: false, problem: (e as Error).message };
+ }
+ if (r.problem) out.problems[seg.id] = r.problem;
+ track(r);
+ out.segments[seg.id] = r.costUsd;
+ const busy = seg.takes.some((t) => t.state === "waiting" || ACTIVE.has(look(t.genId)?.status ?? ""));
+ if (states[gi].status !== "ready" && !busy) {
+ shotCost = add(shotCost, r.costUsd);
+ count++;
+ }
+ }
+ out.shots[shot.id] = { costUsd: shotCost, segments: count };
+ out.project = { costUsd: add(out.project.costUsd, shotCost), segments: out.project.segments + count };
+ }
+ // The assembly with every swapped segment's take (stand-ins where none is made yet).
+ const pieces = assemblyPiecesForPrice(p, clip);
+ if (pieces.length) {
+ const a = price(planAssembly({ engine, clip: working, pieces, videoOf: () => "/api/files/placeholder-take.mp4" }).steps);
+ track(a);
+ out.assembly[clip.id] = a.costUsd;
+ }
+ }
+ const sample = p.clips[0];
+ if (sample) {
+ const working = engine === "open" && !sample.normalized?.url ? { ...sample, normalized: { url: "/api/files/placeholder-24fps.mp4" } } : sample;
+ for (const am of ANCHOR_MODELS[engine]) {
+ const offered = isOffered(am.id, engine);
+ let costUsd: number | null = null;
+ if (offered) {
+ const r = price(planAnchor({ engine, project: stand, clip: working, shot: sample.shots[0], frame: 0, modelId: am.id }));
+ track(r);
+ costUsd = r.costUsd;
+ }
+ out.anchors.push({ id: am.id, label: am.label, note: am.note, costUsd, offered });
+ }
+ }
+ out.notes = studioNotes(engine);
+ if (loraNote) out.notes.unshift(loraNote);
+ if (out.demo) out.free = false;
+ return out;
+}
+
+/** The assembly's pieces with a stand-in take wherever a segment has none yet (for its price). */
+function assemblyPiecesForPrice(p: SwapProject, clip: SwapClip) {
+ if (!clip.shots.some((s) => s.mode === "generate")) return [];
+ const stand: SwapTake = { id: "price", createdAt: 0, engine: p.engine, state: "launched", signature: "", dependencies: [], prompt: "", seed: 0, favourite: false, decision: "pending", notes: "" };
+ const out: Parameters<typeof planAssembly>[0]["pieces"] = [];
+ for (const shot of clip.shots) {
+ if (shot.mode === "preserve") {
+ const last = out.at(-1);
+ if (last?.kind === "source" && last.end === shot.start) last.end = shot.end;
+ else out.push({ kind: "source", start: shot.start, end: shot.end });
+ continue;
+ }
+ for (const seg of currentSegments(shot)) out.push({ kind: "take", start: shot.start + seg.start, end: shot.start + seg.end, take: stand, segmentId: seg.id });
+ }
+ return out;
+}
+
+/** What the page says about each engine (licences as information). */
+export function studioNotes(engine: Engine): string[] {
+ if (engine === "open") {
+ return [
+ WORKERS_NOTE,
+ "Needs H3 Relay 2.0's nodes on your ComfyUI (scripts/comfy/install-comfyui.sh with H3_RELAY=1) and a 24 GB GPU with offloading; the masks need SAM 3.1",
+ "Each segment is one H3 Relay pass with the approved mask, its anchor and the previous take's lossless (FFV1) master as continuation history",
+ characterLicenceLine("open", STUDIO_MODELS.open.swap),
+ ];
+ }
+ return [
+ "On fal, H3 has no mask: who to swap is said in words, and the whole frame is regenerated around them",
+ "fal's H3 reads 2–15 s of the clip a call and bills whole seconds (5–15 s): a segment runs 2–15 s",
+ "A continuing segment starts from the previous take's last frame — fal's H3 takes no continuation history",
+ "SAM 3.1 on fal marks the person from your clicks or words, for review; the swap itself doesn't read the mask",
+ characterLicenceLine("cloud", STUDIO_MODELS.cloud.swap),
+ ];
+}
+
+// ---------------------------------------------------------------------------
+// Review
+
+/** "Export decisions": every clip's review and every take's favourite, decision and notes, as JSON. */
+export function decisions(projectId: string): DecisionExport {
+ const p = advanceProject(projectId);
+ const look = lookup();
+ return exportDecisions(p, (t) => {
+ const g = look(t.genId);
+ return g?.status === "succeeded" ? mainOutput(g)?.url : undefined;
+ });
+}
diff --git a/tests/swap-studio-api.test.ts b/tests/swap-studio-api.test.ts
new file mode 100644
index 00000000..79bc0f54
--- /dev/null
+++ b/tests/swap-studio-api.test.ts
@@ -0,0 +1,291 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { currentSegments, jobState, type SwapProject } from "@/lib/catalog/swap-studio";
+import type { SwapProjectView } from "@/server/swap-studio";
+
+vi.setConfig({ testTimeout: 240_000 });
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+// Character Swap Studio's API end to end in demo mode (no keys, no ComfyUI): projects, clips, cuts, words, masks,
+// anchors, segments queued with continuations (waiting, launched, stopped), review and the assembly, on both engines.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-studio-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+const { encodePng } = await import("@/server/png");
+const { recordExists } = await import("@/server/records");
+const projects = await import("@/app/api/swap-studio/projects/route");
+const project = await import("@/app/api/swap-studio/projects/[id]/route");
+const clips = await import("@/app/api/swap-studio/projects/[id]/clips/route");
+const transcribe = await import("@/app/api/swap-studio/projects/[id]/transcribe/route");
+const masks = await import("@/app/api/swap-studio/projects/[id]/masks/route");
+const anchors = await import("@/app/api/swap-studio/projects/[id]/anchors/route");
+const queue = await import("@/app/api/swap-studio/projects/[id]/queue/route");
+const stopTake = await import("@/app/api/swap-studio/projects/[id]/takes/stop/route");
+const assemble = await import("@/app/api/swap-studio/projects/[id]/assemble/route");
+const estimate = await import("@/app/api/swap-studio/projects/[id]/estimate/route");
+const decisionsRoute = await import("@/app/api/swap-studio/projects/[id]/decisions/route");
+
+const req = (method: string, body?: unknown) => new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+let clip = "";
+let hero = "";
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ // A 12 s, 16 fps, 72×128 clip with a sound track.
+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "dance.mp4" }).url;
+ const data = Buffer.alloc(64 * 64 * 4, 200);
+ hero = saveFile({ data: encodePng({ width: 64, height: 64, data }), contentType: "image/png", source: "upload", name: "hero.png" }).url;
+});
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+async function view(id: string): Promise<SwapProjectView> {
+ const res = await project.GET(req("GET"), ctx(id) as never);
+ expect(res.status).toBe(200);
+ return res.json();
+}
+
+async function patch(id: string, edit: unknown): Promise<SwapProject> {
+ const res = await project.PATCH(req("PATCH", edit), ctx(id) as never);
+ if (res.status !== 200) throw new Error(`${res.status}: ${(await res.json()).error}`);
+ return res.json();
+}
+
+async function post(route: { POST: (r: Request, c: never) => Promise<Response> }, id: string, body: unknown, status = 201) {
+ const res = await route.POST(req("POST", body), ctx(id) as never);
+ const out = await res.json();
+ if (res.status !== status) throw new Error(`${res.status}: ${out.error}`);
+ return out;
+}
+
+/** Poll the project (as the page does) until `done` holds. */
+async function until(id: string, done: (v: SwapProjectView) => boolean, ms = 150_000): Promise<SwapProjectView> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = await view(id);
+ if (done(v)) return v;
+ if (Date.now() > end) throw new Error(`timed out: ${JSON.stringify(Object.values(v.gens).map((g) => g.status))}`);
+ await sleep(400);
+ }
+}
+
+const statusOf = (v: SwapProjectView, genId?: string) => (genId ? v.gens[genId]?.status : undefined);
+
+describe("Character Swap Studio: the cloud, as a demo", () => {
+ let id = "";
+
+ it("makes a project, takes a clip and refuses one it can't", async () => {
+ const created = await post(projects, "", { name: "Rain scene", engine: "cloud", character: { image: hero, description: "a woman in a yellow raincoat" } });
+ id = created.id;
+ 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();
+ expect(list.items[0]).toMatchObject({ id, clips: 0 });
+
+ const p = await post(clips, id, { url: clip, name: "dance.mp4" });
+ const c = p.clips[0];
+ // 12 s at 24 fps; the cloud keeps the clip as filmed (no 24 fps copy).
+ expect(c).toMatchObject({ name: "dance", frames: 288, normalized: null, cutsReviewed: false, source: { duration: 12, hasAudio: true, width: 72, height: 128 } });
+ expect(c.shots).toHaveLength(1);
+ await expect(post(clips, id, { url: clip, name: "dance.gif" })).rejects.toThrow(/MP4, MOV, MKV, WebM or AVI/);
+ await expect(post(clips, id, { url: "/api/files/uploads/nothing.mp4", name: "x.mp4" })).rejects.toThrow(/upload it again/);
+ });
+
+ it("confirms cuts, transcribes the words with who speaks, builds the prompts", async () => {
+ let p = (await view(id)).project;
+ const c = p.clips[0];
+ p = await patch(id, { type: "detected", clipId: c.id, cuts: [96, 200] });
+ expect(p.clips[0].detected).toEqual([96, 200]);
+ p = await patch(id, { type: "cuts", clipId: c.id, cuts: [96], modes: ["generate", "preserve"] });
+ expect(p.clips[0].shots.map((s) => [s.start, s.end, s.mode])).toEqual([
+ [0, 96, "generate"],
+ [96, 288, "preserve"],
+ ]);
+ p = await post(transcribe, id, { clipId: c.id }, 200);
+ expect(p.clips[0].transcript).toMatchObject({ modelId: "scribe-v2", cues: null });
+ const v = await until(id, (x) => !!x.project.clips[0].transcript?.cues);
+ expect(v.project.clips[0].transcript!.cues!.length).toBeGreaterThan(0);
+ p = await patch(id, { type: "build-prompts", clipId: c.id });
+ expect(p.clips[0].shots[0].prompt).toMatch(/Current shot dialogue: "This is a demo transcript\./);
+ expect(p.clips[0].shots[1].prompt).toBeNull();
+ });
+
+ it("prices before running: a take of each segment, the shot, the project", async () => {
+ const res = await estimate.GET(req("GET"), ctx(id) as never);
+ const e = await res.json();
+ const shot = (await view(id)).project.clips[0].shots[0];
+ expect(e).toMatchObject({ engine: "cloud", demo: true, free: false });
+ const segs = currentSegments(shot);
+ expect(Object.keys(e.segments)).toEqual(segs.map((g) => g.id));
+ expect(e.shots[shot.id].segments).toBe(segs.length);
+ expect(e.project.segments).toBe(segs.length);
+ expect(e.notes.join(" ")).toMatch(/no mask/);
+ expect(e.anchors.map((a: { id: string }) => a.id)).toEqual(["gpt-image-2-5-sunburst", "nano-banana-pro"]);
+ });
+
+ it("who to swap: clicks on a frame become a SAM 3.1 mask version; a scene anchor is made and approved", async () => {
+ const p = (await view(id)).project;
+ const [c] = p.clips;
+ const shot = c.shots[0];
+ // An exclude point alone is refused.
+ await expect(post(masks, id, { clipId: c.id, shotId: shot.id, kind: "track", frame: 0, points: [{ x: 10, y: 10, label: "negative" }] })).rejects.toThrow(/include point/);
+ await expect(post(masks, id, { clipId: c.id, shotId: shot.id, kind: "frame", frame: 3, points: [{ x: 10, y: 10 }] })).rejects.toThrow(/Track the shot first/);
+ // Clicked on a 144×256 picture of the 72×128 clip: the points are halved.
+ let q = await post(masks, id, { clipId: c.id, shotId: shot.id, kind: "track", frame: 0, points: [{ x: 72, y: 128, label: "positive" }], size: { width: 144, height: 256 } });
+ const m = q.clips[0].shots[0].masks[0];
+ expect(m).toMatchObject({ kind: "track", engine: "cloud", frame: 0, points: [{ x: 36, y: 64, label: "positive" }], pieces: [{ from: 0, frames: 96 }] });
+ const sam = gens.getGeneration(m.genId)!;
+ expect(sam.modelId).toBe("sam-3-1-video-mask");
+ q = await post(anchors, id, { clipId: c.id, shotId: shot.id, modelId: "nano-banana-pro" });
+ const a = q.clips[0].shots[0].anchors[0];
+ expect(a).toMatchObject({ source: "generated", modelId: "nano-banana-pro" });
+ // Approving before it is made is refused.
+ await expect(patch(id, { type: "shot", clipId: c.id, shotId: shot.id, patch: { approvedAnchor: a.id } })).rejects.toThrow(/isn't ready/);
+ const v = await until(id, (x) => !!x.project.clips[0].shots[0].anchors[0].url && !!x.project.clips[0].shots[0].masks[0].pieces[0].url);
+ expect(jobState(m.genId, m.stepIds, v.gens).status).toBe("succeeded");
+ const done = await patch(id, { type: "shot", clipId: c.id, shotId: shot.id, patch: { approvedAnchor: a.id, approvedMask: m.id } });
+ expect(done.clips[0].shots[0]).toMatchObject({ approvedAnchor: a.id, approvedMask: m.id });
+ // Update frame on the cloud: a one-frame piece over the tracked version.
+ q = await post(masks, id, { clipId: c.id, shotId: shot.id, kind: "frame", frame: 3, points: [{ x: 30, y: 60 }] });
+ expect(q.clips[0].shots[0].masks[1].pieces.map((x: { from: number; frames: number }) => [x.from, x.frames])).toEqual([
+ [0, 96],
+ [3, 1],
+ ]);
+ });
+
+ it("queues two segments: the second waits for the first, then starts from its last frame", async () => {
+ let p = (await view(id)).project;
+ const [c] = p.clips;
+ const shot = c.shots[0];
+ p = await patch(id, { type: "layout", clipId: c.id, shotId: shot.id, op: { op: "partition", frames: 48 } });
+ const segs = p.clips[0].shots[0].segments!;
+ expect(segs.map((g) => [g.start, g.end, g.connection])).toEqual([
+ [0, 48, "start"],
+ [48, 96, "continue"],
+ ]);
+ // Segment 2 alone can't run before segment 1 has a take.
+ await expect(post(queue, id, { clipId: c.id, shotId: shot.id, segmentId: segs[1].id, mode: "segment" })).rejects.toThrow(/Generate segment 1 first/);
+ const out = await post(queue, id, { clipId: c.id, shotId: shot.id, segmentId: segs[0].id, mode: "all" });
+ const [t1, t2] = out.project.clips[0].shots[0].segments!.map((g: { takes: { id: string; state: string; waitsOn?: unknown[] }[] }) => g.takes[0]);
+ expect(t1.state).toBe("launched");
+ expect(t2).toMatchObject({ state: "waiting", waitsOn: [{ segmentId: segs[0].id, takeId: t1.id }] });
+ // Asking again while they run: nothing to queue.
+ await expect(post(queue, id, { clipId: c.id, shotId: shot.id, segmentId: segs[0].id, mode: "all" })).rejects.toThrow(/already current, queued or generating/);
+ // The layout can't change under them.
+ await expect(patch(id, { type: "layout", clipId: c.id, shotId: shot.id, op: { op: "merge", index: 1 } })).rejects.toThrow(/409: Wait for this shot's takes/);
+ const v = await until(id, (x) => {
+ const s = x.project.clips[0].shots[0].segments!;
+ return s.every((g) => g.selectedTake && statusOf(x, g.takes[0].genId) === "succeeded");
+ });
+ const after = v.project.clips[0].shots[0].segments!;
+ expect(after.map((g) => g.selectedTake)).toEqual([t1.id, t2.id]);
+ // The second take: cut, the first take's last frame, then H3 with the swap LoRA and both pictures.
+ const take2 = after[1].takes[0];
+ const steps = take2.stepIds!.map((s) => gens.getGeneration(s)!);
+ expect(steps.map((g) => g.modelId)).toEqual(["trim-video", "extract-frame", "fuobe-character-swap"]);
+ expect(steps[1].request.inputs?.video).toBe(v.gens[after[0].takes[0].genId!].url);
+ expect(steps[1].request.params?.extra).toEqual({ frame_type: "last" });
+ const swap = steps[2].request;
+ expect(swap.loras?.[0]?.file).toMatch(/swap/i);
+ expect(swap.params).toMatchObject({ duration: 5, sourceDuration: 2 });
+ // The anchor is Image 2 on the first segment; after the boundary the boundary frame is Image 2, the anchor Image 3.
+ expect(gens.getGeneration(after[0].takes[0].genId!)!.request.prompt).toMatch(/Image 2 is the exact first-frame scene/);
+ expect(swap.prompt).toMatch(/Image 2 is the generated boundary/);
+ });
+
+ it("review: favourite, decide, note; Export decisions; assemble over the original timeline with its sound", async () => {
+ const p = (await view(id)).project;
+ const [c] = p.clips;
+ const shot = c.shots[0];
+ const seg = shot.segments![0];
+ await patch(id, { type: "take", clipId: c.id, shotId: shot.id, segmentId: seg.id, takeId: seg.takes[0].id, favourite: true, decision: "keep", notes: "eyes match" });
+ await patch(id, { type: "clip", clipId: c.id, review: "keep", reviewNotes: "ship it" });
+ const res = await decisionsRoute.GET(req("GET"), ctx(id) as never);
+ expect(res.headers.get("Content-Disposition")).toMatch(/Rain-scene-decisions\.json/);
+ const d = await res.json();
+ expect(d).toMatchObject({ project: "Rain scene", clips: [{ clip: "dance", review: "keep", notes: "ship it", shots: [{ shot: 1, frames: [0, 96], mode: "generate" }, { shot: 2, mode: "preserve", segments: [] }] }] });
+ expect(d.clips[0].shots[0].segments[0].takes[0]).toMatchObject({ favourite: true, decision: "keep", notes: "eyes match" });
+
+ const q = await post(assemble, id, { clipId: c.id });
+ const asm = q.clips[0].assembly;
+ expect(asm.takes).toEqual(shot.segments!.map((g) => g.selectedTake));
+ await expect(post(assemble, id, { clipId: c.id })).rejects.toThrow(/being assembled/);
+ const v = await until(id, (x) => statusOf(x, x.project.clips[0].assembly?.genId) === "succeeded");
+ const steps = asm.stepIds.map((s: string) => gens.getGeneration(s)!);
+ // Two takes and the kept shot cut to their frames, joined, the clip's sound put back.
+ expect(steps.map((g: { modelId: string }) => g.modelId)).toEqual(["trim-video", "trim-video", "trim-video", "join-clips", "merge-audio-video"]);
+ const final = gens.getGeneration(asm.genId)!;
+ expect(final).toMatchObject({ feature: "swap-studio", op: "mux" });
+ expect(final.request.inputs?.audio).toBe(clip);
+ expect(steps[2].request.params).toMatchObject({ startTime: 4, endTime: 12 });
+ expect(v.gens[asm.genId].url).toBeTruthy();
+ // The step generations stay out of the Library; the assembled clip is in it.
+ expect(gens.listGenerations({ feature: "swap-studio" }).map((g) => g.id)).toContain(asm.genId);
+ });
+});
+
+describe("Character Swap Studio: your GPU, as a demo", () => {
+ let id = "";
+
+ it("prepares the clip at 24 fps, continues from the previous take's lossless master, stops what follows a failed take", async () => {
+ id = (await post(projects, "", { name: "GPU", engine: "open", character: { image: hero, description: "a knight" } })).id;
+ let p: SwapProject = await post(clips, id, { url: clip, name: "dance.mp4" });
+ const c = p.clips[0];
+ const norm = gens.getGeneration(c.normalized!.genId!)!;
+ expect(norm.modelId).toBe("oss-fit-clip");
+ expect(norm.request.params).toMatchObject({ startTime: 0, fps: 24, extra: { width: 72, height: 128 } });
+ // Masks wait for the 24 fps copy.
+ await expect(post(masks, id, { clipId: c.id, shotId: c.shots[0].id, kind: "track", frame: 0, points: [] })).rejects.toThrow(/being prepared at 24 fps/);
+ await until(id, (x) => !!x.project.clips[0].normalized?.url);
+ const e = await (await estimate.GET(req("GET"), ctx(id) as never)).json();
+ expect(e).toMatchObject({ engine: "open", demo: true });
+ expect(e.notes.join(" ")).toMatch(/H3 Relay 2\.0/);
+
+ const shot = c.shots[0];
+ p = await patch(id, { type: "shot", clipId: c.id, shotId: shot.id, patch: { settings: { useAnchor: false } } });
+ p = await patch(id, { type: "layout", clipId: c.id, shotId: shot.id, op: { op: "partition", frames: 144 } });
+ let segs = p.clips[0].shots[0].segments!;
+ for (const g of segs) p = await patch(id, { type: "segment", clipId: c.id, shotId: shot.id, segmentId: g.id, patch: { anchorMode: "none" } });
+ segs = p.clips[0].shots[0].segments!;
+ const out = await post(queue, id, { clipId: c.id, shotId: shot.id, segmentId: segs[0].id, mode: "all" });
+ const [t1, t2] = out.project.clips[0].shots[0].segments.map((g: { takes: { id: string }[] }) => g.takes[0]);
+ const v = await until(id, (x) => statusOf(x, x.project.clips[0].shots[0].segments![1].takes[0].genId) === "succeeded");
+ const after = v.project.clips[0].shots[0].segments!;
+ const first = gens.getGeneration(after[0].takes[0].genId!)!;
+ const second = gens.getGeneration(after[1].takes[0].genId!)!;
+ expect(first).toMatchObject({ modelId: "oss-h3-swap-segment", op: "video-swap", feature: "swap-studio-step" });
+ expect(first.request.inputs?.video).toBe(v.project.clips[0].normalized!.url);
+ expect(first.request.params?.extra).not.toHaveProperty("historyVideo");
+ // Segment 2 reads 18 frames of history from take 1's master (144 frames long).
+ expect(second.request.params?.extra).toMatchObject({ historyVideo: v.gens[first.id].master, historyStart: 126, historyLength: 18 });
+ expect(v.gens[first.id].master).toBeTruthy();
+ expect(after.map((g) => g.selectedTake)).toEqual([t1.id, t2.id]);
+
+ // Segment 1 made stale (a new seed): "Queue from here" makes both again, segment 2 waiting on segment 1's new take.
+ await patch(id, { type: "segment", clipId: c.id, shotId: shot.id, segmentId: segs[0].id, patch: { seed: 7 } });
+ const q = await post(queue, id, { clipId: c.id, shotId: shot.id, segmentId: segs[0].id, mode: "from" });
+ const [a, b] = q.project.clips[0].shots[0].segments.map((g: { takes: { id: string; state: string }[] }) => g.takes.at(-1)!);
+ expect(a.state).toBe("launched");
+ expect(b).toMatchObject({ state: "waiting", waitsOn: [{ segmentId: segs[0].id, takeId: a.id }] });
+ // Stopping segment 1's take stops segment 2's, with the reason, before it runs.
+ await stopTake.POST(req("POST", { clipId: c.id, shotId: shot.id, segmentId: segs[0].id, takeId: a.id }), ctx(id) as never);
+ const stopped = await until(id, (x) => x.project.clips[0].shots[0].segments![1].takes.at(-1)!.state === "stopped", 20_000);
+ expect(stopped.project.clips[0].shots[0].segments![1].takes.at(-1)!.reason).toMatch(/^Stopped: segment 1's take was stopped/);
+ });
+
+ it("deletes the project, and its page is a 404", async () => {
+ const res = await project.DELETE(req("DELETE"), ctx(id) as never);
+ expect(res.status).toBe(204);
+ expect(recordExists({ kind: "swap-project", ids: [id] })).toBe(false);
+ expect((await project.GET(req("GET"), ctx(id) as never)).status).toBe(404);
+ });
+});
diff --git a/tests/swap-studio-edit.test.ts b/tests/swap-studio-edit.test.ts
new file mode 100644
index 00000000..79d1ab45
--- /dev/null
+++ b/tests/swap-studio-edit.test.ts
@@ -0,0 +1,264 @@
+import { describe, expect, it } from "vitest";
+import {
+ currentSegments,
+ DEFAULT_SETTINGS,
+ dependencies,
+ freezeTake,
+ jobState,
+ newSegment,
+ newShot,
+ planQueue,
+ segmentPrompt,
+ settingSignature,
+ type GenSummary,
+ type SwapClip,
+ type SwapProject,
+ type SwapTake,
+} from "@/lib/catalog/swap-studio";
+import { applyEdit, cleanSettings, EditError, shotBusy, type SwapEdit } from "@/lib/catalog/swap-studio-edit";
+import { frozenTakePlan } from "@/lib/catalog/swap-studio-plan";
+
+// Character Swap Studio's edits (Akatz Labs' rules) and a queued take's frozen plan: pure, no server.
+
+let tick = 0;
+const rand = () => (((tick++ * 0.6180339887) % 1) + 1) % 1;
+
+function clipOf(over: Partial<SwapClip> = {}): SwapClip {
+ return {
+ id: "clip-1",
+ name: "walk",
+ source: { url: "/api/files/uploads/x/walk.mp4", name: "walk.mp4", duration: 20, fps: 30, width: 1920, height: 1080, hasAudio: true },
+ normalized: { url: "/api/files/outputs/x/walk24.mp4", genId: "g-norm" },
+ frames: 480,
+ cuts: [],
+ detected: null,
+ cutsReviewed: false,
+ shots: [{ ...newShot(0, 480, DEFAULT_SETTINGS, true, rand), id: "shot-a" }],
+ transcript: { genId: "g-words", cues: [{ start: 0.5, end: 2, text: "Where were you", speaker: "s1" }], voices: {} },
+ review: "pending",
+ reviewNotes: "",
+ assembly: null,
+ ...over,
+ };
+}
+
+function projectOf(clips: SwapClip[] = [clipOf()], engine: SwapProject["engine"] = "open"): SwapProject {
+ return { id: "p1", name: "Demo", engine, character: { image: "/api/files/uploads/x/hero.png", description: "a woman in a yellow raincoat" }, defaults: { ...DEFAULT_SETTINGS }, clips, createdAt: 0, updatedAt: 0, revision: 1 };
+}
+
+const take = (id: string, over: Partial<SwapTake> = {}): SwapTake => ({ id, createdAt: 1, engine: "open", state: "launched", genId: `g-${id}`, signature: "", dependencies: [], prompt: "", seed: 1, favourite: false, decision: "pending", notes: "", ...over });
+const edit = (p: SwapProject, e: SwapEdit, active: (id: string) => boolean = () => false) => applyEdit(p, e, { active, rand });
+const shotOf = (p: SwapProject, i = 0) => p.clips[0].shots[i];
+const refused = (f: () => unknown) => {
+ try {
+ f();
+ } catch (e) {
+ return { message: (e as Error).message, status: (e as EditError).status };
+ }
+ throw new Error("expected the edit to be refused");
+};
+
+describe("project edits", () => {
+ it("rename, defaults and engine keep to known values", () => {
+ const p = projectOf();
+ expect(edit(p, { type: "rename", name: " Rain scene " }).name).toBe("Rain scene");
+ expect(refused(() => edit(p, { type: "rename", name: " " })).message).toMatch(/name/);
+ expect(edit(p, { type: "defaults", settings: { renderMp: 0.5, lora: "v1" } }).defaults).toMatchObject({ renderMp: 0.5, lora: "v1" });
+ expect(refused(() => cleanSettings({ windowFrames: 100 })).message).toMatch(/17n \+ 5/);
+ expect(refused(() => cleanSettings({ expansion: 300 })).message).toMatch(/0–256/);
+ expect(refused(() => cleanSettings({ renderMp: 0.7 as 0.5 })).message).toMatch(/0\.5 MP/);
+ expect(refused(() => cleanSettings({ windowFrames: 22, historyFrames: 35 })).message).toMatch(/shorter than the window/);
+ expect(edit(p, { type: "engine", engine: "cloud" }).engine).toBe("cloud");
+ });
+
+ it("a new character picture un-approves the anchors made with the old one; a new description doesn't", () => {
+ const p = projectOf([clipOf({ shots: [{ ...shotOf(projectOf()), anchors: [{ id: "a1", createdAt: 1, source: "generated", url: "/api/files/a1.png" }], approvedAnchor: "a1" }] })]);
+ expect(shotOf(edit(p, { type: "character", description: "a man in a grey suit" })).approvedAnchor).toBe("a1");
+ const after = edit(p, { type: "character", image: "/api/files/uploads/x/other.png" });
+ expect(after.character.image).toBe("/api/files/uploads/x/other.png");
+ expect(shotOf(after).approvedAnchor).toBeNull();
+ // The anchors themselves stay, to approve again.
+ expect(shotOf(after).anchors).toHaveLength(1);
+ });
+
+ it("detected edits are kept apart until confirmed; confirmed cuts make shots, with Replace or Keep for each", () => {
+ let p = edit(projectOf(), { type: "detected", clipId: "clip-1", cuts: [120, 0, 600, 120, 300] });
+ expect(p.clips[0].detected).toEqual([120, 300]);
+ expect(p.clips[0].shots).toHaveLength(1);
+ p = edit(p, { type: "cuts", clipId: "clip-1", cuts: [300, 120], modes: ["generate", "preserve", "generate"] });
+ expect(p.clips[0]).toMatchObject({ cuts: [120, 300], detected: null, cutsReviewed: true });
+ expect(p.clips[0].shots.map((s) => [s.start, s.end, s.mode])).toEqual([
+ [0, 120, "generate"],
+ [120, 300, "preserve"],
+ [300, 480, "generate"],
+ ]);
+ expect(refused(() => edit(p, { type: "cuts", clipId: "clip-1", cuts: [480] })).message).toMatch(/inside the clip/);
+ expect(refused(() => edit(p, { type: "cuts", clipId: "clip-1", cuts: [100], modes: ["generate"] })).message).toMatch(/each shot/);
+ expect(refused(() => edit(p, { type: "cuts", clipId: "nope", cuts: [] })).status).toBe(404);
+ });
+
+ it("a shot's cuts can't change under a take that is still being made", () => {
+ const p = projectOf();
+ const s = shotOf(p);
+ const busy = projectOf([clipOf({ shots: [{ ...s, segments: currentSegments(s).map((g, i) => (i ? g : { ...g, takes: [take("t1", { genId: "g-run" })] })) }] })]);
+ expect(shotBusy(shotOf(busy), (id) => id === "g-run")).toBe(true);
+ expect(refused(() => edit(busy, { type: "cuts", clipId: "clip-1", cuts: [100] }, (id) => id === "g-run")).status).toBe(409);
+ expect(refused(() => edit(busy, { type: "layout", clipId: "clip-1", shotId: s.id, op: { op: "split", frame: 50 } }, (id) => id === "g-run")).status).toBe(409);
+ expect(refused(() => edit(busy, { type: "remove-clip", clipId: "clip-1" }, (id) => id === "g-run")).status).toBe(409);
+ // Finished: all three go through.
+ expect(edit(busy, { type: "cuts", clipId: "clip-1", cuts: [100] }).clips[0].shots).toHaveLength(2);
+ expect(edit(busy, { type: "remove-clip", clipId: "clip-1" }).clips).toHaveLength(0);
+ });
+
+ it("who to swap, approvals and settings on a shot", () => {
+ const base = projectOf();
+ const s = { ...shotOf(base), anchors: [{ id: "a1", createdAt: 1, source: "generated" as const, genId: "g-a1" }], masks: [{ id: "m1", createdAt: 1, kind: "track" as const, engine: "open" as const, frame: 0, points: [], who: base.clips[0].shots[0].who, pieces: [{ from: 0, frames: 480, genId: "g-m1" }] }] };
+ const p = projectOf([clipOf({ shots: [s] })]);
+ const after = edit(p, { type: "shot", clipId: "clip-1", shotId: s.id, patch: { who: { selection: "index", index: 2, words: "the man in the hat" }, settings: { expansion: 24, useMask: false } } });
+ expect(shotOf(after).who).toEqual({ selection: "index", index: 2, words: "the man in the hat" });
+ expect(shotOf(after).settings).toMatchObject({ expansion: 24, useMask: false });
+ // Not made yet: can't be approved.
+ expect(refused(() => edit(p, { type: "shot", clipId: "clip-1", shotId: s.id, patch: { approvedAnchor: "a1" } })).message).toMatch(/isn't ready/);
+ expect(refused(() => edit(p, { type: "shot", clipId: "clip-1", shotId: s.id, patch: { approvedMask: "m1" } })).message).toMatch(/isn't ready/);
+ const made = projectOf([clipOf({ shots: [{ ...s, anchors: [{ ...s.anchors[0], url: "/api/files/a1.png" }], masks: [{ ...s.masks[0], pieces: [{ ...s.masks[0].pieces[0], url: "/api/files/m1.mp4" }] }] }] })]);
+ const approved = edit(made, { type: "shot", clipId: "clip-1", shotId: s.id, patch: { approvedAnchor: "a1", approvedMask: "m1" } });
+ expect(shotOf(approved)).toMatchObject({ approvedAnchor: "a1", approvedMask: "m1" });
+ // Removing the approved mask or anchor takes the approval with it.
+ expect(shotOf(edit(approved, { type: "remove-mask", clipId: "clip-1", shotId: s.id, maskId: "m1" })).approvedMask).toBeNull();
+ expect(shotOf(edit(approved, { type: "remove-anchor", clipId: "clip-1", shotId: s.id, anchorId: "a1" })).approvedAnchor).toBeNull();
+ // A mask still being made can't be removed.
+ expect(refused(() => edit(p, { type: "remove-mask", clipId: "clip-1", shotId: s.id, maskId: "m1" }, (id) => id === "g-m1")).message).toMatch(/still being made/);
+ });
+
+ it("Build shot prompts writes each swapped shot's prompt from its speaker and words", () => {
+ const p = edit(projectOf(), { type: "cuts", clipId: "clip-1", cuts: [240], modes: ["generate", "preserve"] });
+ const built = edit(p, { type: "build-prompts", clipId: "clip-1" });
+ expect(shotOf(built).prompt).toContain('Current shot dialogue: "Where were you".');
+ expect(shotOf(built).prompt).toContain("The selected character is speaking.");
+ expect(shotOf(built, 1).prompt).toBeNull();
+ // Marking the voice as someone else's changes what the next build says.
+ const other = edit(edit(built, { type: "voices", clipId: "clip-1", voices: { s1: "other" } }), { type: "build-prompts", clipId: "clip-1" });
+ expect(shotOf(other).prompt).toContain("Another person is speaking");
+ });
+});
+
+describe("segment edits", () => {
+ const p = projectOf();
+ const s = shotOf(p);
+ const [first] = currentSegments(s);
+
+ it("editing a segment's words or speaker keeps its prompt as it reads now; Update prompt rebuilds it", () => {
+ const before = segmentPrompt(p, p.clips[0], s, first);
+ const after = edit(p, { type: "segment", clipId: "clip-1", shotId: s.id, segmentId: first.id, patch: { dialogue: "Nowhere, I was here", speaker: "offscreen" } });
+ const seg = shotOf(after).segments![0];
+ expect(seg).toMatchObject({ dialogue: "Nowhere, I was here", speaker: "offscreen", performancePrompt: before });
+ const rebuilt = edit(after, { type: "update-prompt", clipId: "clip-1", shotId: s.id, segmentId: first.id });
+ const prompt = shotOf(rebuilt).segments![0].performancePrompt!;
+ expect(prompt).toContain('Current segment dialogue: "Nowhere, I was here".');
+ expect(prompt).toContain("Speech is offscreen");
+ });
+
+ it("refuses a first segment that continues, a seed out of range and a reference that isn't made", () => {
+ expect(refused(() => edit(p, { type: "segment", clipId: "clip-1", shotId: s.id, segmentId: first.id, patch: { connection: "continue" } })).message).toMatch(/first segment starts fresh/);
+ expect(refused(() => edit(p, { type: "segment", clipId: "clip-1", shotId: s.id, segmentId: first.id, patch: { seed: -1 } })).message).toMatch(/whole-number seed/);
+ expect(refused(() => edit(p, { type: "segment", clipId: "clip-1", shotId: s.id, segmentId: first.id, patch: { anchor: "nope" } })).message).toMatch(/isn't ready/);
+ expect(refused(() => edit(p, { type: "segment", clipId: "clip-1", shotId: s.id, segmentId: "gone", patch: { seed: 2 } })).status).toBe(404);
+ });
+
+ it("layouts: 5 s segments, split at the playhead, merge back", () => {
+ const five = edit(p, { type: "layout", clipId: "clip-1", shotId: s.id, op: { op: "partition", frames: 120 } });
+ expect(shotOf(five).segments!.map((g) => [g.start, g.end, g.connection])).toEqual([
+ [0, 120, "start"],
+ [120, 240, "continue"],
+ [240, 360, "continue"],
+ [360, 480, "continue"],
+ ]);
+ const split = edit(five, { type: "layout", clipId: "clip-1", shotId: s.id, op: { op: "split", frame: 60 } });
+ expect(shotOf(split).segments!.map((g) => g.end)).toEqual([60, 120, 240, 360, 480]);
+ const merged = edit(split, { type: "layout", clipId: "clip-1", shotId: s.id, op: { op: "merge", index: 1 } });
+ expect(shotOf(merged).segments!.map((g) => g.end)).toEqual([120, 240, 360, 480]);
+ expect(refused(() => edit(p, { type: "layout", clipId: "clip-1", shotId: s.id, op: { op: "partition", frames: 400 } })).message).toMatch(/15 seconds/);
+ });
+
+ it("imported references: one per segment picked by default, at most 12", () => {
+ const one = edit(p, { type: "anchor-import", clipId: "clip-1", shotId: s.id, segmentId: first.id, url: "/api/files/uploads/x/ref.png", id: "r1", at: 5 });
+ expect(shotOf(one).segments![0]).toMatchObject({ anchor: "r1", anchors: [{ id: "r1", source: "imported", url: "/api/files/uploads/x/ref.png" }] });
+ expect(refused(() => edit(p, { type: "anchor-import", clipId: "clip-1", shotId: s.id, url: "https://example.com/x.png", id: "r2", at: 5 })).message).toMatch(/Upload/);
+ let full = p;
+ for (let i = 0; i < 12; i++) full = edit(full, { type: "anchor-import", clipId: "clip-1", shotId: s.id, url: `/api/files/a${i}.png`, id: `a${i}`, at: i });
+ expect(refused(() => edit(full, { type: "anchor-import", clipId: "clip-1", shotId: s.id, url: "/api/files/a12.png", id: "a12", at: 12 })).message).toMatch(/at most 12/);
+ });
+
+ it("takes: choose a finished one, favourite, decide, note, remove; a running one can't be removed", () => {
+ const withTakes = projectOf([clipOf({ shots: [{ ...s, segments: currentSegments(s).map((g, i) => (i ? g : { ...g, takes: [take("t1"), take("t2"), take("w", { state: "waiting" })] })) }] })]);
+ const ref = { type: "take" as const, clipId: "clip-1", shotId: s.id, segmentId: first.id };
+ let q = edit(withTakes, { ...ref, takeId: "t2", select: true, favourite: true, decision: "keep", notes: "best eyes" });
+ expect(shotOf(q).segments![0].selectedTake).toBe("t2");
+ expect(shotOf(q).segments![0].takes[1]).toMatchObject({ favourite: true, decision: "keep", notes: "best eyes" });
+ expect(refused(() => edit(withTakes, { ...ref, takeId: "w", select: true })).message).toMatch(/didn't run/);
+ expect(refused(() => edit(withTakes, { ...ref, takeId: "w", remove: true })).message).toMatch(/Stop the take/);
+ q = edit(q, { ...ref, takeId: "t2", remove: true });
+ expect(shotOf(q).segments![0]).toMatchObject({ selectedTake: null });
+ expect(shotOf(q).segments![0].takes.map((t) => t.id)).toEqual(["t1", "w"]);
+ });
+
+ it("clip review: a decision and notes", () => {
+ const q = edit(p, { type: "clip", clipId: "clip-1", review: "maybe", reviewNotes: "lips drift in shot 2" });
+ expect(q.clips[0]).toMatchObject({ review: "maybe", reviewNotes: "lips drift in shot 2" });
+ });
+});
+
+describe("queued takes", () => {
+ it("your GPU continues from the segment right before only (its master holds that segment's frames)", () => {
+ const p = projectOf();
+ const s = { ...shotOf(p), approvedAnchor: null, settings: { ...DEFAULT_SETTINGS, useAnchor: false } };
+ const at = (bounds: number[], history: number[]) => bounds.slice(0, -1).map((b, i) => ({ ...newSegment(s, b, bounds[i + 1], i, rand), history: history[i], anchorMode: "none" as const }));
+ // Segment 2 is 20 frames long and segment 3 wants 35 frames of history: that reaches into segment 1.
+ const gpu = { ...s, segments: at([0, 100, 120, 480], [0, 18, 35]) };
+ const clip = { ...p.clips[0], shots: [gpu] };
+ const q = planQueue({ ...p, clips: [clip] }, clip, gpu, gpu.segments[0].id, "all", { active: () => false, hasMaster: () => true });
+ expect("problem" in q && q.problem).toMatch(/Segment 3: its 35 frames of history reach back past segment 2/);
+ // Within segment 2: fine.
+ const ok = { ...s, segments: at([0, 100, 140, 480], [0, 18, 35]) };
+ const okClip = { ...p.clips[0], shots: [ok] };
+ expect("entries" in planQueue({ ...p, clips: [okClip] }, okClip, ok, ok.segments[0].id, "all", { active: () => false, hasMaster: () => true })).toBe(true);
+ // The cloud carries only the last frame across.
+ const cloud = { ...s, segments: at([0, 100, 150, 480], [0, 18, 52]) };
+ const cloudClip = { ...p.clips[0], shots: [cloud] };
+ expect("entries" in planQueue({ ...p, engine: "cloud", clips: [cloudClip] }, cloudClip, cloud, cloud.segments[0].id, "all", { active: () => false })).toBe(true);
+ });
+
+ it("a frozen take runs with what it was queued with, not later edits", () => {
+ const p = projectOf();
+ const s = { ...shotOf(p), settings: { ...DEFAULT_SETTINGS, useAnchor: false } };
+ const items = currentSegments(s).map((g) => ({ ...g, anchorMode: "none" as const }));
+ const shot = { ...s, segments: items };
+ const clip = { ...p.clips[0], shots: [shot] };
+ const proj = { ...p, clips: [clip] };
+ const seg = items[1];
+ const t: SwapTake = { ...take("q1", { state: "waiting", genId: undefined }), prompt: segmentPrompt(proj, clip, shot, seg), seed: seg.seed, signature: settingSignature(proj, clip, shot, seg), dependencies: dependencies(items, 1), frozen: freezeTake(proj, shot, seg) };
+ expect(t.frozen).toMatchObject({ reference: "/api/files/uploads/x/hero.png", shotStart: 0, start: seg.start, end: seg.end, history: seg.history, anchor: null, mask: null });
+ // Edited after queueing: another character, LoRA and who to swap.
+ const edited = { ...proj, character: { ...proj.character, image: "/api/files/other.png" } };
+ const later = { ...shot, settings: { ...shot.settings, lora: "none" as const, renderMp: 0.5 as const }, who: { selection: "leftmost" as const, index: 0, words: "the child" } };
+ const plan = frozenTakePlan(edited, clip, later, seg, t, { shot: 1, segment: 2, take: 1 }, { master: "/api/files/master.mkv", frames: items[0].end - items[0].start });
+ const r = plan.steps[0].request;
+ expect(r.inputs?.images).toEqual(["/api/files/uploads/x/hero.png"]);
+ expect(r.params?.resolution).toBe("768p");
+ expect(r.params?.extra).toMatchObject({ selection: "largest", maskPrompt: "person", historyVideo: "/api/files/master.mkv", historyStart: items[0].end - items[0].start - seg.history, historyLength: seg.history });
+ expect(r.params?.extra).not.toHaveProperty("lora");
+ expect(() => frozenTakePlan(edited, clip, later, seg, { ...t, frozen: undefined }, { shot: 1, segment: 2, take: 1 }, null)).toThrow(/queue the segment again/);
+ });
+});
+
+describe("job state", () => {
+ const g = (status: GenSummary["status"], over: Partial<GenSummary> = {}): GenSummary => ({ status, progress: null, message: null, error: null, costUsd: 0, demo: true, ...over });
+
+ it("a job is its final generation, unless a step before it failed (that error is the reason)", () => {
+ expect(jobState(undefined, undefined, {})).toEqual({ status: "missing", progress: null, message: null });
+ expect(jobState("f", ["a", "f"], { a: g("succeeded"), f: g("succeeded") })).toEqual({ status: "succeeded", progress: 1, message: null });
+ expect(jobState("f", ["a", "b", "f"], { a: g("succeeded"), b: g("running", { progress: 0.5, message: "Tracking" }), f: g("queued") })).toEqual({ status: "running", progress: 0.5, message: "Tracking" });
+ expect(jobState("f", ["a", "f"], { a: g("failed", { error: "fal: 422 video too long" }), f: g("failed", { error: "An earlier step didn't finish" }) })).toEqual({ status: "failed", progress: null, message: "fal: 422 video too long" });
+ expect(jobState("f", ["f"], { f: g("canceled", { message: "Canceled" }) }).status).toBe("canceled");
+ });
+});