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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Genjutsu: group swap, scene edit, From picture and Finish, each opening after its test
Adarshe27b14542d73
diff --git a/src/app/(studio)/genjutsu/page.tsx b/src/app/(studio)/genjutsu/page.tsxindex b9c9f49d..46358912 100644--- a/src/app/(studio)/genjutsu/page.tsx+++ b/src/app/(studio)/genjutsu/page.tsx@@ -1,9 +1,11 @@import type { Metadata } from "next";import { GenjutsuStudio } from "@/components/genjutsu/genjutsu-studio";import { studioExamples } from "@/lib/studio-examples";+import { genjutsuLive } from "@/server/genjutsu-live";export const metadata: Metadata = { title: "Genjutsu" };export default function Page() {- return <GenjutsuStudio examples={studioExamples("genjutsu")} />;+ // Which Openjutsu modes are open to everyone (two committed files, read as the page is built; the owner sees them all).+ return <GenjutsuStudio examples={studioExamples("genjutsu")} live={genjutsuLive()} />;}diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex cb0f0fbf..b7f9f38d 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -9,6 +9,8 @@ import { getSetting } from "@/server/settings";import { RUNS_ON_COMPUTER_NOTE } from "@/lib/relay";import { OPERATION_LABELS } from "@/lib/catalog/types";import { ANY_ANGLE } from "@/lib/catalog/any-angle";+import { directRunFeatures } from "@/lib/catalog/genjutsu";+import { genjutsuLive } from "@/server/genjutsu-live";import { relightRunTitle } from "@/lib/relight/engine";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { accountInputProblem } from "@/server/account-inputs";@@ -92,6 +94,16 @@ export async function POST(request: Request) {const asked = relightTitle ? { ...sent, title: relightTitle } : sent;// Public sign-up: an account runs on its own ComfyUI or its own fal.ai or Replicate key, never the install's providers.// Without a key of its own it stays on the open engine; with one, the engine it asked for.+ // Genjutsu's new makers open one by one (src/server/genjutsu-live.ts): sent here directly, a maker that hasn't opened+ // runs for the owner only, as on the Genjutsu page.+ if (viewer.kind !== "owner") {+ const extra = asked.params?.extra?.openjutsu;+ const needs = directRunFeatures(asked.modelId, extra && typeof extra === "object" ? (extra as Record<string, unknown>) : {});+ if (needs) {+ const live = genjutsuLive();+ if (needs.some((f) => !live[f])) return refuse(403, OWN_GPU_TOOL_MESSAGE, { code: "own-gpu-tool" });+ }+ }let req = account ? { ...asked, account: account.id, engine: accountEngineMode(account.id) === "open" ? ("open" as const) : asked.engine } : { ...asked, account: undefined };const onOwn = <T,>(fn: () => T): T => (account ? asAccount(account.id, fn) : fn());// A visitor's price check: priced as it would run, as that visitor (an account: its own GPU and keys; a guest: the opendiff --git a/src/app/api/genjutsu/estimate/route.ts b/src/app/api/genjutsu/estimate/route.tsindex b5465048..70625b30 100644--- a/src/app/api/genjutsu/estimate/route.ts+++ b/src/app/api/genjutsu/estimate/route.ts@@ -1,3 +1,4 @@+import { requestViewer } from "@/server/auth";import { estimateGenjutsu, GenjutsuEstimateSchema } from "@/server/genjutsu";import { body, handle } from "@/server/shorts-schemas";import { priceAs } from "@/server/visitor";@@ -6,7 +7,8 @@ import { priceAs } from "@/server/visitor";async function post(request: Request) {return handle(async () => {const input = await body(request, GenjutsuEstimateSchema, "Add a clip and pick a mode");- return Response.json(await estimateGenjutsu(input));+ // A feature that hasn't opened is refused to everyone but the owner (src/server/genjutsu-live.ts).+ return Response.json(await estimateGenjutsu(input, { owner: requestViewer(request).kind === "owner" }));});}diff --git a/src/app/api/genjutsu/route.ts b/src/app/api/genjutsu/route.tsindex df10c6d7..f3708371 100644--- a/src/app/api/genjutsu/route.ts+++ b/src/app/api/genjutsu/route.ts@@ -1,3 +1,4 @@+import { requestViewer } from "@/server/auth";import { createGenjutsu, GenjutsuBodySchema } from "@/server/genjutsu";import { body, handle, once } from "@/server/shorts-schemas";@@ -6,7 +7,7 @@ export async function POST(request: Request) {return handle(async () => {const input = await body(request, GenjutsuBodySchema, "Add a clip, pick a mode and add your references");// A repeated requestId (a second click on Generate) gets the run the first one started.- const { final, items } = await once("genjutsu", input.requestId, () => createGenjutsu(input));+ const { final, items } = await once("genjutsu", input.requestId, () => createGenjutsu(input, { owner: requestViewer(request).kind === "owner" }));return Response.json({ final, items }, { status: 201 });}, request);}diff --git a/src/app/api/genjutsu/scene/route.ts b/src/app/api/genjutsu/scene/route.tsnew file mode 100644index 00000000..fd1cc152--- /dev/null+++ b/src/app/api/genjutsu/scene/route.ts@@ -0,0 +1,11 @@+import { requestViewer } from "@/server/auth";+import { describeScene, SceneSchema } from "@/server/genjutsu";+import { body, handle } from "@/server/shorts-schemas";++/** From picture's "What happens": starts the describer on the part; the page waits for its text (a generation). */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, SceneSchema, "Make and pick the first frame first");+ return Response.json(describeScene(input, { owner: requestViewer(request).kind === "owner" }), { status: 201 });+ }, request);+}diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex 1cdb2b8a..ef03471f 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -4,7 +4,7 @@ import { Brush, Download, Info, Loader2, RotateCcw, Sparkles, Undo2, Wand2 } froimport Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";import { nanoid } from "nanoid";-import { Suspense, useEffect, useMemo, useRef, useState } from "react";+import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -27,13 +27,20 @@ import { openInStudio } from "@/components/swap-studio/hooks";import { SelfHostNote } from "@/components/self-host-note";import { ExampleRow } from "@/components/studio/example-row";import { useEdgeFade } from "@/components/studio/use-edge-fade";-import { useEngine, useGenerations, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useEngine, useGenerations, useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";import { CHARACTER_SWAP, cutsInPart, cutWarning, partWords, seedProblem, type CharacterChoice, type CharacterOptions } from "@/lib/catalog/character-swap";import {chooseMaker,decodeSetup,GENJUTSU,GENJUTSU_MODES,+ modeOpen,+ type FeatureCheck,+ type FinishOptions,+ type GenjutsuFeature,+ type ObjectEdit,+ type PictureOptions,+ type SceneAction,genjutsuProblem,getMode,makerOffered,@@ -61,14 +68,15 @@ import type { StudioExampleRow } from "@/lib/studio-examples";import { cn } from "@/lib/utils";import { refusalShown, toastError } from "@/lib/refusals";import { CharacterControls, CharacterFacts, qualityOff } from "./character-panel";-import { useDescribeCharacter, useGenjutsuEstimate, useGenjutsuRun, useTranscribeClip, waitForGeneration, type GenjutsuBody } from "./hooks";+import { useDescribeCharacter, useDescribeScene, useGenjutsuEstimate, useGenjutsuRun, useTranscribeClip, waitForGeneration, type GenjutsuBody } from "./hooks";+import { FinishFields, FrameCompare, LightPicker, More, OnlyYou, PERSON_COLOURS, PictureSteps, roleForTap, SceneEditFields, WhoBecomesWho } from "./openjutsu-panels";import { LookPicker, type LookSource } from "./look-picker";import { SetupCode } from "./setup-code";import { useClipCuts } from "./use-cuts";/** The upload box's line: the mode's own window (Character swap: 5–15 s of one shot). */-const limits = (character: boolean) =>- `MP4, MOV or WebM · ${character ? `${CHARACTER_SWAP.minSeconds}–${CHARACTER_SWAP.maxSeconds}` : `${GENJUTSU.minSeconds}–${GENJUTSU.maxSeconds}`} s are used · ${GENJUTSU.maxBytes / 1024 / 1024} MB`;+const limits = (mode: GenjutsuMode) =>+ `MP4, MOV or WebM · ${mode === "character" ? `${CHARACTER_SWAP.minSeconds}–${CHARACTER_SWAP.maxSeconds}` : mode === "picture" ? "2–15" : mode === "finish" ? "up to 60" : `${GENJUTSU.minSeconds}–${GENJUTSU.maxSeconds}`} s are used · ${GENJUTSU.maxBytes / 1024 / 1024} MB`;interface Paint {mask: string;@@ -102,8 +110,12 @@ const seedOf = (s: string): number | undefined => (s.trim() === "" ? undefined :* Setups copy and paste as a short code. The plan: src/lib/catalog/genjutsu.ts; the server: src/server/genjutsu.ts.* examples: "See what it makes" (studioExamples("genjutsu"), from the page), under the clip drop until there is a run of one's own.*/-export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {+export function GenjutsuStudio({ examples, live }: { examples?: StudioExampleRow; live?: Partial<Record<GenjutsuFeature, boolean>> }) {const [engine, setEngine, engineMode] = useEngine();+ // The Openjutsu modes open one by one, each after its GPU test (src/server/genjutsu-live.ts); the owner sees them all.+ const owner = useIsOwner();+ const open: FeatureCheck = useCallback((f) => owner || !!live?.[f], [owner, live]);+ const ownerOnly: FeatureCheck = (f) => owner && !live?.[f];// Genjutsu doesn't run on an account's own GPU yet (only the studios' generations do): said here, not after Generate.const visitor = useLikelyVisitor();const access = useModelAccess();@@ -135,12 +147,23 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {const [frame, setFrame] = useState<Frame | null>(null);const [frameError, setFrameError] = useState(false);const [run, setRun] = useState<Run | null>(null);+ // Scene edit, From picture, Finish and Group swap's taps.+ const [action, setAction] = useState<SceneAction>("change");+ const [objectEdit, setObjectEdit] = useState<ObjectEdit>({ action: "change" });+ const [picture, setPicture] = useState<PictureOptions>({ stage: "frame" });+ const [frameTry, setFrameTry] = useState<string | null>(null);+ const [frameUrl, setFrameUrl] = useState<string | null>(null);+ const [scene, setScene] = useState("");+ const [describing, setDescribing] = useState(false);+ const [finish, setFinish] = useState<FinishOptions>({ tool: "colours" });+ const [tapFor, setTapFor] = useState<number | null>(null);const runMutation = useGenjutsuRun();+ const sceneMutation = useDescribeScene();const guard = useSubmitGuard();const history = useGenerations({ features: [GENJUTSU.feature], limit: 24 });// The ways of pointing this engine has a model for (the open graphs: swap by name, insert by paint).- const supported = MODE_TARGETS[mode].filter((t) => makersFor(engine, mode, t).length > 0);+ const supported = MODE_TARGETS[mode].filter((t) => makersFor(engine, mode, t, open).length > 0);const wanted = targets[mode] ?? MODE_TARGETS[mode][0];const target = MODE_TARGETS[mode].length ? (supported.includes(wanted) ? wanted : (supported[0] ?? wanted)) : undefined;const prompt = prompts[mode] ?? "";@@ -149,15 +172,17 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {const lookSource: LookSource = lookChoice;const isCharacter = mode === "character";- const partMax = isCharacter ? (longPart ? CHARACTER_SWAP.maxContinued : CHARACTER_SWAP.maxSeconds) : GENJUTSU.maxSeconds;- const partMin = isCharacter ? CHARACTER_SWAP.minSeconds : GENJUTSU.minSeconds;+ const modeMax = mode === "picture" ? 15 : mode === "finish" ? 60 : null;+ const partMax = isCharacter ? (longPart ? CHARACTER_SWAP.maxContinued : CHARACTER_SWAP.maxSeconds) : (modeMax ?? GENJUTSU.maxSeconds);+ const partMin = isCharacter ? CHARACTER_SWAP.minSeconds : mode === "picture" ? 2 : mode === "finish" ? 1 : GENJUTSU.minSeconds;const setMode = (m: GenjutsuMode) => {setModeState(m);- // Character swap takes a 5–15 s part: a longer selection is cut back to its first 15 s.- if (m === "character" && range && range.endTime - range.startTime > CHARACTER_SWAP.maxSeconds + 0.05) {+ // Character swap takes a 5–15 s part: a longer selection is cut back to its first 15 s (From picture: 15 s too).+ const most = m === "character" || m === "picture" ? CHARACTER_SWAP.maxSeconds : null;+ if (most && range && range.endTime - range.startTime > most + 0.05) {setLongPart(false);- setRange({ ...range, endTime: Math.round((range.startTime + CHARACTER_SWAP.maxSeconds) * 100) / 100 });+ setRange({ ...range, endTime: Math.round((range.startTime + most) * 100) / 100 });}const url = new URL(window.location.href);url.searchParams.set("mode", m);@@ -177,13 +202,31 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {const choiceKey = `${engine}:${mode}:${target ?? ""}:${lookKind}`;// Models switched off in Settings → Models & licences leave the list, and the pick falls back to one that is on.const isOn = (id: string) => offered(access, id, engine);- const choice = chooseMaker({ engine, mode, target, tier, look: effLook ?? (mode === "restyle" ? lookPlaceholder(lookSource) : undefined), modelId: picked[choiceKey], offered: isOn });+ const readyRefs = ready(refs).length;+ const choice = chooseMaker({+ engine,+ mode,+ target,+ tier,+ look: effLook ?? (mode === "restyle" ? lookPlaceholder(lookSource) : undefined),+ modelId: picked[choiceKey],+ offered: isOn,+ open,+ refs: readyRefs,+ action: mode === "swap" ? action : undefined,+ tool: mode === "finish" ? finish.tool : undefined,+ });const maker: Maker | null = "maker" in choice ? choice.maker : null;- const options = keepOffered(makersFor(engine, mode, target), (m) => makerOffered(m, isOn));- const references = mode === "restyle" ? [] : ready(refs);- const showRefs = mode !== "restyle";- const maxRefs = isCharacter ? Math.max(1, maker?.refs.max ?? 1) : GENJUTSU.maxReferences;- const needsFrame = ((mode === "swap" || isCharacter) && target === "click") || ((mode === "swap" || mode === "insert") && target === "paint");+ const options = keepOffered(makersFor(engine, mode, target, open), (m) => makerOffered(m, isOn)).filter((m) => mode !== "finish" || m.tool === finish.tool);+ const group = isCharacter && !!maker?.group;+ const sceneEdit = mode === "swap" && !!maker?.actions;+ const fresh = !!(maker?.group || maker?.actions || maker?.review || maker?.tool);+ const references = mode === "restyle" || (sceneEdit && action === "remove") || (mode === "picture" && picture.ownPerson) || (mode === "finish" && finish.tool === "colours") ? [] : ready(refs);+ const showRefs = mode !== "restyle" && !(sceneEdit && action === "remove") && !(mode === "picture" && picture.ownPerson) && !(mode === "finish" && finish.tool === "colours");+ // Two characters or more move the swap to Group swap on your GPU (once it is open to this viewer).+ const groupOn = isCharacter && engine === "open" && makersFor(engine, "character", target, open).some((m) => m.group);+ const maxRefs = isCharacter ? Math.max(1, maker?.refs.max ?? 1, groupOn ? 4 : 1) : mode === "picture" || mode === "finish" || sceneEdit ? 1 : GENJUTSU.maxReferences;+ const needsFrame = ((mode === "swap" || isCharacter) && target === "click") || ((mode === "swap" || mode === "insert") && target === "paint") || group || mode === "picture";// Character swap: the clip's hard cuts (found in the browser), for the "one continuous shot" warning.const cuts = useClipCuts(clip?.preview, isCharacter && !!clip && !clip.error);const partCuts = isCharacter && range ? cutsInPart(cuts ?? undefined, { start: range.startTime, end: range.endTime }) : [];@@ -289,6 +332,17 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {}}+ const pictureKey = mode === "picture" ? JSON.stringify([previewSrc, startAt, range?.endTime, references, picture.light, picture.ownPerson, picture.keepCrop]) : "";+ const [pictureAt, setPictureAt] = useState(pictureKey);+ if (pictureKey !== pictureAt) {+ setPictureAt(pictureKey);+ if (frameUrl && pictureAt) {+ setFrameUrl(null);+ setScene("");+ }+ }+ const pictureStage: "frame" | "video" = frameUrl ? "video" : "frame";+const apply = (s: GenjutsuSetup) => {// Through setMode: the URL's ?mode= follows (a reload keeps the pasted mode).setMode(s.mode);@@ -314,6 +368,12 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {}const kind = s.mode === "restyle" ? (s.look?.kind === "custom" ? "custom" : s.look?.kind === "soul" ? "soul" : "fuobe") : "";if (s.model) setPicked((x) => ({ ...x, [`${e}:${s.mode}:${t ?? ""}:${kind}`]: s.model! }));+ if (s.object) {+ setAction(s.object.action);+ setObjectEdit(s.object);+ }+ if (s.picture) setPicture({ ...s.picture, stage: "frame" });+ if (s.finish) setFinish(s.finish);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." });};@@ -334,12 +394,19 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {return v !== null && v !== was ? v : null;};const m = fresh("mode");- if (isMode(m)) setModeState(m);+ if (isMode(m) && modeOpen(m, open)) setModeState(m);+ const tool = fresh("tool");+ if ((tool === "faces" && open("finish-faces")) || (tool === "colours" && open("finish-colours"))) setFinish({ tool });+ const fr = fresh("frame");+ if (fr?.startsWith("/api/files/") && open("picture")) {+ setFrameUrl(fr);+ setPicture((p) => ({ ...p, stage: "video" }));+ }const image = fresh("image");if (image?.startsWith("/api/files/")) setRefs([asSlot(image)]);const code = fresh("setup");if (code) {- const s = decodeSetup(code);+ const s = decodeSetup(code, open);if (s) apply(s);else toast.error("That setup code didn't read — ask for it again");}@@ -361,6 +428,22 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {// eslint-disable-next-line react-hooks/exhaustive-deps}, [params]);+ // The owner is known after the first render (after hydration): a link to a mode or tool only the owner has opens it then.+ const [ownerLinked, setOwnerLinked] = useState(false);+ if (owner && !ownerLinked) {+ setOwnerLinked(true);+ const p = new URLSearchParams(window.location.search);+ const m = p.get("mode");+ if (isMode(m) && (m === "picture" || m === "finish")) setModeState(m);+ const tool = p.get("tool");+ if (tool === "faces" || tool === "colours") setFinish({ tool });+ const fr = p.get("frame");+ if (fr?.startsWith("/api/files/")) {+ setFrameUrl(fr);+ setPicture((x) => ({ ...x, stage: "video" }));+ }+ }+const setup: GenjutsuSetup = {mode,engine,@@ -373,6 +456,9 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {...(effLook ? { look: effLook } : {}),...(references.length ? { references } : {}),...(isCharacter && Object.keys(character).length ? { character } : {}),+ ...(sceneEdit ? { object: { ...objectEdit, action } } : {}),+ ...(mode === "picture" ? { picture: { ...(picture.light ? { light: picture.light } : {}), ...(picture.ownPerson ? { ownPerson: true } : {}), ...(picture.keepCrop ? { keepCrop: true } : {}), ...(picture.adjust ? { adjust: picture.adjust } : {}) } } : {}),+ ...(mode === "finish" ? { finish } : {}),};function clearMarks() {@@ -411,6 +497,9 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {mask: !!paint,look: effLook,...(isCharacter ? { seed: seedNumber, character } : {}),+ ...(sceneEdit ? { object: { ...objectEdit, action } } : {}),+ ...(mode === "picture" ? { picture: { ...picture, stage: pictureStage, ...(frameUrl ? { frame: frameUrl } : {}) } } : {}),+ ...(mode === "finish" ? { finish } : {}),}): null;const body: GenjutsuBody | null =@@ -432,6 +521,10 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {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 },...(isCharacter ? { character, ...(seedNumber !== undefined ? { seed: seedNumber } : {}), ...(cuts?.length ? { cuts } : {}) } : {}),+ ...(fresh && !isCharacter && seedNumber !== undefined ? { seed: seedNumber } : {}),+ ...(sceneEdit ? { object: { ...objectEdit, action } } : {}),+ ...(mode === "picture" ? { picture: { ...picture, stage: pictureStage, ...(frameUrl ? { frame: frameUrl } : {}), ...(scene.trim() ? { scene: scene.trim() } : {}) } } : {}),+ ...(mode === "finish" ? { finish } : {}),}: null;const estimate = useGenjutsuEstimate(body);@@ -458,10 +551,16 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {: null;/** Generate (the form as it is), or Run again (`again`: that run's own request, with a new seed). */- const start = (again?: Run) => {+ const start = (again?: Run, newSeed = false) => {if (!again && (blocker || !body)) return void toast(blocker ?? "Not ready yet", { id: "genjutsu-blocker" });const base = again?.body ?? body!;- const b = again ? { ...base, seed: Math.floor(Math.random() * 2 ** 31) } : base;+ const b = again || newSeed ? { ...base, seed: Math.floor(Math.random() * 2 ** 31) } : base;+ if (!again && base.mode === "picture" && base.picture?.stage === "frame") {+ void guard(JSON.stringify(b), (requestId) => runMutation.mutateAsync({ ...b, requestId }))+ .then((r) => r && setFrameTry(r.final.id))+ .catch((e: Error) => !refusalShown(e) && toast.error(friendly(e.message)));+ return;+ }const ratio = again ? again.ratio : size.width && size.height ? size.width / size.height : undefined;const before = again?.before ?? clip!.url!;const at = again?.start ?? range!.startTime;@@ -474,8 +573,48 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {.catch((e: Error) => !refusalShown(e) && toast.error(friendly(e.message)));};+ const pickFrame = async (url: string) => {+ setFrameUrl(url);+ setPicture((p) => ({ ...p, stage: "video" }));+ const u = new URL(window.location.href);+ u.searchParams.set("frame", url);+ window.history.replaceState(null, "", u);+ if (!clip?.url || !range) return;+ setDescribing(true);+ try {+ const { id } = await sceneMutation.mutateAsync({ engine: "open", source: { url: clip.url, ...(duration ? { duration } : {}) }, range: { start: range.startTime, end: range.endTime }, ...(picture.ownPerson ? { ownPerson: true } : { frame: url }) });+ const g = await waitForGeneration(id);+ const text = g.outputs.find((o) => o.kind === "text")?.text?.trim();+ if (text) setScene(text.slice(0, 2000));+ } catch (e) {+ if (!refusalShown(e as Error)) toast(friendly((e as Error).message), { description: "Write what happens in your own words, or leave it empty." });+ } finally {+ setDescribing(false);+ }+ };+ // From picture: another first frame (a new seed), from step 1 again even after one was picked.+ const retryFrame = () => {+ if (!body?.picture) return void toast(blocker ?? "Not ready yet", { id: "genjutsu-blocker" });+ setFrameUrl(null);+ setScene("");+ const { light, ownPerson, keepCrop, adjust } = body.picture;+ const b: GenjutsuBody = { ...body, picture: { stage: "frame", light, ownPerson, keepCrop, adjust }, seed: Math.floor(Math.random() * 2 ** 31) };+ void guard(JSON.stringify(b), (requestId) => runMutation.mutateAsync({ ...b, requestId }))+ .then((r) => r && setFrameTry(r.final.id))+ .catch((e: Error) => !refusalShown(e) && toast.error(friendly(e.message)));+ };+ // A tap on the part's first frame places a character's pin and writes the words when the field is empty.+ const placePin = (x: number, y: number) => {+ if (tapFor === null) return;+ const people = refs.map((_, k) => character.people?.[k] ?? { role: "" });+ const pin = { x: Math.round(x * 1000) / 1000, y: Math.round(y * 1000) / 1000 };+ people[tapFor] = { role: roleForTap(people[tapFor]?.role, pin), pin };+ setCharacter({ ...character, people });+ setTapFor(null);+ };+const modeInfo = getMode(mode);- const tabs = <ModeTabsRow mode={mode} onMode={setMode} />;+ const tabs = <ModeTabsRow modes={GENJUTSU_MODES.filter((m) => modeOpen(m.id, open))} mode={mode} onMode={setMode} onlyYou={(m) => owner && !modeOpen(m, (f) => !!live?.[f])} />;return (<ToolShell title="Genjutsu" tabs={tabs} header={<SetupCode setup={setup} onPaste={apply} />} wide selfHostedOnly>@@ -493,7 +632,7 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {{!clip ? (<ClipDropaccept={GENJUTSU.accept}- limits={limits(mode === "character")}+ limits={limits(mode)}disabled={visitor}onFile={(f) => {const err = source.pick(f);@@ -516,8 +655,8 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {src={clip.preview}value={range}onChange={setRange}- min={partMin}- max={partMax}+ min={maker?.part ? Math.min(partMin, maker.part.min) : partMin}+ max={maker?.part ? (isCharacter ? maker.part.max : Math.min(partMax, maker.part.max)) : partMax}duration={clip.info?.duration}label={isCharacter ? "The part to swap" : "Part of the clip to use"}hint={@@ -547,7 +686,18 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {</div></Panel>- {needsFrame && (+ {group && (+ <Panel title="First frame" aside={tapFor !== null ? <span className="text-[12px] text-muted-foreground">Tap character {tapFor + 1}'s person</span> : undefined}>+ {frame ? (+ <PinStage frame={frame.url} pins={(character.people ?? []).map((p) => p.pin)} active={tapFor} onTap={placePin} />+ ) : (+ <div className="grid aspect-video place-items-center rounded-xl bg-muted text-[13px] text-muted-foreground">{frameError ? "This browser can't show the clip's frames — say where each person stands in words." : <Loader2 className="size-5 animate-spin" aria-label="Reading the first frame" />}</div>+ )}+ <p className="mt-2 text-[12px] text-muted-foreground">Press “Tap them” next to a character, then tap the person they replace.</p>+ </Panel>+ )}++ {needsFrame && !group && mode !== "picture" && (<Paneltitle="First frame"aside={@@ -609,6 +759,12 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {</Panel>)}+ {mode === "picture" && (frameTry || frameUrl) && (+ <Panel title={frameUrl ? "Your first frame" : "Check the first frame"}>+ <FrameReview id={frameTry} approved={frameUrl} clipFrame={frame?.url} onAgain={retryFrame} onUse={(u) => void pickFrame(u)} />+ </Panel>+ )}+{mode === "restyle" && (<Panel title="Look"><LookPicker look={look} onLook={setLook} source={lookSource} onSource={setLookSource} custom={custom} onCustom={setCustom} words={words} onWords={setWords} />@@ -616,9 +772,12 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {)}{showRefs && (- <Panel title={modeInfo.refs} aside={<span className="text-[12px] text-muted-foreground tabular-nums">{refs.length}/{maxRefs}</span>}>- <div className="flex flex-wrap gap-2">- {refs.map((r) => (+ <Panel+ title={sceneEdit ? (action === "background" ? "The new place (optional)" : "What goes in (optional)") : modeInfo.refs}+ aside={<span className="text-[12px] text-muted-foreground tabular-nums">{refs.length}/{maxRefs}</span>}+ >+ <div className={cn("flex flex-wrap gap-2", isCharacter && maxRefs > 1 && "grid grid-cols-2 sm:flex")}>+ {refs.slice(0, maxRefs).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 < maxRefs && (@@ -634,7 +793,7 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {)}</div><p className="mt-2 text-[12px] text-muted-foreground">- {REF_HINT[mode]}+ {group ? "Up to four characters, each taking over one person in the clip — same moves, same scene, same sound." : REF_HINT[mode]}{maker && maker.refs.max > 0 && maker.refs.max < maxRefs && ` ${maker.label} uses ${maker.refs.max === 1 ? "the first one" : `up to ${maker.refs.max}`}.`}</p></Panel>@@ -642,9 +801,67 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {</div><Panel className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+112px)]">+ {mode === "picture" && <PictureSteps stage={pictureStage} />}<p className="text-[13px] text-pretty text-muted-foreground">{modeInfo.hint}</p>- {MODE_TARGETS[mode].length > 0 && (+ {mode === "finish" && <FinishFields value={finish} onChange={setFinish} open={open} ownerOnly={ownerOnly} seed={seed} onSeed={setSeed} />}++ {mode === "picture" && pictureStage === "frame" && (+ <>+ <LightPicker value={picture} onChange={setPicture} open={open} ownerOnlyLight={ownerOnly("picture-light")} ownerOnlyOwn={ownerOnly("picture-own-person")} />+ <Field label="Adjust (optional)" htmlFor="gj-adjust">+ <Input id="gj-adjust" value={picture.adjust ?? ""} onChange={(e) => setPicture({ ...picture, adjust: e.target.value.slice(0, 300) || undefined })} maxLength={300} placeholder="e.g. “arms crossed, chin up”" className="h-11 text-[13px]" />+ </Field>+ </>+ )}+ {mode === "picture" && pictureStage === "video" && (+ <>+ <Field label="What happens" htmlFor="gj-scene" hint={describing ? "Writing…" : undefined}>+ <Textarea+ id="gj-scene"+ value={scene}+ onChange={(e) => setScene(e.target.value.slice(0, 2000))}+ maxLength={2000}+ rows={5}+ disabled={describing}+ placeholder="What the person does, moment by moment"+ className={cn("resize-none text-[13px]", describing && "animate-pulse")}+ />+ </Field>+ <More>+ <Field label="Motion detail">+ <Segmented+ label="Motion detail"+ value={String(picture.motionDetail ?? 0)}+ onChange={(v) => setPicture({ ...picture, motionDetail: (Number(v) || undefined) as PictureOptions["motionDetail"] })}+ options={[+ { value: "0", label: "Match the video" },+ { value: "512", label: "512" },+ { value: "768", label: "768" },+ ]}+ />+ </Field>+ {owner && (+ <Field label="Renderer" hint={<OnlyYou />}>+ <Segmented+ label="Renderer"+ value={picture.renderer ?? "solar"}+ onChange={(renderer) => setPicture({ ...picture, renderer: renderer === "solar" ? undefined : renderer })}+ options={[+ { value: "solar", label: "Standard" },+ { value: "h3", label: "H3" },+ ]}+ />+ </Field>+ )}+ <Field label="Seed" htmlFor="gj-pic-seed" hint="Blank: a new one each time">+ <Input id="gj-pic-seed" inputMode="numeric" value={seed} onChange={(e) => setSeed(e.target.value.replace(/[^0-9]/g, "").slice(0, 10))} className="h-11 text-[13px]" />+ </Field>+ </More>+ </>+ )}++ {MODE_TARGETS[mode].length > 0 && !group && (<Field label={TARGET_QUESTION[mode]}><Segmentedlabel={TARGET_QUESTION[mode]}@@ -657,11 +874,43 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {title: supported.includes(t) ? TARGET_LABELS[mode][t]!.hint : engine === "open" ? "On the cloud engine" : "On your GPU (the open engine)",}))}/>- {supported.length < MODE_TARGETS[mode].length && <p className="text-[12px] text-muted-foreground">{engine === "open" ? OPEN_TARGET_PROBLEM[mode] : CLICK_ON_GPU}.</p>}+ {supported.length < MODE_TARGETS[mode].length && (+ <p className="text-[12px] text-muted-foreground">{engine === "open" ? (mode === "swap" && supported.includes("paint") ? "Clicking is on the cloud engine" : OPEN_TARGET_PROBLEM[mode]) : CLICK_ON_GPU}.</p>+ )}</Field>)}- {mode === "swap" && (+ {sceneEdit && (+ <SceneEditFields+ value={objectEdit}+ onChange={setObjectEdit}+ action={action}+ onAction={(a) => {+ setAction(a);+ setObjectEdit((o) => ({ ...o, action: a }));+ }}+ open={open}+ ownerOnly={ownerOnly}+ painted={!!paint}+ target={target}+ seed={seed}+ onSeed={setSeed}+ />+ )}++ {group && (+ <WhoBecomesWho+ refs={refs.filter((r) => !r.uploading)}+ value={character}+ onChange={setCharacter}+ onTap={frame ? (i) => setTapFor(i) : null}+ oneByOne={{ show: refs.length === 2 && open("group-swap-one-by-one"), ownerOnly: ownerOnly("group-swap-one-by-one") }}+ seed={seed}+ onSeed={setSeed}+ />+ )}++ {mode === "swap" && !sceneEdit && (<Field label={target === "type" && !maker?.promptOptional ? "What to swap" : "What to swap (optional)"} htmlFor="gj-subject"><Inputid="gj-subject"@@ -674,7 +923,7 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {</Field>)}- {isCharacter && (+ {isCharacter && !group && (<CharacterControlsengine={engine}maker={maker}@@ -691,8 +940,8 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {/>)}- {/* The looks are words of their own: Restyle takes no prompt. */}- {mode !== "restyle" && (+ {/* The looks are words of their own: Restyle takes no prompt (nor do the Openjutsu modes: they have fields of their own). */}+ {mode !== "restyle" && !fresh && (<Field label={PROMPT_LABEL[mode](target)} htmlFor="gj-prompt"><Textareaid="gj-prompt"@@ -708,7 +957,16 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {{maker && options.length > 1 && (<Field label="Model">- <MakerList options={options} value={maker.pair && maker.tier === "high" ? maker.pair : maker.id} onChange={(id) => setPicked((p) => ({ ...p, [choiceKey]: id }))} />+ <MakerList+ options={options}+ value={maker.pair && maker.tier === "high" ? maker.pair : maker.id}+ onChange={(id) => {+ setPicked((p) => ({ ...p, [choiceKey]: id }));+ // Another model than Scene edit: back to swapping (Remove it and New background are Scene edit's).+ if (mode === "swap" && !options.find((m) => m.id === id)?.actions) setAction("change");+ }}+ onlyYou={(m) => !!m.features && !m.features.some((f) => !!live?.[f]) && owner}+ /></Field>)}{maker && options.length <= 1 && (@@ -731,7 +989,7 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {</Field>)}- {(!isCharacter || !maker?.h3) && (+ {(!isCharacter || !maker?.h3) && mode !== "finish" && !(mode === "picture" && pictureStage === "frame") && (<Field label="Resolution" hint={maker ? upFirst(resolutionWords(maker, quality)) : undefined}>{/* What renders is what shows as picked: a model that stops at 480p shows 480p, not the 720p asked for. */}<Segmented@@ -762,8 +1020,8 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {</>)}</div>- <Button className="rounded-full" onClick={() => start()} disabled={!!blocker || runMutation.isPending || visitor}>- {runMutation.isPending ? <Loader2 className="size-4 animate-spin" /> : <Wand2 className="size-4" />} Generate+ <Button className="rounded-full" onClick={() => start()} disabled={!!blocker || runMutation.isPending || visitor || describing}>+ {runMutation.isPending ? <Loader2 className="size-4 animate-spin" /> : <Wand2 className="size-4" />} {mode === "picture" ? (pictureStage === "frame" ? "Make the first frame" : "Make the video") : "Generate"}</Button></div>{visitor && <SelfHostNote>Genjutsu isn't available here.</SelfHostNote>}@@ -777,7 +1035,7 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {))}</ul>)}- {isCharacter && <CharacterFacts+ {isCharacter && !group && <CharacterFactsengine={engine}maker={maker}cut={cut}@@ -793,7 +1051,20 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {{examples && !clip && !run && (visitor || (history.isSuccess && !history.data.length)) && <ExampleRow row={examples} className="mt-12" />}- {run && <RunPanel run={run} onAgain={() => start(run)} />}+ {run && (+ <RunPanel+ run={run}+ onAgain={() => start(run)}+ finish={[...(open("finish-faces") ? (["faces"] as const) : []), ...(open("finish-colours") ? (["colours"] as const) : [])]}+ onFinish={(tool, url) => {+ const q = new URLSearchParams({ mode: "finish", tool, video: url });+ const photo = run.body.references?.length === 1 && run.body.mode !== "finish" ? run.body.references[0] : null;+ if (tool === "faces" && photo) q.set("image", photo);+ setRun(null);+ router.push(`/genjutsu?${q}`);+ }}+ />+ )}{(history.data?.length ?? 0) > 0 && (<section className="mt-10" aria-labelledby="genjutsu-history">@@ -852,9 +1123,17 @@ function lookPlaceholder(s: LookSource): GenjutsuLook {const CLICK_ON_GPU = "Clicking runs on your GPU (SAM 3.1 marks them) — on the cloud, pick who in words";-const TARGET_QUESTION: Record<GenjutsuMode, string> = { motion: "", restyle: "", character: "Who gets swapped?", swap: "What gets swapped?", insert: "Where does it go?" };+const TARGET_QUESTION: Record<GenjutsuMode, string> = { motion: "", restyle: "", character: "Who gets swapped?", swap: "What gets swapped?", insert: "Where does it go?", picture: "", finish: "" };-const REF_CTA: Record<GenjutsuMode, string> = { motion: "Add your character", character: "Add your character", swap: "Add what goes in", insert: "Add what to add", restyle: "Add a character" };+const REF_CTA: Record<GenjutsuMode, string> = {+ motion: "Add your character",+ character: "Add your character",+ swap: "Add what goes in",+ insert: "Add what to add",+ restyle: "Add a character",+ picture: "Add your character",+ finish: "Add the character photo",+};const REF_HINT: Record<GenjutsuMode, string> = {motion: "A clear, full-body picture of the character who takes over the performance. More angles help Genjutsu.",@@ -862,6 +1141,8 @@ const REF_HINT: Record<GenjutsuMode, string> = {swap: "The thing, person or outfit that goes in — cut out on a plain background works best.",insert: "The object or character to add — cut out on a plain background works best.",restyle: "Optional: characters who should appear in the look.",+ picture: "One picture gives both the look and the setting. Full body, in the place you want them.",+ finish: "The face to match: a clear, front-facing photo of your character.",};const PROMPT_LABEL: Record<GenjutsuMode, (t?: GenjutsuTarget) => string> = {@@ -870,6 +1151,8 @@ const PROMPT_LABEL: Record<GenjutsuMode, (t?: GenjutsuTarget) => string> = {swap: () => "Describe the result (optional)",insert: (t) => (t === "type" ? "Where it goes" : "What appears there (optional)"),restyle: () => "Anything to keep (optional)",+ picture: () => "Adjust (optional)",+ finish: () => "",};const PROMPT_PLACEHOLDER: Record<GenjutsuMode, string> = {@@ -878,6 +1161,8 @@ const PROMPT_PLACEHOLDER: Record<GenjutsuMode, string> = {swap: "e.g. “a white horse trotting at the same pace”",insert: "e.g. “on the table, next to the cup”",restyle: "e.g. “keep her pink hair the same in every shot”",+ picture: "e.g. “arms crossed, chin up”",+ finish: "",};function frameHint(mode: GenjutsuMode, target: GenjutsuTarget | undefined, points: number, painted: boolean): string {@@ -887,8 +1172,8 @@ function frameHint(mode: GenjutsuMode, target: GenjutsuTarget | undefined, pointreturn 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 }) {+/** The modes as tabs under the header (the selected one is in the URL as ?mode=); only the ones open to this viewer. */+function ModeTabsRow({ modes, mode, onMode, onlyYou }: { modes: typeof GENJUTSU_MODES; mode: GenjutsuMode; onMode: (m: GenjutsuMode) => void; onlyYou: (m: GenjutsuMode) => boolean }) {const [row, fade] = useEdgeFade<HTMLDivElement>();// The selected tab stays in view on a phone, where the row scrolls (only the row: the page stays put).useEffect(() => {@@ -899,7 +1184,7 @@ function ModeTabsRow({ mode, onMode }: { mode: GenjutsuMode; onMode: (m: Genjutsreturn (<div className="border-b"><div ref={row} style={fade} 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) => {+ {modes.map((m) => {const on = m.id === mode;return (<button@@ -910,12 +1195,13 @@ function ModeTabsRow({ mode, onMode }: { mode: GenjutsuMode; onMode: (m: GenjutstabIndex={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",+ "relative flex h-11 shrink-0 items-center gap-1.5 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}+ {onlyYou(m.id) && <OnlyYou />}</button>);})}@@ -939,7 +1225,7 @@ function SourceBadge({ source }: { source: Maker["source"] }) {}/** The models for this mode and engine, one line each (where it comes from, what it's good at, its limits). */-function MakerList({ options, value, onChange }: { options: Maker[]; value: string; onChange: (id: string) => void }) {+function MakerList({ options, value, onChange, onlyYou }: { options: Maker[]; value: string; onChange: (id: string) => void; onlyYou?: (m: Maker) => boolean }) {// A guest or an account: open weights run on a self-hosted Fuobe only, not on their own GPU yet.const visitor = useLikelyVisitor();return (@@ -961,6 +1247,7 @@ function MakerList({ options, value, onChange }: { options: Maker[]; value: stri<span className="min-w-0"><span className="flex flex-wrap items-center gap-1.5 text-[13px] font-medium">{m.label} <SourceBadge source={m.source} />+ {onlyYou?.(m) && <OnlyYou />}</span><span className="block text-[12px] leading-snug text-muted-foreground">{visitor ? withoutOwnGpu(m.note) : m.note}</span></span>@@ -971,7 +1258,7 @@ function MakerList({ options, value, onChange }: { options: Maker[]; value: stri}/** 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 }) {+function RunPanel({ run, onAgain, finish = [], onFinish }: { run: Run; onAgain: () => void; finish?: ("faces" | "colours")[]; onFinish?: (tool: "faces" | "colours", url: string) => 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);@@ -996,6 +1283,13 @@ function RunPanel({ run, onAgain }: { run: Run; onAgain: () => void }) {</a></Button>)}+ {out &&+ onFinish &&+ finish.map((tool) => (+ <Button key={tool} size="sm" variant="outline" className="h-11 rounded-full sm:h-8" onClick={() => onFinish(tool, out.url)}>+ <Sparkles className="size-3.5" /> {tool === "faces" ? "Fix faces" : "Fix colours"}+ </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"}@@ -1027,3 +1321,45 @@ function RunPanel({ run, onAgain }: { run: Run; onAgain: () => void }) {</section>);}++/** Group swap's taps: the part's first frame with each character's numbered pin; a tap places the active one. */+function PinStage({ frame, pins, active, onTap }: { frame: string; pins: ({ x: number; y: number } | undefined)[]; active: number | null; onTap: (x: number, y: number) => void }) {+ return (+ <div+ role="button"+ tabIndex={active === null ? -1 : 0}+ aria-label={active === null ? "The part's first frame" : `Tap the person character ${active + 1} replaces`}+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ onTap((e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") onTap(0.5, 0.5);+ }}+ className={cn("relative overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring", active !== null && "cursor-crosshair ring-2 ring-primary")}+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={frame} alt="" className="block w-full" draggable={false} />+ {pins.map((p, i) =>+ p ? (+ <span+ key={i}+ className="absolute grid size-7 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border-2 border-white text-[12px] font-semibold text-white shadow"+ style={{ left: `${p.x * 100}%`, top: `${p.y * 100}%`, background: PERSON_COLOURS[i] }}+ >+ {i + 1}+ </span>+ ) : null,+ )}+ </div>+ );+}++/** From picture's first frame: the try being made (or the approved one) next to the clip's, with Try again / Use this frame. */+function FrameReview({ id, approved, clipFrame, onAgain, onUse }: { id: string | null; approved: string | null; clipFrame?: string; onAgain: () => void; onUse: (url: string) => void }) {+ const list = useGenerationList(id ? [id] : []).data;+ const g = id ? list?.find((x) => x.id === id) : undefined;+ const made = approved ?? (g?.status === "succeeded" ? g.outputs.find((o) => o.kind === "image")?.url : undefined);+ const failed = g?.status === "failed" ? friendly(g.error ?? "It didn't finish") : undefined;+ return <FrameCompare clip={clipFrame} made={made} busy={!approved && !!id && !made && !failed} error={failed} onAgain={onAgain} onUse={() => made && onUse(made)} />;+}diff --git a/src/components/genjutsu/hooks.ts b/src/components/genjutsu/hooks.tsindex 384c4fad..ac441e76 100644--- a/src/components/genjutsu/hooks.ts+++ b/src/components/genjutsu/hooks.ts@@ -2,7 +2,7 @@import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import type { CharacterOptions } from "@/lib/catalog/character-swap";-import type { GenjutsuLook, GenjutsuMode, GenjutsuTarget, GenjutsuTier, MakerSource } from "@/lib/catalog/genjutsu";+import type { FinishOptions, GenjutsuLook, GenjutsuMode, GenjutsuTarget, GenjutsuTier, MakerSource, ObjectEdit, PictureOptions } 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";@@ -30,6 +30,10 @@ export interface GenjutsuBody {character?: CharacterOptions;/** Hard cuts the browser found in the clip (seconds): the server warns when the part has one. */cuts?: number[];+ /** Object swap on Scene edit, From picture, Finish. */+ object?: ObjectEdit;+ picture?: PictureOptions;+ finish?: FinishOptions;/** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */requestId?: string;}@@ -82,6 +86,14 @@ export function useDescribeCharacter() {return useMutation({ mutationFn: (b: { engine: Engine; image: string }) => send<{ description: string }>("/api/genjutsu/describe", "POST", b) });}+/** From picture's "What happens": the describer starts on the part (the page waits for its text). */+export function useDescribeScene() {+ return useMutation({+ mutationFn: (b: { engine: "open"; source: { url: string; duration?: number }; range: { start: number; end: number }; frame?: string; ownPerson?: boolean }) =>+ send<{ id: string; modelId: string }>("/api/genjutsu/scene", "POST", b),+ });+}+/** The clip's words (one transcription; the page takes the part's lines from its cues). */export function useTranscribeClip() {return useMutation({ mutationFn: (b: { engine: Engine; source: { url: string; duration?: number } }) => send<{ id: string; modelId: string }>("/api/genjutsu/transcribe", "POST", b) });diff --git a/src/components/genjutsu/openjutsu-panels.tsx b/src/components/genjutsu/openjutsu-panels.tsxnew file mode 100644index 00000000..837c4487--- /dev/null+++ b/src/components/genjutsu/openjutsu-panels.tsx@@ -0,0 +1,517 @@+"use client";++import { Check, ChevronDown, MapPin, X } from "lucide-react";+import { useState } from "react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { Field, Segmented } from "@/components/shorts/ui";+import type { SlotValue } from "@/components/studio/media-slot";+import { roleFromPin, type CharacterOptions } from "@/lib/catalog/character-swap";+import { OPENJUTSU_LIMITS, SCENE_ACTIONS, type FeatureCheck, type FinishOptions, type ObjectEdit, type PictureOptions, type SceneAction } from "@/lib/catalog/genjutsu";+import { LIGHT_LOOKS, type LookId } from "@/lib/openjutsu-graphs";+import { cn } from "@/lib/utils";++/**+ * Genjutsu's Openjutsu panels (Group swap's Who becomes who, Scene edit, From picture's light and steps, Finish): phone+ * first (44 px taps, wraps, no sideways scroll). What hasn't opened yet shows to the owner only, with an "Only you" badge.+ */++/** The owner's mark on a tab, an action or a card nobody else sees yet. */+export function OnlyYou({ className }: { className?: string }) {+ return <span className={cn("inline-flex h-4 shrink-0 items-center rounded-[4px] bg-muted px-1 align-[1px] text-[10px] font-medium text-muted-foreground", className)}>Only you</span>;+}++/** Each character's colour: the number badge and the pin on the frame. */+export const PERSON_COLOURS = ["#e11d48", "#2563eb", "#16a34a", "#d97706"] as const;++/** A part of the panel that opens on a tap (More). */+export function More({ children, label = "More" }: { children: React.ReactNode; label?: string }) {+ const [open, setOpen] = useState(false);+ return (+ <div className="rounded-xl border">+ <button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="flex min-h-11 w-full items-center justify-between px-3 text-[13px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {label}+ <ChevronDown className={cn("size-4 transition-transform", open && "rotate-180")} />+ </button>+ {open && <div className="space-y-3 border-t px-3 py-3">{children}</div>}+ </div>+ );+}++function SwitchRow({ label, hint, checked, onChange }: { label: string; hint?: string; checked: boolean; onChange: (on: boolean) => void }) {+ return (+ <label className="flex min-h-11 items-center gap-3 text-[13px]">+ <Switch checked={checked} onCheckedChange={onChange} aria-label={label} />+ <span className="min-w-0">+ <span className="block font-medium">{label}</span>+ {hint && <span className="block text-[12px] text-muted-foreground">{hint}</span>}+ </span>+ </label>+ );+}++const EDGES = [+ { value: "tight" as const, label: "Tight" },+ { value: "normal" as const, label: "Normal" },+ { value: "loose" as const, label: "Loose" },+];++// ---------------------------------------------------------------------------+// Group swap: Who becomes who++export function WhoBecomesWho({+ refs,+ value,+ onChange,+ onTap,+ oneByOne,+ seed,+ onSeed,+}: {+ refs: SlotValue[];+ value: CharacterOptions;+ onChange: (c: CharacterOptions) => void;+ /** Opens the part's first frame for this character's tap (null while the frame can't be shown). */+ onTap: ((i: number) => void) | null;+ /** The Render choice shows (exactly 2 characters, and it is open to this viewer). */+ oneByOne: { show: boolean; ownerOnly: boolean };+ seed: string;+ onSeed: (s: string) => void;+}) {+ const people = value.people ?? [];+ const setRole = (i: number, role: string) => {+ const next = refs.map((_, k) => people[k] ?? { role: "" });+ next[i] = { ...next[i], role: role.slice(0, OPENJUTSU_LIMITS.roleChars) };+ onChange({ ...value, people: next });+ };+ return (+ <div className="space-y-3">+ <Field label="Who becomes who">+ <ol className="space-y-2">+ {refs.map((r, i) => (+ <li key={r.id} className="flex items-center gap-2">+ <span className="relative size-12 shrink-0 overflow-hidden rounded-lg bg-muted">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {r.preview && <img src={r.preview} alt="" className="size-full object-cover" />}+ <span className="absolute top-0.5 left-0.5 grid size-5 place-items-center rounded-full text-[11px] font-semibold text-white" style={{ background: PERSON_COLOURS[i] }}>+ {i + 1}+ </span>+ </span>+ <Input+ aria-label={`Character ${i + 1} replaces`}+ value={people[i]?.role ?? ""}+ onChange={(e) => setRole(i, e.target.value)}+ maxLength={OPENJUTSU_LIMITS.roleChars}+ placeholder="Replaces…"+ className="h-11 min-w-0 flex-1 text-[13px]"+ />+ <Button type="button" variant="outline" className="h-11 shrink-0 rounded-full px-3" disabled={!onTap} onClick={() => onTap?.(i)}>+ <MapPin className="size-3.5" /> Tap them+ </Button>+ </li>+ ))}+ </ol>+ <p className="text-[12px] text-muted-foreground">Say where they stand or what they do. Clothes and hair words can carry over.</p>+ </Field>+ {oneByOne.show && (+ <Field label="Render" hint={oneByOne.ownerOnly ? <OnlyYou /> : undefined}>+ <Segmented+ label="Render"+ value={value.onePerPerson ? "one" : "both"}+ onChange={(v) => onChange({ ...value, onePerPerson: v === "one" || undefined })}+ options={[+ { value: "both", label: "Both at once" },+ { value: "one", label: "One by one" },+ ]}+ />+ <p className="text-[12px] text-muted-foreground">One by one draws each person on their own pass. Sharper, about twice as long.</p>+ </Field>+ )}+ <More>+ <SwitchRow label="Hats and big hair" hint="A little slower" checked={!!value.hats} onChange={(on) => onChange({ ...value, hats: on || undefined })} />+ <SwitchRow+ label="Mouths follow the sound"+ hint="Off for music clips where nobody sings"+ checked={value.mouthsFollowSound !== false}+ onChange={(on) => onChange({ ...value, mouthsFollowSound: on ? undefined : false })}+ />+ <Field label="Edge">+ <Segmented label="Edge" value={value.edge ?? "normal"} onChange={(edge) => onChange({ ...value, edge: edge === "normal" ? undefined : edge })} options={EDGES} />+ </Field>+ <Field label="Motion detail">+ <Segmented+ label="Motion detail"+ value={value.motionDetail === 768 ? "high" : "standard"}+ onChange={(v) => onChange({ ...value, motionDetail: v === "high" ? 768 : undefined })}+ options={[+ { value: "standard", label: "Standard" },+ { value: "high", label: "High" },+ ]}+ />+ </Field>+ <SeedField seed={seed} onSeed={onSeed} />+ </More>+ </div>+ );+}++function SeedField({ seed, onSeed }: { seed: string; onSeed: (s: string) => void }) {+ return (+ <Field label="Seed" htmlFor="oj-seed" hint="Blank: a new one each time">+ <Input id="oj-seed" inputMode="numeric" value={seed} onChange={(e) => onSeed(e.target.value.replace(/[^0-9]/g, "").slice(0, 10))} className="h-11 text-[13px]" />+ </Field>+ );+}++/** The words a tap writes, when the field is empty (the person can then edit them). */+export function roleForTap(current: string | undefined, pin: { x: number; y: number }): string {+ return current?.trim() ? current : roleFromPin(pin);+}++// ---------------------------------------------------------------------------+// Scene edit++export function SceneEditFields({+ value,+ onChange,+ action,+ onAction,+ open,+ ownerOnly,+ painted,+ target,+ seed,+ onSeed,+ removeLink,+}: {+ value: ObjectEdit;+ onChange: (o: ObjectEdit) => void;+ action: SceneAction;+ onAction: (a: SceneAction) => void;+ open: FeatureCheck;+ /** Not open to everyone yet: the owner sees it with a badge. */+ ownerOnly: FeatureCheck;+ painted: boolean;+ target: "type" | "paint" | "click" | undefined;+ seed: string;+ onSeed: (s: string) => void;+ /** "For a quick clean-up, Video tools → Remove object." (shown when that tool is the better one). */+ removeLink?: boolean;+}) {+ const actions = SCENE_ACTIONS.filter((a) => open(a.feature));+ const info = SCENE_ACTIONS.find((a) => a.id === action)!;+ const set = (o: Partial<ObjectEdit>) => onChange({ ...value, ...o, action });+ return (+ <div className="space-y-3">+ {actions.length > 1 && (+ <Field label="Action" hint={ownerOnly(info.feature) ? <OnlyYou /> : undefined}>+ <Segmented label="Action" value={action} onChange={onAction} options={actions.map((a) => ({ value: a.id, label: a.label }))} />+ </Field>+ )}+ <p className="text-[12px] text-muted-foreground">{info.hint}</p>+ {(action !== "change" || target !== "paint") && (+ <Field label={action === "remove" ? "What goes" : action === "background" ? "What stays" : "What changes"} htmlFor="oj-target">+ <Input+ id="oj-target"+ value={value.target ?? ""}+ onChange={(e) => set({ target: e.target.value.slice(0, 120) })}+ maxLength={120}+ placeholder={action === "remove" ? "e.g. “the handbag”" : action === "background" ? "the people" : "e.g. “her coat”"}+ className="h-11 text-[13px]"+ />+ </Field>+ )}+ {action === "change" && target === "paint" && !painted && <p className="text-[12px] text-muted-foreground">Paint over what changes on the first frame.</p>}+ <Field label={action === "remove" ? "What shows there (optional)" : action === "background" ? "The new place" : "What it becomes"} htmlFor="oj-becomes">+ <Textarea+ id="oj-becomes"+ value={value.becomes ?? ""}+ onChange={(e) => set({ becomes: e.target.value.slice(0, 300) })}+ maxLength={300}+ rows={2}+ placeholder={action === "remove" ? "e.g. “the boulevard continues”" : action === "background" ? "e.g. “an Amalfi cliff terrace at golden hour”" : "e.g. “a crimson velvet tailored blazer”"}+ className="resize-none text-[13px]"+ />+ </Field>+ {action === "remove" && removeLink && <p className="text-[12px] text-muted-foreground">For a quick clean-up, Video tools → Remove object.</p>}+ {action === "change" && (+ <>+ <SwitchRow label="Only the biggest one" checked={!!value.biggestOnly} onChange={(on) => set({ biggestOnly: on || undefined })} />+ <SwitchRow label="Keep its shape" hint="The new one follows the old outline" checked={!!value.keepShape} onChange={(on) => set({ keepShape: on || undefined })} />+ </>+ )}+ <More>+ <Field label="Edge">+ <Segmented label="Edge" value={value.edge ?? "normal"} onChange={(edge) => set({ edge: edge === "normal" ? undefined : edge })} options={EDGES} />+ </Field>+ <Field label="Motion detail">+ <Segmented+ label="Motion detail"+ value={value.motionDetail === 768 ? "high" : "standard"}+ onChange={(v) => set({ motionDetail: v === "high" ? 768 : undefined })}+ options={[+ { value: "standard", label: "Standard" },+ { value: "high", label: "High" },+ ]}+ />+ </Field>+ <SeedField seed={seed} onSeed={onSeed} />+ </More>+ </div>+ );+}++// ---------------------------------------------------------------------------+// From picture++/** Each look's swatch until its preview picture is made (two colours of its light). */+const LOOK_SWATCH: Record<LookId, [string, string]> = {+ "cold-spotlight": ["#cbd5e1", "#0f172a"],+ "golden-halo": ["#fbbf24", "#7c2d12"],+ "red-and-blue": ["#dc2626", "#1d4ed8"],+ "magenta-club": ["#db2777", "#3b0764"],+ "teal-lasers": ["#22d3ee", "#0c1e3e"],+ "acid-green": ["#84cc16", "#052e16"],+ "lime-and-violet": ["#d9f99d", "#5b21b6"],+ "cyan-glow": ["#a5f3fc", "#020617"],+ "crimson-room": ["#991b1b", "#1c0606"],+ "venetian-blinds": ["#fcd34d", "#111827"],+ "phone-glow": ["#bfdbfe", "#000000"],+ firelight: ["#f97316", "#190a02"],+ "sunset-window": ["#fb923c", "#3f1d0b"],+ "evening-lamp": ["#fdba74", "#292524"],+ "rim-light": ["#f8fafc", "#0a0a0a"],+ "blue-night": ["#818cf8", "#0b1026"],+ "camera-flash": ["#ffffff", "#262626"],+};++export function PictureSteps({ stage }: { stage: "frame" | "video" }) {+ return (+ <ol className="flex items-center gap-2 text-[13px]" aria-label="Steps">+ <li className={cn(stage === "frame" ? "font-semibold text-foreground" : "text-muted-foreground")} aria-current={stage === "frame" ? "step" : undefined}>+ 1 First frame+ </li>+ <li aria-hidden className="text-muted-foreground">+ ·+ </li>+ <li className={cn(stage === "video" ? "font-semibold text-foreground" : "text-muted-foreground")} aria-current={stage === "video" ? "step" : undefined}>+ 2 Video+ </li>+ </ol>+ );+}++export function LightPicker({+ value,+ onChange,+ open,+ ownerOnlyLight,+ ownerOnlyOwn,+}: {+ value: PictureOptions;+ onChange: (p: PictureOptions) => void;+ open: FeatureCheck;+ ownerOnlyLight: boolean;+ ownerOnlyOwn: boolean;+}) {+ const light = value.light;+ const pick = (l: PictureOptions["light"]) => onChange({ ...value, light: l });+ const words = light && "words" in light;+ const card = (key: string, label: string, on: boolean, onClick: () => void, swatch?: [string, string]) => (+ <button+ key={key}+ type="button"+ role="radio"+ aria-checked={on}+ onClick={onClick}+ className={cn("group flex min-w-0 flex-col items-stretch gap-1 rounded-xl p-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring", on && "bg-brand-faint")}+ >+ <span+ className={cn("relative grid aspect-square w-full place-items-center overflow-hidden rounded-lg border", on && "border-primary")}+ style={swatch ? { background: `radial-gradient(circle at 35% 30%, ${swatch[0]} 0%, ${swatch[1]} 75%)` } : undefined}+ >+ {on && <Check className="size-4 text-white drop-shadow" />}+ </span>+ <span className="truncate px-0.5 text-[12px] leading-tight">{label}</span>+ </button>+ );+ return (+ <div className="space-y-3">+ {open("picture-light") && (+ <Field label="Light" hint={ownerOnlyLight ? <OnlyYou /> : undefined}>+ <div role="radiogroup" aria-label="Light" className="grid grid-cols-3 gap-1.5 sm:grid-cols-4">+ {!value.ownPerson && card("none", "As in your picture", !light, () => pick(undefined))}+ {LIGHT_LOOKS.map((l) => card(l.id, l.name, !!light && "look" in light && light.look === l.id, () => pick({ look: l.id }), LOOK_SWATCH[l.id]))}+ {card("words", "Your own words", !!words, () => pick({ words: words ? (light as { words: string }).words : "" }))}+ </div>+ {light && "look" in light && <p className="text-[12px] text-muted-foreground">{LIGHT_LOOKS.find((l) => l.id === light.look)?.hint}.</p>}+ {words && (+ <Textarea+ aria-label="The light, in your words"+ value={(light as { words: string }).words}+ onChange={(e) => pick({ words: e.target.value.slice(0, OPENJUTSU_LIMITS.lightChars) })}+ maxLength={OPENJUTSU_LIMITS.lightChars}+ rows={2}+ placeholder="e.g. “soft pearl light from a high window, warm shadows”"+ className="resize-none text-[13px]"+ />+ )}+ <p className="text-[12px] text-muted-foreground">Pose and light are set in one pass, so the picture stays clean.</p>+ </Field>+ )}+ {open("picture-own-person") && (+ <div>+ <SwitchRow+ label="Keep the clip's own person"+ hint="Relights the person already in the clip instead of bringing in a character."+ checked={!!value.ownPerson}+ onChange={(on) => onChange({ ...value, ownPerson: on || undefined, ...(on ? {} : { keepCrop: undefined }) })}+ />+ {ownerOnlyOwn && <OnlyYou className="ml-14" />}+ {value.ownPerson && <SwitchRow label="Keep the frame's crop" checked={!!value.keepCrop} onChange={(on) => onChange({ ...value, keepCrop: on || undefined })} />}+ </div>+ )}+ </div>+ );+}++/** The made first frame next to the clip's: a 2-up toggle on phones, side by side on wider screens. */+export function FrameCompare({ clip, made, busy, error, onAgain, onUse }: { clip?: string; made?: string; busy: boolean; error?: string; onAgain: () => void; onUse: () => void }) {+ const [show, setShow] = useState<"clip" | "made">("made");+ return (+ <div className="space-y-3">+ <div className="sm:hidden">+ <Segmented+ label="Compare"+ value={show}+ onChange={setShow}+ options={[+ { value: "clip", label: "The clip" },+ { value: "made", label: "Yours" },+ ]}+ />+ </div>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ <figure className={cn("min-w-0", show === "made" && "hidden sm:block")}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {clip ? <img src={clip} alt="The clip's first frame" className="w-full rounded-xl bg-muted object-contain" /> : <div className="aspect-video rounded-xl bg-muted" />}+ <figcaption className="mt-1 text-[12px] text-muted-foreground">The pose</figcaption>+ </figure>+ <figure className={cn("min-w-0", show === "clip" && "hidden sm:block")}>+ {made ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={made} alt="Your first frame" className="w-full rounded-xl bg-muted object-contain" />+ ) : (+ <div className="grid aspect-video place-items-center rounded-xl bg-muted text-[13px] text-muted-foreground" aria-live="polite">+ {error ? error : busy ? "Making your first frame…" : null}+ </div>+ )}+ <figcaption className="mt-1 text-[12px] text-muted-foreground">Yours</figcaption>+ </figure>+ </div>+ <div className="flex flex-wrap gap-2">+ <Button type="button" variant="outline" className="h-11 rounded-full" disabled={busy} onClick={onAgain}>+ <X className="size-4" /> Try again+ </Button>+ <Button type="button" className="h-11 rounded-full" disabled={busy || !made} onClick={onUse}>+ <Check className="size-4" /> Use this frame+ </Button>+ </div>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Finish++export function FinishFields({+ value,+ onChange,+ open,+ ownerOnly,+ seed,+ onSeed,+}: {+ value: FinishOptions;+ onChange: (f: FinishOptions) => void;+ open: FeatureCheck;+ ownerOnly: FeatureCheck;+ seed: string;+ onSeed: (s: string) => void;+}) {+ const tools = ([+ { value: "faces" as const, label: "Fix faces", feature: "finish-faces" as const },+ { value: "colours" as const, label: "Fix colours", feature: "finish-colours" as const },+ ]).filter((t) => open(t.feature));+ const set = (f: Partial<FinishOptions>) => onChange({ ...value, ...f });+ return (+ <div className="space-y-3">+ {tools.length > 1 && (+ <Field label="Tool" hint={ownerOnly(value.tool === "faces" ? "finish-faces" : "finish-colours") ? <OnlyYou /> : undefined}>+ <Segmented label="Tool" value={value.tool} onChange={(tool) => onChange({ tool })} options={tools.map(({ value: v, label }) => ({ value: v, label }))} />+ </Field>+ )}+ {value.tool === "faces" ? (+ <>+ <p className="text-[12px] text-muted-foreground">Redraws small or soft faces so they match your character's photo.</p>+ <Field label="Style">+ <Segmented+ label="Style"+ value={value.faceStyle ?? "mouth"}+ onChange={(faceStyle) => set({ faceStyle })}+ options={[+ { value: "photo", label: "Match the photo" },+ { value: "mouth", label: "Follow the mouth" },+ ]}+ />+ </Field>+ <More>+ <Field label="Section length">+ <Segmented+ label="Section length"+ value={String(value.chunkSeconds ?? 6.5)}+ onChange={(v) => set({ chunkSeconds: Number(v) as 4 | 6.5 | 10 })}+ options={[+ { value: "4", label: "4 s" },+ { value: "6.5", label: "6.5 s" },+ { value: "10", label: "10 s" },+ ]}+ />+ </Field>+ <SeedField seed={seed} onSeed={onSeed} />+ </More>+ </>+ ) : (+ <>+ <p className="text-[12px] text-muted-foreground">A soft film finish: gentler contrast, smoother detail, rich blacks.</p>+ <Field label="Finish">+ <Segmented+ label="Finish"+ value={value.finish ?? "soft"}+ onChange={(finish) => set({ finish })}+ options={[+ { value: "soft", label: "Soft film" },+ { value: "filmic", label: "Filmic" },+ { value: "rich", label: "Rich" },+ { value: "off", label: "Off" },+ ]}+ />+ </Field>+ <Slider label="Strength" value={value.strength ?? 0.4} onChange={(strength) => set({ strength })} />+ <Slider label="Soften detail" value={value.soften ?? 0.33} onChange={(soften) => set({ soften })} />+ </>+ )}+ </div>+ );+}++function Slider({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) {+ const id = `oj-${label.toLowerCase().replace(/\s+/g, "-")}`;+ return (+ <Field label={label} htmlFor={id} hint={`${Math.round(value * 100)}%`}>+ <input id={id} type="range" min={0} max={1} step={0.01} value={value} onChange={(e) => onChange(Number(e.target.value))} className="h-11 w-full accent-primary" />+ </Field>+ );+}diff --git a/src/components/studio/hub-chrome.tsx b/src/components/studio/hub-chrome.tsxindex bbb3b19a..6a2c3b5d 100644--- a/src/components/studio/hub-chrome.tsx+++ b/src/components/studio/hub-chrome.tsx@@ -155,7 +155,7 @@ function HubTabs({onClick={(e) => isPlainClick(e) && tap(m.id)}aria-current={on ? "page" : undefined}className={cn(- "relative flex h-10 shrink-0 items-center rounded-md px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",+ "relative flex h-11 shrink-0 items-center rounded-md px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset","after:absolute after:inset-x-2.5 after:bottom-0 after:h-0.5 after:rounded-full focus-visible:after:bg-ring",on && "text-foreground after:bg-foreground",)}diff --git a/src/lib/av/video-finish.ts b/src/lib/av/video-finish.tsindex 9e229d49..86cb8a89 100644--- a/src/lib/av/video-finish.ts+++ b/src/lib/av/video-finish.ts@@ -93,13 +93,15 @@ export function wholeClipBytes(clip: ClipFacts, copies: number): number | undefi}/**- * An open tool that decodes the whole clip (FPS Boost, SDR to HDR, EXR export): its name and the frame-sized+ * An open tool that decodes the whole clip (FPS Boost, SDR to HDR, EXR export, Fix faces): its name and the frame-sized* copies of the clip it holds at its peak (`multiplier` = FPS Boost's m). Null for tools that work in passes.*/export function wholeClipTool(op: Operation | undefined, format: VideoFormat | undefined, multiplier = 1): { what: string; copies: number; op: Operation } | null {if (op === "interpolate") return { what: "FPS Boost on the open engine", copies: multiplier >= 2 ? 2 + multiplier : 2, op };if (op === "sdr-to-hdr") return { what: "SDR to HDR on the open engine", copies: 2, op };if (op === "export-video" && format === "exr") return { what: "EXR export on the open engine", copies: 2, op };+ // Fix faces decodes the whole clip and pastes the redrawn faces back at full size.+ if (op === "face-fix-video") return { what: "Fix faces", copies: 2, op };return null;}diff --git a/src/lib/catalog/character-swap.ts b/src/lib/catalog/character-swap.tsindex 9a78f59f..61f5fc53 100644--- a/src/lib/catalog/character-swap.ts+++ b/src/lib/catalog/character-swap.ts@@ -161,6 +161,28 @@ export interface CharacterOptions {historyFrames?: number;/** 1080p / 2K / 4K on your GPU: the regenerate's start noise (sharpen.ts; for evaluations, the page leaves it). */sharpenSigma?: number;+ /**+ * Group swap (2–4 characters): who each character replaces, in words (index = the character), and where they were+ * tapped on the part's first frame (0–1 of its width and height; only an aid for writing the words).+ */+ people?: { role: string; pin?: { x: number; y: number } }[];+ /** Group swap with exactly 2 characters: a pass for each person (sharper, about twice as long). */+ onePerPerson?: boolean;+ /** Group swap: hats and big hair are masked too (a little slower). */+ hats?: boolean;+ /** Group swap: mouths follow the sound (on by default; off for music clips where nobody sings). */+ mouthsFollowSound?: boolean;+ /** Group swap: how far the redrawn area reaches past each person. */+ edge?: "tight" | "normal" | "loose";+ /** Group swap: the motion reference's long edge (512 standard, 768 high). */+ motionDetail?: 512 | 768;+}++/** Who becomes who: the words a tap on the part's first frame writes (where the person stands). */+export function roleFromPin(pin: { x: number; y: number }): string {+ const side = pin.x < 1 / 3 ? "on the left" : pin.x > 2 / 3 ? "on the right" : "in the centre";+ const depth = pin.y > 2 / 3 ? " in front" : pin.y < 1 / 3 ? " at the back" : "";+ return `the person ${side}${depth}`;}// ---------------------------------------------------------------------------diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.tsindex cf63946f..bd6dd969 100644--- a/src/lib/catalog/genjutsu.ts+++ b/src/lib/catalog/genjutsu.ts@@ -61,11 +61,12 @@ import {import { firstFramePrompt, getShortsPreset, lookFromPreset, planShorts, segmentPrompt, SHORTS_TOOLS, type PlanStep, type ShortsLook } from "./shorts";import { getModel } from "./index";import { REPLACED_BY } from "./replaced";+import { LOOK_IDS, lightWords, type LookId, type PaintKeyframe } from "../openjutsu-graphs";import { soulLook } from "./soul";import { filmSize, SHARPEN_COPY, sharpenPrompt, sharpenSteps, sharpenTierFor, type SharpenTier } from "./sharpen";import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";-export type GenjutsuMode = "motion" | "character" | "swap" | "restyle" | "insert";+export type GenjutsuMode = "motion" | "character" | "swap" | "restyle" | "insert" | "picture" | "finish";/** How you say what changes (Object swap and Insert) or who (Character swap): words, clicks on the first frame, or paint on it. */export type GenjutsuTarget = RemoveMode;/** Genjutsu's qualities; 2K and 4K are the Character swap's finishing sizes (sharpen.ts). */@@ -103,16 +104,25 @@ export const GENJUTSU_MODES: { id: GenjutsuMode; label: string; hint: string; re{ id: "swap", label: "Object swap", hint: "Swap a thing, a person or an outfit in the clip for your reference — everything else stays.", refs: "What goes in" },{ id: "restyle", label: "Restyle", hint: "Pick a look or bring your own images. Every frame takes the look — motion, camera, and framing stay as filmed.", refs: "Characters (optional)" },{ id: "insert", label: "Insert", hint: "Add your reference to the shot — say where, or paint the spot on the first frame.", refs: "What to add" },+ {+ id: "picture",+ label: "From picture",+ hint: "Your character, in your picture's own setting, moves exactly like the person in the clip. You check the first frame before the video is made.",+ refs: "Your character",+ },+ { id: "finish", label: "Finish", hint: "Give a finished video sharper faces or a soft film finish.", refs: "Character photo" },];export const getMode = (id: GenjutsuMode) => GENJUTSU_MODES.find((m) => m.id === id)!;/** The ways of saying what changes, per mode (Motion transfer and Restyle change the whole shot; Character swap says who). */-export const MODE_TARGETS: Record<GenjutsuMode, GenjutsuTarget[]> = { motion: [], restyle: [], character: ["type", "click"], swap: ["type", "click", "paint"], insert: ["type", "paint"] };+export const MODE_TARGETS: Record<GenjutsuMode, GenjutsuTarget[]> = { motion: [], restyle: [], character: ["type", "click"], swap: ["type", "click", "paint"], insert: ["type", "paint"], picture: [], finish: [] };export const TARGET_LABELS: Record<GenjutsuMode, Partial<Record<GenjutsuTarget, { label: string; hint: string }>>> = {motion: {},restyle: {},+ picture: {},+ finish: {},character: {type: { label: "Pick who", hint: "The largest, leftmost or rightmost person, or a number" },click: { label: "Click them", hint: "Click the person on the part's first frame" },@@ -128,6 +138,156 @@ export const TARGET_LABELS: Record<GenjutsuMode, Partial<Record<GenjutsuTarget,},};+// ---------------------------------------------------------------------------+// The Openjutsu modes: what opens to everyone on its own (each after its GPU test), and their settings++/**+ * One thing that opens to everyone on its own, once every workflow it needs has been accepted by ComfyUI and its GPU test+ * passed (src/server/genjutsu-live.ts). Until then only the owner sees and runs it.+ */+export type GenjutsuFeature =+ | "group-swap"+ | "group-swap-one-by-one"+ | "object-change"+ | "object-remove"+ | "object-background"+ | "picture"+ | "picture-light"+ | "picture-own-person"+ | "picture-h3-renderer"+ | "finish-faces"+ | "finish-colours";++export const GENJUTSU_FEATURES: Record<GenjutsuFeature, { mode: GenjutsuMode; workflows: string[]; maker: string }> = {+ "group-swap": { mode: "character", workflows: ["video-group-swap-h3"], maker: "oss-h3-group-swap" },+ "group-swap-one-by-one": { mode: "character", workflows: ["video-group-swap-h3-one-by-one"], maker: "oss-h3-group-swap" },+ "object-change": { mode: "swap", workflows: ["video-scene-edit-h3"], maker: "oss-h3-scene-edit" },+ "object-remove": { mode: "swap", workflows: ["video-scene-edit-h3"], maker: "oss-h3-scene-edit" },+ "object-background": { mode: "swap", workflows: ["video-scene-edit-h3"], maker: "oss-h3-scene-edit" },+ picture: { mode: "picture", workflows: ["image-from-picture-prepare", "video-scene-describe", "video-from-picture-solar"], maker: "oss-from-picture" },+ "picture-light": { mode: "picture", workflows: ["image-from-picture-prepare"], maker: "oss-from-picture" },+ "picture-own-person": { mode: "picture", workflows: ["image-from-picture-prepare"], maker: "oss-from-picture" },+ "picture-h3-renderer": { mode: "picture", workflows: ["video-from-picture-h3"], maker: "oss-from-picture" },+ "finish-faces": { mode: "finish", workflows: ["video-fix-faces-h3"], maker: "oss-h3-fix-faces" },+ "finish-colours": { mode: "finish", workflows: ["video-fix-colours"], maker: "oss-fix-colours" },+};++export const GENJUTSU_FEATURE_KEYS = Object.keys(GENJUTSU_FEATURES) as GenjutsuFeature[];++/** Which features are open to this viewer: everything for the owner (and in tests), else what has passed. */+export type FeatureCheck = (f: GenjutsuFeature) => boolean;+export const ALL_FEATURES: FeatureCheck = () => true;++/** Whether a mode shows for this viewer (the new modes need one of their features open). */+export function modeOpen(mode: GenjutsuMode, open: FeatureCheck = ALL_FEATURES): boolean {+ if (mode === "picture") return open("picture");+ if (mode === "finish") return open("finish-faces") || open("finish-colours");+ return true;+}++/** Scene edit's three actions. */+export type SceneAction = "change" | "remove" | "background";+export const SCENE_ACTIONS: { id: SceneAction; label: string; hint: string; feature: GenjutsuFeature }[] = [+ { id: "change", label: "Change it", hint: "Name what changes and what it becomes. Add a picture to match it exactly.", feature: "object-change" },+ { id: "remove", label: "Remove it", hint: "Name what goes. The space behind it is filled in, and the sound stays.", feature: "object-remove" },+ { id: "background", label: "New background", hint: "The people stay as filmed. Say or show the new place.", feature: "object-background" },+];++/** Object swap on Scene edit: what changes and how. */+export interface ObjectEdit {+ action: SceneAction;+ /** What SAM follows (several, comma-separated); for New background, what stays ("the people"). */+ target?: string;+ /** What it becomes; for Remove it, what shows there. */+ becomes?: string;+ biggestOnly?: boolean;+ keepShape?: boolean;+ edge?: "tight" | "normal" | "loose";+ motionDetail?: 512 | 768;+}++/** From picture's settings: the first frame (stage "frame") or the video (stage "video", from an approved frame). */+export interface PictureOptions {+ stage: "frame" | "video";+ light?: { look: LookId } | { words: string };+ /** Relight the person already in the clip (no character picture). */+ ownPerson?: boolean;+ /** Own person: keep the frame's crop. */+ keepCrop?: boolean;+ /** Extra words for the pose ("arms crossed, chin up"). */+ adjust?: string;+ /** The approved first frame (stage video): a frame this install made. */+ frame?: string;+ /** What happens in the part, in words (the describer's, edited). */+ scene?: string;+ /** The owner's renderer choice (SolarRenderer by default). */+ renderer?: "solar" | "h3";+ /** Motion detail: 0 = match the video, else the motion reference's long edge. */+ motionDetail?: 0 | 512 | 768;+}++/** Finish's settings: Fix faces or Fix colours. */+export interface FinishOptions {+ tool: "faces" | "colours";+ faceStyle?: "photo" | "mouth";+ chunkSeconds?: 4 | 6.5 | 10;+ finish?: "soft" | "filmic" | "rich" | "off";+ /** 0–1 (Orion's 0–0.5). */+ strength?: number;+ /** 0–1 (detail contrast 0 … −0.6). */+ soften?: number;+}++/** The part a new maker takes (seconds): Group swap, Scene edit and From picture 2–15 s; Finish the whole clip. */+export const OPENJUTSU_LIMITS = { minSeconds: 2, maxSeconds: 15, facesMaxSeconds: 10, coloursMaxSeconds: 60, maxCharacters: 4, roleChars: 80, lightChars: 300, sceneChars: 2000 } as const;++/** The feature a request needs (null: an existing Genjutsu feature, always open). */+export function requestFeatures(o: { mode: GenjutsuMode; maker: Maker; character?: CharacterOptions; object?: ObjectEdit; picture?: PictureOptions; finish?: FinishOptions }): GenjutsuFeature[] {+ const m = o.maker;+ if (m.group) return o.character?.onePerPerson ? ["group-swap", "group-swap-one-by-one"] : ["group-swap"];+ if (m.actions) return [SCENE_ACTIONS.find((a) => a.id === (o.object?.action ?? "change"))!.feature];+ if (m.review) {+ const p = o.picture;+ return [+ "picture",+ ...(p?.light ? (["picture-light"] as const) : []),+ ...(p?.ownPerson ? (["picture-own-person"] as const) : []),+ ...(p?.renderer === "h3" ? (["picture-h3-renderer"] as const) : []),+ ];+ }+ if (m.tool) return [m.tool === "faces" ? "finish-faces" : "finish-colours"];+ return [];+}++/**+ * The features a run of one of the new makers' models needs when it is sent straight to POST /api/generations (a script,+ * the CLI, MCP), read from its params.extra.openjutsu: a viewer who isn't the owner runs it only when every one is open.+ * Null for any other model.+ */+export function directRunFeatures(modelId: string, settings: Record<string, unknown> = {}): GenjutsuFeature[] | null {+ const s = settings;+ const light = typeof s.light === "string" && s.light.trim() !== "";+ const own = s.ownPerson === true;+ switch (modelId) {+ case "oss-h3-group-swap":+ return s.onePerPerson === true ? ["group-swap", "group-swap-one-by-one"] : ["group-swap"];+ case "oss-h3-scene-edit":+ return [(SCENE_ACTIONS.find((a) => a.id === s.action) ?? SCENE_ACTIONS[0]).feature];+ case "oss-from-picture-frame":+ return ["picture", ...(light ? (["picture-light"] as const) : []), ...(own ? (["picture-own-person"] as const) : [])];+ case "oss-scene-describe":+ return ["picture", ...(own ? (["picture-own-person"] as const) : [])];+ case "oss-from-picture":+ return ["picture", ...(s.renderer === "h3" ? (["picture-h3-renderer"] as const) : [])];+ case "oss-h3-fix-faces":+ return ["finish-faces"];+ case "oss-fix-colours":+ return ["finish-colours"];+ default:+ return null;+ }+}+// ---------------------------------------------------------------------------// Models ("makers")@@ -183,6 +343,18 @@ export interface Maker {* can regenerate the whole frame instead of only the person (Openjutsu's use_mask; H3 Relay's graph has no switch).*/h3?: { anchor: boolean; maskSwitch?: boolean };+ /** The features that open it (the owner always sees it; others once one of these has passed its GPU test). */+ features?: GenjutsuFeature[];+ /** Group swap: 2–4 characters by role (Who becomes who). */+ group?: boolean;+ /** Scene edit: its actions. */+ actions?: SceneAction[];+ /** From picture: the first frame is made and approved before the video. */+ review?: boolean;+ /** Finish: the tool it is. */+ tool?: "faces" | "colours";+ /** The part it takes, when it isn't the mode's own (seconds). */+ part?: { min: number; max: number };}/** fal's hosted Wan VACE (2.1 14B and 2.2 Fun): 17–241 frames (4n+1, the clip's own count and rate), at most 30 fps. */@@ -579,6 +751,86 @@ export const MAKERS: Maker[] = [readsLookImages: 2,},+ // The Openjutsu modes (your GPU only): Group swap, Scene edit, From picture, Fix faces, Fix colours.+ {+ id: "oss-h3-group-swap",+ engine: "open",+ modes: ["character"],+ targets: ["type", "click"],+ label: "Group swap",+ note: "Keeps the clip's sound · 2–15 s · up to 4 characters",+ source: "open",+ refs: { min: 1, max: OPENJUTSU_LIMITS.maxCharacters },+ keepsSound: true,+ qualities: ["480p", "720p", "1080p"],+ promptOptional: true,+ people: true,+ group: true,+ features: ["group-swap"],+ part: { min: OPENJUTSU_LIMITS.minSeconds, max: OPENJUTSU_LIMITS.maxSeconds },+ },+ {+ id: "oss-h3-scene-edit",+ engine: "open",+ modes: ["swap"],+ targets: ["type", "paint"],+ label: "Scene edit",+ note: "Change a thing, remove it or put the people somewhere new · keeps the clip's sound · 2–15 s",+ source: "open",+ refs: { min: 0, max: 1 },+ keepsSound: true,+ qualities: ["480p", "720p", "1080p"],+ promptOptional: true,+ actions: ["change", "remove", "background"],+ features: ["object-change", "object-remove", "object-background"],+ part: { min: OPENJUTSU_LIMITS.minSeconds, max: OPENJUTSU_LIMITS.maxSeconds },+ },+ {+ id: "oss-from-picture",+ engine: "open",+ modes: ["picture"],+ label: "From picture",+ note: "You check the first frame first · keeps the clip's sound · 2–15 s",+ source: "open",+ refs: { min: 1, max: 1 },+ keepsSound: true,+ qualities: ["480p", "720p"],+ promptOptional: true,+ review: true,+ features: ["picture"],+ part: { min: OPENJUTSU_LIMITS.minSeconds, max: OPENJUTSU_LIMITS.maxSeconds },+ },+ {+ id: "oss-h3-fix-faces",+ engine: "open",+ modes: ["finish"],+ label: "Face fix",+ note: "Redraws small or soft faces to match your character's photo · up to 10 s",+ source: "open",+ refs: { min: 1, max: 1 },+ keepsSound: true,+ renders: "keeps your clip's size",+ promptOptional: true,+ tool: "faces",+ features: ["finish-faces"],+ part: { min: 1, max: OPENJUTSU_LIMITS.facesMaxSeconds },+ },+ {+ id: "oss-fix-colours",+ engine: "open",+ modes: ["finish"],+ label: "Colour finish",+ note: "A soft film finish in seconds · up to 60 s",+ source: "open",+ refs: { min: 0, max: 0 },+ keepsSound: true,+ renders: "keeps your clip's size",+ promptOptional: true,+ tool: "colours",+ features: ["finish-colours"],+ part: { min: 1, max: OPENJUTSU_LIMITS.coloursMaxSeconds },+ },+// Insert (no Original yet: VACE inserts in a painted spot on both engines).{id: "oss-vace-insert",@@ -618,9 +870,11 @@ const SOURCE_RANK: Record<MakerSource, number> = { original: 0, open: 1, partnerexport const makerOffered = (m: Maker, on: (id: string) => boolean) => on(m.id) || (!!m.pair && on(m.pair));/** The models you can pick for this engine, mode and way of pointing: Fuobe's Original first, then open weights, then partners. */-export function makersFor(engine: Engine, mode: GenjutsuMode, target?: GenjutsuTarget): Maker[] {+export function makersFor(engine: Engine, mode: GenjutsuMode, target?: GenjutsuTarget, open: FeatureCheck = ALL_FEATURES): Maker[] {return MAKERS.filter((m) => {if (m.engine !== engine || !m.modes.includes(mode)) return false;+ // A maker that hasn't opened yet: the owner's alone.+ if (m.features && !m.features.some(open)) return false;if (MODE_TARGETS[mode].length && !(m.targets ?? []).includes(target ?? MODE_TARGETS[mode][0])) return false;// Lite and the full Original are one choice in the picker (Quality: Standard / High).if (m.tier === "high") return false;@@ -652,11 +906,30 @@ export function chooseMaker(o: {* all of them off the pick stays, and its run names the switch).*/offered?: (id: string) => boolean;+ /** The features open to this viewer (default: all, as for the owner). */+ open?: FeatureCheck;+ /** Character swap: characters added (2 or more: a model that takes them). */+ refs?: number;+ /** Object swap: Scene edit's action (Remove it and New background need Scene edit). */+ action?: SceneAction;+ /** Finish: the tool. */+ tool?: "faces" | "colours";}): { maker: Maker } | { problem: string } {const target = MODE_TARGETS[o.mode].length ? (o.target ?? MODE_TARGETS[o.mode][0]) : undefined;if (target && !MODE_TARGETS[o.mode].includes(target)) return { problem: `${getMode(o.mode).label} doesn't take ${target === "click" ? "clicks" : target === "paint" ? "paint" : "that"} — pick another way` };const on = o.offered;- const all = makersFor(o.engine, o.mode, target);+ let all = makersFor(o.engine, o.mode, target, o.open);+ // Two characters or more: only a model that takes them all (Group swap on your GPU, Recast in the cloud).+ if (o.mode === "character" && (o.refs ?? 0) > 1) {+ const many = all.filter((m) => m.refs.max >= (o.refs ?? 0));+ if (many.length) all = many;+ }+ // Remove it and New background: Scene edit's actions.+ if (o.mode === "swap" && o.action && o.action !== "change") {+ all = all.filter((m) => m.actions?.includes(o.action!));+ if (!all.length) return { problem: o.engine === "cloud" ? "Remove it and New background run on your GPU" : "Nothing on this engine does that yet" };+ }+ if (o.mode === "finish" && o.tool) all = all.filter((m) => m.tool === o.tool);const options = on ? keepOffered(all, (m) => makerOffered(m, on)) : all;if (!options.length) {if (o.engine === "cloud" && o.mode === "character" && target === "click") return { problem: CLOUD_CLICK_PROBLEM };@@ -865,10 +1138,48 @@ export interface GenjutsuCheck {seed?: number;/** Character swap's settings (the LoRA and the window plan are checked). */character?: CharacterOptions;+ object?: ObjectEdit;+ picture?: PictureOptions;+ finish?: FinishOptions;+}++/** The first thing that stops a request on one of the Openjutsu makers, in words, or null. */+function openjutsuProblem(c: GenjutsuCheck): string | null {+ const m = c.maker;+ if (m.group) {+ if (c.references < 1) return REFS_MISSING.character;+ if (c.references > OPENJUTSU_LIMITS.maxCharacters) return "Up to four characters";+ if (c.character?.onePerPerson && c.references < 2) return "Add a second character";+ if (c.character?.onePerPerson && c.references > 2) return "One by one takes two characters";+ return null;+ }+ if (m.actions) {+ const action = c.object?.action ?? "change";+ if (action === "change" && c.target === "paint") return c.mask ? null : "Paint over what changes";+ if (action !== "background" && !c.object?.target?.trim() && !c.subject?.trim()) return action === "remove" ? "Name what goes" : "Name what changes";+ return null;+ }+ if (m.review) {+ const p = c.picture ?? { stage: "frame" };+ if (p.ownPerson && !p.light) return "Pick a light, or turn off Keep the clip's own person";+ if (p.light && "words" in p.light && !p.light.words.trim()) return "Say how the light looks";+ if (!p.ownPerson && c.references < 1) return REFS_MISSING.picture;+ if (p.stage === "video" && !p.frame) return "Make and pick the first frame first";+ return null;+ }+ if (m.tool === "faces" && c.references < 1) return REFS_MISSING.finish;+ return null;}/** What's wrong with the selection whatever the model, or null. */-export function rangeProblem(source: Pick<RemoveSource, "duration">, range: RemoveRange, mode?: GenjutsuMode): string | null {+export function rangeProblem(source: Pick<RemoveSource, "duration">, range: RemoveRange, mode?: GenjutsuMode, maker?: Maker): string | null {+ if (maker?.part) {+ const len = range.end - range.start;+ if (!(len > 0) || range.start < 0) return "Pick a part of the clip";+ if (source.duration !== undefined && range.end > source.duration + 0.05) return "The selection runs past the end of the clip";+ if (len < maker.part.min - 0.05 || len > maker.part.max + 0.05) return maker.tool ? `Pick up to ${maker.part.max} seconds of the video` : `Pick a part between ${maker.part.min} and ${maker.part.max} seconds`;+ return null;+ }if (mode === "character") return partProblem(range, source.duration);const len = range.end - range.start;if (!(len > 0) || range.start < 0) return "Pick a part of the clip";@@ -884,13 +1195,16 @@ const REFS_MISSING: Record<GenjutsuMode, string> = {swap: "Add a picture of what goes in",insert: "Add a picture of what to add",restyle: "",+ picture: "Add a picture of your character",+ finish: "Add the character photo",};/** The first thing that stops this request, in words, or null. */export function genjutsuProblem(c: GenjutsuCheck): string | null {- const general = rangeProblem(c.source, c.range, c.mode);+ const general = rangeProblem(c.source, c.range, c.mode, c.maker);if (general) return general;const m = c.maker;+ if (m.group || m.actions || m.review || m.tool) return openjutsuProblem(c);const len = c.range.end - c.range.start;const { width: w, height: h } = c.source;const target = MODE_TARGETS[c.mode].length ? (c.target ?? MODE_TARGETS[c.mode][0]) : undefined;@@ -975,6 +1289,11 @@ export interface GenjutsuPlanInput {seed?: number;/** Character swap's settings. */character?: CharacterOptions;+ object?: ObjectEdit;+ picture?: PictureOptions;+ finish?: FinishOptions;+ /** Scene edit's painted area, as the pack's keyframe (the server reads it from the paint). */+ paint?: PaintKeyframe[];}export interface GenjutsuPlan {@@ -995,7 +1314,7 @@ const r3 = (n: number) => Math.round(n * 1000) / 1000;const r6 = (n: number) => Math.round(n * 1e6) / 1e6;const pieceLabel = (p: Piece, n: number, what: string) => ({ label: n > 1 ? `Piece ${p.index + 1} of ${n} · ${what}` : what[0].toUpperCase() + what.slice(1), index: p.index, of: n });-const OP: Record<GenjutsuMode, GenerationRequest["op"]> = { motion: "motion-transfer", character: "video-swap", swap: "video-swap", insert: "video-insert", restyle: "v2v" };+const OP: Record<GenjutsuMode, GenerationRequest["op"]> = { motion: "motion-transfer", character: "video-swap", swap: "video-swap", insert: "video-insert", restyle: "v2v", picture: "picture-video", finish: "tone-video" };/** Steps on a model that runs on both engines say which one (Originals, the Soul look's first frame). */function pinEngines(steps: PlanStep[], engine: Engine): PlanStep[] {@@ -1020,6 +1339,8 @@ export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {}function planSteps(input: GenjutsuPlanInput): GenjutsuPlan {+ const om = input.maker;+ if (om.group || om.actions || om.review || om.tool) return planOpenjutsu(input);if (input.mode === "character" && input.maker.h3) return planCharacterSwap(input);if (input.mode === "restyle" && input.maker.id === ORIGINALS.restyle && input.maker.engine === "cloud") return planCloudRestyle(input);if (input.mode === "restyle" && input.maker.looks === "fuobe") return planFuobeRestyle(input);@@ -1407,6 +1728,146 @@ function planCharacterSwap(input: GenjutsuPlanInput): GenjutsuPlan {return { steps, final: "mute", pieces: n, sound, tracked: false, anchors: anchorOn ? n : 0 };}+// ---------------------------------------------------------------------------+// The Openjutsu modes++/** The part's size at a short edge (never larger than the clip), on even numbers. */+export function fitSize(width: number, height: number, shortEdge: number): { width: number; height: number } {+ const k = Math.min(1, shortEdge / Math.min(width, height));+ return { width: Math.max(2, Math.round((width * k) / 2) * 2), height: Math.max(2, Math.round((height * k) / 2) * 2) };+}++/** The short edge each quality fits the part to (the pack's own 736p for 720p). */+const SHORT_EDGE: Record<string, number> = { "480p": 480, "720p": 736, "1080p": 1080 };++/** The scene edit's words for its plan (what goes, what it becomes). */+export function sceneWords(o: ObjectEdit | undefined, subject?: string): { target: string; becomes: string } {+ const action = o?.action ?? "change";+ const target = (o?.target ?? subject ?? "").replace(/\s+/g, " ").trim().slice(0, 120);+ return { target: target || (action === "background" ? "the people" : ""), becomes: (o?.becomes ?? "").replace(/\s+/g, " ").trim().slice(0, 300) };+}++/**+ * Group swap, Scene edit, From picture and Finish on your GPU: the part fitted first (24 fps, the quality's short edge,+ * the clip's sound: video-fit-clip, so ComfyUI never decodes more of the clip than it needs), then one job on the+ * Openjutsu graph with its settings (params.extra.openjutsu). From picture's first frame reads the clip itself (one frame).+ */+function planOpenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {+ const m = input.maker;+ const base = { feature: GENJUTSU.feature, batchTitle: input.title, title: input.title };+ const helper = { feature: GENJUTSU.stepFeature, batchTitle: input.title };+ const seed = input.seed !== undefined ? { seed: input.seed } : {};+ const start = r3(input.range.start);+ const end = r3(input.range.end);+ const steps: PlanStep[] = [];+ const w = input.source.width;+ const h = input.source.height;+ const quality = qualityFor(m, input.quality) ?? "720p";+ const fit = (size: { width: number; height: number } | null) => {+ steps.push({+ key: "part",+ request: { ...helper, modelId: SHARPEN_TOOLS.fit, op: "trim", inputs: { video: input.source.url }, params: { startTime: start, endTime: end, fps: 24, ...(size ? { extra: { ...size } } : {}) }, step: { label: "The part at 24 fps", index: 0, of: 1 } },+ });+ };+ const sized = (short: number) => (w && h ? fitSize(w, h, short) : null);+ const job = (key: string, op: GenerationRequest["op"], label: string, images: string[], settings: Record<string, unknown>, own = base): PlanStep => ({+ key,+ request: { ...own, modelId: m.id, op, ...(images.length ? { inputs: { images } } : {}), params: { ...seed, ...(m.qualities ? { resolution: quality } : {}), extra: { openjutsu: { ...settings, ...seed } } }, step: { label, index: 0, of: 1 } },+ after: ["part"],+ chain: [{ slot: "video" }],+ });+ const c = input.character ?? {};+ if (m.group) {+ const refs = input.references.slice(0, OPENJUTSU_LIMITS.maxCharacters);+ fit(sized(SHORT_EDGE[quality] ?? 736));+ steps.push(+ job("swap", "group-swap", refs.length > 1 ? "Swap the characters" : "Swap the character", refs, {+ pictures: refs.length,+ roles: refs.map((_, i) => c.people?.[i]?.role ?? ""),+ quality,+ motion: c.motionDetail ?? 512,+ hats: !!c.hats,+ mouthsFollowSound: c.mouthsFollowSound !== false,+ edge: c.edge ?? "normal",+ ...(c.onePerPerson && refs.length === 2 ? { onePerPerson: true } : {}),+ }),+ );+ return { steps, final: "swap", pieces: 1, sound: false, tracked: false };+ }+ if (m.actions) {+ const o = input.object ?? { action: "change" as const };+ const words = sceneWords(o, input.subject);+ const picture = o.action !== "remove" && input.references.length > 0;+ fit(sized(SHORT_EDGE[quality] ?? 736));+ steps.push(+ job("edit", "scene-edit", o.action === "remove" ? "Remove it" : o.action === "background" ? "Put them somewhere new" : "Change it", picture ? input.references.slice(0, 1) : [], {+ action: o.action,+ target: words.target,+ becomes: words.becomes,+ picture,+ biggestOnly: !!o.biggestOnly,+ keepShape: o.action === "change" && !!o.keepShape,+ edge: o.edge ?? "normal",+ motion: o.motionDetail ?? 512,+ quality,+ ...(o.action === "change" && input.paint?.length ? { paint: input.paint } : {}),+ }),+ );+ return { steps, final: "edit", pieces: 1, sound: false, tracked: false };+ }+ if (m.review) {+ const p = input.picture ?? { stage: "frame" as const };+ if (p.stage === "frame") {+ steps.push({+ key: "frame",+ request: {+ ...base,+ feature: GENJUTSU.stepFeature,+ modelId: "oss-from-picture-frame",+ op: "picture-frame",+ inputs: { video: input.source.url, ...(p.ownPerson ? {} : { images: input.references.slice(0, 1) }) },+ params: { startTime: start, ...seed, extra: { openjutsu: { light: lightWords(p.light), ownPerson: !!p.ownPerson, keepCrop: !!p.keepCrop, adjust: p.adjust ?? "", ...seed } } },+ step: { label: "The first frame", index: 0, of: 1 },+ },+ });+ return { steps, final: "frame", pieces: 1, sound: false, tracked: false };+ }+ if (!p.frame) throw new Error("Make and pick the first frame first");+ const preset = quality === "720p" ? 736 : 480;+ fit(w && h ? fitSize(w, h, preset) : null);+ steps.push(+ job("video", "picture-video", "Make the video", [p.frame], {+ seconds: r3(end - start),+ quality,+ motion: p.motionDetail ?? 0,+ scene: (p.scene ?? "").slice(0, OPENJUTSU_LIMITS.sceneChars),+ ...(p.renderer === "h3" ? { renderer: "h3" } : {}),+ }),+ );+ return { steps, final: "video", pieces: 1, sound: false, tracked: false };+ }+ // Finish: the part, fitted only when it isn't the whole clip or is over 1080p.+ const f = input.finish ?? { tool: m.tool ?? "colours" };+ const whole = wholeClip(input.range, input.source.duration);+ const big = !!w && !!h && Math.min(w, h) > 1080;+ if (!whole || big || m.tool === "faces") fit(sized(1080));+ const settings =+ m.tool === "faces"+ ? { faceStyle: f.faceStyle ?? "mouth", chunkSeconds: f.chunkSeconds ?? 6.5 }+ : { finish: f.finish ?? "soft", strength: f.strength ?? 0.4, soften: f.soften ?? 0.33 };+ const step = job("fix", m.tool === "faces" ? "face-fix-video" : "tone-video", m.tool === "faces" ? "Fix the faces" : "Fix the colours", m.tool === "faces" ? input.references.slice(0, 1) : [], settings);+ if (!steps.length) {+ delete step.after;+ delete step.chain;+ step.request = { ...step.request, inputs: { ...step.request.inputs, video: input.source.url } };+ }+ steps.push(step);+ return { steps, final: "fix", pieces: 1, sound: false, tracked: false };+}++/** How many sections Fix faces renders (for the estimate's note). */+export { faceChunkCount } from "../openjutsu-graphs";+// ---------------------------------------------------------------------------// Restyle@@ -1524,6 +1985,10 @@ export interface GenjutsuSetup {references?: string[];/** Character swap's settings (not the part's words: they belong to the clip). */character?: Omit<CharacterOptions, "dialogue">;+ object?: ObjectEdit;+ /** From picture's settings (not the frame or the words: they belong to a run). */+ picture?: Omit<PictureOptions, "frame" | "scene" | "stage">;+ finish?: FinishOptions;}const MODES = new Set<string>(GENJUTSU_MODES.map((m) => m.id));@@ -1575,9 +2040,82 @@ export function cleanCharacter(v: unknown): Omit<CharacterOptions, "dialogue"> |if (wf !== undefined) out.windowFrames = wf;const hf = num(o.historyFrames, 0, 341);if (hf !== undefined) out.historyFrames = hf;+ if (Array.isArray(o.people)) {+ const people = o.people.slice(0, OPENJUTSU_LIMITS.maxCharacters).map((p) => {+ const x = p && typeof p === "object" ? (p as Record<string, unknown>) : {};+ const pin = x.pin && typeof x.pin === "object" ? (x.pin as Record<string, unknown>) : undefined;+ const at = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? Math.max(0, Math.min(1, Math.round(v * 1000) / 1000)) : undefined);+ const px = at(pin?.x);+ const py = at(pin?.y);+ return { role: typeof x.role === "string" ? x.role.slice(0, OPENJUTSU_LIMITS.roleChars) : "", ...(px !== undefined && py !== undefined ? { pin: { x: px, y: py } } : {}) };+ });+ if (people.some((p) => p.role || p.pin)) out.people = people;+ }+ if (o.onePerPerson === true) out.onePerPerson = true;+ if (o.hats === true) out.hats = true;+ if (o.mouthsFollowSound === false) out.mouthsFollowSound = false;+ const edge = oneOf(o.edge, ["tight", "normal", "loose"] as const);+ if (edge) out.edge = edge;+ if (o.motionDetail === 512 || o.motionDetail === 768) out.motionDetail = o.motionDetail;return Object.keys(out).length ? out : undefined;}+/** Scene edit's settings as they travel in a code. */+export function cleanObject(v: unknown): ObjectEdit | undefined {+ if (!v || typeof v !== "object") return undefined;+ const o = v as Record<string, unknown>;+ const action = oneOf(o.action, ["change", "remove", "background"] as const);+ if (!action) return undefined;+ const out: ObjectEdit = { action };+ const target = str(o.target, 120);+ if (target) out.target = target;+ const becomes = str(o.becomes, 300);+ if (becomes) out.becomes = becomes;+ if (o.biggestOnly === true) out.biggestOnly = true;+ if (o.keepShape === true) out.keepShape = true;+ const edge = oneOf(o.edge, ["tight", "normal", "loose"] as const);+ if (edge) out.edge = edge;+ if (o.motionDetail === 512 || o.motionDetail === 768) out.motionDetail = o.motionDetail;+ return out;+}++/** From picture's settings as they travel in a code (the frame and the words stay with the run). */+export function cleanPicture(v: unknown): Omit<PictureOptions, "frame" | "scene" | "stage"> | undefined {+ if (!v || typeof v !== "object") return undefined;+ const o = v as Record<string, unknown>;+ const out: Omit<PictureOptions, "frame" | "scene" | "stage"> = {};+ const l = o.light as Record<string, unknown> | undefined;+ if (l && typeof l === "object") {+ if (typeof l.look === "string" && (LOOK_IDS as string[]).includes(l.look)) out.light = { look: l.look as LookId };+ else if (str(l.words, OPENJUTSU_LIMITS.lightChars)) out.light = { words: str(l.words, OPENJUTSU_LIMITS.lightChars)! };+ }+ if (o.ownPerson === true) out.ownPerson = true;+ if (o.keepCrop === true) out.keepCrop = true;+ const adjust = str(o.adjust, 300);+ if (adjust) out.adjust = adjust;+ if (o.renderer === "h3") out.renderer = "h3";+ if (o.motionDetail === 512 || o.motionDetail === 768) out.motionDetail = o.motionDetail;+ return Object.keys(out).length ? out : undefined;+}++/** Finish's settings as they travel in a code. */+export function cleanFinish(v: unknown): FinishOptions | undefined {+ if (!v || typeof v !== "object") return undefined;+ const o = v as Record<string, unknown>;+ const tool = oneOf(o.tool, ["faces", "colours"] as const);+ if (!tool) return undefined;+ const out: FinishOptions = { tool };+ const style = oneOf(o.faceStyle, ["photo", "mouth"] as const);+ if (style) out.faceStyle = style;+ if (o.chunkSeconds === 4 || o.chunkSeconds === 6.5 || o.chunkSeconds === 10) out.chunkSeconds = o.chunkSeconds;+ const finish = oneOf(o.finish, ["soft", "filmic", "rich", "off"] as const);+ if (finish) out.finish = finish;+ const unit = (x: unknown) => (typeof x === "number" && Number.isFinite(x) ? Math.max(0, Math.min(1, Math.round(x * 100) / 100)) : undefined);+ if (unit(o.strength) !== undefined) out.strength = unit(o.strength);+ if (unit(o.soften) !== undefined) out.soften = unit(o.soften);+ return out;+}+const ANCHOR_IDS = new Set(["gpt-image-2-5-sunburst", "nano-banana-pro", "oss-qwen-image-21", "oss-krea2-identity-edit", "oss-qwen-edit"]);/** A setup as a short code ("gj1." + base64url JSON with short keys; empty fields left out). */@@ -1595,12 +2133,18 @@ export function encodeSetup(s: GenjutsuSetup): string {l: look,r: s.references?.length ? s.references : undefined,c: s.character && cleanCharacter(s.character),+ o: s.object && cleanObject(s.object),+ i: s.picture && cleanPicture(s.picture),+ f: s.finish && cleanFinish(s.finish),};return `gj1.${toBase64Url(JSON.stringify(o))}`;}-/** A setup read back from a code (or a link with ?setup=…), checked field by field; null when it isn't one. */-export function decodeSetup(input: string): GenjutsuSetup | null {+/**+ * A setup read back from a code (or a link with ?setup=…), checked field by field; null when it isn't one. A code naming+ * a mode or a setting not open to this viewer opens without it (a mode that isn't open: Motion transfer).+ */+export function decodeSetup(input: string, open: FeatureCheck = ALL_FEATURES): GenjutsuSetup | null {let o: Record<string, unknown>;try {let code = input.trim();@@ -1613,13 +2157,14 @@ export function decodeSetup(input: string): GenjutsuSetup | null {return null;}if (!o || typeof o !== "object" || typeof o.m !== "string" || !MODES.has(o.m)) return null;- const mode = o.m as GenjutsuMode;+ const mode = modeOpen(o.m as GenjutsuMode, open) ? (o.m as GenjutsuMode) : "motion";const out: GenjutsuSetup = { mode };if (o.e === "cloud" || o.e === "open") out.engine = o.e;const model = str(o.x, 80);// Codes from before the Originals name a retired Genjutsu model or the round-4 open models: the Original that replaced it.const current = model && (LEGACY_MAKERS[model] ?? model);- if (current && getMaker(current)) out.model = current;+ const known = current ? getMaker(current) : undefined;+ if (current && known && (!known.features || known.features.some(open))) out.model = current;if (o.t === "standard" || o.t === "high") out.tier = o.t;if (typeof o.q === "string" && QUALITIES.has(o.q)) out.quality = o.q as GenjutsuQuality;if (typeof o.g === "string" && MODE_TARGETS[mode].includes(o.g as GenjutsuTarget)) out.target = o.g as GenjutsuTarget;@@ -1640,7 +2185,21 @@ export function decodeSetup(input: string): GenjutsuSetup | null {const refs = files(o.r, GENJUTSU.maxReferences);if (refs.length) out.references = refs;const character = mode === "character" ? cleanCharacter(o.c) : undefined;- if (character) out.character = character;+ if (character) {+ if (character.onePerPerson && !open("group-swap-one-by-one")) delete character.onePerPerson;+ out.character = character;+ }+ const object = mode === "swap" ? cleanObject(o.o) : undefined;+ if (object && open(SCENE_ACTIONS.find((a) => a.id === object.action)!.feature)) out.object = object;+ const picture = mode === "picture" ? cleanPicture(o.i) : undefined;+ if (picture) {+ if (picture.light && !open("picture-light")) delete picture.light;+ if (picture.ownPerson && !open("picture-own-person")) delete picture.ownPerson;+ if (picture.renderer && !open("picture-h3-renderer")) delete picture.renderer;+ if (Object.keys(picture).length) out.picture = picture;+ }+ const finish = mode === "finish" ? cleanFinish(o.f) : undefined;+ if (finish && open(finish.tool === "faces" ? "finish-faces" : "finish-colours")) out.finish = finish;return out;}diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex ffcc5783..4d647514 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -1115,6 +1115,87 @@ const open: ModelDef[] = [routes: [comfy("video-swap", "video-character-swap-h3-relay", "H3 Relay toolkit: SAM 3.1 subject, 124-frame windows with 18 frames of history, the clip's sound kept")],options: { seed: true, resolutions: ["480p", "768p"], maxImages: 1 },}),+ // Genjutsu's Openjutsu modes (D3voz/openjutsu, MIT; src/lib/openjutsu-graphs.ts): Group swap (2–4 characters by role),+ // Scene edit (change / remove / new background), From picture (the first frame, what happens, the video), Fix faces and+ // Fix colours. Your GPU only. Genjutsu offers them (each opens to everyone after its GPU test), so they stay out of the+ // composer's lists.+ o({+ id: "oss-h3-group-swap",+ name: "Group swap",+ vendor: "MiniMax × Openjutsu",+ family: "minimax-h3",+ kind: "video",+ tagline: "Up to four characters, each taking over the person you name · the clip's sound kept · 24 GB GPU",+ hidden: true,+ routes: [comfy("group-swap", "video-group-swap-h3", "Openjutsu advanced: SAM 3.1 tracks, Qwen3-VL labels each by role, MiniMax H3 + DMAD redraw them clip by clip; one by one (2 characters) runs a pass per person")],+ options: { seed: true, resolutions: ["480p", "720p", "1080p"], maxImages: 4 },+ }),+ o({+ id: "oss-h3-scene-edit",+ name: "Scene edit",+ vendor: "MiniMax × Openjutsu",+ family: "minimax-h3",+ kind: "video",+ tagline: "Change a thing, remove it or put the people somewhere new · the clip's sound kept · 24 GB GPU",+ hidden: true,+ routes: [comfy("scene-edit", "video-scene-edit-h3", "Openjutsu object: SAM 3.1 tracks what you name, MiniMax H3 + DMAD redraw only that, clip by clip")],+ options: { seed: true, resolutions: ["480p", "720p", "1080p"], maxImages: 1 },+ }),+ o({+ id: "oss-from-picture-frame",+ name: "From picture · first frame",+ vendor: "Black Forest Labs × Openjutsu",+ family: "flux",+ kind: "image",+ tagline: "Your character in the pose of the clip's first frame, in your picture's setting and light",+ hidden: true,+ routes: [comfy("picture-frame", "image-from-picture-prepare", "FLUX 3 Image Klein with its prompt upsampler; one pass for pose and light")],+ options: { seed: true, maxImages: 1 },+ }),+ o({+ id: "oss-scene-describe",+ name: "From picture · what happens",+ vendor: "Qwen × Openjutsu",+ family: "utility",+ kind: "text",+ tagline: "What happens in a part of a clip, written for the first frame you picked",+ hidden: true,+ routes: [comfy("describe-video", "video-scene-describe", "Qwen3-VL 8B at 2 frames a second, then rewritten for the picture")],+ options: { maxImages: 1 },+ }),+ o({+ id: "oss-from-picture",+ name: "From picture",+ vendor: "MiniMax × Openjutsu",+ family: "minimax-h3",+ kind: "video",+ tagline: "The first frame you approved, moving exactly like the person in the clip · the clip's sound kept · 24 GB GPU",+ hidden: true,+ routes: [comfy("picture-video", "video-from-picture-solar", "SolarRenderer: MiniMax H3 with its 4-step and control LoRAs, Metric3D normals as the motion (or native H3 + DMAD)")],+ options: { seed: true, resolutions: ["480p", "720p"], maxImages: 1 },+ }),+ o({+ id: "oss-h3-fix-faces",+ name: "Fix faces",+ vendor: "MiniMax × Openjutsu",+ family: "minimax-h3",+ kind: "video",+ tagline: "Redraws small or soft faces in a finished video so they match your character's photo · 24 GB GPU",+ hidden: true,+ routes: [comfy("face-fix-video", "video-fix-faces-h3", "H3-FaceRefine tracking and paste-back, MiniMax H3 + DMAD in overlapping sections")],+ options: { seed: true, maxImages: 1 },+ }),+ o({+ id: "oss-fix-colours",+ name: "Fix colours",+ vendor: "Openjutsu",+ family: "utility",+ kind: "video",+ tagline: "A soft film finish for a finished video: gentler contrast, smoother detail, rich blacks · no model, seconds",+ hidden: true,+ routes: [comfy("tone-video", "video-fix-colours", "Image Detail Contrast + Orion4D's DCTL tone mapper")],+ options: {},+ }),// Remove object's "Remove a person (H3)" (docs/research/openjutsu-6.md §11.1): H3 Relay's Person Removal with Akatz// Labs' Person Remover LoRA, from a clean first frame (Remove object makes it, fits the clip to 24 fps, puts the sound back).o({diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.tsindex 197ffd82..aaa1a335 100644--- a/src/lib/catalog/plan.ts+++ b/src/lib/catalog/plan.ts@@ -800,6 +800,14 @@ const NEEDS: Partial<composite: { videos: 3, mask: true, msg: "Add the footage, the redrawn clip, the swap and the person's mask to put the character back over it" },// N7-5 (the open engine also needs the browser's render along the path: its model's options.requires.video)"camera-path": { images: 1, msg: "Add the still to film along the path" },+ // Genjutsu's Openjutsu modes+ "group-swap": { video: true, images: 1, msg: "Add the clip and your characters" },+ "scene-edit": { video: true, msg: "Add the clip to edit" },+ "picture-frame": { video: true, msg: "Add the clip whose first frame sets the pose" },+ "picture-video": { video: true, images: 1, msg: "Add the clip and the first frame" },+ "face-fix-video": { video: true, images: 1, msg: "Add the video and the character photo" },+ "tone-video": { video: true, msg: "Add the video to finish" },+ "describe-video": { video: true, msg: "Add the clip to describe" },};const given = (v: unknown) => (Array.isArray(v) ? v.length > 0 : !!v);diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 56ac9c53..c1d95959 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -91,7 +91,15 @@ export type Operation =// archive-restore| "restore-video" // archive video (+ prompt: period, place, light; negative: what not to invent) → the same shot clean, in colour, larger// Design a voice- | "voice-design"; // params.voiceDescription (who is speaking) + prompt (the line) → the line in a new voice made from the words+ | "voice-design" // params.voiceDescription (who is speaking) + prompt (the line) → the line in a new voice made from the words+ // Genjutsu's Openjutsu modes+ | "face-fix-video" // video + face photo → the same video with small or soft faces redrawn to match the photo+ | "tone-video" // video → the same video with a film finish (detail softened, tone-mapped)+ | "describe-video" // video part (+ a picture) → what happens in it, in words (text)+ | "group-swap" // video part + 1–4 character pictures + roles → each named person replaced by their character+ | "scene-edit" // video part (+ a picture) + params.extra (change / remove / new background) → the scene edited, the rest kept+ | "picture-frame" // video part (+ a character picture) → its first frame with the character in that pose (or relit)+ | "picture-video"; // video part + an approved first frame (+ what happens) → the frame animated with the part's motionexport const OPERATION_LABELS: Record<Operation, string> = {t2i: "Text to image",@@ -165,6 +173,13 @@ export const OPERATION_LABELS: Record<Operation, string> = {"camera-path": "Fly path",composite: "Character over the footage","restore-video": "Restore & colourise",+ "face-fix-video": "Fix faces",+ "tone-video": "Fix colours",+ "describe-video": "Describe a video",+ "group-swap": "Group swap",+ "scene-edit": "Scene edit",+ "picture-frame": "First frame from a picture",+ "picture-video": "Video from a picture",};export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {@@ -240,6 +255,13 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {"camera-path": "video",composite: "video","restore-video": "video",+ "face-fix-video": "video",+ "tone-video": "video",+ "describe-video": "text",+ "group-swap": "video",+ "scene-edit": "video",+ "picture-frame": "image",+ "picture-video": "video",};/**diff --git a/src/lib/comfy-variants.ts b/src/lib/comfy-variants.tsindex 4d9fa402..d488acc3 100644--- a/src/lib/comfy-variants.ts+++ b/src/lib/comfy-variants.ts@@ -36,6 +36,15 @@ export const H3_ORBIT_GRAPH: Record<string, string> = { "minimax-h3-i2v": "minim*/export const REUSE_BED_GRAPH: Record<string, string> = { "voice-clean-reuse": "voice-clean-bed-reuse" };+/**+ * Genjutsu's Openjutsu graphs (params.extra.openjutsu): Group swap one by one (exactly 2 characters, a pass each) and From+ * picture on native H3 (the owner's renderer) run graphs of their own.+ */+export const OPENJUTSU_VARIANTS: Record<string, { key: string; value: unknown; graph: string }> = {+ "video-group-swap-h3": { key: "onePerPerson", value: true, graph: "video-group-swap-h3-one-by-one" },+ "video-from-picture-solar": { key: "renderer", value: "h3", graph: "video-from-picture-h3" },+};+export interface VariantRequest {op: string;/** Clips a join takes ("video-concat-{n}"). */@@ -73,6 +82,9 @@ export function resolveWorkflowId(endpointTemplate: string, r: VariantRequest):const best = H3_BEST_GRAPH[endpoint];if (orbit && r.extra.orbit === true && r.has(orbit)) endpoint = orbit;else if (best && r.extra.quality === "best" && r.has(best)) endpoint = best;+ const oj = OPENJUTSU_VARIANTS[endpoint];+ const ojSettings = r.extra.openjutsu as Record<string, unknown> | undefined;+ if (oj && ojSettings?.[oj.key] === oj.value && r.has(oj.graph)) endpoint = oj.graph;const bed = REUSE_BED_GRAPH[endpoint];if (bed && r.extra.background === "keep" && r.has(bed)) endpoint = bed;return endpoint;diff --git a/src/lib/openjutsu-graphs.ts b/src/lib/openjutsu-graphs.tsnew file mode 100644index 00000000..81457a83--- /dev/null+++ b/src/lib/openjutsu-graphs.ts@@ -0,0 +1,645 @@+/**+ * The Openjutsu graphs Genjutsu sends to your GPU (Group swap, Scene edit, From picture, Fix faces, Fix colours): the+ * settings each request writes into Fuobe's copies of D3voz's Openjutsu graphs (MIT, scripts/comfy/hand-built/), and the+ * branches it leaves out. Ported from Openjutsu's lib/{simple,advanced,object,picture,face,color}.ts at 7fe118bb: nodes+ * are found by their titles, as there. Pure, so the provider (src/server/providers/comfyui.ts) and the tests share it.+ *+ * Fuobe's changes to the port: every job gets its own Context Loop run name (fuobe_<generation id>), so a job never+ * resumes another one's clips and its folder can be deleted afterwards; the request and look words name only what is+ * wanted; the video canvas never goes past 2048 px a side.+ */+import type { ComfyWorkflow } from "./comfy";++type Link = [string, number];+export const isLink = (v: unknown): v is Link => Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "number";++const clone = (g: ComfyWorkflow): ComfyWorkflow => JSON.parse(JSON.stringify(g)) as ComfyWorkflow;++export function nodeByTitle(graph: ComfyWorkflow, title: string): string {+ const ids = Object.keys(graph).filter((id) => graph[id]._meta?.title === title);+ if (ids.length !== 1) throw new Error(`Expected one "${title}" node in the workflow, found ${ids.length}.`);+ return ids[0];+}++/** Every link still points at a node that is there. */+export function danglingLinks(graph: ComfyWorkflow): string[] {+ const out: string[] = [];+ for (const [id, n] of Object.entries(graph)) for (const [k, v] of Object.entries(n.inputs)) if (isLink(v) && !graph[v[0]]) out.push(`${id}.${k} → ${v[0]}`);+ return out;+}++function assertLinked(graph: ComfyWorkflow) {+ const d = danglingLinks(graph);+ if (d.length) throw new Error(`The graph still links to removed nodes: ${d.join(", ")}`);+}++// ---------------------------------------------------------------------------+// Shared settings++/** Genjutsu's quality → the pack's preset (short edge): 720p is the pack's own 736p. */+export const OJ_RESOLUTION: Record<string, string> = { "480p": "480p", "720p": "736p", "1080p": "1080p" };+export const ojResolution = (q: string | undefined) => OJ_RESOLUTION[q ?? ""] ?? "736p";++/** Mask growth at SAM's 1008 px canvas. */+export const SWAP_MARGINS = { tight: 20, normal: 40, loose: 60 } as const;+export const OBJECT_MARGINS = { tight: 10, normal: 20, loose: 40 } as const;+export type Edge = keyof typeof SWAP_MARGINS;++/** Long edge of the grey-mannequin motion reference H3 follows. */+export const MOTION_SIZES = [512, 768] as const;+export type MotionSize = (typeof MOTION_SIZES)[number];++/** Each H3 clip of a Context Loop job: 6 s, with 39 frames of overlap. */+export const CLIP_SECONDS = 6;++/** The canvas the pack makes for a source of this size (plan_clips), on 32 px steps. */+export function canvasSize(width: number, height: number, preset: string): [number, number] {+ const scale = parseInt(preset, 10) / Math.min(width, height);+ return [width, height].map((side) => Math.max(32, Math.round((side * scale) / 32) * 32)) as [number, number];+}++/** A canvas at most `max` px on its long side (Openjutsu issue #37: wide clips at 1080p went past 2048). */+export function clampCanvas([w, h]: [number, number], max = 2048): [number, number] {+ const k = Math.min(1, max / Math.max(w, h));+ return k === 1 ? [w, h] : [Math.max(32, Math.floor((w * k) / 32) * 32), Math.max(32, Math.floor((h * k) / 32) * 32)];+}++/** The Context Loop run name of one Fuobe job: its folder under output/h3_chains is this job's alone. */+export const runName = (generationId: string) => `fuobe_${generationId.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 48) || "job"}`;++function setRunName(graph: ComfyWorkflow, name: string) {+ const plans = Object.values(graph).filter((n) => n.class_type === "MiniMaxH3ChainPlanModern");+ if (plans.length !== 1) throw new Error(`Expected one Production Plan node in the workflow, found ${plans.length}.`);+ plans[0].inputs.run_name = name;+}++function setMotionSize(graph: ComfyWorkflow, size: MotionSize) {+ const nodes = Object.values(graph).filter((n) => n.class_type === "ImageScaleToMaxDimension" && /motion reference/i.test(n._meta?.title ?? ""));+ if (!nodes.length) throw new Error("Expected a motion reference resize in the workflow.");+ for (const n of nodes) n.inputs.largest_size = size;+}++// The No lip-sync nodes, titled the same in every swap graph.+const MUTE = /^Mute the (clip|reference) audio H3 hears$/;+const NO_LIP_SYNC = /^(No lip-sync in the prompt|SAM: faces|SAM 3\.1 track faces|Faces \(shown on the mannequins?\))$/;++/** Mouths follow the sound (No lip-sync off): those nodes go, H3 hears the soundtrack and the mannequins get no faces. */+export function dropNoLipSync(graph: ComfyWorkflow) {+ const through = new Map<string, unknown>();+ for (const [id, n] of Object.entries(graph)) {+ const title = n._meta?.title ?? "";+ if (MUTE.test(title)) through.set(id, n.inputs.audio);+ else if (NO_LIP_SYNC.test(title)) through.set(id, undefined);+ }+ for (const id of through.keys()) delete graph[id];+ for (const [id, n] of Object.entries(graph)) {+ for (const [name, value] of Object.entries(n.inputs)) {+ if (!isLink(value) || !through.has(value[0])) continue;+ if (through.get(value[0])) n.inputs[name] = through.get(value[0]);+ else if (["no_lip_sync", "faces", "face_size"].includes(name)) delete n.inputs[name];+ else throw new Error(`Node ${id}.${name} still links to removed node ${value[0]}.`);+ }+ }+}++// ---------------------------------------------------------------------------+// Group swap (advanced / advanced_maxq)++export const GROUP_PLAN = "Swap Plan (roles, seed, size)";+export const MAX_CHARACTERS = 4;+const HAT = /\bhats?\b/i;++export interface GroupSwapSettings {+ /** Character pictures sent (1–4; one by one takes exactly 2). */+ pictures: number;+ /** Who each character replaces, in words ("" lets the describer name them). */+ roles: string[];+ resolution: string;+ motion: MotionSize;+ hatFix: boolean;+ noLipSync: boolean;+ edge: Edge;+ seed: number;+ run: string;+}++export const pictureCount = (graph: ComfyWorkflow) => Object.values(graph).filter((n) => n.class_type === "LoadImage" && /^Picture \d$/.test(n._meta?.title ?? "")).length;++/** Names for characters left without a role when others have one, as the Swap Plan's own defaults. */+export function ordinalRole(i: number, count: number): string {+ return count === 1 ? "the main person" : `the person with the ${["", "second ", "third ", "fourth "][i]}most screen time`;+}++/** The Swap Plan's roles, one line per character ("" when none was given). */+export function rolesText(roles: string[], pictures: number): string {+ const r = Array.from({ length: pictures }, (_, i) => (roles[i] ?? "").replace(/\s+/g, " ").trim().slice(0, 80));+ return r.some(Boolean) ? r.map((role, i) => role || ordinalRole(i, pictures)).join("\n") : "";+}++export function pruneGroupSwap(source: ComfyWorkflow, s: GroupSwapSettings): ComfyWorkflow {+ const graph = clone(source);+ const available = pictureCount(graph);+ if (s.pictures < 1 || s.pictures > available) throw new Error(`This takes 1–${available} character pictures.`);+ const removed = new Set<string>();+ // Unused pictures: the photo, its shrink and its describer go; inputs that read them are dropped.+ for (let k = s.pictures + 1; k <= available; k++) {+ const load = nodeByTitle(graph, `Picture ${k}`);+ const shrink = Object.keys(graph).find((id) => graph[id].class_type === "ImageScaleToMaxDimension" && isLink(graph[id].inputs.image) && (graph[id].inputs.image as Link)[0] === load);+ const describe = nodeByTitle(graph, `Describe picture ${k}`);+ for (const id of [load, shrink, describe]) if (id) removed.add(id);+ }+ // Hats off: the hat nodes go; whatever read "people + hats" reads the people mask instead.+ const bypass = new Map<string, unknown>();+ if (!s.hatFix) {+ for (const [id, n] of Object.entries(graph)) {+ if (!HAT.test(n._meta?.title ?? "")) continue;+ removed.add(id);+ if (n.class_type === "MaskComposite" && n.inputs.operation === "add") bypass.set(id, n.inputs.destination);+ }+ }+ for (const id of removed) delete graph[id];+ for (const [id, n] of Object.entries(graph)) {+ for (const [name, value] of Object.entries(n.inputs)) {+ if (!isLink(value) || !removed.has(value[0])) continue;+ if (bypass.has(value[0])) n.inputs[name] = bypass.get(value[0]);+ else if (/^picture_\d/.test(name) || name.startsWith("ref_images.")) delete n.inputs[name];+ else throw new Error(`Node ${id}.${name} still links to removed node ${value[0]}.`);+ }+ }+ if (!s.noLipSync) dropNoLipSync(graph);+ setMotionSize(graph, s.motion);+ for (const n of Object.values(graph)) if (n.class_type === "GrowMaskWithBlur" && / grow mask /.test(n._meta?.title ?? "")) n.inputs.expand = SWAP_MARGINS[s.edge];+ const plan = graph[nodeByTitle(graph, GROUP_PLAN)].inputs;+ Object.assign(plan, { resolution: s.resolution, seed: s.seed, clip_seconds: CLIP_SECONDS, roles: rolesText(s.roles, s.pictures) });+ setRunName(graph, s.run);+ assertLinked(graph);+ return graph;+}++// ---------------------------------------------------------------------------+// Scene edit (object)++export type SceneAction = "change" | "remove" | "background";+export const SCENE_PLAN = "Object Swap Plan (what to change)";++/** A painted keyframe: run-length encoded at ≤ 256 px (start, length pairs over the row-major mask). */+export interface PaintKeyframe {+ frame: number;+ width: number;+ height: number;+ runs: number[];+}++export interface SceneEditSettings {+ action: SceneAction;+ /** What SAM tracks (several, comma-separated); for New background, what stays. */+ target: string;+ /** What it becomes, or for Remove it what shows there. */+ becomes: string;+ /** A picture was sent ("What goes in" / "The new place"). */+ picture: boolean;+ biggestOnly: boolean;+ keepShape: boolean;+ edge: Edge;+ motion: MotionSize;+ resolution: string;+ seed: number;+ run: string;+ paint?: PaintKeyframe[];+}++export const objectTargets = (target: string) => target.split(",").map((t) => t.trim()).filter(Boolean);++/** The picture describer names only what is copied from the picture, about 20 more words for each thing. */+function sceneDescriber(s: SceneEditSettings) {+ const background = s.action === "background";+ const things = background ? ["place (the setting, its lighting and what is around)"] : objectTargets(s.target);+ const named = things.length === 1 ? things[0] : `${things.slice(0, -1).join(", ")} and the ${things.at(-1)}`;+ const words = 30 + 20 * things.length;+ return {+ prompt:+ `Describe the ${named} in this picture in about ${words} words${things.length > 1 ? ", one sentence for each" : ""}: their shape, colours, materials, patterns and details. ` ++ (background ? "" : "Include every layer worn there, outer layer first: an open shirt or jacket over a top is part of the top. ") ++ "Start straight with the description.",+ max_length: 2 * words + 40,+ };+}++/** A painted mask (white = paint) as the pack's run-length keyframe, scaled to at most 256 px a side. */+export function paintKeyframe(mask: { width: number; height: number; data: Uint8Array | Uint8ClampedArray; channels?: number }): PaintKeyframe {+ const ch = mask.channels ?? 4;+ const k = Math.min(1, 256 / Math.max(mask.width, mask.height));+ const w = Math.max(1, Math.round(mask.width * k));+ const h = Math.max(1, Math.round(mask.height * k));+ const runs: number[] = [];+ let start = -1;+ for (let i = 0; i < w * h; i++) {+ const x = Math.min(mask.width - 1, Math.floor(((i % w) + 0.5) / k));+ const y = Math.min(mask.height - 1, Math.floor((Math.floor(i / w) + 0.5) / k));+ const on = mask.data[(y * mask.width + x) * ch] > 127;+ if (on && start < 0) start = i;+ if (!on && start >= 0) {+ runs.push(start, i - start);+ start = -1;+ }+ }+ if (start >= 0) runs.push(start, w * h - start);+ return { frame: 0, width: w, height: h, runs };+}++export function pruneSceneEdit(source: ComfyWorkflow, s: SceneEditSettings): ComfyWorkflow {+ const graph = clone(source);+ const id = (title: string) => nodeByTitle(graph, title);+ const plan = graph[id(SCENE_PLAN)].inputs;+ const ref = graph[id("Reference Conditioning")].inputs;+ const grow = graph[id("Grow mask")].inputs;+ const grey = graph[id("Turn it grey (shape and movement only)")].inputs;+ if (s.picture && s.action !== "remove") Object.assign(graph[id("Describe picture 1")].inputs, sceneDescriber(s));+ if (!s.picture || s.action === "remove") {+ for (const title of ["Picture 1", "Shrink for the describer", "Describe picture 1"]) delete graph[id(title)];+ delete plan.picture_1;+ delete plan.picture_1_text;+ delete ref["ref_images.ref_image_0"];+ }+ // H3 copies a grey shape's outline: a changed top keeps the old silhouette, and a removed thing would come back grey.+ if (s.action === "remove" || (s.action === "change" && !s.keepShape)) {+ delete ref["ref_videos.ref_video_0"];+ delete ref["ref_video_audios.ref_video_audio_0"];+ }+ // New background: everything but what stays, reaching a little into its edge; the whole of it turns grey.+ if (s.action === "background") {+ grow.flip_input = true;+ grey.mask = [id("Grow mask"), 0];+ grey.size = [id("Grow mask"), 0];+ }+ grow.expand = OBJECT_MARGINS[s.edge];+ setMotionSize(graph, s.motion);+ const most = s.biggestOnly ? objectTargets(s.target).length : 0;+ for (const title of ["Tracked area", "Tracked area, tight (for the grey shape)"]) graph[id(title)].inputs.max_people = most;+ graph[id("SAM: what to change")].inputs.text = s.target;+ Object.assign(plan, { mode: s.action, target: s.target, change_to: s.becomes, keep_outline: s.keepShape, seed: s.seed, clip_seconds: CLIP_SECONDS, resolution: s.resolution });+ if (s.action === "change" && s.paint?.length) {+ const paint = JSON.stringify(s.paint);+ plan.paint = paint;+ // Track the whole part once: later clips still need the box at each painted frame.+ graph[id("SAM 3.1 track it")].inputs.images = [id("SAM video (1008 px, SAM's own size)"), 0];+ graph[id("Tracked area")].inputs.hold_frames = 0;+ graph.object_paint = {+ class_type: "H3PaintedEditArea",+ inputs: { tracked: [id("Tracked area"), 0], paint, start_frame: 0, width: [id(SCENE_PLAN), 1], height: [id(SCENE_PLAN), 2] },+ _meta: { title: "Painted edit area (follows tracked mask)" },+ };+ const slice = (mask: Link) => ({ class_type: "MiniMaxH3ContexLoopMaskSlice", inputs: { mask, state: [id("Current Clip"), 0], source_fps: 24 } });+ graph.object_paint_clip = slice(["object_paint", 0]);+ grow.mask = ["object_paint_clip", 0];+ for (const [input, output] of [["mask", 0], ["size", 1]] as const) {+ const key = `object_tight_${input}`;+ graph[key] = slice([id("Tracked area, tight (for the grey shape)"), output]);+ grey[input] = [key, 0];+ }+ }+ setRunName(graph, s.run);+ assertLinked(graph);+ return graph;+}++// ---------------------------------------------------------------------------+// From picture: the first frame, what happens, the video++/** The 17 light looks: Fuobe's names and hints, and the words the prompt helper reads (each names only what is wanted). */+export const LIGHT_LOOKS = [+ { id: "cold-spotlight", name: "Cold spotlight", hint: "One narrow beam from above, deep shadows", light: "Light the new photo as a dark, dramatic scene: a single narrow cold white spotlight shines straight down from directly above, with a visible beam of light cutting through dusty air above the head; it lights the top of the hair, forehead, cheekbones, nose and shoulders, leaves deep shadows in the eye sockets and under the nose and chin, and the background falls to black. Cold, desaturated blue-grey colour grade." },+ { id: "golden-halo", name: "Golden halo", hint: "Warm amber backlight and a golden rim", light: "Light the new photo with a warm golden glow: a strong amber backlight behind the head turns the background into glowing orange-gold haze and puts a bright golden rim on the hair and shoulders, while soft warm gold light falls on the face from the front. Rich honey and orange tones, glowing highlights, warm shadows, like sunset in a cathedral." },+ { id: "red-and-blue", name: "Red and blue", hint: "Two coloured lights, one from each side", light: "Light the new photo with two coloured gel lights in a dark room: saturated red light from the left and deep electric blue light from the right, each colour wrapping around its side of the face, hair and body, purple where they meet, and a dark red-blue background. High-contrast cinematic colour." },+ { id: "magenta-club", name: "Magenta club", hint: "Colours the room more than the person", light: "Light the new photo as a night club scene: the face, hair, skin and clothes are washed in hot magenta and purple stage light from above and the left, with pink highlights and deep violet shadows on the person, pink haze in the air and a blurry purple background with sparkling lights." },+ { id: "teal-lasers", name: "Teal lasers", hint: "Colours the room more than the person", light: "Light the new photo as a dark club scene in teal and blue: the face, hair, skin and clothes are lit by cold cyan light from the side, with blue-tinted skin, cyan highlights and deep navy shadows on the person; thin bright cyan laser beams cut diagonally through the haze behind, and the background is dark blue-black." },+ { id: "acid-green", name: "Acid green", hint: "Vivid green light from below", light: "Light the new photo with eerie toxic green light: a vivid green light from below and the side lights the face, hair and clothes, green laser beams shine through dark haze behind, deep green-black shadows, the whole scene tinted acid green." },+ { id: "lime-and-violet", name: "Lime and violet", hint: "Bold lime light, violet shadows", light: "Light the new photo with two bold gel colours: acid yellow-lime light from the front left floods the face and hair, deep purple light fills the shadows on the right and the background, high saturation and strong contrast, like a music video." },+ { id: "cyan-glow", name: "Cyan glow", hint: "A small cool light close to the face", light: "Light the new photo as a dark, moody scene lit only by a small glowing cold-blue light orb floating close to the face on the right side of the frame; the person is in darkness except where the orb's cool cyan-white light falls on the near side of the face, falling off quickly into blue-black shadow, with blue highlights in the eyes. The orb is the only light source." },+ { id: "crimson-room", name: "Crimson room", hint: "Deep red everywhere, one white highlight", light: "Light the new photo with deep crimson red light filling the whole scene, dark red shadows and a red-black background, and one small bright white light at the left edge of the frame that puts a cold white highlight on the near cheek and in the eyes." },+ { id: "venetian-blinds", name: "Venetian blinds", hint: "Film-noir stripes of sunlight", light: "Light the new photo as a film noir scene: hard low afternoon sunlight comes through venetian blinds from the left and casts sharp parallel diagonal stripes of bright light and black shadow across the face, hair, neck, clothes and the wall behind; thin rays of light are visible in the smoky air, the rest of the room is dark. Warm amber highlights, deep black shadows, high contrast." },+ { id: "phone-glow", name: "Phone glow", hint: "A screen's cool light from below", light: "Light the new photo as a dark room at night lit only by a phone screen held just below the face; its cold blue-white light falls on the chin, lips, nose and cheeks from below, reflects as small bright squares in the eyes, and fades to black on the hair, shoulders and body, with a pitch-black background. Cold blue tones, the rest of the frame in deep darkness." },+ { id: "firelight", name: "Firelight", hint: "Warm flicker from a fire below", light: "Light the new photo as a night scene beside a campfire just outside the frame at the bottom left; flickering orange-red firelight lights the face, hair and clothes from below and the left, glowing embers and sparks float up through the dark air, the far side of the face falls into deep shadow and the background is black night. Hot orange and red tones against darkness." },+ { id: "sunset-window", name: "Sunset window", hint: "Low golden sun through a window", light: "Light the new photo as a dim room at golden hour: low orange sunlight through a window on the left falls as a hard warm patch across one side of the face, hair and shoulder, with the window-frame shadow cutting across the body; the other side of the face is in deep brown shadow and the room behind is dark. Rich orange highlights, dark warm shadows." },+ { id: "evening-lamp", name: "Evening lamp", hint: "One warm lamp, an intimate night", light: "Light the new photo as a room in the evening lit only by a table lamp just out of frame on the right at shoulder height: soft warm orange light falls on that side of the face, hair and body, the other side fades into dim brown shadow, and the room behind is dark and cosy at night. Warm amber tones, low brightness, intimate night-time mood." },+ { id: "rim-light", name: "Rim light", hint: "A bright outline from behind", light: "Light the new photo with one hard light directly behind the person and slightly above: it draws a thin bright white rim along the hair, the edges of the face, the shoulders and the arms, light glows through loose strands of hair, the front of the face and body stay in deep shadow with only a faint fill, and the background is dark. High-contrast cinematic silhouette lighting." },+ { id: "blue-night", name: "Blue night", hint: "Soft cool light from one side", light: "Light the new photo as a room at night lit by soft cool light from the left side: dim blue-violet light falls on the near side of the face, hair and clothes, the other side sinks into deep blue-black shadow, and the background is dark navy. Low brightness, quiet futuristic night mood, cool blue and purple tones." },+ { id: "camera-flash", name: "Camera flash", hint: "Direct flash, a candid night look", light: "Light the new photo with a direct on-camera flash at night: hard flat white light straight from the camera hits the face and body brightly, gives the skin a slight glossy shine, small bright catchlights in the eyes, a hard dark shadow just behind the person on the wall, and the background falls off quickly into darkness. Candid party-photo look, high contrast." },+] as const;++export type LookId = (typeof LIGHT_LOOKS)[number]["id"];+export const LOOK_IDS = LIGHT_LOOKS.map((l) => l.id) as LookId[];+export const getLook = (id: string) => LIGHT_LOOKS.find((l) => l.id === id);++export const RELIGHT_PROMPT =+ "Create a photograph of the person from <image 1>, with their own face, identity, eye colour, hair and clothing, in exactly the pose, head angle, hand and arm positions, camera angle, framing and body cut of the person in <image 2>; describe that pose fully. They make exactly the facial expression of the person in <image 2>, with the same mouth shape, eyebrows and gaze; describe that expression. {look}";++export const FRAME_RELIGHT_PROMPT = "Relight this photograph. Keep the person, face, identity, expression, pose, hair, clothing, framing and setting exactly as they are; change only the lighting and the colour of the light. {look}";++const KLEIN_UPSAMPLER =+ "You are the prompt upsampler of an image-editing model. You see the reference image(s), attached in order (the first image, the second image, ...), and the user's short request. Expand it into ONE detailed, self-contained instruction: the caption the editing model receives together with the same images. Output only the instruction as one continuous English prose block, with no greetings, explanations, Markdown, JSON, coordinates, ids or angle-bracket tokens. Read a vague or conversational request as the most plausible edit of the supplied images.\n\nPick the voice by task shape. When one reference stays and gets bounded changes, write an imperative editing instruction on it (\"Remove the ...\", \"Change the ... to ...\", \"Zoom in on ...\"); a whole-image transformation opens with its scope (\"Convert the entire image into ...\", \"Apply a ... filter over the entire scene\", \"Horizontally flip the entire image so that ...\", \"Shift the camera viewpoint to ...\", then where the major elements should now be). When the references are drawn into a newly composed frame (combining subjects, a new scene, a garment, object or style donor), write a generation request (\"Create a photograph of ...\", \"Create an anime-style illustration of ...\", \"Generate a new image featuring ...\") that says what to take from each image, by ordinal, and what is newly generated.\n\nKeep every explicit edit, constraint, count, position, style cue and piece of wording, and decide what is left open as one concrete plan. Ground everything in what is actually visible: identify each referent unambiguously by its real appearance, never mention content that is not there, and use every image the user attached. State every end state concretely (which color, how large, which pose, which material) and give new content enough appearance to be generated. Cover the knock-on effects of the change (shadows, reflections, occlusion, perspective, scale, lighting) and say what fills a removed region. A zoom-in names what stays in frame and which neighbors are cropped out; an outpainting continues the scene in the same medium. Describe the change, not the whole scene, and close an editing instruction with one compact clause naming what stays unchanged; transferred people keep their identity, face and accessories unless asked otherwise. Transcribe on-image text verbatim in its original language inside double quotes, with line breaks as \\n, and match the original font, size and color when replacing it. Name recognizable public figures, brands and landmarks you can see. Directions are frame-relative; use no evaluative or quality words. Typical length is 50 to 150 words.\n\nOutput only the instruction.";++/** The light asked for, in the prompt helper's words ("" for none). */+export function lightWords(light: { look: string } | { words: string } | undefined): string {+ if (!light) return "";+ if ("look" in light) return getLook(light.look)?.light ?? "";+ const w = light.words.replace(/\s+/g, " ").trim().slice(0, 300);+ return w ? `Light the new photo this way: ${w.replace(/[.\s]+$/, "")}.` : "";+}++export interface PrepareSettings {+ /** The clip's size: the edit canvas is its shape at 768 px on the short side. */+ width: number;+ height: number;+ seed: number;+ /** The light's words (lightWords), or "" to keep the picture's own light. */+ light: string;+ /** Relight the person already in the clip (no character picture). */+ ownPerson: boolean;+ /** Own person: keep the frame's crop (start from it at denoise 0.9). */+ keepCrop: boolean;+ /** Extra words for the pose ("arms crossed, chin up"). */+ adjust?: string;+}++function relightRequest(graph: ComfyWorkflow, light: string) {+ const request = String(graph["6"].inputs.value);+ graph["6"].inputs.value = request.includes("{look}") ? request.replaceAll("{look}", light) : `${request} ${light}`;+ graph["25"].inputs.value = KLEIN_UPSAMPLER;+ Object.assign(graph["23"].inputs, {+ max_length: 3584,+ sampling_mode: "on",+ "sampling_mode.temperature": 1,+ "sampling_mode.top_k": 1,+ "sampling_mode.top_p": 0.95,+ "sampling_mode.min_p": 0,+ "sampling_mode.repetition_penalty": 1.05,+ "sampling_mode.seed": 0,+ });+}++/** From picture's first frame: the character in the clip's first-frame pose, in the picture's setting (and light). */+export function preparePicture(source: ComfyWorkflow, s: PrepareSettings): ComfyWorkflow {+ const graph = clone(source);+ const [w, h] = canvasSize(s.width, s.height, "768p");+ for (const id of ["3", "5"]) if (graph[id]) Object.assign(graph[id].inputs, { width: w, height: h });+ graph["19"].inputs.seed = s.seed;+ const adjust = (s.adjust ?? "").replace(/\s+/g, " ").trim().slice(0, 300);+ if (s.ownPerson) {+ if (!s.light) throw new Error("Pick a light for the clip's own person.");+ graph["6"].inputs.value = FRAME_RELIGHT_PROMPT;+ relightRequest(graph, s.light);+ for (const id of ["4", "5", "7"]) delete graph[id];+ graph["8"].inputs.image = ["2", 0];+ const { positive, negative, vae } = graph["15"].inputs;+ graph["15"] = { class_type: "ReferenceMultiLatent", inputs: { positive, negative, vae, resolution: "resize", "resolution.megapixels": 3, "images.image0": ["2", 0] }, _meta: { title: "Raw frame only, 3 MP" } };+ graph["19"].inputs.denoise = s.keepCrop ? 0.9 : 1;+ if (s.keepCrop) {+ graph.relight_frame = { class_type: "ImageScaleToTotalPixels", inputs: { image: ["2", 0], upscale_method: "lanczos", megapixels: 3, resolution_steps: 16 }, _meta: { title: "Raw frame at 3 MP" } };+ graph.relight_start = { class_type: "VAEEncode", inputs: { pixels: ["relight_frame", 0], vae: ["12", 0] }, _meta: { title: "Start from the frame" } };+ graph["19"].inputs.latent_image = ["relight_start", 0];+ }+ } else if (s.light) {+ // Pose and light in one pass: FLUX sees only the character at 3 MP; the frame reaches it through the written pose.+ graph["6"].inputs.value = adjust ? `${RELIGHT_PROMPT.replace(" {look}", "")} ${cap(adjust)}. {look}` : RELIGHT_PROMPT;+ relightRequest(graph, s.light);+ delete graph["5"];+ graph["7"] = { class_type: "BatchImagesNode", inputs: { "images.image0": ["4", 0], "images.image1": ["3", 0] }, _meta: { title: "Character picture + raw frame for the prompt upsampler" } };+ const { positive, negative, vae } = graph["15"].inputs;+ graph["15"] = { class_type: "ReferenceMultiLatent", inputs: { positive, negative, vae, resolution: "resize", "resolution.megapixels": 3, "images.image0": ["4", 0] }, _meta: { title: "Character picture only, 3 MP" } };+ graph.relight_canvas = { class_type: "ImageScaleToTotalPixels", inputs: { image: ["3", 0], upscale_method: "lanczos", megapixels: 3, resolution_steps: 16 }, _meta: { title: "Frame shape at 3 MP" } };+ graph.relight_size = { class_type: "GetImageSize", inputs: { image: ["relight_canvas", 0] } };+ graph.relight_latent = { class_type: "EmptyFlux2LatentImage", inputs: { width: ["relight_size", 0], height: ["relight_size", 1], batch_size: 1 }, _meta: { title: "Relit canvas" } };+ graph["19"].inputs.latent_image = ["relight_latent", 0];+ } else if (adjust) {+ graph["6"].inputs.value = `${String(graph["6"].inputs.value)} ${cap(adjust)}.`;+ }+ assertLinked(graph);+ return graph;+}++const cap = (t: string) => (t ? t[0].toUpperCase() + t.slice(1).replace(/[.\s]+$/, "") : t);++/** From picture's video length: whole frames on H3's 17k + 5 grid at 24 fps (6 s → 141 frames, 5.875 s). */+export function pictureFrames(seconds: number): number {+ return Math.max(5, Math.floor((Math.floor(seconds * 24 + 1e-6) - 5) / 17) * 17 + 5);+}++/** What happens in the part: the describer reads it at 2 fps and rewrites it for the approved frame (or not, for the clip's own person). */+export function describeScene(source: ComfyWorkflow, s: { frames: number; ownPerson: boolean }): ComfyWorkflow {+ const graph = clone(source);+ graph["1"].inputs.frame_load_cap = s.frames;+ if (s.ownPerson) {+ for (const id of ["74", "75", "76", "77", "78", "80", "81", "82"]) delete graph[id];+ graph["79"].inputs.source = ["73", 0];+ }+ assertLinked(graph);+ return graph;+}++export interface PictureVideoSettings {+ renderer: "solar" | "h3";+ /** The part's length in seconds (rounded down to the frame grid). */+ seconds: number;+ /** The clip's size and the quality: the canvas keeps the clip's shape at that short edge, at most 2048 px. */+ width: number;+ height: number;+ quality: string;+ /** Motion detail: 0 = the output canvas, else the long edge of the motion reference. */+ motion: 0 | MotionSize;+ seed: number;+ /** What happens, in words (the describer's, edited): opens the detailed description. */+ description?: string;+}++/** The two renderers' fixed steps: Solar's four-step LoRA, H3's DMAD at six. */+export const PICTURE_STEPS = { solar: 4, h3: 6 } as const;++export function pictureVideo(source: ComfyWorkflow, s: PictureVideoSettings): ComfyWorkflow {+ const graph = clone(source);+ const [width, height] = clampCanvas(canvasSize(s.width, s.height, s.quality === "720p" ? "736p" : "480p"));+ const length = pictureFrames(s.seconds);+ if (s.renderer === "solar" && length < 22) throw new Error("Pick a part of at least one second.");+ graph["1"].inputs.frame_load_cap = length;+ Object.assign(graph["56"].inputs, { width, height, length });+ const scale = s.motion ? s.motion / Math.max(width, height) : 1;+ Object.assign(graph["33"].inputs, { width: Math.max(32, Math.round((width * scale) / 32) * 32), height: Math.max(32, Math.round((height * scale) / 32) * 32), crop: "center" });+ graph["58"].inputs.noise_seed = s.seed;+ graph["60"].inputs.steps = PICTURE_STEPS[s.renderer];+ if (s.renderer === "solar" && graph["65"]) graph["65"].inputs.seed = s.seed;+ const text = (s.description ?? "").trim().replace(/\s+/g, " ").slice(0, 2000);+ if (text) {+ const prompt = String(graph["56"].inputs.prompt);+ graph["56"].inputs.prompt = s.renderer === "solar"+ ? prompt.replace(/detailed_description:\n(\[Shot 1\] The shot begins from <Video 2>\. )?/, (head) => `${head}${text} `)+ : prompt.replace(/detailed_description:\n/, (head) => `${head}${text} `);+ }+ assertLinked(graph);+ return graph;+}++// ---------------------------------------------------------------------------+// Finish: Fix faces, Fix colours++export type FaceStyle = "photo" | "mouth";+export const CHUNK_SECONDS = [4, 6.5, 10] as const;++/** How many sections Fix faces renders (H3FaceChunks, before close-up-only sections are dropped). */+export function faceChunkCount(seconds: number, chunkSeconds: number): number {+ const total = Math.floor(seconds * 24);+ const length = Math.floor((Math.floor(chunkSeconds * 24) - 5) / 17) * 17 + 5;+ return total <= length ? 1 : Math.ceil((total - 24) / (length - 24));+}++export function pruneFace(source: ComfyWorkflow, s: { style: FaceStyle; seed: number; chunkSeconds: number }): ComfyWorkflow {+ const graph = clone(source);+ const id = (title: string) => nodeByTitle(graph, title);+ const chunks = graph[id("Face Fix Chunks")].inputs;+ // Match the photo: no blurred face to follow, so H3 draws the expressions and mouth anew from the picture.+ if (s.style === "photo") {+ delete graph[id("Blurred face (follow the mouth)")];+ delete chunks.follow_mouth;+ delete graph[id("Reference Conditioning")].inputs["ref_videos.ref_video_0"];+ }+ chunks.chunk_seconds = s.chunkSeconds;+ graph[id("Seed")].inputs.noise_seed = s.seed;+ for (const n of Object.values(graph)) if (n.class_type === "H3FaceTrackCrop") n.inputs.select = "largest_face";+ assertLinked(graph);+ return graph;+}++export type ColourFinish = "soft" | "filmic" | "rich" | "off";++/** Openjutsu's "H3 soft" tone settings, with the strength the slider sets (0–1 → Orion's 0–0.5). */+const SOFT_TONE = { mode: "Reinhard", exposure: 0.09, contrast: 0.84, pivot: 0.69, highlight_rolloff: 0.27, shadow_lift: 0.15, black_floor: 0.03, saturation: 1.05 };++/** The tone mapper's settings for a finish (null: no tone step). */+export function toneFor(finish: ColourFinish, strength01: number): Record<string, number | string> | null {+ if (finish === "off") return null;+ const strength = Math.round(Math.max(0, Math.min(1, strength01)) * 0.5 * 1000) / 1000;+ if (finish === "soft") return { ...SOFT_TONE, strength };+ if (finish === "filmic") return { ...SOFT_TONE, mode: "Filmic Soft", strength };+ return { ...SOFT_TONE, mode: "Filmic Strong", strength: Math.max(strength, 0.35) };+}++/** Soften detail 0–1 → the detail contrast 0 … −0.6 (0 drops the step). */+export const detailFor = (soften01: number) => (soften01 <= 0 ? null : -Math.round(Math.min(1, soften01) * 0.6 * 1000) / 1000);++export function pruneColor(source: ComfyWorkflow, s: { detail: number | null; tone: Record<string, number | string> | null }): ComfyWorkflow {+ const graph = clone(source);+ const detail = nodeByTitle(graph, "Detail contrast");+ const tone = nodeByTitle(graph, "Tone mapper");+ if (s.detail === null) {+ graph[tone].inputs.image = graph[detail].inputs.image;+ delete graph[detail];+ } else graph[detail].inputs.detail_contrast = s.detail;+ if (s.tone === null) {+ graph[nodeByTitle(graph, "Fixed video")].inputs.images = graph[tone].inputs.image;+ delete graph[tone];+ } else {+ const n = graph[tone].inputs;+ n.raw_settings = JSON.stringify({ node_type: "color_fx_dctl_tone_mapper", preset: n.preset, settings: { ...s.tone, preserve_luminosity: false, clamp_output: true } });+ }+ assertLinked(graph);+ return graph;+}++// ---------------------------------------------------------------------------+// The provider's branch: one settings object per workflow (params.extra.openjutsu)++export const OPENJUTSU_WORKFLOWS = {+ group: "video-group-swap-h3",+ groupOneByOne: "video-group-swap-h3-one-by-one",+ scene: "video-scene-edit-h3",+ prepare: "image-from-picture-prepare",+ describe: "video-scene-describe",+ solar: "video-from-picture-solar",+ h3: "video-from-picture-h3",+ faces: "video-fix-faces-h3",+ colours: "video-fix-colours",+} as const;++export const OPENJUTSU_IDS = new Set<string>(Object.values(OPENJUTSU_WORKFLOWS));+/** The Context Loop jobs: their run folder is deleted once the result is in. */+export const CONTEXT_LOOP_IDS = new Set<string>([OPENJUTSU_WORKFLOWS.group, OPENJUTSU_WORKFLOWS.groupOneByOne, OPENJUTSU_WORKFLOWS.scene]);++/** Settings as they travel (params.extra.openjutsu). Unknown values fall back to the defaults. */+export type OpenjutsuSettings = Record<string, unknown>;++const num = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) ? v : d);+const str = (v: unknown, d = "") => (typeof v === "string" ? v : d);+const edgeOf = (v: unknown): Edge => (v === "tight" || v === "loose" ? v : "normal");+const motionOf = (v: unknown): MotionSize => (v === 768 ? 768 : 512);++/** The graph for one Openjutsu workflow, with this request's settings (after the manifest's bindings went in). */+export function openjutsuGraph(id: string, wf: ComfyWorkflow, o: OpenjutsuSettings, ctx: { generationId: string; clip?: { width?: number; height?: number } }): ComfyWorkflow {+ const run = runName(ctx.generationId);+ const seed = Math.max(0, Math.min(0xffffffff, Math.round(num(o.seed, 0))));+ switch (id) {+ case OPENJUTSU_WORKFLOWS.group:+ case OPENJUTSU_WORKFLOWS.groupOneByOne:+ return pruneGroupSwap(wf, {+ pictures: Math.round(num(o.pictures, 1)),+ roles: Array.isArray(o.roles) ? o.roles.map((r) => str(r)) : [],+ resolution: ojResolution(str(o.quality)),+ motion: motionOf(o.motion),+ hatFix: o.hats === true,+ noLipSync: o.mouthsFollowSound === false,+ edge: edgeOf(o.edge),+ seed,+ run,+ });+ case OPENJUTSU_WORKFLOWS.scene: {+ const action = o.action === "remove" || o.action === "background" ? o.action : "change";+ return pruneSceneEdit(wf, {+ action,+ target: str(o.target, action === "background" ? "person" : "").slice(0, 120),+ becomes: str(o.becomes).slice(0, 300),+ picture: o.picture === true,+ biggestOnly: o.biggestOnly === true,+ keepShape: o.keepShape === true,+ edge: edgeOf(o.edge),+ motion: motionOf(o.motion),+ resolution: ojResolution(str(o.quality)),+ seed,+ run,+ paint: Array.isArray(o.paint) ? (o.paint as PaintKeyframe[]) : undefined,+ });+ }+ case OPENJUTSU_WORKFLOWS.prepare: {+ const w = ctx.clip?.width;+ const h = ctx.clip?.height;+ if (!w || !h) throw new Error("Couldn't read the clip's size to make the first frame.");+ return preparePicture(wf, { width: w, height: h, seed, light: str(o.light), ownPerson: o.ownPerson === true, keepCrop: o.keepCrop === true, adjust: str(o.adjust) });+ }+ case OPENJUTSU_WORKFLOWS.describe:+ return describeScene(wf, { frames: pictureFrames(num(o.seconds, 6)), ownPerson: o.ownPerson === true });+ case OPENJUTSU_WORKFLOWS.solar:+ case OPENJUTSU_WORKFLOWS.h3: {+ const w = ctx.clip?.width;+ const h = ctx.clip?.height;+ if (!w || !h) throw new Error("Couldn't read the clip's size to make the video.");+ const motion = o.motion === 512 || o.motion === 768 ? o.motion : 0;+ return pictureVideo(wf, { renderer: id === OPENJUTSU_WORKFLOWS.h3 ? "h3" : "solar", seconds: num(o.seconds, 6), width: w, height: h, quality: str(o.quality, "480p"), motion, seed, description: str(o.scene) });+ }+ case OPENJUTSU_WORKFLOWS.faces:+ return pruneFace(wf, { style: o.faceStyle === "photo" ? "photo" : "mouth", seed, chunkSeconds: (CHUNK_SECONDS as readonly number[]).includes(num(o.chunkSeconds, 6.5)) ? num(o.chunkSeconds, 6.5) : 6.5 });+ case OPENJUTSU_WORKFLOWS.colours: {+ const finish: ColourFinish = o.finish === "filmic" || o.finish === "rich" || o.finish === "off" ? o.finish : "soft";+ return pruneColor(wf, { detail: detailFor(num(o.soften, 0.33)), tone: toneFor(finish, num(o.strength, 0.4)) });+ }+ default:+ return wf;+ }+}++/** The media inputs a request leaves out on purpose (their nodes go in openjutsuGraph). */+export function openjutsuLeftOut(id: string, o: OpenjutsuSettings): string[] {+ if (id === OPENJUTSU_WORKFLOWS.group || id === OPENJUTSU_WORKFLOWS.groupOneByOne) {+ const n = Math.round(num(o.pictures, 1));+ return ["image", "image2", "image3", "image4"].slice(Math.max(1, n));+ }+ if (id === OPENJUTSU_WORKFLOWS.scene) return o.picture === true && o.action !== "remove" ? [] : ["image"];+ if (id === OPENJUTSU_WORKFLOWS.prepare || id === OPENJUTSU_WORKFLOWS.describe) return o.ownPerson === true ? ["image"] : [];+ return [];+}diff --git a/src/server/genjutsu-live.ts b/src/server/genjutsu-live.tsnew file mode 100644index 00000000..1bb7ef46--- /dev/null+++ b/src/server/genjutsu-live.ts@@ -0,0 +1,34 @@+import "server-only";+import fs from "node:fs";+import path from "node:path";+import { GENJUTSU_FEATURE_KEYS, GENJUTSU_FEATURES, type GenjutsuFeature } from "@/lib/catalog/genjutsu";++const DIR = path.join(process.cwd(), "workflows", "comfyui");+const MANIFEST = path.join(DIR, "manifest.json");+/** The record of real renders that passed, one entry per feature (written when a feature passes its test on a GPU). */+const GPU_TESTED = path.join(DIR, "gpu-tested.json");++export type GenjutsuLive = Record<GenjutsuFeature, boolean>;++const read = (file: string): unknown => {+ try {+ return JSON.parse(fs.readFileSync(file, "utf8"));+ } catch {+ return null;+ }+};++/**+ * Which of Genjutsu's Openjutsu features are open to everyone: every workflow a feature needs has been accepted by ComfyUI+ * (the manifest's `validated`) AND its record says a real render passed (`features[key].passed`). The manifest flag alone+ * never opens one: it is set by a check that never renders. Until then only the owner sees and runs it. A file that can't+ * be read opens nothing.+ */+export function genjutsuLive(manifest = MANIFEST, record = GPU_TESTED): GenjutsuLive {+ const m = read(manifest) as { workflows?: { id?: string; validated?: boolean }[] } | null;+ const r = read(record) as { features?: Record<string, { passed?: boolean }> } | null;+ const validated = new Set((m?.workflows ?? []).filter((w) => w.validated === true).map((w) => w.id));+ return Object.fromEntries(+ GENJUTSU_FEATURE_KEYS.map((k) => [k, GENJUTSU_FEATURES[k].workflows.every((id) => validated.has(id)) && r?.features?.[k]?.passed === true]),+ ) as GenjutsuLive;+}diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.tsindex 0ff264b0..db9e9a96 100644--- a/src/server/genjutsu.ts+++ b/src/server/genjutsu.ts@@ -21,9 +21,19 @@ import {import { ACCESS_PLACE } from "@/lib/model-access";import { openCapNote, SHARPEN_COPY, SHARPEN_SIGMA_RANGE } from "@/lib/catalog/sharpen";import {+ ALL_FEATURES,chooseMaker,cutsInPart,+ faceChunkCount,GENJUTSU,+ getMaker,+ modeOpen,+ OPENJUTSU_LIMITS,+ requestFeatures,+ type FeatureCheck,+ type FinishOptions,+ type ObjectEdit,+ type PictureOptions,genjutsuProblem,genjutsuTitle,makersFor,@@ -49,6 +59,10 @@ import { silenceWriter } from "./canvas";import { createPipeline } from "./chains";import { llmText, llmTextBackend } from "./enhance";import { ConnectComfyError, createGenerations, previewChained } from "./generations";+import { db } from "./db";+import { genjutsuLive } from "./genjutsu-live";+import { decodePng } from "./png";+import { LOOK_IDS, paintKeyframe, type LookId, type PaintKeyframe } from "@/lib/openjutsu-graphs";import { localLabel } from "./llm";import { isOffered, offeredLoras, offeredModel } from "./model-access";import { provider } from "./providers";@@ -93,8 +107,24 @@ export interface GenjutsuBody {character?: CharacterOptions;/** Hard cuts the browser found in the clip (seconds), for the "one continuous shot" warning. */cuts?: number[];+ /** Object swap on Scene edit. */+ object?: ObjectEdit;+ /** From picture: the first frame, or the video from an approved one. */+ picture?: PictureOptions;+ /** Finish: Fix faces or Fix colours. */+ finish?: FinishOptions;}+/** Who is asking: the owner sees and runs every feature; others only what has opened (src/server/genjutsu-live.ts). */+export interface GenjutsuViewer {+ owner: boolean;+}++const OWNER: GenjutsuViewer = { owner: true };++/** The words a visitor gets for a feature that hasn't opened. */+export const NOT_HERE = "That isn't available here.";+const fileUrl = z.string().startsWith("/api/files/").max(500);const seconds = z.number().finite().min(0).max(3600);const point = z.object({ x: z.number().finite().min(0).max(20000), y: z.number().finite().min(0).max(20000), label: z.enum(["positive", "negative"]).optional() });@@ -120,12 +150,49 @@ const character = z.object({historyFrames: z.number().int().min(0).max(341).optional(),/** 1080p / 2K / 4K on your GPU: the regenerate's start noise (an evaluation knob; the page doesn't set it). */sharpenSigma: z.number().min(SHARPEN_SIGMA_RANGE.min).max(SHARPEN_SIGMA_RANGE.max).optional(),+ people: z+ .array(z.object({ role: z.string().max(OPENJUTSU_LIMITS.roleChars), pin: z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) }).optional() }))+ .max(OPENJUTSU_LIMITS.maxCharacters)+ .optional(),+ onePerPerson: z.boolean().optional(),+ hats: z.boolean().optional(),+ mouthsFollowSound: z.boolean().optional(),+ edge: z.enum(["tight", "normal", "loose"]).optional(),+ motionDetail: z.union([z.literal(512), z.literal(768)]).optional(),+});+const objectEdit = z.object({+ action: z.enum(["change", "remove", "background"]),+ target: z.string().max(120).optional(),+ becomes: z.string().max(300).optional(),+ biggestOnly: z.boolean().optional(),+ keepShape: z.boolean().optional(),+ edge: z.enum(["tight", "normal", "loose"]).optional(),+ motionDetail: z.union([z.literal(512), z.literal(768)]).optional(),+});+const picture = z.object({+ stage: z.enum(["frame", "video"]),+ light: z.union([z.object({ look: z.enum(LOOK_IDS as [LookId, ...LookId[]]) }), z.object({ words: z.string().max(OPENJUTSU_LIMITS.lightChars) })]).optional(),+ ownPerson: z.boolean().optional(),+ keepCrop: z.boolean().optional(),+ adjust: z.string().max(300).optional(),+ frame: fileUrl.optional(),+ scene: z.string().max(OPENJUTSU_LIMITS.sceneChars).optional(),+ renderer: z.enum(["solar", "h3"]).optional(),+ motionDetail: z.union([z.literal(0), z.literal(512), z.literal(768)]).optional(),+});+const finish = z.object({+ tool: z.enum(["faces", "colours"]),+ faceStyle: z.enum(["photo", "mouth"]).optional(),+ chunkSeconds: z.union([z.literal(4), z.literal(6.5), z.literal(10)]).optional(),+ finish: z.enum(["soft", "filmic", "rich", "off"]).optional(),+ strength: z.number().min(0).max(1).optional(),+ soften: z.number().min(0).max(1).optional(),});/** The body of /api/genjutsu (and /estimate). */export const GenjutsuBodySchema = z.object({engine: z.enum(["cloud", "open"]),- mode: z.enum(["motion", "character", "swap", "restyle", "insert"]),+ mode: z.enum(["motion", "character", "swap", "restyle", "insert", "picture", "finish"]),modelId: z.string().max(80).optional(),tier: z.enum(["standard", "high"]).optional(),quality: z.enum(["480p", "720p", "768p", "1080p", "2K", "4K"]).optional(),@@ -149,6 +216,9 @@ export const GenjutsuBodySchema = z.object({range: z.object({ start: seconds, end: seconds }).optional(),seed: z.number().int().min(0).max(2 ** 48).optional(),character: character.optional(),+ object: objectEdit.optional(),+ picture: picture.optional(),+ finish: finish.optional(),cuts: z.array(seconds).max(200).optional(),/** A client nonce for one submit: a repeat gets the first answer (see once()). */requestId: z.string().trim().min(8).max(64).optional(),@@ -174,19 +244,41 @@ interface Planned {notes: string[];}-async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<Planned> {+/** What this viewer may use: everything for the owner; for a guest or an account, what has opened. */+function openFor(viewer: GenjutsuViewer): FeatureCheck {+ if (viewer.owner) return ALL_FEATURES;+ const live = genjutsuLive();+ return (f) => live[f];+}++async function planInput(body: GenjutsuBody, opts: { probe: boolean; viewer?: GenjutsuViewer }): Promise<Planned> {mustMatchMode(body.engine);- const picked = chooseMaker({+ const open = openFor(opts.viewer ?? OWNER);+ if (!modeOpen(body.mode, open)) throw new ShortsError(NOT_HERE, 422);+ // A model named that hasn't opened yet: the owner's alone.+ const named = body.modelId ? getMaker(body.modelId, body.engine) : undefined;+ if (named?.features && !named.features.some(open)) throw new ShortsError(NOT_HERE, 422);+ const ask = {engine: body.engine,mode: body.mode,target: body.target,tier: body.tier,look: body.look,modelId: body.modelId,- offered: (id) => isOffered(id, body.engine),- });- if ("problem" in picked) throw new ShortsError(picked.problem, 422);+ offered: (id: string) => isOffered(id, body.engine),+ refs: body.references?.length ?? 0,+ action: body.mode === "swap" ? body.object?.action : undefined,+ tool: body.mode === "finish" ? (body.finish?.tool ?? "colours") : undefined,+ };+ const picked = chooseMaker({ ...ask, open });+ if ("problem" in picked) {+ // Something only a feature that hasn't opened yet does (Remove it, say): the owner's alone.+ if (open !== ALL_FEATURES && "maker" in chooseMaker({ ...ask, open: ALL_FEATURES })) throw new ShortsError(NOT_HERE, 422);+ throw new ShortsError(picked.problem, 422);+ }const maker = picked.maker;+ // A setting that hasn't opened (one by one, a light, the clip's own person…): the owner's alone.+ if (requestFeatures({ mode: body.mode, maker, character: body.character, object: body.object, picture: body.picture, finish: body.finish }).some((f) => !open(f))) throw new ShortsError(NOT_HERE, 422);// The header's facts win over what the browser read (the estimate runs before the upload is read).const info = opts.probe ? await probeSource(body.source.url) : {};const source: RemoveSource = {@@ -198,15 +290,21 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<// Sound we couldn't read counts as none (putting it back would fail after the work was paid for).hasAudio: opts.probe ? (info.hasAudio ?? false) : (body.source.hasAudio ?? false),};- // Character swap's part defaults to the first 15 s (Openjutsu's Length); the other modes take up to 30 s.- const longest = body.mode === "character" ? CHARACTER_SWAP.maxSeconds : GENJUTSU.maxSeconds;+ // Character swap's part defaults to the first 15 s (Openjutsu's Length); From picture's to the first 6 s; Finish takes+ // the whole video (up to its limit); the other modes up to 30 s.+ const longest = maker.review ? 6 : maker.part ? maker.part.max : body.mode === "character" ? CHARACTER_SWAP.maxSeconds : GENJUTSU.maxSeconds;const range = body.range ?? (source.duration ? { start: 0, end: Math.min(source.duration, longest) } : null);if (!range) throw new ShortsError("Reading the clip… try again in a moment");const target = MODE_TARGETS[body.mode].length ? (body.target ?? MODE_TARGETS[body.mode][0]) : undefined;const references = body.references ?? [];const clicks = (body.points ?? []).filter((p) => p.label !== "negative").length;- const problem = genjutsuProblem({ mode: body.mode, maker, source, range, references: references.length, target, subject: body.subject, prompt: body.prompt, points: clicks, mask: !!body.mask, look: body.look, seed: body.seed, character: body.character });+ const problem = genjutsuProblem({ mode: body.mode, maker, source, range, references: references.length, target, subject: body.subject, prompt: body.prompt, points: clicks, mask: !!body.mask, look: body.look, seed: body.seed, character: body.character, object: body.object, picture: body.picture, finish: body.finish });if (problem) throw new ShortsError(problem, 422);+ // From picture's video starts from a first frame this install made (the review step can't be skipped).+ if (maker.review && body.picture?.stage === "video" && opts.probe && !madeFrame(body.picture.frame)) throw new ShortsError("Make and pick the first frame first", 422);+ // Scene edit's painted area, as the pack's keyframe (one, on the part's first frame).+ let paint: PaintKeyframe[] | undefined;+ if (maker.actions && (body.object?.action ?? "change") === "change" && target === "paint" && body.mask && opts.probe) paint = [await paintFrom(body.mask)];const switched = body.mode === "character" && maker.h3 ? characterSwitches(maker, body.character ?? {}) : { character: body.character, notes: [] };// Clicks on the first frame, in the clip's pixels; paint is followed from its deepest points (SAM 3.1 on fal).@@ -243,10 +341,44 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<look: body.look,...(body.seed !== undefined ? { seed: body.seed } : {}),...(body.mode === "character" ? { character: switched.character ?? {} } : {}),+ ...(body.object ? { object: body.object } : {}),+ ...(body.picture ? { picture: body.picture } : {}),+ ...(body.finish ? { finish: body.finish } : {}),+ ...(paint ? { paint } : {}),},};}+/** Whether a first frame is one this install's From picture made (and finished). */+function madeFrame(url: string | undefined): boolean {+ if (!url) return false;+ // Looked up by its address, however old (not in the Trash, not an account's run).+ const row = db()+ .prepare(+ `SELECT 1 FROM generations g+ WHERE g.model_id = 'oss-from-picture-frame' AND g.status = 'succeeded'+ AND json_extract(g.request_json, '$.account') IS NULL+ AND NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = g.id)+ AND EXISTS (SELECT 1 FROM json_each(g.outputs_json) o WHERE json_extract(o.value, '$.url') = ?)+ LIMIT 1`,+ )+ .get(url);+ return !!row;+}++/** The painted mask as Scene edit's keyframe (run-length, at most 256 px a side). */+async function paintFrom(mask: string): Promise<PaintKeyframe> {+ let png: ReturnType<typeof decodePng>;+ try {+ png = decodePng((await readRef(mask)).data);+ } catch {+ throw new ShortsError("Couldn't read the painted area — paint it again", 400);+ }+ const k = paintKeyframe({ width: png.width, height: png.height, data: png.data, channels: 4 });+ if (!k.runs.length) throw new ShortsError("Paint over what changes", 422);+ return k;+}+/*** The Character swap with what Settings → Models & licences switched off taken out: the first-frame model (the next one* that is on, else no first frame) and the swap LoRA (on your GPU H3 runs without it; fal's route needs one). Turbo off@@ -279,6 +411,10 @@ function notesFor(body: GenjutsuBody, m: Maker, source: RemoveSource, range: Remconst fps = source.fps ?? 30;const fuobeLook = body.mode === "restyle" && m.looks === "fuobe";const len = range.end - range.start;+ if (m.group || m.actions || m.review || m.tool) {+ notes.push(...openjutsuNotes(body, m, range));+ return notes;+ }if (body.mode === "character" && m.h3) {const c = body.character ?? {};if (m.engine === "open") {@@ -352,6 +488,31 @@ function notesFor(body: GenjutsuBody, m: Maker, source: RemoveSource, range: Remreturn notes;}+/** The Openjutsu makers' notes: the time on your GPU, the sound, and what to expect. */+function openjutsuNotes(body: GenjutsuBody, m: Maker, range: RemoveRange): string[] {+ const len = range.end - range.start;+ const notes: string[] = [];+ const minutes = (perSecond: number) => Math.max(1, Math.round((len * perSecond) / 60));+ if (m.group) {+ const n = body.references?.length ?? 1;+ const twice = body.character?.onePerPerson && n === 2;+ notes.push(`About ${minutes(twice ? 120 : 60)} min on your GPU · keeps the clip's sound`);+ if (n > 1) notes.push("Say who each character replaces, or leave it blank and the people with the most screen time are picked in order");+ const warn = cutWarning(cutsInPart(body.cuts, range));+ if (warn) notes.push(warn);+ } else if (m.actions) {+ notes.push(`About ${minutes(50)} min on your GPU · keeps the clip's sound`);+ if (body.object?.action === "background") notes.push("The people stay exactly as filmed");+ } else if (m.review) {+ notes.push(body.picture?.stage === "video" ? `About ${minutes(60)} min on your GPU · keeps the clip's sound` : "The first frame takes about a minute: check it before the video is made");+ } else if (m.tool === "faces") {+ const chunks = faceChunkCount(len, body.finish?.chunkSeconds ?? 6.5);+ notes.push(`${chunks} section${chunks > 1 ? "s" : ""} · about ${minutes(60)} min on your GPU · keeps the sound`);+ notes.push("Faces that already fill the frame are left as they are");+ } else if (m.tool === "colours") notes.push("Takes seconds · keeps the sound");+ return notes;+}+const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });/** The helper steps in words, for a run that can't have them (they run on fal; the open ones on ComfyUI). */@@ -485,8 +646,8 @@ export interface GenjutsuEstimate {gpu?: { weightsGb: number; tested: string; advice: string; speed: string };}-export async function estimateGenjutsu(body: GenjutsuBody): Promise<GenjutsuEstimate> {- const { input, maker, notes } = await planInput(body, { probe: false });+export async function estimateGenjutsu(body: GenjutsuBody, viewer: GenjutsuViewer = OWNER): Promise<GenjutsuEstimate> {+ const { input, maker, notes } = await planInput(body, { probe: false, viewer });let plan: ReturnType<typeof planGenjutsu>;try {plan = planGenjutsu(input);@@ -514,8 +675,8 @@ export async function estimateGenjutsu(body: GenjutsuBody): Promise<GenjutsuEsti}/** Start it; returns the finished video's generation (the other steps wait for each other). */-export async function createGenjutsu(body: GenjutsuBody): Promise<{ final: Generation; items: Generation[] }> {- const { input } = await planInput(body, { probe: true });+export async function createGenjutsu(body: GenjutsuBody, viewer: GenjutsuViewer = OWNER): Promise<{ final: Generation; items: Generation[] }> {+ const { input } = await planInput(body, { probe: true, viewer });try {const plan = planGenjutsu(input);// The same check as the estimate: nothing starts when only some of the steps have a provider.@@ -574,6 +735,45 @@ export async function describeCharacter(body: z.infer<typeof DescribeSchema>): Preturn { description };}+export const SceneSchema = z.object({+ engine: z.literal("open"),+ source: z.object({ url: fileUrl, duration: z.number().finite().positive().max(3600).optional() }),+ range: z.object({ start: seconds, end: seconds }),+ /** The approved first frame (left out for the clip's own person). */+ frame: fileUrl.optional(),+ ownPerson: z.boolean().optional(),+});++/**+ * From picture's "What happens": the describer reads the part at 2 frames a second and writes it for the approved first+ * frame (a step of its own; the page waits for its text and puts it in an editable box). Owner-only, like the runs.+ */+export function describeScene(body: z.infer<typeof SceneSchema>, viewer: GenjutsuViewer = OWNER): { id: string; modelId: string } {+ mustMatchMode("open");+ if (!openFor(viewer)("picture")) throw new ShortsError(NOT_HERE, 422);+ const len = body.range.end - body.range.start;+ if (!(len >= OPENJUTSU_LIMITS.minSeconds - 0.05 && len <= OPENJUTSU_LIMITS.maxSeconds + 0.05)) throw new ShortsError(`Pick a part between ${OPENJUTSU_LIMITS.minSeconds} and ${OPENJUTSU_LIMITS.maxSeconds} seconds`, 422);+ if (!body.ownPerson && !body.frame) throw new ShortsError("Make and pick the first frame first", 422);+ if (!body.ownPerson && !madeFrame(body.frame)) throw new ShortsError("Make and pick the first frame first", 422);+ const modelId = "oss-scene-describe";+ if (!isOffered(modelId, "open")) throw new ShortsError(`Describing is switched off in ${ACCESS_PLACE} — write what happens in your own words`, 422);+ try {+ const [g] = createGenerations({+ feature: GENJUTSU.stepFeature,+ batchTitle: "Genjutsu · what happens",+ modelId,+ op: "describe-video",+ inputs: { video: body.source.url, ...(body.ownPerson ? {} : { images: [body.frame!] }) },+ params: { startTime: body.range.start, extra: { openjutsu: { seconds: len, ownPerson: !!body.ownPerson } } },+ step: { label: "What happens in the part", index: 0, of: 1 },+ });+ return { id: g.id, modelId };+ } catch (e) {+ if (e instanceof ConnectComfyError) throw e;+ throw new ShortsError((e as Error).message, 422);+ }+}+/** The transcriber per engine (Fuobe's Transcribe studio's defaults). */export const TRANSCRIBERS: Record<Engine, string> = { cloud: "scribe-v2", open: "oss-qwen3-asr" };diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex c50a95c1..7eceb33a 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -61,6 +61,7 @@ import { CHARACTER_SWAP, packResolution, samCoords, swapPrompt, SWAP_LORAS, windimport { maskMemoryProblem } from "@/lib/catalog/swap-studio";import { STUDIO_WORKFLOWS } from "@/lib/catalog/swap-studio-plan";import { maskGraph, segmentGraph, type MaskGraphOptions, type SegmentGraphOptions } from "@/lib/swap-studio-graphs";+import { CONTEXT_LOOP_IDS, OPENJUTSU_IDS, openjutsuGraph, openjutsuLeftOut, runName, type OpenjutsuSettings } from "@/lib/openjutsu-graphs";import { RESTORE_EXTRA_KEYS, restoreGraph, restoreJob, type RestoreJob } from "@/lib/restore-graph";import { getMaker, makerPrompt, OPEN_TARGET_PROBLEM, ORIGINALS, swapTarget } from "@/lib/catalog/genjutsu";import { CLICK_OPEN_PROBLEM, HAND_OFF, REMOVE_SCENE, targetPhrase } from "@/lib/catalog/remove-object";@@ -1122,6 +1123,7 @@ function videoFinishValues(manifest: ManifestWorkflow, input: GenInput, clip: Me// Graphs that decode the whole clip (src/lib/av/video-finish.ts wholeClipTool says how many copies they hold).if (manifest.capability === "sdr-to-hdr") out.wholeClip = wholeClipTool("sdr-to-hdr", input.format);if (manifest.id === "video-export-exr") out.wholeClip = wholeClipTool("export-video", "exr");+ if (manifest.capability === "video-fix-faces") out.wholeClip = wholeClipTool("face-fix-video", undefined);// FPS Boost: interpolate by m, keep every n-th frame (the graph computes the output frame rate itself).if (b.every && b.multiplier) {const target = input.targetFps;@@ -1163,6 +1165,9 @@ function videoFinishValues(manifest: ManifestWorkflow, input: GenInput, clip: Me}} else if (b.framesPerBatch && manifest.capability === "export-video" && extra.framesPerBatch === undefined) {values.framesPerBatch = framesPerPass(facts, { min: 8, max: 256, fallback: Number(d.framesPerBatch ?? 64) });+ } else if (b.framesPerBatch && manifest.capability === "video-tone" && extra.framesPerBatch === undefined) {+ // Fix colours: a pass holds three frame-sized copies (the decoded frames, the softened ones, the toned ones).+ values.framesPerBatch = framesPerPass(facts, { modelScale: 1, min: 8, max: 128, fallback: Number(d.framesPerBatch ?? 48) });}return out;}@@ -1469,6 +1474,10 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,}if (b.prompt) values.prompt = REMOVE_SCENE;}+ // Genjutsu's Openjutsu modes (src/lib/openjutsu-graphs.ts): the settings travel as params.extra.openjutsu and are written+ // into the graph by node title after the media are bound; the pictures a request leaves out go with their branches.+ const openjutsu = OPENJUTSU_IDS.has(manifest.id) ? ((extra.openjutsu && typeof extra.openjutsu === "object" ? extra.openjutsu : {}) as OpenjutsuSettings) : null;+ delete extra.openjutsu;// Genjutsu's Character swap (MiniMax H3 on the h3_character_swap / H3 Relay packs): the part, the quality as the// unpatched pack's string, who to swap (SAM words, largest / leftmost / rightmost / index, or clicks moved into H3's// canvas), the swap LoRA's release, the window plan; the anchor first frame is images[1] (absent: its nodes go).@@ -1706,7 +1715,7 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,// optional inputs, else the previous image again where that's harmless (style boards, multi-reference edits), else a// clear "add …" message.let graph = workflow;- const left: string[] = [...studioLeft];+ const left: string[] = [...studioLeft, ...(openjutsu ? openjutsuLeftOut(manifest.id, openjutsu) : [])];// A side nobody photographed is left out (its cut-out and crop with it); the front is needed.if (rules.views) {for (const k of IMAGE_SLOTS.slice(1)) {@@ -1771,6 +1780,14 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,// The prompt helper (FLUX 3 Image Klein's upsampler) off, or a layout with boxes it would rewrite: the words as typed.if (PROMPT_HELPER_GRAPHS.has(manifest.id) && (helper === "off" || laidOut)) wf = skipPromptHelper(wf, outputIds);if (dropAnchor) wf = withoutAnchor(wf, b.image2![0].node);+ if (openjutsu) {+ try {+ const seed = typeof openjutsu.seed === "number" ? openjutsu.seed : typeof values.seed === "number" ? values.seed : randomSeed();+ wf = openjutsuGraph(manifest.id, wf, { ...openjutsu, seed }, { generationId: ctx.generationId, clip: clip ? { width: clip.width, height: clip.height } : undefined });+ } catch (e) {+ throw new ProviderError((e as Error).message, 400);+ }+ }// LoRA "none": the swap LoRA's loader is linked out (H3 runs with the Turbo LoRA alone).if (dropSwapLora && b.lora?.length === 1) wf = bypassNode(wf, b.lora[0].node, "model", outputIds);if (studioSegment) wf = segmentGraph(wf, { ...studioSegment, outputs: outputIds });@@ -1981,6 +1998,29 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,return uploaded;}+/**+ * Deletes a finished Context Loop job's run folder (output/h3_chains/<run>) through the pack's own routes: a preview gives+ * the folder's snapshot, the delete names it and the run again. A failure is logged and the run goes on.+ */+export async function deleteRunFolder(run: string, worker: ComfyWorker = "main"): Promise<boolean> {+ try {+ const preview = await comfyFetch("/minimax_h3_context_loop/run-folder/delete-preview", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ run_name: run }) }, worker);+ const p = (await preview.json().catch(() => ({}))) as { snapshot?: string };+ if (!preview.ok || !p.snapshot) return false;+ const done = await comfyFetch(+ "/minimax_h3_context_loop/run-folder/delete",+ { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ run_name: run, snapshot: p.snapshot, confirmation: run }) },+ worker,+ );+ discardBody(done);+ if (!done.ok) console.warn(`Couldn't delete the H3 run folder ${run} (HTTP ${done.status})`);+ return done.ok;+ } catch (e) {+ console.warn(`Couldn't delete the H3 run folder ${run}: ${(e as Error).message}`);+ return false;+ }+}+type QueueEntry = unknown[];const postJson = (p: string, body: unknown, worker: ComfyWorker = "main") =>comfyFetch(p, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }, worker).catch(() => undefined);@@ -2252,6 +2292,9 @@ export const comfyProvider: ProviderAdapter = {return serverScope.run(true, () => comfyProvider.poll({ externalId, meta, model, ...rest }));}const finished = async (entry: HistoryEntry) => {+ // A Context Loop job (Group swap, Scene edit): its clips and checkpoints under output/h3_chains go once it ends (the+ // final video is copied out of that folder first).+ if (manifest && CONTEXT_LOOP_IDS.has(manifest.id) && typeof meta.generationId === "string") void deleteRunFolder(runName(meta.generationId), worker);if (entry.status?.status_str === "error") {forget(externalId);return { state: "failed" as const, error: explainExecutionError(executionError(entry), manifest) };