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
Originals O13: Fuobe Evolution on both engines, the change intensity as denoise and video_strength, the direction written from the references
Claudecc2eca401ada
diff --git a/docs/research/fuobe-originals-recipes-5.json b/docs/research/fuobe-originals-recipes-5.jsonindex 944be8bb..cbf6ed54 100644--- a/docs/research/fuobe-originals-recipes-5.json+++ b/docs/research/fuobe-originals-recipes-5.json@@ -17768,6 +17768,62 @@],"licence": "Wan Animate 2 / Wan VACE / Fun VACE Apache-2.0; SCAIL-2 MIT; SAM 3.1 Meta SAM License (commercial use allowed)"},+ {+ "id": "evolution",+ "higgsfield": "Higgsfield Evolution (hf_evolution, a gated test model): one video plus up to 40 reference images or elements, change_intensity low / medium / high, an optional creative direction of up to 10,000 characters, 480p / 720p / 1080p. What runs underneath is speculative (7 credits a second at 720p, Seedance 2.5's price): see higgsfield-originals-5.md §3.20.",+ "open": "Fuobe video-evolution-wan22-fun-vace: per ≤81-frame segment at 16 fps, the segment's first frame is taken toward the creative direction by Qwen-Image-Edit 2511 (images 2–3 = the first references), then Wan 2.2 Fun VACE re-renders the segment starting from the segment itself, noised to the intensity's denoise, with depth control and the direction frame as the VACE reference",+ "hosted": [+ "fal-ai/ltx-2.3-22b/video-to-video (video_strength = 1 − denoise; $0.001605 per megapixel of video)",+ "fal-ai/ltx-2.3-22b/video-to-video/lora when a LoRA rides along ($0.001805 per megapixel of video)"+ ],+ "licence": "Wan 2.2 Fun VACE, lightx2v, Qwen-Image-Edit 2511 Apache-2.0; LTX-2.x Community License (free under US$10M annual revenue)",+ "original": {+ "model": "fuobe-evolution",+ "added": "2026-10-29 (build plan O13)",+ "source": "Fuobe's own recipe for Higgsfield Evolution's Original, from build plan O13 (denoise by intensity, an LLM-written direction) and the LTX-2.3 22B video-to-video schema read on 2026-10-24 (§3.1). Unmeasured until the evaluation harness (O8) runs the evolution suite on a GPU and on fal.",+ "intensity": {+ "low": 0.45,+ "medium": 0.65,+ "high": 0.85+ },+ "limits": {+ "minSeconds": 4,+ "maxSeconds": 30,+ "maxReferences": 40,+ "maxDirectionChars": 10000+ },+ "direction": "An LLM writes the creative direction from the references (images sent to a model that can see them: Claude, or Ollama with a vision model on the open engine) and the user's few words, as a description of the finished video's scene (the LTX endpoint renders a scene, not an instruction); with no LLM, or in demo mode, Fuobe's offline writer builds it from the intensity, the words and the number of references. The user can edit it before the run; a run with none writes one first.",+ "cloud": {+ "endpoint": "fal-ai/ltx-2.3-22b/video-to-video",+ "loraEndpoint": "fal-ai/ltx-2.3-22b/video-to-video/lora",+ "strengthField": "video_strength",+ "strength": "1 − denoise: low 0.55, medium 0.35, high 0.15 (the field's description: lower values give the model more freedom to change the video; fal's default 0.01 all but re-renders it)",+ "fixed": {+ "enable_prompt_expansion": false,+ "generate_audio": false,+ "match_video_length": false,+ "match_input_fps": false,+ "fps": 24+ },+ "fps": 24,+ "maxFrames": 481,+ "pieces": "a clip over 20 s (481 frames at 24 fps) is cut into equal pieces of at most 20 s, each evolved on its own and joined",+ "sizes": "the tier's size for the clip's nearest shape, from Fuobe Cinema's table (studios[cinema-studio].original.cloud.sizes)",+ "sound": "generate_audio off; the clip's own sound is put back on the joined result (merge-audio-video)",+ "references": "the endpoint takes no images: references shape the direction only (unverified whether fal-ai/ltx-2.3-22b/reference-video-to-video/lora's IC-LoRA could carry one)"+ },+ "open": {+ "segments": "≤81 frames (4n+1) at 16 fps, back to back (video-segment-resample), 480p or 720p",+ "directionFrame": "qwen-image-edit-2511 on the segment's first frame with the direction, up to 2 references as images 2–3",+ "video": "video-evolution-wan22-fun-vace: reference latent + VAE-encoded segment, noised to the intensity's denoise the way KSampler does it (a schedule of floor(4 / denoise) steps, the last 4 run, Lightx2v 4-step), the high-noise expert for the first half; Depth Anything 3 depth on every frame",+ "join": "video-concat-N, then the clip's own sound (video-mux-audio)"+ },+ "unverified": [+ "nothing rendered: the denoise values, LTX-2.3's video_strength at these values, and whether fal resamples a 30 fps input to the fixed 24 fps",+ "the high-noise expert at low denoise (Wan 2.2's experts split by noise level; at 0.45 the first steps start below the usual switch point)"+ ]+ }+ },{"id": "mixed-media","higgsfield": "Mixed Media: 33 per-frame stylisation presets on a source video",@@ -17950,7 +18006,13 @@"fal-ai/qwen-image-edit-plus-lora-gallery/next-scene ($0.035/MP)","fal-ai/qwen-image-edit-2511/lora with a next-scene LoRA"],- "licence": "Apache-2.0"+ "licence": "Apache-2.0",+ "original": {+ "added": "2026-10-29 (build plan O13)",+ "looks": "a board can take one of Fuobe Soul's 139 looks: frame 1 is made on Fuobe Soul with the look (its LoRAs, words and grade) on either engine, the next frames continue from it with the look's words, and every frame gets the look's grade and overlay after it is made (the browser's Soul finish); each next frame is made from the previous frame as it came out, before its finish, so the grade is applied once",+ "references": "with references, frame 1 stays on the reference model (Nano Banana Pro in the cloud, Qwen-Image-Edit on the GPU) with the look's words, and the look's grade",+ "next": "unchanged: Nano Banana Pro edits in the cloud, Qwen-Image-Edit 2509 + next-scene LoRA on the GPU; the hosted next-scene route (fal-ai/qwen-image-edit-plus-lora-gallery/next-scene) is not schema-read yet"+ }},{"id": "marketing",diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.pyindex 627cc805..0307ef8c 100644--- a/scripts/gen-cloud-models.py+++ b/scripts/gen-cloud-models.py@@ -602,6 +602,25 @@ model("fuobe-character-swap", "Fuobe Character swap", "Fuobe Original", "fuobe-coriginal=True, fit_values=True, badges=["audio"],pricing=("second", 0.075, "768p; 480p $0.0625/s; whole seconds, 5–15 per call", {"byResolution": {"768p": 0.075, "480p": 0.0625}}),options={"resolutions": ["480p", "768p"]}, defaults={"resolution": "768p"})+# ----- Originals (O13): Fuobe Evolution's cloud half (research §8 evolution → studios[evolution].original): Higgsfield+# Evolution's change intensity as LTX-2.3 22B video-to-video's video_strength (1 − the denoise the open graph uses; set by+# src/lib/catalog/evolution.ts through params.extra), the LLM-written direction as the prompt, prompt expansion off. Silent+# (the clip's own sound goes back on), 24 fps, at most 481 frames a call (Evolution cuts longer clips into pieces); the+# tier's size for the clip's shape from Fuobe Cinema's table. Priced per megapixel of video like Fuobe Cinema.+EVOLUTION = next(s for s in ORIGINALS["studios"] if s["id"] == "evolution")["original"]["cloud"]+EVOLUTION_MP = per_megapixel(EVOLUTION["endpoint"])+EVOLUTION_MP_LORA = per_megapixel(EVOLUTION["loraEndpoint"])+EVOLUTION_PER_SECOND = {t: round(s["16:9"][0] * s["16:9"][1] * EVOLUTION["fps"] / 1e6 * EVOLUTION_MP, 4) for t, s in CINEMA_SIZES.items()}+EVOLUTION_PER_SECOND_LORA = {t: round(s["16:9"][0] * s["16:9"][1] * EVOLUTION["fps"] / 1e6 * EVOLUTION_MP_LORA, 4) for t, s in CINEMA_SIZES.items()}+model("fuobe-evolution", "Fuobe Evolution", "Fuobe Original", "fuobe-evolution", "video",+ "Takes your clip further in a direction an LLM writes from your references: LTX-2.3 video to video at a change intensity",+ [("v2v", EVOLUTION["endpoint"], "fal", {"loraEndpoint": EVOLUTION["loraEndpoint"], "fixed": EVOLUTION["fixed"]})],+ original=True, sizes=CINEMA_SIZES,+ pricing=("second", EVOLUTION_PER_SECOND["720p"],+ f"${EVOLUTION_MP} per megapixel of video (width × height × frames): about ${round(EVOLUTION_PER_SECOND['720p'] * 5, 2)} for 5 s at 720p; ${EVOLUTION_MP_LORA} with LoRAs",+ {"byResolution": EVOLUTION_PER_SECOND, "withLoras": EVOLUTION_PER_SECOND_LORA["720p"], "withLorasByResolution": EVOLUTION_PER_SECOND_LORA,+ "videoMegapixel": {"usd": EVOLUTION_MP, "withLoras": EVOLUTION_MP_LORA}}),+ defaults={"aspectRatio": "16:9", "duration": 5, "resolution": "720p"}, frame_step=8)model("ltx-2-5", "LTX 2.5 Pro", "Lightricks", "ltx", "video", "Fast 4K-capable video with audio",[("t2v", "lightricks/ltx-2.5/text-to-video/pro"), ("i2v", "lightricks/ltx-2.5/image-to-video/pro")],badges=["audio"], defaults={"aspectRatio": "16:9"})diff --git a/src/app/api/evolution/direction/route.ts b/src/app/api/evolution/direction/route.tsnew file mode 100644index 00000000..72ad5c17--- /dev/null+++ b/src/app/api/evolution/direction/route.ts@@ -0,0 +1,10 @@+import { DirectionSchema, writeDirection } from "@/server/evolution";+import { body, handle } from "@/server/shorts-schemas";++/** Write the creative direction from the references and your words: Claude, Ollama, or Fuobe's offline writer. Never generates. */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, DirectionSchema, "Pick how much should change, then add references or a few words");+ return Response.json(await writeDirection(input));+ });+}diff --git a/src/app/api/evolution/estimate/route.ts b/src/app/api/evolution/estimate/route.tsnew file mode 100644index 00000000..2dabbcb7--- /dev/null+++ b/src/app/api/evolution/estimate/route.ts@@ -0,0 +1,10 @@+import { estimateEvolution, EvolutionEstimateSchema } from "@/server/evolution";+import { body, handle } from "@/server/shorts-schemas";++/** The price, the pieces and the notes for the current settings, before anything runs ("Free" on your GPU). */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, EvolutionEstimateSchema, "Add a clip and pick how much should change");+ return Response.json(estimateEvolution(input));+ });+}diff --git a/src/app/api/evolution/route.ts b/src/app/api/evolution/route.tsnew file mode 100644index 00000000..b6911fbe--- /dev/null+++ b/src/app/api/evolution/route.ts@@ -0,0 +1,12 @@+import { createEvolution, EvolutionBodySchema } from "@/server/evolution";+import { body, handle, once } from "@/server/shorts-schemas";++/** Evolve a clip (Fuobe Evolution): the direction is written first when none is given; pieces are joined and the sound put back. */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, EvolutionBodySchema, "Add a clip and pick how much should change");+ // A repeated requestId (a second click on Evolve) gets the run the first one started.+ const result = await once("evolution", input.requestId, () => createEvolution(input));+ return Response.json(result, { status: 201 });+ });+}diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.tsindex a083abef..334b82d8 100644--- a/src/lib/catalog/cloud-models.generated.ts+++ b/src/lib/catalog/cloud-models.generated.ts@@ -19093,5 +19093,198 @@ export const ORIGINAL_CLOUD: ModelDef[] = ["480p": 0.0625}}+ },+ {+ "id": "fuobe-evolution",+ "name": "Fuobe Evolution",+ "vendor": "Fuobe Original",+ "family": "fuobe-evolution",+ "engine": "cloud",+ "kind": "video",+ "tagline": "Takes your clip further in a direction an LLM writes from your references: LTX-2.3 video to video at a change intensity",+ "routes": [+ {+ "op": "v2v",+ "provider": "fal",+ "endpoint": "fal-ai/ltx-2.3-22b/video-to-video",+ "map": {+ "negativePrompt": "negative_prompt",+ "video": "video_url",+ "seed": "seed",+ "generateAudio": "generate_audio",+ "fps": "fps",+ "numFrames": {+ "key": "num_frames",+ "fps": 24,+ "min": 9,+ "max": 481,+ "step": 8+ },+ "size": {+ "key": "video_size",+ "multiple": 16,+ "table": {+ "480p": {+ "21:9": [+ 1120,+ 480+ ],+ "16:9": [+ 864,+ 480+ ],+ "4:3": [+ 640,+ 480+ ],+ "1:1": [+ 480,+ 480+ ],+ "3:4": [+ 480,+ 640+ ],+ "9:16": [+ 480,+ 864+ ]+ },+ "720p": {+ "21:9": [+ 1504,+ 640+ ],+ "16:9": [+ 1280,+ 704+ ],+ "4:3": [+ 1024,+ 768+ ],+ "1:1": [+ 960,+ 960+ ],+ "3:4": [+ 768,+ 1024+ ],+ "9:16": [+ 704,+ 1280+ ]+ },+ "1080p": {+ "21:9": [+ 2240,+ 960+ ],+ "16:9": [+ 1920,+ 1088+ ],+ "4:3": [+ 1440,+ 1088+ ],+ "1:1": [+ 1088,+ 1088+ ],+ "3:4": [+ 1088,+ 1440+ ],+ "9:16": [+ 1088,+ 1920+ ]+ }+ }+ },+ "fixed": {+ "enable_prompt_expansion": false,+ "generate_audio": false,+ "match_video_length": false,+ "match_input_fps": false,+ "fps": 24+ },+ "loras": {+ "shape": "items",+ "key": "loras",+ "required": true,+ "range": {+ "min": 0,+ "max": 4+ },+ "weightName": true+ }+ },+ "loraEndpoint": "fal-ai/ltx-2.3-22b/video-to-video/lora"+ }+ ],+ "options": {+ "durations": [+ 3,+ 4,+ 5,+ 6,+ 8,+ 10,+ 12,+ 15,+ 20+ ],+ "aspectRatios": [+ "21:9",+ "16:9",+ "4:3",+ "1:1",+ "3:4",+ "9:16"+ ],+ "resolutions": [+ "480p",+ "720p",+ "1080p"+ ],+ "negativePrompt": true,+ "seed": true,+ "audio": true+ },+ "licence": {+ "licence": "LTX-2 / LTX-2.x Community License",+ "commercial": true,+ "note": "Free for companies under US$10M annual revenue; above that a paid licence (github.com/Lightricks/LTX-2 LICENSE-2, LICENSE-2_x, section 2.1)",+ "checked": "2026-10-23"+ },+ "defaults": {+ "aspectRatio": "16:9",+ "duration": 5,+ "resolution": "720p",+ "generateAudio": true+ },+ "pricing": {+ "unit": "second",+ "usd": 0.0347,+ "note": "$0.001605 per megapixel of video (width \u00d7 height \u00d7 frames): about $0.17 for 5 s at 720p; $0.001805 with LoRAs",+ "byResolution": {+ "480p": 0.016,+ "720p": 0.0347,+ "1080p": 0.0805+ },+ "withLoras": 0.039,+ "withLorasByResolution": {+ "480p": 0.018,+ "720p": 0.039,+ "1080p": 0.0905+ },+ "videoMegapixel": {+ "usd": 0.001605,+ "withLoras": 0.001805+ }+ }}];diff --git a/src/lib/catalog/evolution.ts b/src/lib/catalog/evolution.tsnew file mode 100644index 00000000..c32f7f33--- /dev/null+++ b/src/lib/catalog/evolution.ts@@ -0,0 +1,366 @@+/**+ * Fuobe Evolution (build plan O13): Higgsfield Evolution's Original. One clip and up to 40 references are taken+ * further in a creative direction an LLM writes from the references (or you write); the change intensity sets how+ * much of the clip stays. Research: docs/research/fuobe-originals-recipes-5.md §8 evolution and its JSON twin+ * (studios[evolution].original); what Higgsfield's does: higgsfield-originals-5.md §3.20.+ *+ * - On your GPU: per ≤81-frame segment at 16 fps, Qwen-Image-Edit takes the segment's first frame toward the direction+ * (the first references as images 2–3), then Wan 2.2 Fun VACE re-renders the segment from the segment itself, noised+ * to the intensity's denoise, with depth control and that frame as its reference (video-evolution-wan22-fun-vace).+ * - In the cloud: LTX-2.3 22B video to video on fal, video_strength = 1 − denoise, the direction as the scene; a clip+ * over 20 s runs as equal pieces. The endpoint takes no images: there the references shape the direction only.+ * - Then the pieces are joined and the clip's own sound put back.+ *+ * Pure module, shared by the page, the server (src/server/evolution.ts) and the tests.+ */+import { planCloudSegments, planOpenSegments, planStitch, SHORTS, SHORTS_TOOLS, wholeClip, type PlanStep, type ShortsPlanInput, type ShortsRange } from "./shorts";+import type { Engine, GenerationRequest } from "./types";++export const EVOLUTION = {+ model: "fuobe-evolution",+ feature: "evolution",+ /** Cuts, direction frames, segments and joins: kept apart from the finished videos. */+ stepFeature: "evolution-step",+ /** Higgsfield's limits: one video of 4–30 s, up to 40 references, a direction of up to 10,000 characters. */+ minSeconds: 4,+ maxSeconds: 30,+ maxReferences: 40,+ maxDirectionChars: 10_000,+ /** What reaches the models: the direction's first sentences, up to this many characters. */+ promptChars: 1500,+ /** LTX-2.3 makes at most 481 frames a call: 20 s at 24 fps. */+ cloudPieceSeconds: 20,+ /** Qwen-Image-Edit takes the frame plus two references. */+ openReferences: 2,+ /** The LLM sees this many references (Claude reads up to 20 images a turn; a local vision model fewer). */+ llmReferences: { cloud: 8, open: 4 } as Record<Engine, number>,+ /** Helper on the GPU: the segment's first frame taken toward the direction. */+ frameModel: "oss-qwen-edit",+ maxBytes: 500 * 1024 * 1024,+ accept: "video/mp4,video/quicktime,video/webm,.mp4,.mov,.m4v,.webm",+} as const;++export type Intensity = "low" | "medium" | "high";++/**+ * Build plan O13's change intensity: the denoise the open graph starts from (the share of each frame redrawn), and in the+ * cloud LTX-2.3's video_strength = 1 − denoise (lower gives the model more freedom). The same numbers are in the research+ * (studios[evolution].original.intensity); tests/evolution.test.ts holds them together.+ */+export const INTENSITIES: { id: Intensity; label: string; denoise: number; hint: string }[] = [+ { id: "low", label: "Low", denoise: 0.45, hint: "Same scene and people, a new finish" },+ { id: "medium", label: "Medium", denoise: 0.65, hint: "The action stays, the world around it changes" },+ { id: "high", label: "High", denoise: 0.85, hint: "Only the motion and timing stay" },+];++const intensity = (i: Intensity) => INTENSITIES.find((x) => x.id === i) ?? INTENSITIES[1];+export const denoiseFor = (i: Intensity): number => intensity(i).denoise;+export const videoStrengthFor = (i: Intensity): number => Math.round((1 - intensity(i).denoise) * 100) / 100;++/** Resolutions per engine (the GPU graph tops out at 1280 px; LTX-2.3 has a 1080p tier) and the default. */+export const EVOLUTION_RESOLUTIONS: Record<Engine, string[]> = { open: ["480p", "720p"], cloud: ["480p", "720p", "1080p"] };+export const EVOLUTION_DEFAULT_RESOLUTION: Record<Engine, string> = { open: "480p", cloud: "720p" };++/** LTX-2.3's shapes (Fuobe Cinema's size table): the clip is made in the one nearest its own. */+export const CLOUD_SHAPES = ["21:9", "16:9", "4:3", "1:1", "3:4", "9:16"] as const;++export function nearestShape(width?: number, height?: number): (typeof CLOUD_SHAPES)[number] {+ if (!width || !height) return "16:9";+ const r = Math.log(width / height);+ let best: (typeof CLOUD_SHAPES)[number] = "16:9";+ let gap = Infinity;+ for (const s of CLOUD_SHAPES) {+ const [a, b] = s.split(":").map(Number);+ const d = Math.abs(Math.log(a / b) - r);+ if (d < gap) {+ gap = d;+ best = s;+ }+ }+ return best;+}++// ---------------------------------------------------------------------------+// Checks++export interface EvolutionSource {+ url: string;+ duration?: number;+ fps?: number;+ width?: number;+ height?: number;+ hasAudio?: boolean;+}++/** What's wrong with a selection, or null. */+export function evolutionRangeProblem(range: ShortsRange, duration?: number): string | null {+ const len = range.end - range.start;+ if (!(len > 0) || range.start < 0) return "Pick a part of the clip";+ if (duration !== undefined && range.end > duration + 0.05) return "The selection runs past the end of the clip";+ if (len < EVOLUTION.minSeconds - 0.05) return `Select at least ${EVOLUTION.minSeconds} seconds`;+ if (len > EVOLUTION.maxSeconds + 0.05) return `Select up to ${EVOLUTION.maxSeconds} seconds`;+ return null;+}++/** Why this run can't start, or null. */+export function evolutionProblem(o: { engine: Engine; source: Pick<EvolutionSource, "duration">; range: ShortsRange; references: number; direction?: string; resolution?: string }): string | null {+ const r = evolutionRangeProblem(o.range, o.source.duration);+ if (r) return r;+ if (o.references > EVOLUTION.maxReferences) return `Use up to ${EVOLUTION.maxReferences} references`;+ if ((o.direction?.length ?? 0) > EVOLUTION.maxDirectionChars) return `Keep the direction under ${EVOLUTION.maxDirectionChars.toLocaleString("en")} characters`;+ if (o.resolution && !EVOLUTION_RESOLUTIONS[o.engine].includes(o.resolution)) return `${o.resolution} isn't offered ${o.engine === "open" ? "on your GPU" : "in the cloud"} — pick ${EVOLUTION_RESOLUTIONS[o.engine].join(" or ")}`;+ return null;+}++// ---------------------------------------------------------------------------+// The creative direction++const tidy = (s: string) => s.replace(/\s+/g, " ").trim();++/** The prompt the models get: the direction, cut after a sentence once it passes EVOLUTION.promptChars. */+export function directionPrompt(direction: string): { text: string; cut: boolean } {+ const t = tidy(direction);+ if (t.length <= EVOLUTION.promptChars) return { text: t, cut: false };+ const head = t.slice(0, EVOLUTION.promptChars);+ const end = Math.max(head.lastIndexOf(". "), head.lastIndexOf("! "), head.lastIndexOf("? "));+ return { text: end > EVOLUTION.promptChars / 2 ? head.slice(0, end + 1) : head.replace(/\s+\S*$/, ""), cut: true };+}++const FRAME_VERB: Record<Intensity, string> = {+ low: "Refine image 1 gently toward this direction",+ medium: "Change image 1 toward this direction",+ high: "Reimagine image 1 boldly in this direction",+};++/** On the GPU: Qwen-Image-Edit's instruction for the segment's first frame (references are images 2 and 3). */+export function directionFramePrompt(direction: string, i: Intensity, refs: number): string {+ const d = directionPrompt(direction).text.replace(/[.\s]+$/, "");+ const keep = i === "high" ? "Keep the composition and the poses of image 1." : "Keep the composition, the people, their faces and poses, and the framing of image 1.";+ const match = refs ? ` Use the characters, objects and style of ${refs > 1 ? "images 2 and 3" : "image 2"} where they fit.` : "";+ return `${FRAME_VERB[i]}: ${d}. ${keep}${match}`;+}++/** The LLM's brief (Fuobe's own words). */+export const DIRECTION_SYSTEM = `You write the creative direction for a video-to-video model that re-renders the user's clip. The clip's motion, timing and camera stay; how much else changes depends on the change intensity:+- low: keep the scene, the people and the setting; refine the look (light, colour, texture, small wardrobe details).+- medium: keep what the people do and how the camera moves; change the setting, wardrobe, light and style.+- high: keep only the motion and timing; reinvent the world, how the characters look and the style.+Use the reference images: take their characters, objects, places, colours and style where they fit. If the user gave an idea, build on it.+Write a description of the finished video, what we see, in the present tense: one paragraph of 50 to 120 words. Not instructions, no camera moves the clip doesn't have, no on-screen text, no lists, no preamble or quotes. Reply with the paragraph only.`;++/** The LLM's question: the intensity, the user's words and what is attached. */+export function directionRequest(o: { intensity: Intensity; idea?: string; references: number; sent: number; frame: boolean; seconds?: number }): string {+ const lines = [`Change intensity: ${o.intensity}.`];+ lines.push(o.idea?.trim() ? `The user's idea: ${tidy(o.idea).slice(0, 2000)}` : "The user gave no idea: propose one that fits the references and the clip.");+ if (o.seconds) lines.push(`The clip is ${Math.round(o.seconds)} s long.`);+ const parts: string[] = [];+ if (o.frame) parts.push("the first image is a frame of the clip");+ if (o.sent) parts.push(`${o.frame ? "the others are" : "the images are"} ${o.sent === o.references ? `the ${o.sent} reference${o.sent > 1 ? "s" : ""}` : `${o.sent} of the ${o.references} references`}`);+ else if (o.references) parts.push(`the user has ${o.references} reference image${o.references > 1 ? "s" : ""} you can't see`);+ if (parts.length) lines.push(`Attached: ${parts.join("; ")}.`);+ return lines.join("\n");+}++const LEAD: Record<Intensity, string> = {+ low: "The same scene, the same people and the same camera,",+ medium: "The same action and the same camera move, now in a new world:",+ high: "The same motion and timing, reimagined from the ground up:",+};+const IDEA: Record<Intensity, string> = {+ low: "with richer light, deeper colour and finer texture, like a high-end film grade",+ medium: "a dreamlike version of the place with new wardrobe and set dressing, soft volumetric light",+ high: "a bold stylised world where the characters take on a new look, vivid colour and dramatic light",+};++/** Fuobe's offline writer: the direction without an LLM (no Claude key or Ollama, demo mode, or the text model off). */+export function offlineDirection(o: { intensity: Intensity; idea?: string; references: number }): string {+ const idea = o.idea?.trim() ? tidy(o.idea).replace(/[.\s]+$/, "") : IDEA[o.intensity];+ const lead = o.intensity === "low" && o.idea?.trim() ? `${LEAD.low} now ${idea[0].toLowerCase()}${idea.slice(1)}` : `${LEAD[o.intensity]} ${idea}`;+ const refs = o.references ? ` It takes the characters, objects, colours and style of the ${o.references === 1 ? "reference image" : `${o.references} reference images`}.` : "";+ return `${lead}.${refs} Smooth, natural motion, consistent from the first frame to the last.`.slice(0, EVOLUTION.maxDirectionChars);+}++/** An LLM's answer as a direction: quotes, labels and lists taken off; null when nothing usable came back. */+export function tidyDirection(text: string | null | undefined): string | null {+ if (!text) return null;+ const t = text+ .replace(/^\s*(creative direction|direction)\s*:\s*/i, "")+ .split("\n")+ .map((l) => l.replace(/^\s*([-*•]|\d+[.)])\s+/, "").trim())+ .filter(Boolean)+ .join(" ")+ .replace(/^["“'\s]+|["”'\s]+$/g, "");+ const out = tidy(t).slice(0, EVOLUTION.maxDirectionChars);+ return out.length >= 12 ? out : null;+}++// ---------------------------------------------------------------------------+// The pipeline: steps for createPipeline (src/server/chains.ts)++export interface EvolutionPlanInput {+ engine: Engine;+ title: string;+ source: EvolutionSource;+ range: ShortsRange;+ intensity: Intensity;+ /** The creative direction (written by you, an LLM or the offline writer). */+ direction: string;+ references: string[];+ resolution?: string;+ seed?: number;+}++export interface EvolutionPlan {+ steps: PlanStep[];+ /** The finished video's step. */+ final: string;+ /** Pieces (cloud) or segments (GPU). */+ pieces: number;+ /** The clip's own sound is put back. */+ sound: boolean;+ /** The direction was longer than the models take: only its first sentences go. */+ cut: boolean;+ /** References that reach a model (the GPU's direction frames); the rest only shape the direction. */+ referencesUsed: number;+}++const r3 = (n: number) => Math.round(n * 1000) / 1000;+const pieceLabel = (i: number, n: number, what: string) => ({ label: n > 1 ? `Piece ${i + 1} of ${n} · ${what}` : what[0].toUpperCase() + what.slice(1), index: i, of: n });++/**+ * The whole job. GPU: per segment, cut it (16 fps), take its first frame toward the direction, evolve it from itself+ * at the intensity's denoise. Cloud: per piece of up to 20 s, cut it (unless it is the whole clip) and evolve it on+ * LTX-2.3 at video_strength 1 − denoise, in the tier's size for the clip's shape. Then join and put the sound back.+ */+export function planEvolution(input: EvolutionPlanInput): EvolutionPlan {+ const { engine } = input;+ const base = { feature: EVOLUTION.feature, batchTitle: input.title };+ const helper = { feature: EVOLUTION.stepFeature, batchTitle: input.title };+ const seed = input.seed !== undefined ? { seed: input.seed } : {};+ const resolution = input.resolution && EVOLUTION_RESOLUTIONS[engine].includes(input.resolution) ? input.resolution : EVOLUTION_DEFAULT_RESOLUTION[engine];+ const { text: prompt, cut } = directionPrompt(input.direction);+ const sound = !!input.source.hasAudio;+ const steps: PlanStep[] = [];+ const keys: string[] = [];+ let referencesUsed = 0;+ let n: number;++ if (engine === "open") {+ const t = SHORTS_TOOLS.open;+ const segs = planOpenSegments(input.range);+ n = segs.length;+ const refs = input.references.slice(0, EVOLUTION.openReferences);+ referencesUsed = refs.length;+ segs.forEach((s, i) => {+ const own = n === 1 && !sound;+ steps.push({+ key: `cut${i}`,+ request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: s.start, endTime: s.end, fps: SHORTS.openFps, aspectRatio: "auto", resolution }, step: pieceLabel(i, n, "cut") },+ });+ steps.push({+ key: `frame${i}`,+ request: {+ ...helper,+ modelId: EVOLUTION.frameModel,+ op: "edit",+ prompt: directionFramePrompt(input.direction, input.intensity, refs.length),+ ...(refs.length ? { inputs: { images: refs } } : {}),+ params: { ...seed },+ step: pieceLabel(i, n, "direction frame"),+ },+ after: [`cut${i}`],+ chain: [{ slot: "images", position: "first" }],+ });+ steps.push({+ key: `evolve${i}`,+ request: {+ ...(own ? { ...base, title: input.title } : helper),+ modelId: EVOLUTION.model,+ engine: "open",+ op: "v2v",+ prompt,+ params: { aspectRatio: "auto", resolution, duration: r3((s.frames ?? Math.round((s.end - s.start) * SHORTS.openFps)) / SHORTS.openFps), extra: { denoise: denoiseFor(input.intensity) }, ...seed },+ step: pieceLabel(i, n, "evolve"),+ },+ after: [`cut${i}`, `frame${i}`],+ chain: [{ slot: "video" }, { slot: "images" }],+ });+ keys.push(`evolve${i}`);+ });+ } else {+ const pieces = planCloudSegments(input.range, EVOLUTION.cloudPieceSeconds);+ n = pieces.length;+ const whole = n === 1 && wholeClip(input.range, input.source.duration);+ const shape = nearestShape(input.source.width, input.source.height);+ pieces.forEach((p, i) => {+ const own = n === 1 && !sound;+ if (!whole) {+ steps.push({+ key: `cut${i}`,+ request: { ...helper, modelId: SHORTS_TOOLS.cloud.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: p.start, endTime: p.end }, step: pieceLabel(i, n, "cut") },+ });+ }+ steps.push({+ key: `evolve${i}`,+ request: {+ ...(own ? { ...base, title: input.title } : helper),+ modelId: EVOLUTION.model,+ engine: "cloud",+ op: "v2v",+ prompt,+ ...(whole ? { inputs: { video: input.source.url } } : {}),+ params: { aspectRatio: shape, resolution, duration: r3(p.end - p.start), extra: { video_strength: videoStrengthFor(input.intensity) }, ...seed },+ step: pieceLabel(i, n, "evolve"),+ },+ ...(whole ? {} : { after: [`cut${i}`], chain: [{ slot: "video" as const }] }),+ });+ keys.push(`evolve${i}`);+ });+ }++ // Join and put the sound back with Shorts' stitch (folding joins, the selection's own sound), then name the steps ours.+ const stitchInput: ShortsPlanInput = {+ engine,+ title: input.title,+ source: input.source,+ range: input.range,+ look: { presetId: "evolution", name: "Evolution", look: prompt },+ aspectRatio: "16:9",+ keepShape: true,+ language: "auto",+ modelId: EVOLUTION.model,+ maxRefs: 0,+ };+ const stitch = planStitch(+ stitchInput,+ keys.map((key) => ({ key })),+ );+ const final = stitch.final ?? keys[0];+ for (const s of stitch.steps) {+ const own = s.key === final;+ const request: GenerationRequest = { ...s.request, ...(own ? { ...base, title: input.title } : helper) };+ // The GPU's joins keep the segments' size (Shorts joins at 480p).+ if (engine === "open" && request.op === "concat") request.params = { ...request.params, resolution };+ steps.push({ ...s, request });+ }+ return { steps, final, pieces: n, sound, cut, referencesUsed };+}++/** A short name for the run: the direction's first words. */+export function evolutionTitle(direction: string, clipName?: string): string {+ let d = tidy(direction);+ // The offline writer's lead ("The same action …: a sunken temple") says nothing about this run: what follows does.+ const colon = d.indexOf(":");+ if (colon > 0 && colon < 100) d = d.slice(colon + 1).trim();+ while (/^the same [^,.:]*,\s*/i.test(d)) d = d.replace(/^the same [^,.:]*,\s*/i, "");+ const words = d+ .replace(/^now\s+/i, "")+ .split(/(?<=[.!?])\s/)[0]+ .split(" ")+ .slice(0, 6)+ .join(" ")+ .replace(/[,.;:!?]+$/, "");+ const head = words ? `Evolution · ${words[0].toUpperCase()}${words.slice(1)}` : "Evolution";+ const name = clipName?.replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);+ return name ? `${head} · ${name}` : head;+}diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex 3e78c2e4..101983a9 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -4,6 +4,7 @@ import { DEFAULT_FPS_TARGET, FPS_TARGETS, SLOW_MOTION } from "@/lib/av/fps";import { ASR_LANGUAGES, WHISPER_LANGUAGES } from "../speech-languages";import { loraEntry, loraRef } from "./loras";import { CINEMA_CROP, SOUL_ASPECTS, SOUL_TIERS } from "./soul";+import { CLOUD_SHAPES, denoiseFor, EVOLUTION, EVOLUTION_DEFAULT_RESOLUTION, EVOLUTION_RESOLUTIONS, INTENSITIES, videoStrengthFor, type Intensity } from "./evolution";import { LAST_FRAME_CHAIN, type ModelDef, type ModelOptions, type ModelRoute, type Operation } from "./types";/*@@ -1569,6 +1570,17 @@ const DOP_OPTIONS: ModelOptions = {requires: { images: 1, msg: "Add a start frame: Fuobe DoP moves the camera through your picture" },};+/** Fuobe Evolution's change intensity as a composer control on one engine's own field (the GPU's denoise, fal's video_strength). */+function intensityControl(param: string, value: (i: Intensity) => number): NonNullable<ModelOptions["controls"]>[number] {+ return {+ param,+ label: "Change",+ values: INTENSITIES.map((i) => value(i.id)),+ default: value("medium"),+ labels: Object.fromEntries(INTENSITIES.map((i) => [String(value(i.id)), i.label])),+ };+}+/** Soul's options on both engines (research §4.3): 7 shapes, a 720p (about 1 MP) and a 1080p (about 2 MP) tier, 1–4 images. */const SOUL_OPTIONS: ModelOptions = { aspectRatios: SOUL_ASPECTS, resolutions: SOUL_TIERS, seed: true, maxOutputs: 4 };@@ -1684,6 +1696,31 @@ const originals: ModelDef[] = [tagline: "Every frame takes a Fuobe look, motion and framing kept · Wan 2.2 Fun VACE free on your GPU (24 GB), or hosted on fal",options: { seed: true, negativePrompt: true, resolutions: ["480p", "720p"], maxImages: 4 },}),+ // Fuobe Evolution (O13): Higgsfield Evolution's Original (src/lib/catalog/evolution.ts plans the segments, the direction+ // frame and the sound; Video tools → Evolution is its studio). The change intensity is the denoise the GPU graph starts+ // from, and LTX-2.3's video_strength (1 − denoise) in the cloud: one control, each engine's own field.+ {+ ...original({+ id: EVOLUTION.model,+ open: [comfy("v2v", "video-evolution-wan22-fun-vace", "Wan 2.2 Fun VACE from the noised segment, depth control, image = the direction frame; ≤81 frames at 16 fps")],+ tagline: "Takes your clip further in a creative direction · Wan 2.2 Fun VACE free on your GPU (24 GB), or LTX-2.3 on fal",+ options: { seed: true, negativePrompt: true, aspectRatios: [...CLOUD_SHAPES], resolutions: EVOLUTION_RESOLUTIONS.cloud, maxImages: 0 },+ }),+ defaults: { aspectRatio: "16:9", duration: 5, resolution: EVOLUTION_DEFAULT_RESOLUTION.cloud },+ engineDefaults: { open: { resolution: EVOLUTION_DEFAULT_RESOLUTION.open, aspectRatio: "auto" } },+ engineOptions: {+ open: {+ aspectRatios: ["auto", ...VID_AR],+ resolutions: EVOLUTION_RESOLUTIONS.open,+ durations: [3, 4, 5],+ maxImages: 1,+ imageLabels: ["direction frame (the clip's first frame as it should look)"],+ controls: [intensityControl("denoise", denoiseFor)],+ requires: { images: 1, msg: "Add the direction frame: the clip's first frame as it should look (Video tools → Evolution makes it for you)" },+ },+ cloud: { controls: [intensityControl("video_strength", videoStrengthFor)] },+ },+ },// Character swap (Openjutsu, Akatz Labs' H3 Character Swap): MiniMax H3 with the Character Swap LoRA. On your GPU the// h3_character_swap graph finds the person with SAM 3.1 and regenerates only them in 124-frame windows, keeping the// clip's own sound; on fal, H3 reference-to-video with the same LoRA (no mask), the clip's sound put back.diff --git a/src/server/evolution.ts b/src/server/evolution.tsnew file mode 100644index 00000000..5081d5e0--- /dev/null+++ b/src/server/evolution.ts@@ -0,0 +1,278 @@+import "server-only";+import { z } from "zod";+import { getModel } from "@/lib/catalog";+import {+ DIRECTION_SYSTEM,+ directionRequest,+ EVOLUTION,+ EVOLUTION_DEFAULT_RESOLUTION,+ EVOLUTION_RESOLUTIONS,+ evolutionProblem,+ evolutionTitle,+ nearestShape,+ offlineDirection,+ planEvolution,+ tidyDirection,+ type EvolutionPlanInput,+ type Intensity,+} from "@/lib/catalog/evolution";+import type { PlanStep } from "@/lib/catalog/shorts";+import type { Engine, Generation } from "@/lib/catalog/types";+import { ACCESS_PLACE } from "@/lib/model-access";+import { createPipeline } from "./chains";+import { llmText, llmTextBackend } from "./enhance";+import { previewChained } from "./generations";+import { isOffered, offeredModel } from "./model-access";+import { probeOllama } from "./providers/llm";+import { engineMode, getSetting } from "./settings";+import { probeSource, ShortsError } from "./shorts";+import { readRef } from "./storage";++/**+ * Video tools → Evolution (Fuobe Evolution, build plan O13): plans, prices and starts a run (src/lib/catalog/evolution.ts)+ * as one pipeline of ordinary generations: feature "evolution" for the finished video, "evolution-step" for the cuts,+ * direction frames, segments and joins. The creative direction is written by an LLM from the references (Claude, or+ * Ollama on the open engine), else by Fuobe's offline writer. No table of its own: the page's history is a feed.+ */++export { ShortsError as EvolutionError };++const fileUrl = z.string().startsWith("/api/files/").max(500);+const seconds = z.number().finite().min(0).max(3600);+const intensity = z.enum(["low", "medium", "high"]);++/** The body of /api/evolution (and /estimate). */+export const EvolutionBodySchema = z.object({+ engine: z.enum(["cloud", "open"]),+ intensity: intensity.default("medium"),+ /** The creative direction; empty: written before the run (LLM or offline writer). */+ direction: z.string().max(EVOLUTION.maxDirectionChars).optional(),+ /** Your few words for the writer, when the direction is left to it. */+ idea: z.string().max(2000).optional(),+ references: z.array(fileUrl).max(EVOLUTION.maxReferences).default([]),+ 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(),+ resolution: z.string().max(10).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(),+});+export type EvolutionBody = z.input<typeof EvolutionBodySchema>;++/** The estimate is asked for before the upload finishes: any URL stands in, references may still be uploading. */+export const EvolutionEstimateSchema = EvolutionBodySchema.extend({+ source: EvolutionBodySchema.shape.source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }),+ references: z.array(z.string().max(500)).max(EVOLUTION.maxReferences).default([]),+});++/** The body of /api/evolution/direction: what the writer works from. */+export const DirectionSchema = z.object({+ engine: z.enum(["cloud", "open"]),+ intensity: intensity.default("medium"),+ idea: z.string().max(2000).optional(),+ references: z.array(fileUrl).max(EVOLUTION.maxReferences).default([]),+ /** A frame of the clip the browser grabbed (a JPEG or PNG data URL, at most about 1.5 MB). */+ frame: z+ .string()+ .max(2_000_000)+ .regex(/^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/)+ .optional(),+ seconds: z.number().finite().positive().max(3600).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);+ }+};++const mustBeOffered = (engine: Engine) => {+ if (!isOffered(EVOLUTION.model, engine)) throw new ShortsError(`Fuobe Evolution is switched off ${engine === "open" ? "on your GPU" : "in the cloud"} in ${ACCESS_PLACE}`, 422);+};++// ---------------------------------------------------------------------------+// The creative direction++export interface DirectionAnswer {+ direction: string;+ /** Who wrote it. */+ by: "claude" | "ollama" | "offline";+ /** Why the offline writer wrote it, when it did. */+ why?: string;+}++const IMAGE = /^image\/(png|jpeg|webp|gif)$/;++/** The references the writer can see: the first few, pictures only, each under 8 MB. */+async function referenceImages(urls: string[], max: number) {+ const out: { data: Buffer; contentType: string }[] = [];+ for (const u of urls) {+ if (out.length >= max) break;+ const f = await readRef(u).catch(() => null);+ if (f && IMAGE.test(f.contentType) && f.data.length <= 8 * 1024 * 1024) out.push({ data: f.data, contentType: f.contentType });+ }+ return out;+}++/**+ * Write the creative direction: Claude (cloud engine) or Ollama with a vision model (open engine, or no Claude key) sees+ * the clip's frame and the first references; without one (no key, Ollama not running, demo mode, the text model+ * switched off) Fuobe's offline writer builds it from the intensity, your words and the number of references.+ */+export async function writeDirection(body: z.infer<typeof DirectionSchema>): Promise<DirectionAnswer> {+ mustMatchMode(body.engine);+ const offline = (why: string): DirectionAnswer => ({ direction: offlineDirection({ intensity: body.intensity as Intensity, idea: body.idea, references: body.references.length }), by: "offline", why });+ if (getSetting("demoMode") === "on") return offline("demo mode");+ const textModel = getModel(body.engine === "open" ? "oss-text-llm" : "text-llm");+ if (!textModel || !offeredModel(textModel)) return offline(`the text model is switched off in ${ACCESS_PLACE}`);+ const backend = llmTextBackend();+ const ollama = backend === "ollama" || (backend === "claude" && body.engine === "open");+ if (!backend) return offline("no text model is set up (Settings → AI helper)");+ if (ollama && !(await probeOllama())) return offline("Ollama isn't running");+ const max = EVOLUTION.llmReferences[body.engine];+ const frame = body.frame ? [{ data: Buffer.from(body.frame.split(",")[1], "base64"), contentType: body.frame.slice(5, body.frame.indexOf(";")) }] : [];+ const refs = await referenceImages(body.references, max - frame.length);+ const user = directionRequest({ intensity: body.intensity as Intensity, idea: body.idea, references: body.references.length, sent: refs.length, frame: frame.length > 0, seconds: body.seconds });+ const answer = tidyDirection(await llmText(DIRECTION_SYSTEM, user, [...frame, ...refs], { ollamaOnly: body.engine === "open" }));+ if (!answer) return offline(ollama ? "Ollama didn't answer (it needs a vision model to see the references: qwen3-vl, gemma3…)" : "the text model didn't answer");+ return { direction: answer, by: ollama ? "ollama" : "claude" };+}++// ---------------------------------------------------------------------------+// Plan, price, run++interface Planned {+ input: EvolutionPlanInput;+ notes: string[];+}++function planInput(body: z.infer<typeof EvolutionBodySchema>, info: Awaited<ReturnType<typeof probeSource>> | Record<string, never>, direction: string, probed: boolean): Planned {+ const engine = body.engine;+ const source = {+ 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 run was paid for).+ hasAudio: probed ? (info.hasAudio ?? false) : (body.source.hasAudio ?? false),+ };+ const range = body.range ?? (source.duration ? { start: 0, end: source.duration } : null);+ if (!range) throw new ShortsError("Reading the clip… try again in a moment");+ const resolution = body.resolution ?? EVOLUTION_DEFAULT_RESOLUTION[engine];+ const problem = evolutionProblem({ engine, source, range, references: body.references.length, direction, resolution });+ if (problem) throw new ShortsError(problem, 422);++ const notes: string[] = [];+ const name = getModel(EVOLUTION.model)?.name ?? "Fuobe Evolution";+ const n = body.references.length;+ if (engine === "open") {+ notes.push(`Each ≤5 s segment: Qwen-Image-Edit takes its first frame toward the direction${n ? ` with your first ${Math.min(n, EVOLUTION.openReferences) === 1 ? "reference" : "two references"}` : ""}, then Wan 2.2 Fun VACE re-renders it from itself at 16 fps`);+ if (n > EVOLUTION.openReferences) notes.push(`The other ${n - EVOLUTION.openReferences} reference${n - EVOLUTION.openReferences > 1 ? "s" : ""} shape the direction only`);+ notes.push("Needs a 24 GB GPU · Wan 2.2 Fun VACE and Qwen-Image-Edit are Apache-2.0");+ } else {+ notes.push(`${name} runs LTX-2.3 video to video on fal in your clip's shape (${nearestShape(source.width, source.height)}) at 24 fps`);+ if (n) notes.push(`LTX-2.3 takes no pictures: your ${n === 1 ? "reference shapes" : `${n} references shape`} the direction`);+ notes.push("LTX-2.x Community License: free under US$10M annual revenue (information, Settings → Models & licences)");+ }+ if (source.hasAudio) notes.push("Your clip's own sound is put back on the result");+ const title = evolutionTitle(direction, body.source.name);+ return {+ notes,+ input: {+ engine,+ title,+ source,+ range,+ intensity: body.intensity as Intensity,+ direction,+ references: body.references,+ resolution,+ ...(body.seed !== undefined ? { seed: body.seed } : {}),+ },+ };+}++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;+ cost = cost === null || p.costUsd === null ? null : cost + p.costUsd;+ }+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo };+}++export interface EvolutionEstimate {+ costUsd: number | null;+ demo: boolean;+ modelName: string;+ engine: Engine;+ resolution: string;+ /** Pieces (cloud) or segments (GPU). */+ pieces: number;+ seconds: number;+ steps: number;+ notes: string[];+}++export function estimateEvolution(body: z.infer<typeof EvolutionEstimateSchema>): EvolutionEstimate {+ mustMatchMode(body.engine);+ mustBeOffered(body.engine);+ // The price doesn't depend on the words: a stand-in direction when none is written yet.+ const { input, notes } = planInput(body, {}, body.direction?.trim() || "the same scene", false);+ const plan = planEvolution(input);+ if (plan.cut) notes.push(`Only the first ${EVOLUTION.promptChars.toLocaleString("en")} characters of the direction reach the model`);+ return {+ ...price(plan.steps),+ modelName: getModel(EVOLUTION.model)?.name ?? "Fuobe Evolution",+ engine: body.engine,+ resolution: input.resolution ?? EVOLUTION_DEFAULT_RESOLUTION[body.engine],+ pieces: plan.pieces,+ seconds: Math.round((input.range.end - input.range.start) * 100) / 100,+ steps: plan.steps.length,+ notes,+ };+}++/** Start the run; a run with no direction gets one written first. Returns the finished video's generation and the direction used. */+export async function createEvolution(body: z.infer<typeof EvolutionBodySchema>): Promise<{ final: Generation; items: Generation[]; direction: string; by: DirectionAnswer["by"] | "you" }> {+ mustMatchMode(body.engine);+ mustBeOffered(body.engine);+ if (body.resolution && !EVOLUTION_RESOLUTIONS[body.engine].includes(body.resolution)) throw new ShortsError(`Pick ${EVOLUTION_RESOLUTIONS[body.engine].join(" or ")}`, 422);+ const info = await probeSource(body.source.url);+ let direction = body.direction?.trim() ?? "";+ let by: DirectionAnswer["by"] | "you" = "you";+ if (!direction) {+ const written = await writeDirection({ engine: body.engine, intensity: body.intensity, idea: body.idea, references: body.references, seconds: info.duration ?? body.source.duration });+ direction = written.direction;+ by = written.by;+ }+ const { input } = planInput(body, info, direction, true);+ const plan = planEvolution(input);+ let p: ReturnType<typeof createPipeline>;+ try {+ p = createPipeline(plan.steps);+ } catch (e) {+ throw new ShortsError((e as Error).message, 422);+ }+ return { final: p.byKey[plan.final], items: p.items, direction, by };+}diff --git a/tests/evolution-api.test.ts b/tests/evolution-api.test.tsnew file mode 100644index 00000000..3bad7493--- /dev/null+++ b/tests/evolution-api.test.ts@@ -0,0 +1,148 @@+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/evolution end to end in demo mode (no keys, no ComfyUI, no LLM): a run on either engine becomes one pipeline of+// ordinary generations that the mock provider runs through; estimates with a fal key price the real LTX-2.3 route.+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-evolution-"));+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/evolution/route");+const estimateRoute = await import("@/app/api/evolution/estimate/route");+const directionRoute = await import("@/app/api/evolution/direction/route");+const { changeAccess } = await import("@/server/model-access");++const json = (body?: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });++let clip = "";+let ref = "";+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: "walk.mp4" }).url;+ const data = Buffer.alloc(32 * 32 * 4, 200);+ ref = saveFile({ data: encodePng({ width: 32, height: 32, data }), contentType: "image/png", source: "upload", name: "ref.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, engine FROM generations WHERE batch_id = ? ORDER BY created_at, id").all(b) as { id: string; model_id: string; op: string; feature: string; engine: string }[];+};++const src = { duration: 12, fps: 16, width: 72, height: 128, hasAudio: true };+const body = (over: Record<string, unknown> = {}) => ({ engine: "cloud", intensity: "medium", references: [ref], source: { url: clip, name: "walk.mp4", ...src }, ...over });++describe("Evolution: estimates", () => {+ it("no keys: a demo; the GPU is free", async () => {+ const cloud = await (await estimateRoute.POST(json(body()))).json();+ expect(cloud).toMatchObject({ modelName: "Fuobe Evolution", engine: "cloud", resolution: "720p", pieces: 1, seconds: 12, demo: true });+ expect(cloud.notes.join(" ")).toMatch(/LTX-2.3 takes no pictures: your reference shapes the direction/);+ const open = await (await estimateRoute.POST(json(body({ engine: "open" })))).json();+ expect(open).toMatchObject({ engine: "open", resolution: "480p", pieces: 3, costUsd: 0 });+ expect(open.notes.join(" ")).toMatch(/Qwen-Image-Edit takes its first frame toward the direction with your first reference/);+ });++ describe("with a fal key (estimates submit nothing)", () => {+ beforeAll(() => setSetting("falKey", "fal-test-key"));+ afterAll(() => setSetting("falKey", ""));++ it("LTX-2.3 per megapixel of video in the clip's shape, plus the sound put back", async () => {+ const e = await (await estimateRoute.POST(json(body()))).json();+ expect(e).toMatchObject({ demo: false, pieces: 1, steps: 2 });+ // 9:16 at 720p is 704 × 1280; 12 s at 24 fps is 289 frames: 260.4 MP → 261 × $0.001605.+ expect(e.costUsd).toBeGreaterThanOrEqual(261 * 0.001605);+ expect(e.costUsd).toBeLessThan(261 * 0.001605 + 0.02);+ const hd = await (await estimateRoute.POST(json(body({ resolution: "1080p" })))).json();+ expect(hd.costUsd).toBeGreaterThan(e.costUsd * 2);+ });+ });++ it("refuses what can't run, in words", async () => {+ const say = async (b: unknown) => (await (await estimateRoute.POST(json(b))).json()).error;+ expect(await say(body({ range: { start: 0, end: 3 } }))).toBe("Select at least 4 seconds");+ expect(await say(body({ engine: "open", resolution: "1080p" }))).toMatch(/isn't offered on your GPU/);+ expect(await say({ engine: "cloud" })).toBe("Add a clip and pick how much should change");+ changeAccess([{ kind: "model", id: "fuobe-evolution", on: false }]);+ expect(await say(body())).toBe("Fuobe Evolution is switched off in the cloud in Settings → Models & licences");+ changeAccess([{ kind: "reset" }]);+ });+});++describe("Evolution: the direction", () => {+ it("no LLM running: Fuobe's offline writer, from the intensity, your words and the references", async () => {+ const res = await directionRoute.POST(json({ engine: "cloud", intensity: "high", idea: "a western at high noon", references: [ref, ref] }));+ expect(res.status).toBe(200);+ const d = await res.json();+ expect(d).toEqual({+ direction: "The same motion and timing, reimagined from the ground up: a western at high noon. It takes the characters, objects, colours and style of the 2 reference images. Smooth, natural motion, consistent from the first frame to the last.",+ by: "offline",+ why: "Ollama isn't running",+ });+ setSetting("demoMode", "on");+ const demo = await (await directionRoute.POST(json({ engine: "open", intensity: "low", references: [] }))).json();+ expect(demo).toMatchObject({ by: "offline", why: "demo mode" });+ expect(demo.direction).toMatch(/^The same scene, the same people and the same camera, with richer light/);+ setSetting("demoMode", "auto");+ });+});++describe("Evolution: runs (demo)", () => {+ const run = async (b: 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[]; direction: string; by: string };+ };++ it("cloud: no direction given, the offline writer writes one; Fuobe Evolution at video_strength 0.35, then the sound", async () => {+ const { final, items, direction, by } = await run(body({ idea: "a rainy neon street" }));+ expect(by).toBe("offline");+ expect(direction).toMatch(/now in a new world: a rainy neon street/);+ expect(final.feature).toBe("evolution");+ expect(items.filter((g) => g.feature === "evolution")).toHaveLength(1);+ const rows = batchOf(final.id);+ expect(rows.map((r) => `${r.op}:${r.model_id}`)).toEqual(["v2v:fuobe-evolution", "mux:merge-audio-video"]);+ const evolve = gens.getGeneration(rows[0].id)!;+ expect(evolve.request).toMatchObject({ engine: "cloud", params: { extra: { video_strength: 0.35 } } });+ expect(evolve.request.prompt).toBe(direction);+ const done = await settle(final.id);+ expect(done.status, done.error).toBe("succeeded");+ expect(done.outputs[0].kind).toBe("video");+ });++ it("GPU: segments cut, direction frames, the graph at denoise 0.85, joined with the clip's sound; your direction as written", async () => {+ const { final, by, direction } = await run(body({ engine: "open", intensity: "high", direction: "A paper-cut diorama world with layered card stock." }));+ expect(by).toBe("you");+ expect(direction).toBe("A paper-cut diorama world with layered card stock.");+ const rows = batchOf(final.id);+ expect(rows.filter((r) => r.model_id === "fuobe-evolution")).toHaveLength(3);+ expect(rows.filter((r) => r.model_id === "oss-qwen-edit")).toHaveLength(3);+ const evolve = gens.getGeneration(rows.find((r) => r.model_id === "fuobe-evolution")!.id)!;+ expect(evolve.request).toMatchObject({ engine: "open", params: { extra: { denoise: 0.85 } } });+ const done = await settle(final.id);+ expect(done.status, done.error).toBe("succeeded");+ expect(done.feature).toBe("evolution");+ });+});diff --git a/tests/evolution.test.ts b/tests/evolution.test.tsnew file mode 100644index 00000000..7446c9a4--- /dev/null+++ b/tests/evolution.test.ts@@ -0,0 +1,213 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { getModel, getPreset } from "@/lib/catalog";+import { onEngine } from "@/lib/catalog/engines";+import {+ denoiseFor,+ directionFramePrompt,+ directionPrompt,+ directionRequest,+ EVOLUTION,+ evolutionProblem,+ evolutionTitle,+ INTENSITIES,+ nearestShape,+ offlineDirection,+ planEvolution,+ tidyDirection,+ videoStrengthFor,+ type EvolutionPlanInput,+} from "@/lib/catalog/evolution";+import { buildPayload } from "@/lib/catalog/payload";+import { estimateCost, planGeneration } from "@/lib/catalog/plan";++const clip = { url: "/api/files/clip.mp4", duration: 12, fps: 30, width: 1280, height: 720, hasAudio: true };+const refs = Array.from({ length: 5 }, (_, i) => `/api/files/ref${i}.png`);+const plan = (o: Partial<EvolutionPlanInput> = {}) =>+ planEvolution({ engine: "cloud", title: "Evolution", source: clip, range: { start: 0, end: 12 }, intensity: "medium", direction: "A neon-lit night market in the rain.", references: refs, ...o });+const step = (p: ReturnType<typeof planEvolution>, key: string) => {+ const s = p.steps.find((x) => x.key === key);+ if (!s) throw new Error(`no step ${key}: ${p.steps.map((x) => x.key).join(", ")}`);+ return s;+};++describe("Fuobe Evolution: intensities", () => {+ it("low / medium / high are denoise 0.45 / 0.65 / 0.85, and LTX-2.3's video_strength is 1 − denoise", () => {+ expect(INTENSITIES.map((i) => [i.id, denoiseFor(i.id), videoStrengthFor(i.id)])).toEqual([+ ["low", 0.45, 0.55],+ ["medium", 0.65, 0.35],+ ["high", 0.85, 0.15],+ ]);+ });++ it("match the research record the generator reads", () => {+ const research = JSON.parse(fs.readFileSync(path.join(__dirname, "../docs/research/fuobe-originals-recipes-5.json"), "utf8"));+ const evo = research.studios.find((s: { id: string }) => s.id === "evolution").original;+ expect(evo.model).toBe(EVOLUTION.model);+ expect(evo.intensity).toEqual(Object.fromEntries(INTENSITIES.map((i) => [i.id, i.denoise])));+ expect(evo.limits).toEqual({ minSeconds: EVOLUTION.minSeconds, maxSeconds: EVOLUTION.maxSeconds, maxReferences: EVOLUTION.maxReferences, maxDirectionChars: EVOLUTION.maxDirectionChars });+ expect(evo.cloud.strengthField).toBe("video_strength");+ });+});++describe("Fuobe Evolution: the model on both engines", () => {+ const m = getModel(EVOLUTION.model)!;++ it("is an Original: the GPU graph and LTX-2.3 video to video on fal, no Higgsfield", () => {+ expect(m).toBeTruthy();+ expect(m.engines).toEqual(["open", "cloud"]);+ expect(m.routes.map((r) => `${r.provider}:${r.endpoint}`)).toEqual(["comfyui:video-evolution-wan22-fun-vace", "fal:fal-ai/ltx-2.3-22b/video-to-video"]);+ expect(m.routes[1].loraEndpoint).toBe("fal-ai/ltx-2.3-22b/video-to-video/lora");+ expect(m.licence?.licence).toMatch(/LTX-2/);+ });++ it("the change control is each engine's own field", () => {+ const open = onEngine(m, "open");+ const cloud = onEngine(m, "cloud");+ expect(open.options.controls?.[0]).toMatchObject({ param: "denoise", values: [0.45, 0.65, 0.85], default: 0.65, labels: { "0.45": "Low", "0.65": "Medium", "0.85": "High" } });+ expect(cloud.options.controls?.[0]).toMatchObject({ param: "video_strength", values: [0.55, 0.35, 0.15], default: 0.35 });+ expect(open.options.resolutions).toEqual(["480p", "720p"]);+ expect(cloud.options.resolutions).toEqual(["480p", "720p", "1080p"]);+ expect(open.defaults?.resolution).toBe("480p");+ });++ it("the fal payload: silent, 24 fps, frames from the piece's length, the tier's size, video_strength from the step", () => {+ const cloud = onEngine(m, "cloud");+ const p = planGeneration(+ { feature: "evolution", modelId: m.id, op: "v2v", prompt: "a night market", inputs: { video: "https://x/clip.mp4" }, params: { aspectRatio: "9:16", resolution: "720p", duration: 10, extra: { video_strength: 0.15 } } },+ (id) => (id === m.id ? cloud : getModel(id)),+ getPreset,+ );+ const route = cloud.routes.find((r) => r.op === "v2v")!;+ const body = buildPayload(route.map!, { ...p.params, prompt: p.prompt, video: "https://x/clip.mp4" });+ expect(body).toMatchObject({+ prompt: "a night market",+ video_url: "https://x/clip.mp4",+ video_size: { width: 704, height: 1280 },+ num_frames: 241,+ fps: 24,+ generate_audio: false,+ match_video_length: false,+ match_input_fps: false,+ enable_prompt_expansion: false,+ video_strength: 0.15,+ });+ // $0.001605 per megapixel of video: 704 × 1280 × 241 frames ≈ 217.2 MP, rounded up.+ expect(estimateCost(cloud, { aspectRatio: "9:16", resolution: "720p", duration: 10 }, 1, "v2v")).toBeCloseTo(218 * 0.001605, 3);+ expect(estimateCost(onEngine(m, "open"), { resolution: "480p", duration: 5 }, 1, "v2v")).toBe(0);+ });+});++describe("Fuobe Evolution: the plan", () => {+ it("cloud, the whole clip in one piece: evolved straight from the upload, then the clip's sound put back", () => {+ const p = plan();+ expect(p.pieces).toBe(1);+ expect(p.steps.map((s) => `${s.key}:${s.request.modelId}`)).toEqual(["evolve0:fuobe-evolution", "final:merge-audio-video"]);+ const e = step(p, "evolve0").request;+ expect(e).toMatchObject({ engine: "cloud", op: "v2v", feature: "evolution-step", inputs: { video: clip.url }, params: { aspectRatio: "16:9", resolution: "720p", duration: 12, extra: { video_strength: 0.35 } } });+ expect(e.inputs?.images).toBeUndefined();+ expect(p.final).toBe("final");+ expect(step(p, "final").request).toMatchObject({ feature: "evolution", title: "Evolution", inputs: { audio: clip.url } });+ expect(p.referencesUsed).toBe(0);+ });++ it("cloud, 30 s: two 15 s pieces cut, evolved, joined, the sound back; a silent clip needs no mux", () => {+ const long = { ...clip, duration: 30 };+ const p = plan({ source: long, range: { start: 0, end: 30 }, intensity: "high", resolution: "1080p" });+ expect(p.pieces).toBe(2);+ expect(p.steps.map((s) => s.key)).toEqual(["cut0", "evolve0", "cut1", "evolve1", "join", "final"]);+ expect(step(p, "evolve1").request.params).toMatchObject({ duration: 15, resolution: "1080p", extra: { video_strength: 0.15 } });+ expect(step(p, "evolve1")).toMatchObject({ after: ["cut1"], chain: [{ slot: "video" }] });+ const silent = plan({ source: { ...long, hasAudio: false }, range: { start: 0, end: 30 } });+ expect(silent.final).toBe("join");+ expect(step(silent, "join").request).toMatchObject({ feature: "evolution", title: "Evolution" });+ });++ it("cloud: the clip's shape picks the nearest LTX-2.3 shape", () => {+ expect(nearestShape(1080, 1920)).toBe("9:16");+ expect(nearestShape(2560, 1080)).toBe("21:9");+ expect(nearestShape(1000, 1000)).toBe("1:1");+ expect(nearestShape(1440, 1080)).toBe("4:3");+ expect(nearestShape()).toBe("16:9");+ expect(step(plan({ source: { ...clip, width: 1080, height: 1920 } }), "evolve0").request.params?.aspectRatio).toBe("9:16");+ });++ it("GPU: per ≤81-frame segment, cut at 16 fps, the direction frame with two references, the graph at the intensity's denoise", () => {+ const p = plan({ engine: "open", intensity: "low" });+ // 12 s at 16 fps = 192 frames → 3 segments of 4n+1 frames.+ expect(p.pieces).toBe(3);+ expect(p.referencesUsed).toBe(2);+ expect(step(p, "cut0").request).toMatchObject({ modelId: "oss-segment", op: "trim", params: { fps: 16, aspectRatio: "auto", resolution: "480p" } });+ const frame = step(p, "frame0");+ expect(frame.request).toMatchObject({ modelId: "oss-qwen-edit", op: "edit", inputs: { images: refs.slice(0, 2) } });+ expect(frame.request.prompt).toMatch(/^Refine image 1 gently toward this direction: A neon-lit night market in the rain\. Keep the composition, the people/);+ expect(frame.request.prompt).toMatch(/images 2 and 3/);+ expect(frame).toMatchObject({ after: ["cut0"], chain: [{ slot: "images", position: "first" }] });+ const e = step(p, "evolve0");+ expect(e.request).toMatchObject({ modelId: "fuobe-evolution", engine: "open", op: "v2v", prompt: "A neon-lit night market in the rain.", params: { aspectRatio: "auto", resolution: "480p", extra: { denoise: 0.45 } } });+ expect(e).toMatchObject({ after: ["cut0", "frame0"], chain: [{ slot: "video" }, { slot: "images" }] });+ // Joined at the segments' size, then the selection's sound.+ expect(p.steps.filter((s) => s.request.op === "concat").every((s) => s.request.params?.resolution === "480p")).toBe(true);+ expect(p.steps.at(-1)!.request).toMatchObject({ modelId: "oss-mux", feature: "evolution" });+ const hd = plan({ engine: "open", resolution: "720p" });+ expect(hd.steps.filter((s) => s.request.op === "concat").every((s) => s.request.params?.resolution === "720p")).toBe(true);+ });++ it("a part of the clip: only that part, and its own sound", () => {+ const p = plan({ range: { start: 2, end: 8 } });+ expect(p.steps.map((s) => s.key)).toEqual(["cut0", "evolve0", "sound", "final"]);+ expect(step(p, "cut0").request.params).toMatchObject({ startTime: 2, endTime: 8 });+ });++ it("checks: 4–30 s, 40 references, 10,000 characters, the engine's resolutions", () => {+ const ok = { engine: "cloud" as const, source: { duration: 12 }, range: { start: 0, end: 12 }, references: 3 };+ expect(evolutionProblem(ok)).toBeNull();+ expect(evolutionProblem({ ...ok, range: { start: 0, end: 3 } })).toBe("Select at least 4 seconds");+ expect(evolutionProblem({ ...ok, source: { duration: 40 }, range: { start: 0, end: 40 } })).toBe("Select up to 30 seconds");+ expect(evolutionProblem({ ...ok, references: 41 })).toBe("Use up to 40 references");+ expect(evolutionProblem({ ...ok, direction: "x".repeat(10_001) })).toMatch(/under 10,000 characters/);+ expect(evolutionProblem({ ...ok, engine: "open", resolution: "1080p" })).toMatch(/isn't offered on your GPU/);+ });+});++describe("Fuobe Evolution: the direction", () => {+ it("a long direction reaches the models cut after a sentence", () => {+ const long = Array.from({ length: 60 }, (_, i) => `Sentence number ${i} describes the scene in some detail.`).join(" ");+ const d = directionPrompt(long);+ expect(d.cut).toBe(true);+ expect(d.text.length).toBeLessThanOrEqual(EVOLUTION.promptChars);+ expect(d.text.endsWith(".")).toBe(true);+ expect(plan({ direction: long }).cut).toBe(true);+ expect(directionPrompt(" short one ").text).toBe("short one");+ });++ it("the GPU frame prompt follows the intensity", () => {+ expect(directionFramePrompt("a snowy village", "high", 0)).toBe("Reimagine image 1 boldly in this direction: a snowy village. Keep the composition and the poses of image 1.");+ expect(directionFramePrompt("a snowy village", "medium", 1)).toMatch(/^Change image 1 toward this direction: a snowy village\. .* image 2 where they fit\.$/);+ });++ it("the offline writer: the intensity's lead, your words or its own idea, the references", () => {+ expect(offlineDirection({ intensity: "medium", idea: "a sunken temple", references: 3 })).toBe(+ "The same action and the same camera move, now in a new world: a sunken temple. It takes the characters, objects, colours and style of the 3 reference images. Smooth, natural motion, consistent from the first frame to the last.",+ );+ expect(offlineDirection({ intensity: "low", idea: "Warm candlelight", references: 0 })).toMatch(/^The same scene, the same people and the same camera, now warm candlelight\. Smooth/);+ expect(offlineDirection({ intensity: "high", references: 1 })).toMatch(/reimagined from the ground up: a bold stylised world.* the reference image\./);+ });++ it("what the LLM is told, and what comes back", () => {+ const q = directionRequest({ intensity: "high", idea: "make it a western", references: 12, sent: 7, frame: true, seconds: 9.6 });+ expect(q).toBe("Change intensity: high.\nThe user's idea: make it a western\nThe clip is 10 s long.\nAttached: the first image is a frame of the clip; the others are 7 of the 12 references.");+ expect(directionRequest({ intensity: "low", references: 2, sent: 0, frame: false })).toMatch(/gave no idea.*\nAttached: the user has 2 reference images you can't see\./);+ expect(tidyDirection('Creative direction: "A dusty frontier town at noon, tumbleweeds rolling past."')).toBe("A dusty frontier town at noon, tumbleweeds rolling past.");+ expect(tidyDirection("- one\n- two lines of words here")).toBe("one two lines of words here");+ expect(tidyDirection("ok")).toBeNull();+ expect(tidyDirection(null)).toBeNull();+ });++ it("names the run after the direction", () => {+ expect(evolutionTitle("The same action and the same camera move, now in a new world: a sunken temple at dawn.", "beach.mp4")).toBe("Evolution · A sunken temple at dawn · beach");+ expect(evolutionTitle(offlineDirection({ intensity: "low", idea: "warm candlelight", references: 0 }))).toBe("Evolution · Warm candlelight");+ expect(evolutionTitle("A neon-lit night market in the rain.")).toBe("Evolution · A neon-lit night market in the");+ });+});