Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Fixes 5: Edit video prices a clip edit on the clip, inside the model's window

Claude33138cc37157
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index 177ab82c..6c968c06 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -55,7 +55,8 @@ export interface StudioConfig {
extraModels?: string[];
/**
* Read the attached clip's header (length, size, frame rate): prices count its seconds and the composer
- * says what comes out ("24 → 60 fps", "1280×720 → 3840×2160"). Upscale hub video modes.
+ * says what comes out ("24 → 60 fps", "1280×720 → 3840×2160"). Upscale hub video modes, and Edit video (a clip
+ * edit that keeps the clip's length is billed on it, inside the model's window).
*/
clipFacts?: boolean;
/**
diff --git a/src/lib/catalog/clip-windows.ts b/src/lib/catalog/clip-windows.ts
new file mode 100644
index 00000000..74504aec
--- /dev/null
+++ b/src/lib/catalog/clip-windows.ts
@@ -0,0 +1,35 @@
+/**
+ * How long a clip each cloud clip-edit model takes (docs/research/paid-model-apis-3.md, "Input windows"): a clip
+ * outside it is paid for and then refused by the provider, or (Happy Horse reads 3–60 s but returns at most the first
+ * 15 s) billed for seconds that never come back. Shorts, Mixed Media and Edit video keep to it. No catalog import
+ * here, so the composer can use it.
+ */
+const SOURCE_SECONDS: Record<string, { min?: number; max?: number }> = {
+ "kling-o3-4k-edit": { min: 3, max: 15 },
+ // It reads 3–60 s but returns at most the first 15 s.
+ "happy-horse-video-edit": { min: 3, max: 15 },
+ "runway-aleph-2": { min: 2, max: 30 },
+ "wan-2-7": { min: 2, max: 10 },
+ // Higgsfield feeds Gemini Omni Flash ≤10 s segments.
+ "gemini-omni-flash": { max: 10 },
+};
+
+export function sourceSeconds(modelId: string): { min?: number; max?: number } {
+ return SOURCE_SECONDS[modelId] ?? {};
+}
+
+const secs = (n: number) => `${Math.round(n * 10) / 10} s`;
+
+/**
+ * Why a clip `seconds` long is outside the model's window, in Generate's words ("Happy Horse Video Edit takes 3–15 s
+ * clips, and this one is 40 s: trim it first"), or null. A header's length can run a frame or so past the cut that
+ * made it, so a few hundredths over are let through.
+ */
+export function clipWindowProblem(model: { id: string; name: string }, seconds: number): string | null {
+ const { min, max } = sourceSeconds(model.id);
+ const long = max !== undefined && seconds > max + 0.05;
+ const short = min !== undefined && seconds < min - 0.05;
+ if (!long && !short) return null;
+ const takes = min !== undefined && max !== undefined ? `${min}–${max} s` : max !== undefined ? `up to ${max} s` : `${min} s or longer`;
+ return `${model.name} takes ${takes} clips, and this one is ${secs(seconds)}: ${long ? "trim it first" : "use a longer one"}`;
+}
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index ce068e0c..847451da 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -11,6 +11,7 @@ import type {
PresetRoute,
Pricing,
} from "./types";
+import { sourceSeconds } from "./clip-windows";
import { chainGapProblem, chainTiming, FIRST_AT_ZERO, frameTimes, keyframeChain, MAX_KEYFRAMES, spread } from "./keyframes";
import { cloudPath, fitLoras, gated, localOnly, loraCapacity, needsToken, routeLoraField, triggerOf } from "./loras";
import { anglesPrompt, anglesWords, ANGLES_ORIGINAL } from "./open-tools";
@@ -604,6 +605,20 @@ export function pricingAt(p: Pricing, now = Date.now()): Pricing {
*/
const CLIP_LENGTH_OPS = new Set<Operation>(["upscale-video", "interpolate", "sdr-to-hdr", "export-video"]);
+/**
+ * The seconds a clip edit that keeps the clip's length is billed for (Happy Horse, Runway Aleph, Lucy Edit, Kling O3 4K
+ * edit…: a v2v model with no length to ask for): the clip's (params.sourceDuration, when the caller knows it), up to the
+ * most its window takes (./clip-windows). Undefined for a model asked for a length, or when the clip's length isn't known.
+ */
+export function clipEditSeconds(model: Pick<ModelDef, "id" | "options" | "routes">, params: Pick<GenParams, "sourceDuration">, op?: Operation): number | undefined {
+ const seconds = params.sourceDuration;
+ if (op !== "v2v" || !seconds || !(seconds > 0) || model.options.durations?.length) return undefined;
+ const routes = model.routes.filter((r) => r.op === "v2v");
+ if (!routes.length || routes.some((r) => r.map?.duration)) return undefined;
+ const max = sourceSeconds(model.id).max;
+ return max !== undefined ? Math.min(seconds, max) : seconds;
+}
+
/**
* The seconds a talking avatar is made (and billed) for a voice `seconds` long: as long as the voice, or what a
* frame-count route's limits make of it, in the seconds it bills (fal's InfiniteTalk: 41–721 frames, 25 a second; Wan 2.2
@@ -693,7 +708,8 @@ export function estimateCost(model: ModelDef, params: GenParams, jobs = 1, op?:
per = usd * (p.roundUp ? Math.ceil(mp - 1e-9) : mp) * n;
}
if (p.unit === "second") {
- const seconds = clip ?? voice ?? params.duration ?? model.defaults?.duration ?? 5;
+ // A length the caller set wins (Shorts, Mixed Media and Genjutsu say the seconds they bill); then a clip edit's clip.
+ const seconds = clip ?? voice ?? params.duration ?? clipEditSeconds(model, params, op) ?? model.defaults?.duration ?? 5;
const mp = p.videoMegapixel ? videoMegapixels(model, params, seconds) : undefined;
const rate = p.videoMegapixel && (withLoras && p.videoMegapixel.withLoras !== undefined ? p.videoMegapixel.withLoras : p.videoMegapixel.usd);
per = mp !== undefined && rate ? Math.ceil(mp - 1e-9) * rate : usd * seconds;
diff --git a/src/lib/catalog/shorts-models.ts b/src/lib/catalog/shorts-models.ts
index 0f543fae..1213b5ee 100644
--- a/src/lib/catalog/shorts-models.ts
+++ b/src/lib/catalog/shorts-models.ts
@@ -4,6 +4,7 @@
* src/server/shorts.ts, src/server/mixed-media.ts); the browser gets the rows. A Fuobe Original runs on
* both engines: each answer is for the engine asked about (its default engine when none is named).
*/
+import { sourceSeconds } from "./clip-windows";
import { onEngine } from "./engines";
import { getModel } from "./index";
import { routesFor } from "./plan";
@@ -44,23 +45,8 @@ export function reframes(modelId: string, engine?: Engine): boolean {
return routes.length > 0 && routes.every((r) => r.map?.aspectRatio);
}
-/**
- * How long a clip each restyle model takes (docs/research/paid-model-apis-3.md, "Input windows"):
- * a cut outside it is paid for and then refused by the provider.
- */
-const SOURCE_SECONDS: Record<string, { min?: number; max?: number }> = {
- "kling-o3-4k-edit": { min: 3, max: 15 },
- // It reads 3–60 s but returns at most the first 15 s.
- "happy-horse-video-edit": { min: 3, max: 15 },
- "runway-aleph-2": { min: 2, max: 30 },
- "wan-2-7": { min: 2, max: 10 },
- // Higgsfield feeds Gemini Omni Flash ≤10 s segments.
- "gemini-omni-flash": { max: 10 },
-};
-
-export function sourceSeconds(modelId: string): { min?: number; max?: number } {
- return SOURCE_SECONDS[modelId] ?? {};
-}
+/** How long a clip each restyle model takes (./clip-windows): a cut outside it is paid for and then refused by the provider. */
+export { sourceSeconds };
/** The cloud model's 720p setting, when it has one (Higgsfield renders Shorts at 720p). */
export function resolutionFor(modelId: string, engine?: Engine): string | undefined {
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index 206ae763..aa285b45 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -7,6 +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 { addFrameAt, frameTimes, framesInputs, removeFrameAt, spread, type FrameSupport } from "./catalog/keyframes";
import { FACE_MOSAIC_MODELS } from "./catalog/open-tools";
import { soulPostStep } from "./catalog/soul";
@@ -264,17 +265,19 @@ export function clipOutcome(
/**
- * What the attached clip's header rules out before Generate, in the server's words (Upscale hub): a tier that
- * wouldn't enlarge the clip (one picked; a default moves up), or an open tool that holds the whole clip (FPS
- * Boost, SDR to HDR, EXR export) in more memory than half the ComfyUI's RAM (`ramBytes`, when it said).
+ * What the attached clip's header rules out before Generate, in the server's words: a clip edit outside the model's
+ * window (Edit video: Happy Horse takes 3–15 s); a tier that wouldn't enlarge the clip (Upscale hub: one picked; a
+ * default moves up), or an open tool that holds the whole clip (FPS Boost, SDR to HDR, EXR export) in more memory
+ * than half the ComfyUI's RAM (`ramBytes`, when it said).
*/
export function clipBlocker(
op: Operation | undefined,
facts: { width?: number; height?: number; fps?: number; duration?: number } | undefined,
params: GenParams,
- model: Pick<ModelDef, "engine" | "options" | "defaults"> | undefined,
+ 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 (!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/lib/studios.ts b/src/lib/studios.ts
index fa4c3cb5..ca0b04ab 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -376,6 +376,8 @@ export const VIDEO_EDIT_STUDIO: StudioConfig = {
feed: { features: ["video-edit"] },
slots: [{ key: "video", label: "Video", accept: "video", required: true }],
multiRef: { label: "Add ref", max: 4 },
+ // A clip edit that keeps the clip's length is priced on its seconds, and one outside the model's window is refused.
+ clipFacts: true,
defaultModels: { cloud: "kling-o3", open: "oss-wan22-fun-control" },
related: { href: "/genjutsu?mode=swap", label: "Swap an object or restyle it with Genjutsu" },
};
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 2338f413..0f339ba1 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -12,7 +12,8 @@ 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, keyframeChain } from "@/lib/catalog/keyframes";
-import { avatarSeconds, estimateCost, inferOperation, planGeneration, presetRoute, routeLoras, routesFor, withoutTriggers } from "@/lib/catalog/plan";
+import { clipWindowProblem } from "@/lib/catalog/clip-windows";
+import { avatarSeconds, clipEditSeconds, estimateCost, inferOperation, planGeneration, presetRoute, routeLoras, routesFor, withoutTriggers } from "@/lib/catalog/plan";
import { framedLength, keepMatte } from "@/lib/catalog/payload";
import { fitLoras, loraName, lorasFit } from "@/lib/catalog/loras";
import { dualEngine, onEngine, pickEngine } from "@/lib/catalog/engines";
@@ -1213,6 +1214,16 @@ async function submit(
if (plan.op === "avatar" && plan.params.sourceDuration === undefined && input.sourceDuration && providerId !== "mock" && plan.model.engine !== "open") {
update(id, { cost_usd: estimateCost(plan.model, { ...plan.params, sourceDuration: input.sourceDuration }, 1, plan.op, plan.loras.length > 0 && !!route.loraEndpoint) });
}
+ // A clip edit of a clip sent as it is (Edit video, an API call; the studios that cut clips keep to the windows
+ // 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);
+ 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) });
+ }
+ }
// An upscale that wouldn't enlarge the clip (a 1080p clip at a default 1080p; a 4K clip would even shrink):
// a tier the model only defaulted to moves up to the next one it offers, one the caller picked is refused.
if (plan.op === "upscale-video" && input.sourceSize) {
diff --git a/tests/e2e/fixes-5.mjs b/tests/e2e/fixes-5.mjs
index 481a4a1f..ec3b6759 100644
--- a/tests/e2e/fixes-5.mjs
+++ b/tests/e2e/fixes-5.mjs
@@ -1,7 +1,8 @@
// Fixes 5 in the browser: Settings → Training holds the AI-Toolkit URL the training messages ask for (Save & test against
// a stand-in AI-Toolkit, then cleared again), and Workflows → "Copy install commands" for the two H3 packs gives commands
-// git can run (clone + checkout of the pinned commit; the sparse copy for h3_character_swap). Then both pages at 1440
-// and 390 px, light and dark, without sideways scroll.
+// git can run (clone + checkout of the pinned commit; the sparse copy for h3_character_swap). Edit video prices Happy
+// Horse on the attached clip and refuses a 40 s one. Then both pages at 1440 and 390 px, light and dark, without
+// sideways scroll.
// Usage: node tests/e2e/fixes-5.mjs [appUrl] [--shots <dir>] (the app in demo mode). Exits 1 on a failed check.
import fs from "node:fs";
import http from "node:http";
@@ -29,6 +30,32 @@ const aitk = http.createServer((req, res) => {
await new Promise((r) => aitk.listen(0, "127.0.0.1", r));
const aitkUrl = `http://127.0.0.1:${aitk.address().port}`;
+/** A tiny MP4 header `seconds` long (one 1280×720 video track): enough for the clip's header read. */
+function mp4(seconds) {
+ const box = (type, ...body) => {
+ const data = Buffer.concat(body);
+ const head = Buffer.alloc(8);
+ head.writeUInt32BE(8 + data.length);
+ head.write(type, 4, "latin1");
+ return Buffer.concat([head, data]);
+ };
+ const mvhd = Buffer.alloc(100);
+ mvhd.writeUInt32BE(1000, 12);
+ mvhd.writeUInt32BE(seconds * 1000, 16);
+ const tkhd = Buffer.alloc(84);
+ tkhd.writeUInt32BE(0x10000, 40);
+ tkhd.writeUInt32BE(0x10000, 56);
+ tkhd.writeUInt32BE(1280 << 16, 76);
+ tkhd.writeUInt32BE(720 << 16, 80);
+ const mdhd = Buffer.alloc(24);
+ mdhd.writeUInt32BE(1000, 12);
+ mdhd.writeUInt32BE(seconds * 1000, 16);
+ const hdlr = Buffer.alloc(24);
+ hdlr.write("vide", 8, "latin1");
+ const trak = box("trak", box("tkhd", tkhd), box("mdia", box("mdhd", mdhd), box("hdlr", hdlr)));
+ return Buffer.concat([box("ftyp", Buffer.from("isom\0\0\0\0isomiso2mp41", "latin1")), box("moov", box("mvhd", mvhd), trak)]);
+}
+
const browser = await launch();
const contextFor = async (viewport = { width: 1440, height: 900 }, colorScheme = "light") => {
const context = await browser.newContext({ viewport, colorScheme, ...(viewport.width < 500 && { isMobile: true, hasTouch: true }) });
@@ -93,6 +120,42 @@ try {
await context.close();
}
+ // ---------------------------------------------------------------------------
+ // Edit video: Happy Horse priced on the attached clip's seconds ($0.28 a second at 720p), a 40 s clip refused.
+ {
+ const before = Object.fromEntries((await (await fetch(`${app}/api/settings`)).json()).settings.map((s) => [s.name, s.value]));
+ await settings({ falKey: "e2e_key_id:e2e_key_secret", demoMode: "auto" });
+ const { context, page } = await contextFor();
+ try {
+ await page.goto(`${app}/video-edit?model=happy-horse-video-edit`, { waitUntil: "load" });
+ await page.getByPlaceholder(/Describe the edit/).fill("make it snow");
+ const input = page.locator('input[type="file"][accept^="video/"]').first();
+ await input.waitFor({ state: "attached" });
+ await input.setInputFiles({ name: "clip-12.mp4", mimeType: "video/mp4", buffer: mp4(12) });
+ const priced = await page.getByText("≈ $3.36", { exact: true }).locator("visible=true").first().waitFor({ timeout: 20_000 }).then(() => true, () => false);
+ check("Edit video prices Happy Horse on the clip: 12 s × $0.28 = $3.36", priced);
+ check("a 12 s clip isn't blocked", (await page.getByRole("button", { name: "Generate", exact: true }).count()) === 1);
+ if (shots) await page.screenshot({ path: path.join(shots, "video-edit-12s-1440-light.png") });
+ await page.reload({ waitUntil: "load" });
+ await page.getByPlaceholder(/Describe the edit/).fill("make it snow");
+ await input.setInputFiles({ name: "clip-40.mp4", mimeType: "video/mp4", buffer: mp4(40) });
+ // Generate says why (its label and tooltip; a click toasts it), as for the Upscale hub's clip checks.
+ const blocked = page.getByRole("button", { name: "Generate — Happy Horse Video Edit takes 3–15 s clips, and this one is 40 s: trim it first" });
+ const said = await blocked.waitFor({ timeout: 20_000 }).then(() => true, () => false);
+ check("a 40 s clip is refused before Generate (Happy Horse returns at most 15 s)", said);
+ if (said) {
+ await blocked.click();
+ const toastSaid = page.getByText("Happy Horse Video Edit takes 3–15 s clips, and this one is 40 s: trim it first").locator("visible=true").first();
+ check("and Generate says why when pressed", await toastSaid.waitFor({ timeout: 10_000 }).then(() => true, () => false));
+ if (shots) await page.screenshot({ path: path.join(shots, "video-edit-40s-pressed-1440-light.png") });
+ }
+ if (shots) await page.screenshot({ path: path.join(shots, "video-edit-40s-1440-light.png") });
+ } finally {
+ await context.close();
+ await settings({ falKey: before.falKey ?? "", demoMode: before.demoMode ?? "auto" });
+ }
+ }
+
// ---------------------------------------------------------------------------
// Both pages at 1440 and 390 px, light and dark: nothing scrolls sideways.
for (const [width, height] of [
diff --git a/tests/edit-video-pricing.test.ts b/tests/edit-video-pricing.test.ts
new file mode 100644
index 00000000..c6a383df
--- /dev/null
+++ b/tests/edit-video-pricing.test.ts
@@ -0,0 +1,125 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+/**
+ * Edit video (the generic v2v studio) prices a clip edit that keeps the clip's length (Happy Horse, Runway Aleph,
+ * Lucy Edit, Kling O3 4K edit…: no length to ask for) on the clip's seconds, and refuses a clip outside the model's
+ * window before anything is paid for (Happy Horse reads up to 60 s but returns at most 15 s, billed for all of it).
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-edit-video-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { createGenerations, getGeneration, previewGeneration } = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { saveFile } = await import("@/server/storage");
+const { getModel } = await import("@/lib/catalog");
+const { estimateCost } = await import("@/lib/catalog/plan");
+const { clipBlocker } = await import("@/lib/composer");
+const { VIDEO_EDIT_STUDIO } = await import("@/lib/studios");
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** A tiny MP4 header `seconds` long (ftyp + moov with one 1280×720 video trak), enough for the server's header read. */
+function mp4(seconds: number): Buffer {
+ const box = (type: string, ...body: Buffer[]) => {
+ const data = Buffer.concat(body);
+ const head = Buffer.alloc(8);
+ head.writeUInt32BE(8 + data.length);
+ head.write(type, 4, "latin1");
+ return Buffer.concat([head, data]);
+ };
+ const mvhd = Buffer.alloc(100);
+ mvhd.writeUInt32BE(1000, 12);
+ mvhd.writeUInt32BE(seconds * 1000, 16);
+ const tkhd = Buffer.alloc(84);
+ tkhd.writeUInt32BE(0x10000, 40);
+ tkhd.writeUInt32BE(0x10000, 56);
+ tkhd.writeUInt32BE(1280 << 16, 76);
+ tkhd.writeUInt32BE(720 << 16, 80);
+ const mdhd = Buffer.alloc(24);
+ mdhd.writeUInt32BE(1000, 12);
+ mdhd.writeUInt32BE(seconds * 1000, 16);
+ const hdlr = Buffer.alloc(24);
+ hdlr.write("vide", 8, "latin1");
+ const trak = box("trak", box("tkhd", tkhd), box("mdia", box("mdhd", mdhd), box("hdlr", hdlr)));
+ return Buffer.concat([box("ftyp", Buffer.from("isom\0\0\0\0isomiso2mp41", "latin1")), box("moov", box("mvhd", mvhd), trak)]);
+}
+const clip = (seconds: number) => saveFile({ data: mp4(seconds), contentType: "video/mp4", name: `clip-${seconds}.mp4`, source: "upload" }).url;
+const HH = "happy-horse-video-edit";
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+});
+afterAll(() => {
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+describe("Edit video: clip edits priced on the clip, inside the model's window", () => {
+ it("prices Happy Horse on the clip's seconds ($0.28 a second at 720p), not a flat 5 s", () => {
+ const hh = getModel(HH)!;
+ expect(estimateCost(hh, { resolution: "720p", sourceDuration: 15 }, 1, "v2v")).toBeCloseTo(4.2, 5);
+ expect(estimateCost(hh, { resolution: "720p", sourceDuration: 3 }, 1, "v2v")).toBeCloseTo(0.84, 5);
+ expect(estimateCost(hh, { resolution: "1080p", sourceDuration: 12 }, 1, "v2v")).toBeCloseTo(6.72, 5);
+ // The others that keep the clip's length, priced the same way.
+ expect(estimateCost(getModel("runway-aleph-2")!, { sourceDuration: 20 }, 1, "v2v")).toBeCloseTo(0.336 * 20, 5);
+ expect(estimateCost(getModel("lucy-edit-pro")!, { sourceDuration: 7 }, 1, "v2v")).toBeCloseTo(0.15 * 7, 5);
+ // A length the caller set wins (Shorts, Mixed Media and Genjutsu say the seconds they bill); a model asked for a
+ // length keeps pricing that length.
+ expect(estimateCost(hh, { resolution: "720p", duration: 10, sourceDuration: 12 }, 1, "v2v")).toBeCloseTo(2.8, 5);
+ const ltx = getModel("ltx-2-3-22b-cloud")!;
+ expect(estimateCost(ltx, { duration: 5, sourceDuration: 12 }, 1, "v2v")).toBe(estimateCost(ltx, { duration: 5 }, 1, "v2v"));
+ // Without the clip's length (an API call that didn't say): the old guess until the server reads the header.
+ expect(estimateCost(hh, { resolution: "720p" }, 1, "v2v")).toBeCloseTo(1.4, 5);
+ });
+
+ it("the studio reads the clip's header, and Generate says when the clip is outside the model's window", () => {
+ expect(VIDEO_EDIT_STUDIO.clipFacts).toBe(true);
+ const hh = getModel(HH)!;
+ const facts = (duration: number) => ({ width: 1280, height: 720, fps: 30, duration });
+ expect(clipBlocker("v2v", facts(40), {}, hh, undefined)).toBe("Happy Horse Video Edit takes 3–15 s clips, and this one is 40 s: trim it first");
+ expect(clipBlocker("v2v", facts(2), {}, hh, undefined)).toBe("Happy Horse Video Edit takes 3–15 s clips, and this one is 2 s: use a longer one");
+ expect(clipBlocker("v2v", facts(12), {}, hh, undefined)).toBeNull();
+ expect(clipBlocker("v2v", facts(15.01), {}, hh, undefined)).toBeNull();
+ // A model with no window says nothing.
+ expect(clipBlocker("v2v", facts(40), {}, getModel("lucy-edit-pro")!, undefined)).toBeNull();
+ });
+
+ it("the server prices an API call for the clip once it reads the header, and refuses one outside the window before fal is asked", async () => {
+ setSetting("falKey", "fal_test_key_123456");
+ const real = globalThis.fetch;
+ const asked: string[] = [];
+ globalThis.fetch = (async (url: string) => {
+ asked.push(String(url));
+ return new Response(JSON.stringify({ request_id: "r1", status_url: "https://queue.fal.test/s", response_url: "https://queue.fal.test/r", cancel_url: "https://queue.fal.test/c" }), { status: 200 });
+ }) as typeof fetch;
+ const { falProvider: fal } = await import("@/server/providers/fal");
+ const upload = fal.prepareFile;
+ fal.prepareFile = async (_d, _t, name) => `https://v3.fal.media/files/${name}`;
+ try {
+ // The composer sends the clip's length: priced for it from the start.
+ expect(previewGeneration({ feature: "video-edit", modelId: HH, engine: "cloud", prompt: "make it snow", inputs: { video: clip(12) }, params: { resolution: "720p", sourceDuration: 12 } }).costUsd).toBeCloseTo(3.36, 5);
+ // An API call that didn't say: the 5 s guess, then the clip's 12 s once submit reads its header.
+ const [g] = createGenerations({ feature: "video-edit", modelId: HH, engine: "cloud", prompt: "make it snow", inputs: { video: clip(12) }, params: { resolution: "720p" } });
+ expect(g.costUsd).toBeCloseTo(1.4, 5);
+ for (let i = 0; i < 200 && getGeneration(g.id)!.costUsd !== 3.36; i++) await sleep(25);
+ expect(getGeneration(g.id)!.costUsd).toBeCloseTo(3.36, 5);
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(g.id);
+ // 40 s: refused before anything goes to fal.
+ asked.length = 0;
+ const [long] = createGenerations({ feature: "video-edit", modelId: HH, engine: "cloud", prompt: "make it snow", inputs: { video: clip(40) }, params: { resolution: "720p" } });
+ for (let i = 0; i < 200 && getGeneration(long.id)!.status !== "failed"; i++) await sleep(25);
+ expect(getGeneration(long.id)).toMatchObject({ status: "failed", error: expect.stringMatching(/takes 3–15 s clips, and this one is 40 s/) });
+ expect(asked.filter((u) => u.includes("happy-horse"))).toEqual([]);
+ } finally {
+ globalThis.fetch = real;
+ fal.prepareFile = upload;
+ setSetting("falKey", "");
+ }
+ });
+});