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.

Video studio: Frames mode, up to 10 frames on a ruler with the clip's length, on both engines

Claude48e59a1f9eaf
diff --git a/src/components/studio/attachments.ts b/src/components/studio/attachments.ts
index 3d0647fa..4f3d12e3 100644
--- a/src/components/studio/attachments.ts
+++ b/src/components/studio/attachments.ts
@@ -3,7 +3,8 @@
import { nanoid } from "nanoid";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef } from "react";
import { toast } from "sonner";
-import { acceptedKinds, fitAttachments, noRoomMessage, onImageChange, placeAttachment, replaceAttachment } from "@/lib/composer";
+import { MAX_KEYFRAMES } from "@/lib/catalog/keyframes";
+import { acceptedKinds, addFrame, fitAttachments, noRoomMessage, onImageChange, placeAttachment, removeFrame, replaceAttachment } from "@/lib/composer";
import type { InputSlot, MediaKind } from "@/lib/catalog/types";
import { fileToSlot, kindOfFile, type SlotValue } from "./media-slot";
import { useStudio, type Draft, type SlotKey } from "./studio-context";
@@ -16,10 +17,10 @@ import { useStudio, type Draft, type SlotKey } from "./studio-context";
const inflight = new Map<string, { ac: AbortController; seen: boolean }>();
/** Abort uploads whose attachment is gone from the draft. Mount once, where the draft is read. */
-export function useUploadReaper(draft: Pick<Draft, "slots" | "refs">) {
+export function useUploadReaper(draft: Pick<Draft, "slots" | "refs" | "frames">) {
useEffect(() => {
if (!inflight.size) return;
- const ids = new Set([...Object.values(draft.slots), ...draft.refs].map((v) => v?.id).filter(Boolean));
+ const ids = new Set([...Object.values(draft.slots), ...draft.refs, ...(draft.frames ?? []).map((f) => f.value)].map((v) => v?.id).filter(Boolean));
for (const [id, e] of inflight) {
if (ids.has(id)) e.seen = true;
else if (e.seen) {
@@ -27,9 +28,12 @@ export function useUploadReaper(draft: Pick<Draft, "slots" | "refs">) {
inflight.delete(id);
}
}
- }, [draft.slots, draft.refs]);
+ }, [draft.slots, draft.refs, draft.frames]);
}
+/** Frames mode is full. */
+const FRAMES_FULL = `Frames mode takes up to ${MAX_KEYFRAMES} frames — remove one to add another`;
+
/** Paste / drop / "+" take at most this many files in one go. */
const MAX_AT_ONCE = 8;
@@ -81,10 +85,11 @@ export function useAttach(slots: InputSlot[], refMax: number) {
const noRoom = useCallback(() => toast(noRoomMessage(refMax, config.multiRef?.kind)), [refMax, config.multiRef]);
- /** Put it wherever it fits best: the first empty slot of its kind, else the references. */
+ /** Put it wherever it fits best: the first empty slot of its kind, else the references (in Frames mode: the next frame). */
const place = useCallback(
(v: SlotValue) =>
setDraft((d) => {
+ if (d.frames) return d.frames.length < MAX_KEYFRAMES && v.kind === "image" ? { frames: addFrame(d.frames, v) } : {};
const r = placeAttachment(d, slots, config.multiRef, refMax, v);
if (!r) return {};
// Pasting over a full image slot drops the drawing made on the old image.
@@ -96,7 +101,11 @@ export function useAttach(slots: InputSlot[], refMax: number) {
/** A library pick (an attachment that needs no upload). */
const attach = useCallback(
(v: SlotValue) => {
- if (!placeAttachment(latest.current, slots, config.multiRef, refMax, v)) return noRoom();
+ const frames = latest.current.frames;
+ if (frames) {
+ if (v.kind !== "image") return void toast("Frames are images — add a still");
+ if (frames.length >= MAX_KEYFRAMES) return void toast(FRAMES_FULL);
+ } else if (!placeAttachment(latest.current, slots, config.multiRef, refMax, v)) return noRoom();
place(v);
},
[place, noRoom, slots, config.multiRef, refMax],
@@ -104,8 +113,16 @@ export function useAttach(slots: InputSlot[], refMax: number) {
const attachFiles = useCallback(
(files: File[]) => {
- const usable = files.filter((f) => kinds.has(kindOfFile(f)));
- if (usable.length < files.length) toast(files.length - usable.length > 1 ? "This studio doesn't take those files" : "This studio doesn't take that kind of file");
+ const frames = latest.current.frames;
+ // Frames mode: each still becomes the next frame, up to ten.
+ const usable = files.filter((f) => (frames ? kindOfFile(f) === "image" : kinds.has(kindOfFile(f))));
+ if (usable.length < files.length) toast(frames ? "Frames are images — the other files were left out" : files.length - usable.length > 1 ? "This studio doesn't take those files" : "This studio doesn't take that kind of file");
+ if (frames) {
+ const room = MAX_KEYFRAMES - frames.length;
+ if (usable.length > room) toast(FRAMES_FULL);
+ for (const f of usable.slice(0, Math.max(0, room))) start(f, place, "image");
+ return;
+ }
if (usable.length > MAX_AT_ONCE) toast(`Added the first ${MAX_AT_ONCE} — that's the most at once`);
const batch = usable.slice(0, MAX_AT_ONCE);
// Room first: a file with nowhere to go never uploads.
@@ -131,7 +148,22 @@ export function useAttach(slots: InputSlot[], refMax: number) {
[start, setDraft, config.multiRef, refMax, noRoom],
);
- return useMemo(() => ({ kinds, attach, attachFiles, setSlotValue, uploadToSlot, removeRef, addRefFile }), [kinds, attach, attachFiles, setSlotValue, uploadToSlot, removeRef, addRefFile]);
+ /** A frame's tile: a new still in its place (its time stays), or null to take the frame out. */
+ const setFrameValue = useCallback(
+ (i: number, v: SlotValue | null) =>
+ setDraft((d) => {
+ if (!d.frames?.[i]) return {};
+ return { frames: v ? d.frames.map((f, j) => (j === i ? { ...f, value: v } : f)) : removeFrame(d.frames, i) };
+ }),
+ [setDraft],
+ );
+
+ const uploadToFrame = useCallback((i: number, file: File) => start(file, (v) => setFrameValue(i, v), "image"), [start, setFrameValue]);
+
+ return useMemo(
+ () => ({ kinds, attach, attachFiles, setSlotValue, uploadToSlot, removeRef, addRefFile, setFrameValue, uploadToFrame }),
+ [kinds, attach, attachFiles, setSlotValue, uploadToSlot, removeRef, addRefFile, setFrameValue, uploadToFrame],
+ );
}
/**
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index d4a0bf69..2a9a1fc4 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ArrowUp, AtSign, Loader2, Sparkles, X } from "lucide-react";
+import { ArrowUp, AtSign, GalleryHorizontalEnd, Loader2, Sparkles, X } from "lucide-react";
import dynamic from "next/dynamic";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
@@ -12,12 +12,31 @@ import type { GenerationRequest, MediaKind, ModelDef, Operation, Preset } from "
import { enhance, useCreateGeneration, useElements, useEngine, useHydrated, useStatus } from "@/lib/api";
import { applyMentions, type StudioElement } from "@/lib/catalog/elements";
import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";
-import { blockerFor, costLabel, filterModels, firstMissingSlot, namedImageSlots, needsMask, PLACEHOLDER, promptShown, pushRecent, settingsShape, startStep } from "@/lib/composer";
+import { chainGapProblem, chainTiming, frameSupport, framesBlocker, framesDuration, framesDurations, framesNote, FRAMES_MODELS, frameTimes, keyframeChain, moveFrameAt, type FrameSupport } from "@/lib/catalog/keyframes";
+import {
+ blockerFor,
+ costLabel,
+ enterFrames,
+ filterModels,
+ firstMissingSlot,
+ framesRequest,
+ framesShape,
+ leaveFrames,
+ namedImageSlots,
+ needsMask,
+ onImageChange,
+ PLACEHOLDER,
+ promptShown,
+ pushRecent,
+ settingsShape,
+ startStep,
+} from "@/lib/composer";
import { formatCost } from "@/lib/format";
import { cn } from "@/lib/utils";
import { AttachMenu } from "./attach-menu";
import { useAttach, useComposerBridge, useUploadReaper } from "./attachments";
import { DialogueEditor, LanguageChip, VoicePicker } from "./audio-controls";
+import { FramesStrip, type FramesNotice } from "./frames-strip";
import { loadFullCatalog, useCatalog } from "./catalog";
import { Chip, chipBase, chipIdle } from "./chip";
import { MediaSlot, SlotPreview, type SlotValue } from "./media-slot";
@@ -56,17 +75,34 @@ const defaultLines = (m: ModelDef) => {
// ---------------------------------------------------------------------------
+/** Frames mode, as the request needs it: what the model does with frames, the clip's length, and whether it's the open chain. */
+interface FramesContext {
+ support: FrameSupport;
+ duration: number;
+ chained: boolean;
+}
+
function buildRequest(
feature: string,
- draft: Pick<Draft, "slots" | "refs" | "presetId" | "modelId" | "prompt" | "negativePrompt" | "params" | "presetOptions" | "presetStrength" | "mix">,
+ draft: Pick<Draft, "slots" | "refs" | "presetId" | "modelId" | "prompt" | "negativePrompt" | "params" | "presetOptions" | "presetStrength" | "mix" | "frames">,
op: Operation | undefined,
promptSuffix?: string,
refKind: MediaKind = "image",
+ frames?: FramesContext,
): GenerationRequest {
const s = draft.slots;
const refs = draft.refs.filter((x) => !!x?.ref).map((x) => x.ref);
- const images = [s.image, s.image2, s.image3].filter((x): x is SlotValue => !!x?.ref).map((x) => x.ref).concat(refKind === "image" ? refs : []);
+ let images = [s.image, s.image2, s.image3].filter((x): x is SlotValue => !!x?.ref).map((x) => x.ref).concat(refKind === "image" ? refs : []);
const videos = refKind === "video" ? refs : [];
+ let endImage = s.endImage?.ref || undefined;
+ let params = draft.params;
+ // Frames mode: the stills in order at their times (or the first and last as start and end frame), at the strip's length.
+ if (draft.frames && frames) {
+ const sent = framesRequest(draft.frames, frames);
+ images = sent.images;
+ endImage = sent.endImage;
+ params = { ...params, ...sent.params };
+ }
return {
feature,
presetId: draft.presetId,
@@ -76,16 +112,16 @@ function buildRequest(
negativePrompt: draft.negativePrompt || undefined,
inputs: {
images: images.length ? images : undefined,
- endImage: s.endImage?.ref || undefined,
+ endImage,
mask: s.mask?.ref || undefined,
sketch: s.sketch?.ref || undefined,
voiceAudio: s.voiceAudio?.ref || undefined,
voiceAudio2: s.voiceAudio2?.ref || undefined,
video: s.video?.ref || undefined,
audio: s.audio?.ref || undefined,
- videos: videos.length ? videos : undefined,
+ videos: videos.length && !draft.frames ? videos : undefined,
},
- params: draft.params,
+ params,
presetOptions: draft.presetOptions,
...(draft.presetId && draft.presetStrength !== undefined && draft.presetStrength < 1 && { presetStrength: draft.presetStrength }),
...(draft.presetId && draft.mix && { mix: draft.mix }),
@@ -190,6 +226,11 @@ export function Composer({ docked }: { docked: boolean }) {
: Math.min(config.multiRef.max, Math.max(0, (opts.maxImages ?? 1) - slots.filter((s) => s.accept === "image").length));
const attach = useAttach(slots, refMax);
+ // Frames mode (Video studio): up to 10 stills at their times, as the picked model can take them.
+ const framesOn = !!config.frames && !!draft.frames;
+ const framesCtx: FramesContext | undefined =
+ framesOn && model ? { support: frameSupport(model), duration: framesDuration(model, draft.params.duration), chained: !!keyframeChain(model) } : undefined;
+
// The page's drop zone hands its files to this composer.
useEffect(() => {
if (!bridgeRef) return;
@@ -202,7 +243,7 @@ export function Composer({ docked }: { docked: boolean }) {
// A picked palette / moodboard routes the request (and can move it to another model) before anything else.
const signature = useSignature(!!config.signature, draft.signature);
const prepare = (d: typeof draft) => {
- const signed = signature.apply(buildRequest(config.feature, d, studioOp, config.promptSuffix, config.multiRef?.kind));
+ const signed = signature.apply(buildRequest(config.feature, d, studioOp, config.promptSuffix, config.multiRef?.kind, framesCtx));
// Planned with the signature's sentences in the prompt (as the server runs it); sent with them apart.
const raw = signed.worded;
const m = catalog.getModel(raw.modelId) ?? model;
@@ -232,7 +273,12 @@ export function Composer({ docked }: { docked: boolean }) {
const first = slots.find((s) => s.key === g[0]);
if (first && !g.some((k) => planSlots[k]?.ref)) planSlots[first.key] = { ref: PLACEHOLDER[first.accept], preview: "", kind: first.accept };
}
- const { request: planned } = prepare({ ...draft, slots: planSlots, refs: draft.refs.map((r) => stand(r, r.kind) as SlotValue) });
+ const { request: planned } = prepare({
+ ...draft,
+ slots: planSlots,
+ refs: draft.refs.map((r) => stand(r, r.kind) as SlotValue),
+ frames: draft.frames?.map((f) => ({ ...f, value: stand(f.value, "image") as SlotValue })),
+ });
const plan = planGeneration({ ...planned, prompt: planned.prompt || (config.promptOptional ? " " : "") }, catalog.getModel, catalog.getPreset);
op = plan.op;
cost = estimateCost(plan.model, plan.params, plan.jobs);
@@ -248,6 +294,7 @@ export function Composer({ docked }: { docked: boolean }) {
loading: !catalog.ready ? "Loading models…" : presetLoading ? "Loading presets…" : null,
model: !!model,
engineError,
+ frames: framesOn && model ? framesBlocker(model, draft.frames!.length) : null,
missing,
uploading,
maskMissing: needsMask(model, config.sketch, draft.slots),
@@ -272,7 +319,7 @@ export function Composer({ docked }: { docked: boolean }) {
setRecent((r) => pushRecent(r, draft.modelId));
// The server resolves @mentions and drawings itself; only pin the operation when there are none.
// No "Queued" toast: the new card (and the "1 generating ↑" pill when it's off-screen) says it.
- const sent = signature.apply(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind));
+ const sent = signature.apply(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx));
// Open palette lock: the images are recoloured to the palette by a chained step (POST /api/palettes/lock).
if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors }, { onError: (e) => toast.error((e as Error).message) });
create.mutate(sent.request, {
@@ -315,7 +362,8 @@ export function Composer({ docked }: { docked: boolean }) {
const opNote = op && model ? routesFor(model, op)[0]?.note : undefined;
const showPrompt = promptShown(config.hidePrompt, preset?.userPrompt, model?.options.promptless);
const effectiveOp = studioOp ?? op;
- const shape = settingsShape(model, effectiveOp, config.kind, showPrompt, p, config.ops);
+ const baseShape = settingsShape(model, effectiveOp, config.kind, showPrompt, p, config.ops);
+ const shape = framesCtx ? framesShape(baseShape, framesCtx.chained) : baseShape;
const demo = !!(model && status && status.demoMode !== "off" && !model.routes.some((r) => status.providers[r.provider]?.configured));
const costText = costLabel({ demo, cost }, formatCost);
@@ -324,10 +372,11 @@ export function Composer({ docked }: { docked: boolean }) {
const hasAttachment = slots.some((s) => draft.slots[s.key]) || draft.refs.length > 0;
// Tools whose only input is a list of clips (Join clips) keep their "Add clip" tile in view.
const showAttachments =
- (slots.length > 0 || !!config.multiRef) && (hasAttachment || !!missing || !!slots.find((s) => s.required && !draft.slots[s.key]) || (!!config.multiRef && !showPrompt));
+ framesOn ||
+ ((slots.length > 0 || !!config.multiRef) && (hasAttachment || !!missing || !!slots.find((s) => s.required && !draft.slots[s.key]) || (!!config.multiRef && !showPrompt)));
const collapsed = docked && !focused;
// Docked and not focused, the tiles fold into one chip on the toolbar (the composer stays one line).
- const attached = [...slots.map((s) => draft.slots[s.key]), ...draft.refs].filter((v): v is SlotValue => !!v);
+ const attached = [...slots.map((s) => draft.slots[s.key]), ...draft.refs, ...(draft.frames ?? []).map((f) => f.value)].filter((v): v is SlotValue => !!v);
// A blocker toast goes away once it's out of date: the photo attached, the prompt typed (or the next blocker is a different one).
const blocking = blocker?.message;
@@ -355,6 +404,60 @@ export function Composer({ docked }: { docked: boolean }) {
if (step === "explain" && blockedSlot) requestAnimationFrame(() => slotButton(root.current, blockedSlot)?.focus({ preventScroll: true }));
}, [step, startRequest, blockedSlot]);
+ const pickModel = (m: ModelDef) => {
+ setDraft((d) => ({ modelId: m.id, params: { ...m.defaults, numOutputs: d.params.numOutputs, enhancePrompt: d.params.enhancePrompt, seed: d.params.seed } }));
+ if (m.engine !== engine) setEngine(m.engine);
+ };
+
+ // Frames on: the start and end frames already attached become the first frames. Off: the first and last frames
+ // go back to start and end (the ones in between can come back with Undo).
+ const framesLength = framesCtx?.duration ?? (model ? framesDuration(model, p.duration) : p.duration);
+ const toggleFrames = () => {
+ if (!draft.frames) {
+ setDraft((d) => {
+ const entered = enterFrames(d.slots);
+ const cleared = onImageChange(d, entered.slots);
+ return { frames: entered.frames, slots: cleared.slots, params: { ...(cleared.params ?? d.params), shots: undefined, multiShot: undefined, duration: framesLength } };
+ });
+ setFocused(true);
+ return;
+ }
+ const before = { frames: draft.frames, slots: draft.slots, params: draft.params };
+ const { slots: back, dropped } = leaveFrames(draft.frames, draft.slots);
+ // A length only the open chain makes goes back to the nearest one the model makes on its own.
+ const lengths = opts.durations;
+ const duration = lengths?.length && p.duration !== undefined && !lengths.includes(p.duration) ? lengths.reduce((a, b) => (Math.abs(b - p.duration!) < Math.abs(a - p.duration!) ? b : a)) : p.duration;
+ setDraft({ frames: undefined, slots: back, params: { ...p, duration } });
+ if (dropped) toast(`Frames off — frames 1 and ${draft.frames.length} are your start and end frames`, { action: { label: "Undo", onClick: () => setDraft(before) } });
+ };
+
+ // What the model does with the frames, said under the strip before anything runs (with the model that takes them all).
+ let framesNotice: FramesNotice | null = null;
+ if (framesCtx && model && draft.frames) {
+ const alt = catalog.getModel(FRAMES_MODELS[model.engine].id);
+ const action = alt && alt.id !== model.id ? { label: `Use ${alt.name}`, onClick: () => pickModel(alt) } : undefined;
+ const count = draft.frames.length;
+ const times = frameTimes(
+ draft.frames.map((f) => f.at),
+ framesCtx.duration,
+ );
+ const gap = framesCtx.chained && count > 1 ? chainGapProblem(times, framesCtx.duration, chainTiming(model)) : null;
+ const note = framesNote(model, count, draft.frames.at(-1)?.at);
+ if (framesCtx.support === "start" || framesCtx.support === "none") framesNotice = { text: `${framesBlocker(model, count)!.message}.`, tone: "warn", action };
+ else if (gap) framesNotice = { text: `${gap}.`, tone: "warn" };
+ else if (note) framesNotice = { text: note, tone: "info", action };
+ }
+ const framesChip = config.frames ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Chip icon={GalleryHorizontalEnd} active={framesOn} aria-pressed={framesOn} onClick={toggleFrames}>
+ Frames
+ </Chip>
+ </TooltipTrigger>
+ <TooltipContent>{framesOn ? "Back to a start and an end frame" : "Up to 10 frames, each at its own time"}</TooltipContent>
+ </Tooltip>
+ ) : null;
+
// Voice, language, motion, style and Director chips: inline from sm up; on phones they live in the settings sheet, so the toolbar fits.
const voiceChips = (
<>
@@ -416,6 +519,7 @@ export function Composer({ docked }: { docked: boolean }) {
</>
);
const hasSecondary =
+ !!config.frames ||
(!!model && (!!opts.voices?.length || !!opts.voiceClone || !!opts.languages || !!opts.presets || !!opts.controls)) ||
!!config.presetPicker ||
!!config.signature ||
@@ -445,7 +549,33 @@ export function Composer({ docked }: { docked: boolean }) {
}
}}
>
- {showAttachments && !collapsed && (
+ {framesOn && !collapsed && draft.frames && (
+ <FramesStrip
+ frames={draft.frames}
+ duration={framesCtx?.duration ?? p.duration ?? 5}
+ durations={model ? framesDurations(model) : [5]}
+ onDuration={(duration) => setP({ duration })}
+ onMove={(i, seconds) =>
+ setDraft((d) => {
+ if (!d.frames || !framesCtx) return {};
+ const ats = moveFrameAt(
+ d.frames.map((f) => f.at),
+ i,
+ seconds,
+ framesCtx.duration,
+ );
+ return { frames: d.frames.map((f, j) => ({ ...f, at: ats[j] })) };
+ })
+ }
+ onFrame={attach.setFrameValue}
+ onFrameFile={attach.uploadToFrame}
+ onAddFile={(f) => attach.attachFiles([f])}
+ onAddPick={attach.attach}
+ onClose={toggleFrames}
+ notice={framesNotice}
+ />
+ )}
+ {showAttachments && !collapsed && !framesOn && (
<div className="scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-1.5 pb-2">
{slots.map((s) => (
<MediaSlot
@@ -601,10 +731,7 @@ export function Composer({ docked }: { docked: boolean }) {
engine={engine}
onEngineChange={setEngine}
defaultModels={config.defaultModels}
- onChange={(m) => {
- setDraft((d) => ({ modelId: m.id, params: { ...m.defaults, numOutputs: d.params.numOutputs, enhancePrompt: d.params.enhancePrompt, seed: d.params.seed } }));
- if (m.engine !== engine) setEngine(m.engine);
- }}
+ onChange={pickModel}
/>
) : (
<Chip icon={Loader2} disabled className="[&>svg]:animate-spin">
@@ -641,7 +768,10 @@ export function Composer({ docked }: { docked: boolean }) {
<TooltipContent>Add a character, location or prop · type @</TooltipContent>
</Tooltip>
)}
- <span className="contents max-sm:hidden">{voiceChips}</span>
+ <span className="contents max-sm:hidden">
+ {framesChip}
+ {voiceChips}
+ </span>
<SettingsChip
model={model}
op={op}
@@ -659,6 +789,7 @@ export function Composer({ docked }: { docked: boolean }) {
extras={
hasSecondary ? (
<>
+ {framesChip}
{voiceChips}
{styleChips}
</>
diff --git a/src/components/studio/frames-strip.tsx b/src/components/studio/frames-strip.tsx
new file mode 100644
index 00000000..244d1701
--- /dev/null
+++ b/src/components/studio/frames-strip.tsx
@@ -0,0 +1,323 @@
+"use client";
+
+import { Loader2, Minus, Plus, X } from "lucide-react";
+import { useId, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { FRAMES_HINT, frameRange, frameTimes, KEYFRAME_SNAP, MAX_KEYFRAMES, secondsLabel } from "@/lib/catalog/keyframes";
+import type { FrameAttachment } from "@/lib/composer";
+import { cn } from "@/lib/utils";
+import { ACCEPT, kindOfFile, MediaSlot, SlotPreview, wrongKindMessage, type SlotValue } from "./media-slot";
+
+export interface FramesNotice {
+ text: string;
+ /** "warn": Generate waits for it; "info": what the model will do. */
+ tone: "info" | "warn";
+ action?: { label: string; onClick: () => void };
+}
+
+const pct = (t: number, duration: number) => `${duration > 0 ? (t / duration) * 100 : 0}%`;
+
+/**
+ * Frames mode's strip (Kling 4.0's Frames, Higgsfield G02): up to 10 frame tiles in order, each with
+ * its time, a ruler to drag them along (snapped to 0.1 s; the first is the start frame and stays at 0),
+ * and the clip's length. Positions are fractions of the clip, so a longer clip stretches them.
+ */
+export function FramesStrip({
+ frames,
+ duration,
+ durations,
+ onDuration,
+ onMove,
+ onFrame,
+ onFrameFile,
+ onAddFile,
+ onAddPick,
+ onClose,
+ notice,
+}: {
+ frames: FrameAttachment<SlotValue>[];
+ duration: number;
+ durations: number[];
+ onDuration: (seconds: number) => void;
+ /** Frame i dragged (or stepped with the keys) to this many seconds. */
+ onMove: (i: number, seconds: number) => void;
+ /** Frame i replaced by another still, or taken out (null). */
+ onFrame: (i: number, v: SlotValue | null) => void;
+ onFrameFile: (i: number, f: File) => void;
+ onAddFile: (f: File) => void;
+ onAddPick: (v: SlotValue) => void;
+ onClose: () => void;
+ notice?: FramesNotice | null;
+}) {
+ const titleId = useId();
+ const hintId = useId();
+ const times = frameTimes(
+ frames.map((f) => f.at),
+ duration,
+ );
+ return (
+ <div role="group" aria-labelledby={titleId} aria-describedby={hintId} data-frames-strip className="space-y-1.5 px-1 pt-1 pb-2">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 pl-1">
+ <span id={titleId} className="text-[13px] font-medium">
+ Frames
+ </span>
+ <span id={hintId} className="order-last basis-full text-[12px] leading-snug text-muted-foreground sm:order-none sm:basis-auto">
+ {FRAMES_HINT}
+ </span>
+ <div className="ml-auto flex items-center gap-1">
+ <LengthStepper value={duration} options={durations} onDuration={onDuration} />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Turn off Frames"
+ className="grid size-7 place-items-center rounded-full text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <X className="size-3.5" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Back to a start and an end frame</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+
+ <div className="scrollbar-none flex items-start gap-2 overflow-x-auto px-1 pt-1.5">
+ {frames.map((f, i) => (
+ <FrameTile key={f.value.id ?? `${f.value.ref}-${i}`} index={i} value={f.value} time={times[i]} onChange={(v) => onFrame(i, v)} onFile={(file) => onFrameFile(i, file)} />
+ ))}
+ {frames.length < MAX_KEYFRAMES && (
+ <div className="flex shrink-0 flex-col items-center gap-1">
+ <MediaSlot slotKey="frames" label={frames.length ? "Add frame" : "Start frame"} kind="image" required={!frames.length} value={null} onChange={(v) => v && onAddPick(v)} onFile={onAddFile} />
+ <span className="text-[11px] text-subtle-foreground tabular-nums">
+ {frames.length} of {MAX_KEYFRAMES}
+ </span>
+ </div>
+ )}
+ </div>
+
+ {frames.length > 0 && <Ruler frames={frames} times={times} duration={duration} onMove={onMove} />}
+
+ {notice && (
+ <p className={cn("px-1 text-[12px] leading-snug", notice.tone === "warn" ? "text-warning" : "text-muted-foreground")} role={notice.tone === "warn" ? "status" : undefined}>
+ {notice.text}
+ {notice.action && (
+ <>
+ {" "}
+ <button type="button" onClick={notice.action.onClick} className="font-medium text-brand-text underline-offset-2 hover:underline">
+ {notice.action.label}
+ </button>
+ </>
+ )}
+ </p>
+ )}
+ </div>
+ );
+}
+
+/** The clip's length: one of the lengths the model (or the open chain) makes. */
+function LengthStepper({ value, options, onDuration }: { value: number; options: number[]; onDuration: (seconds: number) => void }) {
+ const sorted = [...new Set(options)].sort((a, b) => a - b);
+ const i = sorted.indexOf(value);
+ const lower = i < 0 ? sorted.findLast((x) => x < value) : sorted[i - 1];
+ const higher = i < 0 ? sorted.find((x) => x > value) : sorted[i + 1];
+ return (
+ <div role="group" aria-label="Clip length" className="flex items-center gap-0.5 rounded-full bg-muted p-0.5">
+ <button
+ type="button"
+ onClick={() => lower !== undefined && onDuration(lower)}
+ disabled={lower === undefined}
+ aria-label="Shorter clip"
+ className="grid size-6 place-items-center rounded-full transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-40"
+ >
+ <Minus className="size-3" />
+ </button>
+ <span className="min-w-9 text-center text-[12px] font-medium tabular-nums" aria-live="polite">
+ {value} s
+ </span>
+ <button
+ type="button"
+ onClick={() => higher !== undefined && onDuration(higher)}
+ disabled={higher === undefined}
+ aria-label="Longer clip"
+ className="grid size-6 place-items-center rounded-full transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-40"
+ >
+ <Plus className="size-3" />
+ </button>
+ </div>
+ );
+}
+
+/** A filled frame: its still (click or drop to replace it), its number, its time, and remove. */
+function FrameTile({ index, value, time, onChange, onFile }: { index: number; value: SlotValue; time: number; onChange: (v: SlotValue | null) => void; onFile: (f: File) => void }) {
+ const input = useRef<HTMLInputElement>(null);
+ const [over, setOver] = useState(false);
+ const name = index === 0 ? "the start frame" : `frame ${index + 1}`;
+ const take = (f: File | undefined) => {
+ if (!f) return;
+ if (kindOfFile(f) !== "image") return void toast(wrongKindMessage("image"));
+ onFile(f);
+ };
+ return (
+ <div className="flex shrink-0 flex-col items-center gap-1">
+ <div
+ className="relative size-14 shrink-0"
+ onDragOver={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setOver(false);
+ take(e.dataTransfer.files?.[0]);
+ }}
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => input.current?.click()}
+ aria-label={`Frame ${index + 1}${index === 0 ? ", the start frame" : ""}, at ${secondsLabel(time)}: replace`}
+ className={cn("size-full overflow-hidden rounded-xl border bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring/50", over && "ring-2 ring-primary")}
+ >
+ <SlotPreview value={{ ...value, name: "" }} />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{index === 0 ? "Start frame" : `Frame ${index + 1} at ${secondsLabel(time)}`} — click or drop to replace</TooltipContent>
+ </Tooltip>
+ {value.uploading && (
+ <div className="pointer-events-none absolute inset-0 grid place-items-center rounded-xl bg-background/60" role="status" aria-label="Uploading">
+ <Loader2 className="size-4 animate-spin" />
+ </div>
+ )}
+ <span aria-hidden className="pointer-events-none absolute bottom-1 left-1 grid h-4 min-w-4 place-items-center rounded-full bg-background/90 px-1 text-[10px] font-semibold tabular-nums">
+ {index + 1}
+ </span>
+ <button
+ type="button"
+ onClick={() => onChange(null)}
+ className="absolute -top-1.5 -right-1.5 grid size-5 place-items-center rounded-full bg-foreground text-background shadow-soft"
+ aria-label={`Remove ${name}`}
+ >
+ <X className="size-3" />
+ </button>
+ <input
+ ref={input}
+ type="file"
+ accept={ACCEPT.image}
+ hidden
+ onChange={(e) => {
+ take(e.target.files?.[0]);
+ e.target.value = "";
+ }}
+ />
+ </div>
+ <span className="text-[11px] font-medium text-muted-foreground tabular-nums">{index === 0 ? "Start" : secondsLabel(time)}</span>
+ </div>
+ );
+}
+
+/** Seconds between labelled ticks for a clip this long. */
+const labelEvery = (d: number) => (d <= 5 ? 1 : d <= 10 ? 2 : d <= 20 ? 5 : 10);
+
+/**
+ * The time ruler: one marker per frame at its time. Drag a marker (it snaps to 0.1 s and stays between
+ * its neighbours), or focus it and use the arrow keys (0.1 s; Shift or Page Up / Down: 1 s; Home / End).
+ */
+function Ruler({ frames, times, duration, onMove }: { frames: FrameAttachment<SlotValue>[]; times: number[]; duration: number; onMove: (i: number, seconds: number) => void }) {
+ const track = useRef<HTMLDivElement>(null);
+ const [active, setActive] = useState<number | null>(null);
+ const secondsAt = (clientX: number) => {
+ const r = track.current?.getBoundingClientRect();
+ return r && r.width ? ((clientX - r.left) / r.width) * duration : 0;
+ };
+ const every = labelEvery(duration);
+ const ticks = Array.from({ length: Math.floor(duration) + 1 }, (_, t) => t);
+ const labels = ticks.filter((t) => t % every === 0 && duration - t >= every / 2).concat(duration);
+ return (
+ <div className="px-3.5 pt-0.5">
+ <div ref={track} className="relative h-9 select-none">
+ <div aria-hidden className="absolute inset-x-0 top-1/2 h-1 -translate-y-1/2 rounded-full bg-muted" />
+ {ticks.map((t) => (
+ <span key={t} aria-hidden className={cn("absolute top-1/2 w-px -translate-y-1/2 bg-border-strong", t % every === 0 ? "h-3" : "h-1.5")} style={{ left: pct(t, duration) }} />
+ ))}
+ {frames.map((f, i) => {
+ const thumb = <SlotPreview value={{ ...f.value, name: "" }} />;
+ const base = "absolute top-1/2 size-7 -translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-full border-2 border-background bg-muted shadow-soft ring-1 ring-border";
+ if (i === 0)
+ return (
+ <span key={f.value.id ?? i} role="img" aria-label="Frame 1, the start frame, at 0 s" className={base} style={{ left: 0 }}>
+ {thumb}
+ </span>
+ );
+ const [lo, hi] = frameRange(times, i, duration);
+ const step = (by: number) => onMove(i, times[i] + by);
+ return (
+ <button
+ key={f.value.id ?? i}
+ type="button"
+ role="slider"
+ aria-label={`Frame ${i + 1} time`}
+ aria-valuemin={lo}
+ aria-valuemax={hi}
+ aria-valuenow={times[i]}
+ aria-valuetext={secondsLabel(times[i])}
+ onPointerDown={(e) => {
+ e.preventDefault();
+ e.currentTarget.focus();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ setActive(i);
+ }}
+ onPointerMove={(e) => {
+ if (active === i && e.currentTarget.hasPointerCapture(e.pointerId)) onMove(i, secondsAt(e.clientX));
+ }}
+ onPointerUp={() => setActive(null)}
+ onPointerCancel={() => setActive(null)}
+ onKeyDown={(e) => {
+ const big = e.shiftKey ? 1 : KEYFRAME_SNAP;
+ const moves: Record<string, () => void> = {
+ ArrowRight: () => step(big),
+ ArrowUp: () => step(big),
+ ArrowLeft: () => step(-big),
+ ArrowDown: () => step(-big),
+ PageUp: () => step(1),
+ PageDown: () => step(-1),
+ Home: () => onMove(i, lo),
+ End: () => onMove(i, hi),
+ };
+ const move = moves[e.key];
+ if (!move) return;
+ e.preventDefault();
+ move();
+ }}
+ className={cn(
+ base,
+ "z-10 cursor-grab touch-none outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing",
+ active === i && "z-20 cursor-grabbing ring-2 ring-primary",
+ )}
+ style={{ left: pct(times[i], duration) }}
+ >
+ {thumb}
+ </button>
+ );
+ })}
+ {active !== null && (
+ <span aria-hidden className="pointer-events-none absolute -top-5 z-30 -translate-x-1/2 rounded-md bg-foreground px-1.5 py-0.5 text-[11px] font-medium text-background tabular-nums" style={{ left: pct(times[active], duration) }}>
+ {secondsLabel(times[active])}
+ </span>
+ )}
+ </div>
+ <div aria-hidden className="relative h-3.5 text-[10px] text-subtle-foreground tabular-nums">
+ {labels.map((t, k) => (
+ <span key={t} className={cn("absolute top-0", k === 0 ? "" : t === duration ? "-translate-x-full" : "-translate-x-1/2")} style={{ left: pct(t, duration) }}>
+ {secondsLabel(t)}
+ </span>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index d7dd7d6b..2f14177b 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -4,6 +4,7 @@ import { createContext, useCallback, useContext, useMemo, useState } from "react
import type { GenParams, InputSlot, MediaKind, Operation, Preset } from "@/lib/catalog/types";
import type { FeedFilter } from "@/lib/api";
import type { Signature } from "@/lib/catalog/palettes";
+import type { FrameAttachment } from "@/lib/composer";
import type { SlotValue } from "./media-slot";
export type SlotKey = InputSlot["key"];
@@ -45,6 +46,8 @@ export interface StudioConfig {
signature?: boolean;
/** Models the studio can be moved to (by the signature chips) beyond its picker list and defaults: kept in its model slice. */
extraModels?: string[];
+ /** Frames mode (Video studio): up to 10 stills, each at its own time in the clip, instead of a start and an end frame. */
+ frames?: boolean;
}
export interface Draft {
@@ -61,6 +64,8 @@ export interface Draft {
mix?: { presetId: string; strength: number };
/** The Color signature and Moodboard picked in the composer (studios with `signature`). */
signature?: Signature;
+ /** Frames mode is on (studios with `frames`): the stills in order, each at its place in the clip. */
+ frames?: FrameAttachment<SlotValue>[];
}
interface Actions {
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index dca7ac8f..dc3b2dd1 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -10,6 +10,7 @@ import { SidebarTrigger } from "@/components/ui/sidebar";
import type { Generation, MediaKind, ModelDef, Preset } from "@/lib/catalog/types";
import { useEngine, useGenerations } from "@/lib/api";
import { claimStartToken, handoffKey, mergeHandoff, promptShown, START_PARAM, withoutStart } from "@/lib/composer";
+import { positionsFrom } from "@/lib/catalog/keyframes";
import { reuseSignature, withSignatureWords } from "@/lib/catalog/palettes";
import { matchSpokenLanguage } from "@/lib/speech-languages";
import { SoulPresetCards } from "@/components/moodboards/soul-preset-cards";
@@ -86,6 +87,13 @@ function draftFromGeneration(g: Generation, config: StudioConfig, getModel: (id:
if (r.inputs?.video) slots.video = slot(r.inputs.video);
if (r.inputs?.audio) slots.audio = slot(r.inputs.audio);
const params = { ...r.params };
+ // A keyframes run comes back in Frames mode, each still at its place in the clip.
+ const times = params.keyframeTimes;
+ const frames =
+ config.frames && times?.length && times.length === imgs.length && imgs.length > 1
+ ? positionsFrom(times, params.duration ?? times[times.length - 1]).map((at, i) => ({ value: slot(imgs[i])!, at }))
+ : undefined;
+ delete params.keyframeTimes;
// A spoken language stored as a name (Assist's "Spanish") or a locale comes back as the model's own code.
const languages = getModel(r.modelId)?.options.sourceLanguages;
if (languages?.length && params.sourceLanguage) params.sourceLanguage = matchSpokenLanguage(params.sourceLanguage, languages) ?? params.sourceLanguage;
@@ -94,8 +102,9 @@ function draftFromGeneration(g: Generation, config: StudioConfig, getModel: (id:
negativePrompt: r.negativePrompt ?? "",
modelId: r.modelId,
params,
- slots,
- refs,
+ slots: frames ? {} : slots,
+ refs: frames ? [] : refs,
+ frames,
presetId: r.presetId,
presetOptions: r.presetOptions ?? {},
presetStrength: r.presetStrength,
diff --git a/src/lib/catalog/keyframes.ts b/src/lib/catalog/keyframes.ts
index 936f7906..5ec2706a 100644
--- a/src/lib/catalog/keyframes.ts
+++ b/src/lib/catalog/keyframes.ts
@@ -183,6 +183,11 @@ export interface ChainTiming {
minSeconds?: number;
}
+/** The open chain's limits for a model: its longest clip is the longest gap between two frames. */
+export function chainTiming(model: Pick<ModelDef, "name" | "options">): ChainTiming {
+ return { name: model.name, maxSeconds: Math.max(...(model.options.durations ?? [5])) };
+}
+
/**
* The open chain's rule for the gaps: each pair of neighbouring frames (and the stretch after the
* last frame, when it isn't at the end) is one clip the model can make. Returns the message for the
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index 1fdb95a5..1637d9ea 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -10,7 +10,7 @@ import type {
PresetRoute,
Pricing,
} from "./types";
-import { chainGapProblem, frameTimes, keyframeChain, MAX_KEYFRAMES, spread } from "./keyframes";
+import { chainGapProblem, chainTiming, frameTimes, keyframeChain, MAX_KEYFRAMES, spread } from "./keyframes";
/** Infer the operation from what the user attached. */
export function inferOperation(model: ModelDef, req: Pick<GenerationRequest, "op" | "inputs" | "params">): Operation {
@@ -305,7 +305,7 @@ function checkKeyframes(model: ModelDef, n: number, params: GenParams) {
}
if (chain && n > 1) {
const length = duration ?? 5;
- const problem = chainGapProblem(times?.length ? times : frameTimes(spread(n), length), length, { name: model.name, maxSeconds: Math.max(...(model.options.durations ?? [5])) });
+ const problem = chainGapProblem(times?.length ? times : frameTimes(spread(n), length), length, chainTiming(model));
if (problem) throw new Error(problem);
}
}
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index f9a53801..afc4bde4 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -3,6 +3,7 @@
* blocker messages, attachment placement and model-picker grouping. No catalog import here, so
* nothing in this file pulls the model list into the browser bundle.
*/
+import { addFrameAt, frameTimes, framesInputs, removeFrameAt, spread, type FrameSupport } from "./catalog/keyframes";
import { COLORMAPS, type Engine, type GenParams, type InputSlot, type MatteOutput, type MediaKind, type ModelDef, type Operation, type Preset } from "./catalog/types";
import { spokenLanguageName } from "./speech-languages";
@@ -76,6 +77,14 @@ export function settingsShape(
};
}
+/**
+ * Frames mode's settings: the strip has its own length control, frames and shots don't mix, and the open
+ * chain makes one film (its clips are the jobs), so it has no batch count.
+ */
+export function framesShape(shape: SettingsShape, chained: boolean): SettingsShape {
+ return { ...shape, duration: null, multiShot: false, count: shape.count && !chained };
+}
+
export const MATTE_OUTPUT_LABELS: Record<MatteOutput, string> = { cutout: "Cutout video", matte: "Alpha mask" };
export const colormapLabel = (v: string) => v.charAt(0).toUpperCase() + v.slice(1);
@@ -204,8 +213,8 @@ export function missingMessage(m: MissingSlot): string {
export interface Blocker {
message: string;
- /** The attachment to point at (pulse) when Generate is pressed ("mask": the Paint area tile). */
- slot?: InputSlot["key"];
+ /** The attachment to point at (pulse) when Generate is pressed ("mask": the Paint area tile; "frames": Frames mode's Add frame tile). */
+ slot?: InputSlot["key"] | "frames";
}
/**
@@ -234,6 +243,8 @@ export function blockerFor(s: {
model: boolean;
engineError?: string | null;
missing?: MissingSlot;
+ /** Frames mode: the start frame to add, or a model that can't follow frames (framesBlocker in catalog/keyframes.ts). */
+ frames?: Blocker | null;
uploading: boolean;
maskMissing?: boolean;
planError?: string | null;
@@ -242,6 +253,7 @@ export function blockerFor(s: {
if (s.loading) return { message: s.loading };
if (!s.model) return { message: "Pick a model" };
if (s.engineError) return { message: s.engineError };
+ if (s.frames) return s.frames;
if (s.missing) return { message: missingMessage(s.missing), slot: s.missing.key };
if (s.uploading) return { message: "Uploading…" };
if (s.maskMissing) return { message: "Paint the area to change", slot: "mask" };
@@ -309,19 +321,81 @@ export function placeAttachment<T extends Attachment>(
* replaced it meanwhile, nothing changes: a finished upload never brings a removed item back.
*/
export function replaceAttachment<T extends Attachment>(
- state: { slots: Partial<Record<InputSlot["key"], T | null>>; refs: T[] },
+ state: { slots: Partial<Record<InputSlot["key"], T | null>>; refs: T[]; frames?: FrameAttachment<T>[] },
id: string,
v: T | null,
-): { slots?: Partial<Record<InputSlot["key"], T | null>>; refs?: T[] } | null {
+): { slots?: Partial<Record<InputSlot["key"], T | null>>; refs?: T[]; frames?: FrameAttachment<T>[] } | null {
for (const [k, s] of Object.entries(state.slots) as [InputSlot["key"], T | null][]) {
if (s?.id === id) return { slots: { ...state.slots, [k]: v ? { ...v, id } : null } };
}
if (state.refs.some((r) => r.id === id)) {
return { refs: v ? state.refs.map((r) => (r.id === id ? { ...v, id } : r)) : state.refs.filter((r) => r.id !== id) };
}
+ // A frame keeps its place in the clip when its upload finishes; a failed one leaves the strip.
+ const f = state.frames?.findIndex((x) => x.value.id === id) ?? -1;
+ if (f >= 0) return { frames: v ? state.frames!.map((x, i) => (i === f ? { ...x, value: { ...v, id } } : x)) : removeFrame(state.frames!, f) };
return null;
}
+// ---------------------------------------------------------------------------
+// Frames mode (Video studio): up to 10 stills, each at its own place in the clip
+
+/** A frame: its still, and where it sits in the clip (0 = the start, 1 = the end; see src/lib/catalog/keyframes.ts). */
+export interface FrameAttachment<T extends Attachment = Attachment> {
+ value: T;
+ at: number;
+}
+
+/** One more frame at the end (evenly spaced frames stay evenly spaced, placed ones keep their places). */
+export function addFrame<T extends Attachment>(frames: FrameAttachment<T>[], value: T): FrameAttachment<T>[] {
+ const ats = addFrameAt(frames.map((f) => f.at));
+ return [...frames, { value, at: 1 }].map((f, i) => ({ ...f, at: ats[i] }));
+}
+
+/** Frame i taken out; the next one becomes the start frame when the first goes. */
+export function removeFrame<T extends Attachment>(frames: FrameAttachment<T>[], i: number): FrameAttachment<T>[] {
+ const ats = removeFrameAt(frames.map((f) => f.at), i);
+ return frames.filter((_, j) => j !== i).map((f, j) => ({ ...f, at: ats[j] }));
+}
+
+/** Frames mode on: the start and end frames already attached become the first frames (a drawing on the start frame goes). */
+export function enterFrames<T extends Attachment>(slots: Partial<Record<InputSlot["key"], T | null>>): { frames: FrameAttachment<T>[]; slots: Partial<Record<InputSlot["key"], T | null>> } {
+ const values = [slots.image, slots.endImage].filter((v): v is T => !!v);
+ const ats = spread(values.length);
+ return { frames: values.map((value, i) => ({ value, at: ats[i] })), slots: { ...slots, image: null, endImage: null, mask: null, sketch: null } };
+}
+
+/**
+ * What Frames mode sends: the stills in order at their times (or the first and last as start and end
+ * frame, as the model takes them), at the strip's length. Frames still uploading (no ref yet) wait.
+ */
+export function framesRequest(
+ frames: FrameAttachment[],
+ ctx: { support: FrameSupport; duration: number; chained: boolean },
+): { images: string[]; endImage?: string; params: Pick<GenParams, "duration" | "keyframeTimes" | "shots" | "multiShot" | "numOutputs"> } {
+ const times = frameTimes(
+ frames.map((f) => f.at),
+ ctx.duration,
+ );
+ const kept = frames.map((f, i) => ({ ref: f.value.ref, time: times[i] })).filter((f) => !!f.ref);
+ const sent = framesInputs(
+ kept.map((f) => f.ref),
+ kept.map((f) => f.time),
+ ctx.support,
+ );
+ // Frames and shots don't mix; the open chain makes one film (its clips are the jobs).
+ return { images: sent.images ?? [], endImage: sent.endImage, params: { duration: ctx.duration, keyframeTimes: sent.keyframeTimes, shots: undefined, multiShot: undefined, ...(ctx.chained && { numOutputs: 1 }) } };
+}
+
+/**
+ * Frames mode off: the first frame is the start frame again and the last (with two or more) the end
+ * frame. `dropped` counts the frames in between that have no slot to go to (the composer offers Undo).
+ */
+export function leaveFrames<T extends Attachment>(frames: FrameAttachment<T>[], slots: Partial<Record<InputSlot["key"], T | null>>): { slots: Partial<Record<InputSlot["key"], T | null>>; dropped: number } {
+ const end = frames.length > 1 ? frames[frames.length - 1].value : null;
+ return { slots: { ...slots, image: frames[0]?.value ?? null, endImage: end, mask: null, sketch: null }, dropped: Math.max(0, frames.length - 2) };
+}
+
/**
* Where a batch of files would land, before any of them uploads: each file's index goes to
* `placed` (it gets a slot or a reference tile) or `rejected` (no room: the references are full or
diff --git a/src/lib/studios.ts b/src/lib/studios.ts
index 77d40095..c895730f 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -80,6 +80,8 @@ export const VIDEO_STUDIO: StudioConfig = {
multiRef: { label: "Add ref", max: 3 },
sketch: ["draw"],
presetPicker: "motion",
+ // Kling 4.0's Frames mode: up to 10 keyframes (FLUX 3 Max on the cloud, Wan 2.2 14B clip by clip on the open engine).
+ frames: true,
defaultModels: { cloud: "seedance-2-5", open: "oss-wan22-14b-fast" },
suggestions: [
"A paper boat drifts down a rain-soaked street gutter, macro, slow motion",
diff --git a/src/server/chains.ts b/src/server/chains.ts
index 397ba8c1..1b5d989e 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -1,7 +1,7 @@
import "server-only";
import { nanoid } from "nanoid";
import { getModel, supportsOp } from "@/lib/catalog";
-import { frameTimes, planKeyframeClips, spread } from "@/lib/catalog/keyframes";
+import { chainTiming, frameTimes, planKeyframeClips, spread } from "@/lib/catalog/keyframes";
import { routesFor } from "@/lib/catalog/plan";
import type { ChainSlot, Engine, Generation, GenerationRequest, ModelDef, ModelRoute, Operation } from "@/lib/catalog/types";
import { db } from "./db";
@@ -179,8 +179,7 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,
const times = original.params?.keyframeTimes?.length ? original.params.keyframeTimes : frameTimes(spread(images.length), duration);
const wf = loadManifest().workflows.find((w) => w.id === route.endpoint);
const clips = planKeyframeClips(times, duration, {
- name: model.name,
- maxSeconds: Math.max(...(model.options.durations ?? [5])),
+ ...chainTiming(model),
fps: Number(wf?.defaults.fps ?? 16),
step: Number(wf?.defaults.frameStep ?? 4),
maxFrames: wf?.limits?.maxFrames,
diff --git a/tests/composer-frames.test.ts b/tests/composer-frames.test.ts
new file mode 100644
index 00000000..7c267d8d
--- /dev/null
+++ b/tests/composer-frames.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "vitest";
+import { getModel, getPreset } from "@/lib/catalog";
+import { frameSupport, framesBlocker, framesDuration, keyframeChain } from "@/lib/catalog/keyframes";
+import { planGeneration } from "@/lib/catalog/plan";
+import { addFrame, blockerFor, enterFrames, framesRequest, framesShape, leaveFrames, removeFrame, replaceAttachment, settingsShape, type Attachment, type FrameAttachment } from "@/lib/composer";
+import { VIDEO_STUDIO } from "@/lib/studios";
+import { studioCatalog } from "@/lib/studio-catalog";
+
+const still = (name: string, extra: Partial<Attachment> = {}): Attachment => ({ id: name, ref: `/api/files/${name}.png`, preview: `/api/files/${name}.png`, kind: "image", ...extra });
+const ctxFor = (id: string, duration?: number) => {
+ const m = getModel(id)!;
+ return { support: frameSupport(m), duration: framesDuration(m, duration), chained: !!keyframeChain(m) };
+};
+const framesOf = (...names: string[]) => names.reduce<FrameAttachment[]>((fs, n) => addFrame(fs, still(n)), []);
+
+describe("Frames mode in the Video studio composer", () => {
+ it("is offered in the Video studio, whose list has the models that take every frame", () => {
+ expect(VIDEO_STUDIO.frames).toBe(true);
+ const ids = studioCatalog(VIDEO_STUDIO).models.map((m) => m.id);
+ expect(ids).toEqual(expect.arrayContaining(["flux-3-max", "oss-wan22-14b-fast", "kling-o3"]));
+ // The client copy keeps the chained route's marker (the field maps stay on the server).
+ const wan = studioCatalog(VIDEO_STUDIO).models.find((m) => m.id === "oss-wan22-14b-fast")!;
+ expect(wan.routes.find((r) => r.op === "keyframes")).toMatchObject({ chained: true });
+ expect(wan.routes.every((r) => !r.map)).toBe(true);
+ });
+
+ it("takes the start and end frames in when it opens, and gives the first and last back when it closes", () => {
+ const start = still("start");
+ const end = still("end");
+ const on = enterFrames({ image: start, endImage: end, sketch: still("drawing") });
+ expect(on.frames).toEqual([
+ { value: start, at: 0 },
+ { value: end, at: 1 },
+ ]);
+ expect(on.slots).toEqual({ image: null, endImage: null, mask: null, sketch: null });
+ expect(enterFrames({}).frames).toEqual([]);
+ const four = framesOf("a", "b", "c", "d");
+ expect(leaveFrames(four, {})).toEqual({ slots: { image: four[0].value, endImage: four[3].value, mask: null, sketch: null }, dropped: 2 });
+ expect(leaveFrames(framesOf("a"), {}).slots).toMatchObject({ image: four[0].value, endImage: null });
+ });
+
+ it("spaces new frames evenly, and a finished upload keeps its frame's place", () => {
+ const fs = framesOf("a", "b", "c");
+ expect(fs.map((f) => f.at)).toEqual([0, 0.5, 1]);
+ const uploading = addFrame(fs, still("d", { ref: "", uploading: true }));
+ expect(uploading.map((f) => f.at)).toEqual([0, 1 / 3, 2 / 3, 1]);
+ const done = replaceAttachment({ slots: {}, refs: [], frames: uploading }, "d", still("d2"));
+ expect(done?.frames?.[3]).toEqual({ value: { ...still("d2"), id: "d" }, at: 1 });
+ // A failed upload leaves the strip; evenly spaced frames close up.
+ expect(replaceAttachment({ slots: {}, refs: [], frames: uploading }, "d", null)?.frames?.map((f) => f.at)).toEqual([0, 0.5, 1]);
+ expect(removeFrame(fs, 0).map((f) => f.value.id)).toEqual(["b", "c"]);
+ });
+
+ it("sends FLUX 3 Max every frame at its time, snapped to 0.1 s, at the strip's length", () => {
+ const fs = framesOf("a", "b", "c", "d");
+ const sent = framesRequest(fs, ctxFor("flux-3-max", 8));
+ expect(sent.images).toEqual(fs.map((f) => f.value.ref));
+ expect(sent.endImage).toBeUndefined();
+ expect(sent.params).toMatchObject({ duration: 8, keyframeTimes: [0, 2.7, 5.3, 8] });
+ expect(sent.params.numOutputs).toBeUndefined();
+ const plan = planGeneration({ feature: "video", modelId: "flux-3-max", prompt: "a paper boat", inputs: { images: sent.images }, params: sent.params }, getModel, getPreset);
+ expect(plan.op).toBe("keyframes");
+ });
+
+ it("keeps only the first and last for a start + end frame model, and the start alone for one frame", () => {
+ const fs = framesOf("a", "b", "c");
+ const sent = framesRequest(fs, ctxFor("kling-o3", 5));
+ expect(sent).toMatchObject({ images: [fs[0].value.ref], endImage: fs[2].value.ref, params: { duration: 5, keyframeTimes: undefined } });
+ const plan = planGeneration({ feature: "video", modelId: "kling-o3", prompt: "x", inputs: { images: sent.images, endImage: sent.endImage }, params: sent.params }, getModel, getPreset);
+ expect(plan.op).toBe("flf2v");
+ expect(framesRequest(framesOf("a"), ctxFor("flux-3-max"))).toMatchObject({ images: ["/api/files/a.png"], params: { keyframeTimes: undefined } });
+ });
+
+ it("makes one film on the open chain, and leaves frames still uploading out", () => {
+ const fs = addFrame(framesOf("a", "b"), still("c", { ref: "", uploading: true }));
+ const sent = framesRequest(fs, ctxFor("oss-wan22-14b-fast", 8));
+ expect(sent.images).toEqual(["/api/files/a.png", "/api/files/b.png"]);
+ expect(sent.params).toMatchObject({ duration: 8, keyframeTimes: [0, 4], numOutputs: 1 });
+ });
+
+ it("asks for the start frame first and says which models can't follow frames", () => {
+ const base = { model: true, uploading: false, promptMissing: true };
+ expect(blockerFor({ ...base, frames: framesBlocker(getModel("flux-3-max")!, 0) })).toEqual({ message: "Add the start frame", slot: "frames" });
+ expect(blockerFor({ ...base, frames: framesBlocker(getModel("oss-ltx25")!, 2) })?.message).toBe("LTX-2.5 takes a start frame only — pick Wan 2.2 14B Lightning to follow your frames, or turn Frames off");
+ // A model that takes every frame (or the ends) falls through to the usual checks.
+ expect(blockerFor({ ...base, frames: framesBlocker(getModel("kling-o3")!, 3) })?.message).toBe("Write a prompt first");
+ expect(blockerFor({ ...base, loading: "Loading models…", frames: framesBlocker(getModel("flux-3-max")!, 0) })?.message).toBe("Loading models…");
+ });
+
+ it("hides the settings the strip owns", () => {
+ const shape = settingsShape(getModel("oss-wan22-14b-fast"), "keyframes", "video", true, {}, VIDEO_STUDIO.ops);
+ expect(shape.duration).not.toBeNull();
+ expect(framesShape(shape, true)).toMatchObject({ duration: null, multiShot: false, count: false });
+ expect(framesShape(settingsShape(getModel("flux-3-max"), "keyframes", "video", true, {}, VIDEO_STUDIO.ops), false)).toMatchObject({ duration: null, count: true });
+ });
+});