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: segments open on the right shot, segments keep their length, stop and retry

Claudeb5ef9f5e905a
diff --git a/src/app/api/katana/[id]/retry/route.ts b/src/app/api/katana/[id]/retry/route.ts
new file mode 100644
index 00000000..57aad703
--- /dev/null
+++ b/src/app/api/katana/[id]/retry/route.ts
@@ -0,0 +1,13 @@
+import { getKatana, rerunKatana, retryKatana } from "@/server/katana";
+
+/** Retry the failed steps of a run (and the ones after them); `?all=1` starts the same run again from scratch. */
+export async function POST(request: Request, ctx: RouteContext<"/api/katana/[id]/retry">) {
+ const { id } = await ctx.params;
+ if (!getKatana(id)) return Response.json({ error: "Not found" }, { status: 404 });
+ try {
+ const all = new URL(request.url).searchParams.get("all") === "1";
+ return Response.json(all ? rerunKatana(id) : retryKatana(id), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/app/api/katana/[id]/route.ts b/src/app/api/katana/[id]/route.ts
index 6d22a2f0..88fad2dc 100644
--- a/src/app/api/katana/[id]/route.ts
+++ b/src/app/api/katana/[id]/route.ts
@@ -8,7 +8,7 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/katana/[id]">)
return job ? Response.json(job) : Response.json({ error: "Not found" }, { status: 404 });
}
-/** Forget the run (its clips stay in the Library). */
+/** Forget the run: steps still running are stopped first (the clips it made 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/components/katana/hooks.ts b/src/components/katana/hooks.ts
index 430ff25f..c1cc7c3e 100644
--- a/src/components/katana/hooks.ts
+++ b/src/components/katana/hooks.ts
@@ -75,5 +75,13 @@ export function useKatanaActions() {
},
onSuccess: (id) => qc.setQueryData<KatanaJobView[]>(["katana"], (xs) => xs?.filter((j) => j.id !== id)),
});
- return { start, remove };
+ /** Retry the failed steps (all: the whole run again, as a new run). */
+ const retry = useMutation({
+ mutationFn: async ({ id, all }: { id: string; all?: boolean }) => json<KatanaJobView>(await fetch(`/api/katana/${id}/retry${all ? "?all=1" : ""}`, { method: "POST" })),
+ onSuccess: (job, { all }) => {
+ qc.setQueryData<KatanaJobView[]>(["katana"], (xs) => (all ? [job, ...(xs ?? [])] : (xs ?? []).map((j) => (j.id === job.id ? job : j))));
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ },
+ });
+ return { start, remove, retry };
}
diff --git a/src/components/katana/katana-studio.tsx b/src/components/katana/katana-studio.tsx
index b65d2d2a..9f9018aa 100644
--- a/src/components/katana/katana-studio.tsx
+++ b/src/components/katana/katana-studio.tsx
@@ -1,9 +1,10 @@
"use client";
-import { ChevronDown, Download, Film, Loader2, ScanLine, Sparkles, Trash2, Users } from "lucide-react";
+import { ChevronDown, Download, Film, Loader2, RotateCcw, ScanLine, Sparkles, Trash2, Users } from "lucide-react";
import { nanoid } from "nanoid";
import { useDeferredValue, useMemo, useState } from "react";
import { toast } from "sonner";
+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Label } from "@/components/ui/label";
@@ -13,25 +14,42 @@ 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 { frameDiff, openVideo, releaseVideo, 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 { detectCutIndices, KATANA_LIMITS, katanaProgress, katanaStage, motionModel, MOTION_MODELS, nearestAspect, planSegments, refineCut, refineTimes, 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). */
+/**
+ * Scene cuts by a frame-difference pass in the browser: about 6 samples a second at 48 px, then each
+ * jump is pinned down with 5 finer samples between the two around it, so the cut sits on the first
+ * frame of the new shot (within a frame at 30 fps), not between samples.
+ */
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 v = await openVideo(src);
+ try {
+ const frames = await sampleFrames(v, times, { width: 48, onProgress: (d) => onProgress(d * 0.8) });
+ const at = frames.map((f) => f.t);
+ const diffs = frames.slice(1).map((f, i) => frameDiff(frames[i].data, f.data));
+ const coarse = detectCutIndices(diffs, at);
+ const cuts: number[] = [];
+ for (const [n, i] of coarse.entries()) {
+ const fine = await sampleFrames(v, refineTimes(at[i], at[i + 1]), { width: 48 });
+ cuts.push(refineCut(fine.slice(1).map((f, k) => frameDiff(fine[k].data, f.data)), fine.map((f) => f.t)));
+ onProgress(0.8 + (0.2 * (n + 1)) / coarse.length);
+ }
+ return cuts;
+ } finally {
+ releaseVideo(v);
+ }
}
const money = (usd: number | null | undefined, demo?: boolean, open?: boolean) => (demo ? "Demo · free" : open ? "Free · your GPU" : usd == null ? "Price unknown" : `≈ $${usd.toFixed(2)}`);
@@ -59,6 +77,7 @@ export function KatanaStudio() {
const segments = useMemo<Segment[] | null>(() => {
if (!meta) return null;
try {
+ if (mode === "scenes" && !cuts) return null;
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;
@@ -86,6 +105,8 @@ export function KatanaStudio() {
? "Uploading…"
: !meta && !unreadable
? "Reading the reference…"
+ : scanning !== null
+ ? "Finding the cuts…"
: !photos.length
? "Add at least one photo of your subject"
: photos.some((p) => p.uploading)
@@ -97,14 +118,16 @@ export function KatanaStudio() {
: null;
const scan = async () => {
- if (!reference || !meta) return;
+ if (!reference || !meta || scanning !== null) return;
+ // The choice shows at once, with its progress; the plan waits for the cuts.
+ setMode("scenes");
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) {
+ if (!cuts) setMode("fixed");
toast.error((e as Error).message);
} finally {
setScanning(null);
@@ -185,10 +208,12 @@ export function KatanaStudio() {
{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>
+ <span className="text-[12px] text-muted-foreground" role="status" aria-live="polite">
+ {scanning !== null ? "Reading the clip in your browser" : `${cuts?.length ?? 0} cut${cuts?.length === 1 ? "" : "s"} found in your browser`}
+ </span>
</div>
)}
- {segments && <SegmentBar segments={segments} duration={Math.min(meta.duration, KATANA_LIMITS.maxReference)} />}
+ {scanning !== null && !cuts ? <Skeleton className="mt-3 h-7 w-full rounded-lg" /> : 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>
)}
@@ -204,6 +229,7 @@ export function KatanaStudio() {
<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>
+ {engine === "open" && <p className="mt-1 text-[12px] text-muted-foreground">The open engine uses your first 2 photos (Qwen-Image-Edit takes the frame and two references).</p>}
</Panel>
<Panel title="Instructions (optional)">
<Textarea
@@ -253,7 +279,7 @@ export function KatanaStudio() {
(blocker ?? "Pricing…")
)}
</p>
- <Button size="lg" className={cn("rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={start.isPending}>
+ <Button size="lg" className={cn("rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={start.isPending || scanning !== null}>
{start.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Recreate
</Button>
</div>
@@ -302,7 +328,12 @@ function stepRows(j: KatanaJobView): { segment: number; rows: StepRow[] }[] {
}
function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {
- const { remove } = useKatanaActions();
+ const { remove, retry } = useKatanaActions();
+ const again = (id: string, all: boolean) =>
+ retry.mutate(
+ { id, all },
+ { onSuccess: (j) => toast.success(all ? `Started again · ${j.segments.length} segment${j.segments.length === 1 ? "" : "s"}` : "Retrying the failed steps"), onError: (e) => toast.error((e as Error).message) },
+ );
if (loading)
return (
<div className="mx-auto mt-10 max-w-[1040px] space-y-2">
@@ -339,9 +370,30 @@ function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {
</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>
+ {stage !== "running" && (
+ <Button variant="ghost" size="sm" className="rounded-full" disabled={retry.isPending} onClick={() => again(j.id, stage === "done")}>
+ <RotateCcw className="size-3.5" /> {stage === "failed" ? "Retry failed steps" : "Run again"}
+ </Button>
+ )}
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label={`Remove ${j.title}`}>
+ <Trash2 className="size-4" />
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove this edit?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {stage === "running" ? "Its steps still running are stopped, and it leaves this list." : "It leaves this list."} The clips it already made stay in your Library.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep it</AlertDialogCancel>
+ <AlertDialogAction onClick={() => remove.mutate(j.id, { onSuccess: () => toast("Removed — its clips stay in your Library"), onError: (e) => toast.error((e as Error).message) })}>Remove</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</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"}
@@ -352,7 +404,9 @@ function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {
<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>
+ <p className="mt-1 text-[12px] text-muted-foreground">
+ {stage === "failed" ? "A step failed — open the steps for the reason, then retry: the finished steps are kept" : `${pct}% · steps run as soon as the ones before them finish`}
+ </p>
</div>
)}
<Collapsible className="mt-2">
diff --git a/src/lib/av/katana.ts b/src/lib/av/katana.ts
index e12e7602..e1971891 100644
--- a/src/lib/av/katana.ts
+++ b/src/lib/av/katana.ts
@@ -50,29 +50,62 @@ export interface Segment {
}
const r2 = (t: number) => Math.round(t * 100) / 100;
+/** Times that must not fall before the moment they stand for (a cut, the clip's end) round up / down. */
+const up2 = (t: number) => Math.ceil(t * 100 - 1e-6) / 100;
+const down2 = (t: number) => Math.floor(t * 100 + 1e-6) / 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.
+ * Where scene cuts are in a frame-difference pass: `diffs[i]` is the change between samples i and i+1.
+ * A cut is a spike well above the clip's usual change (its median), at least `minGap` seconds apart;
+ * returns i for each (the cut lies between samples i and i+1).
*/
-export function detectCuts(diffs: number[], times: number[], o: { minGap?: number; floor?: number; ratio?: number } = {}): number[] {
+export function detectCutIndices(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[] = [];
+ const out: 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);
+ if (out.length && times[i + 1] - times[out.at(-1)! + 1] < minGap) continue;
+ out.push(i);
}
- return cuts;
+ return out;
+}
+
+/**
+ * Scene cuts from a frame-difference pass sampled at `times`. Each cut is placed at the first sample of
+ * the new shot (the later sample of the jump), never between the samples, so a segment starting there
+ * opens on the new shot (its keyframe is the right shot). Refine with refineCut for frame accuracy.
+ */
+export function detectCuts(diffs: number[], times: number[], o: { minGap?: number; floor?: number; ratio?: number } = {}): number[] {
+ return detectCutIndices(diffs, times, o).map((i) => up2(times[i + 1]));
}
+/**
+ * A cut found between two coarse samples, pinned down with finer ones: `times` run from the last sample
+ * of the old shot to the first of the new one, `diffs[i]` is the change between times[i] and times[i+1];
+ * the cut is the sample right after the biggest jump.
+ */
+export function refineCut(diffs: number[], times: number[]): number {
+ let best = 0;
+ diffs.forEach((d, i) => {
+ if (d > diffs[best]) best = i;
+ });
+ return up2(times[best + 1] ?? times.at(-1)!);
+}
+
+/** Fine sample times between two coarse samples (both ends included). */
+export function refineTimes(a: number, b: number, steps = 5): number[] {
+ return Array.from({ length: steps + 1 }, (_, i) => a + ((b - a) * i) / steps);
+}
+
+/** How far into a segment its keyframe is taken (s): clear of a cut's blended or late frame. */
+export const KEYFRAME_OFFSET = 0.1;
+
/** 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));
@@ -84,7 +117,8 @@ function pieces(a: number, b: number, max: number): Segment[] {
* 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));
+ // Rounded down: the last segment must not ask for time past the end of the file.
+ const duration = down2(Math.min(o.duration, KATANA_LIMITS.maxReference));
if (!(duration > 0)) return [];
const min = Math.min(o.min, duration);
let segs: Segment[];
@@ -183,11 +217,14 @@ export function katanaSteps(o: KatanaInput): KatanaStep[] {
? { 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") } });
+ // The keyframe a few frames in on the open engine (frame accurate); the cloud tool takes the first frame.
+ const pick = o.engine === "open" ? { at: KEYFRAME_OFFSET } : ("first" as const);
+ steps.push({ key: `frame${i}`, after: `cut${i}`, chain: [{ slot: "video" }], request: { ...base, modelId: FRAME_MODEL[o.engine], op: "frame", params: frameParams(o.engine, pick), 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") };
+ // Open models render as long as they're told (Wan Fun Control defaults to 81 frames ≈ 5 s): ask for the segment's length.
+ const motion: GenerationRequest = { ...base, modelId: m.id, op: m.op, prompt: motionPrompt(o.instructions), params: { aspectRatio: aspect, ...(o.engine === "open" && { resolution: "480p", duration: r2(s.end - s.start) }) }, 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) } } });
@@ -229,6 +266,20 @@ export function katanaSteps(o: KatanaInput): KatanaStep[] {
return steps;
}
+/** The steps a retry makes again: the failed ones and every step after them (in pipeline order). */
+export function stepsToRedo(steps: KatanaStep[], failed: string[]): string[] {
+ const redo = new Set(failed);
+ for (let grew = true; grew; ) {
+ grew = false;
+ for (const st of steps) {
+ if (redo.has(st.key) || !(st.after === undefined ? [] : [st.after].flat()).some((a) => redo.has(a))) continue;
+ redo.add(st.key);
+ grew = true;
+ }
+ }
+ return steps.filter((st) => redo.has(st.key)).map((st) => st.key);
+}
+
/** 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";
@@ -244,9 +295,13 @@ export interface KatanaJob {
motionModel: string;
segments: Segment[];
keepAudio: boolean;
+ /** The render shape (older runs: 16:9). */
+ aspectRatio?: string;
batchId: string;
/** Generation id per step key. */
steps: Record<string, string>;
+ /** Steps made again by a retry: the generations they replaced, by step key. */
+ replaced?: Record<string, string[]>;
final: string;
createdAt: number;
updatedAt: number;
diff --git a/src/server/katana.ts b/src/server/katana.ts
index 90f611ca..4cdeba80 100644
--- a/src/server/katana.ts
+++ b/src/server/katana.ts
@@ -2,13 +2,13 @@ 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 { finalKey, KATANA_FEATURE, KATANA_LIMITS, katanaSteps, katanaStage, motionModel, MOTION_MODELS, planSegments, stepsToRedo, 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 { cancelGeneration, createGenerations, getGeneration, previewChained } from "./generations";
import { engineMode } from "./settings";
import fs from "node:fs";
import { absolutePath } from "./storage";
@@ -47,10 +47,86 @@ export function listKatana(limit = 20): KatanaJobView[] {
return rows.map((r) => view(toJob(r)));
}
+/** Steps that haven't finished are stopped (nothing more is spent); finished clips stay in the Library. */
+function stopUnfinished(ids: string[]): void {
+ for (const gid of ids) {
+ const g = getGeneration(gid);
+ if (g && (g.status === "queued" || g.status === "running")) void cancelGeneration(gid);
+ }
+}
+
export function deleteKatana(id: string): boolean {
+ const j = getKatana(id);
+ if (j) stopUnfinished(Object.values(j.steps));
return db().prepare("DELETE FROM katana_jobs WHERE id = ?").run(id).changes > 0;
}
+function saveJob(j: KatanaJob): KatanaJob {
+ const { id, createdAt, ...data } = j;
+ const now = Date.now();
+ delete (data as Partial<KatanaJob>).updatedAt;
+ db().prepare("UPDATE katana_jobs SET data_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(data), now, id);
+ return { ...j, id, createdAt, updatedAt: now };
+}
+
+const inputOf = (j: KatanaJob): KatanaInput => ({
+ engine: j.engine,
+ reference: j.reference,
+ photos: j.photos,
+ instructions: j.instructions,
+ segments: j.segments,
+ motionModel: j.motionModel,
+ aspectRatio: j.aspectRatio,
+ keepAudio: j.keepAudio,
+ title: j.title,
+});
+
+/**
+ * Retry a run whose steps failed: the failed steps and every step after them are made again (new
+ * generations in the same batch, fed by the steps that did finish); nothing that succeeded is paid twice.
+ */
+export function retryKatana(id: string): KatanaJobView {
+ const found = getKatana(id);
+ if (!found) throw new Error("This run no longer exists");
+ const { generations, ...j } = found;
+ const failed = Object.entries(j.steps)
+ .filter(([, gid]) => {
+ const g = generations[gid];
+ return !g || g.status === "failed" || g.status === "canceled";
+ })
+ .map(([k]) => k);
+ if (!failed.length) throw new Error("No step failed — the run is done or still going");
+ const steps = katanaSteps(inputOf(j));
+ const redo = stepsToRedo(steps, failed);
+ // Old steps downstream of the failure that are still waiting would fail anyway: stop them now.
+ stopUnfinished(redo.map((k) => j.steps[k]).filter(Boolean));
+ const ids = { ...j.steps };
+ const made: string[] = [];
+ try {
+ for (const key of redo) {
+ const st = steps.find((x) => x.key === key)!;
+ const after = st.after === undefined ? [] : [st.after].flat();
+ const g = createGenerations({ ...st.request, ...(st.chain && { chain: st.chain }) }, { batchId: j.batchId, ...(after.length && { dependsOn: after.map((a) => ids[a]) }) })[0];
+ made.push(g.id);
+ ids[key] = g.id;
+ }
+ } catch (e) {
+ for (const gid of made) void cancelGeneration(gid);
+ throw e;
+ }
+ const replaced = { ...j.replaced };
+ for (const k of redo) if (j.steps[k] && j.steps[k] !== ids[k]) replaced[k] = [...(replaced[k] ?? []), j.steps[k]];
+ return view(saveJob({ ...j, steps: ids, replaced }));
+}
+
+/** The same reference, photos and settings as a new run. */
+export function rerunKatana(id: string): KatanaJobView {
+ const j = getKatana(id);
+ if (!j) throw new Error("This run no longer exists");
+ const aspect = j.aspectRatio === "16:9" || j.aspectRatio === "9:16" || j.aspectRatio === "1:1" ? j.aspectRatio : undefined;
+ return createKatana({ ...inputOf(j), aspectRatio: aspect, duration: j.segments.at(-1)?.end });
+}
+
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({
@@ -124,6 +200,7 @@ export function createKatana(body: KatanaRequest): KatanaJobView {
motionModel: input.motionModel!,
segments: input.segments,
keepAudio: input.keepAudio !== false,
+ ...(input.aspectRatio && { aspectRatio: input.aspectRatio }),
batchId: run.batchId,
steps: Object.fromEntries(Object.entries(run.byKey).map(([k, g]) => [k, g.id])),
final: finalKey(steps),
diff --git a/tests/av-katana.test.ts b/tests/av-katana.test.ts
index 78512786..d22229d1 100644
--- a/tests/av-katana.test.ts
+++ b/tests/av-katana.test.ts
@@ -3,7 +3,7 @@ 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 { detectCuts, finalKey, KEYFRAME_OFFSET, katanaStage, katanaSteps, nearestAspect, planSegments, refineCut, refineTimes, stepsToRedo } from "@/lib/av/katana";
import { frameParams, frameRequest } from "@/lib/av/frames";
vi.setConfig({ testTimeout: 150_000 });
@@ -39,10 +39,39 @@ describe("katana segment planning", () => {
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]);
+ // Each cut is the first sample of the new shot, never the midpoint (which lies in the old shot).
+ expect(detectCuts(diffs, times)).toEqual([3, 7]);
expect(detectCuts(diffs.map(() => 0.03), times)).toEqual([]);
});
+ it("places a cut that falls between samples at or after the real cut, so the segment opens on the new shot", () => {
+ // Hard cuts at 4.0 s and 7.0 s, sampled every 1/6 s from 0.08 s (as the studio does, off the frame grid).
+ const shotAt = (t: number) => (t < 4 ? 0 : t < 7 ? 1 : 2);
+ const times = Array.from({ length: 60 }, (_, i) => 0.08 + i / 6);
+ const diffs = times.slice(1).map((t, i) => (shotAt(t) !== shotAt(times[i]) ? 0.7 : 0.02));
+ const cuts = detectCuts(diffs, times);
+ expect(cuts).toHaveLength(2);
+ cuts.forEach((c, i) => {
+ expect(c).toBeGreaterThanOrEqual([4, 7][i]);
+ expect(shotAt(c)).toBe(i + 1);
+ expect(c - [4, 7][i]).toBeLessThan(1 / 6 + 0.01);
+ });
+ // Refined with finer samples between the two around the jump: within a 30 fps frame of the cut.
+ const fine = refineTimes(times[23], times[24]);
+ const at = refineCut(fine.slice(1).map((t, k) => (shotAt(t) !== shotAt(fine[k]) ? 0.7 : 0.02)), fine);
+ expect(at).toBeGreaterThanOrEqual(4);
+ expect(at - 4).toBeLessThan(1 / 30 + 0.01);
+ // The planned segments start at the cuts: every segment's keyframe is in its own shot.
+ const segs = planSegments({ duration: 10, mode: "scenes", cuts, min: 1, max: 5 });
+ expect(segs.map((s) => shotAt(s.start))).toEqual([0, 1, 2]);
+ expect(segs.map((s) => shotAt(s.start + KEYFRAME_OFFSET))).toEqual([0, 1, 2]);
+ });
+
+ it("never plans past the end of the file (the end rounds down)", () => {
+ expect(planSegments({ duration: 10.008, mode: "fixed", length: 5, min: 1, max: 5 }).at(-1)!.end).toBe(10);
+ expect(planSegments({ duration: 10.008, mode: "scenes", cuts: [3.001], min: 1, max: 5 }).at(-1)!.end).toBe(10);
+ });
+
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 },
@@ -107,6 +136,10 @@ describe("katana steps", () => {
["final", "oss-mux", "mux"],
]);
expect(steps[0].request.params).toMatchObject({ startTime: 0, endTime: 4, aspectRatio: "9:16" });
+ // The keyframe is taken a few frames in, clear of a cut's edge.
+ expect(steps[1].request.params).toEqual({ startTime: KEYFRAME_OFFSET, endTime: KEYFRAME_OFFSET + 0.5, extra: { frameIndex: 0 } });
+ // The open motion model is told the segment's length (Fun Control would render its 81-frame default).
+ expect(steps[3].request.params).toMatchObject({ duration: 4, resolution: "480p" });
// 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" }] });
@@ -115,6 +148,27 @@ describe("katana steps", () => {
expect(finalKey(steps)).toBe("final");
});
+ it("open Wan Fun Control renders each segment as long as it is", async () => {
+ const segs = [
+ { start: 0, end: 3 },
+ { start: 3, end: 7.5 },
+ ];
+ const steps = katanaSteps({ engine: "open", reference: "/r.mp4", photos, segments: segs, motionModel: "oss-wan22-fun-control" });
+ const moves = steps.filter((s) => s.key.startsWith("move"));
+ expect(moves.map((s) => s.request.params?.duration)).toEqual([3, 4.5]);
+ // …which the ComfyUI provider turns into the 4n+1 frame count for that span at 16 fps (3 s → 49, not 81).
+ const { prepareWorkflow } = await import("@/server/providers/comfyui");
+ const { workflow, manifest } = await prepareWorkflow("wan22-fun-control-14b", { prompt: "p", images: ["k.png"], video: "cut.mp4", duration: 3, aspectRatio: "16:9", resolution: "480p" }, { generationId: "g", op: "motion-transfer", upload: async () => "x" });
+ const frames = manifest.bindings.frames!.map((t) => workflow[t.node].inputs[t.input]);
+ expect(frames.every((f) => f === 49)).toBe(true);
+ });
+
+ it("a retry redoes the failed steps and everything after them, nothing before", () => {
+ const steps = katanaSteps({ engine: "open", reference: "/r.mp4", photos, segments });
+ expect(stepsToRedo(steps, ["move1"])).toEqual(["move1", "join", "final"]);
+ expect(stepsToRedo(steps, ["frame0"])).toEqual(["frame0", "key0", "move0", "join", "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 });
@@ -162,6 +216,32 @@ describe("katana runs (demo mode)", () => {
expect(katana.listKatana().map((j) => j.id)).toContain(job.id);
});
+ it("a failed step can be retried without redoing what finished; removing a run stops it", async () => {
+ const reference = file("demo-portrait.mp4", "video/mp4");
+ const photo = file("grade-sample.jpg", "image/jpeg");
+ const job = katana.createKatana({ engine: "open", reference, photos: [photo], duration: 8, length: 4, title: "Retry me" });
+ expect((await settle(job.steps[job.final])).status).toBe("succeeded");
+ // Pretend the second segment's motion step failed.
+ const { db } = await import("@/server/db");
+ db().prepare("UPDATE generations SET status = 'failed', error = 'GPU out of memory' WHERE id = ?").run(job.steps.move1);
+ expect(katanaStage(katana.getKatana(job.id)!)).toBe("failed");
+ const retried = katana.retryKatana(job.id);
+ for (const k of ["cut0", "frame0", "key0", "move0", "cut1", "frame1", "key1"]) expect(retried.steps[k]).toBe(job.steps[k]);
+ for (const k of ["move1", "join", "final"]) expect(retried.steps[k]).not.toBe(job.steps[k]);
+ expect(retried.replaced?.move1).toEqual([job.steps.move1]);
+ expect(gens.getGeneration(retried.steps.move1)!.batchId).toBe(job.batchId);
+ expect((await settle(retried.steps[retried.final])).status).toBe("succeeded");
+ expect(katanaStage(katana.getKatana(job.id)!)).toBe("done");
+ expect(() => katana.retryKatana(job.id)).toThrow(/No step failed/);
+ // Run again: a new run with the same settings.
+ const again = katana.rerunKatana(job.id);
+ expect(again.id).not.toBe(job.id);
+ expect(again.segments).toEqual(job.segments);
+ expect(katana.deleteKatana(again.id)).toBe(true);
+ for (const id of Object.values(again.steps)) expect(["canceled", "succeeded"]).toContain((await settle(id)).status);
+ expect(Object.values(again.steps).some((id) => gens.getGeneration(id)!.status === "canceled")).toBe(true);
+ });
+
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");