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.

Genjutsu: the /genjutsu studio — four modes, references, looks, price first, compare and Run again

Claude4a66a37eb783
diff --git a/src/app/(studio)/genjutsu/page.tsx b/src/app/(studio)/genjutsu/page.tsx
new file mode 100644
index 00000000..920ced0b
--- /dev/null
+++ b/src/app/(studio)/genjutsu/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { GenjutsuStudio } from "@/components/genjutsu/genjutsu-studio";
+
+export const metadata: Metadata = { title: "Genjutsu" };
+
+export default function Page() {
+ return <GenjutsuStudio />;
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index d78ed3b5..96d237be 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -51,6 +51,7 @@ import {
Presentation,
Box,
Swords,
+ WandSparkles,
TrendingUp,
type LucideIcon,
} from "lucide-react";
@@ -136,6 +137,7 @@ const NAV: NavGroupDef[] = [
{ href: "/faceless", label: "Faceless Studio", icon: Tv },
{ href: "/explainer", label: "Explainer", icon: Presentation },
{ href: "/lipsync", label: "Lipsync & avatars", icon: Mic2 },
+ { href: "/genjutsu", label: "Genjutsu", icon: WandSparkles },
{ href: "/motion-control", label: "Motion control", icon: PersonStanding },
{ href: "/video-edit", label: "Edit video", icon: Scissors },
{ href: "/extend", label: "Extend video", icon: FastForward },
diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsx
new file mode 100644
index 00000000..ca7a4752
--- /dev/null
+++ b/src/components/genjutsu/genjutsu-studio.tsx
@@ -0,0 +1,729 @@
+"use client";
+
+import { Brush, Download, Loader2, RotateCcw, Sparkles, Undo2, Wand2 } from "lucide-react";
+import { nanoid } from "nanoid";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { StepList, type StepRow } from "@/components/av/step-list";
+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
+import { useGenerationList } from "@/components/av/use-generation";
+import { FrameStage, frameFromBlob, type Frame } from "@/components/remove-object/frame-stage";
+import { VideoCompare } from "@/components/remove-object/video-compare";
+import { useSubmitGuard } from "@/components/shorts/hooks";
+import { ClipBar, ClipDrop, costText, Field, Segmented, tabKeys } from "@/components/shorts/ui";
+import { clipDuration, clipSize, useSourceClip } from "@/components/shorts/use-source-clip";
+import { Feed } from "@/components/studio/feed";
+import { fileToList, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
+import { SketchEditor, type Stroke } from "@/components/studio/sketch-editor";
+import { VideoTrimmer, type TrimRange, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";
+import { useEngine, useGenerations, useStatus } from "@/lib/api";
+import {
+ chooseMaker,
+ decodeSetup,
+ GENJUTSU,
+ GENJUTSU_MODES,
+ genjutsuProblem,
+ getMode,
+ makersFor,
+ MODE_TARGETS,
+ TARGET_LABELS,
+ type GenjutsuLook,
+ type GenjutsuMode,
+ type GenjutsuQuality,
+ type GenjutsuSetup,
+ type GenjutsuTarget,
+ type GenjutsuTier,
+ type Maker,
+} from "@/lib/catalog/genjutsu";
+import { chainState } from "@/lib/catalog/shorts";
+import type { PixelPoint } from "@/lib/catalog/types";
+import { downloadHref, downloadName } from "@/lib/library";
+import { cn } from "@/lib/utils";
+import { useGenjutsuEstimate, useGenjutsuRun, type GenjutsuBody } from "./hooks";
+import { LookPicker, type LookSource } from "./look-picker";
+import { SetupCode } from "./setup-code";
+
+const LIMITS = `MP4, MOV or WebM · ${GENJUTSU.minSeconds}–${GENJUTSU.maxSeconds} s are used · ${GENJUTSU.maxBytes / 1024 / 1024} MB`;
+
+interface Paint {
+ mask: string;
+ overlay: string;
+ strokes: Stroke[];
+}
+
+interface Run {
+ final: string;
+ ids: string[];
+ /** The original the result is compared with, and where the selection starts. */
+ before: string;
+ start: number;
+ ratio?: number;
+}
+
+const isMode = (v: string | null): v is GenjutsuMode => !!v && GENJUTSU_MODES.some((m) => m.id === v);
+const asSlot = (ref: string): SlotValue => ({ id: nanoid(8), ref, preview: ref, kind: "image" });
+const ready = (xs: SlotValue[]) => xs.filter((x) => !x.uploading).map((x) => x.ref);
+
+/**
+ * Genjutsu: keep a clip's motion, camera and framing and change what is in it — Motion transfer, Object swap, Restyle
+ * or Insert. Pick the mode, add the clip (4–30 s, trimmed here) and your references, say what changes, see the price
+ * (or "Free" on your ComfyUI), get the result with a before / after wipe. Setups copy and paste as a short code.
+ * The plan: src/lib/catalog/genjutsu.ts; the server: src/server/genjutsu.ts.
+ */
+export function GenjutsuStudio() {
+ const [engine, setEngine, engineMode] = useEngine();
+ const status = useStatus().data;
+ const higgsfield = !!status?.providers.higgsfield?.configured;
+ const [mode, setModeState] = useState<GenjutsuMode>("motion");
+ const source = useSourceClip(GENJUTSU.maxBytes);
+ const clip = source.clip;
+ const trimmer = useRef<VideoTrimmerHandle>(null);
+ const [range, setRange] = useState<TrimRange | null>(null);
+ const [refs, setRefs] = useState<SlotValue[]>([]);
+ const [targets, setTargets] = useState<Partial<Record<GenjutsuMode, GenjutsuTarget>>>({});
+ const [subject, setSubject] = useState("");
+ const [prompts, setPrompts] = useState<Partial<Record<GenjutsuMode, string>>>({});
+ const [picked, setPicked] = useState<Record<string, string>>({});
+ const [tier, setTier] = useState<GenjutsuTier>("standard");
+ const [quality, setQuality] = useState<GenjutsuQuality>(GENJUTSU.defaultQuality);
+ const [lookSource, setLookSource] = useState<LookSource>("fuobe");
+ const [look, setLook] = useState<GenjutsuLook | null>(null);
+ const [custom, setCustom] = useState<SlotValue[]>([]);
+ const [words, setWords] = useState("");
+ const [points, setPoints] = useState<PixelPoint[]>([]);
+ const [pointLabel, setPointLabel] = useState<"positive" | "negative">("positive");
+ const [paint, setPaint] = useState<Paint | null>(null);
+ const [painting, setPainting] = useState(false);
+ const [frame, setFrame] = useState<Frame | null>(null);
+ const [frameError, setFrameError] = useState(false);
+ const [run, setRun] = useState<Run | null>(null);
+ const runMutation = useGenjutsuRun();
+ const guard = useSubmitGuard();
+ const history = useGenerations({ features: [GENJUTSU.feature], limit: 24 });
+
+ const target = MODE_TARGETS[mode].length ? (targets[mode] ?? MODE_TARGETS[mode][0]) : undefined;
+ const prompt = prompts[mode] ?? "";
+ const duration = clipDuration(clip);
+ const size = clipSize(clip);
+
+ const setMode = (m: GenjutsuMode) => {
+ setModeState(m);
+ const url = new URL(window.location.href);
+ url.searchParams.set("mode", m);
+ window.history.replaceState(null, "", url);
+ };
+
+ // Restyle's look as it is now (a custom look's images while they upload don't count yet).
+ const effLook: GenjutsuLook | undefined =
+ mode !== "restyle"
+ ? undefined
+ : lookSource === "custom"
+ ? { kind: "custom", images: ready(custom), ...(words.trim() ? { words: words.trim() } : {}) }
+ : look && look.kind === (lookSource === "fuobe" ? "preset" : "higgsfield")
+ ? look
+ : undefined;
+ const lookKind = mode === "restyle" ? (lookSource === "higgsfield" ? "higgsfield" : "fuobe") : "";
+ const choiceKey = `${engine}:${mode}:${target ?? ""}:${lookKind}`;
+ const choice = chooseMaker({ engine, mode, target, tier, look: effLook ?? (mode === "restyle" ? lookPlaceholder(lookSource) : undefined), modelId: picked[choiceKey], higgsfield });
+ const maker: Maker | null = "maker" in choice ? choice.maker : null;
+ const options = makersFor(engine, mode, target, effLook ?? (mode === "restyle" ? lookPlaceholder(lookSource) : undefined));
+ const references = mode === "restyle" && lookSource !== "higgsfield" ? [] : ready(refs);
+ const showRefs = mode !== "restyle" || lookSource === "higgsfield";
+ const needsFrame = (mode === "swap" && (target === "click" || target === "paint")) || (mode === "insert" && target === "paint");
+
+ // The selection's first frame, grabbed by the browser: what points and paint are made on.
+ const startAt = range ? Math.round(range.startTime * 100) / 100 : null;
+ const previewSrc = clip?.preview;
+ useEffect(() => {
+ if (!needsFrame || !previewSrc || startAt === null) return;
+ let alive = true;
+ const t = setTimeout(async () => {
+ const blob = await trimmer.current?.grabFrame(startAt, 1280);
+ if (!alive) return;
+ if (!blob) return setFrameError(true);
+ const f = await frameFromBlob(blob).catch(() => null);
+ if (!alive || !f) return;
+ setFrameError(false);
+ setFrame((old) => {
+ if (old) URL.revokeObjectURL(old.url);
+ return f;
+ });
+ }, 350);
+ return () => {
+ alive = false;
+ clearTimeout(t);
+ };
+ }, [needsFrame, previewSrc, startAt]);
+ // A new first frame: points and paint made on the old one no longer line up.
+ const [frameAt, setFrameAt] = useState<string | null>(null);
+ const frameKey = `${previewSrc}|${startAt}`;
+ if (frameKey !== frameAt) {
+ setFrameAt(frameKey);
+ if (points.length || paint) {
+ setPoints([]);
+ setPaint(null);
+ }
+ }
+
+ const apply = (s: GenjutsuSetup) => {
+ setModeState(s.mode);
+ const e = s.engine && engineMode === "both" ? s.engine : engine;
+ if (s.engine && engineMode === "both") setEngine(s.engine);
+ if (s.tier) setTier(s.tier);
+ if (s.quality) setQuality(s.quality);
+ const t = s.target ?? MODE_TARGETS[s.mode][0];
+ if (s.target) setTargets((x) => ({ ...x, [s.mode]: s.target }));
+ setSubject(s.subject ?? "");
+ setPrompts((x) => ({ ...x, [s.mode]: s.prompt ?? "" }));
+ if (s.look?.kind === "custom") {
+ setLookSource("custom");
+ setCustom(s.look.images.map(asSlot));
+ setWords(s.look.words ?? "");
+ } else if (s.look) {
+ setLookSource(s.look.kind === "preset" ? "fuobe" : "higgsfield");
+ setLook(s.look);
+ }
+ if (s.model) setPicked((x) => ({ ...x, [`${e}:${s.mode}:${t ?? ""}:${s.mode === "restyle" ? (s.look?.kind === "higgsfield" ? "higgsfield" : "fuobe") : ""}`]: s.model! }));
+ if (s.references?.length) setRefs(s.references.map(asSlot));
+ toast("Setup pasted", { description: clip ? "Check the references and press Generate." : "Add a clip to run it on." });
+ };
+
+ // Hand-offs: ?mode=swap, ?video=/api/files/…, ?image=/api/files/… (a reference), ?setup=gj1.….
+ useEffect(() => {
+ const p = new URLSearchParams(window.location.search);
+ /* eslint-disable react-hooks/set-state-in-effect -- read once after hydration */
+ const m = p.get("mode");
+ if (isMode(m)) setModeState(m);
+ const image = p.get("image");
+ if (image?.startsWith("/api/files/")) setRefs([asSlot(image)]);
+ const code = p.get("setup");
+ if (code) {
+ const s = decodeSetup(code);
+ if (s) apply(s);
+ else toast.error("That setup code didn't read — ask for it again");
+ }
+ /* eslint-enable react-hooks/set-state-in-effect */
+ const video = p.get("video");
+ if (video?.startsWith("/api/files/")) source.adopt(video, video.split("/").pop());
+ // Once, on arrival.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const setup: GenjutsuSetup = {
+ mode,
+ engine,
+ ...(maker ? { model: maker.id } : {}),
+ ...(maker?.tier ? { tier: maker.tier } : {}),
+ quality,
+ ...(target ? { target } : {}),
+ ...(mode === "swap" && subject.trim() ? { subject: subject.trim() } : {}),
+ ...(prompt.trim() ? { prompt: prompt.trim() } : {}),
+ ...(effLook ? { look: effLook } : {}),
+ ...(references.length ? { references } : {}),
+ };
+
+ const reset = () => {
+ source.clear();
+ setRange(null);
+ setFrame(null);
+ setFrameError(false);
+ setPoints([]);
+ setPaint(null);
+ };
+
+ const uploaded = !!clip?.url && !clip.uploading && !clip.error && !!duration && !!range;
+ const clicks = points.filter((p) => p.label !== "negative").length;
+ const problem =
+ uploaded && maker
+ ? genjutsuProblem({
+ mode,
+ maker,
+ source: { url: clip.url!, duration, fps: clip.info?.fps, width: size.width, height: size.height, hasAudio: clip.info?.hasAudio },
+ range: { start: range.startTime, end: range.endTime },
+ references: references.length,
+ target,
+ subject,
+ prompt,
+ points: clicks,
+ mask: !!paint,
+ look: effLook,
+ })
+ : null;
+ const body: GenjutsuBody | null =
+ uploaded && maker && !problem && !refs.some((r) => r.uploading) && !custom.some((r) => r.uploading)
+ ? {
+ engine,
+ mode,
+ modelId: maker.id,
+ ...(maker.tier ? { tier: maker.tier } : {}),
+ quality,
+ ...(target ? { target } : {}),
+ ...(mode === "swap" && subject.trim() ? { subject: subject.trim() } : {}),
+ ...(prompt.trim() ? { prompt: prompt.trim() } : {}),
+ ...(target === "click" ? { points } : {}),
+ ...(target === "paint" && paint ? { mask: paint.mask } : {}),
+ ...(needsFrame && frame ? { frame: { width: frame.width, height: frame.height } } : {}),
+ references,
+ ...(effLook ? { look: effLook } : {}),
+ source: { url: clip.url!, name: clip.name, duration, fps: clip.info?.fps, width: size.width, height: size.height, hasAudio: clip.info?.hasAudio },
+ range: { start: range.startTime, end: range.endTime },
+ }
+ : null;
+ const estimate = useGenjutsuEstimate(body);
+ const est = estimate.data && !estimate.isError ? estimate.data : undefined;
+
+ const blocker = !clip
+ ? "Add a clip"
+ : clip.error
+ ? clip.error
+ : clip.uploading
+ ? clip.progress < 1
+ ? `Uploading… ${Math.round(clip.progress * 100)}%`
+ : "Reading the clip…"
+ : !range || !duration
+ ? "Reading the clip…"
+ : "problem" in choice
+ ? choice.problem
+ : problem
+ ? problem
+ : refs.some((r) => r.uploading) || custom.some((r) => r.uploading)
+ ? "Uploading your images…"
+ : estimate.isError
+ ? (estimate.error as Error).message
+ : null;
+
+ const start = (seed?: number) => {
+ if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "genjutsu-blocker" });
+ const b = seed !== undefined ? { ...body, seed } : body;
+ void guard(JSON.stringify(b), (requestId) => runMutation.mutateAsync({ ...b, requestId }))
+ .then((r) => {
+ if (!r) return;
+ const ratio = size.width && size.height ? size.width / size.height : undefined;
+ setRun({ final: r.final.id, ids: r.items.map((g) => g.id), before: clip!.preview, start: range!.startTime, ratio });
+ toast("Genjutsu is on it", { description: "Follow it below — it lands in your Library too." });
+ })
+ .catch((e: Error) => toast.error(e.message));
+ };
+
+ const modeInfo = getMode(mode);
+ const tabs = <ModeTabsRow mode={mode} onMode={setMode} />;
+
+ return (
+ <ToolShell title="Genjutsu" tabs={tabs} header={<SetupCode setup={setup} onPaste={apply} />} wide>
+ {!clip && <ToolHero title={modeInfo.label} subtitle={`${modeInfo.hint} Priced before it runs; free on your own ComfyUI.`} />}
+ <div className={cn("mx-auto", clip ? "pt-4" : "mt-8 max-w-[640px]")}>
+ {!clip ? (
+ <ClipDrop
+ accept={GENJUTSU.accept}
+ limits={LIMITS}
+ onFile={(f) => {
+ const err = source.pick(f);
+ if (err) toast.error(err);
+ else setRange(null);
+ }}
+ onLibrary={(url, name) => {
+ source.adopt(url, name);
+ setRange(null);
+ }}
+ />
+ ) : (
+ <div className="grid grid-cols-1 items-start gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">
+ <div className="min-w-0 space-y-4">
+ <Panel>
+ <div className="space-y-3">
+ <ClipBar clip={clip} onRemove={reset} />
+ <VideoTrimmer
+ ref={trimmer}
+ src={clip.preview}
+ value={range}
+ onChange={setRange}
+ min={GENJUTSU.minSeconds}
+ max={GENJUTSU.maxSeconds}
+ duration={clip.info?.duration}
+ label="Part of the clip to use"
+ hint={duration && duration > GENJUTSU.maxSeconds ? `Pick up to ${GENJUTSU.maxSeconds} s — only that part comes out` : `${GENJUTSU.minSeconds}–${GENJUTSU.maxSeconds} s; the whole clip, or just the part you need`}
+ onMeta={source.setBrowserMeta}
+ />
+ </div>
+ </Panel>
+
+ {needsFrame && (
+ <Panel
+ title="First frame"
+ aside={
+ target === "click" ? (
+ <Segmented
+ label="What a click marks"
+ value={pointLabel}
+ onChange={setPointLabel}
+ className="w-auto"
+ options={[
+ { value: "positive", label: "Swap" },
+ { value: "negative", label: "Keep" },
+ ]}
+ />
+ ) : null
+ }
+ >
+ {frame ? (
+ <FrameStage
+ frame={frame}
+ points={target === "click" ? points : []}
+ onPoints={target === "click" ? setPoints : undefined}
+ pointLabel={pointLabel}
+ overlay={target === "paint" ? paint?.overlay : undefined}
+ clickable={target === "click"}
+ maxPoints={GENJUTSU.maxPoints}
+ />
+ ) : (
+ <div className="grid aspect-video place-items-center rounded-xl bg-muted text-[13px] text-muted-foreground">
+ {frameError ? (
+ <p className="max-w-xs px-4 text-center">This browser can&apos;t show the clip&apos;s frames (an H.265 or ProRes file?). Saying it in words works without them.</p>
+ ) : (
+ <Loader2 className="size-5 animate-spin" aria-label="Reading the first frame" />
+ )}
+ </div>
+ )}
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {target === "paint" ? (
+ <>
+ <Button size="sm" className="rounded-full" variant={paint ? "outline" : "default"} disabled={!frame} onClick={() => setPainting(true)}>
+ <Brush className="size-3.5" /> {paint ? "Touch up the paint" : mode === "insert" ? "Paint the spot" : "Paint over it"}
+ </Button>
+ {paint && (
+ <Button size="sm" variant="ghost" className="rounded-full" onClick={() => setPaint(null)}>
+ <RotateCcw className="size-3.5" /> Clear
+ </Button>
+ )}
+ </>
+ ) : (
+ <Button size="sm" variant="ghost" className="rounded-full" disabled={!points.length} onClick={() => setPoints(points.slice(0, -1))}>
+ <Undo2 className="size-3.5" /> Undo
+ </Button>
+ )}
+ <p className="min-w-0 flex-1 text-[12px] text-muted-foreground">{frameHint(mode, target, points.length, !!paint)}</p>
+ </div>
+ </Panel>
+ )}
+
+ {mode === "restyle" && (
+ <Panel title="Look">
+ <LookPicker
+ look={look}
+ onLook={setLook}
+ source={lookSource}
+ onSource={setLookSource}
+ custom={custom}
+ onCustom={setCustom}
+ words={words}
+ onWords={setWords}
+ higgsfield={higgsfield}
+ />
+ </Panel>
+ )}
+
+ {showRefs && (
+ <Panel title={modeInfo.refs} aside={<span className="text-[12px] text-muted-foreground tabular-nums">{refs.length}/{GENJUTSU.maxReferences}</span>}>
+ <div className="flex flex-wrap gap-2">
+ {refs.map((r) => (
+ <MediaSlot key={r.id} label="Reference" kind="image" value={r} onChange={(v) => setRefs((xs) => (v ? xs.map((x) => (x.id === r.id ? { ...v, id: r.id } : x)) : xs.filter((x) => x.id !== r.id)))} size="lg" />
+ ))}
+ {refs.length < GENJUTSU.maxReferences && (
+ <MediaSlot
+ label={refs.length ? "Add another" : REF_CTA[mode]}
+ kind="image"
+ value={null}
+ onChange={(v) => v && setRefs((xs) => [...xs, { ...v, id: v.id ?? nanoid(8) }])}
+ onFile={(f) => fileToList(f, setRefs, "image")}
+ size="lg"
+ required={mode !== "restyle"}
+ />
+ )}
+ </div>
+ <p className="mt-2 text-[12px] text-muted-foreground">{REF_HINT[mode]}</p>
+ </Panel>
+ )}
+ </div>
+
+ <Panel className="space-y-4 lg:sticky lg:top-[112px]">
+ <p className="text-[13px] text-pretty text-muted-foreground">{modeInfo.hint}</p>
+
+ {MODE_TARGETS[mode].length > 0 && (
+ <Field label={mode === "insert" ? "Where does it go?" : "What gets swapped?"}>
+ <Segmented
+ label={mode === "insert" ? "Where does it go?" : "What gets swapped?"}
+ value={target!}
+ onChange={(t) => setTargets((x) => ({ ...x, [mode]: t }))}
+ options={MODE_TARGETS[mode].map((t) => ({ value: t, label: TARGET_LABELS[mode][t]!.label }))}
+ />
+ </Field>
+ )}
+
+ {mode === "swap" && (
+ <Field label={target === "type" && !maker?.promptOptional ? "What to swap" : "What to swap (optional)"} htmlFor="gj-subject">
+ <Input
+ id="gj-subject"
+ value={subject}
+ onChange={(e) => setSubject(e.target.value)}
+ maxLength={300}
+ placeholder={maker?.people ? "e.g. “the presenter”" : "e.g. “the red car”, “her jacket”"}
+ className="text-[13px]"
+ />
+ </Field>
+ )}
+
+ <Field label={PROMPT_LABEL[mode](target)} htmlFor="gj-prompt">
+ <Textarea
+ id="gj-prompt"
+ value={prompt}
+ onChange={(e) => setPrompts((x) => ({ ...x, [mode]: e.target.value }))}
+ maxLength={GENJUTSU.maxPromptChars}
+ rows={2}
+ disabled={mode === "restyle" && lookSource !== "higgsfield"}
+ placeholder={PROMPT_PLACEHOLDER[mode]}
+ className="resize-none text-[13px]"
+ />
+ </Field>
+
+ {maker && options.length > 1 && (
+ <Field label="Model">
+ <MakerList options={options} value={maker.pair && maker.tier === "high" ? maker.pair : maker.id} higgsfield={higgsfield} onChange={(id) => setPicked((p) => ({ ...p, [choiceKey]: id }))} />
+ </Field>
+ )}
+ {maker && options.length <= 1 && (
+ <p className="text-[12px] text-muted-foreground">
+ <span className="font-medium text-foreground">{maker.label}</span> · {maker.note}
+ {maker.higgsfield && !higgsfield && " · needs a Higgsfield key (runs as a demo without one)"}
+ </p>
+ )}
+
+ {maker?.pair && (
+ <Field label="Quality" hint={tier === "standard" ? "Genjutsu Lite — about a sixth of the price" : "Genjutsu — the full model"}>
+ <Segmented
+ label="Quality"
+ value={maker.tier ?? tier}
+ onChange={setTier}
+ options={[
+ { value: "standard" as const, label: "Standard" },
+ { value: "high" as const, label: "High" },
+ ]}
+ />
+ </Field>
+ )}
+
+ <Field label="Resolution" hint={maker && !maker.qualities ? "Keeps your clip's size" : est?.quality && est.quality !== quality ? `Renders ${est.quality}` : undefined}>
+ <Segmented label="Resolution" value={quality} onChange={setQuality} options={GENJUTSU.qualities.map((q) => ({ value: q, label: q }))} />
+ </Field>
+
+ <div className="space-y-3 border-t pt-3">
+ <div className="flex items-center gap-2">
+ <div className="min-w-0 flex-1" aria-live="polite">
+ {blocker ? (
+ <p className="text-[13px] text-muted-foreground">{blocker}</p>
+ ) : (
+ <>
+ <p className="flex items-center gap-1.5 text-[15px] font-semibold tabular-nums">
+ {costText(est, engine)}
+ {estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" aria-label="Updating the price" />}
+ </p>
+ {est && (
+ <p className="text-[12px] leading-snug text-muted-foreground">
+ {est.modelName} · {est.seconds} s{est.pieces > 1 ? ` in ${est.pieces} ${engine === "open" && mode !== "restyle" ? "windows" : "pieces"}` : ""}
+ </p>
+ )}
+ </>
+ )}
+ </div>
+ <Button className="rounded-full" onClick={() => start()} disabled={!!blocker || runMutation.isPending}>
+ {runMutation.isPending ? <Loader2 className="size-4 animate-spin" /> : <Wand2 className="size-4" />} Generate
+ </Button>
+ </div>
+ {est && est.notes.length > 0 && !blocker && (
+ <ul className="space-y-1 text-[12px] leading-snug text-muted-foreground">
+ {est.notes.map((n) => (
+ <li key={n} className="flex gap-1.5">
+ <Sparkles className="mt-0.5 size-3 shrink-0 text-brand-text" />
+ <span>{n}.</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </Panel>
+ </div>
+ )}
+ </div>
+
+ {run && <RunPanel run={run} onAgain={() => start(Math.floor(Math.random() * 2 ** 31))} />}
+
+ {(history.data?.length ?? 0) > 0 && (
+ <section className="mt-10" aria-labelledby="genjutsu-history">
+ <h3 id="genjutsu-history" className="mb-3 font-heading text-[22px]">
+ Your Genjutsu
+ </h3>
+ <Feed items={history.data!} />
+ </section>
+ )}
+
+ {frame && (
+ <SketchEditor
+ open={painting}
+ onOpenChange={setPainting}
+ image={frame.url}
+ mode="mask"
+ initialStrokes={paint?.strokes}
+ onDone={(r) => r.mask && setPaint({ mask: r.mask, overlay: r.overlay, strokes: r.strokes })}
+ />
+ )}
+ </ToolShell>
+ );
+}
+
+/** Restyle before a look is picked: the kind of look the tab stands for (so the model list matches it). */
+function lookPlaceholder(s: LookSource): GenjutsuLook {
+ return s === "higgsfield" ? { kind: "higgsfield", id: "" } : s === "custom" ? { kind: "custom", images: [] } : { kind: "preset", id: "" };
+}
+
+const REF_CTA: Record<GenjutsuMode, string> = { motion: "Add your character", swap: "Add what goes in", insert: "Add what to add", restyle: "Add a character" };
+
+const REF_HINT: Record<GenjutsuMode, string> = {
+ motion: "A clear, full-body picture of the character who takes over the performance. More angles help Genjutsu; Kling and the open engine use the first.",
+ swap: "The thing, person or outfit that goes in — cut out on a plain background works best. Up to 10.",
+ insert: "The object or character to add — cut out on a plain background works best.",
+ restyle: "Optional: characters who should appear in the look (Genjutsu Restyle takes up to 5).",
+};
+
+const PROMPT_LABEL: Record<GenjutsuMode, (t?: GenjutsuTarget) => string> = {
+ motion: () => "Describe your character (optional)",
+ swap: () => "Describe the result (optional)",
+ insert: (t) => (t === "type" ? "Where it goes" : "What appears there (optional)"),
+ restyle: () => "Anything to keep (optional)",
+};
+
+const PROMPT_PLACEHOLDER: Record<GenjutsuMode, string> = {
+ motion: "e.g. “a knight in silver armour, in a stone hall”",
+ swap: "e.g. “a white horse trotting at the same pace”",
+ insert: "e.g. “on the table, next to the cup”",
+ restyle: "With Higgsfield's looks: e.g. “keep her pink hair”",
+};
+
+function frameHint(mode: GenjutsuMode, target: GenjutsuTarget | undefined, points: number, painted: boolean): string {
+ if (target === "click") return points ? "Add points on the same thing, or mark what stays with Keep." : "Click what to swap. Keyboard: arrows move the crosshair, Enter adds a point.";
+ if (mode === "insert") return painted ? "Red is where it goes. It stays there for the whole shot." : "Paint where it should appear — it stays there for the whole shot, so a still camera works best.";
+ return painted ? "Red is what gets swapped. Touch up the paint, or clear it." : "Paint over what to swap — it only needs to cover it on this frame.";
+}
+
+/** The four modes as tabs under the header (the selected one is in the URL as ?mode=). */
+function ModeTabsRow({ mode, onMode }: { mode: GenjutsuMode; onMode: (m: GenjutsuMode) => void }) {
+ return (
+ <div className="border-b">
+ <div role="tablist" aria-label="Genjutsu modes" onKeyDown={tabKeys} className="scrollbar-none flex gap-1 overflow-x-auto px-3 sm:px-6">
+ {GENJUTSU_MODES.map((m) => {
+ const on = m.id === mode;
+ return (
+ <button
+ key={m.id}
+ type="button"
+ role="tab"
+ aria-selected={on}
+ tabIndex={on ? 0 : -1}
+ onClick={() => onMode(m.id)}
+ className={cn(
+ "relative flex h-10 shrink-0 items-center px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:text-foreground",
+ "after:absolute after:inset-x-2.5 after:bottom-0 after:h-0.5 after:rounded-full after:transition-colors focus-visible:after:bg-ring",
+ on && "text-foreground after:bg-foreground",
+ )}
+ >
+ {m.label}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+/** The models for this mode and engine, one line each (what it's good at, its limits). */
+function MakerList({ options, value, higgsfield, onChange }: { options: Maker[]; value: string; higgsfield: boolean; onChange: (id: string) => void }) {
+ return (
+ <div role="radiogroup" aria-label="Model" onKeyDown={radioKeys} className="space-y-1.5">
+ {options.map((m) => (
+ <button
+ key={m.id}
+ type="button"
+ role="radio"
+ aria-checked={value === m.id}
+ tabIndex={radioTab(value === m.id)}
+ onClick={() => onChange(m.id)}
+ className={cn(
+ "flex w-full min-w-0 items-start gap-2.5 rounded-xl border px-3 py-2 text-left transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
+ value === m.id && "border-primary bg-brand-faint hover:bg-brand-faint-hover",
+ )}
+ >
+ <span className={cn("mt-1 size-3 shrink-0 rounded-full border-2", value === m.id ? "border-primary bg-primary" : "border-border-strong")} />
+ <span className="min-w-0">
+ <span className="block text-[13px] font-medium">{m.label}</span>
+ <span className="block text-[12px] leading-snug text-muted-foreground">
+ {m.note}
+ {m.higgsfield && !higgsfield && " · needs a Higgsfield key (a demo without one)"}
+ </span>
+ </span>
+ </button>
+ ))}
+ </div>
+ );
+}
+
+/** What a run's steps are doing, then the result with a before / after wipe, Download and Run again. */
+function RunPanel({ run, onAgain }: { run: Run; onAgain: () => void }) {
+ const list = useGenerationList(run.ids).data;
+ const byId = useMemo(() => new Map((list ?? []).map((g) => [g.id, g])), [list]);
+ const final = byId.get(run.final);
+ const rows: StepRow[] = run.ids.map((id) => {
+ const g = byId.get(id);
+ return { key: id, label: g?.request.step?.label ?? "A step", g };
+ });
+ const state = chainState(rows.map((r) => ({ g: r.g, label: r.label })).sort((a, b) => (a.g?.id === run.final ? 1 : b.g?.id === run.final ? -1 : 0)));
+ const out = final?.status === "succeeded" ? final.outputs.find((o) => o.kind === "video") : undefined;
+ return (
+ <section className="mt-6" aria-labelledby="gj-run-title">
+ <Panel
+ title={<span id="gj-run-title">{final?.request.title ?? "Your Genjutsu"}</span>}
+ aside={
+ <div className="flex flex-wrap items-center justify-end gap-1.5">
+ {out && final && (
+ <Button asChild size="sm" variant="outline" className="rounded-full">
+ <a href={downloadHref(out.url, downloadName(final, out, 0))}>
+ <Download className="size-3.5" /> Download
+ </a>
+ </Button>
+ )}
+ {(out || state.status === "failed") && (
+ <Button size="sm" variant="outline" className="rounded-full" onClick={onAgain}>
+ <RotateCcw className="size-3.5" /> {state.status === "failed" ? "Try again" : "Run again"}
+ </Button>
+ )}
+ </div>
+ }
+ >
+ {out ? (
+ <VideoCompare before={run.before} after={out.url} start={run.start} ratio={run.ratio} />
+ ) : (
+ <div className="space-y-3">
+ <div className="h-1.5 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(state.progress * 100)} aria-label="Progress">
+ <div className={cn("h-full transition-[width]", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(4, state.progress * 100)}%` }} />
+ </div>
+ <p className={cn("text-[13px]", state.status === "failed" ? "text-destructive" : "text-muted-foreground")} aria-live="polite">
+ {state.status === "failed" ? `${state.label}: ${state.error}` : state.label}
+ </p>
+ {rows.length > 1 && <StepList steps={rows} />}
+ </div>
+ )}
+ </Panel>
+ </section>
+ );
+}
diff --git a/src/components/genjutsu/hooks.ts b/src/components/genjutsu/hooks.ts
new file mode 100644
index 00000000..3932620a
--- /dev/null
+++ b/src/components/genjutsu/hooks.ts
@@ -0,0 +1,84 @@
+"use client";
+
+import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import type { GenjutsuLook, GenjutsuMode, GenjutsuTarget, GenjutsuTier } from "@/lib/catalog/genjutsu";
+import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";
+import { useDebounced } from "@/components/faceless/hooks";
+import { send } from "@/components/shorts/hooks";
+
+/** React Query hooks for /api/genjutsu/** and Higgsfield's live Genjutsu looks. */
+
+export interface GenjutsuBody {
+ engine: Engine;
+ mode: GenjutsuMode;
+ modelId?: string;
+ tier?: GenjutsuTier;
+ quality?: string;
+ target?: GenjutsuTarget;
+ subject?: string;
+ prompt?: string;
+ points?: PixelPoint[];
+ frame?: { width: number; height: number };
+ mask?: string;
+ references?: string[];
+ look?: GenjutsuLook;
+ source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };
+ range?: { start: number; end: number };
+ seed?: number;
+ /** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */
+ requestId?: string;
+}
+
+export interface GenjutsuEstimate {
+ costUsd: number | null;
+ demo: boolean;
+ modelId: string;
+ modelName: string;
+ tier?: GenjutsuTier;
+ quality?: string;
+ pieces: number;
+ seconds: number;
+ steps: number;
+ notes: string[];
+ higgsfield: boolean;
+}
+
+/** The price and shape of a run for the current settings, asked for once typing pauses (300 ms). */
+export function useGenjutsuEstimate(body: GenjutsuBody | null) {
+ const key = useDebounced(body ? JSON.stringify(body) : null, 300);
+ return useQuery({
+ queryKey: ["genjutsu", "estimate", key],
+ queryFn: async () => send<GenjutsuEstimate>("/api/genjutsu/estimate", "POST", JSON.parse(key!)),
+ enabled: !!key,
+ placeholderData: keepPreviousData,
+ retry: false,
+ staleTime: 30_000,
+ });
+}
+
+export function useGenjutsuRun() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (b: GenjutsuBody) => send<{ final: Generation; items: Generation[] }>("/api/genjutsu", "POST", b),
+ onSuccess: (r) => {
+ r.items.forEach((g) => qc.setQueryData(["generation", g.id], g));
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ },
+ });
+}
+
+export interface HiggsfieldLook {
+ id: string;
+ name: string;
+ preview?: string;
+}
+
+/** Higgsfield's own Genjutsu looks (a key is needed; the list comes live from Higgsfield). */
+export function useHiggsfieldLooks(enabled: boolean) {
+ return useQuery({
+ queryKey: ["provider-presets", "genjutsu-restyle"],
+ queryFn: async () => (await (await fetch("/api/providers/higgsfield/presets?source=genjutsu-restyle")).json()) as { items: HiggsfieldLook[]; error?: string },
+ enabled,
+ staleTime: 60 * 60 * 1000,
+ });
+}
diff --git a/src/components/genjutsu/look-picker.tsx b/src/components/genjutsu/look-picker.tsx
new file mode 100644
index 00000000..5fd15b58
--- /dev/null
+++ b/src/components/genjutsu/look-picker.tsx
@@ -0,0 +1,166 @@
+"use client";
+
+import { Check, ImagePlus, Loader2, Search } from "lucide-react";
+import { nanoid } from "nanoid";
+import { useMemo, useState } from "react";
+import { Input } from "@/components/ui/input";
+import { fileToList, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { LookCard } from "@/components/shorts/preset-card";
+import { tabKeys } from "@/components/shorts/ui";
+import { GENJUTSU, type GenjutsuLook } from "@/lib/catalog/genjutsu";
+import { SHORTS_PRESETS, shortsPreview } from "@/lib/catalog/shorts";
+import { cn } from "@/lib/utils";
+import { useHiggsfieldLooks } from "./hooks";
+
+export type LookSource = "fuobe" | "higgsfield" | "custom";
+
+/**
+ * Restyle's look: one of the 44 Shorts looks, one of Higgsfield's own Genjutsu looks (with a key), or your own look
+ * from up to 8 images and a few words.
+ */
+export function LookPicker({
+ look,
+ onLook,
+ source,
+ onSource,
+ custom,
+ onCustom,
+ words,
+ onWords,
+ higgsfield,
+}: {
+ look: GenjutsuLook | null;
+ onLook: (l: GenjutsuLook) => void;
+ source: LookSource;
+ onSource: (s: LookSource) => void;
+ custom: SlotValue[];
+ onCustom: (update: (xs: SlotValue[]) => SlotValue[]) => void;
+ words: string;
+ onWords: (w: string) => void;
+ /** A Higgsfield key is set. */
+ higgsfield: boolean;
+}) {
+ const [q, setQ] = useState("");
+ const tabs: { id: LookSource; label: string }[] = [
+ { id: "fuobe", label: "Looks" },
+ { id: "higgsfield", label: "Higgsfield" },
+ { id: "custom", label: "Your own" },
+ ];
+ const presets = useMemo(() => {
+ const t = q.trim().toLowerCase();
+ return t ? SHORTS_PRESETS.filter((p) => `${p.name} ${p.category} ${p.description}`.toLowerCase().includes(t)) : SHORTS_PRESETS;
+ }, [q]);
+ return (
+ <div className="space-y-3">
+ <div role="tablist" aria-label="Where the look comes from" onKeyDown={tabKeys} className="flex w-full rounded-full bg-muted p-0.5">
+ {tabs.map((t) => (
+ <button
+ key={t.id}
+ type="button"
+ role="tab"
+ id={`look-tab-${t.id}`}
+ aria-selected={source === t.id}
+ aria-controls={`look-panel-${t.id}`}
+ tabIndex={source === t.id ? 0 : -1}
+ onClick={() => onSource(t.id)}
+ className={cn(
+ "flex h-8 min-w-0 flex-1 items-center justify-center rounded-full px-2 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
+ source === t.id && "bg-background text-foreground shadow-soft",
+ )}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
+
+ {source === "fuobe" && (
+ <div role="tabpanel" id="look-panel-fuobe" aria-labelledby="look-tab-fuobe" className="space-y-2">
+ <div className="relative">
+ <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search 44 looks — claymation, comic, watercolour…" aria-label="Search looks" className="h-8 pl-8 text-[13px]" />
+ </div>
+ <div className="grid max-h-[460px] grid-cols-3 gap-1 overflow-y-auto pr-0.5 sm:grid-cols-4 xl:grid-cols-5">
+ {presets.map((p) => (
+ <LookCard
+ key={p.id}
+ id={p.id}
+ name={p.name}
+ description={p.description}
+ preview={shortsPreview(p)}
+ hue={p.hue}
+ selected={look?.kind === "preset" && look.id === p.id}
+ onSelect={(id) => onLook({ kind: "preset", id })}
+ />
+ ))}
+ {!presets.length && <p className="col-span-full py-6 text-center text-[13px] text-muted-foreground">No look matches “{q}”.</p>}
+ </div>
+ </div>
+ )}
+
+ {source === "higgsfield" && (
+ <div role="tabpanel" id="look-panel-higgsfield" aria-labelledby="look-tab-higgsfield">
+ <HiggsfieldLooks enabled={higgsfield} selected={look?.kind === "higgsfield" ? look.id : undefined} onPick={(id, name) => onLook({ kind: "higgsfield", id, name })} />
+ </div>
+ )}
+
+ {source === "custom" && (
+ <div role="tabpanel" id="look-panel-custom" aria-labelledby="look-tab-custom" className="space-y-2.5">
+ <p className="text-[12px] text-muted-foreground">Up to {GENJUTSU.maxLookImages} images of the look you want — stills, paintings, frames from a film. Every frame takes their colours, textures and style.</p>
+ <div className="flex flex-wrap gap-2">
+ {custom.map((v) => (
+ <MediaSlot key={v.id} label="Look image" kind="image" value={v} onChange={(nv) => onCustom((xs) => (nv ? xs.map((x) => (x.id === v.id ? { ...nv, id: v.id } : x)) : xs.filter((x) => x.id !== v.id)))} />
+ ))}
+ {custom.length < GENJUTSU.maxLookImages && (
+ <MediaSlot label={custom.length ? "Add image" : "Add an image"} kind="image" value={null} onChange={(v) => v && onCustom((xs) => [...xs, { ...v, id: v.id ?? nanoid(8) }])} onFile={(f) => fileToList(f, onCustom, "image")} />
+ )}
+ </div>
+ <Input value={words} onChange={(e) => onWords(e.target.value)} maxLength={300} placeholder="In a few words (optional) — e.g. “grainy 70s film, warm and faded”" aria-label="Describe your look" className="h-8 text-[13px]" />
+ </div>
+ )}
+ </div>
+ );
+}
+
+function HiggsfieldLooks({ enabled, selected, onPick }: { enabled: boolean; selected?: string; onPick: (id: string, name: string) => void }) {
+ const list = useHiggsfieldLooks(enabled);
+ if (!enabled) {
+ return (
+ <p className="rounded-xl bg-muted/60 p-3 text-[13px] text-muted-foreground">
+ Higgsfield&apos;s own Genjutsu looks load live with a Higgsfield key (Settings → API keys). The 44 looks and Your own work without one.
+ </p>
+ );
+ }
+ if (list.isLoading) {
+ return (
+ <p className="flex items-center gap-2 py-6 text-[13px] text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" /> Loading Higgsfield&apos;s looks…
+ </p>
+ );
+ }
+ const items = list.data?.items ?? [];
+ if (!items.length) return <p className="py-6 text-[13px] text-muted-foreground">{list.data?.error ?? "Higgsfield returned no looks — try again later, or pick one of the 44 looks."}</p>;
+ return (
+ <div className="grid max-h-[460px] grid-cols-3 gap-1.5 overflow-y-auto sm:grid-cols-4 xl:grid-cols-5">
+ {items.map((p) => (
+ <button
+ key={p.id}
+ type="button"
+ aria-pressed={selected === p.id}
+ onClick={() => onPick(p.id, p.name)}
+ className={cn("flex min-w-0 flex-col gap-1.5 rounded-xl p-1.5 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring", selected === p.id && "bg-brand-faint hover:bg-brand-faint-hover")}
+ >
+ <span className={cn("relative grid aspect-[4/5] w-full place-items-center overflow-hidden rounded-lg bg-muted", selected === p.id && "ring-2 ring-primary")}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {p.preview ? <img src={p.preview} alt="" className="size-full object-cover" loading="lazy" /> : <ImagePlus className="size-5 text-muted-foreground" />}
+ {selected === p.id && (
+ <span className="absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full bg-primary text-primary-foreground">
+ <Check className="size-3.5" />
+ </span>
+ )}
+ </span>
+ <span className="truncate px-0.5 text-[13px] font-medium">{p.name}</span>
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/src/components/genjutsu/setup-code.tsx b/src/components/genjutsu/setup-code.tsx
new file mode 100644
index 00000000..2627330f
--- /dev/null
+++ b/src/components/genjutsu/setup-code.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { ClipboardPaste, Copy } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { copyText } from "@/lib/clipboard";
+import { decodeSetup, encodeSetup, type GenjutsuSetup } from "@/lib/catalog/genjutsu";
+
+/**
+ * Higgsfield's "share a setup by code", done locally: Copy setup puts a link with the settings as a short code
+ * (/genjutsu?setup=gj1.…) on the clipboard; Paste setup reads a code or such a link back. The clip itself isn't in
+ * it; reference images are files of this install.
+ */
+export function SetupCode({ setup, onPaste }: { setup: GenjutsuSetup; onPaste: (s: GenjutsuSetup) => void }) {
+ const [open, setOpen] = useState(false);
+ const [text, setText] = useState("");
+ const copy = async () => {
+ const link = `${window.location.origin}/genjutsu?setup=${encodeSetup(setup)}`;
+ if (await copyText(link)) toast("Setup copied", { description: "A link with this mode, model and references — paste it here, or send it to someone on this Fuobe." });
+ else toast.error("Couldn't copy — your browser blocked the clipboard");
+ };
+ const paste = () => {
+ const s = decodeSetup(text);
+ if (!s) return void toast.error("That isn't a Genjutsu setup code (they start with gj1.)");
+ onPaste(s);
+ setOpen(false);
+ setText("");
+ };
+ return (
+ <div className="flex items-center gap-1">
+ <Button variant="ghost" size="sm" className="rounded-full" onClick={() => void copy()} aria-label="Copy setup">
+ <Copy className="size-3.5" />
+ <span className="hidden sm:inline">Copy setup</span>
+ </Button>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" size="sm" className="rounded-full" aria-label="Paste setup">
+ <ClipboardPaste className="size-3.5" />
+ <span className="hidden sm:inline">Paste setup</span>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-[min(92vw,360px)] space-y-2 p-3">
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ paste();
+ }}
+ className="space-y-2"
+ >
+ <label htmlFor="gj-setup-code" className="block text-[13px] font-medium">
+ Paste a setup code or link
+ </label>
+ <Input id="gj-setup-code" value={text} onChange={(e) => setText(e.target.value)} placeholder="gj1.… or a /genjutsu?setup= link" className="h-8 text-[13px]" autoFocus />
+ <div className="flex justify-end">
+ <Button type="submit" size="sm" className="rounded-full" disabled={!text.trim()}>
+ Use this setup
+ </Button>
+ </div>
+ </form>
+ </PopoverContent>
+ </Popover>
+ </div>
+ );
+}
diff --git a/src/components/remove-object/remove-object-tool.tsx b/src/components/remove-object/remove-object-tool.tsx
index edbb4f67..9cea1874 100644
--- a/src/components/remove-object/remove-object-tool.tsx
+++ b/src/components/remove-object/remove-object-tool.tsx
@@ -1,6 +1,7 @@
"use client";
import { Brush, Cloud, Download, Eraser as EraserIcon, Eye, Loader2, RotateCcw, Sparkles, Type, Undo2 } from "lucide-react";
+import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
@@ -395,6 +396,15 @@ export function RemoveObjectTool({ tabs }: { tabs?: React.ReactNode }) {
</div>
)}
+ {clip?.url && (
+ <p className="text-[12px] text-muted-foreground">
+ Want something in its place?{" "}
+ <Link href={`/genjutsu?mode=swap&video=${encodeURIComponent(clip.url)}`} className="font-medium text-foreground underline-offset-2 hover:underline">
+ Swap it with Genjutsu
+ </Link>
+ </p>
+ )}
+
{mode === "type" && (
<label className="flex items-center gap-3 rounded-xl border px-3 py-2.5">
<span className="min-w-0 flex-1">
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 47ae5bae..4f775c0d 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -23,6 +23,7 @@ import {
Trash2,
UserRoundPlus,
Wand2,
+ WandSparkles,
ZoomIn,
type LucideIcon,
} from "lucide-react";
@@ -69,6 +70,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
reframe: Crop,
lipsync: Mic2,
"add-sound": AudioLines,
+ genjutsu: WandSparkles,
"voice-change": AudioLines,
"copy-text": Copy,
"view-3d": Box,
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index b087f4a6..7907d987 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -15,6 +15,8 @@ export interface StudioConfig {
hero: string;
/** Small line under the hero (e.g. which models an app runs on). */
subtitle?: string;
+ /** A studio that does the job in more depth, linked under the hero (Edit video → Genjutsu). */
+ related?: { href: string; label: string };
placeholder: string;
kind: MediaKind;
/** Operations whose models appear in the picker. */
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index 065976ff..fbf97f9c 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -1,6 +1,7 @@
"use client";
-import { ArrowUp, Loader2, Upload } from "lucide-react";
+import { ArrowRight, ArrowUp, Loader2, Upload } from "lucide-react";
+import Link from "next/link";
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -252,6 +253,12 @@ function StudioBody({ header, tabs }: { header?: React.ReactNode; tabs?: React.R
<div className="flex flex-col items-center pt-[16vh] text-center">
<h2 className="font-heading text-display text-balance">{config.hero}</h2>
{config.subtitle && <p className="mt-2 max-w-xl text-[13px] text-muted-foreground">{config.subtitle}</p>}
+ {config.related && (
+ <Link href={config.related.href} className="mt-3 inline-flex items-center gap-1 rounded-full bg-muted px-3 py-1 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
+ {config.related.label}
+ <ArrowRight className="size-3" />
+ </Link>
+ )}
</div>
)}
</main>
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index 56948458..03e06c00 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -21,6 +21,7 @@ export type OutputActionId =
| "reframe"
| "lipsync"
| "add-sound"
+ | "genjutsu"
| "voice-change"
| "copy-text"
| "view-3d"
@@ -85,6 +86,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
link("reference", "Use as reference", `/image?ref=${q(o.url)}`);
link("grade", "Color grade", `/color-grade?image=${q(o.url)}`);
link("layers", "Open in Layers", layersHref(g, o.url));
+ link("genjutsu", "Animate with Genjutsu", `/genjutsu?mode=motion&image=${q(o.url)}`);
out.push({ id: "save-character", label: "Save as character", placement: "menu" });
break;
case "video":
@@ -95,6 +97,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
link("upscale", "Upscale", `/upscale/video?video=${q(o.url)}`);
link("add-sound", "Add sound", `/audio/video?video=${q(o.url)}`);
link("grade", "Color grade", `/color-grade?video=${q(o.url)}`);
+ link("genjutsu", "Use in Genjutsu", `/genjutsu?video=${q(o.url)}`);
break;
case "audio":
link("lipsync", "Lipsync", `/lipsync?audio=${q(o.url)}`, "primary");
diff --git a/src/lib/studios.ts b/src/lib/studios.ts
index 62076a91..f9669c49 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -266,6 +266,7 @@ export const MOTION_CONTROL_STUDIO: StudioConfig = {
],
defaultModels: { cloud: "kling-motion-control", open: "oss-wan22-animate" },
promptOptional: true,
+ related: { href: "/genjutsu?mode=motion", label: "Clips up to 30 s with several references: Genjutsu motion transfer" },
};
export const VIDEO_EDIT_STUDIO: StudioConfig = {
@@ -279,6 +280,7 @@ export const VIDEO_EDIT_STUDIO: StudioConfig = {
slots: [{ key: "video", label: "Video", accept: "video", required: true }],
multiRef: { label: "Add ref", max: 4 },
defaultModels: { cloud: "kling-o3", open: "oss-wan22-fun-control" },
+ related: { href: "/genjutsu?mode=swap", label: "Swap an object or a person, or restyle every frame, with Genjutsu" },
};
export const EXTEND_STUDIO: StudioConfig = {
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
index 2a233eb4..cfa6d294 100644
--- a/tests/library-pure.test.ts
+++ b/tests/library-pure.test.ts
@@ -49,6 +49,7 @@ describe("outputActions", () => {
"menu:reference",
"menu:grade",
"menu:layers",
+ "menu:genjutsu",
"menu:save-character",
"menu:reuse",
"menu:copy-prompt",
@@ -62,7 +63,7 @@ describe("outputActions", () => {
it("gives videos Extend first and the video hand-offs", () => {
const g = gen({ kind: "video", op: "t2v", outputs: [{ url: "/api/files/o/v.mp4", kind: "video", draftId: "d1" }] });
- expect(ids(g)).toEqual(["primary:extend", "bar:download", "bar:favorite", "menu:reframe", "menu:lipsync", "menu:upscale", "menu:add-sound", "menu:grade", "menu:finalize", "menu:copy-prompt", "menu:delete"]);
+ expect(ids(g)).toEqual(["primary:extend", "bar:download", "bar:favorite", "menu:reframe", "menu:lipsync", "menu:upscale", "menu:add-sound", "menu:grade", "menu:genjutsu", "menu:finalize", "menu:copy-prompt", "menu:delete"]);
});
it("handles audio, text, 3D, layers, favorites and the Trash", () => {