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.

Katana: recreate an edit with your subject, on both engines, and as an Assist tool

Claude227f45c75de9
diff --git a/src/app/(studio)/katana/page.tsx b/src/app/(studio)/katana/page.tsx
new file mode 100644
index 00000000..da6ba673
--- /dev/null
+++ b/src/app/(studio)/katana/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { KatanaStudio } from "@/components/katana/katana-studio";
+
+export const metadata: Metadata = { title: "Katana" };
+
+export default function Page() {
+ return <KatanaStudio />;
+}
diff --git a/src/app/api/katana/[id]/route.ts b/src/app/api/katana/[id]/route.ts
new file mode 100644
index 00000000..6d22a2f0
--- /dev/null
+++ b/src/app/api/katana/[id]/route.ts
@@ -0,0 +1,15 @@
+import { connection } from "next/server";
+import { deleteKatana, getKatana } from "@/server/katana";
+
+export async function GET(_req: Request, ctx: RouteContext<"/api/katana/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const job = getKatana(id);
+ return job ? Response.json(job) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+/** Forget the run (its clips stay in the Library). */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/katana/[id]">) {
+ const { id } = await ctx.params;
+ return deleteKatana(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/katana/route.ts b/src/app/api/katana/route.ts
new file mode 100644
index 00000000..ddf27759
--- /dev/null
+++ b/src/app/api/katana/route.ts
@@ -0,0 +1,25 @@
+import { connection } from "next/server";
+import { createKatana, KatanaBody, listKatana, previewKatana } from "@/server/katana";
+
+/** Recent Katana runs with the state of every step. */
+export async function GET(request: Request) {
+ await connection();
+ const limit = Number(new URL(request.url).searchParams.get("limit") ?? 20);
+ return Response.json({ items: listKatana(Number.isFinite(limit) ? limit : 20) });
+}
+
+/** Start a run; `?preview=1` only plans and prices it (segments, steps, cost). */
+export async function POST(request: Request) {
+ const parsed = KatanaBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) {
+ const path = String(parsed.error.issues[0]?.path[0] ?? "");
+ const msg = path === "reference" ? "Add the reference edit" : path === "photos" ? "Add 1–5 photos of your subject" : path === "instructions" ? "Keep the instructions under 2,000 characters" : "Check the Katana settings";
+ return Response.json({ error: msg }, { status: 400 });
+ }
+ try {
+ if (new URL(request.url).searchParams.get("preview") === "1") return Response.json(previewKatana(parsed.data));
+ return Response.json(createKatana(parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/components/katana/hooks.ts b/src/components/katana/hooks.ts
new file mode 100644
index 00000000..430ff25f
--- /dev/null
+++ b/src/components/katana/hooks.ts
@@ -0,0 +1,79 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useGenerationEvents } from "@/lib/api";
+import type { KatanaJobView, Segment } from "@/lib/av/katana";
+import type { Engine } from "@/lib/catalog/types";
+
+async function json<T>(res: Response): Promise<T> {
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
+ return body;
+}
+
+export interface KatanaBody {
+ engine: Engine;
+ reference: string;
+ photos: string[];
+ instructions?: string;
+ segments?: Segment[];
+ length?: number;
+ duration?: number;
+ motionModel?: string;
+ aspectRatio?: "16:9" | "9:16" | "1:1";
+ keepAudio?: boolean;
+ title?: string;
+}
+
+export interface KatanaPreview {
+ segments: Segment[];
+ steps: number;
+ costUsd: number | null;
+ demo: boolean;
+ model: string;
+}
+
+const post = async <T>(url: string, body: KatanaBody) => json<T>(await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
+
+export function useKatanaJobs() {
+ const qc = useQueryClient();
+ const connected = useGenerationEvents((ev) => {
+ if (ev.type === "generation" && ev.generation.feature === "katana") void qc.invalidateQueries({ queryKey: ["katana"] });
+ });
+ return useQuery({
+ queryKey: ["katana"],
+ queryFn: async () => (await json<{ items: KatanaJobView[] }>(await fetch("/api/katana"))).items,
+ refetchInterval: (q) => (q.state.data?.some((j) => Object.values(j.generations).some((g) => g.status === "queued" || g.status === "running")) ? (connected ? 8000 : 2000) : false),
+ });
+}
+
+/** The plan and price of the current settings (debounced by the caller through `body`). */
+export function useKatanaPreview(body: KatanaBody | null) {
+ return useQuery({
+ queryKey: ["katana-preview", body],
+ enabled: !!body,
+ queryFn: () => post<KatanaPreview>("/api/katana?preview=1", body!),
+ retry: false,
+ staleTime: 30_000,
+ });
+}
+
+export function useKatanaActions() {
+ const qc = useQueryClient();
+ const start = useMutation({
+ mutationFn: (body: KatanaBody) => post<KatanaJobView>("/api/katana", body),
+ onSuccess: (job) => {
+ qc.setQueryData<KatanaJobView[]>(["katana"], (xs) => [job, ...(xs ?? [])]);
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ },
+ });
+ const remove = useMutation({
+ mutationFn: async (id: string) => {
+ const res = await fetch(`/api/katana/${id}`, { method: "DELETE" });
+ if (!res.ok && res.status !== 404) throw new Error("Couldn't remove it");
+ return id;
+ },
+ onSuccess: (id) => qc.setQueryData<KatanaJobView[]>(["katana"], (xs) => xs?.filter((j) => j.id !== id)),
+ });
+ return { start, remove };
+}
diff --git a/src/components/katana/katana-studio.tsx b/src/components/katana/katana-studio.tsx
new file mode 100644
index 00000000..b65d2d2a
--- /dev/null
+++ b/src/components/katana/katana-studio.tsx
@@ -0,0 +1,389 @@
+"use client";
+
+import { ChevronDown, Download, Film, Loader2, ScanLine, Sparkles, Trash2, Users } from "lucide-react";
+import { nanoid } from "nanoid";
+import { useDeferredValue, useMemo, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Slider } from "@/components/ui/slider";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { fileToList, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { frameDiff, sampleFrames } from "@/components/av/frame-sampler";
+import { MediaDrop } from "@/components/av/media-drop";
+import { StepList, type StepRow } from "@/components/av/step-list";
+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
+import { useEngine } from "@/lib/api";
+import { formatCueTime } from "@/lib/av/cue-edit";
+import { detectCuts, KATANA_LIMITS, katanaProgress, katanaStage, motionModel, MOTION_MODELS, nearestAspect, planSegments, type KatanaJobView, type Segment } from "@/lib/av/katana";
+import { cn } from "@/lib/utils";
+import { useKatanaActions, useKatanaJobs, useKatanaPreview, type KatanaBody } from "./hooks";
+
+type SplitMode = "fixed" | "scenes";
+
+/** Scene cuts by a frame-difference pass in the browser (about 6 samples a second, 48 px wide). */
+async function findCuts(src: string, duration: number, onProgress: (p: number) => void): Promise<number[]> {
+ const fps = Math.min(6, 180 / Math.max(1, duration));
+ const times = Array.from({ length: Math.max(2, Math.floor(duration * fps)) }, (_, i) => i / fps);
+ const frames = await sampleFrames(src, times, { width: 48, onProgress });
+ const diffs = frames.slice(1).map((f, i) => frameDiff(frames[i].data, f.data));
+ return detectCuts(diffs, frames.map((f) => f.t));
+}
+
+const money = (usd: number | null | undefined, demo?: boolean, open?: boolean) => (demo ? "Demo · free" : open ? "Free · your GPU" : usd == null ? "Price unknown" : `≈ $${usd.toFixed(2)}`);
+
+/** Katana: rebuild a reference edit with your subject, shot for shot. */
+export function KatanaStudio() {
+ const [engine] = useEngine();
+ const jobs = useKatanaJobs();
+ const { start } = useKatanaActions();
+ const [reference, setReference] = useState<SlotValue | null>(null);
+ const [meta, setMeta] = useState<{ duration: number; aspect: "16:9" | "9:16" | "1:1" } | null>(null);
+ // The browser can't decode the clip (H.265…): the server reads its length from the file and plans evenly.
+ const [unreadable, setUnreadable] = useState(false);
+ const [photos, setPhotos] = useState<SlotValue[]>([]);
+ const [instructions, setInstructions] = useState("");
+ const [mode, setMode] = useState<SplitMode>("fixed");
+ const [length, setLength] = useState<number | null>(null);
+ const [cuts, setCuts] = useState<number[] | null>(null);
+ const [scanning, setScanning] = useState<number | null>(null);
+ const [modelId, setModelId] = useState<string | undefined>(undefined);
+ const [keepAudio, setKeepAudio] = useState(true);
+ const m = motionModel(engine, modelId);
+ const len = Math.min(m.max, Math.max(m.min, length ?? m.max));
+
+ const segments = useMemo<Segment[] | null>(() => {
+ if (!meta) return null;
+ try {
+ return mode === "scenes" && cuts ? planSegments({ duration: meta.duration, mode: "scenes", cuts, min: m.min, max: m.max }) : planSegments({ duration: meta.duration, mode: "fixed", length: len, min: m.min, max: m.max });
+ } catch {
+ return null;
+ }
+ }, [meta, mode, cuts, len, m.min, m.max]);
+
+ const ready = reference && !reference.uploading && photos.length > 0 && photos.every((p) => !p.uploading) && (segments?.length || (unreadable && !meta));
+ const body: KatanaBody | null = ready
+ ? {
+ engine,
+ reference: reference.ref,
+ photos: photos.map((p) => p.ref),
+ instructions: instructions.trim() || undefined,
+ ...(meta && segments ? { segments, duration: meta.duration, aspectRatio: meta.aspect } : { length: len }),
+ motionModel: m.id,
+ keepAudio,
+ title: reference.name?.replace(/\.[a-z0-9]+$/i, "") || "Katana edit",
+ }
+ : null;
+ const preview = useKatanaPreview(useDeferredValue(body));
+ const shown = segments ?? preview.data?.segments ?? null;
+ const blocker = !reference
+ ? "Add the reference edit"
+ : reference.uploading
+ ? "Uploading…"
+ : !meta && !unreadable
+ ? "Reading the reference…"
+ : !photos.length
+ ? "Add at least one photo of your subject"
+ : photos.some((p) => p.uploading)
+ ? "Uploading…"
+ : meta && !segments?.length
+ ? "This clip can't be split for this model"
+ : preview.error
+ ? (preview.error as Error).message
+ : null;
+
+ const scan = async () => {
+ if (!reference || !meta) return;
+ setScanning(0);
+ try {
+ const found = await findCuts(reference.ref, Math.min(meta.duration, KATANA_LIMITS.maxReference), setScanning);
+ setCuts(found);
+ setMode("scenes");
+ toast(found.length ? `${found.length} cut${found.length === 1 ? "" : "s"} found` : "No hard cuts — it'll be split evenly");
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setScanning(null);
+ }
+ };
+
+ const go = () => {
+ if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "katana-blocker" });
+ start.mutate(body, {
+ onSuccess: (j) => toast.success(`Katana started · ${j.segments.length} segment${j.segments.length === 1 ? "" : "s"}`),
+ onError: (e) => toast.error((e as Error).message),
+ });
+ };
+
+ return (
+ <ToolShell title="Katana">
+ <ToolHero title="Recreate the edit. Make it yours." subtitle="Drop a reference edit and up to 5 photos of your subject — Katana rebuilds it shot for shot, at the original cut times, with the original sound." />
+ <div className="mx-auto mt-8 grid max-w-[1040px] gap-4 lg:grid-cols-[minmax(0,6fr)_minmax(0,5fr)]">
+ <div className="min-w-0 space-y-3">
+ <MediaDrop
+ kind="video"
+ value={reference}
+ onChange={(v) => {
+ setReference(v);
+ setMeta(null);
+ setUnreadable(false);
+ setCuts(null);
+ setMode("fixed");
+ }}
+ onDuration={(d) => setMeta((x) => ({ duration: d, aspect: x?.aspect ?? "16:9" }))}
+ onUnreadable={() => setUnreadable(true)}
+ title="Add the edit you want to recreate"
+ hint="1–30 s · MP4, MOV or WebM · the soundtrack is kept"
+ compact
+ />
+ {reference && !reference.uploading && <ShapeProbe src={reference.ref} onShape={(aspect) => setMeta((x) => (x ? { ...x, aspect } : x))} />}
+ {unreadable && !meta && (
+ <Panel title="Segments" aside={<span className="text-[12px] text-muted-foreground">{shown?.length ?? "…"} × up to {m.max} s</span>}>
+ <p className="text-[13px] text-muted-foreground">This browser can&apos;t preview the clip, so it&apos;s cut evenly every {len} s (scene cuts need a preview).</p>
+ <div className="mt-3 flex items-center gap-3">
+ <Slider min={m.min} max={m.max} step={0.5} value={[len]} onValueChange={(v) => setLength(v[0])} aria-label="Segment length" aria-valuetext={`${len} seconds`} className="max-w-64" />
+ <span className="font-mono text-[12px] text-muted-foreground">{len} s</span>
+ </div>
+ {shown && shown.length > 0 && <SegmentBar segments={shown} duration={shown.at(-1)!.end} />}
+ </Panel>
+ )}
+ {meta && (
+ <Panel
+ title="Segments"
+ aside={
+ <span className="text-[12px] text-muted-foreground">
+ {segments?.length ?? 0} × up to {m.max} s
+ </span>
+ }
+ >
+ <div role="radiogroup" aria-label="How to cut the reference" className="inline-flex rounded-full bg-muted p-0.5">
+ {(["fixed", "scenes"] as const).map((x) => (
+ <button
+ key={x}
+ type="button"
+ role="radio"
+ aria-checked={mode === x}
+ onClick={() => (x === "scenes" && !cuts ? void scan() : setMode(x))}
+ className={cn("h-7 rounded-full px-3 text-[12px] font-medium transition", mode === x ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ >
+ {x === "fixed" ? "Every few seconds" : "At scene cuts"}
+ </button>
+ ))}
+ </div>
+ {mode === "fixed" ? (
+ <div className="mt-3 flex items-center gap-3">
+ <Slider min={m.min} max={m.max} step={0.5} value={[len]} onValueChange={(v) => setLength(v[0])} aria-label="Segment length" aria-valuetext={`${len} seconds`} className="max-w-64" />
+ <span className="font-mono text-[12px] text-muted-foreground">{len} s</span>
+ </div>
+ ) : (
+ <div className="mt-3 flex items-center gap-2">
+ <Button variant="outline" size="sm" className="rounded-full" onClick={() => void scan()} disabled={scanning !== null}>
+ {scanning !== null ? <Loader2 className="size-3.5 animate-spin" /> : <ScanLine className="size-3.5" />}
+ {scanning !== null ? `Looking for cuts… ${Math.round(scanning * 100)}%` : "Find the cuts again"}
+ </Button>
+ <span className="text-[12px] text-muted-foreground">{cuts?.length ?? 0} cuts found in your browser</span>
+ </div>
+ )}
+ {segments && <SegmentBar segments={segments} duration={Math.min(meta.duration, KATANA_LIMITS.maxReference)} />}
+ {meta.duration > KATANA_LIMITS.maxReference && <p className="mt-2 text-[12px] text-muted-foreground">Only the first 30 s are recreated.</p>}
+ </Panel>
+ )}
+ </div>
+ <div className="min-w-0 space-y-3">
+ <Panel title="Your subject" aside={<span className="text-[12px] text-muted-foreground">{photos.length}/5</span>}>
+ <div className="flex flex-wrap gap-2">
+ {photos.map((p) => (
+ <MediaSlot key={p.id} label="Photo" kind="image" value={p} onChange={(v) => setPhotos((xs) => (v ? xs.map((x) => (x.id === p.id ? { ...v, id: p.id } : x)) : xs.filter((x) => x.id !== p.id)))} size="lg" />
+ ))}
+ {photos.length < KATANA_LIMITS.maxPhotos && <MediaSlot label={photos.length ? "Add photo" : "Add your subject"} kind="image" value={null} onChange={(v) => v && setPhotos((xs) => [...xs, { ...v, id: v.id ?? nanoid(8) }])} onFile={(f) => fileToList(f, setPhotos, "image")} size="lg" required />}
+ </div>
+ <p className="mt-2 flex items-start gap-1.5 text-[12px] text-muted-foreground">
+ <Users className="mt-0.5 size-3.5 shrink-0" /> A person, a product or an outfit. Clear, well-lit photos from a couple of angles work best.
+ </p>
+ </Panel>
+ <Panel title="Instructions (optional)">
+ <Textarea
+ value={instructions}
+ onChange={(e) => setInstructions(e.target.value.slice(0, KATANA_LIMITS.maxInstructions))}
+ placeholder="Anything to pay attention to, e.g. “keep the red jacket, swap the guitar for my product”"
+ className="min-h-20 resize-none text-[14px]"
+ aria-label="Instructions"
+ />
+ <p className="mt-1 text-right font-mono text-[11px] text-subtle-foreground">
+ {instructions.length}/{KATANA_LIMITS.maxInstructions}
+ </p>
+ </Panel>
+ <Panel title="Motion">
+ <div className="flex flex-col gap-1.5 sm:flex-row sm:items-center">
+ <Label htmlFor="katana-model" className="text-[13px] sm:w-20">
+ Model
+ </Label>
+ <Select value={m.id} onValueChange={setModelId}>
+ <SelectTrigger id="katana-model" className="h-9 w-full rounded-full sm:w-72">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {MOTION_MODELS[engine].map((x) => (
+ <SelectItem key={x.id} value={x.id}>
+ {x.label} · {x.min}–{x.max} s
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="mt-3 flex items-center gap-2">
+ <Switch id="katana-audio" checked={keepAudio} onCheckedChange={setKeepAudio} />
+ <Label htmlFor="katana-audio" className="text-[13px]">
+ Keep the reference&apos;s soundtrack
+ </Label>
+ </div>
+ </Panel>
+ <div className="flex items-center gap-3 pt-1">
+ <p className="flex-1 text-[13px] text-muted-foreground">
+ {preview.data ? (
+ <>
+ {preview.data.segments.length} segment{preview.data.segments.length === 1 ? "" : "s"} · {preview.data.steps} steps ·{" "}
+ <span className="font-mono text-foreground">{money(preview.data.costUsd, preview.data.demo, engine === "open")}</span>
+ </>
+ ) : (
+ (blocker ?? "Pricing…")
+ )}
+ </p>
+ <Button size="lg" className={cn("rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={start.isPending}>
+ {start.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Recreate
+ </Button>
+ </div>
+ </div>
+ </div>
+ <Runs jobs={jobs.data} loading={jobs.isLoading} />
+ </ToolShell>
+ );
+}
+
+/** Reads the reference's width and height (the render shape). */
+function ShapeProbe({ src, onShape }: { src: string; onShape: (a: "16:9" | "9:16" | "1:1") => void }) {
+ return <video src={src} preload="metadata" muted className="hidden" onLoadedMetadata={(e) => e.currentTarget.videoWidth && onShape(nearestAspect(e.currentTarget.videoWidth, e.currentTarget.videoHeight))} />;
+}
+
+function SegmentBar({ segments, duration }: { segments: Segment[]; duration: number }) {
+ return (
+ <div className="mt-3">
+ <div className="flex h-7 overflow-hidden rounded-lg" role="list" aria-label="Segments">
+ {segments.map((s, i) => (
+ <div
+ key={i}
+ role="listitem"
+ className={cn("grid min-w-0 place-items-center border-r border-background text-[11px] font-medium last:border-r-0", i % 2 ? "bg-brand-faint text-brand-text" : "bg-primary/70 text-primary-foreground")}
+ style={{ width: `${((s.end - s.start) / duration) * 100}%` }}
+ title={`${formatCueTime(s.start)} – ${formatCueTime(s.end)}`}
+ >
+ <span className="truncate px-1">{i + 1}</span>
+ </div>
+ ))}
+ </div>
+ <div className="mt-1 flex justify-between font-mono text-[11px] text-subtle-foreground">
+ <span>0:00</span>
+ <span>{formatCueTime(duration)}</span>
+ </div>
+ </div>
+ );
+}
+
+function stepRows(j: KatanaJobView): { segment: number; rows: StepRow[] }[] {
+ const labels: Record<string, string> = { cut: "Cut", frame: "First frame", key: "Your subject", move: "Motion" };
+ return j.segments.map((_, i) => ({
+ segment: i,
+ rows: ["cut", "frame", "key", "move"].filter((k) => j.steps[`${k}${i}`]).map((k) => ({ key: `${k}${i}`, label: labels[k], g: j.generations[j.steps[`${k}${i}`]] })),
+ }));
+}
+
+function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {
+ const { remove } = useKatanaActions();
+ if (loading)
+ return (
+ <div className="mx-auto mt-10 max-w-[1040px] space-y-2">
+ <Skeleton className="h-6 w-32" />
+ <Skeleton className="h-24 w-full rounded-2xl" />
+ </div>
+ );
+ if (!jobs?.length) return null;
+ return (
+ <section className="mx-auto mt-12 max-w-[1040px]" aria-labelledby="katana-runs">
+ <h3 id="katana-runs" className="mb-3 font-heading text-[22px]">
+ Your edits
+ </h3>
+ <ul className="space-y-3">
+ {jobs.map((j) => {
+ const stage = katanaStage(j);
+ const final = j.generations[j.steps[j.final]];
+ const out = final?.status === "succeeded" ? final.outputs.find((o) => o.kind === "video") : undefined;
+ const pct = Math.round(katanaProgress(j) * 100);
+ const others = ["join", "final", ...Object.keys(j.steps).filter((k) => k.startsWith("join") && k !== "join")].filter((k) => j.steps[k]);
+ return (
+ <li key={j.id} className="overflow-hidden rounded-2xl border bg-background shadow-soft">
+ <div className="grid gap-3 p-3 sm:grid-cols-[220px_minmax(0,1fr)] sm:p-4">
+ <div className="aspect-video overflow-hidden rounded-xl bg-media">
+ {out ? <video src={out.url} controls playsInline preload="metadata" className="size-full object-contain" /> : <div className="grid size-full place-items-center text-muted-foreground">{stage === "failed" ? <Film className="size-6" /> : <Loader2 className="size-6 animate-spin" />}</div>}
+ </div>
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <p className="min-w-0 flex-1 truncate text-[15px] font-medium">{j.title}</p>
+ {out && (
+ <Button asChild variant="outline" size="sm" className="rounded-full">
+ <a href={out.url} download={`${j.title}.mp4`}>
+ <Download className="size-3.5" /> Download
+ </a>
+ </Button>
+ )}
+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label={`Remove ${j.title}`} onClick={() => remove.mutate(j.id, { onSuccess: () => toast("Removed — its clips stay in your Library") })}>
+ <Trash2 className="size-4" />
+ </Button>
+ </div>
+ <p className="mt-0.5 text-[12px] text-muted-foreground">
+ {j.segments.length} segment{j.segments.length === 1 ? "" : "s"} · {MOTION_MODELS[j.engine].find((x) => x.id === j.motionModel)?.label ?? j.motionModel} · {j.engine === "open" ? "Open source" : "Cloud"}
+ {final?.provider === "mock" ? " · demo" : ""}
+ </p>
+ {stage !== "done" && (
+ <div className="mt-3">
+ <div className="h-1.5 overflow-hidden rounded-full bg-muted">
+ <div className={cn("h-full rounded-full transition-[width] duration-500", stage === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(3, pct)}%` }} />
+ </div>
+ <p className="mt-1 text-[12px] text-muted-foreground">{stage === "failed" ? "A step failed — see below" : `${pct}% · steps run as soon as the ones before them finish`}</p>
+ </div>
+ )}
+ <Collapsible className="mt-2">
+ <CollapsibleTrigger className="group inline-flex items-center gap-1 text-[12px] font-medium text-muted-foreground hover:text-foreground">
+ Steps <ChevronDown className="size-3.5 transition-transform group-data-[state=open]:rotate-180" />
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <div className="mt-2 grid gap-3 sm:grid-cols-2">
+ {stepRows(j).map((s) => (
+ <div key={s.segment}>
+ <p className="mb-1 text-[12px] font-semibold">
+ Segment {s.segment + 1} · {formatCueTime(j.segments[s.segment].start)}–{formatCueTime(j.segments[s.segment].end)}
+ </p>
+ <StepList steps={s.rows} />
+ </div>
+ ))}
+ {others.length > 0 && (
+ <div>
+ <p className="mb-1 text-[12px] font-semibold">Finish</p>
+ <StepList steps={others.map((k) => ({ key: k, label: k === "final" ? "Original soundtrack" : "Join at the cut times", g: j.generations[j.steps[k]] }))} />
+ </div>
+ )}
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
diff --git a/src/lib/assist.ts b/src/lib/assist.ts
index 75eb6ea3..2fc7dfec 100644
--- a/src/lib/assist.ts
+++ b/src/lib/assist.ts
@@ -6,7 +6,7 @@ import type { Engine, Generation, MediaKind, Operation } from "./catalog/types";
/** One job the agent wants to run, priced before the user approves it. */
export interface PlannedJob {
- tool: "generate" | "create_storyboard";
+ tool: "generate" | "create_storyboard" | "katana";
modelId: string;
modelName: string;
kind: MediaKind;
diff --git a/src/lib/av/katana.ts b/src/lib/av/katana.ts
new file mode 100644
index 00000000..a67bf658
--- /dev/null
+++ b/src/lib/av/katana.ts
@@ -0,0 +1,268 @@
+import type { ChainSlot, Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+import { FRAME_MODEL, frameParams } from "./frames";
+
+/**
+ * Katana: rebuild a reference edit with your own subject. The reference is cut into segments (fixed
+ * length, or at the scene cuts the browser finds with a frame-difference pass); for each segment the
+ * first frame gets your subject (an edit model with your photos), then the segment is regenerated with
+ * the reference's motion; the new segments are joined at the original cut times and the reference's
+ * soundtrack goes back on. Planned as plain data (client and server); run with createPipeline.
+ */
+export const KATANA_FEATURE = "katana";
+
+export const KATANA_LIMITS = { maxReference: 30, minReference: 1, maxPhotos: 5, maxSegments: 12, maxInstructions: 2000 };
+
+export interface MotionModel {
+ id: string;
+ label: string;
+ /** "v2v": the model edits the segment with reference images; "motion-transfer": a character image follows the segment's motion. */
+ op: "v2v" | "motion-transfer";
+ /** Segment length the model takes (seconds). */
+ min: number;
+ max: number;
+ /** Reference images it takes besides the keyframe (photos of the subject). */
+ maxRefs: number;
+}
+
+export const MOTION_MODELS: Record<Engine, MotionModel[]> = {
+ cloud: [
+ { id: "kling-o3", label: "Kling O3 edit", op: "v2v", min: 3, max: 10, maxRefs: 4 },
+ { id: "genjutsu-motion-transfer", label: "Higgsfield Genjutsu motion transfer", op: "motion-transfer", min: 3, max: 10, maxRefs: 8 },
+ { id: "kling-motion-control", label: "Kling 3.0 Motion Control", op: "motion-transfer", min: 3, max: 10, maxRefs: 1 },
+ ],
+ open: [
+ { id: "oss-wan22-animate", label: "Wan 2.2 Animate", op: "motion-transfer", min: 1, max: 5, maxRefs: 1 },
+ { id: "oss-wan22-fun-control", label: "Wan 2.2 Fun Control", op: "motion-transfer", min: 1, max: 5, maxRefs: 1 },
+ ],
+};
+
+export const KEYFRAME_MODEL: Record<Engine, string> = { cloud: "nano-banana-pro", open: "oss-qwen-edit" };
+
+export const motionModel = (engine: Engine, id?: string): MotionModel => MOTION_MODELS[engine].find((m) => m.id === id) ?? MOTION_MODELS[engine][0];
+
+export interface Segment {
+ start: number;
+ end: number;
+}
+
+const r2 = (t: number) => Math.round(t * 100) / 100;
+
+/**
+ * Scene cuts from a frame-difference pass: `diffs[i]` is the change between frame i and i+1 (sampled at
+ * `times`). A cut is a spike well above the clip's usual change (its median), at least `minGap` apart.
+ */
+export function detectCuts(diffs: number[], times: number[], o: { minGap?: number; floor?: number; ratio?: number } = {}): number[] {
+ if (diffs.length < 2) return [];
+ const sorted = [...diffs].sort((a, b) => a - b);
+ const median = sorted[Math.floor(sorted.length / 2)];
+ const threshold = Math.max(o.floor ?? 0.12, median * (o.ratio ?? 4));
+ const minGap = o.minGap ?? 0.8;
+ const cuts: number[] = [];
+ for (let i = 0; i < diffs.length; i++) {
+ const d = diffs[i];
+ // A local peak above the threshold.
+ if (d < threshold || d < (diffs[i - 1] ?? 0) || d < (diffs[i + 1] ?? 0)) continue;
+ const t = r2((times[i] + times[i + 1]) / 2);
+ if (cuts.length && t - cuts.at(-1)! < minGap) continue;
+ cuts.push(t);
+ }
+ return cuts;
+}
+
+/** Split [a, b] into equal pieces no longer than `max`. */
+function pieces(a: number, b: number, max: number): Segment[] {
+ const n = Math.max(1, Math.ceil((b - a) / max - 1e-9));
+ return Array.from({ length: n }, (_, i) => ({ start: r2(a + ((b - a) * i) / n), end: r2(a + ((b - a) * (i + 1)) / n) }));
+}
+
+/**
+ * The segments to regenerate: every `length` seconds, or at the scene cuts. Segments shorter than `min`
+ * join a neighbour, longer than `max` are split evenly; the whole clip is covered without gaps.
+ */
+export function planSegments(o: { duration: number; mode: "fixed" | "scenes"; length?: number; cuts?: number[]; min: number; max: number; maxSegments?: number }): Segment[] {
+ const duration = r2(Math.min(o.duration, KATANA_LIMITS.maxReference));
+ if (!(duration > 0)) return [];
+ const min = Math.min(o.min, duration);
+ let segs: Segment[];
+ if (o.mode === "fixed") {
+ const len = Math.max(min, Math.min(o.max, o.length ?? o.max));
+ segs = pieces(0, duration, len);
+ // A short tail joins the previous piece (then that piece is split again if too long).
+ const last = segs.at(-1)!;
+ if (segs.length > 1 && last.end - last.start < min) {
+ const prev = segs[segs.length - 2];
+ segs = [...segs.slice(0, -2), ...pieces(prev.start, last.end, o.max)];
+ }
+ } else {
+ const cuts = [...new Set((o.cuts ?? []).map(r2))].filter((c) => c > 0 && c < duration).sort((a, b) => a - b);
+ const bounds = [0, ...cuts, duration];
+ const raw = bounds.slice(1).map((end, i) => ({ start: bounds[i], end }));
+ // Merge short scenes into the shorter neighbour until none is short.
+ const merged = raw.slice();
+ for (;;) {
+ const i = merged.findIndex((s) => s.end - s.start < min);
+ if (i < 0 || merged.length === 1) break;
+ const left = merged[i - 1];
+ const right = merged[i + 1];
+ const intoLeft = left && (!right || left.end - left.start <= right.end - right.start);
+ if (intoLeft) merged.splice(i - 1, 2, { start: left.start, end: merged[i].end });
+ else merged.splice(i, 2, { start: merged[i].start, end: right!.end });
+ }
+ segs = merged.flatMap((s) => pieces(s.start, s.end, o.max));
+ }
+ const cap = o.maxSegments ?? KATANA_LIMITS.maxSegments;
+ if (segs.length > cap) throw new Error(`That makes ${segs.length} segments — Katana takes up to ${cap}. Use a shorter clip or longer segments`);
+ return segs;
+}
+
+/** The nearest aspect ratio the steps render at. */
+export function nearestAspect(width: number, height: number): "16:9" | "9:16" | "1:1" {
+ const r = width / Math.max(1, height);
+ return r > 1.3 ? "16:9" : r < 0.77 ? "9:16" : "1:1";
+}
+
+export interface KatanaInput {
+ engine: Engine;
+ reference: string;
+ photos: string[];
+ instructions?: string;
+ segments: Segment[];
+ motionModel?: string;
+ aspectRatio?: string;
+ /** Keep the reference's soundtrack (default on). */
+ keepAudio?: boolean;
+ title?: string;
+}
+
+export interface KatanaStep {
+ key: string;
+ request: GenerationRequest;
+ after?: string | string[];
+ chain?: ChainSlot[];
+}
+
+const tidy = (s?: string) => (s ?? "").trim().replace(/[.\s]+$/, "");
+
+/** The keyframe edit: the segment's first frame with your subject in it. */
+export function keyframePrompt(instructions?: string, photos = 1): string {
+ const refs = photos > 1 ? `the subject shown in images 2 to ${photos + 1}` : "the subject from image 2";
+ const extra = tidy(instructions);
+ return `Replace the main subject of image 1 with ${refs}, keeping their identity, face, outfit and details. Keep image 1's pose, framing, camera angle, lighting, background and composition exactly.${extra ? ` ${extra}.` : ""}`;
+}
+
+export function motionPrompt(instructions?: string): string {
+ const extra = tidy(instructions);
+ return `Recreate the source clip with the new subject: the same camera motion, timing, action and framing, cut for cut.${extra ? ` ${extra}.` : ""}`;
+}
+
+/** Every step of a Katana run, for createPipeline. The final video is the step keyed "final" (or "join" without audio). */
+export function katanaSteps(o: KatanaInput): KatanaStep[] {
+ if (!o.photos.length) throw new Error("Add at least one photo of your subject");
+ if (o.photos.length > KATANA_LIMITS.maxPhotos) throw new Error(`Add up to ${KATANA_LIMITS.maxPhotos} photos`);
+ if (!o.segments.length) throw new Error("The reference needs at least one segment");
+ if ((o.instructions?.length ?? 0) > KATANA_LIMITS.maxInstructions) throw new Error(`Keep the instructions under ${KATANA_LIMITS.maxInstructions} characters`);
+ const m = motionModel(o.engine, o.motionModel);
+ const tooLong = o.segments.find((s) => s.end - s.start > m.max + 0.05);
+ if (tooLong) throw new Error(`${m.label} takes segments up to ${m.max} s — split the clip finer`);
+ const tooShort = o.segments.find((s) => s.end - s.start < m.min - 0.05);
+ if (tooShort) throw new Error(`${m.label} needs segments of at least ${m.min} s`);
+ const base = { feature: KATANA_FEATURE, ...(o.title && { batchTitle: o.title }) };
+ const n = o.segments.length;
+ const steps: KatanaStep[] = [];
+ const aspect = o.aspectRatio ?? "16:9";
+ o.segments.forEach((s, i) => {
+ const label = (what: string) => ({ label: `Segment ${i + 1} of ${n} · ${what}`, index: i, of: n });
+ const span = { startTime: r2(s.start), endTime: r2(s.end) };
+ // Cut the segment (the open engine resamples it to the motion model's frame rate and size), take its first frame.
+ steps.push(
+ o.engine === "open"
+ ? { key: `cut${i}`, request: { ...base, modelId: "oss-segment", op: "trim", inputs: { video: o.reference }, params: { ...span, aspectRatio: aspect, resolution: "480p" }, step: label("cut") } }
+ : { key: `cut${i}`, request: { ...base, modelId: "trim-video", op: "trim", inputs: { video: o.reference }, params: span, step: label("cut") } },
+ );
+ steps.push({ key: `frame${i}`, after: `cut${i}`, chain: [{ slot: "video" }], request: { ...base, modelId: FRAME_MODEL[o.engine], op: "frame", params: frameParams(o.engine, "first"), step: label("first frame") } });
+ // Your subject in that frame (Qwen-Image-Edit takes up to 3 images: the frame and two photos).
+ const photos = o.engine === "open" ? o.photos.slice(0, 2) : o.photos;
+ steps.push({ key: `key${i}`, after: `frame${i}`, chain: [{ slot: "images", position: "first" }], request: { ...base, modelId: KEYFRAME_MODEL[o.engine], op: "edit", prompt: keyframePrompt(o.instructions, photos.length), inputs: { images: photos }, step: label("your subject") } });
+ const motion: GenerationRequest = { ...base, modelId: m.id, op: m.op, prompt: motionPrompt(o.instructions), params: { aspectRatio: aspect, ...(o.engine === "open" && { resolution: "480p" }) }, step: label("motion") };
+ if (m.op === "v2v") {
+ // The segment is edited with the new keyframe first among its references, then the photos.
+ steps.push({ key: `move${i}`, after: [`cut${i}`, `key${i}`], chain: [{ slot: "video" }, { slot: "images", position: "first" }], request: { ...motion, inputs: { images: o.photos.slice(0, m.maxRefs - 1) } } });
+ } else {
+ const refs = m.maxRefs > 1 ? o.photos.slice(0, m.maxRefs - 1) : [];
+ steps.push({ key: `move${i}`, after: [`key${i}`, `cut${i}`], chain: [{ slot: "images", position: "first" }, { slot: "video" }], request: { ...motion, ...(refs.length && { inputs: { images: refs } }) } });
+ }
+ });
+ // Join the regenerated segments in order (the open join takes 4 clips at a time: fold).
+ const join = o.engine === "open" ? "oss-join-clips" : "join-clips";
+ const max = o.engine === "open" ? 4 : 24;
+ let level = o.segments.map((_, i) => `move${i}`);
+ let j = 0;
+ const joinStep = (keys: string[], key: string): KatanaStep => ({
+ key,
+ after: keys,
+ chain: keys.map(() => ({ slot: "videos" as const })),
+ request: { ...base, modelId: join, op: "concat", prompt: o.title ?? "Katana", params: { aspectRatio: aspect, resolution: o.engine === "open" ? "480p" : "720p" }, step: { label: "Joining the segments", index: n, of: n + 1 } },
+ });
+ if (level.length === 1) {
+ // Nothing to join: the one segment is the edit.
+ } else {
+ while (level.length > max) {
+ const key = `join${j++}`;
+ steps.push(joinStep(level.slice(0, max), key));
+ level = [key, ...level.slice(max)];
+ }
+ steps.push(joinStep(level, "join"));
+ level = ["join"];
+ }
+ if (o.keepAudio !== false) {
+ steps.push({
+ key: "final",
+ after: level[0],
+ chain: [{ slot: "video" }],
+ request: { ...base, modelId: o.engine === "open" ? "oss-mux" : "merge-audio-video", op: "mux", inputs: { audio: o.reference }, step: { label: "Original soundtrack", index: n, of: n + 1 } },
+ });
+ }
+ return steps;
+}
+
+/** The key of the step that makes the finished video. */
+export function finalKey(steps: KatanaStep[]): string {
+ return steps.some((s) => s.key === "final") ? "final" : steps.some((s) => s.key === "join") ? "join" : "move0";
+}
+
+export interface KatanaJob {
+ id: string;
+ title: string;
+ engine: Engine;
+ reference: string;
+ photos: string[];
+ instructions?: string;
+ motionModel: string;
+ segments: Segment[];
+ keepAudio: boolean;
+ batchId: string;
+ /** Generation id per step key. */
+ steps: Record<string, string>;
+ final: string;
+ createdAt: number;
+ updatedAt: number;
+}
+
+export interface KatanaJobView extends KatanaJob {
+ generations: Record<string, Generation>;
+}
+
+export type KatanaStage = "running" | "done" | "failed";
+
+export function katanaStage(j: KatanaJobView): KatanaStage {
+ const gs = Object.values(j.steps).map((id) => j.generations[id]);
+ if (gs.some((g) => !g || g.status === "failed" || g.status === "canceled")) return "failed";
+ return j.generations[j.steps[j.final]]?.status === "succeeded" ? "done" : "running";
+}
+
+/** Share of the steps finished (for one progress bar). */
+export function katanaProgress(j: KatanaJobView): number {
+ const gs = Object.values(j.steps).map((id) => j.generations[id]);
+ if (!gs.length) return 0;
+ return gs.reduce((acc, g) => acc + (g?.status === "succeeded" ? 1 : g?.status === "running" ? (g.progress ?? 0.3) : 0), 0) / gs.length;
+}
diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.ts
index 95dbaac0..2ae0bfe8 100644
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@ -13,6 +13,7 @@ import { provider } from "../providers";
import { llmBackends } from "../providers/llm";
import { engineMode } from "../settings";
import { readRef } from "../storage";
+import { katanaTool } from "../katana";
import { createStoryboard } from "../storyboard";
type ResultContent = Anthropic.Beta.BetaToolResultBlockParam["content"];
@@ -499,7 +500,7 @@ const storyboard = defineTool({
// ---------------------------------------------------------------------------
// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export const TOOLS: ToolDef<any>[] = [searchModels, listElementsTool, listRecent, checkGenerations, generate, storyboard];
+export const TOOLS: ToolDef<any>[] = [searchModels, listElementsTool, listRecent, checkGenerations, generate, storyboard, defineTool(katanaTool)];
export const getTool = (name: string) => TOOLS.find((t) => t.name === name);
/** JSON Schema for the API: every object closed, constraints the API doesn't take removed (zod still checks them). */
diff --git a/src/server/katana.ts b/src/server/katana.ts
new file mode 100644
index 00000000..90f611ca
--- /dev/null
+++ b/src/server/katana.ts
@@ -0,0 +1,205 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import type { PlannedJob } from "@/lib/assist";
+import { finalKey, KATANA_FEATURE, KATANA_LIMITS, katanaSteps, katanaStage, motionModel, MOTION_MODELS, planSegments, type KatanaInput, type KatanaJob, type KatanaJobView, type Segment } from "@/lib/av/katana";
+import { getModel } from "@/lib/catalog";
+import type { Engine, Generation } from "@/lib/catalog/types";
+import { probeMedia } from "@/lib/media-probe";
+import { createPipeline } from "./chains";
+import { db } from "./db";
+import { getGeneration, previewChained } from "./generations";
+import { engineMode } from "./settings";
+import fs from "node:fs";
+import { absolutePath } from "./storage";
+
+/**
+ * Katana jobs: a reference edit rebuilt with your subject (src/lib/av/katana.ts plans it). The steps
+ * are chained generations in one batch; the job row keeps what was asked and which generation makes
+ * each step, so the studio and Assist can follow it.
+ */
+
+interface Row {
+ id: string;
+ data_json: string;
+ created_at: number;
+ updated_at: number;
+}
+
+const toJob = (r: Row): KatanaJob => ({ ...(JSON.parse(r.data_json) as Omit<KatanaJob, "id" | "createdAt" | "updatedAt">), id: r.id, createdAt: r.created_at, updatedAt: r.updated_at });
+
+function view(j: KatanaJob): KatanaJobView {
+ const generations: Record<string, Generation> = {};
+ for (const id of Object.values(j.steps)) {
+ const g = getGeneration(id, { includeDeleted: true });
+ if (g) generations[id] = g;
+ }
+ return { ...j, generations };
+}
+
+export function getKatana(id: string): KatanaJobView | null {
+ const r = db().prepare("SELECT * FROM katana_jobs WHERE id = ?").get(id) as Row | undefined;
+ return r ? view(toJob(r)) : null;
+}
+
+export function listKatana(limit = 20): KatanaJobView[] {
+ const rows = db().prepare("SELECT * FROM katana_jobs ORDER BY updated_at DESC LIMIT ?").all(Math.max(1, Math.min(100, limit))) as Row[];
+ return rows.map((r) => view(toJob(r)));
+}
+
+export function deleteKatana(id: string): boolean {
+ return db().prepare("DELETE FROM katana_jobs WHERE id = ?").run(id).changes > 0;
+}
+
+const Seg = z.object({ start: z.number().min(0).max(KATANA_LIMITS.maxReference), end: z.number().min(0).max(KATANA_LIMITS.maxReference + 1) });
+
+export const KatanaBody = z.object({
+ engine: z.enum(["cloud", "open"]),
+ reference: z.string().startsWith("/api/files/"),
+ photos: z.array(z.string().startsWith("/api/files/")).min(1).max(KATANA_LIMITS.maxPhotos),
+ instructions: z.string().max(KATANA_LIMITS.maxInstructions).optional(),
+ /** Segments chosen in the studio (scene cuts); without them the clip is cut every `length` seconds. */
+ segments: z.array(Seg).max(KATANA_LIMITS.maxSegments).optional(),
+ length: z.number().min(1).max(10).optional(),
+ duration: z.number().positive().max(600).optional(),
+ motionModel: z.string().max(80).optional(),
+ aspectRatio: z.enum(["16:9", "9:16", "1:1"]).optional(),
+ keepAudio: z.boolean().optional(),
+ title: z.string().max(200).optional(),
+});
+export type KatanaRequest = z.infer<typeof KatanaBody>;
+
+/** The reference's length: what the browser measured, else the file's header (MP4, MOV). */
+function referenceLength(ref: string, given?: number): number {
+ if (given) return given;
+ let d: number | undefined;
+ try {
+ const info = probeMedia(fs.readFileSync(absolutePath(decodeURIComponent(ref.slice("/api/files/".length)))));
+ d = info?.videoDuration ?? info?.duration;
+ } catch {
+ d = undefined;
+ }
+ if (!d) throw new Error("Couldn't read how long the reference is — try an MP4");
+ return d;
+}
+
+function validSegments(segs: Segment[], duration: number): Segment[] {
+ const sorted = [...segs].sort((a, b) => a.start - b.start);
+ sorted.forEach((s, i) => {
+ if (!(s.end > s.start)) throw new Error("A segment ends before it starts");
+ if (i && s.start < sorted[i - 1].end - 0.01) throw new Error("Segments overlap");
+ });
+ if (sorted.at(-1)!.end > duration + 0.5) throw new Error("A segment runs past the end of the reference");
+ return sorted;
+}
+
+/** The plan (segments + steps) of a request, validated; throws a readable message. */
+export function planKatana(body: KatanaRequest): { input: KatanaInput; engine: Engine } {
+ const mode = engineMode();
+ const engine: Engine = mode === "both" ? body.engine : mode;
+ const duration = Math.min(referenceLength(body.reference, body.duration), KATANA_LIMITS.maxReference);
+ if (duration < KATANA_LIMITS.minReference) throw new Error("The reference is too short");
+ const m = motionModel(engine, body.motionModel);
+ if (body.motionModel && m.id !== body.motionModel) throw new Error(`${getModel(body.motionModel)?.name ?? body.motionModel} isn't a ${engine === "open" ? "open-source" : "cloud"} motion model for Katana`);
+ const segments = body.segments?.length ? validSegments(body.segments, duration) : planSegments({ duration, mode: "fixed", length: body.length ?? m.max, min: m.min, max: m.max });
+ const title = body.title?.trim().slice(0, 120) || "Katana edit";
+ return {
+ engine,
+ input: { engine, reference: body.reference, photos: body.photos, instructions: body.instructions, segments, motionModel: m.id, aspectRatio: body.aspectRatio, keepAudio: body.keepAudio, title },
+ };
+}
+
+export function createKatana(body: KatanaRequest): KatanaJobView {
+ const { input, engine } = planKatana(body);
+ const steps = katanaSteps(input);
+ const run = createPipeline(steps, {});
+ const now = Date.now();
+ const job: KatanaJob = {
+ id: nanoid(10),
+ title: input.title ?? "Katana edit",
+ engine,
+ reference: input.reference,
+ photos: input.photos,
+ instructions: input.instructions,
+ motionModel: input.motionModel!,
+ segments: input.segments,
+ keepAudio: input.keepAudio !== false,
+ batchId: run.batchId,
+ steps: Object.fromEntries(Object.entries(run.byKey).map(([k, g]) => [k, g.id])),
+ final: finalKey(steps),
+ createdAt: now,
+ updatedAt: now,
+ };
+ const { id, createdAt, updatedAt, ...data } = job;
+ db().prepare("INSERT INTO katana_jobs (id, data_json, created_at, updated_at) VALUES (?, ?, ?, ?)").run(id, JSON.stringify(data), createdAt, updatedAt);
+ return view(job);
+}
+
+/** Price a run without starting it (Assist's approval card, the studio's estimate). */
+export function previewKatana(body: KatanaRequest): { segments: Segment[]; steps: number; costUsd: number | null; demo: boolean; model: string } {
+ const { input } = planKatana(body);
+ const steps = katanaSteps(input);
+ let cost: number | null = 0;
+ let demo = false;
+ for (const s of steps) {
+ const p = previewChained(s.chain ? { ...s.request, chain: s.chain } : s.request, [s.after ?? []].flat().length);
+ demo ||= p.demo;
+ cost = cost === null || p.costUsd === null ? null : cost + p.costUsd;
+ }
+ return { segments: input.segments, steps: steps.length, costUsd: cost, demo, model: input.motionModel! };
+}
+
+// ---------------------------------------------------------------------------
+// Assist / MCP tool ("katana")
+
+const KatanaToolInput = z.object({
+ reference: z.string().describe("The reference edit to recreate: a video URL from the chat (/api/files/…), 1–30 s."),
+ photos: z.array(z.string()).describe("1–5 photos of your subject (person, product or outfit) as /api/files/… URLs."),
+ instructions: z.string().optional().describe("What to pay attention to when recreating it (optional, ≤2000 characters)."),
+ segment_seconds: z.number().optional().describe("Cut the reference every N seconds (default: the longest the motion model takes)."),
+ motion_model: z.string().optional().describe(`Motion model: cloud ${MOTION_MODELS.cloud.map((m) => m.id).join(" | ")}; open ${MOTION_MODELS.open.map((m) => m.id).join(" | ")}.`),
+ keep_audio: z.boolean().optional().describe("Keep the reference's soundtrack (default true)."),
+});
+
+const toBody = (s: z.infer<typeof KatanaToolInput>, engine: Engine): KatanaRequest =>
+ KatanaBody.parse({ engine, reference: s.reference, photos: s.photos, instructions: s.instructions, length: s.segment_seconds, motionModel: s.motion_model, keepAudio: s.keep_audio });
+
+/** The tool definition, appended to Assist's TOOLS (and so to MCP). */
+export const katanaTool = {
+ name: "katana",
+ description:
+ "Katana: recreate a reference edit (a 1–30 s video) with the user's own subject from 1–5 photos. The reference is cut into segments; each segment's first frame gets the subject, then the segment is regenerated with the reference's motion, joined at the original cut times, with the reference's soundtrack. Use it for 'make this edit with me / my product'. Gated by the same approval card as generate.",
+ schema: KatanaToolInput,
+ gated: true,
+ plan: (s: z.infer<typeof KatanaToolInput>, ctx: { engine: Engine }): PlannedJob[] => {
+ const engine = engineMode() === "both" ? ctx.engine : (engineMode() as Engine);
+ const m = motionModel(engine, s.motion_model);
+ const job: PlannedJob = {
+ tool: "katana",
+ modelId: m.id,
+ modelName: `Katana · ${m.label}`,
+ kind: "video",
+ op: "v2v",
+ prompt: s.instructions?.trim() || "Recreate the reference edit with the subject from the photos",
+ count: 1,
+ costUsd: null,
+ demo: false,
+ };
+ try {
+ const p = previewKatana(toBody(s, ctx.engine));
+ return [{ ...job, modelId: p.model, prompt: `${job.prompt} (${p.segments.length} segment${p.segments.length === 1 ? "" : "s"}, ${p.steps} steps)`, costUsd: p.costUsd, demo: p.demo }];
+ } catch (e) {
+ return [{ ...job, error: e instanceof z.ZodError ? "Give the reference video and 1–5 photos as /api/files/… URLs" : (e as Error).message }];
+ }
+ },
+ async run(s: z.infer<typeof KatanaToolInput>, ctx: { engine: Engine }) {
+ const job = createKatana(toBody(s, ctx.engine));
+ const final = job.steps[job.final];
+ return {
+ content: JSON.stringify({ katana: job.id, segments: job.segments, final, note: `Open /katana to follow it. ${Object.keys(job.steps).length} steps; the finished video is generation ${final}.` }),
+ items: [{ id: "", role: "generations" as const, ids: [final] }],
+ };
+ },
+};
+
+export { KATANA_FEATURE, katanaStage };
diff --git a/tests/av-katana.test.ts b/tests/av-katana.test.ts
new file mode 100644
index 00000000..78512786
--- /dev/null
+++ b/tests/av-katana.test.ts
@@ -0,0 +1,175 @@
+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 { detectCuts, finalKey, katanaStage, katanaSteps, nearestAspect, planSegments } from "@/lib/av/katana";
+import { frameParams, frameRequest } from "@/lib/av/frames";
+
+vi.setConfig({ testTimeout: 150_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-av-katana-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const katana = await import("@/server/katana");
+const { getTool } = await import("@/server/assist/tools");
+const { saveFile } = await import("@/server/storage");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+async function settle(id: string, ms = 140_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, 250));
+ }
+}
+
+const file = (name: string, type: string) => saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples", name)), contentType: type, source: "upload" }).url;
+
+describe("katana segment planning", () => {
+ it("finds scene cuts as spikes over the clip's usual change", () => {
+ const times = Array.from({ length: 21 }, (_, i) => i * 0.5);
+ const diffs = times.slice(1).map((_, i) => (i === 5 || i === 13 ? 0.6 : i === 14 ? 0.5 : 0.02));
+ // Spikes between 2.5–3.0 s and 6.5–7.0 s; the one right after (7.0–7.5) is within the minimum gap.
+ expect(detectCuts(diffs, times)).toEqual([2.75, 6.75]);
+ expect(detectCuts(diffs.map(() => 0.03), times)).toEqual([]);
+ });
+
+ it("cuts every N seconds, evenly, within the model's limits", () => {
+ expect(planSegments({ duration: 12, mode: "fixed", length: 5, min: 3, max: 5 })).toEqual([
+ { start: 0, end: 4 },
+ { start: 4, end: 8 },
+ { start: 8, end: 12 },
+ ]);
+ expect(planSegments({ duration: 4, mode: "fixed", length: 10, min: 3, max: 10 })).toEqual([{ start: 0, end: 4 }]);
+ // References over 30 s are cut to the first 30 s.
+ expect(planSegments({ duration: 45, mode: "fixed", length: 10, min: 3, max: 10 }).at(-1)!.end).toBe(30);
+ });
+
+ it("follows the scene cuts: short scenes join a neighbour, long ones are split", () => {
+ expect(planSegments({ duration: 12, mode: "scenes", cuts: [0.5, 4, 4.8, 9], min: 1, max: 5 })).toEqual([
+ { start: 0, end: 4.8 },
+ { start: 4.8, end: 9 },
+ { start: 9, end: 12 },
+ ]);
+ expect(planSegments({ duration: 14, mode: "scenes", cuts: [], min: 1, max: 5 })).toEqual([
+ { start: 0, end: 4.67 },
+ { start: 4.67, end: 9.33 },
+ { start: 9.33, end: 14 },
+ ]);
+ expect(() => planSegments({ duration: 30, mode: "fixed", length: 1, min: 1, max: 1 })).toThrow(/up to 12/);
+ });
+
+ it("picks the nearest render shape", () => {
+ expect(nearestAspect(1920, 1080)).toBe("16:9");
+ expect(nearestAspect(1080, 1920)).toBe("9:16");
+ expect(nearestAspect(1000, 1100)).toBe("1:1");
+ });
+});
+
+describe("frame requests", () => {
+ it("cloud: first/last frame; open: a decoded window", () => {
+ expect(frameParams("cloud", "last")).toEqual({ extra: { frame_type: "last" } });
+ expect(() => frameParams("cloud", { at: 2 })).toThrow(/trim the clip first/);
+ expect(frameParams("open", "last")).toBeUndefined();
+ expect(frameParams("open", { at: 2.5 })).toEqual({ startTime: 2.5, endTime: 3, extra: { frameIndex: 0 } });
+ expect(frameRequest({ feature: "x", engine: "open", video: "/v.mp4", pick: "first" })).toMatchObject({ modelId: "oss-extract-frame", op: "frame", inputs: { video: "/v.mp4" }, params: { startTime: 0 } });
+ });
+});
+
+describe("katana steps", () => {
+ const segments = [
+ { start: 0, end: 4 },
+ { start: 4, end: 8 },
+ ];
+ const photos = ["/a.png", "/b.png", "/c.png"];
+
+ it("open: cut → first frame → your subject → Wan Animate per segment, joined, original sound", () => {
+ const steps = katanaSteps({ engine: "open", reference: "/ref.mp4", photos, segments, aspectRatio: "9:16", title: "My edit" });
+ expect(steps.map((s) => [s.key, s.request.modelId, s.request.op])).toEqual([
+ ["cut0", "oss-segment", "trim"],
+ ["frame0", "oss-extract-frame", "frame"],
+ ["key0", "oss-qwen-edit", "edit"],
+ ["move0", "oss-wan22-animate", "motion-transfer"],
+ ["cut1", "oss-segment", "trim"],
+ ["frame1", "oss-extract-frame", "frame"],
+ ["key1", "oss-qwen-edit", "edit"],
+ ["move1", "oss-wan22-animate", "motion-transfer"],
+ ["join", "oss-join-clips", "concat"],
+ ["final", "oss-mux", "mux"],
+ ]);
+ expect(steps[0].request.params).toMatchObject({ startTime: 0, endTime: 4, aspectRatio: "9:16" });
+ // Qwen-Image-Edit gets the frame first, then two photos.
+ expect(steps[2]).toMatchObject({ after: "frame0", chain: [{ slot: "images", position: "first" }], request: { inputs: { images: ["/a.png", "/b.png"] } } });
+ expect(steps[3]).toMatchObject({ after: ["key0", "cut0"], chain: [{ slot: "images", position: "first" }, { slot: "video" }] });
+ expect(steps[8]).toMatchObject({ after: ["move0", "move1"], chain: [{ slot: "videos" }, { slot: "videos" }] });
+ expect(steps[9]).toMatchObject({ after: "join", chain: [{ slot: "video" }], request: { inputs: { audio: "/ref.mp4" } } });
+ expect(finalKey(steps)).toBe("final");
+ });
+
+ it("open joins fold 4 clips at a time", () => {
+ const six = Array.from({ length: 6 }, (_, i) => ({ start: i * 4, end: i * 4 + 4 }));
+ const steps = katanaSteps({ engine: "open", reference: "/r.mp4", photos, segments: six, keepAudio: false });
+ const joins = steps.filter((s) => s.request.op === "concat");
+ expect(joins.map((s) => [s.key, s.after])).toEqual([
+ ["join0", ["move0", "move1", "move2", "move3"]],
+ ["join", ["join0", "move4", "move5"]],
+ ]);
+ expect(finalKey(steps)).toBe("join");
+ });
+
+ it("cloud: trim → first frame → Nano Banana Pro → Kling O3 edit with the new keyframe first", () => {
+ const steps = katanaSteps({ engine: "cloud", reference: "/ref.mp4", photos, segments });
+ expect(steps.slice(0, 4).map((s) => [s.key, s.request.modelId])).toEqual([
+ ["cut0", "trim-video"],
+ ["frame0", "extract-frame"],
+ ["key0", "nano-banana-pro"],
+ ["move0", "kling-o3"],
+ ]);
+ expect(steps[1].request.params).toEqual({ extra: { frame_type: "first" } });
+ expect(steps[3]).toMatchObject({ after: ["cut0", "key0"], chain: [{ slot: "video" }, { slot: "images", position: "first" }], request: { op: "v2v", inputs: { images: ["/a.png", "/b.png", "/c.png"] } } });
+ expect(steps.at(-1)!.request.modelId).toBe("merge-audio-video");
+ });
+
+ it("refuses segments the motion model can't take", () => {
+ expect(() => katanaSteps({ engine: "open", reference: "/r", photos, segments: [{ start: 0, end: 8 }] })).toThrow(/up to 5 s/);
+ expect(() => katanaSteps({ engine: "cloud", reference: "/r", photos, segments: [{ start: 0, end: 2 }] })).toThrow(/at least 3 s/);
+ expect(() => katanaSteps({ engine: "cloud", reference: "/r", photos: [], segments })).toThrow(/at least one photo/);
+ });
+});
+
+describe("katana runs (demo mode)", () => {
+ it("runs every step and finishes with the edit", async () => {
+ const reference = file("demo-portrait.mp4", "video/mp4");
+ const photo = file("grade-sample.jpg", "image/jpeg");
+ const preview = katana.previewKatana({ engine: "open", reference, photos: [photo], duration: 8, length: 4 });
+ expect(preview.segments).toHaveLength(2);
+ expect(preview.steps).toBe(10);
+ const job = katana.createKatana({ engine: "open", reference, photos: [photo], duration: 8, length: 4, instructions: "keep the red jacket", title: "Dance" });
+ expect(Object.keys(job.steps)).toHaveLength(10);
+ expect(job.generations[job.steps.key0].request.prompt).toContain("keep the red jacket");
+ const final = await settle(job.steps[job.final]);
+ expect(final.status).toBe("succeeded");
+ expect(katanaStage(katana.getKatana(job.id)!)).toBe("done");
+ expect(katana.listKatana().map((j) => j.id)).toContain(job.id);
+ });
+
+ it("is an Assist tool with a priced plan", () => {
+ const reference = file("demo-landscape.mp4", "video/mp4");
+ const photo = file("grade-sample.jpg", "image/jpeg");
+ const tool = getTool("katana")!;
+ expect(tool.gated).toBe(true);
+ const [job] = tool.plan!({ reference, photos: [photo], segment_seconds: 4 }, { engine: "open" });
+ expect(job).toMatchObject({ tool: "katana", kind: "video", modelId: "oss-wan22-animate" });
+ expect(job.error).toBeUndefined();
+ expect(tool.plan!({ reference: "nope", photos: [] }, { engine: "cloud" })[0].error).toBeTruthy();
+ });
+});