The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Kling 4.0: Cinema takes, Genjutsu swap and insert, clip limits and tests
Claude058dd0f19066
diff --git a/src/lib/catalog/cinema.ts b/src/lib/catalog/cinema.tsindex 173c5b57..e862604b 100644--- a/src/lib/catalog/cinema.ts+++ b/src/lib/catalog/cinema.ts@@ -1,7 +1,7 @@import { DEFAULT_MOTION, PATH_FPS, PATH_FRAMES, normalizeKeys, toH3MaxTrajectory, type CameraKey } from "@/lib/camera-path";import { APERTURE, LENS, anglesNote, poseWords, recomposePrompt, type ScenePose } from "@/lib/scene3d";import { getModel, getPreset } from "./index";-import { plannedDurations } from "./clip-lengths";+import { lengthRange, PLANNED_DURATIONS, plannedDurations } from "./clip-lengths";import { DOP_MODEL, LTX25_HOSTED } from "./dop";import { dualEngine, onEngine } from "./engines";import { localOnly, needsToken, triggerOf } from "./loras";@@ -602,7 +602,8 @@ export const CAST_SHEET_MODEL = "oss-zimage-soul-cast";*/export const CINEMA_MODELS: Record<CinemaMode, Record<Engine, string[]>> = {video: {- cloud: [CINEMA_MODEL, "minimax-h3", "seedance-2-5", "kling-3", "veo-3-1", "minimax-h3-max"],+ // Kling 4.0: a 30 s take (up to 6 shots) in one call, with @Elements and reference clips.+ cloud: [CINEMA_MODEL, "minimax-h3", "seedance-2-5", "kling-4", "kling-3", "veo-3-1", "minimax-h3-max"],open: [CINEMA_MODEL, "oss-minimax-h3", "oss-ltx25", "oss-wan22-14b"],},image: { cloud: [CINEMA_STILL_MODEL, "nano-banana-pro", "seedream-5-pro"], open: [CINEMA_STILL_MODEL, "oss-ideogram-4", "oss-qwen-image-21", "oss-krea2-realism", "oss-moss-image"] },@@ -1349,7 +1350,10 @@ function fitParams(model: ModelDef, input: CinemaGenerateInput, notes: string[],// Fuobe Cinema in the cloud: any whole second; past 20 s planVideo adds an extend for the rest.if (anyLength(model)) params.duration = Math.min(want, CINEMA_MAX_SECONDS);else {- params.duration = allowed?.length ? nearest(allowed, want) : want;+ // A model that renders any whole second in a range (Kling 4.0: 3–30 s) makes the length asked, within it, unless+ // Cinema plans it with a few lengths of its own (MiniMax H3 on your GPU: 5, 10 or 15 s).+ const range = PLANNED_DURATIONS[model.id] ? undefined : lengthRange(model);+ params.duration = range ? Math.max(range[0], Math.min(range[1], want)) : allowed?.length ? nearest(allowed, want) : want;if (params.duration !== want) notes.push(`${model.name} makes ${params.duration}s clips — use Extend for longer scenes`);}if (o.audio === true) params.generateAudio = input.audio !== false;diff --git a/src/lib/catalog/clip-lengths.ts b/src/lib/catalog/clip-lengths.tsindex e916a40d..e906cf49 100644--- a/src/lib/catalog/clip-lengths.ts+++ b/src/lib/catalog/clip-lengths.ts@@ -10,10 +10,14 @@ export const PLANNED_DURATIONS: Readonly<Record<string, readonly number[]>> = {/*** Models that render any whole number of seconds in a range, where a studio fits the clip to a length of its own- * (a Faceless scene cut to its lines, a Marketing motion ad of the length asked for). MiniMax H3 on your GPU renders- * any length on its 17n + 5 frame grid: 3 s up to the 15 s it is trained for.+ * (a Faceless scene cut to its lines, a Marketing motion ad of the length asked for, a Cinema take). MiniMax H3 on your+ * GPU renders any length on its 17n + 5 frame grid: 3 s up to the 15 s it is trained for.*/-export const LENGTH_RANGES: Readonly<Record<string, readonly [number, number]>> = { "oss-minimax-h3": [3, 15] };+export const LENGTH_RANGES: Readonly<Record<string, readonly [number, number]>> = {+ "oss-minimax-h3": [3, 15],+ // Kling 4.0 in the cloud: any whole second from 3 to 30 (fal's and Replicate's duration field).+ "kling-4": [3, 30],+};/** The clip lengths a studio plans with on a model: PLANNED_DURATIONS, else the catalog's own. */export function plannedDurations(model: Pick<ModelDef, "id" | "options"> | undefined): number[] | undefined {diff --git a/src/lib/catalog/clip-windows.ts b/src/lib/catalog/clip-windows.tsindex d81814be..afa4b71e 100644--- a/src/lib/catalog/clip-windows.ts+++ b/src/lib/catalog/clip-windows.ts@@ -20,6 +20,18 @@ export function sourceSeconds(modelId: string): { min?: number; max?: number } {return SOURCE_SECONDS[modelId] ?? {};}+/** The sides a clip edit takes, in pixels (Kling 4.0's edit: 700–4553 px on each side). */+const SOURCE_SIDES: Record<string, { min: number; max: number }> = { "kling-4": { min: 700, max: 4553 } };++/** Why a clip `width`×`height` is outside the sides the model takes, in Generate's words, or null. */+export function clipSizeProblem(model: { id: string; name: string }, width: number, height: number): string | null {+ const s = SOURCE_SIDES[model.id];+ if (!s || !(width > 0) || !(height > 0)) return null;+ if (Math.min(width, height) < s.min) return `${model.name} needs a clip at least ${s.min} px on each side, and this one is ${width}×${height}: upscale it first or pick another model`;+ if (Math.max(width, height) > s.max) return `${model.name} takes clips up to ${s.max} px on a side, and this one is ${width}×${height}: scale it down first`;+ return null;+}+/*** The most seconds of clips a run takes in all, where the model says (Kling 4.0: "the source, reference and element* videos must total at most 30s").diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.tsindex cadb8d14..bb9dfbf3 100644--- a/src/lib/catalog/genjutsu.ts+++ b/src/lib/catalog/genjutsu.ts@@ -430,6 +430,23 @@ export const MAKERS: Maker[] = [sides: { min: 720, max: 3840 },renders: "keeps your clip's size",},+ {+ // Kling 4.0's edit (fal, nm10-kling-4): @Video1 is the piece, @Image1.. what goes in. Billed on the seconds in plus out,+ // at least twice the output: an edit keeps the piece's length, so twice the piece (the catalog's clipInput price).+ id: "kling-4",+ engine: "cloud",+ modes: ["swap", "insert"],+ targets: ["type"],+ label: "Kling 4.0 edit",+ note: "Kuaishou's closed model · up to 10 references as @Image · 3–30 s a piece · billed on the seconds in and out",+ source: "partner",+ refs: { min: 1, max: 10 },+ maxSeconds: 30,+ minSeconds: 3,+ keepsSound: false,+ sides: { min: 700, max: 4553 },+ qualities: ["720p", "1080p"],+ },{id: "p-video-replace",engine: "cloud",@@ -820,7 +837,8 @@ export function makerPrompt(p: PromptInput): string | undefined {const out = [described ? `The character: ${described}.` : "", words ? `${cap(words)}.` : ""].filter(Boolean).join(" ");return out || undefined;}- if (m.id === "kling-o3") {+ // Kling O3 and Kling 4.0 edit: the clip is @Video1, the references @Image1...+ if (m.id === "kling-o3" || m.id === "kling-4") {const refs = imageTags(Math.max(1, p.refs));if (p.mode === "insert") return `Add ${refs} to @Video1${words ? `: ${words}` : ""}. Keep everything else the same: the motion, camera, framing and light.`;return `Replace ${what || "the main subject"} in @Video1 with ${refs}${also}${words ? `. ${cap(words)}` : ""}. Keep everything else the same: the motion, camera, framing and light.`;diff --git a/src/lib/catalog/keyframes.ts b/src/lib/catalog/keyframes.tsindex 64adfd5a..051d8961 100644--- a/src/lib/catalog/keyframes.ts+++ b/src/lib/catalog/keyframes.ts@@ -15,7 +15,12 @@*/import type { Engine, GenerationRequest, ModelDef, ModelRoute, Operation } from "./types";-/** Kling 4.0 and FLUX 3 Max take up to 10 frames. */+/**+ * Up to 10 frames, as Kling 4.0's own app and FLUX 3 Max keyframes-to-video take. Frames mode runs on FLUX 3 Max in the+ * cloud, never on Kling 4.0: its hosted API (fal and Replicate, read 2026-11-01) takes a start frame, up to 8 middle+ * frames in order and an end frame, with no time for any of them, so a frame can't be placed where the strip puts it.+ * Kling 4.0 runs here as a start + end frame model (only the first and the last frame).+ */export const MAX_KEYFRAMES = 10;/** Frame times snap to a tenth of a second. */export const KEYFRAME_SNAP = 0.1;diff --git a/src/lib/composer.ts b/src/lib/composer.tsindex 6392098f..fbd280dd 100644--- a/src/lib/composer.ts+++ b/src/lib/composer.ts@@ -7,7 +7,7 @@ import { FORMAT_INFO } from "./av/formats";import { fpsPlan, fpsSummary } from "./av/fps";import { targetShortEdge, upscaledSize, upscaleFactorFor, upscaleTier } from "./av/upscale";import { wholeClipProblem, wholeClipTool } from "./av/video-finish";-import { clipWindowProblem } from "./catalog/clip-windows";+import { clipSizeProblem, clipWindowProblem } from "./catalog/clip-windows";import { clipBilling } from "./catalog/plan";import { addFrameAt, frameTimes, framesInputs, removeFrameAt, spread, type FrameSupport } from "./catalog/keyframes";import { FACE_MOSAIC_MODELS } from "./catalog/open-tools";@@ -293,7 +293,10 @@ export function clipBlocker(model: (Pick<ModelDef, "engine" | "options" | "defaults"> & Partial<Pick<ModelDef, "id" | "name">>) | undefined,ramBytes: number | undefined,): string | null {- if (op === "v2v" && model?.id && facts?.duration) return clipWindowProblem({ id: model.id, name: model.name ?? model.id }, facts.duration);+ if (op === "v2v" && model?.id && (facts?.duration || facts?.width)) {+ const named = { id: model.id, name: model.name ?? model.id };+ return (facts.duration ? clipWindowProblem(named, facts.duration) : null) ?? (facts.width && facts.height ? clipSizeProblem(named, facts.width, facts.height) : null);+ }if (!facts?.width || !facts.height || !model) return null;if (op === "upscale-video") {const tier = upscaleTier(params.resolution ?? model.defaults?.resolution, model.options.resolutions, { width: facts.width, height: facts.height }, params.resolution !== undefined);diff --git a/src/server/generations.ts b/src/server/generations.tsindex 9d156099..0980bee4 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -12,7 +12,7 @@ import { cueText, type Cue } from "@/lib/cues";import { HELPER_FEATURES, HELPER_SUFFIX, isReviewStatus, type AssetUse, type ReviewFilter } from "@/lib/library";import { upscaleTier } from "@/lib/av/upscale";import { chainedWaitMessage, framesWait, keyframeChain } from "@/lib/catalog/keyframes";-import { clipTotalProblem, clipWindowProblem } from "@/lib/catalog/clip-windows";+import { clipSizeProblem, clipTotalProblem, clipWindowProblem } from "@/lib/catalog/clip-windows";import { avatarSeconds, clipEditSeconds, estimateCost, inferOperation, movedAppRequest, planGeneration, presetRoute, routeLoras, routesFor, withoutTriggers } from "@/lib/catalog/plan";import { framedLength, keepMatte } from "@/lib/catalog/payload";import { fitLoras, loraName, lorasFit } from "@/lib/catalog/loras";@@ -1582,7 +1582,7 @@ async function submitNow(// themselves): one outside the model's window is refused before it's paid for (Happy Horse bills 60 s and returns// 15), and one that keeps the clip's length is priced for it once the header is read (a call that didn't say).if (plan.op === "v2v" && input.sourceDuration && !req.chain?.length && req.params?.duration === undefined && providerId !== "mock" && plan.model.engine !== "open") {- const problem = clipWindowProblem(plan.model, input.sourceDuration);+ const problem = clipWindowProblem(plan.model, input.sourceDuration) ?? (input.sourceSize ? clipSizeProblem(plan.model, input.sourceSize.width, input.sourceSize.height) : null);if (problem) throw new Error(problem);if (plan.params.sourceDuration === undefined && clipEditSeconds(plan.model, input, plan.op) !== undefined) {update(id, { cost_usd: estimateCost(plan.model, { ...plan.params, sourceDuration: input.sourceDuration }, 1, plan.op, plan.loras.length > 0 && !!route.loraEndpoint) });diff --git a/tests/account-kling-clips.test.ts b/tests/account-kling-clips.test.tsnew file mode 100644index 00000000..8f356da4--- /dev/null+++ b/tests/account-kling-clips.test.ts@@ -0,0 +1,74 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++/**+ * Kling 4.0's reference clips and clip elements (nm10-kling-4): the server reads each clip's header to price it (input+ * plus output seconds). For an account's run that read is its own files only, as every other input: the run route's+ * check (account-inputs.ts) and storage's guard on the read (readRef) both refuse another's clip, and an account's+ * @mentions never pull the owner's Elements (their photos or clips) into its run.+ */+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-kling-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;++const auth = await import("@/server/auth");+const { runAsTenant } = await import("@/server/tenant");+const { readRef, saveFile } = await import("@/server/storage");+const { accountInputProblem } = await import("@/server/account-inputs");+const { mentionElements } = await import("@/server/generations");+const { createElement } = await import("@/server/elements");+const { getModel } = await import("@/lib/catalog");+const { applyMentions } = await import("@/lib/catalog/elements");+type Req = import("@/lib/catalog/types").GenerationRequest;++let a = "";+let b = "";+beforeAll(() => {+ auth.setPassword("install password");+ a = auth.createAccount("[email protected]", "long enough").id;+ b = auth.createAccount("[email protected]", "long enough").id;+});+afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++const CLIP = Buffer.from("not really an mp4, but a stored file");+const asA = <T,>(fn: () => T) => runAsTenant({ kind: "account", id: a }, fn);+const kling = getModel("kling-4")!;+const run = (videos: string[]): Req => ({ feature: "video", modelId: "kling-4", op: "ref2v", prompt: "@Maya walks in", inputs: { videos }, params: { duration: 10 } });++describe("an account's Kling 4.0 reference clips", () => {+ it("are its own uploads: another's clip is refused before the run and again when its header is read", async () => {+ const mine = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", accountId: a });+ const theirs = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", accountId: b });+ const owners = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload" });+ expect(accountInputProblem(run([mine.url]), a)).toBeNull();+ expect(accountInputProblem(run([mine.url, theirs.url]), a)).toMatchObject({ code: "input-not-yours" });+ expect(accountInputProblem(run([owners.url]), a)).toMatchObject({ code: "input-not-yours" });+ expect(accountInputProblem(run(["https://example.com/clip.mp4"]), a)).toMatchObject({ code: "input-not-allowed" });+ // The read that measures a clip for the price (generations.ts prepClip) goes through readRef's guard.+ await asA(async () => {+ expect((await readRef(mine.url)).data.equals(CLIP)).toBe(true);+ await expect(readRef(theirs.url)).rejects.toThrow(/isn't yours/);+ await expect(readRef(owners.url)).rejects.toThrow(/isn't yours/);+ });+ });++ it("never take the owner's Elements as Kling elements", () => {+ const clip = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload" });+ createElement({ name: "Maya", kind: "character", references: [clip.url] });+ // The owner's run turns @Maya into a clip element; an account's sees no Elements, so its request stays as it was.+ expect(applyMentions(run([]), kling, mentionElements()).request.params?.elements).toEqual([{ video: 0 }]);+ asA(() => {+ const { request, mentioned } = applyMentions(run([]), kling, mentionElements());+ expect(mentioned).toEqual([]);+ expect(request.inputs?.videos).toEqual([]);+ expect(request.params?.elements).toBeUndefined();+ });+ });+});diff --git a/tests/cinema-models.test.ts b/tests/cinema-models.test.tsindex a33acd59..b92e3ccc 100644--- a/tests/cinema-models.test.ts+++ b/tests/cinema-models.test.ts@@ -13,7 +13,7 @@ const refs = Array.from({ length: 6 }, (_, i) => `/api/files/uploads/r${i}.png`)describe("Cinema Studio's models", () => {it("video: Fuobe Cinema, then MiniMax H3, on both engines; the cloud adds H3 Max", () => {expect(CINEMA_MODELS.video.open).toEqual(["fuobe-cinema", "oss-minimax-h3", "oss-ltx25", "oss-wan22-14b"]);- expect(CINEMA_MODELS.video.cloud).toEqual(["fuobe-cinema", "minimax-h3", "seedance-2-5", "kling-3", "veo-3-1", "minimax-h3-max"]);+ expect(CINEMA_MODELS.video.cloud).toEqual(["fuobe-cinema", "minimax-h3", "seedance-2-5", "kling-4", "kling-3", "veo-3-1", "minimax-h3-max"]);for (const engine of ["open", "cloud"] as const) for (const id of CINEMA_MODELS.video[engine]) expect(getModel(id), id).toBeTruthy();// The default stays Fuobe Cinema.expect(planCinema(input({}), ctx).model.id).toBe("fuobe-cinema");diff --git a/tests/genjutsu.test.ts b/tests/genjutsu.test.tsindex 8cf14c75..bc013a0b 100644--- a/tests/genjutsu.test.ts+++ b/tests/genjutsu.test.ts@@ -75,7 +75,8 @@ describe("Genjutsu: which model runs", () => {const sources = (engine: Engine, mode: "motion" | "character" | "swap" | "restyle" | "insert", target?: "type" | "click" | "paint") =>Object.fromEntries(makersFor(engine, mode, target).map((m) => [m.id, m.source]));expect(sources("cloud", "character")).toEqual({ [ORIGINALS.character]: "original", "scail-2": "open", "h3-max-recast": "partner", "wan-22-animate-replace": "open", "kling-o3": "partner", "p-video-replace": "partner" });- expect(sources("cloud", "swap", "type")).toEqual({ [ORIGINALS.swapLite]: "original", "kling-o3": "partner", "p-video-replace": "partner" });+ expect(sources("cloud", "swap", "type")).toEqual({ [ORIGINALS.swapLite]: "original", "kling-o3": "partner", "kling-4": "partner", "p-video-replace": "partner" });+ expect(sources("cloud", "insert", "type")).toMatchObject({ "kling-o3": "partner", "kling-4": "partner" });expect(sources("cloud", "swap", "paint")).toEqual({ [ORIGINALS.swapLite]: "original", "wan-22-vace-inpaint": "open" });expect(sources("cloud", "restyle")).toEqual({ [ORIGINALS.restyle]: "original", "gemini-omni-flash": "partner", "kling-o3-4k-edit": "partner", "happy-horse-video-edit": "partner" });expect(sources("open", "character", "type")).toEqual({ [ORIGINALS.character]: "original", "oss-h3-character-swap-relay": "open" });diff --git a/tests/kling-4.test.ts b/tests/kling-4.test.tsnew file mode 100644index 00000000..31391fdd--- /dev/null+++ b/tests/kling-4.test.ts@@ -0,0 +1,334 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";++/**+ * Kling 4.0 in the cloud (build package nm10-kling-4): fal's four kling/v4 endpoints (API open since round 4 held them+ * back) and Replicate's kwaivgi/kling-v4.0 for text and frames. Payloads are checked against the stored schemas+ * (docs/research/paid-model-apis-4.json, re-read 2026-11-01). No paid call is made: demo mode and pure functions only.+ */++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kling-4-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const { getModel, getPreset, MODELS, modelsFor } = await import("@/lib/catalog");+const { buildPayload } = await import("@/lib/catalog/payload");+const { clipBilling, estimateCost, planGeneration, routesFor } = await import("@/lib/catalog/plan");+const { applyMentions, elementsNote } = await import("@/lib/catalog/elements");+const { planCinema } = await import("@/lib/catalog/cinema");+const { clipSizeProblem, clipTotalProblem, clipWindowProblem } = await import("@/lib/catalog/clip-windows");+const { frameSupport } = await import("@/lib/catalog/keyframes");+const { genjutsuProblem, getMaker, makerPrompt } = await import("@/lib/catalog/genjutsu");+const { studioBest, clipBlocker, clipOutcome } = await import("@/lib/composer");+const { pickerPrice } = await import("@/lib/model-rows");+const { VIDEO_STUDIO } = await import("@/lib/studios");+const { modelLicence, isOffered } = await import("@/server/model-access");+const { mockProvider } = await import("@/server/providers/mock");+type Req = import("@/lib/catalog/types").GenerationRequest;+type Route = import("@/lib/catalog/types").ModelRoute;+type StudioElement = import("@/lib/catalog/elements").StudioElement;++type Spec = { type?: string; values?: unknown[]; maxItems?: number; minimum?: number; maximum?: number; required?: boolean; itemSchema?: Record<string, Spec> };+type Endpoint = { provider: string; endpoint: string; status: string; checked?: string; inputs: Record<string, Spec>; keyFields: Record<string, string> };+const research = (JSON.parse(fs.readFileSync("docs/research/paid-model-apis-4.json", "utf8")) as { endpoints: Endpoint[] }).endpoints;+const schemaOf = (r: Route) => research.find((e) => e.provider === r.provider && e.endpoint === r.endpoint)!;++const kling = getModel("kling-4")!;+const route = (op: string, provider = "fal") => kling.routes.find((r) => r.op === op && r.provider === provider)!;++/** Every field the payload sends is one the stored schema has, with a value its enum and limits allow. */+function checkAgainstSchema(r: Route, payload: Record<string, unknown>) {+ const { inputs } = schemaOf(r);+ for (const [k, v] of Object.entries(payload)) {+ const spec = inputs[k];+ expect(spec, `${r.endpoint} has no ${k}`).toBeDefined();+ if (spec.values) expect(spec.values, `${r.endpoint} ${k}`).toContain(v);+ if (spec.type === "integer") expect(Number.isInteger(v), `${k} is whole`).toBe(true);+ if (typeof v === "number" && spec.minimum !== undefined) expect(v).toBeGreaterThanOrEqual(spec.minimum);+ if (typeof v === "number" && spec.maximum !== undefined) expect(v).toBeLessThanOrEqual(spec.maximum);+ if (Array.isArray(v) && spec.maxItems !== undefined) expect(v.length, `${k} items`).toBeLessThanOrEqual(spec.maxItems);+ if (Array.isArray(v) && spec.itemSchema) for (const item of v as Record<string, unknown>[]) for (const f of Object.keys(item)) expect(spec.itemSchema[f], `${k}.${f}`).toBeDefined();+ }+ for (const [k, spec] of Object.entries(inputs)) if (spec.required) expect(payload[k], `${r.endpoint} requires ${k}`).toBeDefined();+}++/** Plan a request as the server does and build the payload its route sends. */+function payloadFor(req: Partial<Req>, provider = "fal") {+ const plan = planGeneration({ feature: "video", modelId: "kling-4", prompt: "A lighthouse keeper climbs the stairs", ...req } as Req, getModel, getPreset);+ const r = routesFor(plan.model, plan.op).find((x) => x.provider === provider)!;+ const payload = buildPayload(r.map!, { ...plan.params, prompt: plan.prompt, images: plan.request?.inputs?.images ?? req.inputs?.images, endImage: req.inputs?.endImage, video: req.inputs?.video, videos: req.inputs?.videos } as never);+ return { plan, route: r, payload };+}++const el = (over: Partial<StudioElement>): StudioElement => ({+ id: over.handle ?? "x",+ name: over.handle ?? "x",+ handle: "x",+ kind: "character",+ description: null,+ references: [],+ loras: [],+ status: "ready",+ createdAt: 0,+ ...over,+});++describe("research: Kling 4.0's API is open", () => {+ it("records all four fal endpoints as active on 2026-11-01, and Replicate's model", () => {+ for (const ep of ["text-to-video", "image-to-video", "reference-to-video", "video-to-video/edit"]) {+ const e = research.find((x) => x.endpoint === `kling/v4/${ep}`)!;+ expect(e.status, ep).toBe("active");+ expect(e.checked, ep).toBe("2026-11-01");+ }+ const rep = research.find((x) => x.endpoint === "kwaivgi/kling-v4.0" && x.provider === "replicate")!;+ expect(rep.status).toBe("active");+ for (const f of Object.values(rep.keyFields)) expect(rep.inputs[f], f).toBeDefined();+ // The edit's reference clips came after round 4.+ expect(research.find((x) => x.endpoint === "kling/v4/video-to-video/edit")!.inputs.video_urls.maxItems).toBe(4);+ });+});++describe("catalog", () => {+ it("is a closed cloud model with text, frames, references, edits and Genjutsu's swap and insert", () => {+ expect(kling.engine).toBe("cloud");+ expect(kling.badges).toEqual(expect.arrayContaining(["top", "30s"]));+ expect([...new Set(kling.routes.map((r) => r.op))].sort()).toEqual(["extend", "flf2v", "i2v", "ref2v", "t2v", "v2v", "video-insert", "video-swap"]);+ // Extend Video continues a take from its last frame with Kling's own image-to-video (the Kling family's chain).+ expect(kling.routes.find((r) => r.op === "extend")?.note).toMatch(/last frame/);+ expect(kling.routes.filter((r) => r.provider === "replicate").map((r) => r.op).sort()).toEqual(["flf2v", "i2v", "t2v"]);+ expect(kling.defaults).toMatchObject({ resolution: "1080p", duration: 5 });+ expect(kling.options.durations).toEqual(expect.arrayContaining([3, 5, 10, 15, 20, 30]));+ expect(kling.options.aspectRatios).toEqual(expect.arrayContaining(["16:9", "9:16", "1:1", "21:9"]));+ expect(kling.options.elements).toMatchObject({ max: 7, views: 3, videos: 3, voices: false });+ });++ it("is in the Video studio's Best list next to Seedance 2.5, on the cloud only", () => {+ const best = studioBest(MODELS, "cloud", VIDEO_STUDIO.defaultModels.cloud, VIDEO_STUDIO.ops);+ expect(best.indexOf("kling-4")).toBe(best.indexOf("seedance-2-5") + 1);+ // "Open source only" lists open models: Kling 4.0 isn't one of them.+ expect(modelsFor({ kind: "video", ops: ["t2v"], engine: "open" }).map((m) => m.id)).not.toContain("kling-4");+ expect(modelsFor({ kind: "video", ops: ["v2v"], engine: "cloud" }).map((m) => m.id)).toContain("kling-4");+ });++ it("is a paid API in Settings → Models & licences, switched on", () => {+ const l = modelLicence(kling);+ expect(l.licence.class).toBe("paid-api");+ expect(l.licence.name).toMatch(/fal/);+ expect(l.licence.name).toMatch(/Replicate/);+ expect(l.licence.note).toMatch(/Kuaishou/);+ expect(isOffered("kling-4", "cloud")).toBe(true);+ });++ it("takes Frames mode's first and last frame only (Frames stays on FLUX 3 Max)", () => {+ expect(frameSupport(kling)).toBe("ends");+ });+});++describe("payloads against the stored schemas", () => {+ it("text to video: 1080p by default, 21:9, whole seconds", () => {+ const { route: r, payload } = payloadFor({ params: { aspectRatio: "21:9", duration: 12 } });+ expect(r.endpoint).toBe("kling/v4/text-to-video");+ expect(payload).toMatchObject({ prompt: expect.any(String), aspect_ratio: "21:9", duration: 12, resolution: "1080p" });+ checkAgainstSchema(r, payload);+ });++ it("shots go as multi_prompt, the take as long as their sum (one 30 s call)", () => {+ const shots = [+ { prompt: "Wide: the storm rolls in", duration: 10 },+ { prompt: "Close: her hands on the rail", duration: 8 },+ { prompt: "A".repeat(700), duration: 12 },+ ];+ const { plan, route: r, payload } = payloadFor({ params: { shots } });+ expect(plan.params.duration).toBe(30);+ const sent = payload.multi_prompt as { prompt: string; duration: number }[];+ expect(sent.map((s) => s.duration)).toEqual([10, 8, 12]);+ expect(sent.reduce((n, s) => n + s.duration, 0)).toBe(payload.duration);+ expect(payload.prompt).toBeUndefined();+ // Each shot's prompt within the 512 characters the API takes.+ expect(Math.max(...sent.map((s) => s.prompt.length))).toBeLessThanOrEqual(512);+ checkAgainstSchema(r, payload);+ });++ it("start and end frames", () => {+ const { route: r, payload } = payloadFor({ op: "flf2v", inputs: { images: ["https://x/start.png"], endImage: "https://x/end.png" } });+ expect(r.endpoint).toBe("kling/v4/image-to-video");+ expect(payload).toMatchObject({ start_image_url: "https://x/start.png", end_image_url: "https://x/end.png" });+ checkAgainstSchema(r, payload);+ // Replicate takes the same run (a second provider), with its own names.+ const rep = payloadFor({ op: "flf2v", inputs: { images: ["https://x/start.png"], endImage: "https://x/end.png" } }, "replicate");+ expect(rep.payload).toMatchObject({ start_image: "https://x/start.png", end_image: "https://x/end.png", resolution: "1080p" });+ expect(rep.payload.reference_images).toBeUndefined();+ checkAgainstSchema(rep.route, rep.payload);+ });++ it("references: images and clips, never the first reference as a start frame", () => {+ const { route: r, payload } = payloadFor({ op: "ref2v", inputs: { images: ["https://x/a.png", "https://x/b.png"], videos: ["https://x/c.mp4"] } });+ expect(r.endpoint).toBe("kling/v4/reference-to-video");+ expect(payload).toMatchObject({ image_urls: ["https://x/a.png", "https://x/b.png"], video_urls: ["https://x/c.mp4"] });+ expect(payload.start_image_url).toBeUndefined();+ checkAgainstSchema(r, payload);+ });++ it("an edit: the clip as @Video1, 4 reference clips, its own length (no duration sent)", () => {+ const videos = ["https://x/r1.mp4", "https://x/r2.mp4", "https://x/r3.mp4", "https://x/r4.mp4"];+ const { route: r, payload } = payloadFor({ feature: "video-edit", op: "v2v", prompt: "Make it snow", inputs: { video: "https://x/src.mp4", videos } });+ expect(r.endpoint).toBe("kling/v4/video-to-video/edit");+ expect(payload).toMatchObject({ prompt: "Make it snow", video_url: "https://x/src.mp4", video_urls: videos, resolution: "1080p" });+ expect(payload.duration).toBeUndefined();+ checkAgainstSchema(r, payload);+ });++ it("7 elements: a frontal photo and up to 3 angles each, or a clip, out of the image and clip lists", () => {+ const r = route("ref2v");+ const images = Array.from({ length: 16 }, (_, i) => `https://x/i${i}.png`);+ const groups = [{ images: [0, 1, 2, 3, 4] }, { images: [5] }, { video: 1 }, { images: [6, 7] }, { images: [8] }, { images: [9] }, { images: [10] }, { images: [11] }];+ const payload = buildPayload(r.map!, { prompt: "@Element1 meets @Element2", images, videos: ["https://x/ref.mp4", "https://x/el.mp4"], elements: groups });+ const list = payload.elements as Record<string, unknown>[];+ expect(list).toHaveLength(7);+ expect(list[0]).toEqual({ frontal_image_url: images[0], reference_image_urls: [images[1], images[2], images[3]] });+ expect(list[1]).toEqual({ frontal_image_url: images[5] });+ expect(list[2]).toEqual({ video_url: "https://x/el.mp4" });+ // The images and clip the elements took leave their lists; the rest keep their order (@Image1.., @Video1..).+ // The eighth group is past the 7 the API takes: its photo stays a reference image.+ expect(payload.image_urls).toEqual([images[4], ...images.slice(11)]);+ expect(payload.video_urls).toEqual(["https://x/ref.mp4"]);+ checkAgainstSchema(r, payload);+ });+});++describe("@mentions become Kling elements", () => {+ const maya = el({ id: "m", name: "Maya", handle: "Maya", kind: "character", references: ["/api/files/m1.png", "/api/files/m2.png", "/api/files/m3.png"] });+ const cup = el({ id: "c", name: "Cup", handle: "Cup", kind: "prop", references: ["/api/files/cup.mp4"] });+ const bay = el({ id: "b", name: "Bay", handle: "Bay", kind: "location", references: ["/api/files/bay.png"] });++ it("characters and props as @Element1.. (a clip as a video element), locations as reference images", () => {+ const req = { feature: "video", modelId: "kling-4", prompt: "@Maya drinks from @Cup on @Bay", params: {} } as Req;+ const { request, notes } = applyMentions(req, kling, [maya, cup, bay]);+ expect(request.op).toBe("ref2v");+ expect(request.prompt).toMatch(/^@Element1 drinks from @Element2 on Bay/);+ expect(request.prompt).toMatch(/Bay is the location in image 1/);+ expect(request.inputs?.images).toEqual(["/api/files/bay.png", ...maya.references]);+ expect(request.inputs?.videos).toEqual(["/api/files/cup.mp4"]);+ expect(request.params?.elements).toEqual([{ images: [1, 2, 3] }, { video: 0 }]);+ expect(notes).toEqual([]);+ const payload = buildPayload(route("ref2v").map!, { prompt: request.prompt, images: request.inputs!.images, videos: request.inputs!.videos, elements: request.params!.elements });+ expect(payload.image_urls).toEqual(["/api/files/bay.png"]);+ expect(payload.elements).toEqual([{ frontal_image_url: maya.references[0], reference_image_urls: maya.references.slice(1) }, { video_url: "/api/files/cup.mp4" }]);+ });++ it("in an edit, the mention goes as an element of the edit", () => {+ const req = { feature: "video-edit", modelId: "kling-4", op: "v2v", prompt: "Replace the man with @Maya", inputs: { video: "/api/files/src.mp4" } } as Req;+ const { request } = applyMentions(req, kling, [maya]);+ expect(request.op).toBe("v2v");+ expect(request.prompt).toBe("Replace the man with @Element1");+ expect(request.params?.elements).toEqual([{ images: [0, 1, 2] }]);+ });++ it("says voices aren't sent yet", () => {+ expect(elementsNote(kling)).toMatch(/voices: not yet/);+ expect(elementsNote(getModel("kling-3"))).toBeUndefined();+ });+});++describe("price", () => {+ it("text and frames: per output second by resolution (5 s at 720p = $0.785)", () => {+ expect(estimateCost(kling, { duration: 5, resolution: "720p" }, 1, "t2v")).toBe(0.785);+ expect(estimateCost(kling, { duration: 5 }, 1, "t2v")).toBe(1.175);+ });++ it("an edit bills max(input + output, 2x output) seconds at the clip rate", () => {+ // A 10 s clip at 1080p: 10 in + 10 out = 20 billed at $0.141.+ expect(clipBilling(kling, { sourceDuration: 10 }, "v2v")).toMatchObject({ input: 10, output: 10, billed: 20, rate: 0.141 });+ expect(estimateCost(kling, { sourceDuration: 10 }, 1, "v2v")).toBe(2.82);+ expect(estimateCost(kling, { sourceDuration: 10, resolution: "720p" }, 1, "video-swap")).toBe(1.88);+ });++ it("reference clips: input plus output, at least twice the output; their length unknown until read", () => {+ // 4 s of clips with a 10 s take: 14 < 20, so twice the output.+ expect(estimateCost(kling, { duration: 10, resolution: "720p", clipSeconds: 4 }, 1, "ref2v")).toBe(1.88);+ // 15 s of clips: 25 s billed.+ expect(estimateCost(kling, { duration: 10, resolution: "720p", clipSeconds: 15 }, 1, "ref2v")).toBe(2.35);+ // Reference images alone are the plain rate.+ expect(estimateCost(kling, { duration: 10, resolution: "720p" }, 1, "ref2v")).toBe(1.57);+ // The planner marks a run with clips, so its estimate is never the plain rate.+ const plan = planGeneration({ feature: "video", modelId: "kling-4", op: "ref2v", prompt: "x", inputs: { videos: ["/api/files/r.mp4"] }, params: { duration: 10, resolution: "720p" } } as Req, getModel, getPreset);+ expect(plan.params.clipSeconds).toBe(0);+ expect(estimateCost(plan.model, plan.params, 1, plan.op)).toBe(1.88);+ });++ it("Edit video shows the edit's rate in the picker and what's billed before the total", () => {+ expect(pickerPrice(kling, 0)).toBe("$0.235/sec");+ expect(pickerPrice(kling, 0, true)).toBe("$0.141/sec in+out");+ expect(clipOutcome("v2v", { duration: 10, width: 1920, height: 1080 }, {}, kling)).toBe("10 s in + 10 s out: billed on 20 s at $0.141/s");+ });+});++describe("limits checked before a paid call", () => {+ it("a clip edit takes 3–30 s, 700–4553 px a side, 30 s of clips in all", () => {+ expect(clipWindowProblem(kling, 31)).toMatch(/3–30 s/);+ expect(clipWindowProblem(kling, 30.03)).toBeNull();+ expect(clipSizeProblem(kling, 640, 360)).toMatch(/700 px/);+ expect(clipSizeProblem(kling, 1920, 1080)).toBeNull();+ expect(clipBlocker("v2v", { duration: 12, width: 640, height: 360 }, {}, kling, undefined)).toMatch(/700 px/);+ expect(clipTotalProblem(kling, 34)).toMatch(/30 s of clips in all/);+ expect(clipTotalProblem(kling, 30)).toBeNull();+ });+});++describe("Cinema Studio", () => {+ const SETTINGS = {} as Parameters<typeof planCinema>[0]["settings"];+ it("a 30 s multi-shot take is one Kling 4.0 call, with no extend", () => {+ const shots = [+ { prompt: "The keeper lights the lamp", duration: 12 },+ { prompt: "The beam sweeps the bay", duration: 10 },+ { prompt: "A ship turns toward the light", duration: 8 },+ ];+ const plan = planCinema(+ { engine: "cloud", mode: "video", action: "generate", modelId: "kling-4", prompt: "A storm at night", settings: SETTINGS, duration: 30, batch: 1, multiShot: { mode: "manual", shots } },+ { cloudAllowed: true },+ );+ expect(plan.model.id).toBe("kling-4");+ expect(plan.steps).toHaveLength(1);+ const req = plan.steps[0].request;+ expect(req.params?.shots?.map((s) => s.duration)).toEqual([12, 10, 8]);+ const planned = planGeneration(req, getModel, getPreset);+ expect(planned.params.duration).toBe(30);+ const r = routesFor(planned.model, planned.op).find((x) => x.provider === "fal")!;+ const payload = buildPayload(r.map!, { ...planned.params, prompt: planned.prompt });+ expect((payload.multi_prompt as unknown[]).length).toBe(3);+ expect(payload.duration).toBe(30);+ expect(plan.costUsd).toBeCloseTo(30 * 0.235, 3);+ });++ it("any whole second from 3 to 30 for a single take", () => {+ const plan = planCinema({ engine: "cloud", mode: "video", action: "generate", modelId: "kling-4", prompt: "x", settings: SETTINGS, duration: 25, batch: 1 }, { cloudAllowed: true });+ expect(plan.steps[0].request.params?.duration).toBe(25);+ expect(plan.notes.join(" ")).not.toMatch(/makes \d+s clips/);+ });+});++describe("Genjutsu", () => {+ it("offers Kling 4.0's edit for Object swap and Insert, with @Video1 and @Image tags and its own limits", () => {+ const m = getMaker("kling-4", "cloud")!;+ expect(m.modes).toEqual(["swap", "insert"]);+ expect(makerPrompt({ mode: "swap", maker: m, subject: "the red car", refs: 2 })).toMatch(/^Replace the red car in @Video1 with @Image1, @Image2/);+ expect(makerPrompt({ mode: "insert", maker: m, refs: 1, prompt: "on the table" })).toMatch(/^Add @Image1 to @Video1: on the table/);+ const check = { mode: "swap" as const, maker: m, references: 1, subject: "the car", target: "type" as const, range: { start: 0, end: 10 } };+ expect(genjutsuProblem({ ...check, source: { url: "/api/files/s.mp4", duration: 10, width: 640, height: 360 } } as never)).toMatch(/700 px/);+ expect(genjutsuProblem({ ...check, source: { url: "/api/files/s.mp4", duration: 10, width: 1920, height: 1080 } } as never)).toBeNull();+ });+});++describe("demo mode", () => {+ it("the mock provider makes a placeholder clip for every route, with no key", async () => {+ for (const r of kling.routes) {+ const sub = await mockProvider.submit({ generationId: "g", model: kling, route: r, input: { prompt: "x", images: ["a.png"], video: "v.mp4", duration: 5 } });+ const res = await mockProvider.poll({ externalId: sub.externalId, meta: { ...sub.meta, startedAt: 0 }, route: r, model: kling, createdAt: 0 });+ if (res.state !== "succeeded") throw new Error(`${r.op}: ${res.state}`);+ expect(res.outputs[0].kind, r.op).toBe("video");+ }+ });+});