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.

Genjutsu: server and API — estimate and run, priced per resolution, blockers in words

Claude4fc34e1a555e
diff --git a/src/app/api/genjutsu/estimate/route.ts b/src/app/api/genjutsu/estimate/route.ts
new file mode 100644
index 00000000..fdab6c41
--- /dev/null
+++ b/src/app/api/genjutsu/estimate/route.ts
@@ -0,0 +1,10 @@
+import { estimateGenjutsu, GenjutsuEstimateSchema } from "@/server/genjutsu";
+import { body, handle } from "@/server/shorts-schemas";
+
+/** The price, the model, the pieces and the notes for the current settings, before anything runs. */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const input = await body(request, GenjutsuEstimateSchema, "Add a clip and pick a mode");
+ return Response.json(await estimateGenjutsu(input));
+ });
+}
diff --git a/src/app/api/genjutsu/route.ts b/src/app/api/genjutsu/route.ts
new file mode 100644
index 00000000..1c79d6f7
--- /dev/null
+++ b/src/app/api/genjutsu/route.ts
@@ -0,0 +1,12 @@
+import { createGenjutsu, GenjutsuBodySchema } from "@/server/genjutsu";
+import { body, handle, once } from "@/server/shorts-schemas";
+
+/** Run a Genjutsu: the pieces or windows are made, joined, and the clip's sound put back. */
+export async function POST(request: Request) {
+ return handle(async () => {
+ const input = await body(request, GenjutsuBodySchema, "Add a clip, pick a mode and add your references");
+ // A repeated requestId (a second click on Generate) gets the run the first one started.
+ const { final, items } = await once("genjutsu", input.requestId, () => createGenjutsu(input));
+ return Response.json({ final, items }, { status: 201 });
+ });
+}
diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.ts
new file mode 100644
index 00000000..f0802e0e
--- /dev/null
+++ b/src/server/genjutsu.ts
@@ -0,0 +1,294 @@
+import "server-only";
+import { z } from "zod";
+import { getModel } from "@/lib/catalog";
+import {
+ chooseMaker,
+ GENJUTSU,
+ genjutsuProblem,
+ genjutsuTitle,
+ MODE_TARGETS,
+ planGenjutsu,
+ planMakerPieces,
+ qualityFor,
+ makerStepUsd,
+ type GenjutsuLook,
+ type GenjutsuMode,
+ type GenjutsuPlanInput,
+ type GenjutsuTarget,
+ type GenjutsuTier,
+ type Maker,
+} from "@/lib/catalog/genjutsu";
+import { scalePoints, wholeClip, type RemoveRange, type RemoveSource } from "@/lib/catalog/remove-object";
+import type { PlanStep } from "@/lib/catalog/shorts";
+import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";
+import { createPipeline } from "./chains";
+import { previewChained } from "./generations";
+import { provider } from "./providers";
+import { pointsFromPaint } from "./remove-object";
+import { engineMode } from "./settings";
+import { probeSource, ShortsError } from "./shorts";
+
+/**
+ * Genjutsu (/genjutsu): plans, prices and starts a Motion transfer, Object swap, Restyle or Insert
+ * (src/lib/catalog/genjutsu.ts) as one pipeline of ordinary generations: feature "genjutsu" for the finished video,
+ * "genjutsu-step" for the cuts, tracks, pieces and joins. No table of its own: the page's history is a feed, and a
+ * setup travels as a code (encodeSetup), not a row.
+ */
+
+export { ShortsError as GenjutsuError };
+
+export interface GenjutsuBody {
+ engine: Engine;
+ mode: GenjutsuMode;
+ /** The model picked (defaults per engine, mode and key). */
+ modelId?: string;
+ /** Genjutsu Lite ("standard") or the full model ("high"). */
+ tier?: GenjutsuTier;
+ quality?: string;
+ target?: GenjutsuTarget;
+ /** Object swap: what goes. */
+ subject?: string;
+ prompt?: string;
+ points?: PixelPoint[];
+ /** The picture the points or the paint were made on (the first frame the browser showed). */
+ frame?: { width: number; height: number };
+ mask?: string;
+ references?: string[];
+ look?: GenjutsuLook;
+ source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };
+ range?: RemoveRange;
+ seed?: number;
+}
+
+const fileUrl = z.string().startsWith("/api/files/").max(500);
+const seconds = z.number().finite().min(0).max(3600);
+const point = z.object({ x: z.number().finite().min(0).max(20000), y: z.number().finite().min(0).max(20000), label: z.enum(["positive", "negative"]).optional() });
+const look = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("preset"), id: z.string().max(80) }),
+ z.object({ kind: z.literal("higgsfield"), id: z.string().max(80), name: z.string().max(120).optional() }),
+ z.object({ kind: z.literal("custom"), images: z.array(fileUrl).max(GENJUTSU.maxLookImages), words: z.string().max(300).optional() }),
+]);
+
+/** The body of /api/genjutsu (and /estimate). */
+export const GenjutsuBodySchema = z.object({
+ engine: z.enum(["cloud", "open"]),
+ mode: z.enum(["motion", "swap", "restyle", "insert"]),
+ modelId: z.string().max(80).optional(),
+ tier: z.enum(["standard", "high"]).optional(),
+ quality: z.enum(["480p", "720p", "1080p"]).optional(),
+ target: z.enum(["type", "click", "paint"]).optional(),
+ subject: z.string().max(300).optional(),
+ prompt: z.string().max(GENJUTSU.maxPromptChars).optional(),
+ points: z.array(point).max(GENJUTSU.maxPoints).optional(),
+ frame: z.object({ width: z.number().int().positive().max(20000), height: z.number().int().positive().max(20000) }).optional(),
+ mask: fileUrl.optional(),
+ references: z.array(fileUrl).max(GENJUTSU.maxReferences).optional(),
+ look: look.optional(),
+ source: z.object({
+ url: fileUrl,
+ name: z.string().max(200).optional(),
+ duration: z.number().finite().positive().max(3600).optional(),
+ fps: z.number().finite().positive().max(240).optional(),
+ width: z.number().int().positive().max(20000).optional(),
+ height: z.number().int().positive().max(20000).optional(),
+ hasAudio: z.boolean().optional(),
+ }),
+ range: z.object({ start: seconds, end: seconds }).optional(),
+ seed: z.number().int().min(0).max(2 ** 48).optional(),
+ /** A client nonce for one submit: a repeat gets the first answer (see once()). */
+ requestId: z.string().trim().min(8).max(64).optional(),
+});
+
+/** The estimate is asked for before uploads finish: any URL stands in. */
+export const GenjutsuEstimateSchema = GenjutsuBodySchema.extend({
+ source: GenjutsuBodySchema.shape.source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }),
+ mask: z.string().max(500).optional(),
+ references: z.array(z.string().max(500)).max(GENJUTSU.maxReferences).optional(),
+});
+
+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);
+ }
+};
+
+/** A Higgsfield key is set (Genjutsu and Genjutsu Lite run on it). */
+export const higgsfieldReady = () => provider("higgsfield").isConfigured();
+
+interface Planned {
+ input: GenjutsuPlanInput;
+ maker: Maker;
+ notes: string[];
+}
+
+async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<Planned> {
+ mustMatchMode(body.engine);
+ const picked = chooseMaker({ engine: body.engine, mode: body.mode, target: body.target, tier: body.tier, look: body.look, modelId: body.modelId, higgsfield: higgsfieldReady() });
+ if ("problem" in picked) throw new ShortsError(picked.problem, 422);
+ const maker = picked.maker;
+ // The header's facts win over what the browser read (the estimate runs before the upload is read).
+ const info = opts.probe ? await probeSource(body.source.url) : {};
+ const source: RemoveSource = {
+ url: body.source.url,
+ duration: info.duration ?? body.source.duration,
+ fps: info.fps ?? body.source.fps,
+ width: info.width ?? body.source.width,
+ height: info.height ?? body.source.height,
+ // Sound we couldn't read counts as none (putting it back would fail after the work was paid for).
+ hasAudio: opts.probe ? (info.hasAudio ?? false) : (body.source.hasAudio ?? false),
+ };
+ const range = body.range ?? (source.duration ? { start: 0, end: Math.min(source.duration, GENJUTSU.maxSeconds) } : null);
+ if (!range) throw new ShortsError("Reading the clip… try again in a moment");
+ const target = MODE_TARGETS[body.mode].length ? (body.target ?? MODE_TARGETS[body.mode][0]) : undefined;
+ const references = body.references ?? [];
+ const clicks = (body.points ?? []).filter((p) => p.label !== "negative").length;
+ const problem = genjutsuProblem({ mode: body.mode, maker, source, range, references: references.length, target, subject: body.subject, prompt: body.prompt, points: clicks, mask: !!body.mask, look: body.look });
+ if (problem) throw new ShortsError(problem, 422);
+
+ // Clicks on the first frame, in the clip's pixels; paint over several hosted VACE pieces is followed from its deepest points.
+ let points: PixelPoint[] | undefined;
+ const size = source.width && source.height ? { width: source.width, height: source.height } : null;
+ if (target === "click") points = body.frame && size ? scalePoints(body.points!.slice(0, GENJUTSU.maxPoints), body.frame, size) : body.points;
+ const pieces = planMakerPieces(maker, source, range);
+ const n = pieces.length || 1;
+ if (target === "paint" && maker.engine === "cloud" && body.mode === "swap" && n > 1) {
+ points = opts.probe ? await pointsFromPaint(body.mask!, source, "Paint over what to swap first") : [{ x: 1, y: 1, label: "positive" }];
+ }
+
+ const notes = notesFor(body, maker, source, range, n, references.length);
+ const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);
+ const title = genjutsuTitle({ mode: body.mode, subject: body.subject, look: body.look });
+ return {
+ maker,
+ notes,
+ input: {
+ engine: body.engine,
+ mode: body.mode,
+ maker,
+ title: name ? `${title} · ${name}` : title,
+ source,
+ range,
+ quality: body.quality ?? GENJUTSU.defaultQuality,
+ references,
+ target,
+ subject: body.subject?.trim() || undefined,
+ prompt: body.prompt?.trim() || undefined,
+ points,
+ mask: target === "paint" ? body.mask : undefined,
+ look: body.look,
+ ...(body.seed !== undefined ? { seed: body.seed } : {}),
+ },
+ };
+}
+
+function notesFor(body: GenjutsuBody, m: Maker, source: RemoveSource, range: RemoveRange, n: number, refs: number): string[] {
+ const notes: string[] = [];
+ const name = getModel(m.id)?.name ?? m.label;
+ const fps = source.fps ?? 30;
+ const fuobeLook = body.mode === "restyle" && m.looks === "fuobe";
+ if (n > 1) {
+ if (m.engine === "open" && m.window) {
+ notes.push(`${name} works on ${m.window.cap} frames at a time (${(m.window.cap / fps).toFixed(1)} s of this clip): it runs as ${n} windows, joined with the clip's own sound. Seams between windows aren't tested on a GPU yet`);
+ } else if (fuobeLook) {
+ notes.push(`${name} restyles ${m.engine === "open" ? "5 s" : "up to 10 s"} at a time: the clip runs as ${n} segments, joined with its own sound`);
+ } else {
+ const limit = m.window ? `${m.window.cap} frames (${(m.window.cap / fps).toFixed(1)} s of this clip)` : `${m.maxSeconds} s`;
+ notes.push(`${name} takes up to ${limit} a call: the clip runs as ${n} pieces, joined with its own sound. Seams between pieces aren't tested yet`);
+ }
+ }
+ if (body.mode !== "restyle" && refs > m.refs.max) notes.push(m.refs.max === 1 ? `${name} uses your first reference image` : `${name} takes ${m.refs.max} references — your first ${m.refs.max} go`);
+ if (fuobeLook && refs) notes.push("Character references go with Higgsfield's looks (Genjutsu Restyle); this look restyles what is filmed");
+ if (fuobeLook && body.look?.kind === "custom" && m.readsLookImages && body.look.images.length > m.readsLookImages) notes.push(`${name} reads ${m.readsLookImages} of your look's images`);
+ if (body.mode === "restyle" && m.looks === "higgsfield" && refs > m.refs.max) notes.push(`Genjutsu Restyle takes ${m.refs.max} character references — your first ${m.refs.max} go`);
+ const quality = body.quality ?? GENJUTSU.defaultQuality;
+ const res = qualityFor(m, quality);
+ if (m.engine === "cloud" && !m.qualities) notes.push(`${name} keeps your clip's size (it has no resolution setting)`);
+ else if (res && res !== quality) notes.push(`${name} renders ${res} at most here — that's what you get`);
+ if (m.id === "wan-22-vace-inpaint") {
+ notes.push(body.mode === "insert" ? "The spot stays where you painted it for the whole shot — best with a still or slow camera" : "Only the area you marked changes; SAM 3.1 follows it through the selection when it runs as pieces or you clicked");
+ }
+ if (m.id === "oss-vace-insert") notes.push("The spot stays where you painted it for the whole shot — best with a still or slow camera");
+ if (m.people) notes.push("P-Video Replace swaps the person on camera — for objects, pick Genjutsu or Kling O3");
+ if (m.higgsfield) notes.push(`${m.tier === "standard" ? "Genjutsu Lite" : "Genjutsu"} is at 50% off on Higgsfield right now (2026-10-22) — the price here is the list price`);
+ if (m.engine === "open") {
+ if (m.id === "oss-wan22-animate") notes.push("Wan Animate 2 needs a 24 GB GPU · Apache-2.0");
+ else if (m.window) notes.push(`Wan 2.1 VACE 14B needs a 24 GB GPU · Apache-2.0${body.mode === "swap" ? " (SAM 3.1: Meta's SAM License)" : ""}`);
+ }
+ if (!wholeClip(range, source.duration)) notes.push("Only the selected part comes out (the rest of the clip isn't kept)");
+ return notes;
+}
+
+const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });
+
+/** What the steps cost together (null when a price is unknown) and whether they would run as a demo. */
+function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean } {
+ let cost: number | null = 0;
+ let demo = false;
+ for (const s of steps) {
+ let p: ReturnType<typeof previewChained>;
+ try {
+ p = previewChained(withChain(s), s.after?.length ?? 0);
+ } catch (e) {
+ throw new ShortsError((e as Error).message, 422);
+ }
+ demo ||= p.demo;
+ // Genjutsu's tiers and Kling O3's edit price aren't in the catalog per resolution: the planner's table.
+ const own = p.demo ? null : makerStepUsd(s.request.modelId, s.request.params);
+ const usd = own ?? p.costUsd;
+ cost = cost === null || usd === null ? null : cost + usd;
+ }
+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo };
+}
+
+export interface GenjutsuEstimate {
+ costUsd: number | null;
+ demo: boolean;
+ /** The model that runs (the default, or the one picked) and its tier. */
+ modelId: string;
+ modelName: string;
+ tier?: GenjutsuTier;
+ /** The resolution it is asked for (none: it keeps the clip's size). */
+ quality?: string;
+ pieces: number;
+ seconds: number;
+ steps: number;
+ notes: string[];
+ /** A Higgsfield key is set. */
+ higgsfield: boolean;
+}
+
+export async function estimateGenjutsu(body: GenjutsuBody): Promise<GenjutsuEstimate> {
+ const { input, maker, notes } = await planInput(body, { probe: false });
+ let plan: ReturnType<typeof planGenjutsu>;
+ try {
+ plan = planGenjutsu(input);
+ } catch (e) {
+ throw new ShortsError((e as Error).message, 422);
+ }
+ return {
+ ...price(plan.steps),
+ modelId: maker.id,
+ modelName: getModel(maker.id)?.name ?? maker.label,
+ ...(maker.tier ? { tier: maker.tier } : {}),
+ ...(qualityFor(maker, input.quality) ? { quality: qualityFor(maker, input.quality) } : {}),
+ pieces: plan.pieces,
+ seconds: Math.round((input.range.end - input.range.start) * 100) / 100,
+ steps: plan.steps.length,
+ notes,
+ higgsfield: higgsfieldReady(),
+ };
+}
+
+/** Start it; returns the finished video's generation (the other steps wait for each other). */
+export async function createGenjutsu(body: GenjutsuBody): Promise<{ final: Generation; items: Generation[] }> {
+ const { input } = await planInput(body, { probe: true });
+ try {
+ const plan = planGenjutsu(input);
+ const p = createPipeline(plan.steps);
+ return { final: p.byKey[plan.final], items: p.items };
+ } catch (e) {
+ if (e instanceof ShortsError) throw e;
+ throw new ShortsError((e as Error).message, 422);
+ }
+}
diff --git a/src/server/remove-object.ts b/src/server/remove-object.ts
index 60ccdcd5..ce8a3686 100644
--- a/src/server/remove-object.ts
+++ b/src/server/remove-object.ts
@@ -123,7 +123,7 @@ const mustMatchMode = (engine: Engine) => {
};
/** Points a SAM 3.1 track starts from: the deepest points of the paint, in the clip's pixels. */
-async function pointsFromPaint(mask: string, size: { width?: number; height?: number }): Promise<PixelPoint[]> {
+export async function pointsFromPaint(mask: string, size: { width?: number; height?: number }, empty = "Paint over what to remove first"): Promise<PixelPoint[]> {
let png: ReturnType<typeof decodePng>;
try {
png = decodePng((await readRef(mask)).data);
@@ -133,7 +133,7 @@ async function pointsFromPaint(mask: string, size: { width?: number; height?: nu
const on = new Uint8Array(png.width * png.height);
for (let i = 0; i < on.length; i++) on[i] = png.data[i * 4] > 127 ? 1 : 0;
const found = paintedPoints(on, png.width, png.height);
- if (!found.length) throw new ShortsError("Paint over what to remove first");
+ if (!found.length) throw new ShortsError(empty);
return size.width && size.height ? scalePoints(found, png, { width: size.width, height: size.height }) : found;
}
diff --git a/tests/genjutsu-api.test.ts b/tests/genjutsu-api.test.ts
new file mode 100644
index 00000000..c8b08b0f
--- /dev/null
+++ b/tests/genjutsu-api.test.ts
@@ -0,0 +1,182 @@
+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 type { Generation } from "@/lib/catalog/types";
+
+vi.setConfig({ testTimeout: 120_000 });
+
+// /api/genjutsu end to end in demo mode (no keys, no ComfyUI): each mode on both engines becomes one pipeline of
+// ordinary generations, which the mock provider runs through; estimates with keys set price the real routes.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-"));
+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 { db } = await import("@/server/db");
+const createRoute = await import("@/app/api/genjutsu/route");
+const estimateRoute = await import("@/app/api/genjutsu/estimate/route");
+
+const json = (body?: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+
+let clip = "";
+let hero = "";
+let mask = "";
+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 px = (w: number, h: number, on: (x: number, y: number) => boolean) => {
+ const data = Buffer.alloc(w * h * 4);
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const at = (y * w + x) * 4;
+ data.fill(on(x, y) ? 255 : 0, at, at + 3);
+ data[at + 3] = 255;
+ }
+ return encodePng({ width: w, height: h, data });
+ };
+ hero = saveFile({ data: px(64, 64, () => true), contentType: "image/png", source: "upload", name: "hero.png" }).url;
+ mask = saveFile({ data: px(72, 128, (x, y) => x >= 20 && x < 50 && y >= 80 && y < 110), contentType: "image/png", source: "upload", name: "mask.png" }).url;
+});
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+async function settle(id: string, ms = 90_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+const batchOf = (id: string) => {
+ const b = (db().prepare("SELECT batch_id FROM generations WHERE id = ?").get(id) as { batch_id: string }).batch_id;
+ return db().prepare("SELECT id, model_id, op, feature FROM generations WHERE batch_id = ? ORDER BY created_at, id").all(b) as { id: string; model_id: string; op: string; feature: string }[];
+};
+
+const src = { duration: 12, fps: 16, width: 1280, height: 720, hasAudio: true };
+const body = (over: Record<string, unknown> = {}) => ({ engine: "cloud", mode: "motion", references: [hero], source: { url: clip, name: "dance.mp4" }, ...over });
+
+describe("Genjutsu: estimates", () => {
+ it("without a Higgsfield key: Kling Motion Control in 10 s pieces, run as a demo", async () => {
+ const res = await estimateRoute.POST(json(body({ source: { url: clip, ...src } })));
+ expect(res.status).toBe(200);
+ const e = await res.json();
+ expect(e).toMatchObject({ modelId: "kling-motion-control", pieces: 2, seconds: 12, demo: true, higgsfield: false });
+ expect(e.notes.join(" ")).toMatch(/2 pieces, joined with its own sound/);
+ });
+
+ describe("with keys (estimates submit nothing, so the prices are the routes' own)", () => {
+ beforeAll(() => {
+ setSetting("higgsfieldKey", "key-id:key-secret");
+ setSetting("falKey", "fal-test-key");
+ });
+ afterAll(() => {
+ setSetting("higgsfieldKey", "");
+ setSetting("falKey", "");
+ });
+
+ it("Genjutsu Lite by default; Quality: High is the full model at its own price per resolution", async () => {
+ const lite = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src }, quality: "1080p" })))).json();
+ // One 12 s call (Lite takes 15 s) that keeps the sound: $0.20 a second at 1080p.
+ expect(lite).toMatchObject({ modelId: "genjutsu-lite-motion-transfer", tier: "standard", quality: "1080p", pieces: 1, steps: 1, demo: false, higgsfield: true });
+ expect(lite.costUsd).toBeCloseTo(2.4, 4);
+ expect(lite.notes.join(" ")).toMatch(/50% off/);
+ const full = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src, duration: 12.3 }, range: { start: 0, end: 12.3 }, tier: "high", quality: "480p" })))).json();
+ // Whole seconds: 13 × $0.318.
+ expect(full).toMatchObject({ modelId: "genjutsu-motion-transfer", tier: "high" });
+ expect(full.costUsd).toBeCloseTo(13 * 0.318, 4);
+ });
+
+ it("Kling O3 swap at its edit price; the hosted VACE per 16-frame second", async () => {
+ const kling = await (await estimateRoute.POST(json(body({ mode: "swap", modelId: "kling-o3", subject: "the red car", source: { url: clip, ...src, duration: 10 }, range: { start: 0, end: 10 } })))).json();
+ expect(kling).toMatchObject({ modelId: "kling-o3", pieces: 1 });
+ expect(kling.costUsd).toBeCloseTo(1.68, 3);
+ expect(kling.notes.join(" ")).toMatch(/keeps your clip's size/);
+ const vace = await (await estimateRoute.POST(json(body({ mode: "insert", target: "paint", mask: "/api/files/m.png", quality: "480p", source: { url: clip, ...src }, range: { start: 0, end: 10 } })))).json();
+ // 160 frames at 16 fps → one piece of 157 frames, billed as 157 / 16 s at $0.05, then the sound put back.
+ expect(vace).toMatchObject({ modelId: "wan-22-vace-inpaint", pieces: 1, quality: "480p" });
+ expect(vace.costUsd).toBeGreaterThanOrEqual((157 / 16) * 0.05);
+ expect(vace.costUsd).toBeLessThan((157 / 16) * 0.05 + 0.01);
+ });
+ });
+
+ it("blockers come back in words", async () => {
+ const say = async (b: Record<string, unknown>) => {
+ const res = await estimateRoute.POST(json(b));
+ expect(res.status).toBe(422);
+ return (await res.json()).error as string;
+ };
+ expect(await say(body({ references: [], source: { url: clip, ...src } }))).toBe("Add a picture of your character");
+ expect(await say(body({ source: { url: clip, ...src }, range: { start: 0, end: 3 } }))).toMatch(/between 4 and 30 seconds/);
+ expect(await say(body({ mode: "swap", target: "paint", engine: "open", source: { url: clip, ...src } }))).toMatch(/name what to swap/);
+ expect(await say(body({ mode: "swap", modelId: "kling-o3", source: { url: clip, ...src, duration: 10 }, range: { start: 0, end: 10 } }))).toMatch(/Say what to swap/);
+ expect(await say(body({ mode: "restyle", references: [], source: { url: clip, ...src } }))).toBe("Pick a look");
+ setSetting("engineMode", "open");
+ expect(await say(body({ source: { url: clip, ...src } }))).toMatch(/open-source models only/);
+ setSetting("engineMode", "both");
+ });
+});
+
+describe("Genjutsu: runs (demo)", () => {
+ const run = async (b: Record<string, unknown>) => {
+ const res = await createRoute.POST(json(b));
+ const out = await res.json();
+ expect(res.status, out.error).toBe(201);
+ return out as { final: Generation; items: Generation[] };
+ };
+
+ it("cloud motion transfer: pieces, a join and the sound, the finished video under feature genjutsu", async () => {
+ const { final, items } = await run(body({ prompt: "a knight in silver armour" }));
+ expect(final.feature).toBe("genjutsu");
+ expect(items.filter((g) => g.feature === "genjutsu")).toHaveLength(1);
+ const rows = batchOf(final.id);
+ expect(rows.filter((r) => r.op === "motion-transfer").map((r) => r.model_id)).toEqual(["kling-motion-control", "kling-motion-control"]);
+ expect(rows.some((r) => r.op === "concat") && rows.some((r) => r.op === "mux")).toBe(true);
+ expect((await settle(final.id)).status).toBe("succeeded");
+ });
+
+ it("a repeated requestId gets the first run", async () => {
+ const b = body({ requestId: "genjutsu-nonce-1" });
+ const a = await run(b);
+ const again = await run(b);
+ expect(again.final.id).toBe(a.final.id);
+ });
+
+ it("open object swap by name: VACE windows from the upload, joined under the sound", async () => {
+ const { final } = await run(body({ engine: "open", mode: "swap", subject: "the skateboard", references: [hero, hero] }));
+ const rows = batchOf(final.id);
+ // 192 frames at 16 fps → 3 windows of ≤81.
+ expect(rows.filter((r) => r.op === "video-swap").map((r) => r.model_id)).toEqual(["oss-vace-swap", "oss-vace-swap", "oss-vace-swap"]);
+ const swap = gens.getGeneration(rows.find((r) => r.op === "video-swap")!.id)!;
+ expect(swap.request.params?.extra).toEqual({ maskPrompt: "the skateboard" });
+ expect(swap.request.inputs?.images).toEqual([hero]);
+ expect((await settle(final.id)).status).toBe("succeeded");
+ });
+
+ it("cloud swap by paint on one hosted VACE piece: the paint itself, no track", async () => {
+ const { final } = await run(body({ mode: "swap", target: "paint", mask, range: { start: 0, end: 12 } }));
+ const rows = batchOf(final.id);
+ expect(rows.some((r) => r.model_id === "sam-3-1-video-mask")).toBe(false);
+ // 12 s at 16 fps is one hosted VACE piece (≤241 frames): the paint itself, no track.
+ expect(rows.filter((r) => r.op === "video-swap").map((r) => r.model_id)).toEqual(["wan-22-vace-inpaint"]);
+ expect((await settle(final.id)).status).toBe("succeeded");
+ });
+
+ it("insert on the open engine and restyle on a Fuobe look run through", async () => {
+ const ins = await run(body({ engine: "open", mode: "insert", target: "paint", mask, prompt: "a lamp on the table", range: { start: 0, end: 5 } }));
+ expect(batchOf(ins.final.id).filter((r) => r.op === "video-insert").length).toBe(1);
+ expect((await settle(ins.final.id)).status).toBe("succeeded");
+ const look = await run(body({ mode: "restyle", references: [], look: { kind: "preset", id: "shorts-claymation" } }));
+ const rows = batchOf(look.final.id);
+ expect(rows.filter((r) => r.op === "v2v").every((r) => r.feature === "genjutsu-step")).toBe(true);
+ expect(rows.filter((r) => r.feature === "genjutsu")).toHaveLength(1);
+ expect((await settle(look.final.id)).status).toBe("succeeded");
+ });
+});