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.

MiniMax H3 at 2K: offered only in the Video studio and Cinema, and the saved-latent finish is the server's to decide

Claude1be4e739a5cb
diff --git a/src/app/api/cinema/projects/[id]/items/[generationId]/finish/route.ts b/src/app/api/cinema/projects/[id]/items/[generationId]/finish/route.ts
index 96845fee..969564a7 100644
--- a/src/app/api/cinema/projects/[id]/items/[generationId]/finish/route.ts
+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/finish/route.ts
@@ -1,10 +1,24 @@
-import { finishTake } from "@/server/cinema";
+import { CinemaError, finishTake } from "@/server/cinema";
import { handle } from "@/server/cinema-schemas";
+import { once } from "@/server/shorts-schemas";
-/** Finish in 2K: a MiniMax H3 take made again at 2K (fal), or redrawn at 2K on your GPU (Open-H3 Regenerate), same folder. */
+/**
+ * Finish in 2K: a MiniMax H3 take made again at 2K (fal), or redrawn at 2K on your GPU (Open-H3 Regenerate), same folder.
+ * The body may carry a requestId: a repeat of it (a double click, a retried POST) gets the first answer, not a second run.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/finish">) {
return handle(async () => {
const { id, generationId } = await ctx.params;
- return Response.json({ items: finishTake(id, generationId) }, { status: 201 });
+ const text = await request.text().catch(() => "");
+ let body: unknown = {};
+ try {
+ body = text.trim() ? JSON.parse(text) : {};
+ } catch {
+ throw new CinemaError("That request body isn't JSON", 400);
+ }
+ const asked = (body as { requestId?: unknown } | null)?.requestId;
+ if (asked !== undefined && !(typeof asked === "string" && /^[\w-]{1,64}$/.test(asked))) throw new CinemaError("Bad request", 400);
+ const items = await once(`cinema-finish:${id}:${generationId}`, asked, () => finishTake(id, generationId));
+ return Response.json({ items }, { status: 201 });
}, request);
}
diff --git a/src/app/api/palettes/lock/route.ts b/src/app/api/palettes/lock/route.ts
index 53931544..dc0f2986 100644
--- a/src/app/api/palettes/lock/route.ts
+++ b/src/app/api/palettes/lock/route.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { createLockedRun, SignatureSchema } from "@/server/palettes";
+import { ClientExtra } from "@/server/request-schema";
const Hex = z.string().regex(/^#?[0-9a-fA-F]{6}$/);
@@ -24,7 +25,7 @@ const RequestSchema = z.object({
enhancePrompt: z.boolean().optional(),
palette: z.array(Hex).max(16).optional(),
styleId: z.string().max(200).optional(),
- extra: z.record(z.string(), z.unknown()).optional(),
+ extra: ClientExtra.optional(),
})
.optional(),
signature: SignatureSchema,
diff --git a/src/components/cinema/cinema-feed.tsx b/src/components/cinema/cinema-feed.tsx
index acef44b7..40c860c2 100644
--- a/src/components/cinema/cinema-feed.tsx
+++ b/src/components/cinema/cinema-feed.tsx
@@ -29,7 +29,7 @@ import {
} from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
-import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
+import { createContext, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
import { Checkbox } from "@/components/ui/checkbox";
import {
@@ -58,7 +58,8 @@ import type { CinemaFolder } from "@/lib/catalog/cinema";
import type { Generation, OutputFile } from "@/lib/catalog/types";
import { formatCost, timeAgo } from "@/lib/format";
import { useEngineMode } from "@/lib/api";
-import { finishIn2k } from "@/lib/catalog/regenerate";
+import { finishedTakes, finishIn2k } from "@/lib/catalog/regenerate";
+import { useSubmitGuard } from "@/components/shorts/hooks";
import { cn } from "@/lib/utils";
import { copyWithToast } from "@/lib/clipboard";
import { toastError } from "@/lib/refusals";
@@ -190,13 +191,20 @@ export function deleteLabel(g: CinemaGeneration): string {
return tiles ? `Delete grid (sheet + ${tiles} tiles)` : "Delete take";
}
+/** The takes the feed's list already finishes in 2K (finishedTakes). */
+const FinishedIn2k = createContext<Set<string>>(new Set());
+
function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; folders: CinemaFolder[]; projectId: string; handlers: FeedHandlers; onDelete: (ids: string[]) => void }) {
const actions = useItemActions(projectId);
const engineMode = useEngineMode();
+ const finished = useContext(FinishedIn2k);
+ // One paid submit at a time, with a nonce the server answers a repeat with (a double click is one 2K render).
+ const guard = useSubmitGuard();
const o = u.output;
const elsewhere = foreign(u.g, projectId);
- // Finish in 2K: a MiniMax H3 take below 2K (fal renders it again at 2K; your GPU redraws it with Open-H3 Regenerate).
- const finish = o?.kind === "video" && !u.tile ? finishIn2k(u.g, engineMode) : null;
+ // Finish in 2K: a MiniMax H3 take below 2K (fal renders it again at 2K; your GPU redraws it with Open-H3 Regenerate),
+ // once: not on a take whose 2K finish is under way or made (a 2K run's own 768p draft included).
+ const finish = o?.kind === "video" && !u.tile && !finished.has(u.g.id) ? finishIn2k(u.g, engineMode) : null;
const seconds = Number(u.g.request.params?.duration ?? 0);
const finishPrice = !finish ? "" : finish.perSecond === null ? "Free" : seconds > 0 ? `≈ ${formatCost(finish.perSecond * seconds)}` : `$${finish.perSecond.toFixed(2)}/s`;
return (
@@ -257,9 +265,8 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold
{finish && (
<DropdownMenuItem
onClick={() =>
- void actions
- .finish2k(u.g)
- .then(() => toast(finish.perSecond === null ? "Finishing in 2K on your GPU" : "Rendering it again at 2K"))
+ void guard(`finish-2k:${u.g.id}`, (requestId) => actions.finish2k(u.g, requestId))
+ .then((done) => done !== undefined && toast(finish.perSecond === null ? "Finishing in 2K on your GPU" : "Rendering it again at 2K"))
.catch((e) => toastError(e))
}
>
@@ -587,6 +594,8 @@ export function CinemaFeed({
const [prefs, setPrefs] = usePrefs();
const actions = useItemActions(projectId);
const qc = useQueryClient();
+ // Takes with a 2K finish under way or made: their menus don't offer Finish in 2K again.
+ const finished = useMemo(() => finishedTakes(items), [items]);
// Stills on Fuobe Soul Cinema and Soul Location's Movie look finish in the browser (the 21:9 crop, the grade).
useSoulFinish(items, CINEMA_KEY);
const [selected, setSelected] = useState<Set<string>>(new Set());
@@ -674,6 +683,7 @@ export function CinemaFeed({
] as const;
return (
+ <FinishedIn2k.Provider value={finished}>
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-2">
<div className="min-w-0 basis-full sm:basis-auto sm:flex-1">{title}</div>
@@ -843,5 +853,6 @@ export function CinemaFeed({
)}
</div>
+ </FinishedIn2k.Provider>
);
}
diff --git a/src/components/cinema/hooks.ts b/src/components/cinema/hooks.ts
index afa7498a..b660b285 100644
--- a/src/components/cinema/hooks.ts
+++ b/src/components/cinema/hooks.ts
@@ -237,8 +237,9 @@ export function useItemActions(projectId: string) {
await send(`/api/cinema/projects/${g.projectId ?? projectId}/items/${g.id}/retry`, "POST").finally(settle);
},
/** Finish in 2K: a MiniMax H3 take made again at 2K (fal) or redrawn at 2K on your GPU, in the same folder. */
- finish2k: async (g: CinemaGeneration) => {
- await send(`/api/cinema/projects/${g.projectId ?? projectId}/items/${g.id}/finish`, "POST").finally(settle);
+ finish2k: async (g: CinemaGeneration, requestId?: string) => {
+ await send(`/api/cinema/projects/${g.projectId ?? projectId}/items/${g.id}/finish`, "POST", requestId ? { requestId } : undefined).finally(settle);
+ return true;
},
saveTiles: async (generationId: string, tiles: CinemaTile[]) => {
await send(`/api/cinema/projects/${projectId}/items/${generationId}/tiles`, "PUT", { tiles });
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index 562834ad..f01a75ed 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -33,6 +33,7 @@ import { editableLayout, EDIT_LAYOUT_PARAM, readEditLayoutParam } from "@/lib/ou
import { positionsFrom, spread } from "@/lib/catalog/keyframes";
import { reuseSignature, withSignatureWords } from "@/lib/catalog/palettes";
import { movedAppRequest } from "@/lib/catalog/plan";
+import { studioResolutions } from "@/lib/catalog/regenerate";
import { currentModelId, migrateRequest } from "@/lib/catalog/replaced";
import { matchSpokenLanguage } from "@/lib/speech-languages";
import { SoulPresetCards } from "@/components/moodboards/soul-preset-cards";
@@ -146,7 +147,7 @@ function initialDraft(
// An output format handed over in the link (Export → "ProRes in the cloud"), when the model writes it.
const format = model?.options.formats?.find((f) => f === sp.get("format"));
// A size handed over (Regenerate in 2K → 1440p), when the model offers it.
- const resolution = model?.options.resolutions?.find((r) => r === sp.get("resolution"));
+ const resolution = studioResolutions(model?.options)?.find((r) => r === sp.get("resolution"));
// Stills handed over as frames (Storyboard's "Animate these panels", a Character Sheet's poses): Frames mode, evenly spaced.
const handed = config.frames ? handoffFrames(sp.get("frames")) : [];
const frames = handed.length ? handed.map((u, i) => ({ value: slot(u)!, at: spread(handed.length)[i] })) : undefined;
diff --git a/src/lib/catalog/cinema.ts b/src/lib/catalog/cinema.ts
index f20cb17c..d95b5ff1 100644
--- a/src/lib/catalog/cinema.ts
+++ b/src/lib/catalog/cinema.ts
@@ -7,6 +7,7 @@ import { DOP_MODEL, LTX25_HOSTED } from "./dop";
import { dualEngine, onEngine } from "./engines";
import { localOnly, needsToken, triggerOf } from "./loras";
import { QMA_MODEL, qmaLabel, qmaView } from "@/lib/qma";
+import { studioResolutions } from "./regenerate";
import { ANGLES_2511_LORA } from "./open-tools";
import { composeShots, estimateCost, planGeneration, routesFor } from "./plan";
import { soulRecipe } from "./soul";
@@ -625,7 +626,7 @@ export const H3_2K_TIER = "2K";
/** Cinema's video tiers for a model: 480p / 720p / 1080p, and 2K for the MiniMax H3 models that offer it. */
export function videoResolutionsFor(model: Pick<ModelDef, "family" | "options"> | undefined): string[] {
- const twoK = !!model && (model.family === "minimax-h3" || model.family === "hailuo") && (model.options.resolutions ?? []).some((r) => r.toLowerCase() === "2k");
+ const twoK = !!model && (model.family === "minimax-h3" || model.family === "hailuo") && (studioResolutions(model.options) ?? []).some((r) => r.toLowerCase() === "2k");
return twoK ? [...VIDEO_RESOLUTIONS, H3_2K_TIER] : VIDEO_RESOLUTIONS;
}
@@ -1380,21 +1381,23 @@ function fitParams(model: ModelDef, input: CinemaGenerateInput, notes: string[],
notes.push(`${model.name} doesn't make ${ar} — using ${params.aspectRatio}`);
} else if (o.aspectRatios?.length || ar) params.aspectRatio = ar;
const res = input.resolution;
- if (res && o.resolutions?.length) {
- if (o.resolutions.includes(res)) params.resolution = res;
- else if (IMAGE_TIER[res] && o.resolutions.includes(IMAGE_TIER[res])) {
+ // A video's tiers include the ones a finishing pass reaches (MiniMax H3's 2K on your GPU), as the Resolution chip shows them.
+ const tiers = (kind === "video" ? studioResolutions(o) : o.resolutions) ?? [];
+ if (res && tiers.length) {
+ if (tiers.includes(res)) params.resolution = res;
+ else if (IMAGE_TIER[res] && tiers.includes(IMAGE_TIER[res])) {
params.resolution = IMAGE_TIER[res];
if (res === "4K") notes.push(`${model.name} makes up to about 2 megapixels (its ${params.resolution} size)`);
- } else if (kind === "video" && videoTier(o.resolutions, res)) {
- const tier = videoTier(o.resolutions, res)!;
+ } else if (kind === "video" && videoTier(tiers, res)) {
+ const tier = videoTier(tiers, res)!;
params.resolution = tier;
if (tier.toLowerCase() !== res.toLowerCase()) {
notes.push(tierHeight(tier)! < tierHeight(res)! ? `${model.name} renders up to ${tier} here` : `${model.name} renders at ${tier} here`);
}
} else {
const order = kind === "video" ? VIDEO_RESOLUTIONS : [...IMAGE_RESOLUTIONS, "0.5K", "1.5K", "720p", "1080p"];
- const below = o.resolutions.filter((r) => order.indexOf(r) <= order.indexOf(res) && order.indexOf(r) >= 0);
- params.resolution = below.sort((a, b) => order.indexOf(b) - order.indexOf(a))[0] ?? o.resolutions[0];
+ const below = tiers.filter((r) => order.indexOf(r) <= order.indexOf(res) && order.indexOf(r) >= 0);
+ params.resolution = below.sort((a, b) => order.indexOf(b) - order.indexOf(a))[0] ?? tiers[0];
notes.push(`${model.name} renders up to ${params.resolution} here`);
}
}
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index ac303d34..f2357faa 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -634,8 +634,10 @@ const open: ModelDef[] = [
options: {
aspectRatios: ["auto", "16:9", "9:16", "1:1", "4:3", "3:4"],
durations: [3, 5, 10, 15],
- // 2K: a 768p draft, then Open-H3 Regenerate at 2K from it (from its latent for text to video), on your GPU only.
- resolutions: ["768p", "2K"],
+ resolutions: ["768p"],
+ // 2K in the Video studio and Cinema only: a 768p draft, then Open-H3 Regenerate at 2K from it (from its latent for
+ // text to video), on your GPU (n7-10).
+ finishTiers: ["2K"],
seed: true,
endFrame: true,
audio: "always",
diff --git a/src/lib/catalog/regenerate.ts b/src/lib/catalog/regenerate.ts
index a7657e86..d5d07460 100644
--- a/src/lib/catalog/regenerate.ts
+++ b/src/lib/catalog/regenerate.ts
@@ -7,7 +7,7 @@
* Nobody hosts the open model, so Regenerate · creative is GPU-only: the cloud engine says it runs on your GPU, and
* Engine mode "Paid APIs only" hides it (the owner's rule of 10-30).
*/
-import type { ChainSlot, Generation, GenerationRequest, LoraRef } from "./types";
+import type { ChainSlot, Generation, GenerationRequest, LoraRef, ModelOptions } from "./types";
export const REGEN_MODEL = "oss-h3-regenerate";
export const REGEN_WORKFLOW = "video-regenerate-h3";
@@ -214,7 +214,7 @@ export function regenFinishSteps(o: FinishStepsInput): { steps: FinishStep[]; fi
/** Edit video's results get "Enhance (H3 regenerate)" (a clip of at most 15 s, one pass). */
export const ENHANCE_FEATURES = new Set(["video-edit"]);
-export const ENHANCE_LABEL = "Enhance (H3 regenerate) · 1080p";
+export const ENHANCE_LABEL = "Enhance (H3 regenerate) · 1080p · on your GPU";
/** Whether a finished video result gets "Enhance (H3 regenerate)": an Edit video result up to 15 s (unknown counts). */
export function canEnhance(g: Pick<Generation, "feature" | "status" | "request">, o: { kind: string; meta?: Record<string, unknown> }, engineMode?: "both" | "open" | "cloud"): boolean {
@@ -250,6 +250,15 @@ export const REGEN_LATENT_WORKFLOW = "video-regenerate-h3-latent";
/** Regenerate's tier for a 2K take (the shorter edge: 2560 x 1440). */
export const H3_FINISH_TIER = "1440p";
+/**
+ * The tiers the Video studio and Cinema offer for a model: its own, then the ones a finishing pass reaches
+ * (ModelOptions.finishTiers: MiniMax H3's 2K on your GPU). Every other tier picker reads `resolutions` alone.
+ */
+export function studioResolutions(o: Pick<ModelOptions, "resolutions" | "finishTiers"> | undefined): string[] | undefined {
+ if (!o?.finishTiers?.length) return o?.resolutions;
+ return [...(o.resolutions ?? []), ...o.finishTiers.filter((t) => !o.resolutions?.includes(t))];
+}
+
/** Whether a request asks the open MiniMax H3 model for its 2K tier. */
export function wantsH3TwoK(modelId: string | undefined, resolution: string | undefined): boolean {
return modelId === H3_OPEN_MODEL && /^(2k|1440p)$/i.test(resolution ?? "");
@@ -260,19 +269,43 @@ export const latentPrefixFor = (generationId: string) => `fuobe_h3_${generationI
/** The file the finish loads: the pack numbers each prefix's files from 00001. */
export const latentFileFor = (generationId: string) => `${latentPrefixFor(generationId)}_00001.safetensors`;
+/**
+ * Server-only flags of the 2K hand-off (params.extra), never taken from a client (the request schemas drop them):
+ * `latentDraft` makes a text-to-video draft keep its 768p latent, `latentFrom` names the run whose latent a finish loads.
+ * The server checks both again when the run starts (src/server/generations.ts latentHandOff).
+ */
+export const LATENT_EXTRA = ["latentDraft", "latentFrom"] as const;
+
+/** lightx2v's FL2V Turbo 4-step v1.2 LoRA, which the 768p draft that keeps its latent loads itself (rdh's "Prompt to 2K"). */
+export const H3_TURBO_4STEP_LORA: LoraRef = {
+ file: "minimax_h3_fl2v_turbo_4step_v1.2_768p_comfyui_bf16.safetensors",
+ url: "https://huggingface.co/lightx2v/Minimax-h3-Turbo/resolve/3ec17a324ced54151364f24f8b5fb6bf7e26414f/minimax_h3_fl2v_turbo_4step_v1.2_768p_comfyui_bf16.safetensors",
+ version: "3ec17a324ced54151364f24f8b5fb6bf7e26414f",
+ licence: { commercial: true, hostedOk: true, snapshotDate: "2026-10-30", name: "Apache-2.0" },
+};
+
+/** Its licence as Settings → Models & licences shows it (Apache-2.0 in its card at the pinned revision). */
+export const H3_TURBO_4STEP_INFO = {
+ name: "MiniMax H3 FL2V Turbo 4-step v1.2 (lightx2v)",
+ url: "https://huggingface.co/lightx2v/Minimax-h3-Turbo/blob/3ec17a324ced54151364f24f8b5fb6bf7e26414f/README.md",
+ note: "Apache-2.0 at the pinned revision (3ec17a3); the current card no longer states a licence. MiniMax H3 at 2K drafts with it on your GPU",
+} as const;
+
/**
* The two steps of an open MiniMax H3 take at 2K: the take at 768p, then Open-H3 Regenerate at 2K from it, from the same
- * words, near the draft (sigma 0.8) with the 768p preset. Text to video drafts on the graph that keeps its latent, and the
- * finish starts from that latent (the server names it after the draft); a take from a start frame is finished from its clip.
+ * words, near the draft (sigma 0.8) with the 768p preset. Text to video drafts on the graph that keeps its latent (unless
+ * `keepLatent` is false: its Turbo 4-step LoRA is switched off), and the finish may start from that latent: the server
+ * decides when it starts (the draft's latent must be on the ComfyUI the finish runs on). Otherwise, and for a take from a
+ * start frame, the finish redraws the draft's clip.
*/
-export function h3TwoKRequests(original: GenerationRequest, op: string): { draft: GenerationRequest; finish: GenerationRequest; fromLatent: boolean } {
- const fromLatent = op === "t2v";
+export function h3TwoKRequests(original: GenerationRequest, op: string, o: { keepLatent?: boolean } = {}): { draft: GenerationRequest; finish: GenerationRequest; fromLatent: boolean } {
+ const fromLatent = op === "t2v" && o.keepLatent !== false;
const params = original.params ?? {};
const draft: GenerationRequest = {
...original,
op: op as GenerationRequest["op"],
params: { ...params, resolution: "768p", numOutputs: 1, extra: { ...params.extra, ...(fromLatent ? { latentDraft: true } : {}) } },
- step: { label: "768p draft", index: 0, of: 2 },
+ step: { label: H3_DRAFT_STEP, index: 0, of: 2 },
};
const finish: GenerationRequest = {
feature: original.feature,
@@ -284,11 +317,18 @@ export function h3TwoKRequests(original: GenerationRequest, op: string): { draft
...(original.demo && { demo: true }),
params: { resolution: H3_FINISH_TIER, numOutputs: 1, ...(params.duration ? { sourceDuration: params.duration } : {}), extra: { startSigma: REGEN_FINISH_SIGMA, draftFrom: "h3" } },
chain: [{ slot: "video" }],
- step: { label: "Finished in 2K", index: 1, of: 2 },
+ step: { label: H3_FINISH_STEP, index: 1, of: 2 },
};
return { draft, finish, fromLatent };
}
+/** The step names of a 2K take: the draft, and the take finished from it. */
+export const H3_DRAFT_STEP = "768p draft";
+export const H3_FINISH_STEP = "Finished in 2K";
+
+/** Said under a 2K run's price on your GPU (previews and the plan). */
+export const H3_2K_STEPS_NOTE = "Each take is drafted at 768p, then redrawn at 2K by Open-H3 Regenerate on your GPU";
+
/** The open H3 takes "Finish in 2K" offers to finish (a take from your GPU, made below 2K). */
export function canFinishOpen(g: Pick<Generation, "engine" | "modelId" | "status" | "kind" | "request">, engineMode?: "both" | "open" | "cloud"): boolean {
if (engineMode === "cloud" || g.engine !== "open" || g.kind !== "video" || g.status !== "succeeded" || !isH3Source(g.modelId) || g.modelId === REGEN_MODEL) return false;
@@ -300,10 +340,12 @@ export function canFinishOpen(g: Pick<Generation, "engine" | "modelId" | "status
* your GPU is redrawn at 2K by Open-H3 Regenerate (free), from its saved latent when its draft kept one. null: not offered.
*/
export function finishIn2k(g: Pick<Generation, "id" | "engine" | "provider" | "modelId" | "status" | "request" | "kind" | "outputs" | "op" | "feature">, engineMode?: "both" | "open" | "cloud"): { request: GenerationRequest; label: string; perSecond: number | null } | null {
- if (canRerender(g, engineMode)) return { request: rerenderRequest(g), label: "Finish in 2K", perSecond: RERENDER[g.modelId].perSecond["2K"] };
+ if (canRerender(g, engineMode)) return { request: { ...rerenderRequest(g), finishOf: g.id }, label: "Finish in 2K", perSecond: RERENDER[g.modelId].perSecond["2K"] };
if (!canFinishOpen(g, engineMode)) return null;
const video = g.outputs.find((o) => o.kind === "video")?.url;
if (!video) return null;
+ // The draft's latent when it kept one: the server uses it only if it is still on the ComfyUI this finish runs on, and
+ // redraws the clip otherwise.
const latent = g.request.params?.extra?.latentDraft === true;
return {
request: {
@@ -313,12 +355,18 @@ export function finishIn2k(g: Pick<Generation, "id" | "engine" | "provider" | "m
...(g.request.prompt?.trim() ? { prompt: g.request.prompt.trim() } : {}),
inputs: { video },
params: { resolution: H3_FINISH_TIER, numOutputs: 1, extra: { startSigma: REGEN_FINISH_SIGMA, ...(latent ? { latentFrom: g.id, draftFrom: "h3" } : {}) } },
+ finishOf: g.id,
},
label: "Finish in 2K",
perSecond: null,
};
}
+/** The takes a list already finishes in 2K (a finish under way or made): "Finish in 2K" isn't offered on them again. */
+export function finishedTakes(list: Pick<Generation, "status" | "request">[]): Set<string> {
+ return new Set(list.flatMap((g) => (g.request.finishOf && g.status !== "failed" && g.status !== "canceled" ? [g.request.finishOf] : [])));
+}
+
/** The note for a clip that isn't 16:9 or 9:16. */
export function regenCropNote(width: number, height: number): string {
return `Regenerate makes ${regenShape(width, height)} video, so this ${width}×${height} clip is cropped to ${regenShape(width, height)} at the centre`;
@@ -344,6 +392,8 @@ export const REGEN_COPY = {
off: "Regenerate isn't available right now. Pick Restore · faithful to sharpen the clip instead.",
gpuOnly: "Runs on your GPU (open source)",
prompt: "Describe the clip: what is in it, how it moves, the light. Regenerate redraws it from these words",
+ /** A 2K finish whose draft's saved copy is gone from the GPU (a retry redraws the draft's clip instead). */
+ latentGone: "The 768p draft's saved copy isn't on this GPU any more. Press Retry to finish it from the draft's clip.",
} as const;
/** The two finishing choices Upscale → Video shows side by side on the open engine. */
@@ -367,8 +417,11 @@ export const REGEN_LORA: LoraRef = {
};
/** The LoRA files a Regenerate graph loads itself, so a run downloads the ones ComfyUI lacks before it starts. */
-export function regenerateGraphLoras(endpoint: string): LoraRef[] {
- return endpoint === REGEN_WORKFLOW || endpoint === "video-regenerate-h3-latent" ? [REGEN_LORA] : [];
+export function regenerateGraphLoras(endpoint: string, extra?: Record<string, unknown>): LoraRef[] {
+ if (endpoint === REGEN_WORKFLOW || endpoint === REGEN_LATENT_WORKFLOW) return [REGEN_LORA];
+ // The 2K tier's 768p draft that keeps its latent (MiniMax H3's text to video with latentDraft) loads the Turbo 4-step LoRA.
+ if (endpoint === H3_LATENT_DRAFT_WORKFLOW || (endpoint === "minimax-h3-t2v" && extra?.latentDraft === true)) return [H3_TURBO_4STEP_LORA];
+ return [];
}
/** The new files and their licences, as the research recorded them (§2.4, §2.5). */
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 3fba4dd1..6f83b796 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -631,6 +631,12 @@ export interface ModelOptions {
inbetween?: true;
aspectRatios?: string[];
resolutions?: string[];
+ /**
+ * Tiers a finishing pass reaches after the model's own render, offered only where the brief puts them (the Video
+ * studio and Cinema, through studioResolutions): MiniMax H3's 2K on your GPU is a 768p draft redrawn by Open-H3
+ * Regenerate. Tier pickers elsewhere (Faceless, Canvas, Assist, Ad Multiplier) keep to `resolutions`.
+ */
+ finishTiers?: string[];
durations?: number[];
/** Max outputs per request the model supports natively. */
maxOutputs?: number;
@@ -1159,6 +1165,11 @@ export interface GenerationRequest {
* (src/server/chains.ts createMosaicRun), so it doesn't start another.
*/
postMade?: boolean;
+ /**
+ * Server-set: the take this run finishes in 2K (MiniMax H3's 2K tier, or "Finish in 2K" on a take; package n7-10), so a
+ * take that has a 2K finish under way or made isn't offered another (src/server/cinema.ts finishTake).
+ */
+ finishOf?: string;
/** Server-set: what the user calls this result, shown instead of the prompt (Library, feeds). */
title?: string;
/** Server-set: the name of the batch it belongs to (an Assist plan's summary): the Library stack's title. */
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index 051ea777..20e4ca23 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -14,6 +14,7 @@ import { keyTimes, totalSeconds, type InbetweenTiming } from "./inbetween";
import { FACE_MOSAIC_MODELS } from "./catalog/open-tools";
import { pricingOn, type PriceClock } from "./catalog/promo";
import { soulPostStep } from "./catalog/soul";
+import { studioResolutions } from "./catalog/regenerate";
import { appModels, ownRoute, presetRoutes, type HasModel, type RecipePreset } from "./catalog/preset-recipe-routes";
import { COLORMAPS, type Engine, type GenParams, type InputSlot, type MatteOutput, type MediaKind, type ModelDef, type Operation, type Preset, type PresetRoute, type VideoFormat } from "./catalog/types";
import { formatCost } from "./format";
@@ -91,7 +92,8 @@ export function settingsShape(
const shaped = routes.length > 0 && routes.every((r) => r.unsized || r.followsImage);
return {
aspect: !sized || shaped || op === "i2v" || op === "flf2v" ? null : many(o.aspectRatios),
- resolution: sized ? many(o.resolutions) : null,
+ // With the tiers a finishing pass reaches (MiniMax H3's 2K on your GPU: a 768p draft redrawn by Open-H3 Regenerate).
+ resolution: sized ? many(studioResolutions(o)) : null,
duration: params.shots ? null : many(o.durations),
count: (kind === "image" || kind === "video") && !single,
draft: !!o.draft,
diff --git a/src/server/canvas.ts b/src/server/canvas.ts
index 0c99062a..12a56a6e 100644
--- a/src/server/canvas.ts
+++ b/src/server/canvas.ts
@@ -48,6 +48,7 @@ import {
} from "@/lib/catalog/canvas";
import type { Engine, Generation, GenerationRequest, MediaKind } from "@/lib/catalog/types";
import { readLayout } from "@/lib/layout-prompt";
+import { LATENT_EXTRA } from "@/lib/catalog/regenerate";
import { createPipeline } from "./chains";
import { db } from "./db";
import { listElements } from "./elements";
@@ -129,7 +130,11 @@ const Params = z.object({
voice: z.string().max(200).optional(),
targetLanguage: z.string().max(80).optional(),
sourceLanguage: z.string().max(80).optional(),
- extra: z.record(z.string(), z.union([z.string().max(2000), z.number(), z.boolean()])).optional(),
+ // Less the server's own (MiniMax H3's 2K hand-off), as POST /api/generations drops them.
+ extra: z
+ .record(z.string(), z.union([z.string().max(2000), z.number(), z.boolean()]))
+ .transform((extra) => Object.fromEntries(Object.entries(extra).filter(([k]) => !(LATENT_EXTRA as readonly string[]).includes(k))))
+ .optional(),
});
/** Free text is clamped, not refused: one over-long paste must never stop the whole board from saving. */
diff --git a/src/server/cinema.ts b/src/server/cinema.ts
index 1c41c993..a6478e96 100644
--- a/src/server/cinema.ts
+++ b/src/server/cinema.ts
@@ -716,6 +716,8 @@ export function finishTake(projectId: string, generationId: string): Generation[
if (!row || !g) throw new CinemaError("That take isn't in this project", 404);
const finish = finishIn2k(g, engineMode());
if (!finish) throw new CinemaError("Finish in 2K is for finished MiniMax H3 takes made below 2K", 422);
+ // Once per take: a 2K finish under way or made (this action's, or the 2K run's own finish of its draft) isn't repeated.
+ if (finishedIn2k(generationId)) throw new CinemaError("This take already has a 2K finish", 409);
const project = getProject(projectId);
let cost = 0;
try {
@@ -741,6 +743,16 @@ export function finishTake(projectId: string, generationId: string): Generation[
return made;
}
+/** Whether a take has a 2K finish that hasn't failed (request.finishOf; one in the Trash doesn't count). */
+function finishedIn2k(generationId: string): boolean {
+ return !!db()
+ .prepare(
+ `SELECT 1 FROM generations g LEFT JOIN generation_trash t ON t.generation_id = g.id
+ WHERE json_extract(g.request_json, '$.finishOf') = ? AND g.status NOT IN ('failed', 'canceled') AND t.deleted_at IS NULL LIMIT 1`,
+ )
+ .get(generationId);
+}
+
export function setTiles(projectId: string, generationId: string, tiles: CinemaTile[]): CinemaItem {
const r = itemRow(projectId, generationId);
if (!r) throw new CinemaError("That take isn't in this project", 404);
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 12a26043..38f9302a 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -59,15 +59,15 @@ import { BLOCKED_CARD_MESSAGE, looksBlocked } from "./safety-card";
import { pollTrainings } from "./training";
import { createEndFrameClip, createExtendChain, createKeyframeFilm, createMosaicRun, createRefinedModel, createRelitClip, createShotFilm, createStillTo3d, joinClips } from "./chains";
import { chainedRefine } from "@/lib/av/hi3d";
-import { createH3TwoKRun, createRegenerateRun } from "./regenerate";
+import { createH3TwoKRun, createRegenerateRun, keepsH3Latent, regenSwitchedOff } from "./regenerate";
import { createVoiceFirstRun, voiceFirstPlanFor } from "./voice-first";
import { BED_NOTES, VOICE_FIRST_LABEL } from "@/lib/av/voice-first";
-import { REGEN_MODEL, regenerateGraphLoras, wantsH3TwoK } from "@/lib/catalog/regenerate";
+import { H3_2K_STEPS_NOTE, h3TwoKRequests, REGEN_COPY, REGEN_MODEL, regenerateGraphLoras, wantsH3TwoK } from "@/lib/catalog/regenerate";
import { enhancePrompt, enhanceSoulWords, ideogramCaption } from "./enhance";
import { carriesLayout } from "@/lib/layout-prompt";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
-import { comfyLoraFiles, computerScope, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, probeComfy, relayFile, type OwnGpu } from "./providers/comfyui";
+import { comfyLoraFiles, comfyPlace, computerScope, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, probeComfy, relayFile, type OwnGpu } from "./providers/comfyui";
import { accountById, accountGpu, gpuLink, type AccountGpu } from "./auth";
import { accountEngineMode, accountKey, paidAllowed } from "./account-keys";
import { addKeyMessage, isCloudProvider, keyRemovedMessage, type CloudProvider } from "@/lib/your-keys";
@@ -841,7 +841,7 @@ function prepare(original: GenerationRequest) {
}
/** The LoRA files a graph loads itself (not injected), so a run downloads the ones ComfyUI lacks before it starts. */
-const graphLoras = (endpoint: string, extra: Record<string, unknown> | undefined) => [...h3GraphLoras(endpoint, extra), ...restoreGraphLoras(endpoint, extra), ...regenerateGraphLoras(endpoint)];
+const graphLoras = (endpoint: string, extra: Record<string, unknown> | undefined) => [...h3GraphLoras(endpoint, extra), ...restoreGraphLoras(endpoint, extra), ...regenerateGraphLoras(endpoint, extra)];
/** Operations whose clip length is the duration picked (made, or added by extend), not an input video's. */
const MADE_LENGTH_OPS = new Set<Operation>(["t2v", "i2v", "flf2v", "ref2v", "extend", "keyframes"]);
@@ -866,8 +866,14 @@ export function previewGeneration(asked: GenerationRequest) {
if (voiced.costUsd !== null) post += voiced.costUsd;
notes.push(...voiced.notes);
}
+ // MiniMax H3 at 2K on your GPU: each take's Open-H3 Regenerate finish is planned and priced beside its draft.
+ const twoK = h3TwoKExtra(moved.request, plan.model, plan.op);
+ if (twoK) {
+ if (twoK.costUsd !== null) post += twoK.costUsd;
+ notes.push(...twoK.notes);
+ }
// A clean-voice step whose price isn't known leaves the run's price unknown too, never the main step's alone.
- const priceUnknown = cost === null || voiced?.costUsd === null;
+ const priceUnknown = cost === null || voiced?.costUsd === null || twoK?.costUsd === null;
return {
model: plan.model,
op: plan.op,
@@ -876,8 +882,9 @@ export function previewGeneration(asked: GenerationRequest) {
demo,
providerId,
costUsd: priceUnknown || cost === null ? null : post ? Math.round((cost * plan.jobs + post) * 1000) / 1000 : cost * plan.jobs,
- // The other steps the run makes beside its own model (Clean the voice first's), so a policy and a price see them all.
- ...(voiced?.steps.length && { steps: voiced.steps }),
+ // The other steps the run makes beside its own model (Clean the voice first's, a 2K take's finish), so a policy and a
+ // price see them all.
+ ...((voiced?.steps.length || twoK?.steps.length) && { steps: [...(voiced?.steps ?? []), ...(twoK?.steps ?? [])] }),
// The engine it runs on (a Fuobe Original picks one per request).
engine: plan.model.engine,
// What the route runs (the evaluation harness records it): the provider endpoint, the final prompt and the LoRAs it loads.
@@ -893,6 +900,24 @@ export function previewGeneration(asked: GenerationRequest) {
};
}
+/**
+ * The finishes MiniMax H3's 2K tier adds on your GPU (createH3TwoKRun): one Open-H3 Regenerate pass per take, checked
+ * (the refiner LoRA's switch, the finish's own plan) and priced as the run makes them.
+ */
+function h3TwoKExtra(req: GenerationRequest, model: ModelDef, op: Operation): { costUsd: number | null; notes: string[]; steps: { model: string; op: string }[] } | null {
+ if (!wantsH3TwoK(model.id, req.params?.resolution)) return null;
+ const off = regenSwitchedOff();
+ if (off) throw new Error(off);
+ const takes = Math.max(1, Math.min(4, Math.round(req.params?.numOutputs ?? 1)));
+ const { finish } = h3TwoKRequests(req, op, { keepLatent: keepsH3Latent() });
+ const p = previewChained(finish, 1);
+ return {
+ costUsd: p.costUsd === null ? null : Math.round(p.costUsd * takes * 10000) / 10000,
+ notes: [H3_2K_STEPS_NOTE],
+ steps: Array.from({ length: takes }, () => ({ model: p.model.id, op: p.op })),
+ };
+}
+
/** The steps "Clean the voice first" adds to a run (all but the run itself), checked and priced as the run makes them. */
function voiceFirstExtra(req: GenerationRequest, model: ModelDef): { costUsd: number | null; notes: string[]; steps: { model: string; op: string }[] } | null {
const vf = voiceFirstPlanFor(req, model);
@@ -964,7 +989,7 @@ export function createGenerations(given: GenerationRequest, opts: CreateOptions
const asked = stampTenant(given, opts);
// A retired model or operation (a retry, an old script, a saved project) runs on what replaced it, and says so.
const moved = currentRequest(asked);
- const original = moved.request;
+ const original = withFinishOf(moved.request, opts.dependsOn);
// Open models make multi-shot films shot by shot, then join the clips. A Fuobe Original is taken on the engine it runs
// on (Fuobe DoP's Frames mode is a GPU chain).
// A model (or an Original's engine asked for) switched off in Settings → Models & licences is refused here, before a
@@ -1444,7 +1469,8 @@ async function advanceDependents(): Promise<void> {
if (model?.routes.some((x) => x.provider === "llm")) await probeLocal();
// Filled with the slots that have an input; stored with its whole chain (and what was skipped) for a retry.
const filled = withChainInputs({ ...request, chain: slots }, values as string[]);
- const original: GenerationRequest = { ...filled, chain: request.chain, chainFilled: true };
+ // A 2K finish names the draft it waits for as the latent to load (never an id stored before: a retried draft is new).
+ const original: GenerationRequest = latentFromDependency({ ...filled, chain: request.chain, chainFilled: true }, allIds.filter(keep), slots, deps);
const prepared = asRun(() => prepare(original));
const mode = chainMode(prepared, deps as Pick<Row, "provider">[], original);
if (mode.error) throw new Error(mode.error);
@@ -1470,6 +1496,65 @@ async function advanceDependents(): Promise<void> {
}
}
+/** A chained 2K finish finishes the run its clip comes from (a retried draft is a new run: read again when it is created). */
+function withFinishOf(req: GenerationRequest, dependsOn: string | string[] | undefined): GenerationRequest {
+ if (!req.finishOf || dependsOn === undefined) return req;
+ const deps = Array.isArray(dependsOn) ? dependsOn : [dependsOn];
+ const at = slotsFor(req, deps.length).findIndex((s) => s.slot === "video");
+ return at >= 0 && deps[at] !== req.finishOf ? { ...req, finishOf: deps[at] } : req;
+}
+
+/**
+ * MiniMax H3's 2K finish (Open-H3 Regenerate chained after its 768p draft): the draft it waits for, when that draft kept
+ * its latent, is the latent it may load (latentHandOff checks it again when it starts). Any other latentFrom is dropped.
+ */
+function latentFromDependency(req: GenerationRequest, ids: string[], slots: ChainSlot[], deps: (Pick<Row, "request_json"> | undefined)[]): GenerationRequest {
+ if (req.modelId !== REGEN_MODEL) return req;
+ const at = slots.findIndex((s) => s.slot === "video");
+ let draft: GenerationRequest | undefined;
+ try {
+ draft = at >= 0 && deps[at] ? (JSON.parse(deps[at]!.request_json) as GenerationRequest) : undefined;
+ } catch {}
+ const { latentFrom: _stored, ...extra } = req.params?.extra ?? {};
+ void _stored;
+ const latentFrom = draft?.params?.extra?.latentDraft === true ? ids[at] : undefined;
+ if (!latentFrom && _stored === undefined) return req;
+ return { ...req, params: { ...req.params, extra: { ...extra, ...(latentFrom && { latentFrom }) } } };
+}
+
+/**
+ * The 2K hand-off as the run starts, on the ComfyUI it runs on (never trusted from the request; package n7-10). A draft
+ * keeps its latent only where one stays between jobs (not the owner's workers) and while its Turbo 4-step LoRA is on. A
+ * finish loads a latent only from a run of the same account (or the owner's own) that kept one on this same ComfyUI,
+ * and that no earlier finish found gone; otherwise it redraws its clip.
+ */
+export function latentHandOff(extra: Record<string, unknown> | undefined, account: string | undefined): Record<string, unknown> | undefined {
+ if (!extra || (extra.latentDraft === undefined && extra.latentFrom === undefined)) return extra;
+ const out = { ...extra };
+ const place = comfyPlace();
+ if (out.latentDraft !== undefined && !(out.latentDraft === true && place && keepsH3Latent())) delete out.latentDraft;
+ if (out.latentFrom !== undefined && !(typeof out.latentFrom === "string" && place && keptLatent(out.latentFrom, account, place))) delete out.latentFrom;
+ return out;
+}
+
+/** Whether run `id` kept its 768p latent on `place` for this account (the owner: undefined), and it is still there. */
+function keptLatent(id: string, account: string | undefined, place: string): boolean {
+ const row = db().prepare("SELECT status, request_json, external_meta_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "request_json" | "external_meta_json"> | undefined;
+ if (!row || row.status !== "succeeded" || accountOf(row) !== account) return false;
+ try {
+ const req = JSON.parse(row.request_json) as GenerationRequest;
+ const meta = JSON.parse(row.external_meta_json ?? "{}") as { latentAt?: unknown };
+ if (req.params?.extra?.latentDraft !== true || meta.latentAt !== place) return false;
+ } catch {
+ return false;
+ }
+ // A finish that found it gone (someone's computer reports that after the fact): the next one redraws the clip.
+ const gone = db()
+ .prepare("SELECT 1 FROM generations WHERE status = 'failed' AND error = ? AND json_extract(request_json, '$.params.extra.latentFrom') = ? LIMIT 1")
+ .get(REGEN_COPY.latentGone, id);
+ return !gone;
+}
+
const statusOf = (id: string) => (db().prepare("SELECT status FROM generations WHERE id = ?").get(id) as Pick<Row, "status"> | undefined)?.status;
/** Start the timeout clock: the job has reached its provider. */
@@ -1672,6 +1757,11 @@ async function submitNow(
submitting().add(id);
/** Why the run failed, once it has: its files still waiting to be sent are not sent. */
let failed: { error: unknown } | undefined;
+ // MiniMax H3's 2K hand-off, decided here, on the ComfyUI this run goes to.
+ if (providerId === "comfyui") {
+ const extra = latentHandOff(plan.params.extra, req.account);
+ if (extra !== plan.params.extra) plan = { ...plan, params: { ...plan.params, extra } };
+ }
try {
// An account's run on its own ComfyUI and keys only (asAccount): outside it, nothing is sent.
const adapter = adapterFor(providerId, req.account);
diff --git a/src/server/marketing.ts b/src/server/marketing.ts
index ad06c108..a4e02f9a 100644
--- a/src/server/marketing.ts
+++ b/src/server/marketing.ts
@@ -63,6 +63,7 @@ import { engineMode } from "./settings";
import { encodePng } from "./png";
import { localHead, saveFile, storedMedia } from "./storage";
import { imageSize } from "@/lib/image-size";
+import { targetShortEdge } from "@/lib/av/upscale";
import { isH3Graph } from "@/lib/h3-prompt";
/**
@@ -1108,7 +1109,17 @@ const ISO: Record<string, string> = {
};
/** The spoken language for the cloud captioner (ISO code); English needs none. */
const languageCode = (name?: string) => (name && name !== "English" ? ISO[name] : undefined);
-const nearestRes = (want: string, m: ModelDef) => (m.options.resolutions?.includes(want) ? want : (m.options.resolutions?.filter((r) => parseInt(r) <= parseInt(want)).pop() ?? m.options.resolutions?.[0] ?? want));
+/**
+ * The model's tier for the one asked: the same, else the tallest at or below it, else its first. Ranked by the height a
+ * tier names (targetShortEdge: "2K" is 1440, never 2), so a finishing tier can't pass for the smallest.
+ */
+function nearestRes(want: string, m: ModelDef): string {
+ const offered = m.options.resolutions ?? [];
+ if (offered.includes(want)) return want;
+ const h = targetShortEdge(want);
+ const below = h === undefined ? [] : offered.filter((r) => (targetShortEdge(r) ?? Infinity) <= h).sort((a, b) => targetShortEdge(a)! - targetShortEdge(b)!);
+ return below.pop() ?? offered[0] ?? want;
+}
// ---------------------------------------------------------------------------
// Estimates and launching
diff --git a/src/server/model-access.ts b/src/server/model-access.ts
index 43f47ea2..df7c2f65 100644
--- a/src/server/model-access.ts
+++ b/src/server/model-access.ts
@@ -1,7 +1,7 @@
import "server-only";
import { getPreset, MODELS } from "@/lib/catalog";
import { CHARACTER_LORAS, characterLora, MINIMAX_H3_LICENCE } from "@/lib/catalog/character-swap";
-import { REGEN_FILES, REGEN_LORA } from "@/lib/catalog/regenerate";
+import { H3_TURBO_4STEP_INFO, H3_TURBO_4STEP_LORA, REGEN_FILES, REGEN_LORA } from "@/lib/catalog/regenerate";
import { onEngine, providerEngine } from "@/lib/catalog/engines";
import { LORA_LIBRARY, MOTION_EFFECT_LORAS } from "@/lib/catalog/lora-library.generated";
import { libraryEntry, loraName } from "@/lib/catalog/loras";
@@ -250,6 +250,7 @@ export function loraLicence(l: Pick<LoraRef, "file" | "url" | "licence">): Licen
const h3 = characterLora(l.file);
if (h3) return characterLoraLicence(h3);
if (l.file === REGEN_LORA.file) return regenLoraLicence();
+ if (l.file === H3_TURBO_4STEP_LORA.file) return turbo4StepLicence();
const e = libraryEntry(l);
return loraLicenceInfo(l.licence ?? e?.licence, e?.page);
}
@@ -260,6 +261,11 @@ function regenLoraLicence(): LicenceInfo {
return { name, class: cls, url: modelCardOf(REGEN_LORA.url) ?? url, note: REGEN_FILES[0].note, ...(excludes && { excludes }), ...(notices?.length && { notices }) };
}
+/** lightx2v's Turbo 4-step v1.2 (MiniMax H3's 2K draft): Apache-2.0 in its card at the pinned revision. */
+function turbo4StepLicence(): LicenceInfo {
+ return { ...licenceInfo("Apache-2.0"), url: H3_TURBO_4STEP_INFO.url, note: H3_TURBO_4STEP_INFO.note };
+}
+
/** A Character swap LoRA's licence as the list shows it (its own recorded terms, its pinned model card). */
function characterLoraLicence(l: (typeof CHARACTER_LORAS)[number]): LicenceInfo {
const { name, class: cls, url, excludes, notices, note } = l.licence;
@@ -357,6 +363,8 @@ function loraRows(access: ModelAccess): LoraInfo[] {
for (const l of CHARACTER_LORAS) rows.push({ file: l.file, name: l.name, group: "adapter", base: "MiniMax H3", licence: characterLoraLicence(l), on: !access.loras.includes(l.file) });
// The refiner LoRA Open-H3 Regenerate's graph loads (and a run downloads).
rows.push({ file: REGEN_LORA.file, name: REGEN_FILES[0].item, group: "adapter", base: "MiniMax H3", licence: regenLoraLicence(), on: !access.loras.includes(REGEN_LORA.file) });
+ // The Turbo 4-step LoRA MiniMax H3's 2K draft loads (off: the draft runs on H3's own graph and the finish redraws its clip).
+ rows.push({ file: H3_TURBO_4STEP_LORA.file, name: H3_TURBO_4STEP_INFO.name, group: "adapter", base: "MiniMax H3", licence: turbo4StepLicence(), on: !access.loras.includes(H3_TURBO_4STEP_LORA.file) });
return rows;
}
@@ -373,7 +381,7 @@ export function knownSwitch(kind: "model" | "provider" | "pack" | "lora", id: st
case "pack":
return NODE_PACKS.some((p) => p.name === id);
case "lora":
- return LORA_LIBRARY.some((e) => e.file === id) || Object.values(OSS_LORAS).some((refs) => refs.some((r) => r.file === id)) || !!characterLora(id) || id === REGEN_LORA.file;
+ return LORA_LIBRARY.some((e) => e.file === id) || Object.values(OSS_LORAS).some((refs) => refs.some((r) => r.file === id)) || !!characterLora(id) || id === REGEN_LORA.file || id === H3_TURBO_4STEP_LORA.file;
}
}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 91329094..42e02581 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -194,6 +194,20 @@ export function computerScope(): Principal | undefined {
/** The owner's ComfyUI jobs go to the workers (Settings: ComfyUI runs on "workers"), not to one computer. */
const onWorkers = (computer: Principal | undefined) => computer === "owner" && !ownGpu() && getSetting("comfyWhere") === "workers";
+/**
+ * Which ComfyUI a job in this scope runs on, as a name two runs are compared by (MiniMax H3's 2K finish loads the latent
+ * its draft saved only on the ComfyUI that saved it): an account's link or computer, the owner's computer, or this
+ * install's server. null where nothing stays between jobs: the owner's workers empty their output folder after each one.
+ */
+export function comfyPlace(): string | null {
+ const own = ownGpu();
+ if (own) return own.kind === "computer" ? `computer:${own.principal}` : own.url ? `link:${own.url}` : null;
+ const computer = computerScope();
+ if (computer) return onWorkers(computer) ? null : `computer:${computer}`;
+ const url = getSetting("comfyUrl").replace(/\/+$/, "");
+ return url ? `server:${url}` : null;
+}
+
/**
* FUOBE_POOL_MEDIA_INPUTS: what a job for workers may send them ("image" unless set; "image,video,audio" for all).
* Pictures are always made again from their pixels first (no EXIF, no GPS, nothing a decoder on that PC could trip on).
@@ -1956,6 +1970,12 @@ export function withoutAnchor(wf: ComfyWorkflow, loaderId: string): ComfyWorkflo
/** What ComfyUI's /prompt answers when it refuses a graph. */
export type PromptRefusalBody = { error?: { type?: string; message?: string; extra_info?: { class_type?: string } }; node_errors?: unknown };
+/** A 2K finish refused because the latent file it loads isn't on that ComfyUI (Load Refined Latent's list of files). */
+export function latentGone(body: PromptRefusalBody, manifest: Pick<ManifestWorkflow, "id">): boolean {
+ if (manifest.id !== REGEN_LATENT_WORKFLOW || !body.node_errors || typeof body.node_errors !== "object") return false;
+ return Object.values(body.node_errors as Record<string, { class_type?: unknown }>).some((n) => n?.class_type === "OpenH3LoadRefinedLatent");
+}
+
/**
* A /prompt refusal in words, with what was missing as a code its failed tile turns into "Fix it" (the GPU pre-flight's
* guided fix). The same for the server's own ComfyUI, a link, and one on someone's computer (its tab reports the answer).
@@ -1981,6 +2001,8 @@ export function promptRefusal(body: PromptRefusalBody, status: number, manifest:
? `This workflow needs the ${packs.join(" + ")} node pack${packs.length > 1 ? "s" : ""} on ${where} (see scripts/comfy/README.md)`
: undefined;
// A LoRA it lacks: point at its model card (a civitai download URL answers 401 without the key) and the LoRA folder setting.
+ // A 2K finish whose draft's saved latent is gone (someone's computer: its tab reports the refusal): plain words, no file.
+ if (latentGone(body, manifest)) return { message: REGEN_COPY.latentGone };
const loraModels = loras.map((l) => ({ file: l.file, folder: "loras", url: loraByFile(l.file)?.page ?? (l.url && !needsToken(l.url) ? l.url : undefined) }));
let detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...loraModels] }) : (missingPack ?? (typeof body.error?.message === "string" ? body.error.message.slice(0, 1024) : undefined));
// (Settings → LoRAs is the owner's page, for the server's own ComfyUI: an account's, or one on a computer, gets its LoRAs by hand.)
@@ -2324,6 +2346,9 @@ export const comfyProvider: ProviderAdapter = {
dbsModels: () => comfyDbsModels(worker, 0),
reuseModels: () => comfyReuseModels(worker, 0),
});
+ // MiniMax H3's 2K draft that kept its latent says where (the finish loads it only there: generations.ts latentHandOff).
+ const latentAt = manifest.id === H3_LATENT_DRAFT_WORKFLOW ? comfyPlace() : null;
+ if (latentAt) meta.latentAt = latentAt;
// On someone's computer: the job waits for their Fuobe tab, which sends exactly this graph under the prompt id minted
// here. A refusal comes back in its report, and the poll explains it as below.
const computer = computerScope();
@@ -2355,6 +2380,13 @@ export const comfyProvider: ProviderAdapter = {
worker,
);
const body = (await res.json().catch(() => ({}))) as PromptRefusalBody & { prompt_id?: string };
+ // A 2K finish whose draft's latent isn't on this ComfyUI any more (its output folder was cleaned): the draft's clip,
+ // chained into the same run, is redrawn instead.
+ if (!res.ok && latentGone(body, manifest) && typeof input.extra?.latentFrom === "string") {
+ const { latentFrom: _gone, ...extra } = input.extra;
+ void _gone;
+ return comfyProvider.submit({ route, input: { ...input, extra }, generationId, model });
+ }
if (!res.ok || !body.prompt_id) {
const refusal = promptRefusal(body, res.status, manifest, input.loras ?? [], worker);
if (!refusal.message && !res.ok && worker === "isolated") throw isolatedAnswer("the prompt", res.status);
diff --git a/src/server/regenerate.ts b/src/server/regenerate.ts
index 40cc4c03..d072c8f1 100644
--- a/src/server/regenerate.ts
+++ b/src/server/regenerate.ts
@@ -2,6 +2,7 @@ import "server-only";
import path from "node:path";
import { nanoid } from "nanoid";
import {
+ H3_TURBO_4STEP_LORA,
h3TwoKRequests,
isH3Source,
needsSmoothing,
@@ -172,10 +173,17 @@ export function createRegenerateRun(
}
}
+/** Whether the 2K draft may keep its latent: its graph loads the Turbo 4-step LoRA, which Settings may switch off. */
+export function keepsH3Latent(): boolean {
+ return !offeredLoras([H3_TURBO_4STEP_LORA]).dropped.length;
+}
+
/**
* MiniMax H3 at 2K on your GPU (n7-10): each take is drafted at 768p, then redrawn at 2K by Open-H3 Regenerate
- * (h3TwoKRequests). A text-to-video draft keeps its latent and the finish loads it by the draft's id; a take from a start
- * frame is finished from its clip. Returns the finished takes first, then their drafts. `create` is createGenerations.
+ * (h3TwoKRequests). A text-to-video draft keeps its latent (unless its Turbo 4-step LoRA is switched off); when the finish
+ * starts, the server loads that latent if it is on the ComfyUI the finish runs on (generations.ts latentHandOff), and
+ * redraws the draft's clip otherwise. Words that come from an earlier step reach the finish too. Returns the finished takes
+ * first, then their drafts. `create` is createGenerations.
*/
export function createH3TwoKRun(
original: GenerationRequest,
@@ -188,14 +196,21 @@ export function createH3TwoKRun(
if (off) throw new Error(off);
const batchId = opts.batchId ?? nanoid(10);
const takes = Math.max(1, Math.min(4, Math.round(original.params?.numOutputs ?? 1)));
+ // An earlier step that writes the words (a Canvas or Assist text node): the finish waits for it too, and redraws from them.
+ const deps = opts.dependsOn === undefined ? [] : Array.isArray(opts.dependsOn) ? opts.dependsOn : [opts.dependsOn];
+ const words = deps.flatMap((id, i) => (original.chain?.[i]?.slot === "prompt" ? [{ id, slot: original.chain[i] }] : []));
+ const keepLatent = keepsH3Latent();
const finished: Generation[] = [];
const drafts: Generation[] = [];
try {
for (let i = 0; i < takes; i++) {
- const { draft, finish, fromLatent } = h3TwoKRequests(original, op);
+ const { draft, finish } = h3TwoKRequests(original, op, { keepLatent });
const [d] = create(draft, { ...opts, batchId });
drafts.push(d);
- const [f] = create({ ...finish, params: { ...finish.params, extra: { ...finish.params?.extra, ...(fromLatent ? { latentFrom: d.id } : {}) } } }, { batchId, dependsOn: d.id });
+ const [f] = create(
+ { ...finish, chain: [...(finish.chain ?? []), ...words.map((w) => w.slot)], finishOf: d.id },
+ { batchId, dependsOn: words.length ? [d.id, ...words.map((w) => w.id)] : d.id },
+ );
finished.push(f);
}
} catch (e) {
diff --git a/src/server/request-schema.ts b/src/server/request-schema.ts
index 2fbf74c7..d1c5632f 100644
--- a/src/server/request-schema.ts
+++ b/src/server/request-schema.ts
@@ -2,8 +2,19 @@ import "server-only";
import { z } from "zod";
import { FORMAT_INFO } from "@/lib/av/formats";
import type { VideoFormat } from "@/lib/catalog/types";
+import { LATENT_EXTRA } from "@/lib/catalog/regenerate";
import { SignatureSchema } from "./palettes";
+/**
+ * params.extra as a client may send it: any settings, less the ones only the server sets (MiniMax H3's 2K hand-off:
+ * latentDraft, latentFrom), the way the run stamp's fields are dropped. The server checks those again when a run starts.
+ */
+export const ClientExtra = z.record(z.string(), z.unknown()).transform((extra) => {
+ const out = { ...extra };
+ for (const k of LATENT_EXTRA) delete out[k];
+ return out;
+});
+
/** A point on a picture as fractions of its width and height. */
const Focus = z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) });
@@ -106,7 +117,7 @@ export const GenerationRequestSchema = z.object({
position: Focus.optional(),
scale: z.number().positive().max(10).optional(),
animation: z.union([z.string().max(200), z.number()]).optional(),
- extra: z.record(z.string(), z.unknown()).optional(),
+ extra: ClientExtra.optional(),
})
.optional(),
presetOptions: z.record(z.string(), z.string()).optional(),
diff --git a/tests/account-latent.test.ts b/tests/account-latent.test.ts
new file mode 100644
index 00000000..c31d62e5
--- /dev/null
+++ b/tests/account-latent.test.ts
@@ -0,0 +1,178 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+import { startFakeComfy, TINY_MP4, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+// MiniMax H3's 2K hand-off under public sign-up (review 3 of package n7-10): which saved 768p latent a finish loads is the
+// server's to say. A client can't name one (POST /api/generations drops latentFrom and latentDraft), and a run inside the
+// server loads one only from a run of the same account that kept it on the same ComfyUI: never the owner's or another
+// account's, even when both sit on one ComfyUI. An account's own 2K run hands its latent over on its own GPU.
+vi.setConfig({ testTimeout: 120_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-latent-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+delete process.env.FUOBE_HOSTED_RUNS;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ if (url.startsWith("http://127.0.0.1:")) return realFetch(input, init);
+ return new Response("not stubbed", { status: 599 });
+}) as typeof fetch;
+
+const R = await import("@/lib/catalog/regenerate");
+const auth = await import("@/server/auth");
+const { POST } = await import("@/app/api/generations/route");
+const gens = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { comfyPlace } = await import("@/server/providers/comfyui");
+
+let fake: FakeComfy;
+let a = "";
+let b = "";
+let cookie = "";
+let place = "";
+beforeAll(async () => {
+ fake = await startFakeComfy({ output: "video", delayMs: 300, loras: [R.REGEN_LORA.file, R.H3_TURBO_4STEP_LORA.file] });
+ globalThis.__fuobeTestGpuPort = fake.port;
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ b = auth.createAccount("[email protected]", "long enough").id;
+ auth.setAccountGpu(a, { url: fake.url });
+ auth.setAccountGpu(b, { url: fake.url });
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+ place = gens.asAccount(a, () => comfyPlace())!;
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestGpuPort = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fake.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ // Each test's runs count alone toward the account's active-run limit.
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+const graphs = () => fake.log.filter((e) => e.path === "/prompt" && e.prompt).map((e) => e.prompt as Graph);
+const has = (g: Graph, cls: string) => Object.values(g).some((n) => n.class_type === cls);
+const loaded = (g: Graph) => Object.values(g).find((n) => n.class_type === "OpenH3LoadRefinedLatent")?.inputs.latent_file;
+
+function run(body: unknown) {
+ const text = JSON.stringify(body);
+ return POST(
+ new Request("http://localhost:3000/api/generations", {
+ method: "POST",
+ headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) },
+ body: text,
+ }),
+ );
+}
+
+/** Wait until the runner has sent this run's graph to the account's ComfyUI (or it stopped), and return that graph. */
+async function sentFor(id: string, from: number): Promise<Graph> {
+ const end = Date.now() + 60_000;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ const sent = graphs().slice(from);
+ if (sent.length && (g.status !== "queued" || g.message === "Queued")) return sent[sent.length - 1];
+ if (g.status === "failed") throw new Error(`failed: ${g.error}`);
+ if (Date.now() > end) throw new Error(`nothing sent: ${g.status} ${g.message ?? ""}`);
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+async function settle(id: string): Promise<Generation> {
+ const end = Date.now() + 60_000;
+ 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, 150));
+ }
+}
+
+/** A finished 768p draft that kept its latent on `latentAt` (whose: an account's, or the owner's). */
+function keptDraft(id: string, account: string | undefined, latentAt: string): void {
+ const now = Date.now();
+ const req = { feature: "video", modelId: R.H3_OPEN_MODEL, op: "t2v", prompt: "x", params: { resolution: "768p", extra: { latentDraft: true } }, ...(account && { account }) };
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, external_meta_json, created_at, updated_at) VALUES (?, 'video', ?, 'open', 'comfyui', 't2v', 'video', 'succeeded', ?, '[]', 'p', ?, ?, ?)",
+ )
+ .run(id, R.H3_OPEN_MODEL, JSON.stringify(req), JSON.stringify({ latentAt }), now, now);
+}
+
+const clipOf = (accountId: string) => saveFile({ data: TINY_MP4, contentType: "video/mp4", name: "clip.mp4", source: "upload", accountId }).url;
+const finishOf = (video: string, latentFrom: string) => ({
+ feature: "video",
+ modelId: R.REGEN_MODEL,
+ op: "upscale-video" as const,
+ prompt: "A lighthouse in a storm",
+ inputs: { video },
+ params: { resolution: "1440p", numOutputs: 1, extra: { startSigma: 0.8, draftFrom: "h3", latentFrom } },
+});
+
+describe("an account's 2K finish and saved latents", () => {
+ it("a client can't name a latent or keep one: the API drops both, and the clip is redrawn", async () => {
+ keptDraft("ownerDraft01", undefined, place);
+ const before = graphs().length;
+ const r = await run({ ...finishOf(clipOf(a), "ownerDraft01"), params: { resolution: "1440p", extra: { startSigma: 0.8, draftFrom: "h3", latentFrom: "ownerDraft01", latentDraft: true } } });
+ expect(r.status).toBe(201);
+ const { items } = (await r.json()) as { items: Generation[] };
+ expect(items[0].request).toMatchObject({ account: a, modelId: R.REGEN_MODEL });
+ expect(items[0].request.params?.extra).toEqual({ startSigma: 0.8, draftFrom: "h3" });
+ const g = await sentFor(items[0].id, before);
+ expect(has(g, "OpenH3LoadRefinedLatent")).toBe(false);
+ expect(has(g, "LoadVideo")).toBe(true);
+ });
+
+ it("inside the server too: a finish loads only its own account's latent, never the owner's or another account's", async () => {
+ keptDraft("ownerDraft02", undefined, place);
+ keptDraft("acctBDraft01", b, place);
+ keptDraft("acctADraft01", a, place);
+ const tryFrom = async (latentFrom: string) => {
+ const before = graphs().length;
+ const [g] = gens.asAccount(a, () => gens.createGenerations(finishOf(clipOf(a), latentFrom)));
+ expect(g.request.account).toBe(a);
+ return sentFor(g.id, before);
+ };
+ for (const theirs of ["ownerDraft02", "acctBDraft01"]) {
+ const g = await tryFrom(theirs);
+ expect(has(g, "OpenH3LoadRefinedLatent"), theirs).toBe(false);
+ expect(has(g, "LoadVideo"), theirs).toBe(true);
+ }
+ expect(loaded(await tryFrom("acctADraft01"))).toBe("fuobe_h3_acctADraft01_00001.safetensors");
+ });
+
+ it("an account's own 2K run keeps its latent on its own GPU, and its finish loads it there", async () => {
+ const before = graphs().length;
+ const r = await run({ feature: "video", modelId: R.H3_OPEN_MODEL, op: "t2v", prompt: "A lighthouse in a storm", params: { resolution: "2K", duration: 5 } });
+ expect(r.status).toBe(201);
+ const { items } = (await r.json()) as { items: Generation[] };
+ const draft = items.find((g) => g.modelId === R.H3_OPEN_MODEL)!;
+ const finish = items.find((g) => g.modelId === R.REGEN_MODEL)!;
+ for (const g of items) expect(g.request.account).toBe(a);
+ expect(await settle(finish.id)).toMatchObject({ status: "succeeded" });
+ const meta = JSON.parse((db().prepare("SELECT external_meta_json AS m FROM generations WHERE id = ?").get(draft.id) as { m: string }).m);
+ expect(meta.latentAt).toBe(place);
+ expect(place).toBe(`link:${fake.url}`);
+ const sent = graphs().slice(before);
+ expect(sent.some((g) => has(g, "MiniMaxH3ImageToVideo") && has(g, "OpenH3SaveRefinedLatent"))).toBe(true);
+ expect(sent.map(loaded).filter(Boolean)).toEqual([`fuobe_h3_${draft.id}_00001.safetensors`]);
+ });
+});
diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.ts
index c7a9f4c2..ff6dd09c 100644
--- a/tests/helpers/fake-comfy-runner.ts
+++ b/tests/helpers/fake-comfy-runner.ts
@@ -10,7 +10,8 @@
* answers), `missing` (a file /prompt answers "not in list" for), `output` ("video" or "image"), `layers` (the
* history lists that many Qwen-Image-Layered layers, node 60), `frames` (an EXR export: a preview clip, node 5, and
* that many frames, node 3), `historyError` (/history answers HTTP 500 and then sends nothing), `uploadStatus` (the HTTP
- * status /upload/image answers, e.g. 500 to fail every upload).
+ * status /upload/image answers, e.g. 500 to fail every upload), `refuseClass` (/prompt answers "not in list" for a graph with
+ * a node of that class).
* This file runs under plain Node too: only erasable TypeScript.
*/
import http from "node:http";
@@ -29,6 +30,8 @@ export interface FakeComfyOptions {
frames?: number;
historyError?: boolean;
uploadStatus?: number;
+ /** /prompt answers "not in list" for a graph with a node of this class (a file that node loads isn't there). */
+ refuseClass?: string;
}
export interface FakeLogEntry {
@@ -105,6 +108,13 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
try {
entry.prompt = (JSON.parse(body.toString("utf8")) as { prompt?: Record<string, unknown> }).prompt;
} catch {}
+ const refused = opts.refuseClass ? Object.entries(entry.prompt ?? {}).find(([, n]) => (n as { class_type?: string })?.class_type === opts.refuseClass) : undefined;
+ if (refused) {
+ return json(400, {
+ error: { type: "prompt_outputs_failed_validation", message: "Prompt outputs failed validation" },
+ node_errors: { [refused[0]]: { errors: [{ type: "value_not_in_list", message: "Value not in list", details: "not in list", extra_info: { input_name: "latent_file", received_value: "x" } }], class_type: opts.refuseClass } },
+ });
+ }
if (opts.missing) {
return json(400, {
error: { type: "prompt_outputs_failed_validation", message: "Prompt outputs failed validation" },
diff --git a/tests/open-minimax-h3.test.ts b/tests/open-minimax-h3.test.ts
index d537c112..711666b6 100644
--- a/tests/open-minimax-h3.test.ts
+++ b/tests/open-minimax-h3.test.ts
@@ -70,8 +70,7 @@ describe("MiniMax H3 on your GPU: the catalog entry", () => {
expect(h3.options).toMatchObject({
aspectRatios: ["auto", "16:9", "9:16", "1:1", "4:3", "3:4"],
durations: [3, 5, 10, 15],
- // 2K (n7-10): a 768p draft finished by Open-H3 Regenerate (tests/regenerate-more-api.test.ts).
- resolutions: ["768p", "2K"],
+ resolutions: ["768p"],
seed: true,
endFrame: true,
audio: "always",
diff --git a/tests/regenerate-latent.test.ts b/tests/regenerate-latent.test.ts
new file mode 100644
index 00000000..cf2bb8f8
--- /dev/null
+++ b/tests/regenerate-latent.test.ts
@@ -0,0 +1,184 @@
+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";
+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+// MiniMax H3's 2K hand-off on a real run path (review 2 of package n7-10): the 768p draft saves its latent on the ComfyUI
+// it ran on and says where; the finish loads it only from there, names the draft it waits for when it starts (so a retried
+// draft is the one loaded), redraws the draft's clip when the latent is gone, and never loads one across places.
+vi.setConfig({ testTimeout: 120_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-regen-latent-"));
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FUOBE_PASSWORD;
+delete process.env.COMFYUI_WHERE;
+
+const R = await import("@/lib/catalog/regenerate");
+const fake: FakeComfy = await startFakeComfy({ output: "video", delayMs: 300, loras: [R.REGEN_LORA.file, R.H3_TURBO_4STEP_LORA.file] });
+process.env.COMFYUI_URL = fake.url;
+
+const gens = await import("@/server/generations");
+const cinema = await import("@/server/cinema");
+const { db } = await import("@/server/db");
+const { setSetting } = await import("@/server/settings");
+const { comfyPlace, onOwnGpu, promptRefusal, getWorkflow } = await import("@/server/providers/comfyui");
+const { readAccess, saveAccess } = await import("@/server/model-access");
+
+beforeAll(() => setSetting("demoMode", "off"));
+afterAll(async () => {
+ await fake.close();
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+const graphs = () => fake.log.filter((e) => e.path === "/prompt" && e.prompt).map((e) => e.prompt as Graph);
+const has = (g: Graph, cls: string) => Object.values(g).some((n) => n.class_type === cls);
+const node = (g: Graph, cls: string) => Object.values(g).find((n) => n.class_type === cls)!;
+const meta = (id: string) => JSON.parse((db().prepare("SELECT external_meta_json AS m FROM generations WHERE id = ?").get(id) as { m: string | null }).m ?? "{}");
+
+async function settle(id: string, ms = 60_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, 150));
+ }
+}
+
+const twoK = (prompt: string) => gens.createGenerations({ feature: "cinema", modelId: R.H3_OPEN_MODEL, op: "t2v", prompt, params: { resolution: "2K", duration: 5 } });
+const split = (made: Generation[]) => ({ draft: made.find((g) => g.modelId === R.H3_OPEN_MODEL)!, finish: made.find((g) => g.modelId === R.REGEN_MODEL)! });
+
+/** A finished 768p draft as the runner records it (whose run, and where its latent was saved). */
+function keptDraft(id: string, o: { account?: string; latentAt?: string; latent?: boolean } = {}): void {
+ const now = Date.now();
+ const req = { feature: "cinema", modelId: R.H3_OPEN_MODEL, op: "t2v", prompt: "x", params: { resolution: "768p", extra: o.latent === false ? {} : { latentDraft: true } }, ...(o.account && { account: o.account }) };
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, external_meta_json, created_at, updated_at) VALUES (?, 'cinema', ?, 'open', 'comfyui', 't2v', 'video', 'succeeded', ?, '[]', 'p', ?, ?, ?)",
+ )
+ .run(id, R.H3_OPEN_MODEL, JSON.stringify(req), JSON.stringify(o.latentAt ? { latentAt: o.latentAt } : {}), now, now);
+}
+
+describe("the draft keeps its latent where it ran, and the finish loads it from there", () => {
+ it("on this install's ComfyUI: the draft saves under its id and says where; the finish loads that file", async () => {
+ const before = graphs().length;
+ const { draft, finish } = split(twoK("A lighthouse in a storm"));
+ expect(await settle(finish.id)).toMatchObject({ status: "succeeded" });
+ const sent = graphs().slice(before);
+ const d = sent.find((g) => has(g, "MiniMaxH3ImageToVideo"))!;
+ expect(has(d, "OpenH3SaveRefinedLatent")).toBe(true);
+ expect(node(d, "OpenH3SaveRefinedLatent").inputs.filename_prefix).toBe(`fuobe_h3_${draft.id}`);
+ expect(meta(draft.id).latentAt).toBe(`server:${fake.url}`);
+ const f = sent.find((g) => has(g, "OpenH3LoadRefinedLatent"))!;
+ expect(node(f, "OpenH3LoadRefinedLatent").inputs.latent_file).toBe(`fuobe_h3_${draft.id}_00001.safetensors`);
+ expect(gens.getGeneration(finish.id)!.request.params?.extra?.latentFrom).toBe(draft.id);
+ });
+
+ it("redraws the draft's clip when the latent is gone from that ComfyUI, in the same run", async () => {
+ fake.opts.refuseClass = "OpenH3LoadRefinedLatent";
+ try {
+ const before = graphs().length;
+ const { finish } = split(twoK("A harbour at dawn"));
+ expect(await settle(finish.id)).toMatchObject({ status: "succeeded" });
+ const sent = graphs().slice(before);
+ expect(sent.filter((g) => has(g, "OpenH3LoadRefinedLatent"))).toHaveLength(1);
+ const clip = sent.find((g) => has(g, "OpenH3RegenPrepareDraft"))!;
+ expect(has(clip, "LoadVideo")).toBe(true);
+ } finally {
+ fake.opts.refuseClass = undefined;
+ }
+ });
+
+ it("a Cinema retry of a failed draft finishes the new draft, from its own latent", async () => {
+ fake.opts.refuseClass = "MiniMaxH3ImageToVideo";
+ const project = cinema.createProject({ name: "Storm" });
+ const made = twoK("A cliff in the rain");
+ cinema.recordTakes(project.id, made, null);
+ const first = split(made);
+ expect(await settle(first.draft.id)).toMatchObject({ status: "failed" });
+ expect(await settle(first.finish.id)).toMatchObject({ status: "failed" });
+ fake.opts.refuseClass = undefined;
+ const before = graphs().length;
+ const again = split(cinema.retryItem(project.id, first.finish.id));
+ expect(again.draft.id).not.toBe(first.draft.id);
+ expect(again.finish.request.finishOf).toBe(again.draft.id);
+ expect(await settle(again.finish.id)).toMatchObject({ status: "succeeded" });
+ expect(gens.getGeneration(again.finish.id)!.request.params?.extra?.latentFrom).toBe(again.draft.id);
+ const f = graphs().slice(before).find((g) => has(g, "OpenH3LoadRefinedLatent"))!;
+ expect(node(f, "OpenH3LoadRefinedLatent").inputs.latent_file).toBe(`fuobe_h3_${again.draft.id}_00001.safetensors`);
+ });
+});
+
+describe("where a latent may be loaded from", () => {
+ it("names the ComfyUI a job goes to; the owner's workers keep nothing between jobs", () => {
+ expect(comfyPlace()).toBe(`server:${fake.url}`);
+ expect(onOwnGpu({ url: "https://gpu.example/" }, () => comfyPlace())).toBe("link:https://gpu.example");
+ expect(onOwnGpu({ kind: "computer", principal: "acct:a1" }, () => comfyPlace())).toBe("computer:acct:a1");
+ setSetting("comfyWhere", "computer");
+ try {
+ expect(comfyPlace()).toBe("computer:owner");
+ setSetting("comfyWhere", "workers");
+ expect(comfyPlace()).toBeNull();
+ } finally {
+ setSetting("comfyWhere", "server");
+ }
+ });
+
+ it("loads only a latent this run's owner kept on this same ComfyUI, and keeps a draft's only where it stays", () => {
+ const here = `server:${fake.url}`;
+ keptDraft("ownHere00001", { latentAt: here });
+ keptDraft("ownThere0001", { latentAt: "server:http://other-comfy.test:8188" });
+ keptDraft("acctDraft001", { latentAt: here, account: "acct-x" });
+ keptDraft("plainDraft01", { latentAt: here, latent: false });
+ const ask = (latentFrom: string, account?: string) => gens.latentHandOff({ latentFrom, startSigma: 0.8 }, account)?.latentFrom;
+ expect(ask("ownHere00001")).toBe("ownHere00001");
+ // Another ComfyUI, a run that didn't keep one, one that doesn't exist.
+ expect(ask("ownThere0001")).toBeUndefined();
+ expect(ask("plainDraft01")).toBeUndefined();
+ expect(ask("nope")).toBeUndefined();
+ // Another's run: the owner's for an account, an account's for the owner or another account.
+ expect(ask("ownHere00001", "acct-x")).toBeUndefined();
+ expect(ask("acctDraft001")).toBeUndefined();
+ expect(ask("acctDraft001", "acct-y")).toBeUndefined();
+ // The same ComfyUI reached as an account's link is another place.
+ expect(onOwnGpu({ url: fake.url }, () => ask("acctDraft001", "acct-x"))).toBeUndefined();
+ // On the owner's workers neither a draft's latent nor a finish from one: each job's output folder is emptied.
+ setSetting("comfyWhere", "workers");
+ try {
+ expect(gens.latentHandOff({ latentDraft: true, latentFrom: "ownHere00001" }, undefined)).toEqual({});
+ } finally {
+ setSetting("comfyWhere", "server");
+ }
+ expect(gens.latentHandOff({ latentDraft: true }, undefined)).toEqual({ latentDraft: true });
+ // The Turbo 4-step LoRA switched off: the draft runs on H3's own graph.
+ const was = readAccess();
+ saveAccess({ ...was, loras: [...was.loras, R.H3_TURBO_4STEP_LORA.file] });
+ try {
+ expect(gens.latentHandOff({ latentDraft: true }, undefined)).toEqual({});
+ } finally {
+ saveAccess(was);
+ }
+ });
+
+ it("says a missing latent in plain words, and the next finish redraws the clip", () => {
+ const { manifest } = getWorkflow(R.REGEN_LATENT_WORKFLOW);
+ const body = { error: { type: "prompt_outputs_failed_validation" }, node_errors: { "1": { class_type: "OpenH3LoadRefinedLatent", errors: [{ message: "Value not in list", extra_info: { input_name: "latent_file", received_value: "fuobe_h3_x_00001.safetensors" } }] } } };
+ const words = promptRefusal(body, 400, manifest, []).message!;
+ expect(words).toBe(R.REGEN_COPY.latentGone);
+ expect(words).not.toMatch(/safetensors|OpenH3|latent_file|fuobe_h3/);
+ // Another graph's refusal keeps ComfyUI's own words.
+ expect(promptRefusal(body, 400, getWorkflow(R.REGEN_WORKFLOW).manifest, []).message).not.toBe(R.REGEN_COPY.latentGone);
+ keptDraft("goneDraft001", { latentAt: `server:${fake.url}` });
+ expect(gens.latentHandOff({ latentFrom: "goneDraft001" }, undefined)?.latentFrom).toBe("goneDraft001");
+ const now = Date.now();
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, error, created_at, updated_at) VALUES ('goneFinish01', 'cinema', ?, 'open', 'comfyui', 'upscale-video', 'video', 'failed', ?, '[]', ?, ?, ?)",
+ )
+ .run(R.REGEN_MODEL, JSON.stringify({ feature: "cinema", modelId: R.REGEN_MODEL, params: { extra: { latentFrom: "goneDraft001" } } }), R.REGEN_COPY.latentGone, now, now);
+ expect(gens.latentHandOff({ latentFrom: "goneDraft001" }, undefined)?.latentFrom).toBeUndefined();
+ });
+});
diff --git a/tests/regenerate-more-api.test.ts b/tests/regenerate-more-api.test.ts
index 42fb72f4..8b70084b 100644
--- a/tests/regenerate-more-api.test.ts
+++ b/tests/regenerate-more-api.test.ts
@@ -25,8 +25,14 @@ const { setSetting } = await import("@/server/settings");
const gens = await import("@/server/generations");
const { createRegenerateRun } = await import("@/server/regenerate");
const { saveFile } = await import("@/server/storage");
+const { db } = await import("@/server/db");
const { runAsTenant } = await import("@/server/tenant");
const cinema = await import("@/server/cinema");
+const mk = await import("@/server/marketing");
+const { pickerData } = await import("@/lib/catalog/faceless");
+const { settingsShape } = await import("@/lib/composer");
+const { accessList, knownSwitch, readAccess, saveAccess } = await import("@/server/model-access");
+const { GenerationRequestSchema } = await import("@/server/request-schema");
const finishRoute = await import("@/app/api/cinema/projects/[id]/items/[generationId]/finish/route");
const ROOT = path.resolve(__dirname, "..");
@@ -107,6 +113,11 @@ describe("the 768p draft that keeps its latent, and the 2K finish from it", () =
expect(resolveWorkflowId("video-regenerate-h3", req({ latentFrom: "g1" }, "upscale-video"))).toBe("video-regenerate-h3-latent");
expect(resolveWorkflowId("video-regenerate-h3", req({}, "upscale-video"))).toBe("video-regenerate-h3");
expect(R.regenerateGraphLoras(R.REGEN_LATENT_WORKFLOW)).toEqual([R.REGEN_LORA]);
+ // The draft that keeps its latent loads the Turbo 4-step LoRA itself, so a run downloads it (or an account's GPU is
+ // checked for it) like the refiner.
+ expect(R.regenerateGraphLoras(R.H3_LATENT_DRAFT_WORKFLOW)).toEqual([R.H3_TURBO_4STEP_LORA]);
+ expect(R.regenerateGraphLoras("minimax-h3-t2v", { latentDraft: true })).toEqual([R.H3_TURBO_4STEP_LORA]);
+ expect(R.regenerateGraphLoras("minimax-h3-t2v", {})).toEqual([]);
});
it("has a row on the GPU pre-flight board with both graphs and the refiner LoRA", async () => {
@@ -114,7 +125,7 @@ describe("the 768p draft that keeps its latent, and the 2K finish from it", () =
const row = STUDIO_ROWS.find((r) => r.label === "MiniMax H3 in 2K")!;
const tool = studioTool(row)!;
expect(tool.workflows).toEqual([R.H3_LATENT_DRAFT_WORKFLOW, R.REGEN_LATENT_WORKFLOW]);
- expect(tool.loras.map((l) => l.file)).toContain(R.REGEN_LORA.file);
+ expect(tool.loras.map((l) => l.file)).toEqual(expect.arrayContaining([R.REGEN_LORA.file, R.H3_TURBO_4STEP_LORA.file]));
});
it("pins the Turbo 4-step v1.2 file at 3ec17a3 with its size and SHA-256", () => {
@@ -139,7 +150,10 @@ describe("MiniMax H3 at 2K on your GPU", () => {
expect(d).toMatchObject({ modelId: "oss-minimax-h3", op: "t2v" });
expect(d.request.params).toMatchObject({ resolution: "768p", numOutputs: 1, extra: { latentDraft: true } });
expect(f).toMatchObject({ modelId: R.REGEN_MODEL, op: "upscale-video" });
- expect(f.request.params).toMatchObject({ resolution: "1440p", extra: { startSigma: 0.8, draftFrom: "h3", latentFrom: d.id } });
+ expect(f.request.params).toMatchObject({ resolution: "1440p", extra: { startSigma: 0.8, draftFrom: "h3" } });
+ // The latent to load is decided when the finish starts, from the draft it waits for (never an id stored now).
+ expect(f.request.params?.extra?.latentFrom).toBeUndefined();
+ expect(f.request.finishOf).toBe(d.id);
expect(f.request.prompt).toBe("A lighthouse in a storm");
}
const png = saveFile({ data: Buffer.from("89504e470d0a1a0a", "hex"), contentType: "image/png", source: "upload" }).url;
@@ -214,6 +228,34 @@ describe("Finish in 2K", () => {
const again = await finishRoute.POST(json("POST"), params({ id: project.id, generationId: items[0].id }));
expect(again.status).toBe(422);
expect((await finishRoute.POST(json("POST"), params({ id: project.id, generationId: "nope" }))).status).toBe(404);
+ // Once per take: a second Finish in 2K is refused while the first is under way or made.
+ const twice = await finishRoute.POST(json("POST"), params({ id: project.id, generationId: g.id }));
+ expect(twice.status).toBe(409);
+ expect((await twice.json()).error).toBe("This take already has a 2K finish");
+ expect(R.finishedTakes(cinema.listItems(project.id))).toEqual(new Set([g.id]));
+ });
+
+ it("answers a repeated request id with the first finish, and offers it again once that finish failed", async () => {
+ const project = cinema.createProject({ name: "Harbour" });
+ const [g] = gens.createGenerations({ feature: "cinema", modelId: "oss-minimax-h3", op: "t2v", prompt: "A harbour at dawn", params: { resolution: "768p", duration: 5 } });
+ cinema.addItems(project.id, [g.id]);
+ expect(await settle(g.id)).toMatchObject({ status: "succeeded" });
+ const send = () => finishRoute.POST(json("POST", { requestId: "finish-nonce-0001" }), params({ id: project.id, generationId: g.id }));
+ const [a, b] = await Promise.all([send(), send()]);
+ expect([a.status, b.status]).toEqual([201, 201]);
+ const [first, second] = [(await a.json()).items, (await b.json()).items];
+ expect(second.map((x: Generation) => x.id)).toEqual(first.map((x: Generation) => x.id));
+ expect(first[0].request.finishOf).toBe(g.id);
+ expect((await finishRoute.POST(json("POST", { requestId: "../x" }), params({ id: project.id, generationId: g.id }))).status).toBe(400);
+ // A finish that failed doesn't count.
+ db().prepare("UPDATE generations SET status = 'failed' WHERE id = ?").run(first[0].id);
+ expect((await finishRoute.POST(json("POST", { requestId: "finish-nonce-0002" }), params({ id: project.id, generationId: g.id }))).status).toBe(201);
+ });
+
+ it("isn't offered on a 2K run's own 768p draft", () => {
+ const made = gens.createGenerations({ feature: "cinema", modelId: "oss-minimax-h3", op: "t2v", prompt: "A lighthouse", params: { resolution: "2K", duration: 5 } });
+ const draft = made.find((x) => x.modelId === "oss-minimax-h3")!;
+ expect(R.finishedTakes(made)).toEqual(new Set([draft.id]));
});
});
@@ -274,3 +316,97 @@ describe("Edit video · Enhance (H3 regenerate)", () => {
runAsTenant({ kind: "account", id: "acct-b" }, () => expect(run(mine)).toEqual([R.REGEN_MODEL]));
});
});
+
+describe("2K stays where it is offered (review 1)", () => {
+ const h3 = () => getModel("oss-minimax-h3")!;
+
+ it("keeps MiniMax H3's own tiers at 768p; only the Video studio and Cinema add the 2K finish", () => {
+ expect(h3().options.resolutions).toEqual(["768p"]);
+ expect(h3().options.finishTiers).toEqual(["2K"]);
+ expect(R.studioResolutions(h3().options)).toEqual(["768p", "2K"]);
+ expect(settingsShape(h3(), "t2v", "video", true).resolution).toEqual(["768p", "2K"]);
+ expect(videoResolutionsFor(h3())).toContain("2K");
+ // A model without finishing tiers keeps its own list as it is.
+ const ltx = getModel("oss-ltx25")!;
+ expect(R.studioResolutions(ltx.options)).toBe(ltx.options.resolutions);
+ });
+
+ it("Ad Multiplier's open hook and CTA stay at 768p whatever quality is asked", () => {
+ const frame = saveFile({ data: Buffer.from("89504e470d0a1a0a", "hex"), contentType: "image/png", source: "upload" }).url;
+ const clip = saveFile({ data: Buffer.from("89504e470d0a1a0a", "hex"), contentType: "video/mp4", name: "ad.mp4", source: "upload" }).url;
+ for (const quality of ["480p", "720p", "1080p"] as const) {
+ const plan = mk.planMultiplier({ engine: "open", video: clip, duration: 12, mode: "sections", hook: "Wait for it", cta: "Shop today", quality, firstFrame: frame, lastFrame: frame }, {});
+ const clips = plan.steps.filter((x) => x.key === "hook" || x.key === "cta");
+ expect(clips.map((x) => x.key)).toEqual(["hook", "cta"]);
+ for (const c of clips) expect(c.request).toMatchObject({ modelId: "oss-minimax-h3", params: { resolution: "768p" } });
+ }
+ });
+
+ it("Faceless's Quality control has no 2K (MiniMax H3 offers one tier there, so no control shows)", () => {
+ const open = pickerData(getModel).videoModels.find((m) => m.id === "oss-minimax-h3");
+ expect(open?.resolutions).toEqual(["768p"]);
+ // (fal's hosted MiniMax H3 renders 2K itself and keeps it, as before.)
+ for (const m of pickerData(getModel).videoModels.filter((x) => x.engine === "open")) expect(m.resolutions, m.id).not.toContain("2K");
+ });
+});
+
+describe("the 2K run's other pieces (review 4 to 8)", () => {
+ it("lists the Turbo 4-step v1.2 LoRA in Settings → Models & licences, Apache-2.0 at 3ec17a3, with a switch the draft honours", () => {
+ const row = accessList().loras.find((l) => l.file === R.H3_TURBO_4STEP_LORA.file)!;
+ expect(row).toMatchObject({ name: "MiniMax H3 FL2V Turbo 4-step v1.2 (lightx2v)", group: "adapter", base: "MiniMax H3", on: true });
+ expect(row.licence).toMatchObject({ name: "Apache-2.0", class: "commercial" });
+ expect(row.licence.url).toContain("3ec17a324ced54151364f24f8b5fb6bf7e26414f");
+ expect(row.licence.note).toMatch(/current card no longer states a licence/);
+ expect(knownSwitch("lora", R.H3_TURBO_4STEP_LORA.file)).toBe(true);
+ const was = readAccess();
+ saveAccess({ ...was, loras: [...was.loras, R.H3_TURBO_4STEP_LORA.file] });
+ try {
+ expect(accessList().loras.find((l) => l.file === R.H3_TURBO_4STEP_LORA.file)?.on).toBe(false);
+ // Off: the 2K tier still runs; its draft runs on H3's own graph and the finish redraws the draft's clip.
+ const made = gens.createGenerations({ feature: "video", modelId: "oss-minimax-h3", op: "t2v", prompt: "A lighthouse", params: { resolution: "2K", duration: 5 } });
+ const draft = made.find((x) => x.modelId === "oss-minimax-h3")!;
+ expect(draft.request.params?.extra?.latentDraft).toBeUndefined();
+ } finally {
+ saveAccess(was);
+ }
+ });
+
+ it("chains words from an earlier step into the finish too", () => {
+ const [write] = gens.createGenerations({ feature: "canvas", modelId: "oss-text-llm", op: "write", prompt: "A storm over a lighthouse" });
+ const made = gens.createGenerations({ feature: "canvas", modelId: "oss-minimax-h3", op: "t2v", prompt: "{text}", chain: [{ slot: "prompt" }], params: { resolution: "2K", duration: 5 } }, { dependsOn: write.id });
+ const finish = made.find((x) => x.modelId === R.REGEN_MODEL)!;
+ const draft = made.find((x) => x.modelId === "oss-minimax-h3")!;
+ expect(finish.request.chain).toEqual([{ slot: "video" }, { slot: "prompt" }]);
+ expect(finish.request.prompt).toBe("{text}");
+ const deps = db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(finish.id) as { depends_on: string };
+ expect(JSON.parse(deps.depends_on)).toEqual([draft.id, write.id]);
+ });
+
+ it("plans and prices each take's finish in a preview, as the run makes it", () => {
+ const p = gens.previewGeneration({ feature: "video", modelId: "oss-minimax-h3", op: "t2v", prompt: "A lighthouse", params: { resolution: "2K", duration: 5, numOutputs: 2 } });
+ expect(p.steps).toEqual([
+ { model: R.REGEN_MODEL, op: "upscale-video" },
+ { model: R.REGEN_MODEL, op: "upscale-video" },
+ ]);
+ expect(p.notes).toContain(R.H3_2K_STEPS_NOTE);
+ expect(p.costUsd).toBe(0);
+ // 768p is the model alone.
+ expect(gens.previewGeneration({ feature: "video", modelId: "oss-minimax-h3", op: "t2v", prompt: "x", params: { resolution: "768p", duration: 5 } }).steps).toBeUndefined();
+ });
+
+ it("says on Edit video's Enhance item that it runs on your GPU", () => {
+ expect(R.ENHANCE_LABEL).toBe("Enhance (H3 regenerate) · 1080p · on your GPU");
+ });
+
+ it("never takes the 2K hand-off's flags from a client", () => {
+ const parsed = GenerationRequestSchema.parse({
+ feature: "video",
+ modelId: R.REGEN_MODEL,
+ inputs: { video: "/api/files/x.mp4" },
+ params: { resolution: "1440p", extra: { latentFrom: "someonesDraft", latentDraft: true, startSigma: 0.8 } },
+ finishOf: "x",
+ });
+ expect(parsed.params?.extra).toEqual({ startSigma: 0.8 });
+ expect(parsed).not.toHaveProperty("finishOf");
+ });
+});
diff --git a/tests/regenerate-more-hosted.test.ts b/tests/regenerate-more-hosted.test.ts
new file mode 100644
index 00000000..c9a58d19
--- /dev/null
+++ b/tests/regenerate-more-hosted.test.ts
@@ -0,0 +1,83 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+// MiniMax H3 at 2K with hosted runs on (review 6 of package n7-10): an account's 2K run on this install's GPUs is planned
+// and priced with each take's Open-H3 Regenerate finish beside its 768p draft, and a policy that keeps the finish's model
+// off those GPUs keeps the whole run off, priced or run.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-regen-hosted-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const probe = http.createServer();
+const comfyPort = await listenInRange(probe);
+await new Promise<void>((r) => probe.close(() => r()));
+const comfy: FakeComfy = await startFakeComfy({ output: "video", delayMs: 0 }, comfyPort);
+process.env.COMFYUI_URL = comfy.url;
+
+const auth = await import("@/server/auth");
+const billing = await import("@/server/billing");
+const { resetRates } = await import("@/server/rate");
+const { decidePlace, poolQuote } = await import("@/server/hosted-run");
+const R = await import("@/lib/catalog/regenerate");
+
+let fake: FakeBilling;
+let a = "";
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await fake.close();
+ await comfy.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { hosted: true, pool: {}, uploads: { image: true, video: false, audio: false }, limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 7, maxSeconds: 7, keepDays: 7, spaceBytes: 7 }, ttlS: 0 };
+});
+
+const twoK = (resolution = "2K") => ({ feature: "video", modelId: R.H3_OPEN_MODEL, op: "t2v" as const, prompt: "A lighthouse in a storm", params: { resolution, duration: 5, numOutputs: 2 } });
+const finishes = (n: number) => Array.from({ length: n }, () => ({ model: R.REGEN_MODEL, op: "upscale-video" }));
+
+describe("MiniMax H3 at 2K on this install's GPUs", () => {
+ it("plans and prices each take's finish beside its draft", async () => {
+ const place = await decidePlace(auth.accountById(a)!, twoK(), undefined);
+ expect(place.kind).toBe("pool");
+ if (place.kind !== "pool") return;
+ expect(place.planned.model.id).toBe(R.H3_OPEN_MODEL);
+ expect(place.planned.steps).toEqual(finishes(2));
+ const before = fake.calls_of("/v1/quote").length;
+ const quoted = await poolQuote(auth.accountById(a)!, twoK(), undefined);
+ expect(quoted?.planned.steps).toEqual(finishes(2));
+ const sent = fake.calls_of("/v1/quote").slice(before).at(-1)?.body as { run: { model: string; jobs: number; steps?: unknown } };
+ expect(sent.run).toMatchObject({ model: R.H3_OPEN_MODEL, jobs: 2, steps: finishes(2) });
+ // 768p is the model alone.
+ expect((await poolQuote(auth.accountById(a)!, twoK("768p"), undefined))?.planned.steps).toBeUndefined();
+ });
+
+ it("a policy that keeps Open-H3 Regenerate off these GPUs keeps the 2K run off; 768p still runs here", async () => {
+ fake.policy = { ...fake.policy, pool: { deny: [R.REGEN_MODEL] } };
+ expect(await poolQuote(auth.accountById(a)!, twoK(), undefined)).toBeNull();
+ expect((await decidePlace(auth.accountById(a)!, twoK(), undefined)).kind).toBe("refuse");
+ expect((await decidePlace(auth.accountById(a)!, twoK("768p"), undefined)).kind).toBe("pool");
+ });
+});